#!/usr/bin/env python3
# summary: Read or change keyboard, mouse, and touchpad settings.
"""starchaser input: change mouse, touchpad, and keyboard settings.

Common commands
  starchaser input get [KEY]              show all settings as JSON, or one setting's value
  starchaser input set KEY VALUE [KEY VALUE ...]   change settings now (names and values below)
  starchaser input restore-defaults       put all input settings back to their defaults (an unreadable file is kept as input.lua.broken)
  starchaser input device NAME KEY VALUE  change a setting for one mouse or touchpad
  starchaser input switch-layout          switch to the next keyboard layout
  starchaser input shortcut list          show your custom keyboard shortcuts

What the fields mean and more commands
Device names may be saved before connecting a device; get lists connected device names.
Mouse, touchpad, keyboard, pointer, animation, sign-in apps and custom shortcuts, for Settings.

  starchaser input device NAME KEY default   one device back to the general setting for that key
  starchaser input device NAME reset       that device back to the general settings
  starchaser input trial start DEVICE OLD NEW   after swapping the mouse buttons (DEVICE "-": the main setting):
                                           OLD comes back by itself in 15 s unless `trial keep` runs first
  starchaser input trial keep | undo       keep the swap, or put the old setting back now
  starchaser input keyboard                the layout being typed in now and Num Lock, as JSON (quick: for a layout switch)
  starchaser input switch-layout [--always]   type in the next keyboard layout (the "Tools: Switch keyboard layout"
                                           shortcut, Super+Alt+Space; does nothing with one layout, or with switch_key
                                           none unless --always: the taskbar's layout tag, clicked)
  starchaser input layouts                 every keyboard layout this computer knows, as JSON
  starchaser input follow-layout           (started by hyprland.lua at sign-in, one per session) a keyboard plugged in
                                           later (a tablet's cover put back, a Bluetooth keyboard waking up) types in
                                           the layout the others are in now, not the first one
  starchaser input apps                    the installed apps (for the pickers), as JSON
  starchaser input autostart list          the apps that start when you sign in, as JSON
  starchaser input autostart add APP-ID    start an installed app at sign-in
  starchaser input autostart add-command NAME COMMAND   run a command at sign-in
  starchaser input autostart edit-command ID NAME COMMAND   correct a command you added
  starchaser input autostart on|off ID     turn one on or off (kept in the list)
  starchaser input autostart remove ID     take one you added off the list (kept aside for restore)
  starchaser input autostart restore ID    put the last one removed under that ID back
  starchaser input shortcut list           your custom shortcuts, as JSON
  starchaser input shortcut state          whether that file can be read, and where a kept copy of an unreadable one is, as JSON
  starchaser input shortcut add NAME KEYS app APP-ID      a key that opens an app
  starchaser input shortcut add NAME KEYS command COMMAND a key that runs a command
        (--replace OLD-NAME first: change that shortcut instead of adding one)
  starchaser input shortcut remove NAME
  starchaser input shortcut restore NAME   put the last one removed under that name back (with its profile changes)
  starchaser input shortcut check KEYS [NAME]   which shortcut already uses KEYS (NAME: the one being changed), JSON
  starchaser input shortcut keep-mine      (run once by hyprland.lua after Starchaser's default keys change) an action
                                           whose new key you already use for something else keeps its old key
  starchaser input supported               whether this computer's hyprland.lua loads what each page saves, as JSON
                                           ({"input", "shortcuts", "autostart"}: true or false)

Shortcut KEYS: join modifiers and one key with +, and quote the combination.
  Modifiers: Super, Ctrl, Alt, Shift (case does not matter).
  Use at least Super, Ctrl or Alt, unless the key is F1-F24 or Print.
  Example: starchaser input shortcut check "Super+Q"

Keys for set (a number outside its range is refused with exit 2 and nothing is saved):
  sensitivity            pointer speed, -1 (slowest) .. 1 (fastest), 0 = the device's own
  accel_profile          adaptive | flat   (adaptive: faster moves go farther)
  left_handed            true | false      (swaps the left and right buttons)
  natural_scroll         true | false      mice: content follows the wheel like a touchscreen
  scroll_factor          0.2 .. 3          mice: scroll speed
  touchpad.natural_scroll, touchpad.tap_to_click, touchpad.disable_while_typing   true | false
  touchpad.scroll_factor 0.2 .. 3
  swipe                  true | false      a three-finger swipe left or right on a touchpad switches desktops
  repeat_delay           150 .. 1000       ms before a held key repeats
  repeat_rate            10 .. 80          repeats per second
  layouts                us,us:dvorak,de   keyboard layouts in order (layout or layout:variant), the first is used at sign-in
  switch_key             shortcut | alt_shift | ctrl_shift | caps | right_alt | none   switches between layouts
                         (shortcut: only the Settings > Shortcuts key, Super+Alt+Space; the others add that XKB key;
                         none: no key, the shortcut included)
  focus                  click | pointer   which window gets the keyboard: the one you click (click, the choice for new
                         installs), or the one the pointer is over (pointer, the choice an install made before this
                         setting existed keeps). Only focus changes; Starchaser never moves the pointer.
  numlock                true | false      Num Lock on when you sign in
  cursor.size            16 .. 96
  cursor.theme           an installed pointer theme, or "" for the standard one
  cursor.hide_while_typing   true | false
  sticky_keys            on | off
  animation_speed        slower | normal | faster | off

Files: the settings live in Starchaser's files under ~/.config and ~/.local/share (a missing or broken file leaves the
usual settings). Changes apply at once.
"""

import fcntl
import json
import math
import os
import re
import select
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import time
import unicodedata
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams, takes_nothing_after, usage_error
from starchaser_system_defaults import loader_root

safe_streams()

# Where the help's "Files" live: ~/.config/hypr/input.lua is a Lua table hyprland.lua reads (a missing or broken
# file leaves the usual settings); ~/.config/autostart/*.desktop is the XDG standard, and at sign-in hyprland.lua
# starts the units systemd's autostart generator makes of them (a typed command runs from
# ~/.local/share/starchaser/sign-in/); ~/.config/hypr/custom-shortcuts.lua is bound in every shortcut profile.
# Changes apply at once with `hyprctl reload`.
HOME = Path.home()
CONFIG = Path(os.environ.get("XDG_CONFIG_HOME") or HOME / ".config")
INPUT_LUA = CONFIG / "hypr/input.lua"
CUSTOM_LUA = CONFIG / "hypr/custom-shortcuts.lua"
AUTOSTART = CONFIG / "autostart"
XKB_LST = Path("/usr/share/X11/xkb/rules/base.lst")
DESKTOP = (os.environ.get("XDG_CURRENT_DESKTOP") or "Hyprland").split(":")

DEFAULTS = {
    "sensitivity": 0.0,
    "focus": "pointer",             # missing in an older input.lua = the behavior that install already had; new installs are set to "click" by setup
    "accel_profile": "adaptive",
    "left_handed": False,
    "natural_scroll": False,
    "scroll_factor": 1.0,
    "touchpad": {"natural_scroll": True, "tap_to_click": True, "disable_while_typing": True, "scroll_factor": 1.0},
    "swipe": True,
    "repeat_delay": 600,
    "repeat_rate": 25,
    "layouts": [{"layout": "us", "variant": ""}],
    "switch_key": "shortcut",
    "switch_key_picked": False,     # true once switch_key was chosen in Settings (see normalize)
    "kb_options": "",
    "numlock": False,
    "cursor": {"size": 24, "theme": "", "hide_while_typing": False},
    "animation_speed": "normal",
    "sticky_keys": False,
    "devices": {},
}
SWITCH_KEYS = {"shortcut": "", "alt_shift": "grp:alt_shift_toggle", "ctrl_shift": "grp:ctrl_shift_toggle", "caps": "grp:caps_toggle",
               "right_alt": "grp:toggle", "none": ""}
SPEEDS = ("slower", "normal", "faster", "off")
DEVICE_KEYS = {"enabled", "sensitivity", "accel_profile", "left_handed", "natural_scroll", "scroll_factor", "tap_to_click",
               "disable_while_typing"}
# the tools the menu's Apps page leaves out (keybinds/menu.py HIDDEN_APPS), and vim (a terminal editor, not a startup app)
HIDDEN_APPS = {"xfce4-about", "avahi-discover", "bssh", "bvnc", "lstopo", "assistant", "qdbusviewer",
               "linguist", "designer", "qv4l2", "qvidcap", "thunar-settings", "vim", "micro", "org.kde.kdeconnect.nonplasma",
               "org.kde.kdeconnect.sms", "org.kde.kmenuedit", "limine-snapper-restore", "nvidia-settings", "cachyos-hello",
               "thunar-volman-settings", "opensnitch_ui", "cups"}
# helper windows of Starchaser's own apps: never offered as apps to pick (sign-in, shortcuts)
HELPER_APPS = {"thunar-bulk-rename", "thunar-settings", "thunar-volman-settings", "org.xfce.mousepad-settings", "kitty-open",
               "xfce4-terminal", "xfce4-terminal-settings"}   # the screen reader's terminal: Terminal opens it then
# Starchaser's own apps by plain names, the same words the taskbar uses (cockpit/Apps.qml plainNames): the program
# name stays in `about` and in the search words, so two terminals can still be told apart
PLAIN_APPS = {"kitty": ("Terminal", "Type commands"), "org.xfce.mousepad": ("Text editor", "Write and edit text files"),
              "mousepad": ("Text editor", "Write and edit text files"),
              "org.lite_xl.lite_xl": ("Code editor", "Write and edit code"),
              "lite-xl": ("Code editor", "Write and edit code"), "com.thisisgm.flea": ("Files", "Browse your files and folders"),
              "thunar": ("Thunar", "Another file manager, the one Files can go back to"),
              "galculator": ("Calculator", "Do math"), "btop": ("System monitor", "See what is using the processor and memory"),
              "yazi": ("Files in the terminal", "Browse files in the terminal using the keyboard"),
              "org.gnome.Papers": ("Document viewer", "Read PDFs and documents"),
              "mpv": ("Video player", "Play videos and music")}
# pointer themes whose own names say another desktop: shown in plain words (no foreign names on screen)
THEME_NAMES = {"adwaita": "Standard", "breeze_cursors": "Rounded", "breeze": "Rounded", "breeze_snow": "Rounded, light",
               "breeze_light": "Rounded, light",
               "oxygen": "Glossy", "hicolor": ""}
# The pointer styles Starchaser ships (decided 2026-10-10: "5-8 hand-picked styles with previews under Mouse &
# touchpad"), in the order Settings shows them, after Standard. Each is a theme folder from an Arch package the
# desktop setup installs (installer/starchaser-desktop-setup.sh): the package is named so a missing one can be told
# apart from one that was never shipped. Styles anyone adds later follow these, by name.
SHIPPED_STYLES = [
    ("capitaine-cursors", "Smooth black", "capitaine-cursors"),
    ("capitaine-cursors-light", "Smooth white", "capitaine-cursors"),
    ("Vanilla-DMZ-AA", "Classic black", "xcursor-vanilla-dmz-aa"),
    ("Vanilla-DMZ", "Classic white", "xcursor-vanilla-dmz"),
    ("Vimix-cursors", "Soft dark", "vimix-cursors"),
    ("Vimix-white-cursors", "Soft white", "vimix-cursors"),
]
for _id, _name, _pkg in SHIPPED_STYLES:
    THEME_NAMES.setdefault(_id.lower(), _name)


class Fail(Exception):
    pass


# ---------------------------------------------------------------- a small Lua table reader and writer

class LuaReader:
    """Reads the Lua this helper writes, and hand edits to it: one `return { ... }` of tables, strings, numbers and
    booleans, with -- comments. Anything else raises ValueError."""

    def __init__(self, text: str):
        self.s, self.i = text, 0

    def ws(self):
        while self.i < len(self.s):
            if self.s[self.i].isspace():
                self.i += 1
            elif self.s.startswith("--[[", self.i):
                end = self.s.find("]]", self.i)
                self.i = len(self.s) if end < 0 else end + 2
            elif self.s.startswith("--", self.i):
                end = self.s.find("\n", self.i)
                self.i = len(self.s) if end < 0 else end + 1
            else:
                break

    def parse(self):
        self.ws()
        if not self.s.startswith("return", self.i):
            raise ValueError("no return")
        self.i += 6
        v = self.value()
        self.ws()
        if self.i < len(self.s):
            raise ValueError(f"unexpected text at {self.i}")
        return v

    def value(self):
        self.ws()
        if self.i >= len(self.s):
            raise ValueError("ends early")
        c = self.s[self.i]
        if c == "{":
            return self.table()
        if c in "\"'":
            return self.string()
        for word, v in (("true", True), ("false", False), ("nil", None)):
            if self.s.startswith(word, self.i) and not (self.s[self.i + len(word):self.i + len(word) + 1] or " ").isalnum():
                self.i += len(word)
                return v
        m = re.compile(r"-?(?:0x[0-9a-fA-F]+|\d+\.?\d*(?:[eE][-+]?\d+)?|\.\d+)").match(self.s, self.i)
        if m:
            self.i = m.end()
            t = m.group(0)
            if "x" in t.lower():
                return int(t, 16)
            return float(t) if any(ch in t for ch in ".eE") else int(t)
        raise ValueError(f"unknown value at {self.i}")

    def string(self):
        q = self.s[self.i]
        self.i += 1
        out = []
        while self.i < len(self.s):
            c = self.s[self.i]
            if c == q:
                self.i += 1
                return "".join(out)
            if c == "\n":
                raise ValueError("line break in a string")
            if c == "\\":
                self.i += 1
                e = self.s[self.i:self.i + 1]
                if e.isdigit():
                    m = re.compile(r"\d{1,3}").match(self.s, self.i)
                    out.append(chr(int(m.group(0))))
                    self.i = m.end()
                    continue
                out.append({"n": "\n", "t": "\t", "r": "\r", "\\": "\\", '"': '"', "'": "'"}.get(e, e))
                self.i += 1
                continue
            out.append(c)
            self.i += 1
        raise ValueError("string not closed")

    def table(self):
        self.i += 1
        arr, obj = [], {}
        while True:
            self.ws()
            if self.i >= len(self.s):
                raise ValueError("table not closed")
            if self.s[self.i] == "}":
                self.i += 1
                break
            if self.s[self.i] == "[":
                self.i += 1
                k = self.value()
                self.ws()
                if self.s[self.i:self.i + 1] != "]":
                    raise ValueError("] expected")
                self.i += 1
                self.ws()
                if self.s[self.i:self.i + 1] != "=":
                    raise ValueError("= expected")
                self.i += 1
                obj[k] = self.value()
            else:
                m = re.compile(r"([A-Za-z_]\w*)\s*=(?!=)").match(self.s, self.i)
                if m:
                    self.i = m.end()
                    obj[m.group(1)] = self.value()
                else:
                    arr.append(self.value())
            self.ws()
            if self.s[self.i:self.i + 1] in (",", ";"):
                self.i += 1
        if arr and obj:
            raise ValueError("mixed table")
        return arr if arr or not obj else obj


def lua_str(v: str) -> str:
    out = []
    for c in str(v):
        if c in '\\"':
            out.append("\\" + c)
        elif ord(c) < 32 or ord(c) == 127:
            out.append("\\%03d" % ord(c))
        else:
            out.append(c)
    return '"' + "".join(out) + '"'


def lua_val(v, ind: str = "    ") -> str:
    if isinstance(v, bool):
        return "true" if v else "false"
    if isinstance(v, (int, float)):
        return repr(round(v, 4)) if isinstance(v, float) else str(v)
    if isinstance(v, str):
        return lua_str(v)
    if isinstance(v, list):
        if not v:
            return "{}"
        return "{\n" + "".join(f"{ind}    {lua_val(x, ind + '    ')},\n" for x in v) + ind + "}"
    if isinstance(v, dict):
        if not v:
            return "{}"
        rows = []
        for k, x in v.items():
            key = k if re.fullmatch(r"[A-Za-z_]\w*", k) else f"[{lua_str(k)}]"
            rows.append(f"{ind}    {key} = {lua_val(x, ind + '    ')},\n")
        return "{\n" + "".join(rows) + ind + "}"
    return "nil"


def read_lua(path: Path, problems=None):
    """(value, broken): None when the file is missing; broken when it can't be read."""
    try:
        text = path.read_text()
    except FileNotFoundError:
        return None, False
    except (OSError, UnicodeError):
        if problems is not None:
            problems.append("The saved file could not be read. Check that it is a readable text file.")
        return None, True
    reader = LuaReader(text)
    try:
        return reader.parse(), False
    except (ValueError, IndexError, AttributeError):
        if problems is not None:
            offset = min(reader.i, len(text))
            line = text.count("\n", 0, offset) + 1
            column = offset - text.rfind("\n", 0, offset)
            problems.append(f"Settings stopped reading {path} at line {line}, column {column}.")
        return None, True


def write_file(path: Path, text: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    # a temporary name of its own: two helpers saving at once (a page's last changes still saving while the next page
    # saves) must not trip over one shared .tmp file
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix="." + path.name + ".", suffix=".tmp")
    try:
        with os.fdopen(fd, "w") as f:
            f.write(text)
            f.flush()
            os.fsync(f.fileno())
        os.chmod(tmp, 0o644)
        os.replace(tmp, path)
    except BaseException:
        try:
            os.unlink(tmp)
        except OSError:
            pass
        raise


def lock_changes():
    """Changes read the whole file and write it back, so they take turns: without this, a save still running (a page
    left before its last change was written) and a new one each wrote back what they read, and one change was lost."""
    path = CONFIG / "hypr/.starchaser-input.lock"
    path.parent.mkdir(parents=True, exist_ok=True)
    f = open(path, "a")
    fcntl.flock(f, fcntl.LOCK_EX)
    return f


def keep_broken(path: Path) -> None:
    """A file that can't be read is kept beside the new one (name.broken), so a hand edit isn't lost."""
    try:
        shutil.copyfile(path, path.with_name(path.name + ".broken"))
    except OSError:
        pass


# ---------------------------------------------------------------- settings (input.lua)

def clamp(v, lo, hi):
    return max(lo, min(hi, v))


def as_bool(v) -> bool:
    if isinstance(v, bool):
        return v
    s = str(v).strip().lower()
    if s in ("true", "yes", "on", "1"):
        return True
    if s in ("false", "no", "off", "0"):
        return False
    raise Fail(f"not on or off: {v}")


def as_num(v, lo, hi, integer=False, strict=False, name="value"):
    """strict (a number the user typed): refuse one outside lo..hi instead of quietly using the nearest allowed one.
    Saved settings are read without it, so an old or hand-edited file still loads."""
    try:
        n = float(v)
    except (TypeError, ValueError):
        raise Fail(f"not a number: {v}") from None
    if math.isnan(n):
        raise Fail(f"not a number: {v}")
    if strict and not math.isfinite(n):
        raise Fail(f"{name} must be a number from {lo} to {hi}, not {v}")
    if strict and not lo <= n <= hi:
        raise Fail(f"{name} must be from {lo} to {hi}, not {v} (nothing was changed)")
    n = clamp(n, lo, hi)
    return int(round(n)) if integer else round(n, 3)


def clean_layouts(v) -> list:
    out = []
    items = v if isinstance(v, list) else str(v).split(",")
    for it in items:
        if isinstance(it, dict):
            lay, var = str(it.get("layout") or ""), str(it.get("variant") or "")
        else:
            lay, _, var = str(it).strip().partition(":")
        if not re.fullmatch(r"[a-z][a-z0-9_-]{0,15}", lay) or (var and not re.fullmatch(r"[A-Za-z0-9_-]{1,40}", var)):
            continue
        if {"layout": lay, "variant": var} not in out:
            out.append({"layout": lay, "variant": var})
    return out[:4]       # XKB holds four layouts at most


def one_of(v, choices):
    if v not in choices:
        raise Fail(f"not one of {', '.join(choices)}: {v}")
    return v


def saved_repeat(v, lo, hi):
    """Saved repeat values must be numbers in range, just as Hyprland reads them."""
    if isinstance(v, bool) or not isinstance(v, (int, float)):
        raise Fail("not a repeat number")
    as_num(v, lo, hi, strict=True)
    return math.floor(v)


def normalize(raw, rejected=None) -> dict:
    """Check input.lua's values, optionally recording fields rejected in favor of defaults."""
    raw = raw if isinstance(raw, dict) else {}
    s = json.loads(json.dumps(DEFAULTS))
    if rejected is None:
        rejected = []

    def put(target, key, src, conv, prefix=""):
        if key in src:
            try:
                target[key] = conv(src[key])
            except Fail:
                rejected.append(prefix + key)
    put(s, "sensitivity", raw, lambda v: as_num(v, -1, 1))
    put(s, "accel_profile", raw, lambda v: one_of(v, ("adaptive", "flat")))
    put(s, "focus", raw, lambda v: one_of(v, ("click", "pointer")))
    for k in ("left_handed", "natural_scroll", "swipe", "numlock", "sticky_keys"):
        put(s, k, raw, as_bool)
    put(s, "scroll_factor", raw, lambda v: as_num(v, 0.2, 3))
    tp = raw.get("touchpad") if isinstance(raw.get("touchpad"), dict) else {}
    for k in ("natural_scroll", "tap_to_click", "disable_while_typing"):
        put(s["touchpad"], k, tp, as_bool, "touchpad.")
    put(s["touchpad"], "scroll_factor", tp, lambda v: as_num(v, 0.2, 3), "touchpad.")
    put(s, "repeat_delay", raw, lambda v: saved_repeat(v, 150, 1000))
    put(s, "repeat_rate", raw, lambda v: saved_repeat(v, 10, 80))
    if "layouts" in raw:
        lays = clean_layouts(raw["layouts"])
        if lays:
            s["layouts"] = lays
    put(s, "switch_key", raw, lambda v: one_of(v, tuple(SWITCH_KEYS)))
    put(s, "switch_key_picked", raw, as_bool)
    # Alt+Shift was the default until 2026-10-08, when layout switching moved to Super+Alt+Space: Settings writes
    # the whole table, so an "alt_shift" saved before then is the old default, not a choice (hyprland.lua reads it
    # the same way)
    if s["switch_key"] == "alt_shift" and not s["switch_key_picked"]:
        s["switch_key"] = "shortcut"
    put(s, "kb_options", raw, lambda v: ",".join(o for o in str(v).split(",") if re.fullmatch(r"[a-z0-9_:+-]+", o)
                                                  and not o.startswith("grp:")))
    cur = raw.get("cursor") if isinstance(raw.get("cursor"), dict) else {}
    put(s["cursor"], "size", cur, lambda v: as_num(v, 16, 96, True), "cursor.")
    put(s["cursor"], "theme", cur, theme_name, "cursor.")
    put(s["cursor"], "hide_while_typing", cur, as_bool, "cursor.")
    put(s, "animation_speed", raw, lambda v: one_of(v, SPEEDS))
    devs = raw.get("devices") if isinstance(raw.get("devices"), dict) else {}
    for name, d in devs.items():
        if not isinstance(name, str) or not isinstance(d, dict) or not re.fullmatch(r"[^\n\"\\]{1,120}", name):
            continue
        one = {}
        for k, v in d.items():
            try:
                one[k] = device_value(k, v)
            except Fail:
                rejected.append(f"devices.{name}.{k}")
        if one:
            s["devices"][name] = one
    return s


def theme_name(v) -> str:
    if not isinstance(v, str) or not re.fullmatch(r"[^/\n\"\\]{0,80}", v):
        raise Fail(f"not a theme name: {v}")
    return v


def device_value(key: str, v, strict=False):
    if key not in DEVICE_KEYS:
        raise Fail(f"unknown device setting: {key}")
    if key == "sensitivity":
        return as_num(v, -1, 1, strict=strict, name=key)
    if key == "scroll_factor":
        return as_num(v, 0.2, 3, strict=strict, name=key)
    if key == "accel_profile":
        if v not in ("adaptive", "flat"):
            raise Fail(f"adaptive or flat, not {v}")
        return v
    return as_bool(v)


def load_settings(rejected=None, problems=None):
    """Read settings; rejected collects invalid fields separately from an unreadable file."""
    raw, broken = read_lua(INPUT_LUA, problems)
    return normalize(raw, rejected), broken, raw is not None


HEADER = """-- Written by Starchaser Settings (bin/starchaser-input): Mouse & touchpad, Keyboard, and the animation speed in
-- Appearance. hyprland.lua reads this table; a missing or broken file leaves the usual settings. Settings rewrites
-- the whole file, so for anything Settings doesn't offer use ~/.config/hypr/user.lua.
"""


def save_settings(s: dict, broken: bool) -> None:
    if broken:
        keep_broken(INPUT_LUA)
    if s["sticky_keys"]:
        write_sticky_keymap(s)
    write_file(INPUT_LUA, HEADER + "return " + lua_val(s, "") + "\n")


def set_key(s: dict, key: str, value: str) -> None:
    top, _, sub = key.partition(".")
    if key == "sensitivity":
        s[key] = as_num(value, -1, 1, strict=True, name=key)
    elif key == "accel_profile":
        if value not in ("adaptive", "flat"):
            raise Fail("accel_profile is adaptive or flat")
        s[key] = value
    elif key == "focus":
        if value not in ("click", "pointer"):
            raise Fail("focus is click or pointer")
        s[key] = value
    elif key in ("left_handed", "natural_scroll", "swipe", "numlock", "sticky_keys"):
        s[key] = as_bool(value)
    elif key == "scroll_factor":
        s[key] = as_num(value, 0.2, 3, strict=True, name=key)
    elif top == "touchpad" and sub in ("natural_scroll", "tap_to_click", "disable_while_typing"):
        s["touchpad"][sub] = as_bool(value)
    elif key == "touchpad.scroll_factor":
        s["touchpad"]["scroll_factor"] = as_num(value, 0.2, 3, strict=True, name=key)
    elif key == "repeat_delay":
        s[key] = as_num(value, 150, 1000, True, strict=True, name=key)
    elif key == "repeat_rate":
        s[key] = as_num(value, 10, 80, True, strict=True, name=key)
    elif key == "layouts":
        lays = clean_layouts(value)
        if not lays:
            raise Fail("at least one keyboard layout is needed")
        known = {(x["layout"], x["variant"]) for x in xkb_layouts()}
        if known:
            for l in lays:
                if (l["layout"], l["variant"]) not in known:
                    raise Fail(f"unknown keyboard layout: {l['layout']}{':' + l['variant'] if l['variant'] else ''}")
        s[key] = lays
    elif key == "switch_key":
        if value not in SWITCH_KEYS:
            raise Fail("switch_key is one of " + ", ".join(SWITCH_KEYS))
        s[key] = value
        s["switch_key_picked"] = True
    elif key == "cursor.size":
        s["cursor"]["size"] = as_num(value, 16, 96, True, strict=True, name=key)
    elif key == "cursor.theme":
        if value and value not in {t["id"] for t in cursor_themes()}:
            raise Fail(f"no pointer theme named {value}")
        s["cursor"]["theme"] = value
    elif key == "cursor.hide_while_typing":
        s["cursor"]["hide_while_typing"] = as_bool(value)
    elif key == "animation_speed":
        if value not in SPEEDS:
            raise Fail("animation_speed is one of " + ", ".join(SPEEDS))
        s[key] = value
    else:
        raise Fail(f"unknown setting: {key}")


def in_hyprland() -> bool:
    return bool(os.environ.get("HYPRLAND_INSTANCE_SIGNATURE")) and shutil.which("hyprctl") is not None


def hypr_ask(request: str, timeout: float) -> str | None:
    """One request on Hyprland's request socket, the way hyprctl sends it; None when the socket can't be used."""
    run, sig = os.environ.get("XDG_RUNTIME_DIR") or "", os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") or ""
    if not run or not sig:
        return None
    try:
        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            s.connect(os.path.join(run, "hypr", sig, ".socket.sock"))
            s.sendall(request.encode())
            out = b""
            while chunk := s.recv(65536):
                out += chunk
        return out.decode(errors="replace")
    except OSError:
        return None


def hyprctl(*args, timeout=10) -> str:
    # the devices list is read after every keyboard event and every 30 s by follow-layout: asked on the socket, so
    # that look starts no process (hyprctl itself when the socket can't be used)
    if args == ("devices", "-j"):
        answer = hypr_ask("j/devices", timeout)
        if answer is not None:
            return answer
    if not shutil.which("hyprctl"):
        return ""
    try:
        return subprocess.run(["hyprctl", *args], capture_output=True, text=True, timeout=timeout).stdout
    except (OSError, subprocess.TimeoutExpired):
        return ""


def reload_hyprland() -> None:
    if in_hyprland():
        hyprctl("reload")


KEYBOARD_KEYS = {"layouts", "switch_key", "repeat_delay", "repeat_rate", "numlock", "sticky_keys"}


def keyboard_config(s: dict) -> dict:
    """The keyboard part of hyprland.lua's input table, built the same way it builds it from input.lua."""
    lays = s["layouts"][:4]
    options = [s["kb_options"]] if s.get("kb_options") else []
    key = s["switch_key"]
    if key == "alt_shift" and not s.get("switch_key_picked"):
        key = "shortcut"
    if len(lays) > 1 and SWITCH_KEYS.get(key):
        options.append(SWITCH_KEYS[key])
    return {"kb_file": str(CONFIG / "hypr/sticky-keys.xkb") if s["sticky_keys"] else "",
            "kb_layout": ",".join(l["layout"] for l in lays), "kb_variant": ",".join(l["variant"] for l in lays),
            "kb_options": ",".join(options), "repeat_delay": int(s["repeat_delay"]), "repeat_rate": int(s["repeat_rate"]),
            "numlock_by_default": bool(s["numlock"])}


def write_sticky_keymap(s: dict) -> None:
    """Latch modifiers in the selected keymap, retaining layouts, variants and layout-switch options."""
    kb = keyboard_config(s)
    result = subprocess.run(["xkbcli", "compile-keymap", "--layout", kb["kb_layout"], "--variant", kb["kb_variant"],
                             "--options", kb["kb_options"]], capture_output=True, text=True, timeout=10)
    if result.returncode or 'xkb_keymap' not in result.stdout:
        raise Fail("Sticky keys couldn't prepare the keyboard layout: " + result.stderr.strip())
    # Latch the ordinary modifier interpretations. Lock keys and layout-switch actions stay intact.
    text, count = re.subn(r'action= SetMods\(modifiers=(modMapMods|Shift|Control|Alt|Meta|Super|Hyper)(?:,clearLocks)?\);',
                          r'action= LatchMods(modifiers=\1,clearLocks,latchToLock);', result.stdout)
    if count == 0:
        raise Fail("Sticky keys aren't supported by this keyboard map.")
    write_file(CONFIG / "hypr/sticky-keys.xkb", text)


def note(msg: str) -> None:
    """One line in ~/.local/state/starchaser/input.log (what a report needs: which way a change was applied and
    why). Never on stderr: Settings shows that as an error under the page."""
    d = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser"
    try:
        d.mkdir(parents=True, exist_ok=True)
        f = d / "input.log"
        if f.exists() and f.stat().st_size > 64 * 1024:
            f.write_text("\n".join(f.read_text(errors="replace").splitlines()[-200:]) + "\n")
        with f.open("a") as out:
            out.write(time.strftime("%F %T ") + msg + "\n")
    except OSError:
        pass


def keep_active_layout_valid(s: dict) -> None:
    """Before a keymap with fewer layouts is applied: a keyboard typing in a layout past the new list's end goes back
    to the first one. Hyprland 0.56 with Num Lock at sign-in (numlock_by_default) on, handed a keymap that no longer
    has the layout a keyboard is typing in, broke every app's connection to the screen ("The Wayland connection
    broke"): the taskbar, the menu and Settings all closed the moment a second layout was removed while it was the one
    in use. Switching to layout 1 first never did (tested 2026-10-09, run 20261009-0013 002)."""
    n = len(s["layouts"][:4])
    try:
        kbs = json.loads(hyprctl("devices", "-j") or "{}").get("keyboards", [])
    except ValueError:
        kbs = []
    if any(isinstance(k, dict) and int(k.get("active_layout_index") or 0) >= n for k in kbs):
        note(f"keyboard: typing in a layout past the new list of {n}; back to the first one before applying")
        hyprctl("switchxkblayout", "all", "0")


def apply_keyboard_live(s: dict) -> bool:
    """A keyboard-only change, applied with one config call instead of a full reload. A full reload rebuilds every
    setting and sent the apps a new keymap in the middle of it; once that broke the taskbar's and Settings' connection
    to the screen ("keymap: dup failed") the moment a layout was removed. True when it was applied this way; False
    means do the full reload (no eval in this Hyprland, or user.lua sets the keyboard itself and has to win). Why it
    returned False goes to input.log."""
    try:
        user = (CONFIG / "hypr/user.lua").read_text(errors="replace")
    except OSError:
        user = ""
    if re.search(r"\bkb_(layout|variant|options)\b|repeat_(delay|rate)|numlock_by_default", re.sub(r"--[^\n]*", "", user)):
        note("keyboard: full reload (user.lua sets the keyboard itself)")
        return False
    # a hyprland.lua of this computer's own that doesn't read input.lua: what it sets itself stays (the reload path)
    if not supported()["input"]:
        note("keyboard: full reload (this hyprland.lua doesn't read input.lua)")
        return False
    kb = keyboard_config(s)
    fields = ", ".join(f"{k} = {lua_val(v) if not isinstance(v, str) else lua_str(v)}" for k, v in kb.items())
    if not shutil.which("hyprctl"):
        note("keyboard: full reload (no hyprctl)")
        return False
    try:
        r = subprocess.run(["hyprctl", "eval", f"hl.config({{ input = {{ {fields} }} }})"], capture_output=True,
                           text=True, timeout=10)
    except (OSError, subprocess.TimeoutExpired) as e:
        note(f"keyboard: full reload (hyprctl eval failed: {type(e).__name__})")
        return False
    out = (r.stdout + r.stderr).strip()
    low = out.lower()
    if r.returncode == 0 and ("error" not in low and "unknown" not in low and "invalid" not in low):
        return True
    note(f"keyboard: full reload (hyprctl eval exit {r.returncode}: {out[:200]!r})")
    return False


def default_cursor_theme() -> str:
    """The theme "standard" means: what the system's default theme points to, else Adwaita."""
    for d in (HOME / ".icons/default", HOME / ".local/share/icons/default", Path("/usr/share/icons/default")):
        try:
            m = re.search(r"(?m)^\s*Inherits\s*=\s*([^,\n]+)", (d / "index.theme").read_text(errors="replace"))
        except OSError:
            continue
        if m and m.group(1).strip():
            return m.group(1).strip()
    return "Adwaita"


def apply_cursor(s: dict) -> None:
    if in_hyprland():
        hyprctl("setcursor", s["cursor"]["theme"] or default_cursor_theme(), str(s["cursor"]["size"]))


def restore_layouts(before: dict) -> None:
    """Puts each keyboard back on the layout it was typing in (before: name -> index) after a change that rebuilt
    the keymaps. One keyboard at a time, by name, so a keyboard with its own layout list keeps its own layout. The
    rebuild can land a moment after hyprctl returns, so it looks a few times. Only a layout the new keymap still has
    (a user.lua that sets its own keyboard may have fewer), never past the list's end (keep_active_layout_valid's
    crash)."""
    for _ in range(6):
        time.sleep(0.25)
        kbs = typing_keyboards()
        if not kbs:
            return
        moved = []
        for k in kbs:
            idx = before.get(k["name"], 0)
            cur = int(k.get("active_layout_index") or 0)
            if not idx or cur == idx:
                continue
            if len([x for x in str(k.get("layout", "")).split(",") if x.strip()]) <= idx:
                note(f"keyboard: {k['name']}: layout {idx + 1} isn't in the new keymap; left on the first one")
                continue
            hyprctl("switchxkblayout", k["name"], str(idx))
            moved.append(idx)
        if moved:
            note(f"keyboard: back to layout {moved[0] + 1} after the keymap was rebuilt")
            time.sleep(0.2)
            tell_osk(typing_keyboards())
            tell_taskbar()
            return


def tell_taskbar() -> None:
    """The taskbar's layout tag reads the layout when the config reloads, which is before restore_layouts puts the one
    in use back, so it showed US with German in use (round 32). One more read, through the cockpit's own "keyboard"
    call. Not waited for; nothing breaks if the cockpit isn't running."""
    if not shutil.which("qs"):
        return
    run = Path(f"/run/user/{os.getuid()}")
    way = os.environ.get("WAYLAND_DISPLAY") or next(
        (p.name for p in sorted(run.glob("wayland-*")) if not p.name.endswith(".lock")), "wayland-1")
    try:
        subprocess.Popen(["qs", "-p", str(HOME / ".config/quickshell/cockpit"), "ipc", "call", "cockpit", "keyboard"],
                         env=dict(os.environ, XDG_RUNTIME_DIR=str(run), WAYLAND_DISPLAY=way),
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    except OSError:
        pass


def cmd_set(args: list) -> int:
    if not args or len(args) % 2:
        raise Fail("set needs KEY VALUE pairs")
    s, broken, _ = load_settings()
    if os.environ.get("STARCHASER_FLEET_APPLY") == "1":
        if broken or not supported()["input"] or trial_now():
            raise Fail("Input settings aren't ready to change.")
    for k, v in zip(args[0::2], args[1::2]):
        set_key(s, k, v)
    save_settings(s, broken)
    if in_hyprland() and (broken or "layouts" in args[0::2]):
        keep_active_layout_valid(s)
    # any other change rebuilds the keymaps too (a new layout-switch key, a repeat rate, a full reload), which puts
    # every keyboard back on the first layout: with German in use, picking Alt + Shift switched typing to English
    # (round 31). Remember the layout in use, put it back after. Not after a change to the layout list itself (the
    # clamp above decides that one)
    keep = {}
    if in_hyprland() and not broken and "layouts" not in args[0::2]:
        keep = {k["name"]: int(k.get("active_layout_index") or 0) for k in typing_keyboards()}
    if broken or not set(args[0::2]) <= KEYBOARD_KEYS or not in_hyprland() or not apply_keyboard_live(s):
        if broken and in_hyprland():
            note("full reload (the settings file was broken and has been replaced)")
        reload_hyprland()
    # the live pointer only changes through setcursor (a reload sets only the size apps read when they start): after
    # a pointer change, and after a broken file was replaced by one with the usual pointer
    if broken or any(k.startswith("cursor.") for k in args[0::2]):
        apply_cursor(s)
    if any(keep.values()):
        restore_layouts(keep)
    # a new layout list: the on-screen keyboard's too (the follower also says it, but only when it next looks)
    if in_hyprland() and "layouts" in args[0::2]:
        time.sleep(0.3)
        tell_osk(typing_keyboards())
        # the taskbar's layout tag only re-reads on Hyprland's activelayout/configreloaded events; a layout list changed
        # live sends neither it waits for, so it kept saying DE after German was removed (round 60). Tell it, and once
        # more after the keymap has settled.
        tell_taskbar()
        time.sleep(0.8)
        tell_taskbar()
    if broken:
        dismiss_broken_notice()
    if sys.stdout.isatty():   # Settings and scripts read the values back and see no change; a terminal is told
        for k, v in zip(args[0::2], args[1::2]):
            print(f"{k} is now {v}")
    return 0


def cmd_restore_defaults(args: list) -> int:
    """A deliberate way out of an unreadable input.lua: keep it as input.lua.broken, write the usual settings."""
    if args:
        raise Fail("restore-defaults takes no arguments")
    _, broken, _ = load_settings()
    old, _, _ = load_settings()
    s = normalize(None)
    s["focus"] = old["focus"]      # how windows take focus isn't a pointer or keyboard setting: a reset keeps the choice
    save_settings(s, broken)
    trial_file().unlink(missing_ok=True)    # the device overrides are gone: a pending button trial has nothing to undo
    if in_hyprland():
        keep_active_layout_valid(s)
        note("full reload (input settings put back to the usual ones)")
    reload_hyprland()
    apply_cursor(s)
    dismiss_broken_notice()
    if sys.stdout.isatty():   # Settings and scripts read the values back and see no change; a terminal is told
        print("Put every pointer and keyboard setting back to its defaults.")
    return 0


def broken_notice_file() -> Path:
    session = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE") or "x"
    return Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / f"starchaser-input-broken-notified-{session}"


def dismiss_broken_notice() -> None:
    """Withdraw only this session's warning, including one still waiting for the taskbar to start."""
    path = broken_notice_file()
    try:
        with path.with_name(path.name + ".lock").open("a") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            if not path.exists():
                return      # no notice was sent or is waiting this session: writing the marker would silence a later one
            try:
                saved = json.loads(path.read_text())
            except (OSError, ValueError):
                saved = {}
            path.write_text('{"dismissed": true}')
            if (isinstance(saved, dict) and str(saved.get("id", "")).isdigit()
                    and re.fullmatch(r":\d+\.\d+", str(saved.get("owner", "")))):
                # A unique bus owner prevents closing an unrelated ID after the taskbar restarts.
                subprocess.run(["gdbus", "call", "--session", "--dest", saved["owner"],
                                "--object-path", "/org/freedesktop/Notifications",
                                "--method", "org.freedesktop.Notifications.CloseNotification", str(saved["id"])],
                               stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5, check=False)
    except (OSError, subprocess.TimeoutExpired):
        pass


def notify_broken_input() -> int:
    path = broken_notice_file()
    try:
        with path.open("x"):
            pass                         # once per sign-in, including config reloads
    except FileExistsError:
        return 0
    time.sleep(8)                        # let the notification server start
    with path.with_name(path.name + ".lock").open("a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if path.read_text():
            return 0                    # Settings opened or restored during the delay
        try:
            result = subprocess.run(["gdbus", "call", "--session", "--dest", "org.freedesktop.DBus",
                                     "--object-path", "/org/freedesktop/DBus",
                                     "--method", "org.freedesktop.DBus.GetNameOwner", "org.freedesktop.Notifications"],
                                    capture_output=True, text=True, timeout=5, check=False)
            owner = re.search(r":\d+\.\d+", result.stdout)
            if not owner:
                return 0
            proc = subprocess.Popen(["stdbuf", "-oL", *['/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", "-p", "-w",
                                     "-h", "boolean:x-starchaser-transient:true", "-A", "open=Open Settings",
                                     "Mouse and keyboard settings not loaded",
                                     "Your saved input settings could not be loaded. Open Settings to restore them."],
                                    stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
        except (OSError, subprocess.TimeoutExpired):
            return 0
        nid = proc.stdout.readline().strip()
        if nid.isdigit():
            path.write_text(json.dumps({"id": nid, "owner": owner.group()}))
    # Release the lock before waiting for an answer, so the repair page can withdraw the card.
    with proc.stdout:
        answer = proc.stdout.read().strip()
    proc.wait()
    if answer == "open":
        subprocess.Popen(["starchaser", "settings", "mouse"], start_new_session=True)
    return 0


def cmd_device(args: list) -> int:
    if len(args) < 2:
        raise Fail("device needs NAME and a setting")
    name = args[0]
    if not re.fullmatch(r"[^\n\"\\]{1,120}", name):
        raise Fail("not a device name")
    s, broken, _ = load_settings()
    devs = s["devices"]
    if args[1] == "reset":
        devs.pop(name, None)
        t = trial_read()            # back to the main setting: a trial still open for this device has nothing to undo
        if t and t.get("device") == name:
            trial_file().unlink(missing_ok=True)
    else:
        if len(args) != 3:
            raise Fail("device NAME KEY VALUE")
        one = dict(devs.get(name) or {})
        if args[2] == "default":
            if args[1] not in DEVICE_KEYS:
                raise Fail(f"unknown device setting: {args[1]}")
            one.pop(args[1], None)
        else:
            one[args[1]] = device_value(args[1], args[2], strict=True)
        if one:
            devs[name] = one
        else:
            devs.pop(name, None)
    save_settings(s, broken)
    # the full reload rebuilds every keymap, like cmd_set's: a replaced (broken) file may have fewer layouts, so a
    # keyboard past the new list's end goes back to the first one first (keep_active_layout_valid's crash); otherwise
    # the layout in use is put back after, or a device change switches typing to the first layout
    keep = {}
    if in_hyprland():
        if broken:
            keep_active_layout_valid(s)
        else:
            keep = {k["name"]: int(k.get("active_layout_index") or 0) for k in typing_keyboards()}
    reload_hyprland()
    if any(keep.values()):
        restore_layouts(keep)
    if broken:
        apply_cursor(s)       # the file it replaced may have had another pointer
        dismiss_broken_notice()
    connected = name in {d["name"] for d in pointing_devices()}
    if sys.stdout.isatty():   # Settings and scripts read the values back and see no change; a terminal is told
        # one line that says what happened: a reset clears the device's own settings, it does not save them
        done = (f"Cleared {name}'s own settings." if args[1] == "reset"
                else f"{args[1]} is now {args[2]} for {name}.")
        if not connected:
            done += f" {name!r} is not connected. Check the name with starchaser input get."
        print(done)
    elif not connected:
        # a warning, not a confirmation: the name may be a typo, so every run says it, and never "Saved settings"
        # after a reset (which cleared the device's own settings)
        print(f"{name!r} is not connected. Check the name with starchaser input get.")
    return 0


# ---------------------------------------------------------------- swapped buttons: keep, or back by themselves

# Swapping the mouse buttons changes the button you'd click to undo it, so a swap is a trial: unless Settings says
# Keep within TRIAL_SECONDS, the old setting comes back by itself. The timer is a process of its own (not the page),
# so leaving the page or closing Settings can't lose it; the file holds which trial is open, and a newer one replaces
# it. DEVICE "-" is the main setting; OLD / NEW are true, false or (a device) default = follows the main setting.
TRIAL_SECONDS = 15


def trial_file() -> Path:
    # the person's own runtime folder (never a /tmp file other accounts could make first)
    run = os.environ.get("XDG_RUNTIME_DIR")
    state = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser"
    return (Path(run) if run else state) / "starchaser-input-buttons-trial.json"


def trial_read() -> dict | None:
    try:
        t = json.loads(trial_file().read_text())
        return t if isinstance(t, dict) and "token" in t else None
    except (OSError, ValueError):
        return None


def trial_now() -> dict | None:
    t = trial_read()
    if not t or t.get("until", 0) < time.time() - 5:
        return None
    return {"device": t.get("device", "-"), "until": t.get("until", 0), "old": t.get("old", "")}


def trial_revert(t: dict, why: str = "") -> None:
    if t.get("device", "-") == "-":
        cmd_set(["left_handed", t["old"]])
    else:
        cmd_device([t["device"], "left_handed", t["old"]])
    if why:
        trial_notice(t, why)


def trial_notice(t: dict, why: str) -> None:
    """Says that the buttons went back by themselves: the countdown is only on the Mouse & touchpad page, and the
    buttons swapping back while someone was on another page (or had closed Settings) read as the mouse breaking."""
    if os.environ.get("STARCHASER_FLEET_APPLY") == "1":
        print("The mouse buttons were switched back.", file=sys.stderr)
        return
    old = t.get("old")
    if old == "default":
        what = f"{t.get('device')} follows the main mouse button setting again"
    else:
        # name the button that clicks now: "the main button is the right one" read as the opposite of what happened
        what = "The " + ("right" if old == "true" else "left") + " button clicks again"
        if t.get("device", "-") != "-":
            what += f" on {t.get('device')}"
    reason = (f"Keep wasn't clicked within {TRIAL_SECONDS} seconds" if why == "expired"
              else "Keep wasn't clicked before you left Mouse & touchpad")
    try:
        subprocess.Popen([*['/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", "input-mouse", "Mouse buttons switched back",
                          f"{what}, because {reason}. You can change it in Settings > Mouse & touchpad."],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True)
    except OSError:
        pass


def cmd_trial(args: list) -> int:
    sub = args[0] if args else ""
    f = trial_file()
    if sub == "start" and len(args) == 4:
        device, old, new = args[1], args[2], args[3]
        for v in (old, new):
            if v not in ("true", "false") + (("default",) if device != "-" else ()):
                raise Fail("trial start DEVICE OLD NEW: true, false or (a device) default")
        t = trial_read()
        if t and t.get("until", 0) > time.time():
            if t.get("device") == device:
                if new == t["old"]:          # back to where it was before the trial: nothing left to keep
                    f.unlink(missing_ok=True)
                    return 0
                old = t["old"]               # still undecided: the setting before the first swap comes back
            else:                            # one trial at a time: another one still undecided switches back first,
                f.unlink(missing_ok=True)    # so it can never stay without Keep
                trial_revert(t)
        token = os.urandom(8).hex()
        f.parent.mkdir(parents=True, exist_ok=True)
        write_file(f, json.dumps({"token": token, "device": device, "old": old, "until": time.time() + TRIAL_SECONDS}))
        subprocess.Popen([sys.executable, os.path.abspath(__file__), "trial", "expire", token],
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
                         start_new_session=True, close_fds=True)
        return 0
    if sub == "keep" and len(args) == 1:
        if not trial_read():
            raise Fail("No mouse-button trial is running. It goes back by itself after 15 seconds.")
        f.unlink(missing_ok=True)
        return 0
    # undo --left-page: Settings' Mouse page closed (another page, or Settings itself) with the trial still open
    if sub == "undo" and (len(args) == 1 or args[1:] == ["--left-page"]):
        t = trial_read()
        if not t and len(args) == 1:
            raise Fail("No mouse-button trial is running. It goes back by itself after 15 seconds.")
        f.unlink(missing_ok=True)
        if t:
            trial_revert(t, "left" if len(args) == 2 else "")
        return 0
    if sub == "expire" and len(args) == 2:
        t = trial_read()
        if not t or t["token"] != args[1]:
            return 0
        time.sleep(max(0.0, t.get("until", 0) - time.time()))
        lock = lock_changes()
        try:
            t = trial_read()
            if t and t["token"] == args[1]:        # not kept, undone or replaced meanwhile
                f.unlink(missing_ok=True)
                trial_revert(t, "expired")
        finally:
            lock.close()
        return 0
    raise Fail("trial start DEVICE OLD NEW | keep | undo")


# ---------------------------------------------------------------- what's attached

def proc_input_devices() -> list:
    """[(name, event number or None)] from /proc/bus/input/devices."""
    out = []
    try:
        text = Path("/proc/bus/input/devices").read_text(errors="replace")
    except OSError:
        return out
    for block in text.split("\n\n"):
        name = re.search(r'(?m)^N: Name="(.*)"$', block)
        ev = re.search(r"(?m)^H: Handlers=.*\bevent(\d+)\b", block)
        if name:
            out.append((name.group(1), int(ev.group(1)) if ev else None))
    return out


def udev_props(event: int) -> set:
    try:
        text = Path(f"/run/udev/data/c13:{64 + event}").read_text(errors="replace")
    except OSError:
        return set()
    return {l[2:].strip() for l in text.splitlines() if l.startswith("E:")}


def hypr_name(name: str) -> str:
    """How Hyprland names a device: lowercase, spaces to dashes."""
    return name.strip().lower().replace(" ", "-")


def pointing_devices() -> list:
    """Mice and touchpads Hyprland sees: [{name (Hyprland's), label (as the device names itself), touchpad}]."""
    try:
        data = json.loads(hyprctl("devices", "-j") or "{}")
    except ValueError:
        data = {}
    known = {}
    for name, ev in proc_input_devices():
        props = udev_props(ev) if ev is not None else set()
        known.setdefault(hypr_name(name), (name, "ID_INPUT_TOUCHPAD=1" in props))
    out = []
    for m in data.get("mice") or []:
        n = str(m.get("name") or "")
        if not n:
            continue
        base = re.sub(r"-\d+$", "", n) if n not in known and re.sub(r"-\d+$", "", n) in known else n
        label, pad = known.get(base, ("", False))
        if not label:
            label = " ".join(w.capitalize() for w in re.split(r"[-_]+", n) if w)
        # Some devices repeat their vendor at the start of the reported name.
        label = re.sub(r"^(\S+)(?:\s+\1)+(?=\s)", r"\1", label, flags=re.I)
        pad = pad or bool(re.search(r"touchpad|trackpad|glidepoint|clickpad", n, re.I))
        out.append({"name": n, "label": label, "touchpad": pad})
    # two devices that name themselves the same (a mouse that shows up twice): numbered, so the rows differ
    seen = {}
    for d in out:
        seen[d["label"]] = seen.get(d["label"], 0) + 1
        if seen[d["label"]] > 1:
            d["label"] += f" ({seen[d['label']]})"
    return out


def display_keyboard(kbs: list):
    """The keyboard whose layout the taskbar and Settings show. Real keyboards first; then any that types
    (squeekboard's own when its keymap is valid). Never one whose keymap reads "error": after typing on the
    on-screen keyboard, its virtual keyboard can be Hyprland's main one, and showing it printed "error"."""
    types = [k for k in kbs if k.get("name") and k.get("active_keymap") != "error"]
    real = [k for k in types if not str(k["name"]).startswith("hl-virtual-keyboard")]
    pool = real or types
    if not pool:
        return None
    return next((k for k in pool if k.get("main")), pool[-1])


# While a keyboard that dropped off (a Bluetooth keyboard reconnecting) is being moved back to the layout in use, it
# is for a moment on the first layout, and Hyprland may call it the main one: the taskbar tag and Settings then said
# "English" for a beat while the layout in use was another (round 57). The follower below writes the layout in use
# here when a device comes back and removes it once its settle pass has run; until then (at most a few seconds) the
# state reports this layout.
KB_HOLD = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-kb-hold"


def held_keymap() -> str:
    try:
        d = json.loads(KB_HOLD.read_text())
        return str(d["active"]) if time.time() < float(d["until"]) else ""
    except (OSError, ValueError, KeyError, TypeError):
        return ""


def set_hold(keymap: str) -> None:
    try:
        KB_HOLD.write_text(json.dumps({"active": keymap, "until": time.time() + 5}))
    except OSError:
        pass


def clear_hold() -> None:
    try:
        KB_HOLD.unlink()
    except OSError:
        pass


def keyboard_state() -> dict:
    try:
        data = json.loads(hyprctl("devices", "-j") or "{}")
    except ValueError:
        return {}
    main = display_keyboard(data.get("keyboards") or [])
    if not main:
        return {}
    active = held_keymap() or main.get("active_keymap", "")
    return {"active": active, "active_label": layout_label(active), "numlock": bool(main.get("numLock")), "name": main.get("name", "")}


def icon_dirs() -> list:
    dirs = [HOME / ".local/share/icons", HOME / ".icons"]
    for d in (os.environ.get("XDG_DATA_DIRS") or "/usr/local/share:/usr/share").split(":"):
        if d:
            dirs.append(Path(d) / "icons")
    return dirs


def cursor_themes() -> list:
    seen, out = set(), []
    for base in icon_dirs():
        try:
            subs = sorted(base.iterdir())
        except OSError:
            continue
        for d in subs:
            if d.name in seen or d.name == "default" or not (d / "cursors").is_dir():
                continue
            seen.add(d.name)
            name = d.name
            try:
                m = re.search(r"(?m)^\s*Name\s*=\s*(.+)$", (d / "index.theme").read_text(errors="replace"))
                if m:
                    name = m.group(1).strip()
            except OSError:
                pass
            plain = THEME_NAMES.get(d.name.lower(), THEME_NAMES.get(name.lower(), name))
            if plain == "":
                continue
            if plain == "Standard":
                # Adwaita is "Standard" only while it is the standard theme (and then it isn't listed); when the
                # system's standard points elsewhere, two "Standard" entries would mean two different looks
                plain = "Plain black"
            out.append({"id": d.name, "name": plain or d.name})
    std = default_cursor_theme().lower()
    # the standard one is offered as "Standard" (theme ""), so it isn't listed twice
    out = [t for t in out if t["id"].lower() != std]
    # the shipped styles first, in their own order; anything added later after them, by name
    order = {sid.lower(): i for i, (sid, _n, _p) in enumerate(SHIPPED_STYLES)}
    out.sort(key=lambda t: (order.get(t["id"].lower(), len(order)), t["name"].lower()))
    for t in out:
        t["preview"] = cursor_preview(t["id"])
    return out


def theme_dir(name: str):
    """The folder of an installed pointer theme, by its folder name, or None."""
    for base in icon_dirs():
        d = base / name
        if (d / "cursors").is_dir():
            return d
    return None


def xcursor_image(path: Path, want: int = 48):
    """The first frame of an Xcursor file, at the nominal size nearest `want` (a bigger one when two are as near):
    (width, height, RGBA bytes, not premultiplied), or None. The format: "Xcur", a header length, a version and a
    table of contents; each image chunk is a 36-byte header (its width and height at offsets 16 and 20) followed by
    width x height premultiplied ARGB words, little-endian."""
    import struct
    try:
        data = path.read_bytes()
    except OSError:
        return None
    if len(data) < 16 or data[:4] != b"Xcur":
        return None
    try:
        hsize, _ver, ntoc = struct.unpack_from("<III", data, 4)
        toc = [struct.unpack_from("<III", data, hsize + 12 * i) for i in range(ntoc)]
    except struct.error:
        return None
    imgs = [(sub, pos) for typ, sub, pos in toc if typ == 0xFFFD0002]
    if not imgs:
        return None
    size = min({sub for sub, _p in imgs}, key=lambda n: (abs(n - want), -n))
    pos = next(p for sub, p in imgs if sub == size)
    try:
        w, h = struct.unpack_from("<II", data, pos + 16)
        if not (0 < w <= 256 and 0 < h <= 256):
            return None
        px = data[pos + 36: pos + 36 + 4 * w * h]
        if len(px) < 4 * w * h:
            return None
    except struct.error:
        return None
    out = bytearray(4 * w * h)
    for i in range(w * h):
        b, g, r, a = px[4 * i], px[4 * i + 1], px[4 * i + 2], px[4 * i + 3]
        if a and a < 255:                           # undo the premultiplied alpha
            r, g, b = min(255, r * 255 // a), min(255, g * 255 // a), min(255, b * 255 // a)
        out[4 * i: 4 * i + 4] = bytes((r, g, b, a))
    return w, h, bytes(out)


def write_png(path: Path, w: int, h: int, rgba: bytes) -> None:
    """A plain RGBA PNG (Python's own zlib: no image library needed)."""
    import struct
    import zlib

    def chunk(kind: bytes, body: bytes) -> bytes:
        return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body) & 0xFFFFFFFF)
    rows = b"".join(b"\x00" + rgba[y * w * 4:(y + 1) * w * 4] for y in range(h))
    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(rows, 9)) + chunk(b"IEND", b""))
    fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".preview-", suffix=".png")
    try:
        with os.fdopen(fd, "wb") as f:
            f.write(png)
        os.replace(tmp, path)
    except OSError:
        Path(tmp).unlink(missing_ok=True)
        raise


# the pointers a preview shows, left to right: the arrow, the hand over a link, the text bar, busy. Each has older
# names some themes use instead.
PREVIEW_SHAPES = [("left_ptr", "default", "arrow"), ("pointer", "hand2", "hand1", "hand"),
                  ("text", "xterm", "ibeam"), ("watch", "wait", "left_ptr_watch", "progress")]


def cursor_preview(theme: str) -> str:
    """A picture of a pointer theme's main pointers side by side, for Settings > Mouse & touchpad: a PNG under
    ~/.cache/starchaser/pointer-styles, made once per theme (again when the theme's files change). "" when the
    theme has none of these pointers or can't be read. Every pointer sits in a square cell of the same size,
    centered, so the styles line up when shown one above another."""
    d = theme_dir(theme)
    if not d:
        return ""
    files = []
    for names in PREVIEW_SHAPES:
        f = next((d / "cursors" / n for n in names if (d / "cursors" / n).is_file()), None)
        if f:
            files.append(f)
    if not files:
        return ""
    try:
        stamp = int(max(f.resolve().stat().st_mtime for f in files))
    except OSError:
        return ""
    cache = Path(os.environ.get("XDG_CACHE_HOME") or HOME / ".cache") / "starchaser/pointer-styles"
    safe = re.sub(r"[^A-Za-z0-9._-]", "_", theme)
    out = cache / f"{safe}-{stamp}-v1.png"
    if out.is_file():
        return str(out)
    imgs = [im for im in (xcursor_image(f) for f in files) if im]
    if not imgs:
        return ""
    cell = max(max(w, h) for w, h, _ in imgs)
    gap = cell // 3
    W, H = len(imgs) * cell + (len(imgs) - 1) * gap, cell
    canvas = bytearray(4 * W * H)
    for k, (w, h, px) in enumerate(imgs):
        ox, oy = k * (cell + gap) + (cell - w) // 2, (cell - h) // 2
        for y in range(h):
            canvas[4 * ((oy + y) * W + ox): 4 * ((oy + y) * W + ox + w)] = px[4 * y * w: 4 * (y + 1) * w]
    try:
        cache.mkdir(parents=True, exist_ok=True)
        for old in cache.glob(f"{safe}-*.png"):      # an older picture of the same theme (not "<safe>-light-…")
            if re.fullmatch(re.escape(safe) + r"-\d+-v\d+\.png", old.name):
                old.unlink(missing_ok=True)
        write_png(out, W, H, bytes(canvas))
    except OSError:
        return ""
    return str(out)


def supported() -> dict:
    """Whether this computer's hyprland.lua loads each file Settings writes: a machine on its own hyprland.lua
    (without Starchaser's blocks) would save changes that never take effect."""
    own = CONFIG / "hypr/hyprland.lua"
    root = loader_root(own)          # the small hyprland.lua: what counts is Starchaser's file it loads
    try:
        text = (root / "config/hypr/hyprland.lua" if root else own).read_text(errors="replace")
    except OSError:
        text = ""
    return {"input": "input.lua" in text, "shortcuts": "custom-shortcuts.lua" in text, "autostart": "@autostart.service" in text}


SWITCH_ACTION = "Tools: Switch keyboard layout"   # the bind's description in hyprland.lua and the profiles


def switch_shortcut() -> str:
    """The key the layout-switch shortcut has now, as people read it ("Super+Alt+Space"), or "" when it has none."""
    try:
        r = subprocess.run(["starchaser", "shortcuts", "key", SWITCH_ACTION], capture_output=True, text=True, timeout=5)
    except (OSError, subprocess.TimeoutExpired):
        return ""
    return r.stdout.strip() if r.returncode == 0 else ""


def cmd_switch_layout(args: list) -> int:
    if args not in ([], ["--always"]):
        return usage_error("starchaser input", f"switch-layout takes only --always (got {' '.join(args)!r})", "switch-layout [--always]")
    s, _, _ = load_settings()
    # the layouts in use are not counted here: user.lua can set kb_layout too, and with one layout "next" changes
    # nothing anyway
    if (s["switch_key"] == "none" and "--always" not in args) or not in_hyprland():
        return 0
    # every keyboard to the layout after the one in use, not "all next": that steps each keyboard on from its own
    # layout, so one left behind (plugged in during a switch) stayed out of step for good, and the taskbar tag flipped
    # between the two as different keyboards were typed on. The cockpit shows the new layout's name (activelayout).
    kbs = typing_keyboards()
    count = len(str(kbs[0].get("layout", "")).split(",")) if kbs else 0
    methods = CONFIG / "starchaser/input-methods.json"
    if methods.is_file():
        import runpy
        try:
            if runpy.run_path(str(Path(__file__).resolve().with_name("starchaser-input-method")))["next_method"](
                    layout_in_use(kbs), count, lambda index: hyprctl("switchxkblayout", "all", str(index))):
                return 0
        except (OSError, ValueError) as error:
            raise Fail(str(error)) from error
    if count > 1:
        hyprctl("switchxkblayout", "all", str((layout_in_use(kbs) + 1) % count))
    else:
        hyprctl("switchxkblayout", "all", "next")
    return 0


def all_keyboards() -> dict:
    """Every keyboard Hyprland has that types with its keymap (squeekboard's own included), by name."""
    try:
        kbs = json.loads(hyprctl("devices", "-j") or "{}").get("keyboards") or []
    except ValueError:
        return {}
    return {k["name"]: k for k in kbs if k.get("name") and k.get("active_keymap") != "error"}


def typing_keyboards() -> list:
    """Hyprland's keyboards that type (not squeekboard's own virtual keyboard, whose keymap reads "error")."""
    try:
        kbs = json.loads(hyprctl("devices", "-j") or "{}").get("keyboards") or []
    except ValueError:
        return []
    return [k for k in kbs if k.get("name") and k.get("active_keymap") != "error"
            and not str(k["name"]).startswith("hl-virtual-keyboard")]


def layout_in_use(kbs: list, skip=()) -> int:
    """The layout index the keyboards are in: the one typed on last's, else the one most of them use."""
    kbs = [k for k in kbs if k["name"] not in skip] or kbs
    main = next((k for k in kbs if k.get("main")), None)
    if main:
        return main.get("active_layout_index", 0)
    idx = [k.get("active_layout_index", 0) for k in kbs]
    return max(set(idx), key=idx.count) if idx else 0


def loose(name: str) -> str:
    """A device name the way Hyprland names it ("Keyboard K380" -> "keyboard-k380"), loosely, for matching."""
    return re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")


def hypr_events(run: str, sig: str):
    """Hyprland's event socket (activelayout and the rest), or None."""
    try:
        sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        sock.connect(os.path.join(run, "hypr", sig, ".socket2.sock"))
        return sock
    except OSError:
        return None


_osk_said = None


def tell_osk(kbs: list):
    """The on-screen keyboard (squeekboard) shows the first layout in org.gnome.desktop.input-sources' "sources" and
    follows it live (checked in a VM, round 30); nothing else told it, so with German in use it stayed English. Writes
    the layout in use first, then the others in order (its globe menu lists them). Base names only ("de", not
    "de+nodeadkeys"): a variant it has no layout for would leave it on English again. Only when squeekboard is
    installed, and only when the list changes."""
    global _osk_said
    if not kbs or not shutil.which("squeekboard") or not shutil.which("gsettings"):
        return
    # the layout list and the index from the same keyboard: the one typed on last (layout_in_use's), else the first
    src = next((k for k in kbs if k.get("main")), kbs[0])
    names = []
    for n in str(src.get("layout", "")).split(","):
        n = n.strip()
        if n and n not in names:
            names.append(n)
    if not names:
        return
    idx = src.get("active_layout_index", 0) if src.get("main") else layout_in_use(kbs)
    full = str(src.get("layout", "")).split(",")
    cur = full[idx].strip() if 0 <= idx < len(full) else names[0]
    order = [cur] + [n for n in names if n != cur]
    value = "[" + ", ".join(f"('xkb', '{n}')" for n in order if re.fullmatch(r"[a-z0-9_-]+", n)) + "]"
    if value == _osk_said or value == "[]":
        return
    r = subprocess.run(["gsettings", "set", "org.gnome.desktop.input-sources", "sources", value],
                       capture_output=True, text=True)
    if r.returncode == 0:
        _osk_said = value


def cmd_follow_layout() -> int:
    """Keeps every keyboard in the same layout. Hyprland gives each keyboard its own:
    - a new one starts on the first layout: after switching to the second, a keyboard plugged in later (a tablet's
      cover put back, a Bluetooth keyboard waking up) typed in the first, and the taskbar tag (the newest keyboard's)
      said so too. Watches input devices come and go (udevadm) and moves each new keyboard to the layout the ones
      already there are in: the one typed on last if it is still there, else the one most of them use. A keyboard
      counts as new when udev says it was added, even under a name already known: one that drops off and comes back
      within one settle time (a cover reseated, a Bluetooth keyboard reconnecting at once) keeps its name.
    - the switch keys other than the shortcut (Alt+Shift, Ctrl+Shift, Caps Lock, Right Alt) are the keyboard's own:
      pressed on the cover they switched the cover only, so the Bluetooth keyboard went on typing in the old layout
      while the taskbar said the new one. Watches Hyprland's activelayout events and moves the others along."""
    run = os.environ.get("XDG_RUNTIME_DIR") or "/tmp"
    sig = os.environ.get("HYPRLAND_INSTANCE_SIGNATURE", "")
    lock = open(os.path.join(run, f"starchaser-follow-layout-{sig}.lock"), "w")
    try:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except OSError:
        return 0                                    # this session already has one
    known = {k["name"]: k for k in typing_keyboards()}
    tell_osk(list(known.values()))
    mon = subprocess.Popen(["udevadm", "monitor", "--udev", "--property", "--subsystem-match=input"],
                           stdout=subprocess.PIPE)
    fd = mon.stdout.fileno()
    events = hypr_events(run, sig) if sig else None
    pending = 0.0                                   # a device burst settles at this time
    buf, ebuf = b"", b""
    added = set()                                   # loose names of the devices udev added in this burst
    settled = {}                                    # keyboard name -> when it was last moved as a new one
    switched = {}                                   # keyboard name -> when its layout changed (activelayout)
    unsure = set()                                  # new keyboards the move above failed on
    fast_until = 0.0                                # watch closely for a just-added keyboard until then
    fast_last = 0.0
    fast_done = set()                               # names moved since their last add/remove event
    while True:
        waits = [fd] + ([events] if events else [])
        wait = 0.05 if fast_until else 0.25 if (pending or switched) else 30
        ready, _, _ = select.select(waits, [], [], wait)
        now_t = time.monotonic()
        if fd in ready:
            data = os.read(fd, 65536)
            if not data:
                return 1                            # udevadm went away
            buf += data
            *blocks, buf = buf.split(b"\n\n")
            for b in blocks:
                if b"ACTION=add" in b or b"ACTION=remove" in b:
                    pending = now_t + 0.8           # one device = a burst of events: look once it settles
                    m = re.search(rb'^NAME="?(.*?)"?$', b, re.M)
                    if m:
                        name = loose(m.group(1).decode(errors="replace"))
                        # The same name can return again before this burst settles.
                        fast_done = {n for n in fast_done if loose(n) != name}
                    if m and b"ACTION=add" in b:
                        added.add(name)
                        if not fast_until:
                            fast_done = set()
                            mk = next((k for k in known.values() if k.get("main")), None) or next(iter(known.values()), None)
                            if mk and mk.get("active_keymap"):
                                set_hold(mk["active_keymap"])   # show the layout in use until the new one is moved to it
                        fast_until = now_t + 1.5    # and look every 50 ms meanwhile (below)
        if events and events in ready:
            data = events.recv(65536)
            if not data:
                events = None                       # Hyprland went away: the udev side still ends the loop
            ebuf += data
            *lines, ebuf = ebuf.split(b"\n")
            for line in lines:
                if line.startswith(b"activelayout>>"):
                    name = line[14:].decode(errors="replace").rsplit(",", 1)[0]
                    switched[name] = now_t + 0.3    # look once the switch (one event per keyboard) is over
        # the close watch: a keyboard back from a short drop (a Bluetooth keyboard reconnecting) starts on the first
        # layout, and keys typed before the settle pass below went in that layout ("yyy" for German "zzz"). Move it
        # as soon as Hyprland lists it, to the layout in use before the burst; the settle pass stays the final check.
        if fast_until and now_t - fast_last >= 0.05:
            fast_last = now_t
            if now_t >= fast_until:
                fast_until = 0.0
            src = list(known.values())
            if src:
                typed_last = next((n for n, k in known.items() if k.get("main")), "")
                want = known[typed_last].get("active_layout_index", 0) if typed_last else layout_in_use(src)
                layout = (known.get(typed_last) or src[0]).get("layout")
                for k in typing_keyboards():
                    n = k["name"]
                    if n in fast_done or not (n not in known or loose(n) in added):
                        continue
                    # one still at the layout in use is either moved already or not re-made by Hyprland yet: wait
                    if k.get("layout") == layout and k.get("active_layout_index", 0) != want:
                        if hyprctl("switchxkblayout", n, str(want)).strip() == "ok":
                            fast_done.add(n)
                            settled[n] = now_t
        if ready:
            continue
        if pending and now_t >= pending:
            pending = 0.0
            now = {k["name"]: k for k in typing_keyboards()}
            fresh = {n for n in now if n not in known or loose(n) in added}
            added = set()
            old = {n: k for n, k in now.items() if n not in fresh}
            src = list(old.values()) or list(known.values())
            if fresh and src:
                # the layout in use: from the keyboards that stayed (their state now), else from before the burst
                typed_last = next((n for n, k in known.items() if k.get("main")), "")
                want = old[typed_last].get("active_layout_index", 0) if typed_last in old else layout_in_use(src)
                layout = src[0].get("layout")
                for n in fresh:
                    settled[n] = now_t
                    unsure.discard(n)
                    k = now[n]
                    if k.get("layout") == layout and k.get("active_layout_index", 0) != want:
                        if hyprctl("switchxkblayout", n, str(want)).strip() != "ok":
                            unsure.add(n)           # not moved: its next event can't be told from a switch key
            known = {k["name"]: k for k in typing_keyboards()} or now
            clear_hold()
            continue
        due = [n for n, t in switched.items() if now_t >= t]
        if due and not pending:
            for n in due:
                del switched[n]
            # a keyboard's own switch key: the others follow. Not a new keyboard's first layout (it comes with one
            # activelayout of its own), nor while devices are still coming and going.
            kbs = {k["name"]: k for k in typing_keyboards()}
            src = []
            for n in due:
                if n not in known or n not in kbs or loose(n) in added:
                    continue
                if now_t - settled.get(n, -9) > 1.5:
                    src.append(n)
                elif n not in unsure:
                    # just moved as a new keyboard: this may be that move's own event, or the person's switch key
                    # pressed right after plugging it in (which was dropped, leaving the keyboards apart). Look again
                    # once the 1.5 s are over: a switch key left it on another layout and the others follow; the
                    # move's own event left it on the one the others are in, and nothing changes.
                    switched[n] = settled[n] + 1.6
            if src:
                k = kbs[src[-1]]
                want = k.get("active_layout_index", 0)
                # the on-screen keyboard's too, or typing on it put its own layout back in the taskbar
                for n, other in all_keyboards().items():
                    if (n != k["name"] and other.get("layout") == k.get("layout")
                            and other.get("active_layout_index", 0) != want):
                        hyprctl("switchxkblayout", n, str(want))
            known = {k["name"]: k for k in typing_keyboards()} or kbs or known
            tell_osk(list(known.values()))
            continue
        if not pending and not switched:
            if sig and not os.path.isdir(os.path.join(run, "hypr", sig)):
                mon.terminate()                     # the session ended
                return 0
            clear_hold()
            known = {k["name"]: k for k in typing_keyboards()} or known   # the layout in use now
            tell_osk(list(known.values()))                                # (and a new layout list)


def cmd_get(args: list) -> int:
    rejected, problems = [], []
    s, broken, exists = load_settings(rejected, problems)
    if args:
        v = s
        for part in args[0].split("."):
            if not isinstance(v, dict) or part not in v:
                raise Fail(f"unknown setting: {args[0]}")
            v = v[part]
        print(json.dumps(v))
        return 0
    old = INPUT_LUA.with_name(INPUT_LUA.name + ".broken")
    print(json.dumps({"settings": s, "broken": broken, "rejected": rejected, "saved": exists, "supported": supported()["input"],
                      "brokenCopy": str(old) if old.is_file() else "", "readProblem": " ".join(problems), "trial": trial_now(),
                      "devices": pointing_devices(), "keyboard": keyboard_state(), "switchShortcut": switch_shortcut(),
                      "cursorThemes": cursor_themes(), "standardTheme": default_cursor_theme(),
                      "standardPreview": cursor_preview(default_cursor_theme())}))
    return 0


# ---------------------------------------------------------------- keyboard layouts

# XKB's short forms spelled out for search; canonical names stay available alongside friendly labels.
LAYOUT_WORDS = {"intl.": "international", "alt.": "alternative", "phon.": "phonetic", "ergo.": "ergonomic",
                "trad.": "traditional", "std.": "standard", "dvp": "programmer dvorak", "ext.": "extended"}
LAYOUT_EXTRA = {("us", "intl"): "international accents dead keys", ("us", "alt-intl"): "international accents dead keys",
                ("us", "altgr-intl"): "international accents"}
LAYOUT_LABELS = {
    "English (US, intl., with dead keys)": "English (US, accents with the apostrophe key)",
    "English (US, alt. intl.)": "English (US, apostrophe accents and extra symbols)",
    "English (intl., with AltGr dead keys)": "English (US, accents with right Alt)",
    "Spanish (dead tilde)": "Spanish (combine ~ with a letter)",
    "Spanish (no dead keys)": "Spanish (accent marks print immediately)",
    "Spanish (Latin American, dead tilde)": "Spanish (Latin American, combine ~ with a letter)",
    "Spanish (Latin American, no dead keys)": "Spanish (Latin American, accent marks print immediately)",
}
# a plain second line for the look-alike layouts people pick most, so the choice doesn't rest on XKB's short names
# (the wrong international layout changes what ' and " do in every app)
LAYOUT_ABOUT = {
    ("us", "intl"): "Type an accent by pressing ' \" ` ~ or ^ and then a letter (' then e types \u00e9). "
                    "For the mark itself, press it and then Space.",
    ("us", "alt-intl"): "Right Alt+E types \u20ac; "
                        "right Alt+Shift+E types \u00a2. Apostrophe (') then e types \u00e9.",
    ("us", "altgr-intl"): "Like US, but hold the right Alt key for accents (right Alt+e types \u00e9). "
                          "' and \" type as usual.",
    ("gb", "intl"): "UK keys. Type an accent by pressing ' \" ` ~ or ^ and then a letter (' then e types \u00e9).",
    ("de", ""): "^, ´ and ` wait for the next letter (´ then e types é; ^ then e types ê). "
                "~ prints immediately with right Alt and +. For an accent mark itself, press it and then Space.",
    ("de", "deadacute"): "´ waits for the next letter (´ then e types é). `, ^ and ~ print immediately. "
                         "Other accents typed with right Alt can still wait for a letter.",
    ("de", "deadgraveacute"): "´ and ` wait for the next letter (´ then e types é; ` then e types è). "
                              "^ and ~ print immediately. Other accents typed with right Alt can still wait for a letter.",
    ("de", "deadtilde"): "Like German: ^, ´ and ` wait for the next letter. ~ also waits: press right Alt and +, "
                         "then n to type ñ. For an accent mark itself, press it and then Space.",
    ("de", "nodeadkeys"): "Accent marks print immediately: ´ then e types ´e, not é; ^ then e types ^e, not ê. "
                          "ä, ö and ü still have their own keys.",
    ("es", "deadtilde"): "Hold right Alt and press 4, then n to type ñ. The ~ accent waits for the next letter. "
                         "For ~ itself, press right Alt+4 and then Space. ñ also has its own key.",
    ("latam", "deadtilde"): "Hold right Alt and press +, then n to type ñ. The ~ accent waits for the next letter. "
                            "For ~ itself, press right Alt++ and then Space. ñ also has its own key.",
    ("es", "nodeadkeys"): "Accent marks print immediately instead of waiting for a letter. ñ still has its own key.",
    ("latam", "nodeadkeys"): "Accent marks print immediately instead of waiting for a letter. ñ still has its own key.",
}


def layout_keys(layout: str, variant: str, name: str) -> str:
    low = name.lower()
    words = [full for short, full in LAYOUT_WORDS.items() if short in low]
    if LAYOUT_EXTRA.get((layout, variant)):
        words.append(LAYOUT_EXTRA[(layout, variant)])
    return " ".join(words)


def layout_label(name: str) -> str:
    """Use plain accent-key labels where known, otherwise expand XKB's short forms."""
    if name in LAYOUT_LABELS:
        return LAYOUT_LABELS[name]
    out = name
    for short, full in LAYOUT_WORDS.items():
        out = re.sub(r"(?<![A-Za-z])" + re.escape(short) + r"(?![A-Za-z])", full, out, flags=re.I)
    return out


def layout_entry(layout: str, variant: str, name: str) -> dict:
    e = {"layout": layout, "variant": variant, "name": name, "keys": layout_keys(layout, variant, name)}
    label = layout_label(name)
    if label != name:
        e["label"] = label
    if (layout, variant) in LAYOUT_ABOUT:
        e["about"] = LAYOUT_ABOUT[(layout, variant)]
    return e


def xkb_layouts() -> list:
    """[{layout, variant, name, keys, about?}] from XKB's list: every layout, then each one's variants. keys: extra words
    search matches (XKB's short forms spelled out). XKB's "custom" placeholder (a layout nobody has filled in) is
    left out."""
    try:
        text = XKB_LST.read_text(errors="replace")
    except OSError:
        return []
    out, section = [], ""
    for line in text.splitlines():
        if line.startswith("!"):
            section = line[1:].strip()
            continue
        line = line.strip()
        if not line:
            continue
        if section == "layout":
            m = re.match(r"(\S+)\s+(.+)", line)
            if m and m.group(1) != "custom":
                out.append(layout_entry(m.group(1), "", m.group(2).strip()))
        elif section == "variant":
            m = re.match(r"(\S+)\s+(\S+):\s+(.+)", line)
            if m and m.group(2) != "custom":
                out.append(layout_entry(m.group(2), m.group(1), m.group(3).strip()))
    return out


# ---------------------------------------------------------------- desktop entries

def read_entry(path: Path) -> dict:
    e, inside = {}, False
    try:
        for line in path.read_text(errors="replace").splitlines():
            if line.startswith("["):
                inside = line.strip() == "[Desktop Entry]"
            elif inside and "=" in line and not line.lstrip().startswith("#"):
                k, v = line.split("=", 1)
                e.setdefault(k.strip(), v.strip())
    except OSError:
        return {}
    return e


def app_dirs() -> list:
    dirs = []
    for d in reversed((os.environ.get("XDG_DATA_DIRS") or "/usr/local/share:/usr/share").split(":")):
        if d:
            dirs.append(Path(d) / "applications")
    dirs += [Path("/var/lib/flatpak/exports/share/applications"), HOME / ".local/share/flatpak/exports/share/applications",
             HOME / ".local/share/applications"]
    return dirs


def find_app(app_id: str) -> Path | None:
    for d in reversed(app_dirs()):
        p = d / f"{app_id}.desktop"
        if p.is_file():
            return p
    return None


def exec_argv(line: str) -> list:
    try:
        words = shlex.split(line)
    except ValueError:
        return []
    return [w.replace("%%", "%") for w in words if not (len(w) == 2 and w[0] == "%" and w[1] in "fFuUdDnNickvm")]


def installed_apps() -> list:
    by = {}
    for d in app_dirs():
        try:
            files = sorted(d.glob("*.desktop"))
        except OSError:
            continue
        for f in files:
            e = read_entry(f)
            if e:
                by[f.stem] = dict(e, id=f.stem)
    out = []
    for e in by.values():
        if (not e.get("Name") or e.get("NoDisplay") == "true" or e.get("Hidden") == "true"
                or e.get("Type", "Application") != "Application" or e["id"] in HIDDEN_APPS or not e.get("Exec")):
            continue
        about = next((x for x in (e.get("GenericName", ""), e.get("Comment", "")) if x and x.lower() != e["Name"].lower()), "")
        plain = PLAIN_APPS.get(e["id"])
        # an extra action of one of Starchaser's own apps ("thunar --bulk-rename") says whose it is
        argv = exec_argv(e.get("Exec", ""))
        owner = PLAIN_APPS.get(os.path.basename(argv[0])) if len(argv) > 1 and not plain else None
        # a settings or helper window of one of Starchaser's own apps is not an app to pick for sign-in or a shortcut;
        # only these named ones: another program started through kitty or mpv is still a real app (r134 review)
        if e["id"] in HELPER_APPS:
            continue
        if owner:
            about = " · ".join(x for x in (about, owner[0]) if x)
        out.append({"id": e["id"], "name": plain[0] if plain else e["Name"], "icon": e.get("Icon", ""),
                    "group": "Usual apps" if plain else "Other apps",
                    "about": plain[1] if plain else about, "program": e["Name"] if plain else "",
                    "search": f"{e['Name']} {about}" if plain else "",
                    "terminal": in_terminal(e)})
    plain_names(out)
    # Starchaser's own apps (Files, Terminal, Text editor ...) first, the people most often want them; then A-Z
    out.sort(key=lambda a: (a["id"] not in PLAIN_APPS, a["name"].lower()))
    return out


def plain_names(out: list) -> None:
    """A plain name ("Text editor") shows the program's own name in its line only when another row has the same
    name, so look-alikes can still be told apart; otherwise a first-time user sees plain words only."""
    seen = {}
    for a in out:
        seen[a["name"].lower()] = seen.get(a["name"].lower(), 0) + 1
    for a in out:
        prog = a.pop("program", "")
        if prog and seen[a["name"].lower()] > 1:
            a["about"] = f"{a['about']} ({prog})"


def in_terminal(e: dict) -> bool:
    """Terminal=true, except on a Flatpak app: Flathub takes only apps with windows of their own, so a Terminal=true
    there is a packaging slip (Solitaire's), and honoring it put a terminal full of the game's log beside the game,
    and closing it closed the game (QA 20261104-0018 002)."""
    return e.get("Terminal", "").lower() == "true" and not e.get("X-Flatpak")


def launch_command(app_id: str) -> str:
    """The command a shortcut runs to open an installed app: gtk-launch, or the terminal for a terminal app (gtk-launch
    can't start those here: it wants a terminal Starchaser doesn't have). Every terminal opens through
    starchaser terminal: kitty, or the screen reader's terminal while that runs."""
    p = find_app(app_id)
    if not p:
        raise Fail(f"no installed app {app_id}")
    e = read_entry(p)
    if app_id == "kitty":
        return "starchaser terminal"
    if e.get("Terminal", "").lower() == "true":
        argv = exec_argv(e.get("Exec", ""))
        if not argv:
            raise Fail(f"{app_id} has nothing to run")
        # no "Are you sure you want to close this OS Window?" from kitty when the app is closed with Super+Q; a
        # Flatpak app's slip (in_terminal) runs by itself, as gtk-launch would look for a terminal and give up, and a
        # real Flathub terminal program (Micro), which then quits at once with an error, opens in kitty after all, and
        # one that prints and quits cleanly (Ponysay) in a kitty that stays open, unless the app's window is open (a
        # clean quit then hands off to it) (QA 20261106-0424 001); as keybinds/menu.py terminal_fallback
        cmd = " ".join(shlex.quote(a) for a in argv)
        kitty = "starchaser terminal -o confirm_os_window_close=0"
        if in_terminal(e):
            return f"{kitty} {cmd}"
        window = shlex.quote(f'"class": "{e.get("X-Flatpak", "")}"')
        return "sh -c " + shlex.quote(f"t=$(date +%s); {cmd}; r=$?; [ $(($(date +%s) - t)) -ge 3 ] && exit; "
                                      f"[ $r != 0 ] && exec {kitty} {cmd}; "
                                      f"hyprctl clients -j | grep -qF {window} || exec {kitty} --hold {cmd}")
    return "gtk-launch " + shlex.quote(app_id)


# ---------------------------------------------------------------- start at sign-in (XDG autostart)

def system_autostart_dirs() -> list:
    return [Path(d) / "autostart" for d in (os.environ.get("XDG_CONFIG_DIRS") or "/etc/xdg").split(":") if d]


def program_there(e: dict) -> bool:
    """False when the entry's program isn't installed: its TryExec, else the program its Exec line starts (an entry
    you added has no TryExec, so an app uninstalled since still read as on; systemd's generator skips both)."""
    te = e.get("TryExec", "")
    if not te:
        argv = exec_argv(e.get("Exec", ""))
        te = argv[0] if argv else ""
    if not te:
        return True
    te = os.path.expanduser(te)
    return bool(shutil.which(te) if "/" not in te else os.access(te, os.X_OK))


def desktop_ok(e: dict) -> bool:
    only = [x for x in e.get("OnlyShowIn", "").split(";") if x]
    never = [x for x in e.get("NotShowIn", "").split(";") if x]
    if only and not any(d in only for d in DESKTOP):
        return False
    return not any(d in never for d in DESKTOP)


def runs_here(e: dict) -> bool:
    return desktop_ok(e) and program_there(e)


def is_on(e: dict) -> bool:
    return e.get("Hidden", "").lower() != "true" and e.get("X-GNOME-Autostart-enabled", "").lower() != "false"


def command_missing(command: str) -> bool:
    """Check a plain executable with arguments without running it; leave shell expressions to the shell."""
    if re.search(r"[;&|<>()`$\n]", command):
        return False
    try:
        words = shlex.split(command)
    except ValueError:
        return False
    if not words or not re.fullmatch(r"[A-Za-z_/.~][A-Za-z0-9_./+~-]*", words[0]):
        return False
    # command -v also recognizes shell built-ins, which shutil.which does not.
    return subprocess.run(["sh", "-c", 'command -v "$1" >/dev/null 2>&1', "sign-in-check",
                           os.path.expanduser(words[0])], check=False).returncode != 0


def autostart_list() -> list:
    system = {}
    for d in reversed(system_autostart_dirs()):
        for f in sorted(d.glob("*.desktop")) if d.is_dir() else []:
            system[f.name] = f
    user = {f.name: f for f in sorted(AUTOSTART.glob("*.desktop"))} if AUTOSTART.is_dir() else {}
    out = []
    for fname in sorted(set(system) | set(user)):
        path = user.get(fname) or system[fname]
        e = read_entry(path)
        if not e or e.get("Type", "Application") != "Application":
            continue
        sys_e = read_entry(system[fname]) if fname in system else {}
        # what never runs here isn't listed, by the rules of systemd's generator: entries for other desktops, ones
        # whose program is missing, ones the system itself removed (Hidden), ones with nothing to run, and ones marked
        # X-systemd-skip=true (xdg-user-dirs: a systemd unit of its own does that job). A GNOME startup phase is no
        # reason: the generator skips a phased entry only when it is for GNOME alone (OnlyShowIn=GNOME, which
        # runs_here already leaves out) and otherwise makes a unit that runs everywhere but GNOME.
        # Everything else is listed, NoDisplay services too: they do start.
        # A copy of your own that turns a system entry on is the one that runs, so it is the one checked: one enabling
        # an entry made for another desktop ran at sign-in but wasn't listed, so its switch couldn't turn it off.
        # A copy that turns one off is checked by the system entry (would it run if turned back on?).
        chk = e if fname in user and is_on(e) else sys_e
        if fname in system and (not runs_here(chk) or (chk is sys_e and sys_e.get("Hidden", "").lower() == "true")
                                or not chk.get("Exec") or chk.get("X-systemd-skip", "").lower() == "true"):
            continue
        # one you added whose program has gone (uninstalled) is still listed, marked missing, so it can be seen and
        # removed; one you added for another desktop only isn't
        missing = fname not in system and not program_there(e)
        if fname not in system and not desktop_ok(e) and is_on(e):
            continue
        plain = PLAIN_APPS.get(fname[:-8])
        name = plain[0] if plain else e.get("Name") or fname[:-8]
        # the line under the name: a typed command as typed; an app's own description, never its Exec line (field
        # codes like %u mean nothing to a person)
        command = e.get("X-Starchaser-Command") or ""
        command_not_found = bool(command) and command_missing(command)
        if not command and fname in system and not e.get("Comment"):
            command = " ".join(exec_argv(e.get("Exec", "")))
        out.append({"id": fname[:-8], "name": name, "icon": e.get("Icon", ""), "command": command,
                    "on": is_on(e), "system": fname in system, "missing": missing or command_not_found,
                    "commandNotFound": command_not_found,
                    "about": plain[1] if plain else e.get("Comment", ""),
                    "program": (e.get("Name") or fname[:-8]) if plain else "",
                    "search": f"{e.get('Name') or ''} {e.get('Comment') or ''}".strip() if plain else ""})
    plain_names(out)
    out.sort(key=lambda a: a["name"].lower())
    return out


def entry_set(text: str, changes: dict) -> str:
    """Set or (value None) remove keys in a desktop file's [Desktop Entry] group; the rest stays as it was."""
    lines, out, inside, done = text.splitlines(), [], False, set()
    for line in lines:
        if line.startswith("["):
            if inside:
                out += [f"{k}={v}" for k, v in changes.items() if v is not None and k not in done]
                done |= set(changes)
            inside = line.strip() == "[Desktop Entry]"
            out.append(line)
            continue
        if inside and "=" in line and not line.lstrip().startswith("#"):
            k = line.split("=", 1)[0].strip()
            if k in changes:
                if changes[k] is not None and k not in done:
                    out.append(f"{k}={changes[k]}")
                done.add(k)
                continue
        out.append(line)
    if inside:
        out += [f"{k}={v}" for k, v in changes.items() if v is not None and k not in done]
    return "\n".join(out).rstrip("\n") + "\n"


def safe_id(v: str) -> str:
    if not re.fullmatch(r"[A-Za-z0-9._+-]{1,120}", v or "") or v.startswith("."):
        raise Fail(f"not an id: {v}")
    return v


SCRIPTS = Path(os.environ.get("XDG_DATA_HOME") or HOME / ".local/share") / "starchaser/sign-in"
# the last entry of each name taken off the list, for Undo (autostart restore)
REMOVED = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/sign-in-removed"


def desktop_exec_path(path) -> str:
    """One word (a program's path, an argument) as a desktop file's Exec has it: as it is, or quoted by the Desktop
    Entry rules when it has to be."""
    p = str(path)
    if re.fullmatch(r"[A-Za-z0-9/._+=:,@-]+", p):
        return p
    return ('"' + re.sub(r'([\\"`$])', r"\\\1", p) + '"').replace("\\", "\\\\").replace("%", "%%")


def cmd_autostart(args: list) -> int:
    sub = args[0] if args else "list"
    if sub == "list":
        if len(args) > 1:
            return takes_nothing_after("starchaser input", "autostart list", args)
        print(json.dumps(autostart_list()))
        return 0
    AUTOSTART.mkdir(parents=True, exist_ok=True)
    if sub == "add" and len(args) == 2:
        app = safe_id(args[1])
        src = find_app(app)
        if not src:
            raise Fail(f"no installed app {app}")
        changes = {"Hidden": None, "X-GNOME-Autostart-enabled": None, "NoDisplay": None, "OnlyShowIn": None,
                   "NotShowIn": None}
        e = read_entry(src)
        if in_terminal(e):
            # systemd's generator ignores Terminal=, so a terminal app would start with no window: open it in the
            # terminal, as a custom shortcut does (field codes like %U mean nothing at sign-in and are dropped); by its
            # full path, as sign-in's PATH may lack ~/.local/bin
            argv = exec_argv(e.get("Exec", ""))
            if not argv:
                raise Fail(f"{app} has nothing to run")
            changes.update({"Exec": " ".join(desktop_exec_path(w) for w in [shutil.which("starchaser") or "starchaser", "terminal",
                                                                      "-o", "confirm_os_window_close=0", *argv]),
                            "Terminal": "false",
                            "TryExec": None})
        text = entry_set(src.read_text(errors="replace"), changes)
        write_file(AUTOSTART / f"{app}.desktop", text)
        print(f"Added {e.get('Name') or app} to the apps that start when you sign in.")
        return 0
    if (sub == "add-command" and len(args) == 3) or (sub == "edit-command" and len(args) == 4):
        name, cmd = args[-2].strip(), args[-1].strip()
        if not name or not cmd or "\n" in name + cmd:
            raise Fail("a name and a command are needed")
        if command_missing(cmd):
            raise Fail("This command wasn't found. Check its spelling or choose an app instead.")
        if sub == "edit-command":
            fid = safe_id(args[1])
            entry = read_entry(AUTOSTART / f"{fid}.desktop")
            if not entry.get("X-Starchaser-Command") or any((d / f"{fid}.desktop").exists() for d in system_autostart_dirs()):
                raise Fail("Only a command you added can be edited here.")
        else:
            entry = {}
            # accents fold away (Café -> cafe); a name with no letters or numbers gets 'command', numbered
            folded = unicodedata.normalize("NFKD", name).encode("ascii", "ignore").decode()
            slug = re.sub(r"[^a-z0-9]+", "-", folded.lower()).strip("-")[:40] or "command"
            fid, n = f"starchaser-{slug}", 2
            while (AUTOSTART / f"{fid}.desktop").exists():
                fid, n = f"starchaser-{slug}-{n}", n + 1
        # the command goes in a small script of its own, run as it was typed: a shell command inside Exec= has to
        # survive two rounds of quoting (the Desktop Entry rules, then systemd's generator), which lost $VARIABLES
        script = SCRIPTS / f"{fid}.sh"
        write_file(script, f"#!/bin/sh\n# {name}: added in Starchaser Settings > Start at sign-in\n{cmd}\n")
        script.chmod(0o755)
        write_file(AUTOSTART / f"{fid}.desktop",
                   "[Desktop Entry]\nType=Application\n"
                   f"Name={name}\nExec={desktop_exec_path(script)}\nX-Starchaser-Command={cmd}\n"
                   + ("Hidden=true\n" if entry and not is_on(entry) else ""))
        # the id too: the next command (on, off, remove) takes the id, and the name typed here is not it
        print(f"Added {name} ({fid}) to the apps that start when you sign in." if sub == "add-command" else f"Saved {name}.")
        return 0
    if sub in ("on", "off") and len(args) == 2:
        fid = safe_id(args[1])
        mine = AUTOSTART / f"{fid}.desktop"
        if not mine.exists():
            src = next((d / f"{fid}.desktop" for d in system_autostart_dirs() if (d / f"{fid}.desktop").is_file()), None)
            if not src:
                raise Fail(f"nothing starts as {fid}. Use an id from 'starchaser input autostart list'.")
            if sub == "on" and is_on(read_entry(src)):
                print(f"Turned {sub} {fid}.")     # a system one with no change of yours is already on
                return 0
            text = src.read_text(errors="replace")
        else:
            text = mine.read_text(errors="replace")
        on = sub == "on"
        new = entry_set(text, {"Hidden": None if on else "true", "X-GNOME-Autostart-enabled": None})
        if on and mine.exists():
            # a system entry turned off and on again: when your copy now differs from the system's only in those
            # two keys, it goes, so later package changes to the entry (Exec, TryExec...) reach you again. A copy
            # with other changes of yours is kept.
            src = next((d / f"{fid}.desktop" for d in system_autostart_dirs() if (d / f"{fid}.desktop").is_file()), None)
            if src:
                base = entry_set(src.read_text(errors="replace"), {"Hidden": None, "X-GNOME-Autostart-enabled": None})
                if base == new and is_on(read_entry(src)):
                    mine.unlink()
                    print(f"Turned {sub} {fid}.")
                    return 0
        write_file(mine, new)
        print(f"Turned {sub} {fid}.")
        return 0
    if sub == "remove" and len(args) == 2:
        fid = safe_id(args[1])
        if any((d / f"{fid}.desktop").is_file() for d in system_autostart_dirs()):
            raise Fail("this one comes with the system: turn it off instead")
        if not (AUTOSTART / f"{fid}.desktop").is_file() and not (SCRIPTS / f"{fid}.sh").is_file():
            raise Fail(f"nothing starts as {fid}. Use an id from 'starchaser input autostart list'.")
        # kept aside (not deleted) so Settings' Undo can put it back: the entry and its script, when it had one
        REMOVED.mkdir(parents=True, exist_ok=True)
        moved = False
        try:
            shutil.move(AUTOSTART / f"{fid}.desktop", REMOVED / f"{fid}.desktop")
            moved = True
        except FileNotFoundError:
            pass
        try:
            shutil.move(SCRIPTS / f"{fid}.sh", REMOVED / f"{fid}.sh")
        except FileNotFoundError:
            if moved:      # an entry without a script: an older script of the same name must not come back with it
                (REMOVED / f"{fid}.sh").unlink(missing_ok=True)
        print(f"Removed {fid}.")
        return 0
    if sub == "restore" and len(args) == 2:
        fid = safe_id(args[1])
        entry = REMOVED / f"{fid}.desktop"
        if not entry.is_file():
            raise Fail("there is nothing to put back")
        if (AUTOSTART / f"{fid}.desktop").exists():
            raise Fail("it is already on the list")
        if (REMOVED / f"{fid}.sh").is_file():
            SCRIPTS.mkdir(parents=True, exist_ok=True)
            shutil.move(REMOVED / f"{fid}.sh", SCRIPTS / f"{fid}.sh")
        shutil.move(entry, AUTOSTART / f"{fid}.desktop")
        print(f"Put {fid} back.")
        return 0
    raise Fail("autostart list | add APP-ID | add-command NAME COMMAND | edit-command ID NAME COMMAND | on ID | off ID | remove ID | restore ID")


# ---------------------------------------------------------------- custom shortcuts

KEYS_HELP = 'Use + between keys, for example: starchaser input shortcut check "Super+Q". Modifiers: Super, Ctrl, Alt, Shift.'
MODS = ("SUPER", "CTRL", "ALT", "SHIFT")
MOD_BITS = {"SHIFT": 1, "CTRL": 4, "ALT": 8, "SUPER": 64}
KEY_RE = re.compile(r"[A-Z0-9]|F([1-9]|1[0-9]|2[0-4])|RETURN|SPACE|TAB|BACKSPACE|DELETE|HOME|END|PRIOR|NEXT|INSERT|"
                    r"PRINT|ESCAPE|left|right|up|down|slash|backslash|comma|period|semicolon|apostrophe|bracketleft|"
                    r"bracketright|minus|equal|grave")


def norm_keys(keys: str) -> str:
    """"super + g" -> "SUPER + G": modifiers in Starchaser's order, then one key. A key without Super, Ctrl or Alt
    (a plain letter) would stop that letter typing anywhere, so one of them is needed (F-keys and Print excepted)."""
    parts = [p.strip() for p in str(keys).split("+") if p.strip()]
    if not parts:
        raise Fail("no keys. " + KEYS_HELP)
    key = parts[-1]
    mods = []
    for p in parts[:-1]:
        u = p.upper().replace("CONTROL", "CTRL").replace("META", "SUPER")
        if u not in MODS:
            raise Fail(f"not a modifier: {p}. " + KEYS_HELP)
        if u not in mods:
            mods.append(u)
    lower = key.lower()
    if lower in ("left", "right", "up", "down") or lower in ("slash", "backslash", "comma", "period", "semicolon",
                                                             "apostrophe", "bracketleft", "bracketright", "minus",
                                                             "equal", "grave"):
        key = lower
    else:
        key = key.upper()
    if not KEY_RE.fullmatch(key):
        raise Fail(f"not a key Settings can bind: {parts[-1]}. " + KEYS_HELP)
    if not any(m in mods for m in ("SUPER", "CTRL", "ALT")) and not re.fullmatch(r"F\d+|PRINT", key):
        raise Fail("a shortcut needs Super, Ctrl or Alt (or an F key)")
    if sorted(mods) == ["ALT", "CTRL"] and re.fullmatch(r"F([1-9]|1[0-2])", key):
        raise Fail("Ctrl + Alt with F1 to F12 switches to a black screen with only text, so it can't be a shortcut")
    mods.sort(key=MODS.index)
    return " + ".join(mods + [key])


def custom_list():
    v, broken = read_lua(CUSTOM_LUA)
    out = []
    for it in v if isinstance(v, list) else []:
        if isinstance(it, dict) and isinstance(it.get("name"), str) and isinstance(it.get("keys"), str) \
                and isinstance(it.get("run"), str):
            out.append({"name": it["name"], "keys": it["keys"], "run": it["run"], "app": str(it.get("app") or "")})
    return out, broken


def custom_list_now() -> list:
    """custom_list, each with `blocked`: the shortcut of the profile in use that holds its key, when hyprland.lua left
    it out for that reason (a key picked in another profile, or given to a profile shortcut since)."""
    items, _ = custom_list()
    binds = bound_keys()
    descs = {d for _, d in binds}
    # hyprland.lua reads the Lua copy: when that is missing or couldn't be loaded (its export says broken), the
    # changes saved in the JSON aren't in effect and every custom shortcut has its own keys
    try:
        ex = json.loads(SHORTCUTS_EXPORT.read_text())
    except (OSError, ValueError):
        ex = {}
    try:
        ov = json.loads(OVERRIDES[0][0].read_text()) if OVERRIDES[0][1].exists() else {}
    except (OSError, ValueError):
        ov = {}
    if not isinstance(ov, dict) or (isinstance(ex, dict) and ex.get("broken") is True):
        ov = {}
    for it in items:
        it["blocked"], it["off"] = "", False
        # a change made to it in Settings > Shortcuts (for the profile in use) wins, the way hyprland.lua reads it:
        # turned off there, or moved to other keys, which are the ones that work
        o = ov.get("Custom: " + it["name"])
        k = o.get("keys") if isinstance(o, dict) else None
        if isinstance(k, str) and k.lower() == "off":
            it["off"] = True
            continue
        if isinstance(k, str) and k:
            it["keys"] = k
        if binds and "Custom: " + it["name"] not in descs:
            it["blocked"] = next((d or "another shortcut" for c, d in binds if same_combo(c, it["keys"])), "")
    return items


CUSTOM_HEADER = """-- Written by Starchaser Settings > Custom shortcuts (bin/starchaser-input). hyprland.lua binds each one as
-- "Custom: <name>" in every shortcut profile; a missing or broken file adds none.
"""


def save_custom(items: list, broken: bool) -> None:
    if broken:
        keep_broken(CUSTOM_LUA)
    write_file(CUSTOM_LUA, CUSTOM_HEADER + "return " + lua_val(items, "") + "\n")


def bound_keys() -> list:
    """[(combo, description)] for every shortcut Hyprland has now."""
    try:
        binds = json.loads(hyprctl("binds", "-j") or "[]")
    except ValueError:
        return []
    out = []
    for b in binds:
        if b.get("submap") or b.get("mouse"):
            continue
        key = str(b.get("key") or "")
        if not key:
            continue
        mods = [m for m in MODS if int(b.get("modmask") or 0) & MOD_BITS[m]]
        out.append((" + ".join(mods + [key]), str(b.get("description") or "")))
    return out


def combo_id(k: str) -> tuple:
    parts = [p.strip().upper().replace("CONTROL", "CTRL") for p in str(k).split("+") if p.strip()]
    return (tuple(sorted(parts[:-1])), parts[-1] if parts else "")


def same_combo(a: str, b: str) -> bool:
    return combo_id(a) == combo_id(b)


SHORTCUTS_EXPORT = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-shortcuts.json"
OVERRIDES = [(HOME / ".config/starchaser/shortcuts.json", CONFIG / "hypr/shortcuts.lua")]
SAVED_PROFILES = HOME / ".config/starchaser/shortcut-profiles"


def other_profile_conflict(keys: str) -> tuple:
    """(description, profile name) of a shortcut that has KEYS in a shortcut profile other than the one in use, from
    what hyprland.lua exports on each load (starchaser shortcuts reads the same file), with your own changes for that
    profile on top. Custom shortcuts load in every profile, so a key one profile uses would clash there."""
    try:
        ex = json.loads(SHORTCUTS_EXPORT.read_text())
    except (OSError, ValueError):
        return "", ""
    if not isinstance(ex, dict) or not isinstance(ex.get("profiles"), dict):
        return "", ""
    profs, code = ex["profiles"], ex.get("code") if isinstance(ex.get("code"), dict) else {}
    hw = set(ex.get("hardware") or [])
    star = (profs.get("starchaser") or {}).get("keys")
    star = star if isinstance(star, dict) else {}
    for pid, prof in profs.items():
        if pid == ex.get("applied") or not isinstance(prof, dict):
            continue
        pk = prof.get("keys") if isinstance(prof.get("keys"), dict) else {}
        try:
            mine = json.loads((SAVED_PROFILES / f"{pid}.json").read_text())
        except (OSError, ValueError):
            mine = {}
        mine = mine if isinstance(mine, dict) else {}
        for d in ex.get("codeOrder") or list(code):
            if not isinstance(d, str) or d in hw or d.startswith("Custom: "):
                continue
            v = pk.get(d, star.get(d, code.get(d, "")))
            for n, k in enumerate(v if isinstance(v, list) else [v]):
                dn = d if n == 0 else f"{d} (key {n + 1})"
                own = mine.get(dn)
                k = own["keys"] if isinstance(own, dict) and isinstance(own.get("keys"), str) else k
                if isinstance(k, str) and k and k != "off" and same_combo(k, keys):
                    return d, str(prof.get("name") or pid)
    return "", ""


def override_files() -> list:
    """[(json, lua)] of the profile in use and every saved profile."""
    pairs = list(OVERRIDES)
    if SAVED_PROFILES.is_dir():
        pairs += [(j, j.with_suffix(".lua")) for j in sorted(SAVED_PROFILES.glob("*.json"))]
    return pairs


def write_overrides(js: Path, lua: Path, st: dict) -> None:
    write_file(js, json.dumps(st, indent=2) + "\n")
    rows = [f"    [{lua_str(d)}] = {lua_str(e['keys'])},\n" for d, e in st.items()
            if isinstance(e, dict) and isinstance(e.get("keys"), str)]
    write_file(lua, '-- Written by Starchaser Settings > Shortcuts. Description -> new keys, or "off".\nreturn {\n'
               + "".join(rows) + "}\n")


# the last custom shortcut of each name taken off the list, with where it was and its changes in each profile
# (Settings' Undo puts all of it back: re-adding it from the keys on screen lost "off" and the other profiles' keys)
REMOVED_SHORTCUTS = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/custom-shortcuts-removed.json"


def stash_removed(item: dict, at: int) -> None:
    ovs = {}
    for js, _ in override_files():
        try:
            st = json.loads(js.read_text())
        except (OSError, ValueError):
            continue
        if isinstance(st, dict) and "Custom: " + item["name"] in st:
            ovs[str(js)] = st["Custom: " + item["name"]]
    try:
        old = json.loads(REMOVED_SHORTCUTS.read_text())
    except (OSError, ValueError):
        old = {}
    if not isinstance(old, dict):
        old = {}
    old[item["name"]] = {"item": item, "at": at, "overrides": ovs}
    REMOVED_SHORTCUTS.parent.mkdir(parents=True, exist_ok=True)
    write_file(REMOVED_SHORTCUTS, json.dumps(old, indent=2) + "\n")


def restore_removed(name: str) -> int:
    try:
        stash = json.loads(REMOVED_SHORTCUTS.read_text())
        r = stash[name]
        item = r["item"]
        assert isinstance(item, dict) and item.get("name") == name and isinstance(item.get("keys"), str) \
            and isinstance(item.get("run"), str)
    except (OSError, ValueError, KeyError, TypeError, AssertionError):
        raise Fail("there is nothing to put back") from None
    items, broken = custom_list()
    if any(i["name"] == name for i in items):
        raise Fail("it is already on the list")
    at = r.get("at") if isinstance(r.get("at"), int) else len(items)
    items.insert(max(0, min(at, len(items))), {"name": name, "keys": item["keys"], "run": item["run"],
                                               "app": str(item.get("app") or "")})
    save_custom(items, broken)
    known = {str(js): (js, lua) for js, lua in override_files()}
    for path, entry in (r.get("overrides") or {}).items():
        if path not in known:          # a profile deleted meanwhile
            continue
        js, lua = known[path]
        try:
            st = json.loads(js.read_text())
        except (OSError, ValueError):
            st = {}
        if not isinstance(st, dict):
            continue
        st["Custom: " + name] = entry
        write_overrides(js, lua, st)
    del stash[name]
    write_file(REMOVED_SHORTCUTS, json.dumps(stash, indent=2) + "\n")
    reload_hyprland()
    print(f'Put shortcut "{name}" back.')
    return 0


def drop_overrides(descs: set) -> None:
    """A custom shortcut's keys changed (or it went): a change made to it in Settings > Shortcuts, in any profile, is
    dropped, so the keys picked on the Custom shortcuts page are the ones that work. Written the way Settings >
    Shortcuts writes them (its JSON, and the Lua table hyprland.lua reads)."""
    for js, lua in override_files():
        try:
            st = json.loads(js.read_text())
        except (OSError, ValueError):
            continue
        if not isinstance(st, dict) or not descs & set(st):
            continue
        for d in descs:
            st.pop(d, None)
        write_overrides(js, lua, st)


def conflict(keys: str, ignore_name: str = "") -> dict:
    """{} when KEYS are free, else {usedBy: description, profile: the other profile's name ("" for the one in use)}."""
    ignore = "Custom: " + ignore_name if ignore_name else None
    for combo, desc in bound_keys():
        if same_combo(combo, keys) and desc != ignore:
            return {"usedBy": desc or "another shortcut", "profile": ""}
    for it in custom_list()[0]:
        if same_combo(it["keys"], keys) and it["name"] != ignore_name:
            return {"usedBy": "Custom: " + it["name"], "profile": ""}
    d, prof = other_profile_conflict(keys)
    return {"usedBy": d, "profile": prof} if d else {}


def conflict_words(keys: str, used: dict) -> str:
    """One plain sentence about keys that are already taken, naming where (the JSON keeps its fields beside it)."""
    if not used:
        return ""
    other = used.get("profile") or ""
    where = other
    if not where:                       # the profile in use: name it too, so "already used" says by what
        try:
            ex = json.loads(SHORTCUTS_EXPORT.read_text())
            profs = ex.get("profiles") if isinstance(ex.get("profiles"), dict) else {}
            applied = profs.get(ex.get("applied") or "")
            where = str((applied or {}).get("name") or ex.get("applied") or "")
        except (OSError, ValueError):
            where = ""
    if other:
        return (f"{keys} is used by '{used['usedBy']}' in the {other} profile; "
                "pick another key or switch to that profile.")
    if where:
        return f"{keys} is used by '{used['usedBy']}' in the {where} profile, the one in use; pick another key."
    return f"{keys} is used by '{used['usedBy']}'; pick another key."


# Starchaser's default keys that changed, in the order they are checked: (the action or one of its keys, its old key,
# its new key). A key the person gave to something else (a change in Settings > Shortcuts, or a custom shortcut) wins:
# the action keeps its old key instead, and that old key is then checked against the next row (Ask's old key is the
# main menu's new one). Every shortcut profile has these keys in these slots.
DEFAULT_KEY_CHANGES = [
    # Historical r541 migration (11-02 #21); current profile defaults follow decision 60 (Ask on Super+A).
    # Keep this once-only migration for older saved custom-key conflicts.
    ("AI: AI slot 1", "SUPER + SHIFT + A", "SUPER + CTRL + ALT + A"),
    ("AI: Ask Starchaser", "SUPER + SPACE", "SUPER + SHIFT + A"),
    # decided 2026-11-03 (#20): the menu on Super+Space (its first key in every profile), no tap of Super
    ("Shell: Open the main menu", "SUPER + Super_L", "SUPER + SPACE"),
]
KEEP_MINE_DONE = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/shortcut-keys-r541"


def keep_mine() -> list:
    """Once, after an update that changed default keys (hyprland.lua runs it before reading your changes): in the
    profile in use and every saved profile, an action whose new default key you had already given to something else
    keeps its old key, written as your own change, so both keep working. Actions you changed yourself are left alone.
    Returns what it kept, as (file, action, key)."""
    customs = custom_list()[0]
    kept = []
    for js, lua in override_files():
        try:
            st = json.loads(js.read_text())
        except (OSError, ValueError):
            st = None
        if not isinstance(st, dict):
            v, broken = read_lua(lua)
            if broken:
                continue        # a file Hyprland can't read either: nothing in it is in effect, leave it for Settings
            st = {d: {"keys": k} for d, k in (v or {}).items() if isinstance(d, str) and isinstance(k, str)} \
                if isinstance(v, dict) else {}
        if not js.exists() and not lua.exists() and js != OVERRIDES[0][0]:
            continue
        mine = {}
        for c in customs:
            o = st.get("Custom: " + c["name"])
            mine[combo_id(o["keys"] if isinstance(o, dict) and isinstance(o.get("keys"), str) else c["keys"])] = \
                "Custom: " + c["name"]
        for d, e in st.items():
            if isinstance(e, dict) and isinstance(e.get("keys"), str) and e["keys"].lower() != "off" and e["keys"]:
                mine[combo_id(e["keys"])] = d
        changed = False
        for desc, old, new in DEFAULT_KEY_CHANGES:
            if desc in st:
                continue
            holder = mine.get(combo_id(new))
            if holder and holder != desc:
                st[desc] = {"keys": old}
                mine[combo_id(old)] = desc
                kept.append((str(js), desc, old))
                changed = True
        if changed:
            write_overrides(js, lua, st)
    return kept


def cmd_shortcut(args: list) -> int:
    sub = args[0] if args else "list"
    if sub == "list":
        if len(args) > 1:
            return takes_nothing_after("starchaser input", "shortcut list", args)
        print(json.dumps(custom_list_now()))
        return 0
    if sub == "state":
        if len(args) > 1:
            return takes_nothing_after("starchaser input", "shortcut state", args)
        old = CUSTOM_LUA.with_name(CUSTOM_LUA.name + ".broken")
        print(json.dumps({"broken": custom_list()[1], "copy": str(old) if old.is_file() else ""}))
        return 0
    if sub == "check" and len(args) in (2, 3):
        keys = norm_keys(args[1])
        used = conflict(keys, args[2] if len(args) == 3 else "")
        words = conflict_words(keys, used)
        if words:
            print("starchaser input: " + words, file=sys.stderr)
        print(json.dumps({"keys": keys, "usedBy": used.get("usedBy", ""), "profile": used.get("profile", "")}))
        return 0
    if sub == "suggest" and len(args) in (1, 2, 3):
        # a few key combinations nothing uses in ANY shortcut profile, so nobody has to guess
        out = []
        # Try the app's letters first, then the usual fallback; keep two-modifier chords only.
        ign = args[1] if len(args) >= 2 else ""
        app_name = args[2] if len(args) == 3 else ""
        letters = dict.fromkeys(ch for ch in app_name.upper() + "GJKQUYZXVBNMH" if "A" <= ch <= "Z")
        for mods in ("SUPER + ALT", "SUPER + CTRL"):
            n = 0
            for ch in letters:
                k = f"{mods} + {ch}"
                if not conflict(k, ign):
                    out.append(k)
                    n += 1
                    if n >= 2:
                        break
        print(json.dumps([norm_keys(k) for k in out]))
        return 0
    if sub == "remove" and len(args) == 2:
        items, broken = custom_list()
        at = next((n for n, i in enumerate(items) if i["name"] == args[1]), None)
        if at is None:
            raise Fail(f"there is no shortcut named {args[1]}")
        # kept aside with its changes in every profile, for Settings' Undo (restore)
        stash_removed(items[at], at)
        save_custom([i for i in items if i["name"] != args[1]], broken)
        drop_overrides({"Custom: " + args[1]})
        reload_hyprland()
        print(f'Removed shortcut "{args[1]}".')
        return 0
    if sub == "restore" and len(args) == 2:
        return restore_removed(args[1])
    if sub == "add":
        rest = args[1:]
        old = ""
        if rest[:1] == ["--replace"]:
            if len(rest) < 2:
                raise Fail("--replace needs a name")
            old, rest = rest[1], rest[2:]
        if len(rest) != 4 or rest[2] not in ("app", "command"):
            raise Fail("shortcut add NAME KEYS app APP-ID | command COMMAND")
        name, keys, kind, what = rest[0].strip(), norm_keys(rest[1]), rest[2], rest[3].strip()
        if not name or len(name) > 60 or not re.fullmatch(r"[^\n\"\\]+", name):
            raise Fail("the name is 1 to 60 characters, without quotes or backslashes")
        if not what or "\n" in what:
            raise Fail("nothing to run")
        if kind == "command" and command_missing(what):
            raise Fail("This command wasn't found. Check its spelling or install the app, then try again.")
        items, broken = custom_list()
        at = next((n for n, i in enumerate(items) if i["name"] == old), None) if old else None
        if old and at is None:      # a typo in --replace: say so and add nothing, instead of adding a new one
            raise Fail(f"there is no shortcut named {old}")
        if any(i["name"] == name for i in items if i["name"] != old):
            raise Fail(f"there is already a shortcut named {name}")
        used = conflict(keys, old)
        if used:
            words = conflict_words(keys, used)
            if words:
                print("starchaser input: " + words, file=sys.stderr)
            print(json.dumps(used))
            return 3
        run = launch_command(safe_id(what)) if kind == "app" else what
        new = {"name": name, "keys": keys, "run": run, "app": what if kind == "app" else ""}
        if at is None:
            items.append(new)
        else:
            # the form shows the keys that work now, which a change in Settings > Shortcuts may have moved: saved
            # with only its command (or app) changed, those keys came back here as "new" keys, replaced the
            # shortcut's own and wiped its changes in every profile. Unchanged keys keep both.
            now = next((i for i in custom_list_now() if i["name"] == old), None)
            if old == name and now and not now.get("off") and same_combo(now["keys"], keys):
                new["keys"] = items[at]["keys"]
            elif items[at]["keys"] != keys or old != name:
                drop_overrides({"Custom: " + old, "Custom: " + name})
            items[at] = new
        save_custom(items, broken)
        reload_hyprland()
        print(f'{"Updated" if old else "Added"} shortcut "{name}" ({keys}).')
        return 0
    if sub == "keep-mine" and len(args) == 1:
        if KEEP_MINE_DONE.exists():
            return 0
        for path, desc, key in keep_mine():
            note(f"shortcut keys: {desc} keeps {key} in {path} (its new default key is one you use)")
        KEEP_MINE_DONE.parent.mkdir(parents=True, exist_ok=True)
        write_file(KEEP_MINE_DONE, "541\n")
        return 0
    raise Fail("shortcut list | state | add | remove NAME | restore NAME | check KEYS | keep-mine")


# ---------------------------------------------------------------- main

def wants_help(a: list) -> bool:
    """-h/--help right after the verb, or after sub-verbs. Inside an add it can be the shortcut's own name (a name
    may be '--help'), so there it is a help request unless a whole add follows it (NAME KEYS app|command WHAT)."""
    rest = a[1:]
    for x in rest:
        if x not in ("-h", "--help"):
            continue
        tail = []
        for i, y in enumerate(rest):
            if y in ("add", "--replace"):
                tail = rest[i + 1:]
                break
        if not tail:
            return True                             # help after the verb or a sub-verb, before any add
        if tail[0] == "--replace":
            tail = tail[2:]                         # --replace and the old name are not the new name's words
        return len(tail) < 4                        # NAME KEYS app|command WHAT is a whole add
    return False


def main() -> int:
    a = sys.argv[1:]
    cmd = a[0] if a else ""
    lock = None
    try:
        if cmd in ("-h", "--help", "help") or wants_help(a):   # help after the verb too
            sys.stdout.write(__doc__.lstrip())
            return 0
        if cmd == "get" and len(a) > 2:
            return usage_error("starchaser input", f"unexpected argument {a[2]!r}", "get [setting]")
        if cmd in ("keyboard", "layouts", "follow-layout", "apps", "supported") and len(a) > 1:
            return takes_nothing_after("starchaser input", cmd, a)
        if cmd == "get":
            return cmd_get(a[1:])
        if a == ["notify-broken"]:
            return notify_broken_input()
        if a == ["dismiss-broken-notice"]:
            dismiss_broken_notice()
            return 0
        if cmd in ("set", "device", "restore-defaults", "autostart", "shortcut") and a[1:2] not in (["list"], ["check"], ["suggest"]) \
                or cmd == "trial" and a[1:2] != ["expire"]:
            lock = lock_changes()       # held until this change is written
        if cmd == "set":
            return cmd_set(a[1:])
        if cmd == "restore-defaults":
            return cmd_restore_defaults(a[1:])
        if cmd == "device":
            return cmd_device(a[1:])
        if cmd == "trial":
            return cmd_trial(a[1:])
        if cmd == "keyboard":
            state = keyboard_state()
            if not state:
                print("starchaser input: Couldn't read the desktop's keyboard state. Run this in your desktop session.", file=sys.stderr)
                return 1
            print(json.dumps(state))
            return 0
        if cmd == "switch-layout":
            return cmd_switch_layout(a[1:])
        if cmd == "layouts":
            print(json.dumps(xkb_layouts()))
            return 0
        if cmd == "follow-layout":
            return cmd_follow_layout()
        if cmd == "apps":
            print(json.dumps(installed_apps()))
            return 0
        if cmd == "supported":
            print(json.dumps(supported()))
            return 0
        if cmd == "autostart":
            return cmd_autostart(a[1:])
        if cmd == "shortcut":
            return cmd_shortcut(a[1:])
    except Fail as e:
        print(f"starchaser input: {e}", file=sys.stderr)
        return 2
    except OSError as e:
        # a settings folder it may not write: plain words naming where to look, not a bare system line
        print(f"starchaser input: {e.strerror or e}" if e.strerror is None else
              f"starchaser input: couldn't save your settings ({e.strerror}). Check that you can write to ~/.config.",
              file=sys.stderr)
        return 1
    finally:
        if lock:
            lock.close()
    if cmd:
        print(f"starchaser input: unknown command {cmd!r}. Run 'starchaser input --help' for more help.", file=sys.stderr)
        return 2
    sys.stderr.write(__doc__.lstrip())
    return 2


if __name__ == "__main__":
    sys.exit(main())
