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