settings_store.rs

   1use anyhow::{Context as _, Result};
   2use collections::{BTreeMap, HashMap, btree_map, hash_map};
   3use fs::Fs;
   4use futures::{
   5    FutureExt, StreamExt,
   6    channel::{mpsc, oneshot},
   7    future::LocalBoxFuture,
   8};
   9use gpui::{
  10    App, AppContext, AsyncApp, BorrowAppContext, Entity, Global, SharedString, Task, UpdateGlobal,
  11};
  12
  13use paths::{local_settings_file_relative_path, task_file_name};
  14use schemars::{JsonSchema, json_schema};
  15use serde_json::Value;
  16use settings_content::ParseStatus;
  17use std::{
  18    any::{Any, TypeId, type_name},
  19    fmt::Debug,
  20    ops::Range,
  21    path::{Path, PathBuf},
  22    rc::Rc,
  23    str,
  24    sync::Arc,
  25};
  26use util::{
  27    ResultExt as _,
  28    rel_path::RelPath,
  29    schemars::{AllowTrailingCommas, DefaultDenyUnknownFields, replace_subschema},
  30};
  31
  32use crate::editorconfig_store::EditorconfigStore;
  33
  34use crate::{
  35    ActiveSettingsProfileName, FontFamilyName, IconThemeName, LanguageSettingsContent,
  36    LanguageToSettingsMap, LspSettings, LspSettingsMap, SemanticTokenRules, ThemeName,
  37    UserSettingsContentExt, VsCodeSettings, WorktreeId,
  38    settings_content::{
  39        ExtensionsSettingsContent, ProjectSettingsContent, RootUserSettings, SettingsContent,
  40        UserSettingsContent, merge_from::MergeFrom,
  41    },
  42};
  43
  44use settings_json::{infer_json_indent_size, update_value_in_json_text};
  45
  46pub const LSP_SETTINGS_SCHEMA_URL_PREFIX: &str = "zed://schemas/settings/lsp/";
  47
  48pub trait SettingsKey: 'static + Send + Sync {
  49    /// The name of a key within the JSON file from which this setting should
  50    /// be deserialized. If this is `None`, then the setting will be deserialized
  51    /// from the root object.
  52    const KEY: Option<&'static str>;
  53
  54    const FALLBACK_KEY: Option<&'static str> = None;
  55}
  56
  57/// A value that can be defined as a user setting.
  58///
  59/// Settings can be loaded from a combination of multiple JSON files.
  60pub trait Settings: 'static + Send + Sync + Sized {
  61    /// The name of the keys in the [`FileContent`](Self::FileContent) that should
  62    /// always be written to a settings file, even if their value matches the default
  63    /// value.
  64    ///
  65    /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
  66    /// is a "version" field that should always be persisted, even if the current
  67    /// user settings match the current version of the settings.
  68    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  69
  70    /// Read the value from default.json.
  71    ///
  72    /// This function *should* panic if default values are missing,
  73    /// and you should add a default to default.json for documentation.
  74    fn from_settings(content: &SettingsContent) -> Self;
  75
  76    #[track_caller]
  77    fn register(cx: &mut App)
  78    where
  79        Self: Sized,
  80    {
  81        SettingsStore::update_global(cx, |store, _| {
  82            store.register_setting::<Self>();
  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_get(cx: &App) -> Option<&Self>
 104    where
 105        Self: Sized,
 106    {
 107        if cx.has_global::<SettingsStore>() {
 108            cx.global::<SettingsStore>().try_get(None)
 109        } else {
 110            None
 111        }
 112    }
 113
 114    #[track_caller]
 115    fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
 116    where
 117        Self: Sized,
 118    {
 119        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
 120    }
 121
 122    #[track_caller]
 123    fn override_global(settings: Self, cx: &mut App)
 124    where
 125        Self: Sized,
 126    {
 127        cx.global_mut::<SettingsStore>().override_global(settings)
 128    }
 129}
 130
 131pub struct RegisteredSetting {
 132    pub settings_value: fn() -> Box<dyn AnySettingValue>,
 133    pub from_settings: fn(&SettingsContent) -> Box<dyn Any>,
 134    pub id: fn() -> TypeId,
 135}
 136
 137inventory::collect!(RegisteredSetting);
 138
 139#[derive(Clone, Copy, Debug)]
 140pub struct SettingsLocation<'a> {
 141    pub worktree_id: WorktreeId,
 142    pub path: &'a RelPath,
 143}
 144
 145pub struct SettingsStore {
 146    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 147    default_settings: Rc<SettingsContent>,
 148    user_settings: Option<UserSettingsContent>,
 149    global_settings: Option<Box<SettingsContent>>,
 150
 151    extension_settings: Option<Box<SettingsContent>>,
 152    server_settings: Option<Box<SettingsContent>>,
 153
 154    language_semantic_token_rules: HashMap<SharedString, SemanticTokenRules>,
 155
 156    merged_settings: Rc<SettingsContent>,
 157
 158    local_settings: BTreeMap<(WorktreeId, Arc<RelPath>), SettingsContent>,
 159    pub editorconfig_store: Entity<EditorconfigStore>,
 160
 161    _setting_file_updates: Task<()>,
 162    setting_file_updates_tx:
 163        mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
 164    file_errors: BTreeMap<SettingsFile, SettingsParseResult>,
 165}
 166
 167#[derive(Clone, PartialEq, Eq, Debug)]
 168pub enum SettingsFile {
 169    Default,
 170    Global,
 171    User,
 172    Server,
 173    /// Represents project settings in ssh projects as well as local projects
 174    Project((WorktreeId, Arc<RelPath>)),
 175}
 176
 177impl PartialOrd for SettingsFile {
 178    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
 179        Some(self.cmp(other))
 180    }
 181}
 182
 183/// Sorted in order of precedence
 184impl Ord for SettingsFile {
 185    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
 186        use SettingsFile::*;
 187        use std::cmp::Ordering;
 188        match (self, other) {
 189            (User, User) => Ordering::Equal,
 190            (Server, Server) => Ordering::Equal,
 191            (Default, Default) => Ordering::Equal,
 192            (Project((id1, rel_path1)), Project((id2, rel_path2))) => id1
 193                .cmp(id2)
 194                .then_with(|| rel_path1.cmp(rel_path2).reverse()),
 195            (Project(_), _) => Ordering::Less,
 196            (_, Project(_)) => Ordering::Greater,
 197            (Server, _) => Ordering::Less,
 198            (_, Server) => Ordering::Greater,
 199            (User, _) => Ordering::Less,
 200            (_, User) => Ordering::Greater,
 201            (Global, _) => Ordering::Less,
 202            (_, Global) => Ordering::Greater,
 203        }
 204    }
 205}
 206
 207#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 208pub enum LocalSettingsKind {
 209    Settings,
 210    Tasks,
 211    Editorconfig,
 212    Debug,
 213}
 214
 215#[derive(Clone, Debug, PartialEq, Eq, Hash)]
 216pub enum LocalSettingsPath {
 217    InWorktree(Arc<RelPath>),
 218    OutsideWorktree(Arc<Path>),
 219}
 220
 221impl LocalSettingsPath {
 222    pub fn is_outside_worktree(&self) -> bool {
 223        matches!(self, Self::OutsideWorktree(_))
 224    }
 225
 226    pub fn to_proto(&self) -> String {
 227        match self {
 228            Self::InWorktree(path) => path.to_proto(),
 229            Self::OutsideWorktree(path) => path.to_string_lossy().to_string(),
 230        }
 231    }
 232
 233    pub fn from_proto(path: &str, is_outside_worktree: bool) -> anyhow::Result<Self> {
 234        if is_outside_worktree {
 235            Ok(Self::OutsideWorktree(PathBuf::from(path).into()))
 236        } else {
 237            Ok(Self::InWorktree(RelPath::from_proto(path)?))
 238        }
 239    }
 240}
 241
 242impl Global for SettingsStore {}
 243
 244#[doc(hidden)]
 245#[derive(Debug)]
 246pub struct SettingValue<T> {
 247    #[doc(hidden)]
 248    pub global_value: Option<T>,
 249    #[doc(hidden)]
 250    pub local_values: Vec<(WorktreeId, Arc<RelPath>, T)>,
 251}
 252
 253#[doc(hidden)]
 254pub trait AnySettingValue: 'static + Send + Sync {
 255    fn setting_type_name(&self) -> &'static str;
 256
 257    fn from_settings(&self, s: &SettingsContent) -> Box<dyn Any>;
 258
 259    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 260    fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
 261    fn set_global_value(&mut self, value: Box<dyn Any>);
 262    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
 263    fn clear_local_values(&mut self, root_id: WorktreeId);
 264}
 265
 266/// Parameters that are used when generating some JSON schemas at runtime.
 267pub struct SettingsJsonSchemaParams<'a> {
 268    pub language_names: &'a [String],
 269    pub font_names: &'a [String],
 270    pub theme_names: &'a [SharedString],
 271    pub icon_theme_names: &'a [SharedString],
 272    pub lsp_adapter_names: &'a [String],
 273}
 274
 275impl SettingsStore {
 276    pub fn new(cx: &mut App, default_settings: &str) -> Self {
 277        Self::new_with_semantic_tokens(cx, default_settings, &crate::default_semantic_token_rules())
 278    }
 279
 280    pub fn new_with_semantic_tokens(
 281        cx: &mut App,
 282        default_settings: &str,
 283        default_semantic_tokens: &str,
 284    ) -> Self {
 285        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 286        let mut default_settings: SettingsContent =
 287            SettingsContent::parse_json_with_comments(default_settings).unwrap();
 288        if let Ok(semantic_token_rules) =
 289            crate::parse_json_with_comments::<SemanticTokenRules>(default_semantic_tokens)
 290        {
 291            let global_lsp = default_settings
 292                .global_lsp_settings
 293                .get_or_insert_with(Default::default);
 294            let existing_rules = global_lsp
 295                .semantic_token_rules
 296                .get_or_insert_with(Default::default);
 297            existing_rules.rules.extend(semantic_token_rules.rules);
 298        }
 299
 300        let default_settings: Rc<SettingsContent> = default_settings.into();
 301        let mut this = Self {
 302            setting_values: Default::default(),
 303            default_settings: default_settings.clone(),
 304            global_settings: None,
 305            server_settings: None,
 306            user_settings: None,
 307            extension_settings: None,
 308            language_semantic_token_rules: HashMap::default(),
 309
 310            merged_settings: default_settings,
 311            local_settings: BTreeMap::default(),
 312            editorconfig_store: cx.new(|_| EditorconfigStore::default()),
 313            setting_file_updates_tx,
 314            _setting_file_updates: cx.spawn(async move |cx| {
 315                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 316                    (setting_file_update)(cx.clone()).await.log_err();
 317                }
 318            }),
 319            file_errors: BTreeMap::default(),
 320        };
 321
 322        this.load_settings_types();
 323
 324        this
 325    }
 326
 327    pub fn observe_active_settings_profile_name(cx: &mut App) -> gpui::Subscription {
 328        cx.observe_global::<ActiveSettingsProfileName>(|cx| {
 329            Self::update_global(cx, |store, cx| {
 330                store.recompute_values(None, cx);
 331            });
 332        })
 333    }
 334
 335    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 336    where
 337        C: BorrowAppContext,
 338    {
 339        cx.update_global(f)
 340    }
 341
 342    /// Add a new type of setting to the store.
 343    pub fn register_setting<T: Settings>(&mut self) {
 344        self.register_setting_internal(&RegisteredSetting {
 345            settings_value: || {
 346                Box::new(SettingValue::<T> {
 347                    global_value: None,
 348                    local_values: Vec::new(),
 349                })
 350            },
 351            from_settings: |content| Box::new(T::from_settings(content)),
 352            id: || TypeId::of::<T>(),
 353        });
 354    }
 355
 356    fn load_settings_types(&mut self) {
 357        for registered_setting in inventory::iter::<RegisteredSetting>() {
 358            self.register_setting_internal(registered_setting);
 359        }
 360    }
 361
 362    fn register_setting_internal(&mut self, registered_setting: &RegisteredSetting) {
 363        let entry = self.setting_values.entry((registered_setting.id)());
 364
 365        if matches!(entry, hash_map::Entry::Occupied(_)) {
 366            return;
 367        }
 368
 369        let setting_value = entry.or_insert((registered_setting.settings_value)());
 370        let value = (registered_setting.from_settings)(&self.merged_settings);
 371        setting_value.set_global_value(value);
 372    }
 373
 374    /// Get the value of a setting.
 375    ///
 376    /// Panics if the given setting type has not been registered, or if there is no
 377    /// value for this setting.
 378    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 379        self.setting_values
 380            .get(&TypeId::of::<T>())
 381            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 382            .value_for_path(path)
 383            .downcast_ref::<T>()
 384            .expect("no default value for setting type")
 385    }
 386
 387    /// Get the value of a setting.
 388    ///
 389    /// Does not panic
 390    pub fn try_get<T: Settings>(&self, path: Option<SettingsLocation>) -> Option<&T> {
 391        self.setting_values
 392            .get(&TypeId::of::<T>())
 393            .map(|value| value.value_for_path(path))
 394            .and_then(|value| value.downcast_ref::<T>())
 395    }
 396
 397    /// Get all values from project specific settings
 398    pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<RelPath>, &T)> {
 399        self.setting_values
 400            .get(&TypeId::of::<T>())
 401            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 402            .all_local_values()
 403            .into_iter()
 404            .map(|(id, path, any)| {
 405                (
 406                    id,
 407                    path,
 408                    any.downcast_ref::<T>()
 409                        .expect("wrong value type for setting"),
 410                )
 411            })
 412            .collect()
 413    }
 414
 415    /// Override the global value for a setting.
 416    ///
 417    /// The given value will be overwritten if the user settings file changes.
 418    pub fn override_global<T: Settings>(&mut self, value: T) {
 419        self.setting_values
 420            .get_mut(&TypeId::of::<T>())
 421            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 422            .set_global_value(Box::new(value))
 423    }
 424
 425    /// Get the user's settings content.
 426    ///
 427    /// For user-facing functionality use the typed setting interface.
 428    /// (e.g. ProjectSettings::get_global(cx))
 429    pub fn raw_user_settings(&self) -> Option<&UserSettingsContent> {
 430        self.user_settings.as_ref()
 431    }
 432
 433    /// Get the default settings content as a raw JSON value.
 434    pub fn raw_default_settings(&self) -> &SettingsContent {
 435        &self.default_settings
 436    }
 437
 438    /// Get the configured settings profile names.
 439    pub fn configured_settings_profiles(&self) -> impl Iterator<Item = &str> {
 440        self.user_settings
 441            .iter()
 442            .flat_map(|settings| settings.profiles.keys().map(|k| k.as_str()))
 443    }
 444
 445    #[cfg(any(test, feature = "test-support"))]
 446    pub fn test(cx: &mut App) -> Self {
 447        Self::new(cx, &crate::test_settings())
 448    }
 449
 450    /// Updates the value of a setting in the user's global configuration.
 451    ///
 452    /// This is only for tests. Normally, settings are only loaded from
 453    /// JSON files.
 454    #[cfg(any(test, feature = "test-support"))]
 455    pub fn update_user_settings(
 456        &mut self,
 457        cx: &mut App,
 458        update: impl FnOnce(&mut SettingsContent),
 459    ) {
 460        let mut content = self.user_settings.clone().unwrap_or_default().content;
 461        update(&mut content);
 462        fn trail(this: &mut SettingsStore, content: Box<SettingsContent>, cx: &mut App) {
 463            let new_text = serde_json::to_string(&UserSettingsContent {
 464                content,
 465                ..Default::default()
 466            })
 467            .unwrap();
 468            _ = this.set_user_settings(&new_text, cx);
 469        }
 470        trail(self, content, cx);
 471    }
 472
 473    pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 474        match fs.load(paths::settings_file()).await {
 475            result @ Ok(_) => result,
 476            Err(err) => {
 477                if let Some(e) = err.downcast_ref::<std::io::Error>()
 478                    && e.kind() == std::io::ErrorKind::NotFound
 479                {
 480                    return Ok(crate::initial_user_settings_content().to_string());
 481                }
 482                Err(err)
 483            }
 484        }
 485    }
 486
 487    fn update_settings_file_inner(
 488        &self,
 489        fs: Arc<dyn Fs>,
 490        update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
 491    ) -> oneshot::Receiver<Result<()>> {
 492        let (tx, rx) = oneshot::channel::<Result<()>>();
 493        self.setting_file_updates_tx
 494            .unbounded_send(Box::new(move |cx: AsyncApp| {
 495                async move {
 496                    let res = async move {
 497                        let old_text = Self::load_settings(&fs).await?;
 498                        let new_text = update(old_text, cx)?;
 499                        let settings_path = paths::settings_file().as_path();
 500                        if fs.is_file(settings_path).await {
 501                            let resolved_path =
 502                                fs.canonicalize(settings_path).await.with_context(|| {
 503                                    format!(
 504                                        "Failed to canonicalize settings path {:?}",
 505                                        settings_path
 506                                    )
 507                                })?;
 508
 509                            fs.atomic_write(resolved_path.clone(), new_text)
 510                                .await
 511                                .with_context(|| {
 512                                    format!("Failed to write settings to file {:?}", resolved_path)
 513                                })?;
 514                        } else {
 515                            fs.atomic_write(settings_path.to_path_buf(), new_text)
 516                                .await
 517                                .with_context(|| {
 518                                    format!("Failed to write settings to file {:?}", settings_path)
 519                                })?;
 520                        }
 521                        anyhow::Ok(())
 522                    }
 523                    .await;
 524
 525                    let new_res = match &res {
 526                        Ok(_) => anyhow::Ok(()),
 527                        Err(e) => Err(anyhow::anyhow!("Failed to write settings to file {:?}", e)),
 528                    };
 529
 530                    _ = tx.send(new_res);
 531                    res
 532                }
 533                .boxed_local()
 534            }))
 535            .map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
 536            .log_with_level(log::Level::Warn);
 537        return rx;
 538    }
 539
 540    pub fn update_settings_file(
 541        &self,
 542        fs: Arc<dyn Fs>,
 543        update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
 544    ) {
 545        _ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
 546            Ok(cx.read_global(|store: &SettingsStore, cx| {
 547                store.new_text_for_update(old_text, |content| update(content, cx))
 548            }))
 549        });
 550    }
 551
 552    pub fn import_vscode_settings(
 553        &self,
 554        fs: Arc<dyn Fs>,
 555        vscode_settings: VsCodeSettings,
 556    ) -> oneshot::Receiver<Result<()>> {
 557        self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
 558            Ok(cx.read_global(|store: &SettingsStore, _cx| {
 559                store.get_vscode_edits(old_text, &vscode_settings)
 560            }))
 561        })
 562    }
 563
 564    pub fn get_all_files(&self) -> Vec<SettingsFile> {
 565        let mut files = Vec::from_iter(
 566            self.local_settings
 567                .keys()
 568                // rev because these are sorted by path, so highest precedence is last
 569                .rev()
 570                .cloned()
 571                .map(SettingsFile::Project),
 572        );
 573
 574        if self.server_settings.is_some() {
 575            files.push(SettingsFile::Server);
 576        }
 577        // ignoring profiles
 578        // ignoring os profiles
 579        // ignoring release channel profiles
 580        // ignoring global
 581        // ignoring extension
 582
 583        if self.user_settings.is_some() {
 584            files.push(SettingsFile::User);
 585        }
 586        files.push(SettingsFile::Default);
 587        files
 588    }
 589
 590    pub fn get_content_for_file(&self, file: SettingsFile) -> Option<&SettingsContent> {
 591        match file {
 592            SettingsFile::User => self
 593                .user_settings
 594                .as_ref()
 595                .map(|settings| settings.content.as_ref()),
 596            SettingsFile::Default => Some(self.default_settings.as_ref()),
 597            SettingsFile::Server => self.server_settings.as_deref(),
 598            SettingsFile::Project(ref key) => self.local_settings.get(key),
 599            SettingsFile::Global => self.global_settings.as_deref(),
 600        }
 601    }
 602
 603    pub fn get_overrides_for_field<T>(
 604        &self,
 605        target_file: SettingsFile,
 606        get: fn(&SettingsContent) -> &Option<T>,
 607    ) -> Vec<SettingsFile> {
 608        let all_files = self.get_all_files();
 609        let mut found_file = false;
 610        let mut overrides = Vec::new();
 611
 612        for file in all_files.into_iter().rev() {
 613            if !found_file {
 614                found_file = file == target_file;
 615                continue;
 616            }
 617
 618            if let SettingsFile::Project((wt_id, ref path)) = file
 619                && let SettingsFile::Project((target_wt_id, ref target_path)) = target_file
 620                && (wt_id != target_wt_id || !target_path.starts_with(path))
 621            {
 622                // if requesting value from a local file, don't return values from local files in different worktrees
 623                continue;
 624            }
 625
 626            let Some(content) = self.get_content_for_file(file.clone()) else {
 627                continue;
 628            };
 629            if get(content).is_some() {
 630                overrides.push(file);
 631            }
 632        }
 633
 634        overrides
 635    }
 636
 637    /// Checks the given file, and files that the passed file overrides for the given field.
 638    /// Returns the first file found that contains the value.
 639    /// The value will only be None if no file contains the value.
 640    /// I.e. if no file contains the value, returns `(File::Default, None)`
 641    pub fn get_value_from_file<'a, T: 'a>(
 642        &'a self,
 643        target_file: SettingsFile,
 644        pick: fn(&'a SettingsContent) -> Option<T>,
 645    ) -> (SettingsFile, Option<T>) {
 646        self.get_value_from_file_inner(target_file, pick, true)
 647    }
 648
 649    /// Same as `Self::get_value_from_file` except that it does not include the current file.
 650    /// Therefore it returns the value that was potentially overloaded by the target file.
 651    pub fn get_value_up_to_file<'a, T: 'a>(
 652        &'a self,
 653        target_file: SettingsFile,
 654        pick: fn(&'a SettingsContent) -> Option<T>,
 655    ) -> (SettingsFile, Option<T>) {
 656        self.get_value_from_file_inner(target_file, pick, false)
 657    }
 658
 659    fn get_value_from_file_inner<'a, T: 'a>(
 660        &'a self,
 661        target_file: SettingsFile,
 662        pick: fn(&'a SettingsContent) -> Option<T>,
 663        include_target_file: bool,
 664    ) -> (SettingsFile, Option<T>) {
 665        // todo(settings_ui): Add a metadata field for overriding the "overrides" tag, for contextually different settings
 666        //  e.g. disable AI isn't overridden, or a vec that gets extended instead or some such
 667
 668        // todo(settings_ui) cache all files
 669        let all_files = self.get_all_files();
 670        let mut found_file = false;
 671
 672        for file in all_files.into_iter() {
 673            if !found_file && file != SettingsFile::Default {
 674                if file != target_file {
 675                    continue;
 676                }
 677                found_file = true;
 678                if !include_target_file {
 679                    continue;
 680                }
 681            }
 682
 683            if let SettingsFile::Project((worktree_id, ref path)) = file
 684                && let SettingsFile::Project((target_worktree_id, ref target_path)) = target_file
 685                && (worktree_id != target_worktree_id || !target_path.starts_with(&path))
 686            {
 687                // if requesting value from a local file, don't return values from local files in different worktrees
 688                continue;
 689            }
 690
 691            let Some(content) = self.get_content_for_file(file.clone()) else {
 692                continue;
 693            };
 694            if let Some(value) = pick(content) {
 695                return (file, Some(value));
 696            }
 697        }
 698
 699        (SettingsFile::Default, None)
 700    }
 701
 702    #[inline(always)]
 703    fn parse_and_migrate_zed_settings<SettingsContentType: RootUserSettings>(
 704        &mut self,
 705        user_settings_content: &str,
 706        file: SettingsFile,
 707    ) -> (Option<SettingsContentType>, SettingsParseResult) {
 708        let mut migration_status = MigrationStatus::NotNeeded;
 709        let (settings, parse_status) = if user_settings_content.is_empty() {
 710            SettingsContentType::parse_json("{}")
 711        } else {
 712            let migration_res = migrator::migrate_settings(user_settings_content);
 713            migration_status = match &migration_res {
 714                Ok(Some(_)) => MigrationStatus::Succeeded,
 715                Ok(None) => MigrationStatus::NotNeeded,
 716                Err(err) => MigrationStatus::Failed {
 717                    error: err.to_string(),
 718                },
 719            };
 720            let content = match &migration_res {
 721                Ok(Some(content)) => content,
 722                Ok(None) => user_settings_content,
 723                Err(_) => user_settings_content,
 724            };
 725            SettingsContentType::parse_json(content)
 726        };
 727
 728        let result = SettingsParseResult {
 729            parse_status,
 730            migration_status,
 731        };
 732        self.file_errors.insert(file, result.clone());
 733        return (settings, result);
 734    }
 735
 736    pub fn error_for_file(&self, file: SettingsFile) -> Option<SettingsParseResult> {
 737        self.file_errors
 738            .get(&file)
 739            .filter(|parse_result| parse_result.requires_user_action())
 740            .cloned()
 741    }
 742}
 743
 744impl SettingsStore {
 745    /// Updates the value of a setting in a JSON file, returning the new text
 746    /// for that JSON file.
 747    pub fn new_text_for_update(
 748        &self,
 749        old_text: String,
 750        update: impl FnOnce(&mut SettingsContent),
 751    ) -> String {
 752        let edits = self.edits_for_update(&old_text, update);
 753        let mut new_text = old_text;
 754        for (range, replacement) in edits.into_iter() {
 755            new_text.replace_range(range, &replacement);
 756        }
 757        new_text
 758    }
 759
 760    pub fn get_vscode_edits(&self, old_text: String, vscode: &VsCodeSettings) -> String {
 761        self.new_text_for_update(old_text, |content| {
 762            content.merge_from(&vscode.settings_content())
 763        })
 764    }
 765
 766    /// Updates the value of a setting in a JSON file, returning a list
 767    /// of edits to apply to the JSON file.
 768    pub fn edits_for_update(
 769        &self,
 770        text: &str,
 771        update: impl FnOnce(&mut SettingsContent),
 772    ) -> Vec<(Range<usize>, String)> {
 773        let old_content = UserSettingsContent::parse_json_with_comments(text)
 774            .log_err()
 775            .unwrap_or_default();
 776        let mut new_content = old_content.clone();
 777        update(&mut new_content.content);
 778
 779        let old_value = serde_json::to_value(&old_content).unwrap();
 780        let new_value = serde_json::to_value(new_content).unwrap();
 781
 782        let mut key_path = Vec::new();
 783        let mut edits = Vec::new();
 784        let tab_size = infer_json_indent_size(&text);
 785        let mut text = text.to_string();
 786        update_value_in_json_text(
 787            &mut text,
 788            &mut key_path,
 789            tab_size,
 790            &old_value,
 791            &new_value,
 792            &mut edits,
 793        );
 794        edits
 795    }
 796
 797    /// Sets the default settings via a JSON string.
 798    ///
 799    /// The string should contain a JSON object with a default value for every setting.
 800    pub fn set_default_settings(
 801        &mut self,
 802        default_settings_content: &str,
 803        cx: &mut App,
 804    ) -> Result<()> {
 805        self.default_settings =
 806            SettingsContent::parse_json_with_comments(default_settings_content)?.into();
 807        self.recompute_values(None, cx);
 808        Ok(())
 809    }
 810
 811    /// Sets the user settings via a JSON string.
 812    #[must_use]
 813    pub fn set_user_settings(
 814        &mut self,
 815        user_settings_content: &str,
 816        cx: &mut App,
 817    ) -> SettingsParseResult {
 818        let (settings, parse_result) = self.parse_and_migrate_zed_settings::<UserSettingsContent>(
 819            user_settings_content,
 820            SettingsFile::User,
 821        );
 822
 823        if let Some(settings) = settings {
 824            self.user_settings = Some(settings);
 825            self.recompute_values(None, cx);
 826        }
 827        return parse_result;
 828    }
 829
 830    /// Sets the global settings via a JSON string.
 831    #[must_use]
 832    pub fn set_global_settings(
 833        &mut self,
 834        global_settings_content: &str,
 835        cx: &mut App,
 836    ) -> SettingsParseResult {
 837        let (settings, parse_result) = self.parse_and_migrate_zed_settings::<SettingsContent>(
 838            global_settings_content,
 839            SettingsFile::Global,
 840        );
 841
 842        if let Some(settings) = settings {
 843            self.global_settings = Some(Box::new(settings));
 844            self.recompute_values(None, cx);
 845        }
 846        return parse_result;
 847    }
 848
 849    pub fn set_server_settings(
 850        &mut self,
 851        server_settings_content: &str,
 852        cx: &mut App,
 853    ) -> Result<()> {
 854        let settings = if server_settings_content.is_empty() {
 855            None
 856        } else {
 857            Option::<SettingsContent>::parse_json_with_comments(server_settings_content)?
 858        };
 859
 860        // Rewrite the server settings into a content type
 861        self.server_settings = settings.map(|settings| Box::new(settings));
 862
 863        self.recompute_values(None, cx);
 864        Ok(())
 865    }
 866
 867    /// Sets language-specific semantic token rules.
 868    ///
 869    /// These rules are registered by language modules (e.g. the Rust language module)
 870    /// and are stored separately from the global rules. They are only applied to
 871    /// buffers of the matching language by the `SemanticTokenStylizer`.
 872    ///
 873    /// These should be registered before any `SemanticTokenStylizer` instances are
 874    /// created (typically during `languages::init`), as existing cached stylizers
 875    /// are not automatically invalidated.
 876    pub fn set_language_semantic_token_rules(
 877        &mut self,
 878        language: SharedString,
 879        rules: SemanticTokenRules,
 880    ) {
 881        self.language_semantic_token_rules.insert(language, rules);
 882    }
 883
 884    /// Returns the language-specific semantic token rules for the given language,
 885    /// if any have been registered.
 886    pub fn language_semantic_token_rules(&self, language: &str) -> Option<&SemanticTokenRules> {
 887        self.language_semantic_token_rules.get(language)
 888    }
 889
 890    /// Add or remove a set of local settings via a JSON string.
 891    pub fn set_local_settings(
 892        &mut self,
 893        root_id: WorktreeId,
 894        path: LocalSettingsPath,
 895        kind: LocalSettingsKind,
 896        settings_content: Option<&str>,
 897        cx: &mut App,
 898    ) -> std::result::Result<(), InvalidSettingsError> {
 899        let content = settings_content
 900            .map(|content| content.trim())
 901            .filter(|content| !content.is_empty());
 902        let mut zed_settings_changed = false;
 903        match (path.clone(), kind, content) {
 904            (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Tasks, _) => {
 905                return Err(InvalidSettingsError::Tasks {
 906                    message: "Attempted to submit tasks into the settings store".to_string(),
 907                    path: directory_path
 908                        .join(RelPath::unix(task_file_name()).unwrap())
 909                        .as_std_path()
 910                        .to_path_buf(),
 911                });
 912            }
 913            (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Debug, _) => {
 914                return Err(InvalidSettingsError::Debug {
 915                    message: "Attempted to submit debugger config into the settings store"
 916                        .to_string(),
 917                    path: directory_path
 918                        .join(RelPath::unix(task_file_name()).unwrap())
 919                        .as_std_path()
 920                        .to_path_buf(),
 921                });
 922            }
 923            (LocalSettingsPath::InWorktree(directory_path), LocalSettingsKind::Settings, None) => {
 924                zed_settings_changed = self
 925                    .local_settings
 926                    .remove(&(root_id, directory_path.clone()))
 927                    .is_some();
 928                self.file_errors
 929                    .remove(&SettingsFile::Project((root_id, directory_path)));
 930            }
 931            (
 932                LocalSettingsPath::InWorktree(directory_path),
 933                LocalSettingsKind::Settings,
 934                Some(settings_contents),
 935            ) => {
 936                let (new_settings, parse_result) = self
 937                    .parse_and_migrate_zed_settings::<ProjectSettingsContent>(
 938                        settings_contents,
 939                        SettingsFile::Project((root_id, directory_path.clone())),
 940                    );
 941                match parse_result.parse_status {
 942                    ParseStatus::Success => Ok(()),
 943                    ParseStatus::Failed { error } => Err(InvalidSettingsError::LocalSettings {
 944                        path: directory_path.join(local_settings_file_relative_path()),
 945                        message: error,
 946                    }),
 947                }?;
 948                if let Some(new_settings) = new_settings {
 949                    match self.local_settings.entry((root_id, directory_path)) {
 950                        btree_map::Entry::Vacant(v) => {
 951                            v.insert(SettingsContent {
 952                                project: new_settings,
 953                                ..Default::default()
 954                            });
 955                            zed_settings_changed = true;
 956                        }
 957                        btree_map::Entry::Occupied(mut o) => {
 958                            if &o.get().project != &new_settings {
 959                                o.insert(SettingsContent {
 960                                    project: new_settings,
 961                                    ..Default::default()
 962                                });
 963                                zed_settings_changed = true;
 964                            }
 965                        }
 966                    }
 967                }
 968            }
 969            (directory_path, LocalSettingsKind::Editorconfig, editorconfig_contents) => {
 970                self.editorconfig_store.update(cx, |store, _| {
 971                    store.set_configs(root_id, directory_path, editorconfig_contents)
 972                })?;
 973            }
 974            (LocalSettingsPath::OutsideWorktree(path), kind, _) => {
 975                log::error!(
 976                    "OutsideWorktree path {:?} with kind {:?} is only supported by editorconfig",
 977                    path,
 978                    kind
 979                );
 980                return Ok(());
 981            }
 982        }
 983        if let LocalSettingsPath::InWorktree(directory_path) = &path {
 984            if zed_settings_changed {
 985                self.recompute_values(Some((root_id, &directory_path)), cx);
 986            }
 987        }
 988        Ok(())
 989    }
 990
 991    pub fn set_extension_settings(
 992        &mut self,
 993        content: ExtensionsSettingsContent,
 994        cx: &mut App,
 995    ) -> Result<()> {
 996        self.extension_settings = Some(Box::new(SettingsContent {
 997            project: ProjectSettingsContent {
 998                all_languages: content.all_languages,
 999                ..Default::default()
1000            },
1001            ..Default::default()
1002        }));
1003        self.recompute_values(None, cx);
1004        Ok(())
1005    }
1006
1007    /// Add or remove a set of local settings via a JSON string.
1008    pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
1009        self.local_settings
1010            .retain(|(worktree_id, _), _| worktree_id != &root_id);
1011
1012        self.editorconfig_store
1013            .update(cx, |store, _cx| store.remove_for_worktree(root_id));
1014
1015        for setting_value in self.setting_values.values_mut() {
1016            setting_value.clear_local_values(root_id);
1017        }
1018        self.recompute_values(Some((root_id, RelPath::empty())), cx);
1019        Ok(())
1020    }
1021
1022    pub fn local_settings(
1023        &self,
1024        root_id: WorktreeId,
1025    ) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
1026        self.local_settings
1027            .range(
1028                (root_id, RelPath::empty().into())
1029                    ..(
1030                        WorktreeId::from_usize(root_id.to_usize() + 1),
1031                        RelPath::empty().into(),
1032                    ),
1033            )
1034            .map(|((_, path), content)| (path.clone(), &content.project))
1035    }
1036
1037    /// Configures common schema replacements shared between user and project
1038    /// settings schemas.
1039    ///
1040    /// This sets up language-specific settings and LSP adapter settings that
1041    /// are valid in both user and project settings.
1042    fn configure_schema_generator(
1043        generator: &mut schemars::SchemaGenerator,
1044        params: &SettingsJsonSchemaParams,
1045    ) {
1046        let language_settings_content_ref = generator
1047            .subschema_for::<LanguageSettingsContent>()
1048            .to_value();
1049
1050        replace_subschema::<LanguageToSettingsMap>(generator, || {
1051            json_schema!({
1052                "type": "object",
1053                "errorMessage": "No language with this name is installed.",
1054                "properties": params.language_names.iter().map(|name| (name.clone(), language_settings_content_ref.clone())).collect::<serde_json::Map<_, _>>()
1055            })
1056        });
1057
1058        generator.subschema_for::<LspSettings>();
1059
1060        let lsp_settings_definition = generator
1061            .definitions()
1062            .get("LspSettings")
1063            .expect("LspSettings should be defined")
1064            .clone();
1065
1066        replace_subschema::<LspSettingsMap>(generator, || {
1067            let mut lsp_properties = serde_json::Map::new();
1068
1069            for adapter_name in params.lsp_adapter_names {
1070                let mut base_lsp_settings = lsp_settings_definition
1071                    .as_object()
1072                    .expect("LspSettings should be an object")
1073                    .clone();
1074
1075                if let Some(properties) = base_lsp_settings.get_mut("properties") {
1076                    if let Some(properties_object) = properties.as_object_mut() {
1077                        properties_object.insert(
1078                            "initialization_options".to_string(),
1079                            serde_json::json!({
1080                                "$ref": format!("{LSP_SETTINGS_SCHEMA_URL_PREFIX}{adapter_name}")
1081                            }),
1082                        );
1083                    }
1084                }
1085
1086                lsp_properties.insert(
1087                    adapter_name.clone(),
1088                    serde_json::Value::Object(base_lsp_settings),
1089                );
1090            }
1091
1092            json_schema!({
1093                "type": "object",
1094                "properties": lsp_properties
1095            })
1096        });
1097    }
1098
1099    pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
1100        let mut generator = schemars::generate::SchemaSettings::draft2019_09()
1101            .with_transform(DefaultDenyUnknownFields)
1102            .with_transform(AllowTrailingCommas)
1103            .into_generator();
1104
1105        UserSettingsContent::json_schema(&mut generator);
1106        Self::configure_schema_generator(&mut generator, params);
1107
1108        replace_subschema::<FontFamilyName>(&mut generator, || {
1109            json_schema!({
1110                "type": "string",
1111                "enum": params.font_names,
1112            })
1113        });
1114
1115        replace_subschema::<ThemeName>(&mut generator, || {
1116            json_schema!({
1117                "type": "string",
1118                "enum": params.theme_names,
1119            })
1120        });
1121
1122        replace_subschema::<IconThemeName>(&mut generator, || {
1123            json_schema!({
1124                "type": "string",
1125                "enum": params.icon_theme_names,
1126            })
1127        });
1128
1129        generator
1130            .root_schema_for::<UserSettingsContent>()
1131            .to_value()
1132    }
1133
1134    /// Generate JSON schema for project settings, including only settings valid
1135    /// for project-level configurations.
1136    pub fn project_json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
1137        let mut generator = schemars::generate::SchemaSettings::draft2019_09()
1138            .with_transform(DefaultDenyUnknownFields)
1139            .with_transform(AllowTrailingCommas)
1140            .into_generator();
1141
1142        ProjectSettingsContent::json_schema(&mut generator);
1143        Self::configure_schema_generator(&mut generator, params);
1144
1145        generator
1146            .root_schema_for::<ProjectSettingsContent>()
1147            .to_value()
1148    }
1149
1150    fn recompute_values(
1151        &mut self,
1152        changed_local_path: Option<(WorktreeId, &RelPath)>,
1153        cx: &mut App,
1154    ) {
1155        // Reload the global and local values for every setting.
1156        let mut project_settings_stack = Vec::<SettingsContent>::new();
1157        let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
1158
1159        if changed_local_path.is_none() {
1160            let mut merged = self.default_settings.as_ref().clone();
1161            merged.merge_from_option(self.extension_settings.as_deref());
1162            merged.merge_from_option(self.global_settings.as_deref());
1163            if let Some(user_settings) = self.user_settings.as_ref() {
1164                merged.merge_from(&user_settings.content);
1165                merged.merge_from_option(user_settings.for_release_channel());
1166                merged.merge_from_option(user_settings.for_os());
1167                merged.merge_from_option(user_settings.for_profile(cx));
1168            }
1169            merged.merge_from_option(self.server_settings.as_deref());
1170            self.merged_settings = Rc::new(merged);
1171
1172            for setting_value in self.setting_values.values_mut() {
1173                let value = setting_value.from_settings(&self.merged_settings);
1174                setting_value.set_global_value(value);
1175            }
1176        }
1177
1178        for ((root_id, directory_path), local_settings) in &self.local_settings {
1179            // Build a stack of all of the local values for that setting.
1180            while let Some(prev_entry) = paths_stack.last() {
1181                if let Some((prev_root_id, prev_path)) = prev_entry
1182                    && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
1183                {
1184                    paths_stack.pop();
1185                    project_settings_stack.pop();
1186                    continue;
1187                }
1188                break;
1189            }
1190
1191            paths_stack.push(Some((*root_id, directory_path.as_ref())));
1192            let mut merged_local_settings = if let Some(deepest) = project_settings_stack.last() {
1193                (*deepest).clone()
1194            } else {
1195                self.merged_settings.as_ref().clone()
1196            };
1197            merged_local_settings.merge_from(local_settings);
1198
1199            project_settings_stack.push(merged_local_settings);
1200
1201            // If a local settings file changed, then avoid recomputing local
1202            // settings for any path outside of that directory.
1203            if changed_local_path.is_some_and(|(changed_root_id, changed_local_path)| {
1204                *root_id != changed_root_id || !directory_path.starts_with(changed_local_path)
1205            }) {
1206                continue;
1207            }
1208
1209            for setting_value in self.setting_values.values_mut() {
1210                let value = setting_value.from_settings(&project_settings_stack.last().unwrap());
1211                setting_value.set_local_value(*root_id, directory_path.clone(), value);
1212            }
1213        }
1214    }
1215}
1216
1217/// The result of parsing settings, including any migration attempts
1218#[derive(Debug, Clone, PartialEq, Eq)]
1219pub struct SettingsParseResult {
1220    /// The result of parsing the settings file (possibly after migration)
1221    pub parse_status: ParseStatus,
1222    /// The result of attempting to migrate the settings file
1223    pub migration_status: MigrationStatus,
1224}
1225
1226#[derive(Debug, Clone, PartialEq, Eq)]
1227pub enum MigrationStatus {
1228    /// No migration was needed - settings are up to date
1229    NotNeeded,
1230    /// Settings were automatically migrated in memory, but the file needs to be updated
1231    Succeeded,
1232    /// Migration was attempted but failed. Original settings were parsed instead.
1233    Failed { error: String },
1234}
1235
1236impl Default for SettingsParseResult {
1237    fn default() -> Self {
1238        Self {
1239            parse_status: ParseStatus::Success,
1240            migration_status: MigrationStatus::NotNeeded,
1241        }
1242    }
1243}
1244
1245impl SettingsParseResult {
1246    pub fn unwrap(self) -> bool {
1247        self.result().unwrap()
1248    }
1249
1250    pub fn expect(self, message: &str) -> bool {
1251        self.result().expect(message)
1252    }
1253
1254    /// Formats the ParseResult as a Result type. This is a lossy conversion
1255    pub fn result(self) -> Result<bool> {
1256        let migration_result = match self.migration_status {
1257            MigrationStatus::NotNeeded => Ok(false),
1258            MigrationStatus::Succeeded => Ok(true),
1259            MigrationStatus::Failed { error } => {
1260                Err(anyhow::format_err!(error)).context("Failed to migrate settings")
1261            }
1262        };
1263
1264        let parse_result = match self.parse_status {
1265            ParseStatus::Success => Ok(()),
1266            ParseStatus::Failed { error } => {
1267                Err(anyhow::format_err!(error)).context("Failed to parse settings")
1268            }
1269        };
1270
1271        match (migration_result, parse_result) {
1272            (migration_result @ Ok(_), Ok(())) => migration_result,
1273            (Err(migration_err), Ok(())) => Err(migration_err),
1274            (_, Err(parse_err)) => Err(parse_err),
1275        }
1276    }
1277
1278    /// Returns true if there were any errors migrating and parsing the settings content or if migration was required but there were no errors
1279    pub fn requires_user_action(&self) -> bool {
1280        matches!(self.parse_status, ParseStatus::Failed { .. })
1281            || matches!(
1282                self.migration_status,
1283                MigrationStatus::Succeeded | MigrationStatus::Failed { .. }
1284            )
1285    }
1286
1287    pub fn ok(self) -> Option<bool> {
1288        self.result().ok()
1289    }
1290
1291    pub fn parse_error(&self) -> Option<String> {
1292        match &self.parse_status {
1293            ParseStatus::Failed { error } => Some(error.clone()),
1294            ParseStatus::Success => None,
1295        }
1296    }
1297}
1298
1299#[derive(Debug, Clone, PartialEq)]
1300pub enum InvalidSettingsError {
1301    LocalSettings {
1302        path: Arc<RelPath>,
1303        message: String,
1304    },
1305    UserSettings {
1306        message: String,
1307    },
1308    ServerSettings {
1309        message: String,
1310    },
1311    DefaultSettings {
1312        message: String,
1313    },
1314    Editorconfig {
1315        path: LocalSettingsPath,
1316        message: String,
1317    },
1318    Tasks {
1319        path: PathBuf,
1320        message: String,
1321    },
1322    Debug {
1323        path: PathBuf,
1324        message: String,
1325    },
1326}
1327
1328impl std::fmt::Display for InvalidSettingsError {
1329    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1330        match self {
1331            InvalidSettingsError::LocalSettings { message, .. }
1332            | InvalidSettingsError::UserSettings { message }
1333            | InvalidSettingsError::ServerSettings { message }
1334            | InvalidSettingsError::DefaultSettings { message }
1335            | InvalidSettingsError::Tasks { message, .. }
1336            | InvalidSettingsError::Editorconfig { message, .. }
1337            | InvalidSettingsError::Debug { message, .. } => {
1338                write!(f, "{message}")
1339            }
1340        }
1341    }
1342}
1343impl std::error::Error for InvalidSettingsError {}
1344
1345impl Debug for SettingsStore {
1346    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1347        f.debug_struct("SettingsStore")
1348            .field(
1349                "types",
1350                &self
1351                    .setting_values
1352                    .values()
1353                    .map(|value| value.setting_type_name())
1354                    .collect::<Vec<_>>(),
1355            )
1356            .field("default_settings", &self.default_settings)
1357            .field("user_settings", &self.user_settings)
1358            .field("local_settings", &self.local_settings)
1359            .finish_non_exhaustive()
1360    }
1361}
1362
1363impl<T: Settings> AnySettingValue for SettingValue<T> {
1364    fn from_settings(&self, s: &SettingsContent) -> Box<dyn Any> {
1365        Box::new(T::from_settings(s)) as _
1366    }
1367
1368    fn setting_type_name(&self) -> &'static str {
1369        type_name::<T>()
1370    }
1371
1372    fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
1373        self.local_values
1374            .iter()
1375            .map(|(id, path, value)| (*id, path.clone(), value as _))
1376            .collect()
1377    }
1378
1379    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1380        if let Some(SettingsLocation { worktree_id, path }) = path {
1381            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1382                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1383                    return value;
1384                }
1385            }
1386        }
1387
1388        self.global_value
1389            .as_ref()
1390            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1391    }
1392
1393    fn set_global_value(&mut self, value: Box<dyn Any>) {
1394        self.global_value = Some(*value.downcast().unwrap());
1395    }
1396
1397    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
1398        let value = *value.downcast().unwrap();
1399        match self
1400            .local_values
1401            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1402        {
1403            Ok(ix) => self.local_values[ix].2 = value,
1404            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1405        }
1406    }
1407
1408    fn clear_local_values(&mut self, root_id: WorktreeId) {
1409        self.local_values
1410            .retain(|(worktree_id, _, _)| *worktree_id != root_id);
1411    }
1412}
1413
1414#[cfg(test)]
1415mod tests {
1416    use std::num::NonZeroU32;
1417
1418    use crate::{
1419        ClosePosition, ItemSettingsContent, VsCodeSettingsSource, default_settings,
1420        settings_content::LanguageSettingsContent, test_settings,
1421    };
1422
1423    use super::*;
1424    use unindent::Unindent;
1425    use util::rel_path::rel_path;
1426
1427    #[derive(Debug, PartialEq)]
1428    struct AutoUpdateSetting {
1429        auto_update: bool,
1430    }
1431
1432    impl Settings for AutoUpdateSetting {
1433        fn from_settings(content: &SettingsContent) -> Self {
1434            AutoUpdateSetting {
1435                auto_update: content.auto_update.unwrap(),
1436            }
1437        }
1438    }
1439
1440    #[derive(Debug, PartialEq)]
1441    struct ItemSettings {
1442        close_position: ClosePosition,
1443        git_status: bool,
1444    }
1445
1446    impl Settings for ItemSettings {
1447        fn from_settings(content: &SettingsContent) -> Self {
1448            let content = content.tabs.clone().unwrap();
1449            ItemSettings {
1450                close_position: content.close_position.unwrap(),
1451                git_status: content.git_status.unwrap(),
1452            }
1453        }
1454    }
1455
1456    #[derive(Debug, PartialEq)]
1457    struct DefaultLanguageSettings {
1458        tab_size: NonZeroU32,
1459        preferred_line_length: u32,
1460    }
1461
1462    impl Settings for DefaultLanguageSettings {
1463        fn from_settings(content: &SettingsContent) -> Self {
1464            let content = &content.project.all_languages.defaults;
1465            DefaultLanguageSettings {
1466                tab_size: content.tab_size.unwrap(),
1467                preferred_line_length: content.preferred_line_length.unwrap(),
1468            }
1469        }
1470    }
1471
1472    #[derive(Debug, PartialEq)]
1473    struct ThemeSettings {
1474        buffer_font_family: FontFamilyName,
1475        buffer_font_fallbacks: Vec<FontFamilyName>,
1476    }
1477
1478    impl Settings for ThemeSettings {
1479        fn from_settings(content: &SettingsContent) -> Self {
1480            let content = content.theme.clone();
1481            ThemeSettings {
1482                buffer_font_family: content.buffer_font_family.unwrap(),
1483                buffer_font_fallbacks: content.buffer_font_fallbacks.unwrap(),
1484            }
1485        }
1486    }
1487
1488    #[gpui::test]
1489    fn test_settings_store_basic(cx: &mut App) {
1490        let mut store = SettingsStore::new(cx, &default_settings());
1491        store.register_setting::<AutoUpdateSetting>();
1492        store.register_setting::<ItemSettings>();
1493        store.register_setting::<DefaultLanguageSettings>();
1494
1495        assert_eq!(
1496            store.get::<AutoUpdateSetting>(None),
1497            &AutoUpdateSetting { auto_update: true }
1498        );
1499        assert_eq!(
1500            store.get::<ItemSettings>(None).close_position,
1501            ClosePosition::Right
1502        );
1503
1504        store
1505            .set_user_settings(
1506                r#"{
1507                    "auto_update": false,
1508                    "tabs": {
1509                      "close_position": "left"
1510                    }
1511                }"#,
1512                cx,
1513            )
1514            .unwrap();
1515
1516        assert_eq!(
1517            store.get::<AutoUpdateSetting>(None),
1518            &AutoUpdateSetting { auto_update: false }
1519        );
1520        assert_eq!(
1521            store.get::<ItemSettings>(None).close_position,
1522            ClosePosition::Left
1523        );
1524
1525        store
1526            .set_local_settings(
1527                WorktreeId::from_usize(1),
1528                LocalSettingsPath::InWorktree(rel_path("root1").into()),
1529                LocalSettingsKind::Settings,
1530                Some(r#"{ "tab_size": 5 }"#),
1531                cx,
1532            )
1533            .unwrap();
1534        store
1535            .set_local_settings(
1536                WorktreeId::from_usize(1),
1537                LocalSettingsPath::InWorktree(rel_path("root1/subdir").into()),
1538                LocalSettingsKind::Settings,
1539                Some(r#"{ "preferred_line_length": 50 }"#),
1540                cx,
1541            )
1542            .unwrap();
1543
1544        store
1545            .set_local_settings(
1546                WorktreeId::from_usize(1),
1547                LocalSettingsPath::InWorktree(rel_path("root2").into()),
1548                LocalSettingsKind::Settings,
1549                Some(r#"{ "tab_size": 9, "auto_update": true}"#),
1550                cx,
1551            )
1552            .unwrap();
1553
1554        assert_eq!(
1555            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1556                worktree_id: WorktreeId::from_usize(1),
1557                path: rel_path("root1/something"),
1558            })),
1559            &DefaultLanguageSettings {
1560                preferred_line_length: 80,
1561                tab_size: 5.try_into().unwrap(),
1562            }
1563        );
1564        assert_eq!(
1565            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1566                worktree_id: WorktreeId::from_usize(1),
1567                path: rel_path("root1/subdir/something"),
1568            })),
1569            &DefaultLanguageSettings {
1570                preferred_line_length: 50,
1571                tab_size: 5.try_into().unwrap(),
1572            }
1573        );
1574        assert_eq!(
1575            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1576                worktree_id: WorktreeId::from_usize(1),
1577                path: rel_path("root2/something"),
1578            })),
1579            &DefaultLanguageSettings {
1580                preferred_line_length: 80,
1581                tab_size: 9.try_into().unwrap(),
1582            }
1583        );
1584        assert_eq!(
1585            store.get::<AutoUpdateSetting>(Some(SettingsLocation {
1586                worktree_id: WorktreeId::from_usize(1),
1587                path: rel_path("root2/something")
1588            })),
1589            &AutoUpdateSetting { auto_update: false }
1590        );
1591    }
1592
1593    #[gpui::test]
1594    fn test_setting_store_assign_json_before_register(cx: &mut App) {
1595        let mut store = SettingsStore::new(cx, &test_settings());
1596        store
1597            .set_user_settings(r#"{ "auto_update": false }"#, cx)
1598            .unwrap();
1599        store.register_setting::<AutoUpdateSetting>();
1600
1601        assert_eq!(
1602            store.get::<AutoUpdateSetting>(None),
1603            &AutoUpdateSetting { auto_update: false }
1604        );
1605    }
1606
1607    #[track_caller]
1608    fn check_settings_update(
1609        store: &mut SettingsStore,
1610        old_json: String,
1611        update: fn(&mut SettingsContent),
1612        expected_new_json: String,
1613        cx: &mut App,
1614    ) {
1615        store.set_user_settings(&old_json, cx).ok();
1616        let edits = store.edits_for_update(&old_json, update);
1617        let mut new_json = old_json;
1618        for (range, replacement) in edits.into_iter() {
1619            new_json.replace_range(range, &replacement);
1620        }
1621        pretty_assertions::assert_eq!(new_json, expected_new_json);
1622    }
1623
1624    #[gpui::test]
1625    fn test_setting_store_update(cx: &mut App) {
1626        let mut store = SettingsStore::new(cx, &test_settings());
1627
1628        // entries added and updated
1629        check_settings_update(
1630            &mut store,
1631            r#"{
1632                "languages": {
1633                    "JSON": {
1634                        "auto_indent": true
1635                    }
1636                }
1637            }"#
1638            .unindent(),
1639            |settings| {
1640                settings
1641                    .languages_mut()
1642                    .get_mut("JSON")
1643                    .unwrap()
1644                    .auto_indent = Some(false);
1645
1646                settings.languages_mut().insert(
1647                    "Rust".into(),
1648                    LanguageSettingsContent {
1649                        auto_indent: Some(true),
1650                        ..Default::default()
1651                    },
1652                );
1653            },
1654            r#"{
1655                "languages": {
1656                    "Rust": {
1657                        "auto_indent": true
1658                    },
1659                    "JSON": {
1660                        "auto_indent": false
1661                    }
1662                }
1663            }"#
1664            .unindent(),
1665            cx,
1666        );
1667
1668        // entries removed
1669        check_settings_update(
1670            &mut store,
1671            r#"{
1672                "languages": {
1673                    "Rust": {
1674                        "language_setting_2": true
1675                    },
1676                    "JSON": {
1677                        "language_setting_1": false
1678                    }
1679                }
1680            }"#
1681            .unindent(),
1682            |settings| {
1683                settings.languages_mut().remove("JSON").unwrap();
1684            },
1685            r#"{
1686                "languages": {
1687                    "Rust": {
1688                        "language_setting_2": true
1689                    }
1690                }
1691            }"#
1692            .unindent(),
1693            cx,
1694        );
1695
1696        check_settings_update(
1697            &mut store,
1698            r#"{
1699                "languages": {
1700                    "Rust": {
1701                        "language_setting_2": true
1702                    },
1703                    "JSON": {
1704                        "language_setting_1": false
1705                    }
1706                }
1707            }"#
1708            .unindent(),
1709            |settings| {
1710                settings.languages_mut().remove("Rust").unwrap();
1711            },
1712            r#"{
1713                "languages": {
1714                    "JSON": {
1715                        "language_setting_1": false
1716                    }
1717                }
1718            }"#
1719            .unindent(),
1720            cx,
1721        );
1722
1723        // weird formatting
1724        check_settings_update(
1725            &mut store,
1726            r#"{
1727                "tabs":   { "close_position": "left", "name": "Max"  }
1728                }"#
1729            .unindent(),
1730            |settings| {
1731                settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left);
1732            },
1733            r#"{
1734                "tabs":   { "close_position": "left", "name": "Max"  }
1735                }"#
1736            .unindent(),
1737            cx,
1738        );
1739
1740        // single-line formatting, other keys
1741        check_settings_update(
1742            &mut store,
1743            r#"{ "one": 1, "two": 2 }"#.to_owned(),
1744            |settings| settings.auto_update = Some(true),
1745            r#"{ "auto_update": true, "one": 1, "two": 2 }"#.to_owned(),
1746            cx,
1747        );
1748
1749        // empty object
1750        check_settings_update(
1751            &mut store,
1752            r#"{
1753                "tabs": {}
1754            }"#
1755            .unindent(),
1756            |settings| settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left),
1757            r#"{
1758                "tabs": {
1759                    "close_position": "left"
1760                }
1761            }"#
1762            .unindent(),
1763            cx,
1764        );
1765
1766        // no content
1767        check_settings_update(
1768            &mut store,
1769            r#""#.unindent(),
1770            |settings| {
1771                settings.tabs = Some(ItemSettingsContent {
1772                    git_status: Some(true),
1773                    ..Default::default()
1774                })
1775            },
1776            r#"{
1777              "tabs": {
1778                "git_status": true
1779              }
1780            }
1781            "#
1782            .unindent(),
1783            cx,
1784        );
1785
1786        check_settings_update(
1787            &mut store,
1788            r#"{
1789            }
1790            "#
1791            .unindent(),
1792            |settings| settings.title_bar.get_or_insert_default().show_branch_name = Some(true),
1793            r#"{
1794              "title_bar": {
1795                "show_branch_name": true
1796              }
1797            }
1798            "#
1799            .unindent(),
1800            cx,
1801        );
1802    }
1803
1804    #[gpui::test]
1805    fn test_vscode_import(cx: &mut App) {
1806        let mut store = SettingsStore::new(cx, &test_settings());
1807        store.register_setting::<DefaultLanguageSettings>();
1808        store.register_setting::<ItemSettings>();
1809        store.register_setting::<AutoUpdateSetting>();
1810        store.register_setting::<ThemeSettings>();
1811
1812        // create settings that werent present
1813        check_vscode_import(
1814            &mut store,
1815            r#"{
1816            }
1817            "#
1818            .unindent(),
1819            r#" { "editor.tabSize": 37 } "#.to_owned(),
1820            r#"{
1821              "base_keymap": "VSCode",
1822              "tab_size": 37
1823            }
1824            "#
1825            .unindent(),
1826            cx,
1827        );
1828
1829        // persist settings that were present
1830        check_vscode_import(
1831            &mut store,
1832            r#"{
1833                "preferred_line_length": 99,
1834            }
1835            "#
1836            .unindent(),
1837            r#"{ "editor.tabSize": 42 }"#.to_owned(),
1838            r#"{
1839                "base_keymap": "VSCode",
1840                "tab_size": 42,
1841                "preferred_line_length": 99,
1842            }
1843            "#
1844            .unindent(),
1845            cx,
1846        );
1847
1848        // don't clobber settings that aren't present in vscode
1849        check_vscode_import(
1850            &mut store,
1851            r#"{
1852                "preferred_line_length": 99,
1853                "tab_size": 42
1854            }
1855            "#
1856            .unindent(),
1857            r#"{}"#.to_owned(),
1858            r#"{
1859                "base_keymap": "VSCode",
1860                "preferred_line_length": 99,
1861                "tab_size": 42
1862            }
1863            "#
1864            .unindent(),
1865            cx,
1866        );
1867
1868        // custom enum
1869        check_vscode_import(
1870            &mut store,
1871            r#"{
1872            }
1873            "#
1874            .unindent(),
1875            r#"{ "git.decorations.enabled": true }"#.to_owned(),
1876            r#"{
1877              "project_panel": {
1878                "git_status": true
1879              },
1880              "outline_panel": {
1881                "git_status": true
1882              },
1883              "base_keymap": "VSCode",
1884              "tabs": {
1885                "git_status": true
1886              }
1887            }
1888            "#
1889            .unindent(),
1890            cx,
1891        );
1892
1893        // font-family
1894        check_vscode_import(
1895            &mut store,
1896            r#"{
1897            }
1898            "#
1899            .unindent(),
1900            r#"{ "editor.fontFamily": "Cascadia Code, 'Consolas', Courier New" }"#.to_owned(),
1901            r#"{
1902              "base_keymap": "VSCode",
1903              "buffer_font_fallbacks": [
1904                "Consolas",
1905                "Courier New"
1906              ],
1907              "buffer_font_family": "Cascadia Code"
1908            }
1909            "#
1910            .unindent(),
1911            cx,
1912        );
1913    }
1914
1915    #[track_caller]
1916    fn check_vscode_import(
1917        store: &mut SettingsStore,
1918        old: String,
1919        vscode: String,
1920        expected: String,
1921        cx: &mut App,
1922    ) {
1923        store.set_user_settings(&old, cx).ok();
1924        let new = store.get_vscode_edits(
1925            old,
1926            &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1927        );
1928        pretty_assertions::assert_eq!(new, expected);
1929    }
1930
1931    #[gpui::test]
1932    fn test_update_git_settings(cx: &mut App) {
1933        let store = SettingsStore::new(cx, &test_settings());
1934
1935        let actual = store.new_text_for_update("{}".to_string(), |current| {
1936            current
1937                .git
1938                .get_or_insert_default()
1939                .inline_blame
1940                .get_or_insert_default()
1941                .enabled = Some(true);
1942        });
1943        pretty_assertions::assert_str_eq!(
1944            actual,
1945            r#"{
1946              "git": {
1947                "inline_blame": {
1948                  "enabled": true
1949                }
1950              }
1951            }
1952            "#
1953            .unindent()
1954        );
1955    }
1956
1957    #[gpui::test]
1958    fn test_global_settings(cx: &mut App) {
1959        let mut store = SettingsStore::new(cx, &test_settings());
1960        store.register_setting::<ItemSettings>();
1961
1962        // Set global settings - these should override defaults but not user settings
1963        store
1964            .set_global_settings(
1965                r#"{
1966                    "tabs": {
1967                        "close_position": "right",
1968                        "git_status": true,
1969                    }
1970                }"#,
1971                cx,
1972            )
1973            .unwrap();
1974
1975        // Before user settings, global settings should apply
1976        assert_eq!(
1977            store.get::<ItemSettings>(None),
1978            &ItemSettings {
1979                close_position: ClosePosition::Right,
1980                git_status: true,
1981            }
1982        );
1983
1984        // Set user settings - these should override both defaults and global
1985        store
1986            .set_user_settings(
1987                r#"{
1988                    "tabs": {
1989                        "close_position": "left"
1990                    }
1991                }"#,
1992                cx,
1993            )
1994            .unwrap();
1995
1996        // User settings should override global settings
1997        assert_eq!(
1998            store.get::<ItemSettings>(None),
1999            &ItemSettings {
2000                close_position: ClosePosition::Left,
2001                git_status: true, // Staff from global settings
2002            }
2003        );
2004    }
2005
2006    #[gpui::test]
2007    fn test_get_value_for_field_basic(cx: &mut App) {
2008        let mut store = SettingsStore::new(cx, &test_settings());
2009        store.register_setting::<DefaultLanguageSettings>();
2010
2011        store
2012            .set_user_settings(r#"{"preferred_line_length": 0}"#, cx)
2013            .unwrap();
2014        let local = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2015        store
2016            .set_local_settings(
2017                local.0,
2018                LocalSettingsPath::InWorktree(local.1.clone()),
2019                LocalSettingsKind::Settings,
2020                Some(r#"{}"#),
2021                cx,
2022            )
2023            .unwrap();
2024
2025        fn get(content: &SettingsContent) -> Option<&u32> {
2026            content
2027                .project
2028                .all_languages
2029                .defaults
2030                .preferred_line_length
2031                .as_ref()
2032        }
2033
2034        let default_value = *get(&store.default_settings).unwrap();
2035
2036        assert_eq!(
2037            store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2038            (SettingsFile::User, Some(&0))
2039        );
2040        assert_eq!(
2041            store.get_value_from_file(SettingsFile::User, get),
2042            (SettingsFile::User, Some(&0))
2043        );
2044        store.set_user_settings(r#"{}"#, cx).unwrap();
2045        assert_eq!(
2046            store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2047            (SettingsFile::Default, Some(&default_value))
2048        );
2049        store
2050            .set_local_settings(
2051                local.0,
2052                LocalSettingsPath::InWorktree(local.1.clone()),
2053                LocalSettingsKind::Settings,
2054                Some(r#"{"preferred_line_length": 80}"#),
2055                cx,
2056            )
2057            .unwrap();
2058        assert_eq!(
2059            store.get_value_from_file(SettingsFile::Project(local.clone()), get),
2060            (SettingsFile::Project(local), Some(&80))
2061        );
2062        assert_eq!(
2063            store.get_value_from_file(SettingsFile::User, get),
2064            (SettingsFile::Default, Some(&default_value))
2065        );
2066    }
2067
2068    #[gpui::test]
2069    fn test_get_value_for_field_local_worktrees_dont_interfere(cx: &mut App) {
2070        let mut store = SettingsStore::new(cx, &test_settings());
2071        store.register_setting::<DefaultLanguageSettings>();
2072        store.register_setting::<AutoUpdateSetting>();
2073
2074        let local_1 = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2075
2076        let local_1_child = (
2077            WorktreeId::from_usize(0),
2078            RelPath::new(
2079                std::path::Path::new("child1"),
2080                util::paths::PathStyle::Posix,
2081            )
2082            .unwrap()
2083            .into_arc(),
2084        );
2085
2086        let local_2 = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
2087        let local_2_child = (
2088            WorktreeId::from_usize(1),
2089            RelPath::new(
2090                std::path::Path::new("child2"),
2091                util::paths::PathStyle::Posix,
2092            )
2093            .unwrap()
2094            .into_arc(),
2095        );
2096
2097        fn get(content: &SettingsContent) -> Option<&u32> {
2098            content
2099                .project
2100                .all_languages
2101                .defaults
2102                .preferred_line_length
2103                .as_ref()
2104        }
2105
2106        store
2107            .set_local_settings(
2108                local_1.0,
2109                LocalSettingsPath::InWorktree(local_1.1.clone()),
2110                LocalSettingsKind::Settings,
2111                Some(r#"{"preferred_line_length": 1}"#),
2112                cx,
2113            )
2114            .unwrap();
2115        store
2116            .set_local_settings(
2117                local_1_child.0,
2118                LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2119                LocalSettingsKind::Settings,
2120                Some(r#"{}"#),
2121                cx,
2122            )
2123            .unwrap();
2124        store
2125            .set_local_settings(
2126                local_2.0,
2127                LocalSettingsPath::InWorktree(local_2.1.clone()),
2128                LocalSettingsKind::Settings,
2129                Some(r#"{"preferred_line_length": 2}"#),
2130                cx,
2131            )
2132            .unwrap();
2133        store
2134            .set_local_settings(
2135                local_2_child.0,
2136                LocalSettingsPath::InWorktree(local_2_child.1.clone()),
2137                LocalSettingsKind::Settings,
2138                Some(r#"{}"#),
2139                cx,
2140            )
2141            .unwrap();
2142
2143        // each local child should only inherit from it's parent
2144        assert_eq!(
2145            store.get_value_from_file(SettingsFile::Project(local_2_child), get),
2146            (SettingsFile::Project(local_2), Some(&2))
2147        );
2148        assert_eq!(
2149            store.get_value_from_file(SettingsFile::Project(local_1_child.clone()), get),
2150            (SettingsFile::Project(local_1.clone()), Some(&1))
2151        );
2152
2153        // adjacent children should be treated as siblings not inherit from each other
2154        let local_1_adjacent_child = (local_1.0, rel_path("adjacent_child").into_arc());
2155        store
2156            .set_local_settings(
2157                local_1_adjacent_child.0,
2158                LocalSettingsPath::InWorktree(local_1_adjacent_child.1.clone()),
2159                LocalSettingsKind::Settings,
2160                Some(r#"{}"#),
2161                cx,
2162            )
2163            .unwrap();
2164        store
2165            .set_local_settings(
2166                local_1_child.0,
2167                LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2168                LocalSettingsKind::Settings,
2169                Some(r#"{"preferred_line_length": 3}"#),
2170                cx,
2171            )
2172            .unwrap();
2173
2174        assert_eq!(
2175            store.get_value_from_file(SettingsFile::Project(local_1_adjacent_child.clone()), get),
2176            (SettingsFile::Project(local_1.clone()), Some(&1))
2177        );
2178        store
2179            .set_local_settings(
2180                local_1_adjacent_child.0,
2181                LocalSettingsPath::InWorktree(local_1_adjacent_child.1),
2182                LocalSettingsKind::Settings,
2183                Some(r#"{"preferred_line_length": 3}"#),
2184                cx,
2185            )
2186            .unwrap();
2187        store
2188            .set_local_settings(
2189                local_1_child.0,
2190                LocalSettingsPath::InWorktree(local_1_child.1.clone()),
2191                LocalSettingsKind::Settings,
2192                Some(r#"{}"#),
2193                cx,
2194            )
2195            .unwrap();
2196        assert_eq!(
2197            store.get_value_from_file(SettingsFile::Project(local_1_child), get),
2198            (SettingsFile::Project(local_1), Some(&1))
2199        );
2200    }
2201
2202    #[gpui::test]
2203    fn test_get_overrides_for_field(cx: &mut App) {
2204        let mut store = SettingsStore::new(cx, &test_settings());
2205        store.register_setting::<DefaultLanguageSettings>();
2206
2207        let wt0_root = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
2208        let wt0_child1 = (WorktreeId::from_usize(0), rel_path("child1").into_arc());
2209        let wt0_child2 = (WorktreeId::from_usize(0), rel_path("child2").into_arc());
2210
2211        let wt1_root = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
2212        let wt1_subdir = (WorktreeId::from_usize(1), rel_path("subdir").into_arc());
2213
2214        fn get(content: &SettingsContent) -> &Option<u32> {
2215            &content.project.all_languages.defaults.preferred_line_length
2216        }
2217
2218        store
2219            .set_user_settings(r#"{"preferred_line_length": 100}"#, cx)
2220            .unwrap();
2221
2222        store
2223            .set_local_settings(
2224                wt0_root.0,
2225                LocalSettingsPath::InWorktree(wt0_root.1.clone()),
2226                LocalSettingsKind::Settings,
2227                Some(r#"{"preferred_line_length": 80}"#),
2228                cx,
2229            )
2230            .unwrap();
2231        store
2232            .set_local_settings(
2233                wt0_child1.0,
2234                LocalSettingsPath::InWorktree(wt0_child1.1.clone()),
2235                LocalSettingsKind::Settings,
2236                Some(r#"{"preferred_line_length": 120}"#),
2237                cx,
2238            )
2239            .unwrap();
2240        store
2241            .set_local_settings(
2242                wt0_child2.0,
2243                LocalSettingsPath::InWorktree(wt0_child2.1.clone()),
2244                LocalSettingsKind::Settings,
2245                Some(r#"{}"#),
2246                cx,
2247            )
2248            .unwrap();
2249
2250        store
2251            .set_local_settings(
2252                wt1_root.0,
2253                LocalSettingsPath::InWorktree(wt1_root.1.clone()),
2254                LocalSettingsKind::Settings,
2255                Some(r#"{"preferred_line_length": 90}"#),
2256                cx,
2257            )
2258            .unwrap();
2259        store
2260            .set_local_settings(
2261                wt1_subdir.0,
2262                LocalSettingsPath::InWorktree(wt1_subdir.1.clone()),
2263                LocalSettingsKind::Settings,
2264                Some(r#"{}"#),
2265                cx,
2266            )
2267            .unwrap();
2268
2269        let overrides = store.get_overrides_for_field(SettingsFile::Default, get);
2270        assert_eq!(
2271            overrides,
2272            vec![
2273                SettingsFile::User,
2274                SettingsFile::Project(wt0_root.clone()),
2275                SettingsFile::Project(wt0_child1.clone()),
2276                SettingsFile::Project(wt1_root.clone()),
2277            ]
2278        );
2279
2280        let overrides = store.get_overrides_for_field(SettingsFile::User, get);
2281        assert_eq!(
2282            overrides,
2283            vec![
2284                SettingsFile::Project(wt0_root.clone()),
2285                SettingsFile::Project(wt0_child1.clone()),
2286                SettingsFile::Project(wt1_root.clone()),
2287            ]
2288        );
2289
2290        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_root), get);
2291        assert_eq!(overrides, vec![]);
2292
2293        let overrides =
2294            store.get_overrides_for_field(SettingsFile::Project(wt0_child1.clone()), get);
2295        assert_eq!(overrides, vec![]);
2296
2297        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_child2), get);
2298        assert_eq!(overrides, vec![]);
2299
2300        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt1_root), get);
2301        assert_eq!(overrides, vec![]);
2302
2303        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt1_subdir), get);
2304        assert_eq!(overrides, vec![]);
2305
2306        let wt0_deep_child = (
2307            WorktreeId::from_usize(0),
2308            rel_path("child1/subdir").into_arc(),
2309        );
2310        store
2311            .set_local_settings(
2312                wt0_deep_child.0,
2313                LocalSettingsPath::InWorktree(wt0_deep_child.1.clone()),
2314                LocalSettingsKind::Settings,
2315                Some(r#"{"preferred_line_length": 140}"#),
2316                cx,
2317            )
2318            .unwrap();
2319
2320        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_deep_child), get);
2321        assert_eq!(overrides, vec![]);
2322
2323        let overrides = store.get_overrides_for_field(SettingsFile::Project(wt0_child1), get);
2324        assert_eq!(overrides, vec![]);
2325    }
2326
2327    #[test]
2328    fn test_file_ord() {
2329        let wt0_root =
2330            SettingsFile::Project((WorktreeId::from_usize(0), RelPath::empty().into_arc()));
2331        let wt0_child1 =
2332            SettingsFile::Project((WorktreeId::from_usize(0), rel_path("child1").into_arc()));
2333        let wt0_child2 =
2334            SettingsFile::Project((WorktreeId::from_usize(0), rel_path("child2").into_arc()));
2335
2336        let wt1_root =
2337            SettingsFile::Project((WorktreeId::from_usize(1), RelPath::empty().into_arc()));
2338        let wt1_subdir =
2339            SettingsFile::Project((WorktreeId::from_usize(1), rel_path("subdir").into_arc()));
2340
2341        let mut files = vec![
2342            &wt1_root,
2343            &SettingsFile::Default,
2344            &wt0_root,
2345            &wt1_subdir,
2346            &wt0_child2,
2347            &SettingsFile::Server,
2348            &wt0_child1,
2349            &SettingsFile::User,
2350        ];
2351
2352        files.sort();
2353        pretty_assertions::assert_eq!(
2354            files,
2355            vec![
2356                &wt0_child2,
2357                &wt0_child1,
2358                &wt0_root,
2359                &wt1_subdir,
2360                &wt1_root,
2361                &SettingsFile::Server,
2362                &SettingsFile::User,
2363                &SettingsFile::Default,
2364            ]
2365        )
2366    }
2367
2368    #[gpui::test]
2369    fn test_lsp_settings_schema_generation(cx: &mut App) {
2370        let store = SettingsStore::test(cx);
2371
2372        let schema = store.json_schema(&SettingsJsonSchemaParams {
2373            language_names: &["Rust".to_string(), "TypeScript".to_string()],
2374            font_names: &["Zed Mono".to_string()],
2375            theme_names: &["One Dark".into()],
2376            icon_theme_names: &["Zed Icons".into()],
2377            lsp_adapter_names: &[
2378                "rust-analyzer".to_string(),
2379                "typescript-language-server".to_string(),
2380            ],
2381        });
2382
2383        let properties = schema
2384            .pointer("/$defs/LspSettingsMap/properties")
2385            .expect("LspSettingsMap should have properties")
2386            .as_object()
2387            .unwrap();
2388
2389        assert!(properties.contains_key("rust-analyzer"));
2390        assert!(properties.contains_key("typescript-language-server"));
2391
2392        let init_options_ref = properties
2393            .get("rust-analyzer")
2394            .unwrap()
2395            .pointer("/properties/initialization_options/$ref")
2396            .expect("initialization_options should have a $ref")
2397            .as_str()
2398            .unwrap();
2399
2400        assert_eq!(init_options_ref, "zed://schemas/settings/lsp/rust-analyzer");
2401    }
2402
2403    #[gpui::test]
2404    fn test_lsp_project_settings_schema_generation(cx: &mut App) {
2405        let store = SettingsStore::test(cx);
2406
2407        let schema = store.project_json_schema(&SettingsJsonSchemaParams {
2408            language_names: &["Rust".to_string(), "TypeScript".to_string()],
2409            font_names: &["Zed Mono".to_string()],
2410            theme_names: &["One Dark".into()],
2411            icon_theme_names: &["Zed Icons".into()],
2412            lsp_adapter_names: &[
2413                "rust-analyzer".to_string(),
2414                "typescript-language-server".to_string(),
2415            ],
2416        });
2417
2418        let properties = schema
2419            .pointer("/$defs/LspSettingsMap/properties")
2420            .expect("LspSettingsMap should have properties")
2421            .as_object()
2422            .unwrap();
2423
2424        assert!(properties.contains_key("rust-analyzer"));
2425        assert!(properties.contains_key("typescript-language-server"));
2426
2427        let init_options_ref = properties
2428            .get("rust-analyzer")
2429            .unwrap()
2430            .pointer("/properties/initialization_options/$ref")
2431            .expect("initialization_options should have a $ref")
2432            .as_str()
2433            .unwrap();
2434
2435        assert_eq!(init_options_ref, "zed://schemas/settings/lsp/rust-analyzer");
2436    }
2437
2438    #[gpui::test]
2439    fn test_project_json_schema_differs_from_user_schema(cx: &mut App) {
2440        let store = SettingsStore::test(cx);
2441
2442        let params = SettingsJsonSchemaParams {
2443            language_names: &["Rust".to_string()],
2444            font_names: &["Zed Mono".to_string()],
2445            theme_names: &["One Dark".into()],
2446            icon_theme_names: &["Zed Icons".into()],
2447            lsp_adapter_names: &["rust-analyzer".to_string()],
2448        };
2449
2450        let user_schema = store.json_schema(&params);
2451        let project_schema = store.project_json_schema(&params);
2452
2453        assert_ne!(user_schema, project_schema);
2454
2455        let user_schema_str = serde_json::to_string(&user_schema).unwrap();
2456        let project_schema_str = serde_json::to_string(&project_schema).unwrap();
2457
2458        assert!(user_schema_str.contains("\"auto_update\""));
2459        assert!(!project_schema_str.contains("\"auto_update\""));
2460    }
2461}