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