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    pub fn new(child: impl IntoElement) -> Self {
78        Self {
79            child: child.into_any_element(),
80            theme: None,
81            direction: None,
82            density: None,
83        }
84    }
85
86    pub fn theme(mut self, theme: MaterialTheme) -> Self {
87        self.theme = Some(Rc::new(theme));
88        self
89    }
90
91    pub fn direction(mut self, direction: Direction) -> Self {
92        self.direction = Some(direction);
93        self
94    }
95
96    pub fn density(mut self, density: Density) -> Self {
97        self.density = Some(density);
98        self
99    }
100
101    /// Carries the current subtree scope across a deferred draw. Wrap the
102    /// content passed to the positioning or overlay host.
103    pub fn inherit(child: impl IntoElement, window: &Window, cx: &App) -> AnyElement {
104        match scoped_theme(window, cx) {
105            Some(theme) => Self {
106                child: child.into_any_element(),
107                theme: Some(theme),
108                direction: None,
109                density: None,
110            }
111            .into_any_element(),
112            None => child.into_any_element(),
113        }
114    }
115
116    /// Runs an action in its originating Material scope (subtree or window
117    /// override). Use this when an action creates a separate native window from
118    /// a scoped trigger.
119    pub fn bind_action<F: Fn(&mut Window, &mut App) + 'static>(
120        action: F,
121        window: &Window,
122        cx: &App,
123    ) -> impl Fn(&mut Window, &mut App) + use<F> {
124        let theme =
125            scoped_theme(window, cx).or_else(|| window_override_handle(window, cx).cloned());
126        move |window, cx| with_scope(theme.as_ref(), window, cx, &action)
127    }
128}
129
130impl IntoElement for ThemeScope {
131    type Element = Self;
132
133    fn into_element(self) -> Self {
134        self
135    }
136}
137
138impl Element for ThemeScope {
139    type RequestLayoutState = ();
140    type PrepaintState = ();
141
142    fn id(&self) -> Option<ElementId> {
143        None
144    }
145
146    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
147        None
148    }
149
150    fn request_layout(
151        &mut self,
152        _: Option<&GlobalElementId>,
153        _: Option<&InspectorElementId>,
154        window: &mut Window,
155        cx: &mut App,
156    ) -> (LayoutId, ()) {
157        if self.direction.is_some() || self.density.is_some() {
158            let mut theme = self.theme.take().unwrap_or_else(|| {
159                scoped_theme(window, cx).unwrap_or_else(|| window_theme_handle(window, cx).clone())
160            });
161            if let Some(direction) = self.direction
162                && theme.layout.direction != direction
163            {
164                Rc::make_mut(&mut theme).layout.direction = direction;
165            }
166            if let Some(density) = self.density
167                && theme.layout.density != density
168            {
169                Rc::make_mut(&mut theme).layout.density = density;
170            }
171            self.theme = Some(theme);
172        }
173        let layout = with_scope(self.theme.as_ref(), window, cx, |window, cx| {
174            self.child.request_layout(window, cx)
175        });
176        (layout, ())
177    }
178
179    fn prepaint(
180        &mut self,
181        _: Option<&GlobalElementId>,
182        _: Option<&InspectorElementId>,
183        _: Bounds<Pixels>,
184        _: &mut (),
185        window: &mut Window,
186        cx: &mut App,
187    ) {
188        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
189            self.child.prepaint(window, cx);
190        });
191    }
192
193    fn paint(
194        &mut self,
195        _: Option<&GlobalElementId>,
196        _: Option<&InspectorElementId>,
197        _: Bounds<Pixels>,
198        _: &mut (),
199        _: &mut (),
200        window: &mut Window,
201        cx: &mut App,
202    ) {
203        with_scope(self.theme.as_ref(), window, cx, |window, cx| {
204            self.child.paint(window, cx);
205        });
206    }
207}