|
| 1 | +"""Persistent GUI-only preferences (appearance theme and interface language). |
| 2 | +
|
| 3 | +These preferences intentionally live outside ``config.json`` because they are |
| 4 | +purely presentational choices made in the desktop shell, not muxing behaviour. |
| 5 | +
|
| 6 | +The GUI previously relied on ``localStorage`` for these values, but pywebview's |
| 7 | +built-in HTTP server binds to a fresh random port on every launch. Because |
| 8 | +``localStorage`` is isolated per-origin (scheme + host + port), a new port means |
| 9 | +a new origin, so the stored theme/language could not be read back and the UI |
| 10 | +always fell back to "System". Persisting through the Python backend keeps the |
| 11 | +choice stable across restarts regardless of the serving port. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import json |
| 17 | +import logging |
| 18 | +import os |
| 19 | +import tempfile |
| 20 | +from pathlib import Path |
| 21 | +from typing import Any |
| 22 | + |
| 23 | +from plexmuxy.config import resolve_config_path |
| 24 | + |
| 25 | +PREFERENCES_FILENAME = "gui-preferences.json" |
| 26 | + |
| 27 | +VALID_THEMES = ("system", "light", "dark") |
| 28 | +VALID_LOCALES = ("system", "en", "zh-CN", "zh-TW", "ru") |
| 29 | + |
| 30 | +DEFAULT_PREFERENCES: dict[str, str] = {"theme": "system", "locale": "system"} |
| 31 | + |
| 32 | + |
| 33 | +def preferences_path() -> Path: |
| 34 | + """Return the GUI preferences file, stored alongside the active config.""" |
| 35 | + return resolve_config_path().parent / PREFERENCES_FILENAME |
| 36 | + |
| 37 | + |
| 38 | +def load_preferences() -> dict[str, str]: |
| 39 | + """Load persisted GUI preferences, falling back to safe defaults.""" |
| 40 | + path = preferences_path() |
| 41 | + if not path.exists(): |
| 42 | + return dict(DEFAULT_PREFERENCES) |
| 43 | + try: |
| 44 | + raw = json.loads(path.read_text(encoding="utf-8")) |
| 45 | + except (OSError, json.JSONDecodeError): |
| 46 | + logging.debug("Could not read GUI preferences at %s", path, exc_info=True) |
| 47 | + return dict(DEFAULT_PREFERENCES) |
| 48 | + if not isinstance(raw, dict): |
| 49 | + return dict(DEFAULT_PREFERENCES) |
| 50 | + theme = raw.get("theme") |
| 51 | + locale = raw.get("locale") |
| 52 | + return { |
| 53 | + "theme": theme if theme in VALID_THEMES else DEFAULT_PREFERENCES["theme"], |
| 54 | + "locale": locale if locale in VALID_LOCALES else DEFAULT_PREFERENCES["locale"], |
| 55 | + } |
| 56 | + |
| 57 | + |
| 58 | +def save_preferences(payload: dict[str, Any]) -> dict[str, str]: |
| 59 | + """Merge and atomically persist GUI preferences, returning the stored values.""" |
| 60 | + if not isinstance(payload, dict): |
| 61 | + raise ValueError("Preferences payload must be an object") |
| 62 | + |
| 63 | + current = load_preferences() |
| 64 | + if "theme" in payload: |
| 65 | + theme = payload["theme"] |
| 66 | + if theme not in VALID_THEMES: |
| 67 | + raise ValueError(f"theme must be one of: {', '.join(VALID_THEMES)}") |
| 68 | + current["theme"] = theme |
| 69 | + if "locale" in payload: |
| 70 | + locale = payload["locale"] |
| 71 | + if locale not in VALID_LOCALES: |
| 72 | + raise ValueError(f"locale must be one of: {', '.join(VALID_LOCALES)}") |
| 73 | + current["locale"] = locale |
| 74 | + |
| 75 | + target = preferences_path() |
| 76 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 77 | + fd, temp_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent) |
| 78 | + try: |
| 79 | + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as output: |
| 80 | + json.dump(current, output, indent=2, ensure_ascii=False) |
| 81 | + output.write("\n") |
| 82 | + output.flush() |
| 83 | + os.fsync(output.fileno()) |
| 84 | + os.replace(temp_name, target) |
| 85 | + except Exception: |
| 86 | + try: |
| 87 | + os.unlink(temp_name) |
| 88 | + except OSError: |
| 89 | + pass |
| 90 | + raise |
| 91 | + return current |
0 commit comments