"""DASHEN UI 1.7 · Python 3.9+ / Tk 8.6.""" import json import os from pathlib import Path import tempfile import tkinter as tk from tkinter import ttk COLORS = { "bg": "#070907", "panel": "#10120f", "text": "#f1e8d6", "muted": "#bcae95", "accent": "#ed6e2e", "label": "#ffae36", "focus": "#ffae36", "success": "#64eaa1", "error": "#ff604c", "line": "#79532c", } DEFAULT = {"name": "编辑", "notifications": True} def config_path(): if os.name == "nt": base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData/Local") else: base = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") return base / "dashen-ui" / "preferences.json" def write_preferences(path, name, notifications): value = {"name": name.strip(), "notifications": bool(notifications)} if not 2 <= len(value["name"]) <= 24: raise ValueError("请输入 2–24 个字符。") path.parent.mkdir(parents=True, exist_ok=True) descriptor, temporary = tempfile.mkstemp(dir=path.parent) try: with os.fdopen(descriptor, "w", encoding="utf-8") as handle: json.dump(value, handle, ensure_ascii=False) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) finally: Path(temporary).unlink(missing_ok=True) return value def draw_button_face(image, width, height, edge, depth): """Draw two 45-degree cuts and the warm action rail at actual pixel size.""" image.configure(width=width, height=height) bottom = height - 4 cut = min(12, height // 3, width // 4) band = max(3, height // 13) spectrum = [] for x in range(width): p = x / max(width - 1, 1) green = round(174 - 53 * p) blue = round(54 - 2 * p) spectrum.append(f"#ff{green:02x}{blue:02x}") for y in range(height): left = max(0, cut - (bottom - y)) right = width - 1 - max(0, cut - y) row = [COLORS["panel"]] * width if y <= bottom: for x in range(left, right + 1): if y in (0, bottom) or x in (left, right): row[x] = edge elif y > bottom - band: row[x] = spectrum[x] elif y <= bottom + depth: row[cut:right + 1] = ["#392612"] * (right + 1 - cut) image.put("{" + " ".join(row) + "}", to=(0, y)) def configure_button(button): style = ttk.Style(button) images = [tk.PhotoImage(master=button, width=130, height=54) for _ in range(3)] # A button of a different size gets its own native state images. button.readout_images = images element = f"readout.{images[0]}.face" widget_style = f"{images[0]}.Readout.TButton" style.element_create(element, "image", images[0], ("pressed", images[2]), ("active", images[1]), width=130, height=54, sticky="nsew") style.layout(widget_style, [(element, {"sticky": "nsew", "children": [ ("Button.padding", {"sticky": "nsew", "children": [ ("Button.focus", {"sticky": "nsew", "children": [ ("Button.label", {"sticky": "nsew"})]})]})]})]) style.configure(widget_style, padding=(16, 7, 16, 21), foreground=COLORS["label"], focuscolor=COLORS["focus"], focusthickness=2, anchor="center") button.configure(style=widget_style) def resize(event): states = ((COLORS["accent"], 3), (COLORS["label"], 3), (COLORS["focus"], 1)) for image, (edge, depth) in zip(images, states): draw_button_face(image, event.width, event.height, edge, depth) button.bind("", resize, add="+") class Preferences: def __init__(self, window, path): self.window = window self.path = path self.name = tk.StringVar(window, DEFAULT["name"]) self.notifications = tk.BooleanVar(window, DEFAULT["notifications"]) window.title("DASHEN UI · 偏好设置") window.configure(bg=COLORS["bg"]) window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) style = ttk.Style(window) style.theme_use("clam") style.configure("Console.TCheckbutton", foreground=COLORS["label"], background=COLORS["panel"], indicatorbackground=COLORS["bg"], focuscolor=COLORS["focus"], padding=6) style.map("Console.TCheckbutton", background=[("active", COLORS["panel"])], indicatorbackground=[("selected", COLORS["accent"])]) panel = tk.Frame(window, bg=COLORS["panel"], padx=20, pady=16, highlightbackground=COLORS["line"], highlightthickness=1) panel.grid(row=0, column=0, padx=16, pady=16, sticky="nsew") panel.columnconfigure(0, weight=1) def label(text, row, color="text", font="TkDefaultFont"): widget = tk.Label(panel, text=text, anchor="w", justify="left", font=font, bg=COLORS["panel"], fg=COLORS[color]) widget.configure(wraplength=260) widget.grid(row=row, column=0, sticky="ew", pady=4) return widget label("ADP-DESKTOP · UI-009 · UI-009-TITLE", 0, "muted") label("偏好设置", 1, "accent", font=("TkDefaultFont", 23, "bold")) rule = tk.Frame(panel, background=COLORS["panel"]) rule.grid(row=2, column=0, sticky="ew", pady=5) for color, height in (("#401a0e", 1), ("#9c3719", 1), ("#ff3300", 2), ("#9c3719", 1), ("#401a0e", 1)): tk.Frame(rule, height=height, background=color).pack(fill="x") label("UI-009-RULE · UI-009-SECTION\n仅保存在此设备上。", 3, "muted") self.field_id = label("UI-006-LABEL · UI-006-FIELD\n显示名称", 4, "label") self.field_invalid = False self.entry = tk.Entry(panel, textvariable=self.name, width=20, relief="flat", background=COLORS["bg"], foreground=COLORS["text"], insertbackground=COLORS["text"], highlightthickness=2, highlightbackground=COLORS["line"], highlightcolor=COLORS["focus"]) self.entry.grid(row=5, column=0, sticky="ew", ipady=7) self.entry.bind("", lambda _: self.sync_field_id(True)) self.entry.bind("", lambda _: self.sync_field_id(False)) self.counter = label("", 6, "muted") style.configure("Name.Horizontal.TProgressbar", troughcolor=COLORS["line"], background=COLORS["accent"], thickness=3, borderwidth=0) self.meter = ttk.Progressbar(panel, style="Name.Horizontal.TProgressbar", maximum=24) self.meter.grid(row=7, column=0, sticky="new") self.toggle = ttk.Checkbutton(panel, text="状态通知 UI-007-LABEL", variable=self.notifications, style="Console.TCheckbutton", command=self.clear) self.toggle.grid(row=8, column=0, sticky="w", pady=(12, 4)) self.button = ttk.Button(panel, text="保存设置", command=self.save) configure_button(self.button) self.toggle_id = label("UI-007-TRACK · UI-007-THUMB", 9, "muted") self.button.grid(row=11, column=0, sticky="w", pady=4) self.key_ids = label("UI-005-PRIMARY · UI-005-CUT · UI-005-RAIL", 10, "muted") self.status_id = label("UI-008-STATUS", 12, "muted") self.status = label("", 13, "muted") self.button.bind("", lambda _: self.key_ids.configure(text="UI-005-HOVER"), add="+") self.button.bind("", lambda _: self.key_ids.configure(text="UI-005-ACTIVE"), add="+") self.button.bind("", lambda _: self.key_ids.configure(text="UI-005-FOCUS"), add="+") for event in ("", "", ""): self.button.bind(event, lambda _: self.key_ids.configure(text="UI-005-PRIMARY · UI-005-CUT · UI-005-RAIL"), add="+") def sync_switch_id(*_): state = "UI-007-ON" if self.notifications.get() else "UI-007-OFF" self.toggle_id.configure(text="UI-007-TRACK · UI-007-THUMB · " + state) self.notifications.trace_add("write", sync_switch_id) sync_switch_id() self.entry.bind("", lambda event: self.save()) window.bind("", lambda event: self.save()) window.bind("", lambda event: self.save()) self.load() self.update_counter() self.name.trace_add("write", self.clear) self.entry.focus_set() def sync_field_id(self, focused): ids = ["UI-006-LABEL", "UI-006-FIELD"] if focused: ids.append("UI-006-FOCUS") if self.field_invalid: ids.append("UI-006-ERROR") self.field_id.configure(text=" · ".join(ids) + "\n显示名称") def update_counter(self): count = len(self.name.get().strip()) self.meter["value"] = min(count, 24) self.counter.configure(text=f"UI-006-HELP 2–24 个字符 {count} / 24", fg=COLORS["muted"] if 2 <= count <= 24 else COLORS["error"]) def clear(self, *_): self.update_counter() self.field_invalid = False self.sync_field_id(self.entry.focus_get() == self.entry) self.status_id.configure(text="UI-008-STATUS") self.status.configure(text="") def load(self): try: with self.path.open(encoding="utf-8") as file: data = json.load(file) if not isinstance(data, dict) or not isinstance(data.get("name"), str) or type(data.get("notifications")) is not bool: raise ValueError self.name.set(data["name"]) self.notifications.set(data["notifications"]) except FileNotFoundError: pass except (OSError, ValueError): self.status_id.configure(text="UI-008-ERROR") self.status.configure(text="读取失败,可重新填写并保存。", fg=COLORS["error"]) def save(self): try: data = write_preferences(self.path, self.name.get(), self.notifications.get()) except ValueError as error: self.field_invalid = True self.sync_field_id(True) self.status_id.configure(text="UI-008-ERROR") self.status.configure(text=str(error), fg=COLORS["error"]) self.entry.focus_set() except OSError: self.status_id.configure(text="UI-008-ERROR") self.status.configure(text="无法写入,请检查目录权限后重试。", fg=COLORS["error"]) else: self.name.set(data["name"]) self.status.configure(text="偏好设置已保存到此设备。", fg=COLORS["success"]) if __name__ == "__main__": root = tk.Tk() Preferences(root, config_path()) root.mainloop()