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