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, FontFeatures, FontStyle, FontWeight, Global, Pixels, Subscription,
  7    ViewContext,
  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::{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 Into<String> for UiDensity {
 74    fn into(self) -> String {
 75        match self {
 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}
 95
 96impl ThemeSettings {
 97    /// Reloads the current theme.
 98    ///
 99    /// Reads the [`ThemeSettings`] to know which theme should be loaded,
100    /// taking into account the current [`SystemAppearance`].
101    pub fn reload_current_theme(cx: &mut AppContext) {
102        let mut theme_settings = ThemeSettings::get_global(cx).clone();
103        let system_appearance = SystemAppearance::global(cx);
104
105        if let Some(theme_selection) = theme_settings.theme_selection.clone() {
106            let mut theme_name = theme_selection.theme(*system_appearance);
107
108            // If the selected theme doesn't exist, fall back to a default theme
109            // based on the system appearance.
110            let theme_registry = ThemeRegistry::global(cx);
111            if theme_registry.get(theme_name).ok().is_none() {
112                theme_name = match *system_appearance {
113                    Appearance::Light => "One Light",
114                    Appearance::Dark => "One Dark",
115                };
116            };
117
118            if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {
119                ThemeSettings::override_global(theme_settings, cx);
120            }
121        }
122    }
123}
124
125/// The appearance of the system.
126#[derive(Debug, Clone, Copy, Deref)]
127pub struct SystemAppearance(pub Appearance);
128
129impl Default for SystemAppearance {
130    fn default() -> Self {
131        Self(Appearance::Dark)
132    }
133}
134
135#[derive(Deref, DerefMut, Default)]
136struct GlobalSystemAppearance(SystemAppearance);
137
138impl Global for GlobalSystemAppearance {}
139
140impl SystemAppearance {
141    /// Initializes the [`SystemAppearance`] for the application.
142    pub fn init(cx: &mut AppContext) {
143        *cx.default_global::<GlobalSystemAppearance>() =
144            GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
145    }
146
147    /// Returns the global [`SystemAppearance`].
148    ///
149    /// Inserts a default [`SystemAppearance`] if one does not yet exist.
150    pub(crate) fn default_global(cx: &mut AppContext) -> Self {
151        cx.default_global::<GlobalSystemAppearance>().0
152    }
153
154    /// Returns the global [`SystemAppearance`].
155    pub fn global(cx: &AppContext) -> Self {
156        cx.global::<GlobalSystemAppearance>().0
157    }
158
159    /// Returns a mutable reference to the global [`SystemAppearance`].
160    pub fn global_mut(cx: &mut AppContext) -> &mut Self {
161        cx.global_mut::<GlobalSystemAppearance>()
162    }
163}
164
165#[derive(Default)]
166pub(crate) struct AdjustedBufferFontSize(Pixels);
167
168impl Global for AdjustedBufferFontSize {}
169
170#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
171#[serde(untagged)]
172pub enum ThemeSelection {
173    Static(#[schemars(schema_with = "theme_name_ref")] String),
174    Dynamic {
175        #[serde(default)]
176        mode: ThemeMode,
177        #[schemars(schema_with = "theme_name_ref")]
178        light: String,
179        #[schemars(schema_with = "theme_name_ref")]
180        dark: String,
181    },
182}
183
184fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {
185    Schema::new_ref("#/definitions/ThemeName".into())
186}
187
188#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
189#[serde(rename_all = "snake_case")]
190pub enum ThemeMode {
191    /// Use the specified `light` theme.
192    Light,
193
194    /// Use the specified `dark` theme.
195    Dark,
196
197    /// Use the theme based on the system's appearance.
198    #[default]
199    System,
200}
201
202impl ThemeSelection {
203    pub fn theme(&self, system_appearance: Appearance) -> &str {
204        match self {
205            Self::Static(theme) => theme,
206            Self::Dynamic { mode, light, dark } => match mode {
207                ThemeMode::Light => light,
208                ThemeMode::Dark => dark,
209                ThemeMode::System => match system_appearance {
210                    Appearance::Light => light,
211                    Appearance::Dark => dark,
212                },
213            },
214        }
215    }
216}
217
218/// Settings for rendering text in UI and text buffers.
219#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
220pub struct ThemeSettingsContent {
221    /// The default font size for text in the UI.
222    #[serde(default)]
223    pub ui_font_size: Option<f32>,
224    /// The name of a font to use for rendering in the UI.
225    #[serde(default)]
226    pub ui_font_family: Option<String>,
227    /// The OpenType features to enable for text in the UI.
228    #[serde(default)]
229    pub ui_font_features: Option<FontFeatures>,
230    /// The name of a font to use for rendering in text buffers.
231    #[serde(default)]
232    pub buffer_font_family: Option<String>,
233    /// The default font size for rendering in text buffers.
234    #[serde(default)]
235    pub buffer_font_size: Option<f32>,
236    /// The buffer's line height.
237    #[serde(default)]
238    pub buffer_line_height: Option<BufferLineHeight>,
239    /// The OpenType features to enable for rendering in text buffers.
240    #[serde(default)]
241    pub buffer_font_features: Option<FontFeatures>,
242    /// The name of the Zed theme to use.
243    #[serde(default)]
244    pub theme: Option<ThemeSelection>,
245
246    /// UNSTABLE: Expect many elements to be broken.
247    ///
248    // Controls the density of the UI.
249    #[serde(rename = "unstable.ui_density", default)]
250    pub ui_density: Option<UiDensity>,
251
252    /// EXPERIMENTAL: Overrides for the current theme.
253    ///
254    /// These values will override the ones on the current theme specified in `theme`.
255    #[serde(rename = "experimental.theme_overrides", default)]
256    pub theme_overrides: Option<ThemeStyleContent>,
257}
258
259#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
260#[serde(rename_all = "snake_case")]
261pub enum BufferLineHeight {
262    #[default]
263    Comfortable,
264    Standard,
265    Custom(f32),
266}
267
268impl BufferLineHeight {
269    pub fn value(&self) -> f32 {
270        match self {
271            BufferLineHeight::Comfortable => 1.618,
272            BufferLineHeight::Standard => 1.3,
273            BufferLineHeight::Custom(line_height) => *line_height,
274        }
275    }
276}
277
278impl ThemeSettings {
279    pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
280        cx.try_global::<AdjustedBufferFontSize>()
281            .map_or(self.buffer_font_size, |size| size.0)
282            .max(MIN_FONT_SIZE)
283    }
284
285    pub fn line_height(&self) -> f32 {
286        f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
287    }
288
289    /// Switches to the theme with the given name, if it exists.
290    ///
291    /// Returns a `Some` containing the new theme if it was successful.
292    /// Returns `None` otherwise.
293    pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
294        let themes = ThemeRegistry::default_global(cx);
295
296        let mut new_theme = None;
297
298        if let Some(theme) = themes.get(theme).log_err() {
299            self.active_theme = theme.clone();
300            new_theme = Some(theme);
301        }
302
303        self.apply_theme_overrides();
304
305        new_theme
306    }
307
308    /// Applies the theme overrides, if there are any, to the current theme.
309    pub fn apply_theme_overrides(&mut self) {
310        if let Some(theme_overrides) = &self.theme_overrides {
311            let mut base_theme = (*self.active_theme).clone();
312
313            if let Some(window_background_appearance) = theme_overrides.window_background_appearance
314            {
315                base_theme.styles.window_background_appearance =
316                    window_background_appearance.into();
317            }
318
319            base_theme
320                .styles
321                .colors
322                .refine(&theme_overrides.theme_colors_refinement());
323            base_theme
324                .styles
325                .status
326                .refine(&theme_overrides.status_colors_refinement());
327            base_theme.styles.player.merge(&theme_overrides.players);
328            base_theme.styles.syntax = Arc::new(SyntaxTheme {
329                highlights: {
330                    let mut highlights = base_theme.styles.syntax.highlights.clone();
331                    // Overrides come second in the highlight list so that they take precedence
332                    // over the ones in the base theme.
333                    highlights.extend(theme_overrides.syntax_overrides());
334                    highlights
335                },
336            });
337
338            self.active_theme = Arc::new(base_theme);
339        }
340    }
341}
342
343pub fn observe_buffer_font_size_adjustment<V: 'static>(
344    cx: &mut ViewContext<V>,
345    f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
346) -> Subscription {
347    cx.observe_global::<AdjustedBufferFontSize>(f)
348}
349
350pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
351    if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
352        let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
353        let delta = *adjusted_size - buffer_font_size;
354        size + delta
355    } else {
356        size
357    }
358    .max(MIN_FONT_SIZE)
359}
360
361pub fn adjust_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
362    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
363    let mut adjusted_size = cx
364        .try_global::<AdjustedBufferFontSize>()
365        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
366
367    f(&mut adjusted_size);
368    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
369    cx.set_global(AdjustedBufferFontSize(adjusted_size));
370    cx.refresh();
371}
372
373pub fn reset_font_size(cx: &mut AppContext) {
374    if cx.has_global::<AdjustedBufferFontSize>() {
375        cx.remove_global::<AdjustedBufferFontSize>();
376        cx.refresh();
377    }
378}
379
380impl settings::Settings for ThemeSettings {
381    const KEY: Option<&'static str> = None;
382
383    type FileContent = ThemeSettingsContent;
384
385    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
386        let themes = ThemeRegistry::default_global(cx);
387        let system_appearance = SystemAppearance::default_global(cx);
388
389        let defaults = sources.default;
390        let mut this = Self {
391            ui_font_size: defaults.ui_font_size.unwrap().into(),
392            ui_font: Font {
393                family: defaults.ui_font_family.clone().unwrap().into(),
394                features: defaults.ui_font_features.clone().unwrap(),
395                weight: Default::default(),
396                style: Default::default(),
397            },
398            buffer_font: Font {
399                family: defaults.buffer_font_family.clone().unwrap().into(),
400                features: defaults.buffer_font_features.clone().unwrap(),
401                weight: FontWeight::default(),
402                style: FontStyle::default(),
403            },
404            buffer_font_size: defaults.buffer_font_size.unwrap().into(),
405            buffer_line_height: defaults.buffer_line_height.unwrap(),
406            theme_selection: defaults.theme.clone(),
407            active_theme: themes
408                .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
409                .or(themes.get(&one_dark().name))
410                .unwrap(),
411            theme_overrides: None,
412            ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
413        };
414
415        for value in sources.user.into_iter().chain(sources.release_channel) {
416            if let Some(value) = value.ui_density {
417                this.ui_density = value;
418            }
419
420            if let Some(value) = value.buffer_font_family.clone() {
421                this.buffer_font.family = value.into();
422            }
423            if let Some(value) = value.buffer_font_features.clone() {
424                this.buffer_font.features = value;
425            }
426
427            if let Some(value) = value.ui_font_family.clone() {
428                this.ui_font.family = value.into();
429            }
430            if let Some(value) = value.ui_font_features.clone() {
431                this.ui_font.features = value;
432            }
433
434            if let Some(value) = &value.theme {
435                this.theme_selection = Some(value.clone());
436
437                let theme_name = value.theme(*system_appearance);
438
439                if let Some(theme) = themes.get(theme_name).log_err() {
440                    this.active_theme = theme;
441                }
442            }
443
444            this.theme_overrides.clone_from(&value.theme_overrides);
445            this.apply_theme_overrides();
446
447            merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
448            merge(
449                &mut this.buffer_font_size,
450                value.buffer_font_size.map(Into::into),
451            );
452            merge(&mut this.buffer_line_height, value.buffer_line_height);
453        }
454
455        Ok(this)
456    }
457
458    fn json_schema(
459        generator: &mut SchemaGenerator,
460        params: &SettingsJsonSchemaParams,
461        cx: &AppContext,
462    ) -> schemars::schema::RootSchema {
463        let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
464        let theme_names = ThemeRegistry::global(cx)
465            .list_names(params.staff_mode)
466            .into_iter()
467            .map(|theme_name| Value::String(theme_name.to_string()))
468            .collect();
469
470        let theme_name_schema = SchemaObject {
471            instance_type: Some(InstanceType::String.into()),
472            enum_values: Some(theme_names),
473            ..Default::default()
474        };
475
476        let available_fonts = params
477            .font_names
478            .iter()
479            .cloned()
480            .map(Value::String)
481            .collect();
482        let fonts_schema = SchemaObject {
483            instance_type: Some(InstanceType::String.into()),
484            enum_values: Some(available_fonts),
485            ..Default::default()
486        };
487        root_schema.definitions.extend([
488            ("ThemeName".into(), theme_name_schema.into()),
489            ("FontFamilies".into(), fonts_schema.into()),
490        ]);
491
492        root_schema
493            .schema
494            .object
495            .as_mut()
496            .unwrap()
497            .properties
498            .extend([
499                (
500                    "buffer_font_family".to_owned(),
501                    Schema::new_ref("#/definitions/FontFamilies".into()),
502                ),
503                (
504                    "ui_font_family".to_owned(),
505                    Schema::new_ref("#/definitions/FontFamilies".into()),
506                ),
507            ]);
508
509        root_schema
510    }
511}
512
513fn merge<T: Copy>(target: &mut T, value: Option<T>) {
514    if let Some(value) = value {
515        *target = value;
516    }
517}