Datasets:
File size: 51,629 Bytes
3bb13c3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 |
import tkinter as tk
from tkinter import ttk, messagebox, font
import json
import os
from loggings import LoggingManager
from appearance import appearance_manager
class NPCManager:
def __init__(self, parent, reload_callback=None, logging_manager=None):
print("Starting NPC Manager initialization...")
try:
self.parent = parent
self.reload_callback = reload_callback
self.logging_manager = logging_manager or LoggingManager(None)
self.window = tk.Toplevel(parent)
self.window.title("NPC Manager")
# กำหนดขนาดหน้าต่างเริ่มต้น
default_width = 1200
default_height = 800
# คำนวณตำแหน่งกลางจอ
screen_width = parent.winfo_screenwidth()
screen_height = parent.winfo_screenheight()
x = (screen_width - default_width) // 2
y = (screen_height - default_height) // 2
# ตั้งค่าขนาดและตำแหน่ง
self.window.withdraw() # ซ่อนก่อนจัดตำแหน่ง
self.window.geometry(f"{default_width}x{default_height}+{x}+{y}")
self.window.minsize(800, 600)
self.window.overrideredirect(True)
self.window.configure(bg=appearance_manager.bg_color)
print("Creating state variables...")
# Initialize state variables
self.current_section = None
self.data = self.load_data()
self.search_var = tk.StringVar()
self.search_var.trace("w", self.on_search_change)
print("Initializing font system...")
# Font management initialization
self.setup_font_system()
self.window.after(100, lambda: self.on_font_change(None))
print("Creating UI components...")
# Create main UI components
self.create_title_bar()
self.create_main_layout()
self.setup_entry_form()
self.setup_json_display()
print("Setting up resize handling...")
# Setup resize functionality
self.setup_resize_handling()
print("Binding window events...")
# Setup window event bindings
self.bind_window_events()
# อัพเดทการคำนวณทั้งหมด
self.window.update_idletasks()
print("Initialization complete")
except Exception as e:
print(f"Critical error during initialization: {e}")
messagebox.showerror(
"Initialization Error", f"Failed to initialize NPC Manager: {str(e)}"
)
raise
def setup_font_system(self):
"""Initialize the font management system"""
print("Setting up font system...")
self.font_sizes = list(range(10, 29, 2)) # 10-28
self.current_font_size = 16
self.available_fonts = self.load_available_fonts()
self.current_font = self.get_default_font()
# Initialize font manager state
self.font_manager = {
"current": self.current_font,
"available": self.available_fonts,
"size": self.current_font_size,
}
print(f"Font system ready with {len(self.available_fonts)} fonts")
def load_available_fonts(self):
"""Load and register fonts from project directory only"""
custom_fonts = []
project_dir = r"C:\Magicite Babel"
try:
if not os.path.exists(project_dir):
return ["Arial"]
# Map file names to display names
font_mapping = {
"BaiJamjuree-Light": "Bai Jamjuree Light.ttf",
"Bai Jamjuree Light": "Bai Jamjuree Light.ttf",
"FCMinimal": "FC Minimal",
"NotoSansThaiLooped": "Noto Sans Thai Looped",
# เพิ่มการ map อื่นๆ ตามที่ต้องการ
}
# อ่านฟอนต์จากโฟลเดอร์
font_files = [
f
for f in os.listdir(project_dir)
if f.lower().endswith((".ttf", ".otf"))
]
for font_file in font_files:
try:
base_name = os.path.splitext(font_file)[0]
# ใช้ชื่อที่ map ไว้ถ้ามี ไม่งั้นใช้ชื่อไฟล์
display_name = font_mapping.get(base_name, base_name)
custom_fonts.append(display_name)
except Exception:
continue
# เพิ่มฟอนต์พื้นฐาน
basic_fonts = [
"Bai Jamjuree Light",
"FC minimal",
"Arial",
"Helvetica",
"TkDefaultFont",
]
available_fonts = list(set(custom_fonts + basic_fonts))
return sorted(available_fonts)
except Exception as e:
return ["Arial"]
def get_default_font(self):
"""Get appropriate default font"""
preferred_fonts = [
"Bai Jamjuree Light",
"Arial",
"Helvetica",
"TkDefaultFont",
]
for font_name in preferred_fonts:
if font_name in self.available_fonts:
return font_name
# ถ้าไม่พบฟอนต์ที่ต้องการ ใช้ฟอนต์แรกที่มี
return self.available_fonts[0] if self.available_fonts else "TkDefaultFont"
def create_title_bar(self):
"""Create custom title bar"""
print("Creating title bar...")
# Title bar frame with gradient effect
self.title_bar = tk.Frame(
self.window, bg=appearance_manager.bg_color, height=40
)
self.title_bar.pack(fill="x", side="top")
self.title_bar.pack_propagate(False)
# Title label
self.title_label = tk.Label(
self.title_bar,
text="NPC Manager",
bg=appearance_manager.bg_color,
fg="white",
font=("Nasalization Rg", 14),
)
self.title_label.pack(side="left", padx=10)
# Close button
self.close_button = tk.Button(
self.title_bar,
text="×",
bg=appearance_manager.bg_color,
fg="white",
bd=0,
font=("Arial", 16),
command=self.hide_window,
)
self.close_button.pack(side="right", padx=5)
# Add drag functionality
self.title_bar.bind("<Button-1>", self.start_move)
self.title_bar.bind("<B1-Motion>", self.do_move)
print("Title bar created")
def setup_resize_handling(self):
"""Setup window resize functionality"""
print("Setting up resize handling...")
self.resize_handle = tk.Label(
self.window,
text="✦",
bg="#2A2A2A",
fg="white",
font=("Arial", 12, "bold"),
cursor="sizing",
)
self.resize_handle.place(relx=1, rely=1, anchor="se")
self.resize_handle.bind("<Button-1>", self.start_resize)
self.resize_handle.bind("<B1-Motion>", self.on_resize)
self.resize_handle.bind("<ButtonRelease-1>", self.stop_resize)
self.is_resizing = False
print("Resize handling setup complete")
def bind_window_events(self):
"""Bind various window events"""
print("Binding window events...")
self.window.bind("<Configure>", self.on_window_configure)
self.window.bind("<Map>", lambda e: self.window.deiconify())
self.window.bind("<Unmap>", lambda e: self.window.withdraw())
print("Window events bound")
def create_main_layout(self):
"""Create the main three-panel layout with visual separators"""
print("Creating main layout...")
# Main container
self.main_container = tk.Frame(self.window, bg=appearance_manager.bg_color)
self.main_container.pack(fill="both", expand=True, padx=10, pady=5)
# Left panel (buttons) with border
self.buttons_panel = tk.Frame(
self.main_container, bg=appearance_manager.bg_color
)
self.buttons_panel.pack(side="left", fill="y", padx=(0, 1))
# Vertical separator after buttons panel
tk.Frame(self.main_container, width=2, bg="#404040").pack(
side="left", fill="y", padx=5
)
# Middle panel (entry form) with border
self.entry_panel = tk.Frame(
self.main_container, bg=appearance_manager.bg_color, width=300
)
self.entry_panel.pack(side="left", fill="y", padx=(1, 1))
self.entry_panel.pack_propagate(False)
# Vertical separator after entry panel
tk.Frame(self.main_container, width=2, bg="#404040").pack(
side="left", fill="y", padx=5
)
# Right panel (JSON display)
self.content_panel = tk.Frame(
self.main_container, bg=appearance_manager.bg_color
)
self.content_panel.pack(side="right", fill="both", expand=True)
# Create section buttons
self.create_section_buttons()
# Create font controls
self.create_font_controls()
print("Main layout created")
def create_section_buttons(self):
"""Create section buttons with improved styling"""
print("Creating section buttons...")
sections = [
("MAIN CHARACTERS", "main_characters"),
("NPCS", "npcs"),
("LORE", "lore"),
("CHARACTER ROLES", "character_roles"),
("WORD FIXES", "word_fixes"),
]
# Title for buttons section
title_label = tk.Label(
self.buttons_panel,
text="EDIT-context",
bg=appearance_manager.bg_color,
fg="#808080",
font=("FC Minimal", 10),
)
title_label.pack(pady=(0, 10))
# เก็บปุ่มไว้ใน dictionary เพื่อเข้าถึงได้ง่าย
self.section_buttons = {}
for text, section in sections:
button_frame = tk.Frame(self.buttons_panel, bg=appearance_manager.bg_color)
button_frame.pack(fill="x", pady=2)
btn = tk.Button(
button_frame,
text=text,
font=("Nasalization Rg", 10),
bg=appearance_manager.bg_color,
fg="white",
bd=0,
activebackground="#FF4444",
command=lambda s=section: self.show_section(s),
)
btn.pack(fill="x", padx=5)
# เก็บปุ่มไว้ใน dictionary
self.section_buttons[section] = btn
# Hover effects
btn.bind("<Enter>", lambda e, b=btn: b.configure(bg="#2A2A2A"))
btn.bind("<Leave>", lambda e, b=btn: self.handle_button_leave(b))
def handle_button_leave(self, button):
"""จัดการสีปุ่มเมื่อเมาส์ออก"""
# ถ้าปุ่มนี้เป็นปุ่มที่เลือกอยู่ ให้คงสีเดิมไว้
if hasattr(self, "current_section") and button == self.section_buttons.get(
self.current_section
):
button.configure(fg="yellow")
else:
button.configure(bg=appearance_manager.bg_color, fg="white")
def create_font_controls(self):
"""Create font selection controls with automatic apply"""
print("Creating font controls...")
font_frame = tk.Frame(self.buttons_panel, bg=appearance_manager.bg_color)
font_frame.pack(side="bottom", fill="x", pady=10)
# Font section title
tk.Label(
font_frame,
text="FONT SETTINGS",
bg=appearance_manager.bg_color,
fg="#808080",
font=("Nasalization Rg", 12),
).pack(pady=(0, 5))
# Font family selector
self.font_var = tk.StringVar(value=self.current_font)
font_dropdown = ttk.Combobox(
font_frame,
textvariable=self.font_var,
values=self.available_fonts,
width=20,
)
font_dropdown.pack(fill="x", padx=5, pady=2)
# Auto-apply on selection
font_dropdown.bind("<<ComboboxSelected>>", self.on_font_change)
self.window.after(
100, lambda: self.on_font_change(None)
) # Trigger font change after window creation
# Font size controls
size_frame = tk.Frame(font_frame, bg=appearance_manager.bg_color)
size_frame.pack(fill="x", padx=5, pady=5)
tk.Label(
size_frame, text="Size:", bg=appearance_manager.bg_color, fg="white"
).pack(side="left")
# Decrease size button
tk.Button(
size_frame,
text="−",
command=self.decrease_font_size,
bg="#2A2A2A",
fg="white",
width=2,
bd=0,
).pack(side="left", padx=2)
# Size label
self.size_label = tk.Label(
size_frame,
text=str(self.current_font_size),
bg=appearance_manager.bg_color,
fg="white",
width=3,
)
self.size_label.pack(side="left", padx=2)
# Increase size button
tk.Button(
size_frame,
text="+",
command=self.increase_font_size,
bg="#2A2A2A",
fg="white",
width=2,
bd=0,
).pack(side="left", padx=2)
print("Font controls created")
def setup_json_display(self):
"""Create the JSON display area with enhanced styling"""
print("Setting up JSON display...")
# Main container for JSON display
self.display_frame = tk.Frame(
self.content_panel, bg=appearance_manager.bg_color
)
self.display_frame.pack(fill="both", expand=True)
# Search container at top
search_frame = tk.Frame(self.display_frame, bg=appearance_manager.bg_color)
search_frame.pack(fill="x", pady=(5, 0))
# Search icon and entry
tk.Label(
search_frame, text="🔍", bg=appearance_manager.bg_color, fg="white"
).pack(side="left", padx=5)
self.search_var = tk.StringVar()
self.search_var.trace("w", self.on_search_change)
self.search_entry = tk.Entry(
search_frame,
textvariable=self.search_var,
bg="#2A2A2A",
fg="white",
insertbackground="white",
font=("Bai Jamjuree Light", 16),
)
self.search_entry.pack(fill="x", expand=True, padx=(0, 5))
# Action buttons container
action_frame = tk.Frame(self.display_frame, bg=appearance_manager.bg_color)
action_frame.pack(fill="x", pady=5)
# Save changes button
self.save_button = tk.Button(
action_frame,
text="SAVE CHANGES",
command=self.save_changes,
bg="#2A2A2A",
fg="white",
activebackground="#FF4444",
bd=0,
font=("Arial", 10, "bold"),
)
self.save_button.pack(side="right", padx=5)
# Text container with scrollbars
text_container = tk.Frame(self.display_frame, bg=appearance_manager.bg_color)
text_container.pack(fill="both", expand=True)
# Scrollbars
yscroll = ttk.Scrollbar(text_container, orient="vertical")
xscroll = ttk.Scrollbar(text_container, orient="horizontal")
# JSON text display
self.json_display = tk.Text(
text_container,
wrap=tk.NONE,
bg="#1A1A1A",
fg="white",
font=("Bai Jamjuree Light.ttf", 16),
insertbackground="white",
yscrollcommand=yscroll.set,
xscrollcommand=xscroll.set,
)
# Configure tags for search highlighting
self.json_display.tag_configure(
"search_highlight", background="#2ECC71", foreground="black"
)
# Configure scrollbars
yscroll.config(command=self.json_display.yview)
xscroll.config(command=self.json_display.xview)
# Grid layout
self.json_display.grid(row=0, column=0, sticky="nsew")
yscroll.grid(row=0, column=1, sticky="ns")
xscroll.grid(row=1, column=0, sticky="ew")
text_container.grid_rowconfigure(0, weight=1)
text_container.grid_columnconfigure(0, weight=1)
def validate_font(self, font_name):
"""Validate if font exists and is usable"""
return (
font_name in font.families()
or os.path.exists(font_name)
or font_name in self.available_fonts
)
def update_font_display(self):
"""Update font display in all relevant widgets"""
if hasattr(self, "json_display"):
try:
font_obj = font.Font(
family=self.current_font, size=self.current_font_size
)
self.json_display.configure(font=font_obj)
self.window.update_idletasks()
except Exception as e:
print(f"Font update failed: {e}")
self.revert_to_default_font()
def revert_to_default_font(self):
"""Revert to default font if current font fails"""
self.current_font = self.get_default_font()
self.update_font_display()
def load_data(self):
"""Load NPC data from JSON file"""
try:
with open("NPC.json", "r", encoding="utf-8") as file:
data = json.load(file)
# สรุปข้อมูลที่โหลด
summary = {
"main_characters": len(data.get("main_characters", [])),
"npcs": len(data.get("npcs", [])),
"lore": len(data.get("lore", {})),
"character_roles": len(data.get("character_roles", {})),
"word_fixes": len(data.get("word_fixes", {})),
}
print("NPC Data Summary:")
for category, count in summary.items():
print(f"- {category}: {count} entries")
return data
except FileNotFoundError:
print("Error: NPC.json file not found")
messagebox.showerror("Error", "NPC.json file not found!")
return {}
except json.JSONDecodeError:
print("Error: Invalid JSON in NPC.json")
messagebox.showerror("Error", "Invalid JSON in NPC.json!")
return {}
def flash_success_message(self, message):
"""Show floating success message with fade effect"""
print(f"Showing success message: {message}")
popup = tk.Toplevel(self.window)
popup.overrideredirect(True)
popup.configure(bg="#28a745")
popup.attributes("-alpha", 0.9)
# Position relative to window
x = self.window.winfo_x() + self.window.winfo_width() // 2
y = self.window.winfo_y() + self.window.winfo_height() // 2
popup.geometry(f"+{x}+{y}")
# Message label
label = tk.Label(
popup,
text=message,
fg="white",
bg="#28a745",
font=("Arial", 12),
padx=20,
pady=10,
)
label.pack()
# Fade effect
def fade_away():
alpha = popup.attributes("-alpha")
if alpha > 0:
popup.attributes("-alpha", alpha - 0.1)
popup.after(50, fade_away)
else:
popup.destroy()
popup.after(500, fade_away)
def setup_entry_form(self):
"""Create and configure the entry form for data input"""
print("Setting up entry form...")
self.entry_vars = {}
# Title container
title_container = tk.Frame(self.entry_panel, bg=appearance_manager.bg_color)
title_container.pack(fill="x", pady=10)
# Form title
self.form_title = tk.Label(
title_container,
text="ENTRY FORM",
font=("Nasalization Rg", 12),
bg=appearance_manager.bg_color,
fg="#808080",
)
self.form_title.pack()
# Scrollable container for fields
self.fields_container = tk.Frame(
self.entry_panel, bg=appearance_manager.bg_color
)
self.fields_container.pack(fill="both", expand=True, padx=10)
# Action buttons container (สร้างครั้งเดียว)
self.action_frame = tk.Frame(
self.entry_panel, bg=appearance_manager.bg_color, height=50
)
self.action_frame.pack(side="bottom", fill="x", padx=10, pady=10)
self.action_frame.pack_propagate(False)
# Add Entry button (สร้างครั้งเดียว)
self.add_btn = tk.Button(
self.action_frame,
text="ADD ENTRY",
command=self.add_entry,
bg="#2A2A2A",
fg="white",
activebackground="#FF4444",
bd=0,
font=("Arial", 10, "bold"),
)
self.add_btn.pack(fill="x", pady=(0, 5))
# Add hover effects
self.add_btn.bind("<Enter>", lambda e: self.add_btn.configure(bg="#404040"))
self.add_btn.bind("<Leave>", lambda e: self.add_btn.configure(bg="#2A2A2A"))
print("Entry form setup complete")
def setup_section_fields(self, section):
"""Create input fields based on section type"""
print(f"Setting up fields for section: {section}")
# Clear existing fields
for widget in self.fields_container.winfo_children():
widget.destroy()
# Define fields based on section
if section == "main_characters":
fields = ["firstName", "lastName", "gender", "role", "relationship"]
elif section == "npcs":
fields = ["name", "role", "description"]
elif section == "lore":
fields = ["term", "description"]
elif section == "character_roles":
fields = ["character", "style"]
elif section == "word_fixes":
fields = ["incorrect", "correct"]
else:
print(f"Unknown section: {section}")
return
# Create fields
print("Creating fields...")
self.entry_vars = {}
for field in fields:
field_frame = tk.Frame(
self.fields_container, bg=appearance_manager.bg_color
)
field_frame.pack(fill="x", pady=5)
# Label with hint
label = tk.Label(
field_frame,
text=field.capitalize(),
bg=appearance_manager.bg_color,
fg="#808080",
font=("Bai Jamjuree Light.ttf", 16),
) # ใช้ฟอนต์เดียวกับที่เลือก
label.pack(anchor="w")
# Entry field
if field in ["description", "style"]:
entry = tk.Text(
field_frame,
height=4,
bg="#2A2A2A",
fg="white",
insertbackground="white",
font=("Bai Jamjuree Light.ttf", 16),
) # ใช้ฟอนต์เดียวกับที่เลือก
entry.pack(fill="x")
self.entry_vars[field] = entry
else:
var = tk.StringVar()
self.entry_vars[field] = var
entry = tk.Entry(
field_frame,
textvariable=var,
bg="#2A2A2A",
fg="white",
insertbackground="white",
font=("Bai Jamjuree Light.ttf", 16),
) # ใช้ฟอนต์เดียวกับที่เลือก
entry.pack(fill="x")
def show_section(self, section):
"""Display and setup selected section"""
print(f"Showing section: {section}")
self.current_section = section
self.setup_section_fields(section)
# Clear search when changing sections
if hasattr(self, "search_var"):
self.search_var.set("")
self.update_json_display()
# Update form title
section_title = section.replace("_", " ").title()
self.form_title.configure(text=f"{section_title} Entry")
# อัพเดทสีของทุกปุ่ม
for section_id, btn in self.section_buttons.items():
if section_id == self.current_section:
btn.configure(bg="#2A2A2A", fg="yellow") # ปุ่มที่เลือก
else:
btn.configure(bg=appearance_manager.bg_color, fg="white") # ปุ่มอื่นๆ
def add_entry(self):
"""Add or update entry in the current section"""
if not self.current_section:
print("No section selected")
return
print("Adding new entry...")
# Collect field values
new_entry = {}
for field, var in self.entry_vars.items():
if isinstance(var, tk.Text):
value = var.get("1.0", tk.END).strip()
else:
value = var.get().strip()
new_entry[field] = value
# ตรวจสอบเฉพาะฟิลด์แรกของแต่ละส่วน
required_first_fields = {
"main_characters": "firstName",
"npcs": "name",
"lore": "term",
"character_roles": "character",
"word_fixes": "incorrect",
}
first_field = required_first_fields.get(self.current_section)
if not first_field or not new_entry.get(first_field):
print(f"Validation failed: Required field {first_field} is empty")
messagebox.showwarning("Warning", f"The field '{first_field}' is required.")
return
try:
# จัดการข้อมูลตามประเภท
if self.current_section in ["main_characters", "npcs"]:
self.add_list_entry(new_entry)
else:
self.add_dict_entry(new_entry)
# เคลียร์ฟอร์มและอัพเดทการแสดงผล
self.clear_entry_fields()
self.update_json_display()
self.flash_success_message("Entry added successfully!")
print("Entry added successfully")
except Exception as e:
print(f"Error adding entry: {e}")
messagebox.showerror("Error", f"Failed to add entry: {str(e)}")
def add_list_entry(self, new_entry):
"""Add entry to list-type sections"""
key_field = "firstName" if self.current_section == "main_characters" else "name"
print(f"Adding list entry with {key_field}: {new_entry[key_field]}")
if not self.current_section in self.data:
self.data[self.current_section] = []
# Check for existing entry
entries = self.data[self.current_section]
for i, entry in enumerate(entries):
if entry.get(key_field, "").lower() == new_entry[key_field].lower():
if messagebox.askyesno(
"Update Entry",
f"Entry with {key_field} '{new_entry[key_field]}' exists.\n"
"Do you want to update it?",
):
entries[i] = new_entry
print("Entry updated")
return
return
# Add new entry
entries.append(new_entry)
print("New entry added to list")
def add_dict_entry(self, new_entry):
"""Add entry to dictionary-type sections"""
if not self.current_section in self.data:
self.data[self.current_section] = {}
# Determine key and value based on section
if self.current_section == "lore":
key, value = new_entry["term"], new_entry["description"]
elif self.current_section == "character_roles":
key, value = new_entry["character"], new_entry["style"]
else: # word_fixes
key, value = new_entry["incorrect"], new_entry["correct"]
print(f"Adding dictionary entry: {key}")
# Check for existing entry
if key in self.data[self.current_section]:
if messagebox.askyesno(
"Update Entry",
f"Entry for '{key}' exists.\n" "Do you want to update it?",
):
self.data[self.current_section][key] = value
print("Entry updated")
else:
self.data[self.current_section][key] = value
print("New entry added to dictionary")
def clear_entry_fields(self):
"""Clear all entry fields"""
print("Clearing entry fields")
for var in self.entry_vars.values():
if isinstance(var, tk.Text):
var.delete("1.0", tk.END)
else:
var.set("")
def on_search_change(self, *args):
"""Handle real-time search with highlighting"""
try:
search_term = self.search_var.get().lower()
if not self.current_section or not self.json_display:
return
# Get current text
current_text = self.json_display.get("1.0", tk.END)
# Remove existing highlights
self.json_display.tag_remove("search_highlight", "1.0", tk.END)
if search_term:
# Find and highlight matches
start_idx = "1.0"
first_match = None
while True:
# Find next match
start_idx = self.json_display.search(
search_term, start_idx, tk.END, nocase=True
)
if not start_idx:
break
# Calculate end index
end_idx = f"{start_idx}+{len(search_term)}c"
# Add highlight
self.json_display.tag_add("search_highlight", start_idx, end_idx)
# Store first match
if not first_match:
first_match = start_idx
# Move to next position
start_idx = end_idx
# Scroll to first match if found
if first_match:
self.json_display.see(first_match)
except Exception as e:
print(f"Search error: {e}")
def start_move(self, event):
"""Start window drag operation"""
self.x = event.x
self.y = event.y
def do_move(self, event):
"""Handle window dragging"""
try:
deltax = event.x - self.x
deltay = event.y - self.y
x = self.window.winfo_x() + deltax
y = self.window.winfo_y() + deltay
self.window.geometry(f"+{x}+{y}")
except Exception as e:
print(f"Move error: {e}")
def start_resize(self, event):
"""Initialize window resize operation"""
self.is_resizing = True
self.resize_x = event.x_root
self.resize_y = event.y_root
self.resize_w = self.window.winfo_width()
self.resize_h = self.window.winfo_height()
print("\rStarting resize operation...", end="", flush=True)
def on_resize(self, event):
"""Handle window resizing"""
if not self.is_resizing:
return
try:
dx = event.x_root - self.resize_x
dy = event.y_root - self.resize_y
w = max(800, self.resize_w + dx)
h = max(600, self.resize_h + dy)
self.window.geometry(f"{w}x{h}")
# No logging during resize
except Exception as e:
print(f"\rResize error: {e}", end="", flush=True)
def stop_resize(self, event):
"""End window resize operation"""
if self.is_resizing:
final_w = self.window.winfo_width()
final_h = self.window.winfo_height()
print(f"\rResize complete - New size: {final_w}x{final_h}")
self.is_resizing = False
def update_json_display(self, search_term=None):
"""อัพเดทการแสดงผล JSON พร้อมรักษา formatting"""
if not self.current_section or self.current_section not in self.data:
print(f"No data for section: {self.current_section}")
self.json_display.delete("1.0", tk.END)
return
try:
section_data = self.data[self.current_section]
# จัดรูปแบบ JSON ให้สวยงาม
json_text = json.dumps(section_data, indent=4, ensure_ascii=False)
# เก็บตำแหน่ง scroll ปัจจุบัน
current_scroll = None
if hasattr(self.json_display, "yview"):
current_scroll = self.json_display.yview()
# อัพเดทข้อความ
self.json_display.config(state="normal")
self.json_display.delete("1.0", tk.END)
self.json_display.insert("1.0", json_text)
# ถ้ามีคำค้นหา ให้ไฮไลท์
if search_term:
self.highlight_search_term(search_term)
# คืนค่า scroll position
if current_scroll:
self.json_display.yview_moveto(current_scroll[0])
except Exception as e:
print(f"Failed to update display: {e}")
messagebox.showerror("Error", f"Failed to update display: {str(e)}")
def highlight_search_term(self, search_term):
"""ไฮไลท์คำที่ค้นหา โดยไม่ใช้ canvas"""
if not search_term:
return
try:
# ลบไฮไลท์เก่า
self.json_display.tag_remove("search_highlight", "1.0", tk.END)
# ค้นหาและไฮไลท์คำใหม่
start_idx = "1.0"
while True:
start_idx = self.json_display.search(
search_term.lower(), start_idx, tk.END, nocase=True
)
if not start_idx:
break
end_idx = f"{start_idx}+{len(search_term)}c"
self.json_display.tag_add("search_highlight", start_idx, end_idx)
start_idx = end_idx
except Exception as e:
print(f"Highlight error: {e}")
def update_data_from_display(self):
"""อัพเดทข้อมูลจาก json_display กลับไปที่ self.data"""
try:
if not self.current_section:
return False
# ดึงข้อความจาก display
json_text = self.json_display.get("1.0", tk.END).strip()
if not json_text:
return False
# แปลง JSON string เป็น Python object
updated_data = json.loads(json_text)
# ตรวจสอบรูปแบบข้อมูล
if self.current_section in ["main_characters", "npcs"]:
if not isinstance(updated_data, list):
raise ValueError(f"Invalid data format for {self.current_section}")
else:
if not isinstance(updated_data, dict):
raise ValueError(f"Invalid data format for {self.current_section}")
# อัพเดทข้อมูลในส่วนที่กำลังแก้ไข
self.data[self.current_section] = updated_data
return True
except json.JSONDecodeError as e:
messagebox.showerror("Error", f"Invalid JSON format: {str(e)}")
return False
except Exception as e:
messagebox.showerror("Error", f"Failed to update data: {str(e)}")
return False
def save_changes(self):
"""บันทึกการเปลี่ยนแปลงลงไฟล์"""
print("Saving changes to file...")
try:
if not self.update_data_from_display():
return
required_sections = [
"main_characters",
"npcs",
"lore",
"character_roles",
"word_fixes",
]
for section in required_sections:
if section not in self.data:
raise ValueError(f"Missing required section: {section}")
with open("NPC.json", "w", encoding="utf-8") as file:
json.dump(self.data, file, indent=4, ensure_ascii=False)
self.flash_success_message("Changes saved successfully!")
print("Changes saved successfully")
# เรียกใช้ callback เพื่อรีโหลดข้อมูล
if self.reload_callback:
print("Triggering NPC data reload...")
self.reload_callback()
self.flash_success_message("NPC context reloaded!")
except Exception as e:
error_msg = f"Failed to save changes: {str(e)}"
print(f"Save error: {error_msg}")
messagebox.showerror("Error", error_msg)
def reload_npc_data(self):
"""เรียกใช้ฟังก์ชัน reload ใน main app"""
try:
# ส่งสัญญาณไปที่ main app
if hasattr(self.parent, "reload_npc_data"):
self.parent.reload_npc_data()
self.flash_success_message("Reloading NPC context data...")
# delay นิดหน่อยก่อนแสดงข้อความสำเร็จ
self.window.after(
1000,
lambda: self.flash_success_message(
"NPC context reloaded successfully!"
),
)
except Exception as e:
messagebox.showerror("Error", f"Failed to reload NPC data: {str(e)}")
def increase_font_size(self):
"""Increase font size by one step"""
print("Increasing font size")
current_idx = self.font_sizes.index(self.current_font_size)
if current_idx < len(self.font_sizes) - 1:
self.current_font_size = self.font_sizes[current_idx + 1]
self.update_font_size()
print(f"New font size: {self.current_font_size}")
def decrease_font_size(self):
"""Decrease font size by one step"""
print("Decreasing font size")
current_idx = self.font_sizes.index(self.current_font_size)
if current_idx > 0:
self.current_font_size = self.font_sizes[current_idx - 1]
self.update_font_size()
print(f"New font size: {self.current_font_size}")
def update_font_size(self):
"""Update font size in JSON display and size label"""
print(f"Updating font size to: {self.current_font_size}")
try:
if hasattr(self, "json_display"):
# Store current text and state
current_text = self.json_display.get("1.0", tk.END)
current_state = self.json_display.cget("state")
# Enable for changes
self.json_display.config(state="normal")
# Update font
self.json_display.configure(
font=(self.current_font, self.current_font_size)
)
# Reapply text
self.json_display.delete("1.0", tk.END)
self.json_display.insert("1.0", current_text)
# Restore state
self.json_display.config(state=current_state)
# Update size label
if hasattr(self, "size_label"):
self.size_label.configure(text=str(self.current_font_size))
print("Font size update complete")
except Exception as e:
print(f"Font size update error: {e}")
messagebox.showerror("Error", f"Failed to update font size: {str(e)}")
def on_font_change(self, event=None):
"""Handle font change with automatic apply"""
new_font = self.font_var.get()
print(f"Font change requested to: {new_font}")
if new_font in self.available_fonts:
try:
self.current_font = new_font
# Update json display
if hasattr(self, "json_display"):
self.json_display.configure(font=(new_font, self.current_font_size))
# Update entry fields
for var in self.entry_vars.values():
if isinstance(var, tk.Text):
var.configure(font=(new_font, self.current_font_size))
self.flash_success_message(f"Font changed to {new_font}")
print("Font change successful")
except Exception as e:
print(f"Font change error: {e}")
self.revert_to_default_font()
def on_window_configure(self, event):
"""Handle window resize events"""
if event and event.widget == self.window and not self.is_resizing:
# Update component positions silently
self.close_button.place(x=self.window.winfo_width() - 30, y=5)
self.resize_handle.place(relx=1, rely=1, anchor="se")
# Maintain minimum size without logging
if event.width < 800:
self.window.geometry(f"800x{event.height}")
if event.height < 600:
self.window.geometry(f"{event.width}x600")
def find_and_display_character(self, character_name: str, is_verified: bool = False) -> None:
try:
# Clear any existing search
if hasattr(self, 'search_var'):
self.search_var.set('')
character_found = False
# Check main characters first
for char in self.data.get('main_characters', []):
if (character_name == char['firstName'] or
character_name == f"{char['firstName']} {char['lastName']}".strip()):
self.show_section('main_characters')
self.search_var.set(character_name)
character_found = True
self.logging_manager.log_npc_manager(f"Found character in main_characters: {character_name}")
break
# If not found in main characters, check NPCs
if not character_found:
for npc in self.data.get('npcs', []):
if character_name == npc['name']:
self.show_section('npcs')
self.search_var.set(character_name)
character_found = True
self.logging_manager.log_npc_manager(f"Found character in NPCs: {character_name}")
break
# If character not found anywhere, prepare for new entry
if not character_found:
self._prepare_new_character_form(character_name)
self.logging_manager.log_npc_manager(f"Preparing form for new character: {character_name}")
except Exception as e:
error_msg = f"Error finding character {character_name}: {e}"
self.logging_manager.log_error(error_msg)
self.flash_message(error_msg, "error")
def _prepare_new_character_form(self, character_name: str) -> None:
"""
เตรียมฟอร์มสำหรับเพิ่มตัวละครใหม่ โดยใส่ชื่อเต็มในช่องเดียว
Args:
character_name: ชื่อตัวละครที่ต้องการเพิ่ม
"""
try:
# Show main characters section for new entry
self.show_section('main_characters')
# Clear existing form fields
for var in self.entry_vars.values():
if isinstance(var, tk.Text):
var.delete('1.0', tk.END)
else:
var.set('')
# ใส่ชื่อเต็มในช่อง firstName โดยไม่แยกนามสกุล
clean_name = character_name.strip(":!?. ")
self.entry_vars['firstName'].set(clean_name)
# Set default values for other fields
self.entry_vars['gender'].set('Neutral')
self.entry_vars['role'].set('Adventure')
self.entry_vars['relationship'].set('Neutral')
# Show helper message
self.flash_success_message(f"Ready to add new character: {clean_name}")
self.logging_manager.log_info(f"Prepared form for new character: {clean_name}")
except Exception as e:
self.logging_manager.log_error(f"Error preparing new character form: {e}")
self.flash_message(f"Error preparing form: {str(e)}", "error")
def flash_message(self, message: str, message_type: str = "info") -> None:
"""
แสดงข้อความแจ้งเตือนแบบ fade
Args:
message: ข้อความที่ต้องการแสดง
message_type: ประเภทข้อความ ('info', 'error', 'success')
"""
# กำหนดสีตามประเภทข้อความ
colors = {
'info': '#2196F3', # สีฟ้า
'error': '#F44336', # สีแดง
'success': '#4CAF50' # สีเขียว
}
bg_color = colors.get(message_type, colors['info'])
popup = tk.Toplevel(self.window)
popup.overrideredirect(True)
popup.configure(bg=bg_color)
popup.attributes('-alpha', 0.9)
# จัดตำแหน่งกลางหน้าต่าง
x = self.window.winfo_x() + self.window.winfo_width() // 2
y = self.window.winfo_y() + self.window.winfo_height() // 2
popup.geometry(f"+{x}+{y}")
# สร้าง label สำหรับข้อความ
label = tk.Label(
popup,
text=message,
fg='white',
bg=bg_color,
font=('Arial', 12),
padx=20,
pady=10
)
label.pack()
# ฟังก์ชัน fade effect
def fade_away():
alpha = popup.attributes('-alpha')
if alpha > 0:
popup.attributes('-alpha', alpha - 0.1)
popup.after(50, fade_away)
else:
popup.destroy()
popup.after(1000, fade_away)
def show_window(self):
"""Show the NPC Manager window"""
print("Showing NPC Manager window")
self.window.deiconify()
if not self.current_section and self.data:
first_section = next(iter(self.data.keys()))
self.show_section(first_section)
print(f"Auto-selected first section: {first_section}")
def hide_window(self):
"""Hide the NPC Manager window"""
print("Hiding NPC Manager window")
self.window.withdraw()
def is_window_showing(self):
"""Check if NPC Manager window is currently visible"""
return (hasattr(self, "window") and
self.window.winfo_exists() and
self.window.state() != "withdrawn")
def toggle_window(self):
"""Toggle window visibility"""
if self.is_window_showing():
self.window.withdraw()
else:
self.show_window()
def cleanup(self):
"""Cleanup resources before closing"""
try:
self.logging_manager.log_info("Cleaning up NPC Manager resources")
# ทำความสะอาด resources ต่างๆ
if hasattr(self, 'window') and self.window.winfo_exists():
self.window.withdraw()
# เคลียร์ค่าต่างๆ
if hasattr(self, 'search_var'):
self.search_var.set('')
# เคลียร์ entry fields
for var in self.entry_vars.values():
if isinstance(var, tk.Text):
var.delete('1.0', tk.END)
else:
var.set('')
except Exception as e:
self.logging_manager.log_error(f"Error during cleanup: {e}")
def create_npc_manager(parent, reload_callback=None, logging_manager=None):
"""Create and return a new NPC Manager instance"""
return NPCManager(parent, reload_callback, logging_manager)
# Main entry point
if __name__ == "__main__":
root = tk.Tk()
app = create_npc_manager(root)
root.mainloop()
|