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 = theme.style.status_colors_refinement();
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 = theme.style.theme_colors_refinement();
196        apply_theme_color_defaults(&mut theme_colors_refinement, &refined_player_colors);
197        refined_theme_colors.refine(&theme_colors_refinement);
198
199        let mut refined_accent_colors = match theme.appearance {
200            AppearanceContent::Light => AccentColors::light(),
201            AppearanceContent::Dark => AccentColors::dark(),
202        };
203        refined_accent_colors.merge(&theme.style.accents);
204
205        let syntax_highlights = theme
206            .style
207            .syntax
208            .iter()
209            .map(|(syntax_token, highlight)| {
210                (
211                    syntax_token.clone(),
212                    HighlightStyle {
213                        color: highlight
214                            .color
215                            .as_ref()
216                            .and_then(|color| try_parse_color(color).ok()),
217                        background_color: highlight
218                            .background_color
219                            .as_ref()
220                            .and_then(|color| try_parse_color(color).ok()),
221                        font_style: highlight.font_style.map(Into::into),
222                        font_weight: highlight.font_weight.map(Into::into),
223                        ..Default::default()
224                    },
225                )
226            })
227            .collect::<Vec<_>>();
228        let syntax_theme = SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
229
230        let window_background_appearance = theme
231            .style
232            .window_background_appearance
233            .map(Into::into)
234            .unwrap_or_default();
235
236        Theme {
237            id: uuid::Uuid::new_v4().to_string(),
238            name: theme.name.clone().into(),
239            appearance,
240            styles: ThemeStyles {
241                system: SystemColors::default(),
242                window_background_appearance,
243                accents: refined_accent_colors,
244                colors: refined_theme_colors,
245                status: refined_status_colors,
246                player: refined_player_colors,
247                syntax: syntax_theme,
248            },
249        }
250    }
251}
252
253/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
254pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
255    let id = Uuid::new_v4().to_string();
256    let name = theme_family_content.name.clone();
257    let author = theme_family_content.author.clone();
258
259    let mut theme_family = ThemeFamily {
260        id,
261        name: name.into(),
262        author: author.into(),
263        themes: vec![],
264        scales: default_color_scales(),
265    };
266
267    let refined_themes = theme_family_content
268        .themes
269        .iter()
270        .map(|theme_content| theme_family.refine_theme(theme_content))
271        .collect();
272
273    theme_family.themes = refined_themes;
274
275    theme_family
276}
277
278/// A theme is the primary mechanism for defining the appearance of the UI.
279#[derive(Clone, Debug, PartialEq)]
280pub struct Theme {
281    /// The unique identifier for the theme.
282    pub id: String,
283    /// The name of the theme.
284    pub name: SharedString,
285    /// The appearance of the theme (light or dark).
286    pub appearance: Appearance,
287    /// The colors and other styles for the theme.
288    pub styles: ThemeStyles,
289}
290
291impl Theme {
292    /// Returns the [`SystemColors`] for the theme.
293    #[inline(always)]
294    pub fn system(&self) -> &SystemColors {
295        &self.styles.system
296    }
297
298    /// Returns the [`AccentColors`] for the theme.
299    #[inline(always)]
300    pub fn accents(&self) -> &AccentColors {
301        &self.styles.accents
302    }
303
304    /// Returns the [`PlayerColors`] for the theme.
305    #[inline(always)]
306    pub fn players(&self) -> &PlayerColors {
307        &self.styles.player
308    }
309
310    /// Returns the [`ThemeColors`] for the theme.
311    #[inline(always)]
312    pub fn colors(&self) -> &ThemeColors {
313        &self.styles.colors
314    }
315
316    /// Returns the [`SyntaxTheme`] for the theme.
317    #[inline(always)]
318    pub fn syntax(&self) -> &Arc<SyntaxTheme> {
319        &self.styles.syntax
320    }
321
322    /// Returns the [`StatusColors`] for the theme.
323    #[inline(always)]
324    pub fn status(&self) -> &StatusColors {
325        &self.styles.status
326    }
327
328    /// Returns the color for the syntax node with the given name.
329    #[inline(always)]
330    pub fn syntax_color(&self, name: &str) -> Hsla {
331        self.syntax().color(name)
332    }
333
334    /// Returns the [`Appearance`] for the theme.
335    #[inline(always)]
336    pub fn appearance(&self) -> Appearance {
337        self.appearance
338    }
339
340    /// Returns the [`WindowBackgroundAppearance`] for the theme.
341    #[inline(always)]
342    pub fn window_background_appearance(&self) -> WindowBackgroundAppearance {
343        self.styles.window_background_appearance
344    }
345
346    /// Darkens the color by reducing its lightness.
347    /// The resulting lightness is clamped to ensure it doesn't go below 0.0.
348    ///
349    /// The first value darkens light appearance mode, the second darkens appearance dark mode.
350    ///
351    /// Note: This is a tentative solution and may be replaced with a more robust color system.
352    pub fn darken(&self, color: Hsla, light_amount: f32, dark_amount: f32) -> Hsla {
353        let amount = match self.appearance {
354            Appearance::Light => light_amount,
355            Appearance::Dark => dark_amount,
356        };
357        let mut hsla = color;
358        hsla.l = (hsla.l - amount).max(0.0);
359        hsla
360    }
361}
362
363/// Asynchronously reads the user theme from the specified path.
364pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
365    let reader = fs.open_sync(theme_path).await?;
366    let theme_family: ThemeFamilyContent = serde_json_lenient::from_reader(reader)?;
367
368    for theme in &theme_family.themes {
369        if theme
370            .style
371            .colors
372            .deprecated_scrollbar_thumb_background
373            .is_some()
374        {
375            log::warn!(
376                r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
377                theme_name = theme.name
378            )
379        }
380    }
381
382    Ok(theme_family)
383}
384
385/// Asynchronously reads the icon theme from the specified path.
386pub async fn read_icon_theme(
387    icon_theme_path: &Path,
388    fs: Arc<dyn Fs>,
389) -> Result<IconThemeFamilyContent> {
390    let reader = fs.open_sync(icon_theme_path).await?;
391    let icon_theme_family: IconThemeFamilyContent = serde_json_lenient::from_reader(reader)?;
392
393    Ok(icon_theme_family)
394}