Skip to main content

gpui_material_foundation/
root.rs

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