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/// Settings for rendering text in UI and text buffers.
159#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
160pub struct ThemeSettingsContent {
161 /// The default font size for text in the UI.
162 #[serde(default)]
163 pub ui_font_size: Option<f32>,
164 /// The name of a font to use for rendering in the UI.
165 #[serde(default)]
166 pub ui_font_family: Option<String>,
167 /// The OpenType features to enable for text in the UI.
168 #[serde(default)]
169 pub ui_font_features: Option<FontFeatures>,
170 /// The name of a font to use for rendering in text buffers.
171 #[serde(default)]
172 pub buffer_font_family: Option<String>,
173 /// The default font size for rendering in text buffers.
174 #[serde(default)]
175 pub buffer_font_size: Option<f32>,
176 /// The buffer's line height.
177 #[serde(default)]
178 pub buffer_line_height: Option<BufferLineHeight>,
179 /// The OpenType features to enable for rendering in text buffers.
180 #[serde(default)]
181 pub buffer_font_features: Option<FontFeatures>,
182 /// The name of the Zed theme to use.
183 #[serde(default)]
184 pub theme: Option<ThemeSelection>,
185
186 /// EXPERIMENTAL: Overrides for the current theme.
187 ///
188 /// These values will override the ones on the current theme specified in `theme`.
189 #[serde(rename = "experimental.theme_overrides", default)]
190 pub theme_overrides: Option<ThemeStyleContent>,
191}
192
193#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, JsonSchema, Default)]
194#[serde(rename_all = "snake_case")]
195pub enum BufferLineHeight {
196 #[default]
197 Comfortable,
198 Standard,
199 Custom(f32),
200}
201
202impl BufferLineHeight {
203 pub fn value(&self) -> f32 {
204 match self {
205 BufferLineHeight::Comfortable => 1.618,
206 BufferLineHeight::Standard => 1.3,
207 BufferLineHeight::Custom(line_height) => *line_height,
208 }
209 }
210}
211
212impl ThemeSettings {
213 pub fn buffer_font_size(&self, cx: &AppContext) -> Pixels {
214 cx.try_global::<AdjustedBufferFontSize>()
215 .map_or(self.buffer_font_size, |size| size.0)
216 .max(MIN_FONT_SIZE)
217 }
218
219 pub fn line_height(&self) -> f32 {
220 f32::max(self.buffer_line_height.value(), MIN_LINE_HEIGHT)
221 }
222
223 /// Switches to the theme with the given name, if it exists.
224 ///
225 /// Returns a `Some` containing the new theme if it was successful.
226 /// Returns `None` otherwise.
227 pub fn switch_theme(&mut self, theme: &str, cx: &mut AppContext) -> Option<Arc<Theme>> {
228 let themes = ThemeRegistry::default_global(cx);
229
230 let mut new_theme = None;
231
232 if let Some(theme) = themes.get(theme).log_err() {
233 self.active_theme = theme.clone();
234 new_theme = Some(theme);
235 }
236
237 self.apply_theme_overrides();
238
239 new_theme
240 }
241
242 /// Applies the theme overrides, if there are any, to the current theme.
243 pub fn apply_theme_overrides(&mut self) {
244 if let Some(theme_overrides) = &self.theme_overrides {
245 let mut base_theme = (*self.active_theme).clone();
246
247 base_theme
248 .styles
249 .colors
250 .refine(&theme_overrides.theme_colors_refinement());
251 base_theme
252 .styles
253 .status
254 .refine(&theme_overrides.status_colors_refinement());
255 base_theme.styles.player.merge(&theme_overrides.players);
256 base_theme.styles.syntax = Arc::new(SyntaxTheme {
257 highlights: {
258 let mut highlights = base_theme.styles.syntax.highlights.clone();
259 // Overrides come second in the highlight list so that they take precedence
260 // over the ones in the base theme.
261 highlights.extend(theme_overrides.syntax_overrides());
262 highlights
263 },
264 });
265
266 self.active_theme = Arc::new(base_theme);
267 }
268 }
269}
270
271pub fn observe_buffer_font_size_adjustment<V: 'static>(
272 cx: &mut ViewContext<V>,
273 f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
274) -> Subscription {
275 cx.observe_global::<AdjustedBufferFontSize>(f)
276}
277
278pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
279 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
280 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
281 let delta = *adjusted_size - buffer_font_size;
282 size + delta
283 } else {
284 size
285 }
286 .max(MIN_FONT_SIZE)
287}
288
289pub fn adjust_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
290 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
291 let mut adjusted_size = cx
292 .try_global::<AdjustedBufferFontSize>()
293 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
294
295 f(&mut adjusted_size);
296 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
297 cx.set_global(AdjustedBufferFontSize(adjusted_size));
298 cx.refresh();
299}
300
301pub fn reset_font_size(cx: &mut AppContext) {
302 if cx.has_global::<AdjustedBufferFontSize>() {
303 cx.remove_global::<AdjustedBufferFontSize>();
304 cx.refresh();
305 }
306}
307
308impl settings::Settings for ThemeSettings {
309 const KEY: Option<&'static str> = None;
310
311 type FileContent = ThemeSettingsContent;
312
313 fn load(
314 defaults: &Self::FileContent,
315 user_values: &[&Self::FileContent],
316 cx: &mut AppContext,
317 ) -> Result<Self> {
318 let themes = ThemeRegistry::default_global(cx);
319 let system_appearance = SystemAppearance::default_global(cx);
320
321 let mut this = Self {
322 ui_font_size: defaults.ui_font_size.unwrap().into(),
323 ui_font: Font {
324 family: defaults.ui_font_family.clone().unwrap().into(),
325 features: defaults.ui_font_features.unwrap(),
326 weight: Default::default(),
327 style: Default::default(),
328 },
329 buffer_font: Font {
330 family: defaults.buffer_font_family.clone().unwrap().into(),
331 features: defaults.buffer_font_features.unwrap(),
332 weight: FontWeight::default(),
333 style: FontStyle::default(),
334 },
335 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
336 buffer_line_height: defaults.buffer_line_height.unwrap(),
337 theme_selection: defaults.theme.clone(),
338 active_theme: themes
339 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
340 .or(themes.get(&one_dark().name))
341 .unwrap(),
342 theme_overrides: None,
343 };
344
345 for value in user_values.iter().copied().cloned() {
346 if let Some(value) = value.buffer_font_family {
347 this.buffer_font.family = value.into();
348 }
349 if let Some(value) = value.buffer_font_features {
350 this.buffer_font.features = value;
351 }
352
353 if let Some(value) = value.ui_font_family {
354 this.ui_font.family = value.into();
355 }
356 if let Some(value) = value.ui_font_features {
357 this.ui_font.features = value;
358 }
359
360 if let Some(value) = &value.theme {
361 this.theme_selection = Some(value.clone());
362
363 let theme_name = value.theme(*system_appearance);
364
365 if let Some(theme) = themes.get(theme_name).log_err() {
366 this.active_theme = theme;
367 }
368 }
369
370 this.theme_overrides = value.theme_overrides;
371 this.apply_theme_overrides();
372
373 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
374 merge(
375 &mut this.buffer_font_size,
376 value.buffer_font_size.map(Into::into),
377 );
378 merge(&mut this.buffer_line_height, value.buffer_line_height);
379 }
380
381 Ok(this)
382 }
383
384 fn json_schema(
385 generator: &mut SchemaGenerator,
386 params: &SettingsJsonSchemaParams,
387 cx: &AppContext,
388 ) -> schemars::schema::RootSchema {
389 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
390 let theme_names = ThemeRegistry::global(cx)
391 .list_names(params.staff_mode)
392 .into_iter()
393 .map(|theme_name| Value::String(theme_name.to_string()))
394 .collect();
395
396 let theme_name_schema = SchemaObject {
397 instance_type: Some(InstanceType::String.into()),
398 enum_values: Some(theme_names),
399 ..Default::default()
400 };
401
402 let available_fonts = params
403 .font_names
404 .iter()
405 .cloned()
406 .map(Value::String)
407 .collect();
408 let fonts_schema = SchemaObject {
409 instance_type: Some(InstanceType::String.into()),
410 enum_values: Some(available_fonts),
411 ..Default::default()
412 };
413 root_schema.definitions.extend([
414 ("ThemeName".into(), theme_name_schema.into()),
415 ("FontFamilies".into(), fonts_schema.into()),
416 ]);
417
418 root_schema
419 .schema
420 .object
421 .as_mut()
422 .unwrap()
423 .properties
424 .extend([
425 (
426 "buffer_font_family".to_owned(),
427 Schema::new_ref("#/definitions/FontFamilies".into()),
428 ),
429 (
430 "ui_font_family".to_owned(),
431 Schema::new_ref("#/definitions/FontFamilies".into()),
432 ),
433 ]);
434
435 root_schema
436 }
437}
438
439fn merge<T: Copy>(target: &mut T, value: Option<T>) {
440 if let Some(value) = value {
441 *target = value;
442 }
443}