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