1use crate::fallback_themes::zed_default_dark;
2use crate::{
3 Appearance, IconTheme, SyntaxTheme, Theme, ThemeRegistry, ThemeStyleContent,
4 DEFAULT_ICON_THEME_NAME,
5};
6use anyhow::Result;
7use derive_more::{Deref, DerefMut};
8use gpui::{
9 px, App, Context, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Global, Pixels,
10 Subscription, Window,
11};
12use refineable::Refineable;
13use schemars::{
14 gen::SchemaGenerator,
15 schema::{InstanceType, Schema, SchemaObject},
16 JsonSchema,
17};
18use serde::{Deserialize, Serialize};
19use serde_json::Value;
20use settings::{add_references_to_properties, Settings, SettingsJsonSchemaParams, SettingsSources};
21use std::sync::Arc;
22use util::ResultExt as _;
23
24const MIN_FONT_SIZE: Pixels = px(6.0);
25const MIN_LINE_HEIGHT: f32 = 1.0;
26
27#[derive(
28 Debug,
29 Default,
30 PartialEq,
31 Eq,
32 PartialOrd,
33 Ord,
34 Hash,
35 Clone,
36 Copy,
37 Serialize,
38 Deserialize,
39 JsonSchema,
40)]
41
42/// Specifies the density of the UI.
43/// Note: This setting is still experimental. See [this tracking issue](https://github.com/zed-industries/zed/issues/18078)
44#[serde(rename_all = "snake_case")]
45pub enum UiDensity {
46 /// A denser UI with tighter spacing and smaller elements.
47 #[serde(alias = "compact")]
48 Compact,
49 #[default]
50 #[serde(alias = "default")]
51 /// The default UI density.
52 Default,
53 #[serde(alias = "comfortable")]
54 /// A looser UI with more spacing and larger elements.
55 Comfortable,
56}
57
58impl UiDensity {
59 /// The spacing ratio of a given density.
60 /// TODO: Standardize usage throughout the app or remove
61 pub fn spacing_ratio(self) -> f32 {
62 match self {
63 UiDensity::Compact => 0.75,
64 UiDensity::Default => 1.0,
65 UiDensity::Comfortable => 1.25,
66 }
67 }
68}
69
70impl From<String> for UiDensity {
71 fn from(s: String) -> Self {
72 match s.as_str() {
73 "compact" => Self::Compact,
74 "default" => Self::Default,
75 "comfortable" => Self::Comfortable,
76 _ => Self::default(),
77 }
78 }
79}
80
81impl From<UiDensity> for String {
82 fn from(val: UiDensity) -> Self {
83 match val {
84 UiDensity::Compact => "compact".to_string(),
85 UiDensity::Default => "default".to_string(),
86 UiDensity::Comfortable => "comfortable".to_string(),
87 }
88 }
89}
90
91/// Customizable settings for the UI and theme system.
92#[derive(Clone, PartialEq)]
93pub struct ThemeSettings {
94 /// The UI font size. Determines the size of text in the UI,
95 /// as well as the size of a [gpui::Rems] unit.
96 ///
97 /// Changing this will impact the size of all UI elements.
98 pub ui_font_size: Pixels,
99 /// The font used for UI elements.
100 pub ui_font: Font,
101 /// The font size used for buffers, and the terminal.
102 ///
103 /// The terminal font size can be overridden using it's own setting.
104 pub buffer_font_size: Pixels,
105 /// The font used for buffers, and the terminal.
106 ///
107 /// The terminal font family can be overridden using it's own setting.
108 pub buffer_font: Font,
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 theme_overrides: Option<ThemeStyleContent>,
123 /// The current icon theme selection.
124 pub icon_theme_selection: Option<IconThemeSelection>,
125 /// The active icon theme.
126 pub active_icon_theme: Arc<IconTheme>,
127 /// The density of the UI.
128 /// Note: This setting is still experimental. See [this tracking issue](
129 pub ui_density: UiDensity,
130 /// The amount of fading applied to unnecessary code.
131 pub unnecessary_code_fade: f32,
132}
133
134impl ThemeSettings {
135 const DEFAULT_LIGHT_THEME: &'static str = "One Light";
136 const DEFAULT_DARK_THEME: &'static str = "One Dark";
137
138 /// Returns the name of the default theme for the given [`Appearance`].
139 pub fn default_theme(appearance: Appearance) -> &'static str {
140 match appearance {
141 Appearance::Light => Self::DEFAULT_LIGHT_THEME,
142 Appearance::Dark => Self::DEFAULT_DARK_THEME,
143 }
144 }
145
146 /// Reloads the current theme.
147 ///
148 /// Reads the [`ThemeSettings`] to know which theme should be loaded,
149 /// taking into account the current [`SystemAppearance`].
150 pub fn reload_current_theme(cx: &mut App) {
151 let mut theme_settings = ThemeSettings::get_global(cx).clone();
152 let system_appearance = SystemAppearance::global(cx);
153
154 if let Some(theme_selection) = theme_settings.theme_selection.clone() {
155 let mut theme_name = theme_selection.theme(*system_appearance);
156
157 // If the selected theme doesn't exist, fall back to a default theme
158 // based on the system appearance.
159 let theme_registry = ThemeRegistry::global(cx);
160 if theme_registry.get(theme_name).ok().is_none() {
161 theme_name = Self::default_theme(*system_appearance);
162 };
163
164 if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {
165 ThemeSettings::override_global(theme_settings, cx);
166 }
167 }
168 }
169
170 /// Reloads the current icon theme.
171 ///
172 /// Reads the [`ThemeSettings`] to know which icon theme should be loaded,
173 /// taking into account the current [`SystemAppearance`].
174 pub fn reload_current_icon_theme(cx: &mut App) {
175 let mut theme_settings = ThemeSettings::get_global(cx).clone();
176 let system_appearance = SystemAppearance::global(cx);
177
178 if let Some(icon_theme_selection) = theme_settings.icon_theme_selection.clone() {
179 let mut icon_theme_name = icon_theme_selection.icon_theme(*system_appearance);
180
181 // If the selected icon theme doesn't exist, fall back to the default theme.
182 let theme_registry = ThemeRegistry::global(cx);
183 if theme_registry
184 .get_icon_theme(icon_theme_name)
185 .ok()
186 .is_none()
187 {
188 icon_theme_name = DEFAULT_ICON_THEME_NAME;
189 };
190
191 if let Some(_theme) = theme_settings.switch_icon_theme(icon_theme_name, cx) {
192 ThemeSettings::override_global(theme_settings, cx);
193 }
194 }
195 }
196}
197
198/// The appearance of the system.
199#[derive(Debug, Clone, Copy, Deref)]
200pub struct SystemAppearance(pub Appearance);
201
202impl Default for SystemAppearance {
203 fn default() -> Self {
204 Self(Appearance::Dark)
205 }
206}
207
208#[derive(Deref, DerefMut, Default)]
209struct GlobalSystemAppearance(SystemAppearance);
210
211impl Global for GlobalSystemAppearance {}
212
213impl SystemAppearance {
214 /// Initializes the [`SystemAppearance`] for the application.
215 pub fn init(cx: &mut App) {
216 *cx.default_global::<GlobalSystemAppearance>() =
217 GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
218 }
219
220 /// Returns the global [`SystemAppearance`].
221 ///
222 /// Inserts a default [`SystemAppearance`] if one does not yet exist.
223 pub(crate) fn default_global(cx: &mut App) -> Self {
224 cx.default_global::<GlobalSystemAppearance>().0
225 }
226
227 /// Returns the global [`SystemAppearance`].
228 pub fn global(cx: &App) -> Self {
229 cx.global::<GlobalSystemAppearance>().0
230 }
231
232 /// Returns a mutable reference to the global [`SystemAppearance`].
233 pub fn global_mut(cx: &mut App) -> &mut Self {
234 cx.global_mut::<GlobalSystemAppearance>()
235 }
236}
237
238#[derive(Default)]
239pub(crate) struct AdjustedBufferFontSize(Pixels);
240
241impl Global for AdjustedBufferFontSize {}
242
243#[derive(Default)]
244pub(crate) struct AdjustedUiFontSize(Pixels);
245
246impl Global for AdjustedUiFontSize {}
247
248/// Represents the selection of a theme, which can be either static or dynamic.
249#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
250#[serde(untagged)]
251pub enum ThemeSelection {
252 /// A static theme selection, represented by a single theme name.
253 Static(#[schemars(schema_with = "theme_name_ref")] String),
254 /// A dynamic theme selection, which can change based the [ThemeMode].
255 Dynamic {
256 /// The mode used to determine which theme to use.
257 #[serde(default)]
258 mode: ThemeMode,
259 /// The theme to use for light mode.
260 #[schemars(schema_with = "theme_name_ref")]
261 light: String,
262 /// The theme to use for dark mode.
263 #[schemars(schema_with = "theme_name_ref")]
264 dark: String,
265 },
266}
267
268fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {
269 Schema::new_ref("#/definitions/ThemeName".into())
270}
271
272// TODO: Rename ThemeMode -> ThemeAppearanceMode
273/// The mode use to select a theme.
274///
275/// `Light` and `Dark` will select their respective themes.
276///
277/// `System` will select the theme based on the system's appearance.
278#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
279#[serde(rename_all = "snake_case")]
280pub enum ThemeMode {
281 /// Use the specified `light` theme.
282 Light,
283
284 /// Use the specified `dark` theme.
285 Dark,
286
287 /// Use the theme based on the system's appearance.
288 #[default]
289 System,
290}
291
292impl ThemeSelection {
293 /// Returns the theme name for the selected [ThemeMode].
294 pub fn theme(&self, system_appearance: Appearance) -> &str {
295 match self {
296 Self::Static(theme) => theme,
297 Self::Dynamic { mode, light, dark } => match mode {
298 ThemeMode::Light => light,
299 ThemeMode::Dark => dark,
300 ThemeMode::System => match system_appearance {
301 Appearance::Light => light,
302 Appearance::Dark => dark,
303 },
304 },
305 }
306 }
307
308 /// Returns the [ThemeMode] for the [ThemeSelection].
309 pub fn mode(&self) -> Option<ThemeMode> {
310 match self {
311 ThemeSelection::Static(_) => None,
312 ThemeSelection::Dynamic { mode, .. } => Some(*mode),
313 }
314 }
315}
316
317fn icon_theme_name_ref(_: &mut SchemaGenerator) -> Schema {
318 Schema::new_ref("#/definitions/IconThemeName".into())
319}
320
321/// Represents the selection of an icon theme, which can be either static or dynamic.
322#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
323#[serde(untagged)]
324pub enum IconThemeSelection {
325 /// A static icon theme selection, represented by a single icon theme name.
326 Static(#[schemars(schema_with = "icon_theme_name_ref")] String),
327 /// A dynamic icon theme selection, which can change based on the [`ThemeMode`].
328 Dynamic {
329 /// The mode used to determine which theme to use.
330 #[serde(default)]
331 mode: ThemeMode,
332 /// The icon theme to use for light mode.
333 #[schemars(schema_with = "icon_theme_name_ref")]
334 light: String,
335 /// The icon theme to use for dark mode.
336 #[schemars(schema_with = "icon_theme_name_ref")]
337 dark: String,
338 },
339}
340
341impl IconThemeSelection {
342 /// Returns the icon theme name based on the given [`Appearance`].
343 pub fn icon_theme(&self, system_appearance: Appearance) -> &str {
344 match self {
345 Self::Static(theme) => theme,
346 Self::Dynamic { mode, light, dark } => match mode {
347 ThemeMode::Light => light,
348 ThemeMode::Dark => dark,
349 ThemeMode::System => match system_appearance {
350 Appearance::Light => light,
351 Appearance::Dark => dark,
352 },
353 },
354 }
355 }
356
357 /// Returns the [`ThemeMode`] for the [`IconThemeSelection`].
358 pub fn mode(&self) -> Option<ThemeMode> {
359 match self {
360 IconThemeSelection::Static(_) => None,
361 IconThemeSelection::Dynamic { mode, .. } => Some(*mode),
362 }
363 }
364}
365
366/// Settings for rendering text in UI and text buffers.
367#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
368pub struct ThemeSettingsContent {
369 /// The default font size for text in the UI.
370 #[serde(default)]
371 pub ui_font_size: Option<f32>,
372 /// The name of a font to use for rendering in the UI.
373 #[serde(default)]
374 pub ui_font_family: Option<String>,
375 /// The font fallbacks to use for rendering in the UI.
376 #[serde(default)]
377 #[schemars(default = "default_font_fallbacks")]
378 pub ui_font_fallbacks: Option<Vec<String>>,
379 /// The OpenType features to enable for text in the UI.
380 #[serde(default)]
381 #[schemars(default = "default_font_features")]
382 pub ui_font_features: Option<FontFeatures>,
383 /// The weight of the UI font in CSS units from 100 to 900.
384 #[serde(default)]
385 pub ui_font_weight: Option<f32>,
386 /// The name of a font to use for rendering in text buffers.
387 #[serde(default)]
388 pub buffer_font_family: Option<String>,
389 /// The font fallbacks to use for rendering in text buffers.
390 #[serde(default)]
391 #[schemars(default = "default_font_fallbacks")]
392 pub buffer_font_fallbacks: Option<Vec<String>>,
393 /// The default font size for rendering in text buffers.
394 #[serde(default)]
395 pub buffer_font_size: Option<f32>,
396 /// The weight of the editor font in CSS units from 100 to 900.
397 #[serde(default)]
398 pub buffer_font_weight: Option<f32>,
399 /// The buffer's line height.
400 #[serde(default)]
401 pub buffer_line_height: Option<BufferLineHeight>,
402 /// The OpenType features to enable for rendering in text buffers.
403 #[serde(default)]
404 #[schemars(default = "default_font_features")]
405 pub buffer_font_features: Option<FontFeatures>,
406 /// The name of the Zed theme to use.
407 #[serde(default)]
408 pub theme: Option<ThemeSelection>,
409 /// The name of the icon theme to use.
410 #[serde(default)]
411 pub icon_theme: Option<IconThemeSelection>,
412
413 /// UNSTABLE: Expect many elements to be broken.
414 ///
415 // Controls the density of the UI.
416 #[serde(rename = "unstable.ui_density", default)]
417 pub ui_density: Option<UiDensity>,
418
419 /// How much to fade out unused code.
420 #[serde(default)]
421 pub unnecessary_code_fade: Option<f32>,
422
423 /// EXPERIMENTAL: Overrides for the current theme.
424 ///
425 /// These values will override the ones on the current theme specified in `theme`.
426 #[serde(rename = "experimental.theme_overrides", default)]
427 pub theme_overrides: Option<ThemeStyleContent>,
428}
429
430fn default_font_features() -> Option<FontFeatures> {
431 Some(FontFeatures::default())
432}
433
434fn default_font_fallbacks() -> Option<FontFallbacks> {
435 Some(FontFallbacks::default())
436}
437
438impl ThemeSettingsContent {
439 /// Sets the theme for the given appearance to the theme with the specified name.
440 pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {
441 if let Some(selection) = self.theme.as_mut() {
442 let theme_to_update = match selection {
443 ThemeSelection::Static(theme) => theme,
444 ThemeSelection::Dynamic { mode, light, dark } => match mode {
445 ThemeMode::Light => light,
446 ThemeMode::Dark => dark,
447 ThemeMode::System => match appearance {
448 Appearance::Light => light,
449 Appearance::Dark => dark,
450 },
451 },
452 };
453
454 *theme_to_update = theme_name.to_string();
455 } else {
456 self.theme = Some(ThemeSelection::Static(theme_name.to_string()));
457 }
458 }
459
460 /// Sets the icon theme for the given appearance to the icon theme with the specified name.
461 pub fn set_icon_theme(&mut self, icon_theme_name: String, appearance: Appearance) {
462 if let Some(selection) = self.icon_theme.as_mut() {
463 let icon_theme_to_update = match selection {
464 IconThemeSelection::Static(theme) => theme,
465 IconThemeSelection::Dynamic { mode, light, dark } => match mode {
466 ThemeMode::Light => light,
467 ThemeMode::Dark => dark,
468 ThemeMode::System => match appearance {
469 Appearance::Light => light,
470 Appearance::Dark => dark,
471 },
472 },
473 };
474
475 *icon_theme_to_update = icon_theme_name.to_string();
476 } else {
477 self.icon_theme = Some(IconThemeSelection::Static(icon_theme_name.to_string()));
478 }
479 }
480
481 /// Sets the mode for the theme.
482 pub fn set_mode(&mut self, mode: ThemeMode) {
483 if let Some(selection) = self.theme.as_mut() {
484 match selection {
485 ThemeSelection::Static(theme) => {
486 // If the theme was previously set to a single static theme,
487 // we don't know whether it was a light or dark theme, so we
488 // just use it for both.
489 self.theme = Some(ThemeSelection::Dynamic {
490 mode,
491 light: theme.clone(),
492 dark: theme.clone(),
493 });
494 }
495 ThemeSelection::Dynamic {
496 mode: mode_to_update,
497 ..
498 } => *mode_to_update = mode,
499 }
500 } else {
501 self.theme = Some(ThemeSelection::Dynamic {
502 mode,
503 light: ThemeSettings::DEFAULT_LIGHT_THEME.into(),
504 dark: ThemeSettings::DEFAULT_DARK_THEME.into(),
505 });
506 }
507
508 if let Some(selection) = self.icon_theme.as_mut() {
509 match selection {
510 IconThemeSelection::Static(icon_theme) => {
511 // If the icon theme was previously set to a single static
512 // theme, we don't know whether it was a light or dark
513 // theme, so we just use it for both.
514 self.icon_theme = Some(IconThemeSelection::Dynamic {
515 mode,
516 light: icon_theme.clone(),
517 dark: icon_theme.clone(),
518 });
519 }
520 IconThemeSelection::Dynamic {
521 mode: mode_to_update,
522 ..
523 } => *mode_to_update = mode,
524 }
525 } else {
526 self.icon_theme = Some(IconThemeSelection::Static(DEFAULT_ICON_THEME_NAME.into()));
527 }
528 }
529}
530
531/// The buffer's line height.
532#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
533#[serde(rename_all = "snake_case")]
534pub enum BufferLineHeight {
535 /// A less dense line height.
536 #[default]
537 Comfortable,
538 /// The default line height.
539 Standard,
540 /// A custom line height.
541 ///
542 /// A line height of 1.0 is the height of the buffer's font size.
543 Custom(f32),
544}
545
546impl BufferLineHeight {
547 /// Returns the value of the line height.
548 pub fn value(&self) -> f32 {
549 match self {
550 BufferLineHeight::Comfortable => 1.618,
551 BufferLineHeight::Standard => 1.3,
552 BufferLineHeight::Custom(line_height) => *line_height,
553 }
554 }
555}
556
557impl ThemeSettings {
558 /// Returns the buffer font size.
559 pub fn buffer_font_size(&self, cx: &App) -> Pixels {
560 cx.try_global::<AdjustedBufferFontSize>()
561 .map_or(self.buffer_font_size, |size| size.0)
562 .max(MIN_FONT_SIZE)
563 }
564
565 // TODO: Rename: `line_height` -> `buffer_line_height`
566 /// Returns the buffer's line height.
567 pub fn line_height(&self) -> f32 {
568 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
569 }
570
571 /// Switches to the theme with the given name, if it exists.
572 ///
573 /// Returns a `Some` containing the new theme if it was successful.
574 /// Returns `None` otherwise.
575 pub fn switch_theme(&mut self, theme: &str, cx: &mut App) -> Option<Arc<Theme>> {
576 let themes = ThemeRegistry::default_global(cx);
577
578 let mut new_theme = None;
579
580 if let Some(theme) = themes.get(theme).log_err() {
581 self.active_theme = theme.clone();
582 new_theme = Some(theme);
583 }
584
585 self.apply_theme_overrides();
586
587 new_theme
588 }
589
590 /// Applies the theme overrides, if there are any, to the current theme.
591 pub fn apply_theme_overrides(&mut self) {
592 if let Some(theme_overrides) = &self.theme_overrides {
593 let mut base_theme = (*self.active_theme).clone();
594
595 if let Some(window_background_appearance) = theme_overrides.window_background_appearance
596 {
597 base_theme.styles.window_background_appearance =
598 window_background_appearance.into();
599 }
600
601 base_theme
602 .styles
603 .colors
604 .refine(&theme_overrides.theme_colors_refinement());
605 base_theme
606 .styles
607 .status
608 .refine(&theme_overrides.status_colors_refinement());
609 base_theme.styles.player.merge(&theme_overrides.players);
610 base_theme.styles.accents.merge(&theme_overrides.accents);
611 base_theme.styles.syntax =
612 SyntaxTheme::merge(base_theme.styles.syntax, theme_overrides.syntax_overrides());
613
614 self.active_theme = Arc::new(base_theme);
615 }
616 }
617
618 /// Switches to the icon theme with the given name, if it exists.
619 ///
620 /// Returns a `Some` containing the new icon theme if it was successful.
621 /// Returns `None` otherwise.
622 pub fn switch_icon_theme(&mut self, icon_theme: &str, cx: &mut App) -> Option<Arc<IconTheme>> {
623 let themes = ThemeRegistry::default_global(cx);
624
625 let mut new_icon_theme = None;
626
627 if let Some(icon_theme) = themes.get_icon_theme(icon_theme).log_err() {
628 self.active_icon_theme = icon_theme.clone();
629 new_icon_theme = Some(icon_theme);
630 cx.refresh_windows();
631 }
632
633 new_icon_theme
634 }
635}
636
637/// Observe changes to the adjusted buffer font size.
638pub fn observe_buffer_font_size_adjustment<V: 'static>(
639 cx: &mut Context<V>,
640 f: impl 'static + Fn(&mut V, &mut Context<V>),
641) -> Subscription {
642 cx.observe_global::<AdjustedBufferFontSize>(f)
643}
644
645/// Sets the adjusted buffer font size.
646pub fn adjusted_font_size(size: Pixels, cx: &App) -> Pixels {
647 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
648 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
649 let delta = *adjusted_size - buffer_font_size;
650 size + delta
651 } else {
652 size
653 }
654 .max(MIN_FONT_SIZE)
655}
656
657/// Returns the adjusted buffer font size.
658pub fn get_buffer_font_size(cx: &App) -> Pixels {
659 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
660 cx.try_global::<AdjustedBufferFontSize>()
661 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0)
662}
663
664/// Adjusts the buffer font size.
665pub fn adjust_buffer_font_size(cx: &mut App, mut f: impl FnMut(&mut Pixels)) {
666 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
667 let mut adjusted_size = cx
668 .try_global::<AdjustedBufferFontSize>()
669 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
670
671 f(&mut adjusted_size);
672 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
673 cx.set_global(AdjustedBufferFontSize(adjusted_size));
674 cx.refresh_windows();
675}
676
677/// Returns whether the buffer font size has been adjusted.
678pub fn has_adjusted_buffer_font_size(cx: &App) -> bool {
679 cx.has_global::<AdjustedBufferFontSize>()
680}
681
682/// Resets the buffer font size to the default value.
683pub fn reset_buffer_font_size(cx: &mut App) {
684 if cx.has_global::<AdjustedBufferFontSize>() {
685 cx.remove_global::<AdjustedBufferFontSize>();
686 cx.refresh_windows();
687 }
688}
689
690// TODO: Make private, change usages to use `get_ui_font_size` instead.
691#[allow(missing_docs)]
692pub fn setup_ui_font(window: &mut Window, cx: &mut App) -> gpui::Font {
693 let (ui_font, ui_font_size) = {
694 let theme_settings = ThemeSettings::get_global(cx);
695 let font = theme_settings.ui_font.clone();
696 (font, get_ui_font_size(cx))
697 };
698
699 window.set_rem_size(ui_font_size);
700 ui_font
701}
702
703/// Gets the adjusted UI font size.
704pub fn get_ui_font_size(cx: &App) -> Pixels {
705 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
706 cx.try_global::<AdjustedUiFontSize>()
707 .map_or(ui_font_size, |adjusted_size| adjusted_size.0)
708}
709
710/// Sets the adjusted UI font size.
711pub fn adjust_ui_font_size(cx: &mut App, mut f: impl FnMut(&mut Pixels)) {
712 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
713 let mut adjusted_size = cx
714 .try_global::<AdjustedUiFontSize>()
715 .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
716
717 f(&mut adjusted_size);
718 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
719 cx.set_global(AdjustedUiFontSize(adjusted_size));
720 cx.refresh_windows();
721}
722
723/// Returns whether the UI font size has been adjusted.
724pub fn has_adjusted_ui_font_size(cx: &App) -> bool {
725 cx.has_global::<AdjustedUiFontSize>()
726}
727
728/// Resets the UI font size to the default value.
729pub fn reset_ui_font_size(cx: &mut App) {
730 if cx.has_global::<AdjustedUiFontSize>() {
731 cx.remove_global::<AdjustedUiFontSize>();
732 cx.refresh_windows();
733 }
734}
735
736fn clamp_font_weight(weight: f32) -> FontWeight {
737 FontWeight(weight.clamp(100., 950.))
738}
739
740impl settings::Settings for ThemeSettings {
741 const KEY: Option<&'static str> = None;
742
743 type FileContent = ThemeSettingsContent;
744
745 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self> {
746 let themes = ThemeRegistry::default_global(cx);
747 let system_appearance = SystemAppearance::default_global(cx);
748
749 let defaults = sources.default;
750 let mut this = Self {
751 ui_font_size: defaults.ui_font_size.unwrap().into(),
752 ui_font: Font {
753 family: defaults.ui_font_family.as_ref().unwrap().clone().into(),
754 features: defaults.ui_font_features.clone().unwrap(),
755 fallbacks: defaults
756 .ui_font_fallbacks
757 .as_ref()
758 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
759 weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
760 style: Default::default(),
761 },
762 buffer_font: Font {
763 family: defaults.buffer_font_family.as_ref().unwrap().clone().into(),
764 features: defaults.buffer_font_features.clone().unwrap(),
765 fallbacks: defaults
766 .buffer_font_fallbacks
767 .as_ref()
768 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
769 weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
770 style: FontStyle::default(),
771 },
772 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
773 buffer_line_height: defaults.buffer_line_height.unwrap(),
774 theme_selection: defaults.theme.clone(),
775 active_theme: themes
776 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
777 .or(themes.get(&zed_default_dark().name))
778 .unwrap(),
779 theme_overrides: None,
780 icon_theme_selection: defaults.icon_theme.clone(),
781 active_icon_theme: defaults
782 .icon_theme
783 .as_ref()
784 .and_then(|selection| {
785 themes
786 .get_icon_theme(selection.icon_theme(*system_appearance))
787 .ok()
788 })
789 .unwrap_or_else(|| themes.get_icon_theme(DEFAULT_ICON_THEME_NAME).unwrap()),
790 ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
791 unnecessary_code_fade: defaults.unnecessary_code_fade.unwrap_or(0.0),
792 };
793
794 for value in sources
795 .user
796 .into_iter()
797 .chain(sources.release_channel)
798 .chain(sources.server)
799 {
800 if let Some(value) = value.ui_density {
801 this.ui_density = value;
802 }
803
804 if let Some(value) = value.buffer_font_family.clone() {
805 this.buffer_font.family = value.into();
806 }
807 if let Some(value) = value.buffer_font_features.clone() {
808 this.buffer_font.features = value;
809 }
810 if let Some(value) = value.buffer_font_fallbacks.clone() {
811 this.buffer_font.fallbacks = Some(FontFallbacks::from_fonts(value));
812 }
813 if let Some(value) = value.buffer_font_weight {
814 this.buffer_font.weight = clamp_font_weight(value);
815 }
816
817 if let Some(value) = value.ui_font_family.clone() {
818 this.ui_font.family = value.into();
819 }
820 if let Some(value) = value.ui_font_features.clone() {
821 this.ui_font.features = value;
822 }
823 if let Some(value) = value.ui_font_fallbacks.clone() {
824 this.ui_font.fallbacks = Some(FontFallbacks::from_fonts(value));
825 }
826 if let Some(value) = value.ui_font_weight {
827 this.ui_font.weight = clamp_font_weight(value);
828 }
829
830 if let Some(value) = &value.theme {
831 this.theme_selection = Some(value.clone());
832
833 let theme_name = value.theme(*system_appearance);
834
835 if let Some(theme) = themes.get(theme_name).log_err() {
836 this.active_theme = theme;
837 }
838 }
839
840 this.theme_overrides.clone_from(&value.theme_overrides);
841 this.apply_theme_overrides();
842
843 if let Some(value) = &value.icon_theme {
844 this.icon_theme_selection = Some(value.clone());
845
846 let icon_theme_name = value.icon_theme(*system_appearance);
847
848 if let Some(icon_theme) = themes.get_icon_theme(icon_theme_name).log_err() {
849 this.active_icon_theme = icon_theme;
850 }
851 }
852
853 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
854 this.ui_font_size = this.ui_font_size.clamp(px(6.), px(100.));
855
856 merge(
857 &mut this.buffer_font_size,
858 value.buffer_font_size.map(Into::into),
859 );
860 this.buffer_font_size = this.buffer_font_size.clamp(px(6.), px(100.));
861
862 merge(&mut this.buffer_line_height, value.buffer_line_height);
863
864 // Clamp the `unnecessary_code_fade` to ensure text can't disappear entirely.
865 merge(&mut this.unnecessary_code_fade, value.unnecessary_code_fade);
866 this.unnecessary_code_fade = this.unnecessary_code_fade.clamp(0.0, 0.9);
867 }
868
869 Ok(this)
870 }
871
872 fn json_schema(
873 generator: &mut SchemaGenerator,
874 params: &SettingsJsonSchemaParams,
875 cx: &App,
876 ) -> schemars::schema::RootSchema {
877 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
878 let theme_names = ThemeRegistry::global(cx)
879 .list_names()
880 .into_iter()
881 .map(|theme_name| Value::String(theme_name.to_string()))
882 .collect();
883
884 let theme_name_schema = SchemaObject {
885 instance_type: Some(InstanceType::String.into()),
886 enum_values: Some(theme_names),
887 ..Default::default()
888 };
889
890 let icon_theme_names = ThemeRegistry::global(cx)
891 .list_icon_themes()
892 .into_iter()
893 .map(|icon_theme| Value::String(icon_theme.name.to_string()))
894 .collect();
895
896 let icon_theme_name_schema = SchemaObject {
897 instance_type: Some(InstanceType::String.into()),
898 enum_values: Some(icon_theme_names),
899 ..Default::default()
900 };
901
902 root_schema.definitions.extend([
903 ("ThemeName".into(), theme_name_schema.into()),
904 ("IconThemeName".into(), icon_theme_name_schema.into()),
905 ("FontFamilies".into(), params.font_family_schema()),
906 ("FontFallbacks".into(), params.font_fallback_schema()),
907 ]);
908
909 add_references_to_properties(
910 &mut root_schema,
911 &[
912 ("buffer_font_family", "#/definitions/FontFamilies"),
913 ("buffer_font_fallbacks", "#/definitions/FontFallbacks"),
914 ("ui_font_family", "#/definitions/FontFamilies"),
915 ("ui_font_fallbacks", "#/definitions/FontFallbacks"),
916 ],
917 );
918
919 root_schema
920 }
921}
922
923fn merge<T: Copy>(target: &mut T, value: Option<T>) {
924 if let Some(value) = value {
925 *target = value;
926 }
927}