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 cx.has_global::<ThemeAnimator>() {
122            let animator = cx.global_mut::<ThemeAnimator>();
123            animator.transition = None;
124            animator.driver = 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        let animator = cx.global_mut::<ThemeAnimator>();
248        animator.transition = None;
249        animator.driver = None;
250    }
251    apply_material_theme(theme, true, cx);
252}
253
254fn schedule_theme_frame(cx: &mut App) {
255    let animator = cx.global::<ThemeAnimator>();
256    if animator.transition.is_none() || animator.driver.is_some() {
257        return;
258    }
259    let active = cx.active_window();
260    let windows = cx.windows();
261    let driver = active
262        .into_iter()
263        .chain(
264            windows
265                .iter()
266                .copied()
267                .filter(|handle| Some(*handle) != active),
268        )
269        .find(|handle| {
270            handle
271                .update(cx, |_, window, _| {
272                    if window.is_visible() {
273                        window.on_next_frame(advance_theme_frame);
274                        true
275                    } else {
276                        false
277                    }
278                })
279                .unwrap_or(false)
280        });
281    if let Some(driver) = driver {
282        cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
283    } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
284        apply_palette(transition.to, cx);
285    }
286}
287
288fn advance_theme_frame(window: &mut Window, cx: &mut App) {
289    let id = window.window_handle().window_id();
290    let now = cx.background_executor().now();
291    let reduce_motion = cx.reduce_motion();
292    let animator = cx.global_mut::<ThemeAnimator>();
293    if animator.driver != Some(id) {
294        return;
295    }
296    let Some(transition) = animator.transition.as_mut() else {
297        animator.driver = None;
298        return;
299    };
300    if reduce_motion {
301        let target = animator.transition.take().unwrap().to;
302        animator.driver = None;
303        apply_palette(target, cx);
304        return;
305    }
306    let (progress, running) = transition.advance(now);
307    if !running || progress >= 0.999 {
308        let target = animator.transition.take().unwrap().to;
309        animator.driver = None;
310        apply_palette(target, cx);
311    } else {
312        let colors = transition.from.blend(&transition.to, progress);
313        apply_palette(colors, cx);
314        if window.is_visible() {
315            window.on_next_frame(advance_theme_frame);
316        } else {
317            cx.global_mut::<ThemeAnimator>().driver = None;
318            cx.defer(schedule_theme_frame);
319        }
320    }
321}
322
323fn apply_palette(colors: ColorScheme, cx: &mut App) {
324    let current = material_theme(cx);
325    if current.colors != colors {
326        let theme = MaterialTheme {
327            colors,
328            typography: current.typography.clone(),
329            motion: current.motion,
330            layout: current.layout,
331        };
332        apply_material_theme(theme, false, cx);
333    }
334}
335
336fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
337    let mut projected = Theme::global(cx);
338    project_base_colors(&mut projected, &theme);
339    if project_typography {
340        project_base_metrics(&mut projected, &theme, cx);
341    }
342    cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
343    cx.set_global(projected);
344    refresh_inherited_windows(cx);
345}
346
347fn refresh_inherited_windows(cx: &mut App) {
348    let overridden: Vec<WindowId> = cx
349        .try_global::<WindowMaterialThemes>()
350        .map(|themes| themes.0.keys().copied().collect())
351        .unwrap_or_default();
352    if overridden.is_empty() {
353        cx.refresh_windows();
354        return;
355    }
356    for handle in cx.windows() {
357        if !overridden.contains(&handle.window_id()) {
358            let _ = handle.update(cx, |_, window, _| window.refresh());
359        }
360    }
361}
362
363fn project_base_colors(projected: &mut Theme, theme: &MaterialTheme) {
364    use ColorRole::*;
365
366    projected.appearance = match theme.colors.appearance() {
367        Appearance::Light => ThemeAppearance::Light,
368        Appearance::Dark => ThemeAppearance::Dark,
369    };
370    let role = |role| color(theme.colors.color(role));
371    let colors = &mut projected.tokens.colors;
372    colors.background = role(Surface);
373    colors.foreground = role(OnSurface);
374    colors.surface = role(SurfaceContainer);
375    colors.surface_foreground = role(OnSurface);
376    colors.primary = role(Primary);
377    colors.primary_foreground = role(OnPrimary);
378    colors.secondary = role(Secondary);
379    colors.secondary_foreground = role(OnSecondary);
380    colors.muted = role(SurfaceContainerHighest);
381    colors.muted_foreground = role(OnSurfaceVariant);
382    colors.accent = role(SecondaryContainer);
383    colors.accent_foreground = role(OnSecondaryContainer);
384    colors.destructive = role(Error);
385    colors.destructive_foreground = role(OnError);
386    colors.border = role(OutlineVariant);
387    colors.input = role(Outline);
388    colors.ring = role(Secondary);
389    colors.selection = role(Primary).opacity(0.3);
390    projected.tokens.shadow = gpui_base::ShadowTokens::elevations(role(Shadow).opacity(0.22));
391    let thumb = role(OnSurfaceVariant);
392    let styles = ScrollbarStyles::default()
393        .track(|track| track.bg(gpui::transparent_black()).width(px(8.)))
394        .thumb(|t| {
395            t.bg(thumb.opacity(0.38))
396                .width(px(4.))
397                .radius(px(2.))
398                .min_length(px(24.))
399        })
400        .thumb_hover(|t| t.bg(thumb.opacity(0.56)))
401        .thumb_active(|t| t.bg(thumb.opacity(0.72)));
402    projected.scrollbar = ScrollbarTheme::new()
403        .with_mode(projected.scrollbar.mode())
404        .with_motion(projected.scrollbar.motion())
405        .with_styles(styles);
406    let mut resizable = ResizableTheme::default();
407    resizable.handle = Some(role(OutlineVariant));
408    resizable.active_handle = Some(role(Primary));
409    projected.resizable = resizable;
410}
411
412fn project_base_metrics(projected: &mut Theme, theme: &MaterialTheme, cx: &App) {
413    let typography = &theme.typography;
414    let radii = &mut projected.tokens.radius;
415    let radius = |role: CornerRole| px(role.shape().radii(100., 100., Default::default())[0]);
416    radii.sm = radius(CornerRole::ExtraSmall);
417    radii.md = radius(CornerRole::Small);
418    radii.lg = radius(CornerRole::Medium);
419    radii.xl = radius(CornerRole::Large);
420    let text = &mut projected.tokens.typography;
421    text.sans = font_for_style(
422        typography,
423        TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
424        cx,
425    )
426    .family;
427    for (slot, role) in [
428        (&mut text.xs, TypeRole::BodySmall),
429        (&mut text.sm, TypeRole::BodyMedium),
430        (&mut text.md, TypeRole::BodyLarge),
431        (&mut text.lg, TypeRole::TitleMedium),
432        (&mut text.xl, TypeRole::TitleLarge),
433    ] {
434        let style = typography.style(role, TypographyEmphasis::Baseline);
435        slot.size = px(style.size);
436        slot.line_height = px(style.line_height);
437        slot.weight = gpui::FontWeight(f32::from(style.weight));
438    }
439}