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