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