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::DEFAULT_DARK_THEME;
 26use ::settings::IntoGpui;
 27use ::settings::Settings;
 28use ::settings::SettingsStore;
 29use anyhow::Result;
 30use fallback_themes::apply_status_color_defaults;
 31use fs::Fs;
 32use gpui::BorrowAppContext;
 33use gpui::Global;
 34use gpui::{
 35    App, AssetSource, HighlightStyle, Hsla, Pixels, Refineable, SharedString, WindowAppearance,
 36    WindowBackgroundAppearance, px,
 37};
 38use serde::Deserialize;
 39use uuid::Uuid;
 40
 41pub use crate::default_colors::*;
 42use crate::fallback_themes::apply_theme_color_defaults;
 43pub use crate::font_family_cache::*;
 44pub use crate::icon_theme::*;
 45pub use crate::icon_theme_schema::*;
 46pub use crate::registry::*;
 47pub use crate::scale::*;
 48pub use crate::schema::*;
 49pub use crate::settings::*;
 50pub use crate::styles::*;
 51pub use ::settings::{
 52    FontStyleContent, HighlightStyleContent, StatusColorsContent, ThemeColorsContent,
 53    ThemeStyleContent,
 54};
 55
 56/// Defines window border radius for platforms that use client side decorations.
 57pub const CLIENT_SIDE_DECORATION_ROUNDING: Pixels = px(10.0);
 58/// Defines window shadow size for platforms that use client side decorations.
 59pub const CLIENT_SIDE_DECORATION_SHADOW: Pixels = px(10.0);
 60
 61/// The appearance of the theme.
 62#[derive(Debug, PartialEq, Clone, Copy, Deserialize)]
 63pub enum Appearance {
 64    /// A light appearance.
 65    Light,
 66    /// A dark appearance.
 67    Dark,
 68}
 69
 70impl Appearance {
 71    /// Returns whether the appearance is light.
 72    pub fn is_light(&self) -> bool {
 73        match self {
 74            Self::Light => true,
 75            Self::Dark => false,
 76        }
 77    }
 78}
 79
 80impl From<WindowAppearance> for Appearance {
 81    fn from(value: WindowAppearance) -> Self {
 82        match value {
 83            WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
 84            WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
 85        }
 86    }
 87}
 88
 89impl From<Appearance> for ThemeAppearanceMode {
 90    fn from(value: Appearance) -> Self {
 91        match value {
 92            Appearance::Light => Self::Light,
 93            Appearance::Dark => Self::Dark,
 94        }
 95    }
 96}
 97
 98/// Which themes should be loaded. This is used primarily for testing.
 99pub enum LoadThemes {
100    /// Only load the base theme.
101    ///
102    /// No user themes will be loaded.
103    JustBase,
104
105    /// Load all of the built-in themes.
106    All(Box<dyn AssetSource>),
107}
108
109/// Initialize the theme system.
110pub fn init(themes_to_load: LoadThemes, cx: &mut App) {
111    SystemAppearance::init(cx);
112    let (assets, load_user_themes) = match themes_to_load {
113        LoadThemes::JustBase => (Box::new(()) as Box<dyn AssetSource>, false),
114        LoadThemes::All(assets) => (assets, true),
115    };
116    ThemeRegistry::set_global(assets, cx);
117
118    if load_user_themes {
119        ThemeRegistry::global(cx).load_bundled_themes();
120    }
121
122    FontFamilyCache::init_global(cx);
123
124    let theme = GlobalTheme::configured_theme(cx);
125    let icon_theme = GlobalTheme::configured_icon_theme(cx);
126    cx.set_global(GlobalTheme { theme, icon_theme });
127
128    let settings = ThemeSettings::get_global(cx);
129
130    let mut prev_buffer_font_size_settings = settings.buffer_font_size_settings();
131    let mut prev_ui_font_size_settings = settings.ui_font_size_settings();
132    let mut prev_agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
133    let mut prev_agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
134    let mut prev_theme_name = settings.theme.name(SystemAppearance::global(cx).0);
135    let mut prev_icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
136    let mut prev_theme_overrides = (
137        settings.experimental_theme_overrides.clone(),
138        settings.theme_overrides.clone(),
139    );
140
141    cx.observe_global::<SettingsStore>(move |cx| {
142        let settings = ThemeSettings::get_global(cx);
143
144        let buffer_font_size_settings = settings.buffer_font_size_settings();
145        let ui_font_size_settings = settings.ui_font_size_settings();
146        let agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
147        let agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
148        let theme_name = settings.theme.name(SystemAppearance::global(cx).0);
149        let icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
150        let theme_overrides = (
151            settings.experimental_theme_overrides.clone(),
152            settings.theme_overrides.clone(),
153        );
154
155        if buffer_font_size_settings != prev_buffer_font_size_settings {
156            prev_buffer_font_size_settings = buffer_font_size_settings;
157            reset_buffer_font_size(cx);
158        }
159
160        if ui_font_size_settings != prev_ui_font_size_settings {
161            prev_ui_font_size_settings = ui_font_size_settings;
162            reset_ui_font_size(cx);
163        }
164
165        if agent_ui_font_size_settings != prev_agent_ui_font_size_settings {
166            prev_agent_ui_font_size_settings = agent_ui_font_size_settings;
167            reset_agent_ui_font_size(cx);
168        }
169
170        if agent_buffer_font_size_settings != prev_agent_buffer_font_size_settings {
171            prev_agent_buffer_font_size_settings = agent_buffer_font_size_settings;
172            reset_agent_buffer_font_size(cx);
173        }
174
175        if theme_name != prev_theme_name || theme_overrides != prev_theme_overrides {
176            prev_theme_name = theme_name;
177            prev_theme_overrides = theme_overrides;
178            GlobalTheme::reload_theme(cx);
179        }
180
181        if icon_theme_name != prev_icon_theme_name {
182            prev_icon_theme_name = icon_theme_name;
183            GlobalTheme::reload_icon_theme(cx);
184        }
185    })
186    .detach();
187}
188
189/// Implementing this trait allows accessing the active theme.
190pub trait ActiveTheme {
191    /// Returns the active theme.
192    fn theme(&self) -> &Arc<Theme>;
193}
194
195impl ActiveTheme for App {
196    fn theme(&self) -> &Arc<Theme> {
197        GlobalTheme::theme(self)
198    }
199}
200
201/// A theme family is a grouping of themes under a single name.
202///
203/// For example, the "One" theme family contains the "One Light" and "One Dark" themes.
204///
205/// It can also be used to package themes with many variants.
206///
207/// For example, the "Atelier" theme family contains "Cave", "Dune", "Estuary", "Forest", "Heath", etc.
208pub struct ThemeFamily {
209    /// The unique identifier for the theme family.
210    pub id: String,
211    /// The name of the theme family. This will be displayed in the UI, such as when adding or removing a theme family.
212    pub name: SharedString,
213    /// The author of the theme family.
214    pub author: SharedString,
215    /// The [Theme]s in the family.
216    pub themes: Vec<Theme>,
217    /// The color scales used by the themes in the family.
218    /// Note: This will be removed in the future.
219    pub scales: ColorScales,
220}
221
222impl ThemeFamily {
223    // This is on ThemeFamily because we will have variables here we will need
224    // in the future to resolve @references.
225    /// Refines ThemeContent into a theme, merging it's contents with the base theme.
226    pub fn refine_theme(&self, theme: &ThemeContent) -> Theme {
227        let appearance = match theme.appearance {
228            AppearanceContent::Light => Appearance::Light,
229            AppearanceContent::Dark => Appearance::Dark,
230        };
231
232        let mut refined_status_colors = match theme.appearance {
233            AppearanceContent::Light => StatusColors::light(),
234            AppearanceContent::Dark => StatusColors::dark(),
235        };
236        let mut status_colors_refinement = status_colors_refinement(&theme.style.status);
237        apply_status_color_defaults(&mut status_colors_refinement);
238        refined_status_colors.refine(&status_colors_refinement);
239
240        let mut refined_player_colors = match theme.appearance {
241            AppearanceContent::Light => PlayerColors::light(),
242            AppearanceContent::Dark => PlayerColors::dark(),
243        };
244        refined_player_colors.merge(&theme.style.players);
245
246        let mut refined_theme_colors = match theme.appearance {
247            AppearanceContent::Light => ThemeColors::light(),
248            AppearanceContent::Dark => ThemeColors::dark(),
249        };
250        let mut theme_colors_refinement =
251            theme_colors_refinement(&theme.style.colors, &status_colors_refinement);
252        apply_theme_color_defaults(&mut theme_colors_refinement, &refined_player_colors);
253        refined_theme_colors.refine(&theme_colors_refinement);
254
255        let mut refined_accent_colors = match theme.appearance {
256            AppearanceContent::Light => AccentColors::light(),
257            AppearanceContent::Dark => AccentColors::dark(),
258        };
259        refined_accent_colors.merge(&theme.style.accents);
260
261        let syntax_highlights = theme.style.syntax.iter().map(|(syntax_token, highlight)| {
262            (
263                syntax_token.clone(),
264                HighlightStyle {
265                    color: highlight
266                        .color
267                        .as_ref()
268                        .and_then(|color| try_parse_color(color).ok()),
269                    background_color: highlight
270                        .background_color
271                        .as_ref()
272                        .and_then(|color| try_parse_color(color).ok()),
273                    font_style: highlight.font_style.map(|s| s.into_gpui()),
274                    font_weight: highlight.font_weight.map(|w| w.into_gpui()),
275                    ..Default::default()
276                },
277            )
278        });
279        let syntax_theme = Arc::new(SyntaxTheme::new(syntax_highlights));
280
281        let window_background_appearance = theme
282            .style
283            .window_background_appearance
284            .map(|w| w.into_gpui())
285            .unwrap_or_default();
286
287        Theme {
288            id: uuid::Uuid::new_v4().to_string(),
289            name: theme.name.clone().into(),
290            appearance,
291            styles: ThemeStyles {
292                system: SystemColors::default(),
293                window_background_appearance,
294                accents: refined_accent_colors,
295                colors: refined_theme_colors,
296                status: refined_status_colors,
297                player: refined_player_colors,
298                syntax: syntax_theme,
299            },
300        }
301    }
302}
303
304/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
305pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
306    let id = Uuid::new_v4().to_string();
307    let name = theme_family_content.name.clone();
308    let author = theme_family_content.author.clone();
309
310    let mut theme_family = ThemeFamily {
311        id,
312        name: name.into(),
313        author: author.into(),
314        themes: vec![],
315        scales: default_color_scales(),
316    };
317
318    let refined_themes = theme_family_content
319        .themes
320        .iter()
321        .map(|theme_content| theme_family.refine_theme(theme_content))
322        .collect();
323
324    theme_family.themes = refined_themes;
325
326    theme_family
327}
328
329/// A theme is the primary mechanism for defining the appearance of the UI.
330#[derive(Clone, Debug, PartialEq)]
331pub struct Theme {
332    /// The unique identifier for the theme.
333    pub id: String,
334    /// The name of the theme.
335    pub name: SharedString,
336    /// The appearance of the theme (light or dark).
337    pub appearance: Appearance,
338    /// The colors and other styles for the theme.
339    pub styles: ThemeStyles,
340}
341
342impl Theme {
343    /// Returns the [`SystemColors`] for the theme.
344    #[inline(always)]
345    pub fn system(&self) -> &SystemColors {
346        &self.styles.system
347    }
348
349    /// Returns the [`AccentColors`] for the theme.
350    #[inline(always)]
351    pub fn accents(&self) -> &AccentColors {
352        &self.styles.accents
353    }
354
355    /// Returns the [`PlayerColors`] for the theme.
356    #[inline(always)]
357    pub fn players(&self) -> &PlayerColors {
358        &self.styles.player
359    }
360
361    /// Returns the [`ThemeColors`] for the theme.
362    #[inline(always)]
363    pub fn colors(&self) -> &ThemeColors {
364        &self.styles.colors
365    }
366
367    /// Returns the [`SyntaxTheme`] for the theme.
368    #[inline(always)]
369    pub fn syntax(&self) -> &Arc<SyntaxTheme> {
370        &self.styles.syntax
371    }
372
373    /// Returns the [`StatusColors`] for the theme.
374    #[inline(always)]
375    pub fn status(&self) -> &StatusColors {
376        &self.styles.status
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}