1use anyhow::{anyhow, Context, Result};
2use collections::{btree_map, hash_map, BTreeMap, HashMap};
3use gpui::{AppContext, AsyncAppContext, BorrowAppContext, Global};
4use lazy_static::lazy_static;
5use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
6use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
7use smallvec::SmallVec;
8use std::{
9 any::{type_name, Any, TypeId},
10 fmt::Debug,
11 ops::Range,
12 path::Path,
13 str,
14 sync::Arc,
15};
16use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
17
18/// A value that can be defined as a user setting.
19///
20/// Settings can be loaded from a combination of multiple JSON files.
21pub trait Settings: 'static + Send + Sync {
22 /// The name of a key within the JSON file from which this setting should
23 /// be deserialized. If this is `None`, then the setting will be deserialized
24 /// from the root object.
25 const KEY: Option<&'static str>;
26
27 /// The type that is stored in an individual JSON file.
28 type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
29
30 /// The logic for combining together values from one or more JSON files into the
31 /// final value for this setting.
32 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self>
33 where
34 Self: Sized;
35
36 fn json_schema(
37 generator: &mut SchemaGenerator,
38 _: &SettingsJsonSchemaParams,
39 _: &AppContext,
40 ) -> RootSchema {
41 generator.root_schema_for::<Self::FileContent>()
42 }
43
44 fn missing_default() -> anyhow::Error {
45 anyhow::anyhow!("missing default")
46 }
47
48 fn register(cx: &mut AppContext)
49 where
50 Self: Sized,
51 {
52 cx.update_global(|store: &mut SettingsStore, cx| {
53 store.register_setting::<Self>(cx);
54 });
55 }
56
57 #[track_caller]
58 fn get<'a>(path: Option<SettingsLocation>, cx: &'a AppContext) -> &'a Self
59 where
60 Self: Sized,
61 {
62 cx.global::<SettingsStore>().get(path)
63 }
64
65 #[track_caller]
66 fn get_global(cx: &AppContext) -> &Self
67 where
68 Self: Sized,
69 {
70 cx.global::<SettingsStore>().get(None)
71 }
72
73 #[track_caller]
74 fn try_read_global<R>(cx: &AsyncAppContext, f: impl FnOnce(&Self) -> R) -> Option<R>
75 where
76 Self: Sized,
77 {
78 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
79 }
80
81 #[track_caller]
82 fn override_global(settings: Self, cx: &mut AppContext)
83 where
84 Self: Sized,
85 {
86 cx.global_mut::<SettingsStore>().override_global(settings)
87 }
88}
89
90#[derive(Clone, Copy, Debug)]
91pub struct SettingsSources<'a, T> {
92 /// The default Zed settings.
93 pub default: &'a T,
94 /// Settings provided by extensions.
95 pub extensions: Option<&'a T>,
96 /// The user settings.
97 pub user: Option<&'a T>,
98 /// The user settings for the current release channel.
99 pub release_channel: Option<&'a T>,
100 /// The project settings, ordered from least specific to most specific.
101 pub project: &'a [&'a T],
102}
103
104impl<'a, T: Serialize> SettingsSources<'a, T> {
105 /// Returns an iterator over the default settings as well as all settings customizations.
106 pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
107 [self.default].into_iter().chain(self.customizations())
108 }
109
110 /// Returns an iterator over all of the settings customizations.
111 pub fn customizations(&self) -> impl Iterator<Item = &T> {
112 self.extensions
113 .into_iter()
114 .chain(self.user)
115 .chain(self.release_channel)
116 .chain(self.project.iter().copied())
117 }
118
119 /// Returns the settings after performing a JSON merge of the provided customizations.
120 ///
121 /// Customizations later in the iterator win out over the earlier ones.
122 pub fn json_merge_with<O: DeserializeOwned>(
123 customizations: impl Iterator<Item = &'a T>,
124 ) -> Result<O> {
125 let mut merged = serde_json::Value::Null;
126 for value in customizations {
127 merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
128 }
129 Ok(serde_json::from_value(merged)?)
130 }
131
132 /// Returns the settings after performing a JSON merge of the customizations into the
133 /// default settings.
134 ///
135 /// More-specific customizations win out over the less-specific ones.
136 pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
137 Self::json_merge_with(self.defaults_and_customizations())
138 }
139}
140
141#[derive(Clone, Copy)]
142pub struct SettingsLocation<'a> {
143 pub worktree_id: usize,
144 pub path: &'a Path,
145}
146
147pub struct SettingsJsonSchemaParams<'a> {
148 pub staff_mode: bool,
149 pub language_names: &'a [String],
150 pub font_names: &'a [String],
151}
152
153/// A set of strongly-typed setting values defined via multiple JSON files.
154pub struct SettingsStore {
155 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
156 raw_default_settings: serde_json::Value,
157 raw_user_settings: serde_json::Value,
158 raw_extension_settings: serde_json::Value,
159 raw_local_settings: BTreeMap<(usize, Arc<Path>), serde_json::Value>,
160 tab_size_callback: Option<(
161 TypeId,
162 Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
163 )>,
164}
165
166impl Global for SettingsStore {}
167
168impl Default for SettingsStore {
169 fn default() -> Self {
170 SettingsStore {
171 setting_values: Default::default(),
172 raw_default_settings: serde_json::json!({}),
173 raw_user_settings: serde_json::json!({}),
174 raw_extension_settings: serde_json::json!({}),
175 raw_local_settings: Default::default(),
176 tab_size_callback: Default::default(),
177 }
178 }
179}
180
181#[derive(Debug)]
182struct SettingValue<T> {
183 global_value: Option<T>,
184 local_values: Vec<(usize, Arc<Path>, T)>,
185}
186
187trait AnySettingValue: 'static + Send + Sync {
188 fn key(&self) -> Option<&'static str>;
189 fn setting_type_name(&self) -> &'static str;
190 fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
191 fn load_setting(
192 &self,
193 sources: SettingsSources<DeserializedSetting>,
194 cx: &mut AppContext,
195 ) -> Result<Box<dyn Any>>;
196 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
197 fn set_global_value(&mut self, value: Box<dyn Any>);
198 fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>);
199 fn json_schema(
200 &self,
201 generator: &mut SchemaGenerator,
202 _: &SettingsJsonSchemaParams,
203 cx: &AppContext,
204 ) -> RootSchema;
205}
206
207struct DeserializedSetting(Box<dyn Any>);
208
209impl SettingsStore {
210 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
211 where
212 C: BorrowAppContext,
213 {
214 cx.update_global(f)
215 }
216
217 /// Add a new type of setting to the store.
218 pub fn register_setting<T: Settings>(&mut self, cx: &mut AppContext) {
219 let setting_type_id = TypeId::of::<T>();
220 let entry = self.setting_values.entry(setting_type_id);
221 if matches!(entry, hash_map::Entry::Occupied(_)) {
222 return;
223 }
224
225 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
226 global_value: None,
227 local_values: Vec::new(),
228 }));
229
230 if let Some(default_settings) = setting_value
231 .deserialize_setting(&self.raw_default_settings)
232 .log_err()
233 {
234 let user_value = setting_value
235 .deserialize_setting(&self.raw_user_settings)
236 .log_err();
237
238 let mut release_channel_value = None;
239 if let Some(release_settings) = &self
240 .raw_user_settings
241 .get(release_channel::RELEASE_CHANNEL.dev_name())
242 {
243 release_channel_value = setting_value
244 .deserialize_setting(release_settings)
245 .log_err();
246 }
247
248 let extension_value = setting_value
249 .deserialize_setting(&self.raw_extension_settings)
250 .log_err();
251
252 if let Some(setting) = setting_value
253 .load_setting(
254 SettingsSources {
255 default: &default_settings,
256 release_channel: release_channel_value.as_ref(),
257 extensions: extension_value.as_ref(),
258 user: user_value.as_ref(),
259 project: &[],
260 },
261 cx,
262 )
263 .context("A default setting must be added to the `default.json` file")
264 .log_err()
265 {
266 setting_value.set_global_value(setting);
267 }
268 }
269 }
270
271 /// Get the value of a setting.
272 ///
273 /// Panics if the given setting type has not been registered, or if there is no
274 /// value for this setting.
275 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
276 self.setting_values
277 .get(&TypeId::of::<T>())
278 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
279 .value_for_path(path)
280 .downcast_ref::<T>()
281 .expect("no default value for setting type")
282 }
283
284 /// Override the global value for a setting.
285 ///
286 /// The given value will be overwritten if the user settings file changes.
287 pub fn override_global<T: Settings>(&mut self, value: T) {
288 self.setting_values
289 .get_mut(&TypeId::of::<T>())
290 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
291 .set_global_value(Box::new(value))
292 }
293
294 /// Get the user's settings as a raw JSON value.
295 ///
296 /// This is only for debugging and reporting. For user-facing functionality,
297 /// use the typed setting interface.
298 pub fn raw_user_settings(&self) -> &serde_json::Value {
299 &self.raw_user_settings
300 }
301
302 #[cfg(any(test, feature = "test-support"))]
303 pub fn test(cx: &mut AppContext) -> Self {
304 let mut this = Self::default();
305 this.set_default_settings(&crate::test_settings(), cx)
306 .unwrap();
307 this.set_user_settings("{}", cx).unwrap();
308 this
309 }
310
311 /// Updates the value of a setting in the user's global configuration.
312 ///
313 /// This is only for tests. Normally, settings are only loaded from
314 /// JSON files.
315 #[cfg(any(test, feature = "test-support"))]
316 pub fn update_user_settings<T: Settings>(
317 &mut self,
318 cx: &mut AppContext,
319 update: impl FnOnce(&mut T::FileContent),
320 ) {
321 let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
322 let new_text = self.new_text_for_update::<T>(old_text, update);
323 self.set_user_settings(&new_text, cx).unwrap();
324 }
325
326 /// Updates the value of a setting in a JSON file, returning the new text
327 /// for that JSON file.
328 pub fn new_text_for_update<T: Settings>(
329 &self,
330 old_text: String,
331 update: impl FnOnce(&mut T::FileContent),
332 ) -> String {
333 let edits = self.edits_for_update::<T>(&old_text, update);
334 let mut new_text = old_text;
335 for (range, replacement) in edits.into_iter() {
336 new_text.replace_range(range, &replacement);
337 }
338 new_text
339 }
340
341 /// Updates the value of a setting in a JSON file, returning a list
342 /// of edits to apply to the JSON file.
343 pub fn edits_for_update<T: Settings>(
344 &self,
345 text: &str,
346 update: impl FnOnce(&mut T::FileContent),
347 ) -> Vec<(Range<usize>, String)> {
348 let setting_type_id = TypeId::of::<T>();
349
350 let setting = self
351 .setting_values
352 .get(&setting_type_id)
353 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
354 let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
355 let old_content = match setting.deserialize_setting(&raw_settings) {
356 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
357 Err(_) => Box::<<T as Settings>::FileContent>::default(),
358 };
359 let mut new_content = old_content.clone();
360 update(&mut new_content);
361
362 let old_value = serde_json::to_value(&old_content).unwrap();
363 let new_value = serde_json::to_value(new_content).unwrap();
364
365 let mut key_path = Vec::new();
366 if let Some(key) = T::KEY {
367 key_path.push(key);
368 }
369
370 let mut edits = Vec::new();
371 let tab_size = self.json_tab_size();
372 let mut text = text.to_string();
373 update_value_in_json_text(
374 &mut text,
375 &mut key_path,
376 tab_size,
377 &old_value,
378 &new_value,
379 &mut edits,
380 );
381 edits
382 }
383
384 /// Configure the tab sized when updating JSON files.
385 pub fn set_json_tab_size_callback<T: Settings>(
386 &mut self,
387 get_tab_size: fn(&T) -> Option<usize>,
388 ) {
389 self.tab_size_callback = Some((
390 TypeId::of::<T>(),
391 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
392 ));
393 }
394
395 fn json_tab_size(&self) -> usize {
396 const DEFAULT_JSON_TAB_SIZE: usize = 2;
397
398 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
399 let setting_value = self.setting_values.get(setting_type_id).unwrap();
400 let value = setting_value.value_for_path(None);
401 if let Some(value) = callback(value) {
402 return value;
403 }
404 }
405
406 DEFAULT_JSON_TAB_SIZE
407 }
408
409 /// Sets the default settings via a JSON string.
410 ///
411 /// The string should contain a JSON object with a default value for every setting.
412 pub fn set_default_settings(
413 &mut self,
414 default_settings_content: &str,
415 cx: &mut AppContext,
416 ) -> Result<()> {
417 let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
418 if settings.is_object() {
419 self.raw_default_settings = settings;
420 self.recompute_values(None, cx)?;
421 Ok(())
422 } else {
423 Err(anyhow!("settings must be an object"))
424 }
425 }
426
427 /// Sets the user settings via a JSON string.
428 pub fn set_user_settings(
429 &mut self,
430 user_settings_content: &str,
431 cx: &mut AppContext,
432 ) -> Result<()> {
433 let settings: serde_json::Value = parse_json_with_comments(user_settings_content)?;
434 if settings.is_object() {
435 self.raw_user_settings = settings;
436 self.recompute_values(None, cx)?;
437 Ok(())
438 } else {
439 Err(anyhow!("settings must be an object"))
440 }
441 }
442
443 /// Add or remove a set of local settings via a JSON string.
444 pub fn set_local_settings(
445 &mut self,
446 root_id: usize,
447 path: Arc<Path>,
448 settings_content: Option<&str>,
449 cx: &mut AppContext,
450 ) -> Result<()> {
451 if let Some(content) = settings_content {
452 self.raw_local_settings
453 .insert((root_id, path.clone()), parse_json_with_comments(content)?);
454 } else {
455 self.raw_local_settings.remove(&(root_id, path.clone()));
456 }
457 self.recompute_values(Some((root_id, &path)), cx)?;
458 Ok(())
459 }
460
461 pub fn set_extension_settings<T: Serialize>(
462 &mut self,
463 content: T,
464 cx: &mut AppContext,
465 ) -> Result<()> {
466 let settings: serde_json::Value = serde_json::to_value(content)?;
467 if settings.is_object() {
468 self.raw_extension_settings = settings;
469 self.recompute_values(None, cx)?;
470 Ok(())
471 } else {
472 Err(anyhow!("settings must be an object"))
473 }
474 }
475
476 /// Add or remove a set of local settings via a JSON string.
477 pub fn clear_local_settings(&mut self, root_id: usize, cx: &mut AppContext) -> Result<()> {
478 self.raw_local_settings.retain(|k, _| k.0 != root_id);
479 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
480 Ok(())
481 }
482
483 pub fn local_settings(&self, root_id: usize) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
484 self.raw_local_settings
485 .range((root_id, Path::new("").into())..(root_id + 1, Path::new("").into()))
486 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
487 }
488
489 pub fn json_schema(
490 &self,
491 schema_params: &SettingsJsonSchemaParams,
492 cx: &AppContext,
493 ) -> serde_json::Value {
494 use schemars::{
495 gen::SchemaSettings,
496 schema::{Schema, SchemaObject},
497 };
498
499 let settings = SchemaSettings::draft07().with(|settings| {
500 settings.option_add_null_type = false;
501 });
502 let mut generator = SchemaGenerator::new(settings);
503 let mut combined_schema = RootSchema::default();
504
505 for setting_value in self.setting_values.values() {
506 let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
507 combined_schema
508 .definitions
509 .extend(setting_schema.definitions);
510
511 let target_schema = if let Some(key) = setting_value.key() {
512 let key_schema = combined_schema
513 .schema
514 .object()
515 .properties
516 .entry(key.to_string())
517 .or_insert_with(|| Schema::Object(SchemaObject::default()));
518 if let Schema::Object(key_schema) = key_schema {
519 key_schema
520 } else {
521 continue;
522 }
523 } else {
524 &mut combined_schema.schema
525 };
526
527 merge_schema(target_schema, setting_schema.schema);
528 }
529
530 fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
531 let source_subschemas = source.subschemas();
532 let target_subschemas = target.subschemas();
533 if let Some(all_of) = source_subschemas.all_of.take() {
534 target_subschemas
535 .all_of
536 .get_or_insert(Vec::new())
537 .extend(all_of);
538 }
539 if let Some(any_of) = source_subschemas.any_of.take() {
540 target_subschemas
541 .any_of
542 .get_or_insert(Vec::new())
543 .extend(any_of);
544 }
545 if let Some(one_of) = source_subschemas.one_of.take() {
546 target_subschemas
547 .one_of
548 .get_or_insert(Vec::new())
549 .extend(one_of);
550 }
551
552 if let Some(source) = source.object {
553 let target_properties = &mut target.object().properties;
554 for (key, value) in source.properties {
555 match target_properties.entry(key) {
556 btree_map::Entry::Vacant(e) => {
557 e.insert(value);
558 }
559 btree_map::Entry::Occupied(e) => {
560 if let (Schema::Object(target), Schema::Object(src)) =
561 (e.into_mut(), value)
562 {
563 merge_schema(target, src);
564 }
565 }
566 }
567 }
568 }
569
570 overwrite(&mut target.instance_type, source.instance_type);
571 overwrite(&mut target.string, source.string);
572 overwrite(&mut target.number, source.number);
573 overwrite(&mut target.reference, source.reference);
574 overwrite(&mut target.array, source.array);
575 overwrite(&mut target.enum_values, source.enum_values);
576
577 fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
578 if let Some(source) = source {
579 *target = Some(source);
580 }
581 }
582 }
583
584 for release_stage in ["dev", "nightly", "stable", "preview"] {
585 let schema = combined_schema.schema.clone();
586 combined_schema
587 .schema
588 .object()
589 .properties
590 .insert(release_stage.to_string(), schema.into());
591 }
592
593 serde_json::to_value(&combined_schema).unwrap()
594 }
595
596 fn recompute_values(
597 &mut self,
598 changed_local_path: Option<(usize, &Path)>,
599 cx: &mut AppContext,
600 ) -> Result<()> {
601 // Reload the global and local values for every setting.
602 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
603 let mut paths_stack = Vec::<Option<(usize, &Path)>>::new();
604 for setting_value in self.setting_values.values_mut() {
605 let default_settings = setting_value.deserialize_setting(&self.raw_default_settings)?;
606
607 let extension_settings = setting_value
608 .deserialize_setting(&self.raw_extension_settings)
609 .log_err();
610
611 let user_settings = setting_value
612 .deserialize_setting(&self.raw_user_settings)
613 .log_err();
614
615 let mut release_channel_settings = None;
616 if let Some(release_settings) = &self
617 .raw_user_settings
618 .get(release_channel::RELEASE_CHANNEL.dev_name())
619 {
620 if let Some(release_settings) = setting_value
621 .deserialize_setting(release_settings)
622 .log_err()
623 {
624 release_channel_settings = Some(release_settings);
625 }
626 }
627
628 // If the global settings file changed, reload the global value for the field.
629 project_settings_stack.clear();
630 paths_stack.clear();
631 if changed_local_path.is_none() {
632 if let Some(value) = setting_value
633 .load_setting(
634 SettingsSources {
635 default: &default_settings,
636 extensions: extension_settings.as_ref(),
637 user: user_settings.as_ref(),
638 release_channel: release_channel_settings.as_ref(),
639 project: &[],
640 },
641 cx,
642 )
643 .log_err()
644 {
645 setting_value.set_global_value(value);
646 }
647 }
648
649 // Reload the local values for the setting.
650 for ((root_id, path), local_settings) in &self.raw_local_settings {
651 // Build a stack of all of the local values for that setting.
652 while let Some(prev_entry) = paths_stack.last() {
653 if let Some((prev_root_id, prev_path)) = prev_entry {
654 if root_id != prev_root_id || !path.starts_with(prev_path) {
655 paths_stack.pop();
656 project_settings_stack.pop();
657 continue;
658 }
659 }
660 break;
661 }
662
663 if let Some(local_settings) =
664 setting_value.deserialize_setting(local_settings).log_err()
665 {
666 paths_stack.push(Some((*root_id, path.as_ref())));
667 project_settings_stack.push(local_settings);
668
669 // If a local settings file changed, then avoid recomputing local
670 // settings for any path outside of that directory.
671 if changed_local_path.map_or(false, |(changed_root_id, changed_local_path)| {
672 *root_id != changed_root_id || !path.starts_with(changed_local_path)
673 }) {
674 continue;
675 }
676
677 if let Some(value) = setting_value
678 .load_setting(
679 SettingsSources {
680 default: &default_settings,
681 extensions: extension_settings.as_ref(),
682 user: user_settings.as_ref(),
683 release_channel: release_channel_settings.as_ref(),
684 project: &project_settings_stack.iter().collect::<Vec<_>>(),
685 },
686 cx,
687 )
688 .log_err()
689 {
690 setting_value.set_local_value(*root_id, path.clone(), value);
691 }
692 }
693 }
694 }
695 Ok(())
696 }
697}
698
699impl Debug for SettingsStore {
700 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
701 f.debug_struct("SettingsStore")
702 .field(
703 "types",
704 &self
705 .setting_values
706 .values()
707 .map(|value| value.setting_type_name())
708 .collect::<Vec<_>>(),
709 )
710 .field("default_settings", &self.raw_default_settings)
711 .field("user_settings", &self.raw_user_settings)
712 .field("local_settings", &self.raw_local_settings)
713 .finish_non_exhaustive()
714 }
715}
716
717impl<T: Settings> AnySettingValue for SettingValue<T> {
718 fn key(&self) -> Option<&'static str> {
719 T::KEY
720 }
721
722 fn setting_type_name(&self) -> &'static str {
723 type_name::<T>()
724 }
725
726 fn load_setting(
727 &self,
728 values: SettingsSources<DeserializedSetting>,
729 cx: &mut AppContext,
730 ) -> Result<Box<dyn Any>> {
731 Ok(Box::new(T::load(
732 SettingsSources {
733 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
734 extensions: values
735 .extensions
736 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
737 user: values
738 .user
739 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
740 release_channel: values
741 .release_channel
742 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
743 project: values
744 .project
745 .iter()
746 .map(|value| value.0.downcast_ref().unwrap())
747 .collect::<SmallVec<[_; 3]>>()
748 .as_slice(),
749 },
750 cx,
751 )?))
752 }
753
754 fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
755 if let Some(key) = T::KEY {
756 if let Some(value) = json.get(key) {
757 json = value;
758 } else {
759 let value = T::FileContent::default();
760 return Ok(DeserializedSetting(Box::new(value)));
761 }
762 }
763 let value = T::FileContent::deserialize(json)?;
764 Ok(DeserializedSetting(Box::new(value)))
765 }
766
767 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
768 if let Some(SettingsLocation { worktree_id, path }) = path {
769 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
770 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
771 return value;
772 }
773 }
774 }
775 self.global_value
776 .as_ref()
777 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
778 }
779
780 fn set_global_value(&mut self, value: Box<dyn Any>) {
781 self.global_value = Some(*value.downcast().unwrap());
782 }
783
784 fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>) {
785 let value = *value.downcast().unwrap();
786 match self
787 .local_values
788 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
789 {
790 Ok(ix) => self.local_values[ix].2 = value,
791 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
792 }
793 }
794
795 fn json_schema(
796 &self,
797 generator: &mut SchemaGenerator,
798 params: &SettingsJsonSchemaParams,
799 cx: &AppContext,
800 ) -> RootSchema {
801 T::json_schema(generator, params, cx)
802 }
803}
804
805fn update_value_in_json_text<'a>(
806 text: &mut String,
807 key_path: &mut Vec<&'a str>,
808 tab_size: usize,
809 old_value: &'a serde_json::Value,
810 new_value: &'a serde_json::Value,
811 edits: &mut Vec<(Range<usize>, String)>,
812) {
813 // If the old and new values are both objects, then compare them key by key,
814 // preserving the comments and formatting of the unchanged parts. Otherwise,
815 // replace the old value with the new value.
816 if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
817 (old_value, new_value)
818 {
819 for (key, old_sub_value) in old_object.iter() {
820 key_path.push(key);
821 let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
822 update_value_in_json_text(
823 text,
824 key_path,
825 tab_size,
826 old_sub_value,
827 new_sub_value,
828 edits,
829 );
830 key_path.pop();
831 }
832 for (key, new_sub_value) in new_object.iter() {
833 key_path.push(key);
834 if !old_object.contains_key(key) {
835 update_value_in_json_text(
836 text,
837 key_path,
838 tab_size,
839 &serde_json::Value::Null,
840 new_sub_value,
841 edits,
842 );
843 }
844 key_path.pop();
845 }
846 } else if old_value != new_value {
847 let mut new_value = new_value.clone();
848 if let Some(new_object) = new_value.as_object_mut() {
849 new_object.retain(|_, v| !v.is_null());
850 }
851 let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
852 text.replace_range(range.clone(), &replacement);
853 edits.push((range, replacement));
854 }
855}
856
857fn replace_value_in_json_text(
858 text: &str,
859 key_path: &[&str],
860 tab_size: usize,
861 new_value: &serde_json::Value,
862) -> (Range<usize>, String) {
863 const LANGUAGE_OVERRIDES: &str = "language_overrides";
864 const LANGUAGES: &str = "languages";
865
866 lazy_static! {
867 static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
868 &tree_sitter_json::language(),
869 "(pair key: (string) @key value: (_) @value)",
870 )
871 .unwrap();
872 }
873
874 let mut parser = tree_sitter::Parser::new();
875 parser.set_language(&tree_sitter_json::language()).unwrap();
876 let syntax_tree = parser.parse(text, None).unwrap();
877
878 let mut cursor = tree_sitter::QueryCursor::new();
879
880 let has_language_overrides = text.contains(LANGUAGE_OVERRIDES);
881
882 let mut depth = 0;
883 let mut last_value_range = 0..0;
884 let mut first_key_start = None;
885 let mut existing_value_range = 0..text.len();
886 let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
887 for mat in matches {
888 if mat.captures.len() != 2 {
889 continue;
890 }
891
892 let key_range = mat.captures[0].node.byte_range();
893 let value_range = mat.captures[1].node.byte_range();
894
895 // Don't enter sub objects until we find an exact
896 // match for the current keypath
897 if last_value_range.contains_inclusive(&value_range) {
898 continue;
899 }
900
901 last_value_range = value_range.clone();
902
903 if key_range.start > existing_value_range.end {
904 break;
905 }
906
907 first_key_start.get_or_insert(key_range.start);
908
909 let found_key = text
910 .get(key_range.clone())
911 .map(|key_text| {
912 if key_path[depth] == LANGUAGES && has_language_overrides {
913 key_text == format!("\"{}\"", LANGUAGE_OVERRIDES)
914 } else {
915 key_text == format!("\"{}\"", key_path[depth])
916 }
917 })
918 .unwrap_or(false);
919
920 if found_key {
921 existing_value_range = value_range;
922 // Reset last value range when increasing in depth
923 last_value_range = existing_value_range.start..existing_value_range.start;
924 depth += 1;
925
926 if depth == key_path.len() {
927 break;
928 }
929
930 first_key_start = None;
931 }
932 }
933
934 // We found the exact key we want, insert the new value
935 if depth == key_path.len() {
936 let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
937 (existing_value_range, new_val)
938 } else {
939 // We have key paths, construct the sub objects
940 let new_key = if has_language_overrides && key_path[depth] == LANGUAGES {
941 LANGUAGE_OVERRIDES
942 } else {
943 key_path[depth]
944 };
945
946 // We don't have the key, construct the nested objects
947 let mut new_value = serde_json::to_value(new_value).unwrap();
948 for key in key_path[(depth + 1)..].iter().rev() {
949 if has_language_overrides && key == &LANGUAGES {
950 new_value = serde_json::json!({ LANGUAGE_OVERRIDES.to_string(): new_value });
951 } else {
952 new_value = serde_json::json!({ key.to_string(): new_value });
953 }
954 }
955
956 if let Some(first_key_start) = first_key_start {
957 let mut row = 0;
958 let mut column = 0;
959 for (ix, char) in text.char_indices() {
960 if ix == first_key_start {
961 break;
962 }
963 if char == '\n' {
964 row += 1;
965 column = 0;
966 } else {
967 column += char.len_utf8();
968 }
969 }
970
971 if row > 0 {
972 // depth is 0 based, but division needs to be 1 based.
973 let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
974 let space = ' ';
975 let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
976 (first_key_start..first_key_start, content)
977 } else {
978 let new_val = serde_json::to_string(&new_value).unwrap();
979 let mut content = format!(r#""{new_key}": {new_val},"#);
980 content.push(' ');
981 (first_key_start..first_key_start, content)
982 }
983 } else {
984 new_value = serde_json::json!({ new_key.to_string(): new_value });
985 let indent_prefix_len = 4 * depth;
986 let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
987 if depth == 0 {
988 new_val.push('\n');
989 }
990
991 (existing_value_range, new_val)
992 }
993 }
994}
995
996fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
997 const SPACES: [u8; 32] = [b' '; 32];
998
999 debug_assert!(indent_size <= SPACES.len());
1000 debug_assert!(indent_prefix_len <= SPACES.len());
1001
1002 let mut output = Vec::new();
1003 let mut ser = serde_json::Serializer::with_formatter(
1004 &mut output,
1005 serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1006 );
1007
1008 value.serialize(&mut ser).unwrap();
1009 let text = String::from_utf8(output).unwrap();
1010
1011 let mut adjusted_text = String::new();
1012 for (i, line) in text.split('\n').enumerate() {
1013 if i > 0 {
1014 adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1015 }
1016 adjusted_text.push_str(line);
1017 adjusted_text.push('\n');
1018 }
1019 adjusted_text.pop();
1020 adjusted_text
1021}
1022
1023pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1024 Ok(serde_json_lenient::from_str(content)?)
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029 use super::*;
1030 use serde_derive::Deserialize;
1031 use unindent::Unindent;
1032
1033 #[gpui::test]
1034 fn test_settings_store_basic(cx: &mut AppContext) {
1035 let mut store = SettingsStore::default();
1036 store.register_setting::<UserSettings>(cx);
1037 store.register_setting::<TurboSetting>(cx);
1038 store.register_setting::<MultiKeySettings>(cx);
1039 store
1040 .set_default_settings(
1041 r#"{
1042 "turbo": false,
1043 "user": {
1044 "name": "John Doe",
1045 "age": 30,
1046 "staff": false
1047 }
1048 }"#,
1049 cx,
1050 )
1051 .unwrap();
1052
1053 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1054 assert_eq!(
1055 store.get::<UserSettings>(None),
1056 &UserSettings {
1057 name: "John Doe".to_string(),
1058 age: 30,
1059 staff: false,
1060 }
1061 );
1062 assert_eq!(
1063 store.get::<MultiKeySettings>(None),
1064 &MultiKeySettings {
1065 key1: String::new(),
1066 key2: String::new(),
1067 }
1068 );
1069
1070 store
1071 .set_user_settings(
1072 r#"{
1073 "turbo": true,
1074 "user": { "age": 31 },
1075 "key1": "a"
1076 }"#,
1077 cx,
1078 )
1079 .unwrap();
1080
1081 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1082 assert_eq!(
1083 store.get::<UserSettings>(None),
1084 &UserSettings {
1085 name: "John Doe".to_string(),
1086 age: 31,
1087 staff: false
1088 }
1089 );
1090
1091 store
1092 .set_local_settings(
1093 1,
1094 Path::new("/root1").into(),
1095 Some(r#"{ "user": { "staff": true } }"#),
1096 cx,
1097 )
1098 .unwrap();
1099 store
1100 .set_local_settings(
1101 1,
1102 Path::new("/root1/subdir").into(),
1103 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1104 cx,
1105 )
1106 .unwrap();
1107
1108 store
1109 .set_local_settings(
1110 1,
1111 Path::new("/root2").into(),
1112 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1113 cx,
1114 )
1115 .unwrap();
1116
1117 assert_eq!(
1118 store.get::<UserSettings>(Some(SettingsLocation {
1119 worktree_id: 1,
1120 path: Path::new("/root1/something"),
1121 })),
1122 &UserSettings {
1123 name: "John Doe".to_string(),
1124 age: 31,
1125 staff: true
1126 }
1127 );
1128 assert_eq!(
1129 store.get::<UserSettings>(Some(SettingsLocation {
1130 worktree_id: 1,
1131 path: Path::new("/root1/subdir/something")
1132 })),
1133 &UserSettings {
1134 name: "Jane Doe".to_string(),
1135 age: 31,
1136 staff: true
1137 }
1138 );
1139 assert_eq!(
1140 store.get::<UserSettings>(Some(SettingsLocation {
1141 worktree_id: 1,
1142 path: Path::new("/root2/something")
1143 })),
1144 &UserSettings {
1145 name: "John Doe".to_string(),
1146 age: 42,
1147 staff: false
1148 }
1149 );
1150 assert_eq!(
1151 store.get::<MultiKeySettings>(Some(SettingsLocation {
1152 worktree_id: 1,
1153 path: Path::new("/root2/something")
1154 })),
1155 &MultiKeySettings {
1156 key1: "a".to_string(),
1157 key2: "b".to_string(),
1158 }
1159 );
1160 }
1161
1162 #[gpui::test]
1163 fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1164 let mut store = SettingsStore::default();
1165 store
1166 .set_default_settings(
1167 r#"{
1168 "turbo": true,
1169 "user": {
1170 "name": "John Doe",
1171 "age": 30,
1172 "staff": false
1173 },
1174 "key1": "x"
1175 }"#,
1176 cx,
1177 )
1178 .unwrap();
1179 store
1180 .set_user_settings(r#"{ "turbo": false }"#, cx)
1181 .unwrap();
1182 store.register_setting::<UserSettings>(cx);
1183 store.register_setting::<TurboSetting>(cx);
1184
1185 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1186 assert_eq!(
1187 store.get::<UserSettings>(None),
1188 &UserSettings {
1189 name: "John Doe".to_string(),
1190 age: 30,
1191 staff: false,
1192 }
1193 );
1194
1195 store.register_setting::<MultiKeySettings>(cx);
1196 assert_eq!(
1197 store.get::<MultiKeySettings>(None),
1198 &MultiKeySettings {
1199 key1: "x".into(),
1200 key2: String::new(),
1201 }
1202 );
1203 }
1204
1205 #[gpui::test]
1206 fn test_setting_store_update(cx: &mut AppContext) {
1207 let mut store = SettingsStore::default();
1208 store.register_setting::<MultiKeySettings>(cx);
1209 store.register_setting::<UserSettings>(cx);
1210 store.register_setting::<LanguageSettings>(cx);
1211
1212 // entries added and updated
1213 check_settings_update::<LanguageSettings>(
1214 &mut store,
1215 r#"{
1216 "languages": {
1217 "JSON": {
1218 "language_setting_1": true
1219 }
1220 }
1221 }"#
1222 .unindent(),
1223 |settings| {
1224 settings
1225 .languages
1226 .get_mut("JSON")
1227 .unwrap()
1228 .language_setting_1 = Some(false);
1229 settings.languages.insert(
1230 "Rust".into(),
1231 LanguageSettingEntry {
1232 language_setting_2: Some(true),
1233 ..Default::default()
1234 },
1235 );
1236 },
1237 r#"{
1238 "languages": {
1239 "Rust": {
1240 "language_setting_2": true
1241 },
1242 "JSON": {
1243 "language_setting_1": false
1244 }
1245 }
1246 }"#
1247 .unindent(),
1248 cx,
1249 );
1250
1251 // weird formatting
1252 check_settings_update::<UserSettings>(
1253 &mut store,
1254 r#"{
1255 "user": { "age": 36, "name": "Max", "staff": true }
1256 }"#
1257 .unindent(),
1258 |settings| settings.age = Some(37),
1259 r#"{
1260 "user": { "age": 37, "name": "Max", "staff": true }
1261 }"#
1262 .unindent(),
1263 cx,
1264 );
1265
1266 // single-line formatting, other keys
1267 check_settings_update::<MultiKeySettings>(
1268 &mut store,
1269 r#"{ "one": 1, "two": 2 }"#.unindent(),
1270 |settings| settings.key1 = Some("x".into()),
1271 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1272 cx,
1273 );
1274
1275 // empty object
1276 check_settings_update::<UserSettings>(
1277 &mut store,
1278 r#"{
1279 "user": {}
1280 }"#
1281 .unindent(),
1282 |settings| settings.age = Some(37),
1283 r#"{
1284 "user": {
1285 "age": 37
1286 }
1287 }"#
1288 .unindent(),
1289 cx,
1290 );
1291
1292 // no content
1293 check_settings_update::<UserSettings>(
1294 &mut store,
1295 r#""#.unindent(),
1296 |settings| settings.age = Some(37),
1297 r#"{
1298 "user": {
1299 "age": 37
1300 }
1301 }
1302 "#
1303 .unindent(),
1304 cx,
1305 );
1306
1307 check_settings_update::<UserSettings>(
1308 &mut store,
1309 r#"{
1310 }
1311 "#
1312 .unindent(),
1313 |settings| settings.age = Some(37),
1314 r#"{
1315 "user": {
1316 "age": 37
1317 }
1318 }
1319 "#
1320 .unindent(),
1321 cx,
1322 );
1323 }
1324
1325 fn check_settings_update<T: Settings>(
1326 store: &mut SettingsStore,
1327 old_json: String,
1328 update: fn(&mut T::FileContent),
1329 expected_new_json: String,
1330 cx: &mut AppContext,
1331 ) {
1332 store.set_user_settings(&old_json, cx).ok();
1333 let edits = store.edits_for_update::<T>(&old_json, update);
1334 let mut new_json = old_json;
1335 for (range, replacement) in edits.into_iter() {
1336 new_json.replace_range(range, &replacement);
1337 }
1338 pretty_assertions::assert_eq!(new_json, expected_new_json);
1339 }
1340
1341 #[derive(Debug, PartialEq, Deserialize)]
1342 struct UserSettings {
1343 name: String,
1344 age: u32,
1345 staff: bool,
1346 }
1347
1348 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1349 struct UserSettingsJson {
1350 name: Option<String>,
1351 age: Option<u32>,
1352 staff: Option<bool>,
1353 }
1354
1355 impl Settings for UserSettings {
1356 const KEY: Option<&'static str> = Some("user");
1357 type FileContent = UserSettingsJson;
1358
1359 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1360 sources.json_merge()
1361 }
1362 }
1363
1364 #[derive(Debug, Deserialize, PartialEq)]
1365 struct TurboSetting(bool);
1366
1367 impl Settings for TurboSetting {
1368 const KEY: Option<&'static str> = Some("turbo");
1369 type FileContent = Option<bool>;
1370
1371 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1372 sources.json_merge()
1373 }
1374 }
1375
1376 #[derive(Clone, Debug, PartialEq, Deserialize)]
1377 struct MultiKeySettings {
1378 #[serde(default)]
1379 key1: String,
1380 #[serde(default)]
1381 key2: String,
1382 }
1383
1384 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1385 struct MultiKeySettingsJson {
1386 key1: Option<String>,
1387 key2: Option<String>,
1388 }
1389
1390 impl Settings for MultiKeySettings {
1391 const KEY: Option<&'static str> = None;
1392
1393 type FileContent = MultiKeySettingsJson;
1394
1395 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1396 sources.json_merge()
1397 }
1398 }
1399
1400 #[derive(Debug, Deserialize)]
1401 struct JournalSettings {
1402 pub path: String,
1403 pub hour_format: HourFormat,
1404 }
1405
1406 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1407 #[serde(rename_all = "snake_case")]
1408 enum HourFormat {
1409 Hour12,
1410 Hour24,
1411 }
1412
1413 #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1414 struct JournalSettingsJson {
1415 pub path: Option<String>,
1416 pub hour_format: Option<HourFormat>,
1417 }
1418
1419 impl Settings for JournalSettings {
1420 const KEY: Option<&'static str> = Some("journal");
1421
1422 type FileContent = JournalSettingsJson;
1423
1424 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1425 sources.json_merge()
1426 }
1427 }
1428
1429 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1430 struct LanguageSettings {
1431 #[serde(default)]
1432 languages: HashMap<String, LanguageSettingEntry>,
1433 }
1434
1435 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1436 struct LanguageSettingEntry {
1437 language_setting_1: Option<bool>,
1438 language_setting_2: Option<bool>,
1439 }
1440
1441 impl Settings for LanguageSettings {
1442 const KEY: Option<&'static str> = None;
1443
1444 type FileContent = Self;
1445
1446 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1447 sources.json_merge()
1448 }
1449 }
1450}