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::BorrowAppContext;
31use gpui::Global;
32use gpui::{
33 App, AssetSource, HighlightStyle, Hsla, Pixels, Refineable, SharedString, WindowAppearance,
34 WindowBackgroundAppearance, px,
35};
36use serde::Deserialize;
37use uuid::Uuid;
38
39pub use crate::default_colors::*;
40use crate::fallback_themes::apply_theme_color_defaults;
41pub use crate::font_family_cache::*;
42pub use crate::icon_theme::*;
43pub use crate::icon_theme_schema::*;
44pub use crate::registry::*;
45pub use crate::scale::*;
46pub use crate::schema::*;
47pub use crate::settings::*;
48pub use crate::styles::*;
49pub use ::settings::{
50 FontStyleContent, HighlightStyleContent, StatusColorsContent, ThemeColorsContent,
51 ThemeStyleContent,
52};
53
54/// Defines window border radius for platforms that use client side decorations.
55pub const CLIENT_SIDE_DECORATION_ROUNDING: Pixels = px(10.0);
56/// Defines window shadow size for platforms that use client side decorations.
57pub const CLIENT_SIDE_DECORATION_SHADOW: Pixels = px(10.0);
58
59/// The appearance of the theme.
60#[derive(Debug, PartialEq, Clone, Copy, Deserialize)]
61pub enum Appearance {
62 /// A light appearance.
63 Light,
64 /// A dark appearance.
65 Dark,
66}
67
68impl Appearance {
69 /// Returns whether the appearance is light.
70 pub fn is_light(&self) -> bool {
71 match self {
72 Self::Light => true,
73 Self::Dark => false,
74 }
75 }
76}
77
78impl From<WindowAppearance> for Appearance {
79 fn from(value: WindowAppearance) -> Self {
80 match value {
81 WindowAppearance::Dark | WindowAppearance::VibrantDark => Self::Dark,
82 WindowAppearance::Light | WindowAppearance::VibrantLight => Self::Light,
83 }
84 }
85}
86
87/// Which themes should be loaded. This is used primarily for testing.
88pub enum LoadThemes {
89 /// Only load the base theme.
90 ///
91 /// No user themes will be loaded.
92 JustBase,
93
94 /// Load all of the built-in themes.
95 All(Box<dyn AssetSource>),
96}
97
98/// Initialize the theme system.
99pub fn init(themes_to_load: LoadThemes, cx: &mut App) {
100 SystemAppearance::init(cx);
101 let (assets, load_user_themes) = match themes_to_load {
102 LoadThemes::JustBase => (Box::new(()) as Box<dyn AssetSource>, false),
103 LoadThemes::All(assets) => (assets, true),
104 };
105 ThemeRegistry::set_global(assets, cx);
106
107 if load_user_themes {
108 ThemeRegistry::global(cx).load_bundled_themes();
109 }
110
111 ThemeSettings::register(cx);
112 FontFamilyCache::init_global(cx);
113
114 let theme = GlobalTheme::configured_theme(cx);
115 let icon_theme = GlobalTheme::configured_icon_theme(cx);
116 cx.set_global(GlobalTheme { theme, icon_theme });
117
118 let settings = ThemeSettings::get_global(cx);
119
120 let mut prev_buffer_font_size_settings = settings.buffer_font_size_settings();
121 let mut prev_ui_font_size_settings = settings.ui_font_size_settings();
122 let mut prev_agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
123 let mut prev_agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
124 let mut prev_theme_name = settings.theme.name(SystemAppearance::global(cx).0);
125 let mut prev_icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
126 let mut prev_theme_overrides = (
127 settings.experimental_theme_overrides.clone(),
128 settings.theme_overrides.clone(),
129 );
130
131 cx.observe_global::<SettingsStore>(move |cx| {
132 let settings = ThemeSettings::get_global(cx);
133
134 let buffer_font_size_settings = settings.buffer_font_size_settings();
135 let ui_font_size_settings = settings.ui_font_size_settings();
136 let agent_ui_font_size_settings = settings.agent_ui_font_size_settings();
137 let agent_buffer_font_size_settings = settings.agent_buffer_font_size_settings();
138 let theme_name = settings.theme.name(SystemAppearance::global(cx).0);
139 let icon_theme_name = settings.icon_theme.name(SystemAppearance::global(cx).0);
140 let theme_overrides = (
141 settings.experimental_theme_overrides.clone(),
142 settings.theme_overrides.clone(),
143 );
144
145 if buffer_font_size_settings != prev_buffer_font_size_settings {
146 prev_buffer_font_size_settings = buffer_font_size_settings;
147 reset_buffer_font_size(cx);
148 }
149
150 if ui_font_size_settings != prev_ui_font_size_settings {
151 prev_ui_font_size_settings = ui_font_size_settings;
152 reset_ui_font_size(cx);
153 }
154
155 if agent_ui_font_size_settings != prev_agent_ui_font_size_settings {
156 prev_agent_ui_font_size_settings = agent_ui_font_size_settings;
157 reset_agent_ui_font_size(cx);
158 }
159
160 if agent_buffer_font_size_settings != prev_agent_buffer_font_size_settings {
161 prev_agent_buffer_font_size_settings = agent_buffer_font_size_settings;
162 reset_agent_buffer_font_size(cx);
163 }
164
165 if theme_name != prev_theme_name || theme_overrides != prev_theme_overrides {
166 prev_theme_name = theme_name;
167 prev_theme_overrides = theme_overrides;
168 GlobalTheme::reload_theme(cx);
169 }
170
171 if icon_theme_name != prev_icon_theme_name {
172 prev_icon_theme_name = icon_theme_name;
173 GlobalTheme::reload_icon_theme(cx);
174 }
175 })
176 .detach();
177}
178
179/// Implementing this trait allows accessing the active theme.
180pub trait ActiveTheme {
181 /// Returns the active theme.
182 fn theme(&self) -> &Arc<Theme>;
183}
184
185impl ActiveTheme for App {
186 fn theme(&self) -> &Arc<Theme> {
187 GlobalTheme::theme(self)
188 }
189}
190
191/// A theme family is a grouping of themes under a single name.
192///
193/// For example, the "One" theme family contains the "One Light" and "One Dark" themes.
194///
195/// It can also be used to package themes with many variants.
196///
197/// For example, the "Atelier" theme family contains "Cave", "Dune", "Estuary", "Forest", "Heath", etc.
198pub struct ThemeFamily {
199 /// The unique identifier for the theme family.
200 pub id: String,
201 /// The name of the theme family. This will be displayed in the UI, such as when adding or removing a theme family.
202 pub name: SharedString,
203 /// The author of the theme family.
204 pub author: SharedString,
205 /// The [Theme]s in the family.
206 pub themes: Vec<Theme>,
207 /// The color scales used by the themes in the family.
208 /// Note: This will be removed in the future.
209 pub scales: ColorScales,
210}
211
212impl ThemeFamily {
213 // This is on ThemeFamily because we will have variables here we will need
214 // in the future to resolve @references.
215 /// Refines ThemeContent into a theme, merging it's contents with the base theme.
216 pub fn refine_theme(&self, theme: &ThemeContent) -> Theme {
217 let appearance = match theme.appearance {
218 AppearanceContent::Light => Appearance::Light,
219 AppearanceContent::Dark => Appearance::Dark,
220 };
221
222 let mut refined_status_colors = match theme.appearance {
223 AppearanceContent::Light => StatusColors::light(),
224 AppearanceContent::Dark => StatusColors::dark(),
225 };
226 let mut status_colors_refinement = status_colors_refinement(&theme.style.status);
227 apply_status_color_defaults(&mut status_colors_refinement);
228 refined_status_colors.refine(&status_colors_refinement);
229
230 let mut refined_player_colors = match theme.appearance {
231 AppearanceContent::Light => PlayerColors::light(),
232 AppearanceContent::Dark => PlayerColors::dark(),
233 };
234 refined_player_colors.merge(&theme.style.players);
235
236 let mut refined_theme_colors = match theme.appearance {
237 AppearanceContent::Light => ThemeColors::light(),
238 AppearanceContent::Dark => ThemeColors::dark(),
239 };
240 let mut theme_colors_refinement =
241 theme_colors_refinement(&theme.style.colors, &status_colors_refinement);
242 apply_theme_color_defaults(&mut theme_colors_refinement, &refined_player_colors);
243 refined_theme_colors.refine(&theme_colors_refinement);
244
245 let mut refined_accent_colors = match theme.appearance {
246 AppearanceContent::Light => AccentColors::light(),
247 AppearanceContent::Dark => AccentColors::dark(),
248 };
249 refined_accent_colors.merge(&theme.style.accents);
250
251 let syntax_highlights = theme
252 .style
253 .syntax
254 .iter()
255 .map(|(syntax_token, highlight)| {
256 (
257 syntax_token.clone(),
258 HighlightStyle {
259 color: highlight
260 .color
261 .as_ref()
262 .and_then(|color| try_parse_color(color).ok()),
263 background_color: highlight
264 .background_color
265 .as_ref()
266 .and_then(|color| try_parse_color(color).ok()),
267 font_style: highlight.font_style.map(Into::into),
268 font_weight: highlight.font_weight.map(Into::into),
269 ..Default::default()
270 },
271 )
272 })
273 .collect::<Vec<_>>();
274 let syntax_theme = SyntaxTheme::merge(Arc::new(SyntaxTheme::default()), syntax_highlights);
275
276 let window_background_appearance = theme
277 .style
278 .window_background_appearance
279 .map(Into::into)
280 .unwrap_or_default();
281
282 Theme {
283 id: uuid::Uuid::new_v4().to_string(),
284 name: theme.name.clone().into(),
285 appearance,
286 styles: ThemeStyles {
287 system: SystemColors::default(),
288 window_background_appearance,
289 accents: refined_accent_colors,
290 colors: refined_theme_colors,
291 status: refined_status_colors,
292 player: refined_player_colors,
293 syntax: syntax_theme,
294 },
295 }
296 }
297}
298
299/// Refines a [ThemeFamilyContent] and it's [ThemeContent]s into a [ThemeFamily].
300pub fn refine_theme_family(theme_family_content: ThemeFamilyContent) -> ThemeFamily {
301 let id = Uuid::new_v4().to_string();
302 let name = theme_family_content.name.clone();
303 let author = theme_family_content.author.clone();
304
305 let mut theme_family = ThemeFamily {
306 id,
307 name: name.into(),
308 author: author.into(),
309 themes: vec![],
310 scales: default_color_scales(),
311 };
312
313 let refined_themes = theme_family_content
314 .themes
315 .iter()
316 .map(|theme_content| theme_family.refine_theme(theme_content))
317 .collect();
318
319 theme_family.themes = refined_themes;
320
321 theme_family
322}
323
324/// A theme is the primary mechanism for defining the appearance of the UI.
325#[derive(Clone, Debug, PartialEq)]
326pub struct Theme {
327 /// The unique identifier for the theme.
328 pub id: String,
329 /// The name of the theme.
330 pub name: SharedString,
331 /// The appearance of the theme (light or dark).
332 pub appearance: Appearance,
333 /// The colors and other styles for the theme.
334 pub styles: ThemeStyles,
335}
336
337impl Theme {
338 /// Returns the [`SystemColors`] for the theme.
339 #[inline(always)]
340 pub fn system(&self) -> &SystemColors {
341 &self.styles.system
342 }
343
344 /// Returns the [`AccentColors`] for the theme.
345 #[inline(always)]
346 pub fn accents(&self) -> &AccentColors {
347 &self.styles.accents
348 }
349
350 /// Returns the [`PlayerColors`] for the theme.
351 #[inline(always)]
352 pub fn players(&self) -> &PlayerColors {
353 &self.styles.player
354 }
355
356 /// Returns the [`ThemeColors`] for the theme.
357 #[inline(always)]
358 pub fn colors(&self) -> &ThemeColors {
359 &self.styles.colors
360 }
361
362 /// Returns the [`SyntaxTheme`] for the theme.
363 #[inline(always)]
364 pub fn syntax(&self) -> &Arc<SyntaxTheme> {
365 &self.styles.syntax
366 }
367
368 /// Returns the [`StatusColors`] for the theme.
369 #[inline(always)]
370 pub fn status(&self) -> &StatusColors {
371 &self.styles.status
372 }
373
374 /// Returns the color for the syntax node with the given name.
375 #[inline(always)]
376 pub fn syntax_color(&self, name: &str) -> Hsla {
377 self.syntax().color(name)
378 }
379
380 /// Returns the [`Appearance`] for the theme.
381 #[inline(always)]
382 pub fn appearance(&self) -> Appearance {
383 self.appearance
384 }
385
386 /// Returns the [`WindowBackgroundAppearance`] for the theme.
387 #[inline(always)]
388 pub fn window_background_appearance(&self) -> WindowBackgroundAppearance {
389 self.styles.window_background_appearance
390 }
391
392 /// Darkens the color by reducing its lightness.
393 /// The resulting lightness is clamped to ensure it doesn't go below 0.0.
394 ///
395 /// The first value darkens light appearance mode, the second darkens appearance dark mode.
396 ///
397 /// Note: This is a tentative solution and may be replaced with a more robust color system.
398 pub fn darken(&self, color: Hsla, light_amount: f32, dark_amount: f32) -> Hsla {
399 let amount = match self.appearance {
400 Appearance::Light => light_amount,
401 Appearance::Dark => dark_amount,
402 };
403 let mut hsla = color;
404 hsla.l = (hsla.l - amount).max(0.0);
405 hsla
406 }
407}
408
409/// Asynchronously reads the user theme from the specified path.
410pub async fn read_user_theme(theme_path: &Path, fs: Arc<dyn Fs>) -> Result<ThemeFamilyContent> {
411 let bytes = fs.load_bytes(theme_path).await?;
412 let theme_family: ThemeFamilyContent = serde_json_lenient::from_slice(&bytes)?;
413
414 for theme in &theme_family.themes {
415 if theme
416 .style
417 .colors
418 .deprecated_scrollbar_thumb_background
419 .is_some()
420 {
421 log::warn!(
422 r#"Theme "{theme_name}" is using a deprecated style property: scrollbar_thumb.background. Use `scrollbar.thumb.background` instead."#,
423 theme_name = theme.name
424 )
425 }
426 }
427
428 Ok(theme_family)
429}
430
431/// Asynchronously reads the icon theme from the specified path.
432pub async fn read_icon_theme(
433 icon_theme_path: &Path,
434 fs: Arc<dyn Fs>,
435) -> Result<IconThemeFamilyContent> {
436 let bytes = fs.load_bytes(icon_theme_path).await?;
437 let icon_theme_family: IconThemeFamilyContent = serde_json_lenient::from_slice(&bytes)?;
438
439 Ok(icon_theme_family)
440}
441
442/// The active theme
443pub struct GlobalTheme {
444 theme: Arc<Theme>,
445 icon_theme: Arc<IconTheme>,
446}
447impl Global for GlobalTheme {}
448
449impl GlobalTheme {
450 fn configured_theme(cx: &mut App) -> Arc<Theme> {
451 let themes = ThemeRegistry::default_global(cx);
452 let theme_settings = ThemeSettings::get_global(cx);
453 let system_appearance = SystemAppearance::global(cx);
454
455 let theme_name = theme_settings.theme.name(*system_appearance);
456
457 let theme = match themes.get(&theme_name.0) {
458 Ok(theme) => theme,
459 Err(err) => {
460 if themes.extensions_loaded() {
461 log::error!("{err}");
462 }
463 themes
464 .get(default_theme(*system_appearance))
465 // fallback for tests.
466 .unwrap_or_else(|_| themes.get(DEFAULT_DARK_THEME).unwrap())
467 }
468 };
469 theme_settings.apply_theme_overrides(theme)
470 }
471
472 /// Reloads the current theme.
473 ///
474 /// Reads the [`ThemeSettings`] to know which theme should be loaded,
475 /// taking into account the current [`SystemAppearance`].
476 pub fn reload_theme(cx: &mut App) {
477 let theme = Self::configured_theme(cx);
478 cx.update_global::<Self, _>(|this, _| this.theme = theme);
479 cx.refresh_windows();
480 }
481
482 fn configured_icon_theme(cx: &mut App) -> Arc<IconTheme> {
483 let themes = ThemeRegistry::default_global(cx);
484 let theme_settings = ThemeSettings::get_global(cx);
485 let system_appearance = SystemAppearance::global(cx);
486
487 let icon_theme_name = theme_settings.icon_theme.name(*system_appearance);
488
489 match themes.get_icon_theme(&icon_theme_name.0) {
490 Ok(theme) => theme,
491 Err(err) => {
492 if themes.extensions_loaded() {
493 log::error!("{err}");
494 }
495 themes.get_icon_theme(DEFAULT_ICON_THEME_NAME).unwrap()
496 }
497 }
498 }
499
500 /// Reloads the current icon theme.
501 ///
502 /// Reads the [`ThemeSettings`] to know which icon theme should be loaded,
503 /// taking into account the current [`SystemAppearance`].
504 pub fn reload_icon_theme(cx: &mut App) {
505 let icon_theme = Self::configured_icon_theme(cx);
506 cx.update_global::<Self, _>(|this, _| this.icon_theme = icon_theme);
507 cx.refresh_windows();
508 }
509
510 /// the active theme
511 pub fn theme(cx: &App) -> &Arc<Theme> {
512 &cx.global::<Self>().theme
513 }
514
515 /// the active icon theme
516 pub fn icon_theme(cx: &App) -> &Arc<IconTheme> {
517 &cx.global::<Self>().icon_theme
518 }
519}