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