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