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) {
122 gpui_base::init(cx);
123 if cx.has_global::<ThemeAnimator>() {
124 let animator = cx.global_mut::<ThemeAnimator>();
125 animator.transition = None;
126 animator.driver = None;
127 }
128 refresh_installed_fonts(cx);
129 apply_material_theme(theme, true, cx);
130 }
131
132 pub fn open_window<V: Render>(
134 options: gpui::WindowOptions,
135 cx: &mut App,
136 build: impl FnOnce(&mut Window, &mut App) -> gpui::Entity<V>,
137 ) -> gpui::Result<WindowHandle<Root>> {
138 cx.open_window(options, |window, cx| {
139 let view = AnyView::from(build(window, cx));
140 cx.new(|cx| Root::new(view, window, cx))
141 })
142 }
143}
144
145pub fn material_theme(cx: &App) -> &MaterialTheme {
147 &cx.global::<ActiveMaterialTheme>().0
148}
149
150pub fn window_material_theme<'a>(window: &Window, cx: &'a App) -> &'a MaterialTheme {
152 window_theme_handle(window, cx)
153}
154
155pub(crate) fn window_override_handle<'a>(
156 window: &Window,
157 cx: &'a App,
158) -> Option<&'a Rc<MaterialTheme>> {
159 cx.try_global::<WindowMaterialThemes>()
160 .and_then(|themes| themes.0.get(&window.window_handle().window_id()))
161}
162
163pub(crate) fn window_theme_handle<'a>(window: &Window, cx: &'a App) -> &'a Rc<MaterialTheme> {
164 window_override_handle(window, cx).unwrap_or_else(|| &cx.global::<ActiveMaterialTheme>().0)
165}
166
167pub fn set_window_material_theme(theme: Option<MaterialTheme>, window: &mut Window, cx: &mut App) {
174 if window_override_handle(window, cx).map(Rc::as_ref) == theme.as_ref() {
175 return;
176 }
177 refresh_installed_fonts(cx);
178 if !cx.has_global::<WindowMaterialThemes>() {
179 cx.set_global(WindowMaterialThemes::default());
180 cx.on_window_closed(|cx, id| {
181 cx.global_mut::<WindowMaterialThemes>().0.remove(&id);
182 })
183 .detach();
184 }
185 let id = window.window_handle().window_id();
186 let themes = &mut cx.global_mut::<WindowMaterialThemes>().0;
187 if let Some(theme) = theme {
188 themes.insert(id, Rc::new(theme));
189 } else {
190 themes.remove(&id);
191 }
192 window.refresh();
193}
194
195pub fn project_base_theme(theme: &MaterialTheme, cx: &App) -> Theme {
201 let mut projected = Theme::global(cx);
202 project_base_colors(&mut projected, theme);
203 project_base_metrics(&mut projected, theme, cx);
204 projected
205}
206
207pub fn set_material_theme(mut theme: MaterialTheme, cx: &mut App) {
211 let has_transition = cx
212 .try_global::<ThemeAnimator>()
213 .is_some_and(|animator| animator.transition.is_some());
214 if !has_transition
215 && cx
216 .try_global::<ActiveMaterialTheme>()
217 .is_some_and(|previous| *previous.0 == theme)
218 {
219 return;
220 }
221 refresh_installed_fonts(cx);
222 let spec = theme
223 .motion
224 .spec(MotionKind::Effects, MotionSpeed::Slow, cx.reduce_motion());
225 let previous = cx.try_global::<ActiveMaterialTheme>();
226 if let Some(previous) = previous
227 && previous.0.colors != theme.colors
228 && !cx.windows().is_empty()
229 && !matches!(spec, MotionSpec::Instant)
230 {
231 let shown = previous.0.colors.clone();
232 let started = cx.background_executor().now();
233 if !cx.has_global::<ThemeAnimator>() {
234 cx.set_global(ThemeAnimator::default());
235 cx.on_window_closed(|cx, closed| {
236 let animator = cx.global_mut::<ThemeAnimator>();
237 if animator.driver == Some(closed) {
238 animator.driver = None;
239 schedule_theme_frame(cx);
240 }
241 })
242 .detach();
243 }
244 let animator = cx.global_mut::<ThemeAnimator>();
245 if !animator
246 .transition
247 .as_ref()
248 .is_some_and(|pending| pending.to == theme.colors && pending.spec == spec)
249 {
250 animator.transition =
251 PaletteTransition::new(shown.clone(), theme.colors.clone(), spec, started);
252 }
253 if animator.transition.is_some() {
254 theme.colors = shown;
255 if animator.driver.is_none() {
256 cx.defer(schedule_theme_frame);
259 }
260 }
261 } else if cx.has_global::<ThemeAnimator>() {
262 let animator = cx.global_mut::<ThemeAnimator>();
263 animator.transition = None;
264 animator.driver = None;
265 }
266 apply_material_theme(theme, true, cx);
267}
268
269fn schedule_theme_frame(cx: &mut App) {
270 let animator = cx.global::<ThemeAnimator>();
271 if animator.transition.is_none() || animator.driver.is_some() {
272 return;
273 }
274 let active = cx.active_window();
275 let windows = cx.windows();
276 let driver = active
277 .into_iter()
278 .chain(
279 windows
280 .iter()
281 .copied()
282 .filter(|handle| Some(*handle) != active),
283 )
284 .find(|handle| {
285 handle
286 .update(cx, |_, window, _| {
287 if window.is_visible() {
288 window.on_next_frame(advance_theme_frame);
289 true
290 } else {
291 false
292 }
293 })
294 .unwrap_or(false)
295 });
296 if let Some(driver) = driver {
297 cx.global_mut::<ThemeAnimator>().driver = Some(driver.window_id());
298 } else if let Some(transition) = cx.global_mut::<ThemeAnimator>().transition.take() {
299 apply_palette(transition.to, cx);
300 }
301}
302
303fn advance_theme_frame(window: &mut Window, cx: &mut App) {
304 let id = window.window_handle().window_id();
305 let now = cx.background_executor().now();
306 let reduce_motion = cx.reduce_motion();
307 let animator = cx.global_mut::<ThemeAnimator>();
308 if animator.driver != Some(id) {
309 return;
310 }
311 let Some(transition) = animator.transition.as_mut() else {
312 animator.driver = None;
313 return;
314 };
315 if reduce_motion {
316 let target = animator.transition.take().unwrap().to;
317 animator.driver = None;
318 apply_palette(target, cx);
319 return;
320 }
321 let (progress, running) = transition.advance(now);
322 if !running || progress >= 0.999 {
323 let target = animator.transition.take().unwrap().to;
324 animator.driver = None;
325 apply_palette(target, cx);
326 } else {
327 let colors = transition.from.blend(&transition.to, progress);
328 apply_palette(colors, cx);
329 if window.is_visible() {
330 window.on_next_frame(advance_theme_frame);
331 } else {
332 cx.global_mut::<ThemeAnimator>().driver = None;
333 cx.defer(schedule_theme_frame);
334 }
335 }
336}
337
338fn apply_palette(colors: ColorScheme, cx: &mut App) {
339 let current = material_theme(cx);
340 if current.colors != colors {
341 let theme = MaterialTheme {
342 colors,
343 typography: current.typography.clone(),
344 motion: current.motion,
345 layout: current.layout,
346 };
347 apply_material_theme(theme, false, cx);
348 }
349}
350
351fn apply_material_theme(theme: MaterialTheme, project_typography: bool, cx: &mut App) {
352 let mut projected = Theme::global(cx);
353 project_base_colors(&mut projected, &theme);
354 if project_typography {
355 project_base_metrics(&mut projected, &theme, cx);
356 }
357 cx.set_global(ActiveMaterialTheme(Rc::new(theme)));
358 cx.set_global(projected);
359 refresh_inherited_windows(cx);
360}
361
362fn refresh_inherited_windows(cx: &mut App) {
363 let overridden: Vec<WindowId> = cx
364 .try_global::<WindowMaterialThemes>()
365 .map(|themes| themes.0.keys().copied().collect())
366 .unwrap_or_default();
367 if overridden.is_empty() {
368 cx.refresh_windows();
369 return;
370 }
371 for handle in cx.windows() {
372 if !overridden.contains(&handle.window_id()) {
373 let _ = handle.update(cx, |_, window, _| window.refresh());
374 }
375 }
376}
377
378fn project_base_colors(projected: &mut Theme, theme: &MaterialTheme) {
379 use ColorRole::*;
380
381 projected.appearance = match theme.colors.appearance() {
382 Appearance::Light => ThemeAppearance::Light,
383 Appearance::Dark => ThemeAppearance::Dark,
384 };
385 let role = |role| color(theme.colors.color(role));
386 let colors = &mut projected.tokens.colors;
387 colors.background = role(Surface);
388 colors.foreground = role(OnSurface);
389 colors.surface = role(SurfaceContainer);
390 colors.surface_foreground = role(OnSurface);
391 colors.primary = role(Primary);
392 colors.primary_foreground = role(OnPrimary);
393 colors.secondary = role(Secondary);
394 colors.secondary_foreground = role(OnSecondary);
395 colors.muted = role(SurfaceContainerHighest);
396 colors.muted_foreground = role(OnSurfaceVariant);
397 colors.accent = role(SecondaryContainer);
398 colors.accent_foreground = role(OnSecondaryContainer);
399 colors.destructive = role(Error);
400 colors.destructive_foreground = role(OnError);
401 colors.border = role(OutlineVariant);
402 colors.input = role(Outline);
403 colors.ring = role(Secondary);
404 colors.selection = role(Primary).opacity(0.3);
405 projected.tokens.shadow = gpui_base::ShadowTokens::elevations(role(Shadow).opacity(0.22));
406 let thumb = role(OnSurfaceVariant);
407 let styles = ScrollbarStyles::default()
408 .track(|track| track.bg(gpui::transparent_black()).width(px(8.)))
409 .thumb(|t| {
410 t.bg(thumb.opacity(0.38))
411 .width(px(4.))
412 .radius(px(2.))
413 .min_length(px(24.))
414 })
415 .thumb_hover(|t| t.bg(thumb.opacity(0.56)))
416 .thumb_active(|t| t.bg(thumb.opacity(0.72)));
417 projected.scrollbar = ScrollbarTheme::new()
418 .with_mode(projected.scrollbar.mode())
419 .with_motion(projected.scrollbar.motion())
420 .with_styles(styles);
421 let mut resizable = ResizableTheme::default();
422 resizable.handle = Some(role(OutlineVariant));
423 resizable.active_handle = Some(role(Primary));
424 projected.resizable = resizable;
425}
426
427fn project_base_metrics(projected: &mut Theme, theme: &MaterialTheme, cx: &App) {
428 let typography = &theme.typography;
429 let radii = &mut projected.tokens.radius;
430 let radius = |role: CornerRole| px(role.shape().radii(100., 100., Default::default())[0]);
431 radii.sm = radius(CornerRole::ExtraSmall);
432 radii.md = radius(CornerRole::Small);
433 radii.lg = radius(CornerRole::Medium);
434 radii.xl = radius(CornerRole::Large);
435 let text = &mut projected.tokens.typography;
436 text.sans = font_for_style(
437 typography,
438 TypeRole::BodyMedium.style(TypographyEmphasis::Baseline),
439 cx,
440 )
441 .family;
442 for (slot, role) in [
443 (&mut text.xs, TypeRole::BodySmall),
444 (&mut text.sm, TypeRole::BodyMedium),
445 (&mut text.md, TypeRole::BodyLarge),
446 (&mut text.lg, TypeRole::TitleMedium),
447 (&mut text.xl, TypeRole::TitleLarge),
448 ] {
449 let style = typography.style(role, TypographyEmphasis::Baseline);
450 slot.size = px(style.size);
451 slot.line_height = px(style.line_height);
452 slot.weight = gpui::FontWeight(f32::from(style.weight));
453 }
454}