//! Keeps the screensaver and idle sleep away while music plays. //! //! Two routes, each held independently: org.freedesktop.ScreenSaver, the one //! Chromium and Electron apps use during playback, and the XDG portal's //! Inhibit, which needs no Flatpak permission and covers desktops where the //! first is not served. A route that fails is logged once and otherwise //! ignored. Services normally drop an inhibit when its client leaves the bus, //! so a crash should not leave one behind. use std::collections::HashMap; use std::time::Duration; use anyhow::Result; use tokio::runtime::Handle; use tokio::sync::{oneshot, watch}; use zbus::Connection; use zbus::zvariant::{OwnedObjectPath, Value}; const APP: &str = "remus"; const REASON: &str = "Playing music"; /// The portal's idle and suspend flags. const PORTAL_FLAGS: u32 = 4 | 8; pub struct Inhibitor { want: watch::Sender, done: oneshot::Receiver<()>, rt: Handle, } impl Inhibitor { pub fn spawn(rt: &Handle) -> Inhibitor { let (want, rx) = watch::channel(false); let (done_tx, done) = oneshot::channel(); rt.spawn(async move { run(DBus::default(), rx).await; let _ = done_tx.send(()); }); Inhibitor { want, done, rt: rt.clone(), } } /// Hold the inhibit while `on`, release it otherwise. pub fn set(&self, on: bool) { self.want.send_if_modified(|v| std::mem::replace(v, on) != on); } /// Releases what is held before the runtime goes away. Called from /// outside the runtime, so it may block briefly. pub fn shutdown(self) { let Inhibitor { want, done, rt } = self; drop(want); // The timer needs the runtime, so it is made inside block_on. let _ = rt.block_on(async { tokio::time::timeout(Duration::from_secs(1), done).await }); } } /// One way of inhibiting, so the loop can be tested without a bus. trait Backend { /// Takes every route that is not held yet. async fn acquire(&mut self); /// Gives back every route that is held. async fn release(&mut self); } /// Follows the wanted state until the sender is dropped, then releases. async fn run(mut backend: impl Backend, mut want: watch::Receiver) { while want.changed().await.is_ok() { // Changes that arrive while a call is in flight coalesce into the latest. if *want.borrow_and_update() { backend.acquire().await; } else { backend.release().await; } } backend.release().await; } #[derive(Default)] struct DBus { conn: Option, cookie: Option, request: Option, warned_bus: bool, warned_screensaver: bool, warned_portal: bool, } impl DBus { async fn connection(&mut self) -> Option { if self.conn.is_none() { match Connection::session().await { Ok(c) => self.conn = Some(c), Err(e) => { warn_once( &mut self.warned_bus, format_args!("no session bus, the screensaver stays on: {e}"), ); return None; } } } self.conn.clone() } } impl Backend for DBus { async fn acquire(&mut self) { let Some(conn) = self.connection().await else { return }; if self.cookie.is_none() { match screensaver_inhibit(&conn).await { Ok(c) => { log::debug!("screensaver inhibited (cookie {c})"); self.cookie = Some(c); } Err(e) => warn_once( &mut self.warned_screensaver, format_args!("org.freedesktop.ScreenSaver inhibit failed: {e:#}"), ), } } if self.request.is_none() { match portal_inhibit(&conn).await { Ok(r) => { log::debug!("portal inhibit requested ({})", r.as_str()); self.request = Some(r); } Err(e) => warn_once(&mut self.warned_portal, format_args!("portal inhibit failed: {e:#}")), } } } async fn release(&mut self) { let Some(conn) = self.conn.clone() else { return }; if let Some(c) = self.cookie.take() { let r = conn .call_method( Some("org.freedesktop.ScreenSaver"), "/org/freedesktop/ScreenSaver", Some("org.freedesktop.ScreenSaver"), "UnInhibit", &(c,), ) .await; match r { Ok(_) => log::debug!("screensaver released (cookie {c})"), Err(e) => log::warn!("org.freedesktop.ScreenSaver uninhibit failed: {e}"), } } if let Some(r) = self.request.take() && let Err(e) = conn .call_method( Some("org.freedesktop.portal.Desktop"), r.as_str(), Some("org.freedesktop.portal.Request"), "Close", &(), ) .await { if gone(&e) { // Some portal backends drop the request at once, for example // when they do not implement Inhibit, so there is nothing to close. log::debug!("portal inhibit was not held any more: {e}"); } else { log::warn!("portal inhibit release failed: {e}"); } } } } async fn screensaver_inhibit(conn: &Connection) -> Result { let reply = conn .call_method( Some("org.freedesktop.ScreenSaver"), "/org/freedesktop/ScreenSaver", Some("org.freedesktop.ScreenSaver"), "Inhibit", &(APP, REASON), ) .await?; Ok(reply.body().deserialize::()?) } async fn portal_inhibit(conn: &Connection) -> Result { let options: HashMap<&str, Value<'_>> = HashMap::from([("reason", Value::from(REASON))]); let reply = conn .call_method( Some("org.freedesktop.portal.Desktop"), "/org/freedesktop/portal/desktop", Some("org.freedesktop.portal.Inhibit"), "Inhibit", // No parent window identifier: the inhibit is for the whole app. &("", PORTAL_FLAGS, options), ) .await?; Ok(reply.body().deserialize::()?) } /// The object being called no longer exists. fn gone(e: &zbus::Error) -> bool { const GONE: [&str; 2] = [ "org.freedesktop.DBus.Error.UnknownMethod", "org.freedesktop.DBus.Error.UnknownObject", ]; match e { zbus::Error::MethodError(name, ..) => GONE.contains(&name.as_str()), zbus::Error::FDO(f) => { matches!( **f, zbus::fdo::Error::UnknownMethod(_) | zbus::fdo::Error::UnknownObject(_) ) } _ => false, } } fn warn_once(warned: &mut bool, msg: std::fmt::Arguments<'_>) { if std::mem::replace(warned, true) { log::debug!("{msg}"); } else { log::warn!("{msg}"); } } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use super::*; #[derive(Clone, Default)] struct Fake { calls: Arc>>, held: Arc>, } impl Backend for Fake { async fn acquire(&mut self) { self.calls.lock().unwrap().push("acquire"); *self.held.lock().unwrap() = true; } async fn release(&mut self) { self.calls.lock().unwrap().push("release"); *self.held.lock().unwrap() = false; } } /// Sends each state and lets the loop act on it before the next. async fn drive(states: &[bool]) -> Fake { let fake = Fake::default(); let (tx, rx) = watch::channel(false); let task = tokio::spawn(run(fake.clone(), rx)); for &s in states { tx.send_if_modified(|v| std::mem::replace(v, s) != s); tokio::task::yield_now().await; } drop(tx); task.await.unwrap(); fake } #[tokio::test] async fn follows_play_and_pause() { let fake = drive(&[true, false, true]).await; assert_eq!( *fake.calls.lock().unwrap(), ["acquire", "release", "acquire", "release"] ); } #[tokio::test] async fn repeated_state_does_not_call_again() { let fake = drive(&[true, true, true]).await; assert_eq!(*fake.calls.lock().unwrap(), ["acquire", "release"]); } #[tokio::test] async fn releases_when_dropped_while_held() { let fake = drive(&[true]).await; assert!(!*fake.held.lock().unwrap()); } #[tokio::test] async fn nothing_held_when_never_played() { let fake = drive(&[false]).await; assert_eq!(*fake.calls.lock().unwrap(), ["release"]); assert!(!*fake.held.lock().unwrap()); } /// Against the real session bus: `cargo test live_inhibit -- --ignored`. /// Prints which routes this session serves rather than failing on a /// missing one, since a desktop may serve only one of them. #[tokio::test] #[ignore] async fn live_inhibit() { let conn = Connection::session().await.expect("session bus"); let ss = screensaver_inhibit(&conn).await; let portal = portal_inhibit(&conn).await; println!("org.freedesktop.ScreenSaver: {ss:?}"); println!("portal: {portal:?}"); assert!(ss.is_ok() || portal.is_ok(), "neither route is served"); let mut bus = DBus { conn: Some(conn), cookie: ss.ok(), request: portal.ok(), ..DBus::default() }; bus.release().await; assert!(bus.cookie.is_none() && bus.request.is_none()); } }