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,
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};
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(Clone)]
25pub struct ThemeSettings {
26 pub ui_font_size: Pixels,
27 pub ui_font: Font,
28 pub buffer_font: Font,
29 pub buffer_font_size: Pixels,
30 pub buffer_line_height: BufferLineHeight,
31 pub theme_selection: Option<ThemeSelection>,
32 pub active_theme: Arc<Theme>,
33 pub theme_overrides: Option<ThemeStyleContent>,
34}
35
36impl ThemeSettings {
37 /// Reloads the current theme.
38 ///
39 /// Reads the [`ThemeSettings`] to know which theme should be loaded,
40 /// taking into account the current [`SystemAppearance`].
41 pub fn reload_current_theme(cx: &mut AppContext) {
42 let mut theme_settings = ThemeSettings::get_global(cx).clone();
43 let system_appearance = SystemAppearance::global(cx);
44
45 if let Some(theme_selection) = theme_settings.theme_selection.clone() {
46 let mut theme_name = theme_selection.theme(*system_appearance);
47
48 // If the selected theme doesn't exist, fall back to a default theme
49 // based on the system appearance.
50 let theme_registry = ThemeRegistry::global(cx);
51 if theme_registry.get(&theme_name).ok().is_none() {
52 theme_name = match *system_appearance {
53 Appearance::Light => "One Light",
54 Appearance::Dark => "One Dark",
55 };
56 };
57
58 if let Some(_theme) = theme_settings.switch_theme(&theme_name, cx) {
59 ThemeSettings::override_global(theme_settings, cx);
60 }
61 }
62 }
63}
64
65/// The appearance of the system.
66#[derive(Debug, Clone, Copy, Deref)]
67pub struct SystemAppearance(pub Appearance);
68
69impl Default for SystemAppearance {
70 fn default() -> Self {
71 Self(Appearance::Dark)
72 }
73}
74
75#[derive(Deref, DerefMut, Default)]
76struct GlobalSystemAppearance(SystemAppearance);
77
78impl Global for GlobalSystemAppearance {}
79
80impl SystemAppearance {
81 /// Initializes the [`SystemAppearance`] for the application.
82 pub fn init(cx: &mut AppContext) {
83 *cx.default_global::<GlobalSystemAppearance>() =
84 GlobalSystemAppearance(SystemAppearance(cx.window_appearance().into()));
85 }
86
87 /// Returns the global [`SystemAppearance`].
88 ///
89 /// Inserts a default [`SystemAppearance`] if one does not yet exist.
90 pub(crate) fn default_global(cx: &mut AppContext) -> Self {
91 cx.default_global::<GlobalSystemAppearance>().0
92 }
93
94 /// Returns the global [`SystemAppearance`].
95 pub fn global(cx: &AppContext) -> Self {
96 cx.global::<GlobalSystemAppearance>().0
97 }
98
99 /// Returns a mutable reference to the global [`SystemAppearance`].
100 pub fn global_mut(cx: &mut AppContext) -> &mut Self {
101 cx.global_mut::<GlobalSystemAppearance>()
102 }
103}
104
105#[derive(Default)]
106pub(crate) struct AdjustedBufferFontSize(Pixels);
107
108impl Global for AdjustedBufferFontSize {}
109
110#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
111#[serde(untagged)]
112pub enum ThemeSelection {
113 Static(#[schemars(schema_with = "theme_name_ref")] String),
114 Dynamic {
115 #[serde(default)]
116 mode: ThemeMode,
117 #[schemars(schema_with = "theme_name_ref")]
118 light: String,
119 #[schemars(schema_with = "theme_name_ref")]
120 dark: String,
121 },
122}
123
124fn theme_name_ref(_: &mut SchemaGenerator) -> Schema {
125 Schema::new_ref("#/definitions/ThemeName".into())
126}
127
128#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
129#[serde(rename_all = "snake_case")]
130pub enum ThemeMode {
131 /// Use the specified `light` theme.
132 Light,
133
134 /// Use the specified `dark` theme.
135 Dark,
136
137 /// Use the theme based on the system's appearance.
138 #[default]
139 System,
140}
141
142impl ThemeSelection {
143 pub fn theme(&self, system_appearance: Appearance) -> &str {
144 match self {
145 Self::Static(theme) => theme,
146 Self::Dynamic { mode, light, dark } => match mode {
147 ThemeMode::Light => light,
148 ThemeMode::Dark => dark,
149 ThemeMode::System => match system_appearance {
150 Appearance::Light => light,
151 Appearance::Dark => dark,
152 },
153 },
154 }
155 }
156}
157
158#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
159pub struct ThemeSettingsContent {
160 #[serde(default)]
161 pub ui_font_size: Option<f32>,
162 #[serde(default)]
163 pub ui_font_family: Option<String>,
164 #[serde(default)]
165 pub ui_font_features: Option<FontFeatures>,
166 #[serde(default)]
167 pub buffer_font_family: Option<String>,
168 #[serde(default)]
169 pub buffer_font_size: Option<f32>,
170 #[serde(default)]
171 pub buffer_line_height: Option<BufferLineHeight>,
172 #[serde(default)]
173 pub buffer_font_features: Option<FontFeatures>,
174 #[serde(default)]
175 pub theme: Option<ThemeSelection>,
176
177 /// EXPERIMENTAL: Overrides for the current theme.
178 ///
179 /// These values will override the ones on the current theme specified in `theme`.
180 #[serde(rename = "experimental.theme_overrides", default)]
181 pub theme_overrides: Option<ThemeStyleContent>,
182}
183
184#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
185#[serde(rename_all = "snake_case")]
186pub enum BufferLineHeight {
187 #[default]
188 Comfortable,
189 Standard,
190 Custom(f32),
191}
192
193impl BufferLineHeight {
194 pub fn value(&self) -> f32 {
195 match self {
196 BufferLineHeight::Comfortable => 1.618,
197 BufferLineHeight::Standard => 1.3,
198 BufferLineHeight::Custom(line_height) => *line_height,
199 }
200 }
201}
202
203impl ThemeSettings {
204 pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
205 cx.try_global::<AdjustedBufferFontSize>()
206 .map_or(self.buffer_font_size, |size| size.0)
207 .max(MIN_FONT_SIZE)
208 }
209
210 pub fn line_height(&self) -> f32 {
211 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
212 }
213
214 /// Switches to the theme with the given name, if it exists.
215 ///
216 /// Returns a `Some` containing the new theme if it was successful.
217 /// Returns `None` otherwise.
218 pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
219 let themes = ThemeRegistry::default_global(cx);
220
221 let mut new_theme = None;
222
223 if let Some(theme) = themes.get(&theme).log_err() {
224 self.active_theme = theme.clone();
225 new_theme = Some(theme);
226 }
227
228 self.apply_theme_overrides();
229
230 new_theme
231 }
232
233 /// Applies the theme overrides, if there are any, to the current theme.
234 pub fn apply_theme_overrides(&mut self) {
235 if let Some(theme_overrides) = &self.theme_overrides {
236 let mut base_theme = (*self.active_theme).clone();
237
238 base_theme
239 .styles
240 .colors
241 .refine(&theme_overrides.theme_colors_refinement());
242 base_theme
243 .styles
244 .status
245 .refine(&theme_overrides.status_colors_refinement());
246 base_theme.styles.syntax = Arc::new(SyntaxTheme {
247 highlights: {
248 let mut highlights = base_theme.styles.syntax.highlights.clone();
249 // Overrides come second in the highlight list so that they take precedence
250 // over the ones in the base theme.
251 highlights.extend(theme_overrides.syntax_overrides());
252 highlights
253 },
254 });
255
256 self.active_theme = Arc::new(base_theme);
257 }
258 }
259}
260
261pub fn observe_buffer_font_size_adjustment<V: 'static>(
262 cx: &mut ViewContext<V>,
263 f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
264) -> Subscription {
265 cx.observe_global::<AdjustedBufferFontSize>(f)
266}
267
268pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
269 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
270 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
271 let delta = *adjusted_size - buffer_font_size;
272 size + delta
273 } else {
274 size
275 }
276 .max(MIN_FONT_SIZE)
277}
278
279pub fn adjust_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
280 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
281 let mut adjusted_size = cx
282 .try_global::<AdjustedBufferFontSize>()
283 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
284
285 f(&mut adjusted_size);
286 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
287 cx.set_global(AdjustedBufferFontSize(adjusted_size));
288 cx.refresh();
289}
290
291pub fn reset_font_size(cx: &mut AppContext) {
292 if cx.has_global::<AdjustedBufferFontSize>() {
293 cx.remove_global::<AdjustedBufferFontSize>();
294 cx.refresh();
295 }
296}
297
298impl settings::Settings for ThemeSettings {
299 const KEY: Option<&'static str> = None;
300
301 type FileContent = ThemeSettingsContent;
302
303 fn load(
304 defaults: &Self::FileContent,
305 user_values: &[&Self::FileContent],
306 cx: &mut AppContext,
307 ) -> Result<Self> {
308 let themes = ThemeRegistry::default_global(cx);
309 let system_appearance = SystemAppearance::default_global(cx);
310
311 let mut this = Self {
312 ui_font_size: defaults.ui_font_size.unwrap().into(),
313 ui_font: Font {
314 family: defaults.ui_font_family.clone().unwrap().into(),
315 features: defaults.ui_font_features.clone().unwrap(),
316 weight: Default::default(),
317 style: Default::default(),
318 },
319 buffer_font: Font {
320 family: defaults.buffer_font_family.clone().unwrap().into(),
321 features: defaults.buffer_font_features.clone().unwrap(),
322 weight: FontWeight::default(),
323 style: FontStyle::default(),
324 },
325 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
326 buffer_line_height: defaults.buffer_line_height.unwrap(),
327 theme_selection: defaults.theme.clone(),
328 active_theme: themes
329 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
330 .or(themes.get(&one_dark().name))
331 .unwrap(),
332 theme_overrides: None,
333 };
334
335 for value in user_values.into_iter().copied().cloned() {
336 if let Some(value) = value.buffer_font_family {
337 this.buffer_font.family = value.into();
338 }
339 if let Some(value) = value.buffer_font_features {
340 this.buffer_font.features = value;
341 }
342
343 if let Some(value) = value.ui_font_family {
344 this.ui_font.family = value.into();
345 }
346 if let Some(value) = value.ui_font_features {
347 this.ui_font.features = value;
348 }
349
350 if let Some(value) = &value.theme {
351 this.theme_selection = Some(value.clone());
352
353 let theme_name = value.theme(*system_appearance);
354
355 if let Some(theme) = themes.get(theme_name).log_err() {
356 this.active_theme = theme;
357 }
358 }
359
360 this.theme_overrides = value.theme_overrides;
361 this.apply_theme_overrides();
362
363 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
364 merge(
365 &mut this.buffer_font_size,
366 value.buffer_font_size.map(Into::into),
367 );
368 merge(&mut this.buffer_line_height, value.buffer_line_height);
369 }
370
371 Ok(this)
372 }
373
374 fn json_schema(
375 generator: &mut SchemaGenerator,
376 params: &SettingsJsonSchemaParams,
377 cx: &AppContext,
378 ) -> schemars::schema::RootSchema {
379 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
380 let theme_names = ThemeRegistry::global(cx)
381 .list_names(params.staff_mode)
382 .into_iter()
383 .map(|theme_name| Value::String(theme_name.to_string()))
384 .collect();
385
386 let theme_name_schema = SchemaObject {
387 instance_type: Some(InstanceType::String.into()),
388 enum_values: Some(theme_names),
389 ..Default::default()
390 };
391
392 let available_fonts = params
393 .font_names
394 .iter()
395 .cloned()
396 .map(Value::String)
397 .collect();
398 let fonts_schema = SchemaObject {
399 instance_type: Some(InstanceType::String.into()),
400 enum_values: Some(available_fonts),
401 ..Default::default()
402 };
403 root_schema.definitions.extend([
404 ("ThemeName".into(), theme_name_schema.into()),
405 ("FontFamilies".into(), fonts_schema.into()),
406 ]);
407
408 root_schema
409 .schema
410 .object
411 .as_mut()
412 .unwrap()
413 .properties
414 .extend([
415 (
416 "buffer_font_family".to_owned(),
417 Schema::new_ref("#/definitions/FontFamilies".into()),
418 ),
419 (
420 "ui_font_family".to_owned(),
421 Schema::new_ref("#/definitions/FontFamilies".into()),
422 ),
423 ]);
424
425 root_schema
426 }
427}
428
429fn merge<T: Copy>(target: &mut T, value: Option<T>) {
430 if let Some(value) = value {
431 *target = value;
432 }
433}