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