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