From 318c7f8db2dbbfceb2b5019d1d4255f0b0de0d47 Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 08:57:38 +0200 Subject: [PATCH 01/15] omamobile-settings: find Hyprland's signature when the app starts without it Some launch paths (the shell's processes) don't pass HYPRLAND_INSTANCE_SIGNATURE, so hyprctl found no Hyprland and the Display page lost its refresh rate rows. display.sh now takes it from the newest live socket under $XDG_RUNTIME_DIR/hypr. --- .../omamobile-settings/backends/display.sh | 16 ++++++++++++++ .../test/display-backend.sh | 22 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/packages/omamobile-settings/backends/display.sh b/packages/omamobile-settings/backends/display.sh index 68090ed0a..d85836669 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" +# Some launch paths (the shell's processes) start the app without HYPRLAND_INSTANCE_SIGNATURE, and hyprctl +# then finds no Hyprland: no refresh rates. Take it from $XDG_RUNTIME_DIR/hypr//.socket.sock, the +# newest live socket if there are several. +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") 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" From 69a6a368c48ccae9fc2cdbdd45beee7cb1f1986d Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:01:06 +0200 Subject: [PATCH 02/15] omamobile-settings: a lock backend and a keyboard watcher backends/lock.sh reads and sets the screen lock time (Omarchy's idle.lock in shell.json, the one timer that locks and then turns the screen off), and with the keyboard toggle on writes 0 there while a Bluetooth or USB keyboard is connected. The choice is kept in ~/.config/omamobile/lock.json; a value changed in Omarchy's own settings is adopted, and nothing is written before the user picks something. omamobile-lock-keyboard (a user unit) runs apply at start and after each burst of input udev events. Tests use a fake sysfs and udev data. --- packages/omamobile-settings/backends/lock.sh | 112 ++++++++++++++++++ packages/omamobile-settings/install | 7 ++ .../libexec/omamobile-lock-keyboard | 15 +++ .../user/omamobile-lock-keyboard.service | 14 +++ packages/omamobile-settings/test/all | 1 + .../omamobile-settings/test/lock-backend.sh | 85 +++++++++++++ 6 files changed, 234 insertions(+) create mode 100755 packages/omamobile-settings/backends/lock.sh create mode 100755 packages/omamobile-settings/libexec/omamobile-lock-keyboard create mode 100644 packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service create mode 100755 packages/omamobile-settings/test/lock-backend.sh diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh new file mode 100755 index 000000000..7a900f9ff --- /dev/null +++ b/packages/omamobile-settings/backends/lock.sh @@ -0,0 +1,112 @@ +#!/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, 300 or 0 (never) +# lock.sh set keyboard on|off stay unlocked while a Bluetooth or USB keyboard is connected +# lock.sh apply write the value in force now (omamobile-lock-keyboard, on each input change) +# 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 with the value last written ("applied"); shell.json's +# idle.lock is the value in force: 0 while the keyboard toggle is on and a keyboard is connected, the +# choice otherwise. If idle.lock no longer holds what this wrote, it was changed elsewhere (Omarchy's own +# settings) and that value becomes the choice. Nothing is written before the user picks something here. +# 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): 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. +set -euo pipefail +set +x +verb=${1:-}; key=${2:-}; value=${3:-} +fail() { printf '{"error":"%s"}\n' "$1"; exit 2; } +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 + +keyboard_connected() { + local ev dev path bus + for ev in "$sys"/class/input/event*; do + [[ -r $ev/dev && -r $ev/device/id/bustype ]] || continue + dev=$(<"$ev/dev") + grep -qx 'E:ID_INPUT_KEYBOARD=1' "$udev/c$dev" 2>/dev/null || continue + bus=$(<"$ev/device/id/bustype") + path=$(realpath -- "$ev/device") + case $bus in + 0005) return 0 ;; + 0003) [[ $path == */devices/virtual/input/* ]] || return 0 ;; + esac + done + return 1 +} +kb=false; keyboard_connected && kb=true + +# All JSON work in one place: reads prefs and shell.json, applies the verb, writes both atomically. +/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$kb" "$verb" "$key" "$value" <<'PY' +import json, os, sys +prefs_path, shell_path, defaults_path, kb, verb, key, value = sys.argv[1:] +kb = kb == "true" +CHOICES = (30, 60, 120, 180, 300, 0) +def out(d): print(json.dumps(d, separators=(",", ":"))); sys.exit(0) +def fail(m): print(json.dumps({"error": m}, separators=(",", ":"))); sys.exit(2) +def load(p): + try: + with open(p) as f: d = json.load(f) + return d if isinstance(d, dict) else None + except (OSError, ValueError): + return None +def save(p, d, indent=None): + os.makedirs(os.path.dirname(p), exist_ok=True) + with open(p + ".new", "w") as f: + json.dump(d, f, indent=indent); f.write("\n") + os.replace(p + ".new", p) +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 + +shell = load(shell_path) +if shell is not None and shell.get("version") != 1: shell = None # Omarchy ignores it: so do we +current = secs(((shell or load(defaults_path) or {}).get("idle") or {}).get("lock"), 300) +prefs = load(prefs_path) +if prefs is not None: + applied = prefs.get("applied") + if isinstance(applied, int) and applied != current: + 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")) + +if verb == "get": + p = prefs or {"lock": current, "keyboardAwake": False} + out({"lock": p["lock"], "keyboardAwake": p["keyboardAwake"], "keyboard": kb, "effective": current}) +elif verb == "set": + p = prefs or {"lock": current, "keyboardAwake": 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 == "apply": + if prefs is None: out({"applied": None}) # never set here: leave Omarchy's value alone +else: + fail("usage: get|set|apply") + +want = 0 if prefs["keyboardAwake"] and kb else prefs["lock"] +if want != current: + if shell is None: + shell = load(defaults_path) # 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") +prefs["applied"] = want +try: save(prefs_path, prefs) +except OSError: fail("cannot save the setting") +out({"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want}) +PY diff --git a/packages/omamobile-settings/install b/packages/omamobile-settings/install index 6847708ce..d6a0c8cc3 100755 --- a/packages/omamobile-settings/install +++ b/packages/omamobile-settings/install @@ -15,3 +15,10 @@ 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 > "Stay unlocked while a keyboard is connected", for every user's graphical session; it does +# nothing until the user picks a lock setting on the page. +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" +install -d "$dest/usr/lib/systemd/user/graphical-session.target.wants" +ln -sfn ../omamobile-lock-keyboard.service "$dest/usr/lib/systemd/user/graphical-session.target.wants/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..5f07e8ec4 --- /dev/null +++ b/packages/omamobile-settings/libexec/omamobile-lock-keyboard @@ -0,0 +1,15 @@ +#!/bin/bash +# SPDX-License-Identifier: MIT +# Keeps the phone unlocked while a keyboard is connected, when the Display page's toggle says so: +# runs the lock backend's apply at start (so a crash with a keyboard attached can't leave "never" behind) +# and after every input add or remove, once the burst of events a device brings has settled (1 s). +# The backend does nothing until the user has picked a lock setting. +set -u +backend=${OMAMOBILE_LOCK_BACKEND:-/usr/lib/omamobile-settings/backends/lock.sh} +apply() { bash "$backend" apply >/dev/null || true; } +apply +udevadm monitor --udev --subsystem-match=input | while read -r line; do + [[ $line == UDEV* ]] || continue + while read -r -t 1 _; do :; done + apply +done 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..4418e8118 --- /dev/null +++ b/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service @@ -0,0 +1,14 @@ +# SPDX-License-Identifier: MIT +# Settings > Display > "Stay unlocked while a keyboard is connected": follows keyboards coming and going. +[Unit] +Description=Omarchy Mobile: stay unlocked while a keyboard is connected +PartOf=graphical-session.target +After=graphical-session.target + +[Service] +ExecStart=/usr/lib/omamobile-settings/omamobile-lock-keyboard +Restart=on-failure +RestartSec=5 + +[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/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh new file mode 100755 index 000000000..5488b7139 --- /dev/null +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -0,0 +1,85 @@ +#!/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 +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"; } +# an input device: N, bus, keyboard (1/0), where it lives under /sys/devices +dev() { + local d=$tmp/sys/devices/$4/input$1 + mkdir -p "$d/id" "$tmp/sys/class/input/event$1" + echo "$2" > "$d/id/bustype" + 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))" +} +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)" '{"lock":0,"keyboardAwake":false,"keyboard":false,"effective":0}' +eq "$(idle)" '0 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"}' +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): never lock +dev 4 0005 1 virtual/misc/uhid/0005:046D:B35B.0001 +eq "$(run apply)" '{"lock":30,"keyboardAwake":true,"keyboard":true,"effective":0}' +eq "$(idle)" '0 0 omamobile.bar' +# picking a time while it is connected keeps "never" in force, and keeps the choice +eq "$(run set lock 300)" '{"lock":300,"keyboardAwake":true,"keyboard":true,"effective":0}' +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":0}' +# 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' + +# the watcher: apply once at start, then once per settled burst of input events (fake udevadm, stub backend) +mkdir -p "$tmp/bin" +printf '#!/bin/sh\necho "monitor will print the received events for:"\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" +PATH="$tmp/bin:$PATH" OMAMOBILE_LOCK_BACKEND=$tmp/stub.sh timeout 20 bash "$src/libexec/omamobile-lock-keyboard" +eq "$(tr '\n' ' ' < "$tmp/calls")" 'apply apply apply ' +echo "lock backend: ok" From b896b2823ac100c0afa20a0e043a52f4f0b66c1a Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:01:06 +0200 Subject: [PATCH 03/15] omamobile-settings 0.1.3: Lock screen after, and stay unlocked with a keyboard The Display page gets 30 s, 1, 2, 3, 5 min and Never, plus an on/off for staying unlocked while a keyboard is connected. The text says that lock and screen off are the same timer and that Never also keeps the phone awake. 0.1.3 clashes with open #629, #630 and #860; renumber at merge. --- packages/omamobile-settings/README.md | 23 ++++++- .../omamobile-settings/app/DisplayPage.qml | 60 ++++++++++++++++++- .../omamobile-settings/app/actionrunner.cpp | 2 +- .../omamobile-settings/app/actionrunner.h | 2 +- packages/omamobile-settings/app/catalog.json | 2 +- .../omamobile-settings/tests/core_tests.cpp | 46 ++++++++++++++ 6 files changed, 128 insertions(+), 7 deletions(-) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index 3cdd006cd..f16eab1a4 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -10,8 +10,27 @@ 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. display.sh finds Hyprland's instance signature from +`$XDG_RUNTIME_DIR/hypr/*/.socket.sock` (the newest live one) when the app was +started without `HYPRLAND_INSTANCE_SIGNATURE`. + +"Lock screen after" (30 s, 1, 2, 3 or 5 min, Never) 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. Never means the +screen stays on and the phone never sleeps by itself (omamobile-sleepd sleeps +only with the screen off behind a secure lock); the power key still locks. +"Stay unlocked while a keyboard is connected" writes 0 there while a Bluetooth +or USB keyboard (udev `ID_INPUT_KEYBOARD=1`, bus 0005, or bus 0003 outside +`/devices/virtual/input`) 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`. The choice lives in +`~/.config/omamobile/lock.json`; a value changed in Omarchy's own settings is +adopted. Nothing is written until the user picks something on the page. A +receiver mouse that also reports keys counts as a keyboard. + 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..f4fa5dc50 100644 --- a/packages/omamobile-settings/app/DisplayPage.qml +++ b/packages/omamobile-settings/app/DisplayPage.qml @@ -12,6 +12,21 @@ 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")}, {s: 0, t: qsTr("Never")}] + function applyLock(r) { + lockBusy = false + if (r.error) { lockError = r.error; return } + if (r.lock === undefined) { lockError = qsTr("The lock backend gave no values."); return } + lockError = ""; lockAfter = r.lock; keyboardAwake = !!r.keyboardAwake; keyboard = !!r.keyboard + } function apply(r) { busy = false if (r.error) { status = r.error; return } @@ -20,8 +35,14 @@ 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"]) } SettingsLabel { text: qsTr("Brightness"); font.weight: Font.DemiBold; color: backend.foreground; Layout.fillWidth: true } Flow { Layout.fillWidth: true; spacing: 8 @@ -51,5 +72,40 @@ ColumnLayout { } } SettingsLabel { text: page.status; color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: 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("Never: the phone stays unlocked and the screen stays on until you press the power key. It also won't go to sleep by itself.") + : 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("Stay unlocked 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. While one is connected the screen also stays on.") + color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true + } Item { Layout.fillHeight: 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/tests/core_tests.cpp b/packages/omamobile-settings/tests/core_tests.cpp index b87a721ce..b67eb83fe 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,49 @@ 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")); + } + void runnerKnowsLockAndRejectsOthers() { + ActionRunner runner; + runner.setBackendDir(stubs("off")); + 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] != "unknown action" && errors[lock] != "bad argument"); + } + void displayPageShowsTheLockAnswer() { + ActionRunner runner; + runner.setBackendDir(stubs("off")); + 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(), 6); + // no lock.sh in the stub dir: the lock rows leave "busy" and show the runner's error + QTRY_VERIFY(!page->property("lockBusy").toBool()); + QVERIFY(!page->property("lockError").toString().isEmpty()); + 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")); From b594960be42088da24688b0a82bb957099ca08dd Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:09:52 +0200 Subject: [PATCH 04/15] omamobile-settings: lock backend never leaves the keyboard's 0 behind lock.json (with an override flag) is saved before shell.json, so our own 0 is never adopted as the user's Never. Both files under one flock, mkstemp temp files with fsync, shell.json read again just before the write. An unparseable or other-version shell.json is an error and nothing is written. The 0 is only written while the watcher runs; the unit restarts always and puts the choice back with lock.sh restore on stop. The watcher exits non-zero when udevadm monitor ends or an apply fails, and skips the udevadm header line. Keyboards need the letter keys and space and a name that isn't a token or scanner. --- packages/omamobile-settings/README.md | 20 +- .../omamobile-settings/app/DisplayPage.qml | 2 +- .../omamobile-settings/backends/display.sh | 2 +- packages/omamobile-settings/backends/lock.sh | 173 ++++++++++++------ .../libexec/omamobile-lock-keyboard | 15 +- .../user/omamobile-lock-keyboard.service | 7 +- .../omamobile-settings/test/lock-backend.sh | 93 +++++++++- 7 files changed, 236 insertions(+), 76 deletions(-) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index f16eab1a4..9841f5cfa 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -24,12 +24,20 @@ screen stays on and the phone never sleeps by itself (omamobile-sleepd sleeps only with the screen off behind a secure lock); the power key still locks. "Stay unlocked while a keyboard is connected" writes 0 there while a Bluetooth or USB keyboard (udev `ID_INPUT_KEYBOARD=1`, bus 0005, or bus 0003 outside -`/devices/virtual/input`) 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`. The choice lives in -`~/.config/omamobile/lock.json`; a value changed in Omarchy's own settings is -adopted. Nothing is written until the user picks something on the page. A -receiver mouse that also reports keys counts as a keyboard. +`/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 always +restarted, and when it stops `lock.sh restore` writes the chosen time back. +The 0 is only written while that unit runs. The choice lives in +`~/.config/omamobile/lock.json`, saved before `shell.json` with a flag saying +whether the 0 in force is the keyboard's, so a crash never turns it into +"Never". 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 diff --git a/packages/omamobile-settings/app/DisplayPage.qml b/packages/omamobile-settings/app/DisplayPage.qml index f4fa5dc50..bda18c5db 100644 --- a/packages/omamobile-settings/app/DisplayPage.qml +++ b/packages/omamobile-settings/app/DisplayPage.qml @@ -104,7 +104,7 @@ ColumnLayout { } SettingsLabel { text: (page.keyboard ? qsTr("A keyboard is connected now. ") : qsTr("No keyboard is connected now. ")) - + qsTr("Any Bluetooth or USB keyboard counts. While one is connected the screen also stays on.") + + qsTr("Any Bluetooth or USB keyboard counts. While one is connected the screen also stays on. A Bluetooth keyboard that goes to sleep counts as disconnected.") color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true } Item { Layout.fillHeight: true } diff --git a/packages/omamobile-settings/backends/display.sh b/packages/omamobile-settings/backends/display.sh index d85836669..65dd0a858 100755 --- a/packages/omamobile-settings/backends/display.sh +++ b/packages/omamobile-settings/backends/display.sh @@ -23,7 +23,7 @@ fake='' # Some launch paths (the shell's processes) start the app without HYPRLAND_INSTANCE_SIGNATURE, and hyprctl # then finds no Hyprland: no refresh rates. Take it from $XDG_RUNTIME_DIR/hypr//.socket.sock, the -# newest live socket if there are several. +# 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 diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index 7a900f9ff..a67dbc8f7 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -5,84 +5,146 @@ # lock.sh set lock N N is 30, 60, 120, 180, 300 or 0 (never) # lock.sh set keyboard on|off stay unlocked while a Bluetooth or USB keyboard is connected # 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 with the value last written ("applied"); shell.json's -# idle.lock is the value in force: 0 while the keyboard toggle is on and a keyboard is connected, the -# choice otherwise. If idle.lock no longer holds what this wrote, it was changed elsewhere (Omarchy's own -# settings) and that value becomes the choice. Nothing is written before the user picks something here. +# The choice is kept in ~/.config/omamobile/lock.json: {lock, keyboardAwake, applied, override}. "applied" is +# the value last written to shell.json's idle.lock, and "override" says that value is the keyboard's 0, not +# the user's choice. lock.json is always saved before shell.json, so after a crash or a failed write the +# keyboard's 0 is never taken for the user's "Never". 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. +# Nothing is written before the user picks something here. The keyboard's 0 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): 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. +# 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". set -euo pipefail set +x verb=${1:-}; key=${2:-}; value=${3:-} -fail() { printf '{"error":"%s"}\n' "$1"; exit 2; } 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 -keyboard_connected() { - local ev dev path bus - for ev in "$sys"/class/input/event*; do - [[ -r $ev/dev && -r $ev/device/id/bustype ]] || continue - dev=$(<"$ev/dev") - grep -qx 'E:ID_INPUT_KEYBOARD=1' "$udev/c$dev" 2>/dev/null || continue - bus=$(<"$ev/device/id/bustype") - path=$(realpath -- "$ev/device") - case $bus in - 0005) return 0 ;; - 0003) [[ $path == */devices/virtual/input/* ]] || return 0 ;; - esac - done - return 1 -} -kb=false; keyboard_connected && kb=true - -# All JSON work in one place: reads prefs and shell.json, applies the verb, writes both atomically. -/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$kb" "$verb" "$key" "$value" <<'PY' -import json, os, sys -prefs_path, shell_path, defaults_path, kb, verb, key, value = sys.argv[1:] -kb = kb == "true" +# All work in one place: finds keyboards, reads prefs and shell.json, applies the verb, writes both. +/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' +import fcntl, json, os, re, struct, sys, tempfile +prefs_path, shell_path, defaults_path, sysfs, udev, watcher, verb, key, value = sys.argv[1:] CHOICES = (30, 60, 120, 180, 300, 0) def out(d): print(json.dumps(d, separators=(",", ":"))); sys.exit(0) def fail(m): print(json.dumps({"error": m}, separators=(",", ":"))); sys.exit(2) -def load(p): + +# --- 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: d = json.load(f) - return d if isinstance(d, dict) else None - except (OSError, ValueError): - return None + 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): - os.makedirs(os.path.dirname(p), exist_ok=True) - with open(p + ".new", "w") as f: - json.dump(d, f, indent=indent); f.write("\n") - os.replace(p + ".new", p) + 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") -shell = load(shell_path) -if shell is not None and shell.get("version") != 1: shell = None # Omarchy ignores it: so do we -current = secs(((shell or load(defaults_path) or {}).get("idle") or {}).get("lock"), 300) -prefs = load(prefs_path) +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) if prefs is not None: - applied = prefs.get("applied") - if isinstance(applied, int) and applied != current: + applied, override = prefs.get("applied"), bool(prefs.get("override")) + if isinstance(applied, int) and applied != current and not (override and current == 0): 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} out({"lock": p["lock"], "keyboardAwake": p["keyboardAwake"], "keyboard": kb, "effective": current}) elif verb == "set": - p = prefs or {"lock": current, "keyboardAwake": False} + 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) @@ -91,22 +153,27 @@ elif verb == "set": p["keyboardAwake"] = value == "on" else: fail("unknown key") prefs = p -elif verb == "apply": +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") + fail("usage: get|set|apply|restore") -want = 0 if prefs["keyboardAwake"] and kb else prefs["lock"] +override = verb != "restore" and watcher == "1" and prefs["keyboardAwake"] and kb and prefs["lock"] != 0 +want = 0 if override else prefs["lock"] +# 1. lock.json first: if we die before shell.json, the next run knows a 0 there is ours +prefs["applied"], prefs["override"] = want, override +try: save(prefs_path, prefs) +except OSError: fail("cannot save the setting") +# 2. shell.json, read again just before the write so a concurrent Omarchy change to other keys is kept if want != current: + try: shell = user_shell() + except Unreadable: fail("shell.json is not readable") if shell is None: - shell = load(defaults_path) # Omarchy never merges: start from its defaults, as omarchy-shell-config does + 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") -prefs["applied"] = want -try: save(prefs_path, prefs) -except OSError: fail("cannot save the setting") out({"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want}) PY diff --git a/packages/omamobile-settings/libexec/omamobile-lock-keyboard b/packages/omamobile-settings/libexec/omamobile-lock-keyboard index 5f07e8ec4..3249a2d31 100755 --- a/packages/omamobile-settings/libexec/omamobile-lock-keyboard +++ b/packages/omamobile-settings/libexec/omamobile-lock-keyboard @@ -3,13 +3,16 @@ # Keeps the phone unlocked while a keyboard is connected, when the Display page's toggle says so: # runs the lock backend's apply at start (so a crash with a keyboard attached can't leave "never" behind) # and after every input add or remove, once the burst of events a device brings has settled (1 s). -# The backend does nothing until the user has picked a lock setting. -set -u +# The backend does nothing until the user has picked a lock setting. If udevadm monitor ends or an apply +# fails, this exits non-zero: the unit restarts it (Restart=always) and its ExecStopPost puts the choice back. +set -u -o pipefail backend=${OMAMOBILE_LOCK_BACKEND:-/usr/lib/omamobile-settings/backends/lock.sh} -apply() { bash "$backend" apply >/dev/null || true; } -apply +apply() { bash "$backend" apply >/dev/null; } +apply || exit 1 udevadm monitor --udev --subsystem-match=input | while read -r line; do - [[ $line == UDEV* ]] || continue + [[ $line == 'UDEV ['* ]] || continue # events only, not the "UDEV - the event which udev sends" header while read -r -t 1 _; do :; done - apply + apply || exit 1 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 index 4418e8118..c0b29e87f 100644 --- a/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service +++ b/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service @@ -1,5 +1,7 @@ # SPDX-License-Identifier: MIT # Settings > Display > "Stay unlocked while a keyboard is connected": follows keyboards coming and going. +# The keyboard's "never lock" is only written while this runs; when it stops for any reason the user's +# chosen timeout is written back (ExecStopPost), and it is always restarted. [Unit] Description=Omarchy Mobile: stay unlocked while a keyboard is connected PartOf=graphical-session.target @@ -7,8 +9,9 @@ After=graphical-session.target [Service] ExecStart=/usr/lib/omamobile-settings/omamobile-lock-keyboard -Restart=on-failure -RestartSec=5 +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/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index 5488b7139..cf0d3bf07 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -5,7 +5,7 @@ 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 +export OMAMOBILE_LOCK_SYSFS=$tmp/sys OMAMOBILE_LOCK_UDEVDATA=$tmp/udev OMAMOBILE_LOCK_WATCHER=1 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" @@ -13,15 +13,19 @@ echo '{"version":1,"bar":{"id":"default"},"idle":{"screensaver":150,"lock":300}} 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"; } -# an input device: N, bus, keyboard (1/0), where it lives under /sys/devices +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" "$tmp/sys/class/input/event$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 @@ -44,7 +48,7 @@ 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"}' +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}' @@ -75,11 +79,86 @@ rm "$shell" eq "$(run set lock 60)" '{"lock":60,"keyboardAwake":false,"keyboard":false,"effective":60}' eq "$(idle)" '60 150 default' -# the watcher: apply once at start, then once per settled burst of input events (fake udevadm, stub backend) +# 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":0}' +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 0 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":0}' + +# a run that died after lock.json (override) but before shell.json, or after both: our 0 is never adopted +gone 6 +echo '{"lock":120,"keyboardAwake":true,"applied":0,"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":0,"override":true}' > "$prefs" +sed -i 's/"lock": 120/"lock": 0/' "$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 [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 "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" -PATH="$tmp/bin:$PATH" OMAMOBILE_LOCK_BACKEND=$tmp/stub.sh timeout 20 bash "$src/libexec/omamobile-lock-keyboard" +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 failed apply also ends it non-zero, so systemd restarts it +printf '#!/bin/sh\nexit 2\n' > "$tmp/stub.sh" +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 "$rc" 1 +grep -qx 'Restart=always' "$src/systemd/user/omamobile-lock-keyboard.service" +grep -q '^ExecStopPost=.*lock.sh restore$' "$src/systemd/user/omamobile-lock-keyboard.service" echo "lock backend: ok" From 4dc530aeb810e7f627d7d22a913bf32586357f03 Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:09:52 +0200 Subject: [PATCH 05/15] omamobile-settings: tests point the action runner at stub backends The lock tests no longer depend on whether the backend is installed on the host. --- .../omamobile-settings/tests/core_tests.cpp | 26 +++++++++++++++---- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/omamobile-settings/tests/core_tests.cpp b/packages/omamobile-settings/tests/core_tests.cpp index b67eb83fe..8ac58c674 100644 --- a/packages/omamobile-settings/tests/core_tests.cpp +++ b/packages/omamobile-settings/tests/core_tests.cpp @@ -144,9 +144,17 @@ private slots: 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(stubs("off")); + 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"}); @@ -156,11 +164,19 @@ private slots: 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] != "unknown action" && errors[lock] != "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(stubs("off")); + 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; @@ -170,9 +186,9 @@ private slots: std::unique_ptr page(component.create()); QVERIFY2(page, qPrintable(component.errorString())); QCOMPARE(page->property("lockChoices").toList().size(), 6); - // no lock.sh in the stub dir: the lock rows leave "busy" and show the runner's error + // the stub backend's error: the lock rows leave "busy" and show it QTRY_VERIFY(!page->property("lockBusy").toBool()); - QVERIFY(!page->property("lockError").toString().isEmpty()); + 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); From 7a7cc18adb2810344b049024053ae4a91b79f5d9 Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:26:41 +0200 Subject: [PATCH 06/15] omamobile-settings: set the brightness through the user's session when brightnessctl can't Settings started from a login outside the graphical session (for example over SSH) is not in the logind session that owns the screen, so brightnessctl's SetBrightness on the caller's session is refused and the buttons did nothing. Fall back to the user's graphical session (loginctl Display) by its object path. --- packages/omamobile-settings/README.md | 7 +++--- .../omamobile-settings/backends/display.sh | 24 +++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index 9841f5cfa..7f32cdc9d 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -12,9 +12,10 @@ 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) and the screen lock. The page runs `backends/display.sh` and `backends/lock.sh` through a fixed-argument runner, -with no shell string. display.sh finds Hyprland's instance signature from -`$XDG_RUNTIME_DIR/hypr/*/.socket.sock` (the newest live one) when the app was -started without `HYPRLAND_INSTANCE_SIGNATURE`. +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, Never) sets `idle.lock` in `~/.config/omarchy/shell.json`, the one timer Omarchy's idle service has: the diff --git a/packages/omamobile-settings/backends/display.sh b/packages/omamobile-settings/backends/display.sh index 65dd0a858..605a7dc4e 100755 --- a/packages/omamobile-settings/backends/display.sh +++ b/packages/omamobile-settings/backends/display.sh @@ -21,8 +21,8 @@ fail() { printf '{"error":"%s"}\n' "$1"; exit 2; } fake='' [[ -z $fake || -r $fake ]] || fail "cannot read the test file" -# Some launch paths (the shell's processes) start the app without HYPRLAND_INSTANCE_SIGNATURE, and hyprctl -# then finds no Hyprland: no refresh rates. Take it from $XDG_RUNTIME_DIR/hypr//.socket.sock, the +# 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 @@ -51,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 From 79e3e9ede7fa325ccfb89c5440af7ef45fcf48be Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:47:52 +0200 Subject: [PATCH 07/15] omamobile-settings: make a new lock time take effect without restarting the shell Omarchy's idle service keeps the timeout its idle monitor was made with, so a lock time changed on the page only applied after the shell restarted (seen on the 8 Pro: 30 s set live never locked, and locked 30 s after a shell restart). After writing idle.lock, switch idle off and on through its IPC when idle is on and stay-awake is off. Tests never touch the host's idle service. --- packages/omamobile-settings/backends/lock.sh | 17 +++++++++++++++- .../omamobile-settings/test/lock-backend.sh | 20 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index a67dbc8f7..ffac90b89 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -40,7 +40,8 @@ if [[ -z $watcher ]]; then fi # All work in one place: finds keyboards, reads prefs and shell.json, applies the verb, writes both. -/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' +rc=0 +res=$(/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' import fcntl, json, os, re, struct, sys, tempfile prefs_path, shell_path, defaults_path, sysfs, udev, watcher, verb, key, value = sys.argv[1:] CHOICES = (30, 60, 120, 180, 300, 0) @@ -177,3 +178,17 @@ if want != current: except OSError: fail("cannot write shell.json") out({"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want}) PY +) || rc=$? +printf '%s\n' "$res" +[[ $rc -eq 0 ]] || exit "$rc" + +# Omarchy's idle service keeps the timeout its idle monitor started with: a new idle.lock only takes +# effect after the shell restarts. Switch idle off and on through its own IPC so the monitor is made +# again with the new value. Only when idle is on and stay-awake is off, so neither is changed. +if [[ $verb != get && -z ${OMAMOBILE_LOCK_NO_REARM:-} ]] && command -v omarchy-shell >/dev/null 2>&1; then + st=$(timeout 5 omarchy-shell idle status 2>/dev/null | tail -n1 || true) + if [[ $st == *'"enabled":true'* && $st == *'"stayAwake":false'* ]]; then + timeout 5 omarchy-shell idle disable >/dev/null 2>&1 || true + timeout 5 omarchy-shell idle enable >/dev/null 2>&1 || true + fi +fi diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index cf0d3bf07..77d161ef6 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -2,6 +2,7 @@ # SPDX-License-Identifier: MIT # backends/lock.sh against a scratch HOME, a fake /sys/class/input and /run/udev/data. set -euo pipefail +export OMAMOBILE_LOCK_NO_REARM=1 # never touch the idle service of the machine running the tests 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 @@ -161,4 +162,23 @@ rc=0; PATH="$tmp/bin:$PATH" OMAMOBILE_LOCK_BACKEND=$tmp/stub.sh timeout 20 bash eq "$rc" 1 grep -qx 'Restart=always' "$src/systemd/user/omamobile-lock-keyboard.service" grep -q '^ExecStopPost=.*lock.sh restore$' "$src/systemd/user/omamobile-lock-keyboard.service" +# The idle re-arm: with idle on and stay-awake off a set switches idle off and on; with stay-awake on, +# or for get, it is left alone. A fake omarchy-shell logs its calls. +mkdir -p "$tmp/rearm"; cat > "$tmp/rearm/omarchy-shell" <<'SH' +#!/bin/bash +echo "$*" >> "$REARM_LOG" +[[ $* == "idle status" ]] && cat "$REARM_STATUS" +exit 0 +SH +chmod +x "$tmp/rearm/omarchy-shell" +export REARM_LOG=$tmp/rearm/log REARM_STATUS=$tmp/rearm/status +echo '{"enabled":true,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG" +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 60 >/dev/null +eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status,idle disable,idle enable," +echo '{"enabled":true,"stayAwake":true}' > "$REARM_STATUS"; : > "$REARM_LOG" +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 120 >/dev/null +eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status," +: > "$REARM_LOG" +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" get >/dev/null +eq "$(cat "$REARM_LOG")" "" echo "lock backend: ok" From f92dc3a22c15a70e90c005e85a07e2b8212f1cb2 Mon Sep 17 00:00:00 2001 From: Lef Date: Tue, 17 Nov 2026 09:54:51 +0200 Subject: [PATCH 08/15] omamobile-settings: re-arm idle only when shell.json changed, and never leave it off From review: the keyboard watcher calls apply after every input change, and each re-arm restarts the idle countdown, so re-arm only when idle.lock was really written. If idle doesn't come back on after disable, retry and fail loudly instead of leaving the phone never locking. --- packages/omamobile-settings/backends/lock.sh | 25 ++++++++++++++----- .../omamobile-settings/test/lock-backend.sh | 24 +++++++++++++++++- 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index ffac90b89..828ae1780 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -40,8 +40,9 @@ if [[ -z $watcher ]]; then fi # All work in one place: finds keyboards, reads prefs and shell.json, applies the verb, writes both. +markdir=$(mktemp -d); trap 'rm -rf "$markdir"' EXIT; mark=$markdir/written rc=0 -res=$(/usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' +res=$(LOCK_WRITTEN_MARK=$mark /usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' import fcntl, json, os, re, struct, sys, tempfile prefs_path, shell_path, defaults_path, sysfs, udev, watcher, verb, key, value = sys.argv[1:] CHOICES = (30, 60, 120, 180, 300, 0) @@ -166,6 +167,7 @@ prefs["applied"], prefs["override"] = want, override try: save(prefs_path, prefs) except OSError: fail("cannot save the setting") # 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") @@ -176,6 +178,9 @@ if want != current: idle["lock"] = want; shell["idle"] = idle try: save(shell_path, shell, indent=2) except OSError: fail("cannot write shell.json") + written = True + mark = os.environ.get("LOCK_WRITTEN_MARK") + if mark: open(mark, "w").close() out({"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want}) PY ) || rc=$? @@ -185,10 +190,18 @@ printf '%s\n' "$res" # Omarchy's idle service keeps the timeout its idle monitor started with: a new idle.lock only takes # effect after the shell restarts. Switch idle off and on through its own IPC so the monitor is made # again with the new value. Only when idle is on and stay-awake is off, so neither is changed. -if [[ $verb != get && -z ${OMAMOBILE_LOCK_NO_REARM:-} ]] && command -v omarchy-shell >/dev/null 2>&1; then - st=$(timeout 5 omarchy-shell idle status 2>/dev/null | tail -n1 || true) - if [[ $st == *'"enabled":true'* && $st == *'"stayAwake":false'* ]]; then - timeout 5 omarchy-shell idle disable >/dev/null 2>&1 || true +idle_status() { timeout 5 omarchy-shell idle status 2>/dev/null | tail -n1 || true; } +idle_on() { local st; st=$(idle_status); [[ $st == *'"enabled":true'* && $st == *'"stayAwake":false'* ]]; } +# Only when shell.json really changed: a re-arm restarts the idle countdown, and the keyboard watcher +# calls apply after every input change. +if [[ -e $mark && -z ${OMAMOBILE_LOCK_NO_REARM:-} ]] && command -v omarchy-shell >/dev/null 2>&1 && idle_on; then + timeout 5 omarchy-shell idle disable >/dev/null 2>&1 || true + # Never leave idle off: enable until the status says so. + for _ in 1 2 3; do timeout 5 omarchy-shell idle enable >/dev/null 2>&1 || true - fi + [[ $(idle_status) == *'"enabled":true'* ]] && exit 0 + sleep 1 + done + echo "lock.sh: could not switch Omarchy's idle back on" >&2 + exit 3 fi diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index 77d161ef6..b92932ad2 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -174,10 +174,32 @@ chmod +x "$tmp/rearm/omarchy-shell" export REARM_LOG=$tmp/rearm/log REARM_STATUS=$tmp/rearm/status echo '{"enabled":true,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG" PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 60 >/dev/null -eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status,idle disable,idle enable," +eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status,idle disable,idle enable,idle status," +# the same value again: shell.json unchanged, no re-arm (it would restart the countdown) +: > "$REARM_LOG" +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 60 >/dev/null +eq "$(cat "$REARM_LOG")" "" +# idle switched off by the user: left alone +echo '{"enabled":false,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG" +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 90 >/dev/null || true +PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 180 >/dev/null +eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status," +# enable that never takes: retried, then a non-zero exit instead of silence +cat > "$tmp/rearm/omarchy-shell" <<'SH' +#!/bin/bash +echo "$*" >> "$REARM_LOG" +[[ $* == "idle status" ]] && { [[ -e $REARM_LOG.disabled ]] && echo '{"enabled":false,"stayAwake":false}' || cat "$REARM_STATUS"; } +[[ $* == "idle disable" ]] && touch "$REARM_LOG.disabled" +exit 0 +SH +echo '{"enabled":true,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG"; rm -f "$REARM_LOG.disabled" +rc=0; PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 300 >/dev/null 2>&1 || rc=$? +eq "$rc" 3 +eq "$(grep -c 'idle enable' "$REARM_LOG")" 3 echo '{"enabled":true,"stayAwake":true}' > "$REARM_STATUS"; : > "$REARM_LOG" PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 120 >/dev/null eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status," +rm -f "$REARM_LOG.disabled" : > "$REARM_LOG" PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" get >/dev/null eq "$(cat "$REARM_LOG")" "" From 41910772e815d2d9119c504c4c5ac5e35f1f2e38 Mon Sep 17 00:00:00 2001 From: Lef Date: Wed, 18 Nov 2026 07:50:09 +0200 Subject: [PATCH 09/15] omamobile-settings: reload the shell config instead of toggling idle, 30 min lock with a keyboard Following Derek's review: a new idle.lock now reaches the running shell through `omarchy-shell shell reloadConfig`, the same way omarchy-shell-config does it. The idle disable/enable step is gone, so Stay awake is never touched. If the reload fails, the value stays saved and the JSON carries an error the page shows. A failed reload stays pending in lock.json and is retried on the next run until it works. If the watcher cannot be started the toggle goes back to off; turning it off does not wait for the unit (--no-block), since the backend has already written the choice back. With a keyboard connected the lock is now 1800 s instead of never (a chosen Never stays never). The watcher unit is no longer enabled for everyone: the toggle enables and starts it, and turning it off stops and disables it, which restores the choice. A failed apply (a broken shell.json) is logged once instead of restarting the unit every 10 s. lock.json is only rewritten when it changed, and depends now lists coreutils and systemd. --- packages/omamobile-settings/README.md | 32 ++-- .../omamobile-settings/app/DisplayPage.qml | 8 +- packages/omamobile-settings/backends/lock.sh | 116 ++++++++---- packages/omamobile-settings/install | 6 +- .../libexec/omamobile-lock-keyboard | 23 ++- .../user/omamobile-lock-keyboard.service | 9 +- .../omamobile-settings/test/lock-backend.sh | 178 ++++++++++++------ 7 files changed, 241 insertions(+), 131 deletions(-) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index 7f32cdc9d..bcc9ab10a 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -23,17 +23,27 @@ 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. Never means the screen stays on and the phone never sleeps by itself (omamobile-sleepd sleeps only with the screen off behind a secure lock); the power key still locks. -"Stay unlocked while a keyboard is connected" writes 0 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 always -restarted, and when it stops `lock.sh restore` writes the chosen time back. -The 0 is only written while that unit runs. The choice lives in -`~/.config/omamobile/lock.json`, saved before `shell.json` with a flag saying -whether the 0 in force is the keyboard's, so a crash never turns it into -"Never". A value changed in Omarchy's own settings is adopted. Nothing is +"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; a chosen Never stays never. 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, 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 diff --git a/packages/omamobile-settings/app/DisplayPage.qml b/packages/omamobile-settings/app/DisplayPage.qml index bda18c5db..945d7f0d1 100644 --- a/packages/omamobile-settings/app/DisplayPage.qml +++ b/packages/omamobile-settings/app/DisplayPage.qml @@ -23,9 +23,11 @@ ColumnLayout { {s: 180, t: qsTr("3 min")}, {s: 300, t: qsTr("5 min")}, {s: 0, t: qsTr("Never")}] 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 = ""; lockAfter = r.lock; keyboardAwake = !!r.keyboardAwake; keyboard = !!r.keyboard + lockError = "" } function apply(r) { busy = false @@ -90,7 +92,7 @@ ColumnLayout { : 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("Stay unlocked while a keyboard is connected"); font.weight: Font.DemiBold; color: backend.foreground; wrapMode: Text.Wrap; Layout.fillWidth: true; Layout.topMargin: 8 } + 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 { @@ -104,7 +106,7 @@ ColumnLayout { } SettingsLabel { text: (page.keyboard ? qsTr("A keyboard is connected now. ") : qsTr("No keyboard is connected now. ")) - + qsTr("Any Bluetooth or USB keyboard counts. While one is connected the screen also stays on. A Bluetooth keyboard that goes to sleep counts as disconnected.") + + 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 (Never stays never). A Bluetooth keyboard that goes to sleep counts as disconnected.") color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true } Item { Layout.fillHeight: true } diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index 828ae1780..914f5f9af 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -3,18 +3,27 @@ # 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, 300 or 0 (never) -# lock.sh set keyboard on|off stay unlocked while a Bluetooth or USB keyboard is connected +# 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 # 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}. "applied" is -# the value last written to shell.json's idle.lock, and "override" says that value is the keyboard's 0, not -# the user's choice. lock.json is always saved before shell.json, so after a crash or a failed write the -# keyboard's 0 is never taken for the user's "Never". If idle.lock holds something else than "applied" and +# 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. -# Nothing is written before the user picks something here. The keyboard's 0 is only written while the +# 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. @@ -39,13 +48,13 @@ if [[ -z $watcher ]]; then 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. -markdir=$(mktemp -d); trap 'rm -rf "$markdir"' EXIT; mark=$markdir/written -rc=0 -res=$(LOCK_WRITTEN_MARK=$mark /usr/bin/python3 -I - "$prefs" "$shell" "$defaults" "$sys" "$udev" "$watcher" "$verb" "$key" "$value" <<'PY' +# 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:] +prefs_path, shell_path, defaults_path, sysfs, udev, watcher, verb, key, value = (sys.argv[1:] + ["", ""])[:9] CHOICES = (30, 60, 120, 180, 300, 0) +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) @@ -134,9 +143,10 @@ 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 == 0): + 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")) @@ -161,11 +171,16 @@ else: fail("usage: get|set|apply|restore") override = verb != "restore" and watcher == "1" and prefs["keyboardAwake"] and kb and prefs["lock"] != 0 -want = 0 if override else prefs["lock"] -# 1. lock.json first: if we die before shell.json, the next run knows a 0 there is ours -prefs["applied"], prefs["override"] = want, override -try: save(prefs_path, prefs) -except OSError: fail("cannot save the setting") +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: @@ -179,29 +194,48 @@ if want != current: try: save(shell_path, shell, indent=2) except OSError: fail("cannot write shell.json") written = True - mark = os.environ.get("LOCK_WRITTEN_MARK") - if mark: open(mark, "w").close() -out({"lock": prefs["lock"], "keyboardAwake": prefs["keyboardAwake"], "keyboard": kb, "effective": want}) +# 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=$? -printf '%s\n' "$res" -[[ $rc -eq 0 ]] || exit "$rc" - -# Omarchy's idle service keeps the timeout its idle monitor started with: a new idle.lock only takes -# effect after the shell restarts. Switch idle off and on through its own IPC so the monitor is made -# again with the new value. Only when idle is on and stay-awake is off, so neither is changed. -idle_status() { timeout 5 omarchy-shell idle status 2>/dev/null | tail -n1 || true; } -idle_on() { local st; st=$(idle_status); [[ $st == *'"enabled":true'* && $st == *'"stayAwake":false'* ]]; } -# Only when shell.json really changed: a re-arm restarts the idle countdown, and the keyboard watcher -# calls apply after every input change. -if [[ -e $mark && -z ${OMAMOBILE_LOCK_NO_REARM:-} ]] && command -v omarchy-shell >/dev/null 2>&1 && idle_on; then - timeout 5 omarchy-shell idle disable >/dev/null 2>&1 || true - # Never leave idle off: enable until the status says so. - for _ in 1 2 3; do - timeout 5 omarchy-shell idle enable >/dev/null 2>&1 || true - [[ $(idle_status) == *'"enabled":true'* ]] && exit 0 - sleep 1 - done - echo "lock.sh: could not switch Omarchy's idle back on" >&2 - exit 3 +} +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. +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 d6a0c8cc3..b0d73fac1 100755 --- a/packages/omamobile-settings/install +++ b/packages/omamobile-settings/install @@ -16,9 +16,7 @@ install -Dm755 "$source_dir/libexec/charge-limit" "$dest/usr/lib/omamobile-setti 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 > "Stay unlocked while a keyboard is connected", for every user's graphical session; it does -# nothing until the user picks a lock setting on the page. +# 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" -install -d "$dest/usr/lib/systemd/user/graphical-session.target.wants" -ln -sfn ../omamobile-lock-keyboard.service "$dest/usr/lib/systemd/user/graphical-session.target.wants/omamobile-lock-keyboard.service" diff --git a/packages/omamobile-settings/libexec/omamobile-lock-keyboard b/packages/omamobile-settings/libexec/omamobile-lock-keyboard index 3249a2d31..874b0be9d 100755 --- a/packages/omamobile-settings/libexec/omamobile-lock-keyboard +++ b/packages/omamobile-settings/libexec/omamobile-lock-keyboard @@ -1,18 +1,25 @@ #!/bin/bash # SPDX-License-Identifier: MIT -# Keeps the phone unlocked while a keyboard is connected, when the Display page's toggle says so: -# runs the lock backend's apply at start (so a crash with a keyboard attached can't leave "never" behind) -# and after every input add or remove, once the burst of events a device brings has settled (1 s). -# The backend does nothing until the user has picked a lock setting. If udevadm monitor ends or an apply -# fails, this exits non-zero: the unit restarts it (Restart=always) and its ExecStopPost puts the choice back. +# 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} -apply() { bash "$backend" apply >/dev/null; } -apply || exit 1 +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 || exit 1 + 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 index c0b29e87f..1ef1f5e94 100644 --- a/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service +++ b/packages/omamobile-settings/systemd/user/omamobile-lock-keyboard.service @@ -1,9 +1,10 @@ # SPDX-License-Identifier: MIT -# Settings > Display > "Stay unlocked while a keyboard is connected": follows keyboards coming and going. -# The keyboard's "never lock" is only written while this runs; when it stops for any reason the user's -# chosen timeout is written back (ExecStopPost), and it is always restarted. +# 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: stay unlocked while a keyboard is connected +Description=Omarchy Mobile: lock after 30 minutes while a keyboard is connected PartOf=graphical-session.target After=graphical-session.target diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index b92932ad2..a11064cc8 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -2,11 +2,17 @@ # SPDX-License-Identifier: MIT # backends/lock.sh against a scratch HOME, a fake /sys/class/input and /run/udev/data. set -euo pipefail -export OMAMOBILE_LOCK_NO_REARM=1 # never touch the idle service of the machine running the tests 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\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" @@ -53,18 +59,18 @@ 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): never lock +# 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":0}' -eq "$(idle)" '0 0 omamobile.bar' -# picking a time while it is connected keeps "never" in force, and keeps the choice -eq "$(run set lock 300)" '{"lock":300,"keyboardAwake":true,"keyboard":true,"effective":0}' +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":0}' +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 @@ -85,21 +91,21 @@ echo '{"version":1,"bar":{"id":"omamobile.bar"},"idle":{"screensaver":0,"lock":6 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":0}' +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 0 is never written +# 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":0}' +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 0 is never adopted +# 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":0,"override":true}' > "$prefs" +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":0,"override":true}' > "$prefs" -sed -i 's/"lock": 120/"lock": 0/' "$shell" +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 @@ -156,51 +162,103 @@ 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 failed apply also ends it non-zero, so systemd restarts it -printf '#!/bin/sh\nexit 2\n' > "$tmp/stub.sh" -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 "$rc" 1 -grep -qx 'Restart=always' "$src/systemd/user/omamobile-lock-keyboard.service" -grep -q '^ExecStopPost=.*lock.sh restore$' "$src/systemd/user/omamobile-lock-keyboard.service" -# The idle re-arm: with idle on and stay-awake off a set switches idle off and on; with stay-awake on, -# or for get, it is left alone. A fake omarchy-shell logs its calls. -mkdir -p "$tmp/rearm"; cat > "$tmp/rearm/omarchy-shell" <<'SH' -#!/bin/bash -echo "$*" >> "$REARM_LOG" -[[ $* == "idle status" ]] && cat "$REARM_STATUS" -exit 0 -SH -chmod +x "$tmp/rearm/omarchy-shell" -export REARM_LOG=$tmp/rearm/log REARM_STATUS=$tmp/rearm/status -echo '{"enabled":true,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG" -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 60 >/dev/null -eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status,idle disable,idle enable,idle status," -# the same value again: shell.json unchanged, no re-arm (it would restart the countdown) -: > "$REARM_LOG" -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 60 >/dev/null -eq "$(cat "$REARM_LOG")" "" -# idle switched off by the user: left alone -echo '{"enabled":false,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG" -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 90 >/dev/null || true -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 180 >/dev/null -eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status," -# enable that never takes: retried, then a non-zero exit instead of silence -cat > "$tmp/rearm/omarchy-shell" <<'SH' -#!/bin/bash -echo "$*" >> "$REARM_LOG" -[[ $* == "idle status" ]] && { [[ -e $REARM_LOG.disabled ]] && echo '{"enabled":false,"stayAwake":false}' || cat "$REARM_STATUS"; } -[[ $* == "idle disable" ]] && touch "$REARM_LOG.disabled" -exit 0 -SH -echo '{"enabled":true,"stayAwake":false}' > "$REARM_STATUS"; : > "$REARM_LOG"; rm -f "$REARM_LOG.disabled" -rc=0; PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 300 >/dev/null 2>&1 || rc=$? +# 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 "$(grep -c 'idle enable' "$REARM_LOG")" 3 -echo '{"enabled":true,"stayAwake":true}' > "$REARM_STATUS"; : > "$REARM_LOG" -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" set lock 120 >/dev/null -eq "$(tr '\n' ',' < "$REARM_LOG")" "idle status," -rm -f "$REARM_LOG.disabled" -: > "$REARM_LOG" -PATH="$tmp/rearm:$PATH" OMAMOBILE_LOCK_NO_REARM= bash "$src/backends/lock.sh" get >/dev/null -eq "$(cat "$REARM_LOG")" "" +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 +! grep -q 'idle' "$STUB_LOG" || { echo "FAIL: idle service touched" >&2; exit 1; } echo "lock backend: ok" From d398146e295eb18dd57000087dc1605d1bd68535 Mon Sep 17 00:00:00 2001 From: Lef Date: Wed, 18 Nov 2026 09:39:25 +0200 Subject: [PATCH 10/15] omamobile-settings: let the Display page scroll On the 8 Pro the keyboard toggle's text ran off the bottom of the page and couldn't be reached. The page is now a ScrollView like the About page. --- packages/omamobile-settings/app/DisplayPage.qml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/packages/omamobile-settings/app/DisplayPage.qml b/packages/omamobile-settings/app/DisplayPage.qml index 945d7f0d1..8766e0fa4 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: [] @@ -45,6 +49,9 @@ ColumnLayout { } } 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 @@ -109,5 +116,5 @@ ColumnLayout { + 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 (Never stays never). A Bluetooth keyboard that goes to sleep counts as disconnected.") color: backend.muted; font.pixelSize: SettingsStyle.fontPx(13); wrapMode: Text.Wrap; Layout.fillWidth: true } - Item { Layout.fillHeight: true } + } } From 6830efcf1376e863f4b9c6d1510105f88dcef8ac Mon Sep 17 00:00:00 2001 From: Lef Date: Wed, 18 Nov 2026 18:32:35 +0200 Subject: [PATCH 11/15] omamobile-settings: no Never for the lock time, and the page needs the idle re-arm 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. depends names omamobile-omarchy>=0.1.49 (derekross/omarchy-mobile#879, the number is set at merge): without its re-arm, changing the lock time on a running shell leaves the phone with no idle lock until the shell restarts. --- packages/omamobile-settings/PKGBUILD | 2 +- packages/omamobile-settings/README.md | 10 +++++----- packages/omamobile-settings/app/DisplayPage.qml | 6 +++--- packages/omamobile-settings/backends/lock.sh | 5 +++-- packages/omamobile-settings/test/lock-backend.sh | 4 ++-- packages/omamobile-settings/tests/core_tests.cpp | 2 +- 6 files changed, 15 insertions(+), 14 deletions(-) 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 bcc9ab10a..e2447c608 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -17,17 +17,17 @@ 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, Never) sets `idle.lock` in +"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. Never means the -screen stays on and the phone never sleeps by itself (omamobile-sleepd sleeps -only with the screen off behind a secure lock); the power key still locks. +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; a chosen Never stays never. The user unit +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, and when it diff --git a/packages/omamobile-settings/app/DisplayPage.qml b/packages/omamobile-settings/app/DisplayPage.qml index 8766e0fa4..70a71d10a 100644 --- a/packages/omamobile-settings/app/DisplayPage.qml +++ b/packages/omamobile-settings/app/DisplayPage.qml @@ -24,7 +24,7 @@ ScrollView { 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")}, {s: 0, t: qsTr("Never")}] + {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 @@ -95,7 +95,7 @@ ScrollView { } SettingsLabel { text: page.lockError !== "" ? page.lockError - : page.lockAfter === 0 ? qsTr("Never: the phone stays unlocked and the screen stays on until you press the power key. It also won't go to sleep by itself.") + : 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 } @@ -113,7 +113,7 @@ ScrollView { } 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 (Never stays never). A Bluetooth keyboard that goes to sleep counts as disconnected.") + + 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/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index 914f5f9af..e0229d64d 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -2,7 +2,8 @@ # 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, 300 or 0 (never) +# 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 @@ -53,7 +54,7 @@ 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, 0) +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) diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index a11064cc8..f0ed96ca9 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -49,8 +49,8 @@ eq "$(run apply)" '{"applied":null}' eq "$(run set lock 120)" '{"lock":120,"keyboardAwake":false,"keyboard":false,"effective":120}' eq "$(idle)" '120 0 omamobile.bar' -eq "$(run set lock 0)" '{"lock":0,"keyboardAwake":false,"keyboard":false,"effective":0}' -eq "$(idle)" '0 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"}' diff --git a/packages/omamobile-settings/tests/core_tests.cpp b/packages/omamobile-settings/tests/core_tests.cpp index 8ac58c674..7166e4d35 100644 --- a/packages/omamobile-settings/tests/core_tests.cpp +++ b/packages/omamobile-settings/tests/core_tests.cpp @@ -185,7 +185,7 @@ private slots: QQmlComponent component(&engine, QUrl("qrc:/DisplayPage.qml")); std::unique_ptr page(component.create()); QVERIFY2(page, qPrintable(component.errorString())); - QCOMPARE(page->property("lockChoices").toList().size(), 6); + 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")); From 854e4fb0835bf502a3447ece073655166265f7aa Mon Sep 17 00:00:00 2001 From: Lef Date: Wed, 18 Nov 2026 20:39:23 +0200 Subject: [PATCH 12/15] omamobile-settings 0.1.4: the lock time on top of 0.1.3 --- packages/omamobile-settings/version | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From b0bc74b0c5e15a144f794b621f1c6ee9b01d5d48 Mon Sep 17 00:00:00 2001 From: Lef Date: Thu, 19 Nov 2026 08:17:03 +0200 Subject: [PATCH 13/15] omamobile-settings: opening the Display page enables the keyboard watcher if lock.json says on An older build could leave keyboardAwake on in lock.json with the unit never enabled, so the page showed On while nothing watched keyboards. lock.sh get now enables+starts the unit in that case and disables it when the choice is off but the unit is enabled. Never on a missing or broken lock.json; a systemctl failure comes back as an error in the JSON. --- packages/omamobile-settings/README.md | 3 ++- packages/omamobile-settings/backends/lock.sh | 26 +++++++++++++++++-- .../omamobile-settings/test/lock-backend.sh | 21 +++++++++++++++ 3 files changed, 47 insertions(+), 3 deletions(-) diff --git a/packages/omamobile-settings/README.md b/packages/omamobile-settings/README.md index e2447c608..6bdd29bcb 100644 --- a/packages/omamobile-settings/README.md +++ b/packages/omamobile-settings/README.md @@ -30,7 +30,8 @@ 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, and when it +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 diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index e0229d64d..2a83d71d5 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -8,6 +8,8 @@ # 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 @@ -33,7 +35,8 @@ # 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_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:-} @@ -155,7 +158,9 @@ if prefs is not None: if verb == "get": p = prefs or {"lock": current, "keyboardAwake": False} - out({"lock": p["lock"], "keyboardAwake": p["keyboardAwake"], "keyboard": kb, "effective": current}) + 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": @@ -223,6 +228,23 @@ err() { # the error already in $res, if any, then this one # 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). +if [[ $verb == get ]]; then + unit=$(/usr/bin/python3 -I -c 'import json,sys; d=json.loads(sys.argv[1]); print({True:"on",False:"off"}.get(d.get("unit"),""))' "$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") + enabled=${OMAMOBILE_LOCK_UNIT_ENABLED:-} + if [[ -n $unit && -z $enabled ]]; then + enabled=0; if timeout 2 systemctl --user is-enabled --quiet omamobile-lock-keyboard.service 2>/dev/null; then enabled=1; fi + fi + if [[ $unit == on && $enabled == 0 ]]; then + timeout 5 systemctl --user enable --now omamobile-lock-keyboard.service >/dev/null 2>&1 || + err "could not start the keyboard watcher" + elif [[ $unit == off && $enabled == 1 ]]; then + 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 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 diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index f0ed96ca9..19ec551a8 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -260,5 +260,26 @@ 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 --quiet 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")" "" +# 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" From bc802ed5dfe6113688c2d9ddc9699b10e392b5fd Mon Sep 17 00:00:00 2001 From: Lef Date: Thu, 19 Nov 2026 08:27:59 +0200 Subject: [PATCH 14/15] omamobile-settings: lock.sh get checks the watcher unit under the lock The choice is read again under the same flock as set, so a set landing meanwhile waits and wins. Only enabled/enabled-runtime and disabled from is-enabled count; anything else is reported and nothing is done. --- packages/omamobile-settings/backends/lock.sh | 38 +++++++++++++------ .../omamobile-settings/test/lock-backend.sh | 25 +++++++++++- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/packages/omamobile-settings/backends/lock.sh b/packages/omamobile-settings/backends/lock.sh index 2a83d71d5..e2023d0f9 100755 --- a/packages/omamobile-settings/backends/lock.sh +++ b/packages/omamobile-settings/backends/lock.sh @@ -230,19 +230,35 @@ err() { # the error already in $res, if any, then this one # 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({True:"on",False:"off"}.get(d.get("unit"),""))' "$res") + 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") - enabled=${OMAMOBILE_LOCK_UNIT_ENABLED:-} - if [[ -n $unit && -z $enabled ]]; then - enabled=0; if timeout 2 systemctl --user is-enabled --quiet omamobile-lock-keyboard.service 2>/dev/null; then enabled=1; fi - fi - if [[ $unit == on && $enabled == 0 ]]; then - timeout 5 systemctl --user enable --now omamobile-lock-keyboard.service >/dev/null 2>&1 || - err "could not start the keyboard watcher" - elif [[ $unit == off && $enabled == 1 ]]; then - timeout 5 systemctl --user disable --now --no-block omamobile-lock-keyboard.service >/dev/null 2>&1 || - err "could not stop the keyboard watcher" + 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 diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index 19ec551a8..d19deb355 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -9,7 +9,7 @@ export OMAMOBILE_LOCK_SYSFS=$tmp/sys OMAMOBILE_LOCK_UDEVDATA=$tmp/udev OMAMOBILE # 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\nexit 0\n' "$c" "$c" > "$tmp/stubs/$c" + 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 @@ -266,11 +266,32 @@ echo '{"lock":120,"keyboardAwake":true,"applied":120,"override":false,"reloadPen 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 --quiet omamobile-lock-keyboard.service" +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 >/dev/null & echo $! > "$STUB_LOG.pid"; sleep 1; echo disabled; fi\nexit 0\n' > "$tmp/stubs/systemctl" +: > "$STUB_LOG"; RACE_SRC=$src run get >/dev/null +while kill -0 "$(cat "$STUB_LOG.pid")" 2>/dev/null; do sleep 0.2; done +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"}' From 5db376295c65c1dc322a4708e2c69e97b917de4c Mon Sep 17 00:00:00 2001 From: Lef Date: Thu, 19 Nov 2026 10:07:41 +0200 Subject: [PATCH 15/15] omamobile-settings: lock test waits on a done file, not kill -0 In CI the racing set keyboard off ends up a child of the container's PID 1, which never reaps it, so kill -0 kept seeing the zombie and the loop never ended (the suite was stopped after 1800 s). The racer's group also gets its own stdout, so it can't hold get's command substitution open. --- packages/omamobile-settings/test/lock-backend.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/omamobile-settings/test/lock-backend.sh b/packages/omamobile-settings/test/lock-backend.sh index d19deb355..ec3cbb180 100755 --- a/packages/omamobile-settings/test/lock-backend.sh +++ b/packages/omamobile-settings/test/lock-backend.sh @@ -285,9 +285,11 @@ printf '#!/bin/bash\necho "systemctl $*" >> "$STUB_LOG"\n[[ $2 == is-enabled ]] 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 >/dev/null & echo $! > "$STUB_LOG.pid"; sleep 1; echo disabled; fi\nexit 0\n' > "$tmp/stubs/systemctl" +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 -while kill -0 "$(cat "$STUB_LOG.pid")" 2>/dev/null; do sleep 0.2; done +# 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"