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