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