Skip to main content

gpui_material_foundation/
root.rs

1use std::{collections::HashMap, rc::Rc, time::Duration};
2
3use gpui::{
4    AnyView, App, AppContext, Global, Render, SpringConfig, SpringState, Window, WindowHandle,
5    WindowId, px,
6};
7use gpui_base::{
8    ResizableTheme, Root, ScrollbarStyles, ScrollbarTheme, Theme, ThemeAppearance, motion::Easing,
9};
10use gpui_material_theme::{
11    Appearance, ColorRole, ColorScheme, CornerRole, MaterialTheme, MotionKind, MotionSpec,
12    MotionSpeed, TypeRole, TypographyEmphasis,
13};
14use web_time::Instant;
15
16use crate::{
17    color, font_for_style,
18    motion::{RetargetTransition, spring_config},
19    typography::refresh_installed_fonts,
20};
21
22struct ActiveMaterialTheme(Rc<MaterialTheme>);
23
24impl Global for ActiveMaterialTheme {}
25
26#[derive(Default)]
27struct WindowMaterialThemes(HashMap<WindowId, Rc<MaterialTheme>>);
28
29impl Global for WindowMaterialThemes {}
30
31enum PaletteCurve {
32    Spring {
33        config: SpringConfig,
34        state: SpringState,
35        updated_at: Instant,
36    },
37    Tween(RetargetTransition),
38}
39
40struct PaletteTransition {
41    from: ColorScheme,
42    to: ColorScheme,
43    curve: PaletteCurve,
44    spec: MotionSpec,
45}
46
47impl PaletteTransition {
48    fn new(from: ColorScheme, to: ColorScheme, spec: MotionSpec, now: Instant) -> Option<Self> {
49        let curve = match spec {
50            MotionSpec::Instant => return None,
51            MotionSpec::Spring(spring) => PaletteCurve::Spring {
52                config: spring_config(spring)?,
53                state: SpringState {
54                    position: 0.0,
55                    velocity: 0.0,
56                },
57                updated_at: now,
58            },
59            MotionSpec::Tween {
60                duration_ms,
61                easing,
62            } => {
63                let duration = Duration::from_millis(u64::from(duration_ms));
64                let curve =
65                    Easing::cubic_bezier(easing.x1, easing.y1, easing.x2, easing.y2).ok()?;
66                if duration.is_zero() {
67                    return None;
68                }
69                let mut transition = RetargetTransition::settled(0.0);
70                transition.animate_to(1.0, duration, curve, now, false);
71                PaletteCurve::Tween(transition)
72            }
73        };
74        Some(Self {
75            from,
76            to,
77            curve,
78            spec,
79        })
80    }
81
82    fn advance(&mut self, now: Instant) -> (f32, bool) {
83        match &mut self.curve {
84            PaletteCurve::Spring {
85                config,
86                state,
87                updated_at,
88            } => {
89                let elapsed = now.saturating_duration_since(*updated_at).as_secs_f32();
90                let stepped = config.step(*state, 1.0, elapsed);
91                *state = stepped;
92                *updated_at = now;
93                if config.is_settled(stepped, 1.0, 0.001) {
94                    (1.0, false)
95                } else {
96                    (stepped.position.clamp(0.0, 1.0), true)
97                }
98            }
99            PaletteCurve::Tween(transition) => {
100                let (value, running) = transition.sample(now, false);
101                (value.clamp(0.0, 1.0), running)
102            }
103        }
104    }
105}
106
107#[derive(Default)]
108struct ThemeAnimator {
109    transition: Option<PaletteTransition>,
110    driver: Option<WindowId>,
111}
112
113impl Global for ThemeAnimator {}
114
115/// Initializes Material and Base before the application opens its first window.
116pub struct MaterialRoot;
117
118impl MaterialRoot {
119    pub fn init(theme: MaterialTheme, cx: &mut App) {
120        gpui_base::init(cx);
121        if let Some(animator) = cx.try_global::<ThemeAnimator>()
122            && animator.transition.is_some()
123        {
124            cx.global_mut::<ThemeAnimator>().transition = None;
125        }
126        refresh_installed_fonts(cx);
127        apply_material_theme(theme, true, cx);
128    }
129
130    /// Opens a window whose Base root owns overlays and keyboard traversal.
131    pub fn open_window<V: Render>(
132        options: gpui::WindowOptions,
133        cx: &mut App,
134        build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
135    ) -> gpui::Result<WindowHandle<Root>> {
136        cx.open_window(options, |window, cx| {
137            let view = AnyView::from(build(window, cx));
138            cx.new(|cx| Root::new(view, window, cx))
139        })
140    }
141}
142
143/// Returns the shared Material theme installed by [`MaterialRoot::init`].
144pub fn material_theme(cx: &App) -> &MaterialTheme {
145    &cx.global::<ActiveMaterialTheme>().0
146}
147
148/// Resolves a window's override or falls back to the current application theme.
149pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
150    window_theme_handle(window, cx)
151}
152
153pub(crate) fn window_override_handle<'a>(
154    window: &Window,
155    cx: &'a App,
156) -> Option<&'a Rc<MaterialTheme>> {
157    cx.try_global::<WindowMaterialThemes>()
158        .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
159}
160
161pub(crate) fn window_theme_handle<'a>(window: &Window, cx: &'a App) -> &'a Rc<MaterialTheme> {
162    window_override_handle(window, cx).unwrap_or_else(|| &cx.global::<ActiveMaterialTheme>().0)
163}
164
165/// Sets or clears the override for Material elements in this window.
166///
167/// Material controls pass local presentation to their Base-backed parts without
168/// mutating Base's application-global theme. Standalone Base controls inside an
169/// overridden window or subtree can call [`crate::current_base_theme`] or
170/// [`project_base_theme`] to apply matching local tokens and scrollbar styles.
171pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
172    refresh_installed_fonts(cx);
173    if !cx.has_global::<WindowMaterialThemes>() {
174        cx.set_global(WindowMaterialThemes::default());
175        cx.on_window_closed(|cx, id| {
176            cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
177        })
178        .detach();
179    }
180    let id = window.window_handle().window_id();
181    let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
182    if let Some(theme) = theme {
183        themes.insert(id, Rc::new(theme));
184    } else {
185        themes.remove(&id);
186    }
187    window.refresh();
188}
189
190/// Projects a [`MaterialTheme`] into a matching `gpui_base::Theme` without
191/// mutating the application-global Base theme.
192///
193/// Use this (or [`crate::current_base_theme`]) when styling standalone Base
194/// controls inside a window override or [`crate::ThemeScope`].
195pub fn project_base_theme(theme: &MaterialTheme, cx: &App) -> Theme {
196    let mut projected = Theme::global(cx);
197    project_base_colors(&mut projected, theme);
198    project_base_metrics(&mut projected, theme, cx);
199    projected
200}
201
202/// Updates the application theme and projects its current values into Base.
203/// Colors follow the new theme's Slow Effects motion spec from the displayed
204/// palette. Typography and layout apply immediately.
205pub fn set_material_theme(mut theme: MaterialTheme, cx: &mut App) {
206    refresh_installed_fonts(cx);
207    let spec = theme
208        .motion
209        .spec(MotionKind::Effects, MotionSpeed::Slow, cx.reduce_motion());
210    let previous = cx.try_global::<ActiveMaterialTheme>();
211    if let Some(previous) = previous
212        && previous.0.colors != theme.colors
213        && !cx.windows().is_empty()
214        && !matches!(spec, MotionSpec::Instant)
215    {
216        let shown = previous.0.colors.clone();
217        let started = cx.background_executor().now();
218        if !cx.has_global::<ThemeAnimator>() {
219            cx.set_global(ThemeAnimator::default());
220            cx.on_window_closed(|cx, closed| {
221                let animator = cx.global_mut::<ThemeAnimator>();
222                if animator.driver == Some(closed) {
223                    animator.driver = None;
224                    schedule_theme_frame(cx);
225                }
226            })
227            .detach();
228        }
229        let animator = cx.global_mut::<ThemeAnimator>();
230        if !animator
231            .transition
232            .as_ref()
233            .is_some_and(|pending| pending.to == theme.colors && pending.spec == spec)
234        {
235            animator.transition =
236                PaletteTransition::new(shown.clone(), theme.colors.clone(), spec, started);
237        }
238        if animator.transition.is_some() {
239            theme.colors = shown;
240            if animator.driver.is_none() {
241                // The caller may already be updating a window. Register the
242                // callback after that window is accessible again.
243                cx.defer(schedule_theme_frame);
244            }
245        }
246    } else if cx.has_global::<ThemeAnimator>() {
247        cx.global_mut::<ThemeAnimator>().transition = None;
248    }
249    apply_material_theme(theme, true, cx);
250}
251
252fn schedule_theme_frame(cx: &mut App) {
253    let animator = cx.global::<ThemeAnimator>();
254    if animator.transition.is_none() || animator.driver.is_some() {
255        return;
256    }
257    let active = cx.active_window();
258    let windows = cx.windows();
259    let driver = active
260        .into_iter()
261        .chain(
262            windows
263                .iter()
264                .copied()
265                .filter(|handle| Some(*handle) != active),
266        )
267        .find(|handle| {
268            handle
269                .update(cx, |_, window, _| {
270                    if window.is_visible() {
271                        window.on_next_frame(advance_theme_frame);
272                        true
273                    } else {
274                        false
275                    }
276                })
277                .unwrap_or(false)
278        });
279    if let Some(driver) = driver {
280        cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
281    } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
282        apply_palette(transition.to, cx);
283    }
284}
285
286fn advance_theme_frame(window: &mut Window, cx: &mut App) {
287    let id = window.window_handle().window_id();
288    let now = cx.background_executor().now();
289    let reduce_motion = cx.reduce_motion();
290    let animator = cx.global_mut::<ThemeAnimator>();
291    if animator.driver != Some(id) {
292        return;
293    }
294    let Some(transition) = animator.transition.as_mut() else {
295        animator.driver = None;
296        return;
297    };
298    if reduce_motion {
299        let target = animator.transition.take().unwrap().to;
300        animator.driver = None;
301        apply_palette(target, cx);
302        return;
303    }
304    let (progress, running) = transition.advance(now);
305    if !running || progress >= 0.999 {
306        let target = animator.transition.take().unwrap().to;
307        animator.driver = None;
308        apply_palette(target, cx);
309    } else {
310        let colors = transition.from.blend(&transition.to, progress);
311        apply_palette(colors, cx);
312        if window.is_visible() {
313            window.on_next_frame(advance_theme_frame);
314        } else {
315            cx.global_mut::<ThemeAnimator>().driver = None;
316            cx.defer(schedule_theme_frame);
317        }
318    }
319}
320
321fn apply_palette(colors: ColorScheme, cx: &mut App) {
322    let mut theme = material_theme(cx).clone();
323    if theme.colors != colors {
324        theme.colors = colors;
325        apply_material_theme(theme, false, cx);
326    }
327}
328
329fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
330    let mut projected = Theme::global(cx);
331    project_base_colors(&mut projected, &theme);
332    if project_typography {
333        project_base_metrics(&mut projected, &theme, cx);
334    }
335    cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
336    cx.set_global(projected);
337    refresh_inherited_windows(cx);
338}
339
340fn refresh_inherited_windows(cx: &mut App) {
341    let overridden: Vec<WindowId> = cx
342        .try_global::<WindowMaterialThemes>()
343        .map(|themes| themes.0.keys().copied().collect())
344        .unwrap_or_default();
345    if overridden.is_empty() {
346        cx.refresh_windows();
347        return;
348    }
349    for handle in cx.windows() {
350        if !overridden.contains(&handle.window_id()) {
351            let _ = handle.update(cx, |_, window, _| window.refresh());
352        }
353    }
354}
355
356fn project_base_colors(projected: &mut Theme, theme: &MaterialTheme) {
357    use ColorRole::*;
358
359    projected.appearance = match theme.colors.appearance() {
360        Appearance::Light => ThemeAppearance::Light,
361        Appearance::Dark => ThemeAppearance::Dark,
362    };
363    let role = |role| color(theme.colors.color(role));
364    let colors = &mut projected.tokens.colors;
365    colors.background = role(Surface);
366    colors.foreground = role(OnSurface);
367    colors.surface = role(SurfaceContainer);
368    colors.surface_foreground = role(OnSurface);
369    colors.primary = role(Primary);
370    colors.primary_foreground = role(OnPrimary);
371    colors.secondary = role(Secondary);
372    colors.secondary_foreground = role(OnSecondary);
373    colors.muted = role(SurfaceContainerHighest);
374    colors.muted_foreground = role(OnSurfaceVariant);
375    colors.accent = role(SecondaryContainer);
376    colors.accent_foreground = role(OnSecondaryContainer);
377    colors.destructive = role(Error);
378    colors.destructive_foreground = role(OnError);
379    colors.border = role(OutlineVariant);
380    colors.input = role(Outline);
381    colors.ring = role(Secondary);
382    colors.selection = role(Primary).opacity(0.3);
383    projected.tokens.shadow = gpui_base::ShadowTokens::elevations(role(Shadow).opacity(0.22));
384    let thumb = role(OnSurfaceVariant);
385    let styles = ScrollbarStyles::default()
386        .track(|track| track.bg(gpui::transparent_black()).width(px(8.)))
387        .thumb(|t| {
388            t.bg(thumb.opacity(0.38))
389                .width(px(4.))
390                .radius(px(2.))
391                .min_length(px(24.))
392        })
393        .thumb_hover(|t| t.bg(thumb.opacity(0.56)))
394        .thumb_active(|t| t.bg(thumb.opacity(0.72)));
395    projected.scrollbar = ScrollbarTheme::new()
396        .with_mode(projected.scrollbar.mode())
397        .with_motion(projected.scrollbar.motion())
398        .with_styles(styles);
399    let mut resizable = ResizableTheme::default();
400    resizable.handle = Some(role(OutlineVariant));
401    resizable.active_handle = Some(role(Primary));
402    projected.resizable = resizable;
403}
404
405fn project_base_metrics(projected: &mut Theme, theme: &MaterialTheme, cx: &App) {
406    let typography = &theme.typography;
407    let radii = &mut projected.tokens.radius;
408    let radius = |role: CornerRole| px(role.shape().radii(100., 100., Default::default())[0]);
409    radii.sm = radius(CornerRole::ExtraSmall);
410    radii.md = radius(CornerRole::Small);
411    radii.lg = radius(CornerRole::Medium);
412    radii.xl = radius(CornerRole::Large);
413    let text = &mut projected.tokens.typography;
414    text.sans = font_for_style(
415        typography,
416        TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
417        cx,
418    )
419    .family;
420    for (slot, role) in [
421        (&mut text.xs, TypeRole::BodySmall),
422        (&mut text.sm, TypeRole::BodyMedium),
423        (&mut text.md, TypeRole::BodyLarge),
424        (&mut text.lg, TypeRole::TitleMedium),
425        (&mut text.xl, TypeRole::TitleLarge),
426    ] {
427        let style = typography.style(role, TypographyEmphasis::Baseline);
428        slot.size = px(style.size);
429        slot.line_height = px(style.line_height);
430        slot.weight = gpui::FontWeight(f32::from(style.weight));
431    }
432}