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>
182 lines
5.4 KiB
Python
182 lines
5.4 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
日志文本框组件
|
|
|
|
带颜色支持的日志显示组件。
|
|
"""
|
|
|
|
import tkinter as tk
|
|
from datetime import datetime
|
|
from gui.log_config import LogTheme
|
|
|
|
|
|
class LogText(tk.Frame):
|
|
"""日志文本框组件(带滚动条)"""
|
|
|
|
# 使用统一日志主题配置
|
|
LOG_COLORS = LogTheme.COLORS
|
|
|
|
def __init__(self, parent, readonly=True, **kwargs):
|
|
"""
|
|
初始化日志文本框
|
|
|
|
Args:
|
|
parent: 父容器
|
|
readonly: 是否为只读模式
|
|
**kwargs: 其他参数
|
|
"""
|
|
super().__init__(parent)
|
|
|
|
# 创建文本框和滚动条
|
|
self.text = tk.Text(self, **kwargs)
|
|
self.scrollbar = tk.Scrollbar(self, orient=tk.VERTICAL, command=self.text.yview)
|
|
self.text.configure(yscrollcommand=self.scrollbar.set)
|
|
|
|
# 布局
|
|
self.text.grid(row=0, column=0, sticky="nsew")
|
|
self.scrollbar.grid(row=0, column=1, sticky="ns")
|
|
|
|
# 配置网格权重
|
|
self.grid_rowconfigure(0, weight=1)
|
|
self.grid_columnconfigure(0, weight=1)
|
|
|
|
# 标记 tags 是否已配置
|
|
self._tags_configured = False
|
|
|
|
# 设置为只读模式
|
|
if readonly:
|
|
self._make_readonly()
|
|
|
|
def _ensure_tags_configured(self):
|
|
"""确保文本标签已配置(延迟配置,在首次使用时)"""
|
|
if not self._tags_configured:
|
|
try:
|
|
for level, color in self.LOG_COLORS.items():
|
|
self.text.tag_config(level.lower(), foreground=color)
|
|
self._tags_configured = True
|
|
except Exception:
|
|
# 如果配置失败,标记为已尝试,避免重复尝试
|
|
self._tags_configured = True
|
|
|
|
def _make_readonly(self):
|
|
"""通过绑定事件使文本框只读"""
|
|
# 允许复制、全选等常用操作,阻止其他编辑操作
|
|
self.text.bind('<Key>', self._handle_key)
|
|
self.text.bind('<Button-1>', self._allow_click) # 允许左键点击选择
|
|
|
|
def _handle_key(self, event):
|
|
"""处理按键事件,允许复制操作,阻止编辑"""
|
|
# 允许的快捷键
|
|
allowed_keys = [
|
|
'Control-c', # 复制
|
|
'Control-C', # 复制(大写)
|
|
'Control-a', # 全选
|
|
'Control-A', # 全选(大写)
|
|
'Control-x', # 剪切(虽然剪不了,但不报错)
|
|
'Control-X',
|
|
]
|
|
|
|
# 检查是否是允许的快捷键
|
|
key_sym = event.keysym
|
|
state = event.state
|
|
|
|
# 检查 Ctrl 组合键
|
|
if state & 0x4: # Ctrl 键被按下
|
|
full_key = f"Control-{key_sym}"
|
|
if full_key in allowed_keys:
|
|
return # 允许执行
|
|
|
|
# 其他所有按键都阻止
|
|
return 'break'
|
|
|
|
def _allow_click(self, event):
|
|
"""允许点击和选择文本"""
|
|
# 不打断事件,允许正常的选择操作
|
|
return
|
|
|
|
def log(self, message: str, level: str = 'INFO') -> None:
|
|
"""
|
|
添加日志消息
|
|
|
|
Args:
|
|
message: 日志消息
|
|
level: 日志级别 (INFO, SUCCESS, WARNING, ERROR, DEBUG)
|
|
"""
|
|
# 确保 tags 已配置
|
|
self._ensure_tags_configured()
|
|
|
|
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
|
log_message = f"[{timestamp}] [{level}] {message}\n"
|
|
|
|
# 插入文本
|
|
tag = level.lower() if self._tags_configured else None
|
|
if tag:
|
|
try:
|
|
self.text.insert('end', log_message, (tag,))
|
|
except Exception:
|
|
# 如果带标签插入失败,尝试不带标签
|
|
self.text.insert('end', log_message)
|
|
else:
|
|
self.text.insert('end', log_message)
|
|
|
|
# 自动滚动到底部
|
|
self.text.see('end')
|
|
|
|
def info(self, message: str) -> None:
|
|
"""添加 INFO 级别日志"""
|
|
self.log(message, 'INFO')
|
|
|
|
def success(self, message: str) -> None:
|
|
"""添加 SUCCESS 级别日志"""
|
|
self.log(message, 'SUCCESS')
|
|
|
|
def warning(self, message: str) -> None:
|
|
"""添加 WARNING 级别日志"""
|
|
self.log(message, 'WARNING')
|
|
|
|
def error(self, message: str) -> None:
|
|
"""添加 ERROR 级别日志"""
|
|
self.log(message, 'ERROR')
|
|
|
|
def debug(self, message: str) -> None:
|
|
"""添加 DEBUG 级别日志"""
|
|
self.log(message, 'DEBUG')
|
|
|
|
def clear(self) -> None:
|
|
"""清空日志"""
|
|
self.text.delete('1.0', 'end')
|
|
|
|
def save_to_file(self, file_path: str) -> bool:
|
|
"""
|
|
保存日志到文件
|
|
|
|
Args:
|
|
file_path: 保存路径
|
|
|
|
Returns:
|
|
是否成功
|
|
"""
|
|
try:
|
|
with open(file_path, 'w', encoding='utf-8') as f:
|
|
f.write(self.text.get('1.0', 'end-1c'))
|
|
return True
|
|
except Exception as e:
|
|
self.error(f"保存日志失败: {e}")
|
|
return False
|
|
|
|
# 委托其他常用方法到内部 text 组件
|
|
def pack(self, **kwargs):
|
|
"""Pack 布局"""
|
|
super().pack(**kwargs)
|
|
|
|
def grid(self, **kwargs):
|
|
"""Grid 布局"""
|
|
super().grid(**kwargs)
|
|
|
|
def apply_font(self, font_family: str, font_size: int):
|
|
"""应用字体设置"""
|
|
from tkinter import font as tk_font
|
|
font_spec = tk_font.Font(family=font_family, size=font_size)
|
|
self.text.configure(font=font_spec)
|