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