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