Datasets:
File size: 23,878 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 |
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("<<ComboboxSelected>>", self.on_change)
self.height_combo.bind("<<ComboboxSelected>>", self.on_change)
self.gpu_var.trace_add("write", lambda *args: self.on_change(None))
# Window Movement
self.advance_window.bind("<Button-1>", self.start_move)
self.advance_window.bind("<ButtonRelease-1>", self.stop_move)
self.advance_window.bind("<B1-Motion>", 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}")
|