From e494464a8c5316bf782c5161093d952e1c459741 Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Mon, 12 Oct 2026 19:00:50 -0400 Subject: [PATCH 1/8] Interface: Animation Effects follows the system setting, or is on or off MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Preferences › Interface › Animation effects replaces the Enable animations checkbox with three choices: Use system setting (the default), On and Off (interface.animationEffects: system, on, off). A saved enableAnimations: false loads as off; prefs.set interface.enableAnimations is now an unknown preference. Use system setting reads the OS through the new Services::system_animations (no answer keeps animations on): - Windows: UISettings.AnimationsEnabled (Settings › Accessibility › Visual effects › Animation effects), a safe WinRT call through the windows crate already in Cargo.lock. - macOS: NSWorkspace.accessibilityDisplayShouldReduceMotion. - Linux: the settings portal (reduced-motion, then GNOME enable-animations and KDE AnimationDurationFactor), followed live through SettingChanged. - Linux without the portal, FreeBSD and the other BSDs: kdeglobals, gsettings (GNOME, MATE) and GTK settings.ini, read at start-up and when the window regains focus. - Web: prefers-reduced-motion. Off now also stops the mouse wheel glide. egui spreads a wheel notch over about 0.2 s with no switch, which the old checkbox never touched (only fades and scroll_to). wheel_nav::unsmooth, called from PhotocraftApp::logic, replaces the frame's smoothed scroll with what its wheel events add up to; trackpad gestures with begin and end phases are left to egui. The label and its choices are translated in all 19 catalogs, replacing the Enable animations entry. The scorecard row UI-217-10 note is updated. The Windows reader was run on a machine with Animation effects off. The macOS and Linux code is compile-checked and linted by cross-target builds only, and FreeBSD not at all locally (a variant without the portal module lints clean). Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + apps/photocraft-web/Cargo.toml | 2 +- apps/photocraft-web/src/web.rs | 6 + apps/photocraft/Cargo.toml | 13 +- apps/photocraft/src/animations.rs | 444 ++++++++++++++++++++++++++++ apps/photocraft/src/appearance.rs | 3 +- apps/photocraft/src/main.rs | 1 + apps/photocraft/src/services.rs | 1 + crates/engine/src/prefs.rs | 23 +- crates/engine/src/prefs/tests.rs | 40 +++ crates/ui-egui/src/i18n/cs.tsv | 3 +- crates/ui-egui/src/i18n/de.tsv | 4 +- crates/ui-egui/src/i18n/el.tsv | 3 +- crates/ui-egui/src/i18n/es.tsv | 4 +- crates/ui-egui/src/i18n/fr.tsv | 4 +- crates/ui-egui/src/i18n/hu.tsv | 3 +- crates/ui-egui/src/i18n/id.tsv | 4 +- crates/ui-egui/src/i18n/it.tsv | 3 +- crates/ui-egui/src/i18n/ja.tsv | 4 +- crates/ui-egui/src/i18n/ko.tsv | 4 +- crates/ui-egui/src/i18n/nl.tsv | 3 +- crates/ui-egui/src/i18n/pl.tsv | 4 +- crates/ui-egui/src/i18n/pt-br.tsv | 3 +- crates/ui-egui/src/i18n/ru.tsv | 4 +- crates/ui-egui/src/i18n/tr.tsv | 3 +- crates/ui-egui/src/i18n/uk.tsv | 4 +- crates/ui-egui/src/i18n/vi.tsv | 4 +- crates/ui-egui/src/i18n/zh-hans.tsv | 4 +- crates/ui-egui/src/i18n/zh-hant.tsv | 4 +- crates/ui-egui/src/input_tests.rs | 25 ++ crates/ui-egui/src/lib.rs | 13 + crates/ui-egui/src/prefs_ui.rs | 117 +++++++- crates/ui-egui/src/wheel_nav.rs | 228 +++++++++++++- docs/scorecard.md | 2 +- scorecard/ui.toml | 2 +- 35 files changed, 940 insertions(+), 50 deletions(-) create mode 100644 apps/photocraft/src/animations.rs diff --git a/Cargo.lock b/Cargo.lock index a0499ca1c8..2cf28244f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4223,6 +4223,7 @@ dependencies = [ "rfd", "ron", "serde_json", + "windows", "winit", "winresource", "winsafe", diff --git a/apps/photocraft-web/Cargo.toml b/apps/photocraft-web/Cargo.toml index a4ded64181..8653b5878b 100644 --- a/apps/photocraft-web/Cargo.toml +++ b/apps/photocraft-web/Cargo.toml @@ -34,7 +34,7 @@ rfd = { workspace = true } wasm-bindgen = "0.2" wasm-bindgen-futures = "0.4" js-sys = "0.3" -web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator"] } +web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration", "Storage", "Event", "EventTarget", "MouseEvent", "PointerEvent", "BeforeUnloadEvent", "AbortController", "AbortSignal", "DomException", "Response", "IdbFactory", "IdbOpenDbRequest", "IdbDatabase", "IdbRequest", "IdbTransaction", "IdbTransactionMode", "IdbObjectStore", "IdbCursor", "IdbCursorWithValue", "RequestInit", "Navigator", "MediaQueryList"] } [dev-dependencies] serde_json = { workspace = true } diff --git a/apps/photocraft-web/src/web.rs b/apps/photocraft-web/src/web.rs index 16781e42bb..6012c0658d 100644 --- a/apps/photocraft-web/src/web.rs +++ b/apps/photocraft-web/src/web.rs @@ -395,6 +395,12 @@ fn services(inbox: Inbox) -> Services { // Preferences live in the browser's localStorage. load_prefs: Some(Box::new(|| local_storage()?.get_item(PREFS_KEY).ok().flatten())), save_prefs: Some(Box::new(|text: &str| local_storage().ok_or("no localStorage")?.set_item(PREFS_KEY, text).map_err(|e| format!("{e:?}")))), + // Animation Effects › Use System Setting: the browser passes on the system's setting. One + // live query, so `matches` follows a change. + system_animations: Some({ + let reduce = web_sys::window().and_then(|w| w.match_media("(prefers-reduced-motion: reduce)").ok().flatten()); + Box::new(move |_| reduce.as_ref().map(|query| !query.matches())) + }), ..Default::default() } } diff --git a/apps/photocraft/Cargo.toml b/apps/photocraft/Cargo.toml index 57b537931c..556f32feec 100644 --- a/apps/photocraft/Cargo.toml +++ b/apps/photocraft/Cargo.toml @@ -49,12 +49,13 @@ core-graphics2 = { version = "=0.6.1", default-features = false, features = ["di # registers the handler (Objective-C interop needs unsafe, which our workspace forbids) behind a # safe API. Pinned exactly: review the diff before bumping. fmv-macos-events = "=0.1.0" -# Safe AppKit calls only: turn off AppKit's title bar dragging (mac_window.rs) and find where the -# pointer is when files are dropped (cursor.rs; winit 0.30 drops carry no position). Already in -# Cargo.lock (winit, photocraft-tablet); pinned exactly to the same versions. +# Safe AppKit calls only: turn off AppKit's title bar dragging (mac_window.rs), find where the +# pointer is when files are dropped (cursor.rs; winit 0.30 drops carry no position) and read +# Reduce Motion (animations.rs: NSWorkspace, NSAccessibility). Already in Cargo.lock (winit, +# photocraft-tablet); pinned exactly to the same versions. objc2 = "=0.6.4" objc2-foundation = { version = "=0.3.2", default-features = false, features = ["std", "NSArray", "NSEnumerator", "NSGeometry"] } -objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSApplication", "NSApplicationScripting", "NSEvent", "NSResponder", "NSView", "NSWindow"] } +objc2-app-kit = { version = "=0.3.2", default-features = false, features = ["std", "NSAccessibility", "NSApplication", "NSApplicationScripting", "NSEvent", "NSResponder", "NSView", "NSWindow", "NSWorkspace"] } # The macOS menu bar (mac_menu.rs): a standalone native menu crate (from the tauri-apps org, but # not Tauri: no webview, no JS), AppKit menus behind a safe API (no GTK with default features off). Pinned exactly: review the diff before bumping. muda = { version = "=0.21.1", default-features = false } @@ -82,6 +83,10 @@ winit = { version = "=0.30.13", default-features = false, features = ["x11"] } # Safe Windows screen-capture bindings; Linux uses the pure-Rust X11 client/portal. xcap = "=0.9.8" winsafe = { version = "=0.0.29", default-features = false, features = ["user"] } +# The system's Animation effects setting (animations.rs): `UISettings.AnimationsEnabled`, a safe +# WinRT call (winsafe's `SystemParametersInfo` is unsafe). Already in Cargo.lock (wgpu, xcap, +# accesskit); pinned exactly to the same version. +windows = { version = "=0.62.2", default-features = false, features = ["std", "UI_ViewManagement"] } # tests/mac_menu_appkit.rs: reads AppKit's menu bar back and sends it real key events. [target.'cfg(target_os = "macos")'.dev-dependencies] diff --git a/apps/photocraft/src/animations.rs b/apps/photocraft/src/animations.rs new file mode 100644 index 0000000000..62d138e756 --- /dev/null +++ b/apps/photocraft/src/animations.rs @@ -0,0 +1,444 @@ +//! The operating system's animation setting, for Preferences › Interface › Animation Effects › +//! Use System Setting (`Services::system_animations`). +//! +//! - **Windows**: Settings › Accessibility › Visual effects › Animation effects, through +//! `UISettings.AnimationsEnabled`. It answers for the session, so a Remote Desktop connection +//! that turns animations off counts too. +//! - **macOS**: System Settings › Accessibility › Display › Reduce motion +//! (`NSWorkspace.accessibilityDisplayShouldReduceMotion`). +//! - **Linux**: the settings portal: `reduced-motion`, then GNOME's `enable-animations` and KDE's +//! `AnimationDurationFactor` as the portal passes them on. Its change signal keeps the value +//! current, and it works inside a Flatpak sandbox. +//! - **Linux without the portal, FreeBSD and the other BSDs**: the desktop's setting where it is +//! stored: KDE's `kdeglobals`, GNOME's or MATE's `enable-animations` (`gsettings`), then GTK's +//! `gtk-enable-animations`. There is no change signal to follow, so it is read at start-up and +//! again whenever the window gets the focus back. +//! +//! `None` means the platform gave no answer; the shell then keeps animations on. +//! +//! No `unsafe`: every OS call goes through a safe binding. + +pub use platform::service; + +/// Windows and macOS answer at once, so the setting is simply asked for again: at most this +/// often, and only on frames that run anyway (coming back from the system's settings is one). +#[cfg(any(target_os = "windows", target_os = "macos"))] +const POLL: std::time::Duration = std::time::Duration::from_secs(1); + +#[cfg(any(target_os = "windows", target_os = "macos"))] +fn polled(read: fn() -> Option) -> photocraft_ui_egui::SystemAnimationsFn { + let last = std::cell::Cell::new(None::<(std::time::Instant, Option)>); + Box::new(move |_| { + if let Some((at, animations)) = last.get() + && at.elapsed() < POLL + { + return animations; + } + let animations = read(); + last.set(Some((std::time::Instant::now(), animations))); + animations + }) +} + +#[cfg(target_os = "windows")] +mod platform { + use photocraft_ui_egui::SystemAnimationsFn; + + pub fn service() -> Option { + Some(super::polled(read)) + } + + pub(super) fn read() -> Option { + windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()).ok() + } +} + +#[cfg(target_os = "macos")] +mod platform { + use photocraft_ui_egui::SystemAnimationsFn; + + pub fn service() -> Option { + Some(super::polled(read)) + } + + fn read() -> Option { + Some(!objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()) + } +} + +#[cfg(not(any(unix, target_os = "windows")))] +mod platform { + pub fn service() -> Option { + None + } +} + +#[cfg(all(unix, not(target_os = "macos")))] +mod platform { + use std::sync::atomic::{AtomicU8, Ordering}; + use std::sync::{Arc, OnceLock, mpsc}; + + use photocraft_ui_egui::SystemAnimationsFn; + + /// Follows the desktop's setting on a worker thread, so a slow session bus or `gsettings` + /// never holds up a frame. Until the first answer lands the setting is unknown. + pub fn service() -> Option { + let value = Arc::new(AtomicU8::new(super::code_of(None))); + let wake: Arc> = Arc::new(OnceLock::new()); + let (refresh, refreshes) = mpsc::channel::<()>(); + let publisher = Publisher { value: Arc::clone(&value), wake: Arc::clone(&wake) }; + std::thread::Builder::new().name("animations-setting".into()).spawn(move || worker(&publisher, &refreshes)).ok()?; + let focused = std::cell::Cell::new(true); + Some(Box::new(move |ctx| { + let _ = wake.set(ctx.clone()); + let now = ctx.input(|i| i.focused); + let was = focused.replace(now); + // Back from the desktop's settings, perhaps: the worker reads again unless it has + // the portal's change signal (then nobody listens, and the send fails quietly). + if now && !was { + let _ = refresh.send(()); + } + super::decode(value.load(Ordering::Relaxed)) + })) + } + + fn worker(publisher: &Publisher, refreshes: &mpsc::Receiver<()>) { + #[cfg(target_os = "linux")] + if portal::follow(publisher) { + return; + } + publisher.publish(desktop::read()); + for () in refreshes { + publisher.publish(desktop::read()); + } + } + + /// The worker's handle on the shared value. A change wakes the registered UI. + struct Publisher { + value: Arc, + wake: Arc>, + } + + impl Publisher { + fn publish(&self, animations: Option) { + let code = super::code_of(animations); + if self.value.swap(code, Ordering::Relaxed) != code + && let Some(ctx) = self.wake.get() + { + ctx.request_repaint(); + } + } + } + + #[cfg(target_os = "linux")] + mod portal { + use zbus::zvariant::{OwnedValue, Value}; + + use super::super::{duration_factor, enabled, reduced_motion}; + + /// Whether animations are on according to a setting's value. + type Reads = fn(&str) -> Option; + + /// The settings the portal may answer for and how each one's value reads, most general + /// first: the cross-desktop one, then the two desktops' own that older portals pass on. + const SETTINGS: [(&str, &str, Reads); 3] = [ + ("org.freedesktop.appearance", "reduced-motion", reduced_motion), + ("org.gnome.desktop.interface", "enable-animations", enabled), + ("org.kde.kdeglobals.KDE", "AnimationDurationFactor", duration_factor), + ]; + + /// Publishes the portal's answer, then every change to it. `false` when the portal has + /// none: no session bus, no portal, or one that knows none of the settings. + pub fn follow(publisher: &super::Publisher) -> bool { + let Some(proxy) = crate::appearance::portal_proxy() else { return false }; + // Subscribe before the first read, so a change during start-up isn't lost. + let signals = proxy.receive_signal("SettingChanged").ok(); + let Some(first) = read(&proxy) else { return false }; + publisher.publish(Some(first)); + for message in signals.into_iter().flatten() { + let Ok((namespace, key, _)) = message.body().deserialize::<(String, String, OwnedValue)>() else { + continue; + }; + // Read them all again: which setting answers first may have changed too. + if SETTINGS.iter().any(|(ns, k, _)| *ns == namespace && *k == key) { + publisher.publish(read(&proxy)); + } + } + true + } + + fn read(proxy: &zbus::blocking::Proxy<'_>) -> Option { + SETTINGS.iter().find_map(|(namespace, key, animations)| { + let value: OwnedValue = proxy.call("Read", &(*namespace, *key)).ok()?; + animations(&text(value)?) + }) + } + + /// A setting's value as the text a settings file would hold. + fn text(value: OwnedValue) -> Option { + let mut value: Value<'_> = value.into(); + // The Settings.Read result is a variant; some portals nest another variant inside it. + for _ in 0..4 { + match value { + Value::Value(inner) => value = *inner, + Value::Bool(on) => return Some(on.to_string()), + Value::U32(n) => return Some(n.to_string()), + Value::I32(n) => return Some(n.to_string()), + Value::F64(n) => return Some(n.to_string()), + Value::Str(text) => return Some(text.to_string()), + _ => return None, + } + } + None + } + + #[cfg(test)] + mod tests { + use super::*; + + fn owned(value: Value<'_>) -> OwnedValue { + OwnedValue::try_from(value).unwrap() + } + + #[test] + fn portal_values_read_as_text() { + let nested = Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))); + assert_eq!(text(owned(nested)).as_deref(), Some("1")); + assert_eq!(text(owned(Value::from(false))).as_deref(), Some("false")); + assert_eq!(text(owned(Value::from("0.5"))).as_deref(), Some("0.5")); + assert_eq!(text(owned(Value::from(vec![1u32, 2]))), None); + // Each setting reads its own type of value, the cross-desktop one first. + let [(_, motion, reduced), (_, _, on), (_, _, factor)] = SETTINGS; + assert_eq!(motion, "reduced-motion"); + assert_eq!(reduced(&text(owned(Value::U32(1))).unwrap()), Some(false)); + assert_eq!(reduced(&text(owned(Value::U32(0))).unwrap()), Some(true)); + assert_eq!(on(&text(owned(Value::from(false))).unwrap()), Some(false)); + assert_eq!(factor(&text(owned(Value::from("0"))).unwrap()), Some(false)); + assert_eq!(factor(&text(owned(Value::F64(0.5))).unwrap()), Some(true)); + } + } + } + + mod desktop { + use std::path::PathBuf; + + /// A settings file is a few kilobytes; a larger one isn't read. + const MAX_CONFIG_BYTES: u64 = 1 << 20; + + pub fn read() -> Option { + let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); + super::super::desktop_setting(&desktop, &config_file, &gsettings) + } + + fn config_home() -> Option { + let dir = |key: &str| std::env::var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from); + dir("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| dir("HOME").map(|home| home.join(".config"))) + } + + fn config_file(name: &str) -> Option { + use std::io::Read as _; + let mut text = String::new(); + std::fs::File::open(config_home()?.join(name)).ok()?.take(MAX_CONFIG_BYTES).read_to_string(&mut text).ok()?; + Some(text) + } + + /// `gsettings get`, by absolute path (`/usr/local` and `/usr/pkg` are where the BSDs + /// install it). + fn gsettings(schema: &str, key: &str) -> Option { + let exe = ["/usr/bin/gsettings", "/bin/gsettings", "/usr/local/bin/gsettings", "/usr/pkg/bin/gsettings"] + .into_iter() + .find(|path| std::path::Path::new(path).is_file())?; + let output = std::process::Command::new(exe).args(["get", schema, key]).output().ok()?; + if !output.status.success() { + return None; + } + String::from_utf8(output.stdout).ok() + } + } +} + +/// `true` or `false` (GSettings, the portal), `1` or `0` (a GTK settings file): animations are on. +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn enabled(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "true" | "1" => Some(true), + "false" | "0" => Some(false), + _ => None, + } +} + +/// KDE's animation speed factor: 0 turns animations off. +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn duration_factor(value: &str) -> Option { + value.trim().parse::().ok().filter(|factor| factor.is_finite()).map(|factor| factor > 0.0) +} + +/// The portal's `reduced-motion`: 1 asks for less motion; 0 and the values it may grow don't. +#[cfg(any(test, target_os = "linux"))] +fn reduced_motion(value: &str) -> Option { + value.trim().parse::().ok().map(|code| code != 1) +} + +/// The last value of `key` in `[section]` of an INI-style file (KDE's config, GTK's settings). +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +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() { + let line = line.trim(); + if let Some(name) = line.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) { + inside = name == section; + } else if inside && let Some((name, value)) = line.split_once('=') { + // KDE marks an entry the user may not change as `Key[$i]=value`. + let name = name.split_once('[').map_or(name, |(name, _)| name); + if name.trim() == key { + found = Some(value.trim()); + } + } + } + found +} + +/// The desktop's setting without the portal. `desktop` is `XDG_CURRENT_DESKTOP`, `file` reads a +/// file under the user's config directory and `gsettings` runs `gsettings get `. +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn desktop_setting(desktop: &str, file: &dyn Fn(&str) -> Option, gsettings: &dyn Fn(&str, &str) -> Option) -> Option { + let running = |name: &str| desktop.split(':').any(|part| part.eq_ignore_ascii_case(name)); + let in_file = |name: &str, section: &str, key: &str, animations: fn(&str) -> Option| animations(ini_value(&file(name)?, section, key)?); + if running("KDE") + && let Some(animations) = in_file("kdeglobals", "KDE", "AnimationDurationFactor", duration_factor) + { + return Some(animations); + } + let schema = if running("MATE") { "org.mate.interface" } else { "org.gnome.desktop.interface" }; + let shell = gsettings(schema, "enable-animations").and_then(|out| enabled(&out)); + if shell == Some(false) { + return shell; + } + // `true` may only be the schema's default on a desktop that doesn't use it. GTK's own file + // is what a bare window manager's user writes, and what KDE keeps in step with its setting. + ["gtk-4.0/settings.ini", "gtk-3.0/settings.ini"].iter().find_map(|name| in_file(name, "Settings", "gtk-enable-animations", enabled)).or(shell) +} + +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn code_of(animations: Option) -> u8 { + match animations { + None => 0, + Some(true) => 1, + Some(false) => 2, + } +} + +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +fn decode(code: u8) -> Option { + match code { + 1 => Some(true), + 2 => Some(false), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_setting_reads_its_own_values() { + for (s, animations) in + [("true\n", Some(true)), ("false\n", Some(false)), ("1", Some(true)), ("0", Some(false)), ("FALSE", Some(false)), ("", None), ("maybe", None)] + { + assert_eq!(enabled(s), animations, "{s:?}"); + } + for (s, animations) in [ + ("0", Some(false)), + ("0.0", Some(false)), + ("0.5", Some(true)), + ("1", Some(true)), + ("-1", Some(false)), + ("", None), + ("fast", None), + ("NaN", None), + ("inf", None), + ] { + assert_eq!(duration_factor(s), animations, "{s:?}"); + } + // reduced-motion: only 1 asks for less motion; unknown values mean no preference. + for (s, animations) in [("0", Some(true)), ("1", Some(false)), ("2", Some(true)), ("true", None), ("-1", None), ("", None)] { + assert_eq!(reduced_motion(s), animations, "{s:?}"); + } + // The shared value round-trips, and a stray code is "unknown". + for animations in [None, Some(true), Some(false)] { + assert_eq!(decode(code_of(animations)), animations); + } + assert_eq!(decode(9), None); + } + + #[test] + fn ini_values_come_from_their_own_section() { + let kde = "[General]\nAnimationDurationFactor=3\n\n[KDE]\nSingleClick=false\n AnimationDurationFactor = 0 \n[KDE][Sub]\nAnimationDurationFactor=7\n"; + assert_eq!(ini_value(kde, "KDE", "AnimationDurationFactor"), Some("0")); + assert_eq!(ini_value(kde, "KDE", "Missing"), None); + assert_eq!(ini_value("[KDE]\nAnimationDurationFactor[$i]=0.5\n", "KDE", "AnimationDurationFactor"), Some("0.5"), "an immutable entry"); + assert_eq!( + ini_value("[Settings]\ngtk-enable-animations=1\ngtk-enable-animations=0\n", "Settings", "gtk-enable-animations"), + Some("0"), + "the last one wins" + ); + // Hostile text: no section, no `=`, stray brackets, non-ASCII. + for junk in ["", "AnimationDurationFactor=0", "[KDE", "[KDE]\n=\n[]\n]]][[[\n", "[KDE]\nклавиша=значение\n\u{0}\u{feff}"] { + assert_eq!(ini_value(junk, "KDE", "AnimationDurationFactor"), None, "{junk:?}"); + } + } + + #[test] + fn the_desktop_setting_is_read_where_each_desktop_keeps_it() { + let files = |kde: Option<&'static str>, gtk: Option<&'static str>| { + move |name: &str| match name { + "kdeglobals" => kde.map(String::from), + "gtk-3.0/settings.ini" => gtk.map(String::from), + _ => None, + } + }; + let none = |_: &str, _: &str| -> Option { None }; + let gnome = |on: &'static str| { + move |schema: &str, key: &str| (schema == "org.gnome.desktop.interface" && key == "enable-animations").then(|| format!("{on}\n")) + }; + let kde_off = Some("[KDE]\nAnimationDurationFactor=0\n"); + let gtk_off = Some("[Settings]\ngtk-enable-animations=false\n"); + + // KDE Plasma: its own file, only when Plasma is the desktop running. + assert_eq!(desktop_setting("KDE", &files(kde_off, None), &none), Some(false)); + assert_eq!(desktop_setting("KDE", &files(Some("[KDE]\nAnimationDurationFactor=0.5\n"), gtk_off), &none), Some(true)); + assert_eq!(desktop_setting("ubuntu:GNOME", &files(kde_off, None), &gnome("true")), Some(true), "a leftover kdeglobals is not GNOME's setting"); + // Plasma without the entry (animations at their default speed) falls through to GTK's file. + assert_eq!(desktop_setting("KDE", &files(Some("[KDE]\nSingleClick=false\n"), gtk_off), &none), Some(false)); + // GNOME and the desktops that share its schema. + assert_eq!(desktop_setting("GNOME", &files(None, None), &gnome("false")), Some(false)); + assert_eq!(desktop_setting("GNOME", &files(None, None), &gnome("true")), Some(true)); + // MATE keeps the same key in its own schema. + let mate = |schema: &str, _: &str| (schema == "org.mate.interface").then(|| "false\n".to_string()); + assert_eq!(desktop_setting("MATE", &files(None, None), &mate), Some(false)); + assert_eq!(desktop_setting("GNOME", &files(None, None), &mate), None); + // A bare window manager: GTK's settings file, which also outranks a schema default. + assert_eq!(desktop_setting("sway", &files(None, gtk_off), &none), Some(false)); + assert_eq!(desktop_setting("", &files(None, gtk_off), &gnome("true")), Some(false)); + assert_eq!(desktop_setting("", &files(None, Some("[Settings]\ngtk-enable-animations=1\n")), &none), Some(true)); + // Nothing to read, or nothing readable: unknown, never a panic. + assert_eq!(desktop_setting("", &files(None, None), &none), None); + assert_eq!( + desktop_setting("KDE:\u{0}::", &files(Some("\u{0}[[[=]]]"), Some("=\n[Settings]\ngtk-enable-animations=perhaps")), &|_, _| Some("\u{fffd}".into())), + None + ); + } + + /// The real setting of the machine the tests run on: whatever it is, reading it doesn't + /// panic and the service passes it on (`--nocapture` shows it). + #[cfg(target_os = "windows")] + #[test] + fn windows_reports_its_animation_setting() { + let animations = platform::read(); + println!("UISettings.AnimationsEnabled: {animations:?}"); + let service = platform::service().expect("service"); + assert_eq!(service(&egui::Context::default()), animations); + } +} diff --git a/apps/photocraft/src/appearance.rs b/apps/photocraft/src/appearance.rs index 8389ee83eb..e4c1e89e08 100644 --- a/apps/photocraft/src/appearance.rs +++ b/apps/photocraft/src/appearance.rs @@ -5,8 +5,9 @@ const PORTAL_NAMESPACE: &str = "org.freedesktop.appearance"; #[cfg(target_os = "linux")] const PORTAL_KEY: &str = "color-scheme"; +/// The settings portal, also asked for the animation setting (`animations.rs`). #[cfg(target_os = "linux")] -fn portal_proxy() -> Option> { +pub(crate) fn portal_proxy() -> Option> { let conn = zbus::blocking::connection::Builder::session().ok()?.method_timeout(std::time::Duration::from_secs(2)).build().ok()?; zbus::blocking::Proxy::new(&conn, "org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Settings").ok() } diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs index aee9eabca1..32b43e2bca 100644 --- a/apps/photocraft/src/main.rs +++ b/apps/photocraft/src/main.rs @@ -20,6 +20,7 @@ #![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod animations; mod app_dirs; mod app_icon; mod appearance; diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs index fea0d34541..c75c2ac694 100644 --- a/apps/photocraft/src/services.rs +++ b/apps/photocraft/src/services.rs @@ -433,6 +433,7 @@ pub fn native(automation: Option) -> photoshop_shortcuts: Some(Box::new(|| crate::photoshop_settings::live_keyboard_shortcuts(&|k| std::env::var_os(k)))), save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))), system_theme: crate::appearance::service(), + system_animations: crate::animations::service(), append_text: Some(Box::new(|path: &str, text: &str| { use std::io::Write; let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| e.to_string())?; diff --git a/crates/engine/src/prefs.rs b/crates/engine/src/prefs.rs index 3a8b7ce695..3d20f784ab 100644 --- a/crates/engine/src/prefs.rs +++ b/crates/engine/src/prefs.rs @@ -83,6 +83,12 @@ choice!( LinuxDisplayServer { Auto = "auto", X11 = "x11" } default Auto ); choice!(UiFontSize { Tiny = "tiny", Small = "small", Medium = "medium", Large = "large" } default Small); +choice!( + /// Interface animations: `system` follows the operating system's animation setting (Windows + /// "Animation effects", macOS "Reduce motion", the desktop's setting on Linux and the BSDs, + /// `prefers-reduced-motion` in a browser) and keeps them on where it cannot be read. + AnimationEffects { System = "system", On = "on", Off = "off" } default System +); choice!(LogDestination { Metadata = "metadata", TextFile = "textFile", Both = "both" } default Metadata); choice!(LogDetail { SessionsOnly = "sessionsOnly", Concise = "concise", Detailed = "detailed" } default Concise); choice!(Ask { Always = "always", Never = "never", Ask = "ask" } default Always); @@ -270,9 +276,9 @@ pub struct Interface { /// Draw menu item colours set with Edit › Menus. pub show_menu_colors: bool, pub show_tooltips: bool, - /// Menus, popups and collapsing sections fade and slide, and scroll areas glide to a new - /// position. Off, everything changes at once (a reduced-motion mode; #1218, #3273). - pub enable_animations: bool, + /// Menus, popups, dialogs and collapsing sections fade and slide, and scrolling glides to + /// its new position. Off, everything changes at once (a reduced-motion mode; #1218, #3273). + pub animation_effects: AnimationEffects, /// Move tool drags show only the layer's outline and an arrow, leaving its pixels in place /// until release. Off (the default), the pixels follow the pointer live inside the outline. pub show_bounding_box_when_dragging_layer: bool, @@ -306,7 +312,7 @@ impl Default for Interface { dynamic_color_sliders: true, show_menu_colors: true, show_tooltips: true, - enable_animations: true, + animation_effects: AnimationEffects::System, show_bounding_box_when_dragging_layer: false, system_title_bar: false, notification_auto_hide: true, @@ -1101,6 +1107,7 @@ pub fn choices(path: &str) -> Option<&'static [&'static str]> { "interface.canvasBorder" => CanvasBorder::NAMES, "interface.uiScale" => UiScale::NAMES, "interface.uiFontSize" => UiFontSize::NAMES, + "interface.animationEffects" => AnimationEffects::NAMES, "historyLog.destination" => LogDestination::NAMES, "historyLog.detail" => LogDetail::NAMES, "fileHandling.imagePreviews" | "fileHandling.maximizePsdCompatibility" => Ask::NAMES, @@ -1548,6 +1555,14 @@ impl Session { interface.insert("appearanceMode".into(), json!(mode)); interface.insert(slot.into(), json!(theme.name())); } + // Animation Effects was the Enable Animations checkbox (on by default) before it could + // follow the system: a saved "off" stays off. + if let Some(interface) = v.get_mut("interface").and_then(Value::as_object_mut) + && !interface.contains_key("animationEffects") + && interface.get("enableAnimations").and_then(Value::as_bool) == Some(false) + { + interface.insert("animationEffects".into(), json!(AnimationEffects::Off.name())); + } let color = v.as_object_mut().and_then(|m| m.remove("colorSettings")); let presets = v.as_object_mut().and_then(|m| m.remove("presets")); let prefs: Preferences = serde_json::from_value(v).map_err(|e| format!("preferences: {e}"))?; diff --git a/crates/engine/src/prefs/tests.rs b/crates/engine/src/prefs/tests.rs index 6bb34a9706..46646c57f3 100644 --- a/crates/engine/src/prefs/tests.rs +++ b/crates/engine/src/prefs/tests.rs @@ -67,6 +67,46 @@ fn appearance_defaults_and_legacy_theme_migrate() { } } +/// Interface › Animation Effects: the system's setting by default, validated like any choice, and +/// the Enable Animations checkbox it replaced still means what it was saved as. +#[test] +fn animation_effects_default_to_the_system_and_keep_a_saved_off() { + assert_eq!(Preferences::default().interface.animation_effects, AnimationEffects::System); + assert_eq!(choices("interface.animationEffects"), Some(AnimationEffects::NAMES)); + assert_eq!(AnimationEffects::NAMES, ["system", "on", "off"]); + let mut s = Session::new(); + for (value, effects) in [("off", AnimationEffects::Off), ("on", AnimationEffects::On), ("system", AnimationEffects::System)] { + s.execute("prefs.set", json!({"path": "interface.animationEffects", "value": value})).unwrap(); + assert_eq!(s.prefs().interface.animation_effects, effects); + assert_eq!(s.execute("prefs.get", json!({"path": "interface.animationEffects"})).unwrap(), json!(value)); + let mut restarted = Session::new(); + restarted.load_prefs_json(&s.prefs_to_json()).unwrap(); + assert_eq!(restarted.prefs().interface.animation_effects, effects, "{value} survives a restart"); + } + // A value that is no choice is an error and changes nothing. + s.execute("prefs.set", json!({"path": "interface.animationEffects", "value": "off"})).unwrap(); + for bad in [json!("sometimes"), json!("Off"), json!(""), json!(true), json!(0), json!(null), json!(["off"]), json!({})] { + assert!(s.execute("prefs.set", json!({"path": "interface.animationEffects", "value": bad})).is_err(), "{bad}"); + assert_eq!(s.prefs().interface.animation_effects, AnimationEffects::Off); + } + s.execute("prefs.reset", json!({"path": "interface.animationEffects"})).unwrap(); + assert_eq!(s.prefs().interface.animation_effects, AnimationEffects::System); + // The checkbox was on by default: a saved "off" stays off, "on" now follows the system, and + // a choice made since wins over the old key left in the file. + for (saved, effects) in [ + (json!({"enableAnimations": false}), AnimationEffects::Off), + (json!({"enableAnimations": true}), AnimationEffects::System), + (json!({"enableAnimations": false, "animationEffects": "on"}), AnimationEffects::On), + (json!({"enableAnimations": "nope"}), AnimationEffects::System), + (json!({}), AnimationEffects::System), + ] { + let mut old = Session::new(); + old.load_prefs_json(&json!({"interface": saved}).to_string()).unwrap(); + assert_eq!(old.prefs().interface.animation_effects, effects, "{saved}"); + } + assert!(s.execute("prefs.set", json!({"path": "interface.enableAnimations", "value": false})).is_err(), "the old path is gone"); +} + #[test] fn appearance_choices_validate_and_legacy_theme_still_selects() { let mut s = Session::new(); diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 36fc380769..1adb5b86e3 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1981,7 +1981,8 @@ Show only crosshair while painting Při malování zobrazit jen nitkový kříž Show slice numbers Zobrazit čísla řezů Show tooltips Zobrazit popisky nástrojů - Enable animations Povolit animace + Animation effects Efekty animace + Use system setting Použít nastavení systému Show highlight on rollover Zobrazit zvýraznění při přejetí Show bounding box when dragging layer Při přetahování vrstvy zobrazit ohraničovací rámeček System title bar Systémové záhlaví okna diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index dc366b4553..f1b676ed9d 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1952,7 +1952,9 @@ Show only crosshair while painting Beim Malen nur Fadenkreuz zeigen Show slice numbers Slice-Nummern anzeigen Show tooltips Tooltips anzeigen - Enable animations Animationen aktivieren + Animation effects Animationseffekte + Use system setting Systemeinstellung verwenden + On Ein Show highlight on rollover Hervorhebung bei Rollover anzeigen Show bounding box when dragging layer Begrenzungsrahmen beim Ziehen einer Ebene anzeigen System title bar System-Titelleiste diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 3f693d543f..e23f2de96f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1468,7 +1468,8 @@ Show only crosshair while painting Εμφάνιση μόνο σταυρονήματος κατά τη ζωγραφική Show slice numbers Εμφάνιση αριθμών τομών Show tooltips Εμφάνιση επεξηγήσεων - Enable animations Ενεργοποίηση κινούμενων εφέ + Animation effects Εφέ κίνησης + Use system setting Χρήση ρύθμισης συστήματος Show highlight on rollover Εμφάνιση επισήμανσης κατά την κατάδειξη Show bounding box when dragging layer Εμφάνιση πλαισίου οριοθέτησης κατά τη μετακίνηση επιπέδου Show transformation values Εμφάνιση τιμών μετασχηματισμού diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3f001c478b..2c745d4a05 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1965,7 +1965,9 @@ Show only crosshair while painting Mostrar solo la retícula al pintar Show slice numbers Mostrar los números de sector Show tooltips Mostrar las descripciones emergentes - Enable animations Activar las animaciones + Animation effects Efectos de animación + Use system setting Usar la configuración del sistema + On Activado Show highlight on rollover Mostrar resaltado al pasar el cursor Show bounding box when dragging layer Mostrar el cuadro delimitador al arrastrar la capa System title bar Barra de título del sistema diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4dd927500c..48ba8375df 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1936,7 +1936,9 @@ Show only crosshair while painting N'afficher que le réticule pendant la peinture Show slice numbers Afficher les numéros de tranche Show tooltips Afficher les info-bulles - Enable animations Activer les animations + Animation effects Effets d'animation + Use system setting Utiliser le réglage du système + On Activé Show highlight on rollover Afficher la mise en surbrillance au survol Show transformation values Afficher les valeurs de transformation Slice color Couleur des tranches diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index a84d19458b..3b46122e02 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2927,6 +2927,8 @@ cameraRaw Yellow Sárga Show rulers Vonalzók megjelenítése Show Rulers Vonalzók megjelenítése Show tooltips Eszköztippek megjelenítése + Animation effects Animációs effektusok + Use system setting Rendszerbeállítás használata Software Szoftver Solarized dark Solarized sötét Sort Rendezés @@ -3162,7 +3164,6 @@ cameraRaw Yellow Sárga Ellipse Tool Ellipszis Elliptical Marquee Tool Ellipszis-kijelölés Enable Bekapcsolás - Enable animations Animációk engedélyezése Enable flick panning Lendítéses pásztázás engedélyezése Enable floating document window docking Lebegő dokumentumablakok dokkolásának engedélyezése Enable narrow options bar Keskeny beállítósáv engedélyezése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ea51c03775..1a01ea5c3d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1930,7 +1930,9 @@ Show only crosshair while painting Tampilkan crosshair saja saat melukis Show slice numbers Tampilkan nomor slice Show tooltips Tampilkan tooltip - Enable animations Aktifkan animasi + Animation effects Efek animasi + Use system setting Gunakan pengaturan sistem + On Hidup Show highlight on rollover Tampilkan sorotan saat kursor melintas Show transformation values Tampilkan nilai transformasi Slice color Warna slice diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 1aa22cc2aa..89b7f2455f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1963,7 +1963,8 @@ Show only crosshair while painting Mostra solo mirino durante pittura Show slice numbers Mostra numeri sezioni Show tooltips Mostra tooltip - Enable animations Attiva animazioni + Animation effects Effetti di animazione + Use system setting Usa impostazione di sistema Show highlight on rollover Mostra evidenziazione al passaggio del mouse Show bounding box when dragging layer Mostra riquadro selezione al trascinamento livello System title bar Barra del titolo di sistema diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 40749c2d0b..cb3cf18a56 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1964,7 +1964,9 @@ Show only crosshair while painting 描画中は十字線のみ表示 Show slice numbers スライス番号を表示 Show tooltips ツールチップを表示 - Enable animations アニメーションを有効にする + Animation effects アニメーション効果 + Use system setting システム設定を使用 + On オン Show highlight on rollover ロールオーバー時にハイライトを表示 Show bounding box when dragging layer レイヤーのドラッグ中にバウンディングボックスを表示 System title bar システムのタイトルバー diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index a93a20be59..04fb2944ea 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1927,7 +1927,9 @@ Show only crosshair while painting 칠하는 동안 십자선만 표시 Show slice numbers 분할 영역 번호 표시 Show tooltips 도구 설명 표시 - Enable animations 애니메이션 사용 + Animation effects 애니메이션 효과 + Use system setting 시스템 설정 사용 + On 켬 Show highlight on rollover 롤오버 시 강조 표시 Show transformation values 변형 값 표시 Slice color 분할 영역 색상 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index fc5809033c..4654b8196d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1937,7 +1937,8 @@ Show only crosshair while painting Alleen dradenkruis tonen tijdens schilderen Show slice numbers Segmentnummers tonen Show tooltips Knopinfo tonen - Enable animations Animaties inschakelen + Animation effects Animatie-effecten + Use system setting Systeeminstelling gebruiken Show highlight on rollover Markering bij aanwijzen tonen Show bounding box when dragging layer Selectiekader tonen bij slepen van laag System title bar Titelbalk van systeem diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 9d3ecd9433..124e3ab6f3 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1957,7 +1957,9 @@ Show only crosshair while painting Podczas malowania pokaż tylko celownik Show slice numbers Pokaż numery plasterków Show tooltips Pokaż podpowiedzi - Enable animations Włącz animacje + Animation effects Efekty animacji + Use system setting Użyj ustawienia systemowego + On Włączone Show highlight on rollover Pokaż podświetlenie po najechaniu Show bounding box when dragging layer Pokaż ramkę ograniczającą podczas przeciągania warstwy Show transformation values Pokaż wartości przekształcenia diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b26e9fd07e..86840fc789 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1932,7 +1932,8 @@ Show only crosshair while painting Mostrar apenas a mira ao pintar Show slice numbers Mostrar números das fatias Show tooltips Mostrar dicas de ferramentas - Enable animations Ativar animações + Animation effects Efeitos de animação + Use system setting Usar configuração do sistema Show highlight on rollover Mostrar realce ao passar o mouse Show transformation values Mostrar valores de transformação Slice color Cor das fatias diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index e57d0686b9..f97672f416 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2380,7 +2380,9 @@ Show only crosshair while painting Только перекрестье при рисовании Show slice numbers Показывать номера фрагментов Show tooltips Показывать подсказки - Enable animations Включить анимацию + Animation effects Эффекты анимации + Use system setting Использовать системную настройку + On Вкл Show highlight on rollover Показывать подсветку при наведении Show bounding box when dragging layer Показывать рамку при перетаскивании слоя System title bar Системная строка заголовка diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3f552460ca..d0bbf40504 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1929,6 +1929,8 @@ Show only crosshair while painting Boyama sırasında yalnızca artı işaretini göster Show slice numbers Dilim numaralarını göster Show tooltips Araç ipuçlarını göster + Animation effects Animasyon efektleri + Use system setting Sistem ayarını kullan Show highlight on rollover Rollover sırasında vurgulamayı göster Show bounding box when dragging layer Katmanı sürüklerken sınırlayıcı kutuyu göster System title bar Sistem başlık çubuğu @@ -2423,7 +2425,6 @@ cameraRaw Color Renk Remove All Tümünü Kaldır Unlock Kilidi aç Enable Etkinleştir - Enable animations Animasyonları etkinleştir Disable Devre dışı bırak On Açık Selected Seçilen diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index f7feba19a7..eeec2df648 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2355,7 +2355,9 @@ Show only crosshair while painting Показувати лише перехрестя під час малювання Show slice numbers Показувати номери фрагментів Show tooltips Показувати підказки - Enable animations Увімкнути анімацію + Animation effects Ефекти анімації + Use system setting Використовувати системне налаштування + On Увімкнено Show highlight on rollover Показувати підсвічування під час наведення Show bounding box when dragging layer Показувати рамку під час перетягування шару System title bar Системний рядок заголовка diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 890533bab2..096eb66b7a 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3512,7 +3512,9 @@ cameraData Lens Ống kính New Document With Mask Tài liệu mới có mặt nạ New Layer With Mask Lớp mới có mặt nạ Convert Point Tool Công cụ Chuyển đổi điểm - Enable animations Bật hiệu ứng chuyển động + Animation effects Hiệu ứng chuyển động + Use system setting Dùng cài đặt hệ thống + On Bật Gloss Contour Đường bao bóng Cone - Inverted Hình nón - Đảo ngược Cove - Deep Lõm - Sâu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 2f13bc3bfb..485b3a3bc4 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1974,7 +1974,9 @@ Show only crosshair while painting 绘画时仅显示十字线 Show slice numbers 显示切片编号 Show tooltips 显示工具提示 - Enable animations 启用动画 + Animation effects 动画效果 + Use system setting 使用系统设置 + On 开启 Show highlight on rollover 鼠标悬停时显示高亮 Show bounding box when dragging layer 拖动图层时显示边界框 System title bar 系统标题栏 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b72aa4509b..7dd463cf3c 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1967,7 +1967,9 @@ Show only crosshair while painting 繪圖時僅顯示十字線 Show slice numbers 顯示切片編號 Show tooltips 顯示工具提示 - Enable animations 啟用動畫 + Animation effects 動畫效果 + Use system setting 使用系統設定 + On 開 Show highlight on rollover 滑鼠懸停時顯示醒目提示 Show bounding box when dragging layer 拖曳圖層時顯示邊界框 System title bar 系統標題列 diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 956a9de9ba..1120aa41d8 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -389,6 +389,31 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); } +/// Preferences › Interface › Animation Effects (#3273): on, a wheel notch glides the canvas to +/// its new place over the frames that follow; off, it is there on the frame the notch arrives. +#[test] +fn animation_effects_off_pans_a_wheel_notch_at_once() { + for (choice, at_once) in [("on", false), ("off", true)] { + let mut h = app_window(); + h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": choice})).unwrap(); + { + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (8.0, [200.0, 150.0], false); + } + h.run_steps(4); + h.hover_at(h.state().last_canvas_rect.center()); + h.run_steps(2); + let c0 = h.state().ui.views[0].center; + wheel(&h, -1.0, Modifiers::NONE); + h.run_steps(1); + let c1 = h.state().ui.views[0].center; + h.run_steps(40); + let c2 = h.state().ui.views[0].center; + assert!((c2[1] - c0[1] - 5.0).abs() < 0.01 && c2[0] == c0[0], "{choice}: one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); + assert_eq!(c1 == c2, at_once, "{choice}: {c0:?} -> {c1:?} -> {c2:?}"); + } +} + #[test] fn alt_scroll_zooms_in_steps_around_the_pointer() { let mut h = harness(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index a144477cdb..57579e2654 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -334,6 +334,10 @@ pub type LoadTextFn = Box Option>; pub type SaveTextFn = Box Result<(), String>>; /// Platform appearance when egui cannot detect it (for example, Wayland without a theme event). pub type SystemThemeFn = Box Option>; +/// Whether the operating system animates its interface (Windows "Animation effects", macOS +/// "Reduce motion", the desktop's setting on Linux and the BSDs, `prefers-reduced-motion` in a +/// browser): `Some(false)` when the user turned animations off there, `None` when it can't tell. +pub type SystemAnimationsFn = Box Option>; /// Autosave a document snapshot for crash recovery: (snapshot, revision, original path). pub type AutosaveFn = Box, u64, Option<&str>) -> Result<(), String>>; /// Poll successful or failed background writes: (document id, revision, result). @@ -423,6 +427,10 @@ pub struct Services { /// Photoshop's live keyboard shortcut set, imported once at first launch (`kys_import`). pub photoshop_shortcuts: Option, pub system_theme: Option, + /// The system's animation setting, for Preferences › Interface › Animation Effects › Use + /// System Setting. Read every frame while that is the choice, so it must be cheap; without + /// it (or without an answer) animations stay on. + pub system_animations: Option, /// The native window is connected directly to a Wayland compositor. pub is_wayland: bool, /// On Wayland, the shell command that starts this install under XWayland, where native file @@ -1603,6 +1611,11 @@ impl eframe::App for PhotocraftApp { self.collect_screenshots(ctx); self.issue_screenshots(ctx); prefs_ui::tick(self, ctx); + // Animation Effects off: the wheel scrolls its whole distance at once, before anything + // reads this frame's scroll (wheel_nav.rs). + if self.prefs_rt.reduce_motion { + wheel_nav::unsmooth(ctx); + } monitor_status::poll_frame(self, ctx, frame); // Control requests and persisted preferences can change the language in this frame. i18n::sync_context(ctx, &self.session.prefs().interface.language); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 202944b58a..84c4c03e78 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -52,6 +52,8 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, + /// Interface › Animation Effects came out as off this frame (see `sync_animations`). + pub(crate) reduce_motion: bool, } /// The GPU canvas colours from Preferences › Transparency & Gamut. @@ -384,11 +386,23 @@ fn sync_tooltips(app: &PhotocraftApp, ctx: &egui::Context) { } } -/// Interface › Enable Animations: off, egui's fades and slides take no time and scroll areas jump -/// straight to their target (#3273). Re-checked every frame because a theme change rebuilds the -/// style; both the dark and light styles are set, so a system appearance switch keeps it. -fn sync_animations(app: &PhotocraftApp, ctx: &egui::Context) { - let on = app.session.prefs().interface.enable_animations; +/// Interface › Animation Effects, resolved: on or off as chosen, or the operating system's own +/// setting for Use System Setting (on where the platform cannot tell). +fn animations_on(app: &PhotocraftApp, ctx: &egui::Context) -> bool { + match app.session.prefs().interface.animation_effects { + prefs::AnimationEffects::On => true, + prefs::AnimationEffects::Off => false, + prefs::AnimationEffects::System => app.services.system_animations.as_ref().and_then(|read| read(ctx)).unwrap_or(true), + } +} + +/// Interface › Animation Effects: off, egui's fades and slides take no time and scroll areas jump +/// straight to their target (#3273); the wheel's own glide is taken out by `wheel_nav::unsmooth`. +/// Re-checked every frame because a theme change rebuilds the style and the system's setting can +/// change; both the dark and light styles are set, so a system appearance switch keeps it. +fn sync_animations(app: &mut PhotocraftApp, ctx: &egui::Context) { + let on = animations_on(app, ctx); + app.prefs_rt.reduce_motion = !on; let time = if on { egui::Style::default().animation_time } else { 0.0 }; if ctx.global_style().animation_time != time { let scroll = if on { egui::style::ScrollAnimation::default() } else { egui::style::ScrollAnimation::none() }; @@ -1077,6 +1091,15 @@ fn choice_label(v: &str) -> String { } } +/// The label of choice `v` of the preference at `path`. Most choices read the same wherever +/// they appear; Animation Effects' `system` says what it does. +fn pref_choice_label(path: &str, v: &str) -> String { + match (path, v) { + ("interface.animationEffects", "system") => "Use system setting".into(), + _ => choice_label(v), + } +} + /// An editable `#rrggbb` field beside a colour swatch (#668): typing a valid value sets the /// colour; while it's being typed a partial value is kept, and it shows the colour otherwise. fn hex_field(ui: &mut egui::Ui, key: &str, rgb: &mut [u8; 3]) { @@ -1497,7 +1520,7 @@ fn section_fields( Value::String(s) if prefs::choices(&path).is_some() => { ui.label(RichText::new(tl!(&label)).color(t.text_dim)); let opts = prefs::choices(&path).unwrap_or(&[]); - let labels: Vec = opts.iter().map(|o| choice_label(o)).collect(); + let labels: Vec = opts.iter().map(|o| pref_choice_label(&path, o)).collect(); let pairs: Vec<(String, &str)> = opts.iter().map(|o| o.to_string()).zip(labels.iter().map(String::as_str)).collect(); let mut cur = s.clone(); crate::widgets::dropdown(ui, &format!("pref-{path}"), &mut cur, &pairs, 220.0); @@ -2350,7 +2373,8 @@ mod tests { continue; // Rendered as star controls beside the theme choices. } let mut labels = vec![humanize(k)]; - labels.extend(prefs::choices(&format!("{sec}.{k}")).into_iter().flatten().map(|c| choice_label(c))); + let path = format!("{sec}.{k}"); + labels.extend(prefs::choices(&path).into_iter().flatten().map(|c| pref_choice_label(&path, c))); missing.extend(labels.into_iter().filter(|l| !crate::i18n::has(lang, l))); } } @@ -2700,28 +2724,89 @@ mod tests { } #[test] - fn enable_animations_off_stops_fades_and_scroll_glides_and_is_remembered() { + fn animation_effects_follow_the_choice_or_the_system_and_are_remembered() { + use std::{cell::Cell, rc::Rc}; let on = egui::Style::default().animation_time; let both = |ctx: &egui::Context| [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time); // Saved off: the first frame after a restart applies it to both appearance styles. - let (mut app, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": false}}).to_string())); + let (mut app, _) = app_with_saved(Some(json!({"interface": {"animationEffects": "off"}}).to_string())); let ctx = egui::Context::default(); tick(&mut app, &ctx); assert_eq!(both(&ctx), [0.0, 0.0]); assert_eq!(ctx.global_style().scroll_animation.duration.max, 0.0); + assert!(app.prefs_rt.reduce_motion); // A theme change rebuilds the style; the next frame turns animations off again. app.apply_theme(&ctx, crate::theme::ThemeKind::StudioLight); tick(&mut app, &ctx); assert_eq!(both(&ctx), [0.0, 0.0]); - app.run("prefs.set", json!({"values": {"interface.enableAnimations": true}})).unwrap(); + app.run("prefs.set", json!({"values": {"interface.animationEffects": "on"}})).unwrap(); tick(&mut app, &ctx); assert_eq!(both(&ctx), [on, on]); - assert!(on > 0.0 && ctx.global_style().scroll_animation.duration.max > 0.0); - // A hand-edited value of the wrong type doesn't crash: the defaults (animations on) stay. - let (mut bad, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": "nope"}}).to_string())); - let ctx2 = egui::Context::default(); - tick(&mut bad, &ctx2); - assert_eq!(both(&ctx2), [on, on]); + assert!(on > 0.0 && ctx.global_style().scroll_animation.duration.max > 0.0 && !app.prefs_rt.reduce_motion); + + // Use System Setting, the default, follows the platform as it changes. + let system = Rc::new(Cell::new(Some(false))); + let (mut app, _) = app_with_store(); + assert_eq!(app.session.prefs().interface.animation_effects, prefs::AnimationEffects::System); + let read = system.clone(); + app.services.system_animations = Some(Box::new(move |_| read.get())); + let ctx = egui::Context::default(); + for (answer, time) in [(Some(false), 0.0), (Some(true), on), (None, on), (Some(false), 0.0)] { + system.set(answer); + tick(&mut app, &ctx); + assert_eq!(both(&ctx), [time, time], "the system says {answer:?}"); + assert_eq!(app.prefs_rt.reduce_motion, time == 0.0); + } + // On and Off hold whatever the system says. + for (answer, choice, time) in [(Some(false), "on", on), (Some(true), "off", 0.0), (Some(true), "system", on)] { + system.set(answer); + app.run("prefs.set", json!({"values": {"interface.animationEffects": choice}})).unwrap(); + tick(&mut app, &ctx); + assert_eq!(both(&ctx), [time, time], "{choice} while the system says {answer:?}"); + } + // A platform that can't tell (no service): Use System Setting keeps animations on. + let (mut plain, _) = app_with_store(); + let ctx = egui::Context::default(); + tick(&mut plain, &ctx); + assert_eq!(both(&ctx), [on, on]); + // The Enable Animations checkbox this replaced: a saved "off" is still off. + let (mut old, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": false}}).to_string())); + let ctx = egui::Context::default(); + tick(&mut old, &ctx); + assert_eq!(both(&ctx), [0.0, 0.0]); + // A hand-edited value that is no choice doesn't crash: the defaults stay. + for junk in [json!("nope"), json!(7), json!(null)] { + let (mut bad, _) = app_with_saved(Some(json!({"interface": {"animationEffects": junk}}).to_string())); + let ctx = egui::Context::default(); + tick(&mut bad, &ctx); + assert_eq!(both(&ctx), [on, on]); + } + } + + /// Interface › Animation Effects is a dropdown of three choices, the system's first. + #[test] + fn animation_effects_is_a_three_way_choice_in_the_interface_section() { + use egui::accesskit::Role; + use egui_kittest::{Harness, kittest::Queryable}; + assert_eq!(humanize("animationEffects"), "Animation effects"); + let labels: Vec = + prefs::choices("interface.animationEffects").unwrap().iter().map(|c| pref_choice_label("interface.animationEffects", c)).collect(); + assert_eq!(labels, ["Use system setting", "On", "Off"]); + assert_eq!(pref_choice_label("general.colorPicker", "system"), "System", "elsewhere `system` keeps its plain label"); + let obj = json!({"animationEffects": "system"}).as_object().unwrap().clone(); + let mut h = Harness::builder() + .with_size(egui::vec2(700.0, 700.0)) + .build_ui_state(|ui, obj: &mut Map| section_fields(ui, "interface", obj, &[], crate::i18n::Lang::from_pref("en"), None, ""), obj); + h.run_steps(4); + assert!(h.get_by_label("Animation effects").rect().is_positive()); + h.get_all_by_role(Role::ComboBox).last().unwrap().click(); + h.run_steps(4); + for choice in ["Use system setting", "On", "Off"] { + assert!(h.query_all_by_label(choice).any(|item| item.rect().is_positive()), "{choice} is offered"); + } + h.get_by_label("Off").click(); + h.run_steps(4); + assert_eq!(h.state()["animationEffects"], "off"); } #[test] diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 4d07537df1..3735f53b7d 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -20,8 +20,11 @@ //! frames, so zooming reads the wheel events themselves and ignores that smoothed tail; panning //! keeps the smoothed delta. The Alt state is taken from the wheel events and kept until the next //! wheel event: releasing Alt while the tail is still settling must not turn it into a pan. +//! +//! Preferences › Interface › Animation Effects off takes that smoothing out everywhere, panels +//! and lists included: [`unsmooth`] scrolls a notch's whole distance the frame it arrives. -use egui::{Context, Event, Id, Modifiers, MouseWheelUnit, RawInput, Vec2}; +use egui::{Context, Event, Id, Modifiers, MouseWheelUnit, RawInput, TouchPhase, Vec2}; /// Zoom factor of one wheel notch: every step is exactly ×1.1. pub const NOTCH: f32 = 1.1; @@ -132,6 +135,67 @@ pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { } } +fn touch_id() -> Id { + Id::new("pc-wheel-touch") +} + +/// What this frame's wheel events scroll in all, in points: each one in its unit and folded +/// sideways or upright by its modifiers, as egui does before it smooths them. `touch` follows +/// trackpad gestures (the ones with a begin and an end phase). `None` leaves egui's own value +/// alone: for a frame with part of such a gesture, which egui applies as it arrives (and whose +/// modifiers it holds from the start), for a wheel event that zooms, and for a hostile sum. +fn arrived(events: &[Event], options: &egui::InputOptions, page: f32, touch: &mut bool) -> Option { + let mut gesture = *touch; + let mut sum = Vec2::ZERO; + for event in events { + let Event::MouseWheel { unit, delta, phase, modifiers } = event else { continue }; + match phase { + TouchPhase::Start => (*touch, gesture) = (true, true), + TouchPhase::End | TouchPhase::Cancel => (*touch, gesture) = (false, true), + TouchPhase::Move => { + if modifiers.matches_any(options.zoom_modifier) { + return None; + } + let delta = *delta + * match unit { + MouseWheelUnit::Point => 1.0, + MouseWheelUnit::Line => options.line_scroll_speed, + MouseWheelUnit::Page => page, + }; + let sideways = modifiers.matches_any(options.horizontal_scroll_modifier); + let upright = modifiers.matches_any(options.vertical_scroll_modifier); + sum += match (sideways, upright) { + (true, false) => Vec2::new(delta.x + delta.y, 0.0), + (false, true) => Vec2::new(0.0, delta.x + delta.y), + _ => delta, + }; + } + } + } + (!gesture && sum.x.is_finite() && sum.y.is_finite()).then_some(sum) +} + +/// Interface › Animation Effects off: scroll the whole distance of a wheel notch in the frame +/// it arrives. egui spreads a notch over the next several frames (a glide of about 0.2 s, with +/// no setting to turn it off), so this replaces the frame's smoothed scroll with everything its +/// wheel events add up to; the frames after it carry only the rest of that glide and no wheel +/// events, and so scroll nothing. Call it once a frame before anything reads the scroll +/// (`PhotocraftApp::logic`). Zooming already reads the wheel events themselves ([`read`]). +pub fn unsmooth(ctx: &Context) { + let options = ctx.options(|o| o.input_options); + let was = ctx.data(|d| d.get_temp::(touch_id())).unwrap_or(false); + let mut touch = was; + ctx.input_mut(|i| { + let page = i.viewport_rect().height(); + if let Some(scroll) = arrived(&i.events, &options, page, &mut touch) { + i.smooth_scroll_delta = scroll; + } + }); + if touch != was { + ctx.data_mut(|d| d.insert_temp(touch_id(), touch)); + } +} + fn alt_id() -> Id { Id::new("pc-wheel-alt") } @@ -180,8 +244,6 @@ pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool) -> Option Input { @@ -362,6 +424,166 @@ mod tests { assert!(matches!(ev[0], Event::MouseWheel { .. })); } + /// `smooth_scroll_delta` as the UI reads it on each of 30 frames at 60 fps, in a context set + /// up like the app's; `off` is Animation Effects off ([`unsmooth`] at the start of the frame). + fn scrolled(frames: Vec>, off: bool) -> Vec { + let ctx = Context::default(); + configure(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0)); + let mut frames = frames.into_iter(); + (0..30) + .map(|n| { + let events = frames.next().unwrap_or_default(); + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, screen_rect: Some(screen), events, ..Default::default() }; + let mut seen = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if off { + unsmooth(ui.ctx()); + } + seen = ui.input(|i| i.smooth_scroll_delta); + }); + out.textures_delta.clear(); + seen + }) + .collect() + } + + fn total(frames: &[Vec2]) -> Vec2 { + frames.iter().fold(Vec2::ZERO, |sum, d| sum + *d) + } + + /// Animation Effects off: a wheel notch scrolls its whole distance the frame it arrives, + /// instead of gliding there over the frames that follow. + #[test] + fn animations_off_scrolls_a_wheel_notch_at_once() { + let notch = || vec![vec![], vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)]]; + // egui by itself: part of the notch on the frame it arrives, the rest over the next ones. + let glide = scrolled(notch(), false); + assert!(glide[1].y < 0.0 && glide[1].y > -30.0, "the notch starts gliding: {:?}", glide[1]); + assert!(glide[2..8].iter().all(|d| d.y < 0.0), "and keeps gliding: {:?}", &glide[2..8]); + assert!(near(total(&glide), Vec2::new(0.0, -40.0)), "{:?}", total(&glide)); + // Off: all of it at once, and nothing after. + let jump = scrolled(notch(), true); + assert_eq!(jump[1], Vec2::new(0.0, -40.0)); + assert!(jump.iter().enumerate().all(|(n, d)| n == 1 || *d == Vec2::ZERO), "{jump:?}"); + // Sideways (⇧ or ⌘/Ctrl + wheel), two notches in one frame, a fraction of a notch each + // way, a page and a coarse pixel step (a wheel on Wayland or the web) jump the same way. + let sent = |unit, y: f32| Event::MouseWheel { unit, delta: Vec2::new(0.0, y), phase: TouchPhase::Move, modifiers: Modifiers::NONE }; + for (events, want) in [ + (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)], Vec2::new(40.0, 0.0)), + (vec![wheel(Vec2::new(0.0, 1.0), CTRL)], Vec2::new(40.0, 0.0)), + (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE), wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)], Vec2::new(0.0, 80.0)), + (vec![wheel(Vec2::new(-0.5, 0.25), Modifiers::NONE)], Vec2::new(-20.0, 10.0)), + (vec![sent(MouseWheelUnit::Page, -1.0)], Vec2::new(0.0, -600.0)), + (vec![sent(MouseWheelUnit::Point, 53.0)], Vec2::new(0.0, 53.0)), + ] { + let jump = scrolled(vec![events.clone()], true); + assert!(near(jump[0], want) && jump[1..].iter().all(|d| *d == Vec2::ZERO), "{events:?}: {jump:?}"); + let glide = total(&scrolled(vec![events.clone()], false)); + assert!((glide - want).length() < 1.0, "the same distance as with animations on: {events:?}: {glide:?}"); + } + // The canvas pans by all of it on that frame too, and Alt + wheel still zooms one step. + let ctx = Context::default(); + configure(&ctx); + let mut seen = None; + for (time, modifiers) in [(0.0, Modifiers::NONE), (1.0, Modifiers::ALT)] { + let raw = RawInput { time: Some(time), predicted_dt: 1.0 / 60.0, events: vec![wheel(Vec2::new(0.0, 1.0), modifiers)], ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| { + unsmooth(ui.ctx()); + seen = read(ui.ctx(), false, true); + }); + out.textures_delta.clear(); + if modifiers.alt { + assert!(matches!(seen, Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-4), "{seen:?}"); + } else { + assert_eq!(seen, Some(Wheel::Pan(Vec2::new(0.0, 40.0)))); + } + } + } + + /// What the setting is for: an egui scroll area (panels, lists, long menus) is at its new + /// place on the frame the notch arrives, where it otherwise glides there. + #[test] + fn animations_off_scroll_areas_jump() { + let offsets = |off: bool| -> Vec { + let ctx = Context::default(); + configure(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0)); + (0..40) + .map(|n| { + let mut events = vec![Event::PointerMoved(egui::pos2(100.0, 100.0))]; + if n == 3 { + events.push(wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)); + } + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, screen_rect: Some(screen), events, ..Default::default() }; + let mut offset = 0.0; + let mut out = ctx.run_ui(raw, |ui| { + if off { + unsmooth(ui.ctx()); + } + let area = egui::ScrollArea::vertical().show(ui, |ui| ui.allocate_space(egui::vec2(100.0, 2000.0))); + offset = area.state.offset.y; + }); + out.textures_delta.clear(); + offset + }) + .collect() + }; + let (glide, jump) = (offsets(false), offsets(true)); + assert!(glide[3] > 0.0 && glide[3] < 30.0 && glide[4] > glide[3], "it glides: {:?}", &glide[..8]); + assert!((glide[39] - 40.0).abs() < 0.01, "to one notch down: {}", glide[39]); + assert_eq!(jump[..3], [0.0; 3]); + assert!(jump[3..].iter().all(|y| *y == 40.0), "off, it is there at once: {:?}", &jump[..8]); + } + + /// A trackpad gesture (begin and end phases) is already applied as it arrives, with its + /// modifiers held from the start: off leaves it exactly as egui has it. + #[test] + fn animations_off_leaves_trackpad_gestures_to_egui() { + let touch = |phase, y: f32, modifiers| Event::MouseWheel { unit: MouseWheelUnit::Point, delta: Vec2::new(0.0, y), phase, modifiers }; + let gesture = || { + vec![ + vec![touch(TouchPhase::Start, 0.0, Modifiers::SHIFT)], + vec![touch(TouchPhase::Move, 3.0, Modifiers::SHIFT)], + // Shift let go mid-gesture: egui keeps scrolling sideways. + vec![touch(TouchPhase::Move, 30.0, Modifiers::NONE)], + vec![touch(TouchPhase::Move, 2.0, Modifiers::NONE), touch(TouchPhase::End, 0.0, Modifiers::NONE)], + vec![], + // The wheel afterwards jumps again. + vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)], + ] + }; + let (on, off) = (scrolled(gesture(), false), scrolled(gesture(), true)); + assert_eq!(on[..5], off[..5], "the gesture reads the same"); + assert_eq!(on[2], Vec2::new(30.0, 0.0), "sideways for the whole gesture"); + assert_eq!(off[5], Vec2::new(0.0, 40.0)); + assert!(off[6..].iter().all(|d| *d == Vec2::ZERO)); + } + + /// A wheel event that zooms (egui's own zoom modifier, which the app turns off) and hostile + /// deltas leave the frame's scroll as egui computed it. + #[test] + fn unsmoothing_skips_zoom_and_hostile_numbers() { + let options = egui::InputOptions::default(); + let mut touch = false; + let zoom = [wheel(Vec2::new(0.0, 1.0), CTRL)]; + assert_eq!(arrived(&zoom, &options, 600.0, &mut touch), None, "egui's default: ⌘/Ctrl + wheel zooms"); + let plain = [wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)]; + assert_eq!(arrived(&plain, &options, 600.0, &mut touch), Some(Vec2::new(0.0, options.line_scroll_speed))); + assert_eq!(arrived(&[], &options, 600.0, &mut touch), Some(Vec2::ZERO), "no wheel event: the rest of a glide is dropped"); + for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, f32::MAX] { + for page in [600.0, f32::NAN, f32::INFINITY, 0.0, -1.0] { + for unit in [MouseWheelUnit::Point, MouseWheelUnit::Line, MouseWheelUnit::Page] { + let events = [Event::MouseWheel { unit, delta: Vec2::new(bad, bad), phase: TouchPhase::Move, modifiers: Modifiers::SHIFT }]; + if let Some(sum) = arrived(&events, &options, page, &mut touch) { + assert!(sum.x.is_finite() && sum.y.is_finite(), "{sum:?} from {bad} {page} {unit:?}"); + } + } + } + } + assert!(!touch, "no gesture phase was seen"); + } + #[test] fn hostile_numbers_never_produce_a_bad_zoom() { for s in [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30] { diff --git a/docs/scorecard.md b/docs/scorecard.md index d2ee641b1e..c6c93f46f6 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -191,7 +191,7 @@ Unread: `general.color_picker`, `general.animated_zoom`, `general.zoom_resizes_w | UI-217-7 | Command palette shows recently run commands on an empty query | done | [#217](https://github.com/storytold/photocraft/issues/217) | palette.rs: note_recent from menus::invoke keeps the last 8 commands (dedup, newest first); an empty query lists them via recent_hits; the_palette_records_and_replays_recent_commands_on_an_empty_query covers record -> empty query -> replay | | UI-217-8 | Tool-specific canvas right-click menu; right-click spelling suggestions in text fields | partial | [#217](https://github.com/storytold/photocraft/issues/217) | paint_mouse.rs brush picker and canvas_tool_menu.rs selection actions; text_field_menu.rs gives every text field its right-click Undo/Cut/Copy/Paste/Delete/Select All menu (#2921); other tools missing; spelling suggestions (edit.checkSpelling suggest) not in the text-field menu yet | | UI-217-9 | UI scale presets 100/115/125/150/200 % through zoom_factor, remembered | done | [#217](https://github.com/storytold/photocraft/issues/217) | prefs::UiScale offers Auto plus 75 to 300 percent (13 presets, more than the five this row lists); prefs_ui.rs display_scale resolves it (Auto follows the system scale, fractional and unscaled 4K included, #1072/#1278) and sync_display_scale applies it with ctx.set_zoom_factor. It is a preference, so it is remembered. The zoom_factor assert in input_tests.rs is about canvas zoom not scaling the interface, not about this setting | -| UI-217-10 | Appearance: animation toggle, canvas pattern toggle per theme, start-screen recents | partial | [#217](https://github.com/storytold/photocraft/issues/217) | interface.enableAnimations (prefs_ui.rs sync_animations, #3273) zeroes egui animation_time and scroll animation in both styles; the Home screen lists recent files (canvas.rs home_recent, #2691); no canvas pattern toggle yet (#2264) and no option to hide the Home screen recents | +| UI-217-10 | Appearance: animation toggle, canvas pattern toggle per theme, start-screen recents | partial | [#217](https://github.com/storytold/photocraft/issues/217) | interface.animationEffects (system, on, off; prefs_ui.rs sync_animations, #3273) zeroes egui animation_time and scroll animation in both styles, and wheel_nav::unsmooth takes out egui's wheel glide; system, the default, follows the OS animation setting through Services::system_animations (apps/photocraft/src/animations.rs for Windows, macOS, Linux and the BSDs; prefers-reduced-motion on the web); the Home screen lists recent files (canvas.rs home_recent, #2691); no canvas pattern toggle yet (#2264) and no option to hide the Home screen recents | | UI-217-11 | Soft dark and soft light themes with picker previews; outlined knobs in light themes | missing | [#217](https://github.com/storytold/photocraft/issues/217) | theme.rs ThemeKind has twelve themes (the four Pro brightness levels, Studio and Studio Light, Classic, Adwaita and Adwaita Dark, Solarized Dark, Breeze Light and Breeze Dark); no Soft dark or Soft light, and no outlined knobs in the light themes | | UI-217-12 | Save custom New Document presets; a real Recent category | done | [#217](https://github.com/storytold/photocraft/issues/217) | document_preset_cmds.rs and new_doc_ui.rs: named presets save/select/delete through preferences; Recent lists Clipboard, the last 20 documents created in the dialog (document.recent.*, persisted with the presets, newest first, deduplicated) and the uncovered defaults (#3131); created_documents_fill_the_recent_category | | UI-217-13 | Numeric fields accept arithmetic and units; scrubby labels; double-click resets a slider | done | [#217](https://github.com/storytold/photocraft/issues/217) | widgets::value_field: arithmetic plus units (1in, 5mm, 72pt, 50%) converted at the document resolution (#3099); widgets::scrub_label makes options-bar, slider-row and Character labels scrubby (Shift x10, Alt fine); slider rows with a known default reset on double-click | diff --git a/scorecard/ui.toml b/scorecard/ui.toml index 3fa79b59fa..2542c2f16c 100644 --- a/scorecard/ui.toml +++ b/scorecard/ui.toml @@ -73,7 +73,7 @@ id = "UI-217-10" target = "Appearance: animation toggle, canvas pattern toggle per theme, start-screen recents" status = "partial" issue = 217 -note = "interface.enableAnimations (prefs_ui.rs sync_animations, #3273) zeroes egui animation_time and scroll animation in both styles; the Home screen lists recent files (canvas.rs home_recent, #2691); no canvas pattern toggle yet (#2264) and no option to hide the Home screen recents" +note = "interface.animationEffects (system, on, off; prefs_ui.rs sync_animations, #3273) zeroes egui animation_time and scroll animation in both styles, and wheel_nav::unsmooth takes out egui's wheel glide; system, the default, follows the OS animation setting through Services::system_animations (apps/photocraft/src/animations.rs for Windows, macOS, Linux and the BSDs; prefers-reduced-motion on the web); the Home screen lists recent files (canvas.rs home_recent, #2691); no canvas pattern toggle yet (#2264) and no option to hide the Home screen recents" [[item]] id = "UI-217-11" From a128094e93e76732f247824b9cdd386f26754cae Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Tue, 13 Oct 2026 04:26:42 -0400 Subject: [PATCH 2/8] chore: opt JeremyYao into public profile credit Co-Authored-By: Claude Opus 5.5 --- contributors/people.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/contributors/people.toml b/contributors/people.toml index bbda6719ec..d360d5525e 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -154,3 +154,6 @@ sync_github_name = true [people.VanTan666] display_name = "VanTan" sync_github_name = false + +[people.JeremyYao] +sync_github_name = true From 5d552d4a605fca75f7d0923829f89af4622f2cf2 Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Sat, 17 Oct 2026 11:52:09 -0400 Subject: [PATCH 3/8] Animation Effects: one wheel fix, readers split by platform, clearer names - wheel_nav: unsmooth is the one place that stops the wheel glide. main's read_with(smooth) from #5883 did the same for the canvas only, and only for plain scrolling; with unsmooth running first in PhotocraftApp::logic it no longer changed anything, so read() is the single reader again and the canvas calls it as before. #5883's test now drives unsmooth and sits with the other Animation Effects tests. - wheel_nav: arrived and touch become unsmoothed_scroll and in_gesture, with plainer docs. - animations.rs: the Linux/BSD settings parsers move to animations/freedesktop.rs (plain functions, tested on every platform), so animations.rs reads as one short reader per platform under a table of where each one reads from. - prefs_ui: Runtime::reduce_motion becomes animations_off, to match animations_on(); the long animation test is split into three focused ones. No change in behaviour. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/animations.rs | 341 +++++------------- apps/photocraft/src/animations/freedesktop.rs | 150 ++++++++ crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/prefs_ui.rs | 84 +++-- crates/ui-egui/src/wheel_nav.rs | 182 +++++----- 6 files changed, 377 insertions(+), 389 deletions(-) create mode 100644 apps/photocraft/src/animations/freedesktop.rs diff --git a/apps/photocraft/src/animations.rs b/apps/photocraft/src/animations.rs index 62d138e756..bae69370b0 100644 --- a/apps/photocraft/src/animations.rs +++ b/apps/photocraft/src/animations.rs @@ -1,36 +1,30 @@ //! The operating system's animation setting, for Preferences › Interface › Animation Effects › -//! Use System Setting (`Services::system_animations`). +//! Use System Setting (`Services::system_animations`). `None` means the platform gave no answer; +//! the app then keeps animations on. //! -//! - **Windows**: Settings › Accessibility › Visual effects › Animation effects, through -//! `UISettings.AnimationsEnabled`. It answers for the session, so a Remote Desktop connection -//! that turns animations off counts too. -//! - **macOS**: System Settings › Accessibility › Display › Reduce motion -//! (`NSWorkspace.accessibilityDisplayShouldReduceMotion`). -//! - **Linux**: the settings portal: `reduced-motion`, then GNOME's `enable-animations` and KDE's -//! `AnimationDurationFactor` as the portal passes them on. Its change signal keeps the value -//! current, and it works inside a Flatpak sandbox. -//! - **Linux without the portal, FreeBSD and the other BSDs**: the desktop's setting where it is -//! stored: KDE's `kdeglobals`, GNOME's or MATE's `enable-animations` (`gsettings`), then GTK's -//! `gtk-enable-animations`. There is no change signal to follow, so it is read at start-up and -//! again whenever the window gets the focus back. -//! -//! `None` means the platform gave no answer; the shell then keeps animations on. +//! | Platform | Read from | +//! |---|---| +//! | Windows | Settings › Accessibility › Visual effects › Animation effects (`UISettings.AnimationsEnabled`) | +//! | macOS | System Settings › Accessibility › Display › Reduce motion | +//! | Linux | The settings portal, followed as it changes; it also works inside a Flatpak | +//! | Linux without the portal, the BSDs | The desktop's own files and `gsettings` (`freedesktop.rs`), read again when the window gets the focus back | //! //! No `unsafe`: every OS call goes through a safe binding. +#[cfg(any(test, all(unix, not(target_os = "macos"))))] +mod freedesktop; + pub use platform::service; -/// Windows and macOS answer at once, so the setting is simply asked for again: at most this -/// often, and only on frames that run anyway (coming back from the system's settings is one). -#[cfg(any(target_os = "windows", target_os = "macos"))] -const POLL: std::time::Duration = std::time::Duration::from_secs(1); - +/// Windows and macOS answer at once, so the setting is asked for again on frames that run anyway +/// (coming back from the system's settings is one), at most once a second. #[cfg(any(target_os = "windows", target_os = "macos"))] fn polled(read: fn() -> Option) -> photocraft_ui_egui::SystemAnimationsFn { + const INTERVAL: std::time::Duration = std::time::Duration::from_secs(1); let last = std::cell::Cell::new(None::<(std::time::Instant, Option)>); Box::new(move |_| { if let Some((at, animations)) = last.get() - && at.elapsed() < POLL + && at.elapsed() < INTERVAL { return animations; } @@ -42,12 +36,12 @@ fn polled(read: fn() -> Option) -> photocraft_ui_egui::SystemAnimationsFn #[cfg(target_os = "windows")] mod platform { - use photocraft_ui_egui::SystemAnimationsFn; - - pub fn service() -> Option { + pub fn service() -> Option { Some(super::polled(read)) } + /// A safe WinRT call; it reports what Windows applies to this session, so a Remote Desktop + /// connection with animations off counts too. pub(super) fn read() -> Option { windows::UI::ViewManagement::UISettings::new().and_then(|settings| settings.AnimationsEnabled()).ok() } @@ -55,9 +49,7 @@ mod platform { #[cfg(target_os = "macos")] mod platform { - use photocraft_ui_egui::SystemAnimationsFn; - - pub fn service() -> Option { + pub fn service() -> Option { Some(super::polled(read)) } @@ -66,42 +58,37 @@ mod platform { } } -#[cfg(not(any(unix, target_os = "windows")))] -mod platform { - pub fn service() -> Option { - None - } -} - +/// Linux and the BSDs. Reading the setting can mean waiting for the session bus or running +/// `gsettings`, so a worker thread does it and the UI reads its latest answer. #[cfg(all(unix, not(target_os = "macos")))] mod platform { use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, OnceLock, mpsc}; - use photocraft_ui_egui::SystemAnimationsFn; + use super::freedesktop; - /// Follows the desktop's setting on a worker thread, so a slow session bus or `gsettings` - /// never holds up a frame. Until the first answer lands the setting is unknown. - pub fn service() -> Option { - let value = Arc::new(AtomicU8::new(super::code_of(None))); + pub fn service() -> Option { + let latest = Arc::new(AtomicU8::new(encode(None))); let wake: Arc> = Arc::new(OnceLock::new()); let (refresh, refreshes) = mpsc::channel::<()>(); - let publisher = Publisher { value: Arc::clone(&value), wake: Arc::clone(&wake) }; + let publisher = Publisher { latest: Arc::clone(&latest), wake: Arc::clone(&wake) }; std::thread::Builder::new().name("animations-setting".into()).spawn(move || worker(&publisher, &refreshes)).ok()?; - let focused = std::cell::Cell::new(true); + let last_focus = std::cell::Cell::new(true); Some(Box::new(move |ctx| { let _ = wake.set(ctx.clone()); - let now = ctx.input(|i| i.focused); - let was = focused.replace(now); - // Back from the desktop's settings, perhaps: the worker reads again unless it has - // the portal's change signal (then nobody listens, and the send fails quietly). - if now && !was { + let focused = ctx.input(|i| i.focused); + let was_focused = last_focus.replace(focused); + // Back from the desktop's settings, perhaps: read again. With the portal's change + // signal nobody listens for this, and the send fails quietly. + if focused && !was_focused { let _ = refresh.send(()); } - super::decode(value.load(Ordering::Relaxed)) + decode(latest.load(Ordering::Relaxed)) })) } + /// Follows the portal when it has an answer; otherwise reads the desktop's own setting now + /// and on every refresh request. fn worker(publisher: &Publisher, refreshes: &mpsc::Receiver<()>) { #[cfg(target_os = "linux")] if portal::follow(publisher) { @@ -113,16 +100,16 @@ mod platform { } } - /// The worker's handle on the shared value. A change wakes the registered UI. + /// The worker's side of the latest answer. A change wakes the UI. struct Publisher { - value: Arc, + latest: Arc, wake: Arc>, } impl Publisher { fn publish(&self, animations: Option) { - let code = super::code_of(animations); - if self.value.swap(code, Ordering::Relaxed) != code + let code = encode(animations); + if self.latest.swap(code, Ordering::Relaxed) != code && let Some(ctx) = self.wake.get() { ctx.request_repaint(); @@ -130,21 +117,37 @@ mod platform { } } + fn encode(animations: Option) -> u8 { + match animations { + None => 0, + Some(true) => 1, + Some(false) => 2, + } + } + + fn decode(code: u8) -> Option { + match code { + 1 => Some(true), + 2 => Some(false), + _ => None, + } + } + #[cfg(target_os = "linux")] mod portal { use zbus::zvariant::{OwnedValue, Value}; - use super::super::{duration_factor, enabled, reduced_motion}; + use super::freedesktop; - /// Whether animations are on according to a setting's value. - type Reads = fn(&str) -> Option; + /// Reads a setting's value as animations on or off. + type Parse = fn(&str) -> Option; - /// The settings the portal may answer for and how each one's value reads, most general - /// first: the cross-desktop one, then the two desktops' own that older portals pass on. - const SETTINGS: [(&str, &str, Reads); 3] = [ - ("org.freedesktop.appearance", "reduced-motion", reduced_motion), - ("org.gnome.desktop.interface", "enable-animations", enabled), - ("org.kde.kdeglobals.KDE", "AnimationDurationFactor", duration_factor), + /// The settings the portal may answer for, most general first: the cross-desktop one, + /// then GNOME's and KDE's own, which older portals pass on. + const SETTINGS: [(&str, &str, Parse); 3] = [ + ("org.freedesktop.appearance", "reduced-motion", freedesktop::from_reduced_motion), + ("org.gnome.desktop.interface", "enable-animations", freedesktop::from_enabled), + ("org.kde.kdeglobals.KDE", "AnimationDurationFactor", freedesktop::from_duration_factor), ]; /// Publishes the portal's answer, then every change to it. `false` when the portal has @@ -168,14 +171,14 @@ mod platform { } fn read(proxy: &zbus::blocking::Proxy<'_>) -> Option { - SETTINGS.iter().find_map(|(namespace, key, animations)| { + SETTINGS.iter().find_map(|(namespace, key, parse)| { let value: OwnedValue = proxy.call("Read", &(*namespace, *key)).ok()?; - animations(&text(value)?) + parse(&as_text(value)?) }) } /// A setting's value as the text a settings file would hold. - fn text(value: OwnedValue) -> Option { + fn as_text(value: OwnedValue) -> Option { let mut value: Value<'_> = value.into(); // The Settings.Read result is a variant; some portals nest another variant inside it. for _ in 0..4 { @@ -203,42 +206,36 @@ mod platform { #[test] fn portal_values_read_as_text() { let nested = Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))); - assert_eq!(text(owned(nested)).as_deref(), Some("1")); - assert_eq!(text(owned(Value::from(false))).as_deref(), Some("false")); - assert_eq!(text(owned(Value::from("0.5"))).as_deref(), Some("0.5")); - assert_eq!(text(owned(Value::from(vec![1u32, 2]))), None); - // Each setting reads its own type of value, the cross-desktop one first. - let [(_, motion, reduced), (_, _, on), (_, _, factor)] = SETTINGS; - assert_eq!(motion, "reduced-motion"); - assert_eq!(reduced(&text(owned(Value::U32(1))).unwrap()), Some(false)); - assert_eq!(reduced(&text(owned(Value::U32(0))).unwrap()), Some(true)); - assert_eq!(on(&text(owned(Value::from(false))).unwrap()), Some(false)); - assert_eq!(factor(&text(owned(Value::from("0"))).unwrap()), Some(false)); - assert_eq!(factor(&text(owned(Value::F64(0.5))).unwrap()), Some(true)); + assert_eq!(as_text(owned(nested)).as_deref(), Some("1")); + assert_eq!(as_text(owned(Value::from(false))).as_deref(), Some("false")); + assert_eq!(as_text(owned(Value::F64(0.5))).as_deref(), Some("0.5")); + assert_eq!(as_text(owned(Value::from("0"))).as_deref(), Some("0")); + assert_eq!(as_text(owned(Value::from(vec![1u32, 2]))), None); + assert_eq!(SETTINGS[0].1, "reduced-motion", "the cross-desktop setting is asked first"); } } } + /// The desktop's own setting, without the portal. mod desktop { use std::path::PathBuf; + use super::freedesktop; + /// A settings file is a few kilobytes; a larger one isn't read. const MAX_CONFIG_BYTES: u64 = 1 << 20; pub fn read() -> Option { let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); - super::super::desktop_setting(&desktop, &config_file, &gsettings) - } - - fn config_home() -> Option { - let dir = |key: &str| std::env::var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from); - dir("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| dir("HOME").map(|home| home.join(".config"))) + freedesktop::without_portal(&desktop, &config_file, &gsettings) } fn config_file(name: &str) -> Option { use std::io::Read as _; + let dir = |key: &str| std::env::var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from); + let config_home = dir("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| dir("HOME").map(|home| home.join(".config")))?; let mut text = String::new(); - std::fs::File::open(config_home()?.join(name)).ok()?.take(MAX_CONFIG_BYTES).read_to_string(&mut text).ok()?; + std::fs::File::open(config_home.join(name)).ok()?.take(MAX_CONFIG_BYTES).read_to_string(&mut text).ok()?; Some(text) } @@ -257,188 +254,22 @@ mod platform { } } -/// `true` or `false` (GSettings, the portal), `1` or `0` (a GTK settings file): animations are on. -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -fn enabled(value: &str) -> Option { - match value.trim().to_ascii_lowercase().as_str() { - "true" | "1" => Some(true), - "false" | "0" => Some(false), - _ => None, +#[cfg(not(any(unix, target_os = "windows")))] +mod platform { + pub fn service() -> Option { + None } } -/// KDE's animation speed factor: 0 turns animations off. -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -fn duration_factor(value: &str) -> Option { - value.trim().parse::().ok().filter(|factor| factor.is_finite()).map(|factor| factor > 0.0) -} - -/// The portal's `reduced-motion`: 1 asks for less motion; 0 and the values it may grow don't. -#[cfg(any(test, target_os = "linux"))] -fn reduced_motion(value: &str) -> Option { - value.trim().parse::().ok().map(|code| code != 1) -} - -/// The last value of `key` in `[section]` of an INI-style file (KDE's config, GTK's settings). -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -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() { - let line = line.trim(); - if let Some(name) = line.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) { - inside = name == section; - } else if inside && let Some((name, value)) = line.split_once('=') { - // KDE marks an entry the user may not change as `Key[$i]=value`. - let name = name.split_once('[').map_or(name, |(name, _)| name); - if name.trim() == key { - found = Some(value.trim()); - } - } - } - found -} - -/// The desktop's setting without the portal. `desktop` is `XDG_CURRENT_DESKTOP`, `file` reads a -/// file under the user's config directory and `gsettings` runs `gsettings get `. -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -fn desktop_setting(desktop: &str, file: &dyn Fn(&str) -> Option, gsettings: &dyn Fn(&str, &str) -> Option) -> Option { - let running = |name: &str| desktop.split(':').any(|part| part.eq_ignore_ascii_case(name)); - let in_file = |name: &str, section: &str, key: &str, animations: fn(&str) -> Option| animations(ini_value(&file(name)?, section, key)?); - if running("KDE") - && let Some(animations) = in_file("kdeglobals", "KDE", "AnimationDurationFactor", duration_factor) - { - return Some(animations); - } - let schema = if running("MATE") { "org.mate.interface" } else { "org.gnome.desktop.interface" }; - let shell = gsettings(schema, "enable-animations").and_then(|out| enabled(&out)); - if shell == Some(false) { - return shell; - } - // `true` may only be the schema's default on a desktop that doesn't use it. GTK's own file - // is what a bare window manager's user writes, and what KDE keeps in step with its setting. - ["gtk-4.0/settings.ini", "gtk-3.0/settings.ini"].iter().find_map(|name| in_file(name, "Settings", "gtk-enable-animations", enabled)).or(shell) -} - -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -fn code_of(animations: Option) -> u8 { - match animations { - None => 0, - Some(true) => 1, - Some(false) => 2, - } -} - -#[cfg(any(test, all(unix, not(target_os = "macos"))))] -fn decode(code: u8) -> Option { - match code { - 1 => Some(true), - 2 => Some(false), - _ => None, - } -} - -#[cfg(test)] +#[cfg(all(test, target_os = "windows"))] mod tests { - use super::*; - - #[test] - fn each_setting_reads_its_own_values() { - for (s, animations) in - [("true\n", Some(true)), ("false\n", Some(false)), ("1", Some(true)), ("0", Some(false)), ("FALSE", Some(false)), ("", None), ("maybe", None)] - { - assert_eq!(enabled(s), animations, "{s:?}"); - } - for (s, animations) in [ - ("0", Some(false)), - ("0.0", Some(false)), - ("0.5", Some(true)), - ("1", Some(true)), - ("-1", Some(false)), - ("", None), - ("fast", None), - ("NaN", None), - ("inf", None), - ] { - assert_eq!(duration_factor(s), animations, "{s:?}"); - } - // reduced-motion: only 1 asks for less motion; unknown values mean no preference. - for (s, animations) in [("0", Some(true)), ("1", Some(false)), ("2", Some(true)), ("true", None), ("-1", None), ("", None)] { - assert_eq!(reduced_motion(s), animations, "{s:?}"); - } - // The shared value round-trips, and a stray code is "unknown". - for animations in [None, Some(true), Some(false)] { - assert_eq!(decode(code_of(animations)), animations); - } - assert_eq!(decode(9), None); - } - - #[test] - fn ini_values_come_from_their_own_section() { - let kde = "[General]\nAnimationDurationFactor=3\n\n[KDE]\nSingleClick=false\n AnimationDurationFactor = 0 \n[KDE][Sub]\nAnimationDurationFactor=7\n"; - assert_eq!(ini_value(kde, "KDE", "AnimationDurationFactor"), Some("0")); - assert_eq!(ini_value(kde, "KDE", "Missing"), None); - assert_eq!(ini_value("[KDE]\nAnimationDurationFactor[$i]=0.5\n", "KDE", "AnimationDurationFactor"), Some("0.5"), "an immutable entry"); - assert_eq!( - ini_value("[Settings]\ngtk-enable-animations=1\ngtk-enable-animations=0\n", "Settings", "gtk-enable-animations"), - Some("0"), - "the last one wins" - ); - // Hostile text: no section, no `=`, stray brackets, non-ASCII. - for junk in ["", "AnimationDurationFactor=0", "[KDE", "[KDE]\n=\n[]\n]]][[[\n", "[KDE]\nклавиша=значение\n\u{0}\u{feff}"] { - assert_eq!(ini_value(junk, "KDE", "AnimationDurationFactor"), None, "{junk:?}"); - } - } - - #[test] - fn the_desktop_setting_is_read_where_each_desktop_keeps_it() { - let files = |kde: Option<&'static str>, gtk: Option<&'static str>| { - move |name: &str| match name { - "kdeglobals" => kde.map(String::from), - "gtk-3.0/settings.ini" => gtk.map(String::from), - _ => None, - } - }; - let none = |_: &str, _: &str| -> Option { None }; - let gnome = |on: &'static str| { - move |schema: &str, key: &str| (schema == "org.gnome.desktop.interface" && key == "enable-animations").then(|| format!("{on}\n")) - }; - let kde_off = Some("[KDE]\nAnimationDurationFactor=0\n"); - let gtk_off = Some("[Settings]\ngtk-enable-animations=false\n"); - - // KDE Plasma: its own file, only when Plasma is the desktop running. - assert_eq!(desktop_setting("KDE", &files(kde_off, None), &none), Some(false)); - assert_eq!(desktop_setting("KDE", &files(Some("[KDE]\nAnimationDurationFactor=0.5\n"), gtk_off), &none), Some(true)); - assert_eq!(desktop_setting("ubuntu:GNOME", &files(kde_off, None), &gnome("true")), Some(true), "a leftover kdeglobals is not GNOME's setting"); - // Plasma without the entry (animations at their default speed) falls through to GTK's file. - assert_eq!(desktop_setting("KDE", &files(Some("[KDE]\nSingleClick=false\n"), gtk_off), &none), Some(false)); - // GNOME and the desktops that share its schema. - assert_eq!(desktop_setting("GNOME", &files(None, None), &gnome("false")), Some(false)); - assert_eq!(desktop_setting("GNOME", &files(None, None), &gnome("true")), Some(true)); - // MATE keeps the same key in its own schema. - let mate = |schema: &str, _: &str| (schema == "org.mate.interface").then(|| "false\n".to_string()); - assert_eq!(desktop_setting("MATE", &files(None, None), &mate), Some(false)); - assert_eq!(desktop_setting("GNOME", &files(None, None), &mate), None); - // A bare window manager: GTK's settings file, which also outranks a schema default. - assert_eq!(desktop_setting("sway", &files(None, gtk_off), &none), Some(false)); - assert_eq!(desktop_setting("", &files(None, gtk_off), &gnome("true")), Some(false)); - assert_eq!(desktop_setting("", &files(None, Some("[Settings]\ngtk-enable-animations=1\n")), &none), Some(true)); - // Nothing to read, or nothing readable: unknown, never a panic. - assert_eq!(desktop_setting("", &files(None, None), &none), None); - assert_eq!( - desktop_setting("KDE:\u{0}::", &files(Some("\u{0}[[[=]]]"), Some("=\n[Settings]\ngtk-enable-animations=perhaps")), &|_, _| Some("\u{fffd}".into())), - None - ); - } - /// The real setting of the machine the tests run on: whatever it is, reading it doesn't /// panic and the service passes it on (`--nocapture` shows it). - #[cfg(target_os = "windows")] #[test] fn windows_reports_its_animation_setting() { - let animations = platform::read(); + let animations = super::platform::read(); println!("UISettings.AnimationsEnabled: {animations:?}"); - let service = platform::service().expect("service"); + let service = super::platform::service().expect("service"); assert_eq!(service(&egui::Context::default()), animations); } } diff --git a/apps/photocraft/src/animations/freedesktop.rs b/apps/photocraft/src/animations/freedesktop.rs new file mode 100644 index 0000000000..437ab5c42a --- /dev/null +++ b/apps/photocraft/src/animations/freedesktop.rs @@ -0,0 +1,150 @@ +//! Where Linux and BSD desktops keep their animation setting, and how to read its value. +//! +//! Plain functions over text, so the tests run on every platform. Each one answers whether +//! animations are on, or `None` when the value doesn't parse (the next source is asked then). + +/// GSettings' and the portal's `true`/`false`, or GTK's `1`/`0`. +pub fn from_enabled(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "true" | "1" => Some(true), + "false" | "0" => Some(false), + _ => None, + } +} + +/// KDE's animation speed factor: 0 turns animations off. +pub fn from_duration_factor(value: &str) -> Option { + value.trim().parse::().ok().filter(|factor| factor.is_finite()).map(|factor| factor > 0.0) +} + +/// The settings portal's `reduced-motion`: 1 asks for less motion; 0 and any value added later +/// mean no preference. +#[cfg(any(test, target_os = "linux"))] +pub fn from_reduced_motion(value: &str) -> Option { + value.trim().parse::().ok().map(|code| code != 1) +} + +/// The desktop's setting when there is no settings portal to ask. `desktop` is +/// `XDG_CURRENT_DESKTOP`, `config_file` reads a file in the user's config directory and +/// `gsettings` runs `gsettings get `. +pub fn without_portal(desktop: &str, config_file: &dyn Fn(&str) -> Option, gsettings: &dyn Fn(&str, &str) -> Option) -> Option { + let running = |name: &str| desktop.split(':').any(|part| part.eq_ignore_ascii_case(name)); + let in_file = |file: &str, section: &str, key: &str, parse: fn(&str) -> Option| parse(ini_value(&config_file(file)?, section, key)?); + + // KDE Plasma keeps it in its own file. A kdeglobals left over from another desktop doesn't count. + if running("KDE") + && let Some(animations) = in_file("kdeglobals", "KDE", "AnimationDurationFactor", from_duration_factor) + { + return Some(animations); + } + // GNOME and the desktops built on it, or MATE's copy of the same key. + let schema = if running("MATE") { "org.mate.interface" } else { "org.gnome.desktop.interface" }; + let gnome = gsettings(schema, "enable-animations").and_then(|out| from_enabled(&out)); + if gnome == Some(false) { + return gnome; + } + // `true` may only be the schema's default on a desktop that doesn't use it, so GTK's own + // file comes first: it is what a bare window manager's user writes, and what KDE keeps in step. + ["gtk-4.0/settings.ini", "gtk-3.0/settings.ini"].iter().find_map(|file| in_file(file, "Settings", "gtk-enable-animations", from_enabled)).or(gnome) +} + +/// The last value of `key` in `[section]` of an INI-style file (KDE's config, GTK's settings). +pub fn ini_value<'a>(text: &'a str, section: &str, key: &str) -> Option<&'a str> { + let mut in_section = false; + let mut found = None; + for line in text.lines().map(str::trim) { + if let Some(name) = line.strip_prefix('[').and_then(|rest| rest.strip_suffix(']')) { + in_section = name == section; + } else if in_section && let Some((name, value)) = line.split_once('=') { + // KDE marks an entry the user may not change as `Key[$i]=value`. + let name = name.split_once('[').map_or(name, |(name, _)| name); + if name.trim() == key { + found = Some(value.trim()); + } + } + } + found +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn each_kind_of_value_reads_as_on_or_off() { + for (value, animations) in + [("true\n", Some(true)), ("false\n", Some(false)), ("1", Some(true)), ("0", Some(false)), ("FALSE", Some(false)), ("", None), ("maybe", None)] + { + assert_eq!(from_enabled(value), animations, "{value:?}"); + } + for (value, animations) in [ + ("0", Some(false)), + ("0.0", Some(false)), + ("0.5", Some(true)), + ("1", Some(true)), + ("-1", Some(false)), + ("", None), + ("fast", None), + ("NaN", None), + ("inf", None), + ] { + assert_eq!(from_duration_factor(value), animations, "{value:?}"); + } + for (value, animations) in [("0", Some(true)), ("1", Some(false)), ("2", Some(true)), ("true", None), ("-1", None), ("", None)] { + assert_eq!(from_reduced_motion(value), animations, "{value:?}"); + } + } + + #[test] + fn ini_values_come_from_their_own_section() { + let kde = "[General]\nAnimationDurationFactor=3\n\n[KDE]\nSingleClick=false\n AnimationDurationFactor = 0 \n[KDE][Sub]\nAnimationDurationFactor=7\n"; + assert_eq!(ini_value(kde, "KDE", "AnimationDurationFactor"), Some("0")); + assert_eq!(ini_value(kde, "KDE", "Missing"), None); + assert_eq!(ini_value("[KDE]\nAnimationDurationFactor[$i]=0.5\n", "KDE", "AnimationDurationFactor"), Some("0.5"), "an immutable entry"); + let gtk = "[Settings]\ngtk-enable-animations=1\ngtk-enable-animations=0\n"; + assert_eq!(ini_value(gtk, "Settings", "gtk-enable-animations"), Some("0"), "the last one wins"); + // Hostile text: no section, no `=`, stray brackets, non-ASCII. + for junk in ["", "AnimationDurationFactor=0", "[KDE", "[KDE]\n=\n[]\n]]][[[\n", "[KDE]\nклавиша=значение\n\u{0}\u{feff}"] { + assert_eq!(ini_value(junk, "KDE", "AnimationDurationFactor"), None, "{junk:?}"); + } + } + + #[test] + fn without_the_portal_each_desktop_is_read_where_it_keeps_the_setting() { + let files = |kdeglobals: Option<&'static str>, gtk3: Option<&'static str>| { + move |file: &str| match file { + "kdeglobals" => kdeglobals.map(String::from), + "gtk-3.0/settings.ini" => gtk3.map(String::from), + _ => None, + } + }; + let no_gsettings = |_: &str, _: &str| -> Option { None }; + let gnome = |on: &'static str| { + move |schema: &str, key: &str| (schema == "org.gnome.desktop.interface" && key == "enable-animations").then(|| format!("{on}\n")) + }; + let kde_off = Some("[KDE]\nAnimationDurationFactor=0\n"); + let gtk_off = Some("[Settings]\ngtk-enable-animations=false\n"); + + // KDE Plasma: its own file, only while Plasma is the desktop. + assert_eq!(without_portal("KDE", &files(kde_off, None), &no_gsettings), Some(false)); + assert_eq!(without_portal("KDE", &files(Some("[KDE]\nAnimationDurationFactor=0.5\n"), gtk_off), &no_gsettings), Some(true)); + assert_eq!(without_portal("ubuntu:GNOME", &files(kde_off, None), &gnome("true")), Some(true), "a leftover kdeglobals is not GNOME's setting"); + // Plasma without the entry (animations at their default speed) falls through to GTK's file. + assert_eq!(without_portal("KDE", &files(Some("[KDE]\nSingleClick=false\n"), gtk_off), &no_gsettings), Some(false)); + // GNOME and the desktops that share its schema. + assert_eq!(without_portal("GNOME", &files(None, None), &gnome("false")), Some(false)); + assert_eq!(without_portal("GNOME", &files(None, None), &gnome("true")), Some(true)); + // MATE keeps the same key in its own schema. + let mate = |schema: &str, _: &str| (schema == "org.mate.interface").then(|| "false\n".to_string()); + assert_eq!(without_portal("MATE", &files(None, None), &mate), Some(false)); + assert_eq!(without_portal("GNOME", &files(None, None), &mate), None); + // A bare window manager: GTK's settings file, which also outranks a schema default. + assert_eq!(without_portal("sway", &files(None, gtk_off), &no_gsettings), Some(false)); + assert_eq!(without_portal("", &files(None, gtk_off), &gnome("true")), Some(false)); + assert_eq!(without_portal("", &files(None, Some("[Settings]\ngtk-enable-animations=1\n")), &no_gsettings), Some(true)); + // Nothing to read, or nothing readable: unknown, never a panic. + assert_eq!(without_portal("", &files(None, None), &no_gsettings), None); + let unreadable = files(Some("\u{0}[[[=]]]"), Some("=\n[Settings]\ngtk-enable-animations=perhaps")); + assert_eq!(without_portal("KDE:\u{0}::", &unreadable, &|_, _| Some("\u{fffd}".into())), None); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 36dca3dbf5..50f3b47ae4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -3260,14 +3260,12 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: let bars_id = egui::Id::new(("pc-canvas-bars-hover", idx)); let over_bars = ctx.data(|d| d.get_temp::(bars_id)).unwrap_or(false); let nav_hovered = response.hovered() || free_hover || over_bars; - // Interface › Enable Animations off: the wheel moves the canvas without a glide (#5721). - let wheel = crate::wheel_nav::read_with( + let wheel = crate::wheel_nav::read( &ctx, app.session.prefs().general.zoom_with_scroll_wheel, app.session.prefs().enhanced_controls.zoom_with_trackpad_pinch, response.id.with("wheel"), nav_hovered, - !app.prefs_rt.reduce_motion, ); if nav_hovered { let pointer = ui.input(|i| i.pointer.hover_pos()); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 13bff3f225..46b15ba93a 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1896,9 +1896,8 @@ impl eframe::App for PhotocraftApp { self.collect_screenshots(ctx); self.issue_screenshots(ctx); prefs_ui::tick(self, ctx); - // Animation Effects off: the wheel scrolls its whole distance at once, before anything - // reads this frame's scroll (wheel_nav.rs). - if self.prefs_rt.reduce_motion { + // Before anything reads this frame's scroll (see `wheel_nav::unsmooth`). + if self.prefs_rt.animations_off { wheel_nav::unsmooth(ctx); } monitor_status::poll_frame(self, ctx, frame); diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index dc64c84297..4cb90dfafa 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -52,8 +52,8 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, - /// Interface › Animation Effects came out as off this frame (see `sync_animations`). - pub(crate) reduce_motion: bool, + /// Interface › Animation Effects resolved to off this frame (see `sync_animations`). + pub(crate) animations_off: bool, pub(crate) selected_tool: Option, } @@ -412,8 +412,8 @@ fn sync_tooltips(app: &PhotocraftApp, ctx: &egui::Context) { } } -/// Interface › Animation Effects, resolved: on or off as chosen, or the operating system's own -/// setting for Use System Setting (on where the platform cannot tell). +/// Interface › Animation Effects, resolved: on or off as chosen, or for Use System Setting what +/// the operating system says (on when it can't tell). fn animations_on(app: &PhotocraftApp, ctx: &egui::Context) -> bool { match app.session.prefs().interface.animation_effects { prefs::AnimationEffects::On => true, @@ -422,13 +422,14 @@ fn animations_on(app: &PhotocraftApp, ctx: &egui::Context) -> bool { } } -/// Interface › Animation Effects: off, egui's fades and slides take no time and scroll areas jump -/// straight to their target (#3273); the wheel's own glide is taken out by `wheel_nav::unsmooth`. -/// Re-checked every frame because a theme change rebuilds the style and the system's setting can -/// change; both the dark and light styles are set, so a system appearance switch keeps it. +/// Interface › Animation Effects: off, egui's fades and slides take no time and `scroll_to` jumps +/// straight to its target (#3273); `PhotocraftApp::logic` takes out the wheel's glide +/// (`wheel_nav::unsmooth`). Checked every frame: a theme change rebuilds the style and the +/// system's setting can change. Both the dark and light styles are set, so an appearance switch +/// keeps it. fn sync_animations(app: &mut PhotocraftApp, ctx: &egui::Context) { let on = animations_on(app, ctx); - app.prefs_rt.reduce_motion = !on; + app.prefs_rt.animations_off = !on; let time = if on { egui::Style::default().animation_time } else { 0.0 }; if ctx.global_style().animation_time != time { let scroll = if on { egui::style::ScrollAnimation::default() } else { egui::style::ScrollAnimation::none() }; @@ -3470,63 +3471,76 @@ mod tests { } } + /// egui's `animation_time` in the dark and the light style. + fn animation_times(ctx: &egui::Context) -> [f32; 2] { + [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time) + } + #[test] - fn animation_effects_follow_the_choice_or_the_system_and_are_remembered() { - use std::{cell::Cell, rc::Rc}; + fn animation_effects_off_stops_egui_animations_and_is_remembered() { let on = egui::Style::default().animation_time; - let both = |ctx: &egui::Context| [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time); + assert!(on > 0.0, "egui animates by default"); // Saved off: the first frame after a restart applies it to both appearance styles. let (mut app, _) = app_with_saved(Some(json!({"interface": {"animationEffects": "off"}}).to_string())); let ctx = egui::Context::default(); tick(&mut app, &ctx); - assert_eq!(both(&ctx), [0.0, 0.0]); + assert_eq!(animation_times(&ctx), [0.0, 0.0]); assert_eq!(ctx.global_style().scroll_animation.duration.max, 0.0); - assert!(app.prefs_rt.reduce_motion); + assert!(app.prefs_rt.animations_off); // A theme change rebuilds the style; the next frame turns animations off again. app.apply_theme(&ctx, crate::theme::ThemeKind::StudioLight); tick(&mut app, &ctx); - assert_eq!(both(&ctx), [0.0, 0.0]); + assert_eq!(animation_times(&ctx), [0.0, 0.0]); app.run("prefs.set", json!({"values": {"interface.animationEffects": "on"}})).unwrap(); tick(&mut app, &ctx); - assert_eq!(both(&ctx), [on, on]); - assert!(on > 0.0 && ctx.global_style().scroll_animation.duration.max > 0.0 && !app.prefs_rt.reduce_motion); + assert_eq!(animation_times(&ctx), [on, on]); + assert!(ctx.global_style().scroll_animation.duration.max > 0.0 && !app.prefs_rt.animations_off); + } - // Use System Setting, the default, follows the platform as it changes. - let system = Rc::new(Cell::new(Some(false))); + #[test] + fn use_system_setting_follows_the_platform() { + use std::{cell::Cell, rc::Rc}; + let on = egui::Style::default().animation_time; + let system = Rc::new(Cell::new(None)); let (mut app, _) = app_with_store(); - assert_eq!(app.session.prefs().interface.animation_effects, prefs::AnimationEffects::System); let read = system.clone(); app.services.system_animations = Some(Box::new(move |_| read.get())); let ctx = egui::Context::default(); + assert_eq!(app.session.prefs().interface.animation_effects, prefs::AnimationEffects::System, "the default"); + // As the system's setting changes; no answer keeps animations on. for (answer, time) in [(Some(false), 0.0), (Some(true), on), (None, on), (Some(false), 0.0)] { system.set(answer); tick(&mut app, &ctx); - assert_eq!(both(&ctx), [time, time], "the system says {answer:?}"); - assert_eq!(app.prefs_rt.reduce_motion, time == 0.0); + assert_eq!(animation_times(&ctx), [time, time], "the system says {answer:?}"); } // On and Off hold whatever the system says. for (answer, choice, time) in [(Some(false), "on", on), (Some(true), "off", 0.0), (Some(true), "system", on)] { system.set(answer); app.run("prefs.set", json!({"values": {"interface.animationEffects": choice}})).unwrap(); tick(&mut app, &ctx); - assert_eq!(both(&ctx), [time, time], "{choice} while the system says {answer:?}"); + assert_eq!(animation_times(&ctx), [time, time], "{choice} while the system says {answer:?}"); } - // A platform that can't tell (no service): Use System Setting keeps animations on. + // A platform without the service can't tell: animations stay on. let (mut plain, _) = app_with_store(); let ctx = egui::Context::default(); tick(&mut plain, &ctx); - assert_eq!(both(&ctx), [on, on]); - // The Enable Animations checkbox this replaced: a saved "off" is still off. - let (mut old, _) = app_with_saved(Some(json!({"interface": {"enableAnimations": false}}).to_string())); - let ctx = egui::Context::default(); - tick(&mut old, &ctx); - assert_eq!(both(&ctx), [0.0, 0.0]); - // A hand-edited value that is no choice doesn't crash: the defaults stay. - for junk in [json!("nope"), json!(7), json!(null)] { - let (mut bad, _) = app_with_saved(Some(json!({"interface": {"animationEffects": junk}}).to_string())); + assert_eq!(animation_times(&ctx), [on, on]); + } + + #[test] + fn old_and_hand_edited_animation_settings_load_safely() { + let on = egui::Style::default().animation_time; + let after_restart = |interface: Value| { + let (mut app, _) = app_with_saved(Some(json!({"interface": interface}).to_string())); let ctx = egui::Context::default(); - tick(&mut bad, &ctx); - assert_eq!(both(&ctx), [on, on]); + tick(&mut app, &ctx); + animation_times(&ctx) + }; + // The Enable Animations checkbox this replaced: a saved "off" is still off. + assert_eq!(after_restart(json!({"enableAnimations": false})), [0.0, 0.0]); + // A value that is no choice doesn't crash: the defaults stay. + for junk in [json!("nope"), json!(7), json!(null)] { + assert_eq!(after_restart(json!({"animationEffects": junk})), [on, on], "{junk}"); } } diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index 900ea3779a..67e44ae608 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -170,28 +170,36 @@ pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { } } -fn touch_id() -> Id { - Id::new("pc-wheel-touch") +fn gesture_id() -> Id { + Id::new("pc-wheel-gesture") } -/// What this frame's wheel events scroll in all, in points: each one in its unit and folded -/// sideways or upright by its modifiers, as egui does before it smooths them. `touch` follows -/// trackpad gestures (the ones with a begin and an end phase). `None` leaves egui's own value -/// alone: for a frame with part of such a gesture, which egui applies as it arrives (and whose -/// modifiers it holds from the start), for a wheel event that zooms, and for a hostile sum. -fn arrived(events: &[Event], options: &egui::InputOptions, page: f32, touch: &mut bool) -> Option { - let mut gesture = *touch; +/// What this frame's wheel events scroll in all, in points, each folded sideways or upright by +/// its modifiers as egui folds it. `in_gesture` carries from frame to frame whether a trackpad +/// gesture (one with begin and end phases) is in progress. +/// +/// `None` keeps egui's own scroll: in a frame with any part of such a gesture, which egui applies +/// at once and with the modifiers it started with; for a wheel event that zooms; and for a sum +/// that isn't finite. +fn unsmoothed_scroll(events: &[Event], options: &egui::InputOptions, page: f32, in_gesture: &mut bool) -> Option { + let mut gesture_frame = *in_gesture; let mut sum = Vec2::ZERO; for event in events { let Event::MouseWheel { unit, delta, phase, modifiers } = event else { continue }; match phase { - TouchPhase::Start => (*touch, gesture) = (true, true), - TouchPhase::End | TouchPhase::Cancel => (*touch, gesture) = (false, true), + TouchPhase::Start => { + *in_gesture = true; + gesture_frame = true; + } + TouchPhase::End | TouchPhase::Cancel => { + *in_gesture = false; + gesture_frame = true; + } TouchPhase::Move => { if modifiers.matches_any(options.zoom_modifier) { return None; } - let delta = *delta + let points = *delta * match unit { MouseWheelUnit::Point => 1.0, MouseWheelUnit::Line => options.line_scroll_speed, @@ -200,35 +208,32 @@ fn arrived(events: &[Event], options: &egui::InputOptions, page: f32, touch: &mu let sideways = modifiers.matches_any(options.horizontal_scroll_modifier); let upright = modifiers.matches_any(options.vertical_scroll_modifier); sum += match (sideways, upright) { - (true, false) => Vec2::new(delta.x + delta.y, 0.0), - (false, true) => Vec2::new(0.0, delta.x + delta.y), - _ => delta, + (true, false) => Vec2::new(points.x + points.y, 0.0), + (false, true) => Vec2::new(0.0, points.x + points.y), + _ => points, }; } } } - (!gesture && sum.x.is_finite() && sum.y.is_finite()).then_some(sum) + (!gesture_frame && sum.x.is_finite() && sum.y.is_finite()).then_some(sum) } -/// Interface › Animation Effects off: scroll the whole distance of a wheel notch in the frame -/// it arrives. egui spreads a notch over the next several frames (a glide of about 0.2 s, with -/// no setting to turn it off), so this replaces the frame's smoothed scroll with everything its -/// wheel events add up to; the frames after it carry only the rest of that glide and no wheel -/// events, and so scroll nothing. Call it once a frame before anything reads the scroll -/// (`PhotocraftApp::logic`). Zooming already reads the wheel events themselves ([`read`]). +/// Interface › Animation Effects off: a wheel notch scrolls its whole distance in the frame it +/// arrives. egui spreads each notch over about 0.2 s and has no setting to stop it, so this +/// replaces the frame's smoothed scroll with what the frame's own wheel events add up to. The +/// frames after a notch carry only the rest of egui's glide, and so scroll nothing. +/// +/// Call it once a frame, before anything reads the scroll (`PhotocraftApp::logic` does). pub fn unsmooth(ctx: &Context) { let options = ctx.options(|o| o.input_options); - let was = ctx.data(|d| d.get_temp::(touch_id())).unwrap_or(false); - let mut touch = was; + let mut in_gesture = ctx.data(|d| d.get_temp::(gesture_id())).unwrap_or(false); ctx.input_mut(|i| { let page = i.viewport_rect().height(); - if let Some(scroll) = arrived(&i.events, &options, page, &mut touch) { + if let Some(scroll) = unsmoothed_scroll(&i.events, &options, page, &mut in_gesture) { i.smooth_scroll_delta = scroll; } }); - if touch != was { - ctx.data_mut(|d| d.insert_temp(touch_id(), touch)); - } + ctx.data_mut(|d| d.insert_temp(gesture_id(), in_gesture)); } fn alt_id() -> Id { @@ -262,13 +267,6 @@ const SNAP_IDLE_TIMEOUT: f64 = 0.5; /// accumulator per viewport. `hovered` gates accumulation: only the viewport receiving /// navigation may add raw input to the snap residual. pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool) -> Option { - read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true) -} - -/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's -/// smoothed delta); off, as with Interface › Enable Animations off, the view moves the whole notch -/// in the frame the wheel turns and stops there (#5721), as scroll areas already do. -pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool) -> Option { let notch = ctx.options(|o| o.input_options.line_scroll_speed); // --- Modifier tracking (always runs for all callers) --- @@ -387,8 +385,6 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: d.remove::(snap_time_id(owner)); }); } - // Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail). - let scroll = if smooth || alt || shift { scroll } else { raw }; classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, notch }) } } @@ -441,42 +437,6 @@ mod tests { (a - b).length() < 0.01 } - /// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and - /// nothing after; smoothed (the default) it glides, reaching the same total over later frames. - #[test] - fn unsmoothed_wheel_pans_at_once_without_a_glide() { - let pans = |smooth: bool| -> Vec { - let owner = Id::new("test-unsmoothed"); - let ctx = Context::default(); - configure(&ctx); - (0..30) - .map(|n| { - let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; - let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; - let mut pan = Vec2::ZERO; - let mut out = ctx.run_ui(raw, |ui| { - if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), false, true, owner, true, smooth) { - pan = d; - } - }); - out.textures_delta.clear(); - pan - }) - .collect() - }; - let notch = { - let ctx = Context::default(); - configure(&ctx); - ctx.options(|o| o.input_options.line_scroll_speed) - }; - let direct = pans(false); - assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); - assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); - let smooth = pans(true); - assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); - assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); - } - #[test] fn plain_scroll_pans() { assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); @@ -711,6 +671,48 @@ mod tests { assert!(matches!(ev[0], Event::MouseWheel { .. })); } + // --- Interface › Animation Effects off (`unsmooth`) + + /// #5721: with Animation Effects off ([`unsmooth`]) a wheel notch pans the canvas the whole + /// notch in the frame it arrives and nothing after; on, it glides, reaching the same total + /// over later frames. + #[test] + fn unsmoothed_wheel_pans_at_once_without_a_glide() { + let pans = |smooth: bool| -> Vec { + let owner = Id::new("test-unsmoothed"); + let ctx = Context::default(); + configure(&ctx); + (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if !smooth { + unsmooth(ui.ctx()); + } + if let Some(Wheel::Pan(d)) = read(ui.ctx(), false, true, owner, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect() + }; + let notch = { + let ctx = Context::default(); + configure(&ctx); + ctx.options(|o| o.input_options.line_scroll_speed) + }; + let direct = pans(false); + assert!(near(direct[0], Vec2::new(0.0, -notch)), "the whole notch at once: {:?}", direct[0]); + assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "no glide after it"); + let smooth = pans(true); + assert!(smooth[0].y.abs() < notch - 0.5, "smoothed, the first frame moves only part of it: {:?}", smooth[0]); + assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); + } + /// `smooth_scroll_delta` as the UI reads it on each of 30 frames at 60 fps, in a context set /// up like the app's; `off` is Animation Effects off ([`unsmooth`] at the start of the frame). fn scrolled(frames: Vec>, off: bool) -> Vec { @@ -769,23 +771,17 @@ mod tests { let glide = total(&scrolled(vec![events.clone()], false)); assert!((glide - want).length() < 1.0, "the same distance as with animations on: {events:?}: {glide:?}"); } - // The canvas pans by all of it on that frame too, and Alt + wheel still zooms one step. + // Alt + wheel still zooms one step, and doesn't pan as well. let ctx = Context::default(); configure(&ctx); + let raw = RawInput { time: Some(0.0), predicted_dt: 1.0 / 60.0, events: vec![wheel(Vec2::new(0.0, 1.0), Modifiers::ALT)], ..Default::default() }; let mut seen = None; - for (time, modifiers) in [(0.0, Modifiers::NONE), (1.0, Modifiers::ALT)] { - let raw = RawInput { time: Some(time), predicted_dt: 1.0 / 60.0, events: vec![wheel(Vec2::new(0.0, 1.0), modifiers)], ..Default::default() }; - let mut out = ctx.run_ui(raw, |ui| { - unsmooth(ui.ctx()); - seen = read(ui.ctx(), false, true, Id::new("test-unsmooth"), true); - }); - out.textures_delta.clear(); - if modifiers.alt { - assert!(matches!(seen, Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-4), "{seen:?}"); - } else { - assert_eq!(seen, Some(Wheel::Pan(Vec2::new(0.0, 40.0)))); - } - } + let mut out = ctx.run_ui(raw, |ui| { + unsmooth(ui.ctx()); + seen = read(ui.ctx(), false, true, Id::new("test-alt"), true); + }); + out.textures_delta.clear(); + assert!(matches!(seen, Some(Wheel::Zoom(f)) if (f - 1.1).abs() < 1e-4), "{seen:?}"); } /// What the setting is for: an egui scroll area (panels, lists, long menus) is at its new @@ -852,23 +848,23 @@ mod tests { #[test] fn unsmoothing_skips_zoom_and_hostile_numbers() { let options = egui::InputOptions::default(); - let mut touch = false; + let mut in_gesture = false; let zoom = [wheel(Vec2::new(0.0, 1.0), CTRL)]; - assert_eq!(arrived(&zoom, &options, 600.0, &mut touch), None, "egui's default: ⌘/Ctrl + wheel zooms"); + assert_eq!(unsmoothed_scroll(&zoom, &options, 600.0, &mut in_gesture), None, "egui's default: ⌘/Ctrl + wheel zooms"); let plain = [wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)]; - assert_eq!(arrived(&plain, &options, 600.0, &mut touch), Some(Vec2::new(0.0, options.line_scroll_speed))); - assert_eq!(arrived(&[], &options, 600.0, &mut touch), Some(Vec2::ZERO), "no wheel event: the rest of a glide is dropped"); + assert_eq!(unsmoothed_scroll(&plain, &options, 600.0, &mut in_gesture), Some(Vec2::new(0.0, options.line_scroll_speed))); + assert_eq!(unsmoothed_scroll(&[], &options, 600.0, &mut in_gesture), Some(Vec2::ZERO), "no wheel event: the rest of a glide is dropped"); for bad in [f32::NAN, f32::INFINITY, -f32::INFINITY, f32::MAX] { for page in [600.0, f32::NAN, f32::INFINITY, 0.0, -1.0] { for unit in [MouseWheelUnit::Point, MouseWheelUnit::Line, MouseWheelUnit::Page] { let events = [Event::MouseWheel { unit, delta: Vec2::new(bad, bad), phase: TouchPhase::Move, modifiers: Modifiers::SHIFT }]; - if let Some(sum) = arrived(&events, &options, page, &mut touch) { + if let Some(sum) = unsmoothed_scroll(&events, &options, page, &mut in_gesture) { assert!(sum.x.is_finite() && sum.y.is_finite(), "{sum:?} from {bad} {page} {unit:?}"); } } } } - assert!(!touch, "no gesture phase was seen"); + assert!(!in_gesture, "no gesture phase was seen"); } #[test] From cfe8ae5c09ee88e7d19e37d16aa20e1e787fb296 Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Sat, 17 Oct 2026 22:20:54 -0400 Subject: [PATCH 4/8] Animation Effects: plainer Linux/BSD reader - The worker thread shares its latest answer with the UI as a plain Option behind a mutex, instead of a byte that needed encode and decode helpers. - Finding the user's config directory is its own small function. - In freedesktop.rs, the two dense one-liners in without_portal are split into named steps, and the parsers are pub(super) (ini_value private): only the animations module uses them. No change in behaviour. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/animations.rs | 40 ++++++++----------- apps/photocraft/src/animations/freedesktop.rs | 18 +++++---- 2 files changed, 27 insertions(+), 31 deletions(-) diff --git a/apps/photocraft/src/animations.rs b/apps/photocraft/src/animations.rs index bae69370b0..b6067fd25d 100644 --- a/apps/photocraft/src/animations.rs +++ b/apps/photocraft/src/animations.rs @@ -62,13 +62,12 @@ mod platform { /// `gsettings`, so a worker thread does it and the UI reads its latest answer. #[cfg(all(unix, not(target_os = "macos")))] mod platform { - use std::sync::atomic::{AtomicU8, Ordering}; - use std::sync::{Arc, OnceLock, mpsc}; + use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, mpsc}; use super::freedesktop; pub fn service() -> Option { - let latest = Arc::new(AtomicU8::new(encode(None))); + let latest = Arc::new(Mutex::new(None)); let wake: Arc> = Arc::new(OnceLock::new()); let (refresh, refreshes) = mpsc::channel::<()>(); let publisher = Publisher { latest: Arc::clone(&latest), wake: Arc::clone(&wake) }; @@ -83,7 +82,7 @@ mod platform { if focused && !was_focused { let _ = refresh.send(()); } - decode(latest.load(Ordering::Relaxed)) + *lock(&latest) })) } @@ -102,14 +101,14 @@ mod platform { /// The worker's side of the latest answer. A change wakes the UI. struct Publisher { - latest: Arc, + latest: Arc>>, wake: Arc>, } impl Publisher { fn publish(&self, animations: Option) { - let code = encode(animations); - if self.latest.swap(code, Ordering::Relaxed) != code + let previous = std::mem::replace(&mut *lock(&self.latest), animations); + if previous != animations && let Some(ctx) = self.wake.get() { ctx.request_repaint(); @@ -117,20 +116,9 @@ mod platform { } } - fn encode(animations: Option) -> u8 { - match animations { - None => 0, - Some(true) => 1, - Some(false) => 2, - } - } - - fn decode(code: u8) -> Option { - match code { - 1 => Some(true), - 2 => Some(false), - _ => None, - } + /// The latest answer; a panic elsewhere while holding it doesn't lose it. + fn lock(latest: &Mutex>) -> MutexGuard<'_, Option> { + latest.lock().unwrap_or_else(PoisonError::into_inner) } #[cfg(target_os = "linux")] @@ -230,12 +218,16 @@ mod platform { freedesktop::without_portal(&desktop, &config_file, &gsettings) } + /// `$XDG_CONFIG_HOME`, or `~/.config` when it isn't set. + fn config_home() -> Option { + let var = |key: &str| std::env::var_os(key).filter(|value| !value.is_empty()).map(PathBuf::from); + var("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| Some(var("HOME")?.join(".config"))) + } + fn config_file(name: &str) -> Option { use std::io::Read as _; - let dir = |key: &str| std::env::var_os(key).filter(|v| !v.is_empty()).map(PathBuf::from); - let config_home = dir("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| dir("HOME").map(|home| home.join(".config")))?; let mut text = String::new(); - std::fs::File::open(config_home.join(name)).ok()?.take(MAX_CONFIG_BYTES).read_to_string(&mut text).ok()?; + std::fs::File::open(config_home()?.join(name)).ok()?.take(MAX_CONFIG_BYTES).read_to_string(&mut text).ok()?; Some(text) } diff --git a/apps/photocraft/src/animations/freedesktop.rs b/apps/photocraft/src/animations/freedesktop.rs index 437ab5c42a..d5b4fbe626 100644 --- a/apps/photocraft/src/animations/freedesktop.rs +++ b/apps/photocraft/src/animations/freedesktop.rs @@ -4,7 +4,7 @@ //! animations are on, or `None` when the value doesn't parse (the next source is asked then). /// GSettings' and the portal's `true`/`false`, or GTK's `1`/`0`. -pub fn from_enabled(value: &str) -> Option { +pub(super) fn from_enabled(value: &str) -> Option { match value.trim().to_ascii_lowercase().as_str() { "true" | "1" => Some(true), "false" | "0" => Some(false), @@ -13,23 +13,26 @@ pub fn from_enabled(value: &str) -> Option { } /// KDE's animation speed factor: 0 turns animations off. -pub fn from_duration_factor(value: &str) -> Option { +pub(super) fn from_duration_factor(value: &str) -> Option { value.trim().parse::().ok().filter(|factor| factor.is_finite()).map(|factor| factor > 0.0) } /// The settings portal's `reduced-motion`: 1 asks for less motion; 0 and any value added later /// mean no preference. #[cfg(any(test, target_os = "linux"))] -pub fn from_reduced_motion(value: &str) -> Option { +pub(super) fn from_reduced_motion(value: &str) -> Option { value.trim().parse::().ok().map(|code| code != 1) } /// The desktop's setting when there is no settings portal to ask. `desktop` is /// `XDG_CURRENT_DESKTOP`, `config_file` reads a file in the user's config directory and /// `gsettings` runs `gsettings get `. -pub fn without_portal(desktop: &str, config_file: &dyn Fn(&str) -> Option, gsettings: &dyn Fn(&str, &str) -> Option) -> Option { +pub(super) fn without_portal(desktop: &str, config_file: &dyn Fn(&str) -> Option, gsettings: &dyn Fn(&str, &str) -> Option) -> Option { let running = |name: &str| desktop.split(':').any(|part| part.eq_ignore_ascii_case(name)); - let in_file = |file: &str, section: &str, key: &str, parse: fn(&str) -> Option| parse(ini_value(&config_file(file)?, section, key)?); + let in_file = |file: &str, section: &str, key: &str, parse: fn(&str) -> Option| { + let text = config_file(file)?; + parse(ini_value(&text, section, key)?) + }; // KDE Plasma keeps it in its own file. A kdeglobals left over from another desktop doesn't count. if running("KDE") @@ -45,11 +48,12 @@ pub fn without_portal(desktop: &str, config_file: &dyn Fn(&str) -> Option(text: &'a str, section: &str, key: &str) -> Option<&'a str> { +fn ini_value<'a>(text: &'a str, section: &str, key: &str) -> Option<&'a str> { let mut in_section = false; let mut found = None; for line in text.lines().map(str::trim) { From 8a9d969dbad47dcf49869db046c3d3d5bbdddc07 Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Thu, 22 Oct 2026 18:34:04 -0400 Subject: [PATCH 5/8] Animation Effects: test the canvas glide without unsmooth (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A canvas in a second OS window (Window › Arrange › New Window) reads input that wheel_nav::unsmooth never sees, so it relies on read_with's smooth flag alone. animation_effects_off_stops_the_canvas_glide_without_unsmooth draws a canvas with the setting resolved to off and no unsmooth: with the flag ignored, as before this fix, the canvas glides and the test fails. The two canvas wheel tests share a notch_pan helper. The comments in prefs_ui.rs and lib.rs say which part takes the glide out where. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/input_tests.rs | 63 ++++++++++++++++++++++++------- crates/ui-egui/src/lib.rs | 3 +- crates/ui-egui/src/prefs_ui.rs | 8 ++-- 3 files changed, 57 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 2d5bcc36c4..92e8c9d72f 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -489,6 +489,24 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); } +/// One wheel notch over the canvas at 800 %: the view's centre before it, on the frame the notch +/// arrives, and once any glide has settled. +fn notch_pan(h: &mut Harness<'static, PhotocraftApp>) -> ([f32; 2], [f32; 2], [f32; 2]) { + { + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (8.0, [200.0, 150.0], false); + } + h.run_steps(4); + h.hover_at(h.state().last_canvas_rect.center()); + h.run_steps(2); + let before = h.state().ui.views[0].center; + wheel(h, -1.0, Modifiers::NONE); + h.run_steps(1); + let on_arrival = h.state().ui.views[0].center; + h.run_steps(40); + (before, on_arrival, h.state().ui.views[0].center) +} + /// Preferences › Interface › Animation Effects (#3273): on, a wheel notch glides the canvas to /// its new place over the frames that follow; off, it is there on the frame the notch arrives. #[test] @@ -496,24 +514,43 @@ fn animation_effects_off_pans_a_wheel_notch_at_once() { for (choice, at_once) in [("on", false), ("off", true)] { let mut h = app_window(); h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": choice})).unwrap(); - { - let v = &mut h.state_mut().ui.views[0]; - (v.zoom, v.center, v.fit_pending) = (8.0, [200.0, 150.0], false); - } - h.run_steps(4); - h.hover_at(h.state().last_canvas_rect.center()); - h.run_steps(2); - let c0 = h.state().ui.views[0].center; - wheel(&h, -1.0, Modifiers::NONE); - h.run_steps(1); - let c1 = h.state().ui.views[0].center; - h.run_steps(40); - let c2 = h.state().ui.views[0].center; + let (c0, c1, c2) = notch_pan(&mut h); assert!((c2[1] - c0[1] - 5.0).abs() < 0.01 && c2[0] == c0[0], "{choice}: one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); assert_eq!(c1 == c2, at_once, "{choice}: {c0:?} -> {c1:?} -> {c2:?}"); } } +/// A canvas in another OS window (Window › Arrange › New Window) reads that window's own input, +/// which `wheel_nav::unsmooth` never sees: it runs on the main window's input only. So the +/// canvas's own wheel read must not glide with Animation Effects off either (#5721). +#[test] +fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.sync_views(); + let mut h = Harness::builder().with_size(vec2(1200.0, 800.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + // Fonts set up after the first frame only apply from the next one. + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + // What `PhotocraftApp::logic` does for a frame, without `unsmooth`. + crate::prefs_ui::tick(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": "off"})).unwrap(); + h.run_steps(1); + assert!(h.state().prefs_rt.animations_off); + let (c0, c1, c2) = notch_pan(&mut h); + assert!((c2[1] - c0[1] - 5.0).abs() < 0.01, "one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); + assert_eq!(c1, c2, "there on the frame the notch arrives: {c0:?} -> {c1:?} -> {c2:?}"); +} + #[test] fn alt_scroll_zooms_in_steps_around_the_pointer() { let mut h = harness(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c8f3eaec54..6be9636fe1 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2292,7 +2292,8 @@ impl eframe::App for PhotocraftApp { self.collect_screenshots(ctx); self.issue_screenshots(ctx); prefs_ui::tick(self, ctx); - // Before anything reads this frame's scroll (see `wheel_nav::unsmooth`). + // Animation Effects off: no wheel glide in the main window's panels and lists. Before + // anything reads this frame's scroll (see `wheel_nav::unsmooth`). if self.prefs_rt.animations_off { wheel_nav::unsmooth(ctx); } diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index 4dc3ed4ae7..a82413e4dd 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -52,7 +52,8 @@ pub struct Runtime { show_rulers: Option, /// Tool options as last remembered in the preferences (see `tool_memory`). pub(crate) tool_options: Option, - /// Interface › Animation Effects resolved to off this frame (see `sync_animations`). + /// Interface › Animation Effects resolved to off this frame (see `sync_animations`). The + /// wheel readers take it as their `smooth` flag (`wheel_nav::read_with`). pub(crate) animations_off: bool, pub(crate) selected_tool: Option, /// The tool owning the session brush and the other tools' brushes, as last remembered. @@ -460,8 +461,9 @@ fn animations_on(app: &PhotocraftApp, ctx: &egui::Context) -> bool { } /// Interface › Animation Effects: off, egui's fades and slides take no time and `scroll_to` jumps -/// straight to its target (#3273); `PhotocraftApp::logic` takes out the wheel's glide -/// (`wheel_nav::unsmooth`). Checked every frame: a theme change rebuilds the style and the +/// straight to its target (#3273). The wheel's glide is taken out where the wheel is read: by +/// `wheel_nav::read_with` on the canvas, in every window, and by `wheel_nav::unsmooth` in the +/// main window's panels and lists. Checked every frame: a theme change rebuilds the style and the /// system's setting can change. Both the dark and light styles are set, so an appearance switch /// keeps it. fn sync_animations(app: &mut PhotocraftApp, ctx: &egui::Context) { From 6fd27d9d82d0a8a3f27b30a5329e9f36da5f52ce Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Thu, 22 Oct 2026 19:13:06 -0400 Subject: [PATCH 6/8] =?UTF-8?q?Animation=20Effects:=20=E2=8C=98/Ctrl=20+?= =?UTF-8?q?=20wheel=20still=20pans=20sideways=20with=20them=20off?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit found that with Animation Effects off, wheel_nav::read_with panned by `raw`, which holds only the frame's plain wheel events. ⌘/Ctrl + wheel over the canvas therefore panned by nothing, in every window, and ⇧ + wheel kept its glide in windows other than the main one. read_with now pans by this_frames_scroll: the frame's wheel events folded sideways or upright by their modifiers as egui folds them, the same sum `unsmooth` uses. Tests: - unsmoothed_wheel_pans_keep_their_modifiers covers plain, ⇧, Ctrl and ⌘ + wheel, and Alt + wheel with Zoom with Scroll Wheel on. It fails with the old `raw` pan. - The canvas test without `unsmooth` now also covers ⇧ and Ctrl + wheel. Also from CodeRabbit's notes: - Focus-regained refresh requests to the Linux/BSD reader go through a one-slot channel, so they coalesce instead of queuing unread while the portal is followed. The comment there claimed they were dropped. - The functions this PR adds have doc comments. Co-Authored-By: Claude Opus 5.5 --- apps/photocraft/src/animations.rs | 22 ++++-- apps/photocraft/src/animations/freedesktop.rs | 3 + crates/ui-egui/src/input_tests.rs | 23 +++--- crates/ui-egui/src/prefs_ui.rs | 6 ++ crates/ui-egui/src/wheel_nav.rs | 71 ++++++++++++++++--- 5 files changed, 101 insertions(+), 24 deletions(-) diff --git a/apps/photocraft/src/animations.rs b/apps/photocraft/src/animations.rs index b6067fd25d..635b626e42 100644 --- a/apps/photocraft/src/animations.rs +++ b/apps/photocraft/src/animations.rs @@ -36,6 +36,7 @@ fn polled(read: fn() -> Option) -> photocraft_ui_egui::SystemAnimationsFn #[cfg(target_os = "windows")] mod platform { + /// Settings › Accessibility › Visual effects › Animation effects. pub fn service() -> Option { Some(super::polled(read)) } @@ -49,10 +50,12 @@ mod platform { #[cfg(target_os = "macos")] mod platform { + /// System Settings › Accessibility › Display › Reduce motion. pub fn service() -> Option { Some(super::polled(read)) } + /// Animations are on unless Reduce motion is. fn read() -> Option { Some(!objc2_app_kit::NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion()) } @@ -66,10 +69,14 @@ mod platform { use super::freedesktop; + /// Starts the worker; the returned reader gives its latest answer and asks it to read again + /// when the window gets the focus back. pub fn service() -> Option { let latest = Arc::new(Mutex::new(None)); let wake: Arc> = Arc::new(OnceLock::new()); - let (refresh, refreshes) = mpsc::channel::<()>(); + // One pending request is enough: focus changes while the worker is busy, or while it + // follows the portal and takes none, add nothing. + let (refresh, refreshes) = mpsc::sync_channel::<()>(1); let publisher = Publisher { latest: Arc::clone(&latest), wake: Arc::clone(&wake) }; std::thread::Builder::new().name("animations-setting".into()).spawn(move || worker(&publisher, &refreshes)).ok()?; let last_focus = std::cell::Cell::new(true); @@ -77,10 +84,9 @@ mod platform { let _ = wake.set(ctx.clone()); let focused = ctx.input(|i| i.focused); let was_focused = last_focus.replace(focused); - // Back from the desktop's settings, perhaps: read again. With the portal's change - // signal nobody listens for this, and the send fails quietly. + // Back from the desktop's settings, perhaps: read again. if focused && !was_focused { - let _ = refresh.send(()); + let _ = refresh.try_send(()); } *lock(&latest) })) @@ -106,6 +112,7 @@ mod platform { } impl Publisher { + /// Stores the worker's answer, and wakes the UI when it changed. fn publish(&self, animations: Option) { let previous = std::mem::replace(&mut *lock(&self.latest), animations); if previous != animations @@ -158,6 +165,7 @@ mod platform { true } + /// The answer of the first setting in [`SETTINGS`] the portal knows. fn read(proxy: &zbus::blocking::Proxy<'_>) -> Option { SETTINGS.iter().find_map(|(namespace, key, parse)| { let value: OwnedValue = proxy.call("Read", &(*namespace, *key)).ok()?; @@ -187,10 +195,13 @@ mod platform { mod tests { use super::*; + /// `value` as the portal hands it over. fn owned(value: Value<'_>) -> OwnedValue { OwnedValue::try_from(value).unwrap() } + /// Each value type a portal sends, nested or not, reads as the text a settings file + /// would hold; other types aren't settings. #[test] fn portal_values_read_as_text() { let nested = Value::Value(Box::new(Value::Value(Box::new(Value::U32(1))))); @@ -213,6 +224,7 @@ mod platform { /// A settings file is a few kilobytes; a larger one isn't read. const MAX_CONFIG_BYTES: u64 = 1 << 20; + /// The setting of the desktop this session runs (`XDG_CURRENT_DESKTOP`). pub fn read() -> Option { let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); freedesktop::without_portal(&desktop, &config_file, &gsettings) @@ -224,6 +236,7 @@ mod platform { var("XDG_CONFIG_HOME").filter(|path| path.is_absolute()).or_else(|| Some(var("HOME")?.join(".config"))) } + /// The text of `name` in the user's config directory, if it is there and not too large. fn config_file(name: &str) -> Option { use std::io::Read as _; let mut text = String::new(); @@ -248,6 +261,7 @@ mod platform { #[cfg(not(any(unix, target_os = "windows")))] mod platform { + /// No reader here: animations stay on. pub fn service() -> Option { None } diff --git a/apps/photocraft/src/animations/freedesktop.rs b/apps/photocraft/src/animations/freedesktop.rs index d5b4fbe626..f11a85e527 100644 --- a/apps/photocraft/src/animations/freedesktop.rs +++ b/apps/photocraft/src/animations/freedesktop.rs @@ -74,6 +74,7 @@ fn ini_value<'a>(text: &'a str, section: &str, key: &str) -> Option<&'a str> { mod tests { use super::*; + /// Each reader turns its own kind of value into on or off, and anything else into `None`. #[test] fn each_kind_of_value_reads_as_on_or_off() { for (value, animations) in @@ -99,6 +100,7 @@ mod tests { } } + /// A key is read from its own section only, the last entry wins, and junk reads as nothing. #[test] fn ini_values_come_from_their_own_section() { let kde = "[General]\nAnimationDurationFactor=3\n\n[KDE]\nSingleClick=false\n AnimationDurationFactor = 0 \n[KDE][Sub]\nAnimationDurationFactor=7\n"; @@ -113,6 +115,7 @@ mod tests { } } + /// Without the portal: KDE's file only on KDE, GNOME's or MATE's key, then GTK's file. #[test] fn without_the_portal_each_desktop_is_read_where_it_keeps_the_setting() { let files = |kdeglobals: Option<&'static str>, gtk3: Option<&'static str>| { diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 92e8c9d72f..806b8f795c 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -489,9 +489,9 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); } -/// One wheel notch over the canvas at 800 %: the view's centre before it, on the frame the notch -/// arrives, and once any glide has settled. -fn notch_pan(h: &mut Harness<'static, PhotocraftApp>) -> ([f32; 2], [f32; 2], [f32; 2]) { +/// One wheel notch (with `modifiers` held) over the canvas at 800 %: the view's centre before it, +/// on the frame the notch arrives, and once any glide has settled. +fn notch_pan(h: &mut Harness<'static, PhotocraftApp>, modifiers: Modifiers) -> ([f32; 2], [f32; 2], [f32; 2]) { { let v = &mut h.state_mut().ui.views[0]; (v.zoom, v.center, v.fit_pending) = (8.0, [200.0, 150.0], false); @@ -500,7 +500,7 @@ fn notch_pan(h: &mut Harness<'static, PhotocraftApp>) -> ([f32; 2], [f32; 2], [f h.hover_at(h.state().last_canvas_rect.center()); h.run_steps(2); let before = h.state().ui.views[0].center; - wheel(h, -1.0, Modifiers::NONE); + wheel(h, -1.0, modifiers); h.run_steps(1); let on_arrival = h.state().ui.views[0].center; h.run_steps(40); @@ -514,7 +514,7 @@ fn animation_effects_off_pans_a_wheel_notch_at_once() { for (choice, at_once) in [("on", false), ("off", true)] { let mut h = app_window(); h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": choice})).unwrap(); - let (c0, c1, c2) = notch_pan(&mut h); + let (c0, c1, c2) = notch_pan(&mut h, Modifiers::NONE); assert!((c2[1] - c0[1] - 5.0).abs() < 0.01 && c2[0] == c0[0], "{choice}: one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); assert_eq!(c1 == c2, at_once, "{choice}: {c0:?} -> {c1:?} -> {c2:?}"); } @@ -522,7 +522,8 @@ fn animation_effects_off_pans_a_wheel_notch_at_once() { /// A canvas in another OS window (Window › Arrange › New Window) reads that window's own input, /// which `wheel_nav::unsmooth` never sees: it runs on the main window's input only. So the -/// canvas's own wheel read must not glide with Animation Effects off either (#5721). +/// canvas's own wheel read must not glide with Animation Effects off either (#5721), and ⇧ or +/// ⌘/Ctrl + wheel must still pan sideways. #[test] fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -546,9 +547,13 @@ fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": "off"})).unwrap(); h.run_steps(1); assert!(h.state().prefs_rt.animations_off); - let (c0, c1, c2) = notch_pan(&mut h); - assert!((c2[1] - c0[1] - 5.0).abs() < 0.01, "one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); - assert_eq!(c1, c2, "there on the frame the notch arrives: {c0:?} -> {c1:?} -> {c2:?}"); + let ctrl = Modifiers { ctrl: true, command: true, ..Modifiers::NONE }; + for (modifiers, axis) in [(Modifiers::NONE, 1), (Modifiers::SHIFT, 0), (ctrl, 0)] { + let (c0, c1, c2) = notch_pan(&mut h, modifiers); + let moved = [c2[0] - c0[0], c2[1] - c0[1]]; + assert!((moved[axis] - 5.0).abs() < 0.01 && moved[1 - axis] == 0.0, "{modifiers:?}: one notch is 40 points, 5 px at 800%: {moved:?}"); + assert_eq!(c1, c2, "{modifiers:?}: there on the frame the notch arrives: {c0:?} -> {c1:?} -> {c2:?}"); + } } #[test] diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rs index a82413e4dd..5668aab5d7 100644 --- a/crates/ui-egui/src/prefs_ui.rs +++ b/crates/ui-egui/src/prefs_ui.rs @@ -3963,6 +3963,8 @@ mod tests { [egui::Theme::Dark, egui::Theme::Light].map(|t| ctx.style_of(t).animation_time) } + /// Off zeroes egui's animation time in both styles, survives a theme change and a restart, + /// and On brings the default back. #[test] fn animation_effects_off_stops_egui_animations_and_is_remembered() { let on = egui::Style::default().animation_time; @@ -3984,6 +3986,8 @@ mod tests { assert!(ctx.global_style().scroll_animation.duration.max > 0.0 && !app.prefs_rt.animations_off); } + /// Use System Setting, the default, follows the system's answer as it changes; On and Off + /// ignore it; no answer keeps animations on. #[test] fn use_system_setting_follows_the_platform() { use std::{cell::Cell, rc::Rc}; @@ -4014,6 +4018,8 @@ mod tests { assert_eq!(animation_times(&ctx), [on, on]); } + /// The old checkbox's saved "off" still turns animations off, and a value that is no choice + /// loads as the default instead of failing. #[test] fn old_and_hand_edited_animation_settings_load_safely() { let on = egui::Style::default().animation_time; diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index f177d98327..c1a0ae53d7 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -175,6 +175,7 @@ pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { } } +/// Where [`unsmooth`] keeps, from frame to frame, whether a trackpad gesture is in progress. fn gesture_id() -> Id { Id::new("pc-wheel-gesture") } @@ -232,15 +233,20 @@ fn unsmoothed_scroll(events: &[Event], options: &egui::InputOptions, page: f32, /// Call it once a frame, before anything reads the scroll. `PhotocraftApp::logic` does, for the /// main window; the canvas, also in other windows, uses [`read_with`]'s `smooth` flag instead. pub fn unsmooth(ctx: &Context) { + let (scroll, in_gesture) = this_frames_scroll(ctx); + if let Some(scroll) = scroll { + ctx.input_mut(|i| i.smooth_scroll_delta = scroll); + } + ctx.data_mut(|d| d.insert_temp(gesture_id(), in_gesture)); +} + +/// [`unsmoothed_scroll`] for this frame's input in `ctx`, and whether a trackpad gesture is in +/// progress after it. +fn this_frames_scroll(ctx: &Context) -> (Option, bool) { let options = ctx.options(|o| o.input_options); let mut in_gesture = ctx.data(|d| d.get_temp::(gesture_id())).unwrap_or(false); - ctx.input_mut(|i| { - let page = i.viewport_rect().height(); - if let Some(scroll) = unsmoothed_scroll(&i.events, &options, page, &mut in_gesture) { - i.smooth_scroll_delta = scroll; - } - }); - ctx.data_mut(|d| d.insert_temp(gesture_id(), in_gesture)); + let scroll = ctx.input(|i| unsmoothed_scroll(&i.events, &options, i.viewport_rect().height(), &mut in_gesture)); + (scroll, in_gesture) } fn alt_id() -> Id { @@ -277,9 +283,9 @@ pub fn read(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, read_with(ctx, zoom_with_wheel, pinch_zooms, owner, hovered, true, true) } -/// [`read`], choosing how a plain wheel scroll pans: `smooth` glides it over a few frames (egui's +/// [`read`], choosing how a wheel scroll pans: `smooth` glides it over a few frames (egui's /// smoothed delta); off, as with Interface › Animation Effects off, the view moves the whole notch -/// in the frame the wheel turns and stops there (#5721). +/// in the frame the wheel turns and stops there (#5721), sideways too for ⇧ or ⌘/Ctrl + wheel. /// `touch_gestures` is Preferences › Enhanced Controls › Enable Gestures: off, a touch screen's /// two-finger pinch doesn't zoom ([`pinch_factor`]). pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: Id, hovered: bool, smooth: bool, touch_gestures: bool) -> Option { @@ -388,8 +394,9 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: d.remove::(snap_time_id(owner)); }); } - // Unsmoothed, a plain scroll pans by this frame's own wheel events (none: no tail). - let scroll = if smooth || alt || shift { scroll } else { raw }; + // Unsmoothed, a scroll pans by this frame's own wheel events, folded sideways or upright by + // their modifiers as egui folds them (none: no tail). + let scroll = if smooth { scroll } else { this_frames_scroll(ctx).0.unwrap_or(scroll) }; classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, notch }) } } @@ -527,6 +534,47 @@ mod tests { assert!(smooth[1..].iter().any(|p| p.y != 0.0), "and the rest follows"); } + /// Smoothing off, ⇧ and ⌘/Ctrl + wheel still pan sideways, and Alt + wheel with Zoom with + /// Scroll Wheel on still pans upright, each the whole notch at once and the same distance as + /// smoothed: the unsmoothed pan is folded by the modifiers as egui folds the smoothed one. + #[test] + fn unsmoothed_wheel_pans_keep_their_modifiers() { + let pans = |modifiers: Modifiers, zoom_with_wheel: bool, smooth: bool| -> Vec { + let owner = Id::new("test-unsmoothed-modifiers"); + let ctx = Context::default(); + configure(&ctx); + (0..30) + .map(|n| { + let events = if n == 0 { vec![wheel(Vec2::new(0.0, -1.0), modifiers)] } else { Vec::new() }; + let raw = RawInput { time: Some(f64::from(n) / 60.0), predicted_dt: 1.0 / 60.0, events, ..Default::default() }; + let mut pan = Vec2::ZERO; + let mut out = ctx.run_ui(raw, |ui| { + if let Some(Wheel::Pan(d)) = read_with(ui.ctx(), zoom_with_wheel, true, owner, true, smooth, true) { + pan = d; + } + }); + out.textures_delta.clear(); + pan + }) + .collect() + }; + let total = |pans: &[Vec2]| pans.iter().fold(Vec2::ZERO, |sum, d| sum + *d); + for (modifiers, zoom_with_wheel, want) in [ + (Modifiers::NONE, false, Vec2::new(0.0, -40.0)), + (Modifiers::SHIFT, false, Vec2::new(-40.0, 0.0)), + (CTRL, false, Vec2::new(-40.0, 0.0)), + (CMD, false, Vec2::new(-40.0, 0.0)), + (CTRL, true, Vec2::new(-40.0, 0.0)), + (Modifiers::ALT, true, Vec2::new(0.0, -40.0)), + ] { + let direct = pans(modifiers, zoom_with_wheel, false); + assert!(near(direct[0], want), "{modifiers:?}: the whole notch at once: {:?}", direct[0]); + assert!(direct[1..].iter().all(|p| *p == Vec2::ZERO), "{modifiers:?}: no glide after it"); + let smooth = total(&pans(modifiers, zoom_with_wheel, true)); + assert!((smooth - want).length() < 1.0, "{modifiers:?}: smoothed, the same distance: {smooth:?}"); + } + } + #[test] fn plain_scroll_pans() { assert_eq!(classify(input(Vec2::new(3.0, -40.0), false)), Some(Wheel::Pan(Vec2::new(3.0, -40.0)))); @@ -787,6 +835,7 @@ mod tests { .collect() } + /// How far the frames scroll in all. fn total(frames: &[Vec2]) -> Vec2 { frames.iter().fold(Vec2::ZERO, |sum, d| sum + *d) } From 54a2f2ac250c508ec5c27290f61d111a981845c5 Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Fri, 23 Oct 2026 16:56:34 -0400 Subject: [PATCH 7/8] Animation Effects: wheel tests read the notch size from egui CodeRabbit noted that the wheel tests this PR adds assumed a notch is 40 points (5 px at 800 %). That is egui's native line_scroll_speed; on wasm32 egui uses 8. The tests now take it from egui instead: - wheel_nav tests: configured_notch(), a context set up like the app's; - canvas tests in input_tests: notch_pan_distance(), the harness's line_scroll_speed over NOTCH_PAN_ZOOM. Distances that aren't notches (the 600-point page, the 53-point pixel step) stay as they are. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/input_tests.rs | 17 +++++++++-- crates/ui-egui/src/wheel_nav.rs | 51 +++++++++++++++++++------------ 2 files changed, 45 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index 806b8f795c..ed5ff14344 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -489,12 +489,21 @@ fn the_wheel_reaches_12800_percent_and_stops_dead_there() { assert!((d2[0] - d0[0]).abs() < 0.02 && (d2[1] - d0[1]).abs() < 0.02, "{d0:?} -> {d2:?}"); } +/// The zoom [`notch_pan`] pans at: 800 %. +const NOTCH_PAN_ZOOM: f32 = 8.0; + +/// How far one wheel notch moves the view at [`NOTCH_PAN_ZOOM`], in document pixels: egui's +/// points per notch (`line_scroll_speed`) over the zoom. +fn notch_pan_distance(h: &Harness<'static, PhotocraftApp>) -> f32 { + h.ctx.options(|o| o.input_options.line_scroll_speed) / NOTCH_PAN_ZOOM +} + /// One wheel notch (with `modifiers` held) over the canvas at 800 %: the view's centre before it, /// on the frame the notch arrives, and once any glide has settled. fn notch_pan(h: &mut Harness<'static, PhotocraftApp>, modifiers: Modifiers) -> ([f32; 2], [f32; 2], [f32; 2]) { { let v = &mut h.state_mut().ui.views[0]; - (v.zoom, v.center, v.fit_pending) = (8.0, [200.0, 150.0], false); + (v.zoom, v.center, v.fit_pending) = (NOTCH_PAN_ZOOM, [200.0, 150.0], false); } h.run_steps(4); h.hover_at(h.state().last_canvas_rect.center()); @@ -515,7 +524,8 @@ fn animation_effects_off_pans_a_wheel_notch_at_once() { let mut h = app_window(); h.state_mut().run("prefs.set", json!({"path": "interface.animationEffects", "value": choice})).unwrap(); let (c0, c1, c2) = notch_pan(&mut h, Modifiers::NONE); - assert!((c2[1] - c0[1] - 5.0).abs() < 0.01 && c2[0] == c0[0], "{choice}: one notch is 40 points, 5 px at 800%: {c0:?} -> {c2:?}"); + let notch = notch_pan_distance(&h); + assert!((c2[1] - c0[1] - notch).abs() < 0.01 && c2[0] == c0[0], "{choice}: one notch is {notch} px at 800%: {c0:?} -> {c2:?}"); assert_eq!(c1 == c2, at_once, "{choice}: {c0:?} -> {c1:?} -> {c2:?}"); } } @@ -551,7 +561,8 @@ fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { for (modifiers, axis) in [(Modifiers::NONE, 1), (Modifiers::SHIFT, 0), (ctrl, 0)] { let (c0, c1, c2) = notch_pan(&mut h, modifiers); let moved = [c2[0] - c0[0], c2[1] - c0[1]]; - assert!((moved[axis] - 5.0).abs() < 0.01 && moved[1 - axis] == 0.0, "{modifiers:?}: one notch is 40 points, 5 px at 800%: {moved:?}"); + let notch = notch_pan_distance(&h); + assert!((moved[axis] - notch).abs() < 0.01 && moved[1 - axis] == 0.0, "{modifiers:?}: one notch is {notch} px at 800%: {moved:?}"); assert_eq!(c1, c2, "{modifiers:?}: there on the frame the notch arrives: {c0:?} -> {c1:?} -> {c2:?}"); } } diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index c1a0ae53d7..d8cd7cfcd5 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -498,6 +498,14 @@ mod tests { (a - b).length() < 0.01 } + /// Points per wheel notch in a context set up like the app's (egui's `line_scroll_speed`: + /// 40 natively, 8 in a browser). + fn configured_notch() -> f32 { + let ctx = Context::default(); + configure(&ctx); + ctx.options(|o| o.input_options.line_scroll_speed) + } + /// #5721: with smoothing off a wheel notch pans the whole notch in the frame it arrives and /// nothing after; smoothed (the default) it glides, reaching the same total over later frames. #[test] @@ -559,13 +567,14 @@ mod tests { .collect() }; let total = |pans: &[Vec2]| pans.iter().fold(Vec2::ZERO, |sum, d| sum + *d); + let notch = configured_notch(); for (modifiers, zoom_with_wheel, want) in [ - (Modifiers::NONE, false, Vec2::new(0.0, -40.0)), - (Modifiers::SHIFT, false, Vec2::new(-40.0, 0.0)), - (CTRL, false, Vec2::new(-40.0, 0.0)), - (CMD, false, Vec2::new(-40.0, 0.0)), - (CTRL, true, Vec2::new(-40.0, 0.0)), - (Modifiers::ALT, true, Vec2::new(0.0, -40.0)), + (Modifiers::NONE, false, Vec2::new(0.0, -notch)), + (Modifiers::SHIFT, false, Vec2::new(-notch, 0.0)), + (CTRL, false, Vec2::new(-notch, 0.0)), + (CMD, false, Vec2::new(-notch, 0.0)), + (CTRL, true, Vec2::new(-notch, 0.0)), + (Modifiers::ALT, true, Vec2::new(0.0, -notch)), ] { let direct = pans(modifiers, zoom_with_wheel, false); assert!(near(direct[0], want), "{modifiers:?}: the whole notch at once: {:?}", direct[0]); @@ -844,24 +853,25 @@ mod tests { /// instead of gliding there over the frames that follow. #[test] fn animations_off_scrolls_a_wheel_notch_at_once() { - let notch = || vec![vec![], vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)]]; + let notch = configured_notch(); + let one_notch_down = || vec![vec![], vec![wheel(Vec2::new(0.0, -1.0), Modifiers::NONE)]]; // egui by itself: part of the notch on the frame it arrives, the rest over the next ones. - let glide = scrolled(notch(), false); - assert!(glide[1].y < 0.0 && glide[1].y > -30.0, "the notch starts gliding: {:?}", glide[1]); + let glide = scrolled(one_notch_down(), false); + assert!(glide[1].y < 0.0 && glide[1].y > -0.75 * notch, "the notch starts gliding: {:?}", glide[1]); assert!(glide[2..8].iter().all(|d| d.y < 0.0), "and keeps gliding: {:?}", &glide[2..8]); - assert!(near(total(&glide), Vec2::new(0.0, -40.0)), "{:?}", total(&glide)); + assert!(near(total(&glide), Vec2::new(0.0, -notch)), "{:?}", total(&glide)); // Off: all of it at once, and nothing after. - let jump = scrolled(notch(), true); - assert_eq!(jump[1], Vec2::new(0.0, -40.0)); + let jump = scrolled(one_notch_down(), true); + assert_eq!(jump[1], Vec2::new(0.0, -notch)); assert!(jump.iter().enumerate().all(|(n, d)| n == 1 || *d == Vec2::ZERO), "{jump:?}"); // Sideways (⇧ or ⌘/Ctrl + wheel), two notches in one frame, a fraction of a notch each // way, a page and a coarse pixel step (a wheel on Wayland or the web) jump the same way. let sent = |unit, y: f32| Event::MouseWheel { unit, delta: Vec2::new(0.0, y), phase: TouchPhase::Move, modifiers: Modifiers::NONE }; for (events, want) in [ - (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)], Vec2::new(40.0, 0.0)), - (vec![wheel(Vec2::new(0.0, 1.0), CTRL)], Vec2::new(40.0, 0.0)), - (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE), wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)], Vec2::new(0.0, 80.0)), - (vec![wheel(Vec2::new(-0.5, 0.25), Modifiers::NONE)], Vec2::new(-20.0, 10.0)), + (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::SHIFT)], Vec2::new(notch, 0.0)), + (vec![wheel(Vec2::new(0.0, 1.0), CTRL)], Vec2::new(notch, 0.0)), + (vec![wheel(Vec2::new(0.0, 1.0), Modifiers::NONE), wheel(Vec2::new(0.0, 1.0), Modifiers::NONE)], Vec2::new(0.0, 2.0 * notch)), + (vec![wheel(Vec2::new(-0.5, 0.25), Modifiers::NONE)], Vec2::new(-0.5 * notch, 0.25 * notch)), (vec![sent(MouseWheelUnit::Page, -1.0)], Vec2::new(0.0, -600.0)), (vec![sent(MouseWheelUnit::Point, 53.0)], Vec2::new(0.0, 53.0)), ] { @@ -911,11 +921,12 @@ mod tests { }) .collect() }; + let notch = configured_notch(); let (glide, jump) = (offsets(false), offsets(true)); - assert!(glide[3] > 0.0 && glide[3] < 30.0 && glide[4] > glide[3], "it glides: {:?}", &glide[..8]); - assert!((glide[39] - 40.0).abs() < 0.01, "to one notch down: {}", glide[39]); + assert!(glide[3] > 0.0 && glide[3] < 0.75 * notch && glide[4] > glide[3], "it glides: {:?}", &glide[..8]); + assert!((glide[39] - notch).abs() < 0.01, "to one notch down: {}", glide[39]); assert_eq!(jump[..3], [0.0; 3]); - assert!(jump[3..].iter().all(|y| *y == 40.0), "off, it is there at once: {:?}", &jump[..8]); + assert!(jump[3..].iter().all(|y| *y == notch), "off, it is there at once: {:?}", &jump[..8]); } /// A trackpad gesture (begin and end phases) is already applied as it arrives, with its @@ -938,7 +949,7 @@ mod tests { let (on, off) = (scrolled(gesture(), false), scrolled(gesture(), true)); assert_eq!(on[..5], off[..5], "the gesture reads the same"); assert_eq!(on[2], Vec2::new(30.0, 0.0), "sideways for the whole gesture"); - assert_eq!(off[5], Vec2::new(0.0, 40.0)); + assert_eq!(off[5], Vec2::new(0.0, configured_notch())); assert!(off[6..].iter().all(|d| *d == Vec2::ZERO)); } From a32d700f62ce4bff21cd5d1cb474ff57fe6fe02d Mon Sep 17 00:00:00 2001 From: Jeremy Yao Date: Fri, 23 Oct 2026 22:33:06 -0400 Subject: [PATCH 8/8] Animation Effects: a trackpad gesture keeps its direction in every window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CodeRabbit found that with `smooth` off, wheel_nav::read_with read the trackpad-gesture state but never recorded it, and its snap, zoom and not-hovered paths returned before even reading it. Outside the main window, where `unsmooth` doesn't run, a gesture's begin was never noted. So a gesture begun with ⇧ held turned into a vertical pan once ⇧ was let go, where egui keeps it sideways. - this_frames_scroll now records the state it computes, and read_with calls it up front with its other per-frame tracking, then reuses the result. - The state is kept per window (keyed by viewport id). The main window and a second document window have input of their own, and must not overwrite each other's gestures. - The canvas test without `unsmooth` gains a phased Start/Move/End case: begun with ⇧ and released mid-gesture, the canvas pans 24 points sideways and not at all vertically. It fails without the fix. Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/src/input_tests.rs | 27 +++++++++++++++++++++++++-- crates/ui-egui/src/wheel_nav.rs | 29 +++++++++++++++++------------ 2 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/input_tests.rs b/crates/ui-egui/src/input_tests.rs index ed5ff14344..8df30bdefb 100644 --- a/crates/ui-egui/src/input_tests.rs +++ b/crates/ui-egui/src/input_tests.rs @@ -532,8 +532,8 @@ fn animation_effects_off_pans_a_wheel_notch_at_once() { /// A canvas in another OS window (Window › Arrange › New Window) reads that window's own input, /// which `wheel_nav::unsmooth` never sees: it runs on the main window's input only. So the -/// canvas's own wheel read must not glide with Animation Effects off either (#5721), and ⇧ or -/// ⌘/Ctrl + wheel must still pan sideways. +/// canvas's own wheel read must not glide with Animation Effects off either (#5721), ⇧ or +/// ⌘/Ctrl + wheel must still pan sideways, and a trackpad gesture must keep its direction. #[test] fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); @@ -565,6 +565,29 @@ fn animation_effects_off_stops_the_canvas_glide_without_unsmooth() { assert!((moved[axis] - notch).abs() < 0.01 && moved[1 - axis] == 0.0, "{modifiers:?}: one notch is {notch} px at 800%: {moved:?}"); assert_eq!(c1, c2, "{modifiers:?}: there on the frame the notch arrives: {c0:?} -> {c1:?} -> {c2:?}"); } + + // A trackpad gesture keeps the direction it began with, as egui does: begun with ⇧ held, it + // still pans sideways after ⇧ is let go. + { + let v = &mut h.state_mut().ui.views[0]; + (v.zoom, v.center, v.fit_pending) = (NOTCH_PAN_ZOOM, [200.0, 150.0], false); + } + h.run_steps(4); + let before = h.state().ui.views[0].center; + let swipe = |phase, dy: f32, modifiers| egui::Event::MouseWheel { unit: egui::MouseWheelUnit::Point, delta: vec2(0.0, dy), phase, modifiers }; + for (phase, dy, modifiers) in [ + (egui::TouchPhase::Start, 0.0, Modifiers::SHIFT), + (egui::TouchPhase::Move, -8.0, Modifiers::SHIFT), + (egui::TouchPhase::Move, -16.0, Modifiers::NONE), + (egui::TouchPhase::End, 0.0, Modifiers::NONE), + ] { + h.event_modifiers(swipe(phase, dy, modifiers), modifiers); + h.run_steps(1); + } + h.run_steps(4); + let after = h.state().ui.views[0].center; + let moved = [after[0] - before[0], after[1] - before[1]]; + assert!((moved[0] - 24.0 / NOTCH_PAN_ZOOM).abs() < 0.01 && moved[1] == 0.0, "24 points sideways for the whole gesture: {moved:?}"); } #[test] diff --git a/crates/ui-egui/src/wheel_nav.rs b/crates/ui-egui/src/wheel_nav.rs index d8cd7cfcd5..a467b81a5f 100644 --- a/crates/ui-egui/src/wheel_nav.rs +++ b/crates/ui-egui/src/wheel_nav.rs @@ -175,9 +175,10 @@ pub fn fold_legacy_pinch(ctx: &Context, raw: &mut RawInput) { } } -/// Where [`unsmooth`] keeps, from frame to frame, whether a trackpad gesture is in progress. -fn gesture_id() -> Id { - Id::new("pc-wheel-gesture") +/// Where each window keeps, from frame to frame, whether a trackpad gesture is in progress in it. +/// Per window: a second document window has input of its own. +fn gesture_id(ctx: &Context) -> Id { + Id::new("pc-wheel-gesture").with(ctx.viewport_id()) } /// What this frame's wheel events scroll in all, in points, each folded sideways or upright by @@ -233,20 +234,21 @@ fn unsmoothed_scroll(events: &[Event], options: &egui::InputOptions, page: f32, /// Call it once a frame, before anything reads the scroll. `PhotocraftApp::logic` does, for the /// main window; the canvas, also in other windows, uses [`read_with`]'s `smooth` flag instead. pub fn unsmooth(ctx: &Context) { - let (scroll, in_gesture) = this_frames_scroll(ctx); - if let Some(scroll) = scroll { + if let Some(scroll) = this_frames_scroll(ctx) { ctx.input_mut(|i| i.smooth_scroll_delta = scroll); } - ctx.data_mut(|d| d.insert_temp(gesture_id(), in_gesture)); } -/// [`unsmoothed_scroll`] for this frame's input in `ctx`, and whether a trackpad gesture is in -/// progress after it. -fn this_frames_scroll(ctx: &Context) -> (Option, bool) { +/// [`unsmoothed_scroll`] for this frame's input in `ctx`'s window, recording that window's +/// trackpad-gesture state for the next frame. Call it on every frame, whether or not the scroll is +/// wanted, so a gesture's begin and end are never missed. Calls in the same frame agree. +fn this_frames_scroll(ctx: &Context) -> Option { let options = ctx.options(|o| o.input_options); - let mut in_gesture = ctx.data(|d| d.get_temp::(gesture_id())).unwrap_or(false); + let id = gesture_id(ctx); + let mut in_gesture = ctx.data(|d| d.get_temp::(id)).unwrap_or(false); let scroll = ctx.input(|i| unsmoothed_scroll(&i.events, &options, i.viewport_rect().height(), &mut in_gesture)); - (scroll, in_gesture) + ctx.data_mut(|d| d.insert_temp(id, in_gesture)); + scroll } fn alt_id() -> Id { @@ -312,6 +314,9 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: } None => ctx.data(|d| d.get_temp::(shift_id())).unwrap_or(false), }; + // The pan with `smooth` off. Read here, before any early return, so the window's trackpad + // gesture state also follows frames that zoom, snap or aren't over this view. + let unsmoothed = this_frames_scroll(ctx); if !hovered { return None; @@ -396,7 +401,7 @@ pub fn read_with(ctx: &Context, zoom_with_wheel: bool, pinch_zooms: bool, owner: } // Unsmoothed, a scroll pans by this frame's own wheel events, folded sideways or upright by // their modifiers as egui folds them (none: no tail). - let scroll = if smooth { scroll } else { this_frames_scroll(ctx).0.unwrap_or(scroll) }; + let scroll = if smooth { scroll } else { unsmoothed.unwrap_or(scroll) }; classify(Input { scroll, raw, zoom_delta, alt, shift, zoom_with_wheel, pinch_zooms, notch }) } }