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            } else {
1500                // No preceding comma, check for trailing comma
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            }
1521            (removal_start..removal_end, String::new())
1522        }
1523    } else {
1524        // We have key paths, construct the sub objects
1525        let new_key = key_path[depth];
1526
1527        // We don't have the key, construct the nested objects
1528        let mut new_value =
1529            serde_json::to_value(new_value.unwrap_or(&serde_json::Value::Null)).unwrap();
1530        for key in key_path[(depth + 1)..].iter().rev() {
1531            new_value = serde_json::json!({ key.to_string(): new_value });
1532        }
1533
1534        if let Some(first_key_start) = first_key_start {
1535            let mut row = 0;
1536            let mut column = 0;
1537            for (ix, char) in text.char_indices() {
1538                if ix == first_key_start {
1539                    break;
1540                }
1541                if char == '\n' {
1542                    row += 1;
1543                    column = 0;
1544                } else {
1545                    column += char.len_utf8();
1546                }
1547            }
1548
1549            if row > 0 {
1550                // depth is 0 based, but division needs to be 1 based.
1551                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
1552                let space = ' ';
1553                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
1554                (first_key_start..first_key_start, content)
1555            } else {
1556                let new_val = serde_json::to_string(&new_value).unwrap();
1557                let mut content = format!(r#""{new_key}": {new_val},"#);
1558                content.push(' ');
1559                (first_key_start..first_key_start, content)
1560            }
1561        } else {
1562            new_value = serde_json::json!({ new_key.to_string(): new_value });
1563            let indent_prefix_len = 4 * depth;
1564            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
1565            if depth == 0 {
1566                new_val.push('\n');
1567            }
1568
1569            (existing_value_range, new_val)
1570        }
1571    }
1572}
1573
1574fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1575    const SPACES: [u8; 32] = [b' '; 32];
1576
1577    debug_assert!(indent_size <= SPACES.len());
1578    debug_assert!(indent_prefix_len <= SPACES.len());
1579
1580    let mut output = Vec::new();
1581    let mut ser = serde_json::Serializer::with_formatter(
1582        &mut output,
1583        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1584    );
1585
1586    value.serialize(&mut ser).unwrap();
1587    let text = String::from_utf8(output).unwrap();
1588
1589    let mut adjusted_text = String::new();
1590    for (i, line) in text.split('\n').enumerate() {
1591        if i > 0 {
1592            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1593        }
1594        adjusted_text.push_str(line);
1595        adjusted_text.push('\n');
1596    }
1597    adjusted_text.pop();
1598    adjusted_text
1599}
1600
1601pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1602    Ok(serde_json_lenient::from_str(content)?)
1603}
1604
1605#[cfg(test)]
1606mod tests {
1607    use crate::VsCodeSettingsSource;
1608
1609    use super::*;
1610    use serde_derive::Deserialize;
1611    use unindent::Unindent;
1612
1613    #[gpui::test]
1614    fn test_settings_store_basic(cx: &mut App) {
1615        let mut store = SettingsStore::new(cx);
1616        store.register_setting::<UserSettings>(cx);
1617        store.register_setting::<TurboSetting>(cx);
1618        store.register_setting::<MultiKeySettings>(cx);
1619        store
1620            .set_default_settings(
1621                r#"{
1622                    "turbo": false,
1623                    "user": {
1624                        "name": "John Doe",
1625                        "age": 30,
1626                        "staff": false
1627                    }
1628                }"#,
1629                cx,
1630            )
1631            .unwrap();
1632
1633        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1634        assert_eq!(
1635            store.get::<UserSettings>(None),
1636            &UserSettings {
1637                name: "John Doe".to_string(),
1638                age: 30,
1639                staff: false,
1640            }
1641        );
1642        assert_eq!(
1643            store.get::<MultiKeySettings>(None),
1644            &MultiKeySettings {
1645                key1: String::new(),
1646                key2: String::new(),
1647            }
1648        );
1649
1650        store
1651            .set_user_settings(
1652                r#"{
1653                    "turbo": true,
1654                    "user": { "age": 31 },
1655                    "key1": "a"
1656                }"#,
1657                cx,
1658            )
1659            .unwrap();
1660
1661        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1662        assert_eq!(
1663            store.get::<UserSettings>(None),
1664            &UserSettings {
1665                name: "John Doe".to_string(),
1666                age: 31,
1667                staff: false
1668            }
1669        );
1670
1671        store
1672            .set_local_settings(
1673                WorktreeId::from_usize(1),
1674                Path::new("/root1").into(),
1675                LocalSettingsKind::Settings,
1676                Some(r#"{ "user": { "staff": true } }"#),
1677                cx,
1678            )
1679            .unwrap();
1680        store
1681            .set_local_settings(
1682                WorktreeId::from_usize(1),
1683                Path::new("/root1/subdir").into(),
1684                LocalSettingsKind::Settings,
1685                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1686                cx,
1687            )
1688            .unwrap();
1689
1690        store
1691            .set_local_settings(
1692                WorktreeId::from_usize(1),
1693                Path::new("/root2").into(),
1694                LocalSettingsKind::Settings,
1695                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1696                cx,
1697            )
1698            .unwrap();
1699
1700        assert_eq!(
1701            store.get::<UserSettings>(Some(SettingsLocation {
1702                worktree_id: WorktreeId::from_usize(1),
1703                path: Path::new("/root1/something"),
1704            })),
1705            &UserSettings {
1706                name: "John Doe".to_string(),
1707                age: 31,
1708                staff: true
1709            }
1710        );
1711        assert_eq!(
1712            store.get::<UserSettings>(Some(SettingsLocation {
1713                worktree_id: WorktreeId::from_usize(1),
1714                path: Path::new("/root1/subdir/something")
1715            })),
1716            &UserSettings {
1717                name: "Jane Doe".to_string(),
1718                age: 31,
1719                staff: true
1720            }
1721        );
1722        assert_eq!(
1723            store.get::<UserSettings>(Some(SettingsLocation {
1724                worktree_id: WorktreeId::from_usize(1),
1725                path: Path::new("/root2/something")
1726            })),
1727            &UserSettings {
1728                name: "John Doe".to_string(),
1729                age: 42,
1730                staff: false
1731            }
1732        );
1733        assert_eq!(
1734            store.get::<MultiKeySettings>(Some(SettingsLocation {
1735                worktree_id: WorktreeId::from_usize(1),
1736                path: Path::new("/root2/something")
1737            })),
1738            &MultiKeySettings {
1739                key1: "a".to_string(),
1740                key2: "b".to_string(),
1741            }
1742        );
1743    }
1744
1745    #[gpui::test]
1746    fn test_setting_store_assign_json_before_register(cx: &mut App) {
1747        let mut store = SettingsStore::new(cx);
1748        store
1749            .set_default_settings(
1750                r#"{
1751                    "turbo": true,
1752                    "user": {
1753                        "name": "John Doe",
1754                        "age": 30,
1755                        "staff": false
1756                    },
1757                    "key1": "x"
1758                }"#,
1759                cx,
1760            )
1761            .unwrap();
1762        store
1763            .set_user_settings(r#"{ "turbo": false }"#, cx)
1764            .unwrap();
1765        store.register_setting::<UserSettings>(cx);
1766        store.register_setting::<TurboSetting>(cx);
1767
1768        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1769        assert_eq!(
1770            store.get::<UserSettings>(None),
1771            &UserSettings {
1772                name: "John Doe".to_string(),
1773                age: 30,
1774                staff: false,
1775            }
1776        );
1777
1778        store.register_setting::<MultiKeySettings>(cx);
1779        assert_eq!(
1780            store.get::<MultiKeySettings>(None),
1781            &MultiKeySettings {
1782                key1: "x".into(),
1783                key2: String::new(),
1784            }
1785        );
1786    }
1787
1788    #[gpui::test]
1789    fn test_setting_store_update(cx: &mut App) {
1790        let mut store = SettingsStore::new(cx);
1791        store.register_setting::<MultiKeySettings>(cx);
1792        store.register_setting::<UserSettings>(cx);
1793        store.register_setting::<LanguageSettings>(cx);
1794
1795        // entries added and updated
1796        check_settings_update::<LanguageSettings>(
1797            &mut store,
1798            r#"{
1799                "languages": {
1800                    "JSON": {
1801                        "language_setting_1": true
1802                    }
1803                }
1804            }"#
1805            .unindent(),
1806            |settings| {
1807                settings
1808                    .languages
1809                    .get_mut("JSON")
1810                    .unwrap()
1811                    .language_setting_1 = Some(false);
1812                settings.languages.insert(
1813                    "Rust".into(),
1814                    LanguageSettingEntry {
1815                        language_setting_2: Some(true),
1816                        ..Default::default()
1817                    },
1818                );
1819            },
1820            r#"{
1821                "languages": {
1822                    "Rust": {
1823                        "language_setting_2": true
1824                    },
1825                    "JSON": {
1826                        "language_setting_1": false
1827                    }
1828                }
1829            }"#
1830            .unindent(),
1831            cx,
1832        );
1833
1834        // entries removed
1835        check_settings_update::<LanguageSettings>(
1836            &mut store,
1837            r#"{
1838                "languages": {
1839                    "Rust": {
1840                        "language_setting_2": true
1841                    },
1842                    "JSON": {
1843                        "language_setting_1": false
1844                    }
1845                }
1846            }"#
1847            .unindent(),
1848            |settings| {
1849                settings.languages.remove("JSON").unwrap();
1850            },
1851            r#"{
1852                "languages": {
1853                    "Rust": {
1854                        "language_setting_2": true
1855                    }
1856                }
1857            }"#
1858            .unindent(),
1859            cx,
1860        );
1861
1862        check_settings_update::<LanguageSettings>(
1863            &mut store,
1864            r#"{
1865                "languages": {
1866                    "Rust": {
1867                        "language_setting_2": true
1868                    },
1869                    "JSON": {
1870                        "language_setting_1": false
1871                    }
1872                }
1873            }"#
1874            .unindent(),
1875            |settings| {
1876                settings.languages.remove("Rust").unwrap();
1877            },
1878            r#"{
1879                "languages": {
1880                    "JSON": {
1881                        "language_setting_1": false
1882                    }
1883                }
1884            }"#
1885            .unindent(),
1886            cx,
1887        );
1888
1889        // weird formatting
1890        check_settings_update::<UserSettings>(
1891            &mut store,
1892            r#"{
1893                "user":   { "age": 36, "name": "Max", "staff": true }
1894            }"#
1895            .unindent(),
1896            |settings| settings.age = Some(37),
1897            r#"{
1898                "user":   { "age": 37, "name": "Max", "staff": true }
1899            }"#
1900            .unindent(),
1901            cx,
1902        );
1903
1904        // single-line formatting, other keys
1905        check_settings_update::<MultiKeySettings>(
1906            &mut store,
1907            r#"{ "one": 1, "two": 2 }"#.unindent(),
1908            |settings| settings.key1 = Some("x".into()),
1909            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1910            cx,
1911        );
1912
1913        // empty object
1914        check_settings_update::<UserSettings>(
1915            &mut store,
1916            r#"{
1917                "user": {}
1918            }"#
1919            .unindent(),
1920            |settings| settings.age = Some(37),
1921            r#"{
1922                "user": {
1923                    "age": 37
1924                }
1925            }"#
1926            .unindent(),
1927            cx,
1928        );
1929
1930        // no content
1931        check_settings_update::<UserSettings>(
1932            &mut store,
1933            r#""#.unindent(),
1934            |settings| settings.age = Some(37),
1935            r#"{
1936                "user": {
1937                    "age": 37
1938                }
1939            }
1940            "#
1941            .unindent(),
1942            cx,
1943        );
1944
1945        check_settings_update::<UserSettings>(
1946            &mut store,
1947            r#"{
1948            }
1949            "#
1950            .unindent(),
1951            |settings| settings.age = Some(37),
1952            r#"{
1953                "user": {
1954                    "age": 37
1955                }
1956            }
1957            "#
1958            .unindent(),
1959            cx,
1960        );
1961    }
1962
1963    #[gpui::test]
1964    fn test_vscode_import(cx: &mut App) {
1965        let mut store = SettingsStore::new(cx);
1966        store.register_setting::<UserSettings>(cx);
1967        store.register_setting::<JournalSettings>(cx);
1968        store.register_setting::<LanguageSettings>(cx);
1969        store.register_setting::<MultiKeySettings>(cx);
1970
1971        // create settings that werent present
1972        check_vscode_import(
1973            &mut store,
1974            r#"{
1975            }
1976            "#
1977            .unindent(),
1978            r#" { "user.age": 37 } "#.to_owned(),
1979            r#"{
1980                "user": {
1981                    "age": 37
1982                }
1983            }
1984            "#
1985            .unindent(),
1986            cx,
1987        );
1988
1989        // persist settings that were present
1990        check_vscode_import(
1991            &mut store,
1992            r#"{
1993                "user": {
1994                    "staff": true,
1995                    "age": 37
1996                }
1997            }
1998            "#
1999            .unindent(),
2000            r#"{ "user.age": 42 }"#.to_owned(),
2001            r#"{
2002                "user": {
2003                    "staff": true,
2004                    "age": 42
2005                }
2006            }
2007            "#
2008            .unindent(),
2009            cx,
2010        );
2011
2012        // don't clobber settings that aren't present in vscode
2013        check_vscode_import(
2014            &mut store,
2015            r#"{
2016                "user": {
2017                    "staff": true,
2018                    "age": 37
2019                }
2020            }
2021            "#
2022            .unindent(),
2023            r#"{}"#.to_owned(),
2024            r#"{
2025                "user": {
2026                    "staff": true,
2027                    "age": 37
2028                }
2029            }
2030            "#
2031            .unindent(),
2032            cx,
2033        );
2034
2035        // custom enum
2036        check_vscode_import(
2037            &mut store,
2038            r#"{
2039                "journal": {
2040                "hour_format": "hour12"
2041                }
2042            }
2043            "#
2044            .unindent(),
2045            r#"{ "time_format": "24" }"#.to_owned(),
2046            r#"{
2047                "journal": {
2048                "hour_format": "hour24"
2049                }
2050            }
2051            "#
2052            .unindent(),
2053            cx,
2054        );
2055
2056        // Multiple keys for one setting
2057        check_vscode_import(
2058            &mut store,
2059            r#"{
2060                "key1": "value"
2061            }
2062            "#
2063            .unindent(),
2064            r#"{
2065                "key_1_first": "hello",
2066                "key_1_second": "world"
2067            }"#
2068            .to_owned(),
2069            r#"{
2070                "key1": "hello world"
2071            }
2072            "#
2073            .unindent(),
2074            cx,
2075        );
2076
2077        // Merging lists together entries added and updated
2078        check_vscode_import(
2079            &mut store,
2080            r#"{
2081                "languages": {
2082                    "JSON": {
2083                        "language_setting_1": true
2084                    },
2085                    "Rust": {
2086                        "language_setting_2": true
2087                    }
2088                }
2089            }"#
2090            .unindent(),
2091            r#"{
2092                "vscode_languages": [
2093                    {
2094                        "name": "JavaScript",
2095                        "language_setting_1": true
2096                    },
2097                    {
2098                        "name": "Rust",
2099                        "language_setting_2": false
2100                    }
2101                ]
2102            }"#
2103            .to_owned(),
2104            r#"{
2105                "languages": {
2106                    "JavaScript": {
2107                        "language_setting_1": true
2108                    },
2109                    "JSON": {
2110                        "language_setting_1": true
2111                    },
2112                    "Rust": {
2113                        "language_setting_2": false
2114                    }
2115                }
2116            }"#
2117            .unindent(),
2118            cx,
2119        );
2120    }
2121
2122    fn check_settings_update<T: Settings>(
2123        store: &mut SettingsStore,
2124        old_json: String,
2125        update: fn(&mut T::FileContent),
2126        expected_new_json: String,
2127        cx: &mut App,
2128    ) {
2129        store.set_user_settings(&old_json, cx).ok();
2130        let edits = store.edits_for_update::<T>(&old_json, update);
2131        let mut new_json = old_json;
2132        for (range, replacement) in edits.into_iter() {
2133            new_json.replace_range(range, &replacement);
2134        }
2135        pretty_assertions::assert_eq!(new_json, expected_new_json);
2136    }
2137
2138    fn check_vscode_import(
2139        store: &mut SettingsStore,
2140        old: String,
2141        vscode: String,
2142        expected: String,
2143        cx: &mut App,
2144    ) {
2145        store.set_user_settings(&old, cx).ok();
2146        let new = store.get_vscode_edits(
2147            old,
2148            &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
2149        );
2150        pretty_assertions::assert_eq!(new, expected);
2151    }
2152
2153    #[derive(Debug, PartialEq, Deserialize)]
2154    struct UserSettings {
2155        name: String,
2156        age: u32,
2157        staff: bool,
2158    }
2159
2160    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
2161    #[schemars(deny_unknown_fields)]
2162    struct UserSettingsContent {
2163        name: Option<String>,
2164        age: Option<u32>,
2165        staff: Option<bool>,
2166    }
2167
2168    impl Settings for UserSettings {
2169        const KEY: Option<&'static str> = Some("user");
2170        type FileContent = UserSettingsContent;
2171
2172        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2173            sources.json_merge()
2174        }
2175
2176        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2177            vscode.u32_setting("user.age", &mut current.age);
2178        }
2179    }
2180
2181    #[derive(Debug, Deserialize, PartialEq)]
2182    struct TurboSetting(bool);
2183
2184    impl Settings for TurboSetting {
2185        const KEY: Option<&'static str> = Some("turbo");
2186        type FileContent = Option<bool>;
2187
2188        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2189            sources.json_merge()
2190        }
2191
2192        fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
2193    }
2194
2195    #[derive(Clone, Debug, PartialEq, Deserialize)]
2196    struct MultiKeySettings {
2197        #[serde(default)]
2198        key1: String,
2199        #[serde(default)]
2200        key2: String,
2201    }
2202
2203    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
2204    #[schemars(deny_unknown_fields)]
2205    struct MultiKeySettingsJson {
2206        key1: Option<String>,
2207        key2: Option<String>,
2208    }
2209
2210    impl Settings for MultiKeySettings {
2211        const KEY: Option<&'static str> = None;
2212
2213        type FileContent = MultiKeySettingsJson;
2214
2215        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2216            sources.json_merge()
2217        }
2218
2219        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2220            let first_value = vscode.read_string("key_1_first");
2221            let second_value = vscode.read_string("key_1_second");
2222
2223            if let Some((first, second)) = first_value.zip(second_value) {
2224                current.key1 = Some(format!("{} {}", first, second));
2225            }
2226        }
2227    }
2228
2229    #[derive(Debug, Deserialize)]
2230    struct JournalSettings {
2231        pub path: String,
2232        pub hour_format: HourFormat,
2233    }
2234
2235    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
2236    #[serde(rename_all = "snake_case")]
2237    enum HourFormat {
2238        Hour12,
2239        Hour24,
2240    }
2241
2242    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
2243    #[schemars(deny_unknown_fields)]
2244    struct JournalSettingsJson {
2245        pub path: Option<String>,
2246        pub hour_format: Option<HourFormat>,
2247    }
2248
2249    impl Settings for JournalSettings {
2250        const KEY: Option<&'static str> = Some("journal");
2251
2252        type FileContent = JournalSettingsJson;
2253
2254        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2255            sources.json_merge()
2256        }
2257
2258        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2259            vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
2260                "12" => Some(HourFormat::Hour12),
2261                "24" => Some(HourFormat::Hour24),
2262                _ => None,
2263            });
2264        }
2265    }
2266
2267    #[gpui::test]
2268    fn test_global_settings(cx: &mut App) {
2269        let mut store = SettingsStore::new(cx);
2270        store.register_setting::<UserSettings>(cx);
2271        store
2272            .set_default_settings(
2273                r#"{
2274                    "user": {
2275                        "name": "John Doe",
2276                        "age": 30,
2277                        "staff": false
2278                    }
2279                }"#,
2280                cx,
2281            )
2282            .unwrap();
2283
2284        // Set global settings - these should override defaults but not user settings
2285        store
2286            .set_global_settings(
2287                r#"{
2288                    "user": {
2289                        "name": "Global User",
2290                        "age": 35,
2291                        "staff": true
2292                    }
2293                }"#,
2294                cx,
2295            )
2296            .unwrap();
2297
2298        // Before user settings, global settings should apply
2299        assert_eq!(
2300            store.get::<UserSettings>(None),
2301            &UserSettings {
2302                name: "Global User".to_string(),
2303                age: 35,
2304                staff: true,
2305            }
2306        );
2307
2308        // Set user settings - these should override both defaults and global
2309        store
2310            .set_user_settings(
2311                r#"{
2312                    "user": {
2313                        "age": 40
2314                    }
2315                }"#,
2316                cx,
2317            )
2318            .unwrap();
2319
2320        // User settings should override global settings
2321        assert_eq!(
2322            store.get::<UserSettings>(None),
2323            &UserSettings {
2324                name: "Global User".to_string(), // Name from global settings
2325                age: 40,                         // Age from user settings
2326                staff: true,                     // Staff from global settings
2327            }
2328        );
2329    }
2330
2331    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2332    struct LanguageSettings {
2333        #[serde(default)]
2334        languages: HashMap<String, LanguageSettingEntry>,
2335    }
2336
2337    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2338    #[schemars(deny_unknown_fields)]
2339    struct LanguageSettingEntry {
2340        language_setting_1: Option<bool>,
2341        language_setting_2: Option<bool>,
2342    }
2343
2344    impl Settings for LanguageSettings {
2345        const KEY: Option<&'static str> = None;
2346
2347        type FileContent = Self;
2348
2349        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2350            sources.json_merge()
2351        }
2352
2353        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2354            current.languages.extend(
2355                vscode
2356                    .read_value("vscode_languages")
2357                    .and_then(|value| value.as_array())
2358                    .map(|languages| {
2359                        languages
2360                            .iter()
2361                            .filter_map(|value| value.as_object())
2362                            .filter_map(|item| {
2363                                let mut rest = item.clone();
2364                                let name = rest.remove("name")?.as_str()?.to_string();
2365                                let entry = serde_json::from_value::<LanguageSettingEntry>(
2366                                    serde_json::Value::Object(rest),
2367                                )
2368                                .ok()?;
2369
2370                                Some((name, entry))
2371                            })
2372                    })
2373                    .into_iter()
2374                    .flatten(),
2375            );
2376        }
2377    }
2378}