Skip to main content

gpui_material_foundation/root/
system_sync.rs

1use gpui::{App, Subscription, Window, WindowAppearance};
2use gpui_material_theme::{Appearance, AppearanceMode, MaterialTheme};
3
4use crate::root::{set_material_theme, set_window_material_theme};
5
6/// The source and value of the application's reduced-motion preference.
7#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
8pub enum ReduceMotionPreference {
9    /// Follow the operating system's reduced-motion setting.
10    #[default]
11    System,
12    /// Reduce motion regardless of the operating system preference.
13    Reduce,
14    /// Allow motion regardless of the operating system preference.
15    Allow,
16}
17
18impl ReduceMotionPreference {
19    pub(crate) const fn to_base(self) -> gpui_base::ReduceMotionPreference {
20        match self {
21            Self::System => gpui_base::ReduceMotionPreference::System,
22            Self::Reduce => gpui_base::ReduceMotionPreference::Reduce,
23            Self::Allow => gpui_base::ReduceMotionPreference::Allow,
24        }
25    }
26}
27
28/// Selects the application's reduced-motion preference.
29///
30/// [`ReduceMotionPreference::Reduce`] and [`ReduceMotionPreference::Allow`] update
31/// [`App::reduce_motion`] and prevent system preference readings from overriding it.
32/// [`ReduceMotionPreference::System`] releases explicit ownership and resumes
33/// following the operating system preference via [`sync_system_reduce_motion`].
34/// Under GPUI's test scheduler, explicit choices and cached readings still apply
35/// without querying the host platform.
36pub fn set_reduce_motion_preference(preference: ReduceMotionPreference, cx: &mut App) {
37    gpui_base::set_reduce_motion_preference(preference.to_base(), cx);
38}
39
40/// Maps a GPUI [`WindowAppearance`] to a Material [`Appearance`].
41///
42/// [`WindowAppearance::Light`] and [`WindowAppearance::VibrantLight`] resolve to
43/// [`Appearance::Light`]; [`WindowAppearance::Dark`] and [`WindowAppearance::VibrantDark`]
44/// resolve to [`Appearance::Dark`].
45pub const fn appearance_from_window(appearance: WindowAppearance) -> Appearance {
46    match appearance {
47        WindowAppearance::Light | WindowAppearance::VibrantLight => Appearance::Light,
48        WindowAppearance::Dark | WindowAppearance::VibrantDark => Appearance::Dark,
49    }
50}
51
52/// Returns the current operating-system [`Appearance`] reported by GPUI on `cx`.
53///
54/// Call this before opening the first window to initialize [`crate::MaterialRoot::init`]
55/// with the active system appearance without a light-to-dark flash.
56pub fn system_appearance(cx: &App) -> Appearance {
57    appearance_from_window(cx.window_appearance())
58}
59
60/// Re-reads the operating system's reduced-motion preference and applies it to `cx`.
61///
62/// Delegates to [`gpui_base::apply_system_reduce_motion`]. `gpui-base` reads the OS
63/// preference once during [`crate::MaterialRoot::init`]; call this helper again to
64/// refresh the setting on platforms that do not push live updates (such as Windows and
65/// macOS). Explicit overrides set via [`set_reduce_motion_preference`] or
66/// [`App::set_reduce_motion`] are preserved, and under GPUI's test scheduler the platform
67/// is never queried.
68pub fn sync_system_reduce_motion(cx: &mut App) {
69    gpui_base::apply_system_reduce_motion(cx);
70}
71
72struct AppearanceTracker<F> {
73    mode: AppearanceMode,
74    last_applied: Option<Appearance>,
75    build_theme: F,
76}
77
78impl<F> AppearanceTracker<F>
79where
80    F: FnMut(Appearance) -> MaterialTheme,
81{
82    fn new(mode: AppearanceMode, build_theme: F) -> Self {
83        Self {
84            mode,
85            last_applied: None,
86            build_theme,
87        }
88    }
89
90    fn next_theme(&mut self, window_appearance: WindowAppearance) -> Option<MaterialTheme> {
91        let resolved = self.mode.resolve(appearance_from_window(window_appearance));
92        if self.last_applied == Some(resolved) {
93            return None;
94        }
95        self.last_applied = Some(resolved);
96        Some((self.build_theme)(resolved))
97    }
98}
99
100/// Synchronizes the application-wide Material theme with `window`'s appearance.
101///
102/// Immediately resolves `mode` against [`Window::appearance`], builds the theme with
103/// `build_theme`, and applies it via [`set_material_theme`]. When `mode` is
104/// [`AppearanceMode::System`], subscribes to [`Window::observe_window_appearance`] so
105/// subsequent OS light/dark changes smoothly transition the application theme through
106/// [`set_material_theme`] while preserving window-level overrides on other windows.
107///
108/// Redundant notifications that resolve to the same [`Appearance`] (for example,
109/// [`WindowAppearance::Light`] to [`WindowAppearance::VibrantLight`] or duplicate
110/// platform callbacks) are skipped without invoking `build_theme` again. Retain the
111/// returned [`Subscription`] for as long as observation should remain active, or call
112/// [`Subscription::detach`] to tie it to the window's lifetime.
113pub fn observe_system_appearance(
114    window: &mut Window,
115    cx: &mut App,
116    mode: AppearanceMode,
117    build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
118) -> Subscription {
119    let mut tracker = AppearanceTracker::new(mode, build_theme);
120    if let Some(theme) = tracker.next_theme(window.appearance()) {
121        set_material_theme(theme, cx);
122    }
123    if mode != AppearanceMode::System {
124        return Subscription::new(|| {});
125    }
126    window.observe_window_appearance(move |window, cx| {
127        if let Some(theme) = tracker.next_theme(window.appearance()) {
128            set_material_theme(theme, cx);
129        }
130    })
131}
132
133/// Synchronizes a single window's Material theme override with `window`'s appearance.
134///
135/// Immediately resolves `mode` against [`Window::appearance`], builds the theme with
136/// `build_theme`, and applies it to `window` via [`set_window_material_theme`] without
137/// mutating the application-wide theme. When `mode` is [`AppearanceMode::System`],
138/// subscribes to [`Window::observe_window_appearance`] and updates only `window` whenever
139/// the resolved [`Appearance`] changes.
140///
141/// Dropping the returned [`Subscription`] stops future updates; call
142/// `set_window_material_theme(None, window, cx)` to clear the override and inherit the
143/// application theme again.
144pub fn observe_window_system_appearance(
145    window: &mut Window,
146    cx: &mut App,
147    mode: AppearanceMode,
148    build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
149) -> Subscription {
150    let mut tracker = AppearanceTracker::new(mode, build_theme);
151    if let Some(theme) = tracker.next_theme(window.appearance()) {
152        set_window_material_theme(Some(theme), window, cx);
153    }
154    if mode != AppearanceMode::System {
155        return Subscription::new(|| {});
156    }
157    window.observe_window_appearance(move |window, cx| {
158        if let Some(theme) = tracker.next_theme(window.appearance()) {
159            set_window_material_theme(Some(theme), window, cx);
160        }
161    })
162}
163
164#[cfg(test)]
165mod tests {
166    use std::cell::Cell;
167
168    use super::*;
169    use gpui_material_theme::{Density, MotionScheme};
170
171    #[test]
172    fn reduce_motion_preference_is_material_owned_and_maps_all_variants() {
173        assert_ne!(
174            std::any::TypeId::of::<ReduceMotionPreference>(),
175            std::any::TypeId::of::<gpui_base::ReduceMotionPreference>()
176        );
177        assert_eq!(
178            ReduceMotionPreference::default(),
179            ReduceMotionPreference::System
180        );
181        assert_eq!(
182            ReduceMotionPreference::System.to_base(),
183            gpui_base::ReduceMotionPreference::System
184        );
185        assert_eq!(
186            ReduceMotionPreference::Reduce.to_base(),
187            gpui_base::ReduceMotionPreference::Reduce
188        );
189        assert_eq!(
190            ReduceMotionPreference::Allow.to_base(),
191            gpui_base::ReduceMotionPreference::Allow
192        );
193    }
194
195    #[test]
196    fn maps_all_window_appearances_to_material_appearance() {
197        const LIGHT: Appearance = appearance_from_window(WindowAppearance::Light);
198        const VIBRANT_LIGHT: Appearance = appearance_from_window(WindowAppearance::VibrantLight);
199        const DARK: Appearance = appearance_from_window(WindowAppearance::Dark);
200        const VIBRANT_DARK: Appearance = appearance_from_window(WindowAppearance::VibrantDark);
201
202        assert_eq!(LIGHT, Appearance::Light);
203        assert_eq!(VIBRANT_LIGHT, Appearance::Light);
204        assert_eq!(DARK, Appearance::Dark);
205        assert_eq!(VIBRANT_DARK, Appearance::Dark);
206    }
207
208    #[test]
209    fn tracker_skips_redundant_updates_and_preserves_custom_builder_settings() {
210        let calls = Cell::new(0usize);
211        let mut tracker = AppearanceTracker::new(AppearanceMode::System, |appearance| {
212            calls.set(calls.get() + 1);
213            MaterialTheme::baseline(appearance)
214                .motion(MotionScheme::Expressive)
215                .density(Density::Compact)
216        });
217
218        let first = tracker.next_theme(WindowAppearance::Light).unwrap();
219        assert_eq!(first.colors.appearance(), Appearance::Light);
220        assert_eq!(first.motion, MotionScheme::Expressive);
221        assert_eq!(first.layout.density, Density::Compact);
222        assert_eq!(calls.get(), 1);
223
224        // Light -> Light and Light -> VibrantLight resolve to the same Appearance.
225        assert!(tracker.next_theme(WindowAppearance::Light).is_none());
226        assert!(tracker.next_theme(WindowAppearance::VibrantLight).is_none());
227        assert_eq!(calls.get(), 1);
228
229        // Switching to Dark or VibrantDark rebuilds once.
230        let dark = tracker.next_theme(WindowAppearance::Dark).unwrap();
231        assert_eq!(dark.colors.appearance(), Appearance::Dark);
232        assert_eq!(dark.motion, MotionScheme::Expressive);
233        assert_eq!(dark.layout.density, Density::Compact);
234        assert_eq!(calls.get(), 2);
235
236        assert!(tracker.next_theme(WindowAppearance::VibrantDark).is_none());
237        assert_eq!(calls.get(), 2);
238
239        // Returning to VibrantLight rebuilds once back to Light.
240        let light_again = tracker.next_theme(WindowAppearance::VibrantLight).unwrap();
241        assert_eq!(light_again.colors.appearance(), Appearance::Light);
242        assert_eq!(calls.get(), 3);
243    }
244
245    #[test]
246    fn fixed_mode_tracker_builds_once_regardless_of_system_changes() {
247        for (mode, expected) in [
248            (AppearanceMode::Light, Appearance::Light),
249            (AppearanceMode::Dark, Appearance::Dark),
250        ] {
251            let calls = Cell::new(0usize);
252            let mut tracker = AppearanceTracker::new(mode, |appearance| {
253                calls.set(calls.get() + 1);
254                MaterialTheme::baseline(appearance)
255            });
256
257            let initial = tracker.next_theme(WindowAppearance::Light).unwrap();
258            assert_eq!(initial.colors.appearance(), expected);
259            assert_eq!(calls.get(), 1);
260
261            assert!(tracker.next_theme(WindowAppearance::Dark).is_none());
262            assert!(tracker.next_theme(WindowAppearance::VibrantDark).is_none());
263            assert!(tracker.next_theme(WindowAppearance::VibrantLight).is_none());
264            assert_eq!(calls.get(), 1);
265        }
266    }
267}