From f191fa98065548b6f8a031a9381ad57cc8cc102a Mon Sep 17 00:00:00 2001 From: LGUG2Z Date: Wed, 28 Oct 2026 20:00:00 -0700 Subject: [PATCH] feat(linux): hear sleep, wake and the lock from D-Bus, and read whether the session is locked logind's PrepareForSleep on the system bus, and the screen saver's ActiveChanged on the session bus, which komorebi for KDE listens to as well; GetActive says whether the screen is locked. --- Cargo.lock | 1 + komorebi-recorder/Cargo.toml | 1 + komorebi-recorder/src/platform/linux/mod.rs | 12 +- komorebi-recorder/src/platform/linux/power.rs | 142 ++++++++++++++++++ .../src/platform/linux/session.rs | 45 ++++++ 5 files changed, 195 insertions(+), 6 deletions(-) create mode 100644 komorebi-recorder/src/platform/linux/power.rs create mode 100644 komorebi-recorder/src/platform/linux/session.rs diff --git a/Cargo.lock b/Cargo.lock index ba3e9862..8e55378e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2180,6 +2180,7 @@ dependencies = [ "wayland-protocols", "wayland-protocols-plasma", "windows 0.62.2", + "zbus", ] [[package]] diff --git a/komorebi-recorder/Cargo.toml b/komorebi-recorder/Cargo.toml index 37687875..ebc24ea4 100644 --- a/komorebi-recorder/Cargo.toml +++ b/komorebi-recorder/Cargo.toml @@ -152,6 +152,7 @@ gstreamer-video = "0.25.4" wayland-client = "0.31.15" wayland-protocols = { version = "0.32.13", features = ["client", "unstable"] } wayland-protocols-plasma = { version = "0.3.12", features = ["client"] } +zbus = "5" [build-dependencies] embed-resource = "3" diff --git a/komorebi-recorder/src/platform/linux/mod.rs b/komorebi-recorder/src/platform/linux/mod.rs index 56d0b2a9..29bf7d20 100644 --- a/komorebi-recorder/src/platform/linux/mod.rs +++ b/komorebi-recorder/src/platform/linux/mod.rs @@ -1,24 +1,24 @@ //! Linux, as KDE Plasma: the host that records komorebi for KDE. //! -//! The master clock, the child processes, the shell and the screen capture are Linux's own. The -//! rest of the host (`apps`, `power`, `session`, `trace`) is still the `unsupported` host's, and is -//! replaced one module at a time as each is written (see `docs/PLATFORM.md`). +//! The master clock, the child processes, the shell, the screen capture, power, the session lock +//! and the window list are Linux's own. The OS trace is still the `unsupported` host's, and is +//! replaced when it is written (see `docs/PLATFORM.md`). // the pieces of the fallback that Linux has its own version of are not used #[allow(dead_code)] #[path = "../unsupported.rs"] mod fallback; +pub mod apps; pub mod capture; pub mod clock; +pub mod power; pub mod process; mod screencast; +pub mod session; pub mod shell; pub mod wayland; -pub use fallback::apps; -pub use fallback::power; -pub use fallback::session; pub use fallback::trace; /// Nothing to do first. diff --git a/komorebi-recorder/src/platform/linux/power.rs b/komorebi-recorder/src/platform/linux/power.rs new file mode 100644 index 00000000..99c3405b --- /dev/null +++ b/komorebi-recorder/src/platform/linux/power.rs @@ -0,0 +1,142 @@ +//! Hearing about sleep, wake and the session lock from D-Bus as they happen. +//! +//! logind announces that the machine is about to sleep, and that it woke, with +//! `PrepareForSleep` on the system bus, and the screen saver says that the session was locked or +//! unlocked with `ActiveChanged` on the session bus (KDE answers on `org.freedesktop.ScreenSaver`, +//! which komorebi for KDE listens to as well). A thread for each reads its signals, stamps each +//! with a clock anchor on arrival and hands it to the recording loop over a channel, which drains +//! it with [`Watcher::drain`]. +//! +//! | D-Bus says | becomes | +//! |---|---| +//! | `PrepareForSleep(true)` | `Suspend` | +//! | `PrepareForSleep(false)` | `Resume` | +//! | `ActiveChanged(true)` | `SessionLocked` | +//! | `ActiveChanged(false)` | `SessionUnlocked` | +//! +//! The lid and the displays' power are not read: the displays are polled, as on a Mac. A bus that +//! cannot be reached (no session bus in a bare shell) is left out, and the other is still heard. +//! The threads end when the next signal finds the watcher gone. + +use crate::clock::Anchor; +use crate::power::PowerEvent; +use crate::power::PowerKind; +use color_eyre::eyre; +use crossbeam_channel::Receiver; +use crossbeam_channel::Sender; +use zbus::blocking::Connection; +use zbus::blocking::Proxy; + +/// Listens for power events until dropped, and holds what it heard until it is drained. +pub struct Watcher { + events: Receiver, +} + +impl Watcher { + /// Returns what has been heard since the last call, oldest first. Each [`PowerEvent`] carries + /// the clock [`Anchor`] sampled when the signal arrived. + #[must_use] + pub fn drain(&self) -> Vec { + self.events.try_iter().collect() + } +} + +/// Reads the boolean argument of each signal `name` that `interface` sends at `path`, and sends +/// the [`PowerKind`] that `kind` makes of it, until the receiver is gone. +fn listen( + connection: Connection, + destination: &'static str, + path: &'static str, + interface: &'static str, + name: &'static str, + kind: fn(bool) -> PowerKind, + events: Sender, +) -> eyre::Result<()> { + let proxy = Proxy::new(&connection, destination, path, interface)?; + let signals = proxy.receive_signal(name)?; + std::thread::Builder::new() + .name(format!("komorebi-recorder-{name}")) + .spawn(move || { + // keeps the bus connection for as long as the signals are read + let _connection = connection; + for signal in signals { + let Ok(argument) = signal.body().deserialize::() else { + continue; + }; + let event = PowerEvent { + kind: kind(argument), + anchor: Anchor::sample(), + }; + if events.send(event).is_err() { + return; + } + } + })?; + Ok(()) +} + +/// Starts listening, and returns the watcher. +/// +/// # Errors +/// +/// Never fails: a bus that cannot be reached, or a service that is not there, means no events +/// of that kind. The result is `None` only if neither could be listened to. +pub fn start() -> eyre::Result> { + let (tx, rx) = crossbeam_channel::unbounded(); + let mut listening = 0; + + if let Ok(system) = Connection::system() + && listen( + system, + "org.freedesktop.login1", + "/org/freedesktop/login1", + "org.freedesktop.login1.Manager", + "PrepareForSleep", + |sleeping| { + if sleeping { + PowerKind::Suspend + } else { + PowerKind::Resume + } + }, + tx.clone(), + ) + .is_ok() + { + listening += 1; + } + + if let Ok(session) = Connection::session() + && listen( + session, + "org.freedesktop.ScreenSaver", + "/org/freedesktop/ScreenSaver", + "org.freedesktop.ScreenSaver", + "ActiveChanged", + |locked| { + if locked { + PowerKind::SessionLocked + } else { + PowerKind::SessionUnlocked + } + }, + tx, + ) + .is_ok() + { + listening += 1; + } + + Ok((listening > 0).then_some(Watcher { events: rx })) +} + +#[cfg(test)] +mod tests { + #[test] + fn a_watcher_starts_with_or_without_buses_and_has_heard_nothing() { + let watcher = super::start().expect("start never fails"); + if let Some(watcher) = watcher { + assert!(watcher.drain().is_empty()); + } + } +} diff --git a/komorebi-recorder/src/platform/linux/session.rs b/komorebi-recorder/src/platform/linux/session.rs new file mode 100644 index 00000000..a886ad33 --- /dev/null +++ b/komorebi-recorder/src/platform/linux/session.rs @@ -0,0 +1,45 @@ +//! Whether the session is locked, from the screen saver on the session bus. +//! +//! KDE's screen locker answers `org.freedesktop.ScreenSaver.GetActive`: `true` while the lock +//! screen is up. The connection to the bus is made once. A session with no bus, or no screen +//! saver, is read as unlocked: that is also what [`SessionState::default`] is, and the recorder +//! then finds a lock the other way, by a stream that stops. + +use crate::system_state::SessionState; +use std::sync::OnceLock; +use zbus::blocking::Connection; + +fn locked() -> Option { + static BUS: OnceLock> = OnceLock::new(); + let bus = BUS.get_or_init(|| Connection::session().ok()).as_ref()?; + bus.call_method( + Some("org.freedesktop.ScreenSaver"), + "/org/freedesktop/ScreenSaver", + Some("org.freedesktop.ScreenSaver"), + "GetActive", + &(), + ) + .ok()? + .body() + .deserialize::() + .ok() +} + +/// Returns the current session state: locked as the screen saver says, and on the console (this +/// host does not tell otherwise). +#[must_use] +pub fn read() -> SessionState { + SessionState { + locked: locked().unwrap_or(false), + on_console: true, + } +} + +#[cfg(test)] +mod tests { + #[test] + fn reading_the_session_never_fails_with_or_without_a_bus() { + // the answer is the machine's, and not asserted: only that one is given + let _ = super::read(); + } +}