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::{
11 gen::SchemaGenerator,
12 schema::{InstanceType, Schema, SchemaObject},
13 JsonSchema,
14};
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use settings::{add_references_to_properties, 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 const DEFAULT_LIGHT_THEME: &'static str = "One Light";
98 const DEFAULT_DARK_THEME: &'static str = "One Dark";
99
100 /// Returns the name of the default theme for the given [`Appearance`].
101 pub fn default_theme(appearance: Appearance) -> &'static str {
102 match appearance {
103 Appearance::Light => Self::DEFAULT_LIGHT_THEME,
104 Appearance::Dark => Self::DEFAULT_DARK_THEME,
105 }
106 }
107
108 /// Reloads the current theme.
109 ///
110 /// Reads the [`ThemeSettings`] to know which theme should be loaded,
111 /// taking into account the current [`SystemAppearance`].
112 pub fn reload_current_theme(cx: &mut AppContext) {
113 let mut theme_settings = ThemeSettings::get_global(cx).clone();
114 let system_appearance = SystemAppearance::global(cx);
115
116 if let Some(theme_selection) = theme_settings.theme_selection.clone() {
117 let mut theme_name = theme_selection.theme(*system_appearance);
118
119 // If the selected theme doesn't exist, fall back to a default theme
120 // based on the system appearance.
121 let theme_registry = ThemeRegistry::global(cx);
122 if theme_registry.get(theme_name).ok().is_none() {
123 theme_name = Self::default_theme(*system_appearance);
124 };
125
126 if let Some(_theme) = theme_settings.switch_theme(theme_name, cx) {
127 ThemeSettings::override_global(theme_settings, cx);
128 }
129 }
130 }
131}
132
133/// The appearance of the system.
134#[derive(Debug, Clone, Copy, Deref)]
135pub struct SystemAppearance(pub Appearance);
136
137impl Default for SystemAppearance {
138 fn default() -> Self {
139 Self(Appearance::Dark)
140 }
141}
142
143#[derive(Deref, DerefMut, Default)]
144struct GlobalSystemAppearance(SystemAppearance);
145
146impl Global for GlobalSystemAppearance {}
147
148impl SystemAppearance {
149 /// Initializes the [`SystemAppearance`] for the application.
150 pub fn init(cx: &mut AppContext) {
151 *cx.default_global::<GlobalSystemAppearance>() =
152 GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
153 }
154
155 /// Returns the global [`SystemAppearance`].
156 ///
157 /// Inserts a default [`SystemAppearance`] if one does not yet exist.
158 pub(crate) fn default_global(cx: &mut AppContext) -> Self {
159 cx.default_global::<GlobalSystemAppearance>().0
160 }
161
162 /// Returns the global [`SystemAppearance`].
163 pub fn global(cx: &AppContext) -> Self {
164 cx.global::<GlobalSystemAppearance>().0
165 }
166
167 /// Returns a mutable reference to the global [`SystemAppearance`].
168 pub fn global_mut(cx: &mut AppContext) -> &mut Self {
169 cx.global_mut::<GlobalSystemAppearance>()
170 }
171}
172
173#[derive(Default)]
174pub(crate) struct AdjustedBufferFontSize(Pixels);
175
176impl Global for AdjustedBufferFontSize {}
177
178#[derive(Default)]
179pub(crate) struct AdjustedUiFontSize(Pixels);
180
181impl Global for AdjustedUiFontSize {}
182
183#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
184#[serde(untagged)]
185pub enum ThemeSelection {
186 Static(#[schemars(schema_with = "theme_name_ref")] String),
187 Dynamic {
188 #[serde(default)]
189 mode: ThemeMode,
190 #[schemars(schema_with = "theme_name_ref")]
191 light: String,
192 #[schemars(schema_with = "theme_name_ref")]
193 dark: String,
194 },
195}
196
197fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {
198 Schema::new_ref("#/definitions/ThemeName".into())
199}
200
201#[derive(Debug, PartialEq, Eq, Clone, Copy, Default, Serialize, Deserialize, JsonSchema)]
202#[serde(rename_all = "snake_case")]
203pub enum ThemeMode {
204 /// Use the specified `light` theme.
205 Light,
206
207 /// Use the specified `dark` theme.
208 Dark,
209
210 /// Use the theme based on the system's appearance.
211 #[default]
212 System,
213}
214
215impl ThemeSelection {
216 pub fn theme(&self, system_appearance: Appearance) -> &str {
217 match self {
218 Self::Static(theme) => theme,
219 Self::Dynamic { mode, light, dark } => match mode {
220 ThemeMode::Light => light,
221 ThemeMode::Dark => dark,
222 ThemeMode::System => match system_appearance {
223 Appearance::Light => light,
224 Appearance::Dark => dark,
225 },
226 },
227 }
228 }
229
230 pub fn mode(&self) -> Option<ThemeMode> {
231 match self {
232 ThemeSelection::Static(_) => None,
233 ThemeSelection::Dynamic { mode, .. } => Some(*mode),
234 }
235 }
236}
237
238/// Settings for rendering text in UI and text buffers.
239#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
240pub struct ThemeSettingsContent {
241 /// The default font size for text in the UI.
242 #[serde(default)]
243 pub ui_font_size: Option<f32>,
244 /// The name of a font to use for rendering in the UI.
245 #[serde(default)]
246 pub ui_font_family: Option<String>,
247 /// The font fallbacks to use for rendering in the UI.
248 #[serde(default)]
249 pub ui_font_fallbacks: Option<Vec<String>>,
250 /// The OpenType features to enable for text in the UI.
251 #[serde(default)]
252 pub ui_font_features: Option<FontFeatures>,
253 /// The weight of the UI font in CSS units from 100 to 900.
254 #[serde(default)]
255 pub ui_font_weight: Option<f32>,
256 /// The name of a font to use for rendering in text buffers.
257 #[serde(default)]
258 pub buffer_font_family: Option<String>,
259 /// The font fallbacks to use for rendering in text buffers.
260 #[serde(default)]
261 pub buffer_font_fallbacks: Option<Vec<String>>,
262 /// The default font size for rendering in text buffers.
263 #[serde(default)]
264 pub buffer_font_size: Option<f32>,
265 /// The weight of the editor font in CSS units from 100 to 900.
266 #[serde(default)]
267 pub buffer_font_weight: Option<f32>,
268 /// The buffer's line height.
269 #[serde(default)]
270 pub buffer_line_height: Option<BufferLineHeight>,
271 /// The OpenType features to enable for rendering in text buffers.
272 #[serde(default)]
273 pub buffer_font_features: Option<FontFeatures>,
274 /// The name of the Zed theme to use.
275 #[serde(default)]
276 pub theme: Option<ThemeSelection>,
277
278 /// UNSTABLE: Expect many elements to be broken.
279 ///
280 // Controls the density of the UI.
281 #[serde(rename = "unstable.ui_density", default)]
282 pub ui_density: Option<UiDensity>,
283
284 /// EXPERIMENTAL: Overrides for the current theme.
285 ///
286 /// These values will override the ones on the current theme specified in `theme`.
287 #[serde(rename = "experimental.theme_overrides", default)]
288 pub theme_overrides: Option<ThemeStyleContent>,
289}
290
291impl ThemeSettingsContent {
292 /// Sets the theme for the given appearance to the theme with the specified name.
293 pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {
294 if let Some(selection) = self.theme.as_mut() {
295 let theme_to_update = match selection {
296 ThemeSelection::Static(theme) => theme,
297 ThemeSelection::Dynamic { mode, light, dark } => match mode {
298 ThemeMode::Light => light,
299 ThemeMode::Dark => dark,
300 ThemeMode::System => match appearance {
301 Appearance::Light => light,
302 Appearance::Dark => dark,
303 },
304 },
305 };
306
307 *theme_to_update = theme_name.to_string();
308 } else {
309 self.theme = Some(ThemeSelection::Static(theme_name.to_string()));
310 }
311 }
312
313 pub fn set_mode(&mut self, mode: ThemeMode) {
314 if let Some(selection) = self.theme.as_mut() {
315 match selection {
316 ThemeSelection::Static(theme) => {
317 // If the theme was previously set to a single static theme,
318 // we don't know whether it was a light or dark theme, so we
319 // just use it for both.
320 self.theme = Some(ThemeSelection::Dynamic {
321 mode,
322 light: theme.clone(),
323 dark: theme.clone(),
324 });
325 }
326 ThemeSelection::Dynamic {
327 mode: mode_to_update,
328 ..
329 } => *mode_to_update = mode,
330 }
331 } else {
332 self.theme = Some(ThemeSelection::Dynamic {
333 mode,
334 light: ThemeSettings::DEFAULT_LIGHT_THEME.into(),
335 dark: ThemeSettings::DEFAULT_DARK_THEME.into(),
336 });
337 }
338 }
339}
340
341#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
342#[serde(rename_all = "snake_case")]
343pub enum BufferLineHeight {
344 #[default]
345 Comfortable,
346 Standard,
347 Custom(f32),
348}
349
350impl BufferLineHeight {
351 pub fn value(&self) -> f32 {
352 match self {
353 BufferLineHeight::Comfortable => 1.618,
354 BufferLineHeight::Standard => 1.3,
355 BufferLineHeight::Custom(line_height) => *line_height,
356 }
357 }
358}
359
360impl ThemeSettings {
361 pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
362 cx.try_global::<AdjustedBufferFontSize>()
363 .map_or(self.buffer_font_size, |size| size.0)
364 .max(MIN_FONT_SIZE)
365 }
366
367 pub fn line_height(&self) -> f32 {
368 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
369 }
370
371 /// Switches to the theme with the given name, if it exists.
372 ///
373 /// Returns a `Some` containing the new theme if it was successful.
374 /// Returns `None` otherwise.
375 pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
376 let themes = ThemeRegistry::default_global(cx);
377
378 let mut new_theme = None;
379
380 if let Some(theme) = themes.get(theme).log_err() {
381 self.active_theme = theme.clone();
382 new_theme = Some(theme);
383 }
384
385 self.apply_theme_overrides();
386
387 new_theme
388 }
389
390 /// Applies the theme overrides, if there are any, to the current theme.
391 pub fn apply_theme_overrides(&mut self) {
392 if let Some(theme_overrides) = &self.theme_overrides {
393 let mut base_theme = (*self.active_theme).clone();
394
395 if let Some(window_background_appearance) = theme_overrides.window_background_appearance
396 {
397 base_theme.styles.window_background_appearance =
398 window_background_appearance.into();
399 }
400
401 base_theme
402 .styles
403 .colors
404 .refine(&theme_overrides.theme_colors_refinement());
405 base_theme
406 .styles
407 .status
408 .refine(&theme_overrides.status_colors_refinement());
409 base_theme.styles.player.merge(&theme_overrides.players);
410 base_theme.styles.accents.merge(&theme_overrides.accents);
411 base_theme.styles.syntax =
412 SyntaxTheme::merge(base_theme.styles.syntax, theme_overrides.syntax_overrides());
413
414 self.active_theme = Arc::new(base_theme);
415 }
416 }
417}
418
419pub fn observe_buffer_font_size_adjustment<V: 'static>(
420 cx: &mut ViewContext<V>,
421 f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
422) -> Subscription {
423 cx.observe_global::<AdjustedBufferFontSize>(f)
424}
425
426pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
427 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
428 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
429 let delta = *adjusted_size - buffer_font_size;
430 size + delta
431 } else {
432 size
433 }
434 .max(MIN_FONT_SIZE)
435}
436
437pub fn get_buffer_font_size(cx: &AppContext) -> Pixels {
438 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
439 cx.try_global::<AdjustedBufferFontSize>()
440 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0)
441}
442
443pub fn adjust_buffer_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
444 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
445 let mut adjusted_size = cx
446 .try_global::<AdjustedBufferFontSize>()
447 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
448
449 f(&mut adjusted_size);
450 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
451 cx.set_global(AdjustedBufferFontSize(adjusted_size));
452 cx.refresh();
453}
454
455pub fn has_adjusted_buffer_font_size(cx: &mut AppContext) -> bool {
456 cx.has_global::<AdjustedBufferFontSize>()
457}
458
459pub fn reset_buffer_font_size(cx: &mut AppContext) {
460 if cx.has_global::<AdjustedBufferFontSize>() {
461 cx.remove_global::<AdjustedBufferFontSize>();
462 cx.refresh();
463 }
464}
465
466pub fn setup_ui_font(cx: &mut WindowContext) -> gpui::Font {
467 let (ui_font, ui_font_size) = {
468 let theme_settings = ThemeSettings::get_global(cx);
469 let font = theme_settings.ui_font.clone();
470 (font, get_ui_font_size(cx))
471 };
472
473 cx.set_rem_size(ui_font_size);
474 ui_font
475}
476
477pub fn get_ui_font_size(cx: &WindowContext) -> Pixels {
478 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
479 cx.try_global::<AdjustedUiFontSize>()
480 .map_or(ui_font_size, |adjusted_size| adjusted_size.0)
481}
482
483pub fn adjust_ui_font_size(cx: &mut WindowContext, f: fn(&mut Pixels)) {
484 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
485 let mut adjusted_size = cx
486 .try_global::<AdjustedUiFontSize>()
487 .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
488
489 f(&mut adjusted_size);
490 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
491 cx.set_global(AdjustedUiFontSize(adjusted_size));
492 cx.refresh();
493}
494
495pub fn has_adjusted_ui_font_size(cx: &mut AppContext) -> bool {
496 cx.has_global::<AdjustedUiFontSize>()
497}
498
499pub fn reset_ui_font_size(cx: &mut WindowContext) {
500 if cx.has_global::<AdjustedUiFontSize>() {
501 cx.remove_global::<AdjustedUiFontSize>();
502 cx.refresh();
503 }
504}
505
506impl settings::Settings for ThemeSettings {
507 const KEY: Option<&'static str> = None;
508
509 type FileContent = ThemeSettingsContent;
510
511 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
512 let themes = ThemeRegistry::default_global(cx);
513 let system_appearance = SystemAppearance::default_global(cx);
514
515 let defaults = sources.default;
516 let mut this = Self {
517 ui_font_size: defaults.ui_font_size.unwrap().into(),
518 ui_font: Font {
519 family: defaults.ui_font_family.as_ref().unwrap().clone().into(),
520 features: defaults.ui_font_features.clone().unwrap(),
521 fallbacks: defaults
522 .ui_font_fallbacks
523 .as_ref()
524 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
525 weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
526 style: Default::default(),
527 },
528 buffer_font: Font {
529 family: defaults.buffer_font_family.as_ref().unwrap().clone().into(),
530 features: defaults.buffer_font_features.clone().unwrap(),
531 fallbacks: defaults
532 .buffer_font_fallbacks
533 .as_ref()
534 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
535 weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
536 style: FontStyle::default(),
537 },
538 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
539 buffer_line_height: defaults.buffer_line_height.unwrap(),
540 theme_selection: defaults.theme.clone(),
541 active_theme: themes
542 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
543 .or(themes.get(&one_dark().name))
544 .unwrap(),
545 theme_overrides: None,
546 ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
547 };
548
549 for value in sources.user.into_iter().chain(sources.release_channel) {
550 if let Some(value) = value.ui_density {
551 this.ui_density = value;
552 }
553
554 if let Some(value) = value.buffer_font_family.clone() {
555 this.buffer_font.family = value.into();
556 }
557 if let Some(value) = value.buffer_font_features.clone() {
558 this.buffer_font.features = value;
559 }
560 if let Some(value) = value.buffer_font_fallbacks.clone() {
561 this.buffer_font.fallbacks = Some(FontFallbacks::from_fonts(value));
562 }
563 if let Some(value) = value.buffer_font_weight {
564 this.buffer_font.weight = FontWeight(value);
565 }
566
567 if let Some(value) = value.ui_font_family.clone() {
568 this.ui_font.family = value.into();
569 }
570 if let Some(value) = value.ui_font_features.clone() {
571 this.ui_font.features = value;
572 }
573 if let Some(value) = value.ui_font_fallbacks.clone() {
574 this.ui_font.fallbacks = Some(FontFallbacks::from_fonts(value));
575 }
576 if let Some(value) = value.ui_font_weight {
577 this.ui_font.weight = FontWeight(value);
578 }
579
580 if let Some(value) = &value.theme {
581 this.theme_selection = Some(value.clone());
582
583 let theme_name = value.theme(*system_appearance);
584
585 if let Some(theme) = themes.get(theme_name).log_err() {
586 this.active_theme = theme;
587 }
588 }
589
590 this.theme_overrides.clone_from(&value.theme_overrides);
591 this.apply_theme_overrides();
592
593 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
594 merge(
595 &mut this.buffer_font_size,
596 value.buffer_font_size.map(Into::into),
597 );
598 merge(&mut this.buffer_line_height, value.buffer_line_height);
599 }
600
601 Ok(this)
602 }
603
604 fn json_schema(
605 generator: &mut SchemaGenerator,
606 params: &SettingsJsonSchemaParams,
607 cx: &AppContext,
608 ) -> schemars::schema::RootSchema {
609 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
610 let theme_names = ThemeRegistry::global(cx)
611 .list_names(params.staff_mode)
612 .into_iter()
613 .map(|theme_name| Value::String(theme_name.to_string()))
614 .collect();
615
616 let theme_name_schema = SchemaObject {
617 instance_type: Some(InstanceType::String.into()),
618 enum_values: Some(theme_names),
619 ..Default::default()
620 };
621
622 root_schema.definitions.extend([
623 ("ThemeName".into(), theme_name_schema.into()),
624 ("FontFamilies".into(), params.font_family_schema()),
625 ("FontFallbacks".into(), params.font_fallback_schema()),
626 ]);
627
628 add_references_to_properties(
629 &mut root_schema,
630 &[
631 ("buffer_font_family", "#/definitions/FontFamilies"),
632 ("buffer_font_fallbacks", "#/definitions/FontFallbacks"),
633 ("ui_font_family", "#/definitions/FontFamilies"),
634 ("ui_font_fallbacks", "#/definitions/FontFallbacks"),
635 ],
636 );
637
638 root_schema
639 }
640}
641
642fn merge<T: Copy>(target: &mut T, value: Option<T>) {
643 if let Some(value) = value {
644 *target = value;
645 }
646}