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