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