aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-11-11 10:10:53 +0100
committerDanilo M. <danix@danix.xyz>2026-11-11 10:10:53 +0100
commited5ff682efbefd3e90d21ea618473af2844b774d (patch)
tree9a25fca9e3aac26792c8eee40f33bf6b843d9cdb
parent6a9a1ae47e758afb9a747a619b5665cb5908834a (diff)
downloaddeck-it-ed5ff682efbefd3e90d21ea618473af2844b774d.tar.gz
deck-it-ed5ff682efbefd3e90d21ea618473af2844b774d.zip
feat(sleep): tell the tablet when the PC shuts down or reboots
The delay inhibitor now covers shutdown too, and dbus-monitor also watches PrepareForShutdown. X-Deckit-Sleep carries the reason ("asleep" or "shutting down") and the page shows "The PC is <reason>", dropping the wake lock as on suspend. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-rw-r--r--AGENTS.md8
-rw-r--r--deckit/server.py4
-rw-r--r--deckit/sleep.py38
-rw-r--r--static/app.js3
-rw-r--r--tests/test_server.py6
-rw-r--r--tests/test_sleep.py39
6 files changed, 63 insertions, 35 deletions
diff --git a/AGENTS.md b/AGENTS.md
index 0998ff4..dd0447a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -80,10 +80,10 @@ Keep the server dependency-free apart from that one package.
(vendored `marked`, HTML escaped, images never fetched).
- The page holds a Screen Wake Lock while visible, so the tablet never sleeps
over the dashboard; nothing on the tablet's settings is changed.
- Before a suspend `deckit/sleep.py` (an elogind delay inhibitor plus
- `dbus-monitor` on PrepareForSleep) marks answers with `X-Deckit-Sleep` for
- 2s, and `app.js` covers the page with "The PC is asleep" and drops the
- lock, so the tablet sleeps too; 15s with no answer at all gives the same
+ Before a suspend, poweroff or reboot `deckit/sleep.py` (an elogind delay
+ inhibitor plus `dbus-monitor` on PrepareForSleep/PrepareForShutdown) marks
+ answers with `X-Deckit-Sleep: asleep|shutting down` for 2s, and `app.js`
+ covers the page with "The PC is <that>" and drops the lock, so the tablet sleeps too; 15s with no answer at all gives the same
overlay as "The PC is not answering". The first plain answer takes both back.
- The Windows tab's previews are `grim -T <stableId>` (Hyprland's stableId is
the ext-foreign-toplevel identifier), served at `/api/windows/image/<id>`
diff --git a/deckit/server.py b/deckit/server.py
index 9246e54..f222ecb 100644
--- a/deckit/server.py
+++ b/deckit/server.py
@@ -171,8 +171,8 @@ class Handler(BaseHTTPRequestHandler):
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "max-age=86400" if cache else "no-store")
- if sleep.sleeping.is_set():
- self.send_header("X-Deckit-Sleep", "1") # the tablet shows "asleep" at once
+ if sleep.why:
+ self.send_header("X-Deckit-Sleep", sleep.why) # the tablet shows it at once
self.end_headers()
self.wfile.write(body)
diff --git a/deckit/sleep.py b/deckit/sleep.py
index 69b5a05..06cb481 100644
--- a/deckit/sleep.py
+++ b/deckit/sleep.py
@@ -14,25 +14,25 @@
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
-"""Tells the tablet the PC is about to sleep.
+"""Tells the tablet the PC is about to sleep, shut down or reboot.
-elogind announces a suspend with PrepareForSleep on the system bus, and
-waits for it only while someone holds a delay inhibitor (at most
-InhibitDelayMaxSec, 5 s by default). deck-it holds one; on the announcement
-the server marks every answer for SHOW seconds, so the tablet's next poll
-sees it, then lets the inhibitor go and the PC sleeps. On resume it takes
-the inhibitor again.
+elogind announces a suspend with PrepareForSleep and a poweroff or reboot
+with PrepareForShutdown on the system bus, and waits for either only while
+someone holds a delay inhibitor (at most InhibitDelayMaxSec, 5 s by
+default). deck-it holds one; on the announcement the server marks every
+answer for SHOW seconds, so the tablet's next poll sees it, then lets the
+inhibitor go. On resume, or a shutdown called off, it takes it again.
"""
import ctypes
import os
import signal
import subprocess
-import threading
import time
SHOW = 2.0 # the tablet polls every second (0.5 s on the assistant tab)
-sleeping = threading.Event()
+WHY = {"PrepareForSleep": "asleep", "PrepareForShutdown": "shutting down"}
+why = "" # the server sends it to the tablet while set: "The PC is <why>"
def _die_with_parent():
@@ -46,8 +46,8 @@ def _inhibit():
# lock delaying every suspend; its own session, so letting go on purpose
# kills the tail too.
return subprocess.Popen(
- ["elogind-inhibit", "--what=sleep", "--mode=delay", "--who=deck-it",
- "--why=Tell the tablet the PC is going to sleep",
+ ["elogind-inhibit", "--what=sleep:shutdown", "--mode=delay", "--who=deck-it",
+ "--why=Tell the tablet the PC is going to sleep or off",
"tail", f"--pid={os.getpid()}", "-f", "/dev/null"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
@@ -62,21 +62,25 @@ def _release(p):
def watch():
"""Runs for the server's life; without elogind or dbus-monitor it does nothing."""
+ global why
+ rule = "type='signal',interface='org.freedesktop.login1.Manager',member='{}'"
try:
mon = subprocess.Popen(
- ["dbus-monitor", "--system",
- "type='signal',interface='org.freedesktop.login1.Manager',member='PrepareForSleep'"],
+ ["dbus-monitor", "--system", *(rule.format(m) for m in WHY)],
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True,
preexec_fn=_die_with_parent)
lock = _inhibit()
except OSError:
return
+ member = ""
for line in mon.stdout:
line = line.strip()
- if line == "boolean true":
- sleeping.set()
+ if line.startswith("signal "):
+ member = next((m for m in WHY if f"member={m}" in line), "")
+ elif line == "boolean true" and member:
+ why = WHY[member]
time.sleep(SHOW)
_release(lock)
- elif line == "boolean false":
- sleeping.clear()
+ elif line == "boolean false" and member:
+ why = ""
lock = _inhibit()
diff --git a/static/app.js b/static/app.js
index c91876b..3e75a4b 100644
--- a/static/app.js
+++ b/static/app.js
@@ -113,7 +113,8 @@ function poll(name, seconds, update) {
const tick = async () => {
try {
const r = await fetch(`/api/${name}`);
- if (r.headers.get("X-Deckit-Sleep")) return goodnight("The PC is asleep");
+ const why = r.headers.get("X-Deckit-Sleep");
+ if (why) return goodnight(`The PC is ${why}`);
awake();
if (r.ok) update(await r.json());
} catch {
diff --git a/tests/test_server.py b/tests/test_server.py
index 4755a03..522b781 100644
--- a/tests/test_server.py
+++ b/tests/test_server.py
@@ -93,15 +93,15 @@ class Server(unittest.TestCase):
def test_answers_say_the_pc_is_going_to_sleep(self):
conn = UnixConnection(self.sock)
- srv.sleep.sleeping.set()
+ srv.sleep.why = "asleep"
try:
conn.request("GET", "/api/demo", headers=HOST)
r = conn.getresponse()
r.read()
finally:
- srv.sleep.sleeping.clear()
+ srv.sleep.why = ""
conn.close()
- self.assertEqual(r.getheader("X-Deckit-Sleep"), "1")
+ self.assertEqual(r.getheader("X-Deckit-Sleep"), "asleep")
def test_background_follows_the_config(self):
from unittest import mock
diff --git a/tests/test_sleep.py b/tests/test_sleep.py
index 99e819c..ced176d 100644
--- a/tests/test_sleep.py
+++ b/tests/test_sleep.py
@@ -40,15 +40,17 @@ def until(fn, secs=3):
return False
+SIG = "signal time=1 sender=:1.2 -> destination=(null destination) serial=9 path=/org/freedesktop/login1; interface=org.freedesktop.login1.Manager; member="
+
+
class Watch(unittest.TestCase):
- def test_flags_then_releases_and_takes_the_lock_again(self):
+ def watch(self, script):
bin_ = tempfile.mkdtemp(dir="/tmp")
self.addCleanup(shutil.rmtree, bin_)
log = Path(bin_) / "log"
- # A suspend announced at 0.3 s, the resume at 1.2 s.
for name, body in {
- "dbus-monitor": "sleep 0.3; echo ' boolean true'; sleep 0.9; echo ' boolean false'; sleep 1",
- "elogind-inhibit": f"echo take >> {log}; exec sleep 100",
+ "dbus-monitor": script,
+ "elogind-inhibit": f"echo \"$1\" >> {log}; exec sleep 100",
}.items():
p = Path(bin_) / name
p.write_text("#!/bin/sh\n" + body + "\n")
@@ -57,18 +59,39 @@ class Watch(unittest.TestCase):
os.environ["PATH"] = bin_ + ":" + path
self.addCleanup(os.environ.__setitem__, "PATH", path)
sleep.SHOW = 0.2
+ sleep.why = ""
taken = []
real = sleep._inhibit
sleep._inhibit = lambda: taken.append(real()) or taken[-1]
self.addCleanup(setattr, sleep, "_inhibit", real)
self.addCleanup(lambda: [subprocess.run(["pkill", "-g", str(p.pid)]) for p in taken])
threading.Thread(target=sleep.watch, daemon=True).start()
+ return taken, log
+
+ def announce(self, member, at, back):
+ # member announced (true) at `at` s, taken back (false) `back` s later
+ return (f"sleep {at}; echo '{SIG}{member}'; echo ' boolean true'; "
+ f"sleep {back}; echo '{SIG}{member}'; echo ' boolean false'; sleep 1")
- self.assertTrue(until(sleep.sleeping.is_set))
- self.assertTrue(until(lambda: taken[0].poll() is not None)) # let go: the PC may sleep
- self.assertTrue(until(lambda: not sleep.sleeping.is_set()))
+ def check(self, member, why):
+ taken, log = self.watch(self.announce(member, 0.3, 0.9))
+ self.assertTrue(until(lambda: sleep.why == why))
+ self.assertTrue(until(lambda: taken[0].poll() is not None)) # let go: the PC may go
+ self.assertTrue(until(lambda: sleep.why == ""))
self.assertTrue(until(lambda: len(taken) == 2 and taken[1].poll() is None))
- self.assertTrue(until(lambda: log.read_text().split() == ["take", "take"]))
+ self.assertTrue(until(lambda: log.read_text().split() == ["--what=sleep:shutdown"] * 2))
+
+ def test_suspend_flags_then_releases_and_takes_the_lock_again(self):
+ self.check("PrepareForSleep", "asleep")
+
+ def test_shutdown_flags_then_releases(self):
+ self.check("PrepareForShutdown", "shutting down")
+
+ def test_other_signals_are_ignored(self):
+ taken, _ = self.watch(f"echo '{SIG}SessionNew'; echo ' boolean true'; sleep 1")
+ time.sleep(0.4)
+ self.assertEqual(sleep.why, "")
+ self.assertIsNone(taken[0].poll())
if __name__ == "__main__":