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::schema::ArrayValidation;
 11use schemars::{
 12    gen::SchemaGenerator,
 13    schema::{InstanceType, Schema, SchemaObject},
 14    JsonSchema,
 15};
 16use serde::{Deserialize, Serialize};
 17use serde_json::Value;
 18use settings::{Settings, SettingsJsonSchemaParams, SettingsSources};
 19use std::sync::Arc;
 20use util::ResultExt as _;
 21
 22const MIN_FONT_SIZE: Pixels = px(6.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#[serde(rename_all = "snake_case")]
 40pub enum UiDensity {
 41    /// A denser UI with tighter spacing and smaller elements.
 42    #[serde(alias = "compact")]
 43    Compact,
 44    #[default]
 45    #[serde(alias = "default")]
 46    /// The default UI density.
 47    Default,
 48    #[serde(alias = "comfortable")]
 49    /// A looser UI with more spacing and larger elements.
 50    Comfortable,
 51}
 52
 53impl UiDensity {
 54    pub fn spacing_ratio(self) -> f32 {
 55        match self {
 56            UiDensity::Compact => 0.75,
 57            UiDensity::Default => 1.0,
 58            UiDensity::Comfortable => 1.25,
 59        }
 60    }
 61}
 62
 63impl From<String> for UiDensity {
 64    fn from(s: String) -> Self {
 65        match s.as_str() {
 66            "compact" => Self::Compact,
 67            "default" => Self::Default,
 68            "comfortable" => Self::Comfortable,
 69            _ => Self::default(),
 70        }
 71    }
 72}
 73
 74impl Into<String> for UiDensity {
 75    fn into(self) -> String {
 76        match self {
 77            UiDensity::Compact => "compact".to_string(),
 78            UiDensity::Default => "default".to_string(),
 79            UiDensity::Comfortable => "comfortable".to_string(),
 80        }
 81    }
 82}
 83
 84#[derive(Clone)]
 85pub struct ThemeSettings {
 86    pub ui_font_size: Pixels,
 87    pub ui_font: Font,
 88    pub buffer_font: Font,
 89    pub buffer_font_size: Pixels,
 90    pub buffer_line_height: BufferLineHeight,
 91    pub theme_selection: Option<ThemeSelection>,
 92    pub active_theme: Arc<Theme>,
 93    pub theme_overrides: Option<ThemeStyleContent>,
 94    pub ui_density: UiDensity,
 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    pub ui_font_fallbacks: Option<Vec<String>>,
251    /// The OpenType features to enable for text in the UI.
252    #[serde(default)]
253    pub ui_font_features: Option<FontFeatures>,
254    /// The weight of the UI font in CSS units from 100 to 900.
255    #[serde(default)]
256    pub ui_font_weight: Option<f32>,
257    /// The name of a font to use for rendering in text buffers.
258    #[serde(default)]
259    pub buffer_font_family: Option<String>,
260    /// The font fallbacks to use for rendering in text buffers.
261    #[serde(default)]
262    pub buffer_font_fallbacks: Option<Vec<String>>,
263    /// The default font size for rendering in text buffers.
264    #[serde(default)]
265    pub buffer_font_size: Option<f32>,
266    /// The weight of the editor font in CSS units from 100 to 900.
267    #[serde(default)]
268    pub buffer_font_weight: Option<f32>,
269    /// The buffer's line height.
270    #[serde(default)]
271    pub buffer_line_height: Option<BufferLineHeight>,
272    /// The OpenType features to enable for rendering in text buffers.
273    #[serde(default)]
274    pub buffer_font_features: Option<FontFeatures>,
275    /// The name of the Zed theme to use.
276    #[serde(default)]
277    pub theme: Option<ThemeSelection>,
278
279    /// UNSTABLE: Expect many elements to be broken.
280    ///
281    // Controls the density of the UI.
282    #[serde(rename = "unstable.ui_density", default)]
283    pub ui_density: Option<UiDensity>,
284
285    /// EXPERIMENTAL: Overrides for the current theme.
286    ///
287    /// These values will override the ones on the current theme specified in `theme`.
288    #[serde(rename = "experimental.theme_overrides", default)]
289    pub theme_overrides: Option<ThemeStyleContent>,
290}
291
292impl ThemeSettingsContent {
293    /// Sets the theme for the given appearance to the theme with the specified name.
294    pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {
295        if let Some(selection) = self.theme.as_mut() {
296            let theme_to_update = match selection {
297                ThemeSelection::Static(theme) => theme,
298                ThemeSelection::Dynamic { mode, light, dark } => match mode {
299                    ThemeMode::Light => light,
300                    ThemeMode::Dark => dark,
301                    ThemeMode::System => match appearance {
302                        Appearance::Light => light,
303                        Appearance::Dark => dark,
304                    },
305                },
306            };
307
308            *theme_to_update = theme_name.to_string();
309        } else {
310            self.theme = Some(ThemeSelection::Static(theme_name.to_string()));
311        }
312    }
313
314    pub fn set_mode(&mut self, mode: ThemeMode) {
315        if let Some(selection) = self.theme.as_mut() {
316            match selection {
317                ThemeSelection::Static(theme) => {
318                    // If the theme was previously set to a single static theme,
319                    // we don't know whether it was a light or dark theme, so we
320                    // just use it for both.
321                    self.theme = Some(ThemeSelection::Dynamic {
322                        mode,
323                        light: theme.clone(),
324                        dark: theme.clone(),
325                    });
326                }
327                ThemeSelection::Dynamic {
328                    mode: mode_to_update,
329                    ..
330                } => *mode_to_update = mode,
331            }
332        } else {
333            self.theme = Some(ThemeSelection::Dynamic {
334                mode,
335                light: ThemeSettings::DEFAULT_LIGHT_THEME.into(),
336                dark: ThemeSettings::DEFAULT_DARK_THEME.into(),
337            });
338        }
339    }
340}
341
342#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
343#[serde(rename_all = "snake_case")]
344pub enum BufferLineHeight {
345    #[default]
346    Comfortable,
347    Standard,
348    Custom(f32),
349}
350
351impl BufferLineHeight {
352    pub fn value(&self) -> f32 {
353        match self {
354            BufferLineHeight::Comfortable => 1.618,
355            BufferLineHeight::Standard => 1.3,
356            BufferLineHeight::Custom(line_height) => *line_height,
357        }
358    }
359}
360
361impl ThemeSettings {
362    pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
363        cx.try_global::<AdjustedBufferFontSize>()
364            .map_or(self.buffer_font_size, |size| size.0)
365            .max(MIN_FONT_SIZE)
366    }
367
368    pub fn line_height(&self) -> f32 {
369        f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
370    }
371
372    /// Switches to the theme with the given name, if it exists.
373    ///
374    /// Returns a `Some` containing the new theme if it was successful.
375    /// Returns `None` otherwise.
376    pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
377        let themes = ThemeRegistry::default_global(cx);
378
379        let mut new_theme = None;
380
381        if let Some(theme) = themes.get(theme).log_err() {
382            self.active_theme = theme.clone();
383            new_theme = Some(theme);
384        }
385
386        self.apply_theme_overrides();
387
388        new_theme
389    }
390
391    /// Applies the theme overrides, if there are any, to the current theme.
392    pub fn apply_theme_overrides(&mut self) {
393        if let Some(theme_overrides) = &self.theme_overrides {
394            let mut base_theme = (*self.active_theme).clone();
395
396            if let Some(window_background_appearance) = theme_overrides.window_background_appearance
397            {
398                base_theme.styles.window_background_appearance =
399                    window_background_appearance.into();
400            }
401
402            base_theme
403                .styles
404                .colors
405                .refine(&theme_overrides.theme_colors_refinement());
406            base_theme
407                .styles
408                .status
409                .refine(&theme_overrides.status_colors_refinement());
410            base_theme.styles.player.merge(&theme_overrides.players);
411            base_theme.styles.accents.merge(&theme_overrides.accents);
412            base_theme.styles.syntax =
413                SyntaxTheme::merge(base_theme.styles.syntax, theme_overrides.syntax_overrides());
414
415            self.active_theme = Arc::new(base_theme);
416        }
417    }
418}
419
420pub fn observe_buffer_font_size_adjustment<V: 'static>(
421    cx: &mut ViewContext<V>,
422    f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
423) -> Subscription {
424    cx.observe_global::<AdjustedBufferFontSize>(f)
425}
426
427pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
428    if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
429        let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
430        let delta = *adjusted_size - buffer_font_size;
431        size + delta
432    } else {
433        size
434    }
435    .max(MIN_FONT_SIZE)
436}
437
438pub fn get_buffer_font_size(cx: &AppContext) -> Pixels {
439    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
440    cx.try_global::<AdjustedBufferFontSize>()
441        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0)
442}
443
444pub fn adjust_buffer_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
445    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
446    let mut adjusted_size = cx
447        .try_global::<AdjustedBufferFontSize>()
448        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
449
450    f(&mut adjusted_size);
451    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
452    cx.set_global(AdjustedBufferFontSize(adjusted_size));
453    cx.refresh();
454}
455
456pub fn has_adjusted_buffer_font_size(cx: &mut AppContext) -> bool {
457    cx.has_global::<AdjustedBufferFontSize>()
458}
459
460pub fn reset_buffer_font_size(cx: &mut AppContext) {
461    if cx.has_global::<AdjustedBufferFontSize>() {
462        cx.remove_global::<AdjustedBufferFontSize>();
463        cx.refresh();
464    }
465}
466
467pub fn setup_ui_font(cx: &mut WindowContext) -> gpui::Font {
468    let (ui_font, ui_font_size) = {
469        let theme_settings = ThemeSettings::get_global(cx);
470        let font = theme_settings.ui_font.clone();
471        (font, get_ui_font_size(cx))
472    };
473
474    cx.set_rem_size(ui_font_size);
475    ui_font
476}
477
478pub fn get_ui_font_size(cx: &WindowContext) -> Pixels {
479    let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
480    cx.try_global::<AdjustedUiFontSize>()
481        .map_or(ui_font_size, |adjusted_size| adjusted_size.0)
482}
483
484pub fn adjust_ui_font_size(cx: &mut WindowContext, f: fn(&mut Pixels)) {
485    let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
486    let mut adjusted_size = cx
487        .try_global::<AdjustedUiFontSize>()
488        .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
489
490    f(&mut adjusted_size);
491    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
492    cx.set_global(AdjustedUiFontSize(adjusted_size));
493    cx.refresh();
494}
495
496pub fn has_adjusted_ui_font_size(cx: &mut AppContext) -> bool {
497    cx.has_global::<AdjustedUiFontSize>()
498}
499
500pub fn reset_ui_font_size(cx: &mut WindowContext) {
501    if cx.has_global::<AdjustedUiFontSize>() {
502        cx.remove_global::<AdjustedUiFontSize>();
503        cx.refresh();
504    }
505}
506
507impl settings::Settings for ThemeSettings {
508    const KEY: Option<&'static str> = None;
509
510    type FileContent = ThemeSettingsContent;
511
512    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
513        let themes = ThemeRegistry::default_global(cx);
514        let system_appearance = SystemAppearance::default_global(cx);
515
516        let defaults = sources.default;
517        let mut this = Self {
518            ui_font_size: defaults.ui_font_size.unwrap().into(),
519            ui_font: Font {
520                family: defaults.ui_font_family.as_ref().unwrap().clone().into(),
521                features: defaults.ui_font_features.clone().unwrap(),
522                fallbacks: defaults
523                    .ui_font_fallbacks
524                    .as_ref()
525                    .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
526                weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
527                style: Default::default(),
528            },
529            buffer_font: Font {
530                family: defaults.buffer_font_family.as_ref().unwrap().clone().into(),
531                features: defaults.buffer_font_features.clone().unwrap(),
532                fallbacks: defaults
533                    .buffer_font_fallbacks
534                    .as_ref()
535                    .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
536                weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
537                style: FontStyle::default(),
538            },
539            buffer_font_size: defaults.buffer_font_size.unwrap().into(),
540            buffer_line_height: defaults.buffer_line_height.unwrap(),
541            theme_selection: defaults.theme.clone(),
542            active_theme: themes
543                .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
544                .or(themes.get(&one_dark().name))
545                .unwrap(),
546            theme_overrides: None,
547            ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
548        };
549
550        for value in sources.user.into_iter().chain(sources.release_channel) {
551            if let Some(value) = value.ui_density {
552                this.ui_density = value;
553            }
554
555            if let Some(value) = value.buffer_font_family.clone() {
556                this.buffer_font.family = value.into();
557            }
558            if let Some(value) = value.buffer_font_features.clone() {
559                this.buffer_font.features = value;
560            }
561            if let Some(value) = value.buffer_font_fallbacks.clone() {
562                this.buffer_font.fallbacks = Some(FontFallbacks::from_fonts(value));
563            }
564            if let Some(value) = value.buffer_font_weight {
565                this.buffer_font.weight = FontWeight(value);
566            }
567
568            if let Some(value) = value.ui_font_family.clone() {
569                this.ui_font.family = value.into();
570            }
571            if let Some(value) = value.ui_font_features.clone() {
572                this.ui_font.features = value;
573            }
574            if let Some(value) = value.ui_font_fallbacks.clone() {
575                this.ui_font.fallbacks = Some(FontFallbacks::from_fonts(value));
576            }
577            if let Some(value) = value.ui_font_weight {
578                this.ui_font.weight = FontWeight(value);
579            }
580
581            if let Some(value) = &value.theme {
582                this.theme_selection = Some(value.clone());
583
584                let theme_name = value.theme(*system_appearance);
585
586                if let Some(theme) = themes.get(theme_name).log_err() {
587                    this.active_theme = theme;
588                }
589            }
590
591            this.theme_overrides.clone_from(&value.theme_overrides);
592            this.apply_theme_overrides();
593
594            merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
595            merge(
596                &mut this.buffer_font_size,
597                value.buffer_font_size.map(Into::into),
598            );
599            merge(&mut this.buffer_line_height, value.buffer_line_height);
600        }
601
602        Ok(this)
603    }
604
605    fn json_schema(
606        generator: &mut SchemaGenerator,
607        params: &SettingsJsonSchemaParams,
608        cx: &AppContext,
609    ) -> schemars::schema::RootSchema {
610        let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
611        let theme_names = ThemeRegistry::global(cx)
612            .list_names(params.staff_mode)
613            .into_iter()
614            .map(|theme_name| Value::String(theme_name.to_string()))
615            .collect();
616
617        let theme_name_schema = SchemaObject {
618            instance_type: Some(InstanceType::String.into()),
619            enum_values: Some(theme_names),
620            ..Default::default()
621        };
622
623        let available_fonts = params
624            .font_names
625            .iter()
626            .cloned()
627            .map(Value::String)
628            .collect::<Vec<_>>();
629        let font_family_schema = SchemaObject {
630            instance_type: Some(InstanceType::String.into()),
631            enum_values: Some(available_fonts),
632            ..Default::default()
633        };
634        let font_fallback_schema = SchemaObject {
635            instance_type: Some(InstanceType::Array.into()),
636            array: Some(Box::new(ArrayValidation {
637                items: Some(schemars::schema::SingleOrVec::Single(Box::new(
638                    font_family_schema.clone().into(),
639                ))),
640                unique_items: Some(true),
641                ..Default::default()
642            })),
643            ..Default::default()
644        };
645
646        root_schema.definitions.extend([
647            ("ThemeName".into(), theme_name_schema.into()),
648            ("FontFamilies".into(), font_family_schema.into()),
649            ("FontFallbacks".into(), font_fallback_schema.into()),
650        ]);
651
652        root_schema
653            .schema
654            .object
655            .as_mut()
656            .unwrap()
657            .properties
658            .extend([
659                (
660                    "buffer_font_family".to_owned(),
661                    Schema::new_ref("#/definitions/FontFamilies".into()),
662                ),
663                (
664                    "buffer_font_fallbacks".to_owned(),
665                    Schema::new_ref("#/definitions/FontFallbacks".into()),
666                ),
667                (
668                    "ui_font_family".to_owned(),
669                    Schema::new_ref("#/definitions/FontFamilies".into()),
670                ),
671                (
672                    "ui_font_fallbacks".to_owned(),
673                    Schema::new_ref("#/definitions/FontFallbacks".into()),
674                ),
675            ]);
676
677        root_schema
678    }
679}
680
681fn merge<T: Copy>(target: &mut T, value: Option<T>) {
682    if let Some(value) = value {
683        *target = value;
684    }
685}