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 <[email protected]>
This commit is contained in:
Jeremy YaoandClaude Opus 5.5 committed 2026-10-17 11:52:09 -04:00
1 parent 382082fd73
commit 5d552d4a60
6 files changed
+377 -389

No files matched your search

+86 -255
View File
@@ -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<bool>) -> 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<bool>)>);
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<bool>) -> photocraft_ui_egui::SystemAnimationsFn
#[cfg(target_os = "windows")]
mod platform {
use photocraft_ui_egui::SystemAnimationsFn;
pub fn service() -> Option<SystemAnimationsFn> {
pub fn service() -> Option<photocraft_ui_egui::SystemAnimationsFn> {
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<bool> {
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<SystemAnimationsFn> {
pub fn service() -> Option<photocraft_ui_egui::SystemAnimationsFn> {
Some(super::polled(read))
}
@@ -66,42 +58,37 @@ mod platform {
}
}
#[cfg(not(any(unix, target_os = "windows")))]
mod platform {
pub fn service() -> Option<photocraft_ui_egui::SystemAnimationsFn> {
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<SystemAnimationsFn> {
let value = Arc::new(AtomicU8::new(super::code_of(None)));
pub fn service() -> Option<photocraft_ui_egui::SystemAnimationsFn> {
let latest = Arc::new(AtomicU8::new(encode(None)));
let wake: Arc<OnceLock<egui::Context>> = 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<AtomicU8>,
latest: Arc<AtomicU8>,
wake: Arc<OnceLock<egui::Context>>,
}
impl Publisher {
fn publish(&self, animations: Option<bool>) {
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<bool>) -> u8 {
match animations {
None => 0,
Some(true) => 1,
Some(false) => 2,
}
}
fn decode(code: u8) -> Option<bool> {
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<bool>;
/// Reads a setting's value as animations on or off.
type Parse = fn(&str) -> Option<bool>;
/// 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<bool> {
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<String> {
fn as_text(value: OwnedValue) -> Option<String> {
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<bool> {
let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
super::super::desktop_setting(&desktop, &config_file, &gsettings)
}
fn config_home() -> Option<PathBuf> {
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<String> {
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<bool> {
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<photocraft_ui_egui::SystemAnimationsFn> {
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<bool> {
value.trim().parse::<f64>().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<bool> {
value.trim().parse::<u32>().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 <schema> <key>`.
#[cfg(any(test, all(unix, not(target_os = "macos"))))]
fn desktop_setting(desktop: &str, file: &dyn Fn(&str) -> Option<String>, gsettings: &dyn Fn(&str, &str) -> Option<String>) -> Option<bool> {
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<bool>| 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<bool>) -> 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<bool> {
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<String> { 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);
}
}
@@ -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<bool> {
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<bool> {
value.trim().parse::<f64>().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<bool> {
value.trim().parse::<u32>().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 <schema> <key>`.
pub fn without_portal(desktop: &str, config_file: &dyn Fn(&str) -> Option<String>, gsettings: &dyn Fn(&str, &str) -> Option<String>) -> Option<bool> {
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<bool>| 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<String> { 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);
}
}
+1 -3
View File
@@ -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::<bool>(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());
+2 -3
View File
@@ -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);
+49 -35
View File
@@ -52,8 +52,8 @@ pub struct Runtime {
show_rulers: Option<bool>,
/// Tool options as last remembered in the preferences (see `tool_memory`).
pub(crate) tool_options: Option<crate::state::ToolOptions>,
/// 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<crate::state::Tool>,
}
@@ -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}");
}
}
+89 -93
View File
@@ -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<Vec2> {
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<Vec2> {
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::<bool>(touch_id())).unwrap_or(false);
let mut touch = was;
let mut in_gesture = ctx.data(|d| d.get_temp::<bool>(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<Wheel> {
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<Wheel> {
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::<f64>(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<Vec2> {
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<Vec2> {
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<Vec<Event>>, off: bool) -> Vec<Vec2> {
@@ -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]