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.
This commit is contained in:
LGUG2Z committed 2026-10-28 22:50:40 -07:00
1 parent caab37e4aa
commit f191fa9806
5 files changed
+195 -6

No files matched your search

Generated
+1
View File
@@ -2180,6 +2180,7 @@ dependencies = [
"wayland-protocols",
"wayland-protocols-plasma",
"windows 0.62.2",
"zbus",
]
[[package]]
+1
View File
@@ -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"
+6 -6
View File
@@ -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.
@@ -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<PowerEvent>,
}
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<PowerEvent> {
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<PowerEvent>,
) -> 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::<bool>() 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<Option<Watcher>> {
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());
}
}
}
@@ -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<bool> {
static BUS: OnceLock<Option<Connection>> = 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::<bool>()
.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();
}
}