From 78954b90dc67c7d54277435c192706a500e68462 Mon Sep 17 00:00:00 2001 From: Guillaume ASSIER Date: Fri, 30 Oct 2026 20:39:17 +0100 Subject: [PATCH] =?UTF-8?q?feat(windows):=20compilation=20crois=C3=A9e=20d?= =?UTF-8?q?epuis=20Linux,=20l'h=C3=B4te=20tourne=20sous=20Wine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le shell Nix `.#windows` (#93) fournit un rustc pour la cible x86_64-pc-windows-gnu (en cache dans nixpkgs), mingw-w64 et une libvpx 1.13 statique construite par nix/libvpx.nix, dont la variante Linux garde son empreinte. aws-lc demande les en-têtes de winpthreads, que le shell ajoute. rs-platform se compile pour Windows: - le portail et zbus ne sont plus que sous Linux; ailleurs, le même API répond `Unsupported`, traduit côté coque (`portal_unsupported`); - la veille a un sous-module par système. Sous Windows, une requête d'alimentation (système et écran requis) empêche la veille, et la notification de suspension et de reprise remplace PrepareForSleep. Les réglages vont dans %APPDATA%\rustscreen, le journal dans %LOCALAPPDATA%\rustscreen\logs. Vérifié sous Wine: `rustscreen-cli.exe --synthetic` prend le verrou de veille, sert la mire et Chromium la reçoit (ICE, DTLS, première image en 170 ms). Les tests du workspace passent sous Wine, sauf la résolution mDNS de rustscreen.local, à vérifier sur un vrai Windows (#94). La CI compile et passe clippy pour Windows quand Nix est présent. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/ci.yml | 14 + AGENTS.md | 16 + Cargo.lock | 1 + apps/desktop/src-tauri/Cargo.lock | 11 +- crates/rs-diag/src/log.rs | 26 +- crates/rs-platform/Cargo.toml | 17 + crates/rs-platform/src/portal.rs | 536 +------------------ crates/rs-platform/src/portal/dbus.rs | 529 ++++++++++++++++++ crates/rs-platform/src/portal/unsupported.rs | 63 +++ crates/rs-platform/src/sleep.rs | 362 +------------ crates/rs-platform/src/sleep/linux.rs | 348 ++++++++++++ crates/rs-platform/src/sleep/windows.rs | 230 ++++++++ crates/rs-session/src/bin/rustscreen-cli.rs | 6 +- crates/rs-session/src/capture.rs | 1 + crates/rs-store/src/lib.rs | 29 +- flake.nix | 43 ++ locales/en.json | 1 + locales/fr.json | 1 + nix/libvpx.nix | 17 +- 19 files changed, 1367 insertions(+), 884 deletions(-) create mode 100644 crates/rs-platform/src/portal/dbus.rs create mode 100644 crates/rs-platform/src/portal/unsupported.rs create mode 100644 crates/rs-platform/src/sleep/linux.rs create mode 100644 crates/rs-platform/src/sleep/windows.rs diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index d0c42db..b3892bb 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -148,6 +148,20 @@ jobs: echo "GStreamer development files missing on the runner: hardware encoding not checked" fi + - name: Windows build (cross-compiled) + run: | + set -euo pipefail + # Windows is built from Linux with mingw-w64 (#93): the `windows` + # shell of the flake brings a rustc for that target, its linker and + # a static libvpx. Without Nix on the runner the step says so and + # passes, like the PipeWire one. + if command -v nix >/dev/null 2>&1; then + nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings + nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli + else + echo "Nix missing on the runner: the Windows build is not checked" + fi + - name: The binary starts run: | set -euo pipefail diff --git a/AGENTS.md b/AGENTS.md index 7a6e99d..f7ece2e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,6 +169,22 @@ cargo run --release -p rs-session --features pipewire --bin rustscreen-cli -- -- cargo run --release -p rs-session --features pipewire,vaapi --bin rustscreen-cli -- --codec h264 ``` +Windows se compile depuis Linux (#93): le shell `.#windows` fournit un rustc pour la cible +`x86_64-pc-windows-gnu`, mingw-w64 et une libvpx statique, et range sa cible sous `target/windows`. +Wine fait tourner le `.exe` et les tests, sans machine Windows (mais pas la capture réelle). + +```bash +nix develop .#windows -c cargo clippy --workspace --all-targets -- -D warnings +nix develop .#windows -c cargo build -p rs-session --bin rustscreen-cli +# tests et binaire sous Wine (nix shell nixpkgs#wine64) +CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUNNER=wine nix develop .#windows -c cargo test --workspace +``` + +Sous Windows, les réglages vont dans `%APPDATA%\rustscreen`, le journal dans +`%LOCALAPPDATA%\rustscreen\logs`. Le portail n'existe pas: `rs_platform::portal` y répond +`Unsupported`, et le code propre à un système vit dans un sous-module par OS (`sleep/linux.rs`, +`sleep/windows.rs`). + La coque desktop demande WebKitGTK au build: elle a son propre workspace Cargo et son shell Nix. ```bash diff --git a/Cargo.lock b/Cargo.lock index a57676a..89955e7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2053,6 +2053,7 @@ dependencies = [ "thiserror", "tokio", "tracing", + "windows-sys 0.61.2", "zbus", ] diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 1c35630..4b6d0cb 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -1290,7 +1290,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -3823,6 +3823,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tracing", + "windows-sys 0.61.2", "zbus", ] @@ -3941,7 +3942,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5003,10 +5004,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.4.3", + "getrandom 0.3.4", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] @@ -5887,7 +5888,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.52.0", ] [[package]] diff --git a/crates/rs-diag/src/log.rs b/crates/rs-diag/src/log.rs index c8fb8d6..6e9f017 100644 --- a/crates/rs-diag/src/log.rs +++ b/crates/rs-diag/src/log.rs @@ -32,8 +32,9 @@ pub struct LogGuard { } /// Where the logs live: `RUSTSCREEN_LOG_DIR`, otherwise the XDG state -/// directory (`~/.local/state/rustscreen/logs`). Logs are state, not data: -/// they can be deleted without losing anything important. +/// directory (`~/.local/state/rustscreen/logs`), or `%LOCALAPPDATA%` on +/// Windows (#93). Logs are state, not data: they can be deleted without losing +/// anything important, and they stay on this machine. pub fn log_dir() -> Option { dir_from(|name| std::env::var_os(name).map(PathBuf::from)) } @@ -42,9 +43,13 @@ fn dir_from(get: impl Fn(&str) -> Option) -> Option { if let Some(dir) = get("RUSTSCREEN_LOG_DIR") { return Some(dir); } - let state = get("XDG_STATE_HOME") - .filter(|p| p.is_absolute()) - .or_else(|| get("HOME").map(|h| h.join(".local/state")))?; + let state = if cfg!(windows) { + get("LOCALAPPDATA").filter(|p| p.is_absolute())? + } else { + get("XDG_STATE_HOME") + .filter(|p| p.is_absolute()) + .or_else(|| get("HOME").map(|h| h.join(".local/state")))? + }; Some(state.join("rustscreen").join("logs")) } @@ -121,6 +126,17 @@ mod tests { } #[test] + #[cfg(windows)] + fn local_app_data_on_windows() { + assert_eq!( + from_pairs(&[("LOCALAPPDATA", r"C:\Users\a\AppData\Local")]), + Some(PathBuf::from(r"C:\Users\a\AppData\Local\rustscreen\logs")) + ); + assert_eq!(from_pairs(&[("HOME", "/home/a")]), None); + } + + #[test] + #[cfg(not(windows))] fn xdg_state_home_then_home() { assert_eq!( from_pairs(&[("XDG_STATE_HOME", "/state"), ("HOME", "/home/a")]), diff --git a/crates/rs-platform/Cargo.toml b/crates/rs-platform/Cargo.toml index a30e9fb..cd2e98c 100644 --- a/crates/rs-platform/Cargo.toml +++ b/crates/rs-platform/Cargo.toml @@ -14,7 +14,24 @@ futures-util = { version = "0.3.34", default-features = false, features = ["std" thiserror.workspace = true tokio = { version = "1", features = ["time"] } tracing.workspace = true + +[target.'cfg(target_os = "linux")'.dependencies] zbus = { version = "6.1.0", default-features = false, features = ["tokio"] } +# Windows (#94): power requests, the resume notification, the registry for +# autostart and the neighbour table for MAC addresses. +[target.'cfg(windows)'.dependencies] +tokio = { version = "1", features = ["sync"] } +windows-sys = { version = "0.61.2", features = [ + "Win32_Foundation", + "Win32_NetworkManagement_IpHelper", + "Win32_Networking_WinSock", + "Win32_System_Power", + "Win32_System_Registry", + "Win32_System_SystemServices", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } + [dev-dependencies] tokio = { version = "1", features = ["rt", "macros"] } diff --git a/crates/rs-platform/src/portal.rs b/crates/rs-platform/src/portal.rs index 9fa41c1..b378ca7 100644 --- a/crates/rs-platform/src/portal.rs +++ b/crates/rs-platform/src/portal.rs @@ -9,38 +9,28 @@ //! Consuming the frames needs `libpipewire`, a system dependency that the //! negotiation does not need. Keeping the two apart lets the negotiation be //! checked alone, on a machine with a desktop, before adding the rest. +//! +//! The portal exists on Linux only. Elsewhere, [`probe`] and [`Session::open`] +//! fail with [`PortalError::Unsupported`], and the host offers the sources of +//! that system instead. -use std::collections::HashMap; -use std::os::fd::OwnedFd; -use std::sync::atomic::{AtomicU32, Ordering}; use std::time::Duration; -use futures_util::StreamExt; -use zbus::{Connection, MatchRule, MessageStream}; -use zbus::{OwnedObjectPath, OwnedVariant, Variant}; +#[cfg(target_os = "linux")] +mod dbus; +#[cfg(target_os = "linux")] +pub use dbus::{Session, SessionClosed, Stream, probe}; -const BUS: &str = "org.freedesktop.portal.Desktop"; -const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; -const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; -const SCREENCAST_INTERFACE: &str = "org.freedesktop.portal.ScreenCast"; -const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request"; -const SESSION_INTERFACE: &str = "org.freedesktop.portal.Session"; +#[cfg(not(target_os = "linux"))] +mod unsupported; +#[cfg(not(target_os = "linux"))] +pub use unsupported::{Session, SessionClosed, Stream, probe}; /// Source types of `SelectSources`, as a bit mask. pub const TYPE_MONITOR: u32 = 1; pub const TYPE_WINDOW: u32 = 2; pub const TYPE_VIRTUAL: u32 = 4; -/// Token counter: one request object per call. A reused token makes the -/// portal answer on an already consumed object, and the answer is lost. -static COUNTER: AtomicU32 = AtomicU32::new(0); - -/// Token unique within this process, valid in a D-Bus path. -fn token(prefix: &str) -> String { - let n = COUNTER.fetch_add(1, Ordering::Relaxed); - format!("rustscreen_{}_{prefix}_{n}", std::process::id()) -} - /// The portal waits for the user's answer in front of a picker. Two minutes /// leave time to choose a display, without leaving a service blocked forever /// if nobody answers. @@ -60,6 +50,9 @@ pub enum PortalError { Timeout, #[error("the portal returned an answer without a usable stream: {0}")] NoStream(String), + /// Not a Linux desktop: there is no portal to ask. + #[error("no desktop portal on this system")] + Unsupported, } /// What the portal announces. @@ -96,502 +89,3 @@ pub enum SourceType { /// only that window; once minimised, it stops sending frames. Window, } - -impl SourceType { - fn mask(self) -> u32 { - match self { - Self::Monitor => TYPE_MONITOR, - Self::Virtual => TYPE_VIRTUAL, - Self::Window => TYPE_WINDOW, - } - } -} - -/// A captured stream: the PipeWire descriptor and its node identifier. -pub struct Stream { - pub node_id: u32, - pub fd: OwnedFd, - /// Size announced by the portal, when it provides one. - pub size: Option<(u32, u32)>, - /// Token that avoids asking for the choice again at the next launch, when - /// the portal returns one (persistent mode). - pub restore_token: Option, -} - -impl std::fmt::Debug for Stream { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("Stream") - .field("node_id", &self.node_id) - .field("size", &self.size) - .field("fd", &self.fd) - .field("restorable", &self.restore_token.is_some()) - .finish() - } -} - -/// An open screencast session. Keeping it alive keeps the capture going; -/// closing it frees the stream and stops the share on the portal side. -pub struct Session { - connection: Connection, - path: OwnedObjectPath, -} - -impl Session { - /// Opens a screencast session. - /// - /// Shows nothing yet: the picker only appears at the `start` step, which - /// leaves time to choose the options. - pub async fn open() -> Result { - let connection = Connection::session() - .await - .map_err(|e| PortalError::Bus(e.to_string()))?; - - let mut options: HashMap = HashMap::new(); - let session_token = token("session"); - options.insert( - "session_handle_token".into(), - Variant::from(session_token.as_str()), - ); - let token = token("create"); - options.insert("handle_token".into(), Variant::from(token.as_str())); - - let results = call( - &connection, - PORTAL_PATH, - SCREENCAST_INTERFACE, - "CreateSession", - &(options,), - &token, - ) - .await?; - - let handle = results - .get("session_handle") - .ok_or_else(|| PortalError::Response("session_handle missing".into()))?; - let path = match &**handle { - Variant::Str(path) => { - OwnedObjectPath::try_from(path.as_str()).map_err(|e| e.to_string()) - } - // An ObjectPath can be owned without any possible failure. - Variant::ObjectPath(path) => Ok::<_, String>(OwnedObjectPath::from(path.clone())), - other => { - return Err(PortalError::Response(format!( - "session_handle of unexpected type: {other:?}" - ))); - } - } - .map_err(PortalError::Response)?; - - Ok(Self { connection, path }) - } - - /// Asks to share a whole display, existing or virtual. - /// - /// `multiple` stays false: a second display does not need to be multiple, - /// and a simple picker is less intimidating. - pub async fn select_monitor(&self, restore: Option<&str>) -> Result<(), PortalError> { - self.select_source(SourceType::Monitor, restore).await - } - - /// Asks for a source of the given type. For a virtual display, the picker - /// has nothing to offer: GNOME creates it directly, at the size the - /// PipeWire consumer will set. - pub async fn select_source( - &self, - source_type: SourceType, - restore: Option<&str>, - ) -> Result<(), PortalError> { - let mut options: HashMap = HashMap::new(); - let token = token("sources"); - options.insert("handle_token".into(), Variant::from(token.as_str())); - options.insert("types".into(), Variant::from(source_type.mask())); - options.insert("multiple".into(), Variant::from(false)); - // Cursor embedded in the frame: without it, a viewer does not see - // where the host clicks, which makes the share useless for explaining. - options.insert("cursor_mode".into(), Variant::from(2u32)); - // A virtual display has nothing to restore: it is recreated every - // time. For a monitor, 2 = persistent: the portal returns a token that - // avoids confirming the choice again at each launch. - if source_type == SourceType::Monitor { - if let Some(restore_token) = restore { - options.insert( - "restore_token".into(), - Variant::from(restore_token.to_string()), - ); - } - options.insert("persist_mode".into(), Variant::from(2u32)); - } - - call( - &self.connection, - // The methods live on the portal object; the session is the first - // argument, not the target of the call. - PORTAL_PATH, - SCREENCAST_INTERFACE, - "SelectSources", - &(&self.path, options), - &token, - ) - .await?; - Ok(()) - } - - /// Starts the capture. This is where the picker shows up. - pub async fn start(&self) -> Result { - let mut options: HashMap = HashMap::new(); - let token = token("start"); - options.insert("handle_token".into(), Variant::from(token.as_str())); - - // Start takes three arguments: session, parent window (empty: no modal - // dialog attached to a window), options. - let results = call( - &self.connection, - // The methods live on the portal object; the session is the first - // argument, not the target of the call. - PORTAL_PATH, - SCREENCAST_INTERFACE, - "Start", - &(&self.path, "", options), - &token, - ) - .await?; - - let (node_id, size) = first_stream(results.get("streams"))?; - let restore_token = results - .get("restore_token") - .and_then(|v| String::try_from(v.clone()).ok()); - - // The descriptor is not in the answer to `Start`: it is requested - // separately, through `OpenPipeWireRemote`, once the capture is granted. - let options: HashMap = HashMap::new(); - let reply = self - .connection - .call_method( - Some(BUS), - PORTAL_PATH, - Some(SCREENCAST_INTERFACE), - "OpenPipeWireRemote", - &(&self.path, options), - ) - .await - .map_err(|e| PortalError::NoStream(format!("OpenPipeWireRemote: {e}")))?; - // Deserialization duplicates the descriptor (`dup`): the copy belongs - // to us and outlives the D-Bus message that carried the original. - let fd: OwnedFd = reply - .body() - .deserialize::() - .map_err(|e| PortalError::NoStream(format!("unreadable descriptor: {e}")))? - .into(); - Ok(Stream { - node_id, - fd, - size, - restore_token, - }) - } - - /// Closes the session on the portal side. The session object carries - /// `Close`, not the request object: calling the latter closes nothing. - pub async fn close(&self) { - let _ = self - .connection - .call_method( - Some(BUS), - self.path.as_str(), - Some(SESSION_INTERFACE), - "Close", - &(), - ) - .await; - } - - /// Prepares to listen for the desktop closing the session (GNOME's "stop - /// sharing" button, revocation). Call it before `start`: a signal emitted - /// before the subscription would be lost. - pub async fn watch_closed(&self) -> Result { - let rule = MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .interface(SESSION_INTERFACE) - .member("Closed") - .path(self.path.as_str()) - .build() - .map_err(|e| PortalError::Response(e.to_string()))?; - let stream = MessageStream::for_match_rule(rule, &self.connection, None) - .await - .map_err(|e| PortalError::Response(e.to_string()))?; - Ok(SessionClosed { stream }) - } - - pub fn path(&self) -> &str { - self.path.as_str() - } -} - -/// Waiting for the desktop to close a session. -pub struct SessionClosed { - stream: MessageStream, -} - -impl SessionClosed { - /// Returns when the desktop has closed the session: the user stopped the - /// share, or the compositor removed the display. - pub async fn wait(mut self) { - // The stream only ends with the connection: either way, the capture - // is over. - let _ = self.stream.next().await; - } -} - -/// Extracts the identifier and size of the first stream in the answer. -/// -/// The portal returns `a(ua{sv})`: a node identifier, then properties of which -/// only the size matters to us for now. -fn first_stream(value: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> { - let value = value.ok_or_else(|| PortalError::NoStream("streams missing".into()))?; - let list = match &**value { - Variant::Array(list) => list, - other => { - return Err(PortalError::NoStream(format!( - "streams of unexpected type: {other:?}" - ))); - } - }; - let first = list - .first() - .ok_or_else(|| PortalError::NoStream("no stream in streams".into()))?; - let structure = match first { - Variant::Structure(structure) => structure, - other => { - return Err(PortalError::NoStream(format!( - "stream of unexpected type: {other:?}" - ))); - } - }; - let fields = structure.fields(); - let node_id = fields - .first() - .and_then(|v| u32::try_from(v.clone()).ok()) - .ok_or_else(|| PortalError::NoStream("unreadable node identifier".into()))?; - - // The size announced by the portal is for the logs; the authoritative one - // is the format negotiated on the PipeWire side. - let size = fields.get(1).and_then(|properties| match properties { - Variant::Dict(dict) => { - dict.get::<_, Variant>(&"size") - .ok() - .flatten() - .and_then(|v| match v { - Variant::Structure(s) => { - let f = s.fields(); - let w = i32::try_from(f.first()?.clone()).ok()?; - let h = i32::try_from(f.get(1)?.clone()).ok()?; - Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?)) - } - _ => None, - }) - } - _ => None, - }); - Ok((node_id, size)) -} - -/// Calls a portal method and waits for its answer. -/// -/// The signal subscription comes before the call: the signal may leave before -/// we subscribe, and a lost answer turns into a two-minute hang. -/// -/// The body is the argument list, not a variant: wrapped in a `Variant`, it -/// goes out with signature `(v)` and the portal rejects it (`InvalidArgs`), an -/// error that only a real session reveals. -async fn call( - connection: &Connection, - object: &str, - interface: &str, - method: &str, - body: &B, - token: &str, -) -> Result, PortalError> -where - B: serde::Serialize + zbus::zvariant::DynamicType, -{ - let response_path = request_path(connection, token)?; - let rule = MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - .interface(REQUEST_INTERFACE) - .member("Response") - .path(response_path.as_str()) - .build() - .map_err(|e| PortalError::Response(e.to_string()))?; - let mut stream = - MessageStream::for_match_rule(rule, connection, std::num::NonZeroUsize::new(4)) - .await - .map_err(|e| PortalError::Response(e.to_string()))?; - - connection - .call_method(Some(BUS), object, Some(interface), method, body) - .await - .map_err(|e| PortalError::Unreachable(e.to_string()))?; - - let message = tokio::time::timeout(RESPONSE_TIMEOUT, stream.next()) - .await - .map_err(|_| PortalError::Timeout)? - .ok_or_else(|| PortalError::Response("response stream closed".into()))? - .map_err(|e| PortalError::Response(e.to_string()))?; - - let (code, results): (u32, HashMap) = message - .body() - .deserialize() - .map_err(|e| PortalError::Response(e.to_string()))?; - - match code { - 0 => Ok(results), - 1 => Err(PortalError::Denied("request cancelled by the user".into())), - // 2 = "other error". Seen for real: the desktop service - // (xdg-desktop-portal-gnome) stops when idle, and its first answer - // after a restart fails before ScreenCast is ready. Retrying a few - // seconds later is enough. - 2 => Err(PortalError::Response( - "the desktop portal failed (code 2): it may have been restarting, \ - retry in a few seconds" - .into(), - )), - other => Err(PortalError::Response(format!( - "the portal answered {other}" - ))), - } -} - -/// The request object path follows a convention derived from the unique name -/// on the bus: `:1.42` becomes `1_42`. -fn request_path(connection: &Connection, token: &str) -> Result { - let unique = connection - .unique_name() - .ok_or_else(|| PortalError::Bus("no unique name on the bus".into()))? - .as_str() - .to_string(); - if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { - // The token ends up in a D-Bus path: a forbidden character must be - // rejected here, not by an obscure bus message. - return Err(PortalError::Response(format!("invalid token: {token}"))); - } - let sender = unique.trim_start_matches(':').replace('.', "_"); - Ok(format!("{PORTAL_PATH}/request/{sender}/{token}")) -} - -/// Queries the portal. -/// -/// Triggers no consent request: we only read the interface version, which -/// needs no user authorisation. -pub async fn probe() -> Result { - let connection = Connection::session() - .await - .map_err(|e| PortalError::Bus(e.to_string()))?; - let version = property(&connection, "version").await?; - // Missing from very old portals: it is then taken as "monitors only", - // which is the only thing they could do. - let types = property(&connection, "AvailableSourceTypes") - .await - .unwrap_or(TYPE_MONITOR); - Ok(PortalInfo { version, types }) -} - -/// Reads an integer property of the ScreenCast interface. -async fn property(connection: &Connection, name: &str) -> Result { - let reply = connection - .call_method( - Some(BUS), - PORTAL_PATH, - Some(PROPERTIES_INTERFACE), - "Get", - &(SCREENCAST_INTERFACE, name), - ) - .await - .map_err(|e| match e { - zbus::Error::MethodError(error_name, _, _) - if error_name.as_str().contains("UnknownInterface") - || error_name.as_str().contains("UnknownObject") - || error_name.as_str().contains("UnknownService") => - { - PortalError::Unreachable("the ScreenCast service is not exposed".into()) - } - other => PortalError::Unreachable(other.to_string()), - })?; - - // The property arrives wrapped in a variant (`v`). - reply - .body() - .deserialize::() - .map_err(|e| PortalError::Response(e.to_string()))? - .downcast::() - .map_err(|_| PortalError::Response(format!("{name} is not an integer"))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_virtual_display_is_read_from_the_source_types() { - // GNOME 46 announces 7 (monitor, window, virtual) in version 5. The - // version alone says nothing: a v5 portal without type 4 creates - // nothing. - let gnome = PortalInfo { - version: 5, - types: 7, - }; - assert!(gnome.supports_virtual_display()); - assert!(gnome.supports_window()); - let old = PortalInfo { - version: 5, - types: TYPE_MONITOR | TYPE_WINDOW, - }; - assert!(!old.supports_virtual_display()); - } - - #[test] - fn tokens_are_unique_and_valid_in_a_path() { - let a = token("x"); - let b = token("x"); - assert_ne!(a, b, "a reused token loses the portal's answer"); - for t in [a, b] { - assert!( - t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), - "{t}" - ); - } - } - - /// On a machine without a portal, the failure must be explained, not - /// panic. The test accepts both outcomes: it checks the behaviour, not the - /// environment of the test machine. - #[tokio::test] - async fn probing_never_panics_and_explains_failure() { - match probe().await { - Ok(info) => assert!(info.version > 0, "a zero version makes no sense"), - Err(error) => { - let message = error.to_string(); - assert!(!message.is_empty(), "the error must be readable"); - assert!( - message.contains("portal") || message.contains("D-Bus"), - "unexpected message: {message}" - ); - } - } - } - - #[tokio::test] - async fn opening_a_session_without_portal_fails_cleanly() { - // Without a portal, opening must return a readable error, never hang: - // this is the case of any machine without xdg-desktop-portal. - match Session::open().await { - Ok(session) => assert!(session.path().starts_with("/org/freedesktop/portal")), - Err(error) => { - let message = error.to_string(); - assert!( - message.contains("portal") || message.contains("D-Bus"), - "unexpected message: {message}" - ); - } - } - } -} diff --git a/crates/rs-platform/src/portal/dbus.rs b/crates/rs-platform/src/portal/dbus.rs new file mode 100644 index 0000000..86dab5c --- /dev/null +++ b/crates/rs-platform/src/portal/dbus.rs @@ -0,0 +1,529 @@ +//! The portal over D-Bus, on Linux. + +use std::collections::HashMap; +use std::os::fd::OwnedFd; +use std::sync::atomic::{AtomicU32, Ordering}; + +use futures_util::StreamExt; +use zbus::{Connection, MatchRule, MessageStream}; +use zbus::{OwnedObjectPath, OwnedVariant, Variant}; + +use super::{ + PortalError, PortalInfo, RESPONSE_TIMEOUT, SourceType, TYPE_MONITOR, TYPE_VIRTUAL, TYPE_WINDOW, +}; + +const BUS: &str = "org.freedesktop.portal.Desktop"; +const PORTAL_PATH: &str = "/org/freedesktop/portal/desktop"; +const PROPERTIES_INTERFACE: &str = "org.freedesktop.DBus.Properties"; +const SCREENCAST_INTERFACE: &str = "org.freedesktop.portal.ScreenCast"; +const REQUEST_INTERFACE: &str = "org.freedesktop.portal.Request"; +const SESSION_INTERFACE: &str = "org.freedesktop.portal.Session"; + +/// Token counter: one request object per call. A reused token makes the +/// portal answer on an already consumed object, and the answer is lost. +static COUNTER: AtomicU32 = AtomicU32::new(0); + +/// Token unique within this process, valid in a D-Bus path. +fn token(prefix: &str) -> String { + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + format!("rustscreen_{}_{prefix}_{n}", std::process::id()) +} + +impl SourceType { + pub(super) fn mask(self) -> u32 { + match self { + Self::Monitor => TYPE_MONITOR, + Self::Virtual => TYPE_VIRTUAL, + Self::Window => TYPE_WINDOW, + } + } +} + +/// A captured stream: the PipeWire descriptor and its node identifier. +pub struct Stream { + pub node_id: u32, + pub fd: OwnedFd, + /// Size announced by the portal, when it provides one. + pub size: Option<(u32, u32)>, + /// Token that avoids asking for the choice again at the next launch, when + /// the portal returns one (persistent mode). + pub restore_token: Option, +} + +impl std::fmt::Debug for Stream { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Stream") + .field("node_id", &self.node_id) + .field("size", &self.size) + .field("fd", &self.fd) + .field("restorable", &self.restore_token.is_some()) + .finish() + } +} + +/// An open screencast session. Keeping it alive keeps the capture going; +/// closing it frees the stream and stops the share on the portal side. +pub struct Session { + connection: Connection, + path: OwnedObjectPath, +} + +impl Session { + /// Opens a screencast session. + /// + /// Shows nothing yet: the picker only appears at the `start` step, which + /// leaves time to choose the options. + pub async fn open() -> Result { + let connection = Connection::session() + .await + .map_err(|e| PortalError::Bus(e.to_string()))?; + + let mut options: HashMap = HashMap::new(); + let session_token = token("session"); + options.insert( + "session_handle_token".into(), + Variant::from(session_token.as_str()), + ); + let token = token("create"); + options.insert("handle_token".into(), Variant::from(token.as_str())); + + let results = call( + &connection, + PORTAL_PATH, + SCREENCAST_INTERFACE, + "CreateSession", + &(options,), + &token, + ) + .await?; + + let handle = results + .get("session_handle") + .ok_or_else(|| PortalError::Response("session_handle missing".into()))?; + let path = match &**handle { + Variant::Str(path) => { + OwnedObjectPath::try_from(path.as_str()).map_err(|e| e.to_string()) + } + // An ObjectPath can be owned without any possible failure. + Variant::ObjectPath(path) => Ok::<_, String>(OwnedObjectPath::from(path.clone())), + other => { + return Err(PortalError::Response(format!( + "session_handle of unexpected type: {other:?}" + ))); + } + } + .map_err(PortalError::Response)?; + + Ok(Self { connection, path }) + } + + /// Asks to share a whole display, existing or virtual. + /// + /// `multiple` stays false: a second display does not need to be multiple, + /// and a simple picker is less intimidating. + pub async fn select_monitor(&self, restore: Option<&str>) -> Result<(), PortalError> { + self.select_source(SourceType::Monitor, restore).await + } + + /// Asks for a source of the given type. For a virtual display, the picker + /// has nothing to offer: GNOME creates it directly, at the size the + /// PipeWire consumer will set. + pub async fn select_source( + &self, + source_type: SourceType, + restore: Option<&str>, + ) -> Result<(), PortalError> { + let mut options: HashMap = HashMap::new(); + let token = token("sources"); + options.insert("handle_token".into(), Variant::from(token.as_str())); + options.insert("types".into(), Variant::from(source_type.mask())); + options.insert("multiple".into(), Variant::from(false)); + // Cursor embedded in the frame: without it, a viewer does not see + // where the host clicks, which makes the share useless for explaining. + options.insert("cursor_mode".into(), Variant::from(2u32)); + // A virtual display has nothing to restore: it is recreated every + // time. For a monitor, 2 = persistent: the portal returns a token that + // avoids confirming the choice again at each launch. + if source_type == SourceType::Monitor { + if let Some(restore_token) = restore { + options.insert( + "restore_token".into(), + Variant::from(restore_token.to_string()), + ); + } + options.insert("persist_mode".into(), Variant::from(2u32)); + } + + call( + &self.connection, + // The methods live on the portal object; the session is the first + // argument, not the target of the call. + PORTAL_PATH, + SCREENCAST_INTERFACE, + "SelectSources", + &(&self.path, options), + &token, + ) + .await?; + Ok(()) + } + + /// Starts the capture. This is where the picker shows up. + pub async fn start(&self) -> Result { + let mut options: HashMap = HashMap::new(); + let token = token("start"); + options.insert("handle_token".into(), Variant::from(token.as_str())); + + // Start takes three arguments: session, parent window (empty: no modal + // dialog attached to a window), options. + let results = call( + &self.connection, + // The methods live on the portal object; the session is the first + // argument, not the target of the call. + PORTAL_PATH, + SCREENCAST_INTERFACE, + "Start", + &(&self.path, "", options), + &token, + ) + .await?; + + let (node_id, size) = first_stream(results.get("streams"))?; + let restore_token = results + .get("restore_token") + .and_then(|v| String::try_from(v.clone()).ok()); + + // The descriptor is not in the answer to `Start`: it is requested + // separately, through `OpenPipeWireRemote`, once the capture is granted. + let options: HashMap = HashMap::new(); + let reply = self + .connection + .call_method( + Some(BUS), + PORTAL_PATH, + Some(SCREENCAST_INTERFACE), + "OpenPipeWireRemote", + &(&self.path, options), + ) + .await + .map_err(|e| PortalError::NoStream(format!("OpenPipeWireRemote: {e}")))?; + // Deserialization duplicates the descriptor (`dup`): the copy belongs + // to us and outlives the D-Bus message that carried the original. + let fd: OwnedFd = reply + .body() + .deserialize::() + .map_err(|e| PortalError::NoStream(format!("unreadable descriptor: {e}")))? + .into(); + Ok(Stream { + node_id, + fd, + size, + restore_token, + }) + } + + /// Closes the session on the portal side. The session object carries + /// `Close`, not the request object: calling the latter closes nothing. + pub async fn close(&self) { + let _ = self + .connection + .call_method( + Some(BUS), + self.path.as_str(), + Some(SESSION_INTERFACE), + "Close", + &(), + ) + .await; + } + + /// Prepares to listen for the desktop closing the session (GNOME's "stop + /// sharing" button, revocation). Call it before `start`: a signal emitted + /// before the subscription would be lost. + pub async fn watch_closed(&self) -> Result { + let rule = MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .interface(SESSION_INTERFACE) + .member("Closed") + .path(self.path.as_str()) + .build() + .map_err(|e| PortalError::Response(e.to_string()))?; + let stream = MessageStream::for_match_rule(rule, &self.connection, None) + .await + .map_err(|e| PortalError::Response(e.to_string()))?; + Ok(SessionClosed { stream }) + } + + pub fn path(&self) -> &str { + self.path.as_str() + } +} + +/// Waiting for the desktop to close a session. +pub struct SessionClosed { + stream: MessageStream, +} + +impl SessionClosed { + /// Returns when the desktop has closed the session: the user stopped the + /// share, or the compositor removed the display. + pub async fn wait(mut self) { + // The stream only ends with the connection: either way, the capture + // is over. + let _ = self.stream.next().await; + } +} + +/// Extracts the identifier and size of the first stream in the answer. +/// +/// The portal returns `a(ua{sv})`: a node identifier, then properties of which +/// only the size matters to us for now. +fn first_stream(value: Option<&OwnedVariant>) -> Result<(u32, Option<(u32, u32)>), PortalError> { + let value = value.ok_or_else(|| PortalError::NoStream("streams missing".into()))?; + let list = match &**value { + Variant::Array(list) => list, + other => { + return Err(PortalError::NoStream(format!( + "streams of unexpected type: {other:?}" + ))); + } + }; + let first = list + .first() + .ok_or_else(|| PortalError::NoStream("no stream in streams".into()))?; + let structure = match first { + Variant::Structure(structure) => structure, + other => { + return Err(PortalError::NoStream(format!( + "stream of unexpected type: {other:?}" + ))); + } + }; + let fields = structure.fields(); + let node_id = fields + .first() + .and_then(|v| u32::try_from(v.clone()).ok()) + .ok_or_else(|| PortalError::NoStream("unreadable node identifier".into()))?; + + // The size announced by the portal is for the logs; the authoritative one + // is the format negotiated on the PipeWire side. + let size = fields.get(1).and_then(|properties| match properties { + Variant::Dict(dict) => { + dict.get::<_, Variant>(&"size") + .ok() + .flatten() + .and_then(|v| match v { + Variant::Structure(s) => { + let f = s.fields(); + let w = i32::try_from(f.first()?.clone()).ok()?; + let h = i32::try_from(f.get(1)?.clone()).ok()?; + Some((u32::try_from(w).ok()?, u32::try_from(h).ok()?)) + } + _ => None, + }) + } + _ => None, + }); + Ok((node_id, size)) +} + +/// Calls a portal method and waits for its answer. +/// +/// The signal subscription comes before the call: the signal may leave before +/// we subscribe, and a lost answer turns into a two-minute hang. +/// +/// The body is the argument list, not a variant: wrapped in a `Variant`, it +/// goes out with signature `(v)` and the portal rejects it (`InvalidArgs`), an +/// error that only a real session reveals. +async fn call( + connection: &Connection, + object: &str, + interface: &str, + method: &str, + body: &B, + token: &str, +) -> Result, PortalError> +where + B: serde::Serialize + zbus::zvariant::DynamicType, +{ + let response_path = request_path(connection, token)?; + let rule = MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + .interface(REQUEST_INTERFACE) + .member("Response") + .path(response_path.as_str()) + .build() + .map_err(|e| PortalError::Response(e.to_string()))?; + let mut stream = + MessageStream::for_match_rule(rule, connection, std::num::NonZeroUsize::new(4)) + .await + .map_err(|e| PortalError::Response(e.to_string()))?; + + connection + .call_method(Some(BUS), object, Some(interface), method, body) + .await + .map_err(|e| PortalError::Unreachable(e.to_string()))?; + + let message = tokio::time::timeout(RESPONSE_TIMEOUT, stream.next()) + .await + .map_err(|_| PortalError::Timeout)? + .ok_or_else(|| PortalError::Response("response stream closed".into()))? + .map_err(|e| PortalError::Response(e.to_string()))?; + + let (code, results): (u32, HashMap) = message + .body() + .deserialize() + .map_err(|e| PortalError::Response(e.to_string()))?; + + match code { + 0 => Ok(results), + 1 => Err(PortalError::Denied("request cancelled by the user".into())), + // 2 = "other error". Seen for real: the desktop service + // (xdg-desktop-portal-gnome) stops when idle, and its first answer + // after a restart fails before ScreenCast is ready. Retrying a few + // seconds later is enough. + 2 => Err(PortalError::Response( + "the desktop portal failed (code 2): it may have been restarting, \ + retry in a few seconds" + .into(), + )), + other => Err(PortalError::Response(format!( + "the portal answered {other}" + ))), + } +} + +/// The request object path follows a convention derived from the unique name +/// on the bus: `:1.42` becomes `1_42`. +fn request_path(connection: &Connection, token: &str) -> Result { + let unique = connection + .unique_name() + .ok_or_else(|| PortalError::Bus("no unique name on the bus".into()))? + .as_str() + .to_string(); + if !token.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { + // The token ends up in a D-Bus path: a forbidden character must be + // rejected here, not by an obscure bus message. + return Err(PortalError::Response(format!("invalid token: {token}"))); + } + let sender = unique.trim_start_matches(':').replace('.', "_"); + Ok(format!("{PORTAL_PATH}/request/{sender}/{token}")) +} + +/// Queries the portal. +/// +/// Triggers no consent request: we only read the interface version, which +/// needs no user authorisation. +pub async fn probe() -> Result { + let connection = Connection::session() + .await + .map_err(|e| PortalError::Bus(e.to_string()))?; + let version = property(&connection, "version").await?; + // Missing from very old portals: it is then taken as "monitors only", + // which is the only thing they could do. + let types = property(&connection, "AvailableSourceTypes") + .await + .unwrap_or(TYPE_MONITOR); + Ok(PortalInfo { version, types }) +} + +/// Reads an integer property of the ScreenCast interface. +async fn property(connection: &Connection, name: &str) -> Result { + let reply = connection + .call_method( + Some(BUS), + PORTAL_PATH, + Some(PROPERTIES_INTERFACE), + "Get", + &(SCREENCAST_INTERFACE, name), + ) + .await + .map_err(|e| match e { + zbus::Error::MethodError(error_name, _, _) + if error_name.as_str().contains("UnknownInterface") + || error_name.as_str().contains("UnknownObject") + || error_name.as_str().contains("UnknownService") => + { + PortalError::Unreachable("the ScreenCast service is not exposed".into()) + } + other => PortalError::Unreachable(other.to_string()), + })?; + + // The property arrives wrapped in a variant (`v`). + reply + .body() + .deserialize::() + .map_err(|e| PortalError::Response(e.to_string()))? + .downcast::() + .map_err(|_| PortalError::Response(format!("{name} is not an integer"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_virtual_display_is_read_from_the_source_types() { + // GNOME 46 announces 7 (monitor, window, virtual) in version 5. The + // version alone says nothing: a v5 portal without type 4 creates + // nothing. + let gnome = PortalInfo { + version: 5, + types: 7, + }; + assert!(gnome.supports_virtual_display()); + assert!(gnome.supports_window()); + let old = PortalInfo { + version: 5, + types: TYPE_MONITOR | TYPE_WINDOW, + }; + assert!(!old.supports_virtual_display()); + } + + #[test] + fn tokens_are_unique_and_valid_in_a_path() { + let a = token("x"); + let b = token("x"); + assert_ne!(a, b, "a reused token loses the portal's answer"); + for t in [a, b] { + assert!( + t.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'), + "{t}" + ); + } + } + + /// On a machine without a portal, the failure must be explained, not + /// panic. The test accepts both outcomes: it checks the behaviour, not the + /// environment of the test machine. + #[tokio::test] + async fn probing_never_panics_and_explains_failure() { + match probe().await { + Ok(info) => assert!(info.version > 0, "a zero version makes no sense"), + Err(error) => { + let message = error.to_string(); + assert!(!message.is_empty(), "the error must be readable"); + assert!( + message.contains("portal") || message.contains("D-Bus"), + "unexpected message: {message}" + ); + } + } + } + + #[tokio::test] + async fn opening_a_session_without_portal_fails_cleanly() { + // Without a portal, opening must return a readable error, never hang: + // this is the case of any machine without xdg-desktop-portal. + match Session::open().await { + Ok(session) => assert!(session.path().starts_with("/org/freedesktop/portal")), + Err(error) => { + let message = error.to_string(); + assert!( + message.contains("portal") || message.contains("D-Bus"), + "unexpected message: {message}" + ); + } + } + } +} diff --git a/crates/rs-platform/src/portal/unsupported.rs b/crates/rs-platform/src/portal/unsupported.rs new file mode 100644 index 0000000..92905f2 --- /dev/null +++ b/crates/rs-platform/src/portal/unsupported.rs @@ -0,0 +1,63 @@ +//! No portal outside Linux: the same API, which always says so. + +use super::{PortalError, PortalInfo, SourceType}; + +/// A captured stream. Never produced here. +#[derive(Debug)] +pub struct Stream { + pub node_id: u32, + pub size: Option<(u32, u32)>, + pub restore_token: Option, +} + +/// A screencast session. Never opened here. +#[derive(Debug)] +pub struct Session { + _never: (), +} + +impl Session { + pub async fn open() -> Result { + Err(PortalError::Unsupported) + } + + pub async fn select_monitor(&self, _restore: Option<&str>) -> Result<(), PortalError> { + Err(PortalError::Unsupported) + } + + pub async fn select_source( + &self, + _source: SourceType, + _restore: Option<&str>, + ) -> Result<(), PortalError> { + Err(PortalError::Unsupported) + } + + pub async fn start(&self) -> Result { + Err(PortalError::Unsupported) + } + + pub async fn close(&self) {} + + pub async fn watch_closed(&self) -> Result { + Err(PortalError::Unsupported) + } + + pub fn path(&self) -> &str { + "" + } +} + +/// Waiting for the desktop to close a session. Never created here. +#[derive(Debug)] +pub struct SessionClosed { + _never: (), +} + +impl SessionClosed { + pub async fn wait(self) {} +} + +pub async fn probe() -> Result { + Err(PortalError::Unsupported) +} diff --git a/crates/rs-platform/src/sleep.rs b/crates/rs-platform/src/sleep.rs index ae36d8d..287d485 100644 --- a/crates/rs-platform/src/sleep.rs +++ b/crates/rs-platform/src/sleep.rs @@ -21,32 +21,26 @@ //! ScreenSaver daemon under a bare window manager): the inhibition succeeds as //! soon as one of them holds, and [`Inhibition::active`] says which, so the UI //! does not display a promise it does not keep. +//! +//! On Windows, a power request (`PowerCreateRequest`, system and display +//! required) holds both at once, as long as its handle stays open; the +//! suspend and resume notification (`PowerRegisterSuspendResumeNotification`) +//! plays the part of `PrepareForSleep` (#94). -use std::fmt; +#[cfg(target_os = "linux")] +mod linux; +#[cfg(target_os = "linux")] +pub use linux::{Inhibition, MECHANISM_LOGIN1, MECHANISM_SCREENSAVER, WakeWatcher, watch_wake}; -use futures_util::StreamExt; -use zbus::{Connection, MatchRule, MessageStream}; +#[cfg(windows)] +mod windows; +#[cfg(windows)] +pub use windows::{Inhibition, MECHANISM_POWER_REQUEST, WakeWatcher, watch_wake}; -const LOGIN1_BUS: &str = "org.freedesktop.login1"; -const LOGIN1_PATH: &str = "/org/freedesktop/login1"; -const LOGIN1_INTERFACE: &str = "org.freedesktop.login1.Manager"; - -const SCREENSAVER_BUS: &str = "org.freedesktop.ScreenSaver"; -const SCREENSAVER_PATH: &str = "/org/freedesktop/ScreenSaver"; -const SCREENSAVER_INTERFACE: &str = "org.freedesktop.ScreenSaver"; - -/// Name shown by `systemd-inhibit --list` and by the desktop. +/// Name shown by `systemd-inhibit --list`, by the desktop and by +/// `powercfg /requests`. const APPLICATION: &str = "rustscreen"; -/// What the `login1` lock blocks: suspend and idle sleep, not the lid nor the -/// power keys. -const LOGIN1_WHAT: &str = "sleep:idle"; - -/// Name of the `login1` mechanism in [`Inhibition::active`] and the logs. -pub const MECHANISM_LOGIN1: &str = "login1"; -/// Name of the ScreenSaver mechanism in [`Inhibition::active`] and the logs. -pub const MECHANISM_SCREENSAVER: &str = "screensaver"; - #[derive(Debug, thiserror::Error)] pub enum SleepError { /// Neither lock could be taken. @@ -56,182 +50,9 @@ pub enum SleepError { Bus(String), #[error("cannot subscribe to PrepareForSleep: {0}")] Subscription(String), -} - -/// List of the mechanisms held, in a stable order. -fn active_names(login1: bool, screensaver: bool) -> Vec<&'static str> { - let mut names = Vec::with_capacity(2); - if login1 { - names.push(MECHANISM_LOGIN1); - } - if screensaver { - names.push(MECHANISM_SCREENSAVER); - } - names -} - -/// Locks against sleep, held as long as the value lives. -/// -/// [`Inhibition::release`] frees everything immediately. Failing that, `Drop` -/// closes the `login1` descriptor (synchronous close, no D-Bus call) and drops -/// the session connection: the ScreenSaver daemon then forgets the cookie on -/// its own, without an explicit `UnInhibit`, which may take the time the -/// connection needs to close. -pub struct Inhibition { - /// Descriptor returned by `login1`: the lock lasts as long as it is open. - login1_lock: Option, - /// Session connection and ScreenSaver cookie. The connection is kept alive - /// on purpose: closing it releases the cookie. - screensaver: Option<(Connection, u32)>, -} - -impl fmt::Debug for Inhibition { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("Inhibition") - .field("active", &self.active()) - .finish() - } -} - -impl Inhibition { - /// Prevents sleep and screen blanking. - /// - /// `reason` is shown by the desktop and `systemd-inhibit --list`: a fixed - /// text from the caller, never a window title. It is not logged. - /// - /// Fails only if neither lock could be taken. - pub async fn acquire(reason: &str) -> Result { - let login1 = inhibit_login1(reason).await; - let screensaver = inhibit_screensaver(reason).await; - - let (login1_lock, screensaver) = match (login1, screensaver) { - (Err(login1), Err(screensaver)) => { - tracing::warn!( - event = "sleep_not_inhibited", - login1 = %login1, - screensaver = %screensaver, - "no lock against sleep" - ); - return Err(SleepError::Inhibition { - login1, - screensaver, - }); - } - (login1, screensaver) => { - if let Err(error) = &login1 { - tracing::warn!(%error, "login1 lock unavailable"); - } - if let Err(error) = &screensaver { - tracing::warn!(%error, "ScreenSaver lock unavailable"); - } - (login1.ok(), screensaver.ok()) - } - }; - - let inhibition = Self { - login1_lock, - screensaver, - }; - tracing::info!( - event = "sleep_inhibited", - mechanisms = ?inhibition.active(), - "sleep prevented during the share" - ); - Ok(inhibition) - } - - /// Mechanisms actually held: [`MECHANISM_LOGIN1`], - /// [`MECHANISM_SCREENSAVER`], or both. - pub fn active(&self) -> Vec<&'static str> { - active_names(self.login1_lock.is_some(), self.screensaver.is_some()) - } - - /// Frees the locks right away: `UnInhibit`, then closing the `login1` - /// descriptor. - pub async fn release(mut self) { - let active = self.active(); - if let Some((connection, cookie)) = self.screensaver.take() { - // A failure here prevents nothing: the connection closes right - // after, and the daemon forgets the cookie with it. - if let Err(error) = connection - .call_method( - Some(SCREENSAVER_BUS), - SCREENSAVER_PATH, - Some(SCREENSAVER_INTERFACE), - "UnInhibit", - &(cookie,), - ) - .await - { - tracing::debug!(%error, "UnInhibit refused, closing will be enough"); - } - } - // Closing the descriptor is enough to hand the lock back to logind. - drop(self.login1_lock.take()); - tracing::info!( - event = "sleep_released", - mechanisms = ?active, - "sleep allowed again" - ); - } -} - -impl Drop for Inhibition { - fn drop(&mut self) { - // Nothing to do if `release` already ran. - let active = self.active(); - if active.is_empty() { - return; - } - // The descriptor closes with the field, the connection too: no D-Bus - // call is possible in a synchronous `Drop`, and none is needed. - tracing::info!( - event = "sleep_released", - mechanisms = ?active, - "sleep allowed again" - ); - } -} - -/// Takes the `login1` lock and returns its descriptor. -async fn inhibit_login1(reason: &str) -> Result { - let connection = Connection::system().await.map_err(|e| e.to_string())?; - let reply = connection - .call_method( - Some(LOGIN1_BUS), - LOGIN1_PATH, - Some(LOGIN1_INTERFACE), - "Inhibit", - &(LOGIN1_WHAT, APPLICATION, reason, "block"), - ) - .await - .map_err(|e| e.to_string())?; - // Deserialization duplicates the descriptor: the copy belongs to us and - // keeps the lock once the message and the connection are gone. - reply - .body() - .deserialize::() - .map_err(|e| format!("unreadable descriptor: {e}")) -} - -/// Takes the ScreenSaver lock and returns the connection that carries it. -async fn inhibit_screensaver(reason: &str) -> Result<(Connection, u32), String> { - let connection = Connection::session().await.map_err(|e| e.to_string())?; - let reply = connection - .call_method( - Some(SCREENSAVER_BUS), - SCREENSAVER_PATH, - Some(SCREENSAVER_INTERFACE), - "Inhibit", - &(APPLICATION, reason), - ) - .await - .map_err(|e| e.to_string())?; - let cookie = reply - .body() - .deserialize::() - .map_err(|e| format!("unreadable cookie: {e}"))?; - Ok((connection, cookie)) + /// Windows: the power request or the resume notification was refused. + #[error("power management refused: {0}")] + Power(String), } /// Transition announced by `PrepareForSleep`. @@ -243,150 +64,3 @@ pub enum SleepEvent { /// connections are probably dead, and so is the capture. WokeUp, } - -impl SleepEvent { - fn from_signal(going_to_sleep: bool) -> Self { - if going_to_sleep { - Self::GoingToSleep - } else { - Self::WokeUp - } - } -} - -/// Listens for the sleeps and wake-ups announced by `login1`. -pub struct WakeWatcher { - stream: MessageStream, -} - -impl fmt::Debug for WakeWatcher { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("WakeWatcher").finish_non_exhaustive() - } -} - -/// Subscribes to `PrepareForSleep` on the system bus. -/// -/// Call it before it is needed: a signal emitted before the subscription is -/// lost, and a missed wake-up leaves the share frozen. -pub async fn watch_wake() -> Result { - let connection = Connection::system() - .await - .map_err(|e| SleepError::Bus(e.to_string()))?; - let rule = MatchRule::builder() - .msg_type(zbus::message::Type::Signal) - // No sender filter: the signal arrives under logind's unique name, not - // under `org.freedesktop.login1`. Only root can emit on this path of - // the system bus. - .interface(LOGIN1_INTERFACE) - .member("PrepareForSleep") - .path(LOGIN1_PATH) - .build() - .map_err(|e| SleepError::Subscription(e.to_string()))?; - let stream = MessageStream::for_match_rule(rule, &connection, None) - .await - .map_err(|e| SleepError::Subscription(e.to_string()))?; - Ok(WakeWatcher { stream }) -} - -impl WakeWatcher { - /// Waits for the next transition. `None` when the connection to the - /// system bus is lost: no wake-up will be announced anymore. - pub async fn next_event(&mut self) -> Option { - loop { - let message = match self.stream.next().await? { - Ok(message) => message, - Err(error) => { - tracing::debug!(%error, "unreadable message on the system bus"); - continue; - } - }; - let Ok(going_to_sleep) = message.body().deserialize::() else { - continue; - }; - let event = SleepEvent::from_signal(going_to_sleep); - match event { - SleepEvent::GoingToSleep => { - tracing::info!(event = "going_to_sleep", "the machine is going to sleep"); - } - SleepEvent::WokeUp => { - tracing::info!(event = "woke_up", "the machine is waking up"); - } - } - return Some(event); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn active_mechanisms_are_named_in_a_stable_order() { - assert_eq!(active_names(true, true), ["login1", "screensaver"]); - assert_eq!(active_names(false, true), ["screensaver"]); - assert_eq!(active_names(true, false), ["login1"]); - assert!(active_names(false, false).is_empty()); - } - - #[test] - fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() { - assert_eq!(SleepEvent::from_signal(true), SleepEvent::GoingToSleep); - assert_eq!(SleepEvent::from_signal(false), SleepEvent::WokeUp); - } - - #[test] - fn the_lid_switch_is_never_inhibited() { - // Closing the lid is an explicit gesture: blocking it would surprise. - assert!(!LOGIN1_WHAT.contains("handle-lid-switch")); - assert_eq!(LOGIN1_WHAT, "sleep:idle"); - } - - /// Lines of `systemd-inhibit --list` that come from this process. - fn locks_of_this_process() -> Vec { - let output = std::process::Command::new("systemd-inhibit") - .args(["--list", "--no-pager", "--no-legend"]) - .output() - .expect("systemd-inhibit not found"); - let pid = std::process::id().to_string(); - String::from_utf8_lossy(&output.stdout) - .lines() - .filter(|l| { - let fields: Vec<&str> = l.split_whitespace().collect(); - fields.first() == Some(&APPLICATION) && fields.contains(&pid.as_str()) - }) - .map(str::to_string) - .collect() - } - - /// Takes a real lock on this machine: needs logind and a desktop that - /// exposes ScreenSaver. `cargo test -p rs-platform sleep -- --ignored`. - #[tokio::test] - #[ignore = "needs logind and a desktop session"] - async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() { - let inhibition = Inhibition::acquire("screen sharing in progress (test)") - .await - .expect("no lock taken"); - let active = inhibition.active(); - assert!(active.contains(&MECHANISM_LOGIN1), "{active:?}"); - eprintln!("mechanisms held: {active:?}"); - - let lines = locks_of_this_process(); - assert_eq!(lines.len(), 1, "{lines:?}"); - assert!(lines[0].contains("sleep:idle"), "{}", lines[0]); - assert!(lines[0].contains("block"), "{}", lines[0]); - - inhibition.release().await; - let lines = locks_of_this_process(); - assert!(lines.is_empty(), "lock still held: {lines:?}"); - } - - #[tokio::test] - async fn subscribing_to_resume_never_panics() { - // Without a system bus, the error must be readable, never a panic. - if let Err(error) = watch_wake().await { - assert!(!error.to_string().is_empty()); - } - } -} diff --git a/crates/rs-platform/src/sleep/linux.rs b/crates/rs-platform/src/sleep/linux.rs new file mode 100644 index 0000000..931689f --- /dev/null +++ b/crates/rs-platform/src/sleep/linux.rs @@ -0,0 +1,348 @@ +//! Sleep on Linux: `login1` and ScreenSaver over D-Bus. + +use std::fmt; + +use futures_util::StreamExt; +use zbus::{Connection, MatchRule, MessageStream}; + +use super::{APPLICATION, SleepError, SleepEvent}; + +const LOGIN1_BUS: &str = "org.freedesktop.login1"; +const LOGIN1_PATH: &str = "/org/freedesktop/login1"; +const LOGIN1_INTERFACE: &str = "org.freedesktop.login1.Manager"; + +const SCREENSAVER_BUS: &str = "org.freedesktop.ScreenSaver"; +const SCREENSAVER_PATH: &str = "/org/freedesktop/ScreenSaver"; +const SCREENSAVER_INTERFACE: &str = "org.freedesktop.ScreenSaver"; + +/// What the `login1` lock blocks: suspend and idle sleep, not the lid nor the +/// power keys. +const LOGIN1_WHAT: &str = "sleep:idle"; + +/// Name of the `login1` mechanism in [`Inhibition::active`] and the logs. +pub const MECHANISM_LOGIN1: &str = "login1"; +/// Name of the ScreenSaver mechanism in [`Inhibition::active`] and the logs. +pub const MECHANISM_SCREENSAVER: &str = "screensaver"; + +/// List of the mechanisms held, in a stable order. +fn active_names(login1: bool, screensaver: bool) -> Vec<&'static str> { + let mut names = Vec::with_capacity(2); + if login1 { + names.push(MECHANISM_LOGIN1); + } + if screensaver { + names.push(MECHANISM_SCREENSAVER); + } + names +} + +/// Locks against sleep, held as long as the value lives. +/// +/// [`Inhibition::release`] frees everything immediately. Failing that, `Drop` +/// closes the `login1` descriptor (synchronous close, no D-Bus call) and drops +/// the session connection: the ScreenSaver daemon then forgets the cookie on +/// its own, without an explicit `UnInhibit`, which may take the time the +/// connection needs to close. +pub struct Inhibition { + /// Descriptor returned by `login1`: the lock lasts as long as it is open. + login1_lock: Option, + /// Session connection and ScreenSaver cookie. The connection is kept alive + /// on purpose: closing it releases the cookie. + screensaver: Option<(Connection, u32)>, +} + +impl fmt::Debug for Inhibition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Inhibition") + .field("active", &self.active()) + .finish() + } +} + +impl Inhibition { + /// Prevents sleep and screen blanking. + /// + /// `reason` is shown by the desktop and `systemd-inhibit --list`: a fixed + /// text from the caller, never a window title. It is not logged. + /// + /// Fails only if neither lock could be taken. + pub async fn acquire(reason: &str) -> Result { + let login1 = inhibit_login1(reason).await; + let screensaver = inhibit_screensaver(reason).await; + + let (login1_lock, screensaver) = match (login1, screensaver) { + (Err(login1), Err(screensaver)) => { + tracing::warn!( + event = "sleep_not_inhibited", + login1 = %login1, + screensaver = %screensaver, + "no lock against sleep" + ); + return Err(SleepError::Inhibition { + login1, + screensaver, + }); + } + (login1, screensaver) => { + if let Err(error) = &login1 { + tracing::warn!(%error, "login1 lock unavailable"); + } + if let Err(error) = &screensaver { + tracing::warn!(%error, "ScreenSaver lock unavailable"); + } + (login1.ok(), screensaver.ok()) + } + }; + + let inhibition = Self { + login1_lock, + screensaver, + }; + tracing::info!( + event = "sleep_inhibited", + mechanisms = ?inhibition.active(), + "sleep prevented during the share" + ); + Ok(inhibition) + } + + /// Mechanisms actually held: [`MECHANISM_LOGIN1`], + /// [`MECHANISM_SCREENSAVER`], or both. + pub fn active(&self) -> Vec<&'static str> { + active_names(self.login1_lock.is_some(), self.screensaver.is_some()) + } + + /// Frees the locks right away: `UnInhibit`, then closing the `login1` + /// descriptor. + pub async fn release(mut self) { + let active = self.active(); + if let Some((connection, cookie)) = self.screensaver.take() { + // A failure here prevents nothing: the connection closes right + // after, and the daemon forgets the cookie with it. + if let Err(error) = connection + .call_method( + Some(SCREENSAVER_BUS), + SCREENSAVER_PATH, + Some(SCREENSAVER_INTERFACE), + "UnInhibit", + &(cookie,), + ) + .await + { + tracing::debug!(%error, "UnInhibit refused, closing will be enough"); + } + } + // Closing the descriptor is enough to hand the lock back to logind. + drop(self.login1_lock.take()); + tracing::info!( + event = "sleep_released", + mechanisms = ?active, + "sleep allowed again" + ); + } +} + +impl Drop for Inhibition { + fn drop(&mut self) { + // Nothing to do if `release` already ran. + let active = self.active(); + if active.is_empty() { + return; + } + // The descriptor closes with the field, the connection too: no D-Bus + // call is possible in a synchronous `Drop`, and none is needed. + tracing::info!( + event = "sleep_released", + mechanisms = ?active, + "sleep allowed again" + ); + } +} + +/// Takes the `login1` lock and returns its descriptor. +async fn inhibit_login1(reason: &str) -> Result { + let connection = Connection::system().await.map_err(|e| e.to_string())?; + let reply = connection + .call_method( + Some(LOGIN1_BUS), + LOGIN1_PATH, + Some(LOGIN1_INTERFACE), + "Inhibit", + &(LOGIN1_WHAT, APPLICATION, reason, "block"), + ) + .await + .map_err(|e| e.to_string())?; + // Deserialization duplicates the descriptor: the copy belongs to us and + // keeps the lock once the message and the connection are gone. + reply + .body() + .deserialize::() + .map_err(|e| format!("unreadable descriptor: {e}")) +} + +/// Takes the ScreenSaver lock and returns the connection that carries it. +async fn inhibit_screensaver(reason: &str) -> Result<(Connection, u32), String> { + let connection = Connection::session().await.map_err(|e| e.to_string())?; + let reply = connection + .call_method( + Some(SCREENSAVER_BUS), + SCREENSAVER_PATH, + Some(SCREENSAVER_INTERFACE), + "Inhibit", + &(APPLICATION, reason), + ) + .await + .map_err(|e| e.to_string())?; + let cookie = reply + .body() + .deserialize::() + .map_err(|e| format!("unreadable cookie: {e}"))?; + Ok((connection, cookie)) +} + +impl SleepEvent { + fn from_signal(going_to_sleep: bool) -> Self { + if going_to_sleep { + Self::GoingToSleep + } else { + Self::WokeUp + } + } +} + +/// Listens for the sleeps and wake-ups announced by `login1`. +pub struct WakeWatcher { + stream: MessageStream, +} + +impl fmt::Debug for WakeWatcher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WakeWatcher").finish_non_exhaustive() + } +} + +/// Subscribes to `PrepareForSleep` on the system bus. +/// +/// Call it before it is needed: a signal emitted before the subscription is +/// lost, and a missed wake-up leaves the share frozen. +pub async fn watch_wake() -> Result { + let connection = Connection::system() + .await + .map_err(|e| SleepError::Bus(e.to_string()))?; + let rule = MatchRule::builder() + .msg_type(zbus::message::Type::Signal) + // No sender filter: the signal arrives under logind's unique name, not + // under `org.freedesktop.login1`. Only root can emit on this path of + // the system bus. + .interface(LOGIN1_INTERFACE) + .member("PrepareForSleep") + .path(LOGIN1_PATH) + .build() + .map_err(|e| SleepError::Subscription(e.to_string()))?; + let stream = MessageStream::for_match_rule(rule, &connection, None) + .await + .map_err(|e| SleepError::Subscription(e.to_string()))?; + Ok(WakeWatcher { stream }) +} + +impl WakeWatcher { + /// Waits for the next transition. `None` when the connection to the + /// system bus is lost: no wake-up will be announced anymore. + pub async fn next_event(&mut self) -> Option { + loop { + let message = match self.stream.next().await? { + Ok(message) => message, + Err(error) => { + tracing::debug!(%error, "unreadable message on the system bus"); + continue; + } + }; + let Ok(going_to_sleep) = message.body().deserialize::() else { + continue; + }; + let event = SleepEvent::from_signal(going_to_sleep); + match event { + SleepEvent::GoingToSleep => { + tracing::info!(event = "going_to_sleep", "the machine is going to sleep"); + } + SleepEvent::WokeUp => { + tracing::info!(event = "woke_up", "the machine is waking up"); + } + } + return Some(event); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn active_mechanisms_are_named_in_a_stable_order() { + assert_eq!(active_names(true, true), ["login1", "screensaver"]); + assert_eq!(active_names(false, true), ["screensaver"]); + assert_eq!(active_names(true, false), ["login1"]); + assert!(active_names(false, false).is_empty()); + } + + #[test] + fn prepare_for_sleep_maps_true_to_sleep_and_false_to_wake() { + assert_eq!(SleepEvent::from_signal(true), SleepEvent::GoingToSleep); + assert_eq!(SleepEvent::from_signal(false), SleepEvent::WokeUp); + } + + #[test] + fn the_lid_switch_is_never_inhibited() { + // Closing the lid is an explicit gesture: blocking it would surprise. + assert!(!LOGIN1_WHAT.contains("handle-lid-switch")); + assert_eq!(LOGIN1_WHAT, "sleep:idle"); + } + + /// Lines of `systemd-inhibit --list` that come from this process. + fn locks_of_this_process() -> Vec { + let output = std::process::Command::new("systemd-inhibit") + .args(["--list", "--no-pager", "--no-legend"]) + .output() + .expect("systemd-inhibit not found"); + let pid = std::process::id().to_string(); + String::from_utf8_lossy(&output.stdout) + .lines() + .filter(|l| { + let fields: Vec<&str> = l.split_whitespace().collect(); + fields.first() == Some(&APPLICATION) && fields.contains(&pid.as_str()) + }) + .map(str::to_string) + .collect() + } + + /// Takes a real lock on this machine: needs logind and a desktop that + /// exposes ScreenSaver. `cargo test -p rs-platform sleep -- --ignored`. + #[tokio::test] + #[ignore = "needs logind and a desktop session"] + async fn a_real_inhibition_shows_in_systemd_inhibit_then_goes_away() { + let inhibition = Inhibition::acquire("screen sharing in progress (test)") + .await + .expect("no lock taken"); + let active = inhibition.active(); + assert!(active.contains(&MECHANISM_LOGIN1), "{active:?}"); + eprintln!("mechanisms held: {active:?}"); + + let lines = locks_of_this_process(); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("sleep:idle"), "{}", lines[0]); + assert!(lines[0].contains("block"), "{}", lines[0]); + + inhibition.release().await; + let lines = locks_of_this_process(); + assert!(lines.is_empty(), "lock still held: {lines:?}"); + } + + #[tokio::test] + async fn subscribing_to_resume_never_panics() { + // Without a system bus, the error must be readable, never a panic. + if let Err(error) = watch_wake().await { + assert!(!error.to_string().is_empty()); + } + } +} diff --git a/crates/rs-platform/src/sleep/windows.rs b/crates/rs-platform/src/sleep/windows.rs new file mode 100644 index 0000000..39a5acc --- /dev/null +++ b/crates/rs-platform/src/sleep/windows.rs @@ -0,0 +1,230 @@ +//! Sleep on Windows: a power request, and the suspend and resume notification. + +use std::ffi::c_void; +use std::fmt; + +use tokio::sync::mpsc; +use windows_sys::Win32::Foundation::{CloseHandle, ERROR_SUCCESS, HANDLE}; +use windows_sys::Win32::System::Power::{ + DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS, PowerClearRequest, PowerCreateRequest, + PowerRegisterSuspendResumeNotification, PowerRequestDisplayRequired, + PowerRequestSystemRequired, PowerSetRequest, PowerUnregisterSuspendResumeNotification, +}; +use windows_sys::Win32::System::SystemServices::POWER_REQUEST_CONTEXT_VERSION; +use windows_sys::Win32::System::Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT}; +use windows_sys::Win32::UI::WindowsAndMessaging::{ + DEVICE_NOTIFY_CALLBACK, PBT_APMRESUMEAUTOMATIC, PBT_APMSUSPEND, +}; + +use super::{APPLICATION, SleepError, SleepEvent}; + +/// Name of the power request in [`Inhibition::active`] and the logs. +pub const MECHANISM_POWER_REQUEST: &str = "power_request"; + +/// A power request, held as long as the value lives: the system stays awake +/// and the display on. `powercfg /requests` lists it under `rustscreen`. +pub struct Inhibition { + request: Option, +} + +// The handle is a kernel object, usable from any thread. +unsafe impl Send for Inhibition {} +unsafe impl Sync for Inhibition {} + +impl fmt::Debug for Inhibition { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Inhibition") + .field("active", &self.active()) + .finish() + } +} + +impl Inhibition { + /// Prevents sleep and screen blanking. `reason` is shown by + /// `powercfg /requests`: a fixed text from the caller, never a window + /// title. It is not logged. + pub async fn acquire(reason: &str) -> Result { + let request = create_request(reason).map_err(|error| { + tracing::warn!(event = "sleep_not_inhibited", %error, "no lock against sleep"); + SleepError::Power(error) + })?; + let inhibition = Self { + request: Some(request), + }; + tracing::info!( + event = "sleep_inhibited", + mechanisms = ?inhibition.active(), + "sleep prevented during the share" + ); + Ok(inhibition) + } + + pub fn active(&self) -> Vec<&'static str> { + if self.request.is_some() { + vec![MECHANISM_POWER_REQUEST] + } else { + Vec::new() + } + } + + /// Frees the request right away. + pub async fn release(mut self) { + self.close(); + } + + fn close(&mut self) { + let Some(request) = self.request.take() else { + return; + }; + // SAFETY: `request` comes from `PowerCreateRequest` and is closed once. + unsafe { + PowerClearRequest(request, PowerRequestSystemRequired); + PowerClearRequest(request, PowerRequestDisplayRequired); + CloseHandle(request); + } + tracing::info!( + event = "sleep_released", + mechanisms = ?[MECHANISM_POWER_REQUEST], + "sleep allowed again" + ); + } +} + +impl Drop for Inhibition { + fn drop(&mut self) { + self.close(); + } +} + +/// Creates the request, system and display required. +fn create_request(reason: &str) -> Result { + // Windows reads the string while the request lives, not only during the + // call: it is leaked on purpose, a few bytes per share. + let text: Vec = format!("{APPLICATION}: {reason}") + .encode_utf16() + .chain(Some(0)) + .collect(); + let text = Box::leak(text.into_boxed_slice()); + let mut context = REASON_CONTEXT { + Version: POWER_REQUEST_CONTEXT_VERSION, + Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING, + ..Default::default() + }; + context.Reason.SimpleReasonString = text.as_mut_ptr(); + // SAFETY: `context` and the string it points to outlive the call. + let request = unsafe { PowerCreateRequest(&context) }; + if request.is_null() || request as isize == -1 { + return Err(format!( + "PowerCreateRequest: {}", + std::io::Error::last_os_error() + )); + } + // SAFETY: `request` is a valid power request handle. + let held = unsafe { + PowerSetRequest(request, PowerRequestSystemRequired) != 0 + && PowerSetRequest(request, PowerRequestDisplayRequired) != 0 + }; + if !held { + let error = std::io::Error::last_os_error(); + // SAFETY: closed once, on the failure path only. + unsafe { CloseHandle(request) }; + return Err(format!("PowerSetRequest: {error}")); + } + Ok(request) +} + +/// Listens for the suspends and resumes Windows announces. +pub struct WakeWatcher { + events: mpsc::UnboundedReceiver, + registration: *mut c_void, + /// Given to Windows as the callback context: freed after unregistering. + sender: *mut mpsc::UnboundedSender, +} + +// The registration handle and the sender are only touched by `Drop`, after +// Windows stopped calling back. +unsafe impl Send for WakeWatcher {} +unsafe impl Sync for WakeWatcher {} + +impl fmt::Debug for WakeWatcher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("WakeWatcher").finish_non_exhaustive() + } +} + +/// Called by Windows on a thread of its own, for each power transition. +unsafe extern "system" fn on_power( + context: *const c_void, + kind: u32, + _setting: *const c_void, +) -> u32 { + let event = match kind { + PBT_APMSUSPEND => SleepEvent::GoingToSleep, + PBT_APMRESUMEAUTOMATIC => SleepEvent::WokeUp, + _ => return ERROR_SUCCESS, + }; + // SAFETY: `context` is the sender boxed by `watch_wake`, alive until the + // registration is withdrawn. + let sender = unsafe { &*context.cast::>() }; + let _ = sender.send(event); + ERROR_SUCCESS +} + +/// Subscribes to the suspend and resume notification. +pub async fn watch_wake() -> Result { + let (sender, events) = mpsc::unbounded_channel(); + let sender = Box::into_raw(Box::new(sender)); + let mut parameters = DEVICE_NOTIFY_SUBSCRIBE_PARAMETERS { + Callback: Some(on_power), + Context: sender.cast(), + }; + let mut registration = std::ptr::null_mut(); + // SAFETY: with DEVICE_NOTIFY_CALLBACK, the recipient is the parameter + // block, which Windows copies; the context stays valid until `Drop`. + let status = unsafe { + PowerRegisterSuspendResumeNotification( + DEVICE_NOTIFY_CALLBACK, + (&raw mut parameters).cast(), + &mut registration, + ) + }; + if status != ERROR_SUCCESS { + // SAFETY: never handed to Windows. + drop(unsafe { Box::from_raw(sender) }); + return Err(SleepError::Subscription( + std::io::Error::from_raw_os_error(status as i32).to_string(), + )); + } + Ok(WakeWatcher { + events, + registration, + sender, + }) +} + +impl WakeWatcher { + /// Waits for the next transition. + pub async fn next_event(&mut self) -> Option { + let event = self.events.recv().await?; + match event { + SleepEvent::GoingToSleep => { + tracing::info!(event = "going_to_sleep", "the machine is going to sleep"); + } + SleepEvent::WokeUp => { + tracing::info!(event = "woke_up", "the machine is waking up"); + } + } + Some(event) + } +} + +impl Drop for WakeWatcher { + fn drop(&mut self) { + // SAFETY: the registration comes from `watch_wake`; once withdrawn, + // Windows no longer calls back, and the sender can go. + unsafe { + PowerUnregisterSuspendResumeNotification(self.registration as isize); + drop(Box::from_raw(self.sender)); + } + } +} diff --git a/crates/rs-session/src/bin/rustscreen-cli.rs b/crates/rs-session/src/bin/rustscreen-cli.rs index feaf564..a17503f 100644 --- a/crates/rs-session/src/bin/rustscreen-cli.rs +++ b/crates/rs-session/src/bin/rustscreen-cli.rs @@ -375,10 +375,8 @@ async fn test_portal() -> Result<(), Error> { println!("session opened: {}", session.path()); session.select_monitor(None).await?; let stream = session.start().await?; - println!( - "stream obtained: node {} descriptor {:?} size {:?}", - stream.node_id, stream.fd, stream.size - ); + // Node, descriptor and size: the Debug of `Stream` says it all. + println!("stream obtained: {stream:?}"); session.close().await; Ok(()) } diff --git a/crates/rs-session/src/capture.rs b/crates/rs-session/src/capture.rs index 6452db1..38b89fe 100644 --- a/crates/rs-session/src/capture.rs +++ b/crates/rs-session/src/capture.rs @@ -87,6 +87,7 @@ impl StartCaptureError { Self::Portal(PortalError::Response(e) | PortalError::NoStream(e)) => { Notice::new("portal_failed", text).with("detail", e) } + Self::Portal(PortalError::Unsupported) => Notice::new("portal_unsupported", text), Self::Encoder(e) => Notice::new("encoder_failed", text).with("detail", e), Self::Playback(e) => Notice::new("playback_failed", text).with("detail", e), Self::PatternTooSmall { width, height } => Notice::new("pattern_too_small", text) diff --git a/crates/rs-store/src/lib.rs b/crates/rs-store/src/lib.rs index 3f06a04..4e732b5 100644 --- a/crates/rs-store/src/lib.rs +++ b/crates/rs-store/src/lib.rs @@ -487,7 +487,8 @@ impl Store { } /// The user's file: `RUSTSCREEN_CONFIG`, otherwise - /// `$XDG_CONFIG_HOME/rustscreen/settings.json`, otherwise `~/.config/...`. + /// `$XDG_CONFIG_HOME/rustscreen/settings.json`, otherwise `~/.config/...`; + /// `%APPDATA%\rustscreen\settings.json` on Windows. pub fn user_default() -> Option { path_from(|name| std::env::var_os(name).map(PathBuf::from)).map(Self::new) } @@ -613,9 +614,15 @@ fn path_from(get: impl Fn(&str) -> Option) -> Option { if let Some(file) = get(ENV_VAR) { return Some(file); } - let config = get("XDG_CONFIG_HOME") - .filter(|p| p.is_absolute()) - .or_else(|| get("HOME").map(|h| h.join(".config")))?; + // Windows (#93): `%APPDATA%`, which follows the user from one machine to + // another on a domain, as settings should. + let config = if cfg!(windows) { + get("APPDATA").filter(|p| p.is_absolute())? + } else { + get("XDG_CONFIG_HOME") + .filter(|p| p.is_absolute()) + .or_else(|| get("HOME").map(|h| h.join(".config")))? + }; Some(config.join("rustscreen").join(FILE_NAME)) } @@ -949,6 +956,20 @@ mod tests { } #[test] + #[cfg(windows)] + fn the_path_follows_app_data_on_windows() { + let env = + |name: &str| (name == "APPDATA").then(|| PathBuf::from(r"C:\Users\a\AppData\Roaming")); + assert_eq!( + path_from(env), + Some(PathBuf::from( + r"C:\Users\a\AppData\Roaming\rustscreen\settings.json" + )) + ); + } + + #[test] + #[cfg(not(windows))] fn the_path_follows_xdg() { let env = |pairs: &'static [(&'static str, &'static str)]| { move |name: &str| { diff --git a/flake.nix b/flake.nix index b7add8d..e41d6e3 100644 --- a/flake.nix +++ b/flake.nix @@ -83,9 +83,52 @@ export LIBVA_DRIVERS_PATH="${pkgs.intel-media-driver}/lib/dri:${pkgs.mesa}/lib/dri" ''; }; + # Windows (#93): cross-compiled from Linux with mingw-w64. A rustc + # built for that target (cached by nixpkgs), its linker, and libvpx + # built as a static library for Windows. + windows = + let + cross = pkgs.pkgsCross.mingwW64; + libvpx = cross.callPackage ./nix/libvpx.nix { }; + in + pkgs.mkShell { + name = "rustscreen-windows"; + packages = [ + cross.buildPackages.rustc + cross.buildPackages.cargo + cross.stdenv.cc + # Build scripts run on Linux, with the Linux compiler. + pkgs.stdenv.cc + pkgs.nasm + cross.buildPackages.clippy + pkgs.rustfmt + pkgs.nodejs_22 + pkgs.pkg-config + ]; + shellHook = '' + export CARGO_BUILD_TARGET=x86_64-pc-windows-gnu + export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_LINKER=${cross.stdenv.cc.targetPrefix}cc + # C dependencies (aws-lc, ring) compiled by the cc crate. + export CC_x86_64_pc_windows_gnu=${cross.stdenv.cc.targetPrefix}cc + export CXX_x86_64_pc_windows_gnu=${cross.stdenv.cc.targetPrefix}c++ + export AR_x86_64_pc_windows_gnu=${cross.stdenv.cc.targetPrefix}ar + # aws-lc includes sched.h and pthread.h: winpthreads, which + # the mingw-w64 of nixpkgs (mcfgthread) does not put in the path. + export CFLAGS_x86_64_pc_windows_gnu="-I${cross.windows.pthreads}/include" + export CARGO_TARGET_X86_64_PC_WINDOWS_GNU_RUSTFLAGS="-L native=${cross.windows.pthreads}/lib" + export VPX_LIB_DIR="${libvpx}/lib" + export VPX_INCLUDE_DIR="${libvpx}/include" + export VPX_VERSION="1.13.0" + export VPX_STATIC=1 + # A separate target directory, under the usual one (the CI + # cache, or ./target): the Linux build keeps its cache. + export CARGO_TARGET_DIR="''${CARGO_TARGET_DIR:-$PWD/target}/windows" + ''; + }; in { default = defaultShell; + inherit windows; # The Tauri shell (apps/desktop) also needs WebKitGTK and GTK: a # separate dev shell, so they are not downloaded when only the host # or the viewer is being worked on. diff --git a/locales/en.json b/locales/en.json index b0655bb..34fb261 100644 --- a/locales/en.json +++ b/locales/en.json @@ -290,6 +290,7 @@ "portal_timeout": "The desktop's sharing dialog did not answer in time.", "portal_unreachable": "The desktop's sharing service cannot be reached: {detail}", "portal_failed": "The desktop's sharing service answered unexpectedly: {detail}", + "portal_unsupported": "This system has no desktop portal: pick a screen from the list.", "encoder_failed": "The video encoder is unavailable: {detail}", "playback_failed": "The test file cannot be read: {detail}", "pattern_too_small": "A {width}×{height} test pattern is too small.", diff --git a/locales/fr.json b/locales/fr.json index ec2c087..7b7e3b1 100644 --- a/locales/fr.json +++ b/locales/fr.json @@ -290,6 +290,7 @@ "portal_timeout": "La fenêtre de partage du bureau n'a pas répondu à temps.", "portal_unreachable": "Le service de partage du bureau est injoignable : {detail}", "portal_failed": "Le service de partage du bureau a répondu de façon inattendue : {detail}", + "portal_unsupported": "Ce système n'a pas de portail de bureau : choisissez un écran dans la liste.", "encoder_failed": "L'encodeur vidéo est indisponible : {detail}", "playback_failed": "Le fichier de test est illisible : {detail}", "pattern_too_small": "Une mire de {width}×{height} est trop petite.", diff --git a/nix/libvpx.nix b/nix/libvpx.nix index ea97824..8bc1593 100644 --- a/nix/libvpx.nix +++ b/nix/libvpx.nix @@ -45,6 +45,12 @@ stdenv.mkDerivation (finalAttrs: { # Left to itself, configure may pick the GNU assembler, which cannot read # the nasm syntax of the .asm files. "--as=nasm" + ] + # Windows (#93): a static library, linked into the .exe by mingw-w64. + ++ lib.optionals stdenv.hostPlatform.isWindows [ + "--target=x86_64-win64-gcc" + "--disable-shared" + "--enable-static" ]; enableParallelBuilding = true; @@ -53,6 +59,15 @@ stdenv.mkDerivation (finalAttrs: { description = "Reference VP8/VP9 encoder and decoder"; homepage = "https://www.webmproject.org/"; license = lib.licenses.bsd3; - platforms = lib.platforms.unix; + platforms = lib.platforms.unix ++ lib.platforms.windows; }; +} +// lib.optionalAttrs stdenv.hostPlatform.isWindows { + # libvpx's configure is not autoconf: it rejects --build and --host, and + # takes the cross compiler from CROSS and the platform from --target. Only + # for Windows, so the Linux library keeps its hash and its cache. + configurePlatforms = [ ]; + preConfigure = '' + export CROSS=${stdenv.cc.targetPrefix} + ''; })