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