diff --git a/packages/omamobile-settings/PKGBUILD b/packages/omamobile-settings/PKGBUILD index cb9f9b41c..5ca56b0ae 100644 --- a/packages/omamobile-settings/PKGBUILD +++ b/packages/omamobile-settings/PKGBUILD @@ -6,7 +6,7 @@ pkgdesc="Native mobile Settings framework and device information" arch=(aarch64 x86_64) url="https://github.com/derekross/omarchy-mobile" license=(MIT) -depends=(omarchy bash coreutils systemd brightnessctl polkit python qt6-base qt6-declarative qt6-svg) +depends=(omarchy 'omamobile-omarchy>=0.1.49' bash coreutils systemd brightnessctl polkit python qt6-base qt6-declarative qt6-svg) makedepends=(gcc make) checkdepends=(dbus python) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index 3cdd006cd..6bdd29bcb 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -10,8 +10,47 @@ This package contains the read-only foundation and one settings page, Display (brightness and, where the monitor lists more than one, the refresh rate; the refresh rate changes the running session only: turning the phone makes auto-rotate apply the monitor's preferred mode again, and a session restart or a -reload of Hyprland's config does too). The page runs -`backends/display.sh` through a fixed-argument runner, with no shell string. +reload of Hyprland's config does too) and the screen lock. The page runs +`backends/display.sh` and `backends/lock.sh` through a fixed-argument runner, +with no shell string. When Settings is started from a login outside the +graphical session (for example over SSH), display.sh finds Hyprland's instance +signature from `$XDG_RUNTIME_DIR/hypr/*/.socket.sock` (the newest live one) and +sets the brightness through the user's graphical session (loginctl Display). + +"Lock screen after" (30 s, 1, 2, 3 or 5 min) sets `idle.lock` in +`~/.config/omarchy/shell.json`, the one timer Omarchy's idle service has: the +phone locks after that long without input and the lock turns the screen off a +few seconds later, so lock and screen off are the same timer. There is no +Never: a phone that never locks by itself isn't offered one tap away. A 0 set +by hand in shell.json still means no idle lock, and the page says so. +"Lock after 30 minutes while a keyboard is connected" writes 1800 there while +a Bluetooth or USB keyboard (udev `ID_INPUT_KEYBOARD=1`, bus 0005, or bus 0003 +outside `/devices/virtual/input`, with the letter keys and space, a name, and +not a known security token or barcode scanner) is connected, and the chosen +time back when it goes. The user unit +`omamobile-lock-keyboard.service` follows `udevadm monitor` for input devices +and runs `lock.sh apply`. It is not enabled by the package: turning the toggle +on enables and starts it, turning it off stops and disables it (opening the +page puts the unit in line with a saved choice, e.g. after an upgrade), and when it +stops `lock.sh restore` writes the chosen time back. The 1800 is only written +while that unit runs; a failed apply (a broken `shell.json`) is logged once and +retried on the next input change instead of restarting the unit. After a write +the running shell is told with `omarchy-shell shell reloadConfig`, as +Omarchy's `omarchy-shell-config` does; if that fails the page shows an error +and the reload is tried again on the next change, even one that writes +nothing. If the watcher cannot be started the toggle goes back to off. +Stay awake and idle on/off are never touched. The choice lives in +`~/.config/omamobile/lock.json`, saved (only when it changed) before +`shell.json` with a flag saying whether the 1800 in force is the keyboard's, +kept until the chosen time is back in `shell.json`, so a crash at any point +never turns it into the owner's choice. A value changed in Omarchy's +own settings is adopted. Nothing is +written until the user picks something on the page, and nothing at all if the +user's `shell.json` does not parse. Both files are written under one `flock`. +Known limits: a USB receiver, dock or KVM that exposes a full keyboard +interface counts even with no keyboard behind it; a Bluetooth keyboard that +goes to sleep disconnects, so the timer comes back until it wakes. + A second page, Battery, sets the charge limit (80, 85, 90, 95 or 100 %), only on a phone whose device package declares one in `/usr/share/omamobile/charge-limit.conf` (a line `supply=NAME`; diff --git a/packages/omamobile-settings/app/DisplayPage.qml b/packages/omamobile-settings/app/DisplayPage.qml index 20609134d..70a71d10a 100644 --- a/packages/omamobile-settings/app/DisplayPage.qml +++ b/packages/omamobile-settings/app/DisplayPage.qml @@ -1,10 +1,14 @@ // SPDX-License-Identifier: MIT import QtQuick +import QtQuick.Controls import QtQuick.Layouts import "." -ColumnLayout { +// Scrolls like the About page, so the keyboard text at the end can be read +// on a short screen. +ScrollView { id: page - spacing: 14 + contentWidth: availableWidth + clip: true property int brightness: -1 property int refresh: -1 property var rates: [] @@ -12,6 +16,23 @@ ColumnLayout { property bool busy: true property int reqId: -1 readonly property var levels: [10, 25, 50, 75, 100] + // Screen lock (backends/lock.sh): one timer locks and then turns the screen off + property int lockAfter: -1 + property bool keyboardAwake: false + property bool keyboard: false + property bool lockBusy: true + property int lockReq: -1 + property string lockError: "" + readonly property var lockChoices: [{s: 30, t: qsTr("30 s")}, {s: 60, t: qsTr("1 min")}, {s: 120, t: qsTr("2 min")}, + {s: 180, t: qsTr("3 min")}, {s: 300, t: qsTr("5 min")}] + function applyLock(r) { + lockBusy = false + // a saved value with an error (the shell did not reload, the watcher did not start) shows both + if (r.lock !== undefined) { lockAfter = r.lock; keyboardAwake = !!r.keyboardAwake; keyboard = !!r.keyboard } + if (r.error) { lockError = r.error; return } + if (r.lock === undefined) { lockError = qsTr("The lock backend gave no values."); return } + lockError = "" + } function apply(r) { busy = false if (r.error) { status = r.error; return } @@ -20,8 +41,17 @@ ColumnLayout { status = rates.length > 1 ? qsTr("Tap a value; it applies at once. The refresh rate lasts until the phone is turned or the session restarts.") : qsTr("Tap a value; it applies at once.") } - Connections { target: actions; function onFinished(tool, r, id) { if (tool === "display" && id === page.reqId) page.apply(r) } } - Component.onCompleted: reqId = actions.run("display", ["get"]) + Connections { + target: actions + function onFinished(tool, r, id) { + if (tool === "display" && id === page.reqId) page.apply(r) + else if (tool === "lock" && id === page.lockReq) page.applyLock(r) + } + } + Component.onCompleted: { reqId = actions.run("display", ["get"]); lockReq = actions.run("lock", ["get"]) } + ColumnLayout { + width: page.availableWidth + spacing: 14 SettingsLabel { text: qsTr("Brightness"); font.weight: Font.DemiBold; color: backend.foreground; Layout.fillWidth: true } Flow { Layout.fillWidth: true; spacing: 8 @@ -51,5 +81,40 @@ ColumnLayout { } } SettingsLabel { text: page.status; color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true } - Item { Layout.fillHeight: true } + SettingsLabel { text: qsTr("Lock screen after"); font.weight: Font.DemiBold; color: backend.foreground; Layout.fillWidth: true; Layout.topMargin: 8 } + Flow { + Layout.fillWidth: true; spacing: 8 + Repeater { + model: page.lockChoices + delegate: SettingsButton { + required property var modelData + text: modelData.t; highlighted: page.lockAfter === modelData.s; enabled: !page.lockBusy + onClicked: { page.lockBusy = true; page.lockReq = actions.run("lock", ["set", "lock", String(modelData.s)]) } + } + } + } + SettingsLabel { + text: page.lockError !== "" ? page.lockError + : page.lockAfter === 0 ? qsTr("The lock time is off in Omarchy's settings file: the phone stays unlocked until you press the power key. Pick a time above to turn it back on.") + : qsTr("With no touch for this long the phone locks, and the screen turns off a few seconds later. Locking and screen off are the same timer.") + color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true + } + SettingsLabel { text: qsTr("Lock after 30 minutes while a keyboard is connected"); font.weight: Font.DemiBold; color: backend.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true; Layout.topMargin: 8 } + Flow { + Layout.fillWidth: true; spacing: 8 + Repeater { + model: [{on: false, t: qsTr("Off")}, {on: true, t: qsTr("On")}] + delegate: SettingsButton { + required property var modelData + text: modelData.t; highlighted: page.lockAfter >= 0 && page.keyboardAwake === modelData.on; enabled: !page.lockBusy + onClicked: { page.lockBusy = true; page.lockReq = actions.run("lock", ["set", "keyboard", modelData.on ? "on" : "off"]) } + } + } + } + SettingsLabel { + text: (page.keyboard ? qsTr("A keyboard is connected now. ") : qsTr("No keyboard is connected now. ")) + + qsTr("Any Bluetooth or USB keyboard counts, a dock or receiver too. While one is connected the phone locks and the screen turns off after 30 minutes without input instead of the time above. A Bluetooth keyboard that goes to sleep counts as disconnected.") + color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true + } + } } diff --git a/packages/omamobile-settings/app/actionrunner.cpp b/packages/omamobile-settings/app/actionrunner.cpp index 83822926e..77b8615a2 100644 --- a/packages/omamobile-settings/app/actionrunner.cpp +++ b/packages/omamobile-settings/app/actionrunner.cpp @@ -16,7 +16,7 @@ void ActionRunner::post(const QString &tool, const QVariantMap &result, int id) int ActionRunner::run(const QString &tool, const QStringList &args) { static const QRegularExpression word("\\A[a-z0-9]{1,16}\\z"); - static const QStringList tools = {"display", "charge"}; + static const QStringList tools = {"display", "charge", "lock"}; const int id = ++m_next; auto fail = [this, &tool, id](const QString &why) { post(tool, {{"error", why}}, id); return id; }; if (!tools.contains(tool) || args.size() > 3) return fail("unknown action"); diff --git a/packages/omamobile-settings/app/actionrunner.h b/packages/omamobile-settings/app/actionrunner.h index 3ebe43868..8504455e0 100644 --- a/packages/omamobile-settings/app/actionrunner.h +++ b/packages/omamobile-settings/app/actionrunner.h @@ -4,7 +4,7 @@ #include #include -// Runs the source-owned backend scripts (display, charge) with a fixed argument list and no shell. Pages call run(); +// Runs the source-owned backend scripts (display, charge, lock) with a fixed argument list and no shell. Pages call run(); // the JSON the script prints comes back through finished(), always from the event loop and never before run() // has returned its id. class ActionRunner : public QObject { diff --git a/packages/omamobile-settings/app/catalog.json b/packages/omamobile-settings/app/catalog.json index 35b266a24..0b10e3c92 100644 --- a/packages/omamobile-settings/app/catalog.json +++ b/packages/omamobile-settings/app/catalog.json @@ -5,7 +5,7 @@ { "id": "display", "title": "Display", - "detail": "Brightness and refresh rate", + "detail": "Brightness, refresh rate and screen lock", "icon": "display", "page": "display" }, diff --git a/packages/omamobile-settings/backends/display.sh b/packages/omamobile-settings/backends/display.sh index 68090ed0a..605a7dc4e 100755 --- a/packages/omamobile-settings/backends/display.sh +++ b/packages/omamobile-settings/backends/display.sh @@ -21,6 +21,22 @@ fail() { printf '{"error":"%s"}\n' "$1"; exit 2; } fake='' [[ -z $fake || -r $fake ]] || fail "cannot read the test file" +# Settings started from a login outside the graphical session (for example over SSH) runs without +# HYPRLAND_INSTANCE_SIGNATURE, and hyprctl then finds no Hyprland: no refresh rates. Take it from $XDG_RUNTIME_DIR/hypr//.socket.sock, the +# newest socket by mtime if there are several (a crashed Hyprland's stale socket file is not told apart). +find_hypr() { + [[ -n ${HYPRLAND_INSTANCE_SIGNATURE:-} ]] && return 0 + local d best='' sig + for d in "${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"/hypr/*/; do + [[ -S $d.socket.sock ]] || continue + if [[ -z $best || $d.socket.sock -nt $best.socket.sock ]]; then best=$d; fi + done + [[ -n $best ]] || return 0 + sig=${best%/}; sig=${sig##*/} + export HYPRLAND_INSTANCE_SIGNATURE=$sig +} +find_hypr + get_brightness() { local v dev if [[ -n $fake ]]; then v=$(sed -n 1p "$fake") @@ -35,8 +51,24 @@ get_brightness() { set_brightness() { local dev dev=$(omarchy-hw-display 2>/dev/null || true) - if [[ -n $dev ]]; then brightnessctl -d "$dev" --quiet set "${1}%" >/dev/null 2>&1 - else brightnessctl --class=backlight --quiet set "${1}%" >/dev/null 2>&1; fi + if [[ -n $dev ]]; then brightnessctl -d "$dev" --quiet set "${1}%" >/dev/null 2>&1 && return 0 + else brightnessctl --class=backlight --quiet set "${1}%" >/dev/null 2>&1 && return 0; fi + set_brightness_session "$1" "$dev" +} + +# brightnessctl asks logind for the caller's own session. When Settings is started from a login outside +# the graphical session (for example over SSH), that is not the session owning the screen and logind +# refuses; ask for the user's graphical session. +set_brightness_session() { + local pct=$1 dev=$2 sid path max + [[ -n $dev ]] || dev=$(ls /sys/class/backlight 2>/dev/null | head -n1) + [[ -n $dev && -r /sys/class/backlight/$dev/max_brightness ]] || return 1 + max=$(cat "/sys/class/backlight/$dev/max_brightness") || return 1 + sid=$(loginctl show-user "$(id -un)" -p Display --value 2>/dev/null) || return 1 + [[ -n $sid ]] || return 1 + path=$(busctl call org.freedesktop.login1 /org/freedesktop/login1 org.freedesktop.login1.Manager GetSession s "$sid" 2>/dev/null | awk '{print $2}' | tr -d '"') || return 1 + [[ $path == /org/freedesktop/login1/session/* ]] || return 1 + busctl call org.freedesktop.login1 "$path" org.freedesktop.login1.Session SetBrightness ssu backlight "$dev" $(( max * pct / 100 )) >/dev/null 2>&1 } monitors_json() { if [[ -n $fake ]]; then sed -n 2p "$fake"; else hyprctl monitors -j 2>/dev/null; fi diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh new file mode 100755 index 000000000..e2023d0f9 --- /dev/null +++ b/packages/omamobile-settings/backends/lock.sh @@ -0,0 +1,280 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Screen lock settings for the Settings app's Display page. Prints one line of JSON. +# lock.sh get {"lock":60,"keyboardAwake":false,"keyboard":false,"effective":60} +# lock.sh set lock N N is 30, 60, 120, 180 or 300 (no Never here: a phone that never locks by +# itself is not offered one tap away; 0 can still be set in shell.json by hand) +# lock.sh set keyboard on|off lock after 30 min (1800 s) while a Bluetooth or USB keyboard is connected; +# on enables and starts the watcher unit (if that fails the toggle goes back to +# off), off disables it and stops it without waiting (--no-block): this run has +# already written the choice back, so the unit's own restore finds nothing to do +# get also enables+starts the watcher unit if lock.json says on and it is not +# enabled (an upgrade from an older build), and disables it if off and enabled +# lock.sh apply write the value in force now (omamobile-lock-keyboard, on each input change) +# lock.sh restore write the user's choice, keyboard or not (the watcher's ExecStopPost) +# How the phone locks: Omarchy's idle service locks after shell.json's idle.lock seconds (0 = never, the +# phone profile's value is 60), and the lock turns the screen off a few seconds later. So this one value +# is both "lock after" and "screen off after"; there is no separate screen-off timer. +# The choice is kept in ~/.config/omamobile/lock.json: {lock, keyboardAwake, applied, override, reloadPending}. +# "applied" is the value last written to shell.json's idle.lock, and "override" says a 1800 in shell.json is +# the keyboard's, not the user's choice. lock.json is always saved before shell.json, and when the 1800 is +# being replaced "override" stays set until shell.json is written (then lock.json is saved again), so a crash +# at any point never turns the keyboard's 1800 into a choice made in Omarchy's settings. lock.json is only +# rewritten when something in it changed. If idle.lock holds something else than "applied" and +# it is not our override, it was changed elsewhere (Omarchy's own settings) and becomes the choice. +# After shell.json is written the running shell is told with `omarchy-shell shell reloadConfig` (5 s at most), +# as Omarchy's own omarchy-shell-config does; if that fails the JSON carries an "error" (the value is saved) +# and "reloadPending" stays set, so the next set/apply/restore reloads again even when it writes nothing. +# Stay awake and idle on/off are never touched. +# Nothing is written before the user picks something here. The keyboard's 1800 is only written while the +# watcher unit runs (it puts the choice back when it stops). If the user's shell.json exists but does not +# parse or has another version, nothing is written: only a missing or empty one starts from the defaults. +# Both files are changed under one flock, through unique temp files. +# A keyboard is an input device udev marks ID_INPUT_KEYBOARD=1 on the Bluetooth bus (0005, uhid included) +# or on USB (0003) outside /devices/virtual/input (uinput devices can claim USB), that also has the letter +# keys and space, and a name that is not empty and not a known security token or barcode scanner. The +# built-in keys, the on-screen keyboard and virtual devices are left out. +# Test hooks: OMAMOBILE_LOCK_SYSFS and OMAMOBILE_LOCK_UDEVDATA stand in for /sys and /run/udev/data; +# OMAMOBILE_LOCK_WATCHER=1/0 stands in for "is the watcher unit active", OMAMOBILE_LOCK_UNIT_ENABLED=1/0 +# for "is it enabled". +set -euo pipefail +set +x +verb=${1:-}; key=${2:-}; value=${3:-} +sys=${OMAMOBILE_LOCK_SYSFS:-/sys} +udev=${OMAMOBILE_LOCK_UDEVDATA:-/run/udev/data} +prefs=${XDG_CONFIG_HOME:-$HOME/.config}/omamobile/lock.json +shell=$HOME/.config/omarchy/shell.json +defaults=${OMARCHY_PATH:-/usr/share/omarchy}/config/omarchy/shell.json +watcher=${OMAMOBILE_LOCK_WATCHER:-} +if [[ -z $watcher ]]; then + watcher=0 + if [[ $verb == apply || $verb == set ]] && + systemctl --user is-active --quiet omamobile-lock-keyboard.service 2>/dev/null; then watcher=1; fi +fi + +# All work in one place: finds keyboards, reads prefs and shell.json, applies the verb, writes both, reloads. +core() { +/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$@" <<'PY' +import fcntl, json, os, re, struct, sys, tempfile +prefs_path, shell_path, defaults_path, sysfs, udev, watcher, verb, key, value = (sys.argv[1:] + ["", ""])[:9] +CHOICES = (30, 60, 120, 180, 300) +KB_LOCK = 1800 # while a keyboard is connected: a long lock, not never +def out(d): print(json.dumps(d, separators=(",", ":"))); sys.exit(0) +def fail(m): print(json.dumps({"error": m}, separators=(",", ":"))); sys.exit(2) + +# --- keyboards +LONG_BITS = struct.calcsize("l") * 8 +NEEDED = list(range(16, 26)) + list(range(30, 39)) + list(range(44, 51)) + [57] # Q..P, A..L, Z..M, space +NOT_KEYBOARDS = re.compile(r"yubikey|yubico|nitrokey|solokey|onlykey|token|barcode|scanner", re.I) +def read(p): + try: + with open(p) as f: return f.read().strip() + except OSError: return None +def keyboard_connected(): + base = os.path.join(sysfs, "class/input") + try: names = sorted(os.listdir(base)) + except OSError: return False + for ev in names: + if not ev.startswith("event"): continue + d = os.path.join(base, ev) + dev, bus = read(d + "/dev"), read(d + "/device/id/bustype") + if not dev or not bus: continue + data = read(os.path.join(udev, "c" + dev)) or "" + if "E:ID_INPUT_KEYBOARD=1" not in data.splitlines(): continue + path = os.path.realpath(d + "/device") + if bus == "0005": pass + elif bus == "0003" and "/devices/virtual/input/" not in path + "/": pass + else: continue + name = read(d + "/device/name") + if not name or NOT_KEYBOARDS.search(name): continue + caps = (read(d + "/device/capabilities/key") or "").split() + try: bits = sum(int(w, 16) << (i * LONG_BITS) for i, w in enumerate(reversed(caps))) + except ValueError: continue + if all(bits >> k & 1 for k in NEEDED): return True + return False +kb = keyboard_connected() + +# --- files +class Unreadable(Exception): pass +def load(p, missing_ok=True): + try: + with open(p) as f: text = f.read() + except FileNotFoundError: + if missing_ok: return None + raise Unreadable() + except OSError: raise Unreadable() + if not text.strip(): return None # empty: as missing, like Omarchy's source_file + try: d = json.loads(text) + except ValueError: raise Unreadable() + if not isinstance(d, dict): raise Unreadable() + return d +def save(p, d, indent=None): + target = os.path.realpath(p) # a symlinked shell.json (dotfiles) stays a symlink + os.makedirs(os.path.dirname(target), exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(target), prefix="." + os.path.basename(target) + ".") + try: + with os.fdopen(fd, "w") as f: + json.dump(d, f, indent=indent, ensure_ascii=False); f.write("\n") + f.flush(); os.fsync(f.fileno()) + if os.path.exists(target): os.chmod(tmp, os.stat(target).st_mode & 0o7777) + else: os.chmod(tmp, 0o644) + os.replace(tmp, target) + except BaseException: + try: os.unlink(tmp) + except OSError: pass + raise +def secs(v, fallback): # as Omarchy's IdleModel.secondsFromConfig + try: n = float(v) + except (TypeError, ValueError): return fallback + return int(n) if n >= 0 and n == n and n != float("inf") else fallback +def user_shell(): + """The user's shell.json, None when missing or empty. Unparseable or another version: Unreadable.""" + s = load(shell_path) + if s is not None and s.get("version") != 1: raise Unreadable() + return s + +try: + os.makedirs(os.path.dirname(prefs_path), exist_ok=True) + lockf = open(prefs_path + ".lock", "a") + fcntl.flock(lockf, fcntl.LOCK_EX) +except OSError: + fail("cannot lock the setting") + +try: shell = user_shell() +except Unreadable: fail("shell.json is not readable") +try: defaults = load(defaults_path) if shell is None else None +except Unreadable: defaults = None +current = secs(((shell or defaults or {}).get("idle") or {}).get("lock"), 300) +try: prefs = load(prefs_path) +except Unreadable: prefs = None # our own file: start again from what is in force (below) +saved = dict(prefs) if prefs is not None else None +if prefs is not None: + applied, override = prefs.get("applied"), bool(prefs.get("override")) + if isinstance(applied, int) and applied != current and not (override and current == KB_LOCK): + prefs["lock"] = current # changed outside this page + if not isinstance(prefs.get("lock"), int) or prefs["lock"] < 0: prefs["lock"] = current + prefs["keyboardAwake"] = bool(prefs.get("keyboardAwake")) + prefs["override"] = override + +if verb == "get": + p = prefs or {"lock": current, "keyboardAwake": False} + r = {"lock": p["lock"], "keyboardAwake": p["keyboardAwake"], "keyboard": kb, "effective": current} + if prefs is not None: r["unit"] = p["keyboardAwake"] # a saved choice: the shell part checks the unit + out(r) +elif verb == "set": + p = prefs or {"lock": current, "keyboardAwake": False, "override": False} + if key == "lock": + if not value.isdigit() or int(value) not in CHOICES: fail("bad value") + p["lock"] = int(value) + elif key == "keyboard": + if value not in ("on", "off"): fail("bad value") + p["keyboardAwake"] = value == "on" + else: fail("unknown key") + prefs = p +elif verb in ("apply", "restore"): + if prefs is None: out({"applied": None}) # never set here: leave Omarchy's value alone +else: + fail("usage: get|set|apply|restore") + +override = verb != "restore" and watcher == "1" and prefs["keyboardAwake"] and kb and prefs["lock"] != 0 +want = KB_LOCK if override else prefs["lock"] +# 1. lock.json first: if we die before shell.json, the next run knows a 1800 there is ours. While the 1800 +# is being replaced, override stays true until shell.json holds the new value (saved again below). +ours = prefs.get("override") and current == KB_LOCK +prefs["applied"], prefs["override"] = want, bool(override or (ours and want != current)) +prefs["reloadPending"] = bool(prefs.get("reloadPending")) or want != current +if prefs != saved: + try: save(prefs_path, prefs) + except OSError: fail("cannot save the setting") +step1 = dict(prefs) +# 2. shell.json, read again just before the write so a concurrent Omarchy change to other keys is kept +written = False +if want != current: + try: shell = user_shell() + except Unreadable: fail("shell.json is not readable") + if shell is None: + shell = defaults # Omarchy never merges: start from its defaults, as omarchy-shell-config does + if shell is None: fail("cannot read shell.json") + idle = shell.get("idle") if isinstance(shell.get("idle"), dict) else {} + idle["lock"] = want; shell["idle"] = idle + try: save(shell_path, shell, indent=2) + except OSError: fail("cannot write shell.json") + written = True +# 3. tell the running shell, as omarchy-shell-config does: after a write, or when an earlier reload failed +result = {"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want} +if prefs["reloadPending"]: + import subprocess + try: + ok = subprocess.run(["timeout", "5", "omarchy-shell", "shell", "reloadConfig"], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode == 0 + except OSError: ok = False + if ok: prefs["reloadPending"] = False + else: result["error"] = "saved, but the shell did not reload its settings" +prefs["override"] = override +if prefs != step1: + try: save(prefs_path, prefs) + except OSError: result["error"] = "cannot save the setting" +print(json.dumps(result, separators=(",", ":"))) +sys.exit(3 if "error" in result else 0) +PY +} +rc=0; res=$(core "$verb" "$key" "$value") || rc=$? +# 3 means the JSON carries an error (the value is saved): the watcher step below still runs. +if [[ $rc -ne 0 && $rc -ne 3 ]]; then printf '%s\n' "$res"; exit "$rc"; fi +err() { # the error already in $res, if any, then this one + res=$(/usr/bin/python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); e=d.get("error"); d["error"]=sys.argv[2] if not e else e if sys.argv[2] in e.split("; ") else e+"; "+sys.argv[2]; print(json.dumps(d,separators=(",",":")))' "$res" "$1") + rc=3 +} +# The watcher runs only while the toggle is on. After the flock above is released, since its restore takes +# it too. off: the choice is already written back above, so don't wait for the unit's restore (--no-block), +# which keeps the whole run well under the page runner's 20 s. +# get (the page opens with it) puts the unit in line with a saved choice: lock.json from an older build +# can say on while the unit was never enabled. Only when lock.json was read fine ("unit" in the JSON). +# Under the same flock as the work above, re-reading the choice, so a set landing meanwhile waits and wins. +# Only "enabled"/"enabled-runtime" and "disabled" count; anything else (masked, timeout, no bus) is reported. +# systemctl runs without fd 9, so nothing it starts holds the lock. enable --now does not wait for the unit's apply (a simple service), so holding the lock cannot deadlock. +if [[ $verb == get ]]; then + unit=$(/usr/bin/python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); print(1 if "unit" in d else "")' "$res") + res=$(/usr/bin/python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); d.pop("unit",None); print(json.dumps(d,separators=(",",":")))' "$res") + if [[ -n $unit ]]; then + act=$( + exec 9>>"$prefs.lock"; flock 9 + want=$(/usr/bin/python3 -I -c 'import json,sys +try: d=json.load(open(sys.argv[1])) +except Exception: d=None +print(("on" if d.get("keyboardAwake") else "off") if isinstance(d,dict) else "")' "$prefs") + [[ -n $want ]] || exit 0 + case ${OMAMOBILE_LOCK_UNIT_ENABLED:-} in + 1) state=enabled ;; 0) state=disabled ;; + *) state=$(timeout 2 systemctl --user is-enabled omamobile-lock-keyboard.service 2>/dev/null 9>&-) || true ;; + esac + case $state in enabled|enabled-runtime) state=1 ;; disabled) state=0 ;; + *) echo "could not tell if the keyboard watcher is enabled"; exit 0 ;; esac + if [[ $want == on && $state == 0 ]]; then + timeout 5 systemctl --user enable --now omamobile-lock-keyboard.service >/dev/null 2>&1 9>&- || + echo "could not start the keyboard watcher" + elif [[ $want == off && $state == 1 ]]; then + timeout 5 systemctl --user disable --now --no-block omamobile-lock-keyboard.service >/dev/null 2>&1 9>&- || + echo "could not stop the keyboard watcher" + fi + ) + [[ -z $act ]] || err "$act" + fi +fi +if [[ $verb == set && $key == keyboard ]]; then + if [[ $value == on ]]; then + if ! timeout 5 systemctl --user enable --now omamobile-lock-keyboard.service >/dev/null 2>&1; then + timeout 2 systemctl --user disable --no-block omamobile-lock-keyboard.service >/dev/null 2>&1 || true + prev=$(/usr/bin/python3 -I -c 'import json,sys; print(json.loads(sys.argv[1]).get("error",""))' "$res") + rc=0; res=$(watcher=0 core set keyboard off) || rc=$? + if [[ $rc -ne 0 && $rc -ne 3 ]]; then printf '%s\n' "$res"; exit "$rc"; fi + [[ -z $prev ]] || err "$prev" + err "could not start the keyboard watcher" + fi + else + timeout 5 systemctl --user disable --now --no-block omamobile-lock-keyboard.service >/dev/null 2>&1 || + err "could not stop the keyboard watcher" + fi +fi +printf '%s\n' "$res" +exit "$rc" diff --git a/packages/omamobile-settings/install b/packages/omamobile-settings/install index 6847708ce..b0d73fac1 100755 --- a/packages/omamobile-settings/install +++ b/packages/omamobile-settings/install @@ -15,3 +15,8 @@ install -Dm755 "$source_dir/backends/charge.sh" "$dest/usr/lib/omamobile-setting install -Dm755 "$source_dir/libexec/charge-limit" "$dest/usr/lib/omamobile-settings/charge-limit" install -Dm644 "$source_dir/vendor/systemd/system/omamobile-charge-limit@.service" "$dest/usr/lib/systemd/system/omamobile-charge-limit@.service" install -Dm644 "$source_dir/vendor/polkit/50-omamobile-charge-limit.rules" "$dest/usr/share/polkit-1/rules.d/50-omamobile-charge-limit.rules" +install -Dm755 "$source_dir/backends/lock.sh" "$dest/usr/lib/omamobile-settings/backends/lock.sh" +# Display > "Lock after 30 minutes while a keyboard is connected": the unit is enabled per user by the +# page's toggle (lock.sh set keyboard on), never by the package. +install -Dm755 "$source_dir/libexec/omamobile-lock-keyboard" "$dest/usr/lib/omamobile-settings/omamobile-lock-keyboard" +install -Dm644 "$source_dir/systemd/user/omamobile-lock-keyboard.service" "$dest/usr/lib/systemd/user/omamobile-lock-keyboard.service" diff --git a/packages/omamobile-settings/libexec/omamobile-lock-keyboard b/packages/omamobile-settings/libexec/omamobile-lock-keyboard new file mode 100755 index 000000000..874b0be9d --- /dev/null +++ b/packages/omamobile-settings/libexec/omamobile-lock-keyboard @@ -0,0 +1,25 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Locks after 30 minutes instead of the chosen time while a keyboard is connected, when the Display page's +# toggle says so: runs the lock backend's apply at start and after every input add or remove, once the +# burst of events a device brings has settled (1 s). The unit runs only while the toggle is on. +# A failed apply (a broken shell.json, say) is logged once and the watcher keeps going, so it is not +# restarted every 10 s; the next input change tries again. If udevadm monitor ends this exits non-zero: +# the unit restarts it and its ExecStopPost puts the choice back. +set -u -o pipefail +backend=${OMAMOBILE_LOCK_BACKEND:-/usr/lib/omamobile-settings/backends/lock.sh} +failing=0 +apply() { + local out + if out=$(bash "$backend" apply 2>&1); then failing=0; return; fi + [[ $failing == 1 ]] || echo "omamobile-lock-keyboard: apply failed: $out" >&2 + failing=1 +} +apply +udevadm monitor --udev --subsystem-match=input | while read -r line; do + [[ $line == 'UDEV ['* ]] || continue # events only, not the "UDEV - the event which udev sends" header + while read -r -t 1 _; do :; done + apply +done +echo "omamobile-lock-keyboard: udevadm monitor ended" >&2 +exit 1 diff --git a/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service b/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service new file mode 100644 index 000000000..1ef1f5e94 --- /dev/null +++ b/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: MIT +# Settings > Display > "Lock after 30 minutes while a keyboard is connected": follows keyboards coming and +# going. Enabled and started by `lock.sh set keyboard on`, stopped and disabled by `off`; not enabled for +# anyone by the package. The keyboard's 1800 s is only written while this runs; when it stops for any +# reason the user's chosen timeout is written back (ExecStopPost). +[Unit] +Description=Omarchy Mobile: lock after 30 minutes while a keyboard is connected +PartOf=graphical-session.target +After=graphical-session.target + +[Service] +ExecStart=/usr/lib/omamobile-settings/omamobile-lock-keyboard +ExecStopPost=/usr/bin/bash /usr/lib/omamobile-settings/backends/lock.sh restore +Restart=always +RestartSec=10 + +[Install] +WantedBy=graphical-session.target diff --git a/packages/omamobile-settings/test/all b/packages/omamobile-settings/test/all index a8623d42a..882b73b40 100755 --- a/packages/omamobile-settings/test/all +++ b/packages/omamobile-settings/test/all @@ -6,6 +6,7 @@ build_dir=${OMAMOBILE_SETTINGS_TEST_BUILD_DIR:-"$source_dir/build/tests"} "$source_dir/bin/build" "$source_dir/test/display-backend.sh" "$source_dir/test/charge-backend.sh" +"$source_dir/test/lock-backend.sh" mkdir -p "$build_dir" fixture=$(mktemp -d) trap 'rm -rf -- "$fixture"' EXIT HUP INT TERM diff --git a/packages/omamobile-settings/test/display-backend.sh b/packages/omamobile-settings/test/display-backend.sh index 83a61ec96..e26465f72 100755 --- a/packages/omamobile-settings/test/display-backend.sh +++ b/packages/omamobile-settings/test/display-backend.sh @@ -45,3 +45,25 @@ eq "$(run get)" '{"brightness":50,"refresh":120,"rates":[60,120]}' sed -i '2s/.*/not json/' "$fake" eq "$(run get)" '{"brightness":50,"refresh":-1,"rates":[]}' echo "display backend: ok" + +# no HYPRLAND_INSTANCE_SIGNATURE in the environment: it is found from the newest live socket under +# $XDG_RUNTIME_DIR/hypr, and hyprctl is run with it (a copy with `fake` empty, fake tools on PATH) +bin=$tmp/bin; rt=$tmp/rt; mkdir -p "$bin" "$rt/hypr/old" "$rt/hypr/new" "$rt/hypr/dead" +printf '#!/bin/sh\necho 50,x,x,50%%,x\n' > "$bin/brightnessctl" +printf '#!/bin/sh\necho panel\n' > "$bin/omarchy-hw-display" +cat > "$bin/hyprctl" <<'EOS' +#!/bin/sh +[ "$HYPRLAND_INSTANCE_SIGNATURE" = new ] || { echo "[]"; exit 0; } +echo '[{"name":"DSI-1","width":1344,"height":2992,"x":0,"y":0,"scale":3.2,"refreshRate":120.0,"availableModes":["1344x2992@120.00Hz","1344x2992@60.00Hz"]}]' +EOS +chmod +x "$bin"/* +mksock() { python3 -I -c 'import socket,sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "$1"; } +mksock "$rt/hypr/old/.socket.sock"; touch -d '-1 hour' "$rt/hypr/old/.socket.sock" +mksock "$rt/hypr/new/.socket.sock" +touch "$rt/hypr/dead/.socket.sock" # a plain file, not a socket: skipped although newest +sed "s|^fake=.*|fake=''|" "$src/backends/display.sh" > "$tmp/live.sh" +live() { env -u HYPRLAND_INSTANCE_SIGNATURE PATH="$bin:$PATH" XDG_RUNTIME_DIR="$rt" bash "$tmp/live.sh" "$@" || true; } +eq "$(live get)" '{"brightness":50,"refresh":120,"rates":[60,120]}' +# a signature already in the environment is kept +eq "$(HYPRLAND_INSTANCE_SIGNATURE=old PATH="$bin:$PATH" XDG_RUNTIME_DIR="$rt" bash "$tmp/live.sh" get || true)" '{"brightness":50,"refresh":-1,"rates":[]}' +echo "display backend (no signature): ok" diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh new file mode 100755 index 000000000..ec3cbb180 --- /dev/null +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -0,0 +1,308 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# backends/lock.sh against a scratch HOME, a fake /sys/class/input and /run/udev/data. +set -euo pipefail +src=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +tmp=$(mktemp -d); trap 'rm -rf -- "$tmp"' EXIT +export HOME=$tmp/home XDG_CONFIG_HOME=$tmp/home/.config OMARCHY_PATH=$tmp/omarchy +export OMAMOBILE_LOCK_SYSFS=$tmp/sys OMAMOBILE_LOCK_UDEVDATA=$tmp/udev OMAMOBILE_LOCK_WATCHER=1 +# stand-ins for omarchy-shell and systemctl: never touch the shell or units of the machine running the tests +mkdir -p "$tmp/stubs"; export STUB_LOG=$tmp/stubs/log STUB_FAIL=$tmp/stubs/fail; : > "$STUB_LOG" +for c in omarchy-shell systemctl; do + printf '#!/bin/bash\necho "%s $*" >> "$STUB_LOG"\n[[ -e $STUB_FAIL.%s ]] && exit 1\n[[ $2 == is-enabled ]] && { cat "$STUB_LOG.state" 2>/dev/null || echo enabled; }\nexit 0\n' "$c" "$c" > "$tmp/stubs/$c" + chmod +x "$tmp/stubs/$c" +done +export PATH=$tmp/stubs:$PATH +mkdir -p "$HOME/.config/omarchy" "$OMARCHY_PATH/config/omarchy" "$tmp/sys/class/input" "$tmp/udev" +shell=$HOME/.config/omarchy/shell.json prefs=$XDG_CONFIG_HOME/omamobile/lock.json +echo '{"version":1,"bar":{"id":"omamobile.bar"},"idle":{"screensaver":0,"lock":60}}' > "$shell" +echo '{"version":1,"bar":{"id":"default"},"idle":{"screensaver":150,"lock":300}}' > "$OMARCHY_PATH/config/omarchy/shell.json" +run() { bash "$src/backends/lock.sh" "$@" || true; } +eq() { [[ $1 == "$2" ]] || { echo "FAIL: got $1, want $2" >&2; exit 1; }; } +idle() { python3 -I -c 'import json,sys; d=json.load(open(sys.argv[1])); print(d["idle"]["lock"], d["idle"]["screensaver"], d["bar"]["id"])' "$shell"; } +full='ffffffffffffffff fffffffffffffffe' # keys 1..127: a whole keyboard +# an input device: N, bus, keyboard (1/0), where it lives under /sys/devices, [name], [key capabilities] +dev() { + local d=$tmp/sys/devices/$4/input$1 + mkdir -p "$d/id" "$d/capabilities" "$tmp/sys/class/input/event$1" + echo "$2" > "$d/id/bustype" + printf '%s\n' "${5-Some Keyboard}" > "$d/name" + echo "${6-$full}" > "$d/capabilities/key" + echo "13:$((64 + $1))" > "$tmp/sys/class/input/event$1/dev" + ln -sfn "$d" "$tmp/sys/class/input/event$1/device" + { echo "E:ID_INPUT=1"; [[ $3 == 1 ]] && echo "E:ID_INPUT_KEYBOARD=1" || echo "E:ID_INPUT_KEY=1"; } > "$tmp/udev/c13:$((64 + $1))" +} +pj() { python3 -I -c 'import json,sys; print(json.load(open(sys.argv[1]))[sys.argv[2]])' "$prefs" "$1"; } +gone() { rm -rf "$tmp/sys/class/input/event$1" "$tmp/udev/c13:$((64 + $1))"; } + +# the phone's own keys (gpio-keys on the host bus 0019, a pmic power key) and a uinput device that says USB +dev 0 0019 1 platform/gpio-keys +dev 1 0000 1 platform/pwrkey +dev 2 0003 1 virtual/input +# AVRCP from Bluetooth headphones: keys, but not a keyboard +dev 3 0005 0 virtual/input + +# nothing chosen yet: get reports Omarchy's value and apply writes nothing +eq "$(run get)" '{"lock":60,"keyboardAwake":false,"keyboard":false,"effective":60}' +eq "$(run apply)" '{"applied":null}' +[[ ! -e $prefs ]] || { echo "FAIL: apply wrote prefs" >&2; exit 1; } + +eq "$(run set lock 120)" '{"lock":120,"keyboardAwake":false,"keyboard":false,"effective":120}' +eq "$(idle)" '120 0 omamobile.bar' +eq "$(run set lock 0)" '{"error":"bad value"}' # no Never on the page (derekross, #866) +eq "$(idle)" '120 0 omamobile.bar' +eq "$(run set lock 45)" '{"error":"bad value"}' +eq "$(run set lock x)" '{"error":"bad value"}' +eq "$(run set keyboard maybe)" '{"error":"bad value"}' +eq "$(run set night on)" '{"error":"unknown key"}' +eq "$(run nonsense)" '{"error":"usage: get|set|apply|restore"}' +eq "$(run set lock 30)" '{"lock":30,"keyboardAwake":false,"keyboard":false,"effective":30}' +eq "$(run set keyboard on)" '{"lock":30,"keyboardAwake":true,"keyboard":false,"effective":30}' + +# a BLE keyboard through uhid (bus 0005 under /devices/virtual/misc/uhid): lock after 1800 s +dev 4 0005 1 virtual/misc/uhid/0005:046D:B35B.0001 +eq "$(run apply)" '{"lock":30,"keyboardAwake":true,"keyboard":true,"effective":1800}' +eq "$(idle)" '1800 0 omamobile.bar' +# picking a time while it is connected keeps 1800 in force, and keeps the choice +eq "$(run set lock 300)" '{"lock":300,"keyboardAwake":true,"keyboard":true,"effective":1800}' +gone 4 +eq "$(run apply)" '{"lock":300,"keyboardAwake":true,"keyboard":false,"effective":300}' +eq "$(idle)" '300 0 omamobile.bar' +# a real USB keyboard +dev 5 0003 1 platform/soc/usb1/1-1/1-1:1.0/0003:04D9:A0F8.0002 +eq "$(run apply)" '{"lock":300,"keyboardAwake":true,"keyboard":true,"effective":1800}' +# the toggle off: the keyboard no longer matters +eq "$(run set keyboard off)" '{"lock":300,"keyboardAwake":false,"keyboard":true,"effective":300}' +gone 5 + +# changed in Omarchy's own settings: adopted, not overwritten +sed -i 's/"lock": 300/"lock": 600/' "$shell" +eq "$(run get)" '{"lock":600,"keyboardAwake":false,"keyboard":false,"effective":600}' +eq "$(run apply)" '{"lock":600,"keyboardAwake":false,"keyboard":false,"effective":600}' +eq "$(idle)" '600 0 omamobile.bar' + +# no user shell.json: start from Omarchy's defaults (it never merges), touching only idle.lock +rm "$shell" +eq "$(run set lock 60)" '{"lock":60,"keyboardAwake":false,"keyboard":false,"effective":60}' +eq "$(idle)" '60 150 default' + +# restore (the watcher's ExecStopPost) writes the choice although a keyboard is connected +echo '{"version":1,"bar":{"id":"omamobile.bar"},"idle":{"screensaver":0,"lock":60}}' > "$shell" +eq "$(run set lock 120)" '{"lock":120,"keyboardAwake":false,"keyboard":false,"effective":120}' +eq "$(run set keyboard on)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +dev 6 0005 1 virtual/misc/uhid/0005:046D:B35B.0003 +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":true,"effective":1800}' +eq "$(pj override)" 'True' +eq "$(run restore)" '{"lock":120,"keyboardAwake":true,"keyboard":true,"effective":120}' +eq "$(idle)" '120 0 omamobile.bar' +# no watcher running: the keyboard's 1800 is never written +eq "$(OMAMOBILE_LOCK_WATCHER=0 run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":true,"effective":120}' +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":true,"effective":1800}' + +# a run that died after lock.json (override) but before shell.json, or after both: our 1800 is never adopted +gone 6 +echo '{"lock":120,"keyboardAwake":true,"applied":1800,"override":true}' > "$prefs" +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +eq "$(idle)" '120 0 omamobile.bar' +echo '{"lock":120,"keyboardAwake":true,"applied":1800,"override":true}' > "$prefs" +sed -i 's/"lock": 120/"lock": 1800/' "$shell" +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +# lock.json cannot be saved: shell.json is not touched (lock.json is written first) +dev 6 0005 1 virtual/misc/uhid/0005:046D:B35B.0003 +chmod a-w "$XDG_CONFIG_HOME/omamobile" +eq "$(run apply)" '{"error":"cannot save the setting"}' +chmod u+w "$XDG_CONFIG_HOME/omamobile" +eq "$(idle)" '120 0 omamobile.bar' +gone 6 +# no temp files left behind +eq "$(find "$HOME" -name '.*.json.*' | wc -l)" 0 + +# concurrent runs: one flock, unique temp files; every run answers and both files stay valid +for i in $(seq 1 15); do + run apply > "$tmp/c$i.a" & run set lock 60 > "$tmp/c$i.b" & run set lock 30 > "$tmp/c$i.c" & +done; wait +! grep -h error "$tmp"/c*.? || { echo "FAIL: concurrent run failed" >&2; exit 1; } +python3 -I -c 'import json,sys; [json.load(open(p)) for p in sys.argv[1:]]' "$shell" "$prefs" + +# the user's shell.json does not parse or has another version: an error, and nothing is written +cp "$shell" "$tmp/shell.good" +echo '{"version":1,"bar":{"id":"omamobile.bar"},}' > "$shell"; cp "$shell" "$tmp/shell.bad" +eq "$(run set lock 300)" '{"error":"shell.json is not readable"}' +cmp -s "$shell" "$tmp/shell.bad" || { echo "FAIL: broken shell.json was replaced" >&2; exit 1; } +echo '{"version":2,"idle":{"lock":60}}' > "$shell" +eq "$(run apply)" '{"error":"shell.json is not readable"}' +eq "$(head -c 13 "$shell")" '{"version":2,' +# an empty one is treated as missing: Omarchy's defaults +: > "$shell" +eq "$(run set lock 180)" '{"lock":180,"keyboardAwake":true,"keyboard":false,"effective":180}' +eq "$(idle)" '180 150 default' +# a symlinked shell.json stays a symlink, other keys and non-ASCII text are kept +mv "$shell" "$tmp/real-shell.json"; ln -s "$tmp/real-shell.json" "$shell" +python3 -I -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); d["clock"]="ώρα"; json.dump(d,open(p,"w"),ensure_ascii=False)' "$shell" +eq "$(run set lock 30)" '{"lock":30,"keyboardAwake":true,"keyboard":false,"effective":30}' +[[ -L $shell ]] || { echo "FAIL: symlink replaced" >&2; exit 1; } +grep -q 'ώρα' "$shell" + +# not a keyboard: no name, a security token, a barcode scanner, too few keys (a receiver's partial key map) +dev 7 0003 1 platform/usb/7 '' +dev 8 0003 1 platform/usb/8 'Yubico YubiKey OTP+FIDO+CCID' +dev 9 0005 1 virtual/misc/uhid/9 'Wireless Barcode Scanner' +dev 10 0003 1 platform/usb/10 'Logitech USB Receiver' 'fffffffe' +eq "$(run get)" '{"lock":30,"keyboardAwake":true,"keyboard":false,"effective":30}' +dev 11 0003 1 platform/usb/11 'Logitech K380' +eq "$(run get)" '{"lock":30,"keyboardAwake":true,"keyboard":true,"effective":30}' +gone 7; gone 8; gone 9; gone 10; gone 11 + +# the watcher: apply once at start, then once per settled burst of input events (fake udevadm, stub backend); +# the real header line "UDEV - the event which udev sends..." is not an event. When udevadm ends it exits 1. +mkdir -p "$tmp/bin" +printf '#!/bin/sh\necho "monitor will print the received events for:"\necho "UDEV - the event which udev sends out after rule processing"\necho "UDEV [1] add /devices/a (input)"\necho "UDEV [1] add /devices/a/event9 (input)"\nsleep 2\necho "UDEV [3] remove /devices/a (input)"\n' > "$tmp/bin/udevadm" +printf '#!/bin/sh\necho "$1" >> "%s/calls"\n' "$tmp" > "$tmp/stub.sh" +chmod +x "$tmp/bin/udevadm" +rc=0; PATH="$tmp/bin:$PATH" OMAMOBILE_LOCK_BACKEND=$tmp/stub.sh timeout 20 bash "$src/libexec/omamobile-lock-keyboard" 2>/dev/null || rc=$? +eq "$(tr '\n' ' ' < "$tmp/calls")" 'apply apply apply ' +eq "$rc" 1 +# a failing apply (a broken shell.json) does not end it: logged once, tried again on the next event +printf '#!/bin/sh\necho "$1" >> "%s/calls2"\necho "{\\"error\\":\\"shell.json is not readable\\"}"\nexit 2\n' "$tmp" > "$tmp/stub.sh" +rc=0; PATH="$tmp/bin:$PATH" OMAMOBILE_LOCK_BACKEND=$tmp/stub.sh timeout 20 bash "$src/libexec/omamobile-lock-keyboard" 2>"$tmp/werr" || rc=$? +eq "$(tr '\n' ' ' < "$tmp/calls2")" 'apply apply apply ' +eq "$(grep -c 'apply failed' "$tmp/werr")" 1 +eq "$rc" 1 # only because the fake udevadm ended +unit=$src/systemd/user/omamobile-lock-keyboard.service +grep -q '^ExecStopPost=.*lock.sh restore$' "$unit" +grep -qx 'WantedBy=graphical-session.target' "$unit" +! grep -q 'graphical-session.target.wants' "$src/install" || { echo "FAIL: unit enabled for everyone" >&2; exit 1; } +grep -q '^depends=.*coreutils.*systemd' "$src/PKGBUILD" + +# reloadConfig after a write, nothing when unchanged; Stay awake / idle on-off are never called +echo '{"version":1,"bar":{"id":"omamobile.bar"},"idle":{"screensaver":0,"lock":60}}' > "$shell"; rm -f "$prefs" +: > "$STUB_LOG" +eq "$(run set lock 120)" '{"lock":120,"keyboardAwake":false,"keyboard":false,"effective":120}' +eq "$(tr '\n' ',' < "$STUB_LOG")" "omarchy-shell shell reloadConfig," +: > "$STUB_LOG"; before=$(stat -c %Y.%i "$prefs"); sleep 1.1 +run set lock 120 >/dev/null; run apply >/dev/null +eq "$(cat "$STUB_LOG")" "" +eq "$(stat -c %Y.%i "$prefs")" "$before" # lock.json not rewritten when nothing changed +# a failed reload: the value is saved, the JSON carries the error, exit 3 +touch "$STUB_FAIL.omarchy-shell" +rc=0; out=$(bash "$src/backends/lock.sh" set lock 300) || rc=$? + +eq "$(python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); print(d["lock"], d["error"])' "$out")" "300 saved, but the shell did not reload its settings" +eq "$rc" 3 +eq "$(idle)" '300 0 omamobile.bar' +rm -f "$STUB_FAIL.omarchy-shell" +# the toggle enables/starts and stops/disables the watcher unit +: > "$STUB_LOG" +eq "$(run set keyboard on)" '{"lock":300,"keyboardAwake":true,"keyboard":false,"effective":300}' +# the reload that failed above is still pending: done now, before the watcher starts +eq "$(tr '\n' ',' < "$STUB_LOG")" "omarchy-shell shell reloadConfig,systemctl --user enable --now omamobile-lock-keyboard.service," +: > "$STUB_LOG" +eq "$(run set keyboard off)" '{"lock":300,"keyboardAwake":false,"keyboard":false,"effective":300}' +eq "$(tr '\n' ',' < "$STUB_LOG")" "systemctl --user disable --now --no-block omamobile-lock-keyboard.service," +err() { python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); print(d["keyboardAwake"], d["effective"], d.get("error"))' "$1"; } +# a) enable fails: the toggle goes back to off (saved), with a keyboard in the 1800 is undone too +dev 12 0005 1 virtual/misc/uhid/12 +touch "$STUB_FAIL.systemctl" +rc=0; out=$(bash "$src/backends/lock.sh" set keyboard on) || rc=$? +eq "$rc" 3 +eq "$(err "$out")" "False 300 could not start the keyboard watcher" +eq "$(pj keyboardAwake)" 'False' +eq "$(pj override)" 'False' +eq "$(idle)" '300 0 omamobile.bar' +rm -f "$STUB_FAIL.systemctl" +# a) a failed reload does not skip enable/disable; both errors are reported together +eq "$(run set keyboard on)" '{"lock":300,"keyboardAwake":true,"keyboard":true,"effective":1800}' +touch "$STUB_FAIL.omarchy-shell"; : > "$STUB_LOG" +rc=0; out=$(bash "$src/backends/lock.sh" set keyboard off) || rc=$? +eq "$rc" 3 +eq "$(err "$out")" "False 300 saved, but the shell did not reload its settings" +grep -q 'systemctl --user disable --now --no-block' "$STUB_LOG" +touch "$STUB_FAIL.systemctl" +rc=0; out=$(bash "$src/backends/lock.sh" set keyboard on) || rc=$? +eq "$rc" 3 +eq "$(err "$out")" "False 300 saved, but the shell did not reload its settings; could not start the keyboard watcher" +eq "$(pj keyboardAwake)" 'False' +rm -f "$STUB_FAIL.systemctl" +# b) the reload is still pending: the same set again writes nothing but reloads, and keeps the error until it works +eq "$(pj reloadPending)" 'True' +: > "$STUB_LOG" +rc=0; out=$(bash "$src/backends/lock.sh" set lock 300) || rc=$? +eq "$rc" 3 +eq "$(err "$out")" "False 300 saved, but the shell did not reload its settings" +rm -f "$STUB_FAIL.omarchy-shell"; : > "$STUB_LOG" +eq "$(run set lock 300)" '{"lock":300,"keyboardAwake":false,"keyboard":true,"effective":300}' +eq "$(tr '\n' ',' < "$STUB_LOG")" "omarchy-shell shell reloadConfig," +eq "$(pj reloadPending)" 'False' +: > "$STUB_LOG"; run set lock 300 >/dev/null +eq "$(cat "$STUB_LOG")" "" +gone 12 +# c) restore died after lock.json, before shell.json: override is still set, so the 1800 is not adopted +echo '{"lock":120,"keyboardAwake":true,"applied":120,"override":true,"reloadPending":true}' > "$prefs" +sed -i 's/"lock": 300/"lock": 1800/' "$shell" +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +eq "$(idle)" '120 0 omamobile.bar' +eq "$(pj override)" 'False' +# c) the real step 1 of a restore keeps override true: kill shell.json's write by making it unwritable +dev 13 0005 1 virtual/misc/uhid/13 +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":true,"effective":1800}' +chmod a-w "$HOME/.config/omarchy" +eq "$(run restore)" '{"error":"cannot write shell.json"}' +chmod u+w "$HOME/.config/omarchy" +eq "$(pj override) $(pj applied)" 'True 120' +gone 13 +eq "$(run apply)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +eq "$(idle)" '120 0 omamobile.bar' +# d) off with a reload that hangs: bounded (5 s reload, --no-block stop), well under the runner's 20 s +printf '#!/bin/bash\necho "omarchy-shell $*" >> "$STUB_LOG"\nsleep 30\n' > "$tmp/stubs/omarchy-shell" +run set keyboard on >/dev/null +dev 14 0005 1 virtual/misc/uhid/14; run apply >/dev/null +t0=$(date +%s); run set keyboard off >/dev/null; t1=$(date +%s) +(( t1 - t0 <= 8 )) || { echo "FAIL: set keyboard off took $((t1 - t0)) s" >&2; exit 1; } +printf '#!/bin/bash\necho "omarchy-shell $*" >> "$STUB_LOG"\n[[ -e $STUB_FAIL.omarchy-shell ]] && exit 1\nexit 0\n' > "$tmp/stubs/omarchy-shell" +gone 14 +# e) get puts the unit in line with lock.json (an upgrade left keyboardAwake on, unit never enabled) +echo '{"lock":120,"keyboardAwake":true,"applied":120,"override":false,"reloadPending":false}' > "$prefs" +: > "$STUB_LOG"; eq "$(OMAMOBILE_LOCK_UNIT_ENABLED=0 run get)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120}' +eq "$(cat "$STUB_LOG")" "systemctl --user enable --now omamobile-lock-keyboard.service" +: > "$STUB_LOG"; OMAMOBILE_LOCK_UNIT_ENABLED=1 run get >/dev/null; eq "$(cat "$STUB_LOG")" "" +: > "$STUB_LOG"; run get >/dev/null # no hook: asks systemctl (the stub says enabled), nothing to change +eq "$(cat "$STUB_LOG")" "systemctl --user is-enabled omamobile-lock-keyboard.service" +echo '{"lock":120,"keyboardAwake":false,"applied":120,"override":false,"reloadPending":false}' > "$prefs" +: > "$STUB_LOG"; OMAMOBILE_LOCK_UNIT_ENABLED=1 run get >/dev/null +eq "$(cat "$STUB_LOG")" "systemctl --user disable --now --no-block omamobile-lock-keyboard.service" +: > "$STUB_LOG"; OMAMOBILE_LOCK_UNIT_ENABLED=0 run get >/dev/null; eq "$(cat "$STUB_LOG")" "" +# is-enabled says something else (masked, garbage) or hangs: nothing done, reported +echo '{"lock":120,"keyboardAwake":true,"applied":120,"override":false,"reloadPending":false}' > "$prefs" +for st in masked garbage; do + echo "$st" > "$STUB_LOG.state"; : > "$STUB_LOG" + eq "$(run get)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120,"error":"could not tell if the keyboard watcher is enabled"}' + eq "$(cat "$STUB_LOG")" "systemctl --user is-enabled omamobile-lock-keyboard.service" +done +rm -f "$STUB_LOG.state" +cp "$tmp/stubs/systemctl" "$tmp/systemctl.keep" +printf '#!/bin/bash\necho "systemctl $*" >> "$STUB_LOG"\n[[ $2 == is-enabled ]] && sleep 10\nexit 0\n' > "$tmp/stubs/systemctl" +: > "$STUB_LOG" +eq "$(run get)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120,"error":"could not tell if the keyboard watcher is enabled"}' +eq "$(grep -c 'enable --now' "$STUB_LOG")" '0' +# race: a set keyboard off started while get is deciding waits for get's lock, then disables +printf '#!/bin/bash\necho "systemctl $*" >> "$STUB_LOG"\nif [[ $2 == is-enabled ]]; then { OMAMOBILE_LOCK_WATCHER=0 bash "$RACE_SRC/backends/lock.sh" set keyboard off; touch "$STUB_LOG.done"; } >/dev/null 2>&1 9>&- & sleep 1; echo disabled; fi\nexit 0\n' > "$tmp/stubs/systemctl" +: > "$STUB_LOG"; RACE_SRC=$src run get >/dev/null +# a done file, not kill -0: the racer is reparented to the container's PID 1, which may never reap it +for _ in $(seq 100); do [[ -e $STUB_LOG.done ]] && break; sleep 0.2; done +[[ -e $STUB_LOG.done ]] || { echo "FAIL: the racing set keyboard off did not end" >&2; exit 1; } +eq "$(pj keyboardAwake)" 'False' +eq "$(grep 'able' "$STUB_LOG" | tail -1)" "systemctl --user disable --now --no-block omamobile-lock-keyboard.service" +cp "$tmp/systemctl.keep" "$tmp/stubs/systemctl" +echo '{"lock":120,"keyboardAwake":false,"applied":120,"override":false,"reloadPending":false}' > "$prefs" +# systemctl fails: reported in the JSON, the choice is kept +touch "$STUB_FAIL.systemctl" +eq "$(OMAMOBILE_LOCK_UNIT_ENABLED=1 run get)" '{"lock":120,"keyboardAwake":false,"keyboard":false,"effective":120,"error":"could not stop the keyboard watcher"}' +echo '{"lock":120,"keyboardAwake":true,"applied":120,"override":false,"reloadPending":false}' > "$prefs" +eq "$(OMAMOBILE_LOCK_UNIT_ENABLED=0 run get)" '{"lock":120,"keyboardAwake":true,"keyboard":false,"effective":120,"error":"could not start the keyboard watcher"}' +eq "$(pj keyboardAwake)" 'True' +rm -f "$STUB_FAIL.systemctl" +# no lock.json, or a broken one: the unit is never touched +rm -f "$prefs"; : > "$STUB_LOG"; OMAMOBILE_LOCK_UNIT_ENABLED=1 run get >/dev/null; eq "$(cat "$STUB_LOG")" "" +echo '{broken' > "$prefs"; OMAMOBILE_LOCK_UNIT_ENABLED=1 run get >/dev/null; eq "$(cat "$STUB_LOG")" "" +! grep -q 'idle' "$STUB_LOG" || { echo "FAIL: idle service touched" >&2; exit 1; } +echo "lock backend: ok" diff --git a/packages/omamobile-settings/tests/core_tests.cpp b/packages/omamobile-settings/tests/core_tests.cpp index b87a721ce..7166e4d35 100644 --- a/packages/omamobile-settings/tests/core_tests.cpp +++ b/packages/omamobile-settings/tests/core_tests.cpp @@ -11,7 +11,10 @@ #include #include #include +#include #include +#include +#include #include class CoreTests : public QObject { @@ -134,6 +137,65 @@ private slots: QMetaObject::invokeMethod(page.get(), "apply", QVariant(QVariantMap{{"available", false}})); QCOMPARE(page->property("status").toString(), QString("Settings cannot set a charge limit on this phone.")); } + void displaySearchFindsTheScreenLock() { + Backend backend; + backend.setBackendDir(stubs("off")); + backend.search("screen lock"); + QCOMPARE(backend.rows().size(), 1); + QCOMPARE(backend.rows().first().toMap()["id"].toString(), QString("display")); + } + // a backend dir with a stub lock.sh that prints the given line + static QString stubBackends(QTemporaryDir &dir, const QByteArray &line) { + QFile script(dir.filePath("lock.sh")); + if (!script.open(QIODevice::WriteOnly)) return {}; + script.write("echo '" + line + "'\n"); + return dir.path(); + } + void runnerKnowsLockAndRejectsOthers() { + QTemporaryDir dir; + ActionRunner runner; + runner.setBackendDir(stubBackends(dir, R"({"lock":60,"keyboardAwake":false,"keyboard":false,"effective":60})")); + QSignalSpy done(&runner, &ActionRunner::finished); + const int bad = runner.run("nope", {"get"}); + const int badArg = runner.run("lock", {"set", "lock", "60;x"}); + const int lock = runner.run("lock", {"get"}); + QTRY_COMPARE(done.count(), 3); + QMap errors; + for (const auto &call : done) errors[call.at(2).toInt()] = call.at(1).toMap()["error"].toString(); + QCOMPARE(errors[bad], QString("unknown action")); + QCOMPARE(errors[badArg], QString("bad argument")); + QVERIFY(errors[lock].isEmpty()); + QCOMPARE(done.at(2).at(1).toMap()["lock"].toInt(), 60); + // no backend there: an error, not a crash + QTemporaryDir empty; + runner.setBackendDir(empty.path()); + runner.run("lock", {"get"}); + QTRY_COMPARE(done.count(), 4); + QVERIFY(!done.at(3).at(1).toMap()["error"].toString().isEmpty()); + } + void displayPageShowsTheLockAnswer() { + QTemporaryDir dir; + ActionRunner runner; + runner.setBackendDir(stubBackends(dir, R"({"error":"stub says no"})")); + Backend backend; // outlives the engine: the style singleton reads it until the engine goes + backend.setBackendDir(stubs("off")); + QQmlEngine engine; + engine.rootContext()->setContextProperty("backend", &backend); + engine.rootContext()->setContextProperty("actions", &runner); + QQmlComponent component(&engine, QUrl("qrc:/DisplayPage.qml")); + std::unique_ptr page(component.create()); + QVERIFY2(page, qPrintable(component.errorString())); + QCOMPARE(page->property("lockChoices").toList().size(), 5); // 30 s to 5 min, no Never + // the stub backend's error: the lock rows leave "busy" and show it + QTRY_VERIFY(!page->property("lockBusy").toBool()); + QCOMPARE(page->property("lockError").toString(), QString("stub says no")); + QMetaObject::invokeMethod(page.get(), "applyLock", + QVariant(QVariantMap{{"lock", 0}, {"keyboardAwake", true}, {"keyboard", true}, {"effective", 0}})); + QCOMPARE(page->property("lockAfter").toInt(), 0); + QVERIFY(page->property("keyboardAwake").toBool()); + QVERIFY(page->property("keyboard").toBool()); + QVERIFY(page->property("lockError").toString().isEmpty()); + } void searchHasOnlyImplementedRoutesAndBackClearsIt() { Backend backend; backend.setBackendDir(stubs("off")); diff --git a/packages/omamobile-settings/version b/packages/omamobile-settings/version index b1e80bb24..845639eef 100644 --- a/packages/omamobile-settings/version +++ b/packages/omamobile-settings/version @@ -1 +1 @@ -0.1.3 +0.1.4