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::root::{project_base_theme, window_override_handle, window_theme_handle};
11
12type ScopeKey = (*const App, WindowId);
13
14thread_local! {
15    static SCOPES: RefCell<Vec<(ScopeKey, Rc<MaterialTheme>)>> = const { RefCell::new(Vec::new()) };
16}
17
18fn scope_key(window: &Window, cx: &App) -> ScopeKey {
19    (cx, window.window_handle().window_id())
20}
21
22fn scoped_theme(window: &Window, cx: &App) -> Option<Rc<MaterialTheme>> {
23    let key = scope_key(window, cx);
24    SCOPES.with_borrow(|scopes| {
25        scopes
26            .iter()
27            .rev()
28            .find(|(id, _)| *id == key)
29            .map(|(_, theme)| theme.clone())
30    })
31}
32
33/// Resolves the closest Material scope, then the window and application defaults.
34pub fn current_material_theme(
35    window: &Window,
36    cx: &App,
37) -> impl Deref<Target = MaterialTheme> + use<> {
38    scoped_theme(window, cx).unwrap_or_else(|| window_theme_handle(window, cx).clone())
39}
40
41/// Projects the active local Material scope (or window/application theme) into
42/// a `gpui_base::Theme` without mutating `gpui_base::Theme::global`.
43pub fn current_base_theme(window: &Window, cx: &App) -> Theme {
44    project_base_theme(&current_material_theme(window, cx), cx)
45}
46
47fn with_scope<R>(
48    theme: Option<&Rc<MaterialTheme>>,
49    window: &mut Window,
50    cx: &mut App,
51    draw: impl FnOnce(&mut Window, &mut App) -> R,
52) -> R {
53    let Some(theme) = theme else {
54        return draw(window, cx);
55    };
56    struct ScopeGuard;
57    impl Drop for ScopeGuard {
58        fn drop(&mut self) {
59            SCOPES.with_borrow_mut(|scopes| scopes.pop());
60        }
61    }
62    SCOPES.with_borrow_mut(|scopes| scopes.push((scope_key(window, cx), theme.clone())));
63    let _guard = ScopeGuard;
64    draw(window, cx)
65}
66
67/// Applies a Material theme, direction, or density to a child and its Material overlays.
68/// The element participates in layout using its child's layout directly.
69pub struct ThemeScope {
70    child: AnyElement,
71    theme: Option<Rc<MaterialTheme>>,
72    direction: Option<Direction>,
73    density: Option<Density>,
74}
75
76impl ThemeScope {
77    /// Wraps `child` in a theme scope that inherits the surrounding theme until overridden.
78    pub fn new(child: impl IntoElement) -> Self {
79        Self {
80            child: child.into_any_element(),
81            theme: None,
82            direction: None,
83            density: None,
84        }
85    }
86
87    /// Replaces the entire [`MaterialTheme`] for this subtree.
88    pub fn theme(mut self, theme: MaterialTheme) -> Self {
89        self.theme = Some(Rc::new(theme));
90        self
91    }
92
93    /// Overrides the layout [`Direction`] for this subtree.
94    pub fn direction(mut self, direction: Direction) -> Self {
95        self.direction = Some(direction);
96        self
97    }
98
99    /// Overrides the visual [`Density`] for this subtree.
100    pub fn density(mut self, density: Density) -> Self {
101        self.density = Some(density);
102        self
103    }
104
105    /// Carries the current subtree scope across a deferred draw. Wrap the
106    /// content passed to the positioning or overlay host.
107    pub fn inherit(child: impl IntoElement, window: &Window, cx: &App) -> AnyElement {
108        match scoped_theme(window, cx) {
109            Some(theme) => Self {
110                child: child.into_any_element(),
111                theme: Some(theme),
112                direction: None,
113                density: None,
114            }
115            .into_any_element(),
116            None => child.into_any_element(),
117        }
118    }
119
120    /// Runs an action in its originating Material scope (subtree or window
121    /// override). Use this when an action creates a separate native window from
122    /// a scoped trigger.
123    pub fn bind_action<F: Fn(&mut Window, &mut App) + 'static>(
124        action: F,
125        window: &Window,
126        cx: &App,
127    ) -> impl Fn(&mut Window, &mut App) + use<F> {
128        let theme =
129            scoped_theme(window, cx).or_else(|| window_override_handle(window, cx).cloned());
130        move |window, cx| with_scope(theme.as_ref(), window, cx, &action)
131    }
132}
133
134impl IntoElement for ThemeScope {
135    type Element = Self;
136
137    fn into_element(self) -> Self {
138        self
139    }
140}
141
142impl Element for ThemeScope {
143    type RequestLayoutState = ();
144    type PrepaintState = ();
145
146    fn id(&self) -> Option<ElementId> {
147        None
148    }
149
150    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
151        None
152    }
153
154    fn request_layout(
155        &mut self,
156        _: Option<&GlobalElementId>,
157        _: Option<&InspectorElementId>,
158        window: &mut Window,
159        cx: &mut App,
160    ) -> (LayoutId, ()) {
161        if self.direction.is_some() || self.density.is_some() {
162            let mut theme = self.theme.take().unwrap_or_else(|| {
163                scoped_theme(window, cx).unwrap_or_else(|| window_theme_handle(window, cx).clone())
164            });
165            if let Some(direction) = self.direction
166                && theme.layout.direction != direction
167            {
168                Rc::make_mut(&mut theme).layout.direction = direction;
169            }
170            if let Some(density) = self.density
171                && theme.layout.density != density
172            {
173                Rc::make_mut(&mut theme).layout.density = density;
174            }
175            self.theme = Some(theme);
176        }
177        let layout = with_scope(self.theme.as_ref(), window, cx, |window, cx| {
178            self.child.request_layout(window, cx)
179        });
180        (layout, ())
181    }
182
183    fn prepaint(
184        &mut self,
185        _: Option<&GlobalElementId>,
186        _: Option<&InspectorElementId>,
187        _: Bounds<Pixels>,
188        _: &mut (),
189        window: &mut Window,
190        cx: &mut App,
191    ) {
192        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
193            self.child.prepaint(window, cx);
194        });
195    }
196
197    fn paint(
198        &mut self,
199        _: Option<&GlobalElementId>,
200        _: Option<&InspectorElementId>,
201        _: Bounds<Pixels>,
202        _: &mut (),
203        _: &mut (),
204        window: &mut Window,
205        cx: &mut App,
206    ) {
207        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
208            self.child.paint(window, cx);
209        });
210    }
211}