gpui_material_foundation/
root.rs1mod base_projection;
2mod system_sync;
3mod transition;
4
5use std::{cell::RefCell, collections::HashMap, rc::Rc};
6
7use gpui::{
8 AnyView, App, AppContext, Global, Render, Subscription, Window, WindowHandle, WindowId,
9};
10use gpui_base::{Root, Theme};
11use gpui_material_theme::{
12 Appearance, AppearanceMode, ColorScheme, MaterialTheme, MotionKind, MotionSpec, MotionSpeed,
13};
14
15use crate::{
16 strings::init_default_strings,
17 typography::{font_cache_revision, refresh_installed_fonts},
18};
19
20pub use base_projection::project_base_theme;
21use base_projection::{project_base_colors, project_base_metrics};
22pub use system_sync::{
23 ReduceMotionPreference, appearance_from_window, observe_system_appearance,
24 observe_window_system_appearance, set_reduce_motion_preference, sync_system_reduce_motion,
25 system_appearance,
26};
27use transition::PaletteTransition;
28
29struct ActiveMaterialTheme(Rc<MaterialTheme>);
30
31impl Global for ActiveMaterialTheme {}
32
33struct WindowThemeEntry {
34 material: Rc<MaterialTheme>,
35 projected: RefCell<Option<(u64, Theme)>>,
36}
37
38#[derive(Default)]
39struct WindowMaterialThemes(HashMap<WindowId, WindowThemeEntry>);
40
41impl Global for WindowMaterialThemes {}
42
43#[derive(Default)]
44struct ThemeAnimator {
45 transition: Option<PaletteTransition>,
46 driver: Option<WindowId>,
47}
48
49impl Global for ThemeAnimator {}
50
51pub struct MaterialRoot;
53
54impl MaterialRoot {
55 pub fn init(theme: MaterialTheme, cx: &mut App) {
58 gpui_base::init(cx);
59 if cx.has_global::<ThemeAnimator>() {
60 let animator = cx.global_mut::<ThemeAnimator>();
61 animator.transition = None;
62 animator.driver = None;
63 }
64 refresh_installed_fonts(cx);
65 init_default_strings(cx);
66 apply_material_theme(theme, true, cx);
67 }
68
69 pub fn open_window<V: Render>(
71 options: gpui::WindowOptions,
72 cx: &mut App,
73 build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
74 ) -> gpui::Result<WindowHandle<Root>> {
75 cx.open_window(options, |window, cx| {
76 let view = AnyView::from(build(window, cx));
77 cx.new(|cx| Root::new(view, window, cx))
78 })
79 }
80
81 pub fn sync_system_appearance(
85 window: &mut Window,
86 cx: &mut App,
87 mode: AppearanceMode,
88 build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
89 ) -> Subscription {
90 observe_system_appearance(window, cx, mode, build_theme)
91 }
92
93 pub fn sync_window_system_appearance(
97 window: &mut Window,
98 cx: &mut App,
99 mode: AppearanceMode,
100 build_theme: impl FnMut(Appearance) -> MaterialTheme + 'static,
101 ) -> Subscription {
102 observe_window_system_appearance(window, cx, mode, build_theme)
103 }
104}
105
106pub fn material_theme(cx: &App) -> &MaterialTheme {
108 &cx.global::<ActiveMaterialTheme>().0
109}
110
111pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
113 window_theme_handle(window, cx)
114}
115
116pub(crate) fn window_override_handle<'a>(
117 window: &Window,
118 cx: &'a App,
119) -> Option<&'a Rc<MaterialTheme>> {
120 cx.try_global::<WindowMaterialThemes>()
121 .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
122 .map(|entry| &entry.material)
123}
124
125pub(crate) fn window_theme_handle<'a>(window: &Window, cx: &'a App) -> &'a Rc<MaterialTheme> {
126 window_override_handle(window, cx).unwrap_or_else(|| &cx.global::<ActiveMaterialTheme>().0)
127}
128
129pub(crate) fn cached_window_base_theme(window: &Window, cx: &App) -> Theme {
132 let Some(entry) = cx
133 .try_global::<WindowMaterialThemes>()
134 .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
135 else {
136 return Theme::global(cx);
137 };
138 let revision = font_cache_revision(cx);
139 if let Some((cached_rev, cached_theme)) = entry.projected.borrow().as_ref()
140 && *cached_rev == revision
141 {
142 return cached_theme.clone();
143 }
144 let projected = project_base_theme(&entry.material, cx);
145 *entry.projected.borrow_mut() = Some((revision, projected.clone()));
146 projected
147}
148
149pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
156 let fonts_changed = refresh_installed_fonts(cx);
157 if !fonts_changed && window_override_handle(window, cx).map(Rc::as_ref) == theme.as_ref() {
158 return;
159 }
160 if !cx.has_global::<WindowMaterialThemes>() {
161 cx.set_global(WindowMaterialThemes::default());
162 cx.on_window_closed(|cx, id| {
163 cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
164 })
165 .detach();
166 }
167 let id = window.window_handle().window_id();
168 let projected = theme
169 .as_ref()
170 .map(|t| (font_cache_revision(cx), project_base_theme(t, cx)));
171 let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
172 if let Some(theme) = theme {
173 themes.insert(
174 id,
175 WindowThemeEntry {
176 material: Rc::new(theme),
177 projected: RefCell::new(projected),
178 },
179 );
180 } else {
181 themes.remove(&id);
182 }
183 window.refresh();
184}
185
186pub fn set_material_theme(mut theme: MaterialTheme, cx: &mut App) {
190 let fonts_changed = refresh_installed_fonts(cx);
191 let has_transition = cx
192 .try_global::<ThemeAnimator>()
193 .is_some_and(|animator| animator.transition.is_some());
194 if !fonts_changed
195 && !has_transition
196 && cx
197 .try_global::<ActiveMaterialTheme>()
198 .is_some_and(|previous| *previous.0 == theme)
199 {
200 return;
201 }
202 let spec = theme
203 .motion
204 .spec(MotionKind::Effects, MotionSpeed::Slow, cx.reduce_motion());
205 let previous = cx.try_global::<ActiveMaterialTheme>();
206 if let Some(previous) = previous
207 && previous.0.colors != theme.colors
208 && !cx.windows().is_empty()
209 && !matches!(spec, MotionSpec::Instant)
210 {
211 let shown = previous.0.colors.clone();
212 let started = cx.background_executor().now();
213 if !cx.has_global::<ThemeAnimator>() {
214 cx.set_global(ThemeAnimator::default());
215 cx.on_window_closed(|cx, closed| {
216 let animator = cx.global_mut::<ThemeAnimator>();
217 if animator.driver == Some(closed) {
218 animator.driver = None;
219 schedule_theme_frame(cx);
220 }
221 })
222 .detach();
223 }
224 let animator = cx.global_mut::<ThemeAnimator>();
225 if !animator
226 .transition
227 .as_ref()
228 .is_some_and(|pending| pending.to == theme.colors && pending.spec == spec)
229 {
230 animator.transition =
231 PaletteTransition::new(shown.clone(), theme.colors.clone(), spec, started);
232 }
233 if animator.transition.is_some() {
234 theme.colors = shown;
235 if animator.driver.is_none() {
236 cx.defer(schedule_theme_frame);
239 }
240 }
241 } else if cx.has_global::<ThemeAnimator>() {
242 let animator = cx.global_mut::<ThemeAnimator>();
243 animator.transition = None;
244 animator.driver = None;
245 }
246 apply_material_theme(theme, true, cx);
247}
248
249fn schedule_theme_frame(cx: &mut App) {
250 let animator = cx.global::<ThemeAnimator>();
251 if animator.transition.is_none() || animator.driver.is_some() {
252 return;
253 }
254 let active = cx.active_window();
255 let windows = cx.windows();
256 let driver = active
257 .into_iter()
258 .chain(
259 windows
260 .iter()
261 .copied()
262 .filter(|handle| Some(*handle) != active),
263 )
264 .find(|handle| {
265 handle
266 .update(cx, |_, window, _| {
267 if window.is_visible() {
268 window.on_next_frame(advance_theme_frame);
269 true
270 } else {
271 false
272 }
273 })
274 .unwrap_or(false)
275 });
276 if let Some(driver) = driver {
277 cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
278 } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
279 apply_palette(transition.to, cx);
280 }
281}
282
283fn advance_theme_frame(window: &mut Window, cx: &mut App) {
284 let id = window.window_handle().window_id();
285 let now = cx.background_executor().now();
286 let reduce_motion = cx.reduce_motion();
287 let animator = cx.global_mut::<ThemeAnimator>();
288 if animator.driver != Some(id) {
289 return;
290 }
291 if reduce_motion {
292 animator.driver = None;
293 if let Some(transition) = animator.transition.take() {
294 apply_palette(transition.to, cx);
295 }
296 return;
297 }
298 let Some(transition) = animator.transition.as_mut() else {
299 animator.driver = None;
300 return;
301 };
302 let (progress, running) = transition.advance(now);
303 if !running || progress >= 0.999 {
304 animator.driver = None;
305 if let Some(transition) = animator.transition.take() {
306 apply_palette(transition.to, cx);
307 }
308 } else {
309 let colors = transition.from.blend(&transition.to, progress);
310 apply_palette(colors, cx);
311 if window.is_visible() {
312 window.on_next_frame(advance_theme_frame);
313 } else {
314 cx.global_mut::<ThemeAnimator>().driver = None;
315 cx.defer(schedule_theme_frame);
316 }
317 }
318}
319
320fn apply_palette(colors: ColorScheme, cx: &mut App) {
321 let current = material_theme(cx);
322 if current.colors != colors {
323 let theme = MaterialTheme {
324 colors,
325 typography: current.typography.clone(),
326 motion: current.motion,
327 layout: current.layout,
328 };
329 apply_material_theme(theme, false, cx);
330 }
331}
332
333fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
334 let mut projected = Theme::global(cx);
335 project_base_colors(&mut projected, &theme);
336 if project_typography {
337 project_base_metrics(&mut projected, &theme, cx);
338 }
339 cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
340 cx.set_global(projected);
341 refresh_inherited_windows(cx);
342}
343
344fn refresh_inherited_windows(cx: &mut App) {
345 let overridden: Vec<WindowId> = cx
346 .try_global::<WindowMaterialThemes>()
347 .map(|themes| themes.0.keys().copied().collect())
348 .unwrap_or_default();
349 if overridden.is_empty() {
350 cx.refresh_windows();
351 return;
352 }
353 for handle in cx.windows() {
354 if !overridden.contains(&handle.window_id()) {
355 let _ = handle.update(cx, |_, window, _| window.refresh());
356 }
357 }
358}