diff --git a/crates/automation/src/client.rs b/crates/automation/src/client.rs index fb9d2dfd4..c199a14c6 100644 --- a/crates/automation/src/client.rs +++ b/crates/automation/src/client.rs @@ -57,7 +57,7 @@ impl ControlClient { stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(io)?; let reader = BufReader::new(stream.try_clone().map_err(io)?); let mut client = Self { stream, broken: false, reader, next_id: 2 }; - // P3(platform-w6): pf.C-A2 — the failure kind is told from the `broken` flag. + // `exchange` marks the client broken on a transport failure only, so an error reply is a refusal. let auth = client.exchange(1, AUTH_METHOD, json!({"token": token})); auth.map_err(|e| if client.broken { ConnectError::Transport(e) } else { ConnectError::Refused(e) })?; Ok(client) diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index c6c963be2..c12ec1e28 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -123,6 +123,37 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { assert!(rx.try_recv().is_err(), "nothing was dispatched"); } +/// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line +/// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. +#[trial] +fn a_browser_post_never_reaches_the_app() { + // Far longer than the trial, so the close comes from the refusal, not the deadline. + let (rx, server) = server::serve_with_deadline(TcpListener::bind("127.0.0.1:0").expect("bound"), TOKEN.into(), host(), Duration::from_secs(60)) + .expect("started"); + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + let body = format!("{}\n{}\n", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}}), json!({"id": 2, "method": "test.ping"})); + write!(stream, "POST / HTTP/1.1\r\n").expect("written"); + let refused = read_json(&mut reader).expect("a reply to the request line"); + assert_eq!(refused["ok"], false, "{refused}"); + assert_eq!(refused["error"], "authentication required", "{refused}"); + // The rest of what the browser sends; the server may already have closed. + let _ = write!( + stream, + "Host: 127.0.0.1\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n{body}", + body.len() + ); + let _ = stream.flush(); + let mut rest = String::new(); + let closed = match reader.read_line(&mut rest) { + Ok(read) => read == 0, + Err(e) => !matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut), + }; + assert!(closed, "the connection closes after the refusal, answering nothing more: {rest:?}"); + assert!(rx.recv_timeout(Duration::from_millis(300)).is_err(), "nothing reached the app"); +} + /// A request line over `MAX_REQUEST_BYTES` without a newline gets an error reply and the connection is closed. #[trial] fn an_over_long_request_is_refused_and_closes_the_connection() { diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 35598a92b..5bb2cb0f4 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -32,10 +32,14 @@ struct Rig { passes: Rc>>, } -/// Document points are screen points doubled, as a canvas at 50 % shows them. -// P3(platform-w6): S-L162 -fn map(_page: usize, at: Pos2) -> Option { - Some(pos2(at.x / 2.0, at.y / 2.0)) +/// Screen points between one page's top and the next's, in a canvas that stacks its pages down the screen. +const PAGE_STEP: f32 = 200.0; + +/// Document points are screen points doubled, as a canvas at 50 % shows them, with each page [`PAGE_STEP`] below +/// the one before. +fn map(page: usize, at: Pos2) -> Option { + let page = u16::try_from(page).ok()?; + Some(pos2(at.x / 2.0, at.y / 2.0 + f32::from(page) * PAGE_STEP)) } impl Rig { @@ -110,6 +114,8 @@ fn a_held_press_stays_down_until_its_release() { assert_eq!(rig.now().pos, Some(pos2(100.0, 50.0)), "the document point is mapped"); rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document"})); assert!(rig.now().primary_down && rig.now().pos == Some(pos2(150.0, 50.0)), "a move while held drags"); + rig.send("ui.move", json!({"x": 300, "y": 100, "coordinates": "document", "page": 1})); + assert_eq!(rig.now().pos, Some(pos2(150.0, 50.0 + PAGE_STEP)), "a document point is mapped on the page it names"); rig.send("ui.release", json!({})); assert!(!rig.now().primary_down, "the release lets it go"); rig.send("ui.click", json!({"x": 10, "y": 10})); @@ -209,7 +215,6 @@ fn injected_passes_are_the_passes_that_carry_a_step() { fn document_points_need_a_canvas() { let rig = Rig::new(); let host = rig.host(); - // P3(platform-w6): S-L162 let none = |_: usize, _: Pos2| None; let refused = input_method("ui.move", &json!({"x": 1, "y": 1, "coordinates": "document"}), &host, ViewportId::ROOT, &none); assert_eq!(refused, Some(Err(NO_DOCUMENT.to_owned()))); diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs index 43bbb4d7c..9052011b0 100644 --- a/crates/platform/src/appearance.rs +++ b/crates/platform/src/appearance.rs @@ -1,5 +1,6 @@ //! Desktop colour, contrast and motion preferences and GNOME's window-button layout through the -//! XDG Settings portal, plus the browser's contrast and motion media queries on the web. +//! XDG Settings portal, the system's animation setting on Windows and macOS, plus the browser's +//! contrast and motion media queries on the web. //! //! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback, //! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility. @@ -51,10 +52,27 @@ struct Shared { /// `XDG_CURRENT_DESKTOP` names GNOME; read once when the watcher starts. #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] gnome: bool, - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[cfg(not(target_arch = "wasm32"))] wake: Box, } impl Shared { + #[cfg(not(target_arch = "wasm32"))] + fn new(active: bool, wake: Box) -> Self { + Self { + value: AtomicU8::new(0), + contrast: AtomicU8::new(0), + motion: AtomicU8::new(0), + generation: AtomicU64::new(0), + active: AtomicBool::new(active), + settled: Mutex::new(false), + settled_changed: Condvar::new(), + layout: Mutex::new(None), + icons: Mutex::new(None), + #[cfg(all(unix, not(target_os = "macos")))] + gnome: is_gnome_session(&|k| std::env::var(k).ok()), + wake, + } + } fn get(&self) -> Option { match self.value.load(Ordering::Acquire) { 1 => Some(Theme::Dark), @@ -62,7 +80,7 @@ impl Shared { _ => None, } } - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[cfg(not(target_arch = "wasm32"))] fn settle(&self) { *self.settled.lock().unwrap_or_else(PoisonError::into_inner) = true; self.settled_changed.notify_all(); @@ -83,7 +101,7 @@ impl Shared { (self.wake)(); } } - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[cfg(not(target_arch = "wasm32"))] fn publish_code(&self, slot: &AtomicU8, code: u8) { if slot.swap(code, Ordering::AcqRel) == code { return; @@ -103,7 +121,7 @@ impl Shared { }, ); } - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[cfg(not(target_arch = "wasm32"))] fn publish_motion(&self, reduced: bool) { self.publish_code(&self.motion, if reduced { 2 } else { 1 }); } @@ -139,12 +157,18 @@ impl Shared { /// Cache reads never block the UI; callers should keep wake callbacks nonblocking. pub struct Watcher { shared: Arc, - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] - stop: async_channel::Sender<()>, - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] - worker: Option>, - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] - finished: std::sync::mpsc::Receiver<()>, + #[cfg(not(target_arch = "wasm32"))] + worker: Worker, +} +/// The thread that feeds a [`Watcher`], and how to stop it. +#[cfg(not(target_arch = "wasm32"))] +enum Worker { + /// Linux and the BSDs: the portal subscription, raced against `stop` on its own executor. + #[cfg(all(unix, not(target_os = "macos")))] + Portal { stop: async_channel::Sender<()>, worker: Option>, finished: std::sync::mpsc::Receiver<()> }, + /// Windows and macOS: the polling loop of `native`, which waits on `stop` between reads. + #[cfg(any(windows, target_os = "macos"))] + Native { stop: std::sync::mpsc::Sender<()>, finished: std::sync::mpsc::Receiver<()>, thread: Option> }, } impl Watcher { /// Start an active subscription, or return `None` on unsupported targets or worker failure. @@ -155,12 +179,22 @@ impl Watcher { /// Start observing with explicit control over wake notifications. /// An inactive subscription still updates its cache. Unsupported targets and worker /// startup failure return `None`; browser targets never start a desktop watcher. + /// + /// Linux and the BSDs subscribe to the XDG Settings portal. Windows and macOS start a worker + /// that reads the system's animation setting once a second and answers + /// [`reduced_motion`](Self::reduced_motion) only: theme and contrast stay `None` there. pub fn start_active(active: bool, wake: impl Fn() + Send + Sync + 'static) -> Option { #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] { Self::spawn(active, wake, portal::watch) } - #[cfg(not(all(unix, not(target_os = "macos"), not(target_arch = "wasm32"))))] + #[cfg(any(windows, target_os = "macos"))] + { + let shared = Arc::new(Shared::new(active, Box::new(wake))); + let (stop, finished, thread) = native::spawn(Arc::clone(&shared))?; + Some(Self { shared, worker: Worker::Native { stop, finished, thread: Some(thread) } }) + } + #[cfg(not(any(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")), windows, target_os = "macos")))] { let _ = (active, wake); None @@ -204,9 +238,8 @@ impl Watcher { /// without a desktop watcher. /// /// It comes over the same connection as the theme, a change runs the same wake callback, and - /// [`Watcher::wait_first`] returns after the first read of it. macOS and Windows have no - /// watcher: reading their settings needs platform bindings, and this crate forbids `unsafe`. - /// On the web use `browser_contrast`. + /// [`Watcher::wait_first`] returns after the first read of it. Always `None` on Windows and + /// macOS, whose watcher reads the animation setting only. On the web use `browser_contrast`. pub fn contrast(&self) -> Option { match self.shared.contrast.load(Ordering::Acquire) { 1 => Some(Contrast::Standard), @@ -214,12 +247,21 @@ impl Watcher { _ => None, } } - /// Whether the desktop asks for reduced motion, from the portal's `org.freedesktop.appearance` - /// `reduced-motion`, or GNOME's `org.gnome.desktop.interface` `enable-animations` (inverted) - /// when the portal has no `reduced-motion` key. `None` until one answers, when neither key - /// exists, and on targets without a desktop watcher. + /// Whether the system asks for reduced motion. /// - /// Wake and [`Watcher::wait_first`] behave as for [`Watcher::contrast`]. On the web use + /// - Linux and the BSDs: three portal keys, combined so that any one asking for reduced + /// motion wins: `org.freedesktop.appearance` `reduced-motion` (1), GNOME's + /// `org.gnome.desktop.interface` `enable-animations` (false) and KDE's + /// `org.kde.kdeglobals.KDE` `AnimationDurationFactor` (0). With no session bus, or when the + /// portal has none of the three, the user's `kdeglobals` and GTK `settings.ini` files under + /// `$XDG_CONFIG_HOME` (or `~/.config`) answer instead, read once. + /// - Windows: Settings › Accessibility › Visual effects › Animation effects (off), through + /// `UISettings`; nothing when the Windows Runtime can't be asked. + /// - macOS: System Settings › Accessibility › Display › Reduce motion, through `NSWorkspace`. + /// + /// Windows and macOS are read once a second, so a change shows within a second. `None` until + /// an answer arrives, when nothing answers, and on targets without a desktop watcher. Wake and + /// [`Watcher::wait_first`] behave as for [`Watcher::contrast`]. On the web use /// `browser_reduced_motion`. pub fn reduced_motion(&self) -> Option { match self.shared.motion.load(Ordering::Acquire) { @@ -231,7 +273,8 @@ impl Watcher { /// Block until the first answer is known, then return it; at most `timeout`. /// /// Returns early, with `current()`, when the portal is absent and the `gsettings` fallback - /// found nothing, or when the desktop reports no preference. Call it once while building the + /// found nothing, or when the desktop reports no preference; on Windows and macOS after the + /// first read of the animation setting, always with `None`. Call it once while building the /// first frame so a light desktop does not flash dark: /// /// ```ignore @@ -253,20 +296,7 @@ impl Watcher { wake: impl Fn() + Send + Sync + 'static, source: impl FnOnce(Arc) -> F + Send + 'static, ) -> Option { - let gnome = is_gnome_session(&|k| std::env::var(k).ok()); - let shared = Arc::new(Shared { - value: AtomicU8::new(0), - contrast: AtomicU8::new(0), - motion: AtomicU8::new(0), - generation: AtomicU64::new(0), - active: AtomicBool::new(active), - settled: Mutex::new(false), - settled_changed: Condvar::new(), - layout: Mutex::new(None), - icons: Mutex::new(None), - gnome, - wake: Box::new(wake), - }); + let shared = Arc::new(Shared::new(active, Box::new(wake))); let worker_shared = Arc::clone(&shared); let (stop, stopped) = async_channel::bounded::<()>(1); let (done, finished) = std::sync::mpsc::channel(); @@ -283,22 +313,39 @@ impl Watcher { let _ = done.send(()); }) .ok()?; - Some(Self { shared, stop, worker: Some(worker), finished }) + Some(Self { shared, worker: Worker::Portal { stop, worker: Some(worker), finished } }) } } impl Drop for Watcher { fn drop(&mut self) { self.set_active(false); - #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + #[cfg(not(target_arch = "wasm32"))] { self.shared.settle(); - self.stop.close(); - if let Some(worker) = self.worker.take() { - let _ = self.finished.recv_timeout(std::time::Duration::from_millis(100)); - // Acknowledgement precedes thread-local destructors. They can block too, so - // never join solely on the acknowledgement (or channel disconnection). - if worker.is_finished() { - let _ = worker.join(); + match &mut self.worker { + #[cfg(all(unix, not(target_os = "macos")))] + Worker::Portal { stop, worker, finished } => { + stop.close(); + if let Some(worker) = worker.take() { + let _ = finished.recv_timeout(std::time::Duration::from_millis(100)); + // Acknowledgement precedes thread-local destructors. They can block too, so + // never join solely on the acknowledgement (or channel disconnection). + if worker.is_finished() { + let _ = worker.join(); + } + } + } + #[cfg(any(windows, target_os = "macos"))] + Worker::Native { stop, finished, thread } => { + // The worker's wait between reads ends at once; a read already in an OS call + // can block, so after a bounded wait an unfinished worker is detached. + let _ = stop.send(()); + if let Some(thread) = thread.take() { + let _ = finished.recv_timeout(std::time::Duration::from_millis(100)); + if thread.is_finished() { + let _ = thread.join(); + } + } } } } @@ -345,5 +392,7 @@ fn is_gnome_session(var: &dyn Fn(&str) -> Option) -> bool { #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod files; +#[cfg(any(windows, target_os = "macos"))] +mod native; #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] mod portal; diff --git a/crates/platform/src/appearance/files.rs b/crates/platform/src/appearance/files.rs index 2204b3766..88c7f4b2c 100644 --- a/crates/platform/src/appearance/files.rs +++ b/crates/platform/src/appearance/files.rs @@ -1,10 +1,78 @@ //! Motion from the GNOME and KDE settings files, for a desktop whose portal does not answer. +//! +//! A bare window manager, or a session with no bus, has no portal to ask; the toolkits still +//! follow the user's own settings files, so those answer instead. +use std::io::Read as _; use std::path::Path; -/// Whether the desktop's settings files under `config_home` ask for reduced motion; `None` when they say nothing. -#[allow(dead_code)] // P3(platform-w6): pf.C-O4 +/// The most of a settings file that is read; they are a few kilobytes, and a bigger one is not a +/// settings file the toolkits wrote. +const CAP: u64 = 256 * 1024; + +/// Whether the desktop's settings files under `config_home` ask for reduced motion; `None` when +/// they say nothing. +/// +/// KDE Plasma's `kdeglobals` `[KDE] AnimationDurationFactor` (0 makes every animation instant) +/// and GTK's `gtk-4.0/settings.ini` and `gtk-3.0/settings.ini` `[Settings] gtk-enable-animations`. +/// Within a file the last value wins, as the toolkits read it; across files any one asking for +/// reduced motion wins. A file that is absent, over 256 KiB or not UTF-8 says nothing. pub(crate) fn reduced_motion_from_files(config_home: &Path) -> Option { - let _ = config_home; - todo!("pf.C-O4") + let text = |file: &str| read_capped(&config_home.join(file)); + let kde = text("kdeglobals").and_then(|t| ini_value(&t, "KDE", "AnimationDurationFactor").and_then(|v| v.parse::().ok()).and_then(kde_factor_reduces)); + let gtk = ["gtk-4.0/settings.ini", "gtk-3.0/settings.ini"] + .map(|file| text(file).and_then(|t| ini_value(&t, "Settings", "gtk-enable-animations").and_then(gtk_switch_reduces))); + let mut answer = None; + for reduced in std::iter::once(kde).chain(gtk).flatten() { + if reduced { + return Some(true); + } + answer = Some(false); + } + answer } + +/// KDE's `AnimationDurationFactor`, a factor on every animation's length, from the file or the +/// portal: reduced at 0 (or below); a non-finite factor is no answer. +pub(super) fn kde_factor_reduces(factor: f64) -> Option { + factor.is_finite().then_some(factor <= 0.0) +} + +/// GTK's switch, written as a boolean or 0/1: reduced when off. +fn gtk_switch_reduces(text: &str) -> Option { + match text.to_ascii_lowercase().as_str() { + "true" | "1" => Some(false), + "false" | "0" => Some(true), + _ => None, + } +} + +/// The value of `key` in `[section]` of a settings file in INI form, trimmed; the last one wins. +/// Comment lines (`#`, `;`) and keys outside any section don't count. +fn ini_value<'a>(text: &'a str, section: &str, key: &str) -> Option<&'a str> { + let mut inside = false; + let mut found = None; + for line in text.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) { + inside = name.trim() == section; + } else if inside + && !line.starts_with(['#', ';']) + && let Some((k, v)) = line.split_once('=') + && k.trim() == key + { + found = Some(v.trim()); + } + } + found +} + +/// A settings file's text; `None` when it is absent, over [`CAP`] or not UTF-8. +fn read_capped(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(CAP + 1).read_to_string(&mut text).ok()?; + (text.len() as u64 <= CAP).then_some(text) +} + +#[cfg(test)] +#[path = "files_tests.rs"] +mod files_tests; diff --git a/crates/platform/src/appearance/files_tests.rs b/crates/platform/src/appearance/files_tests.rs new file mode 100644 index 000000000..adc615e5e --- /dev/null +++ b/crates/platform/src/appearance/files_tests.rs @@ -0,0 +1,70 @@ +//! Behaviour tests of `appearance::files`. +// Unwrapping and expecting on failure is fine in tests, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use super::reduced_motion_from_files; +use std::path::{Path, PathBuf}; + +fn temp_config(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("craft-motion-files-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(d.join("gtk-4.0")).expect("gtk-4.0"); + std::fs::create_dir_all(d.join("gtk-3.0")).expect("gtk-3.0"); + d +} + +fn write(dir: &Path, file: &str, text: &str) { + std::fs::write(dir.join(file), text).expect("write settings file"); +} + +fn clear(dir: &Path) { + for file in ["kdeglobals", "gtk-4.0/settings.ini", "gtk-3.0/settings.ini"] { + let _ = std::fs::remove_file(dir.join(file)); + } +} + +// Without a portal, KDE's AnimationDurationFactor=0 and GTK's gtk-enable-animations=false each ask +// for reduced motion; the last value in a file wins, any file asking wins across files, and an +// absent, oversized or silent file says nothing. +#[test] +fn settings_files_answer_without_a_portal() { + let dir = temp_config("answer"); + assert_eq!(reduced_motion_from_files(&dir), None, "no files say nothing"); + + write(&dir, "kdeglobals", "[General]\nColorScheme=Breeze\n\n[KDE]\nAnimationDurationFactor=0\nSingleClick=false\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(true), "KDE's factor 0 makes animations instant"); + write(&dir, "kdeglobals", "[KDE]\nAnimationDurationFactor = 0.5\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(false), "a positive factor plays animations"); + write(&dir, "kdeglobals", "[KDE]\r\nAnimationDurationFactor=0\r\nAnimationDurationFactor=1\r\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(false), "the last value in a file wins"); + write(&dir, "kdeglobals", "[KDE]\nAnimationDurationFactor=1\nAnimationDurationFactor=0\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(true), "the last value in a file wins"); + for silent in [ + "[Other]\nAnimationDurationFactor=0\n", + "[KDE]\n#AnimationDurationFactor=0\n;AnimationDurationFactor=0\n", + "AnimationDurationFactor=0\n", + "[KDE]\nAnimationDurationFactor=fast\n", + "[KDE]\nAnimationDurationFactor=inf\n", + "[KDE]\nAnimationDurationFactor=NaN\n", + ] { + write(&dir, "kdeglobals", silent); + assert_eq!(reduced_motion_from_files(&dir), None, "{silent:?} says nothing"); + } + + clear(&dir); + write(&dir, "gtk-3.0/settings.ini", "[Settings]\ngtk-theme-name=Adwaita\ngtk-enable-animations=false\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(true), "GTK's switch off reduces motion"); + write(&dir, "gtk-4.0/settings.ini", "# written by hand\n[Settings]\ngtk-enable-animations=true\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(true), "one file asking for reduced motion is enough"); + write(&dir, "gtk-3.0/settings.ini", "[Settings]\ngtk-enable-animations=0\ngtk-enable-animations=1\n"); + assert_eq!(reduced_motion_from_files(&dir), Some(false), "every file that answers plays animations"); + + // A file over the 256 KiB cap is not a settings file the toolkit wrote: it says nothing. + clear(&dir); + let mut big = String::from("[KDE]\nAnimationDurationFactor=0\n"); + big.push_str(&"#".repeat(256 * 1024)); + write(&dir, "kdeglobals", &big); + assert_eq!(reduced_motion_from_files(&dir), None, "an oversized file is ignored"); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/platform/src/appearance/native.rs b/crates/platform/src/appearance/native.rs new file mode 100644 index 000000000..01ad092a7 --- /dev/null +++ b/crates/platform/src/appearance/native.rs @@ -0,0 +1,61 @@ +//! Windows and macOS: the system's animation setting, read on a worker thread once a second. +//! +//! Neither system offers a change notification through a safe binding, and the workspace forbids +//! `unsafe`, so the worker polls. Both reads are safe calls that need no main thread: +//! `UISettings` is a Windows Runtime object any thread may create, and `NSWorkspace`'s +//! accessibility query takes no `MainThreadMarker`. + +use super::Shared; +use std::{ + sync::{Arc, mpsc}, + thread::JoinHandle, + time::Duration, +}; + +/// How long a read answer stands before the system is asked again. +const REFRESH: Duration = Duration::from_secs(1); + +/// Starts the worker: it reads at once, publishes, settles `wait_first`, then reads again every +/// [`REFRESH`] until `stop` sends or is dropped. The returned receiver gets a message when the +/// worker has finished, so a drop can wait for it a bounded time. `None` when the thread can't be +/// spawned. +pub(super) fn spawn(shared: Arc) -> Option<(mpsc::Sender<()>, mpsc::Receiver<()>, JoinHandle<()>)> { + let (stop, stopped) = mpsc::channel::<()>(); + let (done, finished) = mpsc::channel::<()>(); + let thread = std::thread::Builder::new() + .name("desktop-appearance".into()) + .spawn(move || { + publish(&shared); + shared.settle(); + while let Err(mpsc::RecvTimeoutError::Timeout) = stopped.recv_timeout(REFRESH) { + publish(&shared); + } + let _ = done.send(()); + }) + .ok()?; + Some((stop, finished, thread)) +} + +/// A read that fails publishes nothing, so the last answer stands. +fn publish(shared: &Shared) { + if let Some(reduced) = reduced_motion() { + shared.publish_motion(reduced); + } +} + +/// Whether Windows has animation effects off; `None` when the Windows Runtime can't be asked (some +/// sessions have none). +#[cfg(windows)] +fn reduced_motion() -> Option { + windows::UI::ViewManagement::UISettings::new() + .and_then(|settings| settings.AnimationsEnabled()) + .map(|enabled| !enabled) + .map_err(|e| log::debug!("system animation setting: {e}")) + .ok() +} + +/// Whether macOS has Reduce motion on. +#[cfg(target_os = "macos")] +fn reduced_motion() -> Option { + Some(objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()) +} diff --git a/crates/platform/src/appearance/portal.rs b/crates/platform/src/appearance/portal.rs index cf3d3087d..fb52d3a54 100644 --- a/crates/platform/src/appearance/portal.rs +++ b/crates/platform/src/appearance/portal.rs @@ -1,8 +1,9 @@ //! The XDG Settings portal: reading colour scheme, contrast, motion, button layout and icons, and watching for changes. +use super::files::{kde_factor_reduces, reduced_motion_from_files}; use super::{Contrast, Shared, Theme}; use futures_lite::{StreamExt, future::zip}; -use std::{sync::Arc, time::Duration}; +use std::{path::PathBuf, sync::Arc, time::Duration}; use zbus::zvariant::{OwnedValue, Value}; const DEST: &str = "org.freedesktop.portal.Desktop"; const PATH: &str = "/org/freedesktop/portal/desktop"; @@ -16,6 +17,8 @@ const ICONS_KEY: &str = "icon-theme"; const CONTRAST_KEY: &str = "contrast"; const MOTION_KEY: &str = "reduced-motion"; const ANIMATIONS_KEY: &str = "enable-animations"; +const KDE: &str = "org.kde.kdeglobals.KDE"; +const KDE_MOTION_KEY: &str = "AnimationDurationFactor"; const TIMEOUT: Duration = Duration::from_secs(2); // Outer None means unknown/malformed; Some(None) is an explicit no-preference answer. @@ -60,11 +63,15 @@ fn contrast_reply(value: &Value<'_>, legacy: bool) -> Option { decode_contrast(STANDARD, unwrap_legacy(value, legacy)?) } // Whether motion is reduced: the portal's `reduced-motion` (1 reduced; other values are no -// preference) or GNOME's `enable-animations` boolean, inverted. `None` means malformed. +// preference), GNOME's `enable-animations` boolean, inverted, or KDE's `AnimationDurationFactor` +// (0 makes every animation instant). `None` means malformed. fn decode_motion(namespace: &str, value: &Value<'_>) -> Option { match (namespace, value) { (STANDARD, Value::U32(n)) => Some(*n == 1), (GNOME, Value::Bool(enabled)) => Some(!enabled), + (KDE, Value::F64(factor)) => kde_factor_reduces(*factor), + // KConfig hands an entry read without a type over as its text. + (KDE, Value::Str(text)) => text.as_str().trim().parse::().ok().and_then(kde_factor_reduces), _ => None, } } @@ -131,17 +138,35 @@ fn owner_rule() -> zbus::Result> { .arg(0, DEST)? .build()) } -/// The one-shot `gsettings` reads used when the portal can't answer, each at most once per -/// watcher, and the `PATH` they search. +/// The one-shot reads used when the portal can't answer, each at most once per watcher: the +/// `gsettings` reads and the `PATH` they search, and the motion settings files under the config +/// folder. pub(super) struct Fallbacks { theme_used: bool, layout_used: bool, icons_used: bool, + motion_used: bool, path: Option, + /// `$XDG_CONFIG_HOME`, or `~/.config` when that is empty or unset. + config_home: Option, } impl Fallbacks { fn from_env() -> Self { - Self { theme_used: false, layout_used: false, icons_used: false, path: std::env::var_os("PATH") } + let config_home = std::env::var_os("XDG_CONFIG_HOME") + .filter(|dir| !dir.is_empty()) + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").filter(|home| !home.is_empty()).map(|home| PathBuf::from(home).join(".config"))); + Self { theme_used: false, layout_used: false, icons_used: false, motion_used: false, path: std::env::var_os("PATH"), config_home } + } + /// The settings files' motion answer, for a session with no bus or a portal that knows none + /// of the three motion keys. + fn motion(&mut self, shared: &Shared) { + if std::mem::replace(&mut self.motion_used, true) { + return; + } + if let Some(reduced) = self.config_home.as_deref().and_then(reduced_motion_from_files) { + shared.publish_motion(reduced); + } } async fn get(&self, schema: &str, key: &str) -> Option { let exe = gsettings_exe(self.path.as_deref())?; @@ -206,6 +231,8 @@ async fn session(shared: &Shared, fallbacks: &mut Fallbacks, connected: &mut boo Err(_) => None, }; let Some(connection) = connection else { + // Motion first: it is a file read, and `wait_first` settles with the theme. + fallbacks.motion(shared); fallbacks.theme(shared).await; fallbacks.layout(shared).await; fallbacks.icons(shared).await; @@ -217,19 +244,31 @@ enum Event { Setting(zbus::Result), Owner(zbus::Result), } -/// The latest valid answer from each source of a setting that combines two namespaces. +/// The latest valid answer from each source of a setting that combines several namespaces. struct Answers { standard: Option>, gnome: Option>, motion: Option, gnome_motion: Option, + kde_motion: Option, } impl Answers { + /// The three motion keys as one: any asking for reduced motion wins, then any answering at + /// all; `None` when none answers. + fn reduced_motion(&self) -> Option { + let answers = [self.motion, self.gnome_motion, self.kde_motion]; + if answers.contains(&Some(true)) { Some(true) } else { answers.into_iter().flatten().next() } + } fn publish_motion(&self, shared: &Shared) { - if let Some(reduced) = self.motion.or(self.gnome_motion) { + if let Some(reduced) = self.reduced_motion() { shared.publish_motion(reduced); } } + /// Replaces the three motion answers with a fresh read and publishes them. + fn reread_motion(&mut self, shared: &Shared, (motion, gnome_motion, kde_motion): MotionReads) { + (self.motion, self.gnome_motion, self.kde_motion) = (motion, gnome_motion, kde_motion); + self.publish_motion(shared); + } /// Apply one `SettingChanged`; malformed values and other settings change nothing. fn apply(&mut self, shared: &Shared, namespace: &str, key: &str, value: &Value<'_>) { match (namespace, key) { @@ -248,12 +287,12 @@ impl Answers { shared.publish_contrast(contrast); } } - (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) => { + (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) | (KDE, KDE_MOTION_KEY) => { let Some(reduced) = decode_motion(namespace, value) else { return }; - if namespace == STANDARD { - self.motion = Some(reduced); - } else { - self.gnome_motion = Some(reduced); + match namespace { + STANDARD => self.motion = Some(reduced), + GNOME => self.gnome_motion = Some(reduced), + _ => self.kde_motion = Some(reduced), } self.publish_motion(shared); } @@ -272,6 +311,22 @@ impl Answers { } } } +/// The three motion keys as read: the portal's, GNOME's and KDE's. +type MotionReads = (Option, Option, Option); +async fn read_motion(connection: &zbus::Connection) -> MotionReads { + let (motion, (gnome_motion, kde_motion)) = zip( + read_with(connection, STANDARD, MOTION_KEY, |value, legacy| motion_reply(STANDARD, value, legacy)), + zip( + read_with(connection, GNOME, ANIMATIONS_KEY, |value, legacy| motion_reply(GNOME, value, legacy)), + read_with(connection, KDE, KDE_MOTION_KEY, |value, legacy| motion_reply(KDE, value, legacy)), + ), + ) + .await; + (motion, gnome_motion, kde_motion) +} +fn is_motion_key(namespace: &str, key: &str) -> bool { + matches!((namespace, key), (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) | (KDE, KDE_MOTION_KEY)) +} async fn subscribe(connection: &zbus::Connection, rule: zbus::Result>, capacity: usize) -> Option { bounded(zbus::MessageStream::for_match_rule(rule.ok()?, connection, Some(capacity))).await?.ok() } @@ -295,26 +350,25 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: subscribe(&connection, rule(CONTRAST_KEY), 8).await?, subscribe(&connection, rule(MOTION_KEY), 8).await?, subscribe(&connection, rule(ANIMATIONS_KEY), 8).await?, + subscribe(&connection, rule(KDE_MOTION_KEY), 8).await?, ]; let mut owners = subscribe(&connection, owner_rule(), 8).await?; // Concurrent reads, so contrast and motion are known by the time the theme settles // `wait_first` without adding round trips before it. - let ((standard, gnome), (contrast, (motion, gnome_motion))) = zip( + let ((standard, gnome), (contrast, (motion, gnome_motion, kde_motion))) = zip( zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)), - zip( - read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), - zip( - read_with(&connection, STANDARD, MOTION_KEY, |value, legacy| motion_reply(STANDARD, value, legacy)), - read_with(&connection, GNOME, ANIMATIONS_KEY, |value, legacy| motion_reply(GNOME, value, legacy)), - ), - ), + zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)), ) .await; - let mut answers = Answers { standard, gnome, motion, gnome_motion }; + let mut answers = Answers { standard, gnome, motion, gnome_motion, kde_motion }; if let Some(contrast) = contrast { shared.publish_contrast(contrast); } - answers.publish_motion(shared); + match answers.reduced_motion() { + Some(reduced) => shared.publish_motion(reduced), + // A portal that knows none of the keys (a bare window manager's) leaves the files to answer. + None => fallbacks.motion(shared), + } match combined(standard, gnome) { Some(answer) => { *connected = true; @@ -350,17 +404,75 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: Event::Setting(message) => message.ok()?, }; if let Ok((namespace, key, value)) = message.body().deserialize::<(String, String, OwnedValue)>() { - answers.apply(shared, &namespace, &key, &value); + if is_motion_key(&namespace, &key) { + // KDE announces a new animation speed only as `reduced-motion`, and its own key has + // no value while the speed is at its default, so all three keys are read again + // rather than kept at what they last said; one answer is published per change. + answers.reread_motion(shared, read_motion(&connection).await); + } else { + answers.apply(shared, &namespace, &key, &value); + } } } } #[cfg(test)] mod tests { - use super::{GNOME, STANDARD, decode}; + use super::{ANIMATIONS_KEY, Answers, GNOME, KDE, KDE_MOTION_KEY, MOTION_KEY, STANDARD, decode, decode_motion}; use crate::appearance::is_gnome_session; use crate::appearance::{Theme, Watcher}; use std::time::Duration; use zbus::zvariant::Value; + // The portal's, GNOME's and KDE's keys each decode to reduced or not; malformed values say + // nothing. Combined, any one asking for reduced motion wins, all answering otherwise is not + // reduced, and none answering publishes nothing. + #[test] + fn motion_answers_combine_any_off_wins() -> Result<(), Box> { + assert_eq!(decode_motion(STANDARD, &Value::U32(1)), Some(true)); + assert_eq!(decode_motion(STANDARD, &Value::U32(0)), Some(false)); + assert_eq!(decode_motion(STANDARD, &Value::U32(2)), Some(false), "a value not defined yet is no preference"); + assert_eq!(decode_motion(GNOME, &Value::Bool(false)), Some(true), "GNOME's switch is inverted"); + assert_eq!(decode_motion(GNOME, &Value::Bool(true)), Some(false)); + assert_eq!(decode_motion(KDE, &Value::F64(0.0)), Some(true), "KDE's factor 0 makes animations instant"); + assert_eq!(decode_motion(KDE, &Value::F64(0.5)), Some(false)); + assert_eq!(decode_motion(KDE, &Value::from("0")), Some(true)); + for malformed in [Value::F64(f64::NAN), Value::F64(f64::INFINITY), Value::from("fast"), Value::Bool(false)] { + assert_eq!(decode_motion(KDE, &malformed), None, "{malformed:?} is malformed"); + } + assert_eq!(decode_motion(STANDARD, &Value::Bool(true)), None); + assert_eq!(decode_motion(GNOME, &Value::U32(0)), None); + + let (send, sent) = std::sync::mpsc::channel(); + let watcher = Watcher::spawn( + false, + || {}, + move |shared| async move { + let _ = send.send(shared); + }, + ) + .ok_or("worker creation failed")?; + let shared = sent.recv_timeout(Duration::from_secs(2))?; + let mut answers = Answers { standard: None, gnome: None, motion: None, gnome_motion: None, kde_motion: None }; + answers.apply(&shared, KDE, "SingleClick", &Value::F64(0.0)); + answers.apply(&shared, KDE, KDE_MOTION_KEY, &Value::from("fast")); + assert_eq!(watcher.reduced_motion(), None, "no key answered, so nothing is published"); + + let keys = [ + (STANDARD, MOTION_KEY, Value::U32(1), Value::U32(0)), + (GNOME, ANIMATIONS_KEY, Value::Bool(false), Value::Bool(true)), + (KDE, KDE_MOTION_KEY, Value::F64(0.0), Value::F64(1.0)), + ]; + for (namespace, key, _, not_reduced) in &keys { + answers.apply(&shared, namespace, key, not_reduced); + } + assert_eq!(watcher.reduced_motion(), Some(false), "every key answering 'not reduced' is not reduced"); + for (namespace, key, reduced, not_reduced) in &keys { + answers.apply(&shared, namespace, key, reduced); + assert_eq!(watcher.reduced_motion(), Some(true), "{namespace} {key} alone asking for reduced motion wins"); + answers.apply(&shared, namespace, key, not_reduced); + assert_eq!(watcher.reduced_motion(), Some(false), "{namespace} {key} back to 'not reduced'"); + } + Ok(()) + } #[test] fn gnome_light_setting_reads_as_light_and_zero_is_no_preference_elsewhere() { assert_eq!(decode(GNOME, &Value::from("default"), true), Some(Some(Theme::Light))); diff --git a/crates/platform/src/default_app_tests.rs b/crates/platform/src/default_app_tests.rs index b6ec0e9ae..aa706ba72 100644 --- a/crates/platform/src/default_app_tests.rs +++ b/crates/platform/src/default_app_tests.rs @@ -2,6 +2,26 @@ use crate::default_app::path_from_arg; +// XDG_DATA_HOME (else ~/.local/share) comes first, then each XDG_DATA_DIRS entry (else +// /usr/local/share:/usr/share); relative and empty entries are skipped, and no home is fine. +// Absolute here means a Unix path, so the trial runs on Unix. +#[cfg(unix)] +#[test] +fn application_dirs_follow_the_xdg_spec() { + use crate::default_app::application_dirs; + let p = |s: &str| std::path::PathBuf::from(s); + assert_eq!( + application_dirs(None, None, Some("/home/a")), + [p("/home/a/.local/share/applications"), p("/usr/local/share/applications"), p("/usr/share/applications")] + ); + assert_eq!( + application_dirs(Some("/data"), Some("/opt/share::relative:/usr/share"), Some("/home/a")), + [p("/data/applications"), p("/opt/share/applications"), p("/usr/share/applications")] + ); + assert_eq!(application_dirs(Some(""), Some(""), None), [p("/usr/local/share/applications"), p("/usr/share/applications")]); + assert_eq!(application_dirs(Some("rel"), None, Some("also-rel")), [p("/usr/local/share/applications"), p("/usr/share/applications")]); +} + // file:///a%20b.pdf and file://localhost/x decode to paths; http://, file://host/x, plain paths // and non-UTF-8 escapes pass through; file:///C:/x.pdf is C:/x.pdf on Windows. #[test] diff --git a/crates/platform/src/logs/crash.rs b/crates/platform/src/logs/crash.rs index 5e0f8e7ae..96249345b 100644 --- a/crates/platform/src/logs/crash.rs +++ b/crates/platform/src/logs/crash.rs @@ -8,7 +8,8 @@ //! //! The crash log is `/crash-.log`, appended to, one entry per panic: //! `=== (unix )`, the summary, the backtrace. On the web there is no file; -//! the previous hook still prints to the browser console. +//! the previous hook still prints to the browser console. Text a panic message quotes between +//! backticks is left out everywhere the message goes: it can be the user's writing. //! //! ```ignore //! crash::install("PhotoCraft", env!("CARGO_PKG_VERSION"), Some(log_dir)); @@ -66,7 +67,8 @@ fn write_log(_summary: &str) {} /// A panic caught by [`catch`]. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Panicked { - /// The panic message (`"panic"` when it carried no text). + /// The panic message with its backticked spans replaced by `…` (`"panic"` when it carried no + /// text). pub message: String, } @@ -82,34 +84,64 @@ impl std::error::Error for Panicked {} /// Install the panic hook, once per process; later calls only change `app`, `version` and the /// crash log directory (`None`: standard error and the log only, as on the web and in tests). /// -/// The hook stores ` (at :, thread )` for [`take_last`], logs it with -/// `log::error!(" internal error: …")`, appends it with a forced backtrace to the crash log, -/// then calls the previous hook, so the panic still reaches standard error or the console. +/// The hook stores ` (at :, thread )` for [`take_last`], with the +/// message's backticked spans replaced by `…` (std quotes the text it was handling there, which +/// can be the user's), and appends it with a forced backtrace +/// to the crash log. It reports the summary once as ` internal error: …`: through +/// `log::error!` when a logger takes errors (the app's logger also prints it to standard error), +/// otherwise straight to standard error. On the web it logs and then calls the previous hook, so +/// the panic still reaches the browser console. pub fn install(app: &'static str, version: &'static str, dir: Option) { // filmcraft: crates/ui-egui/src/crash.rs:15 with pc: apps/photocraft/src/crash_guard.rs:11 (log::error!) *lock(&STATE) = Some(State { app, version, dir }); static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { + #[cfg(target_arch = "wasm32")] let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - let message = payload_message(info.payload()); + let message = redact_quoted(&payload_message(info.payload())); let at = info.location().map(|l| format!("{}:{}", l.file(), l.line())).unwrap_or_default(); let thread = std::thread::current().name().unwrap_or("unnamed").to_owned(); let summary = format!("{message} (at {at}, thread {thread})"); *lock(&LAST) = Some(summary.clone()); let app = lock(&STATE).as_ref().map_or("app", |s| s.app); - log::error!("{app} internal error: {summary}"); - write_log(&summary); - prev(info); + #[cfg(not(target_arch = "wasm32"))] + { + if log::log_enabled!(log::Level::Error) { + log::error!("{app} internal error: {summary}"); + } else { + use std::io::Write as _; + // `eprintln!` panics on a closed standard error, and a panic inside the hook aborts. + let _ = writeln!(std::io::stderr(), "{app} internal error: {summary}"); + } + write_log(&summary); + } + #[cfg(target_arch = "wasm32")] + { + log::error!("{app} internal error: {summary}"); + prev(info); + } })); }); } -/// `message` with each backticked span replaced by `…`, so a panic text carries no quoted user data. -#[allow(dead_code)] // P3(platform-w6): pf.C-O5 +/// `message` with each backticked span replaced by `…`, so a panic text carries no quoted user +/// data: std quotes the string it was slicing (``byte index 5 is not a char boundary; … of `` ``), and that string can be the user's writing. An unpaired backtick leaves the rest +/// of the message out too. fn redact_quoted(message: &str) -> String { - let _ = message; - todo!("pf.C-O5") + let mut out = String::with_capacity(message.len()); + for (i, part) in message.split('`').enumerate() { + if i % 2 == 1 { + out.push_str("`…"); + } else { + if i > 0 { + out.push('`'); + } + out.push_str(part); + } + } + out } /// Write a fatal error that isn't a panic (the window could not be created) to the crash log. @@ -137,12 +169,14 @@ pub fn log_path() -> Option { None } -/// Run `f`; a panic inside it is logged by the hook and comes back as [`Panicked`]. The caller -/// reports that error, so the panic is not kept for [`take_last`] as well. +/// Run `f`; a panic inside it is logged by the hook and comes back as [`Panicked`], its message +/// redacted as the hook redacts it. The caller reports that error, so the panic is not kept for +/// [`take_last`] as well. pub fn catch(f: impl FnOnce() -> T) -> Result { // pc: apps/photocraft/src/crash_guard.rs:20 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(|payload| { - let message = payload_message(&*payload); + // The hook stored the redacted message; comparing the raw one would keep a quoted panic. + let message = redact_quoted(&payload_message(&*payload)); let mut last = lock(&LAST); if last.as_deref().is_some_and(|summary| summary.starts_with(&message)) { *last = None; diff --git a/crates/platform/src/logs/crash_tests.rs b/crates/platform/src/logs/crash_tests.rs index 649cc691a..492115215 100644 --- a/crates/platform/src/logs/crash_tests.rs +++ b/crates/platform/src/logs/crash_tests.rs @@ -1,10 +1,19 @@ //! Behaviour tests of `logs::crash`. use super::*; +/// The hook, its crash log directory and the last-panic slot are process-wide; trials that +/// install and panic take turns. +#[cfg(not(target_arch = "wasm32"))] +fn serial() -> MutexGuard<'static, ()> { + static SERIAL: Mutex<()> = Mutex::new(()); + lock(&SERIAL) +} + // A panic on a named worker thread is kept for take_last with its message and thread, and appended to the crash log. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_worker_panic_is_kept_and_written_to_the_crash_log() { + let _serial = serial(); let dir = std::env::temp_dir().join(format!("craft-crash-{}", std::process::id())); install("CrashTest", "1.2.3", Some(dir.clone())); let _ = take_last(); @@ -21,3 +30,43 @@ fn a_worker_panic_is_kept_and_written_to_the_crash_log() { assert!(std::fs::read_to_string(&path).expect("crash log").contains("window could not be created")); let _ = std::fs::remove_dir_all(dir); } + +// Text a panic quotes between backticks (std quotes the string it was slicing, which can be the +// user's writing) reaches neither take_last, the crash log nor the Panicked that catch returns; +// an unpaired backtick hides the rest, a message without backticks is unchanged, and catch still +// leaves a quoted panic out of take_last. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_panic_report_leaves_out_quoted_text() { + let _serial = serial(); + let dir = std::env::temp_dir().join(format!("craft-crash-quoted-{}", std::process::id())); + install("CrashTest", "1.2.3", Some(dir.clone())); + let _ = take_last(); + let secret = "Dear Ms Smith"; + let joined = std::thread::Builder::new() + .name("crash-quoted-worker".into()) + .spawn(move || panic!("byte index 5 is not a char boundary; it is inside 'é' (bytes 4..6) of `{secret}`")) + .expect("spawn") + .join(); + assert!(joined.is_err()); + let last = take_last().expect("the hook kept the panic"); + assert!(last.starts_with("byte index 5 is not a char boundary") && last.contains("of `…` (at "), "{last}"); + assert!(!last.contains(secret), "{last}"); + let log = std::fs::read_to_string(log_path().expect("crash log path")).expect("crash log"); + assert!(log.contains("of `…` (at ") && !log.contains(secret), "{log}"); + + let caught = catch(|| -> u8 { panic!("of `{secret}` and `more`") }); + let message = caught.expect_err("the closure panicked").message; + assert!(message.starts_with("of `…`") && message.contains(" and "), "the text outside the backticks stays: {message}"); + assert!(!message.contains(secret) && !message.contains("more"), "{message}"); + assert!(take_last().is_none(), "a caught quoted panic is reported once, by the caller"); + let caught = catch(|| -> u8 { panic!("of `half a sentence that {secret} wrote") }); + let message = caught.expect_err("the closure panicked").message; + assert!(message.starts_with("of `") && !message.contains("half a sentence") && !message.contains(secret), "an unpaired backtick hides the rest: {message}"); + assert!(take_last().is_none()); + let plain = "index out of bounds: the len is 3 but the index is 5"; + let caught = catch(|| -> u8 { panic!("{plain}") }); + assert_eq!(caught.map_err(|p| p.message), Err(plain.to_owned()), "a message without backticks is unchanged"); + assert!(take_last().is_none()); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/platform/src/logs_tests.rs b/crates/platform/src/logs_tests.rs index 420b110d9..8a61b9e26 100644 --- a/crates/platform/src/logs_tests.rs +++ b/crates/platform/src/logs_tests.rs @@ -20,6 +20,159 @@ fn read(path: &Path) -> String { std::fs::read_to_string(path).expect("read log") } +// Directives follow env_logger: the most specific matching one wins, at `::` boundaries or as a +// `*` prefix, a bare target turns everything on, levels are case-blind; a hostile spec never +// panics and an unusable part is skipped, leaving errors only for the targets it would have named. +#[test] +fn filter_directives_follow_env_logger_and_hostile_specs_never_panic() { + let f = Filter::parse("info,wgpu_core=error,photocraft_pdf=trace,photocraft_pdf::fonts=off"); + assert_eq!(f.level_for("eframe"), LevelFilter::Info); + assert_eq!(f.level_for("wgpu_core::instance"), LevelFilter::Error); + assert_eq!(f.level_for("photocraft_pdf::images"), LevelFilter::Trace); + assert_eq!(f.level_for("photocraft_pdf::fonts"), LevelFilter::Off, "the longer directive wins"); + assert_eq!(f.max(), LevelFilter::Trace); + assert_eq!(f.level_for("wgpu_core_extra"), LevelFilter::Info, "a module name matches at `::` boundaries, not as a bare prefix"); + assert_eq!(Filter::parse("photocraft*=debug").level_for("photocraft_layout::lines"), LevelFilter::Debug); + assert_eq!(Filter::parse("photocraft*=debug").level_for("eframe"), LevelFilter::Error); + assert_eq!(Filter::parse("naga").level_for("naga::front"), LevelFilter::Trace, "a bare target turns everything from it on"); + assert_eq!(Filter::parse("naga").level_for("eframe"), LevelFilter::Error); + assert_eq!(Filter::parse(" WARN , photocraft = Debug ").level_for("photocraft"), LevelFilter::Debug); + assert_eq!(Filter::parse(" WARN , photocraft = Debug ").level_for("eframe"), LevelFilter::Warn); + let defaults = Filter::parse(&NAMES.default_filter()); + assert_eq!(defaults.level_for("photocraft_gpu::device"), LevelFilter::Info); + assert_eq!(defaults.level_for("wgpu_core::device"), LevelFilter::Warn); + + let long = "x".repeat(100_000); + let many = "a=info,".repeat(10_000); + for spec in + ["", ",,,", "=", "==", "=debug", "photocraft=", "nonsense=loud", "🦀=info", "*", "*=", "=*", "a=b=c", "\0", "é::ü=trace", &long, &many] + { + let f = Filter::parse(spec); + for target in ["", "photocraft", "🦀", "a::b", "*"] { + let _ = f.level_for(target); + } + let _ = f.max(); + } + assert_eq!(Filter::parse("warn,,photocraft=DEBUG").level_for("photocraft"), LevelFilter::Debug); + assert_eq!(Filter::parse("nonsense=loud").level_for("nonsense"), LevelFilter::Error, "an unknown level is skipped"); + assert_eq!(Filter::parse("photocraft=").level_for("photocraft"), LevelFilter::Error); + assert_eq!(Filter::parse("=debug").max(), LevelFilter::Error, "a directive without a target is skipped"); + assert_eq!(Filter::parse("🦀=info").level_for("🦀::claw"), LevelFilter::Info); +} + +// The hand-rolled civil-from-days calendar gives UTC dates with milliseconds at the epoch, leap +// days (2000 is a leap year, 2100 is not), year ends and years past 9999; a clock before 1970 +// reads as the epoch. +#[test] +fn timestamps_are_utc_with_milliseconds() { + use std::time::Duration; + use web_time::UNIX_EPOCH; + assert_eq!(timestamp(UNIX_EPOCH), "1970-01-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_791_446_357_728)), "2026-10-08T07:59:17.728Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_164_800)), "2024-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_199)), "2024-02-29T23:59:59.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_709_251_200)), "2024-03-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_millis(1_735_689_599_999)), "2024-12-31T23:59:59.999Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(1_735_689_600)), "2025-01-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(951_782_400)), "2000-02-29T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(4_107_542_400)), "2100-03-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH - Duration::from_secs(5)), "1970-01-01T00:00:00.000Z"); + assert_eq!(timestamp(UNIX_EPOCH + Duration::from_secs(253_402_300_800)), "10000-01-01T00:00:00.000Z"); +} + +// Before attach, lines up to MAX_PENDING are kept and written on attach, the overflow becomes one +// drop note, exactly a full buffer drops nothing, later lines follow, and once no file will come +// nothing is kept. +#[test] +fn the_pending_buffer_is_bounded_and_says_how_much_it_dropped() { + let dir = temp_dir("bounded"); + let LogFile { path, file, .. } = rotate(&dir, NAMES).expect("rotate"); + let overflow = 5; + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING + overflow { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + sink.write("late\n"); + let text = read(&path); + assert_eq!(text.lines().filter(|l| l.starts_with("line ")).count(), MAX_PENDING); + assert_eq!(text.matches("earlier log lines were dropped").count(), 1, "{text}"); + assert!(text.contains(&format!("{overflow} earlier log lines were dropped")), "{text}"); + assert!(text.starts_with("line 0\n") && !text.contains(&format!("line {MAX_PENDING}\n")), "the first lines are kept"); + assert!(text.ends_with("late\n"), "{text}"); + let _ = std::fs::remove_dir_all(&dir); + + let dir = temp_dir("full"); + let LogFile { path, file, .. } = rotate(&dir, NAMES).expect("rotate"); + let mut sink = Sink::new(MAX_FILE_BYTES); + for i in 0..MAX_PENDING { + sink.write(&format!("line {i}\n")); + } + sink.attach(file); + let text = read(&path); + assert_eq!(text.lines().count(), MAX_PENDING); + assert!(!text.contains("dropped"), "exactly a full buffer drops nothing"); + let _ = std::fs::remove_dir_all(&dir); + + let mut sink = Sink::new(MAX_FILE_BYTES); + sink.write("early\n"); + sink.close(); + for _ in 0..MAX_PENDING + 1 { + sink.write("late\n"); + } + assert!(sink.pending.is_empty() && sink.dropped == 0, "without a file nothing is kept"); +} + +// A sink attached to a file stops at max_bytes: the line that would pass it is replaced by one +// note and nothing follows. +#[test] +fn the_file_stops_at_its_size_cap_with_one_note() { + let dir = temp_dir("cap"); + let LogFile { path, file, .. } = rotate(&dir, NAMES).expect("rotate"); + let mut sink = Sink::new(100); + sink.attach(file); + for i in 0..50 { + sink.write(&format!("line {i:02} with some padding\n")); + } + let text = read(&path); + let written: usize = text.lines().filter(|l| l.starts_with("line ")).map(|l| l.len() + 1).sum(); + assert!(written > 0 && written <= 100, "the lines before the note fit the cap: {text}"); + assert!(text.lines().filter(|l| l.starts_with("line ")).count() < 50, "the cap cut the writing off: {text}"); + assert_eq!(text.matches("log file reached").count(), 1, "{text}"); + let after_note = text.lines().skip_while(|l| !l.contains("log file reached")).skip(1).count(); + assert_eq!(after_note, 0, "nothing follows the note: {text}"); + let _ = std::fs::remove_dir_all(&dir); +} + +// Eight threads logging through one AppLogger leave 800 whole lines in its file, none torn. +#[test] +fn records_from_many_threads_are_whole_lines() { + use log::Log; + let dir = temp_dir("threads"); + let logger = std::sync::Arc::new(AppLogger::new(NAMES, Filter::parse("info"), false)); + let path = logger.attach_dir(&dir).expect("attach"); + let workers: Vec<_> = (0..8) + .map(|t| { + let l = std::sync::Arc::clone(&logger); + std::thread::spawn(move || { + for i in 0..100 { + l.log(&log::Record::builder().level(log::Level::Info).target("photocraft").args(format_args!("thread {t} record {i}")).build()); + } + }) + }) + .collect(); + for w in workers { + w.join().expect("worker"); + } + let text = read(&path); + assert_eq!(text.lines().count(), 800); + assert!(text.lines().all(|l| l.contains(" INFO [") && l.contains(" photocraft: thread ") && l.contains(" record ")), "{text}"); + for t in 0..8 { + assert_eq!(text.matches(&format!(": thread {t} record ")).count(), 100, "thread {t}"); + } + let _ = std::fs::remove_dir_all(&dir); +} + // Each start shifts app.log to app.1.log and app.2.log; while another instance holds the owner lock, a start writes app-.log and leaves the chain alone. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 7d87a8738..b0e71f912 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -1,8 +1,11 @@ -//! Files reaching the app from outside, and the app handing files to the system. +//! OS requests reaching the app from outside, and the app handing files to the system. //! -//! - [`FileIntake`]: one queue for files the OS asks the app to open (Finder double-click, Open -//! With, a Dock drop, a second launch handing its paths to the first) and files dropped on the -//! window, with where they were dropped ([`DropTarget`]). +//! - [`FileIntake`]: one queue for the OS requests: files the OS asks the app to open (Finder +//! double-click, Open With, a Dock drop, a second launch handing its paths to the first), files +//! dropped on the window with where they were dropped ([`DropTarget`]), and the OS asking the +//! app to quit. +//! - `apple_events` (macOS, feature `apple-events`): the open-documents and quit Apple events, +//! fed into a [`FileIntake`]. //! - [`natural_cmp`], [`same_file`]: the order files open in and the check that keeps an open //! file from opening twice. //! - [`OPEN_FAILED`] and the other [`PlatformText`]s: the open errors every app words the same way. @@ -24,6 +27,9 @@ use craft_host::Wake; pub use craft_docpath::names::natural_cmp; +#[cfg(all(target_os = "macos", feature = "apple-events"))] +pub mod apple_events; + use crate::PlatformText; /// "Couldn't open {name}: {error}", shown in the status bar and as an error notice. @@ -100,7 +106,49 @@ const _: () = { sendable::(); }; +/// A source of OS requests that lives on the UI thread (the Apple-event inbox is not `Send`), +/// emptied into its [`IntakeSender`] by [`FileIntake::take`]. +#[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] +struct RegisteredDrain { + queue: std::sync::Weak>>, + drain: std::rc::Rc, +} + +#[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] +thread_local! { + static DRAINS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +/// Keeps a drain registered on the thread that registered it; dropping it unregisters. +#[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] +pub(crate) struct DrainRegistration { + drain: std::rc::Rc, +} + +#[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] +impl Drop for DrainRegistration { + fn drop(&mut self) { + DRAINS.with(|drains| drains.borrow_mut().retain(|d| !std::rc::Rc::ptr_eq(&d.drain, &self.drain))); + } +} + impl IntakeSender { + /// Wakes the UI without queueing anything: for a source that must not drain where it hears + /// the OS (it may hold its own lock there) and is drained by [`FileIntake::take`] instead. + #[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] + pub(crate) fn wake_ui(&self) { + self.wake.wake(); + } + + /// Registers `drain`, which [`FileIntake::take`] runs on the calling thread before it returns, + /// to move the requests a thread-bound source collected into this intake. + #[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] + pub(crate) fn register_drain(&self, drain: impl Fn(&IntakeSender) + 'static) -> DrainRegistration { + let drain: std::rc::Rc = std::rc::Rc::new(drain); + DRAINS.with(|drains| drains.borrow_mut().push(RegisteredDrain { queue: Arc::downgrade(&self.queue), drain: std::rc::Rc::clone(&drain) })); + DrainRegistration { drain } + } + /// Queues an OS open request and wakes the UI (`wake` is the app's `request_repaint`). pub fn open(&self, paths: Vec) { if paths.is_empty() { @@ -114,30 +162,38 @@ impl IntakeSender { /// Queues files dropped on the window and wakes the UI; an empty list is ignored. pub fn dropped(&self, files: Vec, target: DropTarget) { - let _ = (files, target); - todo!("pf.C-O1") + if files.is_empty() { + return; + } + push(&self.queue, Intake::Dropped { files, target }); + self.wake.wake(); } /// Queues an OS quit request and wakes the UI. pub fn quit(&self) { - todo!("pf.C-O1") + push(&self.queue, Intake::Quit); + self.wake.wake(); } } -/// Files waiting to be opened, read once per frame on the UI thread (spec Q-S4F-7). +/// OS requests waiting for the app (files to open, files dropped, quit), read once per frame on +/// the UI thread (spec Q-S4F-7). /// -/// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS, pushes -/// drops from its frame with [`dropped`](Self::dropped), and takes the batches with +/// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS +/// (`apple_events::install` on macOS, its single-instance socket elsewhere), pushes drops +/// through a sender's [`dropped`](IntakeSender::dropped), and takes the requests with /// [`take`](Self::take). An [`Intake::Open`] batch comes made absolute and sorted by /// [`natural_cmp`] of the path text; the app focuses documents already open ([`same_file`]) and /// opens the rest, then brings its window to the front (on Wayland, a user-attention request). +/// [`Intake::Quit`] closes the app the way its own Quit command does. /// /// ```ignore /// let (intake, sender) = FileIntake::new(Wake::new(move || ctx.request_repaint())); -/// // macOS: the app's Apple Event handler calls `sender.open(paths)`; elsewhere its single-instance socket does. +/// #[cfg(target_os = "macos")] +/// let _events = craft_platform::open::apple_events::install(sender.clone()); /// // each frame: -/// intake.dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect()), target); -/// for batch in intake.take() { app.open_batch(batch); } +/// intake.sender().dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect()), target); +/// for request in intake.take() { app.handle(request); } /// ``` pub struct FileIntake { queue: Arc>>, @@ -157,16 +213,23 @@ impl FileIntake { self.sender.clone() } - /// Queues files dropped this frame; an empty list is ignored. - pub fn dropped(&self, files: Vec, target: DropTarget) { - if !files.is_empty() { - push(&self.queue, Intake::Dropped { files, target }); - } - } - - /// The batches in arrival order, emptied. + /// The requests in arrival order, emptied. // pc: crates/ui-egui/src/file_open.rs:157 open_paths (absolute, sorted) pub fn take(&self) -> Vec { + #[cfg(any(test, all(target_os = "macos", feature = "apple-events")))] + { + let mine: Vec> = DRAINS.with(|drains| { + drains + .borrow() + .iter() + .filter(|d| d.queue.upgrade().is_some_and(|q| Arc::ptr_eq(&q, &self.queue))) + .map(|d| std::rc::Rc::clone(&d.drain)) + .collect() + }); + for drain in mine { + drain(&self.sender); + } + } let mut queue = self.queue.lock().unwrap_or_else(PoisonError::into_inner); queue.drain(..).collect() } diff --git a/crates/platform/src/open/apple_events.rs b/crates/platform/src/open/apple_events.rs new file mode 100644 index 000000000..9e88e4747 --- /dev/null +++ b/crates/platform/src/open/apple_events.rs @@ -0,0 +1,51 @@ +//! macOS open-documents and quit Apple events, fed into a [`FileIntake`](super::FileIntake). +//! +//! Finder double-clicks, Open With, drops on the Dock icon and `open -a App file` don't pass paths +//! on the command line: LaunchServices sends the running (or just-launched) app a +//! `kAEOpenDocuments` ('odoc') Apple event. winit doesn't handle it and owns the +//! `NSApplicationDelegate`, so without a handler AppKit answers that the app cannot open files of +//! that format. Handling it needs Objective-C class declarations, i.e. `unsafe`, which the +//! workspace forbids; `fmv-macos-events` wraps exactly that (an `NSAppleEventManager` handler +//! registered before Finder's launch event, leaving winit's delegate alone) behind a safe +//! main-thread API. + +use fmv_macos_events::{Event, Inbox, Registration}; + +use super::{DrainRegistration, IntakeSender}; + +/// Keeps the Apple-event handlers registered; hold it until the event loop returns. +pub struct AppleEvents { + _registration: Registration, + // The inbox is not `Send`, so it stays here and in the drain registered on this thread. + _inbox: Inbox, + _drain: DrainRegistration, +} + +/// Registers the open-documents and quit handlers and routes their events into `sender`: an open +/// event becomes [`IntakeSender::open`], a quit event [`IntakeSender::quit`], when the app next +/// takes its intake. +/// +/// The inbox calls its wake while it holds its own borrow, so the wake only asks the UI to +/// repaint; the events are drained on the main thread by `FileIntake::take`. +/// +/// Call on the main thread before the event loop starts, so the event that launched the app (a +/// Finder double-click) is caught too. +pub fn install(sender: IntakeSender) -> AppleEvents { + let (registration, inbox) = Registration::install(); + let woken = sender.clone(); + inbox.set_wake(move || woken.wake_ui()); + let source = inbox.clone(); + let drain = sender.register_drain(move |sender| forward(&source, sender)); + // An event queued before the wake was set has no wake to run it. + sender.wake_ui(); + AppleEvents { _registration: registration, _inbox: inbox, _drain: drain } +} + +fn forward(inbox: &Inbox, sender: &IntakeSender) { + for event in inbox.drain() { + match event { + Event::Open(paths) => sender.open(paths.into_iter().map(Into::into).collect()), + Event::Quit => sender.quit(), + } + } +} diff --git a/crates/platform/src/open_tests.rs b/crates/platform/src/open_tests.rs index 9c05c13fb..2321201b3 100644 --- a/crates/platform/src/open_tests.rs +++ b/crates/platform/src/open_tests.rs @@ -1,5 +1,40 @@ //! `craft_platform::open`. +// A source whose push calls the wake while holding its own borrow (the Apple-event inbox does) +// must not be drained from the wake: the wake only repaints, and the next `take` collects it. +#[test] +fn a_request_pushed_while_its_source_is_borrowed_is_taken_on_the_next_take() { + use crate::open::{FileIntake, Intake}; + use craft_host::Wake; + use std::cell::RefCell; + use std::path::PathBuf; + use std::rc::Rc; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let woken = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&woken); + let (intake, sender) = FileIntake::new(Wake::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + })); + let source: Rc>> = Rc::default(); + let drained = Rc::clone(&source); + let _registration = sender.register_drain(move |sender| { + let paths = std::mem::take(&mut *drained.borrow_mut()); + sender.open(paths); + }); + + { + let mut held = source.borrow_mut(); + held.push(PathBuf::from("/tmp/a.docx")); + sender.wake_ui(); + } + assert_eq!(woken.load(Ordering::SeqCst), 1, "the wake ran once, under the source's borrow, and drained nothing"); + let taken = intake.take(); + assert!(matches!(taken.as_slice(), [Intake::Open(paths)] if paths.len() == 1), "{taken:?}"); + assert!(intake.take().is_empty(), "the source was emptied"); +} + // The target is one argument after `--` (or the Windows handler), so no shell reads a `&` and no // tool reads a leading `-` as an option. #[cfg(not(target_arch = "wasm32"))]