Skip to main content

gpui_material_foundation/
root.rs

1mod base_projection;
2mod system_sync;
3mod transition;
4
5use std::{cell::RefCell, collections::HashMap, rc::Rc};
6
7use gpui::{
8    AnyView, App, AppContext, Global, Render, Subscription, Window, WindowHandle, WindowId,
9};
10use gpui_base::{Root, Theme};
11use gpui_material_theme::{
12    Appearance, AppearanceMode, ColorScheme, MaterialTheme, MotionKind, MotionSpec, MotionSpeed,
13};
14
15use crate::{
16    strings::init_default_strings,
17    typography::{font_cache_revision, refresh_installed_fonts},
18};
19
20pub use base_projection::project_base_theme;
21use base_projection::{project_base_colors, project_base_metrics};
22pub use system_sync::{
23    ReduceMotionPreference, appearance_from_window, observe_system_appearance,
24    observe_window_system_appearance, set_reduce_motion_preference, sync_system_reduce_motion,
25    system_appearance,
26};
27use transition::PaletteTransition;
28
29struct ActiveMaterialTheme(Rc<MaterialTheme>);
30
31impl Global for ActiveMaterialTheme {}
32
33struct WindowThemeEntry {
34    material: Rc<MaterialTheme>,
35    projected: RefCell<Option<(u64, Theme)>>,
36}
37
38#[derive(Default)]
39struct WindowMaterialThemes(HashMap<WindowId, WindowThemeEntry>);
40
41impl Global for WindowMaterialThemes {}
42
43#[derive(Default)]
44struct ThemeAnimator {
45    transition: Option<PaletteTransition>,
46    driver: Option<WindowId>,
47}
48
49impl Global for ThemeAnimator {}
50
51/// Initializes Material and Base before the application opens its first window.
52pub struct MaterialRoot;
53
54impl MaterialRoot {
55    /// Initializes `gpui-base`, refreshes installed fonts, and installs the application-wide
56    /// Material theme. Call once at startup before opening windows.
57    pub fn init(theme: MaterialTheme, cx: &mut App) {
58        gpui_base::init(cx);
59        if cx.has_global::<ThemeAnimator>() {
60            let animator = cx.global_mut::<ThemeAnimator>();
61            animator.transition = None;
62            animator.driver = None;
63        }
64        refresh_installed_fonts(cx);
65        init_default_strings(cx);
66        apply_material_theme(theme, true, cx);
67    }
68
69    /// Opens a window whose Base root owns overlays and keyboard traversal.
70    pub fn open_window<V: Render>(
71        options: gpui::WindowOptions,
72        cx: &mut App,
73        build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
74    ) -> gpui::Result<WindowHandle<Root>> {
75        cx.open_window(options, |window, cx| {
76            let view = AnyView::from(build(window, cx));
77            cx.new(|cx| Root::new(view, window, cx))
78        })
79    }
80
81    /// Synchronizes the application-wide Material theme with `window`'s appearance.
82    ///
83    /// Convenience alias for [`observe_system_appearance`].
84    pub fn sync_system_appearance(
85        window: &mut Window,
86        cx: &mut App,
87        mode: AppearanceMode,
88        build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
89    ) -> Subscription {
90        observe_system_appearance(window, cx, mode, build_theme)
91    }
92
93    /// Synchronizes a single window's Material theme override with `window`'s appearance.
94    ///
95    /// Convenience alias for [`observe_window_system_appearance`].
96    pub fn sync_window_system_appearance(
97        window: &mut Window,
98        cx: &mut App,
99        mode: AppearanceMode,
100        build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
101    ) -> Subscription {
102        observe_window_system_appearance(window, cx, mode, build_theme)
103    }
104}
105
106/// Returns the shared Material theme installed by [`MaterialRoot::init`].
107pub fn material_theme(cx: &App) -> &MaterialTheme {
108    &cx.global::<ActiveMaterialTheme>().0
109}
110
111/// Resolves a window's override or falls back to the current application theme.
112pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
113    window_theme_handle(window, cx)
114}
115
116pub(crate) fn window_override_handle<'a>(
117    window: &Window,
118    cx: &'a App,
119) -> Option<&'a Rc<MaterialTheme>> {
120    cx.try_global::<WindowMaterialThemes>()
121        .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
122        .map(|entry| &entry.material)
123}
124
125pub(crate) fn window_theme_handle<'a>(window: &Window, cx: &'a App) -> &'a Rc<MaterialTheme> {
126    window_override_handle(window, cx).unwrap_or_else(|| &cx.global::<ActiveMaterialTheme>().0)
127}
128
129/// Returns the cached projected `gpui_base::Theme` for `window` without re-projecting when
130/// the window override (or application global) and installed font revision are unchanged.
131pub(crate) fn cached_window_base_theme(window: &Window, cx: &App) -> Theme {
132    let Some(entry) = cx
133        .try_global::<WindowMaterialThemes>()
134        .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
135    else {
136        return Theme::global(cx);
137    };
138    let revision = font_cache_revision(cx);
139    if let Some((cached_rev, cached_theme)) = entry.projected.borrow().as_ref()
140        && *cached_rev == revision
141    {
142        return cached_theme.clone();
143    }
144    let projected = project_base_theme(&entry.material, cx);
145    *entry.projected.borrow_mut() = Some((revision, projected.clone()));
146    projected
147}
148
149/// Sets or clears the override for Material elements in this window.
150///
151/// Material controls pass local presentation to their Base-backed parts without
152/// mutating Base's application-global theme. Standalone Base controls inside an
153/// overridden window or subtree can call [`crate::current_base_theme`] or
154/// [`project_base_theme`] to apply matching local tokens and scrollbar styles.
155pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
156    let fonts_changed = refresh_installed_fonts(cx);
157    if !fonts_changed && window_override_handle(window, cx).map(Rc::as_ref) == theme.as_ref() {
158        return;
159    }
160    if !cx.has_global::<WindowMaterialThemes>() {
161        cx.set_global(WindowMaterialThemes::default());
162        cx.on_window_closed(|cx, id| {
163            cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
164        })
165        .detach();
166    }
167    let id = window.window_handle().window_id();
168    let projected = theme
169        .as_ref()
170        .map(|t| (font_cache_revision(cx), project_base_theme(t, cx)));
171    let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
172    if let Some(theme) = theme {
173        themes.insert(
174            id,
175            WindowThemeEntry {
176                material: Rc::new(theme),
177                projected: RefCell::new(projected),
178            },
179        );
180    } else {
181        themes.remove(&id);
182    }
183    window.refresh();
184}
185
186/// Updates the application theme and projects its current values into Base.
187/// Colors follow the new theme's Slow Effects motion spec from the displayed
188/// palette. Typography and layout apply immediately.
189pub fn set_material_theme(mut theme: MaterialTheme, cx: &mut App) {
190    let fonts_changed = refresh_installed_fonts(cx);
191    let has_transition = cx
192        .try_global::<ThemeAnimator>()
193        .is_some_and(|animator| animator.transition.is_some());
194    if !fonts_changed
195        && !has_transition
196        && cx
197            .try_global::<ActiveMaterialTheme>()
198            .is_some_and(|previous| *previous.0 == theme)
199    {
200        return;
201    }
202    let spec = theme
203        .motion
204        .spec(MotionKind::Effects, MotionSpeed::Slow, cx.reduce_motion());
205    let previous = cx.try_global::<ActiveMaterialTheme>();
206    if let Some(previous) = previous
207        && previous.0.colors != theme.colors
208        && !cx.windows().is_empty()
209        && !matches!(spec, MotionSpec::Instant)
210    {
211        let shown = previous.0.colors.clone();
212        let started = cx.background_executor().now();
213        if !cx.has_global::<ThemeAnimator>() {
214            cx.set_global(ThemeAnimator::default());
215            cx.on_window_closed(|cx, closed| {
216                let animator = cx.global_mut::<ThemeAnimator>();
217                if animator.driver == Some(closed) {
218                    animator.driver = None;
219                    schedule_theme_frame(cx);
220                }
221            })
222            .detach();
223        }
224        let animator = cx.global_mut::<ThemeAnimator>();
225        if !animator
226            .transition
227            .as_ref()
228            .is_some_and(|pending| pending.to == theme.colors && pending.spec == spec)
229        {
230            animator.transition =
231                PaletteTransition::new(shown.clone(), theme.colors.clone(), spec, started);
232        }
233        if animator.transition.is_some() {
234            theme.colors = shown;
235            if animator.driver.is_none() {
236                // The caller may already be updating a window. Register the
237                // callback after that window is accessible again.
238                cx.defer(schedule_theme_frame);
239            }
240        }
241    } else if cx.has_global::<ThemeAnimator>() {
242        let animator = cx.global_mut::<ThemeAnimator>();
243        animator.transition = None;
244        animator.driver = None;
245    }
246    apply_material_theme(theme, true, cx);
247}
248
249fn schedule_theme_frame(cx: &mut App) {
250    let animator = cx.global::<ThemeAnimator>();
251    if animator.transition.is_none() || animator.driver.is_some() {
252        return;
253    }
254    let active = cx.active_window();
255    let windows = cx.windows();
256    let driver = active
257        .into_iter()
258        .chain(
259            windows
260                .iter()
261                .copied()
262                .filter(|handle| Some(*handle) != active),
263        )
264        .find(|handle| {
265            handle
266                .update(cx, |_, window, _| {
267                    if window.is_visible() {
268                        window.on_next_frame(advance_theme_frame);
269                        true
270                    } else {
271                        false
272                    }
273                })
274                .unwrap_or(false)
275        });
276    if let Some(driver) = driver {
277        cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
278    } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
279        apply_palette(transition.to, cx);
280    }
281}
282
283fn advance_theme_frame(window: &mut Window, cx: &mut App) {
284    let id = window.window_handle().window_id();
285    let now = cx.background_executor().now();
286    let reduce_motion = cx.reduce_motion();
287    let animator = cx.global_mut::<ThemeAnimator>();
288    if animator.driver != Some(id) {
289        return;
290    }
291    if reduce_motion {
292        animator.driver = None;
293        if let Some(transition) = animator.transition.take() {
294            apply_palette(transition.to, cx);
295        }
296        return;
297    }
298    let Some(transition) = animator.transition.as_mut() else {
299        animator.driver = None;
300        return;
301    };
302    let (progress, running) = transition.advance(now);
303    if !running || progress >= 0.999 {
304        animator.driver = None;
305        if let Some(transition) = animator.transition.take() {
306            apply_palette(transition.to, cx);
307        }
308    } else {
309        let colors = transition.from.blend(&transition.to, progress);
310        apply_palette(colors, cx);
311        if window.is_visible() {
312            window.on_next_frame(advance_theme_frame);
313        } else {
314            cx.global_mut::<ThemeAnimator>().driver = None;
315            cx.defer(schedule_theme_frame);
316        }
317    }
318}
319
320fn apply_palette(colors: ColorScheme, cx: &mut App) {
321    let current = material_theme(cx);
322    if current.colors != colors {
323        let theme = MaterialTheme {
324            colors,
325            typography: current.typography.clone(),
326            motion: current.motion,
327            layout: current.layout,
328        };
329        apply_material_theme(theme, false, cx);
330    }
331}
332
333fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
334    let mut projected = Theme::global(cx);
335    project_base_colors(&mut projected, &theme);
336    if project_typography {
337        project_base_metrics(&mut projected, &theme, cx);
338    }
339    cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
340    cx.set_global(projected);
341    refresh_inherited_windows(cx);
342}
343
344fn refresh_inherited_windows(cx: &mut App) {
345    let overridden: Vec<WindowId> = cx
346        .try_global::<WindowMaterialThemes>()
347        .map(|themes| themes.0.keys().copied().collect())
348        .unwrap_or_default();
349    if overridden.is_empty() {
350        cx.refresh_windows();
351        return;
352    }
353    for handle in cx.windows() {
354        if !overridden.contains(&handle.window_id()) {
355            let _ = handle.update(cx, |_, window, _| window.refresh());
356        }
357    }
358}