settings_store.rs

   1use anyhow::{Context as _, Result};
   2use collections::{BTreeMap, HashMap, btree_map, hash_map};
   3use ec4rs::{ConfigParser, PropertiesSource, Section};
   4use fs::Fs;
   5use futures::{
   6    FutureExt, StreamExt,
   7    channel::{mpsc, oneshot},
   8    future::LocalBoxFuture,
   9};
  10use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
  11
  12use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
  13use schemars::{JsonSchema, json_schema};
  14use serde_json::Value;
  15use smallvec::SmallVec;
  16use std::{
  17    any::{Any, TypeId, type_name},
  18    fmt::Debug,
  19    ops::Range,
  20    path::PathBuf,
  21    rc::Rc,
  22    str::{self, FromStr},
  23    sync::Arc,
  24};
  25use util::{
  26    ResultExt as _,
  27    rel_path::RelPath,
  28    schemars::{DefaultDenyUnknownFields, replace_subschema},
  29};
  30
  31pub type EditorconfigProperties = ec4rs::Properties;
  32
  33use crate::{
  34    ActiveSettingsProfileName, FontFamilyName, IconThemeName, LanguageSettingsContent,
  35    LanguageToSettingsMap, SettingsJsonSchemaParams, ThemeName, VsCodeSettings, WorktreeId,
  36    merge_from::MergeFrom,
  37    parse_json_with_comments,
  38    settings_content::{
  39        ExtensionsSettingsContent, ProjectSettingsContent, SettingsContent, UserSettingsContent,
  40    },
  41    update_value_in_json_text,
  42};
  43
  44pub trait SettingsKey: 'static + Send + Sync {
  45    /// The name of a key within the JSON file from which this setting should
  46    /// be deserialized. If this is `None`, then the setting will be deserialized
  47    /// from the root object.
  48    const KEY: Option<&'static str>;
  49
  50    const FALLBACK_KEY: Option<&'static str> = None;
  51}
  52
  53/// A value that can be defined as a user setting.
  54///
  55/// Settings can be loaded from a combination of multiple JSON files.
  56pub trait Settings: 'static + Send + Sync + Sized {
  57    /// The name of the keys in the [`FileContent`](Self::FileContent) that should
  58    /// always be written to a settings file, even if their value matches the default
  59    /// value.
  60    ///
  61    /// This is useful for tagged [`FileContent`](Self::FileContent)s where the tag
  62    /// is a "version" field that should always be persisted, even if the current
  63    /// user settings match the current version of the settings.
  64    const PRESERVED_KEYS: Option<&'static [&'static str]> = None;
  65
  66    /// Read the value from default.json.
  67    ///
  68    /// This function *should* panic if default values are missing,
  69    /// and you should add a default to default.json for documentation.
  70    fn from_settings(content: &SettingsContent, cx: &mut App) -> Self;
  71
  72    fn missing_default() -> anyhow::Error {
  73        anyhow::anyhow!("missing default for: {}", std::any::type_name::<Self>())
  74    }
  75
  76    /// Use [the helpers in the vscode_import module](crate::vscode_import) to apply known
  77    /// equivalent settings from a vscode config to our config
  78    fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut SettingsContent) {}
  79
  80    #[track_caller]
  81    fn register(cx: &mut App)
  82    where
  83        Self: Sized,
  84    {
  85        SettingsStore::update_global(cx, |store, cx| {
  86            store.register_setting::<Self>(cx);
  87        });
  88    }
  89
  90    #[track_caller]
  91    fn get<'a>(path: Option<SettingsLocation>, cx: &'a App) -> &'a Self
  92    where
  93        Self: Sized,
  94    {
  95        cx.global::<SettingsStore>().get(path)
  96    }
  97
  98    #[track_caller]
  99    fn get_global(cx: &App) -> &Self
 100    where
 101        Self: Sized,
 102    {
 103        cx.global::<SettingsStore>().get(None)
 104    }
 105
 106    #[track_caller]
 107    fn try_get(cx: &App) -> Option<&Self>
 108    where
 109        Self: Sized,
 110    {
 111        if cx.has_global::<SettingsStore>() {
 112            cx.global::<SettingsStore>().try_get(None)
 113        } else {
 114            None
 115        }
 116    }
 117
 118    #[track_caller]
 119    fn try_read_global<R>(cx: &AsyncApp, f: impl FnOnce(&Self) -> R) -> Option<R>
 120    where
 121        Self: Sized,
 122    {
 123        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
 124    }
 125
 126    #[track_caller]
 127    fn override_global(settings: Self, cx: &mut App)
 128    where
 129        Self: Sized,
 130    {
 131        cx.global_mut::<SettingsStore>().override_global(settings)
 132    }
 133}
 134
 135#[derive(Clone, Copy, Debug)]
 136pub struct SettingsLocation<'a> {
 137    pub worktree_id: WorktreeId,
 138    pub path: &'a RelPath,
 139}
 140
 141pub struct SettingsStore {
 142    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 143    default_settings: Rc<SettingsContent>,
 144    user_settings: Option<UserSettingsContent>,
 145    global_settings: Option<Box<SettingsContent>>,
 146
 147    extension_settings: Option<Box<SettingsContent>>,
 148    server_settings: Option<Box<SettingsContent>>,
 149
 150    merged_settings: Rc<SettingsContent>,
 151
 152    local_settings: BTreeMap<(WorktreeId, Arc<RelPath>), SettingsContent>,
 153    raw_editorconfig_settings: BTreeMap<(WorktreeId, Arc<RelPath>), (String, Option<Editorconfig>)>,
 154
 155    _setting_file_updates: Task<()>,
 156    setting_file_updates_tx:
 157        mpsc::UnboundedSender<Box<dyn FnOnce(AsyncApp) -> LocalBoxFuture<'static, Result<()>>>>,
 158}
 159
 160#[derive(Clone, PartialEq, Debug)]
 161pub enum SettingsFile {
 162    User,
 163    Server,
 164    Default,
 165    /// Local also represents project settings in ssh projects as well as local projects
 166    Local((WorktreeId, Arc<RelPath>)),
 167}
 168
 169#[derive(Clone)]
 170pub struct Editorconfig {
 171    pub is_root: bool,
 172    pub sections: SmallVec<[Section; 5]>,
 173}
 174
 175impl FromStr for Editorconfig {
 176    type Err = anyhow::Error;
 177
 178    fn from_str(contents: &str) -> Result<Self, Self::Err> {
 179        let parser = ConfigParser::new_buffered(contents.as_bytes())
 180            .context("creating editorconfig parser")?;
 181        let is_root = parser.is_root;
 182        let sections = parser
 183            .collect::<Result<SmallVec<_>, _>>()
 184            .context("parsing editorconfig sections")?;
 185        Ok(Self { is_root, sections })
 186    }
 187}
 188
 189#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
 190pub enum LocalSettingsKind {
 191    Settings,
 192    Tasks,
 193    Editorconfig,
 194    Debug,
 195}
 196
 197impl Global for SettingsStore {}
 198
 199#[derive(Debug)]
 200struct SettingValue<T> {
 201    global_value: Option<T>,
 202    local_values: Vec<(WorktreeId, Arc<RelPath>, T)>,
 203}
 204
 205trait AnySettingValue: 'static + Send + Sync {
 206    fn setting_type_name(&self) -> &'static str;
 207
 208    fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any>;
 209
 210    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 211    fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)>;
 212    fn set_global_value(&mut self, value: Box<dyn Any>);
 213    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>);
 214    fn import_from_vscode(
 215        &self,
 216        vscode_settings: &VsCodeSettings,
 217        settings_content: &mut SettingsContent,
 218    );
 219}
 220
 221impl SettingsStore {
 222    pub fn new(cx: &App, default_settings: &str) -> Self {
 223        let (setting_file_updates_tx, mut setting_file_updates_rx) = mpsc::unbounded();
 224        let default_settings: Rc<SettingsContent> =
 225            parse_json_with_comments(default_settings).unwrap();
 226        Self {
 227            setting_values: Default::default(),
 228            default_settings: default_settings.clone(),
 229            global_settings: None,
 230            server_settings: None,
 231            user_settings: None,
 232            extension_settings: None,
 233
 234            merged_settings: default_settings,
 235            local_settings: BTreeMap::default(),
 236            raw_editorconfig_settings: BTreeMap::default(),
 237            setting_file_updates_tx,
 238            _setting_file_updates: cx.spawn(async move |cx| {
 239                while let Some(setting_file_update) = setting_file_updates_rx.next().await {
 240                    (setting_file_update)(cx.clone()).await.log_err();
 241                }
 242            }),
 243        }
 244    }
 245
 246    pub fn observe_active_settings_profile_name(cx: &mut App) -> gpui::Subscription {
 247        cx.observe_global::<ActiveSettingsProfileName>(|cx| {
 248            Self::update_global(cx, |store, cx| {
 249                store.recompute_values(None, cx).log_err();
 250            });
 251        })
 252    }
 253
 254    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 255    where
 256        C: BorrowAppContext,
 257    {
 258        cx.update_global(f)
 259    }
 260
 261    /// Add a new type of setting to the store.
 262    pub fn register_setting<T: Settings>(&mut self, cx: &mut App) {
 263        let setting_type_id = TypeId::of::<T>();
 264        let entry = self.setting_values.entry(setting_type_id);
 265
 266        if matches!(entry, hash_map::Entry::Occupied(_)) {
 267            return;
 268        }
 269
 270        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 271            global_value: None,
 272            local_values: Vec::new(),
 273        }));
 274        let value = T::from_settings(&self.merged_settings, cx);
 275        setting_value.set_global_value(Box::new(value));
 276    }
 277
 278    /// Get the value of a setting.
 279    ///
 280    /// Panics if the given setting type has not been registered, or if there is no
 281    /// value for this setting.
 282    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 283        self.setting_values
 284            .get(&TypeId::of::<T>())
 285            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 286            .value_for_path(path)
 287            .downcast_ref::<T>()
 288            .expect("no default value for setting type")
 289    }
 290
 291    /// Get the value of a setting.
 292    ///
 293    /// Does not panic
 294    pub fn try_get<T: Settings>(&self, path: Option<SettingsLocation>) -> Option<&T> {
 295        self.setting_values
 296            .get(&TypeId::of::<T>())
 297            .map(|value| value.value_for_path(path))
 298            .and_then(|value| value.downcast_ref::<T>())
 299    }
 300
 301    /// Get all values from project specific settings
 302    pub fn get_all_locals<T: Settings>(&self) -> Vec<(WorktreeId, Arc<RelPath>, &T)> {
 303        self.setting_values
 304            .get(&TypeId::of::<T>())
 305            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 306            .all_local_values()
 307            .into_iter()
 308            .map(|(id, path, any)| {
 309                (
 310                    id,
 311                    path,
 312                    any.downcast_ref::<T>()
 313                        .expect("wrong value type for setting"),
 314                )
 315            })
 316            .collect()
 317    }
 318
 319    /// Override the global value for a setting.
 320    ///
 321    /// The given value will be overwritten if the user settings file changes.
 322    pub fn override_global<T: Settings>(&mut self, value: T) {
 323        self.setting_values
 324            .get_mut(&TypeId::of::<T>())
 325            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 326            .set_global_value(Box::new(value))
 327    }
 328
 329    /// Get the user's settings content.
 330    ///
 331    /// For user-facing functionality use the typed setting interface.
 332    /// (e.g. ProjectSettings::get_global(cx))
 333    pub fn raw_user_settings(&self) -> Option<&UserSettingsContent> {
 334        self.user_settings.as_ref()
 335    }
 336
 337    /// Get the default settings content as a raw JSON value.
 338    pub fn raw_default_settings(&self) -> &SettingsContent {
 339        &self.default_settings
 340    }
 341
 342    /// Get the configured settings profile names.
 343    pub fn configured_settings_profiles(&self) -> impl Iterator<Item = &str> {
 344        self.user_settings
 345            .iter()
 346            .flat_map(|settings| settings.profiles.keys().map(|k| k.as_str()))
 347    }
 348
 349    #[cfg(any(test, feature = "test-support"))]
 350    pub fn test(cx: &mut App) -> Self {
 351        Self::new(cx, &crate::test_settings())
 352    }
 353
 354    /// Updates the value of a setting in the user's global configuration.
 355    ///
 356    /// This is only for tests. Normally, settings are only loaded from
 357    /// JSON files.
 358    #[cfg(any(test, feature = "test-support"))]
 359    pub fn update_user_settings(
 360        &mut self,
 361        cx: &mut App,
 362        update: impl FnOnce(&mut SettingsContent),
 363    ) {
 364        let mut content = self.user_settings.clone().unwrap_or_default().content;
 365        update(&mut content);
 366        let new_text = serde_json::to_string(&UserSettingsContent {
 367            content,
 368            ..Default::default()
 369        })
 370        .unwrap();
 371        self.set_user_settings(&new_text, cx).unwrap();
 372    }
 373
 374    pub async fn load_settings(fs: &Arc<dyn Fs>) -> Result<String> {
 375        match fs.load(paths::settings_file()).await {
 376            result @ Ok(_) => result,
 377            Err(err) => {
 378                if let Some(e) = err.downcast_ref::<std::io::Error>()
 379                    && e.kind() == std::io::ErrorKind::NotFound
 380                {
 381                    return Ok(crate::initial_user_settings_content().to_string());
 382                }
 383                Err(err)
 384            }
 385        }
 386    }
 387
 388    fn update_settings_file_inner(
 389        &self,
 390        fs: Arc<dyn Fs>,
 391        update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
 392    ) -> oneshot::Receiver<Result<()>> {
 393        let (tx, rx) = oneshot::channel::<Result<()>>();
 394        self.setting_file_updates_tx
 395            .unbounded_send(Box::new(move |cx: AsyncApp| {
 396                async move {
 397                    let res = async move {
 398                        let old_text = Self::load_settings(&fs).await?;
 399                        let new_text = update(old_text, cx)?;
 400                        let settings_path = paths::settings_file().as_path();
 401                        if fs.is_file(settings_path).await {
 402                            let resolved_path =
 403                                fs.canonicalize(settings_path).await.with_context(|| {
 404                                    format!(
 405                                        "Failed to canonicalize settings path {:?}",
 406                                        settings_path
 407                                    )
 408                                })?;
 409
 410                            fs.atomic_write(resolved_path.clone(), new_text)
 411                                .await
 412                                .with_context(|| {
 413                                    format!("Failed to write settings to file {:?}", resolved_path)
 414                                })?;
 415                        } else {
 416                            fs.atomic_write(settings_path.to_path_buf(), new_text)
 417                                .await
 418                                .with_context(|| {
 419                                    format!("Failed to write settings to file {:?}", settings_path)
 420                                })?;
 421                        }
 422                        anyhow::Ok(())
 423                    }
 424                    .await;
 425
 426                    let new_res = match &res {
 427                        Ok(_) => anyhow::Ok(()),
 428                        Err(e) => Err(anyhow::anyhow!("Failed to write settings to file {:?}", e)),
 429                    };
 430
 431                    _ = tx.send(new_res);
 432                    res
 433                }
 434                .boxed_local()
 435            }))
 436            .map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
 437            .log_with_level(log::Level::Warn);
 438        return rx;
 439    }
 440
 441    pub fn update_settings_file(
 442        &self,
 443        fs: Arc<dyn Fs>,
 444        update: impl 'static + Send + FnOnce(&mut SettingsContent, &App),
 445    ) {
 446        _ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
 447            cx.read_global(|store: &SettingsStore, cx| {
 448                store.new_text_for_update(old_text, |content| update(content, cx))
 449            })
 450        });
 451    }
 452
 453    pub fn import_vscode_settings(
 454        &self,
 455        fs: Arc<dyn Fs>,
 456        vscode_settings: VsCodeSettings,
 457    ) -> oneshot::Receiver<Result<()>> {
 458        self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
 459            cx.read_global(|store: &SettingsStore, _cx| {
 460                store.get_vscode_edits(old_text, &vscode_settings)
 461            })
 462        })
 463    }
 464
 465    pub fn get_all_files(&self) -> Vec<SettingsFile> {
 466        let mut files = Vec::from_iter(
 467            self.local_settings
 468                .keys()
 469                // rev because these are sorted by path, so highest precedence is last
 470                .rev()
 471                .cloned()
 472                .map(SettingsFile::Local),
 473        );
 474
 475        if self.server_settings.is_some() {
 476            files.push(SettingsFile::Server);
 477        }
 478        // ignoring profiles
 479        // ignoring os profiles
 480        // ignoring release channel profiles
 481        // ignoring global
 482        // ignoring extension
 483
 484        if self.user_settings.is_some() {
 485            files.push(SettingsFile::User);
 486        }
 487        files.push(SettingsFile::Default);
 488        files
 489    }
 490
 491    fn get_content_for_file(&self, file: SettingsFile) -> Option<&SettingsContent> {
 492        match file {
 493            SettingsFile::User => self
 494                .user_settings
 495                .as_ref()
 496                .map(|settings| settings.content.as_ref()),
 497            SettingsFile::Default => Some(self.default_settings.as_ref()),
 498            SettingsFile::Server => self.server_settings.as_deref(),
 499            SettingsFile::Local(ref key) => self.local_settings.get(key),
 500        }
 501    }
 502
 503    pub fn get_overrides_for_field<T>(
 504        &self,
 505        target_file: SettingsFile,
 506        get: fn(&SettingsContent) -> &Option<T>,
 507    ) -> Vec<SettingsFile> {
 508        let all_files = self.get_all_files();
 509        let mut found_file = false;
 510        let mut overrides = Vec::new();
 511
 512        for file in all_files.into_iter().rev() {
 513            if !found_file {
 514                found_file = file == target_file;
 515                continue;
 516            }
 517
 518            if let SettingsFile::Local((wt_id, ref path)) = file
 519                && let SettingsFile::Local((target_wt_id, ref target_path)) = target_file
 520                && (wt_id != target_wt_id || !target_path.starts_with(path))
 521            {
 522                // if requesting value from a local file, don't return values from local files in different worktrees
 523                continue;
 524            }
 525
 526            let Some(content) = self.get_content_for_file(file.clone()) else {
 527                continue;
 528            };
 529            if get(content).is_some() {
 530                overrides.push(file);
 531            }
 532        }
 533
 534        overrides
 535    }
 536
 537    pub fn get_value_from_file<T>(
 538        &self,
 539        target_file: SettingsFile,
 540        pick: fn(&SettingsContent) -> &Option<T>,
 541    ) -> (SettingsFile, &T) {
 542        // TODO: Add a metadata field for overriding the "overrides" tag, for contextually different settings
 543        //  e.g. disable AI isn't overridden, or a vec that gets extended instead or some such
 544
 545        // todo(settings_ui) cache all files
 546        let all_files = self.get_all_files();
 547        let mut found_file = false;
 548
 549        for file in all_files.into_iter() {
 550            if !found_file && file != target_file && file != SettingsFile::Default {
 551                continue;
 552            }
 553            found_file = true;
 554
 555            if let SettingsFile::Local((wt_id, ref path)) = file
 556                && let SettingsFile::Local((target_wt_id, ref target_path)) = target_file
 557                && (wt_id != target_wt_id || !target_path.starts_with(&path))
 558            {
 559                // if requesting value from a local file, don't return values from local files in different worktrees
 560                continue;
 561            }
 562
 563            let Some(content) = self.get_content_for_file(file.clone()) else {
 564                continue;
 565            };
 566            if let Some(value) = pick(content).as_ref() {
 567                return (file, value);
 568            }
 569        }
 570
 571        unreachable!("All values should have defaults");
 572    }
 573}
 574
 575impl SettingsStore {
 576    /// Updates the value of a setting in a JSON file, returning the new text
 577    /// for that JSON file.
 578    pub fn new_text_for_update(
 579        &self,
 580        old_text: String,
 581        update: impl FnOnce(&mut SettingsContent),
 582    ) -> String {
 583        let edits = self.edits_for_update(&old_text, update);
 584        let mut new_text = old_text;
 585        for (range, replacement) in edits.into_iter() {
 586            new_text.replace_range(range, &replacement);
 587        }
 588        new_text
 589    }
 590
 591    pub fn get_vscode_edits(&self, old_text: String, vscode: &VsCodeSettings) -> String {
 592        self.new_text_for_update(old_text, |settings_content| {
 593            for v in self.setting_values.values() {
 594                v.import_from_vscode(vscode, settings_content)
 595            }
 596        })
 597    }
 598
 599    /// Updates the value of a setting in a JSON file, returning a list
 600    /// of edits to apply to the JSON file.
 601    pub fn edits_for_update(
 602        &self,
 603        text: &str,
 604        update: impl FnOnce(&mut SettingsContent),
 605    ) -> Vec<(Range<usize>, String)> {
 606        let old_content: UserSettingsContent =
 607            parse_json_with_comments(text).log_err().unwrap_or_default();
 608        let mut new_content = old_content.clone();
 609        update(&mut new_content.content);
 610
 611        let old_value = serde_json::to_value(&old_content).unwrap();
 612        let new_value = serde_json::to_value(new_content).unwrap();
 613
 614        let mut key_path = Vec::new();
 615        let mut edits = Vec::new();
 616        let tab_size = self.json_tab_size();
 617        let mut text = text.to_string();
 618        update_value_in_json_text(
 619            &mut text,
 620            &mut key_path,
 621            tab_size,
 622            &old_value,
 623            &new_value,
 624            &mut edits,
 625        );
 626        edits
 627    }
 628
 629    pub fn json_tab_size(&self) -> usize {
 630        2
 631    }
 632
 633    /// Sets the default settings via a JSON string.
 634    ///
 635    /// The string should contain a JSON object with a default value for every setting.
 636    pub fn set_default_settings(
 637        &mut self,
 638        default_settings_content: &str,
 639        cx: &mut App,
 640    ) -> Result<()> {
 641        self.default_settings = parse_json_with_comments(default_settings_content)?;
 642        self.recompute_values(None, cx)?;
 643        Ok(())
 644    }
 645
 646    /// Sets the user settings via a JSON string.
 647    pub fn set_user_settings(&mut self, user_settings_content: &str, cx: &mut App) -> Result<()> {
 648        let settings: UserSettingsContent = if user_settings_content.is_empty() {
 649            parse_json_with_comments("{}")?
 650        } else {
 651            parse_json_with_comments(user_settings_content)?
 652        };
 653
 654        self.user_settings = Some(settings);
 655        self.recompute_values(None, cx)?;
 656        Ok(())
 657    }
 658
 659    /// Sets the global settings via a JSON string.
 660    pub fn set_global_settings(
 661        &mut self,
 662        global_settings_content: &str,
 663        cx: &mut App,
 664    ) -> Result<()> {
 665        let settings: SettingsContent = if global_settings_content.is_empty() {
 666            parse_json_with_comments("{}")?
 667        } else {
 668            parse_json_with_comments(global_settings_content)?
 669        };
 670
 671        self.global_settings = Some(Box::new(settings));
 672        self.recompute_values(None, cx)?;
 673        Ok(())
 674    }
 675
 676    pub fn set_server_settings(
 677        &mut self,
 678        server_settings_content: &str,
 679        cx: &mut App,
 680    ) -> Result<()> {
 681        let settings: Option<SettingsContent> = if server_settings_content.is_empty() {
 682            None
 683        } else {
 684            parse_json_with_comments(server_settings_content)?
 685        };
 686
 687        // Rewrite the server settings into a content type
 688        self.server_settings = settings.map(|settings| Box::new(settings));
 689
 690        self.recompute_values(None, cx)?;
 691        Ok(())
 692    }
 693
 694    /// Add or remove a set of local settings via a JSON string.
 695    pub fn set_local_settings(
 696        &mut self,
 697        root_id: WorktreeId,
 698        directory_path: Arc<RelPath>,
 699        kind: LocalSettingsKind,
 700        settings_content: Option<&str>,
 701        cx: &mut App,
 702    ) -> std::result::Result<(), InvalidSettingsError> {
 703        let mut zed_settings_changed = false;
 704        match (
 705            kind,
 706            settings_content
 707                .map(|content| content.trim())
 708                .filter(|content| !content.is_empty()),
 709        ) {
 710            (LocalSettingsKind::Tasks, _) => {
 711                return Err(InvalidSettingsError::Tasks {
 712                    message: "Attempted to submit tasks into the settings store".to_string(),
 713                    path: directory_path
 714                        .join(RelPath::unix(task_file_name()).unwrap())
 715                        .as_std_path()
 716                        .to_path_buf(),
 717                });
 718            }
 719            (LocalSettingsKind::Debug, _) => {
 720                return Err(InvalidSettingsError::Debug {
 721                    message: "Attempted to submit debugger config into the settings store"
 722                        .to_string(),
 723                    path: directory_path
 724                        .join(RelPath::unix(task_file_name()).unwrap())
 725                        .as_std_path()
 726                        .to_path_buf(),
 727                });
 728            }
 729            (LocalSettingsKind::Settings, None) => {
 730                zed_settings_changed = self
 731                    .local_settings
 732                    .remove(&(root_id, directory_path.clone()))
 733                    .is_some()
 734            }
 735            (LocalSettingsKind::Editorconfig, None) => {
 736                self.raw_editorconfig_settings
 737                    .remove(&(root_id, directory_path.clone()));
 738            }
 739            (LocalSettingsKind::Settings, Some(settings_contents)) => {
 740                let new_settings = parse_json_with_comments::<ProjectSettingsContent>(
 741                    settings_contents,
 742                )
 743                .map_err(|e| InvalidSettingsError::LocalSettings {
 744                    path: directory_path.join(local_settings_file_relative_path()),
 745                    message: e.to_string(),
 746                })?;
 747                match self.local_settings.entry((root_id, directory_path.clone())) {
 748                    btree_map::Entry::Vacant(v) => {
 749                        v.insert(SettingsContent {
 750                            project: new_settings,
 751                            ..Default::default()
 752                        });
 753                        zed_settings_changed = true;
 754                    }
 755                    btree_map::Entry::Occupied(mut o) => {
 756                        if &o.get().project != &new_settings {
 757                            o.insert(SettingsContent {
 758                                project: new_settings,
 759                                ..Default::default()
 760                            });
 761                            zed_settings_changed = true;
 762                        }
 763                    }
 764                }
 765            }
 766            (LocalSettingsKind::Editorconfig, Some(editorconfig_contents)) => {
 767                match self
 768                    .raw_editorconfig_settings
 769                    .entry((root_id, directory_path.clone()))
 770                {
 771                    btree_map::Entry::Vacant(v) => match editorconfig_contents.parse() {
 772                        Ok(new_contents) => {
 773                            v.insert((editorconfig_contents.to_owned(), Some(new_contents)));
 774                        }
 775                        Err(e) => {
 776                            v.insert((editorconfig_contents.to_owned(), None));
 777                            return Err(InvalidSettingsError::Editorconfig {
 778                                message: e.to_string(),
 779                                path: directory_path
 780                                    .join(RelPath::unix(EDITORCONFIG_NAME).unwrap()),
 781                            });
 782                        }
 783                    },
 784                    btree_map::Entry::Occupied(mut o) => {
 785                        if o.get().0 != editorconfig_contents {
 786                            match editorconfig_contents.parse() {
 787                                Ok(new_contents) => {
 788                                    o.insert((
 789                                        editorconfig_contents.to_owned(),
 790                                        Some(new_contents),
 791                                    ));
 792                                }
 793                                Err(e) => {
 794                                    o.insert((editorconfig_contents.to_owned(), None));
 795                                    return Err(InvalidSettingsError::Editorconfig {
 796                                        message: e.to_string(),
 797                                        path: directory_path
 798                                            .join(RelPath::unix(EDITORCONFIG_NAME).unwrap()),
 799                                    });
 800                                }
 801                            }
 802                        }
 803                    }
 804                }
 805            }
 806        };
 807
 808        if zed_settings_changed {
 809            self.recompute_values(Some((root_id, &directory_path)), cx)?;
 810        }
 811        Ok(())
 812    }
 813
 814    pub fn set_extension_settings(
 815        &mut self,
 816        content: ExtensionsSettingsContent,
 817        cx: &mut App,
 818    ) -> Result<()> {
 819        self.extension_settings = Some(Box::new(SettingsContent {
 820            project: ProjectSettingsContent {
 821                all_languages: content.all_languages,
 822                ..Default::default()
 823            },
 824            ..Default::default()
 825        }));
 826        self.recompute_values(None, cx)?;
 827        Ok(())
 828    }
 829
 830    /// Add or remove a set of local settings via a JSON string.
 831    pub fn clear_local_settings(&mut self, root_id: WorktreeId, cx: &mut App) -> Result<()> {
 832        self.local_settings
 833            .retain(|(worktree_id, _), _| worktree_id != &root_id);
 834        self.recompute_values(Some((root_id, RelPath::empty())), cx)?;
 835        Ok(())
 836    }
 837
 838    pub fn local_settings(
 839        &self,
 840        root_id: WorktreeId,
 841    ) -> impl '_ + Iterator<Item = (Arc<RelPath>, &ProjectSettingsContent)> {
 842        self.local_settings
 843            .range(
 844                (root_id, RelPath::empty().into())
 845                    ..(
 846                        WorktreeId::from_usize(root_id.to_usize() + 1),
 847                        RelPath::empty().into(),
 848                    ),
 849            )
 850            .map(|((_, path), content)| (path.clone(), &content.project))
 851    }
 852
 853    pub fn local_editorconfig_settings(
 854        &self,
 855        root_id: WorktreeId,
 856    ) -> impl '_ + Iterator<Item = (Arc<RelPath>, String, Option<Editorconfig>)> {
 857        self.raw_editorconfig_settings
 858            .range(
 859                (root_id, RelPath::empty().into())
 860                    ..(
 861                        WorktreeId::from_usize(root_id.to_usize() + 1),
 862                        RelPath::empty().into(),
 863                    ),
 864            )
 865            .map(|((_, path), (content, parsed_content))| {
 866                (path.clone(), content.clone(), parsed_content.clone())
 867            })
 868    }
 869
 870    pub fn json_schema(&self, params: &SettingsJsonSchemaParams) -> Value {
 871        let mut generator = schemars::generate::SchemaSettings::draft2019_09()
 872            .with_transform(DefaultDenyUnknownFields)
 873            .into_generator();
 874
 875        UserSettingsContent::json_schema(&mut generator);
 876
 877        let language_settings_content_ref = generator
 878            .subschema_for::<LanguageSettingsContent>()
 879            .to_value();
 880
 881        replace_subschema::<LanguageToSettingsMap>(&mut generator, || {
 882            json_schema!({
 883                "type": "object",
 884                "properties": params
 885                    .language_names
 886                    .iter()
 887                    .map(|name| {
 888                        (
 889                            name.clone(),
 890                            language_settings_content_ref.clone(),
 891                        )
 892                    })
 893                    .collect::<serde_json::Map<_, _>>(),
 894                "errorMessage": "No language with this name is installed."
 895            })
 896        });
 897
 898        replace_subschema::<FontFamilyName>(&mut generator, || {
 899            json_schema!({
 900                "type": "string",
 901                "enum": params.font_names,
 902            })
 903        });
 904
 905        replace_subschema::<ThemeName>(&mut generator, || {
 906            json_schema!({
 907                "type": "string",
 908                "enum": params.theme_names,
 909            })
 910        });
 911
 912        replace_subschema::<IconThemeName>(&mut generator, || {
 913            json_schema!({
 914                "type": "string",
 915                "enum": params.icon_theme_names,
 916            })
 917        });
 918
 919        generator
 920            .root_schema_for::<UserSettingsContent>()
 921            .to_value()
 922    }
 923
 924    fn recompute_values(
 925        &mut self,
 926        changed_local_path: Option<(WorktreeId, &RelPath)>,
 927        cx: &mut App,
 928    ) -> std::result::Result<(), InvalidSettingsError> {
 929        // Reload the global and local values for every setting.
 930        let mut project_settings_stack = Vec::<SettingsContent>::new();
 931        let mut paths_stack = Vec::<Option<(WorktreeId, &RelPath)>>::new();
 932
 933        if changed_local_path.is_none() {
 934            let mut merged = self.default_settings.as_ref().clone();
 935            merged.merge_from_option(self.extension_settings.as_deref());
 936            merged.merge_from_option(self.global_settings.as_deref());
 937            if let Some(user_settings) = self.user_settings.as_ref() {
 938                merged.merge_from(&user_settings.content);
 939                merged.merge_from_option(user_settings.for_release_channel());
 940                merged.merge_from_option(user_settings.for_os());
 941                merged.merge_from_option(user_settings.for_profile(cx));
 942            }
 943            merged.merge_from_option(self.server_settings.as_deref());
 944            self.merged_settings = Rc::new(merged);
 945
 946            for setting_value in self.setting_values.values_mut() {
 947                let value = setting_value.from_settings(&self.merged_settings, cx);
 948                setting_value.set_global_value(value);
 949            }
 950        }
 951
 952        for ((root_id, directory_path), local_settings) in &self.local_settings {
 953            // Build a stack of all of the local values for that setting.
 954            while let Some(prev_entry) = paths_stack.last() {
 955                if let Some((prev_root_id, prev_path)) = prev_entry
 956                    && (root_id != prev_root_id || !directory_path.starts_with(prev_path))
 957                {
 958                    paths_stack.pop();
 959                    project_settings_stack.pop();
 960                    continue;
 961                }
 962                break;
 963            }
 964
 965            paths_stack.push(Some((*root_id, directory_path.as_ref())));
 966            let mut merged_local_settings = if let Some(deepest) = project_settings_stack.last() {
 967                (*deepest).clone()
 968            } else {
 969                self.merged_settings.as_ref().clone()
 970            };
 971            merged_local_settings.merge_from(local_settings);
 972
 973            project_settings_stack.push(merged_local_settings);
 974
 975            // If a local settings file changed, then avoid recomputing local
 976            // settings for any path outside of that directory.
 977            if changed_local_path.is_some_and(|(changed_root_id, changed_local_path)| {
 978                *root_id != changed_root_id || !directory_path.starts_with(changed_local_path)
 979            }) {
 980                continue;
 981            }
 982
 983            for setting_value in self.setting_values.values_mut() {
 984                let value =
 985                    setting_value.from_settings(&project_settings_stack.last().unwrap(), cx);
 986                setting_value.set_local_value(*root_id, directory_path.clone(), value);
 987            }
 988        }
 989        Ok(())
 990    }
 991
 992    pub fn editorconfig_properties(
 993        &self,
 994        for_worktree: WorktreeId,
 995        for_path: &RelPath,
 996    ) -> Option<EditorconfigProperties> {
 997        let mut properties = EditorconfigProperties::new();
 998
 999        for (directory_with_config, _, parsed_editorconfig) in
1000            self.local_editorconfig_settings(for_worktree)
1001        {
1002            if !for_path.starts_with(&directory_with_config) {
1003                properties.use_fallbacks();
1004                return Some(properties);
1005            }
1006            let parsed_editorconfig = parsed_editorconfig?;
1007            if parsed_editorconfig.is_root {
1008                properties = EditorconfigProperties::new();
1009            }
1010            for section in parsed_editorconfig.sections {
1011                section
1012                    .apply_to(&mut properties, for_path.as_std_path())
1013                    .log_err()?;
1014            }
1015        }
1016
1017        properties.use_fallbacks();
1018        Some(properties)
1019    }
1020}
1021
1022#[derive(Debug, Clone, PartialEq)]
1023pub enum InvalidSettingsError {
1024    LocalSettings { path: Arc<RelPath>, message: String },
1025    UserSettings { message: String },
1026    ServerSettings { message: String },
1027    DefaultSettings { message: String },
1028    Editorconfig { path: Arc<RelPath>, message: String },
1029    Tasks { path: PathBuf, message: String },
1030    Debug { path: PathBuf, message: String },
1031}
1032
1033impl std::fmt::Display for InvalidSettingsError {
1034    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1035        match self {
1036            InvalidSettingsError::LocalSettings { message, .. }
1037            | InvalidSettingsError::UserSettings { message }
1038            | InvalidSettingsError::ServerSettings { message }
1039            | InvalidSettingsError::DefaultSettings { message }
1040            | InvalidSettingsError::Tasks { message, .. }
1041            | InvalidSettingsError::Editorconfig { message, .. }
1042            | InvalidSettingsError::Debug { message, .. } => {
1043                write!(f, "{message}")
1044            }
1045        }
1046    }
1047}
1048impl std::error::Error for InvalidSettingsError {}
1049
1050impl Debug for SettingsStore {
1051    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1052        f.debug_struct("SettingsStore")
1053            .field(
1054                "types",
1055                &self
1056                    .setting_values
1057                    .values()
1058                    .map(|value| value.setting_type_name())
1059                    .collect::<Vec<_>>(),
1060            )
1061            .field("default_settings", &self.default_settings)
1062            .field("user_settings", &self.user_settings)
1063            .field("local_settings", &self.local_settings)
1064            .finish_non_exhaustive()
1065    }
1066}
1067
1068impl<T: Settings> AnySettingValue for SettingValue<T> {
1069    fn from_settings(&self, s: &SettingsContent, cx: &mut App) -> Box<dyn Any> {
1070        Box::new(T::from_settings(s, cx)) as _
1071    }
1072
1073    fn setting_type_name(&self) -> &'static str {
1074        type_name::<T>()
1075    }
1076
1077    fn all_local_values(&self) -> Vec<(WorktreeId, Arc<RelPath>, &dyn Any)> {
1078        self.local_values
1079            .iter()
1080            .map(|(id, path, value)| (*id, path.clone(), value as _))
1081            .collect()
1082    }
1083
1084    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
1085        if let Some(SettingsLocation { worktree_id, path }) = path {
1086            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
1087                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
1088                    return value;
1089                }
1090            }
1091        }
1092
1093        self.global_value
1094            .as_ref()
1095            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
1096    }
1097
1098    fn set_global_value(&mut self, value: Box<dyn Any>) {
1099        self.global_value = Some(*value.downcast().unwrap());
1100    }
1101
1102    fn set_local_value(&mut self, root_id: WorktreeId, path: Arc<RelPath>, value: Box<dyn Any>) {
1103        let value = *value.downcast().unwrap();
1104        match self
1105            .local_values
1106            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
1107        {
1108            Ok(ix) => self.local_values[ix].2 = value,
1109            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
1110        }
1111    }
1112
1113    fn import_from_vscode(
1114        &self,
1115        vscode_settings: &VsCodeSettings,
1116        settings_content: &mut SettingsContent,
1117    ) {
1118        T::import_from_vscode(vscode_settings, settings_content);
1119    }
1120}
1121
1122#[cfg(test)]
1123mod tests {
1124    use std::num::NonZeroU32;
1125
1126    use crate::{
1127        ClosePosition, ItemSettingsContent, VsCodeSettingsSource, default_settings,
1128        settings_content::LanguageSettingsContent, test_settings,
1129    };
1130
1131    use super::*;
1132    use unindent::Unindent;
1133    use util::rel_path::rel_path;
1134
1135    #[derive(Debug, PartialEq)]
1136    struct AutoUpdateSetting {
1137        auto_update: bool,
1138    }
1139
1140    impl Settings for AutoUpdateSetting {
1141        fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1142            AutoUpdateSetting {
1143                auto_update: content.auto_update.unwrap(),
1144            }
1145        }
1146    }
1147
1148    #[derive(Debug, PartialEq)]
1149    struct ItemSettings {
1150        close_position: ClosePosition,
1151        git_status: bool,
1152    }
1153
1154    impl Settings for ItemSettings {
1155        fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1156            let content = content.tabs.clone().unwrap();
1157            ItemSettings {
1158                close_position: content.close_position.unwrap(),
1159                git_status: content.git_status.unwrap(),
1160            }
1161        }
1162
1163        fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1164            let mut show = None;
1165
1166            vscode.bool_setting("workbench.editor.decorations.colors", &mut show);
1167            if let Some(show) = show {
1168                content
1169                    .tabs
1170                    .get_or_insert_default()
1171                    .git_status
1172                    .replace(show);
1173            }
1174        }
1175    }
1176
1177    #[derive(Debug, PartialEq)]
1178    struct DefaultLanguageSettings {
1179        tab_size: NonZeroU32,
1180        preferred_line_length: u32,
1181    }
1182
1183    impl Settings for DefaultLanguageSettings {
1184        fn from_settings(content: &SettingsContent, _: &mut App) -> Self {
1185            let content = &content.project.all_languages.defaults;
1186            DefaultLanguageSettings {
1187                tab_size: content.tab_size.unwrap(),
1188                preferred_line_length: content.preferred_line_length.unwrap(),
1189            }
1190        }
1191
1192        fn import_from_vscode(vscode: &VsCodeSettings, content: &mut SettingsContent) {
1193            let content = &mut content.project.all_languages.defaults;
1194
1195            if let Some(size) = vscode
1196                .read_value("editor.tabSize")
1197                .and_then(|v| v.as_u64())
1198                .and_then(|n| NonZeroU32::new(n as u32))
1199            {
1200                content.tab_size = Some(size);
1201            }
1202        }
1203    }
1204
1205    #[gpui::test]
1206    fn test_settings_store_basic(cx: &mut App) {
1207        let mut store = SettingsStore::new(cx, &default_settings());
1208        store.register_setting::<AutoUpdateSetting>(cx);
1209        store.register_setting::<ItemSettings>(cx);
1210        store.register_setting::<DefaultLanguageSettings>(cx);
1211
1212        assert_eq!(
1213            store.get::<AutoUpdateSetting>(None),
1214            &AutoUpdateSetting { auto_update: true }
1215        );
1216        assert_eq!(
1217            store.get::<ItemSettings>(None).close_position,
1218            ClosePosition::Right
1219        );
1220
1221        store
1222            .set_user_settings(
1223                r#"{
1224                    "auto_update": false,
1225                    "tabs": {
1226                      "close_position": "left"
1227                    }
1228                }"#,
1229                cx,
1230            )
1231            .unwrap();
1232
1233        assert_eq!(
1234            store.get::<AutoUpdateSetting>(None),
1235            &AutoUpdateSetting { auto_update: false }
1236        );
1237        assert_eq!(
1238            store.get::<ItemSettings>(None).close_position,
1239            ClosePosition::Left
1240        );
1241
1242        store
1243            .set_local_settings(
1244                WorktreeId::from_usize(1),
1245                rel_path("root1").into(),
1246                LocalSettingsKind::Settings,
1247                Some(r#"{ "tab_size": 5 }"#),
1248                cx,
1249            )
1250            .unwrap();
1251        store
1252            .set_local_settings(
1253                WorktreeId::from_usize(1),
1254                rel_path("root1/subdir").into(),
1255                LocalSettingsKind::Settings,
1256                Some(r#"{ "preferred_line_length": 50 }"#),
1257                cx,
1258            )
1259            .unwrap();
1260
1261        store
1262            .set_local_settings(
1263                WorktreeId::from_usize(1),
1264                rel_path("root2").into(),
1265                LocalSettingsKind::Settings,
1266                Some(r#"{ "tab_size": 9, "auto_update": true}"#),
1267                cx,
1268            )
1269            .unwrap();
1270
1271        assert_eq!(
1272            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1273                worktree_id: WorktreeId::from_usize(1),
1274                path: rel_path("root1/something"),
1275            })),
1276            &DefaultLanguageSettings {
1277                preferred_line_length: 80,
1278                tab_size: 5.try_into().unwrap(),
1279            }
1280        );
1281        assert_eq!(
1282            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1283                worktree_id: WorktreeId::from_usize(1),
1284                path: rel_path("root1/subdir/something"),
1285            })),
1286            &DefaultLanguageSettings {
1287                preferred_line_length: 50,
1288                tab_size: 5.try_into().unwrap(),
1289            }
1290        );
1291        assert_eq!(
1292            store.get::<DefaultLanguageSettings>(Some(SettingsLocation {
1293                worktree_id: WorktreeId::from_usize(1),
1294                path: rel_path("root2/something"),
1295            })),
1296            &DefaultLanguageSettings {
1297                preferred_line_length: 80,
1298                tab_size: 9.try_into().unwrap(),
1299            }
1300        );
1301        assert_eq!(
1302            store.get::<AutoUpdateSetting>(Some(SettingsLocation {
1303                worktree_id: WorktreeId::from_usize(1),
1304                path: rel_path("root2/something")
1305            })),
1306            &AutoUpdateSetting { auto_update: false }
1307        );
1308    }
1309
1310    #[gpui::test]
1311    fn test_setting_store_assign_json_before_register(cx: &mut App) {
1312        let mut store = SettingsStore::new(cx, &test_settings());
1313        store
1314            .set_user_settings(r#"{ "auto_update": false }"#, cx)
1315            .unwrap();
1316        store.register_setting::<AutoUpdateSetting>(cx);
1317
1318        assert_eq!(
1319            store.get::<AutoUpdateSetting>(None),
1320            &AutoUpdateSetting { auto_update: false }
1321        );
1322    }
1323
1324    #[track_caller]
1325    fn check_settings_update(
1326        store: &mut SettingsStore,
1327        old_json: String,
1328        update: fn(&mut SettingsContent),
1329        expected_new_json: String,
1330        cx: &mut App,
1331    ) {
1332        store.set_user_settings(&old_json, cx).ok();
1333        let edits = store.edits_for_update(&old_json, update);
1334        let mut new_json = old_json;
1335        for (range, replacement) in edits.into_iter() {
1336            new_json.replace_range(range, &replacement);
1337        }
1338        pretty_assertions::assert_eq!(new_json, expected_new_json);
1339    }
1340
1341    #[gpui::test]
1342    fn test_setting_store_update(cx: &mut App) {
1343        let mut store = SettingsStore::new(cx, &test_settings());
1344
1345        // entries added and updated
1346        check_settings_update(
1347            &mut store,
1348            r#"{
1349                "languages": {
1350                    "JSON": {
1351                        "auto_indent": true
1352                    }
1353                }
1354            }"#
1355            .unindent(),
1356            |settings| {
1357                settings
1358                    .languages_mut()
1359                    .get_mut("JSON")
1360                    .unwrap()
1361                    .auto_indent = Some(false);
1362
1363                settings.languages_mut().insert(
1364                    "Rust".into(),
1365                    LanguageSettingsContent {
1366                        auto_indent: Some(true),
1367                        ..Default::default()
1368                    },
1369                );
1370            },
1371            r#"{
1372                "languages": {
1373                    "Rust": {
1374                        "auto_indent": true
1375                    },
1376                    "JSON": {
1377                        "auto_indent": false
1378                    }
1379                }
1380            }"#
1381            .unindent(),
1382            cx,
1383        );
1384
1385        // entries removed
1386        check_settings_update(
1387            &mut store,
1388            r#"{
1389                "languages": {
1390                    "Rust": {
1391                        "language_setting_2": true
1392                    },
1393                    "JSON": {
1394                        "language_setting_1": false
1395                    }
1396                }
1397            }"#
1398            .unindent(),
1399            |settings| {
1400                settings.languages_mut().remove("JSON").unwrap();
1401            },
1402            r#"{
1403                "languages": {
1404                    "Rust": {
1405                        "language_setting_2": true
1406                    }
1407                }
1408            }"#
1409            .unindent(),
1410            cx,
1411        );
1412
1413        check_settings_update(
1414            &mut store,
1415            r#"{
1416                "languages": {
1417                    "Rust": {
1418                        "language_setting_2": true
1419                    },
1420                    "JSON": {
1421                        "language_setting_1": false
1422                    }
1423                }
1424            }"#
1425            .unindent(),
1426            |settings| {
1427                settings.languages_mut().remove("Rust").unwrap();
1428            },
1429            r#"{
1430                "languages": {
1431                    "JSON": {
1432                        "language_setting_1": false
1433                    }
1434                }
1435            }"#
1436            .unindent(),
1437            cx,
1438        );
1439
1440        // weird formatting
1441        check_settings_update(
1442            &mut store,
1443            r#"{
1444                "tabs":   { "close_position": "left", "name": "Max"  }
1445                }"#
1446            .unindent(),
1447            |settings| {
1448                settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left);
1449            },
1450            r#"{
1451                "tabs":   { "close_position": "left", "name": "Max"  }
1452                }"#
1453            .unindent(),
1454            cx,
1455        );
1456
1457        // single-line formatting, other keys
1458        check_settings_update(
1459            &mut store,
1460            r#"{ "one": 1, "two": 2 }"#.to_owned(),
1461            |settings| settings.auto_update = Some(true),
1462            r#"{ "auto_update": true, "one": 1, "two": 2 }"#.to_owned(),
1463            cx,
1464        );
1465
1466        // empty object
1467        check_settings_update(
1468            &mut store,
1469            r#"{
1470                "tabs": {}
1471            }"#
1472            .unindent(),
1473            |settings| settings.tabs.as_mut().unwrap().close_position = Some(ClosePosition::Left),
1474            r#"{
1475                "tabs": {
1476                    "close_position": "left"
1477                }
1478            }"#
1479            .unindent(),
1480            cx,
1481        );
1482
1483        // no content
1484        check_settings_update(
1485            &mut store,
1486            r#""#.unindent(),
1487            |settings| {
1488                settings.tabs = Some(ItemSettingsContent {
1489                    git_status: Some(true),
1490                    ..Default::default()
1491                })
1492            },
1493            r#"{
1494                "tabs": {
1495                    "git_status": true
1496                }
1497            }
1498            "#
1499            .unindent(),
1500            cx,
1501        );
1502
1503        check_settings_update(
1504            &mut store,
1505            r#"{
1506            }
1507            "#
1508            .unindent(),
1509            |settings| settings.title_bar.get_or_insert_default().show_branch_name = Some(true),
1510            r#"{
1511                "title_bar": {
1512                    "show_branch_name": true
1513                }
1514            }
1515            "#
1516            .unindent(),
1517            cx,
1518        );
1519    }
1520
1521    #[gpui::test]
1522    fn test_vscode_import(cx: &mut App) {
1523        let mut store = SettingsStore::new(cx, &test_settings());
1524        store.register_setting::<DefaultLanguageSettings>(cx);
1525        store.register_setting::<ItemSettings>(cx);
1526        store.register_setting::<AutoUpdateSetting>(cx);
1527
1528        // create settings that werent present
1529        check_vscode_import(
1530            &mut store,
1531            r#"{
1532            }
1533            "#
1534            .unindent(),
1535            r#" { "editor.tabSize": 37 } "#.to_owned(),
1536            r#"{
1537                "tab_size": 37
1538            }
1539            "#
1540            .unindent(),
1541            cx,
1542        );
1543
1544        // persist settings that were present
1545        check_vscode_import(
1546            &mut store,
1547            r#"{
1548                "preferred_line_length": 99,
1549            }
1550            "#
1551            .unindent(),
1552            r#"{ "editor.tabSize": 42 }"#.to_owned(),
1553            r#"{
1554                "tab_size": 42,
1555                "preferred_line_length": 99,
1556            }
1557            "#
1558            .unindent(),
1559            cx,
1560        );
1561
1562        // don't clobber settings that aren't present in vscode
1563        check_vscode_import(
1564            &mut store,
1565            r#"{
1566                "preferred_line_length": 99,
1567                "tab_size": 42
1568            }
1569            "#
1570            .unindent(),
1571            r#"{}"#.to_owned(),
1572            r#"{
1573                "preferred_line_length": 99,
1574                "tab_size": 42
1575            }
1576            "#
1577            .unindent(),
1578            cx,
1579        );
1580
1581        // custom enum
1582        check_vscode_import(
1583            &mut store,
1584            r#"{
1585            }
1586            "#
1587            .unindent(),
1588            r#"{ "workbench.editor.decorations.colors": true }"#.to_owned(),
1589            r#"{
1590                "tabs": {
1591                    "git_status": true
1592                }
1593            }
1594            "#
1595            .unindent(),
1596            cx,
1597        );
1598    }
1599
1600    #[track_caller]
1601    fn check_vscode_import(
1602        store: &mut SettingsStore,
1603        old: String,
1604        vscode: String,
1605        expected: String,
1606        cx: &mut App,
1607    ) {
1608        store.set_user_settings(&old, cx).ok();
1609        let new = store.get_vscode_edits(
1610            old,
1611            &VsCodeSettings::from_str(&vscode, VsCodeSettingsSource::VsCode).unwrap(),
1612        );
1613        pretty_assertions::assert_eq!(new, expected);
1614    }
1615
1616    #[gpui::test]
1617    fn test_update_git_settings(cx: &mut App) {
1618        let store = SettingsStore::new(cx, &test_settings());
1619
1620        let actual = store.new_text_for_update("{}".to_string(), |current| {
1621            current
1622                .git
1623                .get_or_insert_default()
1624                .inline_blame
1625                .get_or_insert_default()
1626                .enabled = Some(true);
1627        });
1628        assert_eq!(
1629            actual,
1630            r#"{
1631            "git": {
1632                "inline_blame": {
1633                    "enabled": true
1634                }
1635            }
1636        }
1637        "#
1638            .unindent()
1639        );
1640    }
1641
1642    #[gpui::test]
1643    fn test_global_settings(cx: &mut App) {
1644        let mut store = SettingsStore::new(cx, &test_settings());
1645        store.register_setting::<ItemSettings>(cx);
1646
1647        // Set global settings - these should override defaults but not user settings
1648        store
1649            .set_global_settings(
1650                r#"{
1651                    "tabs": {
1652                        "close_position": "right",
1653                        "git_status": true,
1654                    }
1655                }"#,
1656                cx,
1657            )
1658            .unwrap();
1659
1660        // Before user settings, global settings should apply
1661        assert_eq!(
1662            store.get::<ItemSettings>(None),
1663            &ItemSettings {
1664                close_position: ClosePosition::Right,
1665                git_status: true,
1666            }
1667        );
1668
1669        // Set user settings - these should override both defaults and global
1670        store
1671            .set_user_settings(
1672                r#"{
1673                    "tabs": {
1674                        "close_position": "left"
1675                    }
1676                }"#,
1677                cx,
1678            )
1679            .unwrap();
1680
1681        // User settings should override global settings
1682        assert_eq!(
1683            store.get::<ItemSettings>(None),
1684            &ItemSettings {
1685                close_position: ClosePosition::Left,
1686                git_status: true, // Staff from global settings
1687            }
1688        );
1689    }
1690
1691    #[gpui::test]
1692    fn test_get_value_for_field_basic(cx: &mut App) {
1693        let mut store = SettingsStore::new(cx, &test_settings());
1694        store.register_setting::<DefaultLanguageSettings>(cx);
1695
1696        store
1697            .set_user_settings(r#"{"preferred_line_length": 0}"#, cx)
1698            .unwrap();
1699        let local = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
1700        store
1701            .set_local_settings(
1702                local.0,
1703                local.1.clone(),
1704                LocalSettingsKind::Settings,
1705                Some(r#"{}"#),
1706                cx,
1707            )
1708            .unwrap();
1709
1710        fn get(content: &SettingsContent) -> &Option<u32> {
1711            &content.project.all_languages.defaults.preferred_line_length
1712        }
1713
1714        let default_value = get(&store.default_settings).unwrap();
1715
1716        assert_eq!(
1717            store.get_value_from_file(SettingsFile::Local(local.clone()), get),
1718            (SettingsFile::User, &0)
1719        );
1720        assert_eq!(
1721            store.get_value_from_file(SettingsFile::User, get),
1722            (SettingsFile::User, &0)
1723        );
1724        store.set_user_settings(r#"{}"#, cx).unwrap();
1725        assert_eq!(
1726            store.get_value_from_file(SettingsFile::Local(local.clone()), get),
1727            (SettingsFile::Default, &default_value)
1728        );
1729        store
1730            .set_local_settings(
1731                local.0,
1732                local.1.clone(),
1733                LocalSettingsKind::Settings,
1734                Some(r#"{"preferred_line_length": 80}"#),
1735                cx,
1736            )
1737            .unwrap();
1738        assert_eq!(
1739            store.get_value_from_file(SettingsFile::Local(local.clone()), get),
1740            (SettingsFile::Local(local), &80)
1741        );
1742        assert_eq!(
1743            store.get_value_from_file(SettingsFile::User, get),
1744            (SettingsFile::Default, &default_value)
1745        );
1746    }
1747
1748    #[gpui::test]
1749    fn test_get_value_for_field_local_worktrees_dont_interfere(cx: &mut App) {
1750        let mut store = SettingsStore::new(cx, &test_settings());
1751        store.register_setting::<DefaultLanguageSettings>(cx);
1752        store.register_setting::<AutoUpdateSetting>(cx);
1753
1754        let local_1 = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
1755
1756        let local_1_child = (
1757            WorktreeId::from_usize(0),
1758            RelPath::new(
1759                std::path::Path::new("child1"),
1760                util::paths::PathStyle::Posix,
1761            )
1762            .unwrap()
1763            .into_arc(),
1764        );
1765
1766        let local_2 = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
1767        let local_2_child = (
1768            WorktreeId::from_usize(1),
1769            RelPath::new(
1770                std::path::Path::new("child2"),
1771                util::paths::PathStyle::Posix,
1772            )
1773            .unwrap()
1774            .into_arc(),
1775        );
1776
1777        fn get(content: &SettingsContent) -> &Option<u32> {
1778            &content.project.all_languages.defaults.preferred_line_length
1779        }
1780
1781        store
1782            .set_local_settings(
1783                local_1.0,
1784                local_1.1.clone(),
1785                LocalSettingsKind::Settings,
1786                Some(r#"{"preferred_line_length": 1}"#),
1787                cx,
1788            )
1789            .unwrap();
1790        store
1791            .set_local_settings(
1792                local_1_child.0,
1793                local_1_child.1.clone(),
1794                LocalSettingsKind::Settings,
1795                Some(r#"{}"#),
1796                cx,
1797            )
1798            .unwrap();
1799        store
1800            .set_local_settings(
1801                local_2.0,
1802                local_2.1.clone(),
1803                LocalSettingsKind::Settings,
1804                Some(r#"{"preferred_line_length": 2}"#),
1805                cx,
1806            )
1807            .unwrap();
1808        store
1809            .set_local_settings(
1810                local_2_child.0,
1811                local_2_child.1.clone(),
1812                LocalSettingsKind::Settings,
1813                Some(r#"{}"#),
1814                cx,
1815            )
1816            .unwrap();
1817
1818        // each local child should only inherit from it's parent
1819        assert_eq!(
1820            store.get_value_from_file(SettingsFile::Local(local_2_child), get),
1821            (SettingsFile::Local(local_2), &2)
1822        );
1823        assert_eq!(
1824            store.get_value_from_file(SettingsFile::Local(local_1_child.clone()), get),
1825            (SettingsFile::Local(local_1.clone()), &1)
1826        );
1827
1828        // adjacent children should be treated as siblings not inherit from each other
1829        let local_1_adjacent_child = (local_1.0, rel_path("adjacent_child").into_arc());
1830        store
1831            .set_local_settings(
1832                local_1_adjacent_child.0,
1833                local_1_adjacent_child.1.clone(),
1834                LocalSettingsKind::Settings,
1835                Some(r#"{}"#),
1836                cx,
1837            )
1838            .unwrap();
1839        store
1840            .set_local_settings(
1841                local_1_child.0,
1842                local_1_child.1.clone(),
1843                LocalSettingsKind::Settings,
1844                Some(r#"{"preferred_line_length": 3}"#),
1845                cx,
1846            )
1847            .unwrap();
1848
1849        assert_eq!(
1850            store.get_value_from_file(SettingsFile::Local(local_1_adjacent_child.clone()), get),
1851            (SettingsFile::Local(local_1.clone()), &1)
1852        );
1853        store
1854            .set_local_settings(
1855                local_1_adjacent_child.0,
1856                local_1_adjacent_child.1,
1857                LocalSettingsKind::Settings,
1858                Some(r#"{"preferred_line_length": 3}"#),
1859                cx,
1860            )
1861            .unwrap();
1862        store
1863            .set_local_settings(
1864                local_1_child.0,
1865                local_1_child.1.clone(),
1866                LocalSettingsKind::Settings,
1867                Some(r#"{}"#),
1868                cx,
1869            )
1870            .unwrap();
1871        assert_eq!(
1872            store.get_value_from_file(SettingsFile::Local(local_1_child), get),
1873            (SettingsFile::Local(local_1), &1)
1874        );
1875    }
1876
1877    #[gpui::test]
1878    fn test_get_overrides_for_field(cx: &mut App) {
1879        let mut store = SettingsStore::new(cx, &test_settings());
1880        store.register_setting::<DefaultLanguageSettings>(cx);
1881
1882        let wt0_root = (WorktreeId::from_usize(0), RelPath::empty().into_arc());
1883        let wt0_child1 = (WorktreeId::from_usize(0), rel_path("child1").into_arc());
1884        let wt0_child2 = (WorktreeId::from_usize(0), rel_path("child2").into_arc());
1885
1886        let wt1_root = (WorktreeId::from_usize(1), RelPath::empty().into_arc());
1887        let wt1_subdir = (WorktreeId::from_usize(1), rel_path("subdir").into_arc());
1888
1889        fn get(content: &SettingsContent) -> &Option<u32> {
1890            &content.project.all_languages.defaults.preferred_line_length
1891        }
1892
1893        store
1894            .set_user_settings(r#"{"preferred_line_length": 100}"#, cx)
1895            .unwrap();
1896
1897        store
1898            .set_local_settings(
1899                wt0_root.0,
1900                wt0_root.1.clone(),
1901                LocalSettingsKind::Settings,
1902                Some(r#"{"preferred_line_length": 80}"#),
1903                cx,
1904            )
1905            .unwrap();
1906        store
1907            .set_local_settings(
1908                wt0_child1.0,
1909                wt0_child1.1.clone(),
1910                LocalSettingsKind::Settings,
1911                Some(r#"{"preferred_line_length": 120}"#),
1912                cx,
1913            )
1914            .unwrap();
1915        store
1916            .set_local_settings(
1917                wt0_child2.0,
1918                wt0_child2.1.clone(),
1919                LocalSettingsKind::Settings,
1920                Some(r#"{}"#),
1921                cx,
1922            )
1923            .unwrap();
1924
1925        store
1926            .set_local_settings(
1927                wt1_root.0,
1928                wt1_root.1.clone(),
1929                LocalSettingsKind::Settings,
1930                Some(r#"{"preferred_line_length": 90}"#),
1931                cx,
1932            )
1933            .unwrap();
1934        store
1935            .set_local_settings(
1936                wt1_subdir.0,
1937                wt1_subdir.1.clone(),
1938                LocalSettingsKind::Settings,
1939                Some(r#"{}"#),
1940                cx,
1941            )
1942            .unwrap();
1943
1944        let overrides = store.get_overrides_for_field(SettingsFile::Default, get);
1945        assert_eq!(
1946            overrides,
1947            vec![
1948                SettingsFile::User,
1949                SettingsFile::Local(wt0_root.clone()),
1950                SettingsFile::Local(wt0_child1.clone()),
1951                SettingsFile::Local(wt1_root.clone()),
1952            ]
1953        );
1954
1955        let overrides = store.get_overrides_for_field(SettingsFile::User, get);
1956        assert_eq!(
1957            overrides,
1958            vec![
1959                SettingsFile::Local(wt0_root.clone()),
1960                SettingsFile::Local(wt0_child1.clone()),
1961                SettingsFile::Local(wt1_root.clone()),
1962            ]
1963        );
1964
1965        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt0_root), get);
1966        assert_eq!(overrides, vec![]);
1967
1968        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt0_child1.clone()), get);
1969        assert_eq!(overrides, vec![]);
1970
1971        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt0_child2), get);
1972        assert_eq!(overrides, vec![]);
1973
1974        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt1_root), get);
1975        assert_eq!(overrides, vec![]);
1976
1977        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt1_subdir), get);
1978        assert_eq!(overrides, vec![]);
1979
1980        let wt0_deep_child = (
1981            WorktreeId::from_usize(0),
1982            rel_path("child1/subdir").into_arc(),
1983        );
1984        store
1985            .set_local_settings(
1986                wt0_deep_child.0,
1987                wt0_deep_child.1.clone(),
1988                LocalSettingsKind::Settings,
1989                Some(r#"{"preferred_line_length": 140}"#),
1990                cx,
1991            )
1992            .unwrap();
1993
1994        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt0_deep_child), get);
1995        assert_eq!(overrides, vec![]);
1996
1997        let overrides = store.get_overrides_for_field(SettingsFile::Local(wt0_child1), get);
1998        assert_eq!(overrides, vec![]);
1999    }
2000}