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