import tkinter as tk from tkinter import ttk, messagebox import logging from loggings import LoggingManager from appearance import appearance_manager class AdvanceUI: def __init__( self, parent, settings, apply_settings_callback, ocr_toggle_callback=None ): self.parent = parent self.settings = settings self.apply_settings_callback = apply_settings_callback self.ocr_toggle_callback = ocr_toggle_callback self.advance_window = None self.is_changed = False self.create_advance_window() def check_screen_resolution(self): """ตรวจสอบขนาดหน้าจอที่ตั้งค่าในวินโดว์ Returns: dict: ผลการตรวจสอบ """ try: # 1. ใช้ win32api ซึ่งเป็นวิธีที่เชื่อถือได้มากกว่า import win32api import win32gui import win32con # 2. ดึงค่าความละเอียดจริงจากการตั้งค่า Windows dm = win32api.EnumDisplaySettings(None, win32con.ENUM_CURRENT_SETTINGS) current_width = dm.PelsWidth # ความกว้างจริง current_height = dm.PelsHeight # ความสูงจริง # 3. ดึงค่าที่ตั้งไว้ใน settings มาเทียบ expected_resolution = self.settings.get("screen_size", "2560x1440") expected_width, expected_height = map(int, expected_resolution.split("x")) # 4. เปรียบเทียบค่า if current_width != expected_width or current_height != expected_height: return { "is_valid": False, "message": ( f"Screen resolution does not match settings!\n" f"Current: {current_width}x{current_height}\n" f"Settings: {expected_width}x{expected_height}\n" f"Please set your screen resolution first." ), "current": f"{current_width}x{current_height}", "expected": expected_resolution, } return { "is_valid": True, "current": f"{current_width}x{current_height}", "expected": expected_resolution, } except Exception as e: print(f"Error checking screen resolution: {e}") return { "is_valid": False, "message": f"Error checking resolution: {str(e)}", "current": "Unknown", "expected": "Unknown", } def create_advance_window(self): """สร้างหน้าต่าง Advanced Settings""" if self.advance_window is None or not self.advance_window.winfo_exists(): self.advance_window = tk.Toplevel(self.parent) self.advance_window.title("Advanced Settings") self.advance_window.geometry("360x400") # เพิ่มความสูงรองรับปุ่มใหม่ self.advance_window.overrideredirect(True) appearance_manager.apply_style(self.advance_window) # Screen Size Settings screen_frame = tk.LabelFrame( self.advance_window, text="Screen Resolution", bg=appearance_manager.bg_color, fg="white", ) screen_frame.pack(fill=tk.X, padx=10, pady=5) # Current Resolution Display current_res_frame = tk.Frame(screen_frame, bg=appearance_manager.bg_color) current_res_frame.pack(fill=tk.X, padx=5, pady=2) tk.Label( current_res_frame, text="Current:", bg=appearance_manager.bg_color, fg="white" ).pack(side=tk.LEFT) self.current_res_label = tk.Label( current_res_frame, text="Detecting...", bg=appearance_manager.bg_color, fg="#2ECC71" ) self.current_res_label.pack(side=tk.RIGHT, padx=5) # Width dropdown width_frame = tk.Frame(screen_frame, bg=appearance_manager.bg_color) width_frame.pack(fill=tk.X, padx=5, pady=2) tk.Label( width_frame, text="Set Width:", bg=appearance_manager.bg_color, fg="white" ).pack(side=tk.LEFT) self.screen_width_var = tk.StringVar() self.width_combo = ttk.Combobox( width_frame, values=["1920", "2560", "3440", "3840"], textvariable=self.screen_width_var, width=8, ) self.width_combo.pack(side=tk.RIGHT, padx=5) # Height dropdown height_frame = tk.Frame(screen_frame, bg=appearance_manager.bg_color) height_frame.pack(fill=tk.X, padx=5, pady=2) tk.Label( height_frame, text="Set Height:", bg=appearance_manager.bg_color, fg="white" ).pack(side=tk.LEFT) self.screen_height_var = tk.StringVar() self.height_combo = ttk.Combobox( height_frame, values=["1080", "1440", "1600", "2160"], textvariable=self.screen_height_var, width=8, ) self.height_combo.pack(side=tk.RIGHT, padx=5) # Screen Control Buttons screen_btn_frame = tk.Frame(screen_frame, bg=appearance_manager.bg_color) screen_btn_frame.pack(fill=tk.X, padx=5, pady=5) self.apply_res_button = ttk.Button( screen_btn_frame, text="Apply Resolution", command=self.apply_resolution ) self.apply_res_button.pack(side=tk.LEFT, padx=2) self.check_res_button = ttk.Button( screen_btn_frame, text="Check", command=self.check_resolution_status ) self.check_res_button.pack(side=tk.RIGHT, padx=2) # Display Scale Settings scale_frame = tk.LabelFrame( self.advance_window, text="Display Scale", bg=appearance_manager.bg_color, fg="white", ) scale_frame.pack(fill=tk.X, padx=10, pady=5) # Scale info scale_info_frame = tk.Frame(scale_frame, bg=appearance_manager.bg_color) scale_info_frame.pack(fill=tk.X, padx=5, pady=5) tk.Label( scale_info_frame, text="Current Scale:", bg=appearance_manager.bg_color, fg="white", ).pack(side=tk.LEFT) self.scale_label = tk.Label( scale_info_frame, text="Detecting...", bg=appearance_manager.bg_color, fg="#2ECC71", ) self.scale_label.pack(side=tk.RIGHT, padx=5) # Scale buttons scale_button_frame = tk.Frame(scale_frame, bg=appearance_manager.bg_color) scale_button_frame.pack(fill=tk.X, padx=5, pady=5) self.scale_button = ttk.Button( scale_button_frame, text="Open Display Settings", command=self.open_display_settings, ) self.scale_button.pack(side=tk.LEFT, padx=5) self.detect_button = ttk.Button( scale_button_frame, text="Check Scale", command=self.check_display_scale, ) self.detect_button.pack(side=tk.RIGHT, padx=5) # OCR Settings ocr_frame = tk.LabelFrame( self.advance_window, text="OCR Settings", bg=appearance_manager.bg_color, fg="white", ) ocr_frame.pack(fill=tk.X, padx=10, pady=5) # GPU Toggle gpu_frame = tk.Frame(ocr_frame, bg=appearance_manager.bg_color) gpu_frame.pack(fill=tk.X, padx=5, pady=5) tk.Label( gpu_frame, text="OCR Processing:", bg=appearance_manager.bg_color, fg="white", ).pack(side=tk.LEFT) self.gpu_var = tk.BooleanVar( value=self.settings.get("use_gpu_for_ocr", False) ) self.gpu_switch = ttk.Checkbutton( gpu_frame, text="Use GPU", style="Switch.TCheckbutton", variable=self.gpu_var, command=self.toggle_gpu, ) self.gpu_switch.pack(side=tk.RIGHT, padx=5) # Save Button self.save_button = appearance_manager.create_styled_button( self.advance_window, "Save", self.save_settings, hover_bg="#404040" ) self.save_button.pack(pady=10) # Close Button close_button = appearance_manager.create_styled_button( self.advance_window, "X", self.close, hover_bg="#404040" ) close_button.place(x=5, y=5, width=20, height=20) # Bind Events self.width_combo.bind("<>", self.on_change) self.height_combo.bind("<>", self.on_change) self.gpu_var.trace_add("write", lambda *args: self.on_change(None)) # Window Movement self.advance_window.bind("", self.start_move) self.advance_window.bind("", self.stop_move) self.advance_window.bind("", self.do_move) # Load Current Settings self.load_current_settings() # ซ่อนหน้าต่างตอนเริ่มต้น self.advance_window.withdraw() # ตรวจสอบ scale หลังจากสร้างหน้าต่างเสร็จ self.advance_window.after(1000, self.check_display_scale) def apply_resolution(self): """Apply the selected screen resolution""" try: new_width = self.screen_width_var.get() new_height = self.screen_height_var.get() new_resolution = f"{new_width}x{new_height}" # บันทึกค่าใหม่ self.settings.set("screen_size", new_resolution) # ตรวจสอบการตั้งค่าใหม่ self.check_resolution_status() # อัพเดท UI self.apply_res_button.config(state="disabled") self.advance_window.after(2000, lambda: self.apply_res_button.config(state="normal")) except Exception as e: messagebox.showerror("Error", f"Failed to apply resolution: {str(e)}") def check_resolution_status(self): """ตรวจสอบและแสดงสถานะความละเอียดหน้าจอ""" resolution_info = self.check_screen_resolution() self.current_res_label.config(text=resolution_info["current"]) if not resolution_info["is_valid"]: self.current_res_label.config(fg="#FF6B6B") # สีแดง else: self.current_res_label.config(fg="#2ECC71") # สีเขียว def validate_screen_resolution(self): """ตรวจสอบความละเอียดหน้าจอโดยคำนึงถึง Display Scale Returns: dict: ผลการตรวจสอบ {"is_valid": bool, "message": str} """ try: # 1. ตรวจสอบ Scale ปัจจุบัน import ctypes user32 = ctypes.windll.user32 current_dpi = user32.GetDpiForSystem() current_scale = current_dpi / 96 # 96 is default DPI # 2. ดึงค่าความละเอียดจริงของหน้าจอ actual_width = self.advance_window.winfo_screenwidth() actual_height = self.advance_window.winfo_screenheight() # 3. คำนวณความละเอียดที่แท้จริงโดยหารด้วย scale real_width = int(actual_width / current_scale) real_height = int(actual_height / current_scale) # 4. ดึงค่าที่ตั้งไว้ใน settings set_resolution = self.settings.get("screen_size", "2560x1440") set_width, set_height = map(int, set_resolution.split("x")) # 5. เปรียบเทียบค่าที่คำนวณได้ if ( abs(real_width - set_width) > 50 or abs(real_height - set_height) > 50 ): # ให้ค่าคลาดเคลื่อนได้นิดหน่อย return { "is_valid": False, "message": ( f"Screen resolution mismatch!\n" f"Current: {real_width}x{real_height} (Scale: {int(current_scale * 100)}%)\n" f"Expected: {set_width}x{set_height}\n" f"Please check your resolution settings." ), "current": f"{real_width}x{real_height}", "expected": set_resolution, "scale": current_scale, } return { "is_valid": True, "message": "Screen resolution matched", "current": f"{real_width}x{real_height}", "expected": set_resolution, "scale": current_scale, } except Exception as e: return { "is_valid": False, "message": f"Error checking resolution: {e}", "current": "Unknown", "expected": "Unknown", "scale": 1.0, } def check_display_scale(self): """ตรวจสอบ Display Scale หลังจากขนาดหน้าจอถูกต้องแล้ว""" try: # 1. ตรวจสอบความละเอียดหน้าจอก่อน resolution_check = self.check_screen_resolution() if not resolution_check["is_valid"]: self.show_resolution_warning(resolution_check) self.scale_label.config(text="Fix Resolution") return None # 2. ถ้าความละเอียดถูกต้อง ค่อยตรวจสอบ Scale import ctypes user32 = ctypes.windll.user32 current_dpi = user32.GetDpiForSystem() current_scale = round(current_dpi / 96, 2) # 96 is default DPI # อัพเดท label แสดงค่า scale self.scale_label.config(text=f"{int(current_scale * 100)}%") # ตรวจสอบว่าต้องแจ้งเตือนหรือไม่ saved_scale = self.settings.get("display_scale") if saved_scale is None or abs(current_scale - saved_scale) > 0.01: # ส่งข้อมูลขนาดหน้าจอที่ถูกต้องไปด้วย self.show_scale_warning(current_scale, resolution_check["current"]) self.settings.set("display_scale", current_scale) return current_scale except Exception as e: print(f"Error checking display scale: {e}") self.scale_label.config(text="Error") return None def show_resolution_warning(self, resolution_info): """แสดงคำเตือนเมื่อขนาดหน้าจอไม่ตรง""" dialog = tk.Toplevel(self.advance_window) dialog.title("Screen Resolution Check") dialog.configure(bg=appearance_manager.bg_color) dialog.geometry("400x200") dialog.overrideredirect(True) message = resolution_info["message"] tk.Label( dialog, text=message, bg=appearance_manager.bg_color, fg="#FF6B6B", # สีแดงอ่อน justify=tk.LEFT, padx=20, pady=10, ).pack(expand=True) btn = tk.Button( dialog, text="Open Display Settings", command=lambda: [dialog.destroy(), self.open_display_settings()], bg="#2A2A2A", fg="white", pady=5, ) btn.pack(pady=10) # จัดตำแหน่งกลางหน้าจอ dialog.update_idletasks() width = dialog.winfo_width() height = dialog.winfo_height() x = (dialog.winfo_screenwidth() // 2) - (width // 2) y = (dialog.winfo_screenheight() // 2) - (height // 2) dialog.geometry(f"+{x}+{y}") dialog.transient(self.advance_window) dialog.grab_set() def open_display_settings(self): """เปิดหน้าต่าง Display Settings ของ Windows""" import os os.system("start ms-settings:display") def show_scale_warning(self, current_scale): """แสดง Dialog เตือนให้ตรวจสอบ Display Scale""" dialog = tk.Toplevel(self.advance_window) dialog.title("Display Scale Check") dialog.configure(bg=appearance_manager.bg_color) dialog.geometry("400x200") dialog.overrideredirect(True) # ไม่แสดง title bar message = ( f"Current Display Scale: {int(current_scale * 100)}%\n\n" "Windows Display Settings will open automatically.\n" "Please check if the scale matches your preference.\n\n" "Recommended: 100% for optimal OCR performance." ) tk.Label( dialog, text=message, bg=appearance_manager.bg_color, fg="white", justify=tk.LEFT, padx=20, pady=10, ).pack(expand=True) def on_ok(): dialog.destroy() self.open_display_settings() tk.Button( dialog, text="OK", command=on_ok, bg="#2A2A2A", fg="white", pady=5 ).pack(pady=10) dialog.transient(self.advance_window) dialog.grab_set() # จัดตำแหน่งกลางหน้าจอ dialog.update_idletasks() width = dialog.winfo_width() height = dialog.winfo_height() x = (dialog.winfo_screenwidth() // 2) - (width // 2) y = (dialog.winfo_screenheight() // 2) - (height // 2) dialog.geometry(f"+{x}+{y}") def load_current_settings(self): """โหลดค่าปัจจุบันจาก settings""" screen_size = self.settings.get("screen_size", "2560x1440") width, height = screen_size.split("x") self.screen_width_var.set(width) self.screen_height_var.set(height) self.gpu_var.set(self.settings.get("use_gpu_for_ocr", False)) self.is_changed = False self.update_save_button() def toggle_gpu(self): """Toggle GPU usage for OCR""" try: current_state = self.gpu_var.get() self.settings.set_gpu_for_ocr(current_state) if self.ocr_toggle_callback: self.ocr_toggle_callback() self.on_change(None) except Exception as e: messagebox.showerror("Error", f"Failed to toggle GPU setting: {str(e)}") def save_settings(self): """Save current settings""" try: # Save screen resolution screen_size = ( f"{self.screen_width_var.get()}x{self.screen_height_var.get()}" ) self.settings.set_screen_size(screen_size) # Save GPU setting use_gpu = self.gpu_var.get() self.settings.set_gpu_for_ocr(use_gpu) print(f"\n=== Settings Saved ===") print(f"Screen Size: {screen_size}") print(f"Use GPU for OCR: {use_gpu}") print("====================\n") new_settings = {"screen_size": screen_size, "use_gpu_for_ocr": use_gpu} if callable(self.apply_settings_callback): self.apply_settings_callback(new_settings) self.save_button.config(text="Saved!") self.advance_window.after( 2000, lambda: self.save_button.config(text="Save") ) self.is_changed = False except Exception as e: messagebox.showerror("Error", f"Failed to save settings: {str(e)}") def on_change(self, event): """Called when any setting is changed""" self.is_changed = True self.update_save_button() def update_save_button(self): """Update save button state based on changes""" self.save_button.config(text="SAVE" if self.is_changed else "Save") def open(self): """Show the advanced settings window""" if not self.advance_window.winfo_viewable(): # Position window x = self.parent.winfo_x() + self.parent.winfo_width() + 10 y = self.parent.winfo_y() self.advance_window.geometry(f"+{x}+{y}") # Show window self.advance_window.deiconify() self.advance_window.lift() self.advance_window.attributes("-topmost", True) # Reset state self.load_current_settings() self.is_changed = False self.update_save_button() def close(self): """Hide the advanced settings window""" if self.advance_window and self.advance_window.winfo_exists(): self.advance_window.withdraw() self.is_changed = False self.save_button.config(text="Save") def start_move(self, event): """Start window drag operation""" self.x = event.x self.y = event.y def stop_move(self, event): """End window drag operation""" self.x = None self.y = None def do_move(self, event): """Handle window dragging""" if hasattr(self, "x") and hasattr(self, "y"): deltax = event.x - self.x deltay = event.y - self.y x = self.advance_window.winfo_x() + deltax y = self.advance_window.winfo_y() + deltay self.advance_window.geometry(f"+{x}+{y}")