#!/usr/bin/env python3
# summary: Choose a theme, colors, wallpaper, and appearance settings.
"""starchaser theme: one palette, every app.

Common commands
    starchaser theme list [--json]          themes and which one is active
    starchaser theme current [--json]       the active theme
    starchaser theme apply <id> [dark|light]   (--dark or --light works too)
    starchaser theme toggle                 flip dark <-> light
    starchaser theme mode <dark|light>      set dark or light (nothing to do if it already is)
    starchaser theme wallpaper list [--json]
    starchaser theme wallpaper <set> [--dark|--light]   your own choice: wallpaper only, colors unchanged
    starchaser theme wallpaper picture <file>   one picture of yours on every screen (your own choice)
    starchaser theme wallpaper follow       the wallpaper follows the theme again
    starchaser theme wallpaper next|previous   the next or previous picture of the wallpaper on screen

Advanced
    starchaser theme look [glass-light|glass|clean|performance|auto|--json]
                                            effects; no argument: show the current effects and selection;
                                            --json: saved choice and resolved profile;
                                            auto = performance in a VM, else glass-light; glass keeps the richer look
    starchaser theme reapply                re-emit the active theme (none yet or gone: apply the default, Starchaser Cockpit)
    starchaser theme browser [on|off|asked]  browser tint for everyone on this computer (default off); no argument: JSON
                                             status ("asked": the one-time "Color the browser too?" was answered; `asked` records it)
    starchaser theme bar [left|right|top|bottom]   where the cockpit spine sits (live)
    starchaser theme cockpit border-width <3-12>   screen border width in pixels (live; default 6)
    starchaser theme cockpit on|off     the cockpit frame and spine, or a slim top bar (live)
    starchaser theme cockpit autohide|hover|dashboard|cputemp|gputemp|clock24|clockdate|closex on|off
                                            one taskbar piece at a time (live): the bar hides until the pointer
                                            reaches it, Quick settings open on hover, Today on the screen edge,
                                            CPU and GPU temperatures, a 24-hour clock, the date beside the clock,
                                            a close x on the focused tiled window
    starchaser theme cockpit compact-menu on|off   compact menu rows (off by default; live)
    starchaser theme cockpit size small|medium   change top bar readability (live)
    starchaser theme cockpit clock digital|analog   the taskbar clock (live)
    starchaser theme cockpit keep <app id>   keep an app's icon on the taskbar, even when it is closed (live)
    starchaser theme cockpit unkeep <app id>...   take kept apps off the taskbar again (live)
    starchaser theme cockpit weather <town or ZIP>|off   where Today's weather is for (live)
    starchaser theme wallpaper restore      re-show the current wallpaper (sign-in or screen connection)
    starchaser theme wallpaper thumbs       make the pickers' missing thumbnails now (list starts this itself)
    starchaser theme data export look|clock-bar   restricted portable settings, as JSON
    starchaser theme data apply look|clock-bar --stdin   replace the portable subset
    starchaser theme data check look|clock-bar --stdin   validate without changing settings

Your changes (Settings > Appearance > Customize), kept apart from the theme and the look so they survive both:
    starchaser theme overrides [--json]     every setting: value, where it comes from, range, contrast warnings
    starchaser theme set <key> <value> [--for <theme>:<dark|light>]    one change, shown at once
    starchaser theme unset <key> [--for <theme>:<dark|light>]          back to the theme's or the look's value
    starchaser theme reset colors|look      this theme's colors (dark or light), or every window and glass change
    starchaser theme undo                   put back the state before the last change (20 steps)
    starchaser theme save <name>            save what you see as a theme of your own, and use it
    starchaser theme save --update <id>     write the color changes into that theme of yours
    starchaser theme export --dir DIR --id ID --name NAME [--from-current] [--json]
                                            write DIR/ID.toml for a theme add-on (Share this look): the default
                                            theme, or with --from-current what you see now (colors with your
                                            changes, window and glass, wallpaper; your own pictures are copied
                                            to DIR/wallpapers). Nothing of yours changes
    starchaser theme rename <id> <name>     rename a theme of yours
    starchaser theme delete <id>            move a theme of yours to the Trash
Keys: windows.glow, windows.glow_color, windows.glow_strength, windows.shadows, windows.border_width,
windows.border_active, windows.border_inactive, windows.inactive_fade, windows.corner_cut, windows.gaps_in,
windows.gaps_out, glass.blur, glass.blur_strength, glass.taskbar, glass.panels, glass.terminal, glass.frame_glow,
motion.animations, colors.<role>. Window and glass changes apply to every theme; colors to the theme in use (dark
or light). Kept in ~/.config/starchaser/theme-overrides.json.

Wallpapers are files named <set>-<dark|light>-<W>x<H>.<png|jpg|webp> (or <set>-<W>x<H>.<ext>, one version for
dark and light), found (recursively) in ~/.local/share/starchaser/wallpapers, /usr/share/starchaser/wallpapers,
~/Pictures/Wallpapers, ~/Documents/Starchaser/Wallpapers and the wallpapers/ folder of each enabled theme
add-on. Each monitor gets the size closest to its shape.
Any other picture in ~/Pictures/Wallpapers can be used as it is ("wallpaper picture").

By default the wallpaper follows the theme: a theme's `wallpaper` key names its set, so applying a theme also
changes the wallpaper. Picking a wallpaper yourself makes it yours: themes and dark/light then leave it alone
(a set of yours still switches to its own dark or light version) until "wallpaper follow".

Themes are TOML files (see themes/README.md) looked up in, in order:
~/.config/starchaser/themes, enabled satellite themes, /usr/share/starchaser/themes,
and ../themes next to this script. User and system theme ids are reserved.
The resolved palette is written to ~/.local/state/starchaser/theme.json, which the bar and
menu watch; every other app gets its own file, and running apps are refreshed where they can be.
"""
import colorsys
import errno
import fcntl
import hashlib
import json
import os
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import time
import tomllib
import unicodedata
from pathlib import Path
from xml.sax.saxutils import escape as xml_escape

sys.path.insert(0, str(Path(__file__).resolve().parent))
import starchaser_accessibility as accessibility
import starchaser_desktop_copy as desktop_copy
import starchaser_theme_apps as app_themes
from starchaser_cli import safe_streams, takes_nothing_after, usage_error

safe_streams()

HOME = Path.home()
SAVER_MODES = ("journey", "calm", "warp", "spores", "polar", "logic", "neonrain", "pawprints", "petals",
               "tunnel", "pendulum", "orrery", "jellyfish", "scope", "rivers")

CONFIG = Path(os.environ.get("XDG_CONFIG_HOME", HOME / ".config"))
DATA = Path(os.environ.get("XDG_DATA_HOME", HOME / ".local/share"))
STATE_DIR = Path(os.environ.get("XDG_STATE_HOME", HOME / ".local/state")) / "starchaser"
STATE = STATE_DIR / "theme.json"


def satellite_theme_dirs() -> list:
    helper = Path(__file__).resolve().with_name("starchaser-satellite")
    try:
        result = subprocess.run([str(helper), "theme-dirs"], capture_output=True, text=True, timeout=5, check=True)
        return [Path(p) for p in json.loads(result.stdout)]
    except (OSError, subprocess.SubprocessError, ValueError, TypeError):
        return []


# These status reads need only the saved JSON, never the add-on inventory. In particular Settings asks for them
# alongside its theme and wallpaper lists; starting an add-on scanner for each answer tripled its startup work.
_saved_only = sys.argv[1:] in (["current", "--json"], ["look", "--json"], ["bar"])
SATELLITE_THEME_DIRS = [] if _saved_only else satellite_theme_dirs()
SYSTEM_THEME_DIR = Path("/usr/share/starchaser/themes")
THEME_DIRS = [CONFIG / "starchaser/themes", *SATELLITE_THEME_DIRS, SYSTEM_THEME_DIR,
              Path(__file__).resolve().parent.parent / "themes"]
MANAGED = "managed by starchaser-theme"
DEFAULT_THEME = "starchaser-cockpit"   # Starchaser Linux default (first boot, fresh installs)
# Look profiles: how much glass. "auto" resolves to performance in a VM (detected, never asked).
# popup_alpha: how solid the shell's panels and menus drawn over windows are (Quick settings, the menu, popups).
# Glass is about 80% so the blurred wallpaper shows through (decided 2026-10-07); Clean and Performance stay solid.
# Keep the original "glass" key for saved choices. New hardware defaults to Soft Glass (#72).
LOOKS = {
    "glass-light": {"bar_alpha": 0.55, "popup_alpha": 0.80, "term_opacity": 1.0, "inactive_opacity": 1.0,
                    "blur": True, "blur_size": 5, "blur_passes": 2, "shadow": True, "shadow_range": 10,
                    "rounding": 14, "border_anim": False, "animations": True, "lock_screenshot": True},
    "glass": {"bar_alpha": 0.55, "popup_alpha": 0.80, "term_opacity": 0.85, "inactive_opacity": 0.85,
              "blur": True, "blur_size": 8, "blur_passes": 3, "shadow": True, "shadow_range": 24,
              "rounding": 14, "border_anim": False, "animations": True, "lock_screenshot": True},
    "clean": {"bar_alpha": 0.85, "popup_alpha": 0.985, "term_opacity": 0.94, "inactive_opacity": 0.95,
              "blur": True, "blur_size": 5, "blur_passes": 2, "shadow": True, "shadow_range": 12,
              "rounding": 12, "border_anim": False, "animations": True, "lock_screenshot": True},
    "performance": {"bar_alpha": 0.97, "popup_alpha": 1.0, "term_opacity": 1.0, "inactive_opacity": 1.0,
                    "blur": False, "blur_size": 0, "blur_passes": 0, "shadow": False, "shadow_range": 0,
                    "rounding": 10, "border_anim": False, "animations": False, "lock_screenshot": False},
}

# enabled theme add-ons' own pictures (<theme folder>/wallpapers) come after yours and before the system's
WALL_DIRS = [DATA / "starchaser/wallpapers", *[d / "wallpapers" for d in SATELLITE_THEME_DIRS],
             Path("/usr/share/starchaser/wallpapers"),
             HOME / "Pictures/Wallpapers", HOME / "Documents/Starchaser/Wallpapers"]
# "-p2", "-p3", ... after the size: the set's second, third ... picture (a theme can ship several, and
# "wallpaper next" moves through them); no number is the first picture
WALL_RE = re.compile(r"^(?P<set>.+?)(?:-(?P<variant>dark|light))?-(?P<w>\d+)x(?P<h>\d+)(?:-p(?P<pic>\d{1,4}))?\.(png|jpe?g|webp)$", re.I)
PICTURES = HOME / "Pictures/Wallpapers"        # the user's own pictures, used as they are
IMAGE_EXT = {".png", ".jpg", ".jpeg", ".webp"}
THUMBS = Path(os.environ.get("XDG_CACHE_HOME", HOME / ".cache")) / "starchaser/thumbs"

ROLES = ["bg", "bg_alt", "surface", "surface_hi", "selection", "border", "text", "subtext", "muted",
         "accent", "accent2", "accent3", "success", "warning", "error", "info"]


# ---------- colors ----------

def rgb(h: str) -> tuple:
    h = h.lstrip("#")
    return tuple(int(h[i:i + 2], 16) / 255 for i in (0, 2, 4))


def hexc(c: tuple) -> str:
    return "#" + "".join(f"{round(max(0, min(1, x)) * 255):02x}" for x in c)


def mix(a: str, b: str, t: float) -> str:
    """t=0 -> a, t=1 -> b"""
    ra, rb = rgb(a), rgb(b)
    return hexc(tuple(x + (y - x) * t for x, y in zip(ra, rb)))


def bare(h: str) -> str:
    return h.lstrip("#").lower()


# ---------- themes ----------

def theme_files() -> dict:
    found = {}
    # Your ids and the bundled ones (system or checkout) stay reserved even though satellite folders come first.
    reserved = {f.stem for d in THEME_DIRS if d not in SATELLITE_THEME_DIRS
                if d.is_dir() for f in d.glob("*.toml")}
    for d in THEME_DIRS:
        if d.is_dir():
            for f in sorted(d.glob("*.toml")):
                if d in SATELLITE_THEME_DIRS and f.stem in reserved:
                    continue
                found.setdefault(f.stem, f)  # earlier dirs win
    return found


THEME_ERRORS = (tomllib.TOMLDecodeError, OSError, UnicodeDecodeError)


def load_theme(f: Path) -> dict | None:
    """One theme file, parsed; None (named on stderr) when it can't be read. A broken file of your own that has the
    same name as a bundled theme is left out, not swapped for the bundled one: it overrides that theme by name."""
    try:
        return tomllib.loads(f.read_text())
    except THEME_ERRORS as ex:
        print(f"starchaser theme: skipping {f}: {ex}", file=sys.stderr)
        return None


def theme_label(st: dict) -> str:
    """'Starchaser Cockpit (dark), id starchaser-cockpit': the name people see, with the id `apply` takes kept
    visible; just 'id (variant)' when the theme file is gone."""
    f = theme_files().get(st["id"])
    t = load_theme(f) if f else None
    name = t.get("name") if t else None
    if not isinstance(name, str) or not name or name == st["id"]:
        return f"{st['id']} ({st['variant']})"
    return f"{name} ({st['variant']}), id {st['id']}"


HEX_RE = re.compile(r"^#[0-9a-fA-F]{6}\Z")      # \Z, not $: "#123456\n" would end a Lua string early
TERM_KEY_RE = re.compile(r"^color([0-9]|1[0-5])$")


def color_problem(f: Path, variant: str, key: str, value) -> str | None:
    if not isinstance(value, str) or not HEX_RE.match(value):
        return f"{f} [{variant}] {key} = {value!r}: use a color like #1a2b3c"
    return None


def check_color(f: Path, variant: str, key: str, value) -> str:
    err = color_problem(f, variant, key, value)
    if err:
        sys.exit("starchaser theme: " + err)
    return value.lower()


def theme_problem(t: dict, f: Path, variant: str | None = None) -> str | None:
    """Why `apply` would refuse this theme (one variant, or every variant it has), or None. `list` uses the same
    check, so it never offers a theme that apply then turns down."""
    # the name and description go into generated config files (Hyprland's Lua, kitty, the editors' XML) as one
    # comment line: a second line would be read as config, so they must be one line of plain text. A name that is
    # not text (name = 42) would also stop the theme lists sorting, emptying every gallery
    for key in ("name", "short", "description"):
        if key not in t:
            continue
        x = t[key]
        if not isinstance(x, str):
            return f"{f} {key} = {x!r}: put the {key} in quotes, like {key} = \"My theme\""
        if key != "description" and not x.strip():
            return f"{f} {key} is empty: give the theme a {key}"
        if any(ord(ch) < 32 or 0x7f <= ord(ch) < 0xa0 or ch in "  " for ch in x):
            return f"{f} {key} has a line break or a control character in it: keep it to one line"
    vs = [variant] if variant else [v for v in ("dark", "light") if v in t]
    if not vs:
        return f"{f} has no [dark] or [light] palette"
    for v in vs:
        p = t.get(v)
        if not isinstance(p, dict):
            other = [x for x in ("dark", "light") if x != v and isinstance(t.get(x), dict)]
            if variant and other:        # Light mode picked (Quick settings, the menu) for a dark-only theme
                return f"{t.get('name', f.stem)} comes only in a {other[0]} version"
            return f"theme '{f.stem}' has no [{v}] palette"
        missing = [r for r in ROLES if r not in p]
        if missing:
            return f"{f} [{v}] is missing {', '.join(missing)}"
        for r in ROLES:
            err = color_problem(f, v, r, p[r])
            if err:
                return err
        term = p.get("term") or {}
        if not isinstance(term, dict):
            return f"{f} [{v}.term] should be a table of color0 to color15"
        for k, x in term.items():
            if not TERM_KEY_RE.match(str(k)):
                return f"{f} [{v}.term] {k!r}: use color0 to color15"
            err = color_problem(f, f"{v}.term", k, x)
            if err:
                return err
        syn = p.get("syntax") or {}
        if not isinstance(syn, dict):
            return f"{f} [{v}.syntax] should be a table of colors"
        for k, x in syn.items():
            err = color_problem(f, f"{v}.syntax", k, x)
            if err:
                return err
    w = t.get("wallpaper", f.stem)
    if not isinstance(w, str) or not w:
        return f"{f} wallpaper = {w!r}: use the name of a wallpaper set"
    wv = t.get("wallpaper_variant")
    if wv is not None and wv not in ("dark", "light"):
        return f"{f} wallpaper_variant = {wv!r}: use \"dark\" or \"light\" (the one picture for both modes)"
    look = t.get("look", {})
    if not isinstance(look, dict):
        return f"{f} [look] should be a table of window and glass settings"
    for k, x in look.items():
        if k not in LOOK_KEYS:
            return f"{f} [look] {k!r}: use one of {', '.join(LOOK_KEYS)}"
        try:
            coerce(LOOK_KEYS[k], x)
        except ValueError as ex:
            return f"{f} [look] {k} = {x!r}: {ex}"
    return None


def wall_key(t: dict, tid: str) -> str:
    """The theme's wallpaper set, as wall_index() names sets (lowercase)."""
    w = t.get("wallpaper", tid)
    return (w if isinstance(w, str) and w else tid).lower()


def lum(h: str) -> float:
    def ch(x):
        return x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055) ** 2.4
    r, g, b = (ch(x) for x in rgb(h))
    return 0.2126 * r + 0.7152 * g + 0.0722 * b


def contrast(a: str, b: str) -> float:
    la, lb = lum(a), lum(b)
    return (max(la, lb) + 0.05) / (min(la, lb) + 0.05)


def readable(fg: str, toward: str, bgs: list, ratio: float = 4.5) -> str:
    """fg moved toward `toward` in small steps until it reads at `ratio` on every one of bgs (the same idea as the
    cockpit's Theme.hint): muted stays for decoration, this is for small text that has to be read."""
    for i in range(21):
        c = mix(fg, toward, i / 20)
        if all(contrast(c, b) >= ratio for b in bgs):
            return c
    return toward


def resolve(tid: str, variant: str, look: str = "auto", overrides: dict | None = None) -> dict:
    """The theme's palette and the look, with your changes on top (read from theme-overrides.json unless given)."""
    files = theme_files()
    if tid not in files:
        # a long pasted id is refused at once and shortened in the message: the refusal's words are looked over
        # again for the notification (plain_refusal), and walking a huge raw id there made the refusal look frozen
        shown = tid if len(tid) <= 64 else tid[:64] + "…"
        sys.exit(f"starchaser theme: no theme '{shown}' (have: {', '.join(files)})")
    try:
        t = tomllib.loads(files[tid].read_text())
    except THEME_ERRORS as ex:
        sys.exit(f"starchaser theme: {files[tid]} can't be read: {ex}")
    # the variant asked for first (its "comes only in a dark version" message), then the whole theme: `list` hides a
    # theme with any broken palette, so apply turns it down too, even in the mode whose palette is fine
    err = theme_problem(t, files[tid], variant) or theme_problem(t, files[tid])
    if err:
        sys.exit("starchaser theme: " + err)
    p = t[variant]
    own = {r: check_color(files[tid], variant, r, p[r]) for r in ROLES}
    ov = read_overrides() if overrides is None else overrides
    c = {**own, **ov["colors"].get(tid, {}).get(variant, {})}
    if accessibility.read()["high_contrast"]:
        c.update(accessibility.CONTRAST)
    # small text that has to be read (placeholders, inactive tabs, counters): muted lifted to 4.5:1 on the surfaces
    hint = readable(c["muted"], c["text"], [c["surface"], c["bg"]])
    # the role colors where they are text (terminal colors 1-6, code in the editors, links, launcher matches): each
    # moved toward the text color just far enough for 4.5:1 on bg and surface, as hint is for muted. Fills, borders
    # and badges keep the plain role colors. Most light palettes need this (the default's light accent2 was 3.75:1)
    ink = {k: readable(c[k], c["text"], [c["surface"], c["bg"]])
           for k in ("error", "success", "warning", "info", "accent", "accent2", "accent3")}
    dark = variant == "dark"

    # 16 terminal colors: normal from the roles, bright = nudged toward the text side
    # In light mode black and white swap sides, so "white" (7) is the faint one. It is still text (prompts, htop,
    # progress bars print in it): border was about 1.5:1 on the light background, so it moves toward the text color
    # just far enough for 4.5:1, like colors 1-6. Only that far: black words on a white block (30;47, dialog boxes)
    # stay about 2 to 3:1 instead of the 1.6:1 a darker gray would leave. Bright white is the same color, not a darker one:
    # it is a block color too (30;107), and a darker bright white would leave black words on it at 1.4 to 2:1.
    # A theme's own [light.term] colors still win.
    lift = "#ffffff" if dark else "#000000"
    white = c["subtext"] if dark else readable(c["border"], c["text"], [c["surface"], c["bg"]])
    base = [c["surface"] if dark else c["text"], ink["error"], ink["success"], ink["warning"],
            ink["info"], ink["accent"], ink["accent2"], white]
    bright = [mix(c["surface"], c["text"], 0.35) if dark else c["muted"]] + \
             [mix(x, lift, 0.22) for x in base[1:7]] + [c["text"] if dark else white]
    term = base + bright
    for k, v in (p.get("term") or {}).items():
        if not TERM_KEY_RE.match(str(k)):
            sys.exit(f"starchaser theme: {files[tid]} [{variant}.term] {k!r}: use color0 to color15")
        term[int(k[5:])] = check_color(files[tid], f"{variant}.term", k, v)

    # comments in hint, not muted: muted is below 4.5:1 in every theme (3.19:1 in Japan light); line numbers and
    # draw-spaces keep muted
    syntax = {"normal": c["text"], "keyword": ink["accent"], "function": ink["accent2"],
              "string": ink["success"], "number": ink["warning"], "type": ink["accent3"],
              "comment": hint, "operator": ink["info"]}
    syntax.update({k: check_color(files[tid], f"{variant}.syntax", k, v) for k, v in (p.get("syntax") or {}).items()})

    # names the Super+Space menu already understands (no '#'). Written as "palette"; also still under the old British
    # key name for one release. The theme.json readers (cheatsheet.py palette(), keybinds/shell.qml's file watcher)
    # take "palette" first since round 28, and since round 29 cheatsheet.py --json and menu.py --json hand it on as
    # "palette" too (keybinds/shell.qml and cheatsheet.py still fall back to the old key). One release on, drop the
    # old copy here and in the ISO installer theme.json, then those two fallbacks
    colours = {f"term{i}": bare(x) for i, x in enumerate(term)}
    colours.update({"surface": bare(c["bg"]), "onSurface": bare(c["text"]),
                    "onSurfaceVariant": bare(c["subtext"]), "outlineVariant": bare(c["border"]),
                    "primary": bare(c["accent"]), "secondary": bare(c["accent2"]),
                    "tertiary": bare(c["accent3"]), "background": bare(c["bg"])})
    effective_look = resolve_look(look, t.get("look") if isinstance(t.get("look"), dict) else {}, ov["look"], variant)
    if accessibility.read()["high_contrast"]:
        effective_look.update(bar_alpha=1, popup_alpha=1, terminal_alpha=1, blur=False)
    return {"id": tid, "name": t.get("name", tid), "description": t.get("description", ""),
            "wallpaper": wall_key(t, tid), "variant": variant,
            "screensaver": t.get("screensaver") if t.get("screensaver") in SAVER_MODES else "journey",
            "variants": [v for v in ("dark", "light") if v in t],
            "colors": c, "hint": hint, "ink": ink, "term": term, "syntax": syntax, "palette": colours, "colours": colours,
            "theme_colors": own, "pinned_term": sorted(int(k[5:]) for k in (p.get("term") or {})),
            "look": effective_look}


def look_profile(name: str) -> str:
    profile = name
    if name == "auto":
        r = subprocess.run(["systemd-detect-virt", "-q"], capture_output=True) if shutil.which("systemd-detect-virt") else None
        profile = "performance" if r and r.returncode == 0 else "glass-light"
    if profile not in LOOKS:
        sys.exit(f"starchaser theme: no look '{name}' (have: auto, {', '.join(LOOKS)})")
    return profile


def resolve_look(name: str, theme_look: dict | None = None, user: dict | None = None, variant: str = "dark") -> dict:
    """The look preset, then the theme's own [look] values, then your changes (docs/theme-customizer.md, section 1).
    The preset's own keys stay (older readers use them) and carry the resulting values."""
    profile = look_profile(name)
    vals, defaults, sources, dsources = look_values(profile, theme_look or {}, user or {})
    out = {"name": name, "profile": profile, **LOOKS[profile], **look_effective(profile, vals, variant)}
    out.update(values=vals, defaults=defaults, sources=sources, default_sources=dsources,
               changes=[k for k in vals if sources[k] == "yours" and vals[k] != defaults[k]])
    return out


# ---------- your changes: one setting at a time, on top of the theme and the look ----------
# docs/theme-customizer.md. Window and glass changes apply to every theme; color changes belong to one theme and one
# variant. Settings calls these commands and never writes the files itself.

OVERRIDES = CONFIG / "starchaser/theme-overrides.json"
HISTORY = STATE_DIR / "overrides-history.json"
HISTORY_MAX = 20
USER_THEMES = THEME_DIRS[0]
BACKUPS = DATA / "starchaser/theme-backups"
SAVE_MARK = "# made by starchaser-theme save; sha256="
GLOW_ON_RANGE = 16          # glow or shadows turned on in a look that has none (Performance)
BLUR_STRENGTH = {"low": (5, 2), "medium": (8, 3), "high": (10, 4)}       # blur size, passes
CORNER_CUT = {"small": 8, "medium": 14, "large": 20}                     # px; medium is starchaser corners' own
CUT_POWER = 1.484375        # starchaser corners' corner code for "all four corners cut"
RULE_ROUNDING_MAX = 20      # the most a Hyprland window rule's rounding takes


def _see_through(alpha: float) -> float:
    return round((1 - alpha) * 100, 1)


# One table for every setting: type, range or choices, the default in each look, and the words Settings shows.
# `overrides --json` hands it to Settings, so no range or default is written twice. The ranges keep corner cuts
# fitting the frame: with its 18 px cut the window's cut leg is 18 - 0.586 * gap, at least 4 px beyond the border.
SETTINGS = {
    "windows.glow": {"type": "bool", "label": "Glow around the active window", "short": "glow",
                     "default": lambda p: LOOKS[p]["shadow"]},
    "windows.glow_color": {"type": "color", "choices": ["accent", "accent2", "accent3"], "label": "Glow color",
                           "short": "glow color", "default": lambda p: "accent"},
    "windows.glow_strength": {"type": "int", "min": 4, "max": 40, "step": 2, "unit": "px", "label": "Glow strength",
                              "short": "glow strength", "default": lambda p: LOOKS[p]["shadow_range"] or GLOW_ON_RANGE},
    "windows.shadows": {"type": "bool", "label": "Shadows under other windows", "short": "shadows",
                        "default": lambda p: LOOKS[p]["shadow"]},
    "windows.border_width": {"type": "int", "min": 0, "max": 4, "step": 1, "unit": "px", "label": "Window outline thickness",
                             "short": "border width", "default": lambda p: 2},
    "windows.border_active": {"type": "color", "choices": ["gradient", "accent", "accent2", "accent3"],
                              "label": "Active window's border", "short": "active border",
                              "default": lambda p: "accent" if p == "performance" else "gradient"},
    "windows.border_inactive": {"type": "color", "choices": ["border", "surface"], "label": "Other windows' border",
                                "short": "other windows' border", "default": lambda p: "border"},
    "windows.inactive_fade": {"type": "int", "min": 0, "max": 50, "step": 5, "unit": "%",
                              "label": "Fade windows you aren't using", "short": "fade",
                              "default": lambda p: round(_see_through(LOOKS[p]["inactive_opacity"]))},
    "windows.corner_cut": {"type": "choice", "choices": ["small", "medium", "large"],
                           "label": "Corner cut on floating windows", "short": "corner cut",
                           "hint": "Tiled windows stay square.", "default": lambda p: "medium"},
    "windows.gaps_in": {"type": "int", "min": 0, "max": 20, "step": 1, "unit": "px", "label": "Space between windows",
                        "short": "space between windows", "default": lambda p: 5},
    "windows.gaps_out": {"type": "int", "min": 0, "max": 16, "step": 1, "unit": "px", "label": "Space around the edge",
                         "short": "space around the edge", "default": lambda p: 10},
    "glass.blur": {"type": "bool", "label": "Blur behind see-through things", "short": "blur",
                   "default": lambda p: LOOKS[p]["blur"]},
    "glass.blur_strength": {"type": "choice", "choices": ["low", "medium", "high"], "label": "Blur strength",
                            "short": "blur strength", "default": lambda p: "medium" if p == "glass" else "low"},
    "glass.taskbar": {"type": "number", "min": 0, "max": 70, "step": 5, "unit": "%", "label": "See-through taskbar",
                      "short": "see-through taskbar", "default": lambda p: _see_through(LOOKS[p]["bar_alpha"])},
    # 70% solid at the least: below that, text over a busy wallpaper stops being readable (glass decision 2026-10-07)
    "glass.panels": {"type": "number", "min": 0, "max": 30, "step": 5, "unit": "%", "label": "See-through menus and panels",
                     "short": "see-through menus", "default": lambda p: _see_through(LOOKS[p]["popup_alpha"])},
    "glass.terminal": {"type": "number", "min": 0, "max": 40, "step": 5, "unit": "%", "label": "See-through terminal",
                       "short": "see-through terminal", "default": lambda p: _see_through(LOOKS[p]["term_opacity"])},
    "glass.frame_glow": {"type": "bool", "label": "Glow on the taskbar frame", "short": "taskbar glow",
                         "default": lambda p: p != "performance"},
    # set only by Settings' Animation speed row; personal (this computer's speed), so never saved into a theme
    "motion.animations": {"type": "bool", "label": "Animations", "short": "animations", "personal": True,
                          "default": lambda p: LOOKS[p]["animations"]},
}
LOOK_KEYS = {k.split(".", 1)[1]: k for k, s in SETTINGS.items() if not s.get("personal")}   # a theme's [look] names
CHOICE_LABELS = {"accent": "Theme color", "accent2": "Second theme color", "accent3": "Third theme color", "gradient": "Color blend",
                 "border": "Border", "surface": "Surface", "small": "Small", "medium": "Medium", "large": "Large",
                 "low": "Low", "high": "High"}
ROLE_LABELS = {"accent": "Theme color", "accent2": "Second theme color", "accent3": "Third theme color", "bg": "Background",
               "bg_alt": "Side background", "surface": "Cards and fields", "surface_hi": "Hovered cards",
               "selection": "Selected text", "border": "Lines and borders", "text": "Text", "subtext": "Secondary text",
               "muted": "Dim text", "success": "Success", "warning": "Warning", "error": "Error", "info": "Info"}
MAIN_ROLES = ("accent", "bg", "text")


def coerce(key: str, raw):
    """One setting's value, checked and in its stored form; ValueError with a plain message when it isn't allowed.
    Takes the words typed on the command line ("off", "3") and values read from JSON or a theme file alike."""
    if key.startswith("colors."):
        role = key[7:]
        if role not in ROLES:
            raise ValueError(f"there is no color called {role!r} (have: {', '.join(ROLES)})")
        if not isinstance(raw, str) or not HEX_RE.match(raw):
            raise ValueError(f"{ROLE_LABELS[role]} needs a color like #1a2b3c")
        return raw.lower()
    s = SETTINGS.get(key)
    if not s:
        raise ValueError(f"there is no setting called {key!r} (see: starchaser theme overrides)")
    kind, label = s["type"], s["label"]
    if kind == "bool":
        if isinstance(raw, bool):
            return raw
        words = {"on": True, "true": True, "yes": True, "1": True, "off": False, "false": False, "no": False, "0": False}
        if isinstance(raw, str) and raw.lower() in words:
            return words[raw.lower()]
        raise ValueError(f"{label} is on or off")
    if kind in ("int", "number"):
        try:
            if isinstance(raw, bool):
                raise ValueError
            v = float(raw)
        except (TypeError, ValueError):
            v = None
        unit = s.get("unit", "")
        rng = f"{s['min']} to {s['max']}{' px' if unit == 'px' else unit}"
        if v is None or v != v or not s["min"] <= v <= s["max"] or (kind == "int" and v != int(v)):
            raise ValueError(f"{label} goes from {rng}" + (", in whole numbers" if kind == "int" else ""))
        return int(v) if kind == "int" else round(v, 1)
    if isinstance(raw, str) and raw.lower() in s["choices"]:
        return raw.lower()
    if kind == "color" and isinstance(raw, str) and HEX_RE.match(raw):
        return raw.lower()
    names = ", ".join(s["choices"])
    raise ValueError(f"{label} is one of {names}" + (", or a color like #1a2b3c" if kind == "color" else ""))


def look_values(profile: str, theme_look: dict, user: dict) -> tuple:
    """(values, defaults, sources, default_sources) for every setting: your change, else the theme's [look] value,
    else the look's. `defaults` is what the setting goes back to without your change."""
    vals, defaults, sources, dsources = {}, {}, {}, {}
    for k, s in SETTINGS.items():
        short = k.split(".", 1)[1]
        d, src = s["default"](profile), "look"
        if not s.get("personal") and short in theme_look:
            try:
                d, src = coerce(k, theme_look[short]), "theme"
            except ValueError:
                pass                        # theme_problem() names it; apply never gets here with one
        defaults[k], dsources[k] = d, src
        vals[k], sources[k] = (user[k], "yours") if k in user else (d, src)
    return vals, defaults, sources, dsources


def glow_alpha(px: int) -> int:
    """The glow's opacity for its width: the presets' 0x55 from 12 to 24 px, fainter when narrower, stronger when
    wider (0x33 at 4 px, 0x88 at 40 px)."""
    if px <= 12:
        return round(0x33 + (px - 4) / 8 * (0x55 - 0x33))
    if px <= 24:
        return 0x55
    return round(0x55 + (px - 24) / 16 * (0x88 - 0x55))


def term_inactive(profile: str, op: float, variant: str) -> float:
    """Keep Soft Glass readable over wallpaper; other looks retain their background fade (term-focus.py reads it)."""
    if op >= 1.0:
        return 1.0
    if profile == "performance" or (profile == "glass" and variant == "light"):
        return op
    return round(max(op - (0.1 if profile == "clean" else 0.4), 0.45), 3)


def look_effective(profile: str, v: dict, variant: str) -> dict:
    """The values the emitters write, from the settings. The glow is the focused window's shadow tinted with the
    glow color; shadows are the plain dark shadow under the other windows. Either one turns Hyprland's shadow on."""
    glow, shadows = v["windows.glow"], v["windows.shadows"]
    size, passes = BLUR_STRENGTH[v["glass.blur_strength"]]
    term = round(1 - v["glass.terminal"] / 100, 3)
    return {"shadow": glow or shadows,
            "shadow_range": v["windows.glow_strength"] if glow else (LOOKS[profile]["shadow_range"] or GLOW_ON_RANGE),
            "glow": glow, "glow_color": v["windows.glow_color"], "glow_alpha": glow_alpha(v["windows.glow_strength"]),
            "shadows": shadows, "border_size": v["windows.border_width"],
            "border_active": v["windows.border_active"], "border_inactive": v["windows.border_inactive"],
            "inactive_opacity": round(1 - v["windows.inactive_fade"] / 100, 2),
            "corner_cut": CORNER_CUT[v["windows.corner_cut"]], "gaps_in": v["windows.gaps_in"],
            "gaps_out": v["windows.gaps_out"], "blur": v["glass.blur"], "blur_size": size, "blur_passes": passes,
            "bar_alpha": round(1 - v["glass.taskbar"] / 100, 3), "popup_alpha": round(1 - v["glass.panels"] / 100, 3),
            "term_opacity": term, "term_inactive_opacity": term_inactive(profile, term, variant),
            "frame_glow": v["glass.frame_glow"], "animations": v["motion.animations"]}


def empty_overrides() -> dict:
    return {"version": 1, "revision": 0, "look": {}, "colors": {}}


_BROKEN_OVERRIDES = ""          # the set-aside name when the changes file couldn't be read (named by `overrides`)


def set_aside_broken() -> str:
    """A changes file that can't be read is kept under a new name (never over an earlier one) and the person told;
    it is never silently replaced."""
    global _BROKEN_OVERRIDES
    stamp = time.strftime("%Y%m%d-%H%M%S")
    for i in range(1, 1000):
        dest = OVERRIDES.with_name(f"theme-overrides.{stamp}{'' if i == 1 else f'-{i}'}.broken.json")
        try:
            os.link(OVERRIDES, dest)        # fails if dest exists: an earlier copy is never overwritten
        except FileExistsError:
            continue
        except OSError:
            return ""
        try:
            OVERRIDES.unlink()
        except OSError:
            pass
        _BROKEN_OVERRIDES = dest.name
        notify("Your appearance changes were set aside", f"The file that keeps them couldn't be read, so it was kept as "
               f"{dest.name} and the theme's own look is in use.")
        return dest.name
    return ""


def read_overrides() -> dict:
    """Your changes; values that are no longer allowed (a file edited by hand) are left out and named on stderr."""
    try:
        d = json.loads(OVERRIDES.read_text())
        if not isinstance(d, dict) or not isinstance(d.get("look", {}), dict) or not isinstance(d.get("colors", {}), dict):
            raise ValueError("not a table of changes")
    except FileNotFoundError:
        return empty_overrides()
    except (OSError, ValueError, UnicodeDecodeError):
        set_aside_broken()
        return empty_overrides()
    out = empty_overrides()
    out["revision"] = d.get("revision", 0) if isinstance(d.get("revision"), int) else 0
    for k, v in d.get("look", {}).items():
        try:
            out["look"][k] = coerce(k, v)
        except ValueError as ex:
            print(f"starchaser theme: ignoring your change to {k}: {ex}", file=sys.stderr)
    for tid, vs in d.get("colors", {}).items():
        for variant, roles in (vs.items() if isinstance(vs, dict) else ()):
            if variant not in ("dark", "light") or not isinstance(roles, dict):
                continue
            for role, v in roles.items():
                try:
                    out["colors"].setdefault(tid, {}).setdefault(variant, {})[role] = coerce("colors." + role, v)
                except ValueError as ex:
                    print(f"starchaser theme: ignoring your {tid} {variant} color {role}: {ex}", file=sys.stderr)
    return out


def write_overrides(ov: dict) -> int:
    ov["revision"] = ov.get("revision", 0) + 1
    ov["colors"] = {t: {v: r for v, r in vs.items() if r} for t, vs in ov["colors"].items()}
    ov["colors"] = {t: vs for t, vs in ov["colors"].items() if vs}
    write(OVERRIDES, json.dumps(ov, indent=2, sort_keys=True) + "\n")
    return ov["revision"]


def read_history() -> list:
    try:
        h = json.loads(HISTORY.read_text())
        return [e for e in h if isinstance(e, dict) and isinstance(e.get("overrides"), dict)] if isinstance(h, list) else []
    except (OSError, ValueError):
        return []


def push_history(label: str, ov: dict, st: dict | None = None, file: dict | None = None, made: str | None = None) -> None:
    """One Undo step. st: only for a save, whose undo goes back to the theme it was made from (a change made before
    a theme switch never switches back). file: {path, text, sha} for an update, whose undo puts the file's old text
    back while the file is still the one written then."""
    h = read_history()
    h.append({"label": label, "overrides": json.loads(json.dumps(ov)),
              "theme": [st["id"], st["variant"]] if has_theme(st) else None, "file": file, "made": made})
    write(HISTORY, json.dumps(h[-HISTORY_MAX:], indent=1) + "\n")


def describe_name(key: str) -> str:
    """What a setting is called in Undo text, sentence case ("Glow color")."""
    n = ROLE_LABELS[key[7:]] if key.startswith("colors.") else SETTINGS[key]["short"]
    return n[:1].upper() + n[1:]


def describe(key: str, value) -> str:
    """A change in a few words, for the Undo button ("Glow off", "Border width 3 px", "Glow color set to Accent 2")."""
    name = describe_name(key)
    if key.startswith("colors."):
        return f"{name} {value}"
    s = SETTINGS[key]
    if s["type"] == "bool":
        return f"{name} {'on' if value else 'off'}"
    if s["type"] in ("int", "number"):
        n = int(value) if float(value).is_integer() else value
        return f"{name} {n}{' px' if s.get('unit') == 'px' else s.get('unit', '')}"
    return f"{name} set to {CHOICE_LABELS.get(value, value)}"


def active_theme(st: dict | None) -> tuple:
    """(theme id, variant, look name) in use, or the first-boot default."""
    look = st["look"]["name"] if st and isinstance(st.get("look"), dict) else "auto"
    return (st["id"], st["variant"], look) if has_theme(st) else (DEFAULT_THEME, "dark", look)


def bad(msg: str, code: int = 2) -> None:
    """A refused change: the reason in plain words on stderr, nothing written."""
    print("starchaser theme: " + msg, file=sys.stderr)
    sys.exit(code)


def emitters_for(keys) -> list:
    """Only what a change touches, so a slider doesn't make every app flash (docs/theme-customizer.md, section 4)."""
    picked = {e_state}
    for k in keys:
        if k.startswith("colors."):
            return [e for e in EMITTERS if e is not e_wallpaper]
        if k == "glass.terminal":
            picked.add(e_kitty)
        elif k not in ("glass.taskbar", "glass.panels", "glass.frame_glow"):
            picked.add(e_look)
    return [e for e in EMITTERS if e in picked]


def apply_changes(keys) -> None:
    keys = list(keys)
    if not keys:
        return
    tid, variant, look = active_theme(read_state())
    th = resolve(tid, variant, look)
    run_emitters(th, emitters_for(keys))
    if "glass.terminal" in keys:
        signal_term_focus()


def changed_keys(a: dict, b: dict, tid: str, variant: str) -> list:
    """The settings two sets of changes disagree on, for the theme in use."""
    keys = [k for k in set(a["look"]) | set(b["look"]) if a["look"].get(k) != b["look"].get(k)]
    ca, cb = a["colors"].get(tid, {}).get(variant, {}), b["colors"].get(tid, {}).get(variant, {})
    keys += ["colors." + r for r in set(ca) | set(cb) if ca.get(r) != cb.get(r)]
    return keys


def for_target(argv: list) -> tuple | None:
    """`--for <theme>:<variant>`, or None."""
    if "--for" not in argv:
        return None
    i = argv.index("--for")
    if i + 1 >= len(argv) or ":" not in argv[i + 1]:
        usage("Usage: --for <theme>:<dark|light>")
    tid, _, variant = argv[i + 1].rpartition(":")
    del argv[i:i + 2]
    return tid, variant


def check_target(want: tuple | None, tid: str, variant: str) -> None:
    """A change Settings sent for one theme must not land on another: the person may have switched theme or
    Dark/Light while it waited. Exit 3, nothing written."""
    if want and want != (tid, variant):
        bad("the theme or Dark/Light changed before this was saved, so nothing was changed", 3)


def cmd_set(argv: list, unset: bool = False) -> None:
    want = for_target(argv)
    if len(argv) != (1 if unset else 2):
        usage("Usage: starchaser theme unset <key> [--for <theme>:<variant>]" if unset
              else "Usage: starchaser theme set <key> <value> [--for <theme>:<variant>]")
    key = argv[0]
    st = read_state()
    tid, variant, _ = active_theme(st)
    try:
        if unset and not (key in SETTINGS or key.startswith("colors.") and key[7:] in ROLES):
            coerce(key, None)                   # raises the "no such setting" message
        value = None if unset else coerce(key, argv[1])
    except ValueError as ex:
        bad(str(ex))
    ov = read_overrides()
    if key.startswith("colors."):
        check_target(want, tid, variant)
        store, field = ov["colors"].setdefault(tid, {}).setdefault(variant, {}), key[7:]
    else:
        store, field = ov["look"], key
    if (field not in store) if unset else (store.get(field) == value):
        print(json.dumps({"ok": True, "revision": ov["revision"], "changed": False}))
        return
    if key == "motion.animations":
        label = "Animation setting"  # Choosing Off can remove the override without being a reset.
    else:
        label = ("Reset " + describe_name(key).lower()) if unset else describe(key, value)
        if key.startswith("colors."):           # Undo can run while another theme is on screen: say whose color it is
            label += f" in {theme_short(tid)} ({variant})"
    push_history(label, ov)
    if unset:
        del store[field]
    else:
        store[field] = value
    rev = write_overrides(ov)
    apply_changes([key])
    print(json.dumps({"ok": True, "revision": rev, "changed": True}))


def cmd_reset(argv: list) -> None:
    want = for_target(argv)
    if len(argv) != 1 or argv[0] not in ("colors", "look"):
        usage("Usage: starchaser theme reset colors|look")
    st = read_state()
    tid, variant, _look = active_theme(st)
    ov = read_overrides()
    before = json.loads(json.dumps(ov))
    if argv[0] == "colors":
        check_target(want, tid, variant)
        if not ov["colors"].get(tid, {}).get(variant):
            print(json.dumps({"ok": True, "revision": ov["revision"], "changed": False}))
            return
        short = theme_short(tid)
        label = f"Reset {short}'s {variant} colors"
        ov["colors"][tid].pop(variant)
    else:
        keys = [k for k in ov["look"] if not SETTINGS[k].get("personal")]   # Reset never touches motion
        if not keys:
            print(json.dumps({"ok": True, "revision": ov["revision"], "changed": False}))
            return
        label = "Reset window and glass changes"
        for k in keys:
            del ov["look"][k]
    push_history(label, before)
    rev = write_overrides(ov)
    apply_changes(changed_keys(before, ov, tid, variant))
    print(json.dumps({"ok": True, "revision": rev, "changed": True}))


def undo_file(info) -> bool:
    """Undoing an update: the theme file's text from before it, but only while the file is still exactly what the
    update wrote (edited, renamed or deleted since: left as it is, and said so)."""
    if not isinstance(info, dict) or not all(isinstance(info.get(k), str) for k in ("path", "text", "sha")):
        return False
    f = Path(info["path"])
    try:
        ok = f.parent == USER_THEMES and not f.is_symlink() and \
            hashlib.sha256(f.read_text().encode()).hexdigest() == info["sha"]
    except (OSError, UnicodeDecodeError):
        ok = False
    if not ok:
        print(f"starchaser theme: {f.name} changed since it was updated, so its file is left as it is", file=sys.stderr)
        return False
    backup_theme(f, f.stem)
    write(f, info["text"])
    return True


def cmd_undo() -> None:
    h = read_history()
    if not h:
        bad("there is nothing to undo", 1)
    entry = h.pop()
    st = read_state()
    tid, variant, look = active_theme(st)
    now = read_overrides()
    back = empty_overrides()
    for k, v in entry["overrides"].get("look", {}).items():
        if k in SETTINGS:
            back["look"][k] = v
    back["colors"] = entry["overrides"].get("colors", {}) if isinstance(entry["overrides"].get("colors"), dict) else {}
    back["revision"] = now["revision"]
    restored = undo_file(entry.get("file"))
    rev = write_overrides(back)
    write(HISTORY, json.dumps(h, indent=1) + "\n")
    if restored:
        run_emitters(resolve(tid, variant, look), [e_state])     # the theme's own colors changed back
    was = entry.get("theme")
    if was and tuple(was) != (tid, variant) and was[0] in theme_files():
        apply(was[0], was[1])               # undoing a save: back to the theme it was made from
    else:
        apply_changes(changed_keys(now, back, tid, variant))
    print(json.dumps({"ok": True, "revision": rev, "undid": entry.get("label", "")}))


# ---------- contrast: warnings, never refusals ----------

def contrast_warnings(th: dict) -> list:
    """Pairs that will be hard to read with these colors (WCAG AA: 4.5:1 for text). One warning per color, the worst
    pair."""
    c, ink = th["colors"], th["ink"]
    found = {}

    def check(key, other, fg, bgc, needs, text):
        r = contrast(fg, bgc)
        if r < needs and (key not in found or r < found[key]["ratio"]):
            found[key] = {"key": key, "with": other, "ratio": round(r, 2), "needs": needs,
                          "text": text.format(r=f"{r:.1f}", n=f"{needs:g}")}
    for b in ("bg", "surface", "surface_hi", "selection"):
        check("colors.text", "colors." + b, c["text"], c[b], 4.5,
              "Text on " + ROLE_LABELS[b].lower() + " is hard to read. Pick a lighter or darker Text color.")
    for b in ("bg", "surface"):
        check("colors.subtext", "colors." + b, c["subtext"], c[b], 4.5,
              "Secondary text on " + ROLE_LABELS[b].lower() + " is hard to read.")
    check("colors.accent", "colors.bg", c["bg"], c["accent"], 4.5, "Words on accent-colored buttons are hard to read.")
    for k, x in ink.items():
        worst = min((c["bg"], c["surface"]), key=lambda b: contrast(x, b))
        if "colors." + k not in found:
            check("colors." + k, "colors.bg", x, worst, 4.5, "Links and highlights in this color are hard to read.")
    # lines are quiet on purpose (every bundled theme is under WCAG's 3:1), so only nearly invisible ones warn
    check("colors.border", "colors.bg", c["border"], c["bg"], 1.25, "Borders will be very hard to see.")
    for i in sorted(th.get("pinned_term", [])):
        check(f"term.color{i}", "colors.bg", th["term"][i], c["bg"], 4.5,
              f"This theme's own terminal color {i} is hard to read on the background.")
    return list(found.values())


def corners_status() -> str:
    """"on", or "off" when starchaser corners found shaders that don't match this Hyprland (every corner square)."""
    try:
        return "off" if json.loads((STATE_DIR / "corners.json").read_text()).get("corners") == "off" else "on"
    except (OSError, ValueError, AttributeError):
        return "on"


# ---------- themes of your own ----------

def is_mine(f: Path) -> bool:
    return f.parent == USER_THEMES


def save_hash_ok(f: Path) -> bool:
    try:
        first, _, rest = f.read_text().partition("\n")
    except (OSError, UnicodeDecodeError):
        return False
    return first.startswith(SAVE_MARK) and first[len(SAVE_MARK):].strip() == hashlib.sha256(rest.encode()).hexdigest()


def editable(f: Path) -> bool:
    """Made by `save`, unedited since, a plain file in your themes folder: the only kind Update and Rename rewrite."""
    try:
        inside = f.resolve().parent == USER_THEMES.resolve()
    except OSError:
        return False
    return is_mine(f) and not f.is_symlink() and inside and save_hash_ok(f)


def theme_short(tid: str) -> str:
    f = theme_files().get(tid)
    t = load_theme(f) if f else None
    return (t.get("short") or t.get("name") or tid) if t else tid


def toml_str(s: str) -> str:
    return json.dumps(s, ensure_ascii=False)       # a JSON string is a valid TOML basic string


def toml_val(v) -> str:
    return ("true" if v else "false") if isinstance(v, bool) else repr(v) if isinstance(v, (int, float)) else toml_str(v)


def theme_toml(t: dict) -> str:
    lines = [f"{k} = {toml_str(t[k])}" for k in ("name", "short", "description", "wallpaper", "screensaver", "based_on") if k in t]
    if t.get("look"):
        lines += ["", "[look]"] + [f"{k} = {toml_val(v)}" for k, v in t["look"].items()]
    for v in ("dark", "light"):
        if v not in t:
            continue
        lines += ["", f"[{v}]"] + [f"{r:<10} = {toml_str(t[v][r])}" for r in ROLES]
        for sub in ("term", "syntax"):
            if t[v].get(sub):
                lines += ["", f"[{v}.{sub}]"] + [
                    f"{k if re.match(r'^[A-Za-z0-9_-]+$', k) else toml_str(k)} = {toml_str(x)}" for k, x in t[v][sub].items()]
    body = "\n".join(lines) + "\n"
    return SAVE_MARK + hashlib.sha256(body.encode()).hexdigest() + "\n" + body


def check_name(name: str) -> str:
    name = name.strip()
    if not name:
        bad("give the theme a name")
    if len(name) > 40:
        bad("keep the name to 40 characters or fewer")
    if any(ord(ch) < 32 or 0x7f <= ord(ch) < 0xa0 or ch in "  " for ch in name):
        bad("keep the name to one line of plain text")
    return name


def plain_slug(name: str) -> str:
    """The id a name asks for ("Night Shift" -> night-shift) before slug_for's never-reuse bump; the same fold, so
    Save can refuse a name whose plain id is taken instead of quietly making a second theme under another id."""
    folded = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
    return re.sub(r"[^a-z0-9]+", "-", folded.lower()).strip("-")[:32].strip("-") or "theme"


def name_taken(name: str) -> bool:
    """True when a theme already goes by this name (any theme's name field, any capitalization), or the plain id the
    name asks for is already a theme or a file of yours: one name points at one theme, so a save can't make a second
    one people can't tell apart (or hide a bundled theme by overriding its file)."""
    want = name.casefold()
    for f in theme_files().values():
        t = load_theme(f)
        if t is not None and isinstance(t.get("name"), str) and t["name"].casefold() == want:
            return True
    base = plain_slug(name)
    return base in theme_files() or (USER_THEMES / f"{base}.toml").exists() or (USER_THEMES / f"{base}.toml").is_symlink()


def slug_for(name: str) -> str:
    """The new theme's id from its name ("Night Shift" -> night-shift), never one that is taken: reusing a bundled
    id would hide that theme (a file of yours overrides one by name). Accents fold away (Café -> cafe); a name with
    no letters or numbers gets 'theme' (numbered when another name asked for that too)."""
    folded = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
    base = re.sub(r"[^a-z0-9]+", "-", folded.lower()).strip("-")[:32].strip("-") or "theme"
    taken = set(theme_files())
    slug, n = base, 2
    while slug in taken or (USER_THEMES / f"{slug}.toml").exists() or (USER_THEMES / f"{slug}.toml").is_symlink():
        slug, n = f"{base}-{n}", n + 1
    return slug


def backup_theme(f: Path, tid: str) -> None:
    """A copy before every rewrite; the last 10 per theme are kept."""
    BACKUPS.mkdir(parents=True, exist_ok=True)
    stamp = time.strftime("%Y%m%d-%H%M%S")
    dest, n = BACKUPS / f"{tid}-{stamp}.toml", 2
    while dest.exists():
        dest, n = BACKUPS / f"{tid}-{stamp}-{n}.toml", n + 1
    shutil.copy2(f, dest)
    for old in sorted(BACKUPS.glob(f"{glob_escape(tid)}-*.toml"), key=lambda p: p.stat().st_mtime)[:-10]:
        old.unlink(missing_ok=True)


def glob_escape(s: str) -> str:
    return re.sub(r"([*?\[])", r"[\1]", s)


def own_theme(tid: str, verb: str) -> tuple:
    """(file, parsed theme) for Update or Rename, or a plain refusal."""
    f = theme_files().get(tid)
    if not f:
        bad(f"there is no theme called {tid!r}", 1)
    if not is_mine(f):
        bad(f"themes that come with Starchaser can't be {verb}. Use Save as my theme to make your own copy", 1)
    if f.is_symlink() or f.resolve().parent != USER_THEMES.resolve():
        bad("this theme's file is a link to a file somewhere else, so it is left as it is", 1)
    if not save_hash_ok(f):
        bad("this theme's file was edited by hand, so it is left as it is. Save your changes as a new theme instead", 1)
    t = load_theme(f)
    if t is None:
        bad("this theme's file can't be read", 1)
    return f, t


def bake_colors(t: dict, colors: dict) -> dict:
    """The theme with your color changes written into its palettes."""
    t = json.loads(json.dumps(t))
    for v, roles in colors.items():
        if isinstance(t.get(v), dict):
            t[v].update(roles)
    return t


def current_theme_table(name: str, tid: str, base: dict, ov: dict) -> dict:
    """What you see as one theme table: the theme `tid` with your color changes for it baked in, its [look] with your
    window and glass changes on top (the personal ones left out), its wallpaper set and screensaver. Save writes it as
    a theme of yours; export writes it into a theme add-on folder to share."""
    new = bake_colors({k: base[k] for k in ("dark", "light") if isinstance(base.get(k), dict)}, ov["colors"].get(tid, {}))
    look_tbl = dict(base.get("look") or {})
    look_tbl.update({k.split(".", 1)[1]: v for k, v in ov["look"].items() if not SETTINGS[k].get("personal")})
    return {"name": name, "short": name, "description": f"Your own theme, made from {base.get('name', tid)}.",
            "wallpaper": wall_key(base, tid),
            **({"screensaver": base["screensaver"]} if base.get("screensaver") in SAVER_MODES else {}),
            "based_on": tid, **({"look": look_tbl} if look_tbl else {}), **new}


def cmd_save(argv: list) -> None:
    if argv[:1] == ["--update"]:
        return cmd_save_update(argv[1:])
    if len(argv) != 1:
        usage("Usage: starchaser theme save <name> | save --update <id>")
    name = check_name(argv[0])
    st = read_state()
    tid, variant, look = active_theme(st)
    base_f = theme_files().get(tid)
    base = load_theme(base_f) if base_f else None
    if name_taken(name):
        # save --update writes over the theme in use: offer it only when that theme is the one carrying this name
        # (its name field, any capitalization), so a clash with another theme never points at the wrong theme
        if base is not None and isinstance(base.get("name"), str) and base["name"].casefold() == name.casefold():
            bad(f"a theme called {name} already exists. Choose another name, or save over the one in use with "
                f"starchaser theme save --update {tid}.", 1)
        bad(f"a theme called {name} already exists. Choose another name.", 1)
    if base is None:
        bad("the theme in use can't be read, so it can't be saved as a new one", 1)
    ov = read_overrides()
    snapshot = json.loads(json.dumps(ov))
    new = current_theme_table(name, tid, base, ov)
    slug = slug_for(name)
    path = USER_THEMES / f"{slug}.toml"
    text = theme_toml(new)
    err = theme_problem(tomllib.loads(text), path)
    if err:
        bad(err, 1)
    write(path, text)
    push_history(f"Save {name}", snapshot, st, made=slug)
    ov["colors"].pop(tid, None)           # they live in the new theme now; window and glass changes stay (global)
    write_overrides(ov)
    try:
        th = resolve(slug, variant if variant in new else theme_variant(slug, variant), look)
    except SystemExit:
        # the new theme was refused: everything is put back as it was
        snapshot["revision"] = ov["revision"]
        write_overrides(snapshot)
        write(HISTORY, json.dumps(read_history()[:-1], indent=1) + "\n")
        path.unlink(missing_ok=True)
        raise
    print(f"{th['name']} ({th['variant']}), saved as {path}", file=LINES[0])
    same_wall = wall_key(base, tid) == th["wallpaper"]
    run_emitters(th, [e for e in EMITTERS if not (same_wall and e is e_wallpaper)])
    print(json.dumps({"ok": True, "id": slug, "file": str(path)}))


def cmd_save_update(argv: list) -> None:
    if len(argv) != 1:
        usage("Usage: starchaser theme save --update <id>")
    tid = argv[0]
    st = read_state()
    active, variant, look = active_theme(st)
    f, t = own_theme(tid, "updated")
    if active != tid:
        bad("only the theme in use can be updated with its color changes", 1)
    ov = read_overrides()
    colors = ov["colors"].get(tid)
    if not colors:
        bad("there are no color changes for this theme to save", 1)
    new = bake_colors(t, colors)
    text = theme_toml(new)
    err = theme_problem(tomllib.loads(text), f)
    if err:
        bad(err, 1)
    old = f.read_text()
    backup_theme(f, tid)
    write(f, text)
    push_history(f"Update {t.get('name', tid)}", ov,
                 file={"path": str(f), "text": old, "sha": hashlib.sha256(text.encode()).hexdigest()})
    ov["colors"].pop(tid)
    rev = write_overrides(ov)
    run_emitters(resolve(tid, variant, look), [e_state])     # the result on screen is the same; the sources change
    print(json.dumps({"ok": True, "id": tid, "revision": rev}))


# ---------- export: your look as a theme folder to share (starchaser satellite new --theme) ----------

EXPORT_ID_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*\Z")      # a satellite id: the theme id inside a theme add-on
# wallpaper sets that come with Starchaser: everyone has them, so an exported theme names the set and copies nothing
BUNDLED_WALLS = [Path("/usr/share/starchaser/wallpapers"), Path(__file__).resolve().parent.parent / "share/wallpapers"]


def image_size(f: Path) -> tuple | None:
    """(width, height) of a PNG, JPEG or WebP picture from its header (no image library), or None."""
    try:
        with open(f, "rb") as fh:
            head = fh.read(32)
            if head[:8] == b"\x89PNG\r\n\x1a\n" and head[12:16] == b"IHDR":
                return int.from_bytes(head[16:20], "big"), int.from_bytes(head[20:24], "big")
            if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
                chunk = head[12:16]
                if chunk == b"VP8 " and head[23:26] == b"\x9d\x01\x2a":
                    return int.from_bytes(head[26:28], "little") & 0x3FFF, int.from_bytes(head[28:30], "little") & 0x3FFF
                if chunk == b"VP8L" and head[20:21] == b"\x2f":
                    bits = int.from_bytes(head[21:25], "little")
                    return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
                if chunk == b"VP8X":
                    return int.from_bytes(head[24:27], "little") + 1, int.from_bytes(head[27:30], "little") + 1
                return None
            if head[:2] == b"\xff\xd8":
                fh.seek(2)
                for _ in range(10000):
                    b = fh.read(1)
                    while b and b != b"\xff":
                        b = fh.read(1)
                    while b == b"\xff":
                        b = fh.read(1)
                    if not b:
                        return None
                    marker = b[0]
                    if marker in (0xD8, 0x01) or 0xD0 <= marker <= 0xD7:
                        continue
                    if marker == 0xD9:
                        return None
                    seg = fh.read(2)
                    if len(seg) < 2:
                        return None
                    n = int.from_bytes(seg, "big")
                    if 0xC0 <= marker <= 0xCF and marker not in (0xC4, 0xC8, 0xCC):
                        body = fh.read(5)
                        if len(body) < 5:
                            return None
                        h, w = int.from_bytes(body[1:3], "big"), int.from_bytes(body[3:5], "big")
                        return (w, h) if w and h else None
                    fh.seek(n - 2, os.SEEK_CUR)
    except OSError:
        return None
    return None


def is_bundled_picture(f: Path) -> bool:
    real = f.resolve()
    return any(real.is_relative_to(d.resolve()) for d in BUNDLED_WALLS if d.is_dir())


class ExportRefused(Exception):
    """One plain sentence why export can't make the theme."""


def export_wallpaper(st: dict | None, base: dict, tid: str, out: Path, sid: str, from_current: bool) -> tuple:
    """(wallpaper set, wallpaper_variant or None, [(source, target)]) for the exported theme: a set that ships with
    Starchaser is named (nothing to copy); your own picture or a set of yours is copied as <sid>-<variant>-<W>x<H>."""
    one = one_picture_sets()
    theme_set = wall_key(base, tid)
    theme_wv = base.get("wallpaper_variant") if base.get("wallpaper_variant") in ("dark", "light") else None
    if not from_current:
        return theme_set, theme_wv, []
    st = st or {}
    now = st.get("wallpaper_now") if isinstance(st.get("wallpaper_now"), dict) else {}
    own = st.get("wallpaper_mode") == "own"
    walls = out / "wallpapers"
    if own and isinstance(now.get("picture"), str) and Path(now["picture"]).is_file():
        pic = Path(now["picture"])
        size = image_size(pic)
        if not size:
            raise ExportRefused("Your wallpaper picture can't be read, so it can't be shared. "
                                "Pick another picture, or Match the theme, and try again.")
        ext = pic.suffix.lower() if pic.suffix.lower() in IMAGE_EXT else ".png"
        return sid, "dark", [(pic, walls / f"{sid}-dark-{size[0]}x{size[1]}{ext}")]
    idx = wall_index()
    ws = now["set"] if own and isinstance(now.get("set"), str) and now["set"] in idx else theme_set
    files = idx.get(ws, {})
    wv = one.get(ws) or (theme_wv if ws == theme_set else None)
    if not files or all(is_bundled_picture(f) for v in files.values() for _, _, f in v):
        return ws, wv, []
    variants = {v: files[v] for v in ("dark", "light") if files.get(v)}
    if len(variants) == 2 and [f for *_, f in variants["dark"]] == [f for *_, f in variants["light"]]:
        variants = {"dark": variants["dark"]}       # a one-picture set lists the same pictures under both
    copies, names = [], set()
    for v, rows in variants.items():
        best = {}                                    # the largest picture of each shape is enough to share
        for w, h, f in wall_pictures(rows)[0]:       # the set's first picture (wallpaper next shows the others)
            size = image_size(f) or (w, h)
            shape = round(size[0] / max(1, size[1]), 2)
            if shape not in best or size[0] * size[1] > best[shape][0][0] * best[shape][0][1]:
                best[shape] = (size, f)
        for size, f in best.values():
            ext = f.suffix.lower() if f.suffix.lower() in IMAGE_EXT else ".png"
            name = f"{sid}-{'dark' if len(variants) == 1 else v}-{size[0]}x{size[1]}{ext}"
            if name not in names:
                names.add(name)
                copies.append((f, walls / name))
    return sid, ("dark" if len(variants) == 1 else None), copies


def cmd_export(argv: list) -> None:
    """export --dir DIR --id ID --name NAME [--from-current] [--json]: the theme in DIR/<ID>.toml (pictures in
    DIR/wallpapers), for a theme add-on. Your themes, history and changes are left as they are."""
    as_json = "--json" in argv

    def fail(msg: str, code: int = 1) -> None:
        if as_json:
            print(json.dumps({"ok": False, "errors": msg}))
        print("starchaser theme: " + msg, file=sys.stderr)
        sys.exit(code)

    opts, rest, flags = {}, list(argv), set()
    while rest:
        a = rest.pop(0)
        if a in ("--dir", "--id", "--name") and rest:
            opts[a[2:]] = rest.pop(0)
        elif a in ("--from-current", "--json"):
            flags.add(a)
        else:
            fail("Use: starchaser theme export --dir DIR --id ID --name NAME [--from-current] [--json]", 2)
    if set(opts) != {"dir", "id", "name"}:
        fail("Use: starchaser theme export --dir DIR --id ID --name NAME [--from-current] [--json]", 2)
    sid, name = opts["id"], opts["name"].strip()
    if not EXPORT_ID_RE.fullmatch(sid) or len(sid) > 80:
        fail("Use a theme id with lowercase letters, digits, and dashes.")
    if not name or len(name) > 40:
        fail("Give the theme a name of 40 characters or fewer.")
    if any(ord(ch) < 32 or 0x7f <= ord(ch) < 0xa0 or ch in "  " for ch in name):
        fail("Keep the theme name to one line of plain text.")
    # a bundled theme or one of yours with this id would hide the shared one (theme_files() lets them win)
    own_dirs = [d for d in THEME_DIRS if d not in SATELLITE_THEME_DIRS and d.is_dir()]
    if any((d / f"{sid}.toml").exists() for d in own_dirs):
        fail("A theme with this name is already here. Choose another name.")
    for d in own_dirs:
        for f in d.glob("*.toml"):
            t = load_theme(f)
            if t is not None and isinstance(t.get("name"), str) and t["name"].casefold() == name.casefold():
                fail("A theme with this name is already here. Choose another name.")
    from_current = "--from-current" in flags
    st = read_state()
    if from_current:
        tid, variant, _ = active_theme(st)
        ov = read_overrides()
    else:
        tid, variant, ov = DEFAULT_THEME, "dark", empty_overrides()
    base_f = theme_files().get(tid)
    base = load_theme(base_f) if base_f else None
    if base is None:
        fail("The theme in use can't be read, so it can't be shared.")
    table = current_theme_table(name, tid, base, ov)
    table.pop("based_on", None)          # the theme it came from may be only on this computer
    table["description"] = (f"Made from {base.get('name', tid)} with your own changes." if from_current
                            else f"A start made from {base.get('name', tid)}.")
    if variant not in table:
        fail(f"The theme in use has no {variant} version, so it can't be shared.")
    out = Path(opts["dir"]).expanduser()
    try:
        wset, wv, copies = export_wallpaper(st, base, tid, out, sid, from_current)
    except ExportRefused as ex:
        fail(str(ex))
    table["wallpaper"] = wset
    body = theme_toml(table).split("\n", 1)[1]           # not save's mark: this file is not a theme of yours
    if wv:
        body = body.replace(f"wallpaper = {toml_str(wset)}\n", f"wallpaper = {toml_str(wset)}\nwallpaper_variant = {toml_str(wv)}\n", 1)
    text = (f"# Made by starchaser theme export from your look ({variant} mode was in use)." if from_current
            else "# Made by starchaser theme export.") + " Roles: see themes/README.md.\n" + body
    target = out / f"{sid}.toml"
    try:
        err = theme_problem(tomllib.loads(text), target)
    except tomllib.TOMLDecodeError as ex:
        err = str(ex)
    if err:
        fail(err)
    try:
        out.mkdir(parents=True, exist_ok=True)
        walls = out / "wallpapers"
        if walls.is_dir():                     # pictures an earlier export of this theme left
            for old in walls.iterdir():
                m = WALL_RE.match(old.name)
                if m and m["set"].lower() == sid and (old.is_file() or old.is_symlink()):
                    old.unlink()
        made = []
        for src, dst in copies:
            dst.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(src, dst)
            made.append(str(dst))
        tmp = target.with_name(f".{target.name}.{os.getpid()}.tmp")
        tmp.write_text(text)
        os.replace(tmp, target)
    except OSError as ex:
        fail(f"The theme couldn't be written to {out} ({ex.strerror or ex}).")
    if as_json:
        print(json.dumps({"ok": True, "id": sid, "file": str(target), "wallpapers": made, "variant": variant}))
    else:
        print(f"Wrote {name} to {target}" + (f" with {len(made)} wallpaper picture{'s' if len(made) != 1 else ''}." if made else "."))


def cmd_rename(argv: list) -> None:
    if len(argv) != 2:
        usage("Usage: starchaser theme rename <id> <name>")
    tid, name = argv[0], check_name(argv[1])
    f, t = own_theme(tid, "renamed")
    t["name"] = t["short"] = name
    text = theme_toml(t)
    err = theme_problem(tomllib.loads(text), f)
    if err:
        bad(err, 1)
    backup_theme(f, tid)
    write(f, text)
    st = read_state()
    active, variant, look = active_theme(st)
    if active == tid:
        run_emitters(resolve(tid, variant, look), [e_state])
    print(json.dumps({"ok": True, "id": tid, "name": name}))


def forget_history_of(tid: str, f: Path, name: str | None) -> None:
    """A deleted theme leaves no Undo step behind: undoing its save would flip the Mode for a theme that is gone."""
    def about(e: dict) -> bool:
        fi = e.get("file")
        if isinstance(fi, dict) and fi.get("path") == str(f):
            return True
        if e.get("made") == tid:
            return True
        if "made" in e or isinstance(fi, dict):
            return False                                   # tied to a file or theme id: a same-named theme is not this one
        return bool(name) and e.get("label") in (f"Save {name}", f"Update {name}")
    h = read_history()
    keep = [e for e in h if not about(e)]
    if len(keep) != len(h):
        write(HISTORY, json.dumps(keep, indent=1) + "\n")


def cmd_delete(argv: list) -> None:
    if len(argv) != 1:
        usage("Usage: starchaser theme delete <id>")
    tid = argv[0]
    f = theme_files().get(tid)
    if not f:
        bad(f"there is no theme called {tid!r}", 1)
    if not is_mine(f):
        bad("themes that come with Starchaser can't be deleted", 1)
    t = load_theme(f) or {}                                # read before anything moves the file to the Trash
    gone_name = t.get("name")
    st = read_state()
    active, variant, _ = active_theme(st)
    where = ""
    if has_theme(st) and active == tid:
        base = t.get("based_on")
        target = base if isinstance(base, str) and base != tid and base in theme_files() else DEFAULT_THEME
        if target == tid:
            # a file of yours named like the default: once it is gone the bundled default is what applies
            where = trash(f)
        apply(target, theme_variant(target, variant))
    where = where or trash(f)
    forget_history_of(tid, f, gone_name)
    print(json.dumps({"ok": True, "id": tid, "moved_to": where}))


def trash(f: Path) -> str:
    """To the Trash, or to ~/.local/share/starchaser/deleted-themes when there is none. Never a plain unlink. A link
    is moved itself, never what it points to."""
    r = run("gio", "trash", "--", str(f))
    if r and r.returncode == 0:
        return "trash"
    d = DATA / "starchaser/deleted-themes"
    d.mkdir(parents=True, exist_ok=True)
    dest, n = d / f.name, 2
    while dest.exists() or dest.is_symlink():
        dest, n = d / f"{f.stem}-{n}{f.suffix}", n + 1
    os.rename(f, dest) if f.is_symlink() else shutil.move(str(f), str(dest))
    return str(dest)


def overrides_report() -> dict:
    st = read_state()
    tid, variant, look = active_theme(st)
    f = theme_files().get(tid)
    t = (load_theme(f) if f else None) or {}
    ov = read_overrides()
    th = resolve(tid, variant, look, ov)
    L = th["look"]
    rows = []
    for k, s in SETTINGS.items():
        row = {"key": k, "group": k.split(".", 1)[0], "type": s["type"], "label": s["label"], "value": L["values"][k],
               "default": L["defaults"][k], "source": L["sources"][k], "default_source": L["default_sources"][k],
               "changed": k in L["changes"]}
        row.update({x: s[x] for x in ("min", "max", "step", "unit", "choices", "hint") if x in s})
        if "choices" in s:
            row["choice_labels"] = {c: CHOICE_LABELS.get(c, c) for c in s["choices"]}
        if k == "glass.blur" and not row["value"]:
            row["hint"] = "Blur is off: see-through parts show the wallpaper sharp, without blur."
        if k == "glass.taskbar" and variant == "light":
            # the light taskbar's ink needs a 95% backing (cockpit/Theme.qml frameAlpha): the slider waits for Dark
            row["hint"] = "In Light mode the taskbar stays solid so its text stays readable."
        rows.append(row)
    mine = ov["colors"].get(tid, {}).get(variant, {})
    for r in ROLES:
        rows.append({"key": "colors." + r, "group": "colors", "type": "hex", "label": ROLE_LABELS[r],
                     "value": th["colors"][r], "default": th["theme_colors"][r], "source": "yours" if r in mine else "theme",
                     "default_source": "theme", "changed": r in mine and mine[r] != th["theme_colors"][r],
                     "main": r in MAIN_ROLES})
    look_changes = [k for k in L["changes"] if not SETTINGS[k].get("personal")]
    color_changes = [r for r in mine if mine[r] != th["theme_colors"][r]]
    hist = read_history()
    # a changes file that couldn't be read is named here too, so the numbers above can't read as "nothing changed"
    problem = (f"Your appearance changes couldn't be read and were kept as {_BROKEN_OVERRIDES}. "
               f"The theme's own look is in use.") if _BROKEN_OVERRIDES else ""
    return {"theme": tid, "theme_name": th["name"], "theme_short": t.get("short") or th["name"], "variant": variant,
            "variants": th["variants"], "look": look, "profile": L["profile"], "revision": ov["revision"],
            "settings": rows, "warnings": contrast_warnings(th), "corners": corners_status(), "problem": problem,
            "undo": hist[-1]["label"] if hist else "", "user_theme": bool(f and is_mine(f)),
            "editable": bool(f and editable(f)), "based_on": t.get("based_on", ""),
            "pinned_term": bool(th.get("pinned_term")), "look_changes": len(look_changes),
            # stored window and glass changes, even ones that now match the theme (Reset window and glass changes)
            "look_overrides": len([k for k in ov["look"] if not SETTINGS[k].get("personal")]),
            "color_changes": len(color_changes), "color_changes_any": bool(ov["colors"].get(tid)),
            # for the Look row, so it never claims what the screen doesn't show (animations included)
            "summary": ", ".join(describe(k, L["values"][k]) for k in L["changes"][:3]) + (" and more" if len(L["changes"]) > 3 else "")}


# ---------- wallpapers ----------

def one_picture_sets() -> dict:
    """{set: variant} for sets a theme shows in one version in Dark and Light (`wallpaper_variant = "dark"` in
    the theme file: Glowcat keeps its cats in Light mode too). Read quietly: a broken theme is named by the
    theme lists, not again by every wallpaper lookup. The first theme to name a set wins, like theme_files()."""
    out = {}
    for tid, f in theme_files().items():
        try:
            t = tomllib.loads(f.read_text())
        except THEME_ERRORS:
            continue
        v = t.get("wallpaper_variant")
        # a theme add-on may only say this for its own set (set name = its theme id), never for a bundled one
        if f.parent in SATELLITE_THEME_DIRS and wall_key(t, tid) != tid.lower():
            continue
        if v in ("dark", "light"):
            out.setdefault(wall_key(t, tid), v)
    return out


def wall_index() -> dict:
    """{set: {variant: [(w, h, path), ...]}}; earlier dirs win for identical file names. A set a theme shows in
    one version (one_picture_sets) lists that version's pictures under both dark and light, so every reader (the
    theme, the wallpaper picker, the theme cards' pictures, Settings' "Match the theme" card, which looks up the
    current mode's picture by name) gets the same picture in Dark and Light."""
    # A theme add-on's pictures count only for its own sets (the theme ids it ships) and never for a set a
    # bundled or user theme or picture folder already uses, so an add-on can't add to or replace other themes'
    # wallpapers behind the permission list.
    sat_sets = {s / "wallpapers": {f.stem.lower() for f in s.glob("*.toml")} for s in SATELLITE_THEME_DIRS}
    found = []
    for d in WALL_DIRS:
        if not d.is_dir():
            continue
        for f in sorted(d.rglob("*")):
            m = WALL_RE.match(f.name)
            if m and f.is_file():
                found.append((d, f, m))
    taken = {m["set"].lower() for d, f, m in found if d not in sat_sets}
    taken |= {f.stem.lower() for d in THEME_DIRS if d not in SATELLITE_THEME_DIRS and d.is_dir()
              for f in d.glob("*.toml")}
    idx, seen = {}, set()
    for d, f, m in found:
        ws = m["set"].lower()
        if d in sat_sets and (ws not in sat_sets[d] or ws in taken):
            continue
        if f.name in seen:
            continue
        seen.add(f.name)
        idx.setdefault(ws, {}).setdefault((m["variant"] or "dark").lower(), []).append((int(m["w"]), int(m["h"]), f))
    for ws, v in one_picture_sets().items():
        if v in idx.get(ws, {}):
            idx[ws] = {"dark": idx[ws][v], "light": idx[ws][v]}
    return idx


def thumb_path(f: Path) -> Path:
    # keyed on the whole path: Trips/a.jpg and Beach/a.png are two pictures, not one thumbnail
    return THUMBS / (hashlib.sha1(str(f.resolve()).encode()).hexdigest()[:16] + ".jpg")


def thumb_fresh(f: Path) -> bool:
    t = thumb_path(f)
    try:
        return t.stat().st_mtime >= f.stat().st_mtime
    except OSError:
        return False


def thumb(f: Path, build: bool = True) -> Path:
    """Small JPEG for the picker; regenerated when the source changes. build=False: never make one here (the
    picture itself until it's ready). It is written under a temp name and moved into place, so a reader running
    at the same time (the welcome, the menu and Settings all list wallpapers at first login) never gets half a
    picture; while another process is still writing it, this call uses the picture itself."""
    t = thumb_path(f)
    if thumb_fresh(f):
        return t
    if not build:
        return f
    tool = shutil.which("magick") or shutil.which("convert")
    if not tool:
        return f
    t.parent.mkdir(parents=True, exist_ok=True)
    tmp = t.with_name(t.stem + ".part.jpg")
    try:
        fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
    except FileExistsError:
        try:                                    # someone else is making it; a leftover from a crash is retried
            if tmp.stat().st_mtime > time.time() - 120:
                return f
            tmp.unlink()
            fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
        except OSError:
            return f
    os.close(fd)
    try:
        r = subprocess.run([tool, str(f), "-resize", "640x640>", "-quality", "85", "jpg:" + str(tmp)], capture_output=True)
        if r.returncode == 0 and tmp.stat().st_size > 0:
            os.replace(tmp, t)
    except OSError:
        pass
    finally:
        try:
            tmp.unlink()
        except OSError:
            pass
    return t if thumb_fresh(f) else f


def thumb_sources() -> list:
    """Every picture the wallpaper pickers show a thumbnail of: each set's largest file per variant, and the
    person's own pictures."""
    out = []
    for vs in wall_index().values():
        for files in vs.values():
            out.append(max(wall_pictures(files)[0], key=lambda x: x[0] * x[1])[2])
    return out + pictures()


def build_thumbs() -> int:
    """Make every missing thumbnail, one builder at a time (a second one just leaves). Returns how many it made."""
    THUMBS.mkdir(parents=True, exist_ok=True)
    lk = open(THUMBS / ".build.lock", "w")
    try:
        fcntl.flock(lk, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        return 0
    n = 0
    for f in thumb_sources():
        if not thumb_fresh(f):
            thumb(f)
            n += thumb_fresh(f)
    return n


def build_thumbs_later() -> None:
    """Missing thumbnails are made in the background (26 large pictures took long enough that the first
    Settings > Appearance and the first menu waited on them); until then the pickers show the pictures themselves."""
    try:
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "wallpaper", "thumbs"],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    except OSError:
        pass


def picture_number(f: Path) -> int:
    """Which of its set's pictures a file is: 1 without a "-pN", else N."""
    m = WALL_RE.match(f.name)
    return int(m["pic"]) if m and m["pic"] else 1


def wall_pictures(files: list) -> list:
    """A set's files for one variant as its pictures in order: [[(w, h, path), ...] per picture]. Each picture can
    come in several sizes; best_file picks the size, this picks the picture."""
    groups = {}
    for row in files:
        groups.setdefault(picture_number(row[2]), []).append(row)
    return [groups[n] for n in sorted(groups)]


def best_file(files: list, mw: int, mh: int) -> Path:
    """Closest aspect ratio; among those, the smallest that still covers the monitor."""
    import math
    want = mw / mh
    files = sorted(files, key=lambda x: abs(math.log((x[0] / x[1]) / want)))
    best = abs(math.log((files[0][0] / files[0][1]) / want))
    close = [x for x in files if abs(math.log((x[0] / x[1]) / want)) <= best + 0.02]
    covering = sorted((x for x in close if x[0] >= mw and x[1] >= mh), key=lambda x: x[0] * x[1])
    return (covering[0] if covering else max(close, key=lambda x: x[0] * x[1]))[2]


def monitors() -> list:
    r = run("hyprctl", "monitors", "-j")
    if not r or r.returncode != 0:
        return []
    out = []
    for m in json.loads(r.stdout):
        w, h = m["width"], m["height"]
        if m.get("transform", 0) % 2 == 1:  # rotated 90 / 270
            w, h = h, w
        out.append((m["name"], w, h))
    return out


def wallpaper_outputs() -> set[str] | None:
    """Outputs the wallpaper service knows, which can lag behind a newly connected screen.
    None when the service couldn't be asked: callers then paint every screen, as before this check."""
    r = run("awww", "query")
    if r is None or r.returncode != 0:
        return None
    # awww 0.12 prints ": HDMI-A-1: 3840x1080, scale: 1, ..." (a leading colon); older builds "HDMI-A-1: ..."
    names = set()
    for line in r.stdout.splitlines():
        m = re.match(r"\s*:?\s*([^:\s][^:]*?)\s*:", line)
        if m:
            names.add(m.group(1))
    return names


def _or_all(available, mons):
    return {name for name, _, _ in mons} if available is None else available


def wallpaper_missing(chosen) -> list[str]:
    """Check again after applying: another screen may have arrived while the commands ran."""
    available = _or_all(wallpaper_outputs(), monitors())
    return [name for name, _, _ in monitors() if name not in chosen or name not in available]


def set_wallpaper(wset: str, variant: str, transition: bool = True, require_all: bool = False,
                  picture: int | None = None) -> str:
    """Show a set. picture is which of its pictures (0 is the first); None keeps the one shown last for this set
    (wallpaper next), so a restore, a dark/light switch or reapplying the theme doesn't jump back to the first."""
    def failed(message):
        if require_all:
            sys.exit(message)  # restore's hotplug watcher retries a nonzero exit
        return message

    idx = wall_index()
    files = idx.get(wset, {}).get(variant)
    if not files:                    # the set's one version (dark when it has both is the old fallback)
        variant = "dark" if idx.get(wset, {}).get("dark") else next(iter(idx.get(wset, {})), variant)
        files = idx.get(wset, {}).get(variant)
    if not files:
        return failed(f"no wallpaper set '{wset}' ({variant})")
    groups = wall_pictures(files)
    if picture is None:
        now = (read_state() or {}).get("wallpaper_now") or {}
        picture = now.get("index") if now.get("set") == wset and isinstance(now.get("index"), int) else 0
    picture %= len(groups)
    files = groups[picture]
    mons = monitors()
    if not mons:
        return failed("no Hyprland monitors (not in a Hyprland session?)")
    err = awww_ready()
    if err:
        return failed(err)
    available = _or_all(wallpaper_outputs(), mons)
    chosen = {}
    for name, w, h in mons:
        if name not in available:
            continue
        f = best_file(files, w, h)
        args = ["awww", "img", "-o", name, "--resize", "crop", str(f)]
        args += (["-t", "grow", "--transition-pos", "center", "--transition-duration", "1.4",
                  "--transition-fps", "120"] if transition else ["-t", "none"])
        r = run(*args)
        if r is not None and r.returncode == 0:
            chosen[name] = str(f)
    if chosen:
        st = read_state() or {}
        st["wallpaper_now"] = {"set": wset, "variant": variant, "index": picture, "outputs": chosen}
        write(STATE, json.dumps(st, indent=2) + "\n")
    missing = wallpaper_missing(chosen)
    if missing:
        return failed("couldn't show wallpaper on " + ", ".join(missing))
    which = f", picture {picture + 1} of {len(groups)}" if len(groups) > 1 else ""
    sizes = {row[2]: f"{row[0]}x{row[1]}" for row in files}
    return f"{wset} ({variant}{which}) on " + ", ".join(f"{n}={sizes.get(Path(f), Path(f).stem)}" for n, f in chosen.items())


def step_wallpaper(st: dict | None, step: int) -> str:
    """wallpaper next (step 1) or previous (-1): the next picture of the set on screen, wrapping around at the end;
    with a picture of your own on screen, the next picture in ~/Pictures/Wallpapers. Only the wallpaper changes
    (never the pointer, the colors or whether the wallpaper follows the theme)."""
    now = (st or {}).get("wallpaper_now") or {}
    if now.get("picture"):
        pics = pictures()
        if not pics:
            return "no pictures of your own to move through"
        names = [str(f) for f in pics]
        at = names.index(now["picture"]) if now["picture"] in names else (-1 if step > 0 else 0)
        status, out = set_picture(pics[(at + step) % len(pics)])
        if status != "ok":
            sys.exit(out)
        return out
    idx = wall_index()
    wset, variant = now.get("set"), now.get("variant")
    if wset not in idx and has_theme(st):
        wset, variant = wall_key(st, st["id"]), st["variant"]
    if wset not in idx:
        sys.exit("no wallpaper on screen to move through (starchaser theme wallpaper list)")
    files = idx[wset].get(variant) or idx[wset].get("dark") or next(iter(idx[wset].values()))
    count = len(wall_pictures(files))
    if count < 2:
        notify("This wallpaper has one picture", "Pick another wallpaper in Settings > Appearance to see more.")
        return f"{wset} has one picture; wallpaper unchanged"
    current = now.get("index") if now.get("set") == wset and isinstance(now.get("index"), int) else 0
    return set_wallpaper(wset, variant if variant in idx[wset] else "dark", picture=(current + step) % count)


def picture_name(f: Path) -> str:
    """A picture's name for people: "photo-1920x1080-picture.jpg" -> "Photo", "sunset_2.png" -> "Sunset 2". Drops
    the "-picture" that Settings adds to a copy whose name looks like part of a sized set, and screen sizes."""
    n = re.sub(r"(-\d+[xX]\d+.*)-picture(?=(-\d+)?$)", r"\1", f.stem)
    n = re.sub(r"(?<![^\W_])\d{3,5}[xX]\d{3,5}(?![^\W_])", " ", n)
    n = " ".join(n.replace("_", " ").replace("-", " ").split())
    if not n:
        return f.stem
    return n[0].upper() + n[1:] if n == n.lower() else n


def natural_key(s: str) -> list:
    """Sort key where "Sunset" comes before "Sunset 2", and "Photo 2" before "Photo 10"."""
    return [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s.casefold())]


def pictures() -> list:
    """The user's own pictures in ~/Pictures/Wallpapers that aren't part of a sized set, by name as people see it."""
    if not PICTURES.is_dir():
        return []
    return sorted((f for f in PICTURES.rglob("*") if f.is_file() and f.suffix.lower() in IMAGE_EXT and not WALL_RE.match(f.name)),
                  key=lambda f: (natural_key(picture_name(f)), str(f).casefold()))


def awww_ready() -> str:
    if not shutil.which("awww"):
        return "awww not installed"
    r = run("awww", "query")
    if r is None or r.returncode != 0:
        subprocess.Popen(["awww-daemon"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
        for _ in range(30):
            r = run("awww", "query")
            if r is not None and r.returncode == 0:
                return ""
            subprocess.run(["sleep", "0.1"])
        return "wallpaper service is not ready"
    return ""


def set_picture(path: Path, transition: bool = True) -> tuple[str, str]:
    """One picture, cropped to fill every monitor. (status, message): status is "ok", "bad" (no such picture, or
    one awww turned down) or "env" (no awww or no monitors: nothing wrong with the picture). A status, not the
    message's first word, since the message starts with the file's own name ("couldn't resist.png on DP-1")."""
    if not path.is_file():
        return "bad", f"no picture {path}"
    err = awww_ready()
    if err:
        return "env", err
    mons = monitors()
    if not mons:
        return "env", "no Hyprland monitors (not in a Hyprland session?)"
    available = _or_all(wallpaper_outputs(), mons)
    shown = []
    for name, _, _ in mons:
        if name not in available:
            continue
        args = ["awww", "img", "-o", name, "--resize", "crop", str(path)]
        args += (["-t", "grow", "--transition-pos", "center", "--transition-duration", "1.4",
                  "--transition-fps", "120"] if transition else ["-t", "none"])
        r = run(*args)
        if r and r.returncode == 0:
            shown.append(name)
    if not shown and all(name in available for name, _, _ in mons):
        # a damaged or unreadable picture: awww turns it down and the old wallpaper stays, so it is not saved as
        # the wallpaper (the gallery would mark it picked, and the next sign-in would try it again)
        return "bad", f"couldn't show {path.name}"
    if shown:
        st = read_state() or {}
        st["wallpaper_now"] = {"picture": str(path), "outputs": {n: str(path) for n in shown}}
        write(STATE, json.dumps(st, indent=2) + "\n")
    missing = wallpaper_missing(shown)
    if missing:
        return "env", "couldn't show wallpaper on " + ", ".join(missing)
    return "ok", f"{path.name} on " + ", ".join(shown)


def set_mode(mode: str) -> None:
    """"theme": the wallpaper follows the theme; "own": the user picked it, themes leave it alone."""
    st = read_state() or {}
    st["wallpaper_mode"] = mode
    write(STATE, json.dumps(st, indent=2) + "\n")


def read_state() -> dict | None:
    try:
        data = json.loads(STATE.read_text())
        return data if isinstance(data, dict) else None
    except Exception:
        return None


def has_theme(st: dict | None) -> bool:
    """A state file can hold only the wallpaper choice (set before any theme): that's not a theme yet."""
    return bool(st and st.get("id") and st.get("variant"))


def write(path: Path, text: str) -> None:
    if path.is_symlink():                       # a linked file (dotfiles): write what it points to, as ini_set does
        path = path.resolve()
    path.parent.mkdir(parents=True, exist_ok=True)
    # a temp name of its own next to the target (same filesystem): two writers can't trip over one ".tmp"
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as fh:
            fh.write(text)
            fh.flush()
            os.fsync(fh.fileno())
        if path.exists():
            try:
                os.chmod(tmp, path.stat().st_mode & 0o7777)
            except OSError:
                pass
        else:
            os.chmod(tmp, 0o644)
        os.replace(tmp, path)  # atomic: watchers never see half a file
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def lock_writers() -> None:
    """One writer at a time (gallery clicks start applies without waiting): queued commands run one after another,
    so the last click wins in every app, not app by app. Held until the process ends."""
    STATE_DIR.mkdir(parents=True, exist_ok=True)
    global _LOCK
    if _LOCK is not None:       # a process that takes the lock twice (the tests call main() repeatedly) lets go of the old one
        _LOCK.close()
    _LOCK = open(STATE_DIR / "apply.lock", "w")
    fcntl.flock(_LOCK, fcntl.LOCK_EX)


_LOCK = None
_CK_LOCK = None
KEPT_MAX = 64      # apps kept on the taskbar (cockpit keep): far more than any taskbar has room for


def lock_cockpit() -> None:
    """One cockpit.json writer at a time: two quick taskbar changes (edge, then auto-hide) both read the old file,
    and the second write put back what the first had changed. Its own lock, so a taskbar change doesn't wait for a
    theme to finish applying. Other writers of cockpit.json take the same lock file."""
    global _CK_LOCK
    d = CONFIG / "starchaser"
    d.mkdir(parents=True, exist_ok=True)
    _CK_LOCK = open(d / ".cockpit.lock", "w")
    fcntl.flock(_CK_LOCK, fcntl.LOCK_EX)


def run(*cmd, **kw) -> subprocess.CompletedProcess | None:
    if not shutil.which(cmd[0]):
        return None
    return subprocess.run(cmd, capture_output=True, text=True, timeout=10, **kw)


def owned(path: Path) -> bool:
    """True if we may (over)write this file: it doesn't exist yet or we wrote it."""
    return not path.exists() or MANAGED in path.read_text(errors="replace")[:400]


# ---------- emitters: each returns a short status line ----------

def e_state(th):
    ck = CONFIG / "starchaser/cockpit.json"   # the cockpit watches this; make sure it exists
    if not ck.exists():
        write(ck, json.dumps({"edge": "left"}, indent=2) + "\n")
    old = read_state() or {}
    if has_theme(old) and old["id"] != th["id"]:
        th = {**th, "previous_theme": {"id": old["id"], "variant": old["variant"]}}
    elif isinstance(old.get("previous_theme"), dict):
        th = {**th, "previous_theme": old["previous_theme"]}
    for k in ("wallpaper_now", "wallpaper_mode"):      # the wallpaper is its own setting: a theme keeps it
        if k in old:
            th = {**th, k: old[k]}
    write(STATE, json.dumps(th, indent=2) + "\n")
    return f"state  {STATE}"


KITTY_SYSTEM = Path("/etc/xdg/kitty/kitty.conf")   # Starchaser's terminal settings, read before ~/.config/kitty/kitty.conf
# the same line the desktop setup looks for (installer/starchaser-desktop-setup.sh); the system copy names the full path
KITTY_INCLUDE = r"(?m)^[ \t]*include[ \t]+(~/\.config/kitty/)?theme\.conf[ \t]*$"


def kitty_reads(path: Path) -> str:
    try:
        return path.read_text(errors="replace")
    except OSError:
        return ""


KITTY_FONT_SIZE = 11.0      # kitty's own default, for a kitty.conf that sets none


def kitty_font_size(conf_text: str):
    """The terminal font size for the accessibility text size: the last font_size in conf_text (the system copy, then
    the person's own kitty.conf) times the scale, or None at 100% (kitty.conf's own size applies). An unreadable
    accessibility file means the usual size."""
    try:
        scale = accessibility.read()["text_scale"]
    except ValueError:
        return None
    if scale == 1:
        return None
    sizes = re.findall(r"(?m)^[ \t]*font_size[ \t]+([0-9]+(?:\.[0-9]+)?)[ \t]*$", conf_text)
    return round((float(sizes[-1]) if sizes else KITTY_FONT_SIZE) * scale, 1)


def reload_kittys() -> int:
    """SIGUSR1 to every running kitty of this user (each listens on @kitty-<pid>, kitty.conf listen_on): kitty reads
    its config files again. Returns how many were told."""
    try:
        pids = {int(p) for p in re.findall(r"@kitty-(\d+)", Path("/proc/net/unix").read_text())}
    except OSError:
        return 0
    n = 0
    for pid in pids:
        try:
            if Path(f"/proc/{pid}/comm").read_text().strip() != "kitty":
                continue
            os.kill(pid, signal.SIGUSR1)
            n += 1
        except (OSError, ValueError):
            pass    # gone, or someone else's: best-effort, the next kitty opened reads the new size anyway
    return n


def e_kitty(th):
    conf = CONFIG / "kitty/kitty.conf"
    mine = kitty_reads(conf)
    if re.search(KITTY_INCLUDE, mine):
        theme, keep = CONFIG / "kitty/theme.conf", set()
    elif re.search(r"(?m)^[ \t]*include[ \t]+~/\.config/kitty/theme\.conf[ \t]*$", kitty_reads(KITTY_SYSTEM)):
        # the system copy brings the colors in, before your own kitty.conf: a color that file sets wins when a terminal
        # opens, so changing the theme doesn't push that color to open terminals either
        theme = HOME / ".config/kitty/theme.conf"
        keep = {line.split()[0] for line in mine.splitlines() if line.strip() and not line.lstrip().startswith("#")}
    else:
        return "kitty  skipped (kitty.conf has no 'include theme.conf')"
    c, t = th["colors"], th["term"]
    lines = [f"# {MANAGED}: {th['name']} ({th['variant']})",
             f"background            {c['bg']}", f"foreground            {c['text']}",
             f"background_opacity    {th['look']['term_opacity']}",
             f"cursor                {c['accent']}", f"cursor_text_color     {c['bg']}",
             f"selection_background  {c['selection']}", f"selection_foreground  {c['text']}",
             f"url_color             {th['ink']['accent2']}",
             f"active_border_color   {c['accent']}", f"inactive_border_color {c['border']}",
             f"active_tab_background   {c['accent']}", f"active_tab_foreground   {c['bg']}",
             f"inactive_tab_background {c['surface']}", f"inactive_tab_foreground {th['hint']}"]
    lines += [f"color{i:<2} {x}" for i, x in enumerate(t)]
    # large text (Settings > Accessibility > Text size): the terminal's own font_size times the text size, the base
    # from your own kitty.conf if it sets one, else from the system copy, else kitty's 11. theme.conf carries the
    # scaled size; kitty.conf keeps the person's own size
    size = kitty_font_size(kitty_reads(KITTY_SYSTEM) + "\n" + mine)
    if size is not None:
        lines.append(f"font_size             {size:g}")
    before = re.findall(r"(?m)^font_size\s.*$", kitty_reads(theme))
    write(theme, "\n".join(lines) + "\n")
    live = theme
    if keep:
        pushed = [line for line in lines if line.startswith("#") or line.split()[0] not in keep]
        live = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / f"starchaser-kitty-colors-{os.getuid()}.conf"
        write(live, "\n".join(pushed) + "\n")
    # set-colors can't change the font (the remote-control password allows colors only): a kitty that is open reads
    # its config again on SIGUSR1, and only when the size changed, so a color change doesn't reload every terminal
    if before != re.findall(r"(?m)^font_size\s.*$", "\n".join(lines)):
        reload_kittys()
    # live: every kitty listens on an abstract socket @kitty-<pid> (kitty.conf listen_on)
    n = 0
    try:
        socks = set(re.findall(r"@(kitty-\d+)", Path("/proc/net/unix").read_text()))
    except OSError:
        socks = set()
    for s in socks:
        r = run("kitty", "@", "--to", f"unix:@{s}", "set-colors", "--all", "--configured", str(live))
        n += bool(r and r.returncode == 0)
    return f"kitty  {theme} (live: {n} window{'s' if n != 1 else ''})"


def xfce_terminal_settings(th: dict, kitty_conf: str) -> dict:
    """The screen reader's terminal (xfce4-terminal, bin/starchaser-terminal) in kitty's colors and font: xfconf
    property -> value. The font is kitty.conf's (the system copy, then the person's own), at the text size."""
    c = th["colors"]
    family = re.findall(r"(?m)^[ \t]*font_family[ \t]+(\S.*?)[ \t]*$", kitty_conf)
    sizes = re.findall(r"(?m)^[ \t]*font_size[ \t]+([0-9]+(?:\.[0-9]+)?)[ \t]*$", kitty_conf)
    size = kitty_font_size(kitty_conf) or (float(sizes[-1]) if sizes else KITTY_FONT_SIZE)
    return {"/color-use-theme": False, "/color-foreground": c["text"], "/color-background": c["bg"],
            "/color-cursor-use-default": False, "/color-cursor": c["accent"], "/color-cursor-foreground": c["bg"],
            "/color-selection-use-default": False, "/color-selection": c["text"],
            "/color-selection-background": c["selection"], "/color-bold-use-default": True,
            "/color-palette": ";".join(th["term"][:16]),
            "/font-use-system": False, "/font-name": f"{family[-1] if family else 'Monospace'} {size:g}"}


def e_xfceterm(th):
    if not shutil.which("xfce4-terminal"):
        return "xfceterm skipped (not installed)"
    kitty_conf = kitty_reads(KITTY_SYSTEM) + "\n" + kitty_reads(CONFIG / "kitty/kitty.conf")
    # through xfconf, where it keeps its settings: an open window changes at once. No settings service (no desktop
    # session) leaves it as it was, like gsettings in e_gtk: the next theme change in the session sets it
    for prop, value in xfce_terminal_settings(th, kitty_conf).items():
        kind, text = ("bool", str(value).lower()) if isinstance(value, bool) else ("string", value)
        r = run("xfconf-query", "-c", "xfce4-terminal", "-p", prop, "-n", "-t", kind, "-s", text)
        if not r or r.returncode != 0:
            return "xfceterm skipped (xfconf failed)"
    return "xfceterm xfconf xfce4-terminal"


def e_look(th):
    """~/.config/hypr/starchaser-look.lua: effects for the active look, in the theme's colors.
    hyprland.lua dofile()s it last, so it overrides the base config."""
    c, L = th["colors"], th["look"]

    def argb(h, a):
        return f"0x{a}{bare(h)}"

    def pick(v):                # a role name ("accent") or a color of yours ("#ff8800")
        return c.get(v, v)
    ba = L["border_active"]
    border = (f'{{ colors = {{"rgba({bare(c["accent"])}ee)", "rgba({bare(c["accent2"])}ee)", '
              f'"rgba({bare(c["accent"])}ee)"}}, angle = 45 }}') if ba == "gradient" \
        else f'"rgba({bare(pick(ba))}ee)"'
    # the glow: the focused window's shadow in the glow color; shadows: the plain dark one under the other windows
    shadow_active = argb(pick(L["glow_color"]), f"{L['glow_alpha']:02x}") if L["glow"] else argb("#000000", "66")
    shadow_other = argb("#000000", "66") if L["shadows"] else "0x00000000"
    # Starchaser's own windows get their cut corners on the first frame (starchaser corners takes over once a window
    # is mapped): its "all four corners" code, with the radius for the corner cut and border picked in Settings
    # A window rule takes 20 at most (Hyprland shows a config error above that): a Large cut starts a little smaller
    # on the first frame, and starchaser corners sets the full cut (set_prop has no such limit) once it is mapped
    cut = min(RULE_ROUNDING_MAX, 2.0 * (max(1.0, L["corner_cut"] - L["border_size"]) + 1.0) / CUT_POWER)
    lua = f"""-- {MANAGED}: {th['name']} ({th['variant']}), look {L['profile']}
-- Loaded near the end of hyprland.lua (your user.lua still comes after it); change these in Settings > Appearance >
-- Customize, or with `starchaser theme look <name>` and `starchaser theme set <key> <value>`.
hl.config({{
    general = {{
        gaps_in     = {L['gaps_in']},
        gaps_out    = {L['gaps_out']},  -- the cockpit frame is the screen edge; windows stay just inside it
        float_gaps  = -1,  -- maximized floating windows keep the same outer gap as tiles
        border_size = {L['border_size']},
        col = {{
            active_border   = {border},
            inactive_border = "rgba({bare(pick(L['border_inactive']))}aa)",
        }},
    }},
    decoration = {{
        rounding         = 0,   -- square windows; the cockpit carves the corners that meet its cut corners
        active_opacity   = 1.0,
        inactive_opacity = {L['inactive_opacity']},
        blur = {{
            enabled    = {str(L['blur']).lower()},
            size       = {max(L['blur_size'], 1)},
            passes     = {max(L['blur_passes'], 1)},
            vibrancy   = 0.18,
            noise      = 0.012,
            contrast   = 0.9,
            brightness = 0.85,
            popups     = {str(L['blur']).lower()},
        }},
        shadow = {{
            enabled        = {str(L['shadow']).lower()},
            range          = {max(L['shadow_range'], 1)},
            render_power   = 3,
            color          = {shadow_active},
            color_inactive = {shadow_other},
        }},
    }},
    animations = {{
        enabled = {str(L['animations']).lower()},
    }},
}})

pcall(hl.window_rule, {{
    name  = "starchaser-cut-first-frame",
    match = {{ title = "^(Starchaser Settings|Welcome to Starchaser Linux|Ask Starchaser|Starchaser Lock Preview)$" }},
    rounding = {round(cut)}, rounding_power = {CUT_POWER},
}})
"""
    if L["border_anim"]:
        lua += '\n-- the active border\'s gradient slowly turns\nhl.animation({ leaf = "borderangle", enabled = true, speed = 100, bezier = "linear", style = "loop" })\n'
    if L["blur"]:
        lua += "\n-- frosted glass behind the shell's own layers\n" + "".join(
            f'hl.layer_rule({{ name = "starchaser-blur-{ns}", match = {{ namespace = "^{ns}$" }}, blur = true, ignore_alpha = 0.2 }})\n'
            for ns in ("starchaser-bar", "starchaser-panel", "starchaser-notifications")
            + (("starchaser-cockpit",) if L["profile"] != "glass-light" else ()))
    f = CONFIG / "hypr/starchaser-look.lua"
    write(f, lua)
    live = ""
    if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):     # hyprland.lua loads this file: a reload applies it now
        r = run("hyprctl", "reload")
        live = " (reloaded)" if r and r.returncode == 0 else " (reload failed)"
    # unfocused terminals' see-through background follows the look: term-focus.py reads it again on SIGHUP. Only
    # the pid it wrote itself (a helper from before it handled the signal would be ended by one)
    signal_term_focus()
    return f"look   {f} ({L['profile']}){live}"


def signal_term_focus() -> None:
    if os.environ.get("STARCHASER_FLEET_APPLY") == "1":
        return
    try:
        pid = int((STATE_DIR / "term-focus.pid").read_text().strip())
        if "term-focus" in Path(f"/proc/{pid}/cmdline").read_bytes().decode(errors="replace"):
            os.kill(pid, signal.SIGHUP)
    except (OSError, ValueError):
        pass


def e_hyprland(th):
    """The palette for your own hypr/user.lua to use if you want it (the shipped config doesn't load it; the look
    file carries the colors). Kept because a user.lua may dofile() it."""
    c = th["colors"]
    f = CONFIG / "hypr/scheme/current.lua"
    body = (f"-- {MANAGED}: {th['name']} ({th['variant']})\n"
            "-- The theme's colors as bare hex, for your own user.lua (dofile); the shipped config doesn't read it.\n"
            "return {\n" +
            "".join(f'    {k:<15}= "{bare(v)}",\n' for k, v in {
                "primary": c["accent"], "secondary": c["accent2"], "tertiary": c["accent3"],
                "outlineVariant": c["border"], "surface": c["bg"], "text": c["text"]}.items()) + "}\n")
    write(f, body)
    return f"hypr   {f}"


LITEXL_SYSTEM = Path("/usr/share/lite-xl")   # Starchaser's plugins and base colors, read after ~/.config/lite-xl


def e_litexl(th):
    if not (CONFIG / "lite-xl").is_dir() and not (LITEXL_SYSTEM / "plugins/starchaser_theme_watch.lua").is_file():
        return "litexl skipped (no ~/.config/lite-xl)"
    c, s = th["colors"], th["syntax"]
    f = CONFIG / "lite-xl/colors/starchaser.lua"
    pairs = {"background": c["bg"], "background2": c["bg_alt"], "background3": c["surface"],
             "text": c["subtext"], "caret": c["accent"], "accent": c["text"], "dim": c["muted"],
             "divider": c["bg_alt"], "selection": c["selection"], "line_number": c["muted"],
             "line_number2": c["accent"], "line_highlight": c["bg_alt"], "scrollbar": c["surface_hi"],
             "scrollbar2": c["border"], "scrollbar_track": c["bg_alt"], "nagbar": c["error"],
             "nagbar_text": c["bg"], "drag_overlay_tab": c["accent"], "good": th["ink"]["success"],
             "warn": th["ink"]["warning"], "error": th["ink"]["error"], "modified": th["ink"]["accent2"]}
    syn = {"normal": s["normal"], "symbol": s["normal"], "comment": s["comment"],
           "keyword": s["keyword"], "keyword2": s["type"], "number": s["number"],
           "literal": s["number"], "string": s["string"], "operator": s["operator"],
           "function": s["function"]}
    out = [f"-- {MANAGED}: {th['name']} ({th['variant']})",
           'local style = require "core.style"', 'local common = require "core.common"', ""]
    out += [f'style.{k} = {{ common.color "{v}" }}' for k, v in pairs.items()]
    # the marker a watcher plugin checks before reloading this file in an open editor: it stays off when your own
    # init.lua picked another editor theme
    out += ["style.starchaser = true"]
    # which background was ours: an init.lua that loads another editor theme after this file (before plugins load)
    # replaces style.background, so the watcher can tell the Starchaser colors are no longer the ones in use (QA r37)
    out += ["style.starchaser_bg = style.background"]
    out += ['style.nagbar_dim = { common.color "rgba(0, 0, 0, 0.45)" }',
            f'style.drag_overlay = {{ common.color "{c["accent"]}" }}',
            "style.drag_overlay[4] = 30", ""]
    out += [f'style.syntax["{k}"] = {{ common.color "{v}" }}' for k, v in syn.items()]
    out += ["", 'style.log["INFO"]  = { icon = "i", color = style.text }',
            'style.log["WARN"]  = { icon = "!", color = style.warn }',
            'style.log["ERROR"] = { icon = "!", color = style.error }', "", "return style"]
    write(f, "\n".join(out) + "\n")
    # open editors follow only with the watcher plugin (plugins/starchaser_theme_watch.lua); without it, new windows
    watched = any((d / "plugins/starchaser_theme_watch.lua").is_file() for d in (CONFIG / "lite-xl", LITEXL_SYSTEM))
    return f"litexl {f}" + ("" if watched else " (new windows)")


def e_gtksourceview(th):
    c, s, v, k = th["colors"], th["syntax"], th["variant"], th["ink"]
    f = DATA / "gtksourceview-5/styles/starchaser.xml"
    st = [("text", f'foreground="{c["text"]}" background="{c["bg"]}"'),
          ("selection", f'foreground="{c["text"]}" background="{c["selection"]}"'),
          ("selection-unfocused", f'foreground="{c["text"]}" background="{c["surface"]}"'),
          ("cursor", f'foreground="{c["accent"]}"'), ("secondary-cursor", f'foreground="{c["accent2"]}"'),
          ("current-line", f'background="{c["bg_alt"]}"'),
          ("line-numbers", f'foreground="{c["muted"]}" background="{c["bg"]}"'),
          ("current-line-number", f'foreground="{readable(k["accent"], c["text"], [c["bg_alt"]])}" background="{c["bg_alt"]}" bold="true"'),
          ("right-margin", f'foreground="{c["surface"]}" background="{c["bg"]}"'),
          ("draw-spaces", f'foreground="{c["muted"]}"'), ("background-pattern", f'background="{c["bg_alt"]}"'),
          ("bracket-match", f'foreground="{c["text"]}" background="{c["selection"]}" bold="true"'),
          ("bracket-mismatch", f'foreground="{k["error"]}" underline="error"'),
          ("search-match", f'foreground="{c["bg"]}" background="{c["warning"]}"'),
          ("def:comment", f'foreground="{s["comment"]}" italic="true"'),
          ("def:shebang", f'foreground="{s["comment"]}" bold="true"'),
          ("def:keyword", f'foreground="{s["keyword"]}"'), ("def:statement", f'foreground="{s["keyword"]}"'),
          ("def:type", f'foreground="{s["type"]}"'), ("def:builtin", f'foreground="{s["type"]}"'),
          ("def:function", f'foreground="{s["function"]}"'), ("def:identifier", f'foreground="{s["normal"]}"'),
          ("def:operator", f'foreground="{s["operator"]}"'), ("def:preprocessor", f'foreground="{s["operator"]}"'),
          ("def:string", f'foreground="{s["string"]}"'), ("def:special-char", f'foreground="{s["function"]}"'),
          ("def:number", f'foreground="{s["number"]}"'), ("def:boolean", f'foreground="{s["number"]}"'),
          ("def:constant", f'foreground="{s["number"]}"'), ("def:special-constant", f'foreground="{s["number"]}"'),
          ("def:heading", f'foreground="{k["accent"]}" bold="true"'), ("def:emphasis", 'italic="true"'),
          ("def:strong-emphasis", 'bold="true"'), ("def:link-text", f'foreground="{k["accent2"]}"'),
          ("def:link-destination", f'foreground="{k["accent2"]}" underline="single"'),
          ("def:note", f'foreground="{c["bg"]}" background="{c["accent2"]}" bold="true"'),
          ("def:warning", f'foreground="{k["warning"]}" underline="error"'),
          ("def:error", f'foreground="{k["error"]}" underline="error"'),
          ("diff:added-line", f'foreground="{k["success"]}"'), ("diff:removed-line", f'foreground="{k["error"]}"'),
          ("diff:changed-line", f'foreground="{k["warning"]}"'), ("diff:location", f'foreground="{k["accent2"]}"')]
    # "Black & Gold" has to be written &amp; in XML, and "--" can't appear inside a comment at all
    name = xml_escape(th["name"])
    xml = (f'<?xml version="1.0" encoding="UTF-8"?>\n<!-- {MANAGED}: {name.replace("-", "&#45;")} ({v}) -->\n'
           '<style-scheme id="starchaser" name="Starchaser" version="1.0">\n'
           "  <author>Starchaser</author>\n"
           f"  <description>{name} ({v})</description>\n"
           f'  <metadata>\n    <property name="variant">{v}</property>\n  </metadata>\n' +
           "".join(f'  <style name="{n}" {a}/>\n' for n, a in st) + "</style-scheme>\n")
    write(f, xml)
    # the same scheme for GtkSourceView 4 (the text editor, Mousepad), which refuses a scheme with <metadata> (a
    # version 5 addition). The starchaser-editor-colors module notices this file change and recolors open windows
    f4 = DATA / "gtksourceview-4/styles/starchaser.xml"
    write(f4, re.sub(r"  <metadata>.*?</metadata>\n", "", xml, flags=re.S))
    # the style file is for any app that uses it; the editor settings only when that editor is installed
    schemas = run("gsettings", "list-schemas")
    if not (schemas and "org.gnome.TextEditor" in schemas.stdout.split()):
        return f"gsv    {f} {f4}"
    rs = [run("gsettings", "set", "org.gnome.TextEditor", "style-variant", v),
          run("gsettings", "set", "org.gnome.TextEditor", "style-scheme", "starchaser")]
    return f"gsv    {f} {f4}" + ("" if all(r and r.returncode == 0 for r in rs) else " (Text Editor settings not set)")


def chamfer_png(path: Path, w: int, h: int, cut: int, fill: tuple, stroke: tuple, sw: float = 2.0) -> None:
    """A w x h RGBA PNG of a box with 45-degree cut corners (4x supersampled), stdlib only.
    fill / stroke are (r, g, b, a) 0-255; the stroke runs just inside the edge."""
    import struct
    import zlib
    ss = 4
    r2 = 2 ** 0.5

    def inside(x, y, inset):
        # inside the chamfered box shrunk by `inset` px: a 45-degree edge x + y = cut moves to
        # x + y = cut + inset * sqrt(2), so the cut stays parallel
        if x < inset or y < inset or x > w - inset or y > h - inset:
            return False
        c = cut + inset * r2
        return x + y >= c and (w - x) + y >= c and (w - x) + (h - y) >= c and x + (h - y) >= c

    rows = []
    for py in range(h):
        row = bytearray([0])
        for px in range(w):
            acc = [0.0, 0.0, 0.0, 0.0]
            for sy in range(ss):
                for sx in range(ss):
                    x, y = px + (sx + 0.5) / ss, py + (sy + 0.5) / ss
                    if inside(x, y, sw):
                        col = fill
                    elif inside(x, y, 0):
                        col = stroke
                    else:
                        continue
                    a = col[3] / 255
                    for i in range(3):
                        acc[i] += col[i] * a
                    acc[3] += a
            n = ss * ss
            alpha = acc[3] / n
            if alpha > 0:
                row += bytes([round(acc[0] / acc[3]), round(acc[1] / acc[3]), round(acc[2] / acc[3]), round(alpha * 255)])
            else:
                row += b"\0\0\0\0"
        rows.append(bytes(row))

    def chunk(t, d):
        return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d) & 0xffffffff)
    png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, 6, 0, 0, 0)) + \
          chunk(b"IDAT", zlib.compress(b"".join(rows), 9)) + chunk(b"IEND", b"")
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_bytes(png)


def e_hyprlock(th):
    c = th["colors"]
    f = CONFIG / "hypr/hyprlock.conf"
    if not owned(f):
        return f"lock   skipped ({f} is hand-written)"

    def rgba(h, a=1.0):
        r, g, b = (round(x * 255) for x in rgb(h))
        return f"rgba({r}, {g}, {b}, {a})"
    # hyprlock can only round its input field, so the chamfered box is an image behind a
    # transparent field (the field's colored outline is dropped; its fail text still shows)
    fw, fh = 320, 56
    field_png = Path(os.environ.get("XDG_CACHE_HOME", HOME / ".cache")) / "starchaser/lock-field.png"

    def rgba255(h, a):
        return tuple(round(x * 255) for x in rgb(h)) + (round(a * 255),)
    chamfer_png(field_png, fw, fh, 12, rgba255(c["surface"], 0.9), rgba255(c["accent"], 1.0), 2.0)

    body = f"""# {MANAGED}: {th['name']} ({th['variant']})
general {{
    hide_cursor = true
}}

background {{
    monitor =
    color = {rgba(c['bg'])}
{"    path = screenshot" + chr(10) + "    blur_passes = 3" + chr(10) + "    blur_size = 8" + chr(10) + "    brightness = 0.6" if th["look"]["lock_screenshot"] else ""}
}}

label {{
    monitor =
    text = cmd[update:1000] date +"%-I:%M"
    color = {rgba(c['text'])}
    font_size = 96
    font_family = JetBrainsMono Nerd Font
    position = 0, 160
    halign = center
    valign = center
}}

label {{
    monitor =
    text = cmd[update:60000] date +"%A, %B %-d"
    color = {rgba(c['subtext'])}
    font_size = 20
    font_family = JetBrainsMono Nerd Font
    position = 0, 60
    halign = center
    valign = center
}}

# the chamfered box (drawn by starchaser theme) sits behind the transparent field
image {{
    monitor =
    path = {field_png}
    size = {fh}   # hyprlock scales the image's shorter side (height) to this
    rounding = 0
    border_size = 0
    position = 0, -60
    halign = center
    valign = center
    zindex = 0
}}

input-field {{
    monitor =
    size = {fw}, {fh}
    outline_thickness = 0
    rounding = 0
    outer_color = rgba(0, 0, 0, 0)
    inner_color = rgba(0, 0, 0, 0)
    zindex = 1
    font_color = {rgba(c['text'])}
    check_color = {rgba(c['accent2'])}
    fail_color = {rgba(c['error'])}
    # hyprlang reads # as a comment; ## is a literal # (a single # here broke the placeholder)
    placeholder_text = <span foreground="##{bare(th['hint'])}">Password</span>
    fade_on_empty = false
    position = 0, -60
    halign = center
    valign = center
}}
"""
    write(f, body)
    return f"lock   {f}"


def gtk3_theme(variant: str) -> str:
    """The GTK3 theme for dark/light: adw-gtk3 (installed by the desktop setup) looks like the GTK4 apps; without it,
    GTK3's built-in Adwaita (which ignores color-scheme, so the dark one has to be named)."""
    dirs = [HOME / ".themes", HOME / ".local/share/themes", Path("/usr/share/themes")]
    if any((d / "adw-gtk3").is_dir() for d in dirs):
        return "adw-gtk3-dark" if variant == "dark" else "adw-gtk3"
    return "Adwaita-dark" if variant == "dark" else "Adwaita"


ICON_MANAGED = {"", "Adwaita", "AdwaitaLegacy", "hicolor", "Papirus", "Papirus-Dark", "Papirus-Light"}


def icon_theme_for(variant: str, current: str) -> str | None:
    """The icon theme that matches dark or light (Papirus-Dark has light artwork for dark windows, Papirus has dark
    artwork for light ones), so the file manager's Home and Recent icons stay readable after a switch. None when
    the icon theme is not installed, or when the person chose their own icon theme (it is left alone)."""
    if current.strip("'\" ") not in ICON_MANAGED:
        return None
    want = "Papirus-Dark" if variant == "dark" else "Papirus"
    dirs = [HOME / ".icons", HOME / ".local/share/icons", Path("/usr/share/icons")]
    return want if any((d / want / "index.theme").exists() for d in dirs) else None


def ini_set(path: Path, section: str, values: dict) -> bool:
    """Set keys in one [section] of an ini file, keeping every other line (and the user's own settings) as it is.
    A value of None removes that key. Returns True if the file changed."""
    if path.is_symlink():                               # a linked file (dotfiles): edit what it points to
        path = path.resolve()
    old = path.read_text(errors="replace") if path.exists() else ""
    lines, out, i, todo = old.splitlines(), [], 0, dict(values)
    head = f"[{section}]"
    while i < len(lines):
        out.append(lines[i])
        if lines[i].strip() == head:
            i += 1
            while i < len(lines) and not lines[i].strip().startswith("["):
                k = lines[i].split("=", 1)[0].strip()
                if "=" in lines[i] and k in todo:
                    val = todo.pop(k)
                    if val is not None:
                        out.append(f"{k}={val}")
                else:
                    out.append(lines[i])
                i += 1
            while out and not out[-1].strip():          # new keys go right after the section's last setting
                out.pop()
            out += [f"{k}={v}" for k, v in todo.items() if v is not None]
            todo = {}
            if i < len(lines):
                out.append("")
            continue
        i += 1
    todo = {k: v for k, v in todo.items() if v is not None}
    if todo:                                            # no such section yet
        if out and out[-1].strip():
            out.append("")
        out += [head] + [f"{k}={v}" for k, v in todo.items()]
    new = "\n".join(out) + "\n"
    if new != old:
        write(path, new)
        return True
    return False


def own_print_backends(path: Path) -> bool:
    """Whether a GTK settings.ini already chooses its print dialog's list (set by hand, or by us before)."""
    try:
        return any(ln.split("=", 1)[0].strip() == "gtk-print-backends" and "=" in ln
                   for ln in path.read_text(errors="replace").splitlines())
    except OSError:
        return False


def session_bus() -> bool:
    if os.environ.get("DBUS_SESSION_BUS_ADDRESS"):
        return True
    rt = os.environ.get("XDG_RUNTIME_DIR")
    return bool(rt) and Path(rt, "bus").exists()


HC_BEGIN = "/* BEGIN starchaser-focus-ring (written by starchaser-theme; the rest of this file is yours) */"
HC_END = "/* END starchaser-focus-ring */"


COLORS_BEGIN = "/* BEGIN starchaser-app-colors (written by starchaser-theme; the rest of this file is yours) */"
COLORS_END = "/* END starchaser-app-colors */"


def gtk_color_sheet(th: dict) -> str:
    """The desktop palette as GTK named colors, so a GTK app follows the theme and not only light or dark (the
    Calculator kept its gray and blue on every theme: fpreimp-look P2-5). The libadwaita names are read by GTK4 apps
    and, through adw-gtk3, by GTK3 ones; the theme_* names are the stock GTK3 theme's own."""
    c = th["colors"]
    on_accent = c["bg"] if contrast(c["bg"], c["accent"]) >= contrast(c["text"], c["accent"]) else c["text"]
    names = {"accent_bg_color": c["accent"], "accent_fg_color": on_accent, "accent_color": th["ink"]["accent"],
             "destructive_bg_color": c["error"], "destructive_fg_color": c["bg"], "destructive_color": th["ink"]["error"],
             "success_bg_color": c["success"], "success_fg_color": c["bg"], "success_color": th["ink"]["success"],
             "warning_bg_color": c["warning"], "warning_fg_color": c["bg"], "warning_color": th["ink"]["warning"],
             "error_bg_color": c["error"], "error_fg_color": c["bg"], "error_color": th["ink"]["error"],
             "window_bg_color": c["bg"], "window_fg_color": c["text"], "view_bg_color": c["bg_alt"], "view_fg_color": c["text"],
             "headerbar_bg_color": c["surface"], "headerbar_fg_color": c["text"], "headerbar_border_color": c["border"],
             "sidebar_bg_color": c["surface"], "sidebar_fg_color": c["text"],
             "card_bg_color": c["surface"], "card_fg_color": c["text"],
             "popover_bg_color": c["surface_hi"], "popover_fg_color": c["text"], "dialog_bg_color": c["bg"], "dialog_fg_color": c["text"],
             "theme_bg_color": c["bg"], "theme_fg_color": c["text"], "theme_base_color": c["bg_alt"], "theme_text_color": c["text"],
             "theme_selected_bg_color": c["accent"], "theme_selected_fg_color": on_accent}
    return "\n".join(f"@define-color {k} {v};" for k, v in names.items())


def gtk4_live_sheet(th: dict) -> str:
    """The same colors for GTK4 with both of the theme's palettes, each inside its prefers-color-scheme query: libadwaita
    switches between them while an app is open, so a dark/light switch reaches open apps and not only ones started
    later. The plain block first stays as the answer for a GTK4 without the query. A theme with one palette gets the
    plain block alone."""
    plain = gtk_color_sheet(th)
    out = [plain]
    pair = {}
    for variant in ("dark", "light"):
        try:
            pair[variant] = th if th["variant"] == variant else resolve(th["id"], variant)
        except (SystemExit, KeyError, OSError):
            return plain
    for variant in ("dark", "light"):
        body = gtk_color_sheet(pair[variant]).replace("\n", "\n    ")
        out.append(f"@media (prefers-color-scheme: {variant}) {{\n    {body}\n}}")
    return "\n".join(out)


def focus_block(f: Path, body: str | None, begin: str = HC_BEGIN, end: str = HC_END) -> None:
    """Put a rule block (the focus ring, or the app colors) in f between its markers, in place when it is already
    there, or take the block out when body is None. The file's own content stays, and a file that holds nothing
    else is not created just to be left empty."""
    old = f.read_text(errors="replace") if f.exists() else ""
    a, b = old.find(begin), old.find(end)
    has = 0 <= a < b
    block = None if body is None else f"{begin}\n{body}\n{end}"
    if has and block is not None:
        new = old[:a] + block + old[b + len(end):]
    elif has:
        new = (old[:a].rstrip("\n") + "\n" + old[b + len(end):].lstrip("\n")).strip("\n")
        new = new + "\n" if new else ""
    elif block is not None:
        new = (old.rstrip("\n") + "\n\n" if old.strip() else "") + block + "\n"
    else:
        return
    if new != old:
        write(f, new)


def e_gtk(th):
    v = th["variant"]
    a11y = accessibility.read()
    # high contrast keeps dark or light: GTK3's HighContrastInverse is its dark one (bright text on black), so a
    # dark desktop's file manager doesn't turn white
    gtheme = ("HighContrastInverse" if v == "dark" else "HighContrast") if a11y["high_contrast"] else gtk3_theme(v)
    # nearest GNOME accent to our accent hue
    h, _, s = colorsys.rgb_to_hls(*rgb(th["colors"]["accent"]))
    hue = h * 360
    names = [(0, "red"), (25, "orange"), (50, "yellow"), (130, "green"), (180, "teal"),
             (215, "blue"), (275, "purple"), (325, "pink"), (360, "red")]
    accent = "slate" if s < 0.2 else min(names, key=lambda n: abs(n[0] - hue))[1]
    sets = [("color-scheme", "prefer-dark" if v == "dark" else "prefer-light"),
            ("gtk-theme", gtheme), ("accent-color", accent), ("text-scaling-factor", str(a11y["text_scale"]))]
    # the shared high-contrast switch only in light mode: GTK3 apps that read settings directly (the file manager)
    # swap any theme for the light HighContrast while it is on, and the file manager opened white on a dark desktop
    # (QA 20261106-1617). In dark mode HighContrastInverse alone carries it; libadwaita apps stay dark. Set here, on
    # every apply, so a dark/light switch keeps it right
    contrast = bool(a11y["high_contrast"]) and v != "dark"
    if session_bus():
        cur = run("gsettings", "get", "org.gnome.desktop.interface", "icon-theme")
    elif shutil.which("dbus-run-session") and shutil.which("gsettings"):
        # no session yet: read the saved choice through a short-lived bus, so a custom icon theme is still left alone
        cur = run("dbus-run-session", "--", "gsettings", "get", "org.gnome.desktop.interface", "icon-theme")
    else:
        cur = None
    icons = icon_theme_for(v, cur.stdout.strip() if cur and cur.returncode == 0 else "")
    if icons:
        sets.append(("icon-theme", icons))
    # Commit the window theme and its icons together. Separate gsettings processes briefly leave light icons
    # on light windows (or dark icons on dark windows) while the remaining settings are still being applied.
    script = """import json, sys
from gi.repository import Gio
settings = Gio.Settings.new('org.gnome.desktop.interface')
settings.delay()
for key, value in json.loads(sys.argv[1]):
    ok = settings.set_double(key, float(value)) if key == 'text-scaling-factor' else settings.set_string(key, value)
    if not ok:
        settings.revert()
        sys.exit(1)
settings.apply()
contrast = Gio.Settings.new('org.gnome.desktop.a11y.interface')
if not contrast.set_boolean('high-contrast', sys.argv[2] == 'true'):
    sys.exit(1)
Gio.Settings.sync()
"""
    command = ("python3", "-c", script, json.dumps(sets), "true" if contrast else "false")
    if session_bus():
        r = run(*command)
        ok = bool(r and r.returncode == 0)
    elif os.environ.get("STARCHASER_FLEET_APPLY") == "1":
        raise OSError("The desktop session bus isn't available.")
    elif shutil.which("dbus-run-session") and shutil.which("gsettings"):
        # no session yet (the installer, before the first login): without a bus gsettings only changes a copy in
        # memory and the setting is lost, so give it a short-lived bus that saves to the user's settings file
        r = run("dbus-run-session", "--", *command)
        ok = bool(r and r.returncode == 0)
    else:
        ok = False
    # GTK3 apps (the file manager) also read this file; it's what they use where the settings above aren't set.
    # The theme name alone carries dark or light. gtk-application-prefer-dark-theme is removed, not set: GTK3 reads
    # it once at start and keeps it, so a file manager opened in dark stayed dark after a switch to light
    ini_vals = {"gtk-theme-name": gtheme, "gtk-application-prefer-dark-theme": None,
                "gtk-xft-dpi": str(round(96 * 1024 * a11y["text_scale"]))}
    ini_file = CONFIG / "gtk-3.0/settings.ini"
    cur_ini = ""
    if ini_file.exists():
        for ln in ini_file.read_text(errors="replace").splitlines():
            if ln.split("=", 1)[0].strip() == "gtk-icon-theme-name" and "=" in ln:
                cur_ini = ln.split("=", 1)[1].strip()
    # the print dialog lists printers and Print to File only: its "Print to LPR" was picked first on a computer with
    # no printer, and Print then did nothing, with no message (QA 2026-11-03). GTK3 (the portal's dialog) reads
    # gtk-3.0/settings.ini and GTK4 apps (the Document Viewer) gtk-4.0/settings.ini. A list set by hand stays. The same
    # list is in /etc/xdg (system/etc/xdg), for a portal that starts before this writes the account's file
    if not own_print_backends(ini_file):
        ini_vals["gtk-print-backends"] = "file,cups"
    ini_icons = icon_theme_for(v, cur_ini)
    if ini_icons:
        ini_vals["gtk-icon-theme-name"] = ini_icons
    ini = ini_set(ini_file, "Settings", ini_vals)
    ini4 = CONFIG / "gtk-4.0/settings.ini"
    if not own_print_backends(ini4):
        ini = ini_set(ini4, "Settings", {"gtk-print-backends": "file,cups"}) or ini
    # the stock high-contrast themes mark keyboard focus with a thin gray dotted line (QA 20261109-2303 004): while
    # high contrast is on, a thick bright outline goes in a block of its own in both gtk.css files, the rest of
    # each file left as it is; off, the block goes again
    ring = "#ffff00" if v == "dark" else "#0000ff"
    focus_css = (f"button:focus, entry:focus, row:focus, switch:focus, checkbutton:focus, radiobutton:focus, "
                 f"spinbutton:focus, combobox:focus, scale:focus, notebook tab:focus, treeview:focus {{\n"
                 f"    outline: 3px solid {ring}; outline-offset: 1px; outline-style: solid; }}") if a11y["high_contrast"] else None
    for gtk_dir in ("gtk-3.0", "gtk-4.0"):
        focus_block(CONFIG / gtk_dir / "gtk.css", focus_css)
    note = ""
    css = CONFIG / "gtk-4.0/gtk.css"
    own_colors = css.exists() and "colors.css" in css.read_text()
    if own_colors:
        note = ", your own gtk-4.0/gtk.css left as it is"
    else:
        # the palette as GTK colors; high contrast keeps the stock high-contrast colors, so the block goes while it is on
        sheet = None if a11y["high_contrast"] else gtk_color_sheet(th)
        for gtk_dir in ("gtk-3.0", "gtk-4.0"):
            body = gtk4_live_sheet(th) if sheet is not None and gtk_dir == "gtk-4.0" else sheet
            focus_block(CONFIG / gtk_dir / "gtk.css", body, COLORS_BEGIN, COLORS_END)
    return (f"gtk    color-scheme {v}, {gtheme}, accent {accent}" + (f", icons {icons}" if icons else "") + ("" if ok else " (gsettings failed)")
            + (", settings.ini updated" if ini else "") + note)


# the block's markers name what it is for, the on-screen keyboard, not the program (another project's name, read by
# anyone who opens the file). Blocks an older version wrote under the old markers are replaced the same way
SQ_BEGIN = "/* BEGIN starchaser-onscreen-keyboard (written by starchaser-theme; the rest of this file is yours) */"
SQ_END = "/* END starchaser-onscreen-keyboard */"
SQ_OLD = ("/* BEGIN starchaser-squeekboard (written by starchaser-theme; the rest of this file is yours) */",
          "/* END starchaser-squeekboard */")


def e_qt(th):
    """Native Qt windows use the current theme's palette in both light and dark mode."""
    c = th["colors"]
    # Qt Quick's Basic folder picker blends Highlight into Light or Midlight.
    # Keep normal ink on a tinted surface so both blended and solid selections read clearly.
    highlight = mix(c["surface"], c["accent"], 0.25)
    # QPalette color-role order, including NoRole (17), PlaceholderText (20), and Accent (21).
    # Qt 5 reads the first 21 entries; Qt 6.6 and later also read Accent.
    active = [c["text"], c["surface"], mix(c["surface"], c["text"], 0.2), c["surface_hi"],
              c["bg_alt"], c["border"], c["text"], c["text"], c["text"], c["bg_alt"],
              c["bg"], c["bg_alt"], highlight, c["text"], c["accent2"], c["accent3"],
              c["surface"], c["bg"], c["surface_hi"], c["text"], c["subtext"], c["accent"]]
    disabled = list(active)
    for role in (0, 6, 8, 13, 19, 20):
        disabled[role] = c["muted"]
    palette = "[ColorScheme]\n" + "".join(
        key + "=" + ", ".join("#ff" + bare(color) for color in colors) + "\n"
        for key, colors in (("active_colors", active), ("inactive_colors", active), ("disabled_colors", disabled)))
    for tool in ("qt6ct", "qt5ct"):
        scheme = CONFIG / tool / "colors/starchaser.conf"
        write(scheme, palette)
        settings = CONFIG / tool / (tool + ".conf")
        a11y = accessibility.read()
        if "qt_fonts" in a11y:
            fonts = dict(a11y["qt_fonts"].get(tool, {}))
            for role, fallback in (("general", "Sans Serif,10,-1,5,50,0,0,0,0,0"), ("fixed", "Monospace,10,-1,5,50,0,0,0,0,0")):
                original = fonts.get(role, fallback).strip('"')
                parts = original.split(',')
                if len(parts) > 1:
                    parts[1] = str(float(parts[1]) * a11y["text_scale"])
                    fonts[role] = '"' + ','.join(parts) + '"'
            if a11y["text_scale"] == 1:
                fonts = {"general": None, "fixed": None, **a11y["qt_fonts"].get(tool, {})}
            ini_set(settings, "Fonts", fonts)
        if not ini_set(settings, "Appearance",
                       {"style": "Fusion", "custom_palette": "true", "color_scheme_path": str(scheme), "standard_dialogs": "xdgdesktopportal"}):
            # qt6ct watches its config directory, not colors/: replacing the unchanged settings file
            # tells running apps to read the freshly written palette after a mode or color change.
            write(settings, settings.read_text())
    return f"qt     palette written for qt6ct/qt5ct ({th['variant']})"


def e_squeekboard(th):
    """The on-screen keyboard (squeekboard, GTK3): colors from the theme via the user GTK3 stylesheet,
    which outranks squeekboard's built-in style. Restarted if running (GTK3 reads gtk.css at start)."""
    c = th["colors"]
    f = CONFIG / "gtk-3.0/gtk.css"
    block = f"""{SQ_BEGIN}
sq_view {{ background-color: alpha({c['bg']}, 0.94); font-family: "JetBrainsMono Nerd Font", sans-serif; font-size: 0.95em;
           box-shadow: inset 0 1px 0 0 alpha({c['accent']}, 0.55); }}
sq_button {{ color: {c['text']}; background: {c['surface']}; border-radius: 3px; margin: 2px;
             border: 1px solid alpha({c['border']}, 0.6); box-shadow: none; }}
sq_button:active {{ background: {c['accent']}; color: {c['bg']}; }}
sq_button.action, sq_button.subtle-highlight, sq_button.subtle-highlight-2,
sq_button.change-view, sq_button.change-view-2, sq_button.change-view-3,
sq_button.emoji-group, sq_button.character-group {{ background: {c['surface_hi']}; color: {c['subtext']};
             border: 1px solid alpha({c['border']}, 0.8); }}
sq_button.latched, sq_button.locked {{ background: {c['accent']}; color: {c['bg']}; }}
sq_view.wide {{ font-size: 0.95em; }}
sq_button.action {{ font-size: 0.8em; }}
sq_button.action:active, sq_button.change-view:active, sq_button.subtle-highlight:active {{ background: {c['accent']}; color: {c['bg']}; }}
{SQ_END}
"""
    old = f.read_text() if f.exists() else ""
    new = old
    if SQ_BEGIN not in new and SQ_OLD[0] in new and SQ_OLD[1] in new:     # an older version's block: renamed in place
        new = new.replace(SQ_OLD[0], SQ_BEGIN, 1).replace(SQ_OLD[1], SQ_END, 1)
    a, b = new.find(SQ_BEGIN), new.find(SQ_END)
    if 0 <= a < b:
        new = new[:a] + block.rstrip("\n") + new[b + len(SQ_END):]
    else:
        new = (new.rstrip("\n") + "\n\n" if new.strip() else "") + block
    if new != old:
        write(f, new)
    restarted = ""
    if os.environ.get("STARCHASER_FLEET_APPLY") != "1" and run("pgrep", "-x", "squeekboard") and run("pgrep", "-x", "squeekboard").returncode == 0 and new != old:
        run("pkill", "-x", "squeekboard")
        run("hyprctl", "dispatch", 'hl.dsp.exec_cmd("squeekboard")')
        restarted = ", restarted"
    return f"osk    on-screen keyboard colors in {f}{restarted}"


# Flea (packages/flea) reads its colors, text size and transparency from here (its starchaser-paths.patch), in the
# colors.toml and shell.toml shapes it was written for. It watches these folders, so an open window follows at once.
FLEA_DIR = HOME / ".local/state/starchaser/flea"
FLEA_TOGGLES = STATE_DIR / "flea/toggles/hypr"
FLEA_BASE_PX = 13       # Starchaser's body text (Theme.qml fsBody) at 100%


def e_flea(th):
    c, term = th["colors"], th["term"]
    pairs = {"background": c["bg"], "foreground": c["text"], "accent": c["accent"], "cursor": c["accent"],
             "selection_background": c["selection"], "selection_foreground": c["text"],
             "dark_background": c["surface"], "red": th["ink"]["error"], "green": th["ink"]["success"],
             "yellow": th["ink"]["warning"], "blue": th["ink"]["info"], "magenta": th["ink"]["accent2"],
             "cyan": th["ink"]["accent3"]}
    pairs.update({f"color{i}": x for i, x in enumerate(term)})
    lines = [f"# {MANAGED}: {th['name']} ({th['variant']})"] + [f'{k} = "{v}"' for k, v in pairs.items()]
    write(FLEA_DIR / "current/theme/colors.toml", "\n".join(lines) + "\n")
    size = round(FLEA_BASE_PX * accessibility.read()["text_scale"])
    write(FLEA_DIR / "shell.toml", f"# {MANAGED}: Settings > Accessibility > Text size\n[font]\nbase-size = {size}\n")
    # Flea draws see-through unless this file exists; Starchaser windows are opaque and the look's fade applies
    write(FLEA_TOGGLES / "window-opaque.lua", f"-- {MANAGED}: Files' window is opaque\n")
    return f"flea   colors and {size} px text in {FLEA_DIR}"


def e_wallpaper(th):
    saved = read_state() or {}                        # e_state kept the user's wallpaper choice in the state file
    if saved.get("wallpaper_mode") == "own":         # the user's own wallpaper: keep it (in this theme's dark/light)
        now = saved.get("wallpaper_now") or {}
        if now.get("picture") and Path(now["picture"]).is_file():
            return "wall   your picture, unchanged"
        if now.get("set") in wall_index():
            v = th["variant"] if th["variant"] in wall_index()[now["set"]] else now.get("variant", "dark")
            if v == now.get("variant"):
                return f"wall   your {now['set']} ({v}), unchanged"
            return "wall   your " + set_wallpaper(now["set"], v)
        # your own set's pictures are gone: the wallpaper follows the theme again (set_wallpaper below would
        # otherwise save the theme's set as your own pick, and every later theme would keep it)
        set_mode("theme")
        if th["wallpaper"] not in wall_index():
            return f"wall   your {now.get('set') or 'wallpaper'} is gone, so it follows the theme again; no '{th['wallpaper']}' wallpapers yet"
        return f"wall   your {now.get('set') or 'wallpaper'} is gone, so it follows the theme again: " + set_wallpaper(th["wallpaper"], th["variant"])
    if th["wallpaper"] not in wall_index():
        return f"wall   no '{th['wallpaper']}' wallpapers yet; wallpaper unchanged"
    return "wall   " + set_wallpaper(th["wallpaper"], th["variant"])


def e_tools(th):
    return app_themes.tools(th, CONFIG, write)


def e_agents(th):
    return app_themes.agents(th, HOME, CONFIG, write)


def e_templates(th):
    return app_themes.templates(th, HOME, CONFIG, write)


BROWSER_PREFERENCE = Path('/etc/brave/starchaser-tint.json')
BROWSER_POLICIES = (Path('/etc/brave/policies/managed/starchaser-color.json'),
                    Path('/etc/chromium/policies/managed/starchaser-color.json'),
                    Path('/var/lib/flatpak/extension/io.github.ungoogled_software.ungoogled_chromium.Policy.starchaser/x86_64/1/policies/managed/starchaser-color.json'))


def browser_enabled():
    try:
        data = json.loads(BROWSER_PREFERENCE.read_text())
        return isinstance(data, dict) and data.get('enabled') is True
    except (OSError, ValueError):
        return False


def browser_policy(color):
    helper = "/usr/local/lib/starchaser/starchaser-browser-theme"
    if not Path(helper).is_file():
        raise OSError("The browser color helper isn't installed yet.")
    result = run("pkexec", "--disable-internal-agent", helper, color)
    if result is None or result.returncode:
        raise OSError("The browser color helper couldn't save the color.")
    # Refresh policy in existing browser processes; the option never opens a new window.
    processes = run("ps", "-u", str(os.getuid()), "-o", "comm=")
    running = set(processes.stdout.split()) if processes and processes.returncode == 0 else set()
    for command in ("brave-origin", "brave", "chromium", "ungoogled-chromium"):
        process = "brave" if command.startswith("brave") else "chromium"
        if process in running and shutil.which(command):
            subprocess.Popen([command, "--refresh-platform-policy", "--no-startup-window"],
                             stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                             start_new_session=True)
    flatpaks = run("flatpak", "ps", "--columns=application")
    app_id = "io.github.ungoogled_software.ungoogled_chromium"
    if flatpaks and app_id in flatpaks.stdout.split():
        subprocess.Popen(["flatpak", "run", app_id, "--refresh-platform-policy", "--no-startup-window"],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)


def e_browser(th):
    # Recheck the computer-wide switch: another account may have turned it off
    # after this process started, including while a background apply waited.
    if not browser_enabled():
        return e_browser_cleanup(th)
    browser_policy(bare(mix(th["colors"]["bg"], th["colors"]["accent"], 0.18)).lower())
    return "browser desktop color"


def e_browser_cleanup(th):
    if browser_enabled():
        return e_browser(th)
    # Remove policies from the earlier always-on implementation on first apply.
    # A fresh install never invokes the privileged helper while tint is off.
    if any(p.exists() or p.is_symlink() for p in BROWSER_POLICIES):
        browser_policy('off')
    return "browser tint off"


BROWSER_ASKED = CONFIG / "starchaser/browser-color-asked"     # this account answered "Color the browser too?"


def browser_command(args):
    if args not in ([], ['on'], ['off'], ['asked']):
        usage("Usage: starchaser theme browser [on|off|asked]")
    if args == ['asked']:
        write(BROWSER_ASKED, "asked\n")
    elif args:
        lock_writers()
        if args == ['off']:
            browser_policy('off')
        else:
            th = read_state()
            if not has_theme(th):
                th = resolve(DEFAULT_THEME, 'dark', 'auto')
            browser_policy(bare(mix(th['colors']['bg'], th['colors']['accent'], 0.18)).lower())
    print(json.dumps({'enabled': browser_enabled(), 'asked': BROWSER_ASKED.exists()}))


def theme_previews(file):
    folder = file.with_suffix("")
    dark, light = folder / "preview.png", folder / "preview-light.png"
    return {v: str(p) for v, p in (("dark", dark), ("light", light if light.is_file() else dark)) if p.is_file()}


# e_hyprland before e_look: e_look reloads Hyprland, and a user.lua that dofile()s scheme/current.lua must get the new colors
EMITTERS = [e_state, e_kitty, e_xfceterm, e_hyprland, e_look, e_litexl, e_gtksourceview, e_hyprlock, e_gtk, e_qt, e_flea, e_squeekboard, e_wallpaper, e_tools, e_agents, e_templates]


BACKGROUND_EMITTERS = [e_litexl, e_gtksourceview, e_hyprlock, e_squeekboard, e_tools, e_agents, e_templates]
for emitters in (EMITTERS, BACKGROUND_EMITTERS):
    emitters.append(e_browser if browser_enabled() else e_browser_cleanup)


# what each emitter colors, in the words a person uses (the failure notice names these)
PARTS = {"state": "the taskbar and menus", "kitty": "the terminal", "xfceterm": "the terminal for the screen reader",
         "hyprland": "your own window settings file",
         "look": "window borders and effects", "litexl": "the code editor", "gtksourceview": "the text editor",
         "hyprlock": "the lock screen",
         "tools": "terminal tools", "agents": "coding agents", "templates": "your app templates", "browser": "the browser",
         "browser_cleanup": "the browser",
         "gtk": "app windows", "qt": "native app windows", "flea": "Files", "squeekboard": "the on-screen keyboard", "wallpaper": "the wallpaper"}


def notify(summary: str, body: str) -> None:
    """One desktop notification (the commands Settings, the welcome and the menu run throw their output away, so a
    failure printed only here would go unseen). Nothing without a desktop session."""
    if os.environ.get("STARCHASER_FLEET_APPLY") == "1":
        print(summary + ": " + body, file=sys.stderr)
        return
    if not (os.environ.get("WAYLAND_DISPLAY") or os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")):
        return
    try:
        run(*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", "preferences-desktop-theme", summary, body)
    except (OSError, subprocess.SubprocessError):
        pass


def plain_refusal(msg: str) -> str:
    """A refused apply, for the notification: a theme file with a mistake in it is named by its theme and file name
    ("The brk theme's file has a mistake ...") instead of opening with its full path; the file's own detail follows
    for whoever wrote it. Other refusals ("comes only in a dark version", "no theme 'x'") are already plain."""
    # the theme folders first, so a file name with a space in it ("my theme.toml") is read whole
    m = None
    for d in THEME_DIRS:
        m = re.search(re.escape(str(d) + "/") + r"([^/]+?)\.toml\b", msg)
        if m:
            break
    m = m or re.search(r"(?:/\S+/)?([^/\s]+)\.toml\b", msg)
    if not m:
        return msg
    name, fname = m.group(1), m.group(1) + ".toml"
    if " " in name:     # "The my theme theme's file" would read as a typo
        name, fname = f'"{name}"', f'"{fname}"'
    detail = (msg[:m.start()] + msg[m.end():]).strip(" :").rstrip(".")
    mine = THEME_DIRS[0]
    if m.group(0).startswith(str(mine) + "/"):
        where = str(mine).replace(str(HOME), "~", 1) if str(mine).startswith(str(HOME) + "/") else str(mine)
        head = f"The {name} theme's file has a mistake, so nothing was changed. Fix {fname} in {where}, or pick another theme."
    else:
        # a theme that came with Starchaser: not the person's to fix
        head = f"The {name} theme's file is damaged, so nothing was changed. Pick another theme."
    return head + (f" What's wrong: {detail}." if detail else "")


def plain_reason(ex: Exception) -> str:
    """Why one app's colors couldn't be written, in words a first-time user follows (the raw error stays in the
    command's own output)."""
    if isinstance(ex, PermissionError):
        return "its settings file couldn't be saved: this account isn't allowed to change it"
    if isinstance(ex, OSError) and ex.errno == errno.ENOSPC:
        return "its settings file couldn't be saved: the disk is full"
    if isinstance(ex, OSError):
        return "its settings file couldn't be saved"
    return "something went wrong while changing its colors"


def apply(tid: str, variant: str, look: str | None = None) -> None:
    if look is None:
        st = read_state()
        look = st["look"]["name"] if st and isinstance(st.get("look"), dict) else "auto"
    th = resolve(tid, variant, look)
    print(f"{th['name']} ({variant}), look {th['look']['profile']}" + (" (auto)" if look == "auto" else ""), file=LINES[0])
    strict = os.environ.get("STARCHASER_ACCESSIBILITY_APPLY") == "1"
    desktop = os.environ.get("WAYLAND_DISPLAY") or os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")
    if desktop and not strict and os.environ.get("STARCHASER_FLEET_APPLY") != "1":
        th["apply_token"] = str(time.time_ns())
        run_emitters(th, [e for e in EMITTERS if e not in BACKGROUND_EMITTERS])
        # The worker reads the committed palette under the same writer lock. An obsolete request does nothing.
        subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "finish-colors", th["apply_token"]],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    else:
        run_emitters(th, EMITTERS, strict=strict)
    satellite_hook("theme-changed", STARCHASER_THEME=tid, STARCHASER_THEME_MODE=variant)


def satellite_hook(event: str, **details: str) -> None:
    """Tell enabled satellites (their hooks/<event> scripts). Best-effort and never waited for: the runner is
    started in a session of its own and left to it, so a slow folder or a broken satellite never holds up or
    fails the theme change."""
    tool = Path(__file__).resolve().parent / "starchaser-satellite"
    if not tool.is_file():
        return
    try:
        subprocess.Popen([str(tool), "hook", event, *(f"{k}={v}" for k, v in details.items())],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    except (OSError, subprocess.SubprocessError):
        pass


# where the emitters' progress lines go: stdout, or stderr for the commands whose stdout is one JSON answer
LINES = [sys.stdout]


def run_emitters(th: dict, emitters: list, strict: bool = False) -> None:
    """Each emitter in turn; one broken app never stops the rest, and a failure is shown as a notification."""
    failed = []
    for e in emitters:
        try:
            line = e(th)
            print("  " + line, file=LINES[0])
            if (strict or os.environ.get("STARCHASER_FLEET_APPLY") == "1") and "(gsettings failed)" in line:
                failed.append("app window colors could not be applied")
            if line.endswith("(reload failed)"):
                failed.append("window borders kept the old colors, because the window settings couldn't be "
                              "reloaded (a mistake in ~/.config/hypr/user.lua is the usual cause)")
        except Exception as ex:  # one broken app must not stop the rest
            print(f"  {e.__name__[2:]:<6} FAILED: {ex}", file=LINES[0])
            failed.append(PARTS.get(e.__name__[2:], e.__name__[2:]) + f" didn't change ({plain_reason(ex)})")
    if failed:
        text = "; ".join(failed)
        if strict or os.environ.get("STARCHASER_FLEET_APPLY") == "1":
            raise OSError("The appearance couldn't be fully applied.")
        notify(f"{th['name']} is only partly applied", text[0].upper() + text[1:] + ". Picking the theme again tries once more.")


def theme_variant(tid: str, wanted: str) -> str:
    """The variant to apply when the person didn't name one: the current mode, or the theme's only version when it
    has just one (a dark-only theme of your own picked in Light mode)."""
    f = theme_files().get(tid)
    t = load_theme(f) if f else None
    if t is not None and wanted not in t:
        for v in ("dark", "light"):
            if isinstance(t.get(v), dict):
                return v
    return wanted


def refit_later() -> None:
    """The cockpit takes a moment to claim its new screen edge; then move floating windows out from under it."""
    subprocess.Popen([sys.executable, str(Path(__file__).resolve()), "refit-after"],
                     stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)


def gaps_out(option: str = "general:gaps_out", fallback: int = 10) -> int:
    """Hyprland's outer gap (hyprland.lua: 10): the room tiled windows keep from the cockpit frame."""
    try:
        o = json.loads(subprocess.run(["hyprctl", "getoption", option, "-j"],
                                      capture_output=True, text=True).stdout)
        for k in ("custom", "int", "str"):
            v = o.get(k)
            if isinstance(v, int):
                return max(0, v)
            if isinstance(v, str):
                m = re.match(r"\s*(\d+)", v)
                if m:
                    return int(m.group(1))
    except (ValueError, AttributeError, TypeError, OSError):
        pass
    return fallback


def refit_box(at, size, area, gap):
    """Where one floating window goes after the cockpit moves: None when it already sits inside the usable area
    with the outer gap to spare (a size and place the person chose are kept), else (w, h, shrunk, x, y): its size,
    smaller only when it no longer fits, and its place moved only as far as it takes to clear the reserved edge
    (so a window arranged by hand keeps its arrangement). `area` is the usable area (x, y, w, h)."""
    ux, uy, uw, uh = area
    x, y = at
    w, h = size
    fx, fy, fw, fh = ux + gap, uy + gap, max(1, uw - 2 * gap), max(1, uh - 2 * gap)
    if x >= fx and y >= fy and x + w <= fx + fw and y + h <= fy + fh:
        return None
    nw, nh = min(w, int(fw)), min(h, int(fh))
    nx = int(min(max(x, fx), fx + fw - nw))
    ny = int(min(max(y, fy), fy + fh - nh))
    return nw, nh, (nw, nh) != (w, h), nx, ny


def refit_floating() -> None:
    """Floating windows (Settings, the welcome, dialogs) stay where they were when the taskbar moves to another edge
    or the cockpit turns into the top bar, and end up under it or right against its frame line; tiled ones re-tile
    by themselves, with gaps_out to spare. A floating window that now reaches into a monitor's reserved edge, or
    into the gap beside it, is nudged just far enough to clear it, and shrunk first only if it is too big to fit
    there with the same gap. Windows that already fit are left alone. Size and place only; the pointer stays put."""
    try:
        mons = json.loads(subprocess.run(["hyprctl", "monitors", "-j"], capture_output=True, text=True).stdout)
        clients = json.loads(subprocess.run(["hyprctl", "clients", "-j"], capture_output=True, text=True).stdout)
    except ValueError:
        return
    # Hyprland draws the border outside the window, so the gap counts it too (else the border sits in the gap)
    # and the cockpit frame's visible ring (about 12 px inside the reserved edge) so a window never ends on its inner line
    gap = gaps_out() + gaps_out("general:border_size", 2) + 12
    for c in clients:
        if not c.get("floating") or c.get("fullscreen") or c.get("pinned"):
            continue
        m = next((m for m in mons if m["id"] == c.get("monitor")), None)
        if not m:
            continue
        sc = m.get("scale") or 1
        rot = (m.get("transform") or 0) % 2 == 1           # 90 or 270: the logical screen is turned
        lw, lh = (m["height"], m["width"]) if rot else (m["width"], m["height"])
        l, t, r, b = m.get("reserved", [0, 0, 0, 0])
        area = (m["x"] + l, m["y"] + t, lw / sc - l - r, lh / sc - t - b)
        fit = refit_box(c["at"], c["size"], area, gap)
        if not fit:
            continue
        sel = f'window = "address:{c["address"]}"'
        nw, nh, shrink, nx, ny = fit
        if shrink:
            subprocess.run(["hyprctl", "dispatch", f"hl.dsp.window.resize({{ x = {nw}, y = {nh}, {sel} }})"],
                           capture_output=True)
        subprocess.run(["hyprctl", "dispatch", f"hl.dsp.window.move({{ x = {nx}, y = {ny}, {sel} }})"],
                       capture_output=True)


def usage(msg: str = __doc__) -> None:
    """Bad usage: the message on stderr and exit 2, like the other starchaser tools (1 is kept for real failures)."""
    print(msg, file=sys.stderr)
    sys.exit(2)


WRITERS = {"apply", "toggle", "mode", "reapply", "set", "unset", "reset", "undo", "save", "rename", "delete"}
# a bare "look" only prints; "look NAME" writes (below)
JSON_ANSWER = {"set", "unset", "reset", "undo", "save", "rename", "delete"}   # stdout is one JSON line


def cockpit_hover_escape() -> None:
    """Own a consuming Escape bind while stdin says on; the shell's pipe is the lifetime lease."""
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    from starchaser_bind_lease import lease
    lease("starchaser_today_escape", "Escape", "starchaser-today:dismiss", "Close Today opened by hovering")


def data_command(argv: list) -> None:
    """Exact portable subsets; exports never set aside or repair unreadable settings."""
    sys.path.insert(0, str(Path(__file__).resolve().parent))
    import starchaser_settings_schema as schema

    def read(path, default):
        try:
            result = schema.loads(path.read_bytes(), limit=4 * 1024 * 1024)
        except FileNotFoundError:
            return default
        schema.require(isinstance(result, dict))
        return result

    def overrides():
        ov = read(OVERRIDES, empty_overrides())
        schema.require(isinstance(ov.get("look", {}), dict) and isinstance(ov.get("colors", {}), dict))
        for key, value in ov.get("look", {}).items():
            schema.require(coerce(key, value) == value)
        for variants in ov.get("colors", {}).values():
            schema.require(isinstance(variants, dict))
            for variant, roles in variants.items():
                schema.require(variant in ("dark", "light") and isinstance(roles, dict))
                for role, value in roles.items():
                    schema.require(coerce("colors." + role, value) == value)
        return {**empty_overrides(), **ov}

    def bundled(data):
        tid, variant = data["theme"], data["variant"]
        selected = theme_files().get(tid)
        roots = (SYSTEM_THEME_DIR, Path(__file__).resolve().parent.parent / "themes")
        if selected is None or not any(selected.resolve() == (root / (tid + ".toml")).resolve() for root in roots):
            raise FileNotFoundError("The bundled appearance isn't installed here.")
        t = tomllib.loads(selected.read_text())
        if variant not in t:
            raise FileNotFoundError("This appearance version isn't installed here.")
        if theme_problem(t, selected, variant) or theme_problem(t, selected):
            raise ValueError("The bundled appearance can't be read.")

    if len(argv) not in (2, 3) or argv[0] not in ("export", "apply", "check") or argv[1] not in ("look", "clock-bar"):
        bad("Choose look or clock-bar. Use data export look|clock-bar, data apply look|clock-bar --stdin, "
            "or data check look|clock-bar --stdin. To check a file without changing settings: "
            "starchaser theme data check look --stdin < settings.json.")
    action, category = argv[:2]
    if (action == "export" and len(argv) != 2) or (action != "export" and argv[2:] != ["--stdin"]):
        bad("Use --stdin when applying or checking settings.")
    LINES[0] = sys.stderr
    incoming = None
    if action != "export":
        try:
            incoming = schema.loads(sys.stdin.buffer.read(schema.MAX_BYTES + 1))
        except ValueError:
            bad("The input is not valid settings JSON.", 1)
        try:
            schema.payload(category, incoming)
        except (ValueError, TypeError, KeyError):
            bad(f"The input has missing or invalid {category} settings. Start with starchaser theme data export {category}.", 1)
    try:
        if action == "apply":
            if category == "look":
                lock_writers()
            else:
                lock_cockpit()
            # settings from another computer: Settings > Recovery > Put my desktop back has the copy from before them
            desktop_copy.save("look" if category == "look" else "taskbar")
        st = read(STATE, {})
        if category == "look":
            ov = overrides()
            if incoming is None:
                tid, variant, look = active_theme(st)
                data = {"theme": tid, "variant": variant, "look": look,
                        "overrides": {k: v for k, v in ov["look"].items() if k in SETTINGS and not SETTINGS[k].get("personal")},
                        "colors": ov["colors"].get(tid, {}).get(variant, {})}
            else:
                data = incoming
            schema.payload(category, data)
            bundled(data)
            if action == "apply":
                ov["look"] = {k: v for k, v in ov["look"].items() if SETTINGS[k].get("personal")}
                ov["look"].update(data["overrides"])
                ov["colors"].setdefault(data["theme"], {})[data["variant"]] = data["colors"]
                th = resolve(data["theme"], data["variant"], data["look"], overrides=ov)
                # Clock format belongs to its own category, including the shell's state-file fallback.
                # Without a saved choice the clock uses the old theme's format (st), so keep that value too:
                # switching theme must never change what Clock and bar exports.
                th["clock24"] = st.get("clock24") is True
                write_overrides(ov)
                run_emitters(th, [e for e in EMITTERS if e is not e_wallpaper], strict=True)
        else:
            cfg = read(CONFIG / "starchaser/cockpit.json", {})
            if incoming is None:
                data = {"edge": cfg.get("edge", "left"), "mode": "bar" if cfg.get("mode") == "bar" else "cockpit",
                        "clock": "analog" if cfg.get("clockStyle") == "analog" else "digital",
                        "frame": cfg.get("frame", 6)}
                for key, stored in schema.CLOCK_MAP.items():
                    if key not in data:
                        default = key in ("hover", "apps", "dashboard")
                        if key == "clock24":
                            default = st.get("clock24") is True
                        data[key] = cfg.get(stored, default)
            else:
                data = incoming
            schema.payload(category, data)
            if action == "apply":
                cfg.update({schema.CLOCK_MAP[key]: value for key, value in data.items()})
                write(CONFIG / "starchaser/cockpit.json", json.dumps(cfg, indent=2) + "\n")
                refit_later()
        print(json.dumps(data if action == "export" else {"ok": True}, sort_keys=True))
    except FileNotFoundError:
        bad("This appearance is not installed here.", 3)
    except (OSError, ValueError, TypeError, KeyError):
        bad("The settings could not be read or fully applied.", 1)


def main(argv: list) -> None:
    if argv[:1] == ['browser']:
        browser_command(argv[1:])
        return
    if argv[:1] == ["finish-colors"]:
        if len(argv) != 2 or not argv[1].isdigit():
            usage("Usage: starchaser theme finish-colors <apply token>")
        lock_writers()
        th = read_state() or {}
        if th.get("apply_token") == argv[1]:
            run_emitters(th, BACKGROUND_EMITTERS)
        return
    if argv[:1] == ["data"]:
        data_command(argv[1:])
        return
    # This read-only helper must not take the cockpit settings writer lock for its whole lifetime.
    if argv == ["cockpit", "hover-escape"]:
        cockpit_hover_escape()
        return
    cmd = argv[0] if argv else "current"
    if cmd in ("current", "list") and argv[1:] not in ([], ["--json"]):
        sys.exit(usage_error("starchaser theme", f"{cmd} accepts only --json", f"{cmd} [--json]"))
    sub = argv[1] if len(argv) > 1 else "list"
    if cmd == "wallpaper" and sub == "list" and argv[2:] not in ([], ["--json"]):
        sys.exit(usage_error("starchaser theme", "wallpaper list accepts only --json", "wallpaper list [--json]"))
    # a typo after these must not flip the theme or restyle the desktop and still say it worked
    if cmd in ("toggle", "reapply") or (cmd == "wallpaper" and sub in ("follow", "restore", "thumbs", "next", "previous")):
        if cmd != "wallpaper" and len(argv) > 1:
            sys.exit(takes_nothing_after("starchaser theme", cmd, argv))
        if cmd == "wallpaper" and len(argv) > 2:
            sys.exit(takes_nothing_after("starchaser theme", f"wallpaper {sub}", argv[1:]))
    if cmd == "mode" and len(argv) > 2:
        sys.exit(usage_error("starchaser theme", f"mode takes one word after it (got {argv[2]!r})", "mode <dark|light>"))
    if cmd == "bar" and len(argv) > 2:
        sys.exit(usage_error("starchaser theme", f"bar takes one word after it (got {argv[2]!r})", "bar [left|right|top|bottom]"))
    if cmd == "look" and len(argv) > 1:
        if len(argv) != 2:
            usage("Usage: starchaser theme look [auto|glass-light|glass|clean|performance|--json]")
        if argv[1] not in ("auto", "--json") and argv[1] not in LOOKS:
            usage(f"starchaser theme: no look '{argv[1]}' (have: auto, {', '.join(LOOKS)})")
    if cmd in WRITERS or (cmd == "look" and len(argv) > 1 and argv[1] != "--json") or (cmd == "wallpaper" and sub not in ("list", "thumbs")):
        lock_writers()                       # before reading the state: toggle and apply depend on it
    if cmd in ("bar", "cockpit") and len(argv) > 1:
        lock_cockpit()                       # before reading cockpit.json: the write is read-change-write
    # Settings > Recovery > Put my desktop back: a copy of the desktop from before this change (at most one an hour)
    why = ("look" if cmd in ("apply", "toggle", "mode", "set", "unset", "reset", "undo")
           or (cmd == "look" and len(argv) > 1 and argv[1] != "--json")
           else "wallpaper" if cmd == "wallpaper" and sub not in ("list", "thumbs", "restore")
           else "taskbar" if cmd in ("bar", "cockpit") and len(argv) > 1 else "")
    if why:
        desktop_copy.save(why)
    if cmd in JSON_ANSWER:
        LINES[0] = sys.stderr
    st = read_state()
    if cmd in ("set", "unset"):
        cmd_set(argv[1:], unset=cmd == "unset")
    elif cmd == "reset":
        cmd_reset(argv[1:])
    elif cmd == "undo":
        if len(argv) != 1:
            usage("Usage: starchaser theme undo")
        cmd_undo()
    elif cmd == "save":
        cmd_save(argv[1:])
    elif cmd == "rename":
        cmd_rename(argv[1:])
    elif cmd == "export":
        cmd_export(argv[1:])
    elif cmd == "delete":
        cmd_delete(argv[1:])
    elif cmd == "overrides":
        if [a for a in argv[1:] if a != "--json"]:
            usage("Usage: starchaser theme overrides [--json]")
        report = overrides_report()
        if "--json" in argv:
            print(json.dumps(report))
        else:
            print(f"{report['theme_name']} ({report['variant']}), look {report['profile']}")
            if report["problem"]:
                print(f"! {report['problem']}")
            for r in report["settings"]:
                mark = "*" if r["changed"] else " "
                print(f"{mark} {r['key']:<24} {str(r['value']):<10} ({r['source']}; without your change: {r['default']})")
            for w in report["warnings"]:
                print(f"! {w['key']}: {w['text']}")
    elif cmd == "list":
        files = theme_files()
        walls = wall_index()
        rows = []
        for tid, f in files.items():
            t = load_theme(f)
            if t is None:
                continue
            err = theme_problem(t, f)
            if err:                          # apply would refuse it: not offered (the reason goes to stderr)
                print(f"starchaser theme: skipping {tid}: {err}", file=sys.stderr)
                continue
            rows.append({"id": tid, "name": t.get("name", tid), "short": t.get("short", t.get("name", tid)),
                         "description": t.get("description", ""),
                         "previews": theme_previews(f),
                         "variants": [v for v in ("dark", "light") if v in t],
                         "wallpaper": wall_key(t, tid) in walls,   # its wallpaper is on this computer
                         "set": wall_key(t, tid),                  # which set that is (previews key on it)
                         "accent": t.get("dark", t.get("light", {})).get("accent", ""),
                         # each variant's own accent, so a light-mode card shows the light dot ("accent" kept for old readers)
                         "accents": {v: t[v].get("accent", "") for v in ("dark", "light") if v in t},
                         # the colors a card samples (window, panel, text, button), so cards compare before applying
                         "palettes": {v: {k: t[v].get(k, "") for k in ("bg", "surface", "text", "accent")}
                                      for v in ("dark", "light") if v in t},
                         # a theme of yours ("Yours" in the gallery), and one save made and nobody edited since
                         "mine": is_mine(f), "editable": editable(f),
                         "active": bool(has_theme(st) and st["id"] == tid)})
        # One order for every screen that lists themes (welcome, Settings, cockpit):
        # the default first, then its open-space sibling, then your own themes, then A-Z by the name people see.
        # Folder/filename order put "Bioluminescent Ocean" (ocean.toml) between N and S.
        first = {DEFAULT_THEME: 0, "starchaser": 1}
        rows.sort(key=lambda r: (first.get(r["id"], 2 if r["mine"] else 3), r["name"].casefold()))
        if "--json" in argv:
            print(json.dumps({"themes": rows, "variant": st["variant"] if has_theme(st) else "dark"}))
        else:
            # Columns grow to the longest id and name so long ones don't push the rest right.
            idw = max([12] + [len(r["id"]) for r in rows])
            namew = max([22] + [len(r["name"]) for r in rows])
            for r in rows:
                print(f"{'*' if r['active'] else ' '} {r['id']:<{idw}} {r['name']:<{namew}} {r['description']}")
    elif cmd == "current":
        if not has_theme(st):
            sys.exit("starchaser theme: no theme applied yet")
        print(json.dumps(st) if "--json" in argv else theme_label(st))
    elif cmd == "apply":
        if len(argv) < 2:
            usage("Usage: starchaser theme apply <id> [dark|light]")
        # the mode as --dark or --light, or the bare word (like `mode dark`); anything else is refused rather than
        # quietly ignored ("apply brk dark" applied the light version and said nothing)
        asked = {a.lstrip("-") for a in argv[2:]}
        if not asked <= {"dark", "light"} or len(asked) > 1:
            usage("Usage: starchaser theme apply <id> [dark|light]")
        variant = asked.pop() if asked else theme_variant(argv[1], st["variant"] if has_theme(st) else "dark")
        apply(argv[1], variant)
    elif cmd == "toggle":
        if not has_theme(st):
            sys.exit("starchaser theme: no theme applied yet")
        apply(st["id"], "light" if st["variant"] == "dark" else "dark")
    elif cmd == "mode":
        # what the person picked (Dark or Light), not a flip: two quick clicks end on the last one, whatever ran between
        if len(argv) < 2 or argv[1] not in ("dark", "light"):
            usage("Usage: starchaser theme mode <dark|light>")
        if has_theme(st) and st["variant"] == argv[1]:
            print(f"{theme_label(st)}, already")
            return
        apply(st["id"] if has_theme(st) else DEFAULT_THEME, argv[1])
    elif cmd == "look":
        if len(argv) < 2 or argv[1] == "--json":
            look = st.get("look") if st else None
            choice = look["name"] if isinstance(look, dict) else "auto"
            profile = look["profile"] if isinstance(look, dict) else look_profile(choice)
            if "--json" in argv:
                print(json.dumps({"choice": choice, "profile": profile}))
            else:
                selection = "automatic selection" if choice == "auto" else "your selection"
                print(f"Effects: {profile} ({selection})")
            return
        apply(st["id"] if has_theme(st) else DEFAULT_THEME, st["variant"] if has_theme(st) else "dark", argv[1])
    elif cmd == "wallpaper":
        if sub == "list":
            idx, files, names, users = wall_index(), theme_files(), {}, {}
            for tid, f in files.items():
                t = load_theme(f)
                if t is None or theme_problem(t, f):
                    continue
                names[wall_key(t, tid)] = (tid, t.get("name", tid))
                users.setdefault(wall_key(t, tid), []).append(tid)
            now = (st or {}).get("wallpaper_now", {})
            sets, missing = [], False
            for ws in sorted(idx):
                tid, name = names.get(ws, (None, ws.replace("-", " ").title()))
                vs = []
                for v in ("dark", "light"):
                    if v in idx[ws]:
                        big = max(wall_pictures(idx[ws][v])[0], key=lambda x: x[0] * x[1])[2]
                        missing |= not thumb_fresh(big)
                        vs.append({"variant": v, "thumb": str(thumb(big, build=False)),
                                   "current": now.get("set") == ws and now.get("variant") == v})
                # "themes": every theme that uses this set (a theme of yours can share a bundled set);
                # "theme" (one of them) is kept for older readers
                sets.append({"set": ws, "name": name, "theme": tid, "themes": users.get(ws, []), "variants": vs})
            # the theme gallery's order (default first, its sibling, then A-Z by name), sets with no theme last,
            # so Settings and the Super+Space wallpaper menu list them the same way
            first = {DEFAULT_THEME: 0, "starchaser": 1}
            sets.sort(key=lambda x: (first.get(x["theme"], 2) if x["theme"] else 3, x["name"].casefold()))
            pics = [{"file": str(f), "name": picture_name(f), "thumb": str(thumb(f, build=False)),
                     "current": now.get("picture") == str(f)} for f in pictures()]
            if missing or any(not thumb_fresh(f) for f in pictures()):
                build_thumbs_later()
            # what "Match the theme" would show: the active theme's own set in its variant (set_wallpaper falls
            # back to dark the same way). Not "current": in own mode that is your pick, not the theme's
            follow = None
            if has_theme(st) and wall_key(st, st["id"]) in idx:
                fw = wall_key(st, st["id"])
                fv = st["variant"] if st["variant"] in idx[fw] else "dark" if "dark" in idx[fw] else None
                if fv:
                    big = max(wall_pictures(idx[fw][fv])[0], key=lambda x: x[0] * x[1])[2]
                    follow = {"set": fw, "variant": fv, "thumb": str(thumb(big, build=False))}
            if "--json" in argv:
                print(json.dumps({"sets": sets, "pictures": pics, "mode": (st or {}).get("wallpaper_mode", "theme"),
                                  "folder": str(PICTURES), "follow": follow}))
            else:
                setw = max([16] + [len(x["set"]) for x in sets])
                namew = max([22] + [len(x["name"]) for x in sets])
                themew = max([12] + [len(",".join(x["themes"]) or "-") for x in sets])
                for x in sets:
                    print(f"{x['set']:<{setw}} {x['name']:<{namew}} theme={','.join(x['themes']) or '-':<{themew}} " +
                          " ".join(v["variant"] + ("*" if v["current"] else "") for v in x["variants"]))
        elif sub == "restore":
            now = (st or {}).get("wallpaper_now")
            if not now and has_theme(st):
                now = {"set": st.get("wallpaper", st["id"]), "variant": st["variant"]}
            status, out = set_picture(Path(now["picture"]), transition=False) if now and now.get("picture") else ("", "")
            if status == "env":
                sys.exit(out)  # a screen still joining the wallpaper service: keep the picture and retry
            if status == "ok":
                print(out)
            elif now and now.get("picture") and has_theme(st) and wall_key(st, st["id"]) in wall_index():
                # your picture was deleted: the theme's set, so the login isn't
                # blank, and the wallpaper follows the theme again from here
                set_mode("theme")
                print(set_wallpaper(wall_key(st, st["id"]), st["variant"], transition=False, require_all=True))
            elif now and now.get("picture"):
                sys.exit(out)
            elif now and now.get("set") not in wall_index() and has_theme(st) and wall_key(st, st["id"]) in wall_index():
                # the saved set's pictures are gone (your own, deleted): the theme's set, so the login isn't blank.
                # The wallpaper follows the theme again from here (left "own", the theme's set would be kept as
                # your pick through every later theme change)
                set_mode("theme")
                print(set_wallpaper(wall_key(st, st["id"]), st["variant"], transition=False, require_all=True))
            else:
                if not now:
                    sys.exit("nothing to restore")
                print(set_wallpaper(now["set"], now["variant"], transition=False, require_all=True))
        elif sub == "thumbs":
            print(f"{build_thumbs()} thumbnails made")
        elif sub == "picture":
            if len(argv) < 3:
                usage("Usage: starchaser theme wallpaper picture <file>")
            status, out = set_picture(Path(argv[2]).expanduser().resolve())
            if status == "bad" and out.startswith("couldn't"):
                notify("The wallpaper didn't change", f"{Path(argv[2]).name} couldn't be shown. It may be damaged, "
                       "or a kind of picture this computer can't open. Try another picture.")
            if status == "env" and out.startswith("couldn't show wallpaper on"):
                set_mode("own")  # shown on some screens and saved: keep it your choice while the rest join
            if status != "ok":
                sys.exit(out)
            set_mode("own")
            print(out)
        elif sub in ("next", "previous"):
            print(step_wallpaper(st, 1 if sub == "next" else -1))
        elif sub == "follow":
            set_mode("theme")
            if has_theme(st):
                w = wall_key(st, st["id"])
                print(set_wallpaper(w, st["variant"]) if w in wall_index()
                      else f"no '{w}' wallpapers yet; wallpaper unchanged")
        else:
            if sub.lower() not in wall_index():
                usage(f"starchaser theme: no wallpaper set '{sub}' (starchaser theme wallpaper list)")
            v = "light" if "--light" in argv else "dark" if "--dark" in argv else (st["variant"] if has_theme(st) else "dark")
            out = set_wallpaper(sub.lower(), v)
            set_mode("own")
            print(out)
    elif cmd == "bar":
        edges = ("left", "right", "top", "bottom")
        f = CONFIG / "starchaser/cockpit.json"
        try:
            cfg = json.loads(f.read_text())
        except Exception:
            cfg = {}
        if len(argv) < 2:
            print(cfg.get("edge", "left"))
            return
        if argv[1] not in edges:
            usage(f"Usage: starchaser theme bar <{'|'.join(edges)}>")
        cfg["edge"] = argv[1]
        write(f, json.dumps(cfg, indent=2) + "\n")
        refit_later()
        print(f"cockpit spine: {argv[1]}")
    elif cmd == "cockpit":
        # cockpit on: the frame + spine; off: a slim top bar, no frame (Settings > Appearance)
        f = CONFIG / "starchaser/cockpit.json"
        try:
            cfg = json.loads(f.read_text())
        except Exception:
            cfg = {}
        # apps: nothing reads it (apps are on the menu's Apps page); still accepted, so a fleet computer's settings
        # that carry it still apply
        keys = {"autohide": "barAutoHide", "hover": "quickHover", "apps": "edgeApps", "dashboard": "edgeDashboard",
                "cputemp": "showCpuTemp", "gputemp": "showGpuTemp", "clock24": "clock24", "clockdate": "clockDate",
                "closex": "closeButtons", "compact-menu": "compactMenu"}     # closex: a close x on the focused tiled window (off unless asked for)
        if len(argv) == 2 and argv[1] in ("on", "off"):
            cfg["mode"] = "cockpit" if argv[1] == "on" else "bar"
        elif len(argv) == 3 and argv[1] == "size" and argv[2] in ("small", "medium"):
            cfg["barSize"] = argv[2]
        elif len(argv) == 3 and argv[1] == "border-width":
            if argv[2] not in tuple(str(n) for n in range(3, 13)):
                usage("Border width must be a whole number from 3 to 12 pixels.")
            cfg["frame"] = int(argv[2])
        elif len(argv) == 3 and argv[1] == "clock" and argv[2] in ("digital", "analog"):
            cfg["clockStyle"] = argv[2]
        elif len(argv) >= 3 and argv[1] in ("keep", "unkeep"):
            # apps kept on the taskbar, Dock-style (decided 2026-11-06 #7): desktop ids in the order they were kept;
            # the taskbar shows each one first, open or not. Keeping one twice changes nothing, so its place holds
            ids = argv[2:]
            if (argv[1] == "keep" and len(ids) != 1) or not all(re.fullmatch(r"[A-Za-z0-9][\w.+-]{0,199}", i) for i in ids):
                usage("starchaser theme: cockpit keep takes one app id (its desktop file's name without .desktop); "
                      "cockpit unkeep takes one or more")
            kept = [i for i in cfg.get("taskbarApps", []) if isinstance(i, str)] if isinstance(cfg.get("taskbarApps"), list) else []
            if argv[1] == "keep" and ids[0] not in kept:
                if len(kept) >= KEPT_MAX:
                    usage(f"starchaser theme: the taskbar keeps up to {KEPT_MAX} apps; remove one first")
                kept.append(ids[0])
            elif argv[1] == "unkeep":
                kept = [i for i in kept if i not in ids]
            cfg["taskbarApps"] = kept
        elif len(argv) == 3 and argv[1] in keys and argv[2] in ("on", "off"):
            cfg[keys[argv[1]]] = argv[2] == "on"
        elif len(argv) >= 3 and argv[1] == "weather":
            # where Today's weather is for: a town, "town, state" or a ZIP code; "off" (or the older "auto") turns
            # weather off: no place is ever guessed from this computer's internet address (decided 2026-11-16)
            args = argv[2:]
            location = None
            if "--location" in args:
                if len(args) != 3 or args[1] != "--location":
                    usage("starchaser theme: use a place followed by --location and its confirmed location")
                try:
                    location = json.loads(args[2])
                    lat, lon, name = location["latitude"], location["longitude"], location["name"]
                    if (type(lat) not in (int, float) or not -90 <= lat <= 90
                            or type(lon) not in (int, float) or not -180 <= lon <= 180
                            or not isinstance(name, str) or not 0 < len(name.strip()) <= 300
                            or any(ord(c) < 32 for c in name)):
                        raise ValueError()
                    location = {"latitude": lat, "longitude": lon, "name": name.strip()}
                except (ValueError, TypeError, KeyError):
                    usage("starchaser theme: the confirmed location needs valid coordinates and a name")
                args = args[:1]
            place = " ".join(args).strip()
            if place.lower() in ("auto", "off"):
                cfg.pop("weatherPlace", None)
            elif 0 < len(place) <= 60 and re.fullmatch(r"[\w .,'-]+", place):
                cfg["weatherPlace"] = place
            else:
                usage("starchaser theme: a weather place is a town, \"town, state\" or a ZIP code (letters, digits, "
                      "spaces, commas, periods, apostrophes and dashes; up to 60), or auto")
            cfg.pop("weatherLocation", None)
            if location is not None and place.lower() not in ("auto", "off"):
                cfg["weatherLocation"] = location
        elif len(argv) == 1:
            print(json.dumps({"mode": cfg.get("mode", "cockpit"), "autohide": cfg.get("barAutoHide", False),
                              "hover": cfg.get("quickHover", True), "apps": cfg.get("edgeApps", True),
                              "dashboard": cfg.get("edgeDashboard", True),
                              "closex": cfg.get("closeButtons", False), "frame": cfg.get("frame", 6)}))
            return
        else:
            usage("Usage: starchaser theme cockpit [on|off] | cockpit autohide|hover|dashboard|cputemp|gputemp|"
                     "clock24|clockdate|closex on|off | cockpit border-width <3-12> | cockpit clock digital|analog | "
                     "cockpit keep <app id> | cockpit unkeep <app id>... | cockpit weather <town or ZIP>|off")
        write(f, json.dumps(cfg, indent=2) + "\n")
        if len(argv) == 2 or argv[1] == "border-width":
            refit_later()
        if argv[1] == "weather":
            print("weather: " + cfg.get("weatherPlace", "off"))
        elif len(argv) == 2:
            # on|off names the mode it chose (the way bar says where the spine sits); the rest confirm the one
            # setting they changed, so a change never reads as a no-op
            print(f"cockpit: {cfg.get('mode', 'cockpit')}")
        elif argv[1] == "border-width":
            print(f"cockpit border width: {argv[2]}")
        elif argv[1] in ("keep", "unkeep"):
            print(f"cockpit {argv[1]}: {' '.join(argv[2:])}")
        else:
            print(f"cockpit {argv[1]}: {argv[2]}")
    elif cmd in ("refit", "refit-after"):
        if len(argv) != 1:
            usage("Use refit without other arguments.")
        if cmd == "refit-after":
            time.sleep(1.5)
        refit_floating()
    elif cmd == "reapply":
        if has_theme(st) and st["id"] in theme_files():
            apply(st["id"], st["variant"])
        else:
            # An add-on may have changed to its only supported mode. Restore the earlier theme's mode too.
            previous = st.get("previous_theme") if isinstance(st, dict) else None
            if (isinstance(previous, dict) and isinstance(previous.get("id"), str)
                    and previous["id"] in theme_files() and previous.get("variant") in ("dark", "light")):
                apply(previous["id"], theme_variant(previous["id"], previous["variant"]))
            else:
                variant = st["variant"] if has_theme(st) else "dark"
                apply(DEFAULT_THEME, theme_variant(DEFAULT_THEME, variant))
    else:
        usage(f"starchaser theme: unknown command {cmd!r}. "
              "Run 'starchaser theme --help' for more help.")


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) or any(a in ("-h", "--help") for a in sys.argv[2:]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    try:
        main(sys.argv[1:])
    except SystemExit as ex:
        # a refused apply (a theme of yours with a mistake in it): Settings, the welcome and the menu throw the
        # message away, so it is shown as a notification too
        if isinstance(ex.code, str) and sys.argv[1:2] and sys.argv[1] in ("apply", "toggle", "mode", "look", "reapply"):
            notify("The theme didn't change", plain_refusal(ex.code.removeprefix("starchaser theme: ")))
        raise
    except ValueError as error:            # shared preferences explain invalid saved values in plain words
        sys.exit(f"starchaser theme: {error}")
    except PermissionError as error:       # a settings folder it may not write: say so, not a traceback
        sys.exit(f"starchaser theme: couldn't save your settings ({error.strerror}). Check that you can write to ~/.config.")
    except OSError as error:               # a step that couldn't finish (a strict apply): its plain words, not a traceback
        sys.exit(f"starchaser theme: {error.strerror or error}")
