1use std::{collections::HashMap, rc::Rc, time::Duration};
2
3use gpui::{
4 AnyView, App, AppContext, Global, Render, SpringConfig, SpringState, Window, WindowHandle,
5 WindowId, px,
6};
7use gpui_base::{
8 ResizableTheme, Root, ScrollbarStyles, ScrollbarTheme, Theme, ThemeAppearance, motion::Easing,
9};
10use gpui_material_theme::{
11 Appearance, ColorRole, ColorScheme, CornerRole, MaterialTheme, MotionKind, MotionSpec,
12 MotionSpeed, TypeRole, TypographyEmphasis,
13};
14use web_time::Instant;
15
16use crate::{
17 color, font_for_style,
18 motion::{RetargetTransition, spring_config},
19 typography::refresh_installed_fonts,
20};
21
22struct ActiveMaterialTheme(Rc<MaterialTheme>);
23
24impl Global for ActiveMaterialTheme {}
25
26#[derive(Default)]
27struct WindowMaterialThemes(HashMap<WindowId, Rc<MaterialTheme>>);
28
29impl Global for WindowMaterialThemes {}
30
31enum PaletteCurve {
32 Spring {
33 config: SpringConfig,
34 state: SpringState,
35 updated_at: Instant,
36 },
37 Tween(RetargetTransition),
38}
39
40struct PaletteTransition {
41 from: ColorScheme,
42 to: ColorScheme,
43 curve: PaletteCurve,
44 spec: MotionSpec,
45}
46
47impl PaletteTransition {
48 fn new(from: ColorScheme, to: ColorScheme, spec: MotionSpec, now: Instant) -> Option<Self> {
49 let curve = match spec {
50 MotionSpec::Instant => return None,
51 MotionSpec::Spring(spring) => PaletteCurve::Spring {
52 config: spring_config(spring)?,
53 state: SpringState {
54 position: 0.0,
55 velocity: 0.0,
56 },
57 updated_at: now,
58 },
59 MotionSpec::Tween {
60 duration_ms,
61 easing,
62 } => {
63 let duration = Duration::from_millis(u64::from(duration_ms));
64 let curve =
65 Easing::cubic_bezier(easing.x1, easing.y1, easing.x2, easing.y2).ok()?;
66 if duration.is_zero() {
67 return None;
68 }
69 let mut transition = RetargetTransition::settled(0.0);
70 transition.animate_to(1.0, duration, curve, now, false);
71 PaletteCurve::Tween(transition)
72 }
73 };
74 Some(Self {
75 from,
76 to,
77 curve,
78 spec,
79 })
80 }
81
82 fn advance(&mut self, now: Instant) -> (f32, bool) {
83 match &mut self.curve {
84 PaletteCurve::Spring {
85 config,
86 state,
87 updated_at,
88 } => {
89 let elapsed = now.saturating_duration_since(*updated_at).as_secs_f32();
90 let stepped = config.step(*state, 1.0, elapsed);
91 *state = stepped;
92 *updated_at = now;
93 if config.is_settled(stepped, 1.0, 0.001) {
94 (1.0, false)
95 } else {
96 (stepped.position.clamp(0.0, 1.0), true)
97 }
98 }
99 PaletteCurve::Tween(transition) => {
100 let (value, running) = transition.sample(now, false);
101 (value.clamp(0.0, 1.0), running)
102 }
103 }
104 }
105}
106
107#[derive(Default)]
108struct ThemeAnimator {
109 transition: Option<PaletteTransition>,
110 driver: Option<WindowId>,
111}
112
113impl Global for ThemeAnimator {}
114
115pub struct MaterialRoot;
117
118impl MaterialRoot {
119 pub fn init(theme: MaterialTheme, cx: &mut App) {
120 gpui_base::init(cx);
121 if cx.has_global::<ThemeAnimator>() {
122 let animator = cx.global_mut::<ThemeAnimator>();
123 animator.transition = None;
124 animator.driver = None;
125 }
126 refresh_installed_fonts(cx);
127 apply_material_theme(theme, true, cx);
128 }
129
130 pub fn open_window<V: Render>(
132 options: gpui::WindowOptions,
133 cx: &mut App,
134 build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
135 ) -> gpui::Result<WindowHandle<Root>> {
136 cx.open_window(options, |window, cx| {
137 let view = AnyView::from(build(window, cx));
138 cx.new(|cx| Root::new(view, window, cx))
139 })
140 }
141}
142
143pub fn material_theme(cx: &App) -> &MaterialTheme {
145 &cx.global::<ActiveMaterialTheme>().0
146}
147
148pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
150 window_theme_handle(window, cx)
151}
152
153pub(crate) fn window_override_handle<'a>(
154 window: &Window,
155 cx: &'a App,
156) -> Option<&'a Rc<MaterialTheme>> {
157 cx.try_global::<WindowMaterialThemes>()
158 .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
159}
160
161pub(crate) fn window_theme_handle<'a>(window: &Window, cx: &'a App) -> &'a Rc<MaterialTheme> {
162 window_override_handle(window, cx).unwrap_or_else(|| &cx.global::<ActiveMaterialTheme>().0)
163}
164
165pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
172 if window_override_handle(window, cx).map(Rc::as_ref) == theme.as_ref() {
173 return;
174 }
175 refresh_installed_fonts(cx);
176 if !cx.has_global::<WindowMaterialThemes>() {
177 cx.set_global(WindowMaterialThemes::default());
178 cx.on_window_closed(|cx, id| {
179 cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
180 })
181 .detach();
182 }
183 let id = window.window_handle().window_id();
184 let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
185 if let Some(theme) = theme {
186 themes.insert(id, Rc::new(theme));
187 } else {
188 themes.remove(&id);
189 }
190 window.refresh();
191}
192
193pub fn project_base_theme(theme: &MaterialTheme, cx: &App) -> Theme {
199 let mut projected = Theme::global(cx);
200 project_base_colors(&mut projected, theme);
201 project_base_metrics(&mut projected, theme, cx);
202 projected
203}
204
205pub fn set_material_theme(mut theme: MaterialTheme, cx: &mut App) {
209 let has_transition = cx
210 .try_global::<ThemeAnimator>()
211 .is_some_and(|animator| animator.transition.is_some());
212 if !has_transition
213 && cx
214 .try_global::<ActiveMaterialTheme>()
215 .is_some_and(|previous| *previous.0 == theme)
216 {
217 return;
218 }
219 refresh_installed_fonts(cx);
220 let spec = theme
221 .motion
222 .spec(MotionKind::Effects, MotionSpeed::Slow, cx.reduce_motion());
223 let previous = cx.try_global::<ActiveMaterialTheme>();
224 if let Some(previous) = previous
225 && previous.0.colors != theme.colors
226 && !cx.windows().is_empty()
227 && !matches!(spec, MotionSpec::Instant)
228 {
229 let shown = previous.0.colors.clone();
230 let started = cx.background_executor().now();
231 if !cx.has_global::<ThemeAnimator>() {
232 cx.set_global(ThemeAnimator::default());
233 cx.on_window_closed(|cx, closed| {
234 let animator = cx.global_mut::<ThemeAnimator>();
235 if animator.driver == Some(closed) {
236 animator.driver = None;
237 schedule_theme_frame(cx);
238 }
239 })
240 .detach();
241 }
242 let animator = cx.global_mut::<ThemeAnimator>();
243 if !animator
244 .transition
245 .as_ref()
246 .is_some_and(|pending| pending.to == theme.colors && pending.spec == spec)
247 {
248 animator.transition =
249 PaletteTransition::new(shown.clone(), theme.colors.clone(), spec, started);
250 }
251 if animator.transition.is_some() {
252 theme.colors = shown;
253 if animator.driver.is_none() {
254 cx.defer(schedule_theme_frame);
257 }
258 }
259 } else if cx.has_global::<ThemeAnimator>() {
260 let animator = cx.global_mut::<ThemeAnimator>();
261 animator.transition = None;
262 animator.driver = None;
263 }
264 apply_material_theme(theme, true, cx);
265}
266
267fn schedule_theme_frame(cx: &mut App) {
268 let animator = cx.global::<ThemeAnimator>();
269 if animator.transition.is_none() || animator.driver.is_some() {
270 return;
271 }
272 let active = cx.active_window();
273 let windows = cx.windows();
274 let driver = active
275 .into_iter()
276 .chain(
277 windows
278 .iter()
279 .copied()
280 .filter(|handle| Some(*handle) != active),
281 )
282 .find(|handle| {
283 handle
284 .update(cx, |_, window, _| {
285 if window.is_visible() {
286 window.on_next_frame(advance_theme_frame);
287 true
288 } else {
289 false
290 }
291 })
292 .unwrap_or(false)
293 });
294 if let Some(driver) = driver {
295 cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
296 } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
297 apply_palette(transition.to, cx);
298 }
299}
300
301fn advance_theme_frame(window: &mut Window, cx: &mut App) {
302 let id = window.window_handle().window_id();
303 let now = cx.background_executor().now();
304 let reduce_motion = cx.reduce_motion();
305 let animator = cx.global_mut::<ThemeAnimator>();
306 if animator.driver != Some(id) {
307 return;
308 }
309 let Some(transition) = animator.transition.as_mut() else {
310 animator.driver = None;
311 return;
312 };
313 if reduce_motion {
314 let target = animator.transition.take().unwrap().to;
315 animator.driver = None;
316 apply_palette(target, cx);
317 return;
318 }
319 let (progress, running) = transition.advance(now);
320 if !running || progress >= 0.999 {
321 let target = animator.transition.take().unwrap().to;
322 animator.driver = None;
323 apply_palette(target, cx);
324 } else {
325 let colors = transition.from.blend(&transition.to, progress);
326 apply_palette(colors, cx);
327 if window.is_visible() {
328 window.on_next_frame(advance_theme_frame);
329 } else {
330 cx.global_mut::<ThemeAnimator>().driver = None;
331 cx.defer(schedule_theme_frame);
332 }
333 }
334}
335
336fn apply_palette(colors: ColorScheme, cx: &mut App) {
337 let current = material_theme(cx);
338 if current.colors != colors {
339 let theme = MaterialTheme {
340 colors,
341 typography: current.typography.clone(),
342 motion: current.motion,
343 layout: current.layout,
344 };
345 apply_material_theme(theme, false, cx);
346 }
347}
348
349fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
350 let mut projected = Theme::global(cx);
351 project_base_colors(&mut projected, &theme);
352 if project_typography {
353 project_base_metrics(&mut projected, &theme, cx);
354 }
355 cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
356 cx.set_global(projected);
357 refresh_inherited_windows(cx);
358}
359
360fn refresh_inherited_windows(cx: &mut App) {
361 let overridden: Vec<WindowId> = cx
362 .try_global::<WindowMaterialThemes>()
363 .map(|themes| themes.0.keys().copied().collect())
364 .unwrap_or_default();
365 if overridden.is_empty() {
366 cx.refresh_windows();
367 return;
368 }
369 for handle in cx.windows() {
370 if !overridden.contains(&handle.window_id()) {
371 let _ = handle.update(cx, |_, window, _| window.refresh());
372 }
373 }
374}
375
376fn project_base_colors(projected: &mut Theme, theme: &MaterialTheme) {
377 use ColorRole::*;
378
379 projected.appearance = match theme.colors.appearance() {
380 Appearance::Light => ThemeAppearance::Light,
381 Appearance::Dark => ThemeAppearance::Dark,
382 };
383 let role = |role| color(theme.colors.color(role));
384 let colors = &mut projected.tokens.colors;
385 colors.background = role(Surface);
386 colors.foreground = role(OnSurface);
387 colors.surface = role(SurfaceContainer);
388 colors.surface_foreground = role(OnSurface);
389 colors.primary = role(Primary);
390 colors.primary_foreground = role(OnPrimary);
391 colors.secondary = role(Secondary);
392 colors.secondary_foreground = role(OnSecondary);
393 colors.muted = role(SurfaceContainerHighest);
394 colors.muted_foreground = role(OnSurfaceVariant);
395 colors.accent = role(SecondaryContainer);
396 colors.accent_foreground = role(OnSecondaryContainer);
397 colors.destructive = role(Error);
398 colors.destructive_foreground = role(OnError);
399 colors.border = role(OutlineVariant);
400 colors.input = role(Outline);
401 colors.ring = role(Secondary);
402 colors.selection = role(Primary).opacity(0.3);
403 projected.tokens.shadow = gpui_base::ShadowTokens::elevations(role(Shadow).opacity(0.22));
404 let thumb = role(OnSurfaceVariant);
405 let styles = ScrollbarStyles::default()
406 .track(|track| track.bg(gpui::transparent_black()).width(px(8.)))
407 .thumb(|t| {
408 t.bg(thumb.opacity(0.38))
409 .width(px(4.))
410 .radius(px(2.))
411 .min_length(px(24.))
412 })
413 .thumb_hover(|t| t.bg(thumb.opacity(0.56)))
414 .thumb_active(|t| t.bg(thumb.opacity(0.72)));
415 projected.scrollbar = ScrollbarTheme::new()
416 .with_mode(projected.scrollbar.mode())
417 .with_motion(projected.scrollbar.motion())
418 .with_styles(styles);
419 let mut resizable = ResizableTheme::default();
420 resizable.handle = Some(role(OutlineVariant));
421 resizable.active_handle = Some(role(Primary));
422 projected.resizable = resizable;
423}
424
425fn project_base_metrics(projected: &mut Theme, theme: &MaterialTheme, cx: &App) {
426 let typography = &theme.typography;
427 let radii = &mut projected.tokens.radius;
428 let radius = |role: CornerRole| px(role.shape().radii(100., 100., Default::default())[0]);
429 radii.sm = radius(CornerRole::ExtraSmall);
430 radii.md = radius(CornerRole::Small);
431 radii.lg = radius(CornerRole::Medium);
432 radii.xl = radius(CornerRole::Large);
433 let text = &mut projected.tokens.typography;
434 text.sans = font_for_style(
435 typography,
436 TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
437 cx,
438 )
439 .family;
440 for (slot, role) in [
441 (&mut text.xs, TypeRole::BodySmall),
442 (&mut text.sm, TypeRole::BodyMedium),
443 (&mut text.md, TypeRole::BodyLarge),
444 (&mut text.lg, TypeRole::TitleMedium),
445 (&mut text.xl, TypeRole::TitleLarge),
446 ] {
447 let style = typography.style(role, TypographyEmphasis::Baseline);
448 slot.size = px(style.size);
449 slot.line_height = px(style.line_height);
450 slot.weight = gpui::FontWeight(f32::from(style.weight));
451 }
452}