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