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,
  20};
  21
  22use util::{ResultExt as _, merge_non_null_json_value_into};
  23
  24pub type EditorconfigProperties = ec4rs::Properties;
  25
  26use crate::{
  27    SettingsJsonSchemaParams, VsCodeSettings, WorktreeId, parse_json_with_comments,
  28    update_value_in_json_text,
  29};
  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
1337#[cfg(test)]
1338mod tests {
1339    use crate::VsCodeSettingsSource;
1340
1341    use super::*;
1342    use serde_derive::Deserialize;
1343    use unindent::Unindent;
1344
1345    #[gpui::test]
1346    fn test_settings_store_basic(cx: &mut App) {
1347        let mut store = SettingsStore::new(cx);
1348        store.register_setting::<UserSettings>(cx);
1349        store.register_setting::<TurboSetting>(cx);
1350        store.register_setting::<MultiKeySettings>(cx);
1351        store
1352            .set_default_settings(
1353                r#"{
1354                    "turbo": false,
1355                    "user": {
1356                        "name": "John Doe",
1357                        "age": 30,
1358                        "staff": false
1359                    }
1360                }"#,
1361                cx,
1362            )
1363            .unwrap();
1364
1365        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1366        assert_eq!(
1367            store.get::<UserSettings>(None),
1368            &UserSettings {
1369                name: "John Doe".to_string(),
1370                age: 30,
1371                staff: false,
1372            }
1373        );
1374        assert_eq!(
1375            store.get::<MultiKeySettings>(None),
1376            &MultiKeySettings {
1377                key1: String::new(),
1378                key2: String::new(),
1379            }
1380        );
1381
1382        store
1383            .set_user_settings(
1384                r#"{
1385                    "turbo": true,
1386                    "user": { "age": 31 },
1387                    "key1": "a"
1388                }"#,
1389                cx,
1390            )
1391            .unwrap();
1392
1393        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1394        assert_eq!(
1395            store.get::<UserSettings>(None),
1396            &UserSettings {
1397                name: "John Doe".to_string(),
1398                age: 31,
1399                staff: false
1400            }
1401        );
1402
1403        store
1404            .set_local_settings(
1405                WorktreeId::from_usize(1),
1406                Path::new("/root1").into(),
1407                LocalSettingsKind::Settings,
1408                Some(r#"{ "user": { "staff": true } }"#),
1409                cx,
1410            )
1411            .unwrap();
1412        store
1413            .set_local_settings(
1414                WorktreeId::from_usize(1),
1415                Path::new("/root1/subdir").into(),
1416                LocalSettingsKind::Settings,
1417                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1418                cx,
1419            )
1420            .unwrap();
1421
1422        store
1423            .set_local_settings(
1424                WorktreeId::from_usize(1),
1425                Path::new("/root2").into(),
1426                LocalSettingsKind::Settings,
1427                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1428                cx,
1429            )
1430            .unwrap();
1431
1432        assert_eq!(
1433            store.get::<UserSettings>(Some(SettingsLocation {
1434                worktree_id: WorktreeId::from_usize(1),
1435                path: Path::new("/root1/something"),
1436            })),
1437            &UserSettings {
1438                name: "John Doe".to_string(),
1439                age: 31,
1440                staff: true
1441            }
1442        );
1443        assert_eq!(
1444            store.get::<UserSettings>(Some(SettingsLocation {
1445                worktree_id: WorktreeId::from_usize(1),
1446                path: Path::new("/root1/subdir/something")
1447            })),
1448            &UserSettings {
1449                name: "Jane Doe".to_string(),
1450                age: 31,
1451                staff: true
1452            }
1453        );
1454        assert_eq!(
1455            store.get::<UserSettings>(Some(SettingsLocation {
1456                worktree_id: WorktreeId::from_usize(1),
1457                path: Path::new("/root2/something")
1458            })),
1459            &UserSettings {
1460                name: "John Doe".to_string(),
1461                age: 42,
1462                staff: false
1463            }
1464        );
1465        assert_eq!(
1466            store.get::<MultiKeySettings>(Some(SettingsLocation {
1467                worktree_id: WorktreeId::from_usize(1),
1468                path: Path::new("/root2/something")
1469            })),
1470            &MultiKeySettings {
1471                key1: "a".to_string(),
1472                key2: "b".to_string(),
1473            }
1474        );
1475    }
1476
1477    #[gpui::test]
1478    fn test_setting_store_assign_json_before_register(cx: &mut App) {
1479        let mut store = SettingsStore::new(cx);
1480        store
1481            .set_default_settings(
1482                r#"{
1483                    "turbo": true,
1484                    "user": {
1485                        "name": "John Doe",
1486                        "age": 30,
1487                        "staff": false
1488                    },
1489                    "key1": "x"
1490                }"#,
1491                cx,
1492            )
1493            .unwrap();
1494        store
1495            .set_user_settings(r#"{ "turbo": false }"#, cx)
1496            .unwrap();
1497        store.register_setting::<UserSettings>(cx);
1498        store.register_setting::<TurboSetting>(cx);
1499
1500        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1501        assert_eq!(
1502            store.get::<UserSettings>(None),
1503            &UserSettings {
1504                name: "John Doe".to_string(),
1505                age: 30,
1506                staff: false,
1507            }
1508        );
1509
1510        store.register_setting::<MultiKeySettings>(cx);
1511        assert_eq!(
1512            store.get::<MultiKeySettings>(None),
1513            &MultiKeySettings {
1514                key1: "x".into(),
1515                key2: String::new(),
1516            }
1517        );
1518    }
1519
1520    fn check_settings_update<T: Settings>(
1521        store: &mut SettingsStore,
1522        old_json: String,
1523        update: fn(&mut T::FileContent),
1524        expected_new_json: String,
1525        cx: &mut App,
1526    ) {
1527        store.set_user_settings(&old_json, cx).ok();
1528        let edits = store.edits_for_update::<T>(&old_json, update);
1529        let mut new_json = old_json;
1530        for (range, replacement) in edits.into_iter() {
1531            new_json.replace_range(range, &replacement);
1532        }
1533        pretty_assertions::assert_eq!(new_json, expected_new_json);
1534    }
1535
1536    #[gpui::test]
1537    fn test_setting_store_update(cx: &mut App) {
1538        let mut store = SettingsStore::new(cx);
1539        store.register_setting::<MultiKeySettings>(cx);
1540        store.register_setting::<UserSettings>(cx);
1541        store.register_setting::<LanguageSettings>(cx);
1542
1543        // entries added and updated
1544        check_settings_update::<LanguageSettings>(
1545            &mut store,
1546            r#"{
1547                "languages": {
1548                    "JSON": {
1549                        "language_setting_1": true
1550                    }
1551                }
1552            }"#
1553            .unindent(),
1554            |settings| {
1555                settings
1556                    .languages
1557                    .get_mut("JSON")
1558                    .unwrap()
1559                    .language_setting_1 = Some(false);
1560                settings.languages.insert(
1561                    "Rust".into(),
1562                    LanguageSettingEntry {
1563                        language_setting_2: Some(true),
1564                        ..Default::default()
1565                    },
1566                );
1567            },
1568            r#"{
1569                "languages": {
1570                    "Rust": {
1571                        "language_setting_2": true
1572                    },
1573                    "JSON": {
1574                        "language_setting_1": false
1575                    }
1576                }
1577            }"#
1578            .unindent(),
1579            cx,
1580        );
1581
1582        // entries removed
1583        check_settings_update::<LanguageSettings>(
1584            &mut store,
1585            r#"{
1586                "languages": {
1587                    "Rust": {
1588                        "language_setting_2": true
1589                    },
1590                    "JSON": {
1591                        "language_setting_1": false
1592                    }
1593                }
1594            }"#
1595            .unindent(),
1596            |settings| {
1597                settings.languages.remove("JSON").unwrap();
1598            },
1599            r#"{
1600                "languages": {
1601                    "Rust": {
1602                        "language_setting_2": true
1603                    }
1604                }
1605            }"#
1606            .unindent(),
1607            cx,
1608        );
1609
1610        check_settings_update::<LanguageSettings>(
1611            &mut store,
1612            r#"{
1613                "languages": {
1614                    "Rust": {
1615                        "language_setting_2": true
1616                    },
1617                    "JSON": {
1618                        "language_setting_1": false
1619                    }
1620                }
1621            }"#
1622            .unindent(),
1623            |settings| {
1624                settings.languages.remove("Rust").unwrap();
1625            },
1626            r#"{
1627                "languages": {
1628                    "JSON": {
1629                        "language_setting_1": false
1630                    }
1631                }
1632            }"#
1633            .unindent(),
1634            cx,
1635        );
1636
1637        // weird formatting
1638        check_settings_update::<UserSettings>(
1639            &mut store,
1640            r#"{
1641                "user":   { "age": 36, "name": "Max", "staff": true }
1642                }"#
1643            .unindent(),
1644            |settings| settings.age = Some(37),
1645            r#"{
1646                "user":   { "age": 37, "name": "Max", "staff": true }
1647                }"#
1648            .unindent(),
1649            cx,
1650        );
1651
1652        // single-line formatting, other keys
1653        check_settings_update::<MultiKeySettings>(
1654            &mut store,
1655            r#"{ "one": 1, "two": 2 }"#.unindent(),
1656            |settings| settings.key1 = Some("x".into()),
1657            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1658            cx,
1659        );
1660
1661        // empty object
1662        check_settings_update::<UserSettings>(
1663            &mut store,
1664            r#"{
1665                "user": {}
1666            }"#
1667            .unindent(),
1668            |settings| settings.age = Some(37),
1669            r#"{
1670                "user": {
1671                    "age": 37
1672                }
1673            }"#
1674            .unindent(),
1675            cx,
1676        );
1677
1678        // no content
1679        check_settings_update::<UserSettings>(
1680            &mut store,
1681            r#""#.unindent(),
1682            |settings| settings.age = Some(37),
1683            r#"{
1684                "user": {
1685                    "age": 37
1686                }
1687            }
1688            "#
1689            .unindent(),
1690            cx,
1691        );
1692
1693        check_settings_update::<UserSettings>(
1694            &mut store,
1695            r#"{
1696            }
1697            "#
1698            .unindent(),
1699            |settings| settings.age = Some(37),
1700            r#"{
1701                "user": {
1702                    "age": 37
1703                }
1704            }
1705            "#
1706            .unindent(),
1707            cx,
1708        );
1709    }
1710
1711    #[gpui::test]
1712    fn test_vscode_import(cx: &mut App) {
1713        let mut store = SettingsStore::new(cx);
1714        store.register_setting::<UserSettings>(cx);
1715        store.register_setting::<JournalSettings>(cx);
1716        store.register_setting::<LanguageSettings>(cx);
1717        store.register_setting::<MultiKeySettings>(cx);
1718
1719        // create settings that werent present
1720        check_vscode_import(
1721            &mut store,
1722            r#"{
1723            }
1724            "#
1725            .unindent(),
1726            r#" { "user.age": 37 } "#.to_owned(),
1727            r#"{
1728                "user": {
1729                    "age": 37
1730                }
1731            }
1732            "#
1733            .unindent(),
1734            cx,
1735        );
1736
1737        // persist settings that were present
1738        check_vscode_import(
1739            &mut store,
1740            r#"{
1741                "user": {
1742                    "staff": true,
1743                    "age": 37
1744                }
1745            }
1746            "#
1747            .unindent(),
1748            r#"{ "user.age": 42 }"#.to_owned(),
1749            r#"{
1750                "user": {
1751                    "staff": true,
1752                    "age": 42
1753                }
1754            }
1755            "#
1756            .unindent(),
1757            cx,
1758        );
1759
1760        // don't clobber settings that aren't present in vscode
1761        check_vscode_import(
1762            &mut store,
1763            r#"{
1764                "user": {
1765                    "staff": true,
1766                    "age": 37
1767                }
1768            }
1769            "#
1770            .unindent(),
1771            r#"{}"#.to_owned(),
1772            r#"{
1773                "user": {
1774                    "staff": true,
1775                    "age": 37
1776                }
1777            }
1778            "#
1779            .unindent(),
1780            cx,
1781        );
1782
1783        // custom enum
1784        check_vscode_import(
1785            &mut store,
1786            r#"{
1787                "journal": {
1788                "hour_format": "hour12"
1789                }
1790            }
1791            "#
1792            .unindent(),
1793            r#"{ "time_format": "24" }"#.to_owned(),
1794            r#"{
1795                "journal": {
1796                "hour_format": "hour24"
1797                }
1798            }
1799            "#
1800            .unindent(),
1801            cx,
1802        );
1803
1804        // Multiple keys for one setting
1805        check_vscode_import(
1806            &mut store,
1807            r#"{
1808                "key1": "value"
1809            }
1810            "#
1811            .unindent(),
1812            r#"{
1813                "key_1_first": "hello",
1814                "key_1_second": "world"
1815            }"#
1816            .to_owned(),
1817            r#"{
1818                "key1": "hello world"
1819            }
1820            "#
1821            .unindent(),
1822            cx,
1823        );
1824
1825        // Merging lists together entries added and updated
1826        check_vscode_import(
1827            &mut store,
1828            r#"{
1829                "languages": {
1830                    "JSON": {
1831                        "language_setting_1": true
1832                    },
1833                    "Rust": {
1834                        "language_setting_2": true
1835                    }
1836                }
1837            }"#
1838            .unindent(),
1839            r#"{
1840                "vscode_languages": [
1841                    {
1842                        "name": "JavaScript",
1843                        "language_setting_1": true
1844                    },
1845                    {
1846                        "name": "Rust",
1847                        "language_setting_2": false
1848                    }
1849                ]
1850            }"#
1851            .to_owned(),
1852            r#"{
1853                "languages": {
1854                    "JavaScript": {
1855                        "language_setting_1": true
1856                    },
1857                    "JSON": {
1858                        "language_setting_1": true
1859                    },
1860                    "Rust": {
1861                        "language_setting_2": false
1862                    }
1863                }
1864            }"#
1865            .unindent(),
1866            cx,
1867        );
1868    }
1869
1870    fn check_vscode_import(
1871        store: &mut SettingsStore,
1872        old: String,
1873        vscode: String,
1874        expected: String,
1875        cx: &mut App,
1876    ) {
1877        store.set_user_settings(&old, cx).ok();
1878        let new = store.get_vscode_edits(
1879            old,
1880            &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1881        );
1882        pretty_assertions::assert_eq!(new, expected);
1883    }
1884
1885    #[derive(Debug, PartialEq, Deserialize)]
1886    struct UserSettings {
1887        name: String,
1888        age: u32,
1889        staff: bool,
1890    }
1891
1892    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1893    #[schemars(deny_unknown_fields)]
1894    struct UserSettingsContent {
1895        name: Option<String>,
1896        age: Option<u32>,
1897        staff: Option<bool>,
1898    }
1899
1900    impl Settings for UserSettings {
1901        const KEY: Option<&'static str> = Some("user");
1902        type FileContent = UserSettingsContent;
1903
1904        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1905            sources.json_merge()
1906        }
1907
1908        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
1909            vscode.u32_setting("user.age", &mut current.age);
1910        }
1911    }
1912
1913    #[derive(Debug, Deserialize, PartialEq)]
1914    struct TurboSetting(bool);
1915
1916    impl Settings for TurboSetting {
1917        const KEY: Option<&'static str> = Some("turbo");
1918        type FileContent = Option<bool>;
1919
1920        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1921            sources.json_merge()
1922        }
1923
1924        fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
1925    }
1926
1927    #[derive(Clone, Debug, PartialEq, Deserialize)]
1928    struct MultiKeySettings {
1929        #[serde(default)]
1930        key1: String,
1931        #[serde(default)]
1932        key2: String,
1933    }
1934
1935    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1936    #[schemars(deny_unknown_fields)]
1937    struct MultiKeySettingsJson {
1938        key1: Option<String>,
1939        key2: Option<String>,
1940    }
1941
1942    impl Settings for MultiKeySettings {
1943        const KEY: Option<&'static str> = None;
1944
1945        type FileContent = MultiKeySettingsJson;
1946
1947        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1948            sources.json_merge()
1949        }
1950
1951        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
1952            let first_value = vscode.read_string("key_1_first");
1953            let second_value = vscode.read_string("key_1_second");
1954
1955            if let Some((first, second)) = first_value.zip(second_value) {
1956                current.key1 = Some(format!("{} {}", first, second));
1957            }
1958        }
1959    }
1960
1961    #[derive(Debug, Deserialize)]
1962    struct JournalSettings {
1963        pub path: String,
1964        pub hour_format: HourFormat,
1965    }
1966
1967    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1968    #[serde(rename_all = "snake_case")]
1969    enum HourFormat {
1970        Hour12,
1971        Hour24,
1972    }
1973
1974    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1975    #[schemars(deny_unknown_fields)]
1976    struct JournalSettingsJson {
1977        pub path: Option<String>,
1978        pub hour_format: Option<HourFormat>,
1979    }
1980
1981    impl Settings for JournalSettings {
1982        const KEY: Option<&'static str> = Some("journal");
1983
1984        type FileContent = JournalSettingsJson;
1985
1986        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
1987            sources.json_merge()
1988        }
1989
1990        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
1991            vscode.enum_setting("time_format", &mut current.hour_format, |s| match s {
1992                "12" => Some(HourFormat::Hour12),
1993                "24" => Some(HourFormat::Hour24),
1994                _ => None,
1995            });
1996        }
1997    }
1998
1999    #[gpui::test]
2000    fn test_global_settings(cx: &mut App) {
2001        let mut store = SettingsStore::new(cx);
2002        store.register_setting::<UserSettings>(cx);
2003        store
2004            .set_default_settings(
2005                r#"{
2006                    "user": {
2007                        "name": "John Doe",
2008                        "age": 30,
2009                        "staff": false
2010                    }
2011                }"#,
2012                cx,
2013            )
2014            .unwrap();
2015
2016        // Set global settings - these should override defaults but not user settings
2017        store
2018            .set_global_settings(
2019                r#"{
2020                    "user": {
2021                        "name": "Global User",
2022                        "age": 35,
2023                        "staff": true
2024                    }
2025                }"#,
2026                cx,
2027            )
2028            .unwrap();
2029
2030        // Before user settings, global settings should apply
2031        assert_eq!(
2032            store.get::<UserSettings>(None),
2033            &UserSettings {
2034                name: "Global User".to_string(),
2035                age: 35,
2036                staff: true,
2037            }
2038        );
2039
2040        // Set user settings - these should override both defaults and global
2041        store
2042            .set_user_settings(
2043                r#"{
2044                    "user": {
2045                        "age": 40
2046                    }
2047                }"#,
2048                cx,
2049            )
2050            .unwrap();
2051
2052        // User settings should override global settings
2053        assert_eq!(
2054            store.get::<UserSettings>(None),
2055            &UserSettings {
2056                name: "Global User".to_string(), // Name from global settings
2057                age: 40,                         // Age from user settings
2058                staff: true,                     // Staff from global settings
2059            }
2060        );
2061    }
2062
2063    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2064    struct LanguageSettings {
2065        #[serde(default)]
2066        languages: HashMap<String, LanguageSettingEntry>,
2067    }
2068
2069    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
2070    #[schemars(deny_unknown_fields)]
2071    struct LanguageSettingEntry {
2072        language_setting_1: Option<bool>,
2073        language_setting_2: Option<bool>,
2074    }
2075
2076    impl Settings for LanguageSettings {
2077        const KEY: Option<&'static str> = None;
2078
2079        type FileContent = Self;
2080
2081        fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
2082            sources.json_merge()
2083        }
2084
2085        fn import_from_vscode(vscode: &VsCodeSettings, current: &mut Self::FileContent) {
2086            current.languages.extend(
2087                vscode
2088                    .read_value("vscode_languages")
2089                    .and_then(|value| value.as_array())
2090                    .map(|languages| {
2091                        languages
2092                            .iter()
2093                            .filter_map(|value| value.as_object())
2094                            .filter_map(|item| {
2095                                let mut rest = item.clone();
2096                                let name = rest.remove("name")?.as_str()?.to_string();
2097                                let entry = serde_json::from_value::<LanguageSettingEntry>(
2098                                    serde_json::Value::Object(rest),
2099                                )
2100                                .ok()?;
2101
2102                                Some((name, entry))
2103                            })
2104                    })
2105                    .into_iter()
2106                    .flatten(),
2107            );
2108        }
2109    }
2110}