1use crate::fallback_themes::zed_default_dark;
2use crate::{
3 Appearance, DEFAULT_ICON_THEME_NAME, IconTheme, IconThemeNotFoundError, SyntaxTheme, Theme,
4 ThemeNotFoundError, ThemeRegistry, ThemeStyleContent,
5};
6use anyhow::Result;
7use collections::HashMap;
8use derive_more::{Deref, DerefMut};
9use gpui::{
10 App, Context, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Global, Pixels,
11 SharedString, Subscription, Window, px,
12};
13use refineable::Refineable;
14use schemars::{JsonSchema, json_schema};
15use serde::{Deserialize, Serialize};
16use settings::{ParameterizedJsonSchema, Settings, SettingsSources, SettingsUi};
17use std::sync::Arc;
18use util::ResultExt as _;
19use util::schemars::replace_subschema;
20
21const MIN_FONT_SIZE: Pixels = px(6.0);
22const MAX_FONT_SIZE: Pixels = px(100.0);
23const MIN_LINE_HEIGHT: f32 = 1.0;
24
25#[derive(
26 Debug,
27 Default,
28 PartialEq,
29 Eq,
30 PartialOrd,
31 Ord,
32 Hash,
33 Clone,
34 Copy,
35 Serialize,
36 Deserialize,
37 JsonSchema,
38)]
39
40/// Specifies the density of the UI.
41/// Note: This setting is still experimental. See [this tracking issue](https://github.com/zed-industries/zed/issues/18078)
42#[serde(rename_all = "snake_case")]
43pub enum UiDensity {
44 /// A denser UI with tighter spacing and smaller elements.
45 #[serde(alias = "compact")]
46 Compact,
47 #[default]
48 #[serde(alias = "default")]
49 /// The default UI density.
50 Default,
51 #[serde(alias = "comfortable")]
52 /// A looser UI with more spacing and larger elements.
53 Comfortable,
54}
55
56impl UiDensity {
57 /// The spacing ratio of a given density.
58 /// TODO: Standardize usage throughout the app or remove
59 pub fn spacing_ratio(self) -> f32 {
60 match self {
61 UiDensity::Compact => 0.75,
62 UiDensity::Default => 1.0,
63 UiDensity::Comfortable => 1.25,
64 }
65 }
66}
67
68impl From<String> for UiDensity {
69 fn from(s: String) -> Self {
70 match s.as_str() {
71 "compact" => Self::Compact,
72 "default" => Self::Default,
73 "comfortable" => Self::Comfortable,
74 _ => Self::default(),
75 }
76 }
77}
78
79impl From<UiDensity> for String {
80 fn from(val: UiDensity) -> Self {
81 match val {
82 UiDensity::Compact => "compact".to_string(),
83 UiDensity::Default => "default".to_string(),
84 UiDensity::Comfortable => "comfortable".to_string(),
85 }
86 }
87}
88
89/// Customizable settings for the UI and theme system.
90#[derive(Clone, PartialEq)]
91pub struct ThemeSettings {
92 /// The UI font size. Determines the size of text in the UI,
93 /// as well as the size of a [gpui::Rems] unit.
94 ///
95 /// Changing this will impact the size of all UI elements.
96 ui_font_size: Pixels,
97 /// The font used for UI elements.
98 pub ui_font: Font,
99 /// The font size used for buffers, and the terminal.
100 ///
101 /// The terminal font size can be overridden using it's own setting.
102 buffer_font_size: Pixels,
103 /// The font used for buffers, and the terminal.
104 ///
105 /// The terminal font family can be overridden using it's own setting.
106 pub buffer_font: Font,
107 /// The agent font size. Determines the size of text in the agent panel. Falls back to the UI font size if unset.
108 agent_font_size: Option<Pixels>,
109 /// The line height for buffers, and the terminal.
110 ///
111 /// Changing this may affect the spacing of some UI elements.
112 ///
113 /// The terminal font family can be overridden using it's own setting.
114 pub buffer_line_height: BufferLineHeight,
115 /// The current theme selection.
116 pub theme_selection: Option<ThemeSelection>,
117 /// The active theme.
118 pub active_theme: Arc<Theme>,
119 /// Manual overrides for the active theme.
120 ///
121 /// Note: This setting is still experimental. See [this tracking issue](https://github.com/zed-industries/zed/issues/18078)
122 pub experimental_theme_overrides: Option<ThemeStyleContent>,
123 /// Manual overrides per theme
124 pub theme_overrides: HashMap<String, ThemeStyleContent>,
125 /// The current icon theme selection.
126 pub icon_theme_selection: Option<IconThemeSelection>,
127 /// The active icon theme.
128 pub active_icon_theme: Arc<IconTheme>,
129 /// The density of the UI.
130 /// Note: This setting is still experimental. See [this tracking issue](
131 pub ui_density: UiDensity,
132 /// The amount of fading applied to unnecessary code.
133 pub unnecessary_code_fade: f32,
134}
135
136impl ThemeSettings {
137 const DEFAULT_LIGHT_THEME: &'static str = "One Light";
138 const DEFAULT_DARK_THEME: &'static str = "One Dark";
139
140 /// Returns the name of the default theme for the given [`Appearance`].
141 pub fn default_theme(appearance: Appearance) -> &'static str {
142 match appearance {
143 Appearance::Light => Self::DEFAULT_LIGHT_THEME,
144 Appearance::Dark => Self::DEFAULT_DARK_THEME,
145 }
146 }
147
148 /// Reloads the current theme.
149 ///
150 /// Reads the [`ThemeSettings`] to know which theme should be loaded,
151 /// taking into account the current [`SystemAppearance`].
152 pub fn reload_current_theme(cx: &mut App) {
153 let mut theme_settings = ThemeSettings::get_global(cx).clone();
154 let system_appearance = SystemAppearance::global(cx);
155
156 if let Some(theme_selection) = theme_settings.theme_selection.clone() {
157 let mut theme_name = theme_selection.theme(*system_appearance);
158
159 // If the selected theme doesn't exist, fall back to a default theme
160 // based on the system appearance.
161 let theme_registry = ThemeRegistry::global(cx);
162 if let Err(err @ ThemeNotFoundError(_)) = theme_registry.get(theme_name) {
163 if theme_registry.extensions_loaded() {
164 log::error!("{err}");
165 }
166
167 theme_name = Self::default_theme(*system_appearance);
168 };
169
170 if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {
171 ThemeSettings::override_global(theme_settings, cx);
172 }
173 }
174 }
175
176 /// Reloads the current icon theme.
177 ///
178 /// Reads the [`ThemeSettings`] to know which icon theme should be loaded,
179 /// taking into account the current [`SystemAppearance`].
180 pub fn reload_current_icon_theme(cx: &mut App) {
181 let mut theme_settings = ThemeSettings::get_global(cx).clone();
182 let system_appearance = SystemAppearance::global(cx);
183
184 if let Some(icon_theme_selection) = theme_settings.icon_theme_selection.clone() {
185 let mut icon_theme_name = icon_theme_selection.icon_theme(*system_appearance);
186
187 // If the selected icon theme doesn't exist, fall back to the default theme.
188 let theme_registry = ThemeRegistry::global(cx);
189 if let Err(err @ IconThemeNotFoundError(_)) =
190 theme_registry.get_icon_theme(icon_theme_name)
191 {
192 if theme_registry.extensions_loaded() {
193 log::error!("{err}");
194 }
195
196 icon_theme_name = DEFAULT_ICON_THEME_NAME;
197 };
198
199 if let Some(_theme) = theme_settings.switch_icon_theme(icon_theme_name, cx) {
200 ThemeSettings::override_global(theme_settings, cx);
201 }
202 }
203 }
204}
205
206/// The appearance of the system.
207#[derive(Debug, Clone, Copy, Deref)]
208pub struct SystemAppearance(pub Appearance);
209
210impl Default for SystemAppearance {
211 fn default() -> Self {
212 Self(Appearance::Dark)
213 }
214}
215
216#[derive(Deref, DerefMut, Default)]
217struct GlobalSystemAppearance(SystemAppearance);
218
219impl Global for GlobalSystemAppearance {}
220
221impl SystemAppearance {
222 /// Initializes the [`SystemAppearance`] for the application.
223 pub fn init(cx: &mut App) {
224 *cx.default_global::<GlobalSystemAppearance>() =
225 GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
226 }
227
228 /// Returns the global [`SystemAppearance`].
229 ///
230 /// Inserts a default [`SystemAppearance`] if one does not yet exist.
231 pub(crate) fn default_global(cx: &mut App) -> Self {
232 cx.default_global::<GlobalSystemAppearance>().0
233 }
234
235 /// Returns the global [`SystemAppearance`].
236 pub fn global(cx: &App) -> Self {
237 cx.global::<GlobalSystemAppearance>().0
238 }
239
240 /// Returns a mutable reference to the global [`SystemAppearance`].
241 pub fn global_mut(cx: &mut App) -> &mut Self {
242 cx.global_mut::<GlobalSystemAppearance>()
243 }
244}
245
246#[derive(Default)]
247struct BufferFontSize(Pixels);
248
249impl Global for BufferFontSize {}
250
251#[derive(Default)]
252pub(crate) struct UiFontSize(Pixels);
253
254impl Global for UiFontSize {}
255
256#[derive(Default)]
257pub(crate) struct AgentFontSize(Pixels);
258
259impl Global for AgentFontSize {}
260
261/// Represents the selection of a theme, which can be either static or dynamic.
262#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
263#[serde(untagged)]
264pub enum ThemeSelection {
265 /// A static theme selection, represented by a single theme name.
266 Static(ThemeName),
267 /// A dynamic theme selection, which can change based the [ThemeMode].
268 Dynamic {
269 /// The mode used to determine which theme to use.
270 #[serde(default)]
271 mode: ThemeMode,
272 /// The theme to use for light mode.
273 light: ThemeName,
274 /// The theme to use for dark mode.
275 dark: ThemeName,
276 },
277}
278
279// TODO: Rename ThemeMode -> ThemeAppearanceMode
280/// The mode use to select a theme.
281///
282/// `Light` and `Dark` will select their respective themes.
283///
284/// `System` will select the theme based on the system's appearance.
285#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
286#[serde(rename_all = "snake_case")]
287pub enum ThemeMode {
288 /// Use the specified `light` theme.
289 Light,
290
291 /// Use the specified `dark` theme.
292 Dark,
293
294 /// Use the theme based on the system's appearance.
295 #[default]
296 System,
297}
298
299impl ThemeSelection {
300 /// Returns the theme name for the selected [ThemeMode].
301 pub fn theme(&self, system_appearance: Appearance) -> &str {
302 match self {
303 Self::Static(theme) => &theme.0,
304 Self::Dynamic { mode, light, dark } => match mode {
305 ThemeMode::Light => &light.0,
306 ThemeMode::Dark => &dark.0,
307 ThemeMode::System => match system_appearance {
308 Appearance::Light => &light.0,
309 Appearance::Dark => &dark.0,
310 },
311 },
312 }
313 }
314
315 /// Returns the [ThemeMode] for the [ThemeSelection].
316 pub fn mode(&self) -> Option<ThemeMode> {
317 match self {
318 ThemeSelection::Static(_) => None,
319 ThemeSelection::Dynamic { mode, .. } => Some(*mode),
320 }
321 }
322}
323
324/// Represents the selection of an icon theme, which can be either static or dynamic.
325#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
326#[serde(untagged)]
327pub enum IconThemeSelection {
328 /// A static icon theme selection, represented by a single icon theme name.
329 Static(IconThemeName),
330 /// A dynamic icon theme selection, which can change based on the [`ThemeMode`].
331 Dynamic {
332 /// The mode used to determine which theme to use.
333 #[serde(default)]
334 mode: ThemeMode,
335 /// The icon theme to use for light mode.
336 light: IconThemeName,
337 /// The icon theme to use for dark mode.
338 dark: IconThemeName,
339 },
340}
341
342impl IconThemeSelection {
343 /// Returns the icon theme name based on the given [`Appearance`].
344 pub fn icon_theme(&self, system_appearance: Appearance) -> &str {
345 match self {
346 Self::Static(theme) => &theme.0,
347 Self::Dynamic { mode, light, dark } => match mode {
348 ThemeMode::Light => &light.0,
349 ThemeMode::Dark => &dark.0,
350 ThemeMode::System => match system_appearance {
351 Appearance::Light => &light.0,
352 Appearance::Dark => &dark.0,
353 },
354 },
355 }
356 }
357
358 /// Returns the [`ThemeMode`] for the [`IconThemeSelection`].
359 pub fn mode(&self) -> Option<ThemeMode> {
360 match self {
361 IconThemeSelection::Static(_) => None,
362 IconThemeSelection::Dynamic { mode, .. } => Some(*mode),
363 }
364 }
365}
366
367/// Settings for rendering text in UI and text buffers.
368#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
369pub struct ThemeSettingsContent {
370 /// The default font size for text in the UI.
371 #[serde(default)]
372 pub ui_font_size: Option<f32>,
373 /// The name of a font to use for rendering in the UI.
374 #[serde(default)]
375 pub ui_font_family: Option<FontFamilyName>,
376 /// The font fallbacks to use for rendering in the UI.
377 #[serde(default)]
378 #[schemars(default = "default_font_fallbacks")]
379 #[schemars(extend("uniqueItems" = true))]
380 pub ui_font_fallbacks: Option<Vec<FontFamilyName>>,
381 /// The OpenType features to enable for text in the UI.
382 #[serde(default)]
383 #[schemars(default = "default_font_features")]
384 pub ui_font_features: Option<FontFeatures>,
385 /// The weight of the UI font in CSS units from 100 to 900.
386 #[serde(default)]
387 pub ui_font_weight: Option<f32>,
388 /// The name of a font to use for rendering in text buffers.
389 #[serde(default)]
390 pub buffer_font_family: Option<FontFamilyName>,
391 /// The font fallbacks to use for rendering in text buffers.
392 #[serde(default)]
393 #[schemars(extend("uniqueItems" = true))]
394 pub buffer_font_fallbacks: Option<Vec<FontFamilyName>>,
395 /// The default font size for rendering in text buffers.
396 #[serde(default)]
397 pub buffer_font_size: Option<f32>,
398 /// The weight of the editor font in CSS units from 100 to 900.
399 #[serde(default)]
400 pub buffer_font_weight: Option<f32>,
401 /// The buffer's line height.
402 #[serde(default)]
403 pub buffer_line_height: Option<BufferLineHeight>,
404 /// The OpenType features to enable for rendering in text buffers.
405 #[serde(default)]
406 #[schemars(default = "default_font_features")]
407 pub buffer_font_features: Option<FontFeatures>,
408 /// The font size for the agent panel. Falls back to the UI font size if unset.
409 #[serde(default)]
410 pub agent_font_size: Option<Option<f32>>,
411 /// The name of the Zed theme to use.
412 #[serde(default)]
413 pub theme: Option<ThemeSelection>,
414 /// The name of the icon theme to use.
415 #[serde(default)]
416 pub icon_theme: Option<IconThemeSelection>,
417
418 /// UNSTABLE: Expect many elements to be broken.
419 ///
420 // Controls the density of the UI.
421 #[serde(rename = "unstable.ui_density", default)]
422 pub ui_density: Option<UiDensity>,
423
424 /// How much to fade out unused code.
425 #[serde(default)]
426 pub unnecessary_code_fade: Option<f32>,
427
428 /// EXPERIMENTAL: Overrides for the current theme.
429 ///
430 /// These values will override the ones on the current theme specified in `theme`.
431 #[serde(rename = "experimental.theme_overrides", default)]
432 pub experimental_theme_overrides: Option<ThemeStyleContent>,
433
434 /// Overrides per theme
435 ///
436 /// These values will override the ones on the specified theme
437 #[serde(default)]
438 pub theme_overrides: HashMap<String, ThemeStyleContent>,
439}
440
441fn default_font_features() -> Option<FontFeatures> {
442 Some(FontFeatures::default())
443}
444
445fn default_font_fallbacks() -> Option<FontFallbacks> {
446 Some(FontFallbacks::default())
447}
448
449impl ThemeSettingsContent {
450 /// Sets the theme for the given appearance to the theme with the specified name.
451 pub fn set_theme(&mut self, theme_name: impl Into<Arc<str>>, appearance: Appearance) {
452 if let Some(selection) = self.theme.as_mut() {
453 let theme_to_update = match selection {
454 ThemeSelection::Static(theme) => theme,
455 ThemeSelection::Dynamic { mode, light, dark } => match mode {
456 ThemeMode::Light => light,
457 ThemeMode::Dark => dark,
458 ThemeMode::System => match appearance {
459 Appearance::Light => light,
460 Appearance::Dark => dark,
461 },
462 },
463 };
464
465 *theme_to_update = ThemeName(theme_name.into());
466 } else {
467 self.theme = Some(ThemeSelection::Static(ThemeName(theme_name.into())));
468 }
469 }
470
471 /// Sets the icon theme for the given appearance to the icon theme with the specified name.
472 pub fn set_icon_theme(&mut self, icon_theme_name: String, appearance: Appearance) {
473 if let Some(selection) = self.icon_theme.as_mut() {
474 let icon_theme_to_update = match selection {
475 IconThemeSelection::Static(theme) => theme,
476 IconThemeSelection::Dynamic { mode, light, dark } => match mode {
477 ThemeMode::Light => light,
478 ThemeMode::Dark => dark,
479 ThemeMode::System => match appearance {
480 Appearance::Light => light,
481 Appearance::Dark => dark,
482 },
483 },
484 };
485
486 *icon_theme_to_update = IconThemeName(icon_theme_name.into());
487 } else {
488 self.icon_theme = Some(IconThemeSelection::Static(IconThemeName(
489 icon_theme_name.into(),
490 )));
491 }
492 }
493
494 /// Sets the mode for the theme.
495 pub fn set_mode(&mut self, mode: ThemeMode) {
496 if let Some(selection) = self.theme.as_mut() {
497 match selection {
498 ThemeSelection::Static(theme) => {
499 // If the theme was previously set to a single static theme,
500 // we don't know whether it was a light or dark theme, so we
501 // just use it for both.
502 self.theme = Some(ThemeSelection::Dynamic {
503 mode,
504 light: theme.clone(),
505 dark: theme.clone(),
506 });
507 }
508 ThemeSelection::Dynamic {
509 mode: mode_to_update,
510 ..
511 } => *mode_to_update = mode,
512 }
513 } else {
514 self.theme = Some(ThemeSelection::Dynamic {
515 mode,
516 light: ThemeName(ThemeSettings::DEFAULT_LIGHT_THEME.into()),
517 dark: ThemeName(ThemeSettings::DEFAULT_DARK_THEME.into()),
518 });
519 }
520
521 if let Some(selection) = self.icon_theme.as_mut() {
522 match selection {
523 IconThemeSelection::Static(icon_theme) => {
524 // If the icon theme was previously set to a single static
525 // theme, we don't know whether it was a light or dark
526 // theme, so we just use it for both.
527 self.icon_theme = Some(IconThemeSelection::Dynamic {
528 mode,
529 light: icon_theme.clone(),
530 dark: icon_theme.clone(),
531 });
532 }
533 IconThemeSelection::Dynamic {
534 mode: mode_to_update,
535 ..
536 } => *mode_to_update = mode,
537 }
538 } else {
539 self.icon_theme = Some(IconThemeSelection::Static(IconThemeName(
540 DEFAULT_ICON_THEME_NAME.into(),
541 )));
542 }
543 }
544}
545
546/// The buffer's line height.
547#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
548#[serde(rename_all = "snake_case")]
549pub enum BufferLineHeight {
550 /// A less dense line height.
551 #[default]
552 Comfortable,
553 /// The default line height.
554 Standard,
555 /// A custom line height, where 1.0 is the font's height. Must be at least 1.0.
556 Custom(#[serde(deserialize_with = "deserialize_line_height")] f32),
557}
558
559fn deserialize_line_height<'de, D>(deserializer: D) -> Result<f32, D::Error>
560where
561 D: serde::Deserializer<'de>,
562{
563 let value = f32::deserialize(deserializer)?;
564 if value < 1.0 {
565 return Err(serde::de::Error::custom(
566 "buffer_line_height.custom must be at least 1.0",
567 ));
568 }
569
570 Ok(value)
571}
572
573impl BufferLineHeight {
574 /// Returns the value of the line height.
575 pub fn value(&self) -> f32 {
576 match self {
577 BufferLineHeight::Comfortable => 1.618,
578 BufferLineHeight::Standard => 1.3,
579 BufferLineHeight::Custom(line_height) => *line_height,
580 }
581 }
582}
583
584impl ThemeSettings {
585 /// Returns the buffer font size.
586 pub fn buffer_font_size(&self, cx: &App) -> Pixels {
587 let font_size = cx
588 .try_global::<BufferFontSize>()
589 .map(|size| size.0)
590 .unwrap_or(self.buffer_font_size);
591 clamp_font_size(font_size)
592 }
593
594 /// Returns the UI font size.
595 pub fn ui_font_size(&self, cx: &App) -> Pixels {
596 let font_size = cx
597 .try_global::<UiFontSize>()
598 .map(|size| size.0)
599 .unwrap_or(self.ui_font_size);
600 clamp_font_size(font_size)
601 }
602
603 /// Returns the agent panel font size. Falls back to the UI font size if unset.
604 pub fn agent_font_size(&self, cx: &App) -> Pixels {
605 cx.try_global::<AgentFontSize>()
606 .map(|size| size.0)
607 .or(self.agent_font_size)
608 .map(clamp_font_size)
609 .unwrap_or_else(|| self.ui_font_size(cx))
610 }
611
612 /// Returns the buffer font size, read from the settings.
613 ///
614 /// The real buffer font size is stored in-memory, to support temporary font size changes.
615 /// Use [`Self::buffer_font_size`] to get the real font size.
616 pub fn buffer_font_size_settings(&self) -> Pixels {
617 self.buffer_font_size
618 }
619
620 /// Returns the UI font size, read from the settings.
621 ///
622 /// The real UI font size is stored in-memory, to support temporary font size changes.
623 /// Use [`Self::ui_font_size`] to get the real font size.
624 pub fn ui_font_size_settings(&self) -> Pixels {
625 self.ui_font_size
626 }
627
628 /// Returns the agent font size, read from the settings.
629 ///
630 /// The real agent font size is stored in-memory, to support temporary font size changes.
631 /// Use [`Self::agent_font_size`] to get the real font size.
632 pub fn agent_font_size_settings(&self) -> Option<Pixels> {
633 self.agent_font_size
634 }
635
636 // TODO: Rename: `line_height` -> `buffer_line_height`
637 /// Returns the buffer's line height.
638 pub fn line_height(&self) -> f32 {
639 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
640 }
641
642 /// Switches to the theme with the given name, if it exists.
643 ///
644 /// Returns a `Some` containing the new theme if it was successful.
645 /// Returns `None` otherwise.
646 pub fn switch_theme(&mut self, theme: &str, cx: &mut App) -> Option<Arc<Theme>> {
647 let themes = ThemeRegistry::default_global(cx);
648
649 let mut new_theme = None;
650
651 match themes.get(theme) {
652 Ok(theme) => {
653 self.active_theme = theme.clone();
654 new_theme = Some(theme);
655 }
656 Err(err @ ThemeNotFoundError(_)) => {
657 log::error!("{err}");
658 }
659 }
660
661 self.apply_theme_overrides();
662
663 new_theme
664 }
665
666 /// Applies the theme overrides, if there are any, to the current theme.
667 pub fn apply_theme_overrides(&mut self) {
668 // Apply the old overrides setting first, so that the new setting can override those.
669 if let Some(experimental_theme_overrides) = &self.experimental_theme_overrides {
670 let mut theme = (*self.active_theme).clone();
671 ThemeSettings::modify_theme(&mut theme, experimental_theme_overrides);
672 self.active_theme = Arc::new(theme);
673 }
674
675 if let Some(theme_overrides) = self.theme_overrides.get(self.active_theme.name.as_ref()) {
676 let mut theme = (*self.active_theme).clone();
677 ThemeSettings::modify_theme(&mut theme, theme_overrides);
678 self.active_theme = Arc::new(theme);
679 }
680 }
681
682 fn modify_theme(base_theme: &mut Theme, theme_overrides: &ThemeStyleContent) {
683 if let Some(window_background_appearance) = theme_overrides.window_background_appearance {
684 base_theme.styles.window_background_appearance = window_background_appearance.into();
685 }
686
687 base_theme
688 .styles
689 .colors
690 .refine(&theme_overrides.theme_colors_refinement());
691 base_theme
692 .styles
693 .status
694 .refine(&theme_overrides.status_colors_refinement());
695 base_theme.styles.player.merge(&theme_overrides.players);
696 base_theme.styles.accents.merge(&theme_overrides.accents);
697 base_theme.styles.syntax = SyntaxTheme::merge(
698 base_theme.styles.syntax.clone(),
699 theme_overrides.syntax_overrides(),
700 );
701 }
702
703 /// Switches to the icon theme with the given name, if it exists.
704 ///
705 /// Returns a `Some` containing the new icon theme if it was successful.
706 /// Returns `None` otherwise.
707 pub fn switch_icon_theme(&mut self, icon_theme: &str, cx: &mut App) -> Option<Arc<IconTheme>> {
708 let themes = ThemeRegistry::default_global(cx);
709
710 let mut new_icon_theme = None;
711
712 if let Some(icon_theme) = themes.get_icon_theme(icon_theme).log_err() {
713 self.active_icon_theme = icon_theme.clone();
714 new_icon_theme = Some(icon_theme);
715 cx.refresh_windows();
716 }
717
718 new_icon_theme
719 }
720}
721
722/// Observe changes to the adjusted buffer font size.
723pub fn observe_buffer_font_size_adjustment<V: 'static>(
724 cx: &mut Context<V>,
725 f: impl 'static + Fn(&mut V, &mut Context<V>),
726) -> Subscription {
727 cx.observe_global::<BufferFontSize>(f)
728}
729
730/// Gets the font size, adjusted by the difference between the current buffer font size and the one set in the settings.
731pub fn adjusted_font_size(size: Pixels, cx: &App) -> Pixels {
732 let adjusted_font_size =
733 if let Some(BufferFontSize(adjusted_size)) = cx.try_global::<BufferFontSize>() {
734 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
735 let delta = *adjusted_size - buffer_font_size;
736 size + delta
737 } else {
738 size
739 };
740 clamp_font_size(adjusted_font_size)
741}
742
743/// Adjusts the buffer font size.
744pub fn adjust_buffer_font_size(cx: &mut App, f: impl FnOnce(Pixels) -> Pixels) {
745 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
746 let adjusted_size = cx
747 .try_global::<BufferFontSize>()
748 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
749 cx.set_global(BufferFontSize(clamp_font_size(f(adjusted_size))));
750 cx.refresh_windows();
751}
752
753/// Resets the buffer font size to the default value.
754pub fn reset_buffer_font_size(cx: &mut App) {
755 if cx.has_global::<BufferFontSize>() {
756 cx.remove_global::<BufferFontSize>();
757 cx.refresh_windows();
758 }
759}
760
761// TODO: Make private, change usages to use `get_ui_font_size` instead.
762#[allow(missing_docs)]
763pub fn setup_ui_font(window: &mut Window, cx: &mut App) -> gpui::Font {
764 let (ui_font, ui_font_size) = {
765 let theme_settings = ThemeSettings::get_global(cx);
766 let font = theme_settings.ui_font.clone();
767 (font, theme_settings.ui_font_size(cx))
768 };
769
770 window.set_rem_size(ui_font_size);
771 ui_font
772}
773
774/// Sets the adjusted UI font size.
775pub fn adjust_ui_font_size(cx: &mut App, f: impl FnOnce(Pixels) -> Pixels) {
776 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
777 let adjusted_size = cx
778 .try_global::<UiFontSize>()
779 .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
780 cx.set_global(UiFontSize(clamp_font_size(f(adjusted_size))));
781 cx.refresh_windows();
782}
783
784/// Resets the UI font size to the default value.
785pub fn reset_ui_font_size(cx: &mut App) {
786 if cx.has_global::<UiFontSize>() {
787 cx.remove_global::<UiFontSize>();
788 cx.refresh_windows();
789 }
790}
791
792/// Sets the adjusted agent panel font size.
793pub fn adjust_agent_font_size(cx: &mut App, f: impl FnOnce(Pixels) -> Pixels) {
794 let agent_font_size = ThemeSettings::get_global(cx).agent_font_size(cx);
795 let adjusted_size = cx
796 .try_global::<AgentFontSize>()
797 .map_or(agent_font_size, |adjusted_size| adjusted_size.0);
798 cx.set_global(AgentFontSize(clamp_font_size(f(adjusted_size))));
799 cx.refresh_windows();
800}
801
802/// Resets the agent panel font size to the default value.
803pub fn reset_agent_font_size(cx: &mut App) {
804 if cx.has_global::<AgentFontSize>() {
805 cx.remove_global::<AgentFontSize>();
806 cx.refresh_windows();
807 }
808}
809
810/// Ensures font size is within the valid range.
811pub fn clamp_font_size(size: Pixels) -> Pixels {
812 size.clamp(MIN_FONT_SIZE, MAX_FONT_SIZE)
813}
814
815fn clamp_font_weight(weight: f32) -> FontWeight {
816 FontWeight(weight.clamp(100., 950.))
817}
818
819impl settings::Settings for ThemeSettings {
820 const KEY: Option<&'static str> = None;
821
822 type FileContent = ThemeSettingsContent;
823
824 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self> {
825 let themes = ThemeRegistry::default_global(cx);
826 let system_appearance = SystemAppearance::default_global(cx);
827
828 fn font_fallbacks_from_settings(
829 fallbacks: Option<Vec<FontFamilyName>>,
830 ) -> Option<FontFallbacks> {
831 fallbacks.map(|fallbacks| {
832 FontFallbacks::from_fonts(
833 fallbacks
834 .into_iter()
835 .map(|font_family| font_family.0.to_string())
836 .collect(),
837 )
838 })
839 }
840
841 let defaults = sources.default;
842 let mut this = Self {
843 ui_font_size: defaults.ui_font_size.unwrap().into(),
844 ui_font: Font {
845 family: defaults.ui_font_family.as_ref().unwrap().0.clone().into(),
846 features: defaults.ui_font_features.clone().unwrap(),
847 fallbacks: font_fallbacks_from_settings(defaults.ui_font_fallbacks.clone()),
848 weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
849 style: Default::default(),
850 },
851 buffer_font: Font {
852 family: defaults
853 .buffer_font_family
854 .as_ref()
855 .unwrap()
856 .0
857 .clone()
858 .into(),
859 features: defaults.buffer_font_features.clone().unwrap(),
860 fallbacks: font_fallbacks_from_settings(defaults.buffer_font_fallbacks.clone()),
861 weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
862 style: FontStyle::default(),
863 },
864 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
865 buffer_line_height: defaults.buffer_line_height.unwrap(),
866 agent_font_size: defaults.agent_font_size.flatten().map(Into::into),
867 theme_selection: defaults.theme.clone(),
868 active_theme: themes
869 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
870 .or(themes.get(&zed_default_dark().name))
871 .unwrap(),
872 experimental_theme_overrides: None,
873 theme_overrides: HashMap::default(),
874 icon_theme_selection: defaults.icon_theme.clone(),
875 active_icon_theme: defaults
876 .icon_theme
877 .as_ref()
878 .and_then(|selection| {
879 themes
880 .get_icon_theme(selection.icon_theme(*system_appearance))
881 .ok()
882 })
883 .unwrap_or_else(|| themes.get_icon_theme(DEFAULT_ICON_THEME_NAME).unwrap()),
884 ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
885 unnecessary_code_fade: defaults.unnecessary_code_fade.unwrap_or(0.0),
886 };
887
888 for value in sources
889 .user
890 .into_iter()
891 .chain(sources.release_channel)
892 .chain(sources.operating_system)
893 .chain(sources.profile)
894 .chain(sources.server)
895 {
896 if let Some(value) = value.ui_density {
897 this.ui_density = value;
898 }
899
900 if let Some(value) = value.buffer_font_family.clone() {
901 this.buffer_font.family = value.0.into();
902 }
903 if let Some(value) = value.buffer_font_features.clone() {
904 this.buffer_font.features = value;
905 }
906 if let Some(value) = value.buffer_font_fallbacks.clone() {
907 this.buffer_font.fallbacks = font_fallbacks_from_settings(Some(value));
908 }
909 if let Some(value) = value.buffer_font_weight {
910 this.buffer_font.weight = clamp_font_weight(value);
911 }
912
913 if let Some(value) = value.ui_font_family.clone() {
914 this.ui_font.family = value.0.into();
915 }
916 if let Some(value) = value.ui_font_features.clone() {
917 this.ui_font.features = value;
918 }
919 if let Some(value) = value.ui_font_fallbacks.clone() {
920 this.ui_font.fallbacks = font_fallbacks_from_settings(Some(value));
921 }
922 if let Some(value) = value.ui_font_weight {
923 this.ui_font.weight = clamp_font_weight(value);
924 }
925
926 if let Some(value) = &value.theme {
927 this.theme_selection = Some(value.clone());
928
929 let theme_name = value.theme(*system_appearance);
930
931 match themes.get(theme_name) {
932 Ok(theme) => {
933 this.active_theme = theme;
934 }
935 Err(err @ ThemeNotFoundError(_)) => {
936 if themes.extensions_loaded() {
937 log::error!("{err}");
938 }
939 }
940 }
941 }
942
943 this.experimental_theme_overrides
944 .clone_from(&value.experimental_theme_overrides);
945 this.theme_overrides.clone_from(&value.theme_overrides);
946 this.apply_theme_overrides();
947
948 if let Some(value) = &value.icon_theme {
949 this.icon_theme_selection = Some(value.clone());
950
951 let icon_theme_name = value.icon_theme(*system_appearance);
952
953 match themes.get_icon_theme(icon_theme_name) {
954 Ok(icon_theme) => {
955 this.active_icon_theme = icon_theme;
956 }
957 Err(err @ IconThemeNotFoundError(_)) => {
958 if themes.extensions_loaded() {
959 log::error!("{err}");
960 }
961 }
962 }
963 }
964
965 merge(
966 &mut this.ui_font_size,
967 value.ui_font_size.map(Into::into).map(clamp_font_size),
968 );
969 merge(
970 &mut this.buffer_font_size,
971 value.buffer_font_size.map(Into::into).map(clamp_font_size),
972 );
973 merge(
974 &mut this.agent_font_size,
975 value
976 .agent_font_size
977 .map(|value| value.map(Into::into).map(clamp_font_size)),
978 );
979
980 merge(&mut this.buffer_line_height, value.buffer_line_height);
981
982 // Clamp the `unnecessary_code_fade` to ensure text can't disappear entirely.
983 merge(&mut this.unnecessary_code_fade, value.unnecessary_code_fade);
984 this.unnecessary_code_fade = this.unnecessary_code_fade.clamp(0.0, 0.9);
985 }
986
987 Ok(this)
988 }
989
990 fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
991 vscode.f32_setting("editor.fontWeight", &mut current.buffer_font_weight);
992 vscode.f32_setting("editor.fontSize", &mut current.buffer_font_size);
993 if let Some(font) = vscode.read_string("editor.font") {
994 current.buffer_font_family = Some(FontFamilyName(font.into()));
995 }
996 // TODO: possibly map editor.fontLigatures to buffer_font_features?
997 }
998}
999
1000/// Newtype for a theme name. Its `ParameterizedJsonSchema` lists the theme names known at runtime.
1001#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1002#[serde(transparent)]
1003pub struct ThemeName(pub Arc<str>);
1004
1005inventory::submit! {
1006 ParameterizedJsonSchema {
1007 add_and_get_ref: |generator, _params, cx| {
1008 replace_subschema::<ThemeName>(generator, || json_schema!({
1009 "type": "string",
1010 "enum": ThemeRegistry::global(cx).list_names(),
1011 }))
1012 }
1013 }
1014}
1015
1016/// Newtype for a icon theme name. Its `ParameterizedJsonSchema` lists the icon theme names known at
1017/// runtime.
1018#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1019#[serde(transparent)]
1020pub struct IconThemeName(pub Arc<str>);
1021
1022inventory::submit! {
1023 ParameterizedJsonSchema {
1024 add_and_get_ref: |generator, _params, cx| {
1025 replace_subschema::<IconThemeName>(generator, || json_schema!({
1026 "type": "string",
1027 "enum": ThemeRegistry::global(cx)
1028 .list_icon_themes()
1029 .into_iter()
1030 .map(|icon_theme| icon_theme.name)
1031 .collect::<Vec<SharedString>>(),
1032 }))
1033 }
1034 }
1035}
1036
1037/// Newtype for font family name. Its `ParameterizedJsonSchema` lists the font families known at
1038/// runtime.
1039#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
1040#[serde(transparent)]
1041pub struct FontFamilyName(pub Arc<str>);
1042
1043inventory::submit! {
1044 ParameterizedJsonSchema {
1045 add_and_get_ref: |generator, params, _cx| {
1046 replace_subschema::<FontFamilyName>(generator, || {
1047 json_schema!({
1048 "type": "string",
1049 "enum": params.font_names,
1050 })
1051 })
1052 }
1053 }
1054}
1055
1056fn merge<T: Copy>(target: &mut T, value: Option<T>) {
1057 if let Some(value) = value {
1058 *target = value;
1059 }
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064 use super::*;
1065 use serde_json::json;
1066
1067 #[test]
1068 fn test_buffer_line_height_deserialize_valid() {
1069 assert_eq!(
1070 serde_json::from_value::<BufferLineHeight>(json!("comfortable")).unwrap(),
1071 BufferLineHeight::Comfortable
1072 );
1073 assert_eq!(
1074 serde_json::from_value::<BufferLineHeight>(json!("standard")).unwrap(),
1075 BufferLineHeight::Standard
1076 );
1077 assert_eq!(
1078 serde_json::from_value::<BufferLineHeight>(json!({"custom": 1.0})).unwrap(),
1079 BufferLineHeight::Custom(1.0)
1080 );
1081 assert_eq!(
1082 serde_json::from_value::<BufferLineHeight>(json!({"custom": 1.5})).unwrap(),
1083 BufferLineHeight::Custom(1.5)
1084 );
1085 }
1086
1087 #[test]
1088 fn test_buffer_line_height_deserialize_invalid() {
1089 assert!(
1090 serde_json::from_value::<BufferLineHeight>(json!({"custom": 0.99}))
1091 .err()
1092 .unwrap()
1093 .to_string()
1094 .contains("buffer_line_height.custom must be at least 1.0")
1095 );
1096 assert!(
1097 serde_json::from_value::<BufferLineHeight>(json!({"custom": 0.0}))
1098 .err()
1099 .unwrap()
1100 .to_string()
1101 .contains("buffer_line_height.custom must be at least 1.0")
1102 );
1103 assert!(
1104 serde_json::from_value::<BufferLineHeight>(json!({"custom": -1.0}))
1105 .err()
1106 .unwrap()
1107 .to_string()
1108 .contains("buffer_line_height.custom must be at least 1.0")
1109 );
1110 }
1111}