1use crate::{
2 highlighter::HighlightTheme, list::ListSettings, notification::NotificationSettings,
3 scroll::ScrollbarMode, sheet::SheetSettings,
4};
5use gpui::{App, Global, Hsla, IsZero as _, Pixels, SharedString, Window, WindowAppearance, px};
6pub use gpui_base::{
7 ColorTokens, RadiusTokens, SemanticThemeTokens, ShadowTokens, SpacingTokens, TextStyleToken,
8 TypographyTokens,
9};
10use schemars::JsonSchema;
11use serde::{Deserialize, Serialize};
12use std::{
13 ops::{Deref, DerefMut},
14 rc::Rc,
15 sync::Arc,
16 time::Duration,
17};
18
19mod color;
20mod registry;
21mod schema;
22mod theme_color;
23
24pub use color::*;
25pub use registry::*;
26pub use schema::*;
27pub use theme_color::*;
28
29pub fn init(cx: &mut App) {
30 registry::init(cx);
31
32 Theme::change(ThemeMode::Light, None, cx);
34 Theme::sync_scrollbar_appearance(cx);
35}
36
37pub trait ActiveTheme {
38 fn theme(&self) -> &Theme;
39}
40
41impl ActiveTheme for App {
42 #[inline(always)]
43 fn theme(&self) -> &Theme {
44 Theme::global(self)
45 }
46}
47
48fn default_true() -> bool {
49 true
50}
51
52const RADIUS_FULL: Pixels = px(9999.);
56
57const SCROLLBAR_IDLE: Duration = Duration::from_secs(2);
59const SCROLLBAR_ENTER: Duration = Duration::from_millis(300);
61const SCROLLBAR_EXIT: Duration = Duration::from_millis(500);
63const SCROLLBAR_EXPAND: Duration = Duration::from_millis(300);
65
66fn scrollbar_motion(mode: ScrollbarMode) -> gpui_base::ScrollbarMotion {
71 gpui_base::ScrollbarMotion::default()
72 .with_idle(SCROLLBAR_IDLE)
73 .with_enter(SCROLLBAR_ENTER)
74 .with_exit(SCROLLBAR_EXIT)
75 .with_expand(SCROLLBAR_EXPAND)
76 .with_entrance(gpui_base::ScrollbarEntrance::Fade)
77 .with_thumb_hover_entrance(match mode {
78 ScrollbarMode::Scrolling | ScrollbarMode::Always => gpui_base::ScrollbarEntrance::Fade,
79 ScrollbarMode::Hover => gpui_base::ScrollbarEntrance::SlideAndFade,
80 })
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
85pub struct Theme {
86 pub colors: ThemeColor,
87 #[serde(default)]
92 pub tokens: ThemeTokens,
93 pub highlight_theme: Arc<HighlightTheme>,
94 pub light_theme: Rc<ThemeConfig>,
95 pub dark_theme: Rc<ThemeConfig>,
96
97 pub mode: ThemeMode,
98 pub font_family: SharedString,
100 pub font_size: Pixels,
102 pub mono_font_family: SharedString,
110 pub mono_font_size: Pixels,
112 pub radius: Pixels,
114 pub radius_lg: Pixels,
116 pub shadow: bool,
117 #[serde(default = "default_true")]
124 pub focus_ring: bool,
125 #[schemars(schema_with = "gpui::hsla_schemar")]
126 pub transparent: Hsla,
127 #[serde(alias = "scrollbar_show")]
129 pub scrollbar_mode: ScrollbarMode,
130 #[serde(skip)]
132 pub notification: NotificationSettings,
133 pub tile_grid_size: Pixels,
135 pub tile_shadow: bool,
137 pub tile_radius: Pixels,
139 pub list: ListSettings,
141 pub sheet: SheetSettings,
143}
144
145impl Default for Theme {
146 fn default() -> Self {
147 Self::from(&ThemeColor::default())
148 }
149}
150
151impl Deref for Theme {
152 type Target = ThemeColor;
153
154 fn deref(&self) -> &Self::Target {
155 &self.colors
156 }
157}
158
159impl DerefMut for Theme {
160 fn deref_mut(&mut self) -> &mut Self::Target {
161 &mut self.colors
162 }
163}
164
165impl Global for Theme {}
166
167impl Theme {
168 #[inline(always)]
170 pub fn global(cx: &App) -> &Theme {
171 cx.global::<Theme>()
172 }
173
174 #[inline(always)]
180 pub fn global_mut(cx: &mut App) -> &mut Theme {
181 cx.global_mut::<Theme>()
182 }
183
184 #[inline(always)]
186 pub fn is_dark(&self) -> bool {
187 self.mode.is_dark()
188 }
189
190 pub fn theme_name(&self) -> &SharedString {
192 if self.is_dark() {
193 &self.dark_theme.name
194 } else {
195 &self.light_theme.name
196 }
197 }
198
199 pub fn sync_system_appearance(window: Option<&mut Window>, cx: &mut App) {
201 let appearance = window
204 .as_ref()
205 .map(|window| window.appearance())
206 .unwrap_or_else(|| cx.window_appearance());
207
208 Self::change(appearance, window, cx);
209 }
210
211 pub fn sync_scrollbar_appearance(cx: &mut App) {
213 let mode = if cx.should_auto_hide_scrollbars() {
214 ScrollbarMode::Scrolling
215 } else {
216 ScrollbarMode::Hover
217 };
218 Self::set_scrollbar_mode(mode, cx);
219 }
220
221 pub fn set_scrollbar_mode(mode: ScrollbarMode, cx: &mut App) {
223 Theme::global_mut(cx).scrollbar_mode = mode;
224 let base_theme = gpui_base::Theme::global_mut(cx);
225 base_theme.scrollbar = base_theme
226 .scrollbar
227 .clone()
228 .with_mode(mode)
229 .with_motion(scrollbar_motion(mode));
230 }
231
232 pub fn change(mode: impl Into<ThemeMode>, window: Option<&mut Window>, cx: &mut App) {
234 let mode = mode.into();
235 if !cx.has_global::<Theme>() {
236 let mut theme = Theme::default();
237 theme.light_theme = ThemeRegistry::global(cx).default_light_theme().clone();
238 theme.dark_theme = ThemeRegistry::global(cx).default_dark_theme().clone();
239 cx.set_global(theme);
240 }
241
242 let theme = cx.global_mut::<Theme>();
243 theme.mode = mode;
244 if mode.is_dark() {
245 theme.apply_config(&theme.dark_theme.clone());
246 } else {
247 theme.apply_config(&theme.light_theme.clone());
248 }
249
250 let base_theme = theme.base_theme();
251 cx.set_global(base_theme);
252
253 if let Some(window) = window {
254 window.refresh();
255 }
256 }
257
258 fn base_theme(&self) -> gpui_base::Theme {
261 gpui_base::Theme {
262 appearance: if self.mode.is_dark() {
263 gpui_base::ThemeAppearance::Dark
264 } else {
265 gpui_base::ThemeAppearance::Light
266 },
267 tokens: self.semantic_tokens(),
268 scrollbar: gpui_base::ScrollbarTheme::new()
269 .with_mode(self.scrollbar_mode)
270 .with_motion(scrollbar_motion(self.scrollbar_mode))
271 .with_styles(
272 gpui_base::ScrollbarStyles::default()
273 .track(|style| style.bg(self.scrollbar))
274 .track_hover(|style| style.bg(self.scrollbar))
275 .track_active(|style| style.bg(self.scrollbar).border_color(self.border))
276 .thumb(|style| style.bg(self.tokens.scrollbar_thumb).radius(self.radius))
277 .thumb_hover(|style| {
278 style
279 .bg(self.tokens.scrollbar_thumb_hover)
280 .radius(self.radius)
281 })
282 .thumb_active(|style| {
283 style
284 .bg(self.tokens.scrollbar_thumb_hover)
285 .radius(self.radius)
286 }),
287 ),
288 resizable: gpui_base::ResizableTheme {
289 handle: Some(self.border),
290 active_handle: Some(self.drag_border),
291 },
292 }
293 }
294
295 pub fn sync_base(cx: &mut App) {
314 let base_theme = Theme::global(cx).base_theme();
315 cx.set_global(base_theme);
316 }
317
318 #[inline]
323 pub fn input_background(&self) -> Hsla {
324 if self.is_dark() {
325 self.input.mix_oklab(self.transparent, 0.3)
326 } else {
327 self.background
328 }
329 }
330
331 #[inline]
333 pub(crate) fn editor_background(&self) -> Hsla {
334 self.highlight_theme
335 .style
336 .editor_background
337 .unwrap_or_else(|| self.input_background())
338 }
339
340 pub fn semantic_tokens(&self) -> SemanticThemeTokens {
344 SemanticThemeTokens {
345 colors: self.color_tokens(),
346 radius: self.radius_tokens(),
347 spacing: self.spacing_tokens(),
348 typography: self.typography_tokens(),
349 shadow: self.shadow_tokens(),
350 }
351 }
352
353 pub fn color_tokens(&self) -> ColorTokens {
354 ColorTokens {
355 background: self.background,
356 foreground: self.foreground,
357 surface: self.popover,
358 surface_foreground: self.popover_foreground,
359 primary: self.primary,
360 primary_foreground: self.primary_foreground,
361 secondary: self.secondary,
362 secondary_foreground: self.secondary_foreground,
363 muted: self.muted,
364 muted_foreground: self.muted_foreground,
365 accent: self.accent,
366 accent_foreground: self.accent_foreground,
367 destructive: self.danger,
368 destructive_foreground: self.danger_foreground,
369 border: self.border,
370 input: self.input,
371 ring: self.ring,
372 }
373 }
374
375 pub fn radius_full(&self) -> Pixels {
384 if self.radius.is_zero() {
385 px(0.)
386 } else {
387 RADIUS_FULL
388 }
389 }
390
391 pub fn radius_tokens(&self) -> RadiusTokens {
392 RadiusTokens {
393 none: px(0.),
394 sm: self.radius / 2.,
395 md: self.radius,
396 lg: self.radius_lg,
397 xl: self.radius * 2.,
398 full: RADIUS_FULL,
399 }
400 }
401
402 pub fn spacing_tokens(&self) -> SpacingTokens {
403 SpacingTokens::default()
404 }
405
406 pub fn typography_tokens(&self) -> TypographyTokens {
407 let mut tokens = TypographyTokens::default();
408 tokens.sans = self.font_family.clone();
409 tokens.mono = self.mono_font_family.clone();
410 tokens.md.size = self.font_size;
411 tokens.mono_md.size = self.mono_font_size;
412 tokens
413 }
414
415 pub fn shadow_tokens(&self) -> ShadowTokens {
416 if self.shadow {
417 ShadowTokens::elevations({
418 let mut color = self.transparent;
419 color.alpha = 0.18;
420 color
421 })
422 } else {
423 ShadowTokens::default()
424 }
425 }
426
427 pub fn apply_semantic_tokens(&mut self, tokens: &SemanticThemeTokens) {
431 let colors = tokens.colors;
432 self.background = colors.background;
433 self.foreground = colors.foreground;
434 self.popover = colors.surface;
435 self.popover_foreground = colors.surface_foreground;
436 self.primary = colors.primary;
437 self.primary_foreground = colors.primary_foreground;
438 self.secondary = colors.secondary;
439 self.secondary_foreground = colors.secondary_foreground;
440 self.muted = colors.muted;
441 self.muted_foreground = colors.muted_foreground;
442 self.accent = colors.accent;
443 self.accent_foreground = colors.accent_foreground;
444 self.danger = colors.destructive;
445 self.danger_foreground = colors.destructive_foreground;
446 self.border = colors.border;
447 self.input = colors.input;
448 self.ring = colors.ring;
449
450 self.tokens.background = colors.background.into();
451 self.tokens.popover = colors.surface.into();
452 self.tokens.primary = colors.primary.into();
453 self.tokens.secondary = colors.secondary.into();
454 self.tokens.muted = colors.muted.into();
455 self.tokens.accent = colors.accent.into();
456 self.tokens.danger = colors.destructive.into();
457
458 self.radius = tokens.radius.md;
459 self.radius_lg = tokens.radius.lg;
460 self.font_family = tokens.typography.sans.clone();
461 self.mono_font_family = tokens.typography.mono.clone();
462 self.font_size = tokens.typography.md.size;
463 self.mono_font_size = tokens.typography.mono_md.size;
464 self.shadow = !tokens.shadow.sm.is_empty()
465 || !tokens.shadow.md.is_empty()
466 || !tokens.shadow.lg.is_empty();
467 }
468
469 pub fn resolve_semantic_config(&self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
472 let mut tokens = self.semantic_tokens();
473 config.apply_to(&mut tokens);
474 tokens
475 }
476
477 pub fn apply_semantic_config(&mut self, config: &SemanticThemeConfig) -> SemanticThemeTokens {
480 let tokens = self.resolve_semantic_config(config);
481 self.apply_semantic_tokens(&tokens);
482 tokens
483 }
484
485 pub fn apply_semantic_config_str(
487 &mut self,
488 content: &str,
489 ) -> anyhow::Result<SemanticThemeTokens> {
490 let config = serde_json::from_str::<SemanticThemeConfigFile>(content)?;
491 Ok(self.apply_semantic_config(&config.tokens))
492 }
493}
494
495#[cfg(test)]
496mod semantic_token_tests {
497 use gpui::{Hsla, IsZero as _, px};
498
499 use super::{RADIUS_FULL, Theme};
500
501 fn with_alpha(mut color: Hsla, alpha: f32) -> Hsla {
502 color.alpha = alpha;
503 color
504 }
505
506 #[test]
507 fn semantic_colors_are_a_live_projection_of_legacy_fields() {
508 let mut theme = Theme::default();
509 let primary = with_alpha(Hsla::default(), 0.42);
510 theme.primary = primary;
511
512 assert_eq!(theme.color_tokens().primary, primary);
513 assert_eq!(theme.semantic_tokens().colors.primary, primary);
514 }
515
516 #[test]
517 fn applying_semantic_tokens_only_updates_generic_legacy_colors() {
518 let mut theme = Theme::default();
519 let component_color = theme.button_primary;
520 let mut tokens = theme.semantic_tokens();
521 tokens.colors.primary = with_alpha(Hsla::default(), 0.25);
522 tokens.colors.destructive = with_alpha(Hsla::default(), 0.75);
523 tokens.radius.md = px(10.);
524
525 theme.apply_semantic_tokens(&tokens);
526
527 assert_eq!(theme.primary, tokens.colors.primary);
528 assert_eq!(theme.tokens.primary.color, tokens.colors.primary);
529 assert_eq!(theme.danger, tokens.colors.destructive);
530 assert_eq!(theme.radius, px(10.));
531 assert_eq!(theme.button_primary, component_color);
532 }
533
534 #[test]
535 fn square_themes_square_off_pills_and_circles() {
536 let mut theme = Theme::default();
537 assert_eq!(theme.radius_full(), RADIUS_FULL);
538 assert_eq!(theme.radius_tokens().full, RADIUS_FULL);
539
540 theme.radius = px(0.);
543 assert_eq!(theme.radius_full(), px(0.));
544 }
545
546 #[test]
547 fn base_projection_carries_a_square_radius_to_the_scrollbar() {
548 let mut theme = Theme::default();
549 assert!(!theme.base_theme().tokens.radius.md.is_zero());
550
551 theme.radius = px(0.);
554 assert!(theme.base_theme().tokens.radius.md.is_zero());
555 }
556
557 #[test]
558 fn disabled_legacy_shadows_project_to_empty_elevations() {
559 let mut theme = Theme::default();
560 theme.shadow = false;
561
562 let shadows = theme.shadow_tokens();
563 assert!(shadows.sm.is_empty());
564 assert!(shadows.md.is_empty());
565 assert!(shadows.lg.is_empty());
566 }
567}
568
569impl From<&ThemeColor> for Theme {
570 fn from(colors: &ThemeColor) -> Self {
571 Theme {
572 mode: ThemeMode::default(),
573 transparent: gpui::transparent_black(),
574 font_family: ".SystemUIFont".into(),
575 font_size: px(16.),
576 mono_font_family: if cfg!(target_os = "macos") {
577 "Menlo".into()
579 } else if cfg!(target_os = "windows") {
580 "Consolas".into()
581 } else {
582 "DejaVu Sans Mono".into()
583 },
584 mono_font_size: px(13.),
585 radius: px(6.),
586 radius_lg: px(8.),
587 shadow: true,
588 focus_ring: true,
589 scrollbar_mode: ScrollbarMode::default(),
590 notification: NotificationSettings::default(),
591 tile_grid_size: px(8.),
592 tile_shadow: true,
593 tile_radius: px(0.),
594 list: ListSettings::default(),
595 colors: *colors,
596 tokens: ThemeTokens::from(colors),
597 light_theme: Rc::new(ThemeConfig::default()),
598 dark_theme: Rc::new(ThemeConfig::default()),
599 highlight_theme: HighlightTheme::default_light(),
600 sheet: SheetSettings::default(),
601 }
602 }
603}
604
605#[derive(
606 Debug,
607 Clone,
608 Copy,
609 Default,
610 PartialEq,
611 PartialOrd,
612 Eq,
613 Ord,
614 Hash,
615 Serialize,
616 Deserialize,
617 JsonSchema,
618)]
619#[serde(rename_all = "snake_case")]
620pub enum ThemeMode {
621 #[default]
622 Light,
623 Dark,
624}
625
626impl ThemeMode {
627 #[inline(always)]
628 pub fn is_dark(&self) -> bool {
629 matches!(self, Self::Dark)
630 }
631
632 pub fn name(&self) -> &'static str {
634 match self {
635 ThemeMode::Light => "light",
636 ThemeMode::Dark => "dark",
637 }
638 }
639}
640
641impl From<WindowAppearance> for ThemeMode {
642 fn from(appearance: WindowAppearance) -> Self {
643 match appearance {
644 WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
645 WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
646 }
647 }
648}
649
650#[cfg(test)]
651mod base_theme_projection_tests {
652 use super::*;
653 use gpui::TestAppContext;
654
655 #[gpui::test]
656 fn base_theme_tracks_initialization_and_mode_changes(cx: &mut TestAppContext) {
657 cx.update(|cx| {
658 init(cx);
659 assert_styled_projection(cx);
660
661 Theme::change(ThemeMode::Dark, None, cx);
662 assert_styled_projection(cx);
663
664 Theme::set_scrollbar_mode(ScrollbarMode::Always, cx);
665 assert_eq!(Theme::global(cx).scrollbar_mode, ScrollbarMode::Always);
666 assert_eq!(
667 gpui_base::Theme::global(cx).scrollbar.mode(),
668 gpui_base::ScrollbarMode::Always
669 );
670 assert_styled_projection(cx);
671 });
672 }
673
674 #[gpui::test]
675 fn scrollbar_motion_is_owned_here_and_projected_onto_base(cx: &mut TestAppContext) {
676 cx.update(|cx| {
677 init(cx);
678
679 let bare = gpui_base::ScrollbarMotion::default();
681 assert_eq!(bare.enter(), Duration::ZERO);
682 assert_eq!(bare.exit(), Duration::ZERO);
683 assert_eq!(bare.expand(), Duration::ZERO);
684
685 Theme::set_scrollbar_mode(ScrollbarMode::Scrolling, cx);
686 let motion = gpui_base::Theme::global(cx).scrollbar.motion();
687 assert_eq!(motion.idle(), SCROLLBAR_IDLE);
688 assert_eq!(motion.enter(), SCROLLBAR_ENTER);
689 assert_eq!(motion.exit(), SCROLLBAR_EXIT);
690 assert_eq!(motion.expand(), SCROLLBAR_EXPAND);
691 assert_eq!(
692 motion.entrance(),
693 gpui_base::ScrollbarEntrance::Fade,
694 "scroll-revealed scrollbars fade in without sliding"
695 );
696
697 Theme::set_scrollbar_mode(ScrollbarMode::Hover, cx);
698 let motion = gpui_base::Theme::global(cx).scrollbar.motion();
699 assert_eq!(motion.entrance(), gpui_base::ScrollbarEntrance::Fade);
700 assert_eq!(
701 motion.thumb_hover_entrance(),
702 gpui_base::ScrollbarEntrance::SlideAndFade
703 );
704 });
705 }
706
707 fn assert_styled_projection(cx: &App) {
708 let theme = Theme::global(cx);
709 let base = gpui_base::Theme::global(cx);
710
711 assert_eq!(base.tokens, theme.semantic_tokens());
712 assert_eq!(base.scrollbar.mode(), theme.scrollbar_mode);
713 assert_eq!(
714 base.scrollbar.motion(),
715 scrollbar_motion(theme.scrollbar_mode)
716 );
717 assert_eq!(base.resizable.handle, Some(theme.border));
718 assert_eq!(base.resizable.active_handle, Some(theme.drag_border));
719 }
720}