from __future__ import annotations import os import tkinter as tk from pathlib import Path from tkinter import ttk from typing import Callable, Iterable, Sequence from . import theme BUTTON_ICONS = { "刷新设备": "⟳", "扫描 WiFi": "⌕", "扫描WiFi": "⌕", "WiFi ADB": "▣", "保存配置": "✓", "截图+OCR": "▧", "开始运行": "▶", "暂停/继续": "Ⅱ", "停止": "■", "强制停止": "!", "发送返回键": "↩", "刷新": "⟳", "刷新预览": "⟳", "刷新列表": "⟳", "刷新映射表": "⟳", "打开pic目录": "□", "打开目录": "□", "验证卡密": "✓", "刷新状态": "⟳", "保存日志配置": "✓", "查看大图": "▢", "复制条目": "◇", "清除": "×", } NAV_ICONS = { "数据看板": "▦", "运行设置": "▶", "筛选设置": "◈", "高价值预约": "◇", "养号设置": "◌", "调试参数": "⌁", "授权": "✓", "日志配置": "☰", "关键词": "⌕", "运行日志": "☰", "截图预览": "▧", "统计信息": "▦", "预约队列": "≡", "高价值房间": "◇", "行为日志": "☷", "实时状态": "●", "OCR结果": "▤", "中奖记录": "□", "映射表": "⌘", "WiFi ADB": "▣", } def _with_icon(text: str, icon: str | None) -> str: if not icon: return text return text if text.startswith(icon) else f"{icon} {text}" def _parent_bg(parent) -> str: try: return str(parent["bg"]) except Exception: return theme.BG class IconButton(tk.Button): def __init__(self, *args, icon: str | None = None, **kwargs): self._icon = icon if "text" in kwargs: kwargs["text"] = _with_icon(str(kwargs["text"]), icon) super().__init__(*args, **kwargs) def configure(self, cnf=None, **kwargs): # type: ignore[override] if "text" in kwargs: kwargs["text"] = _with_icon(str(kwargs["text"]), self._icon) return super().configure(cnf, **kwargs) config = configure def rounded_rect(canvas: tk.Canvas, x1: int, y1: int, x2: int, y2: int, radius: int, **kwargs) -> int: points = [ x1 + radius, y1, x2 - radius, y1, x2, y1, x2, y1 + radius, x2, y2 - radius, x2, y2, x2 - radius, y2, x1 + radius, y2, x1, y2, x1, y2 - radius, x1, y1 + radius, x1, y1, ] return canvas.create_polygon(points, smooth=True, splinesteps=16, **kwargs) class RoundedSurface(tk.Frame): def __init__( self, parent, *, fill: str = theme.SURFACE, outline: str = theme.BORDER, radius: int = theme.RADIUS_MD, ) -> None: super().__init__(parent, bg=_parent_bg(parent), highlightthickness=0, bd=0) self._fill = fill self._outline = outline self._radius = radius self._canvas = tk.Canvas(self, bg=_parent_bg(parent), highlightthickness=0, bd=0) self._canvas.place(x=0, y=0, relwidth=1, relheight=1) self._canvas.tk.call("lower", self._canvas._w) self.bind("", self._draw_surface) def _draw_surface(self, _event=None) -> None: width = max(2, self.winfo_width()) height = max(2, self.winfo_height()) self._canvas.delete("all") rounded_rect( self._canvas, 1, 1, width - 2, height - 2, self._radius, fill=self._fill, outline=self._outline, ) def rounded_surface( parent, *, fill: str = theme.SURFACE, outline: str = theme.BORDER, radius: int = theme.RADIUS_MD, ) -> RoundedSurface: return RoundedSurface(parent, fill=fill, outline=outline, radius=radius) class RoundedButton(tk.Canvas): def __init__( self, parent, text: str, command: Callable[[], None] | None, *, kind: str = "soft", icon: str | None = None, width: int | None = None, ) -> None: self._icon = icon self.text = _with_icon(text, icon) self.command = command self.kind = kind self._state = "normal" colors = { "primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK), "danger": (theme.RED_SOFT, theme.RED, "#ffe5e2"), "amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8"), "soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER), "ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT), } self.bg_color, self.fg_color, self.hover_color = colors.get(kind, colors["soft"]) w = width or max(98, len(self.text) * 14 + 34) super().__init__(parent, width=w, height=38, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2") self._draw(self.bg_color) self.bind("", self._click) self.bind("", lambda _e: self._draw(self.hover_color)) self.bind("", lambda _e: self._draw(self.bg_color)) def _draw(self, fill: str) -> None: self.delete("all") outline = theme.TEAL if self.kind == "primary" else theme.BORDER fg = self.fg_color if self._state != "disabled" else theme.SUBTLE rounded_rect(self, 1, 1, int(self["width"]) - 2, int(self["height"]) - 2, theme.RADIUS_SM, fill=fill, outline=outline) self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 12, "bold") if self.kind == "primary" else theme.FONT_UI) def _click(self, _event) -> None: if self.command and self._state != "disabled": self.command() def configure(self, cnf=None, **kwargs): # type: ignore[override] if cnf: kwargs.update(cnf) if "text" in kwargs: self.text = _with_icon(str(kwargs.pop("text")), self._icon) if "state" in kwargs: self._state = str(kwargs.pop("state")) self.configure(cursor="arrow" if self._state == "disabled" else "hand2") result = super().configure(**kwargs) if kwargs else None self._draw(self.bg_color) return result config = configure class RoundedNavButton(tk.Canvas): def __init__(self, parent, text: str, command: Callable[[], None], *, active: bool = False) -> None: self.raw_text = text self.text = _with_icon(text, NAV_ICONS.get(text)) self.command = command self.active = active super().__init__(parent, height=34, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2") self.bind("", lambda _e: self._draw()) self.bind("", lambda _e: self.command()) self.bind("", lambda _e: self._draw(hover=True)) self.bind("", lambda _e: self._draw()) def set_active(self, active: bool) -> None: self.active = active self._draw() def _draw(self, hover: bool = False) -> None: self.delete("all") width = max(1, self.winfo_width()) bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE) fg = theme.TEAL_DARK if self.active else theme.TEXT rounded_rect(self, 1, 2, width - 2, 32, theme.RADIUS_SM, fill=bg, outline=bg) if self.active: rounded_rect(self, 3, 8, 8, 26, 4, fill=theme.TEAL, outline=theme.TEAL) self.create_text(18 if self.active else 13, 17, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 11, "bold") if self.active else theme.FONT_UI) def clear(frame: tk.Misc) -> None: for child in frame.winfo_children(): child.destroy() def button(parent, text: str, command: Callable[[], None] | None = None, *, kind: str = "soft", width: int | None = None) -> tk.Canvas: return RoundedButton(parent, text, command, kind=kind, icon=BUTTON_ICONS.get(text), width=width) def nav_button(parent, text: str, command: Callable[[], None], *, active: bool = False) -> tk.Canvas: return RoundedNavButton(parent, text, command, active=active) def pill(parent, text: str, *, fg: str = theme.TEAL, bg: str = theme.TEAL_SOFT) -> tk.Label: return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3) def status_pill(parent, text: str, *, color: str = theme.GREEN, bg: str = theme.GREEN_SOFT) -> tk.Label: return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=14, pady=5) def card(parent, title: str | None = None, *, padding: int = 14) -> tk.Frame: frame = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) if title: head = tk.Frame(frame, bg=theme.SURFACE) head.pack(fill="x", padx=padding + 2, pady=(padding, 7)) tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10)) ttk.Label(head, text=title, style="H2.TLabel").pack(side="left") return frame def metric(parent, title: str, value: object, hint: str = "", color: str = theme.TEAL) -> tk.Frame: box = card(parent) top = tk.Frame(box, bg=theme.SURFACE) top.pack(fill="x", padx=14, pady=(10, 3)) tk.Label(top, text="●", fg=color, bg=theme.SURFACE, font=("Segoe UI", 11, "bold")).pack(side="left") ttk.Label(top, text=title, style="Small.TLabel").pack(side="left", padx=(6, 0)) ttk.Label(box, text=str(value), style="Value.TLabel").pack(anchor="w", padx=14) ttk.Label(box, text=hint, style="Small.TLabel").pack(anchor="w", padx=14, pady=(0, 10)) return box def stat_tile(parent, title: str, value: object, hint: str, *, color: str, soft: str, compact: bool = False) -> tk.Frame: box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD) if compact: box.configure(height=72) accent = tk.Frame(box, bg=color, width=4) accent.pack(side="left", fill="y") inner = tk.Frame(box, bg=theme.SURFACE) inner.pack(side="left", fill="both", expand=True) head = tk.Frame(inner, bg=theme.SURFACE) head.pack(fill="x", padx=16, pady=(10, 2)) tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left") tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 10, "bold")).pack(side="right") tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 19, "bold")).pack(anchor="w", padx=16) tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=3).pack(anchor="w", padx=16, pady=(6, 10)) return box def section(parent, title: str, subtitle: str = "") -> tk.Frame: row = tk.Frame(parent, bg=theme.BG) row.pack(fill="x", pady=(2, 10)) ttk.Label(row, text=title, style="Title.TLabel").pack(side="left") if subtitle: tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=12, pady=4).pack(side="left", padx=(12, 0)) return row def flow_grid(parent, columns: int = 4) -> tk.Frame: grid = tk.Frame(parent, bg=theme.BG) grid.pack(fill="x", pady=(0, 14)) for idx in range(columns): grid.grid_columnconfigure(idx, weight=1, uniform="metric") return grid def text_panel(parent, title: str, lines: Iterable[str], height: int = 10) -> tk.Frame: box = card(parent, title) text = tk.Text( box, height=height, wrap="none", bd=0, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, font=theme.FONT_MONO, padx=14, pady=12, spacing1=3, spacing3=4, ) text.pack(fill="both", expand=True, padx=11, pady=(4, 11)) content = "\n".join(list(lines)[:260]) or "暂无数据" text.insert("1.0", content) text.configure(state="disabled") return box def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tuple[tk.Frame, tk.Text]: box = card(parent, title) wrap = tk.Frame(box, bg=theme.SURFACE_ALT) wrap.pack(fill="both", expand=True, padx=11, pady=(4, 11)) wrap.grid_rowconfigure(0, weight=1) wrap.grid_columnconfigure(0, weight=1) text = tk.Text( wrap, height=height, wrap="none", bd=0, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, font=theme.FONT_MONO, padx=14, pady=12, spacing1=3, spacing3=4, ) yscroll = ttk.Scrollbar(wrap, orient="vertical", command=text.yview) xscroll = ttk.Scrollbar(wrap, orient="horizontal", command=text.xview) text.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set) text.grid(row=0, column=0, sticky="nsew") yscroll.grid(row=0, column=1, sticky="ns") xscroll.grid(row=1, column=0, sticky="ew") content = "\n".join(list(lines)[-1000:]) or "暂无数据" text.insert("1.0", content) text.configure(state="disabled") def _wheel(event): text.yview_scroll(int(-1 * (event.delta / 120)), "units") return "break" def _shift_wheel(event): text.xview_scroll(int(-1 * (event.delta / 120)), "units") return "break" text.bind("", _wheel) text.bind("", _shift_wheel) return box, text def table_panel(parent, title: str, columns: Sequence[tuple[str, str, int]], rows: Sequence[dict], height: int = 8) -> tk.Frame: box = card(parent, title) table_wrap = tk.Frame(box, bg=theme.SURFACE) table_wrap.pack(fill="both", expand=True, padx=14, pady=(4, 14)) table_wrap.grid_rowconfigure(0, weight=1) table_wrap.grid_columnconfigure(0, weight=1) tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height) ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview) xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview) tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set) for key, label, width in columns: tree.heading(key, text=label) tree.column(key, width=width, minwidth=min(width, 90), anchor="w", stretch=False) for row in rows: tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns]) if not rows: tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)]) tree.grid(row=0, column=0, sticky="nsew") ybar.grid(row=0, column=1, sticky="ns") xbar.grid(row=1, column=0, sticky="ew") box.tree = tree # type: ignore[attr-defined] box.columns_spec = list(columns) # type: ignore[attr-defined] return box def mini_table(parent, title: str, rows: Sequence[tuple[str, str, str]], *, color: str = theme.TEAL) -> tk.Frame: box = card(parent, title) body = tk.Frame(box, bg=theme.SURFACE) body.pack(fill="both", expand=True, padx=11, pady=(4, 11)) if not rows: tk.Label(body, text="暂无数据", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_READ, pady=20).pack(fill="x") return box for idx, (a, b, c) in enumerate(rows[:8]): row = tk.Frame(body, bg=theme.SURFACE if idx % 2 == 0 else theme.SURFACE_ALT) row.pack(fill="x", pady=1) tk.Label(row, text=a, bg=row["bg"], fg=theme.TEXT, font=theme.FONT_READ, anchor="w").pack(side="left", fill="x", expand=True, padx=9, pady=7) tk.Label(row, text=b, bg=row["bg"], fg=color, font=("Microsoft YaHei UI", 10, "bold"), width=10).pack(side="left", padx=5) tk.Label(row, text=c, bg=row["bg"], fg=theme.MUTED, font=theme.FONT_READ, width=12).pack(side="left", padx=5) return box def field_shell(parent, label: str) -> tk.Frame: row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM) tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=9, pady=(7, 1)) return row def field(parent, label: str, variable: tk.Variable | None = None, *, value: object = "", wide: bool = False) -> tk.Frame: row = field_shell(parent, label) if variable is None: variable = tk.StringVar(value=str(value)) entry = tk.Entry( row, textvariable=variable, bg=theme.SURFACE_ALT, fg=theme.TEXT, insertbackground=theme.TEAL, relief="flat", bd=0, font=theme.FONT_UI, ) entry.pack(fill="x", padx=9, pady=(0, 8)) return row def select_field( parent, label: str, variable: tk.Variable | None = None, *, value: object = "", values: Sequence[object] = (), width: int | None = None, ) -> tk.Frame: row = field_shell(parent, label) if variable is None: variable = tk.StringVar(value=str(value)) combo = ttk.Combobox( row, textvariable=variable, values=[str(item) for item in values], state="readonly", width=width, ) combo.pack(fill="x", padx=9, pady=(0, 8)) return row def spin_field( parent, label: str, variable: tk.Variable | None = None, *, value: object = "", from_: float | int = 0, to: float | int = 99999, increment: float | int = 1, width: int | None = None, state: str = "normal", ) -> tk.Frame: return field(parent, label, variable, value=value) def switch_row(parent, label: str, variable: tk.Variable | None = None, value: bool = False) -> tk.Frame: row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM) var = variable if variable is not None else tk.BooleanVar(value=bool(value)) tk.Checkbutton( row, text=label, variable=var, bg=theme.SURFACE_ALT, fg=theme.TEXT, activebackground=theme.SURFACE_ALT, activeforeground=theme.TEXT, selectcolor=theme.SURFACE, relief="flat", bd=0, anchor="w", justify="left", font=theme.FONT_SMALL, ).pack(fill="x", padx=9, pady=6) return row def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]] | Sequence[str]) -> tk.Frame: row = tk.Frame(parent, bg=theme.BG) row.pack(fill="x", pady=(0, 8)) for item in actions: if isinstance(item, str): text, command, kind = item, None, "soft" else: text, command, kind = item button(row, text, command, kind=kind).pack(side="left", padx=(0, 6)) return row def preview_panel(parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560)) -> tk.Frame: box = card(parent, title) body = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1) body.pack(fill="both", expand=True, padx=14, pady=(4, 14)) if image_path and image_path.exists(): try: from PIL import Image, ImageTk img = Image.open(image_path).convert("RGB") img.thumbnail(max_size) photo = ImageTk.PhotoImage(img) label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT) label.image = photo label.pack(expand=True, pady=12) ttk.Label(body, text=os.path.basename(str(image_path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8)) return box except Exception: pass tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True) return box class ScrollFrame(ttk.Frame): def __init__(self, parent): super().__init__(parent, style="Dashboard.TFrame") self.canvas = tk.Canvas(self, bg=theme.BG, highlightthickness=0, bd=0) self.scroll = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview) self.inner = tk.Frame(self.canvas, bg=theme.BG) self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw") self.canvas.configure(yscrollcommand=self.scroll.set) self.canvas.pack(side="left", fill="both", expand=True) self.scroll.pack(side="right", fill="y") self.inner.bind("", lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))) self.canvas.bind("", lambda e: self.canvas.itemconfigure(self.window_id, width=e.width)) self.canvas.bind_all("", self._wheel) def _wheel(self, event) -> None: try: widget = event.widget while widget is not None: if str(widget.winfo_class()) in {"Text", "Treeview", "Listbox", "TCombobox", "TSpinbox", "Entry"}: return if widget is self.canvas: break widget = widget.master self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units") except Exception: pass