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