Files
playwrite/gui/user_selection_dialog.py
Misaka Server f715cb97e3 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>
2026-02-26 18:40:26 +08:00

171 lines
5.0 KiB
Python

"""
User Selection Dialog - Allows Admin to choose which user identity to use
"""
import tkinter as tk
from tkinter import ttk, messagebox
from typing import Optional, Dict, Any, List
class UserSelectionDialog:
"""
Modal dialog for Admin users to select which user identity to use
Usage:
dialog = UserSelectionDialog(parent, users_list, current_username)
selected_user = dialog.get_selected_user()
if selected_user:
# Use the selected user info
"""
def __init__(self, parent, users: List[Dict[str, Any]], current_username: str):
"""
Initialize the user selection dialog
Args:
parent: The parent Tkinter window
users: List of user dictionaries [{id, username, user_type}]
current_username: The currently logged-in Admin's username
"""
self.parent = parent
self.users = users
self.current_username = current_username
self.selected_user = None
self.dialog = None
self.selected_var = None
self._create_dialog()
self.parent.wait_window(self.dialog)
def _create_dialog(self):
"""Create the user selection dialog UI"""
# 使用普通 Toplevel
self.dialog = tk.Toplevel(self.parent)
self.dialog.title("选择用户身份")
self.dialog.resizable(False, False)
# 设置固定大小
dialog_width = 450
dialog_height = 400
self.dialog.geometry(f"{dialog_width}x{dialog_height}")
# 设置为模态对话框
self.dialog.transient(self.parent)
self.dialog.grab_set()
# 居中显示到屏幕(而不是父窗口)
self._center_on_screen()
self._create_widgets()
def _center_on_screen(self):
"""将对话框居中到屏幕"""
self.dialog.update_idletasks()
dialog_width = 450
dialog_height = 400
screen_width = self.dialog.winfo_screenwidth()
screen_height = self.dialog.winfo_screenheight()
x = (screen_width - dialog_width) // 2
y = (screen_height - dialog_height) // 2
self.dialog.geometry(f"{dialog_width}x{dialog_height}+{x}+{y}")
def _create_widgets(self):
"""Create dialog widgets"""
main_frame = ttk.Frame(self.dialog, padding="20")
main_frame.pack(fill=tk.BOTH, expand=True)
# Title
title_label = ttk.Label(
main_frame,
text="请选择要使用的用户身份",
font=('', 14, 'bold')
)
title_label.pack(pady=(0, 20))
# User list with scrollbar
list_frame = ttk.Frame(main_frame)
list_frame.pack(fill=tk.BOTH, expand=True)
scrollbar = ttk.Scrollbar(list_frame)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
self.selected_var = tk.StringVar()
# Sort users: current user first, then by username
sorted_users = sorted(
self.users,
key=lambda u: (0 if u['username'] == self.current_username else 1, u['username'])
)
for user in sorted_users:
username = user['username']
user_type = user['user_type']
is_current = username == self.current_username
# Mark current user
display_text = f"{username} ({user_type})"
if is_current:
display_text += " [当前]"
rb = ttk.Radiobutton(
list_frame,
text=display_text,
variable=self.selected_var,
value=username
)
rb.pack(anchor=tk.W, pady=3, padx=5)
# Select current user by default
self.selected_var.set(self.current_username)
# Buttons
button_frame = ttk.Frame(main_frame)
button_frame.pack(pady=(20, 0))
confirm_btn = ttk.Button(
button_frame,
text="确认",
command=self._on_confirm,
width=10
)
confirm_btn.pack(side=tk.LEFT, padx=5)
cancel_btn = ttk.Button(
button_frame,
text="取消",
command=self._on_cancel,
width=10
)
cancel_btn.pack(side=tk.LEFT, padx=5)
def _on_confirm(self):
"""Handle confirm button click"""
selected_username = self.selected_var.get()
if not selected_username:
messagebox.showwarning("未选择", "请选择一个用户")
return
# Find the selected user
for user in self.users:
if user['username'] == selected_username:
self.selected_user = user
break
self.dialog.destroy()
def _on_cancel(self):
"""Handle cancel button click"""
self.selected_user = None
self.dialog.destroy()
def get_selected_user(self) -> Optional[Dict[str, Any]]:
"""
Get the selected user info
Returns:
User dict {id, username, user_type} if confirmed, None if cancelled
"""
return self.selected_user