settings.rs

  1use crate::one_themes::one_dark;
  2use crate::{Appearance, SyntaxTheme, Theme, ThemeRegistry, ThemeStyleContent};
  3use anyhow::Result;
  4use derive_more::{Deref, DerefMut};
  5use gpui::{
  6    px, AppContext, Font, FontFallbacks, FontFeatures, FontStyle, FontWeight, Global, Pixels,
  7    Subscription, ViewContext, WindowContext,
  8};
  9use refineable::Refineable;
 10use schemars::{
 11    gen::SchemaGenerator,
 12    schema::{InstanceType, Schema, SchemaObject},
 13    JsonSchema,
 14};
 15use serde::{Deserialize, Serialize};
 16use serde_json::Value;
 17use settings::{add_references_to_properties, Settings, SettingsJsonSchemaParams, SettingsSources};
 18use std::sync::Arc;
 19use util::ResultExt as _;
 20
 21const MIN_FONT_SIZE: Pixels = px(6.0);
 22const MIN_LINE_HEIGHT: f32 = 1.0;
 23
 24#[derive(
 25    Debug,
 26    Default,
 27    PartialEq,
 28    Eq,
 29    PartialOrd,
 30    Ord,
 31    Hash,
 32    Clone,
 33    Copy,
 34    Serialize,
 35    Deserialize,
 36    JsonSchema,
 37)]
 38#[serde(rename_all = "snake_case")]
 39pub enum UiDensity {
 40    /// A denser UI with tighter spacing and smaller elements.
 41    #[serde(alias = "compact")]
 42    Compact,
 43    #[default]
 44    #[serde(alias = "default")]
 45    /// The default UI density.
 46    Default,
 47    #[serde(alias = "comfortable")]
 48    /// A looser UI with more spacing and larger elements.
 49    Comfortable,
 50}
 51
 52impl UiDensity {
 53    pub fn spacing_ratio(self) -> f32 {
 54        match self {
 55            UiDensity::Compact => 0.75,
 56            UiDensity::Default => 1.0,
 57            UiDensity::Comfortable => 1.25,
 58        }
 59    }
 60}
 61
 62impl From<String> for UiDensity {
 63    fn from(s: String) -> Self {
 64        match s.as_str() {
 65            "compact" => Self::Compact,
 66            "default" => Self::Default,
 67            "comfortable" => Self::Comfortable,
 68            _ => Self::default(),
 69        }
 70    }
 71}
 72
 73impl From<UiDensity> for String {
 74    fn from(val: UiDensity) -> Self {
 75        match val {
 76            UiDensity::Compact => "compact".to_string(),
 77            UiDensity::Default => "default".to_string(),
 78            UiDensity::Comfortable => "comfortable".to_string(),
 79        }
 80    }
 81}
 82
 83#[derive(Clone)]
 84pub struct ThemeSettings {
 85    pub ui_font_size: Pixels,
 86    pub ui_font: Font,
 87    pub buffer_font: Font,
 88    pub buffer_font_size: Pixels,
 89    pub buffer_line_height: BufferLineHeight,
 90    pub theme_selection: Option<ThemeSelection>,
 91    pub active_theme: Arc<Theme>,
 92    pub theme_overrides: Option<ThemeStyleContent>,
 93    pub ui_density: UiDensity,
 94    pub unnecessary_code_fade: f32,
 95}
 96
 97impl ThemeSettings {
 98    const DEFAULT_LIGHT_THEME: &'static str = "One Light";
 99    const DEFAULT_DARK_THEME: &'static str = "One Dark";
100
101    /// Returns the name of the default theme for the given [`Appearance`].
102    pub fn default_theme(appearance: Appearance) -> &'static str {
103        match appearance {
104            Appearance::Light => Self::DEFAULT_LIGHT_THEME,
105            Appearance::Dark => Self::DEFAULT_DARK_THEME,
106        }
107    }
108
109    /// Reloads the current theme.
110    ///
111    /// Reads the [`ThemeSettings`] to know which theme should be loaded,
112    /// taking into account the current [`SystemAppearance`].
113    pub fn reload_current_theme(cx: &mut AppContext) {
114        let mut theme_settings = ThemeSettings::get_global(cx).clone();
115        let system_appearance = SystemAppearance::global(cx);
116
117        if let Some(theme_selection) = theme_settings.theme_selection.clone() {
118            let mut theme_name = theme_selection.theme(*system_appearance);
119
120            // If the selected theme doesn't exist, fall back to a default theme
121            // based on the system appearance.
122            let theme_registry = ThemeRegistry::global(cx);
123            if theme_registry.get(theme_name).ok().is_none() {
124                theme_name = Self::default_theme(*system_appearance);
125            };
126
127            if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {
128                ThemeSettings::override_global(theme_settings, cx);
129            }
130        }
131    }
132}
133
134/// The appearance of the system.
135#[derive(Debug, Clone, Copy, Deref)]
136pub struct SystemAppearance(pub Appearance);
137
138impl Default for SystemAppearance {
139    fn default() -> Self {
140        Self(Appearance::Dark)
141    }
142}
143
144#[derive(Deref, DerefMut, Default)]
145struct GlobalSystemAppearance(SystemAppearance);
146
147impl Global for GlobalSystemAppearance {}
148
149impl SystemAppearance {
150    /// Initializes the [`SystemAppearance`] for the application.
151    pub fn init(cx: &mut AppContext) {
152        *cx.default_global::<GlobalSystemAppearance>() =
153            GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
154    }
155
156    /// Returns the global [`SystemAppearance`].
157    ///
158    /// Inserts a default [`SystemAppearance`] if one does not yet exist.
159    pub(crate) fn default_global(cx: &mut AppContext) -> Self {
160        cx.default_global::<GlobalSystemAppearance>().0
161    }
162
163    /// Returns the global [`SystemAppearance`].
164    pub fn global(cx: &AppContext) -> Self {
165        cx.global::<GlobalSystemAppearance>().0
166    }
167
168    /// Returns a mutable reference to the global [`SystemAppearance`].
169    pub fn global_mut(cx: &mut AppContext) -> &mut Self {
170        cx.global_mut::<GlobalSystemAppearance>()
171    }
172}
173
174#[derive(Default)]
175pub(crate) struct AdjustedBufferFontSize(Pixels);
176
177impl Global for AdjustedBufferFontSize {}
178
179#[derive(Default)]
180pub(crate) struct AdjustedUiFontSize(Pixels);
181
182impl Global for AdjustedUiFontSize {}
183
184#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
185#[serde(untagged)]
186pub enum ThemeSelection {
187    Static(#[schemars(schema_with = "theme_name_ref")] String),
188    Dynamic {
189        #[serde(default)]
190        mode: ThemeMode,
191        #[schemars(schema_with = "theme_name_ref")]
192        light: String,
193        #[schemars(schema_with = "theme_name_ref")]
194        dark: String,
195    },
196}
197
198fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {
199    Schema::new_ref("#/definitions/ThemeName".into())
200}
201
202#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
203#[serde(rename_all = "snake_case")]
204pub enum ThemeMode {
205    /// Use the specified `light` theme.
206    Light,
207
208    /// Use the specified `dark` theme.
209    Dark,
210
211    /// Use the theme based on the system's appearance.
212    #[default]
213    System,
214}
215
216impl ThemeSelection {
217    pub fn theme(&self, system_appearance: Appearance) -> &str {
218        match self {
219            Self::Static(theme) => theme,
220            Self::Dynamic { mode, light, dark } => match mode {
221                ThemeMode::Light => light,
222                ThemeMode::Dark => dark,
223                ThemeMode::System => match system_appearance {
224                    Appearance::Light => light,
225                    Appearance::Dark => dark,
226                },
227            },
228        }
229    }
230
231    pub fn mode(&self) -> Option<ThemeMode> {
232        match self {
233            ThemeSelection::Static(_) => None,
234            ThemeSelection::Dynamic { mode, .. } => Some(*mode),
235        }
236    }
237}
238
239/// Settings for rendering text in UI and text buffers.
240#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
241pub struct ThemeSettingsContent {
242    /// The default font size for text in the UI.
243    #[serde(default)]
244    pub ui_font_size: Option<f32>,
245    /// The name of a font to use for rendering in the UI.
246    #[serde(default)]
247    pub ui_font_family: Option<String>,
248    /// The font fallbacks to use for rendering in the UI.
249    #[serde(default)]
250    #[schemars(default = "default_font_fallbacks")]
251    pub ui_font_fallbacks: Option<Vec<String>>,
252    /// The OpenType features to enable for text in the UI.
253    #[serde(default)]
254    #[schemars(default = "default_font_features")]
255    pub ui_font_features: Option<FontFeatures>,
256    /// The weight of the UI font in CSS units from 100 to 900.
257    #[serde(default)]
258    pub ui_font_weight: Option<f32>,
259    /// The name of a font to use for rendering in text buffers.
260    #[serde(default)]
261    pub buffer_font_family: Option<String>,
262    /// The font fallbacks to use for rendering in text buffers.
263    #[serde(default)]
264    #[schemars(default = "default_font_fallbacks")]
265    pub buffer_font_fallbacks: Option<Vec<String>>,
266    /// The default font size for rendering in text buffers.
267    #[serde(default)]
268    pub buffer_font_size: Option<f32>,
269    /// The weight of the editor font in CSS units from 100 to 900.
270    #[serde(default)]
271    pub buffer_font_weight: Option<f32>,
272    /// The buffer's line height.
273    #[serde(default)]
274    pub buffer_line_height: Option<BufferLineHeight>,
275    /// The OpenType features to enable for rendering in text buffers.
276    #[serde(default)]
277    #[schemars(default = "default_font_features")]
278    pub buffer_font_features: Option<FontFeatures>,
279    /// The name of the Zed theme to use.
280    #[serde(default)]
281    pub theme: Option<ThemeSelection>,
282
283    /// UNSTABLE: Expect many elements to be broken.
284    ///
285    // Controls the density of the UI.
286    #[serde(rename = "unstable.ui_density", default)]
287    pub ui_density: Option<UiDensity>,
288
289    /// How much to fade out unused code.
290    #[serde(default)]
291    pub unnecessary_code_fade: Option<f32>,
292
293    /// EXPERIMENTAL: Overrides for the current theme.
294    ///
295    /// These values will override the ones on the current theme specified in `theme`.
296    #[serde(rename = "experimental.theme_overrides", default)]
297    pub theme_overrides: Option<ThemeStyleContent>,
298}
299
300fn default_font_features() -> Option<FontFeatures> {
301    Some(FontFeatures::default())
302}
303
304fn default_font_fallbacks() -> Option<FontFallbacks> {
305    Some(FontFallbacks::default())
306}
307
308impl ThemeSettingsContent {
309    /// Sets the theme for the given appearance to the theme with the specified name.
310    pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {
311        if let Some(selection) = self.theme.as_mut() {
312            let theme_to_update = match selection {
313                ThemeSelection::Static(theme) => theme,
314                ThemeSelection::Dynamic { mode, light, dark } => match mode {
315                    ThemeMode::Light => light,
316                    ThemeMode::Dark => dark,
317                    ThemeMode::System => match appearance {
318                        Appearance::Light => light,
319                        Appearance::Dark => dark,
320                    },
321                },
322            };
323
324            *theme_to_update = theme_name.to_string();
325        } else {
326            self.theme = Some(ThemeSelection::Static(theme_name.to_string()));
327        }
328    }
329
330    pub fn set_mode(&mut self, mode: ThemeMode) {
331        if let Some(selection) = self.theme.as_mut() {
332            match selection {
333                ThemeSelection::Static(theme) => {
334                    // If the theme was previously set to a single static theme,
335                    // we don't know whether it was a light or dark theme, so we
336                    // just use it for both.
337                    self.theme = Some(ThemeSelection::Dynamic {
338                        mode,
339                        light: theme.clone(),
340                        dark: theme.clone(),
341                    });
342                }
343                ThemeSelection::Dynamic {
344                    mode: mode_to_update,
345                    ..
346                } => *mode_to_update = mode,
347            }
348        } else {
349            self.theme = Some(ThemeSelection::Dynamic {
350                mode,
351                light: ThemeSettings::DEFAULT_LIGHT_THEME.into(),
352                dark: ThemeSettings::DEFAULT_DARK_THEME.into(),
353            });
354        }
355    }
356}
357
358#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
359#[serde(rename_all = "snake_case")]
360pub enum BufferLineHeight {
361    #[default]
362    Comfortable,
363    Standard,
364    Custom(f32),
365}
366
367impl BufferLineHeight {
368    pub fn value(&self) -> f32 {
369        match self {
370            BufferLineHeight::Comfortable => 1.618,
371            BufferLineHeight::Standard => 1.3,
372            BufferLineHeight::Custom(line_height) => *line_height,
373        }
374    }
375}
376
377impl ThemeSettings {
378    pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
379        cx.try_global::<AdjustedBufferFontSize>()
380            .map_or(self.buffer_font_size, |size| size.0)
381            .max(MIN_FONT_SIZE)
382    }
383
384    pub fn line_height(&self) -> f32 {
385        f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
386    }
387
388    /// Switches to the theme with the given name, if it exists.
389    ///
390    /// Returns a `Some` containing the new theme if it was successful.
391    /// Returns `None` otherwise.
392    pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
393        let themes = ThemeRegistry::default_global(cx);
394
395        let mut new_theme = None;
396
397        if let Some(theme) = themes.get(theme).log_err() {
398            self.active_theme = theme.clone();
399            new_theme = Some(theme);
400        }
401
402        self.apply_theme_overrides();
403
404        new_theme
405    }
406
407    /// Applies the theme overrides, if there are any, to the current theme.
408    pub fn apply_theme_overrides(&mut self) {
409        if let Some(theme_overrides) = &self.theme_overrides {
410            let mut base_theme = (*self.active_theme).clone();
411
412            if let Some(window_background_appearance) = theme_overrides.window_background_appearance
413            {
414                base_theme.styles.window_background_appearance =
415                    window_background_appearance.into();
416            }
417
418            base_theme
419                .styles
420                .colors
421                .refine(&theme_overrides.theme_colors_refinement());
422            base_theme
423                .styles
424                .status
425                .refine(&theme_overrides.status_colors_refinement());
426            base_theme.styles.player.merge(&theme_overrides.players);
427            base_theme.styles.accents.merge(&theme_overrides.accents);
428            base_theme.styles.syntax =
429                SyntaxTheme::merge(base_theme.styles.syntax, theme_overrides.syntax_overrides());
430
431            self.active_theme = Arc::new(base_theme);
432        }
433    }
434}
435
436pub fn observe_buffer_font_size_adjustment<V: 'static>(
437    cx: &mut ViewContext<V>,
438    f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
439) -> Subscription {
440    cx.observe_global::<AdjustedBufferFontSize>(f)
441}
442
443pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
444    if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
445        let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
446        let delta = *adjusted_size - buffer_font_size;
447        size + delta
448    } else {
449        size
450    }
451    .max(MIN_FONT_SIZE)
452}
453
454pub fn get_buffer_font_size(cx: &AppContext) -> Pixels {
455    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
456    cx.try_global::<AdjustedBufferFontSize>()
457        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0)
458}
459
460pub fn adjust_buffer_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
461    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
462    let mut adjusted_size = cx
463        .try_global::<AdjustedBufferFontSize>()
464        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
465
466    f(&mut adjusted_size);
467    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
468    cx.set_global(AdjustedBufferFontSize(adjusted_size));
469    cx.refresh();
470}
471
472pub fn has_adjusted_buffer_font_size(cx: &mut AppContext) -> bool {
473    cx.has_global::<AdjustedBufferFontSize>()
474}
475
476pub fn reset_buffer_font_size(cx: &mut AppContext) {
477    if cx.has_global::<AdjustedBufferFontSize>() {
478        cx.remove_global::<AdjustedBufferFontSize>();
479        cx.refresh();
480    }
481}
482
483pub fn setup_ui_font(cx: &mut WindowContext) -> gpui::Font {
484    let (ui_font, ui_font_size) = {
485        let theme_settings = ThemeSettings::get_global(cx);
486        let font = theme_settings.ui_font.clone();
487        (font, get_ui_font_size(cx))
488    };
489
490    cx.set_rem_size(ui_font_size);
491    ui_font
492}
493
494pub fn get_ui_font_size(cx: &WindowContext) -> Pixels {
495    let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
496    cx.try_global::<AdjustedUiFontSize>()
497        .map_or(ui_font_size, |adjusted_size| adjusted_size.0)
498}
499
500pub fn adjust_ui_font_size(cx: &mut WindowContext, f: fn(&mut Pixels)) {
501    let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
502    let mut adjusted_size = cx
503        .try_global::<AdjustedUiFontSize>()
504        .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
505
506    f(&mut adjusted_size);
507    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
508    cx.set_global(AdjustedUiFontSize(adjusted_size));
509    cx.refresh();
510}
511
512pub fn has_adjusted_ui_font_size(cx: &mut AppContext) -> bool {
513    cx.has_global::<AdjustedUiFontSize>()
514}
515
516pub fn reset_ui_font_size(cx: &mut WindowContext) {
517    if cx.has_global::<AdjustedUiFontSize>() {
518        cx.remove_global::<AdjustedUiFontSize>();
519        cx.refresh();
520    }
521}
522
523impl settings::Settings for ThemeSettings {
524    const KEY: Option<&'static str> = None;
525
526    type FileContent = ThemeSettingsContent;
527
528    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
529        let themes = ThemeRegistry::default_global(cx);
530        let system_appearance = SystemAppearance::default_global(cx);
531
532        let defaults = sources.default;
533        let mut this = Self {
534            ui_font_size: defaults.ui_font_size.unwrap().into(),
535            ui_font: Font {
536                family: defaults.ui_font_family.as_ref().unwrap().clone().into(),
537                features: defaults.ui_font_features.clone().unwrap(),
538                fallbacks: defaults
539                    .ui_font_fallbacks
540                    .as_ref()
541                    .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
542                weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
543                style: Default::default(),
544            },
545            buffer_font: Font {
546                family: defaults.buffer_font_family.as_ref().unwrap().clone().into(),
547                features: defaults.buffer_font_features.clone().unwrap(),
548                fallbacks: defaults
549                    .buffer_font_fallbacks
550                    .as_ref()
551                    .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
552                weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
553                style: FontStyle::default(),
554            },
555            buffer_font_size: defaults.buffer_font_size.unwrap().into(),
556            buffer_line_height: defaults.buffer_line_height.unwrap(),
557            theme_selection: defaults.theme.clone(),
558            active_theme: themes
559                .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
560                .or(themes.get(&one_dark().name))
561                .unwrap(),
562            theme_overrides: None,
563            ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
564            unnecessary_code_fade: defaults.unnecessary_code_fade.unwrap_or(0.0),
565        };
566
567        for value in sources.user.into_iter().chain(sources.release_channel) {
568            if let Some(value) = value.ui_density {
569                this.ui_density = value;
570            }
571
572            if let Some(value) = value.buffer_font_family.clone() {
573                this.buffer_font.family = value.into();
574            }
575            if let Some(value) = value.buffer_font_features.clone() {
576                this.buffer_font.features = value;
577            }
578            if let Some(value) = value.buffer_font_fallbacks.clone() {
579                this.buffer_font.fallbacks = Some(FontFallbacks::from_fonts(value));
580            }
581            if let Some(value) = value.buffer_font_weight {
582                this.buffer_font.weight = FontWeight(value);
583            }
584
585            if let Some(value) = value.ui_font_family.clone() {
586                this.ui_font.family = value.into();
587            }
588            if let Some(value) = value.ui_font_features.clone() {
589                this.ui_font.features = value;
590            }
591            if let Some(value) = value.ui_font_fallbacks.clone() {
592                this.ui_font.fallbacks = Some(FontFallbacks::from_fonts(value));
593            }
594            if let Some(value) = value.ui_font_weight {
595                this.ui_font.weight = FontWeight(value);
596            }
597
598            if let Some(value) = &value.theme {
599                this.theme_selection = Some(value.clone());
600
601                let theme_name = value.theme(*system_appearance);
602
603                if let Some(theme) = themes.get(theme_name).log_err() {
604                    this.active_theme = theme;
605                }
606            }
607
608            this.theme_overrides.clone_from(&value.theme_overrides);
609            this.apply_theme_overrides();
610
611            merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
612            merge(
613                &mut this.buffer_font_size,
614                value.buffer_font_size.map(Into::into),
615            );
616            merge(&mut this.buffer_line_height, value.buffer_line_height);
617
618            // Clamp the `unnecessary_code_fade` to ensure text can't disappear entirely.
619            merge(&mut this.unnecessary_code_fade, value.unnecessary_code_fade);
620            this.unnecessary_code_fade = this.unnecessary_code_fade.clamp(0.0, 0.9);
621        }
622
623        Ok(this)
624    }
625
626    fn json_schema(
627        generator: &mut SchemaGenerator,
628        params: &SettingsJsonSchemaParams,
629        cx: &AppContext,
630    ) -> schemars::schema::RootSchema {
631        let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
632        let theme_names = ThemeRegistry::global(cx)
633            .list_names(params.staff_mode)
634            .into_iter()
635            .map(|theme_name| Value::String(theme_name.to_string()))
636            .collect();
637
638        let theme_name_schema = SchemaObject {
639            instance_type: Some(InstanceType::String.into()),
640            enum_values: Some(theme_names),
641            ..Default::default()
642        };
643
644        root_schema.definitions.extend([
645            ("ThemeName".into(), theme_name_schema.into()),
646            ("FontFamilies".into(), params.font_family_schema()),
647            ("FontFallbacks".into(), params.font_fallback_schema()),
648        ]);
649
650        add_references_to_properties(
651            &mut root_schema,
652            &[
653                ("buffer_font_family", "#/definitions/FontFamilies"),
654                ("buffer_font_fallbacks", "#/definitions/FontFallbacks"),
655                ("ui_font_family", "#/definitions/FontFamilies"),
656                ("ui_font_fallbacks", "#/definitions/FontFallbacks"),
657            ],
658        );
659
660        root_schema
661    }
662}
663
664fn merge<T: Copy>(target: &mut T, value: Option<T>) {
665    if let Some(value) = value {
666        *target = value;
667    }
668}