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