settings_store.rs

   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 schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
   7use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
   8use smallvec::SmallVec;
   9use std::{
  10    any::{type_name, Any, TypeId},
  11    fmt::Debug,
  12    ops::Range,
  13    path::Path,
  14    str,
  15    sync::{Arc, LazyLock},
  16};
  17use tree_sitter::Query;
  18use tree_sitter_json::language;
  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 = setting_value
 699                .deserialize_setting(&self.raw_user_settings)
 700                .log_err();
 701
 702            let mut release_channel_settings = None;
 703            if let Some(release_settings) = &self
 704                .raw_user_settings
 705                .get(release_channel::RELEASE_CHANNEL.dev_name())
 706            {
 707                if let Some(release_settings) = setting_value
 708                    .deserialize_setting(release_settings)
 709                    .log_err()
 710                {
 711                    release_channel_settings = Some(release_settings);
 712                }
 713            }
 714
 715            // If the global settings file changed, reload the global value for the field.
 716            if changed_local_path.is_none() {
 717                if let Some(value) = setting_value
 718                    .load_setting(
 719                        SettingsSources {
 720                            default: &default_settings,
 721                            extensions: extension_settings.as_ref(),
 722                            user: user_settings.as_ref(),
 723                            release_channel: release_channel_settings.as_ref(),
 724                            project: &[],
 725                        },
 726                        cx,
 727                    )
 728                    .log_err()
 729                {
 730                    setting_value.set_global_value(value);
 731                }
 732            }
 733
 734            // Reload the local values for the setting.
 735            paths_stack.clear();
 736            project_settings_stack.clear();
 737            for ((root_id, path), local_settings) in &self.raw_local_settings {
 738                // Build a stack of all of the local values for that setting.
 739                while let Some(prev_entry) = paths_stack.last() {
 740                    if let Some((prev_root_id, prev_path)) = prev_entry {
 741                        if root_id != prev_root_id || !path.starts_with(prev_path) {
 742                            paths_stack.pop();
 743                            project_settings_stack.pop();
 744                            continue;
 745                        }
 746                    }
 747                    break;
 748                }
 749
 750                if let Some(local_settings) =
 751                    setting_value.deserialize_setting(local_settings).log_err()
 752                {
 753                    paths_stack.push(Some((*root_id, path.as_ref())));
 754                    project_settings_stack.push(local_settings);
 755
 756                    // If a local settings file changed, then avoid recomputing local
 757                    // settings for any path outside of that directory.
 758                    if changed_local_path.map_or(false, |(changed_root_id, changed_local_path)| {
 759                        *root_id != changed_root_id || !path.starts_with(changed_local_path)
 760                    }) {
 761                        continue;
 762                    }
 763
 764                    if let Some(value) = setting_value
 765                        .load_setting(
 766                            SettingsSources {
 767                                default: &default_settings,
 768                                extensions: extension_settings.as_ref(),
 769                                user: user_settings.as_ref(),
 770                                release_channel: release_channel_settings.as_ref(),
 771                                project: &project_settings_stack.iter().collect::<Vec<_>>(),
 772                            },
 773                            cx,
 774                        )
 775                        .log_err()
 776                    {
 777                        setting_value.set_local_value(*root_id, path.clone(), value);
 778                    }
 779                }
 780            }
 781        }
 782        Ok(())
 783    }
 784}
 785
 786impl Debug for SettingsStore {
 787    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 788        f.debug_struct("SettingsStore")
 789            .field(
 790                "types",
 791                &self
 792                    .setting_values
 793                    .values()
 794                    .map(|value| value.setting_type_name())
 795                    .collect::<Vec<_>>(),
 796            )
 797            .field("default_settings", &self.raw_default_settings)
 798            .field("user_settings", &self.raw_user_settings)
 799            .field("local_settings", &self.raw_local_settings)
 800            .finish_non_exhaustive()
 801    }
 802}
 803
 804impl<T: Settings> AnySettingValue for SettingValue<T> {
 805    fn key(&self) -> Option<&'static str> {
 806        T::KEY
 807    }
 808
 809    fn setting_type_name(&self) -> &'static str {
 810        type_name::<T>()
 811    }
 812
 813    fn load_setting(
 814        &self,
 815        values: SettingsSources<DeserializedSetting>,
 816        cx: &mut AppContext,
 817    ) -> Result<Box<dyn Any>> {
 818        Ok(Box::new(T::load(
 819            SettingsSources {
 820                default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
 821                extensions: values
 822                    .extensions
 823                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 824                user: values
 825                    .user
 826                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 827                release_channel: values
 828                    .release_channel
 829                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 830                project: values
 831                    .project
 832                    .iter()
 833                    .map(|value| value.0.downcast_ref().unwrap())
 834                    .collect::<SmallVec<[_; 3]>>()
 835                    .as_slice(),
 836            },
 837            cx,
 838        )?))
 839    }
 840
 841    fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
 842        if let Some(key) = T::KEY {
 843            if let Some(value) = json.get(key) {
 844                json = value;
 845            } else {
 846                let value = T::FileContent::default();
 847                return Ok(DeserializedSetting(Box::new(value)));
 848            }
 849        }
 850        let value = T::FileContent::deserialize(json)?;
 851        Ok(DeserializedSetting(Box::new(value)))
 852    }
 853
 854    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
 855        if let Some(SettingsLocation { worktree_id, path }) = path {
 856            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
 857                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
 858                    return value;
 859                }
 860            }
 861        }
 862        self.global_value
 863            .as_ref()
 864            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
 865    }
 866
 867    fn set_global_value(&mut self, value: Box<dyn Any>) {
 868        self.global_value = Some(*value.downcast().unwrap());
 869    }
 870
 871    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<Path>, value: Box<dyn Any>) {
 872        let value = *value.downcast().unwrap();
 873        match self
 874            .local_values
 875            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
 876        {
 877            Ok(ix) => self.local_values[ix].2 = value,
 878            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
 879        }
 880    }
 881
 882    fn json_schema(
 883        &self,
 884        generator: &mut SchemaGenerator,
 885        params: &SettingsJsonSchemaParams,
 886        cx: &AppContext,
 887    ) -> RootSchema {
 888        T::json_schema(generator, params, cx)
 889    }
 890}
 891
 892fn update_value_in_json_text<'a>(
 893    text: &mut String,
 894    key_path: &mut Vec<&'a str>,
 895    tab_size: usize,
 896    old_value: &'a serde_json::Value,
 897    new_value: &'a serde_json::Value,
 898    preserved_keys: &[&str],
 899    edits: &mut Vec<(Range<usize>, String)>,
 900) {
 901    // If the old and new values are both objects, then compare them key by key,
 902    // preserving the comments and formatting of the unchanged parts. Otherwise,
 903    // replace the old value with the new value.
 904    if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
 905        (old_value, new_value)
 906    {
 907        for (key, old_sub_value) in old_object.iter() {
 908            key_path.push(key);
 909            let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
 910            update_value_in_json_text(
 911                text,
 912                key_path,
 913                tab_size,
 914                old_sub_value,
 915                new_sub_value,
 916                preserved_keys,
 917                edits,
 918            );
 919            key_path.pop();
 920        }
 921        for (key, new_sub_value) in new_object.iter() {
 922            key_path.push(key);
 923            if !old_object.contains_key(key) {
 924                update_value_in_json_text(
 925                    text,
 926                    key_path,
 927                    tab_size,
 928                    &serde_json::Value::Null,
 929                    new_sub_value,
 930                    preserved_keys,
 931                    edits,
 932                );
 933            }
 934            key_path.pop();
 935        }
 936    } else if key_path
 937        .last()
 938        .map_or(false, |key| preserved_keys.contains(key))
 939        || old_value != new_value
 940    {
 941        let mut new_value = new_value.clone();
 942        if let Some(new_object) = new_value.as_object_mut() {
 943            new_object.retain(|_, v| !v.is_null());
 944        }
 945        let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
 946        text.replace_range(range.clone(), &replacement);
 947        edits.push((range, replacement));
 948    }
 949}
 950
 951fn replace_value_in_json_text(
 952    text: &str,
 953    key_path: &[&str],
 954    tab_size: usize,
 955    new_value: &serde_json::Value,
 956) -> (Range<usize>, String) {
 957    static PAIR_QUERY: LazyLock<Query> = LazyLock::new(|| {
 958        Query::new(&language(), "(pair key: (string) @key value: (_) @value)")
 959            .expect("Failed to create PAIR_QUERY")
 960    });
 961
 962    let mut parser = tree_sitter::Parser::new();
 963    parser.set_language(&tree_sitter_json::language()).unwrap();
 964    let syntax_tree = parser.parse(text, None).unwrap();
 965
 966    let mut cursor = tree_sitter::QueryCursor::new();
 967
 968    let mut depth = 0;
 969    let mut last_value_range = 0..0;
 970    let mut first_key_start = None;
 971    let mut existing_value_range = 0..text.len();
 972    let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
 973    for mat in matches {
 974        if mat.captures.len() != 2 {
 975            continue;
 976        }
 977
 978        let key_range = mat.captures[0].node.byte_range();
 979        let value_range = mat.captures[1].node.byte_range();
 980
 981        // Don't enter sub objects until we find an exact
 982        // match for the current keypath
 983        if last_value_range.contains_inclusive(&value_range) {
 984            continue;
 985        }
 986
 987        last_value_range = value_range.clone();
 988
 989        if key_range.start > existing_value_range.end {
 990            break;
 991        }
 992
 993        first_key_start.get_or_insert(key_range.start);
 994
 995        let found_key = text
 996            .get(key_range.clone())
 997            .map(|key_text| key_text == format!("\"{}\"", key_path[depth]))
 998            .unwrap_or(false);
 999
1000        if found_key {
1001            existing_value_range = value_range;
1002            // Reset last value range when increasing in depth
1003            last_value_range = existing_value_range.start..existing_value_range.start;
1004            depth += 1;
1005
1006            if depth == key_path.len() {
1007                break;
1008            }
1009
1010            first_key_start = None;
1011        }
1012    }
1013
1014    // We found the exact key we want, insert the new value
1015    if depth == key_path.len() {
1016        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
1017        (existing_value_range, new_val)
1018    } else {
1019        // We have key paths, construct the sub objects
1020        let new_key = key_path[depth];
1021
1022        // We don't have the key, construct the nested objects
1023        let mut new_value = serde_json::to_value(new_value).unwrap();
1024        for key in key_path[(depth + 1)..].iter().rev() {
1025            new_value = serde_json::json!({ key.to_string(): new_value });
1026        }
1027
1028        if let Some(first_key_start) = first_key_start {
1029            let mut row = 0;
1030            let mut column = 0;
1031            for (ix, char) in text.char_indices() {
1032                if ix == first_key_start {
1033                    break;
1034                }
1035                if char == '\n' {
1036                    row += 1;
1037                    column = 0;
1038                } else {
1039                    column += char.len_utf8();
1040                }
1041            }
1042
1043            if row > 0 {
1044                // depth is 0 based, but division needs to be 1 based.
1045                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1046                let space = ' ';
1047                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1048                (first_key_start..first_key_start, content)
1049            } else {
1050                let new_val = serde_json::to_string(&new_value).unwrap();
1051                let mut content = format!(r#""{new_key}": {new_val},"#);
1052                content.push(' ');
1053                (first_key_start..first_key_start, content)
1054            }
1055        } else {
1056            new_value = serde_json::json!({ new_key.to_string(): new_value });
1057            let indent_prefix_len = 4 * depth;
1058            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1059            if depth == 0 {
1060                new_val.push('\n');
1061            }
1062
1063            (existing_value_range, new_val)
1064        }
1065    }
1066}
1067
1068fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1069    const SPACES: [u8; 32] = [b' '; 32];
1070
1071    debug_assert!(indent_size <= SPACES.len());
1072    debug_assert!(indent_prefix_len <= SPACES.len());
1073
1074    let mut output = Vec::new();
1075    let mut ser = serde_json::Serializer::with_formatter(
1076        &mut output,
1077        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1078    );
1079
1080    value.serialize(&mut ser).unwrap();
1081    let text = String::from_utf8(output).unwrap();
1082
1083    let mut adjusted_text = String::new();
1084    for (i, line) in text.split('\n').enumerate() {
1085        if i > 0 {
1086            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1087        }
1088        adjusted_text.push_str(line);
1089        adjusted_text.push('\n');
1090    }
1091    adjusted_text.pop();
1092    adjusted_text
1093}
1094
1095pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1096    Ok(serde_json_lenient::from_str(content)?)
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101    use super::*;
1102    use serde_derive::Deserialize;
1103    use unindent::Unindent;
1104
1105    #[gpui::test]
1106    fn test_settings_store_basic(cx: &mut AppContext) {
1107        let mut store = SettingsStore::new(cx);
1108        store.register_setting::<UserSettings>(cx);
1109        store.register_setting::<TurboSetting>(cx);
1110        store.register_setting::<MultiKeySettings>(cx);
1111        store
1112            .set_default_settings(
1113                r#"{
1114                    "turbo": false,
1115                    "user": {
1116                        "name": "John Doe",
1117                        "age": 30,
1118                        "staff": false
1119                    }
1120                }"#,
1121                cx,
1122            )
1123            .unwrap();
1124
1125        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1126        assert_eq!(
1127            store.get::<UserSettings>(None),
1128            &UserSettings {
1129                name: "John Doe".to_string(),
1130                age: 30,
1131                staff: false,
1132            }
1133        );
1134        assert_eq!(
1135            store.get::<MultiKeySettings>(None),
1136            &MultiKeySettings {
1137                key1: String::new(),
1138                key2: String::new(),
1139            }
1140        );
1141
1142        store
1143            .set_user_settings(
1144                r#"{
1145                    "turbo": true,
1146                    "user": { "age": 31 },
1147                    "key1": "a"
1148                }"#,
1149                cx,
1150            )
1151            .unwrap();
1152
1153        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1154        assert_eq!(
1155            store.get::<UserSettings>(None),
1156            &UserSettings {
1157                name: "John Doe".to_string(),
1158                age: 31,
1159                staff: false
1160            }
1161        );
1162
1163        store
1164            .set_local_settings(
1165                WorktreeId::from_usize(1),
1166                Path::new("/root1").into(),
1167                Some(r#"{ "user": { "staff": true } }"#),
1168                cx,
1169            )
1170            .unwrap();
1171        store
1172            .set_local_settings(
1173                WorktreeId::from_usize(1),
1174                Path::new("/root1/subdir").into(),
1175                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1176                cx,
1177            )
1178            .unwrap();
1179
1180        store
1181            .set_local_settings(
1182                WorktreeId::from_usize(1),
1183                Path::new("/root2").into(),
1184                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1185                cx,
1186            )
1187            .unwrap();
1188
1189        assert_eq!(
1190            store.get::<UserSettings>(Some(SettingsLocation {
1191                worktree_id: WorktreeId::from_usize(1),
1192                path: Path::new("/root1/something"),
1193            })),
1194            &UserSettings {
1195                name: "John Doe".to_string(),
1196                age: 31,
1197                staff: true
1198            }
1199        );
1200        assert_eq!(
1201            store.get::<UserSettings>(Some(SettingsLocation {
1202                worktree_id: WorktreeId::from_usize(1),
1203                path: Path::new("/root1/subdir/something")
1204            })),
1205            &UserSettings {
1206                name: "Jane Doe".to_string(),
1207                age: 31,
1208                staff: true
1209            }
1210        );
1211        assert_eq!(
1212            store.get::<UserSettings>(Some(SettingsLocation {
1213                worktree_id: WorktreeId::from_usize(1),
1214                path: Path::new("/root2/something")
1215            })),
1216            &UserSettings {
1217                name: "John Doe".to_string(),
1218                age: 42,
1219                staff: false
1220            }
1221        );
1222        assert_eq!(
1223            store.get::<MultiKeySettings>(Some(SettingsLocation {
1224                worktree_id: WorktreeId::from_usize(1),
1225                path: Path::new("/root2/something")
1226            })),
1227            &MultiKeySettings {
1228                key1: "a".to_string(),
1229                key2: "b".to_string(),
1230            }
1231        );
1232    }
1233
1234    #[gpui::test]
1235    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1236        let mut store = SettingsStore::new(cx);
1237        store
1238            .set_default_settings(
1239                r#"{
1240                    "turbo": true,
1241                    "user": {
1242                        "name": "John Doe",
1243                        "age": 30,
1244                        "staff": false
1245                    },
1246                    "key1": "x"
1247                }"#,
1248                cx,
1249            )
1250            .unwrap();
1251        store
1252            .set_user_settings(r#"{ "turbo": false }"#, cx)
1253            .unwrap();
1254        store.register_setting::<UserSettings>(cx);
1255        store.register_setting::<TurboSetting>(cx);
1256
1257        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1258        assert_eq!(
1259            store.get::<UserSettings>(None),
1260            &UserSettings {
1261                name: "John Doe".to_string(),
1262                age: 30,
1263                staff: false,
1264            }
1265        );
1266
1267        store.register_setting::<MultiKeySettings>(cx);
1268        assert_eq!(
1269            store.get::<MultiKeySettings>(None),
1270            &MultiKeySettings {
1271                key1: "x".into(),
1272                key2: String::new(),
1273            }
1274        );
1275    }
1276
1277    #[gpui::test]
1278    fn test_setting_store_update(cx: &mut AppContext) {
1279        let mut store = SettingsStore::new(cx);
1280        store.register_setting::<MultiKeySettings>(cx);
1281        store.register_setting::<UserSettings>(cx);
1282        store.register_setting::<LanguageSettings>(cx);
1283
1284        // entries added and updated
1285        check_settings_update::<LanguageSettings>(
1286            &mut store,
1287            r#"{
1288                "languages": {
1289                    "JSON": {
1290                        "language_setting_1": true
1291                    }
1292                }
1293            }"#
1294            .unindent(),
1295            |settings| {
1296                settings
1297                    .languages
1298                    .get_mut("JSON")
1299                    .unwrap()
1300                    .language_setting_1 = Some(false);
1301                settings.languages.insert(
1302                    "Rust".into(),
1303                    LanguageSettingEntry {
1304                        language_setting_2: Some(true),
1305                        ..Default::default()
1306                    },
1307                );
1308            },
1309            r#"{
1310                "languages": {
1311                    "Rust": {
1312                        "language_setting_2": true
1313                    },
1314                    "JSON": {
1315                        "language_setting_1": false
1316                    }
1317                }
1318            }"#
1319            .unindent(),
1320            cx,
1321        );
1322
1323        // weird formatting
1324        check_settings_update::<UserSettings>(
1325            &mut store,
1326            r#"{
1327                "user":   { "age": 36, "name": "Max", "staff": true }
1328            }"#
1329            .unindent(),
1330            |settings| settings.age = Some(37),
1331            r#"{
1332                "user":   { "age": 37, "name": "Max", "staff": true }
1333            }"#
1334            .unindent(),
1335            cx,
1336        );
1337
1338        // single-line formatting, other keys
1339        check_settings_update::<MultiKeySettings>(
1340            &mut store,
1341            r#"{ "one": 1, "two": 2 }"#.unindent(),
1342            |settings| settings.key1 = Some("x".into()),
1343            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1344            cx,
1345        );
1346
1347        // empty object
1348        check_settings_update::<UserSettings>(
1349            &mut store,
1350            r#"{
1351                "user": {}
1352            }"#
1353            .unindent(),
1354            |settings| settings.age = Some(37),
1355            r#"{
1356                "user": {
1357                    "age": 37
1358                }
1359            }"#
1360            .unindent(),
1361            cx,
1362        );
1363
1364        // no content
1365        check_settings_update::<UserSettings>(
1366            &mut store,
1367            r#""#.unindent(),
1368            |settings| settings.age = Some(37),
1369            r#"{
1370                "user": {
1371                    "age": 37
1372                }
1373            }
1374            "#
1375            .unindent(),
1376            cx,
1377        );
1378
1379        check_settings_update::<UserSettings>(
1380            &mut store,
1381            r#"{
1382            }
1383            "#
1384            .unindent(),
1385            |settings| settings.age = Some(37),
1386            r#"{
1387                "user": {
1388                    "age": 37
1389                }
1390            }
1391            "#
1392            .unindent(),
1393            cx,
1394        );
1395    }
1396
1397    fn check_settings_update<T: Settings>(
1398        store: &mut SettingsStore,
1399        old_json: String,
1400        update: fn(&mut T::FileContent),
1401        expected_new_json: String,
1402        cx: &mut AppContext,
1403    ) {
1404        store.set_user_settings(&old_json, cx).ok();
1405        let edits = store.edits_for_update::<T>(&old_json, update);
1406        let mut new_json = old_json;
1407        for (range, replacement) in edits.into_iter() {
1408            new_json.replace_range(range, &replacement);
1409        }
1410        pretty_assertions::assert_eq!(new_json, expected_new_json);
1411    }
1412
1413    #[derive(Debug, PartialEq, Deserialize)]
1414    struct UserSettings {
1415        name: String,
1416        age: u32,
1417        staff: bool,
1418    }
1419
1420    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1421    struct UserSettingsJson {
1422        name: Option<String>,
1423        age: Option<u32>,
1424        staff: Option<bool>,
1425    }
1426
1427    impl Settings for UserSettings {
1428        const KEY: Option<&'static str> = Some("user");
1429        type FileContent = UserSettingsJson;
1430
1431        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1432            sources.json_merge()
1433        }
1434    }
1435
1436    #[derive(Debug, Deserialize, PartialEq)]
1437    struct TurboSetting(bool);
1438
1439    impl Settings for TurboSetting {
1440        const KEY: Option<&'static str> = Some("turbo");
1441        type FileContent = Option<bool>;
1442
1443        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1444            sources.json_merge()
1445        }
1446    }
1447
1448    #[derive(Clone, Debug, PartialEq, Deserialize)]
1449    struct MultiKeySettings {
1450        #[serde(default)]
1451        key1: String,
1452        #[serde(default)]
1453        key2: String,
1454    }
1455
1456    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1457    struct MultiKeySettingsJson {
1458        key1: Option<String>,
1459        key2: Option<String>,
1460    }
1461
1462    impl Settings for MultiKeySettings {
1463        const KEY: Option<&'static str> = None;
1464
1465        type FileContent = MultiKeySettingsJson;
1466
1467        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1468            sources.json_merge()
1469        }
1470    }
1471
1472    #[derive(Debug, Deserialize)]
1473    struct JournalSettings {
1474        pub path: String,
1475        pub hour_format: HourFormat,
1476    }
1477
1478    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1479    #[serde(rename_all = "snake_case")]
1480    enum HourFormat {
1481        Hour12,
1482        Hour24,
1483    }
1484
1485    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1486    struct JournalSettingsJson {
1487        pub path: Option<String>,
1488        pub hour_format: Option<HourFormat>,
1489    }
1490
1491    impl Settings for JournalSettings {
1492        const KEY: Option<&'static str> = Some("journal");
1493
1494        type FileContent = JournalSettingsJson;
1495
1496        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1497            sources.json_merge()
1498        }
1499    }
1500
1501    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1502    struct LanguageSettings {
1503        #[serde(default)]
1504        languages: HashMap<String, LanguageSettingEntry>,
1505    }
1506
1507    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1508    struct LanguageSettingEntry {
1509        language_setting_1: Option<bool>,
1510        language_setting_2: Option<bool>,
1511    }
1512
1513    impl Settings for LanguageSettings {
1514        const KEY: Option<&'static str> = None;
1515
1516        type FileContent = Self;
1517
1518        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1519            sources.json_merge()
1520        }
1521    }
1522}