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