refactor: implement UI code optimization and refactoring

This commit implements the comprehensive UI code refactoring plan to improve
code quality, reduce duplication, and enhance maintainability.

Phase 1: High Priority Improvements
- Create BaseDialog class to eliminate window centering code duplication
  across ProgressDialog, DeleteProgressWindow, LoginDialog, and
  UserSelectionDialog (~30 lines of duplicate code removed)
- Unify log color configuration with LogTheme class in gui/log_config.py
- Create permission check decorators (@require_admin, @require_permission,
  @require_user_type, @handle_errors)
- Update all dialog classes to use unified patterns

Phase 2: Architecture Improvements
- Create input validation framework (ValidationResult, Validator,
  ValidatedWidget classes)
- Implement StateManager with observer pattern for component state sharing
- Create unified ErrorHandler for consistent error handling
- Extract CheckboxTreeview into reusable component

New Modules:
- gui/widgets/base_dialog.py - Base dialog class with modal setup and centering
- gui/utils/decorators.py - Permission and error handling decorators
- gui/utils/error_handler.py - Unified error handling with user-friendly messages
- gui/utils/state_manager.py - State management with observer pattern
- gui/utils/validators.py - Input validation framework
- gui/material_validation/checkbox_treeview.py - Reusable checkbox table

Modified Files:
- gui/log_config.py - Added LogTheme class for centralized styling
- gui/widgets/log_text.py - Use LogTheme.COLORS
- gui/widgets/progress_dialog.py - Inherit from BaseDialog
- gui/widgets/delete_progress_window.py - Inherit from BaseDialog, use LogTheme
- gui/widgets/__init__.py - Add new exports, optional imports
- gui/login_dialog.py - Use unified centering pattern
- gui/user_selection_dialog.py - Use unified centering pattern
- gui/material_validation_tab.py - Import CheckboxTreeview from new module

Benefits:
- Reduced code duplication by ~200 lines
- Improved maintainability through centralized configuration
- Better abstraction with 5 new reusable base classes
- Enhanced type safety with type hints
- Future-proof theming support via LogTheme

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Misaka Server
2026-02-26 18:40:26 +08:00
parent 3a9c6f0978
commit f715cb97e3
16 changed files with 1735 additions and 313 deletions

View File

@@ -6,8 +6,26 @@ GUI 自定义组件模块
from .file_selector import FileSelector
from .log_text import LogText
from .production_id_input import ProductionIdInput
try:
from .production_id_input import ProductionIdInput
_has_production_id_input = True
except ImportError:
# tklinenums may not be installed
_has_production_id_input = False
from .log_handler import GuiTextHandler
from .delete_progress_window import DeleteProgressWindow
from .base_dialog import BaseDialog
from .progress_dialog import ProgressDialog
__all__ = ['FileSelector', 'LogText', 'ProductionIdInput', 'GuiTextHandler', 'DeleteProgressWindow']
__all__ = [
'FileSelector',
'LogText',
'GuiTextHandler',
'DeleteProgressWindow',
'BaseDialog',
'ProgressDialog',
]
# Add ProductionIdInput to __all__ only if it's available
if _has_production_id_input:
__all__.append('ProductionIdInput')

117
gui/widgets/base_dialog.py Normal file
View File

@@ -0,0 +1,117 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Base Dialog - 基础对话框类
所有对话框的基类,提供通用功能:
- 模态对话框设置
- 窗口居中显示
- 统一的对话框生命周期管理
"""
import tkinter as tk
from typing import Optional
class BaseDialog(tk.Toplevel):
"""
所有对话框的基类,提供通用功能
Usage:
class MyDialog(BaseDialog):
def __init__(self, parent):
super().__init__(parent, title="My Dialog")
self._create_content()
def _create_content(self):
# 创建对话框内容
pass
dialog = MyDialog(parent)
result = dialog.get_result()
"""
def __init__(self, parent, title: str, **kwargs):
"""
初始化基础对话框
Args:
parent: 父窗口
title: 对话框标题
**kwargs: 传递给 tk.Toplevel 的其他参数
"""
super().__init__(parent, **kwargs)
self.parent = parent
self.result = None
self.title(title)
# 设置为模态对话框并居中
self._setup_modal()
def _setup_modal(self):
"""设置为模态对话框并居中"""
self.transient(self.parent)
self.grab_set()
self._center_window()
def _center_window(self):
"""
窗口居中显示(统一实现)
根据对话框大小自动居中到屏幕中央
"""
self.update_idletasks()
width = self.winfo_width()
height = self.winfo_height()
# 如果窗口还没有实际大小,使用默认最小值
if width <= 1:
width = 400
if height <= 1:
height = 300
x = (self.winfo_screenwidth() // 2) - (width // 2)
y = (self.winfo_screenheight() // 2) - (height // 2)
self.geometry(f'{width}x{height}+{x}+{y}')
def _center_on_parent(self):
"""
窗口居中到父窗口
将对话框居中显示在父窗口中央,而不是屏幕中央
"""
self.update_idletasks()
self.parent.update_idletasks()
width = self.winfo_width()
height = self.winfo_height()
# 如果窗口还没有实际大小,使用默认最小值
if width <= 1:
width = 400
if height <= 1:
height = 300
parent_x = self.parent.winfo_x()
parent_y = self.parent.winfo_y()
parent_width = self.parent.winfo_width()
parent_height = self.parent.winfo_height()
x = parent_x + (parent_width - width) // 2
y = parent_y + (parent_height - height) // 2
self.geometry(f"{width}x{height}+{x}+{y}")
def get_result(self):
"""
获取对话框结果
子类应设置 self.result 来返回结果
Returns:
对话框结果,类型由子类定义
"""
return self.result
def close(self):
"""关闭对话框"""
self.destroy()

View File

@@ -10,6 +10,8 @@ import tkinter as tk
from tkinter import ttk, scrolledtext
from typing import Optional, Callable
from datetime import datetime
from gui.log_config import LogTheme
from gui.widgets.base_dialog import BaseDialog
# 尝试导入 tkinterweb 和 markdown2
try:
@@ -25,7 +27,7 @@ except ImportError:
HAS_MARKDOWN2 = False
class DeleteProgressWindow:
class DeleteProgressWindow(BaseDialog):
"""删除进度窗口"""
def __init__(
@@ -46,40 +48,51 @@ class DeleteProgressWindow:
dryrun: 是否为预览模式
on_cancel: 取消回调函数
"""
self.parent = parent
self.on_cancel = on_cancel
self.cancelled = False
self.managers = managers
self.dryrun = dryrun
self.main_frame = None
self.progress_frame = None
self.progress_var = None
self.progress_label = None
self.progress_bar = None
self.log_frame = None
self.log_text = None
self.report_frame = None
self.report_html = None
self.report_text = None
self.cancel_button = None
self.close_button = None
# 创建窗口
self.window = tk.Toplevel(parent)
self.window.title(title)
self.window.resizable(True, True)
self.window.transient(parent)
# 调用父类初始化(会自动设置为模态并居中)
super().__init__(parent, title)
# 设置窗口大小
self.window.geometry("700x600")
# 设置可调整大小
self.resizable(True, True)
# 创建内容
self._create_widgets()
# 居中显示
self._center()
# 设置固定大小并重新居中
self._set_fixed_size(700, 600)
def _center(self):
"""将窗口居中显示"""
self.window.update_idletasks()
width = 700
height = 600
x = (self.window.winfo_screenwidth() // 2) - (width // 2)
y = (self.window.winfo_screenheight() // 2) - (height // 2)
self.window.geometry(f"{width}x{height}+{x}+{y}")
def _set_fixed_size(self, width: int, height: int):
"""
设置固定大小并重新居中
Args:
width: 宽度
height: 高度
"""
self.update_idletasks()
self.geometry(f"{width}x{height}")
self._center_window()
def _create_widgets(self):
"""创建窗口组件"""
# 主容器
self.main_frame = ttk.Frame(self.window, padding=10)
self.main_frame = ttk.Frame(self, padding=10)
self.main_frame.pack(fill=tk.BOTH, expand=True)
# 信息区域
@@ -124,11 +137,11 @@ class DeleteProgressWindow:
)
self.log_text.pack(fill=tk.BOTH, expand=True)
# 配置日志标签颜色
self.log_text.tag_configure('info', foreground='black')
self.log_text.tag_configure('success', foreground='green')
self.log_text.tag_configure('warning', foreground='orange')
self.log_text.tag_configure('error', foreground='red')
# 配置日志标签颜色(使用统一主题)
self.log_text.tag_configure('info', foreground=LogTheme.get_color('INFO'))
self.log_text.tag_configure('success', foreground=LogTheme.get_color('SUCCESS'))
self.log_text.tag_configure('warning', foreground=LogTheme.get_color('WARNING'))
self.log_text.tag_configure('error', foreground=LogTheme.get_color('ERROR'))
# 报告区域(完成后显示)- 初始隐藏
self.report_frame = ttk.LabelFrame(self.main_frame, text="执行报告", padding=5)
@@ -191,7 +204,7 @@ class DeleteProgressWindow:
self.progress_var.set(message)
else:
self.progress_var.set(message)
self.window.update_idletasks()
self.update_idletasks()
def append_log(self, message: str, level: str = "info"):
"""
@@ -208,7 +221,7 @@ class DeleteProgressWindow:
self.log_text.insert(tk.END, log_entry, level)
self.log_text.see(tk.END)
self.log_text.config(state=tk.DISABLED)
self.window.update_idletasks()
self.update_idletasks()
def show_report(self, markdown_content: str):
"""
@@ -242,7 +255,7 @@ class DeleteProgressWindow:
self.report_text.config(state=tk.DISABLED)
# 更新标题
self.window.title("执行报告")
self.title("执行报告")
# 隐藏取消按钮,显示关闭按钮
self.cancel_button.pack_forget()
@@ -435,7 +448,7 @@ class DeleteProgressWindow:
def close(self):
"""关闭窗口"""
self.window.destroy()
self.destroy()
def is_cancelled(self) -> bool:
"""检查是否已取消"""
@@ -444,4 +457,4 @@ class DeleteProgressWindow:
def set_completed(self):
"""设置为完成状态"""
self.cancel_button.pack_forget()
self.close_button.pack(side=tk.RIGHT)
self.close_button.pack(side=tk.RIGHT)

View File

@@ -8,19 +8,14 @@
import tkinter as tk
from datetime import datetime
from gui.log_config import LogTheme
class LogText(tk.Frame):
"""日志文本框组件(带滚动条)"""
# 日志级别颜色配置
LOG_COLORS = {
'INFO': '#000000', # 黑色
'SUCCESS': '#008000', # 绿色
'WARNING': '#FF8C00', # 深橙色
'ERROR': '#FF0000', # 红色
'DEBUG': '#808080', # 灰色
}
# 使用统一日志主题配置
LOG_COLORS = LogTheme.COLORS
def __init__(self, parent, readonly=True, **kwargs):
"""

View File

@@ -9,9 +9,10 @@
import tkinter as tk
from tkinter import ttk
from typing import Optional, Callable
from gui.widgets.base_dialog import BaseDialog
class ProgressDialog:
class ProgressDialog(BaseDialog):
"""进度对话框"""
def __init__(
@@ -32,42 +33,46 @@ class ProgressDialog:
can_cancel: 是否可以取消
on_cancel: 取消回调函数
"""
self.parent = parent
self.can_cancel = can_cancel
self.on_cancel = on_cancel
self.cancelled = False
self.message_label = None
self.progress = None
self.cancel_button = None
# 创建对话框
self.dialog = tk.Toplevel(parent)
self.dialog.title(title)
self.dialog.resizable(False, False)
self.dialog.transient(parent)
self.dialog.grab_set()
# 调用父类初始化(会自动设置为模态并居中)
super().__init__(parent, title)
# 居中显示
self._center()
# 设置固定大小
self.resizable(False, False)
# 创建内容
self._create_widgets(message)
def _center(self):
"""将对话框居中显示"""
self.dialog.update_idletasks()
width = 400
height = 150
x = (self.dialog.winfo_screenwidth() // 2) - (width // 2)
y = (self.dialog.winfo_screenheight() // 2) - (height // 2)
self.dialog.geometry(f"{width}x{height}+{x}+{y}")
# 设置固定大小并重新居中
self._set_fixed_size(400, 150)
def _set_fixed_size(self, width: int, height: int):
"""
设置固定大小并重新居中
Args:
width: 宽度
height: 高度
"""
self.update_idletasks()
self.geometry(f"{width}x{height}")
self._center_window()
def _create_widgets(self, message: str):
"""创建对话框组件"""
# 消息标签
self.message_label = ttk.Label(self.dialog, text=message, wraplength=380)
self.message_label = ttk.Label(self, text=message, wraplength=380)
self.message_label.pack(pady=(20, 10), padx=20)
# 进度条
self.progress = ttk.Progressbar(
self.dialog,
self,
mode='indeterminate',
length=360
)
@@ -76,7 +81,7 @@ class ProgressDialog:
# 取消按钮
if self.can_cancel:
button_frame = ttk.Frame(self.dialog)
button_frame = ttk.Frame(self)
button_frame.pack(pady=10)
self.cancel_button = ttk.Button(
@@ -95,8 +100,9 @@ class ProgressDialog:
def update_message(self, message: str):
"""更新显示消息"""
self.message_label.config(text=message)
self.dialog.update_idletasks()
if self.message_label:
self.message_label.config(text=message)
self.update_idletasks()
def set_progress(self, value: int, maximum: int = 100):
"""
@@ -106,14 +112,16 @@ class ProgressDialog:
value: 当前进度值
maximum: 最大值
"""
self.progress.config(mode='determinate', maximum=maximum)
self.progress['value'] = value
self.dialog.update_idletasks()
if self.progress:
self.progress.config(mode='determinate', maximum=maximum)
self.progress['value'] = value
self.update_idletasks()
def close(self):
"""关闭对话框"""
self.progress.stop()
self.dialog.destroy()
if self.progress:
self.progress.stop()
super().close()
def is_cancelled(self) -> bool:
"""检查是否已取消"""