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