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