1use anyhow::{Context as _, Result};
2use collections::{BTreeMap, HashMap, btree_map, hash_map};
3use ec4rs::{ConfigParser, PropertiesSource, Section};
4use fs::Fs;
5use futures::{
6 FutureExt, StreamExt,
7 channel::{mpsc, oneshot},
8 future::LocalBoxFuture,
9};
10use gpui::{App, AsyncApp, BorrowAppContext, Global, SharedString, Task, UpdateGlobal};
11
12use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
13use schemars::JsonSchema;
14use serde::{Serialize, de::DeserializeOwned};
15use serde_json::{Value, json};
16use smallvec::SmallVec;
17use std::{
18 any::{Any, TypeId, type_name},
19 env,
20 fmt::Debug,
21 ops::Range,
22 path::{Path, PathBuf},
23 str::{self, FromStr},
24 sync::Arc,
25};
26use util::{
27 ResultExt as _, merge_non_null_json_value_into,
28 schemars::{DefaultDenyUnknownFields, add_new_subschema},
29};
30
31pub type EditorconfigProperties = ec4rs::Properties;
32
33use crate::{
34 ActiveSettingsProfileName, ParameterizedJsonSchema, SettingsJsonSchemaParams, SettingsUiEntry,
35 VsCodeSettings, WorktreeId, parse_json_with_comments, replace_value_in_json_text,
36 settings_ui_core::SettingsUi, update_value_in_json_text,
37};
38
39pub trait SettingsKey: 'static + Send + Sync {
40 /// The name of a key within the JSON file from which this setting should
41 /// be deserialized. If this is `None`, then the setting will be deserialized
42 /// from the root object.
43 const KEY: Option<&'static str>;
44
45 const FALLBACK_KEY: Option<&'static str> = None;
46}
47
48/// A value that can be defined as a user setting.
49///
50/// Settings can be loaded from a combination of multiple JSON files.
51pub trait Settings: 'static + Send + Sync {
52 /// The name of the keys in the [`FileContent`](Self::FileContent) that should
53 /// always be written to a settings file, even if their value matches the default
54 /// value.
55 ///
56 /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
57 /// is a "version" field that should always be persisted, even if the current
58 /// user settings match the current version of the settings.
59 const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
60
61 /// The type that is stored in an individual JSON file.
62 type FileContent: Clone
63 + Default
64 + Serialize
65 + DeserializeOwned
66 + JsonSchema
67 + SettingsUi
68 + SettingsKey;
69
70 /*
71 * let path = Settings
72 *
73 *
74 */
75 /// The logic for combining together values from one or more JSON files into the
76 /// final value for this setting.
77 ///
78 /// # Warning
79 /// `Self::FileContent` deserialized field names should match with `Self` deserialized field names
80 /// otherwise the field won't be deserialized properly and you will get the error:
81 /// "A default setting must be added to the `default.json` file"
82 fn load(sources: SettingsSources<Self::FileContent>, cx: &mut App) -> Result<Self>
83 where
84 Self: Sized;
85
86 fn missing_default() -> anyhow::Error {
87 anyhow::anyhow!("missing default for: {}", std::any::type_name::<Self>())
88 }
89
90 /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
91 /// equivalent settings from a vscode config to our config
92 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent);
93
94 #[track_caller]
95 fn register(cx: &mut App)
96 where
97 Self: Sized,
98 {
99 SettingsStore::update_global(cx, |store, cx| {
100 store.register_setting::<Self>(cx);
101 });
102 }
103
104 #[track_caller]
105 fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
106 where
107 Self: Sized,
108 {
109 cx.global::<SettingsStore>().get(path)
110 }
111
112 #[track_caller]
113 fn get_global(cx: &App) -> &Self
114 where
115 Self: Sized,
116 {
117 cx.global::<SettingsStore>().get(None)
118 }
119
120 #[track_caller]
121 fn try_get(cx: &App) -> Option<&Self>
122 where
123 Self: Sized,
124 {
125 if cx.has_global::<SettingsStore>() {
126 cx.global::<SettingsStore>().try_get(None)
127 } else {
128 None
129 }
130 }
131
132 #[track_caller]
133 fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
134 where
135 Self: Sized,
136 {
137 cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
138 }
139
140 #[track_caller]
141 fn override_global(settings: Self, cx: &mut App)
142 where
143 Self: Sized,
144 {
145 cx.global_mut::<SettingsStore>().override_global(settings)
146 }
147}
148
149#[derive(Clone, Copy, Debug)]
150pub struct SettingsSources<'a, T> {
151 /// The default Zed settings.
152 pub default: &'a T,
153 /// Global settings (loaded before user settings).
154 pub global: Option<&'a T>,
155 /// Settings provided by extensions.
156 pub extensions: Option<&'a T>,
157 /// The user settings.
158 pub user: Option<&'a T>,
159 /// The user settings for the current release channel.
160 pub release_channel: Option<&'a T>,
161 /// The user settings for the current operating system.
162 pub operating_system: Option<&'a T>,
163 /// The settings associated with an enabled settings profile
164 pub profile: Option<&'a T>,
165 /// The server's settings.
166 pub server: Option<&'a T>,
167 /// The project settings, ordered from least specific to most specific.
168 pub project: &'a [&'a T],
169}
170
171impl<'a, T: Serialize> SettingsSources<'a, T> {
172 /// Returns an iterator over the default settings as well as all settings customizations.
173 pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
174 [self.default].into_iter().chain(self.customizations())
175 }
176
177 /// Returns an iterator over all of the settings customizations.
178 pub fn customizations(&self) -> impl Iterator<Item = &T> {
179 self.global
180 .into_iter()
181 .chain(self.extensions)
182 .chain(self.user)
183 .chain(self.release_channel)
184 .chain(self.operating_system)
185 .chain(self.profile)
186 .chain(self.server)
187 .chain(self.project.iter().copied())
188 }
189
190 /// Returns the settings after performing a JSON merge of the provided customizations.
191 ///
192 /// Customizations later in the iterator win out over the earlier ones.
193 pub fn json_merge_with<O: DeserializeOwned>(
194 customizations: impl Iterator<Item = &'a T>,
195 ) -> Result<O> {
196 let mut merged = Value::Null;
197 for value in customizations {
198 merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
199 }
200 Ok(serde_json::from_value(merged)?)
201 }
202
203 /// Returns the settings after performing a JSON merge of the customizations into the
204 /// default settings.
205 ///
206 /// More-specific customizations win out over the less-specific ones.
207 pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
208 Self::json_merge_with(self.defaults_and_customizations())
209 }
210}
211
212#[derive(Clone, Copy, Debug)]
213pub struct SettingsLocation<'a> {
214 pub worktree_id: WorktreeId,
215 pub path: &'a Path,
216}
217
218/// A set of strongly-typed setting values defined via multiple config files.
219pub struct SettingsStore {
220 setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
221 raw_default_settings: Value,
222 raw_global_settings: Option<Value>,
223 raw_user_settings: Value,
224 raw_server_settings: Option<Value>,
225 raw_extension_settings: Value,
226 raw_local_settings: BTreeMap<(WorktreeId, Arc<Path>), Value>,
227 raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<Path>), (String, Option<Editorconfig>)>,
228 tab_size_callback: Option<(
229 TypeId,
230 Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
231 )>,
232 _setting_file_updates: Task<()>,
233 setting_file_updates_tx:
234 mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
235}
236
237#[derive(Clone)]
238pub struct Editorconfig {
239 pub is_root: bool,
240 pub sections: SmallVec<[Section; 5]>,
241}
242
243impl FromStr for Editorconfig {
244 type Err = anyhow::Error;
245
246 fn from_str(contents: &str) -> Result<Self, Self::Err> {
247 let parser = ConfigParser::new_buffered(contents.as_bytes())
248 .context("creating editorconfig parser")?;
249 let is_root = parser.is_root;
250 let sections = parser
251 .collect::<Result<SmallVec<_>, _>>()
252 .context("parsing editorconfig sections")?;
253 Ok(Self { is_root, sections })
254 }
255}
256
257#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
258pub enum LocalSettingsKind {
259 Settings,
260 Tasks,
261 Editorconfig,
262 Debug,
263}
264
265impl Global for SettingsStore {}
266
267#[derive(Debug)]
268struct SettingValue<T> {
269 global_value: Option<T>,
270 local_values: Vec<(WorktreeId, Arc<Path>, T)>,
271}
272
273trait AnySettingValue: 'static + Send + Sync {
274 fn key(&self) -> Option<&'static str>;
275 fn setting_type_name(&self) -> &'static str;
276 fn deserialize_setting(&self, json: &Value) -> Result<DeserializedSetting> {
277 self.deserialize_setting_with_key(json).1
278 }
279 fn deserialize_setting_with_key(
280 &self,
281 json: &Value,
282 ) -> (Option<&'static str>, Result<DeserializedSetting>);
283 fn load_setting(
284 &self,
285 sources: SettingsSources<DeserializedSetting>,
286 cx: &mut App,
287 ) -> Result<Box<dyn Any>>;
288 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
289 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)>;
290 fn set_global_value(&mut self, value: Box<dyn Any>);
291 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>);
292 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema;
293 fn edits_for_update(
294 &self,
295 raw_settings: &serde_json::Value,
296 tab_size: usize,
297 vscode_settings: &VsCodeSettings,
298 text: &mut String,
299 edits: &mut Vec<(Range<usize>, String)>,
300 );
301 fn settings_ui_item(&self) -> SettingsUiEntry;
302}
303
304struct DeserializedSetting(Box<dyn Any>);
305
306impl SettingsStore {
307 pub fn new(cx: &App) -> Self {
308 let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
309 Self {
310 setting_values: Default::default(),
311 raw_default_settings: json!({}),
312 raw_global_settings: None,
313 raw_user_settings: json!({}),
314 raw_server_settings: None,
315 raw_extension_settings: json!({}),
316 raw_local_settings: Default::default(),
317 raw_editorconfig_settings: BTreeMap::default(),
318 tab_size_callback: Default::default(),
319 setting_file_updates_tx,
320 _setting_file_updates: cx.spawn(async move |cx| {
321 while let Some(setting_file_update) = setting_file_updates_rx.next().await {
322 (setting_file_update)(cx.clone()).await.log_err();
323 }
324 }),
325 }
326 }
327
328 pub fn observe_active_settings_profile_name(cx: &mut App) -> gpui::Subscription {
329 cx.observe_global::<ActiveSettingsProfileName>(|cx| {
330 Self::update_global(cx, |store, cx| {
331 store.recompute_values(None, cx).log_err();
332 });
333 })
334 }
335
336 pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
337 where
338 C: BorrowAppContext,
339 {
340 cx.update_global(f)
341 }
342
343 /// Add a new type of setting to the store.
344 pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
345 let setting_type_id = TypeId::of::<T>();
346 let entry = self.setting_values.entry(setting_type_id);
347
348 if matches!(entry, hash_map::Entry::Occupied(_)) {
349 return;
350 }
351
352 let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
353 global_value: None,
354 local_values: Vec::new(),
355 }));
356
357 if let Some(default_settings) = setting_value
358 .deserialize_setting(&self.raw_default_settings)
359 .log_err()
360 {
361 let user_value = setting_value
362 .deserialize_setting(&self.raw_user_settings)
363 .log_err();
364
365 let mut release_channel_value = None;
366 if let Some(release_settings) = &self
367 .raw_user_settings
368 .get(release_channel::RELEASE_CHANNEL.dev_name())
369 {
370 release_channel_value = setting_value
371 .deserialize_setting(release_settings)
372 .log_err();
373 }
374
375 let mut os_settings_value = None;
376 if let Some(os_settings) = &self.raw_user_settings.get(env::consts::OS) {
377 os_settings_value = setting_value.deserialize_setting(os_settings).log_err();
378 }
379
380 let mut profile_value = None;
381 if let Some(active_profile) = cx.try_global::<ActiveSettingsProfileName>()
382 && let Some(profiles) = self.raw_user_settings.get("profiles")
383 && let Some(profile_settings) = profiles.get(&active_profile.0)
384 {
385 profile_value = setting_value
386 .deserialize_setting(profile_settings)
387 .log_err();
388 }
389
390 let server_value = self
391 .raw_server_settings
392 .as_ref()
393 .and_then(|server_setting| {
394 setting_value.deserialize_setting(server_setting).log_err()
395 });
396
397 let extension_value = setting_value
398 .deserialize_setting(&self.raw_extension_settings)
399 .log_err();
400
401 if let Some(setting) = setting_value
402 .load_setting(
403 SettingsSources {
404 default: &default_settings,
405 global: None,
406 extensions: extension_value.as_ref(),
407 user: user_value.as_ref(),
408 release_channel: release_channel_value.as_ref(),
409 operating_system: os_settings_value.as_ref(),
410 profile: profile_value.as_ref(),
411 server: server_value.as_ref(),
412 project: &[],
413 },
414 cx,
415 )
416 .context("A default setting must be added to the `default.json` file")
417 .log_err()
418 {
419 setting_value.set_global_value(setting);
420 }
421 }
422 }
423
424 /// Get the value of a setting.
425 ///
426 /// Panics if the given setting type has not been registered, or if there is no
427 /// value for this setting.
428 pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
429 self.setting_values
430 .get(&TypeId::of::<T>())
431 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
432 .value_for_path(path)
433 .downcast_ref::<T>()
434 .expect("no default value for setting type")
435 }
436
437 /// Get the value of a setting.
438 ///
439 /// Does not panic
440 pub fn try_get<T: Settings>(&self, path: Option<SettingsLocation>) -> Option<&T> {
441 self.setting_values
442 .get(&TypeId::of::<T>())
443 .map(|value| value.value_for_path(path))
444 .and_then(|value| value.downcast_ref::<T>())
445 }
446
447 /// Get all values from project specific settings
448 pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<Path>, &T)> {
449 self.setting_values
450 .get(&TypeId::of::<T>())
451 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
452 .all_local_values()
453 .into_iter()
454 .map(|(id, path, any)| {
455 (
456 id,
457 path,
458 any.downcast_ref::<T>()
459 .expect("wrong value type for setting"),
460 )
461 })
462 .collect()
463 }
464
465 /// Override the global value for a setting.
466 ///
467 /// The given value will be overwritten if the user settings file changes.
468 pub fn override_global<T: Settings>(&mut self, value: T) {
469 self.setting_values
470 .get_mut(&TypeId::of::<T>())
471 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
472 .set_global_value(Box::new(value))
473 }
474
475 /// Get the user's settings as a raw JSON value.
476 ///
477 /// For user-facing functionality use the typed setting interface.
478 /// (e.g. ProjectSettings::get_global(cx))
479 pub fn raw_user_settings(&self) -> &Value {
480 &self.raw_user_settings
481 }
482
483 /// Replaces current settings with the values from the given JSON.
484 pub fn set_raw_user_settings(&mut self, new_settings: Value, cx: &mut App) -> Result<()> {
485 self.raw_user_settings = new_settings;
486 self.recompute_values(None, cx)?;
487 Ok(())
488 }
489
490 /// Get the configured settings profile names.
491 pub fn configured_settings_profiles(&self) -> impl Iterator<Item = &str> {
492 self.raw_user_settings
493 .get("profiles")
494 .and_then(|v| v.as_object())
495 .into_iter()
496 .flat_map(|obj| obj.keys())
497 .map(|s| s.as_str())
498 }
499
500 /// Access the raw JSON value of the global settings.
501 pub fn raw_global_settings(&self) -> Option<&Value> {
502 self.raw_global_settings.as_ref()
503 }
504
505 /// Access the raw JSON value of the default settings.
506 pub fn raw_default_settings(&self) -> &Value {
507 &self.raw_default_settings
508 }
509
510 #[cfg(any(test, feature = "test-support"))]
511 pub fn test(cx: &mut App) -> Self {
512 let mut this = Self::new(cx);
513 this.set_default_settings(&crate::test_settings(), cx)
514 .unwrap();
515 this.set_user_settings("{}", cx).unwrap();
516 this
517 }
518
519 /// Updates the value of a setting in the user's global configuration.
520 ///
521 /// This is only for tests. Normally, settings are only loaded from
522 /// JSON files.
523 #[cfg(any(test, feature = "test-support"))]
524 pub fn update_user_settings<T: Settings>(
525 &mut self,
526 cx: &mut App,
527 update: impl FnOnce(&mut T::FileContent),
528 ) {
529 let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
530 let new_text = self.new_text_for_update::<T>(old_text, update);
531 self.set_user_settings(&new_text, cx).unwrap();
532 }
533
534 pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
535 match fs.load(paths::settings_file()).await {
536 result @ Ok(_) => result,
537 Err(err) => {
538 if let Some(e) = err.downcast_ref::<std::io::Error>()
539 && e.kind() == std::io::ErrorKind::NotFound
540 {
541 return Ok(crate::initial_user_settings_content().to_string());
542 }
543 Err(err)
544 }
545 }
546 }
547
548 fn update_settings_file_inner(
549 &self,
550 fs: Arc<dyn Fs>,
551 update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
552 ) -> oneshot::Receiver<Result<()>> {
553 let (tx, rx) = oneshot::channel::<Result<()>>();
554 self.setting_file_updates_tx
555 .unbounded_send(Box::new(move |cx: AsyncApp| {
556 async move {
557 let res = async move {
558 let old_text = Self::load_settings(&fs).await?;
559 let new_text = update(old_text, cx)?;
560 let settings_path = paths::settings_file().as_path();
561 if fs.is_file(settings_path).await {
562 let resolved_path =
563 fs.canonicalize(settings_path).await.with_context(|| {
564 format!(
565 "Failed to canonicalize settings path {:?}",
566 settings_path
567 )
568 })?;
569
570 fs.atomic_write(resolved_path.clone(), new_text)
571 .await
572 .with_context(|| {
573 format!("Failed to write settings to file {:?}", resolved_path)
574 })?;
575 } else {
576 fs.atomic_write(settings_path.to_path_buf(), new_text)
577 .await
578 .with_context(|| {
579 format!("Failed to write settings to file {:?}", settings_path)
580 })?;
581 }
582 anyhow::Ok(())
583 }
584 .await;
585
586 let new_res = match &res {
587 Ok(_) => anyhow::Ok(()),
588 Err(e) => Err(anyhow::anyhow!("Failed to write settings to file {:?}", e)),
589 };
590
591 _ = tx.send(new_res);
592 res
593 }
594 .boxed_local()
595 }))
596 .map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
597 .log_with_level(log::Level::Warn);
598 return rx;
599 }
600
601 pub fn update_settings_file_at_path(
602 &self,
603 fs: Arc<dyn Fs>,
604 path: &[impl AsRef<str>],
605 new_value: serde_json::Value,
606 ) -> oneshot::Receiver<Result<()>> {
607 let key_path = path
608 .into_iter()
609 .map(AsRef::as_ref)
610 .map(SharedString::new)
611 .collect::<Vec<_>>();
612 let update = move |mut old_text: String, cx: AsyncApp| {
613 cx.read_global(|store: &SettingsStore, _cx| {
614 // todo(settings_ui) use `update_value_in_json_text` for merging new and old objects with comment preservation, needs old value though...
615 let (range, replacement) = replace_value_in_json_text(
616 &old_text,
617 key_path.as_slice(),
618 store.json_tab_size(),
619 Some(&new_value),
620 None,
621 );
622 old_text.replace_range(range, &replacement);
623 old_text
624 })
625 };
626 self.update_settings_file_inner(fs, update)
627 }
628
629 pub fn update_settings_file<T: Settings>(
630 &self,
631 fs: Arc<dyn Fs>,
632 update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
633 ) {
634 _ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
635 cx.read_global(|store: &SettingsStore, cx| {
636 store.new_text_for_update::<T>(old_text, |content| update(content, cx))
637 })
638 });
639 }
640
641 pub fn import_vscode_settings(
642 &self,
643 fs: Arc<dyn Fs>,
644 vscode_settings: VsCodeSettings,
645 ) -> oneshot::Receiver<Result<()>> {
646 self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
647 cx.read_global(|store: &SettingsStore, _cx| {
648 store.get_vscode_edits(old_text, &vscode_settings)
649 })
650 })
651 }
652
653 pub fn settings_ui_items(&self) -> impl IntoIterator<Item = SettingsUiEntry> {
654 self.setting_values
655 .values()
656 .map(|item| item.settings_ui_item())
657 }
658}
659
660impl SettingsStore {
661 /// Updates the value of a setting in a JSON file, returning the new text
662 /// for that JSON file.
663 pub fn new_text_for_update<T: Settings>(
664 &self,
665 old_text: String,
666 update: impl FnOnce(&mut T::FileContent),
667 ) -> String {
668 let edits = self.edits_for_update::<T>(&old_text, update);
669 let mut new_text = old_text;
670 for (range, replacement) in edits.into_iter() {
671 new_text.replace_range(range, &replacement);
672 }
673 new_text
674 }
675
676 pub fn get_vscode_edits(&self, mut old_text: String, vscode: &VsCodeSettings) -> String {
677 let mut new_text = old_text.clone();
678 let mut edits: Vec<(Range<usize>, String)> = Vec::new();
679 let raw_settings = parse_json_with_comments::<Value>(&old_text).unwrap_or_default();
680 let tab_size = self.json_tab_size();
681 for v in self.setting_values.values() {
682 v.edits_for_update(&raw_settings, tab_size, vscode, &mut old_text, &mut edits);
683 }
684 for (range, replacement) in edits.into_iter() {
685 new_text.replace_range(range, &replacement);
686 }
687 new_text
688 }
689
690 /// Updates the value of a setting in a JSON file, returning a list
691 /// of edits to apply to the JSON file.
692 pub fn edits_for_update<T: Settings>(
693 &self,
694 text: &str,
695 update: impl FnOnce(&mut T::FileContent),
696 ) -> Vec<(Range<usize>, String)> {
697 let setting_type_id = TypeId::of::<T>();
698
699 let preserved_keys = T::PRESERVED_KEYS.unwrap_or_default();
700
701 let setting = self
702 .setting_values
703 .get(&setting_type_id)
704 .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
705 let raw_settings = parse_json_with_comments::<Value>(text).unwrap_or_default();
706 let (key, deserialized_setting) = setting.deserialize_setting_with_key(&raw_settings);
707 let old_content = match deserialized_setting {
708 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
709 Err(_) => Box::<<T as Settings>::FileContent>::default(),
710 };
711 let mut new_content = old_content.clone();
712 update(&mut new_content);
713
714 let old_value = serde_json::to_value(&old_content).unwrap();
715 let new_value = serde_json::to_value(new_content).unwrap();
716
717 let mut key_path = Vec::new();
718 if let Some(key) = key {
719 key_path.push(key);
720 }
721
722 let mut edits = Vec::new();
723 let tab_size = self.json_tab_size();
724 let mut text = text.to_string();
725 update_value_in_json_text(
726 &mut text,
727 &mut key_path,
728 tab_size,
729 &old_value,
730 &new_value,
731 preserved_keys,
732 &mut edits,
733 );
734 edits
735 }
736
737 /// Configure the tab sized when updating JSON files.
738 pub fn set_json_tab_size_callback<T: Settings>(
739 &mut self,
740 get_tab_size: fn(&T) -> Option<usize>,
741 ) {
742 self.tab_size_callback = Some((
743 TypeId::of::<T>(),
744 Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
745 ));
746 }
747
748 pub fn json_tab_size(&self) -> usize {
749 const DEFAULT_JSON_TAB_SIZE: usize = 2;
750
751 if let Some((setting_type_id, callback)) = &self.tab_size_callback {
752 let setting_value = self.setting_values.get(setting_type_id).unwrap();
753 let value = setting_value.value_for_path(None);
754 if let Some(value) = callback(value) {
755 return value;
756 }
757 }
758
759 DEFAULT_JSON_TAB_SIZE
760 }
761
762 /// Sets the default settings via a JSON string.
763 ///
764 /// The string should contain a JSON object with a default value for every setting.
765 pub fn set_default_settings(
766 &mut self,
767 default_settings_content: &str,
768 cx: &mut App,
769 ) -> Result<()> {
770 let settings: Value = parse_json_with_comments(default_settings_content)?;
771 anyhow::ensure!(settings.is_object(), "settings must be an object");
772 self.raw_default_settings = settings;
773 self.recompute_values(None, cx)?;
774 Ok(())
775 }
776
777 /// Sets the user settings via a JSON string.
778 pub fn set_user_settings(
779 &mut self,
780 user_settings_content: &str,
781 cx: &mut App,
782 ) -> Result<Value> {
783 let settings: Value = if user_settings_content.is_empty() {
784 parse_json_with_comments("{}")?
785 } else {
786 parse_json_with_comments(user_settings_content)?
787 };
788
789 anyhow::ensure!(settings.is_object(), "settings must be an object");
790 self.raw_user_settings = settings.clone();
791 self.recompute_values(None, cx)?;
792 Ok(settings)
793 }
794
795 /// Sets the global settings via a JSON string.
796 pub fn set_global_settings(
797 &mut self,
798 global_settings_content: &str,
799 cx: &mut App,
800 ) -> Result<Value> {
801 let settings: Value = if global_settings_content.is_empty() {
802 parse_json_with_comments("{}")?
803 } else {
804 parse_json_with_comments(global_settings_content)?
805 };
806
807 anyhow::ensure!(settings.is_object(), "settings must be an object");
808 self.raw_global_settings = Some(settings.clone());
809 self.recompute_values(None, cx)?;
810 Ok(settings)
811 }
812
813 pub fn set_server_settings(
814 &mut self,
815 server_settings_content: &str,
816 cx: &mut App,
817 ) -> Result<()> {
818 let settings: Option<Value> = if server_settings_content.is_empty() {
819 None
820 } else {
821 parse_json_with_comments(server_settings_content)?
822 };
823
824 anyhow::ensure!(
825 settings
826 .as_ref()
827 .map(|value| value.is_object())
828 .unwrap_or(true),
829 "settings must be an object"
830 );
831 self.raw_server_settings = settings;
832 self.recompute_values(None, cx)?;
833 Ok(())
834 }
835
836 /// Add or remove a set of local settings via a JSON string.
837 pub fn set_local_settings(
838 &mut self,
839 root_id: WorktreeId,
840 directory_path: Arc<Path>,
841 kind: LocalSettingsKind,
842 settings_content: Option<&str>,
843 cx: &mut App,
844 ) -> std::result::Result<(), InvalidSettingsError> {
845 let mut zed_settings_changed = false;
846 match (
847 kind,
848 settings_content
849 .map(|content| content.trim())
850 .filter(|content| !content.is_empty()),
851 ) {
852 (LocalSettingsKind::Tasks, _) => {
853 return Err(InvalidSettingsError::Tasks {
854 message: "Attempted to submit tasks into the settings store".to_string(),
855 path: directory_path.join(task_file_name()),
856 });
857 }
858 (LocalSettingsKind::Debug, _) => {
859 return Err(InvalidSettingsError::Debug {
860 message: "Attempted to submit debugger config into the settings store"
861 .to_string(),
862 path: directory_path.join(task_file_name()),
863 });
864 }
865 (LocalSettingsKind::Settings, None) => {
866 zed_settings_changed = self
867 .raw_local_settings
868 .remove(&(root_id, directory_path.clone()))
869 .is_some()
870 }
871 (LocalSettingsKind::Editorconfig, None) => {
872 self.raw_editorconfig_settings
873 .remove(&(root_id, directory_path.clone()));
874 }
875 (LocalSettingsKind::Settings, Some(settings_contents)) => {
876 let new_settings =
877 parse_json_with_comments::<Value>(settings_contents).map_err(|e| {
878 InvalidSettingsError::LocalSettings {
879 path: directory_path.join(local_settings_file_relative_path()),
880 message: e.to_string(),
881 }
882 })?;
883 match self
884 .raw_local_settings
885 .entry((root_id, directory_path.clone()))
886 {
887 btree_map::Entry::Vacant(v) => {
888 v.insert(new_settings);
889 zed_settings_changed = true;
890 }
891 btree_map::Entry::Occupied(mut o) => {
892 if o.get() != &new_settings {
893 o.insert(new_settings);
894 zed_settings_changed = true;
895 }
896 }
897 }
898 }
899 (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
900 match self
901 .raw_editorconfig_settings
902 .entry((root_id, directory_path.clone()))
903 {
904 btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
905 Ok(new_contents) => {
906 v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
907 }
908 Err(e) => {
909 v.insert((editorconfig_contents.to_owned(), None));
910 return Err(InvalidSettingsError::Editorconfig {
911 message: e.to_string(),
912 path: directory_path.join(EDITORCONFIG_NAME),
913 });
914 }
915 },
916 btree_map::Entry::Occupied(mut o) => {
917 if o.get().0 != editorconfig_contents {
918 match editorconfig_contents.parse() {
919 Ok(new_contents) => {
920 o.insert((
921 editorconfig_contents.to_owned(),
922 Some(new_contents),
923 ));
924 }
925 Err(e) => {
926 o.insert((editorconfig_contents.to_owned(), None));
927 return Err(InvalidSettingsError::Editorconfig {
928 message: e.to_string(),
929 path: directory_path.join(EDITORCONFIG_NAME),
930 });
931 }
932 }
933 }
934 }
935 }
936 }
937 };
938
939 if zed_settings_changed {
940 self.recompute_values(Some((root_id, &directory_path)), cx)?;
941 }
942 Ok(())
943 }
944
945 pub fn set_extension_settings<T: Serialize>(&mut self, content: T, cx: &mut App) -> Result<()> {
946 let settings: Value = serde_json::to_value(content)?;
947 anyhow::ensure!(settings.is_object(), "settings must be an object");
948 self.raw_extension_settings = settings;
949 self.recompute_values(None, cx)?;
950 Ok(())
951 }
952
953 /// Add or remove a set of local settings via a JSON string.
954 pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
955 self.raw_local_settings
956 .retain(|(worktree_id, _), _| worktree_id != &root_id);
957 self.recompute_values(Some((root_id, "".as_ref())), cx)?;
958 Ok(())
959 }
960
961 pub fn local_settings(
962 &self,
963 root_id: WorktreeId,
964 ) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
965 self.raw_local_settings
966 .range(
967 (root_id, Path::new("").into())
968 ..(
969 WorktreeId::from_usize(root_id.to_usize() + 1),
970 Path::new("").into(),
971 ),
972 )
973 .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
974 }
975
976 pub fn local_editorconfig_settings(
977 &self,
978 root_id: WorktreeId,
979 ) -> impl '_ + Iterator<Item = (Arc<Path>, String, Option<Editorconfig>)> {
980 self.raw_editorconfig_settings
981 .range(
982 (root_id, Path::new("").into())
983 ..(
984 WorktreeId::from_usize(root_id.to_usize() + 1),
985 Path::new("").into(),
986 ),
987 )
988 .map(|((_, path), (content, parsed_content))| {
989 (path.clone(), content.clone(), parsed_content.clone())
990 })
991 }
992
993 pub fn json_schema(&self, schema_params: &SettingsJsonSchemaParams, cx: &App) -> Value {
994 let mut generator = schemars::generate::SchemaSettings::draft2019_09()
995 .with_transform(DefaultDenyUnknownFields)
996 .into_generator();
997 let mut combined_schema = json!({
998 "type": "object",
999 "properties": {}
1000 });
1001
1002 // Merge together settings schemas, similarly to json schema's "allOf". This merging is
1003 // recursive, though at time of writing this recursive nature isn't used very much. An
1004 // example of it is the schema for `jupyter` having contribution from both `EditorSettings`
1005 // and `JupyterSettings`.
1006 //
1007 // This logic could be removed in favor of "allOf", but then there isn't the opportunity to
1008 // validate and fully control the merge.
1009 for setting_value in self.setting_values.values() {
1010 let mut setting_schema = setting_value.json_schema(&mut generator);
1011
1012 if let Some(key) = setting_value.key() {
1013 if let Some(properties) = combined_schema.get_mut("properties")
1014 && let Some(properties_obj) = properties.as_object_mut()
1015 {
1016 if let Some(target) = properties_obj.get_mut(key) {
1017 merge_schema(target, setting_schema.to_value());
1018 } else {
1019 properties_obj.insert(key.to_string(), setting_schema.to_value());
1020 }
1021 }
1022 } else {
1023 setting_schema.remove("description");
1024 setting_schema.remove("additionalProperties");
1025 merge_schema(&mut combined_schema, setting_schema.to_value());
1026 }
1027 }
1028
1029 fn merge_schema(target: &mut serde_json::Value, source: serde_json::Value) {
1030 let (Some(target_obj), serde_json::Value::Object(source_obj)) =
1031 (target.as_object_mut(), source)
1032 else {
1033 return;
1034 };
1035
1036 for (source_key, source_value) in source_obj {
1037 match source_key.as_str() {
1038 "properties" => {
1039 let serde_json::Value::Object(source_properties) = source_value else {
1040 log::error!(
1041 "bug: expected object for `{}` json schema field, but got: {}",
1042 source_key,
1043 source_value
1044 );
1045 continue;
1046 };
1047 let target_properties =
1048 target_obj.entry(source_key.clone()).or_insert(json!({}));
1049 let Some(target_properties) = target_properties.as_object_mut() else {
1050 log::error!(
1051 "bug: expected object for `{}` json schema field, but got: {}",
1052 source_key,
1053 target_properties
1054 );
1055 continue;
1056 };
1057 for (key, value) in source_properties {
1058 if let Some(existing) = target_properties.get_mut(&key) {
1059 merge_schema(existing, value);
1060 } else {
1061 target_properties.insert(key, value);
1062 }
1063 }
1064 }
1065 "allOf" | "anyOf" | "oneOf" => {
1066 let serde_json::Value::Array(source_array) = source_value else {
1067 log::error!(
1068 "bug: expected array for `{}` json schema field, but got: {}",
1069 source_key,
1070 source_value,
1071 );
1072 continue;
1073 };
1074 let target_array =
1075 target_obj.entry(source_key.clone()).or_insert(json!([]));
1076 let Some(target_array) = target_array.as_array_mut() else {
1077 log::error!(
1078 "bug: expected array for `{}` json schema field, but got: {}",
1079 source_key,
1080 target_array,
1081 );
1082 continue;
1083 };
1084 target_array.extend(source_array);
1085 }
1086 "type"
1087 | "$ref"
1088 | "enum"
1089 | "minimum"
1090 | "maximum"
1091 | "pattern"
1092 | "description"
1093 | "additionalProperties" => {
1094 if let Some(old_value) =
1095 target_obj.insert(source_key.clone(), source_value.clone())
1096 && old_value != source_value
1097 {
1098 log::error!(
1099 "bug: while merging JSON schemas, \
1100 mismatch `\"{}\": {}` (before was `{}`)",
1101 source_key,
1102 old_value,
1103 source_value
1104 );
1105 }
1106 }
1107 _ => {
1108 log::error!(
1109 "bug: while merging settings JSON schemas, \
1110 encountered unexpected `\"{}\": {}`",
1111 source_key,
1112 source_value
1113 );
1114 }
1115 }
1116 }
1117 }
1118
1119 // add schemas which are determined at runtime
1120 for parameterized_json_schema in inventory::iter::<ParameterizedJsonSchema>() {
1121 (parameterized_json_schema.add_and_get_ref)(&mut generator, schema_params, cx);
1122 }
1123
1124 // add merged settings schema to the definitions
1125 const ZED_SETTINGS: &str = "ZedSettings";
1126 let zed_settings_ref = add_new_subschema(&mut generator, ZED_SETTINGS, combined_schema);
1127
1128 // add `ZedSettingsOverride` which is the same as `ZedSettings` except that unknown
1129 // fields are rejected. This is used for release stage settings and profiles.
1130 let mut zed_settings_override = zed_settings_ref.clone();
1131 zed_settings_override.insert("unevaluatedProperties".to_string(), false.into());
1132 let zed_settings_override_ref = add_new_subschema(
1133 &mut generator,
1134 "ZedSettingsOverride",
1135 zed_settings_override.to_value(),
1136 );
1137
1138 // Remove `"additionalProperties": false` added by `DefaultDenyUnknownFields` so that
1139 // unknown fields can be handled by the root schema and `ZedSettingsOverride`.
1140 let mut definitions = generator.take_definitions(true);
1141 definitions
1142 .get_mut(ZED_SETTINGS)
1143 .unwrap()
1144 .as_object_mut()
1145 .unwrap()
1146 .remove("additionalProperties");
1147
1148 let meta_schema = generator
1149 .settings()
1150 .meta_schema
1151 .as_ref()
1152 .expect("meta_schema should be present in schemars settings")
1153 .to_string();
1154
1155 json!({
1156 "$schema": meta_schema,
1157 "title": "Zed Settings",
1158 "unevaluatedProperties": false,
1159 // ZedSettings + settings overrides for each release stage / OS / profiles
1160 "allOf": [
1161 zed_settings_ref,
1162 {
1163 "properties": {
1164 "dev": zed_settings_override_ref,
1165 "nightly": zed_settings_override_ref,
1166 "stable": zed_settings_override_ref,
1167 "preview": zed_settings_override_ref,
1168 "linux": zed_settings_override_ref,
1169 "macos": zed_settings_override_ref,
1170 "windows": zed_settings_override_ref,
1171 "profiles": {
1172 "type": "object",
1173 "description": "Configures any number of settings profiles.",
1174 "additionalProperties": zed_settings_override_ref
1175 }
1176 }
1177 }
1178 ],
1179 "$defs": definitions,
1180 })
1181 }
1182
1183 fn recompute_values(
1184 &mut self,
1185 changed_local_path: Option<(WorktreeId, &Path)>,
1186 cx: &mut App,
1187 ) -> std::result::Result<(), InvalidSettingsError> {
1188 // Reload the global and local values for every setting.
1189 let mut project_settings_stack = Vec::<DeserializedSetting>::new();
1190 let mut paths_stack = Vec::<Option<(WorktreeId, &Path)>>::new();
1191 for setting_value in self.setting_values.values_mut() {
1192 let default_settings = setting_value
1193 .deserialize_setting(&self.raw_default_settings)
1194 .map_err(|e| InvalidSettingsError::DefaultSettings {
1195 message: e.to_string(),
1196 })?;
1197
1198 let global_settings = self
1199 .raw_global_settings
1200 .as_ref()
1201 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1202
1203 let extension_settings = setting_value
1204 .deserialize_setting(&self.raw_extension_settings)
1205 .log_err();
1206
1207 let user_settings = match setting_value.deserialize_setting(&self.raw_user_settings) {
1208 Ok(settings) => Some(settings),
1209 Err(error) => {
1210 return Err(InvalidSettingsError::UserSettings {
1211 message: error.to_string(),
1212 });
1213 }
1214 };
1215
1216 let server_settings = self
1217 .raw_server_settings
1218 .as_ref()
1219 .and_then(|setting| setting_value.deserialize_setting(setting).log_err());
1220
1221 let mut release_channel_settings = None;
1222 if let Some(release_settings) = &self
1223 .raw_user_settings
1224 .get(release_channel::RELEASE_CHANNEL.dev_name())
1225 && let Some(release_settings) = setting_value
1226 .deserialize_setting(release_settings)
1227 .log_err()
1228 {
1229 release_channel_settings = Some(release_settings);
1230 }
1231
1232 let mut os_settings = None;
1233 if let Some(settings) = &self.raw_user_settings.get(env::consts::OS)
1234 && let Some(settings) = setting_value.deserialize_setting(settings).log_err()
1235 {
1236 os_settings = Some(settings);
1237 }
1238
1239 let mut profile_settings = None;
1240 if let Some(active_profile) = cx.try_global::<ActiveSettingsProfileName>()
1241 && let Some(profiles) = self.raw_user_settings.get("profiles")
1242 && let Some(profile_json) = profiles.get(&active_profile.0)
1243 {
1244 profile_settings = setting_value.deserialize_setting(profile_json).log_err();
1245 }
1246
1247 // If the global settings file changed, reload the global value for the field.
1248 if changed_local_path.is_none()
1249 && let Some(value) = setting_value
1250 .load_setting(
1251 SettingsSources {
1252 default: &default_settings,
1253 global: global_settings.as_ref(),
1254 extensions: extension_settings.as_ref(),
1255 user: user_settings.as_ref(),
1256 release_channel: release_channel_settings.as_ref(),
1257 operating_system: os_settings.as_ref(),
1258 profile: profile_settings.as_ref(),
1259 server: server_settings.as_ref(),
1260 project: &[],
1261 },
1262 cx,
1263 )
1264 .log_err()
1265 {
1266 setting_value.set_global_value(value);
1267 }
1268
1269 // Reload the local values for the setting.
1270 paths_stack.clear();
1271 project_settings_stack.clear();
1272 for ((root_id, directory_path), local_settings) in &self.raw_local_settings {
1273 // Build a stack of all of the local values for that setting.
1274 while let Some(prev_entry) = paths_stack.last() {
1275 if let Some((prev_root_id, prev_path)) = prev_entry
1276 && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
1277 {
1278 paths_stack.pop();
1279 project_settings_stack.pop();
1280 continue;
1281 }
1282 break;
1283 }
1284
1285 match setting_value.deserialize_setting(local_settings) {
1286 Ok(local_settings) => {
1287 paths_stack.push(Some((*root_id, directory_path.as_ref())));
1288 project_settings_stack.push(local_settings);
1289
1290 // If a local settings file changed, then avoid recomputing local
1291 // settings for any path outside of that directory.
1292 if changed_local_path.is_some_and(
1293 |(changed_root_id, changed_local_path)| {
1294 *root_id != changed_root_id
1295 || !directory_path.starts_with(changed_local_path)
1296 },
1297 ) {
1298 continue;
1299 }
1300
1301 if let Some(value) = setting_value
1302 .load_setting(
1303 SettingsSources {
1304 default: &default_settings,
1305 global: global_settings.as_ref(),
1306 extensions: extension_settings.as_ref(),
1307 user: user_settings.as_ref(),
1308 release_channel: release_channel_settings.as_ref(),
1309 operating_system: os_settings.as_ref(),
1310 profile: profile_settings.as_ref(),
1311 server: server_settings.as_ref(),
1312 project: &project_settings_stack.iter().collect::<Vec<_>>(),
1313 },
1314 cx,
1315 )
1316 .log_err()
1317 {
1318 setting_value.set_local_value(*root_id, directory_path.clone(), value);
1319 }
1320 }
1321 Err(error) => {
1322 return Err(InvalidSettingsError::LocalSettings {
1323 path: directory_path.join(local_settings_file_relative_path()),
1324 message: error.to_string(),
1325 });
1326 }
1327 }
1328 }
1329 }
1330 Ok(())
1331 }
1332
1333 pub fn editorconfig_properties(
1334 &self,
1335 for_worktree: WorktreeId,
1336 for_path: &Path,
1337 ) -> Option<EditorconfigProperties> {
1338 let mut properties = EditorconfigProperties::new();
1339
1340 for (directory_with_config, _, parsed_editorconfig) in
1341 self.local_editorconfig_settings(for_worktree)
1342 {
1343 if !for_path.starts_with(&directory_with_config) {
1344 properties.use_fallbacks();
1345 return Some(properties);
1346 }
1347 let parsed_editorconfig = parsed_editorconfig?;
1348 if parsed_editorconfig.is_root {
1349 properties = EditorconfigProperties::new();
1350 }
1351 for section in parsed_editorconfig.sections {
1352 section.apply_to(&mut properties, for_path).log_err()?;
1353 }
1354 }
1355
1356 properties.use_fallbacks();
1357 Some(properties)
1358 }
1359}
1360
1361#[derive(Debug, Clone, PartialEq)]
1362pub enum InvalidSettingsError {
1363 LocalSettings { path: PathBuf, message: String },
1364 UserSettings { message: String },
1365 ServerSettings { message: String },
1366 DefaultSettings { message: String },
1367 Editorconfig { path: PathBuf, message: String },
1368 Tasks { path: PathBuf, message: String },
1369 Debug { path: PathBuf, message: String },
1370}
1371
1372impl std::fmt::Display for InvalidSettingsError {
1373 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1374 match self {
1375 InvalidSettingsError::LocalSettings { message, .. }
1376 | InvalidSettingsError::UserSettings { message }
1377 | InvalidSettingsError::ServerSettings { message }
1378 | InvalidSettingsError::DefaultSettings { message }
1379 | InvalidSettingsError::Tasks { message, .. }
1380 | InvalidSettingsError::Editorconfig { message, .. }
1381 | InvalidSettingsError::Debug { message, .. } => {
1382 write!(f, "{message}")
1383 }
1384 }
1385 }
1386}
1387impl std::error::Error for InvalidSettingsError {}
1388
1389impl Debug for SettingsStore {
1390 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1391 f.debug_struct("SettingsStore")
1392 .field(
1393 "types",
1394 &self
1395 .setting_values
1396 .values()
1397 .map(|value| value.setting_type_name())
1398 .collect::<Vec<_>>(),
1399 )
1400 .field("default_settings", &self.raw_default_settings)
1401 .field("user_settings", &self.raw_user_settings)
1402 .field("local_settings", &self.raw_local_settings)
1403 .finish_non_exhaustive()
1404 }
1405}
1406
1407impl<T: Settings> AnySettingValue for SettingValue<T> {
1408 fn key(&self) -> Option<&'static str> {
1409 T::FileContent::KEY
1410 }
1411
1412 fn setting_type_name(&self) -> &'static str {
1413 type_name::<T>()
1414 }
1415
1416 fn load_setting(
1417 &self,
1418 values: SettingsSources<DeserializedSetting>,
1419 cx: &mut App,
1420 ) -> Result<Box<dyn Any>> {
1421 Ok(Box::new(T::load(
1422 SettingsSources {
1423 default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
1424 global: values
1425 .global
1426 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1427 extensions: values
1428 .extensions
1429 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1430 user: values
1431 .user
1432 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1433 release_channel: values
1434 .release_channel
1435 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1436 operating_system: values
1437 .operating_system
1438 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1439 profile: values
1440 .profile
1441 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1442 server: values
1443 .server
1444 .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
1445 project: values
1446 .project
1447 .iter()
1448 .map(|value| value.0.downcast_ref().unwrap())
1449 .collect::<SmallVec<[_; 3]>>()
1450 .as_slice(),
1451 },
1452 cx,
1453 )?))
1454 }
1455
1456 fn deserialize_setting_with_key(
1457 &self,
1458 mut json: &Value,
1459 ) -> (Option<&'static str>, Result<DeserializedSetting>) {
1460 let mut key = None;
1461 if let Some(k) = T::FileContent::KEY {
1462 if let Some(value) = json.get(k) {
1463 json = value;
1464 key = Some(k);
1465 } else if let Some((k, value)) =
1466 T::FileContent::FALLBACK_KEY.and_then(|k| Some((k, json.get(k)?)))
1467 {
1468 json = value;
1469 key = Some(k);
1470 } else {
1471 let value = T::FileContent::default();
1472 return (
1473 T::FileContent::KEY,
1474 Ok(DeserializedSetting(Box::new(value))),
1475 );
1476 }
1477 }
1478 let value = serde_path_to_error::deserialize::<_, T::FileContent>(json)
1479 .map(|value| DeserializedSetting(Box::new(value)))
1480 .map_err(|err| {
1481 // construct a path using the key and reported error path if possible.
1482 // Unfortunately, serde_path_to_error does not expose the necessary
1483 // methods and data to simply add the key to the path
1484 let mut path = String::new();
1485 if let Some(key) = key {
1486 path.push_str(key);
1487 }
1488 let err_path = err.path().to_string();
1489 // when the path is empty, serde_path_to_error stringifies the path as ".",
1490 // when the path is unknown, serde_path_to_error stringifies the path as an empty string
1491 if !err_path.is_empty() && !err_path.starts_with(".") {
1492 path.push('.');
1493 path.push_str(&err_path);
1494 }
1495 if path.is_empty() {
1496 anyhow::Error::from(err.into_inner())
1497 } else {
1498 anyhow::anyhow!("'{}': {}", err.into_inner(), path)
1499 }
1500 });
1501 (key, value)
1502 }
1503
1504 fn all_local_values(&self) -> Vec<(WorktreeId, Arc<Path>, &dyn Any)> {
1505 self.local_values
1506 .iter()
1507 .map(|(id, path, value)| (*id, path.clone(), value as _))
1508 .collect()
1509 }
1510
1511 fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1512 if let Some(SettingsLocation { worktree_id, path }) = path {
1513 for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1514 if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1515 return value;
1516 }
1517 }
1518 }
1519
1520 self.global_value
1521 .as_ref()
1522 .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1523 }
1524
1525 fn set_global_value(&mut self, value: Box<dyn Any>) {
1526 self.global_value = Some(*value.downcast().unwrap());
1527 }
1528
1529 fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
1530 let value = *value.downcast().unwrap();
1531 match self
1532 .local_values
1533 .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1534 {
1535 Ok(ix) => self.local_values[ix].2 = value,
1536 Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1537 }
1538 }
1539
1540 fn json_schema(&self, generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1541 T::FileContent::json_schema(generator)
1542 }
1543
1544 fn edits_for_update(
1545 &self,
1546 raw_settings: &serde_json::Value,
1547 tab_size: usize,
1548 vscode_settings: &VsCodeSettings,
1549 text: &mut String,
1550 edits: &mut Vec<(Range<usize>, String)>,
1551 ) {
1552 let (key, deserialized_setting) = self.deserialize_setting_with_key(raw_settings);
1553 let old_content = match deserialized_setting {
1554 Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
1555 Err(_) => Box::<<T as Settings>::FileContent>::default(),
1556 };
1557 let mut new_content = old_content.clone();
1558 T::import_from_vscode(vscode_settings, &mut new_content);
1559
1560 let old_value = serde_json::to_value(&old_content).unwrap();
1561 let new_value = serde_json::to_value(new_content).unwrap();
1562
1563 let mut key_path = Vec::new();
1564 if let Some(key) = key {
1565 key_path.push(key);
1566 }
1567
1568 update_value_in_json_text(
1569 text,
1570 &mut key_path,
1571 tab_size,
1572 &old_value,
1573 &new_value,
1574 T::PRESERVED_KEYS.unwrap_or_default(),
1575 edits,
1576 );
1577 }
1578
1579 fn settings_ui_item(&self) -> SettingsUiEntry {
1580 <<T as Settings>::FileContent as SettingsUi>::settings_ui_entry()
1581 }
1582}
1583
1584#[cfg(test)]
1585mod tests {
1586 use crate::VsCodeSettingsSource;
1587
1588 use super::*;
1589 // This is so the SettingsUi macro can still work properly
1590 use crate as settings;
1591 use serde_derive::Deserialize;
1592 use settings_ui_macros::{SettingsKey, SettingsUi};
1593 use unindent::Unindent;
1594
1595 #[gpui::test]
1596 fn test_settings_store_basic(cx: &mut App) {
1597 let mut store = SettingsStore::new(cx);
1598 store.register_setting::<UserSettings>(cx);
1599 store.register_setting::<TurboSetting>(cx);
1600 store.register_setting::<MultiKeySettings>(cx);
1601 store
1602 .set_default_settings(
1603 r#"{
1604 "turbo": false,
1605 "user": {
1606 "name": "John Doe",
1607 "age": 30,
1608 "staff": false
1609 }
1610 }"#,
1611 cx,
1612 )
1613 .unwrap();
1614
1615 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1616 assert_eq!(
1617 store.get::<UserSettings>(None),
1618 &UserSettings {
1619 name: "John Doe".to_string(),
1620 age: 30,
1621 staff: false,
1622 }
1623 );
1624 assert_eq!(
1625 store.get::<MultiKeySettings>(None),
1626 &MultiKeySettings {
1627 key1: String::new(),
1628 key2: String::new(),
1629 }
1630 );
1631
1632 store
1633 .set_user_settings(
1634 r#"{
1635 "turbo": true,
1636 "user": { "age": 31 },
1637 "key1": "a"
1638 }"#,
1639 cx,
1640 )
1641 .unwrap();
1642
1643 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1644 assert_eq!(
1645 store.get::<UserSettings>(None),
1646 &UserSettings {
1647 name: "John Doe".to_string(),
1648 age: 31,
1649 staff: false
1650 }
1651 );
1652
1653 store
1654 .set_local_settings(
1655 WorktreeId::from_usize(1),
1656 Path::new("/root1").into(),
1657 LocalSettingsKind::Settings,
1658 Some(r#"{ "user": { "staff": true } }"#),
1659 cx,
1660 )
1661 .unwrap();
1662 store
1663 .set_local_settings(
1664 WorktreeId::from_usize(1),
1665 Path::new("/root1/subdir").into(),
1666 LocalSettingsKind::Settings,
1667 Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1668 cx,
1669 )
1670 .unwrap();
1671
1672 store
1673 .set_local_settings(
1674 WorktreeId::from_usize(1),
1675 Path::new("/root2").into(),
1676 LocalSettingsKind::Settings,
1677 Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1678 cx,
1679 )
1680 .unwrap();
1681
1682 assert_eq!(
1683 store.get::<UserSettings>(Some(SettingsLocation {
1684 worktree_id: WorktreeId::from_usize(1),
1685 path: Path::new("/root1/something"),
1686 })),
1687 &UserSettings {
1688 name: "John Doe".to_string(),
1689 age: 31,
1690 staff: true
1691 }
1692 );
1693 assert_eq!(
1694 store.get::<UserSettings>(Some(SettingsLocation {
1695 worktree_id: WorktreeId::from_usize(1),
1696 path: Path::new("/root1/subdir/something")
1697 })),
1698 &UserSettings {
1699 name: "Jane Doe".to_string(),
1700 age: 31,
1701 staff: true
1702 }
1703 );
1704 assert_eq!(
1705 store.get::<UserSettings>(Some(SettingsLocation {
1706 worktree_id: WorktreeId::from_usize(1),
1707 path: Path::new("/root2/something")
1708 })),
1709 &UserSettings {
1710 name: "John Doe".to_string(),
1711 age: 42,
1712 staff: false
1713 }
1714 );
1715 assert_eq!(
1716 store.get::<MultiKeySettings>(Some(SettingsLocation {
1717 worktree_id: WorktreeId::from_usize(1),
1718 path: Path::new("/root2/something")
1719 })),
1720 &MultiKeySettings {
1721 key1: "a".to_string(),
1722 key2: "b".to_string(),
1723 }
1724 );
1725 }
1726
1727 #[gpui::test]
1728 fn test_setting_store_assign_json_before_register(cx: &mut App) {
1729 let mut store = SettingsStore::new(cx);
1730 store
1731 .set_default_settings(
1732 r#"{
1733 "turbo": true,
1734 "user": {
1735 "name": "John Doe",
1736 "age": 30,
1737 "staff": false
1738 },
1739 "key1": "x"
1740 }"#,
1741 cx,
1742 )
1743 .unwrap();
1744 store
1745 .set_user_settings(r#"{ "turbo": false }"#, cx)
1746 .unwrap();
1747 store.register_setting::<UserSettings>(cx);
1748 store.register_setting::<TurboSetting>(cx);
1749
1750 assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1751 assert_eq!(
1752 store.get::<UserSettings>(None),
1753 &UserSettings {
1754 name: "John Doe".to_string(),
1755 age: 30,
1756 staff: false,
1757 }
1758 );
1759
1760 store.register_setting::<MultiKeySettings>(cx);
1761 assert_eq!(
1762 store.get::<MultiKeySettings>(None),
1763 &MultiKeySettings {
1764 key1: "x".into(),
1765 key2: String::new(),
1766 }
1767 );
1768 }
1769
1770 fn check_settings_update<T: Settings>(
1771 store: &mut SettingsStore,
1772 old_json: String,
1773 update: fn(&mut T::FileContent),
1774 expected_new_json: String,
1775 cx: &mut App,
1776 ) {
1777 store.set_user_settings(&old_json, cx).ok();
1778 let edits = store.edits_for_update::<T>(&old_json, update);
1779 let mut new_json = old_json;
1780 for (range, replacement) in edits.into_iter() {
1781 new_json.replace_range(range, &replacement);
1782 }
1783 pretty_assertions::assert_eq!(new_json, expected_new_json);
1784 }
1785
1786 #[gpui::test]
1787 fn test_setting_store_update(cx: &mut App) {
1788 let mut store = SettingsStore::new(cx);
1789 store.register_setting::<MultiKeySettings>(cx);
1790 store.register_setting::<UserSettings>(cx);
1791 store.register_setting::<LanguageSettings>(cx);
1792
1793 // entries added and updated
1794 check_settings_update::<LanguageSettings>(
1795 &mut store,
1796 r#"{
1797 "languages": {
1798 "JSON": {
1799 "language_setting_1": true
1800 }
1801 }
1802 }"#
1803 .unindent(),
1804 |settings| {
1805 settings
1806 .languages
1807 .get_mut("JSON")
1808 .unwrap()
1809 .language_setting_1 = Some(false);
1810 settings.languages.insert(
1811 "Rust".into(),
1812 LanguageSettingEntry {
1813 language_setting_2: Some(true),
1814 ..Default::default()
1815 },
1816 );
1817 },
1818 r#"{
1819 "languages": {
1820 "Rust": {
1821 "language_setting_2": true
1822 },
1823 "JSON": {
1824 "language_setting_1": false
1825 }
1826 }
1827 }"#
1828 .unindent(),
1829 cx,
1830 );
1831
1832 // entries removed
1833 check_settings_update::<LanguageSettings>(
1834 &mut store,
1835 r#"{
1836 "languages": {
1837 "Rust": {
1838 "language_setting_2": true
1839 },
1840 "JSON": {
1841 "language_setting_1": false
1842 }
1843 }
1844 }"#
1845 .unindent(),
1846 |settings| {
1847 settings.languages.remove("JSON").unwrap();
1848 },
1849 r#"{
1850 "languages": {
1851 "Rust": {
1852 "language_setting_2": true
1853 }
1854 }
1855 }"#
1856 .unindent(),
1857 cx,
1858 );
1859
1860 check_settings_update::<LanguageSettings>(
1861 &mut store,
1862 r#"{
1863 "languages": {
1864 "Rust": {
1865 "language_setting_2": true
1866 },
1867 "JSON": {
1868 "language_setting_1": false
1869 }
1870 }
1871 }"#
1872 .unindent(),
1873 |settings| {
1874 settings.languages.remove("Rust").unwrap();
1875 },
1876 r#"{
1877 "languages": {
1878 "JSON": {
1879 "language_setting_1": false
1880 }
1881 }
1882 }"#
1883 .unindent(),
1884 cx,
1885 );
1886
1887 // weird formatting
1888 check_settings_update::<UserSettings>(
1889 &mut store,
1890 r#"{
1891 "user": { "age": 36, "name": "Max", "staff": true }
1892 }"#
1893 .unindent(),
1894 |settings| settings.age = Some(37),
1895 r#"{
1896 "user": { "age": 37, "name": "Max", "staff": true }
1897 }"#
1898 .unindent(),
1899 cx,
1900 );
1901
1902 // single-line formatting, other keys
1903 check_settings_update::<MultiKeySettings>(
1904 &mut store,
1905 r#"{ "one": 1, "two": 2 }"#.unindent(),
1906 |settings| settings.key1 = Some("x".into()),
1907 r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1908 cx,
1909 );
1910
1911 // empty object
1912 check_settings_update::<UserSettings>(
1913 &mut store,
1914 r#"{
1915 "user": {}
1916 }"#
1917 .unindent(),
1918 |settings| settings.age = Some(37),
1919 r#"{
1920 "user": {
1921 "age": 37
1922 }
1923 }"#
1924 .unindent(),
1925 cx,
1926 );
1927
1928 // no content
1929 check_settings_update::<UserSettings>(
1930 &mut store,
1931 r#""#.unindent(),
1932 |settings| settings.age = Some(37),
1933 r#"{
1934 "user": {
1935 "age": 37
1936 }
1937 }
1938 "#
1939 .unindent(),
1940 cx,
1941 );
1942
1943 check_settings_update::<UserSettings>(
1944 &mut store,
1945 r#"{
1946 }
1947 "#
1948 .unindent(),
1949 |settings| settings.age = Some(37),
1950 r#"{
1951 "user": {
1952 "age": 37
1953 }
1954 }
1955 "#
1956 .unindent(),
1957 cx,
1958 );
1959 }
1960
1961 #[gpui::test]
1962 fn test_vscode_import(cx: &mut App) {
1963 let mut store = SettingsStore::new(cx);
1964 store.register_setting::<UserSettings>(cx);
1965 store.register_setting::<JournalSettings>(cx);
1966 store.register_setting::<LanguageSettings>(cx);
1967 store.register_setting::<MultiKeySettings>(cx);
1968
1969 // create settings that werent present
1970 check_vscode_import(
1971 &mut store,
1972 r#"{
1973 }
1974 "#
1975 .unindent(),
1976 r#" { "user.age": 37 } "#.to_owned(),
1977 r#"{
1978 "user": {
1979 "age": 37
1980 }
1981 }
1982 "#
1983 .unindent(),
1984 cx,
1985 );
1986
1987 // persist settings that were present
1988 check_vscode_import(
1989 &mut store,
1990 r#"{
1991 "user": {
1992 "staff": true,
1993 "age": 37
1994 }
1995 }
1996 "#
1997 .unindent(),
1998 r#"{ "user.age": 42 }"#.to_owned(),
1999 r#"{
2000 "user": {
2001 "staff": true,
2002 "age": 42
2003 }
2004 }
2005 "#
2006 .unindent(),
2007 cx,
2008 );
2009
2010 // don't clobber settings that aren't present in vscode
2011 check_vscode_import(
2012 &mut store,
2013 r#"{
2014 "user": {
2015 "staff": true,
2016 "age": 37
2017 }
2018 }
2019 "#
2020 .unindent(),
2021 r#"{}"#.to_owned(),
2022 r#"{
2023 "user": {
2024 "staff": true,
2025 "age": 37
2026 }
2027 }
2028 "#
2029 .unindent(),
2030 cx,
2031 );
2032
2033 // custom enum
2034 check_vscode_import(
2035 &mut store,
2036 r#"{
2037 "journal": {
2038 "hour_format": "hour12"
2039 }
2040 }
2041 "#
2042 .unindent(),
2043 r#"{ "time_format": "24" }"#.to_owned(),
2044 r#"{
2045 "journal": {
2046 "hour_format": "hour24"
2047 }
2048 }
2049 "#
2050 .unindent(),
2051 cx,
2052 );
2053
2054 // Multiple keys for one setting
2055 check_vscode_import(
2056 &mut store,
2057 r#"{
2058 "key1": "value"
2059 }
2060 "#
2061 .unindent(),
2062 r#"{
2063 "key_1_first": "hello",
2064 "key_1_second": "world"
2065 }"#
2066 .to_owned(),
2067 r#"{
2068 "key1": "hello world"
2069 }
2070 "#
2071 .unindent(),
2072 cx,
2073 );
2074
2075 // Merging lists together entries added and updated
2076 check_vscode_import(
2077 &mut store,
2078 r#"{
2079 "languages": {
2080 "JSON": {
2081 "language_setting_1": true
2082 },
2083 "Rust": {
2084 "language_setting_2": true
2085 }
2086 }
2087 }"#
2088 .unindent(),
2089 r#"{
2090 "vscode_languages": [
2091 {
2092 "name": "JavaScript",
2093 "language_setting_1": true
2094 },
2095 {
2096 "name": "Rust",
2097 "language_setting_2": false
2098 }
2099 ]
2100 }"#
2101 .to_owned(),
2102 r#"{
2103 "languages": {
2104 "JavaScript": {
2105 "language_setting_1": true
2106 },
2107 "JSON": {
2108 "language_setting_1": true
2109 },
2110 "Rust": {
2111 "language_setting_2": false
2112 }
2113 }
2114 }"#
2115 .unindent(),
2116 cx,
2117 );
2118 }
2119
2120 fn check_vscode_import(
2121 store: &mut SettingsStore,
2122 old: String,
2123 vscode: String,
2124 expected: String,
2125 cx: &mut App,
2126 ) {
2127 store.set_user_settings(&old, cx).ok();
2128 let new = store.get_vscode_edits(
2129 old,
2130 &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
2131 );
2132 pretty_assertions::assert_eq!(new, expected);
2133 }
2134
2135 #[derive(Debug, PartialEq, Deserialize, SettingsUi)]
2136 struct UserSettings {
2137 name: String,
2138 age: u32,
2139 staff: bool,
2140 }
2141
2142 #[derive(Default, Clone, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey)]
2143 #[settings_key(key = "user")]
2144 struct UserSettingsContent {
2145 name: Option<String>,
2146 age: Option<u32>,
2147 staff: Option<bool>,
2148 }
2149
2150 impl Settings for UserSettings {
2151 type FileContent = UserSettingsContent;
2152
2153 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2154 sources.json_merge()
2155 }
2156
2157 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2158 vscode.u32_setting("user.age", &mut current.age);
2159 }
2160 }
2161
2162 #[derive(Debug, Deserialize, PartialEq)]
2163 struct TurboSetting(bool);
2164
2165 #[derive(
2166 Copy,
2167 Clone,
2168 PartialEq,
2169 Eq,
2170 Debug,
2171 Default,
2172 serde::Serialize,
2173 serde::Deserialize,
2174 SettingsUi,
2175 SettingsKey,
2176 JsonSchema,
2177 )]
2178 #[serde(default)]
2179 #[settings_key(None)]
2180 pub struct TurboSettingContent {
2181 turbo: Option<bool>,
2182 }
2183
2184 impl Settings for TurboSetting {
2185 type FileContent = TurboSettingContent;
2186
2187 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2188 Ok(Self(
2189 sources
2190 .user
2191 .or(sources.server)
2192 .unwrap_or(sources.default)
2193 .turbo
2194 .unwrap_or_default(),
2195 ))
2196 }
2197
2198 fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2199 }
2200
2201 #[derive(Clone, Debug, PartialEq, Deserialize)]
2202 struct MultiKeySettings {
2203 #[serde(default)]
2204 key1: String,
2205 #[serde(default)]
2206 key2: String,
2207 }
2208
2209 #[derive(Clone, Default, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey)]
2210 #[settings_key(None)]
2211 struct MultiKeySettingsJson {
2212 key1: Option<String>,
2213 key2: Option<String>,
2214 }
2215
2216 impl Settings for MultiKeySettings {
2217 type FileContent = MultiKeySettingsJson;
2218
2219 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2220 sources.json_merge()
2221 }
2222
2223 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2224 let first_value = vscode.read_string("key_1_first");
2225 let second_value = vscode.read_string("key_1_second");
2226
2227 if let Some((first, second)) = first_value.zip(second_value) {
2228 current.key1 = Some(format!("{} {}", first, second));
2229 }
2230 }
2231 }
2232
2233 #[derive(Debug, Deserialize)]
2234 struct JournalSettings {
2235 pub path: String,
2236 pub hour_format: HourFormat,
2237 }
2238
2239 #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2240 #[serde(rename_all = "snake_case")]
2241 enum HourFormat {
2242 Hour12,
2243 Hour24,
2244 }
2245
2246 #[derive(
2247 Clone, Default, Debug, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey,
2248 )]
2249 #[settings_key(key = "journal")]
2250 struct JournalSettingsJson {
2251 pub path: Option<String>,
2252 pub hour_format: Option<HourFormat>,
2253 }
2254
2255 impl Settings for JournalSettings {
2256 type FileContent = JournalSettingsJson;
2257
2258 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2259 sources.json_merge()
2260 }
2261
2262 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2263 vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2264 "12" => Some(HourFormat::Hour12),
2265 "24" => Some(HourFormat::Hour24),
2266 _ => None,
2267 });
2268 }
2269 }
2270
2271 #[gpui::test]
2272 fn test_global_settings(cx: &mut App) {
2273 let mut store = SettingsStore::new(cx);
2274 store.register_setting::<UserSettings>(cx);
2275 store
2276 .set_default_settings(
2277 r#"{
2278 "user": {
2279 "name": "John Doe",
2280 "age": 30,
2281 "staff": false
2282 }
2283 }"#,
2284 cx,
2285 )
2286 .unwrap();
2287
2288 // Set global settings - these should override defaults but not user settings
2289 store
2290 .set_global_settings(
2291 r#"{
2292 "user": {
2293 "name": "Global User",
2294 "age": 35,
2295 "staff": true
2296 }
2297 }"#,
2298 cx,
2299 )
2300 .unwrap();
2301
2302 // Before user settings, global settings should apply
2303 assert_eq!(
2304 store.get::<UserSettings>(None),
2305 &UserSettings {
2306 name: "Global User".to_string(),
2307 age: 35,
2308 staff: true,
2309 }
2310 );
2311
2312 // Set user settings - these should override both defaults and global
2313 store
2314 .set_user_settings(
2315 r#"{
2316 "user": {
2317 "age": 40
2318 }
2319 }"#,
2320 cx,
2321 )
2322 .unwrap();
2323
2324 // User settings should override global settings
2325 assert_eq!(
2326 store.get::<UserSettings>(None),
2327 &UserSettings {
2328 name: "Global User".to_string(), // Name from global settings
2329 age: 40, // Age from user settings
2330 staff: true, // Staff from global settings
2331 }
2332 );
2333 }
2334
2335 #[derive(
2336 Clone, Debug, Default, Serialize, Deserialize, JsonSchema, SettingsUi, SettingsKey,
2337 )]
2338 #[settings_key(None)]
2339 struct LanguageSettings {
2340 #[serde(default)]
2341 languages: HashMap<String, LanguageSettingEntry>,
2342 }
2343
2344 #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2345 struct LanguageSettingEntry {
2346 language_setting_1: Option<bool>,
2347 language_setting_2: Option<bool>,
2348 }
2349
2350 impl Settings for LanguageSettings {
2351 type FileContent = Self;
2352
2353 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2354 sources.json_merge()
2355 }
2356
2357 fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2358 current.languages.extend(
2359 vscode
2360 .read_value("vscode_languages")
2361 .and_then(|value| value.as_array())
2362 .map(|languages| {
2363 languages
2364 .iter()
2365 .filter_map(|value| value.as_object())
2366 .filter_map(|item| {
2367 let mut rest = item.clone();
2368 let name = rest.remove("name")?.as_str()?.to_string();
2369 let entry = serde_json::from_value::<LanguageSettingEntry>(
2370 serde_json::Value::Object(rest),
2371 )
2372 .ok()?;
2373
2374 Some((name, entry))
2375 })
2376 })
2377 .into_iter()
2378 .flatten(),
2379 );
2380 }
2381 }
2382}