Skip to main content

gpui_material_foundation/
root.rs

1use std::collections::HashMap;
2
3use gpui::{AnyView, App, AppContext, Global, Render, Window, WindowHandle, WindowId, px};
4use gpui_base::{Root, Theme, ThemeAppearance};
5use gpui_material_theme::{
6    Appearance, ColorRole, CornerRole, MaterialTheme, TypeRole, TypographyEmphasis,
7};
8
9use crate::{color, font_for_style, typography::refresh_installed_fonts};
10
11struct ActiveMaterialTheme(MaterialTheme);
12
13impl Global for ActiveMaterialTheme {}
14
15#[derive(Default)]
16struct WindowMaterialThemes(HashMap<WindowId, MaterialTheme>);
17
18impl Global for WindowMaterialThemes {}
19
20/// Initializes Material and Base before the application opens its first window.
21pub struct MaterialRoot;
22
23impl MaterialRoot {
24    pub fn init(theme: MaterialTheme, cx: &mut App) {
25        gpui_base::init(cx);
26        set_material_theme(theme, cx);
27    }
28
29    /// Opens a window whose Base root owns overlays and keyboard traversal.
30    pub fn open_window<V: Render>(
31        options: gpui::WindowOptions,
32        cx: &mut App,
33        build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
34    ) -> gpui::Result<WindowHandle<Root>> {
35        cx.open_window(options, |window, cx| {
36            let view = AnyView::from(build(window, cx));
37            cx.new(|cx| Root::new(view, window, cx))
38        })
39    }
40}
41
42/// Returns the shared Material theme installed by [`MaterialRoot::init`].
43pub fn material_theme(cx: &App) -> &MaterialTheme {
44    &cx.global::<ActiveMaterialTheme>().0
45}
46
47/// Resolves a window's override or falls back to the current application theme.
48pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
49    cx.try_global::<WindowMaterialThemes>()
50        .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
51        .unwrap_or_else(|| material_theme(cx))
52}
53
54/// Sets or clears the override for Material elements in this window.
55///
56/// Material controls pass local presentation to their Base-backed parts. This
57/// does not replace Base's application-global theme: standalone Base controls,
58/// scrollbars, resize handles, and caret-blink policy retain application defaults.
59/// Use their explicit styling APIs for local presentation instead of swapping
60/// the Base global while rendering a window.
61pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
62    refresh_installed_fonts(cx);
63    if !cx.has_global::<WindowMaterialThemes>() {
64        cx.set_global(WindowMaterialThemes::default());
65        cx.on_window_closed(|cx, id| {
66            cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
67        })
68        .detach();
69    }
70    let id = window.window_handle().window_id();
71    let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
72    if let Some(theme) = theme {
73        themes.insert(id, theme);
74    } else {
75        themes.remove(&id);
76    }
77    window.refresh();
78}
79
80/// Commits the application theme and projects semantic defaults into Base before
81/// refreshing windows. A window or subtree can pass an explicit theme to its elements.
82pub fn set_material_theme(theme: MaterialTheme, cx: &mut App) {
83    use ColorRole::*;
84
85    refresh_installed_fonts(cx);
86    let typography = &theme.typography;
87    let sans = font_for_style(
88        typography,
89        TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
90        cx,
91    )
92    .family;
93    let mut projected = Theme::global(cx);
94    projected.appearance = match theme.colors.appearance() {
95        Appearance::Light => ThemeAppearance::Light,
96        Appearance::Dark => ThemeAppearance::Dark,
97    };
98    let role = |role| color(theme.colors.color(role));
99    let colors = &mut projected.tokens.colors;
100    colors.background = role(Surface);
101    colors.foreground = role(OnSurface);
102    colors.surface = role(SurfaceContainer);
103    colors.surface_foreground = role(OnSurface);
104    colors.primary = role(Primary);
105    colors.primary_foreground = role(OnPrimary);
106    colors.secondary = role(Secondary);
107    colors.secondary_foreground = role(OnSecondary);
108    colors.muted = role(SurfaceContainerHighest);
109    colors.muted_foreground = role(OnSurfaceVariant);
110    colors.accent = role(SecondaryContainer);
111    colors.accent_foreground = role(OnSecondaryContainer);
112    colors.destructive = role(Error);
113    colors.destructive_foreground = role(OnError);
114    colors.border = role(OutlineVariant);
115    colors.input = role(Outline);
116    colors.ring = role(Secondary);
117    colors.selection = role(Primary).opacity(0.3);
118    let radii = &mut projected.tokens.radius;
119    let radius = |role: CornerRole| px(role.shape().radii(100., 100., Default::default())[0]);
120    radii.sm = radius(CornerRole::ExtraSmall);
121    radii.md = radius(CornerRole::Small);
122    radii.lg = radius(CornerRole::Medium);
123    radii.xl = radius(CornerRole::Large);
124    let text = &mut projected.tokens.typography;
125    text.sans = sans;
126    for (slot, role) in [
127        (&mut text.xs, TypeRole::BodySmall),
128        (&mut text.sm, TypeRole::BodyMedium),
129        (&mut text.md, TypeRole::BodyLarge),
130        (&mut text.lg, TypeRole::TitleMedium),
131        (&mut text.xl, TypeRole::TitleLarge),
132    ] {
133        let style = role.style(TypographyEmphasis::Baseline);
134        slot.size = px(style.size);
135        slot.line_height = px(style.line_height);
136        slot.weight = gpui::FontWeight(f32::from(style.weight));
137    }
138    projected.tokens.shadow = gpui_base::ShadowTokens::elevations(role(Shadow).opacity(0.22));
139
140    cx.set_global(ActiveMaterialTheme(theme));
141    cx.set_global(projected);
142    cx.refresh_windows();
143}