| import time
|
| import tkinter as tk
|
| from tkinter import ttk
|
| from PIL import ImageTk, Image
|
| import logging
|
| import os
|
| import math
|
| from tkinter import colorchooser
|
| from typing import Optional, Dict, List, Tuple, Callable, Any, Union
|
| from dataclasses import dataclass
|
| from appearance import appearance_manager
|
| from settings import Settings
|
| from tkinter import ttk, messagebox
|
|
|
| logging.basicConfig(level=logging.INFO)
|
|
|
|
|
| @dataclass
|
| class UIState:
|
| """Class for managing UI state"""
|
|
|
| is_locked: bool = False
|
| is_typing: bool = False
|
| blinking: bool = False
|
| arrow_visible: bool = False
|
| arrow_blinking: bool = False
|
| buttons_visible: bool = True
|
| full_text: str = ""
|
| typing_timer: Optional[str] = None
|
| last_name: Optional[str] = None
|
|
|
|
|
| class UIComponents:
|
| """Class for managing UI components references"""
|
|
|
| def __init__(self):
|
| self.main_frame: Optional[tk.Frame] = None
|
| self.text_frame: Optional[tk.Frame] = None
|
| self.canvas: Optional[tk.Canvas] = None
|
| self.control_area: Optional[tk.Frame] = None
|
| self.scrollbar: Optional[ttk.Scrollbar] = None
|
| self.buttons: Dict[str, tk.Button] = {}
|
| self.text_container: Optional[int] = None
|
| self.outline_container: List[int] = []
|
| self.arrow_label: Optional[tk.Label] = None
|
|
|
|
|
| class Translated_UI:
|
| """Main class for translation window UI"""
|
|
|
| def __init__(
|
| self,
|
| root: tk.Tk,
|
| toggle_translation: Callable,
|
| stop_translation: Callable,
|
| force_translate: Callable,
|
| toggle_main_ui: Callable,
|
| toggle_ui: Callable,
|
| settings: Settings,
|
| switch_area: Callable,
|
| logging_manager: Any,
|
| character_names: Optional[set] = None,
|
| main_app=None
|
| ):
|
| self.root = root
|
| self.toggle_translation = toggle_translation
|
| self.stop_translation = stop_translation
|
| self.force_translate = force_translate
|
| self.toggle_main_ui = toggle_main_ui
|
| self.toggle_ui = toggle_ui
|
| self.settings = settings
|
| self.switch_area = switch_area
|
| self.logging_manager = logging_manager
|
| self.names = character_names or set()
|
| self.lock_mode = 0
|
| self.main_app = main_app
|
|
|
|
|
| self.state = UIState()
|
| self.components = UIComponents()
|
|
|
|
|
| self.x: Optional[int] = None
|
| self.y: Optional[int] = None
|
|
|
|
|
| self.load_icons()
|
|
|
|
|
| self.last_resize_time = 0
|
| self.resize_throttle = 0.016
|
|
|
|
|
| self.setup_ui()
|
| self.setup_bindings()
|
| self._setup_character_name_binding()
|
| logging.info("TranslatedUI initialized successfully")
|
|
|
| def load_icons(self) -> None:
|
| """Load and prepare all required icons"""
|
| try:
|
|
|
| confirm_icon = Image.open("confirm.png")
|
| confirm_icon = confirm_icon.resize((28, 28))
|
| self.confirm_icon = ImageTk.PhotoImage(confirm_icon)
|
|
|
|
|
| button_size = 20
|
| self.lock_image = ImageTk.PhotoImage(
|
| Image.open("lock.png").resize((button_size, button_size))
|
| )
|
| self.unlock_image = ImageTk.PhotoImage(
|
| Image.open("unlock.png").resize((button_size, button_size))
|
| )
|
| self.bg_lock_image = ImageTk.PhotoImage(
|
| Image.open("BG_lock.png").resize((button_size, button_size))
|
| )
|
|
|
|
|
| self.force_image = ImageTk.PhotoImage(
|
| Image.open("s_force.png").resize((button_size, button_size))
|
| )
|
|
|
| except Exception as e:
|
| logging.error(f"Error loading icons: {e}")
|
| self.confirm_icon = None
|
|
|
|
|
| def setup_ui(self) -> None:
|
| """Initialize and setup all UI components"""
|
| self.root.title("Translated Text")
|
| self.root.geometry(
|
| f"{self.settings.get('width')}x{self.settings.get('height')}"
|
| )
|
| self.root.overrideredirect(True)
|
| self.root.attributes("-topmost", True)
|
| self.custom_font = appearance_manager.apply_style(self.root)
|
|
|
|
|
| self.root.configure(bd=0, highlightthickness=0)
|
|
|
|
|
| self.components.main_frame = tk.Frame(
|
| self.root,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| )
|
| self.components.main_frame.pack(fill=tk.BOTH, expand=True)
|
|
|
|
|
| self.components.text_frame = tk.Frame(
|
| self.components.main_frame,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| )
|
| self.components.text_frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
|
|
|
|
|
| self.components.control_area = tk.Frame(
|
| self.components.main_frame,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| width=30,
|
| )
|
| self.components.control_area.pack(side=tk.RIGHT, fill=tk.Y)
|
| self.components.control_area.pack_propagate(False)
|
|
|
|
|
| self.resize_handle = tk.Label(
|
| self.components.main_frame,
|
| text="✦",
|
| bg="#2A2A2A",
|
| fg="white",
|
| font=("Arial", 12, "bold"),
|
| cursor="sizing",
|
| bd=0,
|
| highlightthickness=0,
|
| )
|
| self.resize_handle.place(relx=1.0, rely=1.0, anchor="se")
|
|
|
|
|
| self.setup_canvas_and_text()
|
| self.setup_scrollbar()
|
| self.setup_buttons()
|
|
|
| def setup_canvas_and_text(self) -> None:
|
| """Setup canvas and text display area with fonts and styling"""
|
|
|
| self.components.canvas = tk.Canvas(
|
| self.components.text_frame,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| relief="flat",
|
| )
|
| self.components.canvas.pack(
|
| side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(10, 85), pady=(10, 20)
|
| )
|
|
|
|
|
| font_name = self.settings.get("font", "IBM Plex Sans Thai Medium")
|
| font_size = self.settings.get("font_size", 24)
|
|
|
| self.components.text_container = self.components.canvas.create_text(
|
| 10,
|
| 10,
|
| anchor="nw",
|
| font=(font_name, font_size),
|
| fill=appearance_manager.fg_color,
|
| width=self.components.text_frame.winfo_width() - 90,
|
| text="",
|
| )
|
|
|
| self.components.outline_container = []
|
|
|
|
|
| self.components.arrow_label = tk.Label(
|
| self.components.main_frame,
|
| text="▼",
|
| font=("Arial", 16),
|
| fg="white",
|
| bg=appearance_manager.bg_color,
|
| )
|
| self.components.arrow_label.place(relx=0.8, rely=0.88, anchor="se", x=-55)
|
| self.components.arrow_label.lower()
|
|
|
| def setup_scrollbar(self) -> None:
|
| """Setup and configure custom scrollbar"""
|
| style = ttk.Style()
|
| style.theme_use("clam")
|
|
|
|
|
| style.configure(
|
| "Modern.Vertical.TScrollbar",
|
| background="#333333",
|
| troughcolor="#1a1a1a",
|
| bordercolor="#1a1a1a",
|
| arrowcolor="#666666",
|
| relief="flat",
|
| borderwidth=0,
|
| width=8,
|
| )
|
|
|
| self.components.scrollbar = ttk.Scrollbar(
|
| self.components.text_frame,
|
| command=self.components.canvas.yview,
|
| style="Modern.Vertical.TScrollbar",
|
| )
|
|
|
|
|
| self.components.scrollbar.place(
|
| x=self.components.text_frame.winfo_width() - 80,
|
| y=0,
|
| relheight=0.95,
|
| anchor="ne",
|
| )
|
|
|
|
|
| self.components.canvas.configure(
|
| yscrollcommand=self.scrollbar_command,
|
| scrollregion=(0, 0, 0, self.components.text_frame.winfo_height() + 50),
|
| )
|
|
|
| def setup_buttons(self) -> None:
|
| """Initialize and setup all control buttons"""
|
| button_size = 20
|
|
|
|
|
| self.components.buttons["close"] = tk.Button(
|
| self.components.control_area,
|
| text="X",
|
| command=self.close_window,
|
| bg=appearance_manager.bg_color,
|
| fg="white",
|
| bd=0,
|
| width=1,
|
| font=(self.settings.get("font"), 12),
|
| cursor="hand2",
|
| activebackground=appearance_manager.bg_color,
|
| activeforeground="white",
|
| )
|
| self.components.buttons["close"].pack(side=tk.TOP, pady=(5, 5))
|
|
|
|
|
| self.components.buttons["lock"] = tk.Button(
|
| self.components.control_area,
|
| image=self.lock_image,
|
| command=self.toggle_lock,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| relief="flat",
|
| compound="center",
|
| cursor="hand2",
|
| activebackground=appearance_manager.bg_color,
|
| )
|
| self.components.buttons["lock"].pack(side=tk.TOP, pady=5)
|
|
|
|
|
| self.components.buttons["color"] = tk.Button(
|
| self.components.control_area,
|
| command=self.change_bg_color,
|
| bg=self.settings.get("bg_color", appearance_manager.bg_color),
|
| bd=1,
|
| relief="solid",
|
| width=1,
|
| height=1,
|
| cursor="hand2",
|
| activebackground=self.settings.get("bg_color", appearance_manager.bg_color),
|
| )
|
| self.components.buttons["color"].pack(side=tk.TOP, pady=5)
|
|
|
|
|
| self.components.buttons["force"] = tk.Button(
|
| self.components.control_area,
|
| image=self.force_image,
|
| command=self.force_translate,
|
| bg=appearance_manager.bg_color,
|
| bd=0,
|
| highlightthickness=0,
|
| relief="flat",
|
| compound="center",
|
| cursor="hand2",
|
| activebackground=appearance_manager.bg_color,
|
| )
|
| self.components.buttons["force"].pack(side=tk.TOP, pady=5)
|
|
|
| def scrollbar_command(self, *args) -> None:
|
| """
|
| Handle scrollbar movement and arrow visibility
|
| Args:
|
| *args: Scrollbar position arguments (start, end)
|
| """
|
| self.components.scrollbar.set(*args)
|
|
|
| try:
|
|
|
| scroll_position = float(args[1])
|
| max_scroll = 0.95
|
|
|
|
|
| bbox = self.components.canvas.bbox("all")
|
| if bbox is not None:
|
| if scroll_position >= max_scroll:
|
| self.hide_overflow_arrow()
|
| elif bbox[3] > self.components.canvas.winfo_height():
|
| self.show_overflow_arrow()
|
| else:
|
| self.hide_overflow_arrow()
|
|
|
| except (TypeError, IndexError) as e:
|
| logging.warning(f"Error in scrollbar_command: {str(e)}")
|
| self.hide_overflow_arrow()
|
|
|
| def setup_bindings(self) -> None:
|
| """Setup all event bindings for the UI"""
|
|
|
| self.root.bind("<Button-1>", self.on_click)
|
| self.root.bind("<ButtonRelease-1>", self.stop_move)
|
| self.root.bind("<B1-Motion>", self.on_drag)
|
| self.components.canvas.bind("<Button-1>", self.show_full_text)
|
| self.components.canvas.bind("<Configure>", self.on_canvas_configure)
|
| self.components.canvas.bind("<MouseWheel>", self.on_mousewheel)
|
|
|
|
|
| for widget in [
|
| self.components.main_frame,
|
| self.components.text_frame,
|
| self.root,
|
| ]:
|
| widget.bind("<MouseWheel>", self.on_mousewheel)
|
|
|
|
|
| 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)
|
|
|
|
|
| widgets_to_bind = [
|
| self.components.main_frame,
|
| self.components.text_frame,
|
| self.components.canvas,
|
| self.root,
|
| ]
|
|
|
| for widget in widgets_to_bind:
|
| widget.bind("<Enter>", self.on_hover_enter)
|
|
|
| def is_mouse_in_ui(self, event: tk.Event) -> bool:
|
| """
|
| Check if mouse is within any UI component
|
| Args:
|
| event: Mouse event containing coordinates
|
| Returns:
|
| bool: True if mouse is within UI bounds
|
| """
|
| x, y = event.x_root, event.y_root
|
| widgets_to_check = [
|
| self.components.main_frame,
|
| self.components.text_frame,
|
| self.components.canvas,
|
| self.root,
|
| ]
|
|
|
| for widget in widgets_to_check:
|
| try:
|
| widget_x = widget.winfo_rootx()
|
| widget_y = widget.winfo_rooty()
|
| widget_width = widget.winfo_width()
|
| widget_height = widget.winfo_height()
|
|
|
| if (
|
| widget_x <= x <= widget_x + widget_width
|
| and widget_y <= y <= widget_y + widget_height
|
| ):
|
| return True
|
| except Exception:
|
| continue
|
| return False
|
|
|
| def show_overflow_arrow(self) -> None:
|
| """Show and start blinking the overflow arrow indicator"""
|
| if not self.state.arrow_visible:
|
| self.state.arrow_visible = True
|
| self.components.arrow_label.lift()
|
| self.blink_arrow()
|
|
|
| def hide_overflow_arrow(self) -> None:
|
| """Hide and stop blinking the overflow arrow indicator"""
|
| self.state.arrow_visible = False
|
| self.state.arrow_blinking = False
|
| self.components.arrow_label.lower()
|
|
|
| def blink_arrow(self) -> None:
|
| """Start arrow blinking animation if not already blinking"""
|
| if self.state.arrow_visible and not self.state.arrow_blinking:
|
| self.state.arrow_blinking = True
|
| self.do_blink()
|
|
|
| def do_blink(self) -> None:
|
| """Handle arrow blinking animation"""
|
| if self.state.arrow_visible and self.state.arrow_blinking:
|
| current_color = self.components.arrow_label.cget("fg")
|
| new_color = (
|
| "white"
|
| if current_color == appearance_manager.bg_color
|
| else appearance_manager.bg_color
|
| )
|
| self.components.arrow_label.config(fg=new_color)
|
| self.root.after(500, self.do_blink)
|
| else:
|
| self.components.arrow_label.config(fg="white")
|
|
|
| def update_text(self, text: str) -> None:
|
| """
|
| Update the displayed text with typewriter effect
|
| Args:
|
| text: Text to display
|
| """
|
| try:
|
| logging.info(f"Updating text in UI: {text}")
|
| if not text:
|
| return
|
|
|
|
|
| outline_offset = 1
|
| outline_color = "#000000"
|
| outline_positions = [
|
| (-1, -1),
|
| (-1, 0),
|
| (-1, 1),
|
| (0, -1),
|
| (0, 1),
|
| (1, -1),
|
| (1, 0),
|
| (1, 1),
|
| ]
|
|
|
|
|
| self.components.canvas.delete("all")
|
| self.components.canvas.yview_moveto(0)
|
|
|
|
|
| current_font_size = self.settings.get("font_size", 24)
|
| small_font_size = int(current_font_size * 0.7)
|
|
|
|
|
| dialogue_font = (self.settings.get("font"), current_font_size)
|
| small_font = (self.settings.get("font"), small_font_size)
|
|
|
| self.state.full_text = text
|
| available_width = self.components.canvas.winfo_width() - 40
|
|
|
|
|
| if text.startswith("คุณจะพูดว่าอย่างไร?") or text.startswith(
|
| "What will you say?"
|
| ):
|
| self._handle_choice_text(
|
| text,
|
| small_font,
|
| dialogue_font,
|
| available_width,
|
| outline_positions,
|
| outline_offset,
|
| outline_color,
|
| )
|
| else:
|
| self._handle_normal_text(
|
| text,
|
| small_font,
|
| dialogue_font,
|
| available_width,
|
| outline_positions,
|
| outline_offset,
|
| outline_color,
|
| )
|
|
|
| except Exception as e:
|
| logging.error(f"Error in update_text: {e}")
|
| self._show_error(str(e))
|
|
|
| def update_character_names(self, new_names):
|
| """อัพเดตรายชื่อตัวละครและรีเฟรช UI"""
|
| self.names = new_names
|
|
|
|
|
| if hasattr(self, "state") and self.state.full_text:
|
| current_text = self.state.full_text
|
| self.update_text(current_text)
|
|
|
| def _handle_choice_text(
|
| self,
|
| text: str,
|
| small_font: tuple,
|
| dialogue_font: tuple,
|
| available_width: int,
|
| outline_positions: list,
|
| outline_offset: int,
|
| outline_color: str,
|
| ) -> None:
|
| """
|
| Handle choice dialogue text display
|
| Args:
|
| text: Full text to display
|
| small_font: Font tuple for header
|
| dialogue_font: Font tuple for choices
|
| available_width: Available width for text
|
| outline_positions: List of outline position offsets
|
| outline_offset: Outline offset value
|
| outline_color: Color for text outline
|
| """
|
|
|
| if "คุณจะพูดว่าอย่างไร?" in text:
|
| header = "คุณจะพูดว่าอย่างไร?"
|
| choices = text.replace(header, "", 1).strip()
|
| else:
|
| header = "What will you say?"
|
| choices = text.replace(header, "", 1).strip()
|
|
|
|
|
| choices = choices.strip("\n")
|
|
|
|
|
| for dx, dy in outline_positions:
|
| outline = self.components.canvas.create_text(
|
| 10 + dx * outline_offset,
|
| 10 + dy * outline_offset,
|
| anchor="nw",
|
| font=small_font,
|
| fill=outline_color,
|
| text=header,
|
| width=available_width,
|
| tags=("header_outline",),
|
| )
|
|
|
|
|
| header_text = self.components.canvas.create_text(
|
| 10,
|
| 10,
|
| anchor="nw",
|
| font=small_font,
|
| fill="#FFD700",
|
| text=header,
|
| width=available_width,
|
| )
|
|
|
|
|
| header_bbox = self.components.canvas.bbox(header_text)
|
| choices_y = header_bbox[3] + 10
|
|
|
|
|
| self.components.outline_container = []
|
| for dx, dy in outline_positions:
|
| outline = self.components.canvas.create_text(
|
| 10 + dx * outline_offset,
|
| choices_y + dy * outline_offset,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill=outline_color,
|
| text="",
|
| width=available_width,
|
| tags=("choices_outline",),
|
| )
|
| self.components.outline_container.append(outline)
|
|
|
|
|
| self.components.text_container = self.components.canvas.create_text(
|
| 10,
|
| choices_y,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill="white",
|
| text="",
|
| width=available_width,
|
| tags=("choices",),
|
| )
|
|
|
|
|
| self.dialogue_text = choices
|
| if hasattr(self, "type_writer_timer"):
|
| self.root.after_cancel(self.type_writer_timer)
|
| self.state.typing = True
|
| self.type_writer_effect(choices)
|
|
|
| def _handle_normal_text(
|
| self,
|
| text: str,
|
| small_font: tuple,
|
| dialogue_font: tuple,
|
| available_width: int,
|
| outline_positions: list,
|
| outline_offset: int,
|
| outline_color: str
|
| ) -> None:
|
| """
|
| จัดการแสดงผลข้อความปกติที่ไม่ใช่ choice dialogue
|
| Args:
|
| text: ข้อความที่จะแสดง
|
| small_font: ฟอนต์สำหรับชื่อ
|
| dialogue_font: ฟอนต์สำหรับบทสนทนา
|
| available_width: ความกว้างที่มีให้แสดงผล
|
| outline_positions: ตำแหน่งของเส้นขอบ
|
| outline_offset: ระยะห่างของเส้นขอบ
|
| outline_color: สีของเส้นขอบ
|
| """
|
| try:
|
|
|
| if ":" in text:
|
| name, dialogue = text.split(":", 1)
|
| name = name.strip()
|
| dialogue = dialogue.strip()
|
|
|
|
|
| name_y = 10
|
| name_x = 10
|
|
|
|
|
| for dx, dy in outline_positions:
|
| self.components.canvas.create_text(
|
| name_x + dx * outline_offset,
|
| name_y + dy * outline_offset,
|
| anchor="nw",
|
| font=small_font,
|
| fill=outline_color,
|
| text=name,
|
| tags=("name_outline",),
|
| )
|
|
|
|
|
| name_color = "#a855f7" if "?" in name else "#38bdf8"
|
|
|
|
|
| name_text = self.components.canvas.create_text(
|
| name_x,
|
| name_y,
|
| anchor="nw",
|
| font=small_font,
|
| fill=name_color,
|
| text=name,
|
| tags=("name",)
|
| )
|
|
|
|
|
| if name in self.names:
|
| name_bbox = self.components.canvas.bbox(name_text)
|
| icon_x = name_bbox[2] + 8
|
| icon_y = name_y + ((name_bbox[3] - name_bbox[1]) // 2)
|
|
|
| self.components.canvas.create_image(
|
| icon_x,
|
| icon_y,
|
| image=self.confirm_icon,
|
| anchor="w",
|
| tags=("confirm_icon",),
|
| )
|
|
|
|
|
| name_bbox = self.components.canvas.bbox(name_text)
|
| dialogue_y = name_bbox[3] + (small_font[1] * 0.3)
|
|
|
|
|
| self.components.outline_container = []
|
| for dx, dy in outline_positions:
|
| outline = self.components.canvas.create_text(
|
| 10 + dx * outline_offset,
|
| dialogue_y + dy * outline_offset,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill=outline_color,
|
| text="",
|
| width=available_width,
|
| tags=("dialogue_outline",),
|
| )
|
| self.components.outline_container.append(outline)
|
|
|
|
|
| self.components.text_container = self.components.canvas.create_text(
|
| 10,
|
| dialogue_y,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill="white",
|
| text="",
|
| width=available_width,
|
| tags=("dialogue",),
|
| )
|
|
|
| else:
|
|
|
| dialogue = text.strip()
|
|
|
| self.components.outline_container = []
|
| for dx, dy in outline_positions:
|
| outline = self.components.canvas.create_text(
|
| 10 + dx * outline_offset,
|
| 10 + dy * outline_offset,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill=outline_color,
|
| text="",
|
| width=available_width,
|
| tags=("text_outline",),
|
| )
|
| self.components.outline_container.append(outline)
|
|
|
| self.components.text_container = self.components.canvas.create_text(
|
| 10,
|
| 10,
|
| anchor="nw",
|
| font=dialogue_font,
|
| fill="white",
|
| text="",
|
| width=available_width,
|
| tags=("text",),
|
| )
|
|
|
|
|
| self.dialogue_text = dialogue
|
| if hasattr(self, "type_writer_timer"):
|
| self.root.after_cancel(self.type_writer_timer)
|
| self.state.typing = True
|
| self.type_writer_effect(dialogue)
|
|
|
| except Exception as e:
|
| self.logging_manager.log_error(f"Error in handle normal text: {e}")
|
|
|
| def type_writer_effect(self, text: str, index: int = 0, delay: int = 5) -> None:
|
| """
|
| Create typewriter effect for text display
|
| Args:
|
| text: Text to display
|
| index: Current character index
|
| delay: Delay between characters in milliseconds
|
| """
|
| try:
|
| if not self.state.typing:
|
| return
|
|
|
| if index < len(text):
|
| next_text = text[: index + 1]
|
|
|
| names = getattr(self, "names", set())
|
| is_combined = (
|
| (":" in text and any(name in text.split(":")[0] for name in names))
|
| if names
|
| else False
|
| )
|
|
|
| if is_combined:
|
| name, message = text.split(":", 1)
|
| display_text = message[: index + 1].strip()
|
| else:
|
| display_text = next_text
|
|
|
|
|
| for outline in self.components.outline_container:
|
| self.components.canvas.itemconfig(outline, text=display_text)
|
| self.components.canvas.tag_lower(outline)
|
|
|
| self.components.canvas.itemconfig(
|
| self.components.text_container, text=display_text
|
| )
|
|
|
| self.root.update_idletasks()
|
| if self.state.typing:
|
| self.type_writer_timer = self.root.after(
|
| delay, lambda: self.type_writer_effect(text, index + 1, delay)
|
| )
|
| else:
|
| self.state.typing = False
|
| self.check_text_overflow()
|
|
|
| except Exception as e:
|
| logging.error(f"Error in type_writer_effect: {e}")
|
| self.state.typing = False
|
|
|
| def show_full_text(self, event: Optional[tk.Event] = None) -> None:
|
| """
|
| Show complete text immediately without typewriter effect
|
| Args:
|
| event: Optional tkinter event
|
| """
|
|
|
| if hasattr(self, "type_writer_timer"):
|
| self.root.after_cancel(self.type_writer_timer)
|
|
|
|
|
| self.state.typing = False
|
|
|
|
|
| if hasattr(self, "dialogue_text") and self.dialogue_text:
|
| if self.dialogue_text.startswith(
|
| "คุณจะพูดว่าอย่างไร?"
|
| ) or self.dialogue_text.startswith("What will you say?"):
|
| parts = self.dialogue_text.split("\n", 1)
|
| header = parts[0].strip()
|
| choices = parts[1].strip() if len(parts) > 1 else ""
|
|
|
|
|
| for item in self.components.canvas.find_withtag("header_outline"):
|
| self.components.canvas.itemconfig(item, text=header)
|
|
|
|
|
| for outline in self.components.outline_container:
|
| self.components.canvas.itemconfig(outline, text=choices)
|
| self.components.canvas.itemconfig(
|
| self.components.text_container, text=choices
|
| )
|
| else:
|
|
|
| is_combined = ":" in self.dialogue_text and any(
|
| name in self.dialogue_text.split(":")[0]
|
| for name in getattr(self, "names", set())
|
| )
|
|
|
| if is_combined:
|
| name, message = self.dialogue_text.split(":", 1)
|
| display_text = message.strip()
|
| else:
|
| display_text = self.dialogue_text
|
|
|
|
|
| for outline in self.components.outline_container:
|
| self.components.canvas.itemconfig(outline, text=display_text)
|
| self.components.canvas.itemconfig(
|
| self.components.text_container, text=display_text
|
| )
|
|
|
|
|
| self.components.canvas.tag_lower("dialogue_outline")
|
| if self.components.canvas.find_withtag("name_outline"):
|
| self.components.canvas.tag_lower("name_outline")
|
|
|
| self.check_text_overflow()
|
|
|
| def check_text_overflow(self) -> None:
|
| """Check if text content overflows the canvas and handle scrollbar visibility"""
|
| self.components.canvas.update_idletasks()
|
|
|
|
|
| content_height = self.components.canvas.bbox("all")[3] + 20
|
| canvas_height = self.components.canvas.winfo_height()
|
|
|
| if content_height > canvas_height:
|
| self.show_overflow_arrow()
|
| self.components.scrollbar.place(
|
| relx=0.98, rely=0, relheight=0.9, anchor="ne", y=10, x=-25
|
| )
|
| self.components.canvas.configure(scrollregion=(0, 0, 0, content_height))
|
| else:
|
| self.hide_overflow_arrow()
|
| self.components.scrollbar.place_forget()
|
|
|
| def adjust_font_size(self, size: int) -> None:
|
| """
|
| Adjust font size for all text elements
|
| Args:
|
| size: New font size
|
| """
|
| try:
|
| font = (self.settings.get("font"), size)
|
|
|
|
|
| if self.components.text_container:
|
| self.components.canvas.itemconfig(
|
| self.components.text_container, font=font
|
| )
|
|
|
|
|
| for tag in ["name_outline", "dialogue_outline"]:
|
| for outline in self.components.canvas.find_withtag(tag):
|
| self.components.canvas.itemconfig(outline, font=font)
|
|
|
| self.check_text_overflow()
|
| logging.info(f"Font size adjusted to: {size}")
|
|
|
| except (ValueError, TypeError) as e:
|
| logging.error(f"Error adjusting font size: {e}")
|
|
|
| self.adjust_font_size(24)
|
|
|
| def update_font(self, font_name: str) -> None:
|
| """
|
| Update font family for all text elements
|
| Args:
|
| font_name: New font family name
|
| """
|
| font = (font_name, self.settings.get("font_size"))
|
|
|
|
|
| if self.components.text_container:
|
| self.components.canvas.itemconfig(self.components.text_container, font=font)
|
|
|
|
|
| for tag in ["name_outline", "dialogue_outline"]:
|
| for outline in self.components.canvas.find_withtag(tag):
|
| self.components.canvas.itemconfig(outline, font=font)
|
|
|
| self.check_text_overflow()
|
| logging.info(f"Font updated to: {font_name}")
|
|
|
| def _show_error(self, error_message: str) -> None:
|
| """
|
| Display error message in the canvas
|
| Args:
|
| error_message: Error message to display
|
| """
|
| self.components.canvas.delete("all")
|
| font = (self.settings.get("font"), self.settings.get("font_size"))
|
| self.components.text_container = self.components.canvas.create_text(
|
| 10,
|
| 10,
|
| anchor="nw",
|
| font=font,
|
| fill="red",
|
| width=self.components.text_frame.winfo_width() - 20,
|
| text=f"Error: {error_message}",
|
| )
|
| self.check_text_overflow()
|
|
|
| def update_transparency(self, alpha: float) -> None:
|
| """
|
| Update window transparency
|
| Args:
|
| alpha: Transparency value (0.0 to 1.0)
|
| """
|
| self.root.attributes("-alpha", alpha)
|
|
|
| def close_window(self) -> None:
|
| """Close the translation window and stop translation"""
|
| self.stop_translation()
|
| if self.root.winfo_exists():
|
| if self.root.state() != "withdrawn":
|
| self.root.withdraw()
|
| logging.info("Translated UI closed by user")
|
| else:
|
| logging.info("Translated UI already hidden")
|
| else:
|
| logging.warning("Translated UI window does not exist")
|
|
|
| def toggle_lock(self) -> None:
|
| """Toggle window lock state with different modes"""
|
| self.lock_mode = (self.lock_mode + 1) % 3
|
| current_bg = self.settings.get("bg_color", appearance_manager.bg_color)
|
|
|
|
|
| widgets_to_update = [
|
| self.components.main_frame,
|
| self.components.text_frame,
|
| self.components.canvas,
|
| self.components.control_area,
|
| ]
|
|
|
| if self.lock_mode == 0:
|
| self.state.is_locked = False
|
| self.components.buttons["lock"].config(image=self.lock_image)
|
| self.root.attributes("-transparentcolor", "")
|
|
|
| for widget in widgets_to_update:
|
| widget.configure(bg=current_bg, bd=0, highlightthickness=0)
|
|
|
| elif self.lock_mode == 1:
|
| self.state.is_locked = True
|
| self.components.buttons["lock"].config(image=self.unlock_image)
|
| self.root.attributes("-transparentcolor", current_bg)
|
|
|
| for widget in widgets_to_update:
|
| widget.configure(bg=current_bg, bd=0, highlightthickness=0)
|
|
|
|
|
| for button in self.components.buttons.values():
|
| button.configure(bg=current_bg, bd=0)
|
|
|
| else:
|
| self.state.is_locked = True
|
| self.components.buttons["lock"].config(image=self.bg_lock_image)
|
| self.root.attributes("-transparentcolor", "")
|
|
|
| for widget in widgets_to_update:
|
| widget.configure(bg=current_bg, bd=0, highlightthickness=0)
|
|
|
| def change_bg_color(self) -> None:
|
| """Open color picker and update background color"""
|
| color = colorchooser.askcolor(
|
| color=self.settings.get("bg_color", appearance_manager.bg_color),
|
| title="Choose Background Color",
|
| )
|
|
|
| if color[1]:
|
| self.settings.set("bg_color", color[1])
|
| self.settings.save_settings()
|
|
|
|
|
| widgets_to_update = [
|
| self.root,
|
| self.components.main_frame,
|
| self.components.text_frame,
|
| self.components.canvas,
|
| self.components.control_area,
|
| ]
|
|
|
| for widget in widgets_to_update:
|
| widget.configure(bg=color[1], bd=0, highlightthickness=0, relief="flat")
|
|
|
|
|
| for button in self.components.buttons.values():
|
| button.configure(bg=color[1], bd=0, relief="flat", highlightthickness=0)
|
|
|
| if self.lock_mode == 1:
|
| self.root.attributes("-transparentcolor", color[1])
|
|
|
| def setup_window_resizing(self) -> None:
|
| """Initialize window resize functionality"""
|
| self.resize_handle = tk.Label(
|
| self.components.main_frame,
|
| 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
|
| self.last_resize_time = 0
|
| self.resize_throttle = 0.016
|
|
|
| def start_resize(self, event: tk.Event) -> None:
|
| """
|
| Initialize window resize operation
|
| Args:
|
| event: Mouse event containing initial coordinates
|
| """
|
| self.is_resizing = True
|
| self.resize_x = event.x_root
|
| self.resize_y = event.y_root
|
| self.resize_w = self.root.winfo_width()
|
| self.resize_h = self.root.winfo_height()
|
| print("\rStarting translated UI resize...", end="", flush=True)
|
|
|
| def on_resize(self, event: tk.Event) -> None:
|
| """
|
| Handle window resizing with throttling
|
| Args:
|
| event: Mouse event containing current coordinates
|
| """
|
| if not self.is_resizing:
|
| return
|
|
|
| try:
|
| current_time = time.time()
|
| if current_time - self.last_resize_time < self.resize_throttle:
|
| return
|
|
|
| dx = event.x_root - self.resize_x
|
| dy = event.y_root - self.resize_y
|
|
|
| new_width = max(300, self.resize_w + dx)
|
| new_height = max(200, self.resize_h + dy)
|
|
|
| self.root.geometry(f"{int(new_width)}x{int(new_height)}")
|
|
|
| self.settings.set("width", new_width)
|
| self.settings.set("height", new_height)
|
|
|
| self.last_resize_time = current_time
|
| print(
|
| f"\rResizing translated UI to {int(new_width)}x{int(new_height)}...",
|
| end="",
|
| flush=True,
|
| )
|
|
|
| except Exception as e:
|
| logging.error(f"Resize error: {e}")
|
| print(f"\rResize error: {e}")
|
|
|
| def stop_resize(self, event: Optional[tk.Event] = None) -> None:
|
| """
|
| End window resize operation and save final settings
|
| Args:
|
| event: Optional mouse event
|
| """
|
| if self.is_resizing:
|
| self.settings.save_settings()
|
|
|
| final_w = self.root.winfo_width()
|
| final_h = self.root.winfo_height()
|
|
|
|
|
| self.on_canvas_configure({"width": final_w - 40})
|
| self.force_check_overflow()
|
|
|
| print(f"\rTranslated UI resize complete: {final_w}x{final_h}")
|
|
|
| self.is_resizing = False
|
|
|
| def force_check_overflow(self) -> None:
|
| """Force check text overflow and update UI accordingly"""
|
| self.check_text_overflow()
|
|
|
| def on_canvas_configure(self, event: Union[tk.Event, Dict[str, int]]) -> None:
|
| """
|
| Handle canvas resize event
|
| Args:
|
| event: Canvas configure event or dictionary with width
|
| """
|
| try:
|
| available_width = (
|
| event.width - 20 if isinstance(event, tk.Event) else event["width"]
|
| )
|
|
|
| if hasattr(self.components, "text_container"):
|
|
|
| self.components.canvas.itemconfig(
|
| self.components.text_container, width=available_width
|
| )
|
|
|
|
|
| for outline in self.components.outline_container:
|
| self.components.canvas.itemconfig(outline, width=available_width)
|
|
|
|
|
| self.components.canvas.update_idletasks()
|
| bbox = self.components.canvas.bbox("all")
|
| if bbox:
|
| self.components.canvas.configure(scrollregion=bbox)
|
|
|
| self.check_text_overflow()
|
|
|
| except Exception as e:
|
| logging.error(f"Canvas configure error: {e}")
|
|
|
| def on_mousewheel(self, event: tk.Event) -> None:
|
| """
|
| Handle mouse wheel scrolling
|
| Args:
|
| event: Mouse wheel event
|
| """
|
| self.components.canvas.yview_scroll(-1 * (event.delta // 120), "units")
|
|
|
| def on_click(self, event: tk.Event) -> None:
|
| """
|
| Handle mouse click event
|
| Args:
|
| event: Mouse click event
|
| """
|
| if self.state.is_locked and not self._is_click_on_button(event):
|
| if self.lock_mode == 2:
|
| self.show_full_text()
|
| return
|
| self._start_move(event)
|
| if not self.state.is_locked:
|
| self.show_full_text()
|
|
|
| def _is_click_on_button(self, event: tk.Event) -> bool:
|
| """
|
| Check if click was on a button
|
| Args:
|
| event: Mouse click event
|
| Returns:
|
| bool: True if click was on a button
|
| """
|
| for button in self.components.buttons.values():
|
| if button.winfo_containing(event.x_root, event.y_root) == button:
|
| return True
|
| return False
|
|
|
| def _is_click_on_scrollbar(self, event: tk.Event) -> bool:
|
| """
|
| Check if click was on scrollbar
|
| Args:
|
| event: Mouse click event
|
| Returns:
|
| bool: True if click was on scrollbar
|
| """
|
| return (
|
| self.components.scrollbar.winfo_containing(event.x_root, event.y_root)
|
| == self.components.scrollbar
|
| )
|
|
|
| def _start_move(self, event: tk.Event) -> None:
|
| """
|
| Initialize window movement
|
| Args:
|
| event: Mouse click event
|
| """
|
| if not self.state.is_locked:
|
| self.x = event.x
|
| self.y = event.y
|
|
|
| def on_drag(self, event: tk.Event) -> None:
|
| """
|
| Handle window dragging
|
| Args:
|
| event: Mouse drag event
|
| """
|
| if not self.state.is_locked:
|
| self._do_move(event)
|
|
|
| def stop_move(self, event: Optional[tk.Event] = None) -> None:
|
| """
|
| Stop window movement
|
| Args:
|
| event: Optional mouse release event
|
| """
|
| self.x = None
|
| self.y = None
|
|
|
| def _do_move(self, event: tk.Event) -> None:
|
| """
|
| Perform window movement
|
| Args:
|
| event: Mouse drag event
|
| """
|
| if not self.state.is_locked and self.x is not None and self.y is not None:
|
| deltax = event.x - self.x
|
| deltay = event.y - self.y
|
| x = self.root.winfo_x() + deltax
|
| y = self.root.winfo_y() + deltay
|
| self.root.geometry(f"+{x}+{y}")
|
|
|
| def on_hover_enter(self, event: Optional[tk.Event] = None) -> None:
|
| """
|
| Handle mouse hover enter event
|
| Args:
|
| event: Optional mouse enter event
|
| """
|
| pass
|
|
|
| @staticmethod
|
| def _calculate_content_dimensions(
|
| text: str, font: tuple, max_width: int
|
| ) -> Tuple[int, int]:
|
| """
|
| Calculate required dimensions for text content
|
| Args:
|
| text: Text content
|
| font: Font configuration tuple
|
| max_width: Maximum available width
|
| Returns:
|
| Tuple[int, int]: Calculated width and height
|
| """
|
| temp_label = tk.Label(text=text, font=font)
|
| temp_label.update_idletasks()
|
|
|
| raw_width = temp_label.winfo_reqwidth()
|
| raw_height = temp_label.winfo_reqheight()
|
|
|
| if raw_width > max_width:
|
|
|
| lines = math.ceil(raw_width / max_width)
|
| height = raw_height * lines
|
| width = max_width
|
| else:
|
| width = raw_width
|
| height = raw_height
|
|
|
| temp_label.destroy()
|
| return width, height
|
|
|
| def cleanup(self) -> None:
|
| """Cleanup resources before closing"""
|
| try:
|
|
|
| if hasattr(self, "type_writer_timer"):
|
| self.root.after_cancel(self.type_writer_timer)
|
|
|
|
|
| if self.components.canvas:
|
| self.components.canvas.delete("all")
|
|
|
|
|
| self.state = UIState()
|
|
|
| logging.info("TranslatedUI cleanup completed")
|
|
|
| except Exception as e:
|
| logging.error(f"Error during cleanup: {e}")
|
|
|
| def _setup_character_name_binding(self):
|
| """Setup binding for character name clicks"""
|
| self.components.canvas.tag_bind("name", "<Button-1>", self._on_name_click)
|
| logging.info("Character name click binding setup")
|
|
|
| def _on_name_click(self, event):
|
| """
|
| จัดการเมื่อมีการคลิกที่ชื่อตัวละคร
|
| - สร้าง click effect
|
| - ส่งต่อไปยัง character handler
|
|
|
| Args:
|
| event: tkinter event object ที่มีข้อมูลตำแหน่งที่คลิก
|
| """
|
| try:
|
|
|
| clicked_item = self.components.canvas.find_closest(
|
| self.components.canvas.canvasx(event.x),
|
| self.components.canvas.canvasy(event.y)
|
| )[0]
|
|
|
|
|
| original_color = self.components.canvas.itemcget(clicked_item, "fill")
|
| original_text = self.components.canvas.itemcget(clicked_item, "text")
|
|
|
|
|
| def flash_effect():
|
|
|
| self.components.canvas.itemconfig(clicked_item, fill="#FF4444")
|
|
|
|
|
| self.root.after(150, lambda: self.components.canvas.itemconfig(
|
| clicked_item,
|
| fill=original_color
|
| ))
|
|
|
|
|
| flash_effect()
|
| self.root.after(50, lambda: self._handle_character_click(original_text))
|
|
|
| except Exception as e:
|
| self.logging_manager.log_error(f"Error in name click effect: {e}")
|
|
|
| def _handle_character_click(self, character_name):
|
| """Process character name click and open NPC Manager"""
|
| try:
|
| if not self.main_app:
|
| self.logging_manager.log_warning("Main application reference not provided to Translated UI")
|
| return
|
|
|
|
|
| self.root.update_idletasks()
|
|
|
| if not hasattr(self.main_app, 'npc_manager') or self.main_app.npc_manager is None:
|
| from npc_manager import create_npc_manager
|
| self.main_app.npc_manager = create_npc_manager(
|
| self.root,
|
| self.main_app.reload_npc_data,
|
| self.logging_manager
|
| )
|
| self.main_app.npc_manager_button.config(bg="#404040")
|
|
|
|
|
| npc_manager = self.main_app.npc_manager
|
| if npc_manager.window.state() == 'withdrawn':
|
| npc_manager.show_window()
|
|
|
| if character_name:
|
| clean_name = character_name.strip(":!?. ")
|
| is_verified = clean_name in self.names
|
| npc_manager.find_and_display_character(clean_name, is_verified)
|
|
|
| except Exception as e:
|
| error_msg = f"Error handling character click: {e}"
|
| self.logging_manager.log_error(error_msg)
|
| messagebox.showerror("Error", error_msg)
|
|
|
| def _setup_character_name_binding(self):
|
| """
|
| ตั้งค่า event binding สำหรับการโต้ตอบกับชื่อตัวละคร
|
| - รองรับ hover effect ด้วย mouse enter/leave
|
| - รองรับการคลิกที่ชื่อ
|
| """
|
|
|
| self.components.canvas.tag_bind("name", "<Enter>", self._on_name_hover_enter)
|
| self.components.canvas.tag_bind("name", "<Leave>", self._on_name_hover_leave)
|
| self.components.canvas.tag_bind("name", "<Button-1>", self._on_name_click)
|
| logging.info("Character name interaction bindings setup")
|
|
|
| def _on_name_hover_enter(self, event):
|
| """
|
| จัดการเมื่อ mouse hover เข้าบริเวณชื่อตัวละคร
|
| Parameters:
|
| event: Event object ที่มีข้อมูลพิกัดของเมาส์
|
| """
|
| try:
|
|
|
| self.components.canvas.configure(cursor="hand2")
|
|
|
|
|
| current_x = self.components.canvas.canvasx(event.x)
|
| current_y = self.components.canvas.canvasy(event.y)
|
| items = self.components.canvas.find_overlapping(
|
| current_x-5, current_y-5,
|
| current_x+5, current_y+5
|
| )
|
|
|
|
|
| name_item = None
|
| for item in items:
|
| if 'name' in self.components.canvas.gettags(item):
|
| name_item = item
|
| break
|
|
|
| if name_item:
|
|
|
| current_color = self.components.canvas.itemcget(name_item, "fill")
|
| tag_name = f"original_color:{current_color}"
|
|
|
|
|
| for tag in self.components.canvas.gettags(name_item):
|
| if tag.startswith('original_color:'):
|
| self.components.canvas.dtag(name_item, tag)
|
|
|
|
|
| self.components.canvas.addtag_withtag(tag_name, name_item)
|
|
|
|
|
| self.components.canvas.itemconfig(name_item, fill="white")
|
|
|
| except Exception as e:
|
| self.logging_manager.log_error(f"Error in hover enter effect: {e}")
|
|
|
| def _on_name_hover_leave(self, event):
|
| """
|
| จัดการเมื่อ mouse ออกจากบริเวณชื่อตัวละคร
|
| Parameters:
|
| event: Event object ที่มีข้อมูลพิกัดของเมาส์
|
| """
|
| try:
|
|
|
| self.components.canvas.configure(cursor="")
|
|
|
|
|
| current_x = self.components.canvas.canvasx(event.x)
|
| current_y = self.components.canvas.canvasy(event.y)
|
| items = self.components.canvas.find_overlapping(
|
| current_x-5, current_y-5,
|
| current_x+5, current_y+5
|
| )
|
|
|
|
|
| for item in items:
|
| if 'name' in self.components.canvas.gettags(item):
|
|
|
| original_color = None
|
| for tag in self.components.canvas.gettags(item):
|
| if tag.startswith('original_color:'):
|
| original_color = tag.split(':')[1]
|
| self.components.canvas.dtag(item, tag)
|
| break
|
|
|
|
|
| if original_color:
|
| self.components.canvas.itemconfig(item, fill=original_color)
|
| else:
|
|
|
| text = self.components.canvas.itemcget(item, "text")
|
| name_color = "#a855f7" if "?" in text else "#38bdf8"
|
| self.components.canvas.itemconfig(item, fill=name_color)
|
| break
|
|
|
| except Exception as e:
|
| self.logging_manager.log_error(f"Error in hover leave effect: {e}")
|
|
|
|
|
| if __name__ == "__main__":
|
| root = tk.Tk()
|
| settings = Settings()
|
|
|
| class DummyLoggingManager:
|
| def log_feedback(
|
| self, original_text: str, translated_text: str, rating: int
|
| ) -> None:
|
| print(f"Logged feedback: {rating}")
|
|
|
| dummy_logging_manager = DummyLoggingManager()
|
|
|
|
|
| app = Translated_UI(
|
| root=root,
|
| toggle_translation=lambda: None,
|
| stop_translation=lambda: None,
|
| force_translate=lambda: None,
|
| toggle_main_ui=lambda: None,
|
| toggle_ui=lambda: None,
|
| settings=settings,
|
| switch_area=lambda x: None,
|
| logging_manager=dummy_logging_manager,
|
| )
|
|
|
| root.mainloop()
|
|
|