diff --git a/CHANGELOG.md b/CHANGELOG.md index a1e2b9d..3e2225a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ One section per version, newest first. +## v0.5.0 (2026-11-04) + +### Features + +- While music plays, remus asks the system to keep the screensaver and sleep away, and lets go when playback is paused or stopped, or remus quits. + ## v0.4.0 (2026-11-04) ### Features diff --git a/Cargo.lock b/Cargo.lock index 16b3b3c..df9e29e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4385,7 +4385,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "remus" -version = "0.4.0" +version = "0.5.0" dependencies = [ "anyhow", "directories", @@ -4404,6 +4404,7 @@ dependencies = [ "slint-build", "tokio", "toml", + "zbus", ] [[package]] @@ -5407,8 +5408,10 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.61.2", ] @@ -6727,6 +6730,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_repr", + "tokio", "tracing", "uds_windows", "uuid", diff --git a/Cargo.toml b/Cargo.toml index 236793d..1b547ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "remus" -version = "0.4.0" +version = "0.5.0" edition = "2024" license = "MIT" @@ -21,6 +21,7 @@ serde_json = "1.0.154" slint = "1.18.1" tokio = { version = "1.54.1", features = ["rt-multi-thread", "sync", "macros", "time"] } toml = "1.1.8" +zbus = { version = "5.19.0", default-features = false, features = ["tokio"] } [build-dependencies] slint-build = "1.18.1" diff --git a/flatpak/me.anshorei.Fettleshed.Remus.metainfo.xml b/flatpak/me.anshorei.Fettleshed.Remus.metainfo.xml index bd4054f..e28e8a6 100644 --- a/flatpak/me.anshorei.Fettleshed.Remus.metainfo.xml +++ b/flatpak/me.anshorei.Fettleshed.Remus.metainfo.xml @@ -20,6 +20,7 @@ + diff --git a/flatpak/me.anshorei.Fettleshed.Remus.yml b/flatpak/me.anshorei.Fettleshed.Remus.yml index 478372b..493fb53 100644 --- a/flatpak/me.anshorei.Fettleshed.Remus.yml +++ b/flatpak/me.anshorei.Fettleshed.Remus.yml @@ -15,6 +15,9 @@ finish-args: # GPU rendering and gamepads (evdev). --device=input would be narrower but # needs Flatpak 1.15.6, which not every SteamOS release ships. - --device=all + # Keeps the screensaver off while music plays, the way Chromium and + # Electron apps do. The XDG portal route needs no permission. + - --talk-name=org.freedesktop.ScreenSaver build-options: append-path: /usr/lib/sdk/rust-stable/bin diff --git a/src/app.rs b/src/app.rs index 9168aab..74c936e 100644 --- a/src/app.rs +++ b/src/app.rs @@ -17,6 +17,7 @@ use tokio::runtime::Handle; use tokio::sync::Semaphore; use crate::config::{self, Config, Settings}; +use crate::inhibit::Inhibitor; use crate::palette::{Lab, Palette, Role, Tone}; use crate::player::{Player, PlayerEvent}; use crate::prompts::{self, Control, Family, Prompts}; @@ -64,6 +65,9 @@ pub fn shutdown() { let app = APP.with(|cell| cell.borrow_mut().take()); if let Some(mut app) = app { app.save_queue(); + if let Some(i) = app.inhibitor.take() { + i.shutdown(); + } } } @@ -206,6 +210,8 @@ pub struct App { rt: Handle, client: Option, player: Option, + /// Keeps the screensaver off while music plays. Taken at shutdown. + inhibitor: Option, screen: Screen, area: Area, section: usize, @@ -257,11 +263,13 @@ impl App { { log::warn!("cover cache disabled, cannot create {}: {e}", d.display()); } + let inhibitor = Inhibitor::spawn(&rt); App { ui, rt, client: None, player: None, + inhibitor: Some(inhibitor), screen: Screen::Login, area: Area::Content, section: 0, @@ -1644,6 +1652,15 @@ impl App { self.save_queue(); } } + self.sync_inhibit(); + } + + /// Inhibits only while sound is coming out: a restored queue is loaded + /// paused and held until play is pressed. + fn sync_inhibit(&self) { + if let Some(i) = &self.inhibitor { + i.set(self.current.is_some() && !self.paused && !self.held); + } } fn send_now_playing(&self) { diff --git a/src/inhibit.rs b/src/inhibit.rs new file mode 100644 index 0000000..24bb80a --- /dev/null +++ b/src/inhibit.rs @@ -0,0 +1,316 @@ +//! 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()); + } +} diff --git a/src/main.rs b/src/main.rs index 99f21dc..d31eac0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,7 @@ slint::include_modules!(); mod app; mod config; mod devscript; +mod inhibit; mod input; mod palette; mod player;