diff --git a/bin/omarchy-debug-idle b/bin/omarchy-debug-idle index 308df73f80eb..48b69306e883 100755 --- a/bin/omarchy-debug-idle +++ b/bin/omarchy-debug-idle @@ -43,6 +43,19 @@ section "Idle inhibitors" hyprctl clients -j 2>/dev/null \ | jq -r '.[] | select(.inhibitingIdle == true or ((.tags // []) | index("noidle"))) | [.pid,.class,.title,((.tags // []) | join(",")),.inhibitingIdle] | @tsv' || true +section "D-Bus idle inhibitors" +if [[ -f $HOME/.local/state/omarchy/idle-inhibitors ]]; then + idle_inhibitors="$(jq -r '.count // 0' "$HOME/.local/state/omarchy/idle-inhibitors" 2>/dev/null)" + if [[ $idle_inhibitors -gt 0 ]]; then + echo "active count: $idle_inhibitors" + jq -r '.inhibitors[]? | " \(.app): \(.reason) (cookie \(.cookie))"' "$HOME/.local/state/omarchy/idle-inhibitors" 2>/dev/null || true + else + echo "none" + fi +else + echo "none" +fi + section "Screensaver detector" if hyprctl clients -j 2>/dev/null | jq -e '.[] | select(.class == "org.omarchy.screensaver" or .initialClass == "org.omarchy.screensaver")' >/dev/null; then echo "running-window" diff --git a/bin/omarchy-idle-inhibit b/bin/omarchy-idle-inhibit new file mode 100755 index 000000000000..a85d24463cfb --- /dev/null +++ b/bin/omarchy-idle-inhibit @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 + +# omarchy:summary=Own the D-Bus idle-inhibit name so apps can suppress the screensaver +# omarchy:group=system +# omarchy:hidden=true + +"""Own org.freedesktop.ScreenSaver on the session bus and track idle inhibitors. + +Quattro replaced hypridle with a Quickshell idle service. hypridle natively owned +the org.freedesktop.ScreenSaver D-Bus name, so apps playing video (Firefox, Chromium, +Zen, VLC) could call Inhibit() to keep the screensaver from firing. That role was +never reimplemented, so D-Bus Inhibit() calls are silently dropped and the +screensaver fires during playback (issue #6475). + +This daemon re-owns that name, counts active Inhibits, and writes the count plus a +detail list to a state file that the Quickshell idle service watches. The service +suppresses idle while any inhibitor is active, exactly as hypridle did. +""" + +import argparse +import json +import os +import signal +import tempfile + +import dbus +import dbus.mainloop.glib +import dbus.service +from gi.repository import GLib +from gi.repository import GLibUnix + +# GLib main loop priority for signal handlers. +_PRIORITY = GLib.PRIORITY_DEFAULT + +STATE_DIR = os.path.expanduser("~/.local/state/omarchy") +STATE_FILE = os.path.join(STATE_DIR, "idle-inhibitors") + +SERVICE_NAME = "org.freedesktop.ScreenSaver" +OBJECT_PATH = "/ScreenSaver" + + +def atomic_write(path, data): + """Write JSON atomically so the watcher never reads a half-written file.""" + os.makedirs(os.path.dirname(path), exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=os.path.dirname(path), prefix=".idle-inhibitors-") + try: + with os.fdopen(fd, "w") as f: + json.dump(data, f, indent=2) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + except BaseException: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +class ScreenSaver(dbus.service.Object): + """Minimal org.freedesktop.ScreenSaver that tracks active inhibitors.""" + + def __init__(self, bus_name, emit): + super().__init__(bus_name, OBJECT_PATH) + self._cookies = {} + self._next_cookie = 1 + self._emit = emit + + def _emit_state(self): + self._emit(len(self._cookies), list(self._cookies.values())) + + @dbus.service.method(SERVICE_NAME, in_signature="ss", out_signature="u", + sender_keyword="sender") + def Inhibit(self, app_name, reason, sender=None): + cookie = self._next_cookie + self._next_cookie += 1 + self._cookies[cookie] = { + "app": app_name, + "reason": reason, + "cookie": cookie, + "owner": sender, + } + self._emit_state() + return cookie + + @dbus.service.method(SERVICE_NAME, in_signature="u", out_signature="") + def UnInhibit(self, cookie): + self._cookies.pop(int(cookie), None) + self._emit_state() + + def release_owner(self, owner): + """Drop every inhibitor registered by a now-disconnected caller. + + Apps can die without calling UnInhibit (a crash, a killed tab, an OOM + kill). If we kept their inhibitors, the screen would stay awake forever, + so we release them as soon as the owning connection leaves the bus. + """ + dead = [cookie for cookie, info in self._cookies.items() + if info.get("owner") == owner] + for cookie in dead: + del self._cookies[cookie] + if dead: + self._emit_state() + + +def parse_args(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "--state-file", + default=STATE_FILE, + help="path to the state file (default: %(default)s)", + ) + return parser.parse_args() + + +def run(state_file): + def emit(count, inhibitors): + atomic_write(state_file, {"count": count, "inhibitors": inhibitors}) + + # Fresh ownership: nothing is inhibited until an app calls Inhibit(). + emit(0, []) + + dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) + bus = dbus.SessionBus() + bus_name = dbus.service.BusName(SERVICE_NAME, bus) + saver = ScreenSaver(bus_name, emit) + + # Apps can die without UnInhibit; release their inhibitors when their + # connection leaves the bus so a crashed browser can't keep the screen + # awake forever. + def on_name_owner_changed(name, _old_owner, new_owner): + if name.startswith(":") and new_owner == "": + saver.release_owner(name) + + bus.add_signal_receiver( + on_name_owner_changed, + dbus_interface="org.freedesktop.DBus", + signal_name="NameOwnerChanged", + path="/org/freedesktop/DBus", + ) + + loop = GLib.MainLoop() + + def shutdown(): + # Releasing the name means no app is inhibited; clear the state file so + # the idle service re-arms immediately rather than waiting for a watcher. + emit(0, []) + loop.quit() + return GLib.SOURCE_REMOVE + + # Handle signals through GLib so they integrate with the main loop instead + # of racing it. Without this, SIGTERM during loop.run() is dropped. + GLibUnix.signal_add(_PRIORITY, signal.SIGTERM, shutdown) + GLibUnix.signal_add(_PRIORITY, signal.SIGINT, shutdown) + + loop.run() + + +if __name__ == "__main__": + run(parse_args().state_file) diff --git a/default/systemd/user/omarchy-idle-inhibit.service b/default/systemd/user/omarchy-idle-inhibit.service new file mode 100644 index 000000000000..30500c53082b --- /dev/null +++ b/default/systemd/user/omarchy-idle-inhibit.service @@ -0,0 +1,20 @@ +[Unit] +Description=Own the D-Bus idle-inhibit name for Omarchy +# The daemon owns org.freedesktop.ScreenSaver on the session bus. Wait until +# UWSM has imported OMARCHY_PATH and WAYLAND_DISPLAY, but keep the default +# target ordering so the daemon starts before graphical-session.target is +# reached. +After=dbus.socket wayland-session-waitenv.service +Requires=dbus.socket +PartOf=graphical-session.target +ConditionEnvironment=OMARCHY_PATH +ConditionEnvironment=WAYLAND_DISPLAY + +[Service] +Type=simple +ExecStart=/usr/bin/omarchy-idle-inhibit +Restart=always +RestartSec=2 + +[Install] +WantedBy=graphical-session.target diff --git a/install/omarchy-base.packages b/install/omarchy-base.packages index 9a1863eceeb1..ff5fb35bfa19 100644 --- a/install/omarchy-base.packages +++ b/install/omarchy-base.packages @@ -102,6 +102,7 @@ plymouth postgresql-libs power-profiles-daemon python-gobject +python-dbus python-poetry-core python-terminaltexteffects qemu-user-static-binfmt diff --git a/install/user/first-run/enable-user-units.sh b/install/user/first-run/enable-user-units.sh index 2af44e881a07..dc8729d61131 100755 --- a/install/user/first-run/enable-user-units.sh +++ b/install/user/first-run/enable-user-units.sh @@ -14,6 +14,7 @@ set -euo pipefail systemctl --user daemon-reload systemctl --user enable --now \ bt-agent.service \ + omarchy-idle-inhibit.service \ omarchy-recover-internal-monitor.service \ omarchy-sleep-lock.service \ omarchy-migrate-notify.service \ diff --git a/migrations/1785963476.sh b/migrations/1785963476.sh new file mode 100644 index 000000000000..1c5c607bebb3 --- /dev/null +++ b/migrations/1785963476.sh @@ -0,0 +1,52 @@ +echo "Enable the D-Bus idle-inhibit daemon so apps can suppress the screensaver" + +# Enable + start the idle-inhibit daemon for existing Quattro users. It owns +# org.freedesktop.ScreenSaver on the session bus so apps playing video can keep +# the screensaver from firing (issue #6475). + +# The daemon imports python-dbus. `omarchy update` runs `pacman -Syu`, which does +# not reconcile install/omarchy-base.packages, so existing users may not have the +# dependency yet; install it before starting the service. +if omarchy-pkg-missing python-dbus; then + omarchy-pkg-add python-dbus +fi + +# The unit is normally installed by the omarchy-settings package to +# /usr/lib/systemd/user. When the package update and this migration do not land +# together (e.g. a local checkout update), link a user copy so systemctl and the +# wants symlink below can find the unit. Symlink, not copy: a copied unit at +# ~/.config/systemd/user would permanently shadow the packaged unit and never +# receive later fixes, while the link tracks the checkout it came from. +user_config_home="${XDG_CONFIG_HOME:-$HOME/.config}" +unit_source="$OMARCHY_PATH/default/systemd/user/omarchy-idle-inhibit.service" +unit_dest="$user_config_home/systemd/user/omarchy-idle-inhibit.service" +unit_target="/usr/lib/systemd/user/omarchy-idle-inhibit.service" + +# Resolve which file systemctl should load: the packaged unit when it exists, +# otherwise the checkout link. Prefer the packaged path so the wants symlink +# keeps tracking package fixes rather than a user-dir copy. +if [[ ! -f $unit_target ]]; then + unit_target="$unit_dest" + if [[ -f $unit_source ]]; then + mkdir -p "$(dirname "$unit_dest")" + ln -sfn "$unit_source" "$unit_dest" + fi +fi + +systemctl --user daemon-reload >/dev/null 2>&1 || true + +# `systemctl enable` needs a live user manager, which an update from a TTY/SSH +# does not have. Fall back to writing exactly the symlink it would have written, +# rather than silently leaving the daemon unenabled and the migration marked +# complete (which would strand the unit at the next graphical login). +if ! systemctl --user enable omarchy-idle-inhibit.service >/dev/null 2>&1; then + wants_dir="$user_config_home/systemd/user/graphical-session.target.wants" + mkdir -p "$wants_dir" + ln -sfn "$unit_target" "$wants_dir/omarchy-idle-inhibit.service" +fi + +# Outside a graphical session there is no shell to feed idle inhibitors to; the +# enablement above is the whole job, and the next graphical login starts it. +if systemctl --user is-active --quiet graphical-session.target; then + systemctl --user start omarchy-idle-inhibit.service >/dev/null 2>&1 || true +fi diff --git a/shell/plugins/services/idle/IdleModel.js b/shell/plugins/services/idle/IdleModel.js index 8e2315d0375a..6c22845e28bf 100644 --- a/shell/plugins/services/idle/IdleModel.js +++ b/shell/plugins/services/idle/IdleModel.js @@ -12,6 +12,34 @@ function eventParts(event, count) { return String(event && event.data ? event.data : "").split(",") } +// The idle-inhibit daemon writes {count, inhibitors} to a state file. Parse the +// file text into a safe count: a missing file, unparseable JSON, or an object +// without a numeric count all mean "no inhibitors" so a daemon failure clears a +// stale nonzero count instead of disabling the lock indefinitely. +function inhibitorCountFromText(text) { + var raw = text !== undefined && text !== null ? String(text) : "" + if (!raw.length) return 0 + + try { + var parsed = JSON.parse(raw) + if (parsed && typeof parsed.count === "number" && parsed.count > 0) { + return Math.floor(parsed.count) + } + } catch (error) { + } + return 0 +} + +// Decide what to do when the observed inhibitor count changes. Returns a string +// the caller switches on: "cancel" (an inhibitor appeared mid-cycle, pull back +// the screensaver/lock), "rearm" (all inhibitors released, idle may resume), or +// "noop" (no transition, keep the current behavior). +function inhibitorTransition(previous, current) { + if (previous === 0 && current > 0) return "cancel" + if (previous > 0 && current === 0) return "rearm" + return "noop" +} + function screensaverWindowsAfter(windows, address, visible) { var key = String(address || "") if (!key) { @@ -47,6 +75,8 @@ if (typeof module !== "undefined") { module.exports = { secondsFromConfig: secondsFromConfig, eventParts: eventParts, - screensaverWindowsAfter: screensaverWindowsAfter + screensaverWindowsAfter: screensaverWindowsAfter, + inhibitorCountFromText: inhibitorCountFromText, + inhibitorTransition: inhibitorTransition } } diff --git a/shell/plugins/services/idle/Service.qml b/shell/plugins/services/idle/Service.qml index 488f29611c34..d562685a5926 100644 --- a/shell/plugins/services/idle/Service.qml +++ b/shell/plugins/services/idle/Service.qml @@ -14,6 +14,8 @@ Item { readonly property string home: Quickshell.env("HOME") readonly property string stayAwakeStateDir: home + "/.local/state/omarchy/indicators" readonly property string stayAwakeStatePath: stayAwakeStateDir + "/stay-awake" + readonly property string inhibitorStateDir: home + "/.local/state/omarchy" + readonly property string inhibitorStatePath: inhibitorStateDir + "/idle-inhibitors" readonly property int defaultScreensaverSeconds: 150 readonly property int defaultLockSeconds: 300 readonly property var idleConfig: shell && shell.shellConfig && shell.shellConfig.idle ? shell.shellConfig.idle : ({}) @@ -22,7 +24,7 @@ Item { readonly property int firstIdleTimeoutSeconds: Math.min(screensaverTimeoutSeconds, lockTimeoutSeconds) readonly property int screensaverDelaySeconds: Math.max(0, screensaverTimeoutSeconds - firstIdleTimeoutSeconds) readonly property int lockDelaySeconds: Math.max(0, lockTimeoutSeconds - firstIdleTimeoutSeconds) - readonly property bool idleEnabled: stayAwakeStateLoaded && !stayAwake + readonly property bool idleEnabled: stayAwakeStateLoaded && !stayAwake && dbusInhibitorCount === 0 readonly property string screensaverClass: "org.omarchy.screensaver" property bool stayAwake: false @@ -35,6 +37,7 @@ Item { property string lastEventAt: "" property var screensaverWindows: ({}) property int screensaverWindowCount: 0 + property int dbusInhibitorCount: 0 function secondsFromConfig(value, fallback) { return IdleModel.secondsFromConfig(value, fallback) @@ -63,6 +66,10 @@ Item { } function launchScreensaver() { + // An inhibitor may have arrived while the screensaver timer was running; never + // blank the screen while a D-Bus inhibitor is active. + if (!root.idleEnabled) return + root.screensaverStartedThisCycle = true screensaverLaunchGraceTimer.restart() runProcess(screensaverProcess, "screensaver", "[[ $(omarchy-shell lock isLocked 2>/dev/null) == \"true\" ]] || omarchy-launch-screensaver") @@ -177,6 +184,37 @@ Item { else handleActiveSignal() } + // Apps that call org.freedesktop.ScreenSaver.Inhibit() (browsers playing video, + // VLC, …) ask us not to blank the screen. The idle-inhibit daemon tracks those + // calls and writes the active count to a state file; we fold that count into + // idleEnabled so any active D-Bus inhibitor suppresses the screensaver and lock. + function handleInhibitorStateChanged(previous) { + switch (IdleModel.inhibitorTransition(previous, root.dbusInhibitorCount)) { + case "cancel": + // An app started inhibiting mid-cycle: pull back the screensaver/lock. + if (root.idledThisCycle) root.cancelIdleCycle("dbus-inhibit") + break + case "rearm": + // All inhibitors released: re-arm idle from the current monitor state. + logEvent("dbus-inhibit", "cleared") + Qt.callLater(root.handleIdleChanged) + break + } + } + + function parseInhibitorState(text) { + var count = IdleModel.inhibitorCountFromText(text) + + if (count !== root.dbusInhibitorCount) { + // Capture the old count before overwriting it so the handler can tell + // whether inhibitors were added or removed. + var previous = root.dbusInhibitorCount + root.dbusInhibitorCount = count + logEvent("dbus-inhibit", "count=" + count) + root.handleInhibitorStateChanged(previous) + } + } + function statusJson() { return JSON.stringify({ enabled: root.idleEnabled, @@ -191,6 +229,7 @@ Item { screensaverDelay: root.screensaverDelaySeconds, lockDelay: root.lockDelaySeconds, screensaverWindows: root.screensaverWindowCount, + dbusInhibitors: root.dbusInhibitorCount, timers: { screensaver: screensaverTimer.running, lock: lockTimer.running, @@ -329,6 +368,36 @@ Item { onFileChanged: root.refreshStayAwakeState() } + // Watch the parent directory, not the file: FileView can't observe a file + // that doesn't exist yet, and the idle-inhibit daemon may create idle-inhibitors + // after the shell has started. When the directory changes, re-probe the file. + Process { + id: inhibitorStateProbe + running: true + // Compact to a single line with jq so the SplitParser sees exactly one JSON + // object regardless of how the daemon formats the file. + command: ["bash", "-c", "jq -c . \"$HOME/.local/state/omarchy/idle-inhibitors\" 2>/dev/null || echo '{}'"] + stdout: SplitParser { onRead: function(line) { root.parseInhibitorState(line) } } + } + + FileView { + path: root.inhibitorStateDir + watchChanges: true + printErrors: false + onFileChanged: inhibitorProbeDebounce.restart() + } + + // The daemon's atomic write creates a temp file and then renames it over the + // state file, so a single update emits two directory events. Debounce them: + // a process already running when the second event arrives would not be + // restarted by setting `running = true` again, leaving the stale count. + Timer { + id: inhibitorProbeDebounce + interval: 50 + repeat: false + onTriggered: inhibitorStateProbe.running = true + } + Component.onCompleted: { logEvent("service-ready") refreshStayAwakeState() @@ -354,7 +423,13 @@ Item { } function toggle(): string { - return root.setIdleEnabled(!root.idleEnabled) + // Toggle the user's stay-awake preference, not the effective idle state. + // idleEnabled is false while a D-Bus inhibitor is active, so deriving from + // it would silently drop a toggle issued during playback: flipping to + // "enable idle" would succeed at nothing, and flipping to "stay awake" + // would clear the flag to enable idle unexpectedly once the inhibitor was + // released. + return root.setIdleEnabled(root.stayAwake) } } } diff --git a/test/shell.d/config-test.sh b/test/shell.d/config-test.sh index 7ee5a8695ad1..61d8e2a5a7ee 100755 --- a/test/shell.d/config-test.sh +++ b/test/shell.d/config-test.sh @@ -135,6 +135,7 @@ package_defaults = [ ("default/applications/mimeapps.list", "/usr/share/applications/mimeapps.list", "mimeapps.list"), ("etc/fastfetch/config.jsonc", "/etc/fastfetch/config.jsonc", "fastfetch/config.jsonc"), ("default/systemd/user/bt-agent.service", "/usr/lib/systemd/user/bt-agent.service", "systemd/user/bt-agent.service"), + ("default/systemd/user/omarchy-idle-inhibit.service", "/usr/lib/systemd/user/omarchy-idle-inhibit.service", "systemd/user/omarchy-idle-inhibit.service"), ("default/systemd/user/omarchy-sleep-lock.service", "/usr/lib/systemd/user/omarchy-sleep-lock.service", "systemd/user/omarchy-sleep-lock.service"), ("default/systemd/user/omarchy-recover-internal-monitor.service", "/usr/lib/systemd/user/omarchy-recover-internal-monitor.service", "systemd/user/omarchy-recover-internal-monitor.service"), ("default/systemd/user/omarchy-migrate-notify.service", "/usr/lib/systemd/user/omarchy-migrate-notify.service", "systemd/user/omarchy-migrate-notify.service"), diff --git a/test/shell.d/idle-inhibit-test.sh b/test/shell.d/idle-inhibit-test.sh new file mode 100755 index 000000000000..4fb808157713 --- /dev/null +++ b/test/shell.d/idle-inhibit-test.sh @@ -0,0 +1,137 @@ +#!/bin/bash + +set -euo pipefail + +source "$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)/base-test.sh" + +test_tmp=$(mktemp -d) +trap 'rm -rf "$test_tmp"' EXIT + +state_file="$test_tmp/.local/state/omarchy/idle-inhibitors" + +# The idle-inhibit daemon writes its state as JSON with a count and a detail list. +# omarchy-debug-idle reads that file and renders the D-Bus inhibitors section. +run_debug_idle() { + HOME="$test_tmp" "$ROOT/bin/omarchy-debug-idle" 2>/dev/null \ + | sed -n '/^== D-Bus idle inhibitors ==$/,/^== .* ==$/p' +} + +# No state file yet: the section reports "none". +[[ ! -f $state_file ]] || fail "no state file should exist yet" +output="$(run_debug_idle)" +[[ $output == *"none"* ]] || fail "missing state file reports none" "$output" +pass "missing state file reports none" + +# Empty inhibitor list: still "none". +mkdir -p "$(dirname "$state_file")" +printf '%s' '{"count":0,"inhibitors":[]}' > "$state_file" +output="$(run_debug_idle)" +[[ $output == *"none"* ]] || fail "empty inhibitor list reports none" "$output" +pass "empty inhibitor list reports none" + +# Active inhibitors: section shows the count and each app/reason. +printf '%s' '{"count":2,"inhibitors":[{"app":"Zen Browser","reason":"Playing video","cookie":1},{"app":"VLC","reason":"Playing audio","cookie":2}]}' > "$state_file" +output="$(run_debug_idle)" +[[ $output == *"active count: 2"* ]] || fail "active count is shown" "$output" +[[ $output == *"Zen Browser: Playing video (cookie 1)"* ]] || fail "first inhibitor is rendered" "$output" +[[ $output == *"VLC: Playing audio (cookie 2)"* ]] || fail "second inhibitor is rendered" "$output" +pass "active inhibitors are rendered with app, reason, and cookie" + +# The daemon binary is syntactically valid and declares its command metadata. +python3 -c "import ast; ast.parse(open('$ROOT/bin/omarchy-idle-inhibit').read())" \ + || fail "idle-inhibit daemon is valid python" +grep -q "omarchy:summary=" "$ROOT/bin/omarchy-idle-inhibit" \ + || fail "idle-inhibit daemon declares a summary" +grep -q "omarchy:hidden=true" "$ROOT/bin/omarchy-idle-inhibit" \ + || fail "idle-inhibit daemon is hidden from listings" +pass "idle-inhibit daemon is valid and declares its metadata" + +# The daemon's primary contract is a D-Bus service: it must own +# org.freedesktop.ScreenSaver, answer Inhibit/UnInhibit, persist the state file, +# and release inhibitors when their caller disconnects. Exercise that over a +# private bus so we don't touch the real session bus. +require_command dbus-run-session +require_command gdbus + +daemon_state="$test_tmp/daemon/idle-inhibitors" +daemon_log="$test_tmp/daemon.log" +mkdir -p "$(dirname "$daemon_state")" + +# A client that Inhibits and holds the connection open until killed. +cat >"$test_tmp/inhibit-hold.py" <"$test_tmp/inhibit-crash.py" </dev/null || true; wait 2>/dev/null || true' EXIT + python3 '$ROOT/bin/omarchy-idle-inhibit' --state-file '$daemon_state' >>'$daemon_log' 2>&1 & + echo \$! >'$test_tmp/daemon.pid' + sleep 1 + $script + sleep 1 + cat '$daemon_state' + " 2>/dev/null | jq -r '.count // 0' +} + +# The daemon starts with zero inhibitors. +[[ $(scenario "true") == "0" ]] || fail "daemon starts with zero inhibitors" +pass "daemon starts with zero inhibitors" + +# A holding client Inhibits; the count is 1 while the connection lives. +hold=$(scenario " + python3 '$test_tmp/inhibit-hold.py' >'$test_tmp/cookie.txt' 2>&1 & + echo \$! >'$test_tmp/hold.pid' + sleep 1 +") +[[ $(cat "$test_tmp/cookie.txt") == "1" ]] || fail "Inhibit returns a cookie" "cookie=$(cat "$test_tmp/cookie.txt")" +[[ $hold == "1" ]] || fail "daemon persists an active inhibitor" "count=$hold" +pass "daemon persists an active inhibitor" + +# UnInhibit clears the inhibitor. +clear=$(scenario " + python3 '$test_tmp/inhibit-hold.py' >'$test_tmp/cookie.txt' 2>&1 & + echo \$! >'$test_tmp/hold.pid' + sleep 1 + gdbus call --session --dest org.freedesktop.ScreenSaver --object-path /ScreenSaver \\ + --method org.freedesktop.ScreenSaver.UnInhibit \$(cat '$test_tmp/cookie.txt') >/dev/null + sleep 1 +") +[[ $clear == "0" ]] || fail "UnInhibit clears the inhibitor" "count=$clear" +pass "UnInhibit clears the inhibitor" + +# A caller that Inhibits then crashes leaves no stale inhibitor behind. +crashed=$(scenario " + python3 '$test_tmp/inhibit-crash.py' >'$test_tmp/cookie.txt' 2>&1 & + echo \$! >'$test_tmp/crash.pid' + sleep 1 + kill -9 \$(cat '$test_tmp/crash.pid') 2>/dev/null + sleep 1 +") +[[ $crashed == "0" ]] || fail "disconnecting caller releases its inhibitor" "count=$crashed" +pass "disconnecting caller releases its inhibitor" diff --git a/test/shell.d/idle-test.sh b/test/shell.d/idle-test.sh index 62a19c2ce03e..41de465d9335 100644 --- a/test/shell.d/idle-test.sh +++ b/test/shell.d/idle-test.sh @@ -33,6 +33,23 @@ assertDeepEqual( { windows: { a: true }, count: 1 }, 'idle leaves screensaver windows unchanged without an address' ) + +// D-Bus inhibitor state parsing. A missing file, unparseable JSON, or an object +// without a numeric count all mean "no inhibitors", so a daemon failure clears a +// stale nonzero count instead of disabling the lock indefinitely. +assertEqual(idle.inhibitorCountFromText('{"count":2,"inhibitors":[]}'), 2, 'inhibitor parses a numeric count') +assertEqual(idle.inhibitorCountFromText('{}'), 0, 'inhibitor treats an empty object as zero') +assertEqual(idle.inhibitorCountFromText(''), 0, 'inhibitor treats missing text as zero') +assertEqual(idle.inhibitorCountFromText('not json'), 0, 'inhibitor treats unparseable text as zero') +assertEqual(idle.inhibitorCountFromText(undefined), 0, 'inhibitor treats undefined as zero') +assertEqual(idle.inhibitorCountFromText('{"count":"2"}'), 0, 'inhibitor ignores a non-numeric count') + +// Transition decisions between observed inhibitor counts. +assertEqual(idle.inhibitorTransition(0, 1), 'cancel', 'a first inhibitor cancels an idle cycle') +assertEqual(idle.inhibitorTransition(2, 0), 'rearm', 'releasing the last inhibitor re-arms idle') +assertEqual(idle.inhibitorTransition(0, 0), 'noop', 'no inhibitor counts mean no transition') +assertEqual(idle.inhibitorTransition(1, 2), 'noop', 'an added inhibitor while others remain is no-op') +assertEqual(idle.inhibitorTransition(2, 1), 'noop', 'a removed inhibitor while others remain is no-op') JS test_tmp=$(mktemp -d)