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