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