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