Skip to main content

gpui_base/
reduce_motion.rs

1//! Honors the operating system's reduced-motion preference.
2//!
3//! Every Base transition, spring, presence and reveal consults
4//! [`App::reduce_motion`], but GPUI never reads the platform's setting into
5//! that flag: it stays `false` until something sets it. [`init`] reads the
6//! setting when Base initializes and writes it into the flag, so an
7//! application inherits the user's choice by calling `gpui_base::init` or
8//! `gpui_component::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 retains the legacy
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_base::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_base::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///
82/// This differs from [`crate::ReducedMotion`], which selects how an individual
83/// animation behaves while reduced motion is active.
84#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
85pub enum ReduceMotionPreference {
86    /// Use the last known system preference and existing platform updates.
87    #[default]
88    System,
89    /// Reduce motion regardless of the system preference.
90    Reduce,
91    /// Allow motion regardless of the system preference.
92    Allow,
93}
94
95/// Selects the application's reduced-motion preference.
96///
97/// [`ReduceMotionPreference::Reduce`] and [`ReduceMotionPreference::Allow`] set
98/// [`App::reduce_motion`] and prevent Base's system readings from changing it,
99/// even when the value already matches. The application can still change the
100/// flag directly; system readings continue to be cached.
101///
102/// [`ReduceMotionPreference::System`] releases application ownership, resumes
103/// the last known system value and calls [`apply_system_reduce_motion`] through
104/// the existing platform mechanism. If no system value is known, the current
105/// flag is kept until a reading arrives. On Linux, an existing portal listener
106/// supplies updates; selecting System does not restart it or force a new read.
107///
108/// System also releases ownership taken through [`App::set_reduce_motion`].
109/// Under the test scheduler, explicit choices and cached readings still apply,
110/// but the platform is never queried.
111pub fn set_reduce_motion_preference(preference: ReduceMotionPreference, cx: &mut App) {
112    match preference {
113        ReduceMotionPreference::Reduce | ReduceMotionPreference::Allow => {
114            cx.default_global::<SystemReduceMotion>().overridden = true;
115            cx.set_reduce_motion(preference == ReduceMotionPreference::Reduce);
116        }
117        ReduceMotionPreference::System => {
118            let current = cx.reduce_motion();
119            let state = cx.default_global::<SystemReduceMotion>();
120            state.overridden = false;
121            // Release both explicit ownership and the legacy value-comparison guard.
122            state.applied = Some(current);
123            let system = state.system;
124            apply_preference(system, cx);
125            apply_system_reduce_motion(cx);
126        }
127    }
128}
129
130/// Whether the application runs on GPUI's deterministic test scheduler,
131/// which must not be woken by a platform answering from its own thread.
132fn is_test_scheduler(cx: &App) -> bool {
133    cx.background_executor()
134        .scheduler_executor()
135        .scheduler()
136        .as_test()
137        .is_some()
138}
139
140/// Writes one reading of the system preference into the flag, unless the
141/// application has taken the flag over since the reading Base last applied.
142fn apply_preference(preference: Option<bool>, cx: &mut App) {
143    let Some(reduce) = preference else {
144        return;
145    };
146    let state = cx.default_global::<SystemReduceMotion>();
147    state.system = Some(reduce);
148    let applied = state.applied;
149    if state.overridden || cx.reduce_motion() != applied.unwrap_or(false) {
150        return;
151    }
152    cx.set_reduce_motion(reduce);
153    cx.default_global::<SystemReduceMotion>().applied = Some(reduce);
154}
155
156#[cfg(target_os = "macos")]
157mod platform {
158    use gpui::App;
159    use objc2_app_kit::NSWorkspace;
160
161    pub(super) fn read() -> Option<bool> {
162        Some(NSWorkspace::sharedWorkspace().accessibilityDisplayShouldReduceMotion())
163    }
164
165    pub(super) fn follow(_cx: &mut App) {}
166}
167
168#[cfg(target_os = "windows")]
169mod platform {
170    use gpui::App;
171    use windows::Win32::{
172        Foundation::BOOL,
173        UI::WindowsAndMessaging::{
174            SPI_GETCLIENTAREAANIMATION, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
175        },
176    };
177
178    pub(super) fn read() -> Option<bool> {
179        let mut animations_enabled = BOOL(0);
180        // SAFETY: SPI_GETCLIENTAREAANIMATION writes one BOOL through `pvParam`
181        // and ignores `uiParam`; the BOOL outlives the call.
182        unsafe {
183            SystemParametersInfoW(
184                SPI_GETCLIENTAREAANIMATION,
185                0,
186                Some((&mut animations_enabled as *mut BOOL).cast()),
187                SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),
188            )
189        }
190        .ok()?;
191        Some(!animations_enabled.as_bool())
192    }
193
194    pub(super) fn follow(_cx: &mut App) {}
195}
196
197#[cfg(target_os = "linux")]
198mod platform {
199    use ashpd::desktop::settings::{ReducedMotion, Settings};
200    use futures::StreamExt as _;
201    use gpui::App;
202
203    /// The portal answers asynchronously; [`follow`] applies the first reading.
204    pub(super) fn read() -> Option<bool> {
205        None
206    }
207
208    pub(super) fn follow(cx: &mut App) {
209        cx.spawn(async move |cx| {
210            let settings = Settings::new().await.ok()?;
211            let current = settings.reduced_motion().await.ok()?;
212            cx.update(|cx| super::apply_preference(Some(reduces(current)), cx));
213            let mut changes = settings.receive_reduced_motion_changed().await.ok()?;
214            while let Some(preference) = changes.next().await {
215                cx.update(|cx| super::apply_preference(Some(reduces(preference)), cx));
216            }
217            Some(())
218        })
219        .detach();
220    }
221
222    fn reduces(preference: ReducedMotion) -> bool {
223        matches!(preference, ReducedMotion::ReducedMotion)
224    }
225}
226
227#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
228mod platform {
229    use gpui::App;
230
231    pub(super) fn read() -> Option<bool> {
232        None
233    }
234
235    pub(super) fn follow(_cx: &mut App) {}
236}
237
238#[cfg(test)]
239mod tests {
240    use gpui::TestAppContext;
241
242    use super::{
243        ReduceMotionPreference, apply_preference, apply_system_reduce_motion,
244        set_reduce_motion_preference,
245    };
246
247    #[gpui::test]
248    fn an_explicit_same_value_override_survives_system_changes(cx: &mut TestAppContext) {
249        cx.update(|cx| {
250            for (preference, value) in [
251                (ReduceMotionPreference::Allow, false),
252                (ReduceMotionPreference::Reduce, true),
253            ] {
254                set_reduce_motion_preference(ReduceMotionPreference::System, cx);
255                apply_preference(Some(value), cx);
256                set_reduce_motion_preference(preference, cx);
257                apply_preference(Some(!value), cx);
258                assert_eq!(cx.reduce_motion(), value);
259                apply_preference(Some(value), cx);
260                apply_preference(Some(!value), cx);
261                assert_eq!(cx.reduce_motion(), value);
262            }
263        });
264    }
265
266    #[gpui::test]
267    fn clearing_an_override_restores_the_latest_system_reading(cx: &mut TestAppContext) {
268        cx.update(|cx| {
269            apply_preference(Some(false), cx);
270            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
271            apply_preference(Some(true), cx);
272            apply_preference(Some(false), cx);
273            assert!(cx.reduce_motion());
274            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
275            assert!(!cx.reduce_motion());
276            apply_preference(Some(true), cx);
277            assert!(cx.reduce_motion());
278
279            set_reduce_motion_preference(ReduceMotionPreference::Allow, cx);
280            apply_preference(Some(false), cx);
281            apply_preference(Some(true), cx);
282            assert!(!cx.reduce_motion());
283            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
284            assert!(cx.reduce_motion());
285            apply_preference(Some(false), cx);
286            assert!(!cx.reduce_motion());
287        });
288    }
289
290    #[gpui::test]
291    fn an_override_before_the_first_reading_is_explicit_even_when_false(cx: &mut TestAppContext) {
292        cx.update(|cx| {
293            set_reduce_motion_preference(ReduceMotionPreference::Allow, cx);
294            apply_preference(Some(true), cx);
295            assert!(!cx.reduce_motion());
296            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
297            assert!(cx.reduce_motion());
298        });
299    }
300
301    #[gpui::test]
302    fn clearing_without_a_system_reading_keeps_the_flag_until_one_arrives(cx: &mut TestAppContext) {
303        cx.update(|cx| {
304            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
305            apply_preference(None, cx);
306            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
307            assert!(cx.reduce_motion());
308            apply_preference(Some(false), cx);
309            assert!(!cx.reduce_motion());
310        });
311    }
312
313    #[gpui::test]
314    fn clearing_can_resume_after_a_legacy_direct_override(cx: &mut TestAppContext) {
315        cx.update(|cx| {
316            apply_preference(Some(false), cx);
317            cx.set_reduce_motion(true);
318            apply_preference(Some(false), cx);
319            assert!(cx.reduce_motion());
320            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
321            assert!(!cx.reduce_motion());
322            // Direct setters retain their previous value-comparison contract.
323            cx.set_reduce_motion(true);
324            apply_preference(Some(false), cx);
325            assert!(cx.reduce_motion());
326        });
327    }
328
329    #[gpui::test]
330    fn unknown_readings_preserve_the_last_known_system_preference(cx: &mut TestAppContext) {
331        cx.update(|cx| {
332            apply_preference(Some(true), cx);
333            set_reduce_motion_preference(ReduceMotionPreference::Allow, cx);
334            apply_preference(None, cx);
335            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
336            assert!(cx.reduce_motion());
337        });
338    }
339
340    #[gpui::test]
341    fn the_application_can_change_its_explicit_override_without_yielding_ownership(
342        cx: &mut TestAppContext,
343    ) {
344        cx.update(|cx| {
345            apply_preference(Some(false), cx);
346            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
347            cx.set_reduce_motion(false);
348            apply_preference(Some(true), cx);
349            assert!(!cx.reduce_motion());
350            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
351            assert!(cx.reduce_motion());
352        });
353    }
354
355    #[gpui::test]
356    fn repeated_clears_and_later_readings_respect_the_current_owner(cx: &mut TestAppContext) {
357        cx.update(|cx| {
358            apply_preference(Some(false), cx);
359            set_reduce_motion_preference(ReduceMotionPreference::Reduce, cx);
360            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
361            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
362            assert!(!cx.reduce_motion());
363            set_reduce_motion_preference(ReduceMotionPreference::Allow, cx);
364            // A platform result arriving after the new choice must only cache.
365            apply_preference(Some(true), cx);
366            assert!(!cx.reduce_motion());
367            set_reduce_motion_preference(ReduceMotionPreference::System, cx);
368            assert!(cx.reduce_motion());
369        });
370    }
371
372    #[gpui::test]
373    fn a_system_preference_for_reduced_motion_sets_the_flag(cx: &mut TestAppContext) {
374        cx.update(|cx| {
375            apply_preference(Some(true), cx);
376            assert!(cx.reduce_motion());
377        });
378    }
379
380    #[gpui::test]
381    fn an_unknown_system_preference_leaves_the_flag_alone(cx: &mut TestAppContext) {
382        cx.update(|cx| {
383            apply_preference(None, cx);
384            assert!(!cx.reduce_motion());
385
386            cx.set_reduce_motion(true);
387            apply_preference(None, cx);
388            assert!(cx.reduce_motion());
389        });
390    }
391
392    #[gpui::test]
393    fn the_system_drives_the_flag_until_the_application_sets_it(cx: &mut TestAppContext) {
394        cx.update(|cx| {
395            apply_preference(Some(true), cx);
396            apply_preference(Some(false), cx);
397            assert!(!cx.reduce_motion());
398            apply_preference(Some(true), cx);
399            assert!(cx.reduce_motion());
400
401            cx.set_reduce_motion(false);
402            apply_preference(Some(true), cx);
403            assert!(!cx.reduce_motion());
404        });
405    }
406
407    #[gpui::test]
408    fn the_test_scheduler_is_never_asked_for_the_platform_preference(cx: &mut TestAppContext) {
409        cx.update(|cx| {
410            apply_system_reduce_motion(cx);
411            assert!(!cx.reduce_motion());
412        });
413        cx.run_until_parked();
414        cx.update(|cx| assert!(!cx.reduce_motion()));
415    }
416
417    #[gpui::test]
418    fn a_flag_the_application_set_before_the_first_reading_is_kept(cx: &mut TestAppContext) {
419        cx.update(|cx| {
420            cx.set_reduce_motion(true);
421            apply_preference(Some(false), cx);
422            assert!(cx.reduce_motion());
423        });
424    }
425}