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::*;
 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_settings =
107        ThemeSettings::get_global(cx).buffer_font_size_settings();
108    let mut prev_ui_font_size_settings = ThemeSettings::get_global(cx).ui_font_size_settings();
109    cx.observe_global::<SettingsStore>(move |cx| {
110        let buffer_font_size_settings = ThemeSettings::get_global(cx).buffer_font_size_settings();
111        if buffer_font_size_settings != prev_buffer_font_size_settings {
112            prev_buffer_font_size_settings = buffer_font_size_settings;
113            reset_buffer_font_size(cx);
114        }
115
116        let ui_font_size_settings = ThemeSettings::get_global(cx).ui_font_size_settings();
117        if ui_font_size_settings != prev_ui_font_size_settings {
118            prev_ui_font_size_settings = ui_font_size_settings;
119            reset_ui_font_size(cx);
120        }
121    })
122    .detach();
123}
124
125/// Implementing this trait allows accessing the active theme.
126pub trait ActiveTheme {
127    /// Returns the active theme.
128    fn theme(&self) -> &Arc<Theme>;
129}
130
131impl ActiveTheme for App {
132    fn theme(&self) -> &Arc<Theme> {
133        &ThemeSettings::get_global(self).active_theme
134    }
135}
136
137/// A theme family is a grouping of themes under a single name.
138///
139/// For example, the "One" theme family contains the "One Light" and "One Dark" themes.
140///
141/// It can also be used to package themes with many variants.
142///
143/// For example, the "Atelier" theme family contains "Cave", "Dune", "Estuary", "Forest", "Heath", etc.
144pub struct ThemeFamily {
145    /// The unique identifier for the theme family.
146    pub id: String,
147    /// The name of the theme family. This will be displayed in the UI, such as when adding or removing a theme family.
148    pub name: SharedString,
149    /// The author of the theme family.
150    pub author: SharedString,
151    /// The [Theme]s in the family.
152    pub themes: Vec<Theme>,
153    /// The color scales used by the themes in the family.
154    /// Note: This will be removed in the future.
155    pub scales: ColorScales,
156}
157
158impl ThemeFamily {
159    // This is on ThemeFamily because we will have variables here we will need
160    // in the future to resolve @references.
161    /// Refines ThemeContent into a theme, merging it's contents with the base theme.
162    pub fn refine_theme(&self, theme: &ThemeContent) -> Theme {
163        let appearance = match theme.appearance {
164            AppearanceContent::Light => Appearance::Light,
165            AppearanceContent::Dark => Appearance::Dark,
166        };
167
168        let mut refined_theme_colors = match theme.appearance {
169            AppearanceContent::Light => ThemeColors::light(),
170            AppearanceContent::Dark => ThemeColors::dark(),
171        };
172        refined_theme_colors.refine(&theme.style.theme_colors_refinement());
173
174        let mut refined_status_colors = match theme.appearance {
175            AppearanceContent::Light => StatusColors::light(),
176            AppearanceContent::Dark => StatusColors::dark(),
177        };
178        let mut status_colors_refinement = theme.style.status_colors_refinement();
179        apply_status_color_defaults(&mut status_colors_refinement);
180        refined_status_colors.refine(&status_colors_refinement);
181
182        let mut refined_player_colors = match theme.appearance {
183            AppearanceContent::Light => PlayerColors::light(),
184            AppearanceContent::Dark => PlayerColors::dark(),
185        };
186        refined_player_colors.merge(&theme.style.players);
187
188        let mut refined_accent_colors = match theme.appearance {
189            AppearanceContent::Light => AccentColors::light(),
190            AppearanceContent::Dark => AccentColors::dark(),
191        };
192        refined_accent_colors.merge(&theme.style.accents);
193
194        let syntax_highlights = theme
195            .style
196            .syntax
197            .iter()
198            .map(|(syntax_token, highlight)| {
199                (
200                    syntax_token.clone(),
201                    HighlightStyle {
202                        color: highlight
203                            .color
204                            .as_ref()
205                            .and_then(|color| try_parse_color(color).ok()),
206                        background_color: highlight
207                            .background_color
208                            .as_ref()
209                            .and_then(|color| try_parse_color(color).ok()),
210                        font_style: highlight.font_style.map(Into::into),
211                        font_weight: highlight.font_weight.map(Into::into),
212                        ..Default::default()
213                    },
214                )
215            })
216            .collect::<Vec<_>>();
217        let syntax_theme = SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
218
219        let window_background_appearance = theme
220            .style
221            .window_background_appearance
222            .map(Into::into)
223            .unwrap_or_default();
224
225        Theme {
226            id: uuid::Uuid::new_v4().to_string(),
227            name: theme.name.clone().into(),
228            appearance,
229            styles: ThemeStyles {
230                system: SystemColors::default(),
231                window_background_appearance,
232                accents: refined_accent_colors,
233                colors: refined_theme_colors,
234                status: refined_status_colors,
235                player: refined_player_colors,
236                syntax: syntax_theme,
237            },
238        }
239    }
240}
241
242/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
243pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
244    let id = Uuid::new_v4().to_string();
245    let name = theme_family_content.name.clone();
246    let author = theme_family_content.author.clone();
247
248    let mut theme_family = ThemeFamily {
249        id: id.clone(),
250        name: name.clone().into(),
251        author: author.clone().into(),
252        themes: vec![],
253        scales: default_color_scales(),
254    };
255
256    let refined_themes = theme_family_content
257        .themes
258        .iter()
259        .map(|theme_content| theme_family.refine_theme(theme_content))
260        .collect();
261
262    theme_family.themes = refined_themes;
263
264    theme_family
265}
266
267/// A theme is the primary mechanism for defining the appearance of the UI.
268#[derive(Clone, PartialEq)]
269pub struct Theme {
270    /// The unique identifier for the theme.
271    pub id: String,
272    /// The name of the theme.
273    pub name: SharedString,
274    /// The appearance of the theme (light or dark).
275    pub appearance: Appearance,
276    /// The colors and other styles for the theme.
277    pub styles: ThemeStyles,
278}
279
280impl Theme {
281    /// Returns the [`SystemColors`] for the theme.
282    #[inline(always)]
283    pub fn system(&self) -> &SystemColors {
284        &self.styles.system
285    }
286
287    /// Returns the [`AccentColors`] for the theme.
288    #[inline(always)]
289    pub fn accents(&self) -> &AccentColors {
290        &self.styles.accents
291    }
292
293    /// Returns the [`PlayerColors`] for the theme.
294    #[inline(always)]
295    pub fn players(&self) -> &PlayerColors {
296        &self.styles.player
297    }
298
299    /// Returns the [`ThemeColors`] for the theme.
300    #[inline(always)]
301    pub fn colors(&self) -> &ThemeColors {
302        &self.styles.colors
303    }
304
305    /// Returns the [`SyntaxTheme`] for the theme.
306    #[inline(always)]
307    pub fn syntax(&self) -> &Arc<SyntaxTheme> {
308        &self.styles.syntax
309    }
310
311    /// Returns the [`StatusColors`] for the theme.
312    #[inline(always)]
313    pub fn status(&self) -> &StatusColors {
314        &self.styles.status
315    }
316
317    /// Returns the color for the syntax node with the given name.
318    #[inline(always)]
319    pub fn syntax_color(&self, name: &str) -> Hsla {
320        self.syntax().color(name)
321    }
322
323    /// Returns the [`Appearance`] for the theme.
324    #[inline(always)]
325    pub fn appearance(&self) -> Appearance {
326        self.appearance
327    }
328
329    /// Returns the [`WindowBackgroundAppearance`] for the theme.
330    #[inline(always)]
331    pub fn window_background_appearance(&self) -> WindowBackgroundAppearance {
332        self.styles.window_background_appearance
333    }
334
335    /// Darkens the color by reducing its lightness.
336    /// The resulting lightness is clamped to ensure it doesn't go below 0.0.
337    ///
338    /// The first value darkens light appearance mode, the second darkens appearance dark mode.
339    ///
340    /// Note: This is a tentative solution and may be replaced with a more robust color system.
341    pub fn darken(&self, color: Hsla, light_amount: f32, dark_amount: f32) -> Hsla {
342        let amount = match self.appearance {
343            Appearance::Light => light_amount,
344            Appearance::Dark => dark_amount,
345        };
346        let mut hsla = color;
347        hsla.l = (hsla.l - amount).max(0.0);
348        hsla
349    }
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}