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    cx.observe_global::<SettingsStore>(move |cx| {
111        let buffer_font_size_settings = ThemeSettings::get_global(cx).buffer_font_size_settings();
112        if buffer_font_size_settings != prev_buffer_font_size_settings {
113            prev_buffer_font_size_settings = buffer_font_size_settings;
114            reset_buffer_font_size(cx);
115        }
116
117        let ui_font_size_settings = ThemeSettings::get_global(cx).ui_font_size_settings();
118        if ui_font_size_settings != prev_ui_font_size_settings {
119            prev_ui_font_size_settings = ui_font_size_settings;
120            reset_ui_font_size(cx);
121        }
122    })
123    .detach();
124}
125
126/// Implementing this trait allows accessing the active theme.
127pub trait ActiveTheme {
128    /// Returns the active theme.
129    fn theme(&self) -> &Arc<Theme>;
130}
131
132impl ActiveTheme for App {
133    fn theme(&self) -> &Arc<Theme> {
134        &ThemeSettings::get_global(self).active_theme
135    }
136}
137
138/// A theme family is a grouping of themes under a single name.
139///
140/// For example, the "One" theme family contains the "One Light" and "One Dark" themes.
141///
142/// It can also be used to package themes with many variants.
143///
144/// For example, the "Atelier" theme family contains "Cave", "Dune", "Estuary", "Forest", "Heath", etc.
145pub struct ThemeFamily {
146    /// The unique identifier for the theme family.
147    pub id: String,
148    /// The name of the theme family. This will be displayed in the UI, such as when adding or removing a theme family.
149    pub name: SharedString,
150    /// The author of the theme family.
151    pub author: SharedString,
152    /// The [Theme]s in the family.
153    pub themes: Vec<Theme>,
154    /// The color scales used by the themes in the family.
155    /// Note: This will be removed in the future.
156    pub scales: ColorScales,
157}
158
159impl ThemeFamily {
160    // This is on ThemeFamily because we will have variables here we will need
161    // in the future to resolve @references.
162    /// Refines ThemeContent into a theme, merging it's contents with the base theme.
163    pub fn refine_theme(&self, theme: &ThemeContent) -> Theme {
164        let appearance = match theme.appearance {
165            AppearanceContent::Light => Appearance::Light,
166            AppearanceContent::Dark => Appearance::Dark,
167        };
168
169        let mut refined_status_colors = match theme.appearance {
170            AppearanceContent::Light => StatusColors::light(),
171            AppearanceContent::Dark => StatusColors::dark(),
172        };
173        let mut status_colors_refinement = theme.style.status_colors_refinement();
174        apply_status_color_defaults(&mut status_colors_refinement);
175        refined_status_colors.refine(&status_colors_refinement);
176
177        let mut refined_player_colors = match theme.appearance {
178            AppearanceContent::Light => PlayerColors::light(),
179            AppearanceContent::Dark => PlayerColors::dark(),
180        };
181        refined_player_colors.merge(&theme.style.players);
182
183        let mut refined_theme_colors = match theme.appearance {
184            AppearanceContent::Light => ThemeColors::light(),
185            AppearanceContent::Dark => ThemeColors::dark(),
186        };
187        let mut theme_colors_refinement = theme.style.theme_colors_refinement();
188        apply_theme_color_defaults(&mut theme_colors_refinement, &refined_player_colors);
189        refined_theme_colors.refine(&theme_colors_refinement);
190
191        let mut refined_accent_colors = match theme.appearance {
192            AppearanceContent::Light => AccentColors::light(),
193            AppearanceContent::Dark => AccentColors::dark(),
194        };
195        refined_accent_colors.merge(&theme.style.accents);
196
197        let syntax_highlights = theme
198            .style
199            .syntax
200            .iter()
201            .map(|(syntax_token, highlight)| {
202                (
203                    syntax_token.clone(),
204                    HighlightStyle {
205                        color: highlight
206                            .color
207                            .as_ref()
208                            .and_then(|color| try_parse_color(color).ok()),
209                        background_color: highlight
210                            .background_color
211                            .as_ref()
212                            .and_then(|color| try_parse_color(color).ok()),
213                        font_style: highlight.font_style.map(Into::into),
214                        font_weight: highlight.font_weight.map(Into::into),
215                        ..Default::default()
216                    },
217                )
218            })
219            .collect::<Vec<_>>();
220        let syntax_theme = SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
221
222        let window_background_appearance = theme
223            .style
224            .window_background_appearance
225            .map(Into::into)
226            .unwrap_or_default();
227
228        Theme {
229            id: uuid::Uuid::new_v4().to_string(),
230            name: theme.name.clone().into(),
231            appearance,
232            styles: ThemeStyles {
233                system: SystemColors::default(),
234                window_background_appearance,
235                accents: refined_accent_colors,
236                colors: refined_theme_colors,
237                status: refined_status_colors,
238                player: refined_player_colors,
239                syntax: syntax_theme,
240            },
241        }
242    }
243}
244
245/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
246pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
247    let id = Uuid::new_v4().to_string();
248    let name = theme_family_content.name.clone();
249    let author = theme_family_content.author.clone();
250
251    let mut theme_family = ThemeFamily {
252        id: id.clone(),
253        name: name.clone().into(),
254        author: author.clone().into(),
255        themes: vec![],
256        scales: default_color_scales(),
257    };
258
259    let refined_themes = theme_family_content
260        .themes
261        .iter()
262        .map(|theme_content| theme_family.refine_theme(theme_content))
263        .collect();
264
265    theme_family.themes = refined_themes;
266
267    theme_family
268}
269
270/// A theme is the primary mechanism for defining the appearance of the UI.
271#[derive(Clone, Debug, PartialEq)]
272pub struct Theme {
273    /// The unique identifier for the theme.
274    pub id: String,
275    /// The name of the theme.
276    pub name: SharedString,
277    /// The appearance of the theme (light or dark).
278    pub appearance: Appearance,
279    /// The colors and other styles for the theme.
280    pub styles: ThemeStyles,
281}
282
283impl Theme {
284    /// Returns the [`SystemColors`] for the theme.
285    #[inline(always)]
286    pub fn system(&self) -> &SystemColors {
287        &self.styles.system
288    }
289
290    /// Returns the [`AccentColors`] for the theme.
291    #[inline(always)]
292    pub fn accents(&self) -> &AccentColors {
293        &self.styles.accents
294    }
295
296    /// Returns the [`PlayerColors`] for the theme.
297    #[inline(always)]
298    pub fn players(&self) -> &PlayerColors {
299        &self.styles.player
300    }
301
302    /// Returns the [`ThemeColors`] for the theme.
303    #[inline(always)]
304    pub fn colors(&self) -> &ThemeColors {
305        &self.styles.colors
306    }
307
308    /// Returns the [`SyntaxTheme`] for the theme.
309    #[inline(always)]
310    pub fn syntax(&self) -> &Arc<SyntaxTheme> {
311        &self.styles.syntax
312    }
313
314    /// Returns the [`StatusColors`] for the theme.
315    #[inline(always)]
316    pub fn status(&self) -> &StatusColors {
317        &self.styles.status
318    }
319
320    /// Returns the color for the syntax node with the given name.
321    #[inline(always)]
322    pub fn syntax_color(&self, name: &str) -> Hsla {
323        self.syntax().color(name)
324    }
325
326    /// Returns the [`Appearance`] for the theme.
327    #[inline(always)]
328    pub fn appearance(&self) -> Appearance {
329        self.appearance
330    }
331
332    /// Returns the [`WindowBackgroundAppearance`] for the theme.
333    #[inline(always)]
334    pub fn window_background_appearance(&self) -> WindowBackgroundAppearance {
335        self.styles.window_background_appearance
336    }
337
338    /// Darkens the color by reducing its lightness.
339    /// The resulting lightness is clamped to ensure it doesn't go below 0.0.
340    ///
341    /// The first value darkens light appearance mode, the second darkens appearance dark mode.
342    ///
343    /// Note: This is a tentative solution and may be replaced with a more robust color system.
344    pub fn darken(&self, color: Hsla, light_amount: f32, dark_amount: f32) -> Hsla {
345        let amount = match self.appearance {
346            Appearance::Light => light_amount,
347            Appearance::Dark => dark_amount,
348        };
349        let mut hsla = color;
350        hsla.l = (hsla.l - amount).max(0.0);
351        hsla
352    }
353}
354
355/// Asynchronously reads the user theme from the specified path.
356pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
357    let reader = fs.open_sync(theme_path).await?;
358    let theme_family: ThemeFamilyContent = serde_json_lenient::from_reader(reader)?;
359
360    for theme in &theme_family.themes {
361        if theme
362            .style
363            .colors
364            .deprecated_scrollbar_thumb_background
365            .is_some()
366        {
367            log::warn!(
368                r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
369                theme_name = theme.name
370            )
371        }
372    }
373
374    Ok(theme_family)
375}
376
377/// Asynchronously reads the icon theme from the specified path.
378pub async fn read_icon_theme(
379    icon_theme_path: &Path,
380    fs: Arc<dyn Fs>,
381) -> Result<IconThemeFamilyContent> {
382    let reader = fs.open_sync(icon_theme_path).await?;
383    let icon_theme_family: IconThemeFamilyContent = serde_json_lenient::from_reader(reader)?;
384
385    Ok(icon_theme_family)
386}