Skip to main content

gpui_deck/
reduce_motion.rs

1// Modified for GPUI Deck: update references to the extracted crate.
2//! Honors the operating system's reduced-motion preference.
3//!
4//! Every Base transition, spring, presence and reveal consults
5//! [`App::reduce_motion`], but GPUI never reads the platform's setting into
6//! that flag: it stays `false` until something sets it. [`init`] reads the
7//! setting when Base initializes and writes it into the flag, so an
8//! application inherits the user's choice by calling `gpui_deck::init`.
9//!
10//! The setting is read on the platforms below; everywhere else the flag is
11//! left alone.
12//!
13//! - macOS: `NSWorkspace.accessibilityDisplayShouldReduceMotion`, the
14//!   "Reduce motion" switch under Accessibility → Display.
15//! - Windows: `SystemParametersInfoW(SPI_GETCLIENTAREAANIMATION)`, the
16//!   "Animation effects" switch under Accessibility → Visual effects, whose
17//!   off state asks for reduced motion.
18//! - Linux: the `reduced-motion` key of the `org.freedesktop.appearance`
19//!   namespace of the XDG desktop portal's Settings interface, which GNOME
20//!   and KDE back with their own animation switches. The portal answers over
21//!   D-Bus, so the reading lands a moment after `init` returns, and Base keeps
22//!   following the portal's change signal for the life of the application.
23//!
24//! Use [`set_reduce_motion_preference`] for an explicit application choice,
25//! including a choice equal to the current flag, or to resume the system
26//! preference. A direct [`App::set_reduce_motion`] call keeps the
27//! value-comparison behavior: Base leaves a value different from what it last
28//! wrote alone, but cannot recognize a same-value override.
29//!
30//! Under GPUI's test scheduler the platform is never consulted, whichever
31//! crate's tests are running: a probe that answers from another thread would
32//! break the scheduler's determinism, and a test wanting reduced motion sets
33//! the flag itself.
34
35use gpui::{App, Global};
36
37/// The last system reading, flag ownership and platform-listener state.
38#[derive(Default)]
39struct SystemReduceMotion {
40    applied: Option<bool>,
41    system: Option<bool>,
42    overridden: bool,
43    following: bool,
44}
45
46impl Global for SystemReduceMotion {}
47
48/// Applies the system's reduced-motion preference during `gpui_deck::init`.
49pub(crate) fn init(cx: &mut App) {
50    apply_system_reduce_motion(cx);
51}
52
53/// Reads the operating system's reduced-motion preference into
54/// [`App::set_reduce_motion`].
55///
56/// `gpui_deck::init` calls this once. Call it again to re-read the preference
57/// on a platform Base does not follow live. The current macOS and Windows
58/// implementations read the preference only when this function is called.
59///
60/// Explicit overrides are preserved. For direct [`App::set_reduce_motion`]
61/// calls, a flag different from what Base last wrote is also left alone; a
62/// same-value application choice cannot be detected. This function does not
63/// clear either override: use [`set_reduce_motion_preference`] with
64/// [`ReduceMotionPreference::System`].
65/// Where the platform cannot say (wasm, an unsupported desktop, a Linux
66/// session without the portal) the flag is left as it is, and under GPUI's
67/// test scheduler the platform is not asked at all.
68pub fn apply_system_reduce_motion(cx: &mut App) {
69    if is_test_scheduler(cx) {
70        return;
71    }
72    apply_preference(platform::read(), cx);
73    let state = cx.default_global::<SystemReduceMotion>();
74    if !state.following {
75        state.following = true;
76        platform::follow(cx);
77    }
78}
79
80/// The source and value of the application's reduced-motion preference.
81#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
82pub enum ReduceMotionPreference {
83    /// Use the last known system preference and existing platform updates.
84    #[default]
85    System,
86    /// Reduce motion regardless of the system preference.
87    Reduce,
88    /// Allow motion regardless of the system preference.
89    Allow,
90}
91
92/// Selects the application's reduced-motion preference.
93///
94/// [`ReduceMotionPreference::Reduce`] and [`ReduceMotionPreference::Allow`] set
95/// [`App::reduce_motion`] and prevent Base's system readings from changing it,
96/// even when the value already matches. The application can still change the
97/// flag directly; system readings continue to be cached.
98///
99/// [`ReduceMotionPreference::System`] releases application ownership, resumes
100/// the last known system value and calls [`apply_system_reduce_motion`] through
101/// the existing platform mechanism. If no system value is known, the current
102/// flag is kept until a reading arrives. On Linux, an existing portal listener
103/// supplies updates; selecting System does not restart it or force a new read.
104///
105/// System also releases ownership taken through [`App::set_reduce_motion`].
106/// Under the test scheduler, explicit choices and cached readings still apply,
107/// but the platform is never queried.
108pub fn set_reduce_motion_preference(preference: ReduceMotionPreference, cx: &mut App) {
109    match preference {
110        ReduceMotionPreference::Reduce | ReduceMotionPreference::Allow => {
111            cx.default_global::<SystemReduceMotion>().overridden = true;
112            cx.set_reduce_motion(preference == ReduceMotionPreference::Reduce);
113        }
114        ReduceMotionPreference::System => {
115            let current = cx.reduce_motion();
116            let state = cx.default_global::<SystemReduceMotion>();
117            state.overridden = false;
118            // Release both explicit ownership and the value-comparison guard.
119            state.applied = Some(current);
120            let system = state.system;
121            apply_preference(system, cx);
122            apply_system_reduce_motion(cx);
123        }
124    }
125}
126
127/// Whether the application runs on GPUI's deterministic test scheduler,
128/// which must not be woken by a platform answering from its own thread.
129fn is_test_scheduler(cx: &App) -> bool {
130    cx.background_executor()
131        .scheduler_executor()
132        .scheduler()
133        .as_test()
134        .is_some()
135}
136
137/// Writes one reading of the system preference into the flag, unless the
138/// application has taken the flag over since the reading Base last applied.
139fn apply_preference(preference: Option<bool>, cx: &mut App) {
140    let Some(reduce) = preference else {
141        return;
142    };
143    let state = cx.default_global::<SystemReduceMotion>();
144    state.system = Some(reduce);
145    let applied = state.applied;
146    if state.overridden || cx.reduce_motion() != applied.unwrap_or(false) {
147        return;
148    }
149    cx.set_reduce_motion(reduce);
150    cx.default_global::<SystemReduceMotion>().applied = Some(reduce);
151}
152
153#[cfg(target_os = "macos")]
154mod platform {
155    use gpui::App;
156    use objc2_app_kit::NSWorkspace;
157
158    pub(super) fn read() -> Option<bool> {
159        Some(NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion())
160    }
161
162    pub(super) fn follow(_cx: &mut App) {}
163}
164
165#[cfg(target_os = "windows")]
166mod platform {
167    use gpui::App;
168    use windows::Win32::{
169        Foundation::BOOL,
170        UI::WindowsAndMessaging::{
171            SPI_GETCLIENTAREAANIMATION, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
172        },
173    };
174
175    pub(super) fn read() -> Option<bool> {
176        let mut animations_enabled = BOOL(0);
177        // SAFETY: SPI_GETCLIENTAREAANIMATION writes one BOOL through `pvParam`
178        // and ignores `uiParam`; the BOOL outlives the call.
179        unsafe {
180            SystemParametersInfoW(
181                SPI_GETCLIENTAREAANIMATION,
182                0,
183                Some((&mut animations_enabled as *mut BOOL).cast()),
184                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
185            )
186        }
187        .ok()?;
188        Some(!animations_enabled.as_bool())
189    }
190
191    pub(super) fn follow(_cx: &mut App) {}
192}
193
194#[cfg(target_os = "linux")]
195mod platform {
196    use ashpd::desktop::settings::{ReducedMotion, Settings};
197    use futures::StreamExt as _;
198    use gpui::App;
199
200    /// The portal answers asynchronously; [`follow`] applies the first reading.
201    pub(super) fn read() -> Option<bool> {
202        None
203    }
204
205    pub(super) fn follow(cx: &mut App) {
206        cx.spawn(async move |cx| {
207            let settings = Settings::new().await.ok()?;
208            let current = settings.reduced_motion().await.ok()?;
209            cx.update(|cx| super::apply_preference(Some(reduces(current)), cx));
210            let mut changes = settings.receive_reduced_motion_changed().await.ok()?;
211            while let Some(preference) = changes.next().await {
212                cx.update(|cx| super::apply_preference(Some(reduces(preference)), cx));
213            }
214            Some(())
215        })
216        .detach();
217    }
218
219    fn reduces(preference: ReducedMotion) -> bool {
220        matches!(preference, ReducedMotion::ReducedMotion)
221    }
222}
223
224#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
225mod platform {
226    use gpui::App;
227
228    pub(super) fn read() -> Option<bool> {
229        None
230    }
231
232    pub(super) fn follow(_cx: &mut App) {}
233}
234
235#[cfg(test)]
236mod tests {
237    use gpui::TestAppContext;
238
239    use super::{
240        ReduceMotionPreference, apply_preference, apply_system_reduce_motion,
241        set_reduce_motion_preference,
242    };
243
244    #[gpui::test]
245    fn an_explicit_same_value_override_survives_system_changes(cx: &mut TestAppContext) {
246        cx.update(|cx| {
247            for (preference, value) in [
248                (ReduceMotionPreference::Allow, false),
249                (ReduceMotionPreference::Reduce, true),
250            ] {
251                set_reduce_motion_preference(ReduceMotionPreference::System, cx);
252                apply_preference(Some(value), cx);
253                set_reduce_motion_preference(preference, cx);
254                apply_preference(Some(!value), cx);
255                assert_eq!(cx.reduce_motion(), value);
256                apply_preference(Some(value), cx);
257                apply_preference(Some(!value), cx);
258                assert_eq!(cx.reduce_motion(), value);
259            }
260        });
261    }
262
263    #[gpui::test]
264    fn clearing_an_override_restores_the_latest_system_reading(cx: &mut TestAppContext) {
265        cx.update(|cx| {
266            apply_preference(Some(false), cx);
267            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
268            apply_preference(Some(true), cx);
269            apply_preference(Some(false), cx);
270            assert!(cx.reduce_motion());
271            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
272            assert!(!cx.reduce_motion());
273            apply_preference(Some(true), cx);
274            assert!(cx.reduce_motion());
275
276            set_reduce_motion_preference(ReduceMotionPreference::Allow, cx);
277            apply_preference(Some(false), cx);
278            apply_preference(Some(true), cx);
279            assert!(!cx.reduce_motion());
280            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
281            assert!(cx.reduce_motion());
282            apply_preference(Some(false), cx);
283            assert!(!cx.reduce_motion());
284        });
285    }
286
287    #[gpui::test]
288    fn clearing_without_a_system_reading_keeps_the_flag_until_one_arrives(cx: &mut TestAppContext) {
289        cx.update(|cx| {
290            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
291            apply_preference(None, cx);
292            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
293            assert!(cx.reduce_motion());
294            apply_preference(Some(false), cx);
295            assert!(!cx.reduce_motion());
296        });
297    }
298
299    #[gpui::test]
300    fn clearing_can_resume_after_a_direct_override(cx: &mut TestAppContext) {
301        cx.update(|cx| {
302            apply_preference(Some(false), cx);
303            cx.set_reduce_motion(true);
304            apply_preference(Some(false), cx);
305            assert!(cx.reduce_motion());
306            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
307            assert!(!cx.reduce_motion());
308            // Direct setters retain their previous value-comparison contract.
309            cx.set_reduce_motion(true);
310            apply_preference(Some(false), cx);
311            assert!(cx.reduce_motion());
312        });
313    }
314
315    #[gpui::test]
316    fn a_system_preference_for_reduced_motion_sets_the_flag(cx: &mut TestAppContext) {
317        cx.update(|cx| {
318            apply_preference(Some(true), cx);
319            assert!(cx.reduce_motion());
320        });
321    }
322
323    #[gpui::test]
324    fn an_unknown_system_preference_leaves_the_flag_alone(cx: &mut TestAppContext) {
325        cx.update(|cx| {
326            apply_preference(None, cx);
327            assert!(!cx.reduce_motion());
328
329            cx.set_reduce_motion(true);
330            apply_preference(None, cx);
331            assert!(cx.reduce_motion());
332        });
333    }
334
335    #[gpui::test]
336    fn the_system_drives_the_flag_until_the_application_sets_it(cx: &mut TestAppContext) {
337        cx.update(|cx| {
338            apply_preference(Some(true), cx);
339            apply_preference(Some(false), cx);
340            assert!(!cx.reduce_motion());
341            apply_preference(Some(true), cx);
342            assert!(cx.reduce_motion());
343
344            cx.set_reduce_motion(false);
345            apply_preference(Some(true), cx);
346            assert!(!cx.reduce_motion());
347        });
348    }
349
350    #[gpui::test]
351    fn the_test_scheduler_is_never_asked_for_the_platform_preference(cx: &mut TestAppContext) {
352        cx.update(|cx| {
353            apply_system_reduce_motion(cx);
354            assert!(!cx.reduce_motion());
355        });
356        cx.run_until_parked();
357        cx.update(|cx| assert!(!cx.reduce_motion()));
358    }
359
360    #[gpui::test]
361    fn a_flag_the_application_set_before_the_first_reading_is_kept(cx: &mut TestAppContext) {
362        cx.update(|cx| {
363            cx.set_reduce_motion(true);
364            apply_preference(Some(false), cx);
365            assert!(cx.reduce_motion());
366        });
367    }
368}