Skip to main content

gpui_component/theme/
mod.rs

1use crate::{
2    highlighter::HighlightTheme, list::ListSettings, notification::NotificationSettings,
3    scroll::ScrollbarMode, sheet::SheetSettings,
4};
5use gpui::{
6    App, Global, Hsla, IsZero as _, Pixels, SharedString, Window, WindowAppearance,
7    prelude::FluentBuilder as _, px,
8};
9pub use gpui_base::{
10    ColorTokens, RadiusTokens, SemanticThemeTokens, ShadowTokens, SpacingTokens, TextStyleToken,
11    TypographyTokens,
12};
13use schemars::JsonSchema;
14use serde::{Deserialize, Serialize};
15use std::{
16    ops::{Deref, DerefMut},
17    rc::Rc,
18    sync::Arc,
19    time::Duration,
20};
21
22mod color;
23mod mono_font;
24mod motion;
25mod registry;
26mod schema;
27mod theme_color;
28
29pub use color::*;
30pub use motion::*;
31pub use registry::*;
32pub use schema::*;
33pub use theme_color::*;
34
35pub fn init(cx: &mut App) {
36    registry::init(cx);
37
38    // Ensure theme is loaded directly on startup for WASM compatibility
39    Theme::change(ThemeMode::Light, None, cx);
40    Theme::sync_scrollbar_appearance(cx);
41}
42
43pub trait ActiveTheme {
44    fn theme(&self) -> &Theme;
45}
46
47impl ActiveTheme for App {
48    #[inline(always)]
49    fn theme(&self) -> &Theme {
50        Theme::global(self)
51    }
52}
53
54fn default_true() -> bool {
55    true
56}
57
58/// The radius that rounds a shape as far as its own size allows, giving a
59/// circle or a pill. Any value past half the shorter side is clamped by the
60/// renderer, so this is simply "as round as it goes".
61const RADIUS_FULL: Pixels = px(9999.);
62
63/// How long a chart's data takes to draw in the first time it is painted.
64///
65/// The mainstream chart libraries agree on about a second: ECharts, Chart.js
66/// and Highcharts all default to 1000 ms, ApexCharts to 800 ms and Recharts to
67/// 1500 ms.
68const PLOT_APPEAR: Duration = Duration::from_millis(1000);
69
70/// The curve a chart's data draws in on: Chart.js' default `easeOutQuart`.
71///
72/// Not the design system's enter curve. That one is an exponential ease-out
73/// built for a popover, done nine-tenths of the way in the first quarter, which
74/// makes a second of drawing in read as a flash. The quartic still leads with
75/// most of the motion but leaves the data a visible glide into place.
76fn plot_appear_easing(t: f32) -> f32 {
77    1. - (1. - t).powi(4)
78}
79
80/// How long the scrollbar stays visible after the last scroll, drag, or hover.
81const SCROLLBAR_IDLE: Duration = Duration::from_secs(2);
82/// How long the scrollbar takes to appear.
83const SCROLLBAR_ENTER: Duration = Duration::from_millis(300);
84/// How long the scrollbar takes to fade away once the idle hold expires.
85const SCROLLBAR_EXIT: Duration = Duration::from_millis(500);
86/// How long the thumb takes to reach its hovered or resting width.
87const SCROLLBAR_EXPAND: Duration = Duration::from_millis(300);
88
89/// The resting thumb width on iOS and Android, matching the 3pt indicator
90/// those platforms draw. Hover and drag keep Base's desktop widths, so a
91/// grabbed thumb still grows under the finger.
92const MOBILE_SCROLLBAR_THUMB_WIDTH: Pixels = px(3.);
93/// How far the resting thumb sits from the edge on iOS and Android. Base's
94/// desktop inset leaves a 3px thumb floating too far from the edge.
95const MOBILE_SCROLLBAR_THUMB_INSET: Pixels = px(2.);
96/// Base's resting thumb width, restated so the hovered thumb keeps it when
97/// the mobile resting width would otherwise cascade into it.
98const SCROLLBAR_THUMB_HOVER_WIDTH: Pixels = px(6.);
99/// Base's dragged thumb width, restated for the same reason.
100const SCROLLBAR_THUMB_ACTIVE_WIDTH: Pixels = px(8.);
101/// Base's hovered and dragged thumb inset, restated for the same reason.
102const SCROLLBAR_THUMB_INSET: Pixels = px(4.);
103
104/// The plot hover motion this design system projects onto Base.
105///
106/// A pointer chases the cursor across neighbouring data, so it has to arrive
107/// well within the time the cursor takes to reach the next datum: ECharts moves
108/// its axis pointer over 200 ms on an exponential ease-out, which is most of
109/// the way there in the first third. The fast tier as a critically damped
110/// response lands in the same place, and the tolerance is sub-pixel so the
111/// spring rests once nothing visible moves. The hover fades on the same tier.
112/// The data draws in over [`PLOT_APPEAR`] on [`plot_appear_easing`].
113fn plot_motion(motion: &MotionTokens) -> gpui_base::PlotMotion {
114    gpui_base::PlotMotion::default()
115        .with_pointer(gpui_base::Spring::new(motion.duration_fast).with_epsilon(0.1))
116        .with_enter(
117            gpui_base::motion::Transition::new(motion.duration_fast)
118                .easing(motion.easing_enter.clone()),
119        )
120        .with_exit(
121            gpui_base::motion::Transition::new(motion.duration_fast)
122                .easing(motion.easing_exit.clone()),
123        )
124        .with_appear(gpui_base::motion::Transition::new(PLOT_APPEAR).ease(plot_appear_easing))
125}
126
127/// The scrollbar motion this design system projects onto Base.
128///
129/// Scrolling and track hover reveal a scrollbar by fading it in place. In hover
130/// mode, pointing at the thumb slides it in from the nearest edge as it fades.
131fn scrollbar_motion(mode: ScrollbarMode) -> gpui_base::ScrollbarMotion {
132    gpui_base::ScrollbarMotion::default()
133        .with_idle(SCROLLBAR_IDLE)
134        .with_enter(SCROLLBAR_ENTER)
135        .with_exit(SCROLLBAR_EXIT)
136        .with_expand(SCROLLBAR_EXPAND)
137        .with_entrance(gpui_base::ScrollbarEntrance::Fade)
138        .with_thumb_hover_entrance(match mode {
139            ScrollbarMode::Scrolling | ScrollbarMode::Always => gpui_base::ScrollbarEntrance::Fade,
140            ScrollbarMode::Hover => gpui_base::ScrollbarEntrance::SlideAndFade,
141        })
142}
143
144/// The global theme configuration.
145#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
146pub struct Theme {
147    pub colors: ThemeColor,
148    /// Component-specific resolved tokens retained for legacy compatibility.
149    ///
150    /// New application-owned presentation should use [`Self::semantic_tokens`]
151    /// rather than extending this legacy surface.
152    #[serde(default)]
153    pub tokens: ThemeTokens,
154    pub highlight_theme: Arc<HighlightTheme>,
155    pub light_theme: Rc<ThemeConfig>,
156    pub dark_theme: Rc<ThemeConfig>,
157
158    pub mode: ThemeMode,
159    /// The font family for the application, default is `.SystemUIFont`.
160    ///
161    /// When the system font resolves to an installed fallback family instead
162    /// of itself (Linux desktops without the family GPUI maps it to),
163    /// [`Theme::change`] names that family here, so every text lookup hits
164    /// the font cache. A family set explicitly is used as-is.
165    pub font_family: SharedString,
166    /// The base font size for the application, default is 16px.
167    pub font_size: Pixels,
168    /// The monospace font family for the application.
169    ///
170    /// Defaults to:
171    ///
172    /// - macOS: `Menlo`
173    /// - Windows: `Consolas`
174    /// - Linux: `DejaVu Sans Mono`
175    ///
176    /// When that default is not installed, [`Theme::change`] swaps it for the
177    /// first installed alternative (`Monaco`, `Cascadia Mono`, `Noto Sans Mono`
178    /// and the like) and finally `.SystemUIFont`, so a missing font cannot
179    /// crash text layout. A family set explicitly is used as-is.
180    pub mono_font_family: SharedString,
181    /// The monospace font size for the application, default is 13px.
182    pub mono_font_size: Pixels,
183    /// Radius for the general elements.
184    pub radius: Pixels,
185    /// Radius for the large elements, e.g.: Dialog, Notification border radius.
186    pub radius_lg: Pixels,
187    pub shadow: bool,
188    /// Whether focused controls draw a ring outside their border, default true.
189    ///
190    /// The ring is painted outside the element, so any ancestor that clips its
191    /// content will cut it off. An application whose layout clips heavily can
192    /// turn it off here: focused controls then show only their tinted border,
193    /// or a 1px ring just inside their edge when they have none. Neither costs
194    /// space or can be clipped.
195    #[serde(default = "default_true")]
196    pub focus_ring: bool,
197    #[schemars(schema_with = "gpui::hsla_schemar")]
198    pub transparent: Hsla,
199    /// Show the scrollbar mode, default: Scrolling
200    #[serde(alias = "scrollbar_show")]
201    pub scrollbar_mode: ScrollbarMode,
202    /// The notification setting.
203    #[serde(skip)]
204    pub notification: NotificationSettings,
205    /// The list settings.
206    pub list: ListSettings,
207    /// The sheet settings.
208    pub sheet: SheetSettings,
209    /// Semantic motion policy for styled components.
210    #[serde(skip)]
211    pub motion: MotionTokens,
212}
213
214impl Default for Theme {
215    fn default() -> Self {
216        Self::from(&ThemeColor::default())
217    }
218}
219
220impl Deref for Theme {
221    type Target = ThemeColor;
222
223    fn deref(&self) -> &Self::Target {
224        &self.colors
225    }
226}
227
228impl DerefMut for Theme {
229    fn deref_mut(&mut self) -> &mut Self::Target {
230        &mut self.colors
231    }
232}
233
234impl Global for Theme {}
235
236impl Theme {
237    /// Returns the global theme reference
238    #[inline(always)]
239    pub fn global(cx: &App) -> &Theme {
240        cx.global::<Theme>()
241    }
242
243    /// Returns the global theme mutable reference.
244    ///
245    /// An edit made through this reference reaches nothing but the field it
246    /// touches: [`Theme::tokens`] keeps the colors it had, and so does the
247    /// Base projection until [`Theme::sync_base`] rebuilds it. Prefer
248    /// [`Theme::update`], which does both after the edit and refreshes every
249    /// window. Keep this for an edit that must not trigger any of that.
250    #[inline(always)]
251    pub fn global_mut(cx: &mut App) -> &mut Theme {
252        cx.global_mut::<Theme>()
253    }
254
255    /// Edits the global theme and keeps every copy of it in step.
256    ///
257    /// The theme holds the same colors twice — [`Theme::colors`] as solid
258    /// colors and [`Theme::tokens`] as renderable backgrounds that may carry a
259    /// gradient — and the Base layer keeps a projection of its own for the
260    /// scrollbar and resize handles. Editing one of them through
261    /// [`Theme::global_mut`] leaves the others where they were, so a sidebar
262    /// can paint its text from the new colors and its background from the old
263    /// tokens. This is the write path that cannot drift:
264    ///
265    /// ```ignore
266    /// Theme::update(cx, |theme| {
267    ///     theme.colors = my_colors;
268    ///     theme.radius = px(8.);
269    /// });
270    /// ```
271    ///
272    /// After the closure returns, a color edited on `colors` replaces its
273    /// token (dropping any gradient — the edit asked for that solid color), a
274    /// token edited on its own writes its solid color back to `colors`, an
275    /// untouched field keeps the gradient a theme file gave it, the Base
276    /// projection is rebuilt, and every window is refreshed.
277    ///
278    /// A field the closure sets to the value it already had counts as
279    /// untouched: assigning a whole palette keeps the gradient of any field
280    /// whose color did not change. Edit the token to replace one.
281    ///
282    /// Setting [`Theme::mode`] loads that mode's registered theme, the same
283    /// as [`Theme::change`]; that load replaces the colors, so edit colors in
284    /// a second `update` after switching mode rather than in the same closure.
285    /// [`Theme::apply_config`] installs a theme file and switches to its mode
286    /// in one step, and the closure may go on editing after it — nothing is
287    /// loaded over its edits.
288    pub fn update<R>(cx: &mut App, edit: impl FnOnce(&mut Theme) -> R) -> R {
289        Self::edit(cx, false, edit)
290    }
291
292    /// The write path behind [`Theme::update`] and [`Theme::change`].
293    ///
294    /// `reload_mode` loads the current mode's registered theme even when the
295    /// mode did not change, which is what `change` promises: a caller that
296    /// swapped [`Theme::light_theme`] or [`Theme::dark_theme`] and then asks
297    /// for that mode gets the new theme applied.
298    fn edit<R>(cx: &mut App, reload_mode: bool, edit: impl FnOnce(&mut Theme) -> R) -> R {
299        let theme = Theme::global_mut(cx);
300        let colors_before = theme.colors;
301        let tokens_before = theme.tokens;
302        let mode_before = theme.mode;
303        let light_before = theme.light_theme.clone();
304        let dark_before = theme.dark_theme.clone();
305        let fonts_before = (theme.font_family.clone(), theme.mono_font_family.clone());
306
307        let result = edit(theme);
308
309        theme
310            .tokens
311            .reconcile(&mut theme.colors, &colors_before, &tokens_before);
312        let mode_changed = theme.mode != mode_before;
313        let (config, config_before) = if theme.mode.is_dark() {
314            (&theme.dark_theme, &dark_before)
315        } else {
316            (&theme.light_theme, &light_before)
317        };
318        // `apply_config` registers the file it applies and switches to its
319        // mode, so a mode change that arrives with a newly registered config
320        // has already loaded it. Loading it again would put the file's radius,
321        // fonts and colors back over whatever the closure edited after it.
322        let installed_by_edit = mode_changed && !Rc::ptr_eq(config, config_before);
323        if (mode_changed || reload_mode) && !installed_by_edit {
324            let config = config.clone();
325            theme.apply_config(&config);
326        }
327        let fonts_changed =
328            (&theme.font_family, &theme.mono_font_family) != (&fonts_before.0, &fonts_before.1);
329        if mode_changed || reload_mode || fonts_changed {
330            // GPUI 0.3 caches virtual system-font resolution in TextSystem.
331            mono_font::resolve_default_mono_font(cx);
332        }
333        Self::sync_base(cx);
334        cx.refresh_windows();
335        result
336    }
337
338    /// Returns true if the theme is dark.
339    #[inline(always)]
340    pub fn is_dark(&self) -> bool {
341        self.mode.is_dark()
342    }
343
344    /// Returns the current theme name.
345    pub fn theme_name(&self) -> &SharedString {
346        if self.is_dark() {
347            &self.dark_theme.name
348        } else {
349            &self.light_theme.name
350        }
351    }
352
353    /// Sync the theme with the system appearance
354    pub fn sync_system_appearance(window: Option<&mut Window>, cx: &mut App) {
355        // Better use window.appearance() for avoid error on Linux.
356        // https://github.com/longbridge/gpui-kit/issues/104
357        let appearance = window
358            .as_ref()
359            .map(|window| window.appearance())
360            .unwrap_or_else(|| cx.window_appearance());
361
362        Self::change(appearance, window, cx);
363    }
364
365    /// Sync the Scrollbar showing behavior with the system
366    pub fn sync_scrollbar_appearance(cx: &mut App) {
367        let mode = if cx.should_auto_hide_scrollbars() {
368            ScrollbarMode::Scrolling
369        } else {
370            ScrollbarMode::Hover
371        };
372        Self::set_scrollbar_mode(mode, cx);
373    }
374
375    /// Changes the scrollbar display mode through [`Theme::update`], which
376    /// projects it onto the Base scrollbar and refreshes every window.
377    pub fn set_scrollbar_mode(mode: ScrollbarMode, cx: &mut App) {
378        Self::update(cx, |theme| theme.scrollbar_mode = mode);
379    }
380
381    /// Change the theme mode.
382    ///
383    /// Loads the registered theme for `mode` — even when `mode` is already
384    /// current, so a caller that swapped [`Theme::light_theme`] or
385    /// [`Theme::dark_theme`] sees the new theme — through [`Theme::update`],
386    /// which keeps every copy of the theme in step and refreshes every
387    /// window. `window` is accepted for compatibility; every window is
388    /// refreshed either way, so it is not read.
389    pub fn change(mode: impl Into<ThemeMode>, _window: Option<&mut Window>, cx: &mut App) {
390        let mode = mode.into();
391        if !cx.has_global::<Theme>() {
392            let mut theme = Theme::default();
393            theme.light_theme = ThemeRegistry::global(cx).default_light_theme().clone();
394            theme.dark_theme = ThemeRegistry::global(cx).default_dark_theme().clone();
395            cx.set_global(theme);
396        }
397
398        Self::edit(cx, true, |theme| theme.mode = mode);
399    }
400
401    /// This theme projected onto the Base layer, which owns the scrollbar and
402    /// resize handles and reads the semantic tokens.
403    fn base_theme(&self) -> gpui_base::Theme {
404        gpui_base::Theme {
405            appearance: if self.mode.is_dark() {
406                gpui_base::ThemeAppearance::Dark
407            } else {
408                gpui_base::ThemeAppearance::Light
409            },
410            tokens: self.semantic_tokens(),
411            scrollbar: gpui_base::ScrollbarTheme::new()
412                .with_mode(self.scrollbar_mode)
413                .with_motion(scrollbar_motion(self.scrollbar_mode))
414                .with_styles(
415                    gpui_base::ScrollbarStyles::default()
416                        .track(|style| style.bg(self.scrollbar))
417                        .track_hover(|style| style.bg(self.scrollbar))
418                        .track_active(|style| style.bg(self.scrollbar).border_color(self.border))
419                        .thumb(|style| {
420                            style
421                                .bg(self.tokens.scrollbar_thumb)
422                                .radius(self.radius)
423                                .when(gpui_base::is_mobile(), |style| {
424                                    style
425                                        .width(MOBILE_SCROLLBAR_THUMB_WIDTH)
426                                        .inset(MOBILE_SCROLLBAR_THUMB_INSET)
427                                        .radius(RADIUS_FULL)
428                                })
429                        })
430                        .thumb_hover(|style| {
431                            style
432                                .bg(self.tokens.scrollbar_thumb_hover)
433                                .radius(self.radius)
434                                .when(gpui_base::is_mobile(), |style| {
435                                    style
436                                        .width(SCROLLBAR_THUMB_HOVER_WIDTH)
437                                        .inset(SCROLLBAR_THUMB_INSET)
438                                })
439                        })
440                        .thumb_active(|style| {
441                            style
442                                .bg(self.tokens.scrollbar_thumb_hover)
443                                .radius(self.radius)
444                                .when(gpui_base::is_mobile(), |style| {
445                                    style
446                                        .width(SCROLLBAR_THUMB_ACTIVE_WIDTH)
447                                        .inset(SCROLLBAR_THUMB_INSET)
448                                })
449                        }),
450                ),
451            resizable: gpui_base::ResizableTheme {
452                handle: Some(self.border),
453                active_handle: Some(self.drag_border),
454            },
455            plot: gpui_base::PlotTheme::new().with_motion(plot_motion(&self.motion)),
456        }
457    }
458
459    /// Push the current theme down to the Base layer.
460    ///
461    /// The Base layer holds its own copy of the theme — the semantic tokens
462    /// plus the scrollbar and resize-handle styles — because it paints those
463    /// without going through `gpui-component`. [`Theme::change`] refreshes that
464    /// copy, but writing to the theme's public fields directly does not, so a
465    /// scrollbar keeps painting with the radius and colors it was last given.
466    ///
467    /// [`Theme::update`] and [`Theme::change`] call this after their edits.
468    /// After editing through [`Theme::global_mut`], call it yourself, then
469    /// refresh the windows.
470    ///
471    /// It rebuilds the Base theme from scratch, so any style written straight
472    /// onto the Base global is replaced. It does not touch [`Theme::tokens`].
473    pub fn sync_base(cx: &mut App) {
474        let theme = Theme::global(cx).clone();
475        let base_theme = theme.base_theme();
476        cx.set_global(base_theme);
477        crate::text::install_text_view_defaults(&theme, cx);
478    }
479
480    /// Get the input background color.
481    ///
482    /// For dark, use a transparent color mixed with the input border: `cx.theme().input`,
483    /// otherwise use the `cx.theme().background` color.
484    #[inline]
485    pub fn input_background(&self) -> Hsla {
486        if self.is_dark() {
487            self.input.mix_oklab(self.transparent, 0.3)
488        } else {
489            self.background
490        }
491    }
492
493    /// Get the editor background color, if not set, use the input background color.
494    #[inline]
495    pub(crate) fn editor_background(&self) -> Hsla {
496        self.highlight_theme
497            .style
498            .editor_background
499            .unwrap_or_else(|| self.input_background())
500    }
501
502    /// Returns a snapshot of the semantic design tokens represented by this
503    /// theme. The snapshot is computed from the legacy public fields so direct
504    /// mutations of those fields are reflected immediately.
505    pub fn semantic_tokens(&self) -> SemanticThemeTokens {
506        SemanticThemeTokens {
507            colors: self.color_tokens(),
508            radius: self.radius_tokens(),
509            spacing: self.spacing_tokens(),
510            typography: self.typography_tokens(),
511            shadow: self.shadow_tokens(),
512        }
513    }
514
515    /// Returns the styled layer's semantic motion policy.
516    pub fn motion_tokens(&self) -> &MotionTokens {
517        &self.motion
518    }
519
520    pub fn color_tokens(&self) -> ColorTokens {
521        ColorTokens {
522            background: self.background,
523            foreground: self.foreground,
524            surface: self.popover,
525            surface_foreground: self.popover_foreground,
526            primary: self.primary,
527            primary_foreground: self.primary_foreground,
528            secondary: self.secondary,
529            secondary_foreground: self.secondary_foreground,
530            muted: self.muted,
531            muted_foreground: self.muted_foreground,
532            accent: self.accent,
533            accent_foreground: self.accent_foreground,
534            destructive: self.danger,
535            destructive_foreground: self.danger_foreground,
536            border: self.border,
537            input: self.input,
538            ring: self.ring,
539            selection: self.selection,
540        }
541    }
542
543    /// The radius of a shape that reads as a circle or a pill — an avatar, a
544    /// slider thumb, a badge dot, a pill tab.
545    ///
546    /// A theme whose [`Theme::radius`] is zero squares these off too, so one
547    /// setting governs the whole UI instead of leaving a handful of
548    /// permanently round elements behind. Use it in place of
549    /// [`gpui::Styled::rounded_full`], or reach for
550    /// [`crate::ThemeStyled::rounded_full_style`] when styling an element.
551    pub fn radius_full(&self) -> Pixels {
552        if self.radius.is_zero() {
553            px(0.)
554        } else {
555            RADIUS_FULL
556        }
557    }
558
559    /// Returns the next surface radius above the existing `xl` theme tier.
560    ///
561    /// Larger surface tiers derive from the same application-controlled base
562    /// radius, so adjusting or squaring the theme updates every tier together.
563    pub fn radius_2xl(&self) -> Pixels {
564        self.radius * 2.5
565    }
566
567    /// Returns the surface radius above [`Self::radius_2xl`].
568    pub fn radius_3xl(&self) -> Pixels {
569        self.radius * 3.
570    }
571
572    /// Returns the surface radius above [`Self::radius_3xl`].
573    pub fn radius_4xl(&self) -> Pixels {
574        self.radius * 3.5
575    }
576
577    pub fn radius_tokens(&self) -> RadiusTokens {
578        RadiusTokens {
579            none: px(0.),
580            sm: self.radius / 2.,
581            md: self.radius,
582            lg: self.radius_lg,
583            xl: self.radius * 2.,
584            full: self.radius_full(),
585        }
586    }
587
588    pub fn spacing_tokens(&self) -> SpacingTokens {
589        SpacingTokens::default()
590    }
591
592    pub fn typography_tokens(&self) -> TypographyTokens {
593        let mut tokens = TypographyTokens::default();
594        tokens.sans = self.font_family.clone();
595        tokens.mono = self.mono_font_family.clone();
596        tokens.md.size = self.font_size;
597        tokens.mono_md.size = self.mono_font_size;
598        tokens
599    }
600
601    pub fn shadow_tokens(&self) -> ShadowTokens {
602        if self.shadow {
603            ShadowTokens::elevations({
604                let mut color = self.transparent;
605                color.alpha = 0.18;
606                color
607            })
608        } else {
609            ShadowTokens::default()
610        }
611    }
612
613    /// Applies the subset of semantic tokens representable by the legacy
614    /// theme. Scale-only spacing and elevation details have no legacy storage;
615    /// legacy components therefore keep their existing behavior.
616    pub fn apply_semantic_tokens(&mut self, tokens: &SemanticThemeTokens) {
617        let colors = tokens.colors;
618        self.background = colors.background;
619        self.foreground = colors.foreground;
620        self.popover = colors.surface;
621        self.popover_foreground = colors.surface_foreground;
622        self.primary = colors.primary;
623        self.primary_foreground = colors.primary_foreground;
624        self.secondary = colors.secondary;
625        self.secondary_foreground = colors.secondary_foreground;
626        self.muted = colors.muted;
627        self.muted_foreground = colors.muted_foreground;
628        self.accent = colors.accent;
629        self.accent_foreground = colors.accent_foreground;
630        self.danger = colors.destructive;
631        self.danger_foreground = colors.destructive_foreground;
632        self.border = colors.border;
633        self.input = colors.input;
634        self.ring = colors.ring;
635
636        self.tokens.background = colors.background.into();
637        self.tokens.popover = colors.surface.into();
638        self.tokens.primary = colors.primary.into();
639        self.tokens.secondary = colors.secondary.into();
640        self.tokens.muted = colors.muted.into();
641        self.tokens.accent = colors.accent.into();
642        self.tokens.danger = colors.destructive.into();
643
644        self.radius = tokens.radius.md;
645        self.radius_lg = tokens.radius.lg;
646        self.font_family = tokens.typography.sans.clone();
647        self.mono_font_family = tokens.typography.mono.clone();
648        self.font_size = tokens.typography.md.size;
649        self.mono_font_size = tokens.typography.mono_md.size;
650        self.shadow = !tokens.shadow.sm.is_empty()
651            || !tokens.shadow.md.is_empty()
652            || !tokens.shadow.lg.is_empty();
653    }
654
655    /// Resolves a standalone semantic configuration over the current legacy
656    /// theme without mutating either value.
657    pub fn resolve_semantic_config(&self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
658        let mut tokens = self.semantic_tokens();
659        config.apply_to(&mut tokens);
660        tokens
661    }
662
663    /// Applies the legacy-representable part of a standalone semantic config
664    /// and returns the complete resolved snapshot for application-owned UI.
665    pub fn apply_semantic_config(&mut self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
666        let tokens = self.resolve_semantic_config(config);
667        self.apply_semantic_tokens(&tokens);
668        tokens
669    }
670
671    /// Parses and applies a standalone `{ "tokens": ... }` semantic theme file.
672    pub fn apply_semantic_config_str(
673        &mut self,
674        content: &str,
675    ) -> anyhow::Result<SemanticThemeTokens> {
676        let config = serde_json::from_str::<SemanticThemeConfigFile>(content)?;
677        Ok(self.apply_semantic_config(&config.tokens))
678    }
679}
680
681#[cfg(test)]
682mod semantic_token_tests {
683    use gpui::{Hsla, IsZero as _, px};
684
685    use super::{RADIUS_FULL, Theme};
686
687    fn with_alpha(mut color: Hsla, alpha: f32) -> Hsla {
688        color.alpha = alpha;
689        color
690    }
691
692    #[test]
693    fn semantic_colors_are_a_live_projection_of_legacy_fields() {
694        let mut theme = Theme::default();
695        let primary = with_alpha(Hsla::default(), 0.42);
696        theme.primary = primary;
697
698        assert_eq!(theme.color_tokens().primary, primary);
699        assert_eq!(theme.semantic_tokens().colors.primary, primary);
700    }
701
702    #[test]
703    fn applying_semantic_tokens_only_updates_generic_legacy_colors() {
704        let mut theme = Theme::default();
705        let component_color = theme.button_primary;
706        let mut tokens = theme.semantic_tokens();
707        tokens.colors.primary = with_alpha(Hsla::default(), 0.25);
708        tokens.colors.destructive = with_alpha(Hsla::default(), 0.75);
709        tokens.radius.md = px(10.);
710
711        theme.apply_semantic_tokens(&tokens);
712
713        assert_eq!(theme.primary, tokens.colors.primary);
714        assert_eq!(theme.tokens.primary.color, tokens.colors.primary);
715        assert_eq!(theme.danger, tokens.colors.destructive);
716        assert_eq!(theme.radius, px(10.));
717        assert_eq!(theme.button_primary, component_color);
718    }
719
720    #[test]
721    fn square_themes_square_off_pills_and_circles() {
722        let mut theme = Theme::default();
723        assert_eq!(theme.radius_full(), RADIUS_FULL);
724        assert_eq!(theme.radius_tokens().full, RADIUS_FULL);
725
726        // An application asking for square corners gets them everywhere, not
727        // just on the elements whose radius happens to come from `radius`.
728        theme.radius = px(0.);
729        assert_eq!(theme.radius_full(), px(0.));
730        assert_eq!(theme.radius_tokens().full, px(0.));
731    }
732
733    #[test]
734    fn larger_surface_radii_follow_the_theme_radius() {
735        let mut theme = Theme::default();
736        assert!(theme.radius_tokens().xl < theme.radius_2xl());
737        assert!(theme.radius_2xl() < theme.radius_3xl());
738        assert!(theme.radius_3xl() < theme.radius_4xl());
739
740        theme.radius = px(10.);
741        assert_eq!(theme.radius_2xl(), px(25.));
742        assert_eq!(theme.radius_3xl(), px(30.));
743        assert_eq!(theme.radius_4xl(), px(35.));
744
745        theme.radius = px(0.);
746        assert_eq!(theme.radius_2xl(), px(0.));
747        assert_eq!(theme.radius_3xl(), px(0.));
748        assert_eq!(theme.radius_4xl(), px(0.));
749    }
750
751    #[test]
752    fn base_projection_carries_a_square_radius_to_the_scrollbar() {
753        let mut theme = Theme::default();
754        assert!(!theme.base_theme().tokens.radius.md.is_zero());
755
756        // The scrollbar paints from the Base layer's copy of the theme, so a
757        // square theme has to reach it or the thumb stays a pill.
758        theme.radius = px(0.);
759        assert!(theme.base_theme().tokens.radius.md.is_zero());
760    }
761
762    #[test]
763    fn disabled_legacy_shadows_project_to_empty_elevations() {
764        let mut theme = Theme::default();
765        theme.shadow = false;
766
767        let shadows = theme.shadow_tokens();
768        assert!(shadows.sm.is_empty());
769        assert!(shadows.md.is_empty());
770        assert!(shadows.lg.is_empty());
771    }
772}
773
774impl From<&ThemeColor> for Theme {
775    fn from(colors: &ThemeColor) -> Self {
776        Theme {
777            mode: ThemeMode::default(),
778            transparent: gpui::transparent_black(),
779            font_family: ".SystemUIFont".into(),
780            font_size: px(16.),
781            mono_font_family: mono_font::default_mono_font_family(),
782            mono_font_size: px(13.),
783            radius: px(6.),
784            radius_lg: px(8.),
785            shadow: true,
786            focus_ring: true,
787            scrollbar_mode: ScrollbarMode::default(),
788            notification: NotificationSettings::default(),
789            list: ListSettings::default(),
790            colors: *colors,
791            tokens: ThemeTokens::from(colors),
792            light_theme: Rc::new(ThemeConfig::default()),
793            dark_theme: Rc::new(ThemeConfig::default()),
794            highlight_theme: HighlightTheme::default_light(),
795            sheet: SheetSettings::default(),
796            motion: MotionTokens::default(),
797        }
798    }
799}
800
801#[derive(
802    Debug,
803    Clone,
804    Copy,
805    Default,
806    PartialEq,
807    PartialOrd,
808    Eq,
809    Ord,
810    Hash,
811    Serialize,
812    Deserialize,
813    JsonSchema,
814)]
815#[serde(rename_all = "snake_case")]
816pub enum ThemeMode {
817    #[default]
818    Light,
819    Dark,
820}
821
822impl ThemeMode {
823    #[inline(always)]
824    pub fn is_dark(&self) -> bool {
825        matches!(self, Self::Dark)
826    }
827
828    /// Return lower_case theme name: `light`, `dark`.
829    pub fn name(&self) -> &'static str {
830        match self {
831            ThemeMode::Light => "light",
832            ThemeMode::Dark => "dark",
833        }
834    }
835}
836
837impl From<WindowAppearance> for ThemeMode {
838    fn from(appearance: WindowAppearance) -> Self {
839        match appearance {
840            WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
841            WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
842        }
843    }
844}
845
846#[cfg(test)]
847mod update_tests {
848    use super::*;
849    use gpui::{TestAppContext, linear_color_stop, linear_gradient};
850
851    fn gradient(from: Hsla, to: Hsla) -> ThemeToken {
852        ThemeToken::new(
853            from,
854            linear_gradient(135., linear_color_stop(from, 0.), linear_color_stop(to, 1.)),
855        )
856    }
857
858    /// A color edited on `colors` reaches the token the components paint
859    /// with, and the Base projection the scrollbar paints with.
860    #[gpui::test]
861    fn editing_colors_updates_the_tokens_and_the_base_projection(cx: &mut TestAppContext) {
862        cx.update(|cx| {
863            init(cx);
864            let sidebar = gpui::rgb_to_hsla(gpui::rgb(0x123456));
865            let primary = gpui::rgb_to_hsla(gpui::rgb(0xabcdef));
866
867            Theme::update(cx, |theme| {
868                theme.sidebar = sidebar;
869                theme.colors.primary = primary;
870                theme.radius = px(0.);
871            });
872
873            let theme = Theme::global(cx);
874            assert_eq!(theme.tokens.sidebar.color, sidebar);
875            assert_eq!(theme.tokens.sidebar.background, sidebar.into());
876            assert_eq!(theme.tokens.primary.color, primary);
877            assert_eq!(gpui_base::Theme::global(cx).tokens.colors.primary, primary);
878            assert!(gpui_base::Theme::global(cx).tokens.radius.md.is_zero());
879        });
880    }
881
882    /// Replacing the whole `colors` struct, as an application installing its
883    /// own palette does, rewrites every token.
884    #[gpui::test]
885    fn replacing_the_palette_rewrites_every_token(cx: &mut TestAppContext) {
886        cx.update(|cx| {
887            init(cx);
888            let palette = *ThemeColor::dark();
889
890            Theme::update(cx, |theme| theme.colors = palette);
891
892            assert_eq!(Theme::global(cx).tokens, ThemeTokens::from(palette));
893        });
894    }
895
896    /// A gradient a theme file gave a token survives edits to other fields;
897    /// editing that field's color replaces the gradient with the solid color.
898    #[gpui::test]
899    fn a_gradient_survives_until_its_own_color_is_edited(cx: &mut TestAppContext) {
900        cx.update(|cx| {
901            init(cx);
902            let from = gpui::rgb_to_hsla(gpui::rgb(0x4f46e5));
903            let to = gpui::rgb_to_hsla(gpui::rgb(0x06b6d4));
904            let token = gradient(from, to);
905            Theme::update(cx, |theme| theme.tokens.primary = token);
906            // The token's solid color is written back, so text painted with
907            // `theme.primary` matches the gradient's representative color.
908            assert_eq!(Theme::global(cx).primary, from);
909
910            Theme::update(cx, |theme| {
911                theme.secondary = gpui::rgb_to_hsla(gpui::rgb(0x222222))
912            });
913            assert_eq!(Theme::global(cx).tokens.primary, token);
914
915            let solid = gpui::rgb_to_hsla(gpui::rgb(0x999999));
916            Theme::update(cx, |theme| theme.primary = solid);
917            assert_eq!(Theme::global(cx).tokens.primary, solid.into());
918        });
919    }
920
921    /// Setting `mode` through `update` loads that mode's theme, the same as
922    /// `change`, and the Base projection follows.
923    #[gpui::test]
924    fn setting_the_mode_loads_that_modes_theme(cx: &mut TestAppContext) {
925        cx.update(|cx| {
926            init(cx);
927            let light_background = Theme::global(cx).background;
928
929            Theme::update(cx, |theme| theme.mode = ThemeMode::Dark);
930
931            let theme = Theme::global(cx);
932            assert!(theme.is_dark());
933            assert_ne!(theme.background, light_background);
934            assert_eq!(theme.tokens.background.color, theme.background);
935            assert_eq!(
936                gpui_base::Theme::global(cx).appearance,
937                gpui_base::ThemeAppearance::Dark
938            );
939            assert_eq!(
940                gpui_base::Theme::global(cx).tokens.colors.background,
941                theme.background
942            );
943        });
944    }
945
946    /// Applying a theme file through `update` keeps the gradients it
947    /// declares: the config sets `colors` and `tokens` to one color, which is
948    /// not a conflict to resolve.
949    #[gpui::test]
950    fn applying_a_config_keeps_its_gradients(cx: &mut TestAppContext) {
951        cx.update(|cx| {
952            init(cx);
953            let config: ThemeConfig = serde_json::from_value(serde_json::json!({
954                "name": "Gradient",
955                "mode": "light",
956                "colors": {
957                    "primary": "#4F46E5",
958                    "primary.background": "linear-gradient(135deg, #4F46E5, #06B6D4)"
959                }
960            }))
961            .unwrap();
962            let config = Rc::new(config);
963
964            Theme::update(cx, |theme| theme.apply_config(&config));
965
966            let theme = Theme::global(cx);
967            assert_eq!(theme.tokens.primary.color, theme.primary);
968            assert_ne!(
969                theme.tokens.primary.background,
970                theme.primary.into(),
971                "the gradient must survive the reconcile"
972            );
973        });
974    }
975
976    /// `apply_config` switches to the file's mode itself, so `edit` must not
977    /// load that mode's theme a second time over what the closure went on to
978    /// set — the same closure has to land the same result from either mode.
979    #[gpui::test]
980    fn edits_after_applying_a_config_of_the_other_mode_survive(cx: &mut TestAppContext) {
981        cx.update(|cx| {
982            init(cx);
983            let config: ThemeConfig = serde_json::from_value(serde_json::json!({
984                "name": "Rounded Dark",
985                "mode": "dark",
986                "radius": 12,
987                "colors": { "primary": "#4F46E5" }
988            }))
989            .unwrap();
990            let config = Rc::new(config);
991            assert!(!Theme::global(cx).is_dark());
992
993            let red = gpui::red();
994            Theme::update(cx, |theme| {
995                theme.apply_config(&config);
996                theme.radius = px(0.);
997                theme.colors.primary = red;
998            });
999
1000            let theme = Theme::global(cx);
1001            assert!(theme.is_dark());
1002            assert!(Rc::ptr_eq(&theme.dark_theme, &config));
1003            assert_eq!(theme.radius, px(0.), "the file's radius must not reload");
1004            assert_eq!(theme.primary, red);
1005            assert_eq!(theme.tokens.primary, red.into());
1006            assert_eq!(gpui_base::Theme::global(cx).tokens.colors.primary, red);
1007        });
1008    }
1009
1010    #[gpui::test]
1011    fn update_returns_the_closure_result(cx: &mut TestAppContext) {
1012        cx.update(|cx| {
1013            init(cx);
1014            let radius = Theme::update(cx, |theme| {
1015                theme.radius = px(6.);
1016                theme.radius
1017            });
1018            assert_eq!(radius, px(6.));
1019        });
1020    }
1021}
1022
1023#[cfg(test)]
1024mod base_theme_projection_tests {
1025    use super::*;
1026    use gpui::TestAppContext;
1027
1028    #[gpui::test]
1029    fn base_theme_tracks_initialization_and_mode_changes(cx: &mut TestAppContext) {
1030        cx.update(|cx| {
1031            init(cx);
1032            assert_styled_projection(cx);
1033
1034            Theme::change(ThemeMode::Dark, None, cx);
1035            assert_styled_projection(cx);
1036
1037            Theme::set_scrollbar_mode(ScrollbarMode::Always, cx);
1038            assert_eq!(Theme::global(cx).scrollbar_mode, ScrollbarMode::Always);
1039            assert_eq!(
1040                gpui_base::Theme::global(cx).scrollbar.mode(),
1041                gpui_base::ScrollbarMode::Always
1042            );
1043            assert_styled_projection(cx);
1044        });
1045    }
1046
1047    #[gpui::test]
1048    fn scrollbar_motion_is_owned_here_and_projected_onto_base(cx: &mut TestAppContext) {
1049        cx.update(|cx| {
1050            init(cx);
1051
1052            // Base itself ships none of this timing.
1053            let bare = gpui_base::ScrollbarMotion::default();
1054            assert_eq!(bare.enter(), Duration::ZERO);
1055            assert_eq!(bare.exit(), Duration::ZERO);
1056            assert_eq!(bare.expand(), Duration::ZERO);
1057
1058            Theme::set_scrollbar_mode(ScrollbarMode::Scrolling, cx);
1059            let motion = gpui_base::Theme::global(cx).scrollbar.motion();
1060            assert_eq!(motion.idle(), SCROLLBAR_IDLE);
1061            assert_eq!(motion.enter(), SCROLLBAR_ENTER);
1062            assert_eq!(motion.exit(), SCROLLBAR_EXIT);
1063            assert_eq!(motion.expand(), SCROLLBAR_EXPAND);
1064            assert_eq!(
1065                motion.entrance(),
1066                gpui_base::ScrollbarEntrance::Fade,
1067                "scroll-revealed scrollbars fade in without sliding"
1068            );
1069
1070            Theme::set_scrollbar_mode(ScrollbarMode::Hover, cx);
1071            let motion = gpui_base::Theme::global(cx).scrollbar.motion();
1072            assert_eq!(motion.entrance(), gpui_base::ScrollbarEntrance::Fade);
1073            assert_eq!(
1074                motion.thumb_hover_entrance(),
1075                gpui_base::ScrollbarEntrance::SlideAndFade
1076            );
1077        });
1078    }
1079
1080    #[test]
1081    fn default_motion_tokens_form_a_coherent_semantic_scale() {
1082        let theme = Theme::default();
1083        let motion = theme.motion_tokens();
1084
1085        assert_eq!(motion.duration_instant, Duration::ZERO);
1086        assert!(motion.duration_fast < motion.duration_normal);
1087        assert!(motion.duration_normal < motion.duration_slow);
1088        assert!(motion.distance_short.0 < motion.distance_medium.0);
1089        assert_eq!(motion.easing_enter.sample(0.0), 0.0);
1090        assert_eq!(motion.easing_enter.sample(1.0), 1.0);
1091    }
1092
1093    fn assert_styled_projection(cx: &App) {
1094        let theme = Theme::global(cx);
1095        let base = gpui_base::Theme::global(cx);
1096
1097        assert_eq!(base.tokens, theme.semantic_tokens());
1098        assert_eq!(base.scrollbar.mode(), theme.scrollbar_mode);
1099        assert_eq!(
1100            base.scrollbar.motion(),
1101            scrollbar_motion(theme.scrollbar_mode)
1102        );
1103        assert_eq!(base.resizable.handle, Some(theme.border));
1104        assert_eq!(base.resizable.active_handle, Some(theme.drag_border));
1105    }
1106
1107    #[gpui::test]
1108    fn default_component_palettes_match_base_light_and_dark_tokens(cx: &mut gpui::TestAppContext) {
1109        fn assert_close(left: ColorTokens, right: ColorTokens) {
1110            macro_rules! color {
1111                ($field:ident) => {
1112                    assert!(
1113                        (left.$field.color.hue.into_degrees()
1114                            - right.$field.color.hue.into_degrees())
1115                        .abs()
1116                            < 1e-4
1117                            && (left.$field.color.saturation - right.$field.color.saturation).abs()
1118                                < 1e-6
1119                            && (left.$field.color.lightness - right.$field.color.lightness).abs()
1120                                < 1e-6
1121                            && (left.$field.alpha - right.$field.alpha).abs() < 1e-6,
1122                        "{} differs: {:?} != {:?}",
1123                        stringify!($field),
1124                        left.$field,
1125                        right.$field
1126                    );
1127                };
1128            }
1129            color!(background);
1130            color!(foreground);
1131            color!(surface);
1132            color!(surface_foreground);
1133            color!(primary);
1134            color!(primary_foreground);
1135            color!(secondary);
1136            color!(secondary_foreground);
1137            color!(muted);
1138            color!(muted_foreground);
1139            color!(accent);
1140            color!(accent_foreground);
1141            color!(destructive);
1142            color!(destructive_foreground);
1143            color!(border);
1144            color!(input);
1145            color!(ring);
1146            color!(selection);
1147        }
1148
1149        cx.update(crate::init);
1150        cx.update(|cx| {
1151            assert_close(Theme::global(cx).color_tokens(), ColorTokens::light());
1152        });
1153
1154        cx.update(|cx| Theme::change(ThemeMode::Dark, None, cx));
1155        cx.update(|cx| {
1156            assert_close(Theme::global(cx).color_tokens(), ColorTokens::dark());
1157        });
1158    }
1159}