MagiciteBabel / npc_manager.py
iarcanar's picture
Upload 23 files
3bb13c3 verified
Raw
History Blame Contribute Delete
51.6 kB
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()