Skip to main content

gpui_material_foundation/
theme_scope.rs

1use std::{cell::RefCell, ops::Deref, rc::Rc};
2
3use gpui::{
4    AnyElement, App, Bounds, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
5    LayoutId, Pixels, Window, WindowId,
6};
7use gpui_base::Theme;
8use gpui_material_theme::{Density, Direction, MaterialTheme};
9
10use crate::{
11    root::{
12        cached_window_base_theme, project_base_theme, window_override_handle, window_theme_handle,
13    },
14    typography::font_cache_revision,
15};
16
17type ScopeKey = (*const App, WindowId);
18
19struct ScopeEntry {
20    key: ScopeKey,
21    material: Rc<MaterialTheme>,
22    projected: RefCell<Option<(u64, Theme)>>,
23}
24
25struct DerivedThemeCacheEntry {
26    parent_ptr: *const MaterialTheme,
27    direction: Option<Direction>,
28    density: Option<Density>,
29    parent: Rc<MaterialTheme>,
30    derived: Rc<MaterialTheme>,
31}
32
33const MAX_DERIVED_CACHE_ENTRIES: usize = 16;
34
35thread_local! {
36    static SCOPES: RefCell<Vec<ScopeEntry>> = const { RefCell::new(Vec::new()) };
37    static DERIVED_THEMES: RefCell<Vec<DerivedThemeCacheEntry>> = const { RefCell::new(Vec::new()) };
38}
39
40fn scope_key(window: &Window, cx: &App) -> ScopeKey {
41    (cx, window.window_handle().window_id())
42}
43
44fn scoped_theme(window: &Window, cx: &App) -> Option<Rc<MaterialTheme>> {
45    let key = scope_key(window, cx);
46    SCOPES.with_borrow(|scopes| {
47        scopes
48            .iter()
49            .rev()
50            .find(|entry| entry.key == key)
51            .map(|entry| entry.material.clone())
52    })
53}
54
55fn derive_scoped_theme(
56    base: Rc<MaterialTheme>,
57    direction: Option<Direction>,
58    density: Option<Density>,
59) -> Rc<MaterialTheme> {
60    let needs_dir = direction.is_some_and(|dir| base.layout.direction != dir);
61    let needs_density = density.is_some_and(|d| base.layout.density != d);
62    if !needs_dir && !needs_density {
63        return base;
64    }
65    let parent_ptr = Rc::as_ptr(&base);
66    if let Some(cached) = DERIVED_THEMES.with_borrow(|cache| {
67        cache
68            .iter()
69            .find(|entry| {
70                entry.parent_ptr == parent_ptr
71                    && entry.direction == direction
72                    && entry.density == density
73                    && Rc::ptr_eq(&entry.parent, &base)
74            })
75            .map(|entry| entry.derived.clone())
76    }) {
77        return cached;
78    }
79    let mut derived = (*base).clone();
80    if let Some(direction) = direction {
81        derived.layout.direction = direction;
82    }
83    if let Some(density) = density {
84        derived.layout.density = density;
85    }
86    let derived = Rc::new(derived);
87    DERIVED_THEMES.with_borrow_mut(|cache| {
88        if cache.len() >= MAX_DERIVED_CACHE_ENTRIES {
89            cache.remove(0);
90        }
91        cache.push(DerivedThemeCacheEntry {
92            parent_ptr,
93            direction,
94            density,
95            parent: base,
96            derived: derived.clone(),
97        });
98    });
99    derived
100}
101
102/// Resolves the closest Material scope, then the window and application defaults.
103pub fn current_material_theme(
104    window: &Window,
105    cx: &App,
106) -> impl Deref<Target = MaterialTheme> + use<> {
107    scoped_theme(window, cx).unwrap_or_else(|| window_theme_handle(window, cx).clone())
108}
109
110/// Projects the active local Material scope (or window/application theme) into
111/// a `gpui_base::Theme` without mutating `gpui_base::Theme::global`.
112///
113/// Reuses cached projections for the application global, window overrides, and active
114/// [`ThemeScope`] entries so repeated lookups do not re-project on every frame.
115pub fn current_base_theme(window: &Window, cx: &App) -> Theme {
116    let key = scope_key(window, cx);
117    let revision = font_cache_revision(cx);
118    let scoped = SCOPES.with_borrow(|scopes| {
119        scopes
120            .iter()
121            .rev()
122            .find(|entry| entry.key == key)
123            .map(|entry| {
124                if let Some((cached_rev, cached_theme)) = entry.projected.borrow().as_ref()
125                    && *cached_rev == revision
126                {
127                    return cached_theme.clone();
128                }
129                let projected = project_base_theme(&entry.material, cx);
130                *entry.projected.borrow_mut() = Some((revision, projected.clone()));
131                projected
132            })
133    });
134    scoped.unwrap_or_else(|| cached_window_base_theme(window, cx))
135}
136
137fn with_scope<R>(
138    theme: Option<&Rc<MaterialTheme>>,
139    window: &mut Window,
140    cx: &mut App,
141    draw: impl FnOnce(&mut Window, &mut App) -> R,
142) -> R {
143    let Some(theme) = theme else {
144        return draw(window, cx);
145    };
146    struct ScopeGuard;
147    impl Drop for ScopeGuard {
148        fn drop(&mut self) {
149            SCOPES.with_borrow_mut(|scopes| scopes.pop());
150        }
151    }
152    SCOPES.with_borrow_mut(|scopes| {
153        scopes.push(ScopeEntry {
154            key: scope_key(window, cx),
155            material: theme.clone(),
156            projected: RefCell::new(None),
157        });
158    });
159    let _guard = ScopeGuard;
160    draw(window, cx)
161}
162
163/// Applies a Material theme, direction, or density to a child and its Material overlays.
164/// The element participates in layout using its child's layout directly.
165pub struct ThemeScope {
166    child: AnyElement,
167    theme: Option<Rc<MaterialTheme>>,
168    direction: Option<Direction>,
169    density: Option<Density>,
170}
171
172impl ThemeScope {
173    /// Wraps `child` in a theme scope that inherits the surrounding theme until overridden.
174    pub fn new(child: impl IntoElement) -> Self {
175        Self {
176            child: child.into_any_element(),
177            theme: None,
178            direction: None,
179            density: None,
180        }
181    }
182
183    /// Replaces the entire [`MaterialTheme`] for this subtree.
184    pub fn theme(mut self, mut theme: MaterialTheme) -> Self {
185        if let Some(direction) = self.direction {
186            theme.layout.direction = direction;
187        }
188        if let Some(density) = self.density {
189            theme.layout.density = density;
190        }
191        self.theme = Some(Rc::new(theme));
192        self
193    }
194
195    /// Overrides the layout [`Direction`] for this subtree.
196    pub fn direction(mut self, direction: Direction) -> Self {
197        self.direction = Some(direction);
198        if let Some(theme) = &mut self.theme
199            && theme.layout.direction != direction
200        {
201            Rc::make_mut(theme).layout.direction = direction;
202        }
203        self
204    }
205
206    /// Overrides the visual [`Density`] for this subtree.
207    pub fn density(mut self, density: Density) -> Self {
208        self.density = Some(density);
209        if let Some(theme) = &mut self.theme
210            && theme.layout.density != density
211        {
212            Rc::make_mut(theme).layout.density = density;
213        }
214        self
215    }
216
217    /// Carries the current subtree scope across a deferred draw. Wrap the
218    /// content passed to the positioning or overlay host.
219    pub fn inherit(child: impl IntoElement, window: &Window, cx: &App) -> AnyElement {
220        match scoped_theme(window, cx) {
221            Some(theme) => Self {
222                child: child.into_any_element(),
223                theme: Some(theme),
224                direction: None,
225                density: None,
226            }
227            .into_any_element(),
228            None => child.into_any_element(),
229        }
230    }
231
232    /// Runs an action in its originating Material scope (subtree or window
233    /// override). Use this when an action creates a separate native window from
234    /// a scoped trigger.
235    pub fn bind_action<F: Fn(&mut Window, &mut App) + 'static>(
236        action: F,
237        window: &Window,
238        cx: &App,
239    ) -> impl Fn(&mut Window, &mut App) + use<F> {
240        let theme =
241            scoped_theme(window, cx).or_else(|| window_override_handle(window, cx).cloned());
242        move |window, cx| with_scope(theme.as_ref(), window, cx, &action)
243    }
244}
245
246impl Element for ThemeScope {
247    type RequestLayoutState = ();
248    type PrepaintState = ();
249
250    fn id(&self) -> Option<ElementId> {
251        None
252    }
253
254    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
255        None
256    }
257
258    fn request_layout(
259        &mut self,
260        _: Option<&GlobalElementId>,
261        _: Option<&InspectorElementId>,
262        window: &mut Window,
263        cx: &mut App,
264    ) -> (LayoutId, ()) {
265        if self.theme.is_none() && (self.direction.is_some() || self.density.is_some()) {
266            let base =
267                scoped_theme(window, cx).unwrap_or_else(|| window_theme_handle(window, cx).clone());
268            self.theme = Some(derive_scoped_theme(base, self.direction, self.density));
269        }
270        let layout = with_scope(self.theme.as_ref(), window, cx, |window, cx| {
271            self.child.request_layout(window, cx)
272        });
273        (layout, ())
274    }
275
276    fn prepaint(
277        &mut self,
278        _: Option<&GlobalElementId>,
279        _: Option<&InspectorElementId>,
280        _: Bounds<Pixels>,
281        _: &mut (),
282        window: &mut Window,
283        cx: &mut App,
284    ) {
285        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
286            self.child.prepaint(window, cx);
287        });
288    }
289
290    fn paint(
291        &mut self,
292        _: Option<&GlobalElementId>,
293        _: Option<&InspectorElementId>,
294        _: Bounds<Pixels>,
295        _: &mut (),
296        _: &mut (),
297        window: &mut Window,
298        cx: &mut App,
299    ) {
300        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
301            self.child.paint(window, cx);
302        });
303    }
304}