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