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, 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(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 if let Some(window_background_appearance) = theme_overrides.window_background_appearance
248 {
249 base_theme.styles.window_background_appearance =
250 window_background_appearance.into();
251 }
252
253 base_theme
254 .styles
255 .colors
256 .refine(&theme_overrides.theme_colors_refinement());
257 base_theme
258 .styles
259 .status
260 .refine(&theme_overrides.status_colors_refinement());
261 base_theme.styles.player.merge(&theme_overrides.players);
262 base_theme.styles.syntax = Arc::new(SyntaxTheme {
263 highlights: {
264 let mut highlights = base_theme.styles.syntax.highlights.clone();
265 // Overrides come second in the highlight list so that they take precedence
266 // over the ones in the base theme.
267 highlights.extend(theme_overrides.syntax_overrides());
268 highlights
269 },
270 });
271
272 self.active_theme = Arc::new(base_theme);
273 }
274 }
275}
276
277pub fn observe_buffer_font_size_adjustment<V: 'static>(
278 cx: &mut ViewContext<V>,
279 f: impl 'static + Fn(&mut V, &mut ViewContext<V>),
280) -> Subscription {
281 cx.observe_global::<AdjustedBufferFontSize>(f)
282}
283
284pub fn adjusted_font_size(size: Pixels, cx: &mut AppContext) -> Pixels {
285 if let Some(AdjustedBufferFontSize(adjusted_size)) = cx.try_global::<AdjustedBufferFontSize>() {
286 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
287 let delta = *adjusted_size - buffer_font_size;
288 size + delta
289 } else {
290 size
291 }
292 .max(MIN_FONT_SIZE)
293}
294
295pub fn adjust_font_size(cx: &mut AppContext, f: fn(&mut Pixels)) {
296 let buffer_font_size = ThemeSettings::get_global(cx).buffer_font_size;
297 let mut adjusted_size = cx
298 .try_global::<AdjustedBufferFontSize>()
299 .map_or(buffer_font_size, |adjusted_size| adjusted_size.0);
300
301 f(&mut adjusted_size);
302 adjusted_size = adjusted_size.max(MIN_FONT_SIZE);
303 cx.set_global(AdjustedBufferFontSize(adjusted_size));
304 cx.refresh();
305}
306
307pub fn reset_font_size(cx: &mut AppContext) {
308 if cx.has_global::<AdjustedBufferFontSize>() {
309 cx.remove_global::<AdjustedBufferFontSize>();
310 cx.refresh();
311 }
312}
313
314impl settings::Settings for ThemeSettings {
315 const KEY: Option<&'static str> = None;
316
317 type FileContent = ThemeSettingsContent;
318
319 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self> {
320 let themes = ThemeRegistry::default_global(cx);
321 let system_appearance = SystemAppearance::default_global(cx);
322
323 let defaults = sources.default;
324 let mut this = Self {
325 ui_font_size: defaults.ui_font_size.unwrap().into(),
326 ui_font: Font {
327 family: defaults.ui_font_family.clone().unwrap().into(),
328 features: defaults.ui_font_features.unwrap(),
329 weight: Default::default(),
330 style: Default::default(),
331 },
332 buffer_font: Font {
333 family: defaults.buffer_font_family.clone().unwrap().into(),
334 features: defaults.buffer_font_features.unwrap(),
335 weight: FontWeight::default(),
336 style: FontStyle::default(),
337 },
338 buffer_font_size: defaults.buffer_font_size.unwrap().into(),
339 buffer_line_height: defaults.buffer_line_height.unwrap(),
340 theme_selection: defaults.theme.clone(),
341 active_theme: themes
342 .get(defaults.theme.as_ref().unwrap().theme(*system_appearance))
343 .or(themes.get(&one_dark().name))
344 .unwrap(),
345 theme_overrides: None,
346 };
347
348 for value in sources.user.into_iter().chain(sources.release_channel) {
349 if let Some(value) = value.buffer_font_family.clone() {
350 this.buffer_font.family = value.into();
351 }
352 if let Some(value) = value.buffer_font_features {
353 this.buffer_font.features = value;
354 }
355
356 if let Some(value) = value.ui_font_family.clone() {
357 this.ui_font.family = value.into();
358 }
359 if let Some(value) = value.ui_font_features {
360 this.ui_font.features = value;
361 }
362
363 if let Some(value) = &value.theme {
364 this.theme_selection = Some(value.clone());
365
366 let theme_name = value.theme(*system_appearance);
367
368 if let Some(theme) = themes.get(theme_name).log_err() {
369 this.active_theme = theme;
370 }
371 }
372
373 this.theme_overrides = value.theme_overrides.clone();
374 this.apply_theme_overrides();
375
376 merge(&mut this.ui_font_size, value.ui_font_size.map(Into::into));
377 merge(
378 &mut this.buffer_font_size,
379 value.buffer_font_size.map(Into::into),
380 );
381 merge(&mut this.buffer_line_height, value.buffer_line_height);
382 }
383
384 Ok(this)
385 }
386
387 fn json_schema(
388 generator: &mut SchemaGenerator,
389 params: &SettingsJsonSchemaParams,
390 cx: &AppContext,
391 ) -> schemars::schema::RootSchema {
392 let mut root_schema = generator.root_schema_for::<ThemeSettingsContent>();
393 let theme_names = ThemeRegistry::global(cx)
394 .list_names(params.staff_mode)
395 .into_iter()
396 .map(|theme_name| Value::String(theme_name.to_string()))
397 .collect();
398
399 let theme_name_schema = SchemaObject {
400 instance_type: Some(InstanceType::String.into()),
401 enum_values: Some(theme_names),
402 ..Default::default()
403 };
404
405 let available_fonts = params
406 .font_names
407 .iter()
408 .cloned()
409 .map(Value::String)
410 .collect();
411 let fonts_schema = SchemaObject {
412 instance_type: Some(InstanceType::String.into()),
413 enum_values: Some(available_fonts),
414 ..Default::default()
415 };
416 root_schema.definitions.extend([
417 ("ThemeName".into(), theme_name_schema.into()),
418 ("FontFamilies".into(), fonts_schema.into()),
419 ]);
420
421 root_schema
422 .schema
423 .object
424 .as_mut()
425 .unwrap()
426 .properties
427 .extend([
428 (
429 "buffer_font_family".to_owned(),
430 Schema::new_ref("#/definitions/FontFamilies".into()),
431 ),
432 (
433 "ui_font_family".to_owned(),
434 Schema::new_ref("#/definitions/FontFamilies".into()),
435 ),
436 ]);
437
438 root_schema
439 }
440}
441
442fn merge<T: Copy>(target: &mut T, value: Option<T>) {
443 if let Some(value) = value {
444 *target = value;
445 }
446}