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 #[schemars(default = "default_font_features")]
253 pub ui_font_features: Option<FontFeatures>,
254 /// The weight of the UI font in CSS units from 100 to 900.
255 #[serde(default)]
256 pub ui_font_weight: Option<f32>,
257 /// The name of a font to use for rendering in text buffers.
258 #[serde(default)]
259 pub buffer_font_family: Option<String>,
260 /// The font fallbacks to use for rendering in text buffers.
261 #[serde(default)]
262 pub buffer_font_fallbacks: Option<Vec<String>>,
263 /// The default font size for rendering in text buffers.
264 #[serde(default)]
265 pub buffer_font_size: Option<f32>,
266 /// The weight of the editor font in CSS units from 100 to 900.
267 #[serde(default)]
268 pub buffer_font_weight: Option<f32>,
269 /// The buffer's line height.
270 #[serde(default)]
271 pub buffer_line_height: Option<BufferLineHeight>,
272 /// The OpenType features to enable for rendering in text buffers.
273 #[serde(default)]
274 #[schemars(default = "default_font_features")]
275 pub buffer_font_features: Option<FontFeatures>,
276 /// The name of the Zed theme to use.
277 #[serde(default)]
278 pub theme: Option<ThemeSelection>,
279
280 /// UNSTABLE: Expect many elements to be broken.
281 ///
282 // Controls the density of the UI.
283 #[serde(rename = "unstable.ui_density", default)]
284 pub ui_density: Option<UiDensity>,
285
286 /// EXPERIMENTAL: Overrides for the current theme.
287 ///
288 /// These values will override the ones on the current theme specified in `theme`.
289 #[serde(rename = "experimental.theme_overrides", default)]
290 pub theme_overrides: Option<ThemeStyleContent>,
291}
292
293fn default_font_features() -> Option<FontFeatures> {
294 Some(FontFeatures::default())
295}
296
297impl ThemeSettingsContent {
298 /// Sets the theme for the given appearance to the theme with the specified name.
299 pub fn set_theme(&mut self, theme_name: String, appearance: Appearance) {
300 if let Some(selection) = self.theme.as_mut() {
301 let theme_to_update = match selection {
302 ThemeSelection::Static(theme) => theme,
303 ThemeSelection::Dynamic { mode, light, dark } => match mode {
304 ThemeMode::Light => light,
305 ThemeMode::Dark => dark,
306 ThemeMode::System => match appearance {
307 Appearance::Light => light,
308 Appearance::Dark => dark,
309 },
310 },
311 };
312
313 *theme_to_update = theme_name.to_string();
314 } else {
315 self.theme = Some(ThemeSelection::Static(theme_name.to_string()));
316 }
317 }
318
319 pub fn set_mode(&mut self, mode: ThemeMode) {
320 if let Some(selection) = self.theme.as_mut() {
321 match selection {
322 ThemeSelection::Static(theme) => {
323 // If the theme was previously set to a single static theme,
324 // we don't know whether it was a light or dark theme, so we
325 // just use it for both.
326 self.theme = Some(ThemeSelection::Dynamic {
327 mode,
328 light: theme.clone(),
329 dark: theme.clone(),
330 });
331 }
332 ThemeSelection::Dynamic {
333 mode: mode_to_update,
334 ..
335 } => *mode_to_update = mode,
336 }
337 } else {
338 self.theme = Some(ThemeSelection::Dynamic {
339 mode,
340 light: ThemeSettings::DEFAULT_LIGHT_THEME.into(),
341 dark: ThemeSettings::DEFAULT_DARK_THEME.into(),
342 });
343 }
344 }
345}
346
347#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
348#[serde(rename_all = "snake_case")]
349pub enum BufferLineHeight {
350 #[default]
351 Comfortable,
352 Standard,
353 Custom(f32),
354}
355
356impl BufferLineHeight {
357 pub fn value(&self) -> f32 {
358 match self {
359 BufferLineHeight::Comfortable => 1.618,
360 BufferLineHeight::Standard => 1.3,
361 BufferLineHeight::Custom(line_height) => *line_height,
362 }
363 }
364}
365
366impl ThemeSettings {
367 pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
368 cx.try_global::<AdjustedBufferFontSize>()
369 .map_or(self.buffer_font_size, |size| size.0)
370 .max(MIN_FONT_SIZE)
371 }
372
373 pub fn line_height(&self) -> f32 {
374 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
375 }
376
377 /// Switches to the theme with the given name, if it exists.
378 ///
379 /// Returns a `Some` containing the new theme if it was successful.
380 /// Returns `None` otherwise.
381 pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
382 let themes = ThemeRegistry::default_global(cx);
383
384 let mut new_theme = None;
385
386 if let Some(theme) = themes.get(theme).log_err() {
387 self.active_theme = theme.clone();
388 new_theme = Some(theme);
389 }
390
391 self.apply_theme_overrides();
392
393 new_theme
394 }
395
396 /// Applies the theme overrides, if there are any, to the current theme.
397 pub fn apply_theme_overrides(&mut self) {
398 if let Some(theme_overrides) = &self.theme_overrides {
399 let mut base_theme = (*self.active_theme).clone();
400
401 if let Some(window_background_appearance) = theme_overrides.window_background_appearance
402 {
403 base_theme.styles.window_background_appearance =
404 window_background_appearance.into();
405 }
406
407 base_theme
408 .styles
409 .colors
410 .refine(&theme_overrides.theme_colors_refinement());
411 base_theme
412 .styles
413 .status
414 .refine(&theme_overrides.status_colors_refinement());
415 base_theme.styles.player.merge(&theme_overrides.players);
416 base_theme.styles.accents.merge(&theme_overrides.accents);
417 base_theme.styles.syntax =
418 SyntaxTheme::merge(base_theme.styles.syntax, theme_overrides.syntax_overrides());
419
420 self.active_theme = Arc::new(base_theme);
421 }
422 }
423}
424
425pub fn observe_buffer_font_size_adjustment<V: 'static>(
426 cx: &mut ViewContext<V>,
427 f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
428) -> Subscription {
429 cx.observe_global::<AdjustedBufferFontSize>(f)
430}
431
432pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
433 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
434 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
435 let delta = *adjusted_size - buffer_font_size;
436 size + delta
437 } else {
438 size
439 }
440 .max(MIN_FONT_SIZE)
441}
442
443pub fn get_buffer_font_size(cx: &AppContext) -> Pixels {
444 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
445 cx.try_global::<AdjustedBufferFontSize>()
446 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0)
447}
448
449pub fn adjust_buffer_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
450 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
451 let mut adjusted_size = cx
452 .try_global::<AdjustedBufferFontSize>()
453 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
454
455 f(&mut adjusted_size);
456 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
457 cx.set_global(AdjustedBufferFontSize(adjusted_size));
458 cx.refresh();
459}
460
461pub fn has_adjusted_buffer_font_size(cx: &mut AppContext) -> bool {
462 cx.has_global::<AdjustedBufferFontSize>()
463}
464
465pub fn reset_buffer_font_size(cx: &mut AppContext) {
466 if cx.has_global::<AdjustedBufferFontSize>() {
467 cx.remove_global::<AdjustedBufferFontSize>();
468 cx.refresh();
469 }
470}
471
472pub fn setup_ui_font(cx: &mut WindowContext) -> gpui::Font {
473 let (ui_font, ui_font_size) = {
474 let theme_settings = ThemeSettings::get_global(cx);
475 let font = theme_settings.ui_font.clone();
476 (font, get_ui_font_size(cx))
477 };
478
479 cx.set_rem_size(ui_font_size);
480 ui_font
481}
482
483pub fn get_ui_font_size(cx: &WindowContext) -> Pixels {
484 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
485 cx.try_global::<AdjustedUiFontSize>()
486 .map_or(ui_font_size, |adjusted_size| adjusted_size.0)
487}
488
489pub fn adjust_ui_font_size(cx: &mut WindowContext, f: fn(&mut Pixels)) {
490 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size;
491 let mut adjusted_size = cx
492 .try_global::<AdjustedUiFontSize>()
493 .map_or(ui_font_size, |adjusted_size| adjusted_size.0);
494
495 f(&mut adjusted_size);
496 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
497 cx.set_global(AdjustedUiFontSize(adjusted_size));
498 cx.refresh();
499}
500
501pub fn has_adjusted_ui_font_size(cx: &mut AppContext) -> bool {
502 cx.has_global::<AdjustedUiFontSize>()
503}
504
505pub fn reset_ui_font_size(cx: &mut WindowContext) {
506 if cx.has_global::<AdjustedUiFontSize>() {
507 cx.remove_global::<AdjustedUiFontSize>();
508 cx.refresh();
509 }
510}
511
512impl settings::Settings for ThemeSettings {
513 const KEY: Option<&'static str> = None;
514
515 type FileContent = ThemeSettingsContent;
516
517 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
518 let themes = ThemeRegistry::default_global(cx);
519 let system_appearance = SystemAppearance::default_global(cx);
520
521 let defaults = sources.default;
522 let mut this = Self {
523 ui_font_size: defaults.ui_font_size.unwrap().into(),
524 ui_font: Font {
525 family: defaults.ui_font_family.as_ref().unwrap().clone().into(),
526 features: defaults.ui_font_features.clone().unwrap(),
527 fallbacks: defaults
528 .ui_font_fallbacks
529 .as_ref()
530 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
531 weight: defaults.ui_font_weight.map(FontWeight).unwrap(),
532 style: Default::default(),
533 },
534 buffer_font: Font {
535 family: defaults.buffer_font_family.as_ref().unwrap().clone().into(),
536 features: defaults.buffer_font_features.clone().unwrap(),
537 fallbacks: defaults
538 .buffer_font_fallbacks
539 .as_ref()
540 .map(|fallbacks| FontFallbacks::from_fonts(fallbacks.clone())),
541 weight: defaults.buffer_font_weight.map(FontWeight).unwrap(),
542 style: FontStyle::default(),
543 },
544 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
545 buffer_line_height: defaults.buffer_line_height.unwrap(),
546 theme_selection: defaults.theme.clone(),
547 active_theme: themes
548 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
549 .or(themes.get(&one_dark().name))
550 .unwrap(),
551 theme_overrides: None,
552 ui_density: defaults.ui_density.unwrap_or(UiDensity::Default),
553 };
554
555 for value in sources.user.into_iter().chain(sources.release_channel) {
556 if let Some(value) = value.ui_density {
557 this.ui_density = value;
558 }
559
560 if let Some(value) = value.buffer_font_family.clone() {
561 this.buffer_font.family = value.into();
562 }
563 if let Some(value) = value.buffer_font_features.clone() {
564 this.buffer_font.features = value;
565 }
566 if let Some(value) = value.buffer_font_fallbacks.clone() {
567 this.buffer_font.fallbacks = Some(FontFallbacks::from_fonts(value));
568 }
569 if let Some(value) = value.buffer_font_weight {
570 this.buffer_font.weight = FontWeight(value);
571 }
572
573 if let Some(value) = value.ui_font_family.clone() {
574 this.ui_font.family = value.into();
575 }
576 if let Some(value) = value.ui_font_features.clone() {
577 this.ui_font.features = value;
578 }
579 if let Some(value) = value.ui_font_fallbacks.clone() {
580 this.ui_font.fallbacks = Some(FontFallbacks::from_fonts(value));
581 }
582 if let Some(value) = value.ui_font_weight {
583 this.ui_font.weight = FontWeight(value);
584 }
585
586 if let Some(value) = &value.theme {
587 this.theme_selection = Some(value.clone());
588
589 let theme_name = value.theme(*system_appearance);
590
591 if let Some(theme) = themes.get(theme_name).log_err() {
592 this.active_theme = theme;
593 }
594 }
595
596 this.theme_overrides.clone_from(&value.theme_overrides);
597 this.apply_theme_overrides();
598
599 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
600 merge(
601 &mut this.buffer_font_size,
602 value.buffer_font_size.map(Into::into),
603 );
604 merge(&mut this.buffer_line_height, value.buffer_line_height);
605 }
606
607 Ok(this)
608 }
609
610 fn json_schema(
611 generator: &mut SchemaGenerator,
612 params: &SettingsJsonSchemaParams,
613 cx: &AppContext,
614 ) -> schemars::schema::RootSchema {
615 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
616 let theme_names = ThemeRegistry::global(cx)
617 .list_names(params.staff_mode)
618 .into_iter()
619 .map(|theme_name| Value::String(theme_name.to_string()))
620 .collect();
621
622 let theme_name_schema = SchemaObject {
623 instance_type: Some(InstanceType::String.into()),
624 enum_values: Some(theme_names),
625 ..Default::default()
626 };
627
628 root_schema.definitions.extend([
629 ("ThemeName".into(), theme_name_schema.into()),
630 ("FontFamilies".into(), params.font_family_schema()),
631 ("FontFallbacks".into(), params.font_fallback_schema()),
632 ]);
633
634 add_references_to_properties(
635 &mut root_schema,
636 &[
637 ("buffer_font_family", "#/definitions/FontFamilies"),
638 ("buffer_font_fallbacks", "#/definitions/FontFallbacks"),
639 ("ui_font_family", "#/definitions/FontFamilies"),
640 ("ui_font_fallbacks", "#/definitions/FontFallbacks"),
641 ],
642 );
643
644 root_schema
645 }
646}
647
648fn merge<T: Copy>(target: &mut T, value: Option<T>) {
649 if let Some(value) = value {
650 *target = value;
651 }
652}