theme.rs

  1#![deny(missing_docs)]
  2
  3//! # Theme
  4//!
  5//! This crate provides the theme system for Zed.
  6//!
  7//! ## Overview
  8//!
  9//! A theme is a collection of colors used to build a consistent appearance for UI components across the application.
 10
 11mod default_colors;
 12mod fallback_themes;
 13mod font_family_cache;
 14mod icon_theme;
 15mod icon_theme_schema;
 16mod registry;
 17mod scale;
 18mod schema;
 19mod settings;
 20mod styles;
 21
 22use std::path::Path;
 23use std::sync::Arc;
 24
 25use ::settings::Settings;
 26use ::settings::SettingsStore;
 27use anyhow::Result;
 28use fallback_themes::apply_status_color_defaults;
 29use fs::Fs;
 30use gpui::BorrowAppContext;
 31use gpui::Global;
 32use gpui::{
 33    App, AssetSource, HighlightStyle, Hsla, Pixels, Refineable, SharedString, WindowAppearance,
 34    WindowBackgroundAppearance, px,
 35};
 36use serde::Deserialize;
 37use uuid::Uuid;
 38
 39pub use crate::default_colors::*;
 40use crate::fallback_themes::apply_theme_color_defaults;
 41pub use crate::font_family_cache::*;
 42pub use crate::icon_theme::*;
 43pub use crate::icon_theme_schema::*;
 44pub use crate::registry::*;
 45pub use crate::scale::*;
 46pub use crate::schema::*;
 47pub use crate::settings::*;
 48pub use crate::styles::*;
 49pub use ::settings::{
 50    FontStyleContent, HighlightStyleContent, StatusColorsContent, ThemeColorsContent,
 51    ThemeStyleContent,
 52};
 53
 54/// Defines window border radius for platforms that use client side decorations.
 55pub const CLIENT_SIDE_DECORATION_ROUNDING: Pixels = px(10.0);
 56/// Defines window shadow size for platforms that use client side decorations.
 57pub const CLIENT_SIDE_DECORATION_SHADOW: Pixels = px(10.0);
 58
 59/// The appearance of the theme.
 60#[derive(Debug, PartialEq, Clone, Copy, Deserialize)]
 61pub enum Appearance {
 62    /// A light appearance.
 63    Light,
 64    /// A dark appearance.
 65    Dark,
 66}
 67
 68impl Appearance {
 69    /// Returns whether the appearance is light.
 70    pub fn is_light(&self) -> bool {
 71        match self {
 72            Self::Light => true,
 73            Self::Dark => false,
 74        }
 75    }
 76}
 77
 78impl From<WindowAppearance> for Appearance {
 79    fn from(value: WindowAppearance) -> Self {
 80        match value {
 81            WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
 82            WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
 83        }
 84    }
 85}
 86
 87/// Which themes should be loaded. This is used primarily for testing.
 88pub enum LoadThemes {
 89    /// Only load the base theme.
 90    ///
 91    /// No user themes will be loaded.
 92    JustBase,
 93
 94    /// Load all of the built-in themes.
 95    All(Box<dyn AssetSource>),
 96}
 97
 98/// Initialize the theme system.
 99pub fn init(themes_to_load: LoadThemes, cx: &mut App) {
100    SystemAppearance::init(cx);
101    let (assets, load_user_themes) = match themes_to_load {
102        LoadThemes::JustBase => (Box::new(()) as Box<dyn AssetSource>, false),
103        LoadThemes::All(assets) => (assets, true),
104    };
105    ThemeRegistry::set_global(assets, cx);
106
107    if load_user_themes {
108        ThemeRegistry::global(cx).load_bundled_themes();
109    }
110
111    FontFamilyCache::init_global(cx);
112
113    let theme = GlobalTheme::configured_theme(cx);
114    let icon_theme = GlobalTheme::configured_icon_theme(cx);
115    cx.set_global(GlobalTheme { theme, icon_theme });
116
117    let settings = ThemeSettings::get_global(cx);
118
119    let mut prev_buffer_font_size_settings = settings.buffer_font_size_settings();
120    let mut prev_ui_font_size_settings = settings.ui_font_size_settings();
121    let mut prev_agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
122    let mut prev_agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
123    let mut prev_theme_name = settings.theme.name(SystemAppearance::global(cx).0);
124    let mut prev_icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
125    let mut prev_theme_overrides = (
126        settings.experimental_theme_overrides.clone(),
127        settings.theme_overrides.clone(),
128    );
129
130    cx.observe_global::<SettingsStore>(move |cx| {
131        let settings = ThemeSettings::get_global(cx);
132
133        let buffer_font_size_settings = settings.buffer_font_size_settings();
134        let ui_font_size_settings = settings.ui_font_size_settings();
135        let agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
136        let agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
137        let theme_name = settings.theme.name(SystemAppearance::global(cx).0);
138        let icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
139        let theme_overrides = (
140            settings.experimental_theme_overrides.clone(),
141            settings.theme_overrides.clone(),
142        );
143
144        if buffer_font_size_settings != prev_buffer_font_size_settings {
145            prev_buffer_font_size_settings = buffer_font_size_settings;
146            reset_buffer_font_size(cx);
147        }
148
149        if ui_font_size_settings != prev_ui_font_size_settings {
150            prev_ui_font_size_settings = ui_font_size_settings;
151            reset_ui_font_size(cx);
152        }
153
154        if agent_ui_font_size_settings != prev_agent_ui_font_size_settings {
155            prev_agent_ui_font_size_settings = agent_ui_font_size_settings;
156            reset_agent_ui_font_size(cx);
157        }
158
159        if agent_buffer_font_size_settings != prev_agent_buffer_font_size_settings {
160            prev_agent_buffer_font_size_settings = agent_buffer_font_size_settings;
161            reset_agent_buffer_font_size(cx);
162        }
163
164        if theme_name != prev_theme_name || theme_overrides != prev_theme_overrides {
165            prev_theme_name = theme_name;
166            prev_theme_overrides = theme_overrides;
167            GlobalTheme::reload_theme(cx);
168        }
169
170        if icon_theme_name != prev_icon_theme_name {
171            prev_icon_theme_name = icon_theme_name;
172            GlobalTheme::reload_icon_theme(cx);
173        }
174    })
175    .detach();
176}
177
178/// Implementing this trait allows accessing the active theme.
179pub trait ActiveTheme {
180    /// Returns the active theme.
181    fn theme(&self) -> &Arc<Theme>;
182}
183
184impl ActiveTheme for App {
185    fn theme(&self) -> &Arc<Theme> {
186        GlobalTheme::theme(self)
187    }
188}
189
190/// A theme family is a grouping of themes under a single name.
191///
192/// For example, the "One" theme family contains the "One Light" and "One Dark" themes.
193///
194/// It can also be used to package themes with many variants.
195///
196/// For example, the "Atelier" theme family contains "Cave", "Dune", "Estuary", "Forest", "Heath", etc.
197pub struct ThemeFamily {
198    /// The unique identifier for the theme family.
199    pub id: String,
200    /// The name of the theme family. This will be displayed in the UI, such as when adding or removing a theme family.
201    pub name: SharedString,
202    /// The author of the theme family.
203    pub author: SharedString,
204    /// The [Theme]s in the family.
205    pub themes: Vec<Theme>,
206    /// The color scales used by the themes in the family.
207    /// Note: This will be removed in the future.
208    pub scales: ColorScales,
209}
210
211impl ThemeFamily {
212    // This is on ThemeFamily because we will have variables here we will need
213    // in the future to resolve @references.
214    /// Refines ThemeContent into a theme, merging it's contents with the base theme.
215    pub fn refine_theme(&self, theme: &ThemeContent) -> Theme {
216        let appearance = match theme.appearance {
217            AppearanceContent::Light => Appearance::Light,
218            AppearanceContent::Dark => Appearance::Dark,
219        };
220
221        let mut refined_status_colors = match theme.appearance {
222            AppearanceContent::Light => StatusColors::light(),
223            AppearanceContent::Dark => StatusColors::dark(),
224        };
225        let mut status_colors_refinement = status_colors_refinement(&theme.style.status);
226        apply_status_color_defaults(&mut status_colors_refinement);
227        refined_status_colors.refine(&status_colors_refinement);
228
229        let mut refined_player_colors = match theme.appearance {
230            AppearanceContent::Light => PlayerColors::light(),
231            AppearanceContent::Dark => PlayerColors::dark(),
232        };
233        refined_player_colors.merge(&theme.style.players);
234
235        let mut refined_theme_colors = match theme.appearance {
236            AppearanceContent::Light => ThemeColors::light(),
237            AppearanceContent::Dark => ThemeColors::dark(),
238        };
239        let mut theme_colors_refinement =
240            theme_colors_refinement(&theme.style.colors, &status_colors_refinement);
241        apply_theme_color_defaults(&mut theme_colors_refinement, &refined_player_colors);
242        refined_theme_colors.refine(&theme_colors_refinement);
243
244        let mut refined_accent_colors = match theme.appearance {
245            AppearanceContent::Light => AccentColors::light(),
246            AppearanceContent::Dark => AccentColors::dark(),
247        };
248        refined_accent_colors.merge(&theme.style.accents);
249
250        let syntax_highlights = theme
251            .style
252            .syntax
253            .iter()
254            .map(|(syntax_token, highlight)| {
255                (
256                    syntax_token.clone(),
257                    HighlightStyle {
258                        color: highlight
259                            .color
260                            .as_ref()
261                            .and_then(|color| try_parse_color(color).ok()),
262                        background_color: highlight
263                            .background_color
264                            .as_ref()
265                            .and_then(|color| try_parse_color(color).ok()),
266                        font_style: highlight.font_style.map(Into::into),
267                        font_weight: highlight.font_weight.map(Into::into),
268                        ..Default::default()
269                    },
270                )
271            })
272            .collect::<Vec<_>>();
273        let syntax_theme = SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
274
275        let window_background_appearance = theme
276            .style
277            .window_background_appearance
278            .map(Into::into)
279            .unwrap_or_default();
280
281        Theme {
282            id: uuid::Uuid::new_v4().to_string(),
283            name: theme.name.clone().into(),
284            appearance,
285            styles: ThemeStyles {
286                system: SystemColors::default(),
287                window_background_appearance,
288                accents: refined_accent_colors,
289                colors: refined_theme_colors,
290                status: refined_status_colors,
291                player: refined_player_colors,
292                syntax: syntax_theme,
293            },
294        }
295    }
296}
297
298/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
299pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
300    let id = Uuid::new_v4().to_string();
301    let name = theme_family_content.name.clone();
302    let author = theme_family_content.author.clone();
303
304    let mut theme_family = ThemeFamily {
305        id,
306        name: name.into(),
307        author: author.into(),
308        themes: vec![],
309        scales: default_color_scales(),
310    };
311
312    let refined_themes = theme_family_content
313        .themes
314        .iter()
315        .map(|theme_content| theme_family.refine_theme(theme_content))
316        .collect();
317
318    theme_family.themes = refined_themes;
319
320    theme_family
321}
322
323/// A theme is the primary mechanism for defining the appearance of the UI.
324#[derive(Clone, Debug, PartialEq)]
325pub struct Theme {
326    /// The unique identifier for the theme.
327    pub id: String,
328    /// The name of the theme.
329    pub name: SharedString,
330    /// The appearance of the theme (light or dark).
331    pub appearance: Appearance,
332    /// The colors and other styles for the theme.
333    pub styles: ThemeStyles,
334}
335
336impl Theme {
337    /// Returns the [`SystemColors`] for the theme.
338    #[inline(always)]
339    pub fn system(&self) -> &SystemColors {
340        &self.styles.system
341    }
342
343    /// Returns the [`AccentColors`] for the theme.
344    #[inline(always)]
345    pub fn accents(&self) -> &AccentColors {
346        &self.styles.accents
347    }
348
349    /// Returns the [`PlayerColors`] for the theme.
350    #[inline(always)]
351    pub fn players(&self) -> &PlayerColors {
352        &self.styles.player
353    }
354
355    /// Returns the [`ThemeColors`] for the theme.
356    #[inline(always)]
357    pub fn colors(&self) -> &ThemeColors {
358        &self.styles.colors
359    }
360
361    /// Returns the [`SyntaxTheme`] for the theme.
362    #[inline(always)]
363    pub fn syntax(&self) -> &Arc<SyntaxTheme> {
364        &self.styles.syntax
365    }
366
367    /// Returns the [`StatusColors`] for the theme.
368    #[inline(always)]
369    pub fn status(&self) -> &StatusColors {
370        &self.styles.status
371    }
372
373    /// Returns the color for the syntax node with the given name.
374    #[inline(always)]
375    pub fn syntax_color(&self, name: &str) -> Hsla {
376        self.syntax().color(name)
377    }
378
379    /// Returns the [`Appearance`] for the theme.
380    #[inline(always)]
381    pub fn appearance(&self) -> Appearance {
382        self.appearance
383    }
384
385    /// Returns the [`WindowBackgroundAppearance`] for the theme.
386    #[inline(always)]
387    pub fn window_background_appearance(&self) -> WindowBackgroundAppearance {
388        self.styles.window_background_appearance
389    }
390
391    /// Darkens the color by reducing its lightness.
392    /// The resulting lightness is clamped to ensure it doesn't go below 0.0.
393    ///
394    /// The first value darkens light appearance mode, the second darkens appearance dark mode.
395    ///
396    /// Note: This is a tentative solution and may be replaced with a more robust color system.
397    pub fn darken(&self, color: Hsla, light_amount: f32, dark_amount: f32) -> Hsla {
398        let amount = match self.appearance {
399            Appearance::Light => light_amount,
400            Appearance::Dark => dark_amount,
401        };
402        let mut hsla = color;
403        hsla.l = (hsla.l - amount).max(0.0);
404        hsla
405    }
406}
407
408/// Asynchronously reads the user theme from the specified path.
409pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
410    let bytes = fs.load_bytes(theme_path).await?;
411    let theme_family: ThemeFamilyContent = serde_json_lenient::from_slice(&bytes)?;
412
413    for theme in &theme_family.themes {
414        if theme
415            .style
416            .colors
417            .deprecated_scrollbar_thumb_background
418            .is_some()
419        {
420            log::warn!(
421                r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
422                theme_name = theme.name
423            )
424        }
425    }
426
427    Ok(theme_family)
428}
429
430/// Asynchronously reads the icon theme from the specified path.
431pub async fn read_icon_theme(
432    icon_theme_path: &Path,
433    fs: Arc<dyn Fs>,
434) -> Result<IconThemeFamilyContent> {
435    let bytes = fs.load_bytes(icon_theme_path).await?;
436    let icon_theme_family: IconThemeFamilyContent = serde_json_lenient::from_slice(&bytes)?;
437
438    Ok(icon_theme_family)
439}
440
441/// The active theme
442pub struct GlobalTheme {
443    theme: Arc<Theme>,
444    icon_theme: Arc<IconTheme>,
445}
446impl Global for GlobalTheme {}
447
448impl GlobalTheme {
449    fn configured_theme(cx: &mut App) -> Arc<Theme> {
450        let themes = ThemeRegistry::default_global(cx);
451        let theme_settings = ThemeSettings::get_global(cx);
452        let system_appearance = SystemAppearance::global(cx);
453
454        let theme_name = theme_settings.theme.name(*system_appearance);
455
456        let theme = match themes.get(&theme_name.0) {
457            Ok(theme) => theme,
458            Err(err) => {
459                if themes.extensions_loaded() {
460                    log::error!("{err}");
461                }
462                themes
463                    .get(default_theme(*system_appearance))
464                    // fallback for tests.
465                    .unwrap_or_else(|_| themes.get(DEFAULT_DARK_THEME).unwrap())
466            }
467        };
468        theme_settings.apply_theme_overrides(theme)
469    }
470
471    /// Reloads the current theme.
472    ///
473    /// Reads the [`ThemeSettings`] to know which theme should be loaded,
474    /// taking into account the current [`SystemAppearance`].
475    pub fn reload_theme(cx: &mut App) {
476        let theme = Self::configured_theme(cx);
477        cx.update_global::<Self, _>(|this, _| this.theme = theme);
478        cx.refresh_windows();
479    }
480
481    fn configured_icon_theme(cx: &mut App) -> Arc<IconTheme> {
482        let themes = ThemeRegistry::default_global(cx);
483        let theme_settings = ThemeSettings::get_global(cx);
484        let system_appearance = SystemAppearance::global(cx);
485
486        let icon_theme_name = theme_settings.icon_theme.name(*system_appearance);
487
488        match themes.get_icon_theme(&icon_theme_name.0) {
489            Ok(theme) => theme,
490            Err(err) => {
491                if themes.extensions_loaded() {
492                    log::error!("{err}");
493                }
494                themes.get_icon_theme(DEFAULT_ICON_THEME_NAME).unwrap()
495            }
496        }
497    }
498
499    /// Reloads the current icon theme.
500    ///
501    /// Reads the [`ThemeSettings`] to know which icon theme should be loaded,
502    /// taking into account the current [`SystemAppearance`].
503    pub fn reload_icon_theme(cx: &mut App) {
504        let icon_theme = Self::configured_icon_theme(cx);
505        cx.update_global::<Self, _>(|this, _| this.icon_theme = icon_theme);
506        cx.refresh_windows();
507    }
508
509    /// the active theme
510    pub fn theme(cx: &App) -> &Arc<Theme> {
511        &cx.global::<Self>().theme
512    }
513
514    /// the active icon theme
515    pub fn icon_theme(cx: &App) -> &Arc<IconTheme> {
516        &cx.global::<Self>().icon_theme
517    }
518}