settings_store.rs

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