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