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