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#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
159pub struct ThemeSettingsContent {
160    #[serde(default)]
161    pub ui_font_size: Option<f32>,
162    #[serde(default)]
163    pub ui_font_family: Option<String>,
164    #[serde(default)]
165    pub ui_font_features: Option<FontFeatures>,
166    #[serde(default)]
167    pub buffer_font_family: Option<String>,
168    #[serde(default)]
169    pub buffer_font_size: Option<f32>,
170    #[serde(default)]
171    pub buffer_line_height: Option<BufferLineHeight>,
172    #[serde(default)]
173    pub buffer_font_features: Option<FontFeatures>,
174    #[serde(default)]
175    pub theme: Option<ThemeSelection>,
176
177    /// EXPERIMENTAL: Overrides for the current theme.
178    ///
179    /// These values will override the ones on the current theme specified in `theme`.
180    #[serde(rename = "experimental.theme_overrides", default)]
181    pub theme_overrides: Option<ThemeStyleContent>,
182}
183
184#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
185#[serde(rename_all = "snake_case")]
186pub enum BufferLineHeight {
187    #[default]
188    Comfortable,
189    Standard,
190    Custom(f32),
191}
192
193impl BufferLineHeight {
194    pub fn value(&self) -> f32 {
195        match self {
196            BufferLineHeight::Comfortable => 1.618,
197            BufferLineHeight::Standard => 1.3,
198            BufferLineHeight::Custom(line_height) => *line_height,
199        }
200    }
201}
202
203impl ThemeSettings {
204    pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
205        cx.try_global::<AdjustedBufferFontSize>()
206            .map_or(self.buffer_font_size, |size| size.0)
207            .max(MIN_FONT_SIZE)
208    }
209
210    pub fn line_height(&self) -> f32 {
211        f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
212    }
213
214    /// Switches to the theme with the given name, if it exists.
215    ///
216    /// Returns a `Some` containing the new theme if it was successful.
217    /// Returns `None` otherwise.
218    pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
219        let themes = ThemeRegistry::default_global(cx);
220
221        let mut new_theme = None;
222
223        if let Some(theme) = themes.get(theme).log_err() {
224            self.active_theme = theme.clone();
225            new_theme = Some(theme);
226        }
227
228        self.apply_theme_overrides();
229
230        new_theme
231    }
232
233    /// Applies the theme overrides, if there are any, to the current theme.
234    pub fn apply_theme_overrides(&mut self) {
235        if let Some(theme_overrides) = &self.theme_overrides {
236            let mut base_theme = (*self.active_theme).clone();
237
238            base_theme
239                .styles
240                .colors
241                .refine(&theme_overrides.theme_colors_refinement());
242            base_theme
243                .styles
244                .status
245                .refine(&theme_overrides.status_colors_refinement());
246            base_theme.styles.player.merge(&theme_overrides.players);
247            base_theme.styles.syntax = Arc::new(SyntaxTheme {
248                highlights: {
249                    let mut highlights = base_theme.styles.syntax.highlights.clone();
250                    // Overrides come second in the highlight list so that they take precedence
251                    // over the ones in the base theme.
252                    highlights.extend(theme_overrides.syntax_overrides());
253                    highlights
254                },
255            });
256
257            self.active_theme = Arc::new(base_theme);
258        }
259    }
260}
261
262pub fn observe_buffer_font_size_adjustment<V: 'static>(
263    cx: &mut ViewContext<V>,
264    f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
265) -> Subscription {
266    cx.observe_global::<AdjustedBufferFontSize>(f)
267}
268
269pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
270    if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
271        let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
272        let delta = *adjusted_size - buffer_font_size;
273        size + delta
274    } else {
275        size
276    }
277    .max(MIN_FONT_SIZE)
278}
279
280pub fn adjust_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
281    let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
282    let mut adjusted_size = cx
283        .try_global::<AdjustedBufferFontSize>()
284        .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
285
286    f(&mut adjusted_size);
287    adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
288    cx.set_global(AdjustedBufferFontSize(adjusted_size));
289    cx.refresh();
290}
291
292pub fn reset_font_size(cx: &mut AppContext) {
293    if cx.has_global::<AdjustedBufferFontSize>() {
294        cx.remove_global::<AdjustedBufferFontSize>();
295        cx.refresh();
296    }
297}
298
299impl settings::Settings for ThemeSettings {
300    const KEY: Option<&'static str> = None;
301
302    type FileContent = ThemeSettingsContent;
303
304    fn load(
305        defaults: &Self::FileContent,
306        user_values: &[&Self::FileContent],
307        cx: &mut AppContext,
308    ) -> Result<Self> {
309        let themes = ThemeRegistry::default_global(cx);
310        let system_appearance = SystemAppearance::default_global(cx);
311
312        let mut this = Self {
313            ui_font_size: defaults.ui_font_size.unwrap().into(),
314            ui_font: Font {
315                family: defaults.ui_font_family.clone().unwrap().into(),
316                features: defaults.ui_font_features.unwrap(),
317                weight: Default::default(),
318                style: Default::default(),
319            },
320            buffer_font: Font {
321                family: defaults.buffer_font_family.clone().unwrap().into(),
322                features: defaults.buffer_font_features.unwrap(),
323                weight: FontWeight::default(),
324                style: FontStyle::default(),
325            },
326            buffer_font_size: defaults.buffer_font_size.unwrap().into(),
327            buffer_line_height: defaults.buffer_line_height.unwrap(),
328            theme_selection: defaults.theme.clone(),
329            active_theme: themes
330                .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
331                .or(themes.get(&one_dark().name))
332                .unwrap(),
333            theme_overrides: None,
334        };
335
336        for value in user_values.iter().copied().cloned() {
337            if let Some(value) = value.buffer_font_family {
338                this.buffer_font.family = value.into();
339            }
340            if let Some(value) = value.buffer_font_features {
341                this.buffer_font.features = value;
342            }
343
344            if let Some(value) = value.ui_font_family {
345                this.ui_font.family = value.into();
346            }
347            if let Some(value) = value.ui_font_features {
348                this.ui_font.features = value;
349            }
350
351            if let Some(value) = &value.theme {
352                this.theme_selection = Some(value.clone());
353
354                let theme_name = value.theme(*system_appearance);
355
356                if let Some(theme) = themes.get(theme_name).log_err() {
357                    this.active_theme = theme;
358                }
359            }
360
361            this.theme_overrides = value.theme_overrides;
362            this.apply_theme_overrides();
363
364            merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
365            merge(
366                &mut this.buffer_font_size,
367                value.buffer_font_size.map(Into::into),
368            );
369            merge(&mut this.buffer_line_height, value.buffer_line_height);
370        }
371
372        Ok(this)
373    }
374
375    fn json_schema(
376        generator: &mut SchemaGenerator,
377        params: &SettingsJsonSchemaParams,
378        cx: &AppContext,
379    ) -> schemars::schema::RootSchema {
380        let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
381        let theme_names = ThemeRegistry::global(cx)
382            .list_names(params.staff_mode)
383            .into_iter()
384            .map(|theme_name| Value::String(theme_name.to_string()))
385            .collect();
386
387        let theme_name_schema = SchemaObject {
388            instance_type: Some(InstanceType::String.into()),
389            enum_values: Some(theme_names),
390            ..Default::default()
391        };
392
393        let available_fonts = params
394            .font_names
395            .iter()
396            .cloned()
397            .map(Value::String)
398            .collect();
399        let fonts_schema = SchemaObject {
400            instance_type: Some(InstanceType::String.into()),
401            enum_values: Some(available_fonts),
402            ..Default::default()
403        };
404        root_schema.definitions.extend([
405            ("ThemeName".into(), theme_name_schema.into()),
406            ("FontFamilies".into(), fonts_schema.into()),
407        ]);
408
409        root_schema
410            .schema
411            .object
412            .as_mut()
413            .unwrap()
414            .properties
415            .extend([
416                (
417                    "buffer_font_family".to_owned(),
418                    Schema::new_ref("#/definitions/FontFamilies".into()),
419                ),
420                (
421                    "ui_font_family".to_owned(),
422                    Schema::new_ref("#/definitions/FontFamilies".into()),
423                ),
424            ]);
425
426        root_schema
427    }
428}
429
430fn merge<T: Copy>(target: &mut T, value: Option<T>) {
431    if let Some(value) = value {
432        *target = value;
433    }
434}