settings_store.rs

   1use anyhow::{anyhow, Context, Result};
   2use collections::{btree_map, hash_map, BTreeMap, HashMap};
   3use gpui::{AppContext, AsyncAppContext, BorrowAppContext, Global, UpdateGlobal};
   4use lazy_static::lazy_static;
   5use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
   6use serde::{de::DeserializeOwned, Deserialize as _, Serialize};
   7use smallvec::SmallVec;
   8use std::{
   9    any::{type_name, Any, TypeId},
  10    fmt::Debug,
  11    ops::Range,
  12    path::Path,
  13    str,
  14    sync::Arc,
  15};
  16use util::{merge_non_null_json_value_into, RangeExt, ResultExt as _};
  17
  18/// A value that can be defined as a user setting.
  19///
  20/// Settings can be loaded from a combination of multiple JSON files.
  21pub trait Settings: 'static + Send + Sync {
  22    /// The name of a key within the JSON file from which this setting should
  23    /// be deserialized. If this is `None`, then the setting will be deserialized
  24    /// from the root object.
  25    const KEY: Option<&'static str>;
  26
  27    /// The type that is stored in an individual JSON file.
  28    type FileContent: Clone + Default + Serialize + DeserializeOwned + JsonSchema;
  29
  30    /// The logic for combining together values from one or more JSON files into the
  31    /// final value for this setting.
  32    fn load(sources: SettingsSources<Self::FileContent>, cx: &mut AppContext) -> Result<Self>
  33    where
  34        Self: Sized;
  35
  36    fn json_schema(
  37        generator: &mut SchemaGenerator,
  38        _: &SettingsJsonSchemaParams,
  39        _: &AppContext,
  40    ) -> RootSchema {
  41        generator.root_schema_for::<Self::FileContent>()
  42    }
  43
  44    fn missing_default() -> anyhow::Error {
  45        anyhow::anyhow!("missing default")
  46    }
  47
  48    fn register(cx: &mut AppContext)
  49    where
  50        Self: Sized,
  51    {
  52        SettingsStore::update_global(cx, |store, cx| {
  53            store.register_setting::<Self>(cx);
  54        });
  55    }
  56
  57    #[track_caller]
  58    fn get<'a>(path: Option<SettingsLocation>, cx: &'a AppContext) -> &'a Self
  59    where
  60        Self: Sized,
  61    {
  62        cx.global::<SettingsStore>().get(path)
  63    }
  64
  65    #[track_caller]
  66    fn get_global(cx: &AppContext) -> &Self
  67    where
  68        Self: Sized,
  69    {
  70        cx.global::<SettingsStore>().get(None)
  71    }
  72
  73    #[track_caller]
  74    fn try_read_global<R>(cx: &AsyncAppContext, f: impl FnOnce(&Self) -> R) -> Option<R>
  75    where
  76        Self: Sized,
  77    {
  78        cx.try_read_global(|s: &SettingsStore, _| f(s.get(None)))
  79    }
  80
  81    #[track_caller]
  82    fn override_global(settings: Self, cx: &mut AppContext)
  83    where
  84        Self: Sized,
  85    {
  86        cx.global_mut::<SettingsStore>().override_global(settings)
  87    }
  88}
  89
  90#[derive(Clone, Copy, Debug)]
  91pub struct SettingsSources<'a, T> {
  92    /// The default Zed settings.
  93    pub default: &'a T,
  94    /// Settings provided by extensions.
  95    pub extensions: Option<&'a T>,
  96    /// The user settings.
  97    pub user: Option<&'a T>,
  98    /// The user settings for the current release channel.
  99    pub release_channel: Option<&'a T>,
 100    /// The project settings, ordered from least specific to most specific.
 101    pub project: &'a [&'a T],
 102}
 103
 104impl<'a, T: Serialize> SettingsSources<'a, T> {
 105    /// Returns an iterator over the default settings as well as all settings customizations.
 106    pub fn defaults_and_customizations(&self) -> impl Iterator<Item = &T> {
 107        [self.default].into_iter().chain(self.customizations())
 108    }
 109
 110    /// Returns an iterator over all of the settings customizations.
 111    pub fn customizations(&self) -> impl Iterator<Item = &T> {
 112        self.extensions
 113            .into_iter()
 114            .chain(self.user)
 115            .chain(self.release_channel)
 116            .chain(self.project.iter().copied())
 117    }
 118
 119    /// Returns the settings after performing a JSON merge of the provided customizations.
 120    ///
 121    /// Customizations later in the iterator win out over the earlier ones.
 122    pub fn json_merge_with<O: DeserializeOwned>(
 123        customizations: impl Iterator<Item = &'a T>,
 124    ) -> Result<O> {
 125        let mut merged = serde_json::Value::Null;
 126        for value in customizations {
 127            merge_non_null_json_value_into(serde_json::to_value(value).unwrap(), &mut merged);
 128        }
 129        Ok(serde_json::from_value(merged)?)
 130    }
 131
 132    /// Returns the settings after performing a JSON merge of the customizations into the
 133    /// default settings.
 134    ///
 135    /// More-specific customizations win out over the less-specific ones.
 136    pub fn json_merge<O: DeserializeOwned>(&'a self) -> Result<O> {
 137        Self::json_merge_with(self.defaults_and_customizations())
 138    }
 139}
 140
 141#[derive(Clone, Copy)]
 142pub struct SettingsLocation<'a> {
 143    pub worktree_id: usize,
 144    pub path: &'a Path,
 145}
 146
 147pub struct SettingsJsonSchemaParams<'a> {
 148    pub staff_mode: bool,
 149    pub language_names: &'a [String],
 150    pub font_names: &'a [String],
 151}
 152
 153/// A set of strongly-typed setting values defined via multiple JSON files.
 154pub struct SettingsStore {
 155    setting_values: HashMap<TypeId, Box<dyn AnySettingValue>>,
 156    raw_default_settings: serde_json::Value,
 157    raw_user_settings: serde_json::Value,
 158    raw_extension_settings: serde_json::Value,
 159    raw_local_settings: BTreeMap<(usize, Arc<Path>), serde_json::Value>,
 160    tab_size_callback: Option<(
 161        TypeId,
 162        Box<dyn Fn(&dyn Any) -> Option<usize> + Send + Sync + 'static>,
 163    )>,
 164}
 165
 166impl Global for SettingsStore {}
 167
 168impl Default for SettingsStore {
 169    fn default() -> Self {
 170        SettingsStore {
 171            setting_values: Default::default(),
 172            raw_default_settings: serde_json::json!({}),
 173            raw_user_settings: serde_json::json!({}),
 174            raw_extension_settings: serde_json::json!({}),
 175            raw_local_settings: Default::default(),
 176            tab_size_callback: Default::default(),
 177        }
 178    }
 179}
 180
 181#[derive(Debug)]
 182struct SettingValue<T> {
 183    global_value: Option<T>,
 184    local_values: Vec<(usize, Arc<Path>, T)>,
 185}
 186
 187trait AnySettingValue: 'static + Send + Sync {
 188    fn key(&self) -> Option<&'static str>;
 189    fn setting_type_name(&self) -> &'static str;
 190    fn deserialize_setting(&self, json: &serde_json::Value) -> Result<DeserializedSetting>;
 191    fn load_setting(
 192        &self,
 193        sources: SettingsSources<DeserializedSetting>,
 194        cx: &mut AppContext,
 195    ) -> Result<Box<dyn Any>>;
 196    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any;
 197    fn set_global_value(&mut self, value: Box<dyn Any>);
 198    fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>);
 199    fn json_schema(
 200        &self,
 201        generator: &mut SchemaGenerator,
 202        _: &SettingsJsonSchemaParams,
 203        cx: &AppContext,
 204    ) -> RootSchema;
 205}
 206
 207struct DeserializedSetting(Box<dyn Any>);
 208
 209impl SettingsStore {
 210    pub fn update<C, R>(cx: &mut C, f: impl FnOnce(&mut Self, &mut C) -> R) -> R
 211    where
 212        C: BorrowAppContext,
 213    {
 214        cx.update_global(f)
 215    }
 216
 217    /// Add a new type of setting to the store.
 218    pub fn register_setting<T: Settings>(&mut self, cx: &mut AppContext) {
 219        let setting_type_id = TypeId::of::<T>();
 220        let entry = self.setting_values.entry(setting_type_id);
 221        if matches!(entry, hash_map::Entry::Occupied(_)) {
 222            return;
 223        }
 224
 225        let setting_value = entry.or_insert(Box::new(SettingValue::<T> {
 226            global_value: None,
 227            local_values: Vec::new(),
 228        }));
 229
 230        if let Some(default_settings) = setting_value
 231            .deserialize_setting(&self.raw_default_settings)
 232            .log_err()
 233        {
 234            let user_value = setting_value
 235                .deserialize_setting(&self.raw_user_settings)
 236                .log_err();
 237
 238            let mut release_channel_value = None;
 239            if let Some(release_settings) = &self
 240                .raw_user_settings
 241                .get(release_channel::RELEASE_CHANNEL.dev_name())
 242            {
 243                release_channel_value = setting_value
 244                    .deserialize_setting(release_settings)
 245                    .log_err();
 246            }
 247
 248            let extension_value = setting_value
 249                .deserialize_setting(&self.raw_extension_settings)
 250                .log_err();
 251
 252            if let Some(setting) = setting_value
 253                .load_setting(
 254                    SettingsSources {
 255                        default: &default_settings,
 256                        release_channel: release_channel_value.as_ref(),
 257                        extensions: extension_value.as_ref(),
 258                        user: user_value.as_ref(),
 259                        project: &[],
 260                    },
 261                    cx,
 262                )
 263                .context("A default setting must be added to the `default.json` file")
 264                .log_err()
 265            {
 266                setting_value.set_global_value(setting);
 267            }
 268        }
 269    }
 270
 271    /// Get the value of a setting.
 272    ///
 273    /// Panics if the given setting type has not been registered, or if there is no
 274    /// value for this setting.
 275    pub fn get<T: Settings>(&self, path: Option<SettingsLocation>) -> &T {
 276        self.setting_values
 277            .get(&TypeId::of::<T>())
 278            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 279            .value_for_path(path)
 280            .downcast_ref::<T>()
 281            .expect("no default value for setting type")
 282    }
 283
 284    /// Override the global value for a setting.
 285    ///
 286    /// The given value will be overwritten if the user settings file changes.
 287    pub fn override_global<T: Settings>(&mut self, value: T) {
 288        self.setting_values
 289            .get_mut(&TypeId::of::<T>())
 290            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()))
 291            .set_global_value(Box::new(value))
 292    }
 293
 294    /// Get the user's settings as a raw JSON value.
 295    ///
 296    /// This is only for debugging and reporting. For user-facing functionality,
 297    /// use the typed setting interface.
 298    pub fn raw_user_settings(&self) -> &serde_json::Value {
 299        &self.raw_user_settings
 300    }
 301
 302    #[cfg(any(test, feature = "test-support"))]
 303    pub fn test(cx: &mut AppContext) -> Self {
 304        let mut this = Self::default();
 305        this.set_default_settings(&crate::test_settings(), cx)
 306            .unwrap();
 307        this.set_user_settings("{}", cx).unwrap();
 308        this
 309    }
 310
 311    /// Updates the value of a setting in the user's global configuration.
 312    ///
 313    /// This is only for tests. Normally, settings are only loaded from
 314    /// JSON files.
 315    #[cfg(any(test, feature = "test-support"))]
 316    pub fn update_user_settings<T: Settings>(
 317        &mut self,
 318        cx: &mut AppContext,
 319        update: impl FnOnce(&mut T::FileContent),
 320    ) {
 321        let old_text = serde_json::to_string(&self.raw_user_settings).unwrap();
 322        let new_text = self.new_text_for_update::<T>(old_text, update);
 323        self.set_user_settings(&new_text, cx).unwrap();
 324    }
 325
 326    /// Updates the value of a setting in a JSON file, returning the new text
 327    /// for that JSON file.
 328    pub fn new_text_for_update<T: Settings>(
 329        &self,
 330        old_text: String,
 331        update: impl FnOnce(&mut T::FileContent),
 332    ) -> String {
 333        let edits = self.edits_for_update::<T>(&old_text, update);
 334        let mut new_text = old_text;
 335        for (range, replacement) in edits.into_iter() {
 336            new_text.replace_range(range, &replacement);
 337        }
 338        new_text
 339    }
 340
 341    /// Updates the value of a setting in a JSON file, returning a list
 342    /// of edits to apply to the JSON file.
 343    pub fn edits_for_update<T: Settings>(
 344        &self,
 345        text: &str,
 346        update: impl FnOnce(&mut T::FileContent),
 347    ) -> Vec<(Range<usize>, String)> {
 348        let setting_type_id = TypeId::of::<T>();
 349
 350        let setting = self
 351            .setting_values
 352            .get(&setting_type_id)
 353            .unwrap_or_else(|| panic!("unregistered setting type {}", type_name::<T>()));
 354        let raw_settings = parse_json_with_comments::<serde_json::Value>(text).unwrap_or_default();
 355        let old_content = match setting.deserialize_setting(&raw_settings) {
 356            Ok(content) => content.0.downcast::<T::FileContent>().unwrap(),
 357            Err(_) => Box::<<T as Settings>::FileContent>::default(),
 358        };
 359        let mut new_content = old_content.clone();
 360        update(&mut new_content);
 361
 362        let old_value = serde_json::to_value(&old_content).unwrap();
 363        let new_value = serde_json::to_value(new_content).unwrap();
 364
 365        let mut key_path = Vec::new();
 366        if let Some(key) = T::KEY {
 367            key_path.push(key);
 368        }
 369
 370        let mut edits = Vec::new();
 371        let tab_size = self.json_tab_size();
 372        let mut text = text.to_string();
 373        update_value_in_json_text(
 374            &mut text,
 375            &mut key_path,
 376            tab_size,
 377            &old_value,
 378            &new_value,
 379            &mut edits,
 380        );
 381        edits
 382    }
 383
 384    /// Configure the tab sized when updating JSON files.
 385    pub fn set_json_tab_size_callback<T: Settings>(
 386        &mut self,
 387        get_tab_size: fn(&T) -> Option<usize>,
 388    ) {
 389        self.tab_size_callback = Some((
 390            TypeId::of::<T>(),
 391            Box::new(move |value| get_tab_size(value.downcast_ref::<T>().unwrap())),
 392        ));
 393    }
 394
 395    fn json_tab_size(&self) -> usize {
 396        const DEFAULT_JSON_TAB_SIZE: usize = 2;
 397
 398        if let Some((setting_type_id, callback)) = &self.tab_size_callback {
 399            let setting_value = self.setting_values.get(setting_type_id).unwrap();
 400            let value = setting_value.value_for_path(None);
 401            if let Some(value) = callback(value) {
 402                return value;
 403            }
 404        }
 405
 406        DEFAULT_JSON_TAB_SIZE
 407    }
 408
 409    /// Sets the default settings via a JSON string.
 410    ///
 411    /// The string should contain a JSON object with a default value for every setting.
 412    pub fn set_default_settings(
 413        &mut self,
 414        default_settings_content: &str,
 415        cx: &mut AppContext,
 416    ) -> Result<()> {
 417        let settings: serde_json::Value = parse_json_with_comments(default_settings_content)?;
 418        if settings.is_object() {
 419            self.raw_default_settings = settings;
 420            self.recompute_values(None, cx)?;
 421            Ok(())
 422        } else {
 423            Err(anyhow!("settings must be an object"))
 424        }
 425    }
 426
 427    /// Sets the user settings via a JSON string.
 428    pub fn set_user_settings(
 429        &mut self,
 430        user_settings_content: &str,
 431        cx: &mut AppContext,
 432    ) -> Result<()> {
 433        let settings: serde_json::Value = if user_settings_content.is_empty() {
 434            parse_json_with_comments("{}")?
 435        } else {
 436            parse_json_with_comments(user_settings_content)?
 437        };
 438        if settings.is_object() {
 439            self.raw_user_settings = settings;
 440            self.recompute_values(None, cx)?;
 441            Ok(())
 442        } else {
 443            Err(anyhow!("settings must be an object"))
 444        }
 445    }
 446
 447    /// Add or remove a set of local settings via a JSON string.
 448    pub fn set_local_settings(
 449        &mut self,
 450        root_id: usize,
 451        path: Arc<Path>,
 452        settings_content: Option<&str>,
 453        cx: &mut AppContext,
 454    ) -> Result<()> {
 455        if settings_content.is_some_and(|content| !content.is_empty()) {
 456            self.raw_local_settings.insert(
 457                (root_id, path.clone()),
 458                parse_json_with_comments(settings_content.unwrap())?,
 459            );
 460        } else {
 461            self.raw_local_settings.remove(&(root_id, path.clone()));
 462        }
 463        self.recompute_values(Some((root_id, &path)), cx)?;
 464        Ok(())
 465    }
 466
 467    pub fn set_extension_settings<T: Serialize>(
 468        &mut self,
 469        content: T,
 470        cx: &mut AppContext,
 471    ) -> Result<()> {
 472        let settings: serde_json::Value = serde_json::to_value(content)?;
 473        if settings.is_object() {
 474            self.raw_extension_settings = settings;
 475            self.recompute_values(None, cx)?;
 476            Ok(())
 477        } else {
 478            Err(anyhow!("settings must be an object"))
 479        }
 480    }
 481
 482    /// Add or remove a set of local settings via a JSON string.
 483    pub fn clear_local_settings(&mut self, root_id: usize, cx: &mut AppContext) -> Result<()> {
 484        self.raw_local_settings.retain(|k, _| k.0 != root_id);
 485        self.recompute_values(Some((root_id, "".as_ref())), cx)?;
 486        Ok(())
 487    }
 488
 489    pub fn local_settings(&self, root_id: usize) -> impl '_ + Iterator<Item = (Arc<Path>, String)> {
 490        self.raw_local_settings
 491            .range((root_id, Path::new("").into())..(root_id + 1, Path::new("").into()))
 492            .map(|((_, path), content)| (path.clone(), serde_json::to_string(content).unwrap()))
 493    }
 494
 495    pub fn json_schema(
 496        &self,
 497        schema_params: &SettingsJsonSchemaParams,
 498        cx: &AppContext,
 499    ) -> serde_json::Value {
 500        use schemars::{
 501            gen::SchemaSettings,
 502            schema::{Schema, SchemaObject},
 503        };
 504
 505        let settings = SchemaSettings::draft07().with(|settings| {
 506            settings.option_add_null_type = false;
 507        });
 508        let mut generator = SchemaGenerator::new(settings);
 509        let mut combined_schema = RootSchema::default();
 510
 511        for setting_value in self.setting_values.values() {
 512            let setting_schema = setting_value.json_schema(&mut generator, schema_params, cx);
 513            combined_schema
 514                .definitions
 515                .extend(setting_schema.definitions);
 516
 517            let target_schema = if let Some(key) = setting_value.key() {
 518                let key_schema = combined_schema
 519                    .schema
 520                    .object()
 521                    .properties
 522                    .entry(key.to_string())
 523                    .or_insert_with(|| Schema::Object(SchemaObject::default()));
 524                if let Schema::Object(key_schema) = key_schema {
 525                    key_schema
 526                } else {
 527                    continue;
 528                }
 529            } else {
 530                &mut combined_schema.schema
 531            };
 532
 533            merge_schema(target_schema, setting_schema.schema);
 534        }
 535
 536        fn merge_schema(target: &mut SchemaObject, mut source: SchemaObject) {
 537            let source_subschemas = source.subschemas();
 538            let target_subschemas = target.subschemas();
 539            if let Some(all_of) = source_subschemas.all_of.take() {
 540                target_subschemas
 541                    .all_of
 542                    .get_or_insert(Vec::new())
 543                    .extend(all_of);
 544            }
 545            if let Some(any_of) = source_subschemas.any_of.take() {
 546                target_subschemas
 547                    .any_of
 548                    .get_or_insert(Vec::new())
 549                    .extend(any_of);
 550            }
 551            if let Some(one_of) = source_subschemas.one_of.take() {
 552                target_subschemas
 553                    .one_of
 554                    .get_or_insert(Vec::new())
 555                    .extend(one_of);
 556            }
 557
 558            if let Some(source) = source.object {
 559                let target_properties = &mut target.object().properties;
 560                for (key, value) in source.properties {
 561                    match target_properties.entry(key) {
 562                        btree_map::Entry::Vacant(e) => {
 563                            e.insert(value);
 564                        }
 565                        btree_map::Entry::Occupied(e) => {
 566                            if let (Schema::Object(target), Schema::Object(src)) =
 567                                (e.into_mut(), value)
 568                            {
 569                                merge_schema(target, src);
 570                            }
 571                        }
 572                    }
 573                }
 574            }
 575
 576            overwrite(&mut target.instance_type, source.instance_type);
 577            overwrite(&mut target.string, source.string);
 578            overwrite(&mut target.number, source.number);
 579            overwrite(&mut target.reference, source.reference);
 580            overwrite(&mut target.array, source.array);
 581            overwrite(&mut target.enum_values, source.enum_values);
 582
 583            fn overwrite<T>(target: &mut Option<T>, source: Option<T>) {
 584                if let Some(source) = source {
 585                    *target = Some(source);
 586                }
 587            }
 588        }
 589
 590        for release_stage in ["dev", "nightly", "stable", "preview"] {
 591            let schema = combined_schema.schema.clone();
 592            combined_schema
 593                .schema
 594                .object()
 595                .properties
 596                .insert(release_stage.to_string(), schema.into());
 597        }
 598
 599        serde_json::to_value(&combined_schema).unwrap()
 600    }
 601
 602    fn recompute_values(
 603        &mut self,
 604        changed_local_path: Option<(usize, &Path)>,
 605        cx: &mut AppContext,
 606    ) -> Result<()> {
 607        // Reload the global and local values for every setting.
 608        let mut project_settings_stack = Vec::<DeserializedSetting>::new();
 609        let mut paths_stack = Vec::<Option<(usize, &Path)>>::new();
 610        for setting_value in self.setting_values.values_mut() {
 611            let default_settings = setting_value.deserialize_setting(&self.raw_default_settings)?;
 612
 613            let extension_settings = setting_value
 614                .deserialize_setting(&self.raw_extension_settings)
 615                .log_err();
 616
 617            let user_settings = setting_value
 618                .deserialize_setting(&self.raw_user_settings)
 619                .log_err();
 620
 621            let mut release_channel_settings = None;
 622            if let Some(release_settings) = &self
 623                .raw_user_settings
 624                .get(release_channel::RELEASE_CHANNEL.dev_name())
 625            {
 626                if let Some(release_settings) = setting_value
 627                    .deserialize_setting(release_settings)
 628                    .log_err()
 629                {
 630                    release_channel_settings = Some(release_settings);
 631                }
 632            }
 633
 634            // If the global settings file changed, reload the global value for the field.
 635            project_settings_stack.clear();
 636            paths_stack.clear();
 637            if changed_local_path.is_none() {
 638                if let Some(value) = setting_value
 639                    .load_setting(
 640                        SettingsSources {
 641                            default: &default_settings,
 642                            extensions: extension_settings.as_ref(),
 643                            user: user_settings.as_ref(),
 644                            release_channel: release_channel_settings.as_ref(),
 645                            project: &[],
 646                        },
 647                        cx,
 648                    )
 649                    .log_err()
 650                {
 651                    setting_value.set_global_value(value);
 652                }
 653            }
 654
 655            // Reload the local values for the setting.
 656            for ((root_id, path), local_settings) in &self.raw_local_settings {
 657                // Build a stack of all of the local values for that setting.
 658                while let Some(prev_entry) = paths_stack.last() {
 659                    if let Some((prev_root_id, prev_path)) = prev_entry {
 660                        if root_id != prev_root_id || !path.starts_with(prev_path) {
 661                            paths_stack.pop();
 662                            project_settings_stack.pop();
 663                            continue;
 664                        }
 665                    }
 666                    break;
 667                }
 668
 669                if let Some(local_settings) =
 670                    setting_value.deserialize_setting(local_settings).log_err()
 671                {
 672                    paths_stack.push(Some((*root_id, path.as_ref())));
 673                    project_settings_stack.push(local_settings);
 674
 675                    // If a local settings file changed, then avoid recomputing local
 676                    // settings for any path outside of that directory.
 677                    if changed_local_path.map_or(false, |(changed_root_id, changed_local_path)| {
 678                        *root_id != changed_root_id || !path.starts_with(changed_local_path)
 679                    }) {
 680                        continue;
 681                    }
 682
 683                    if let Some(value) = setting_value
 684                        .load_setting(
 685                            SettingsSources {
 686                                default: &default_settings,
 687                                extensions: extension_settings.as_ref(),
 688                                user: user_settings.as_ref(),
 689                                release_channel: release_channel_settings.as_ref(),
 690                                project: &project_settings_stack.iter().collect::<Vec<_>>(),
 691                            },
 692                            cx,
 693                        )
 694                        .log_err()
 695                    {
 696                        setting_value.set_local_value(*root_id, path.clone(), value);
 697                    }
 698                }
 699            }
 700        }
 701        Ok(())
 702    }
 703}
 704
 705impl Debug for SettingsStore {
 706    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 707        f.debug_struct("SettingsStore")
 708            .field(
 709                "types",
 710                &self
 711                    .setting_values
 712                    .values()
 713                    .map(|value| value.setting_type_name())
 714                    .collect::<Vec<_>>(),
 715            )
 716            .field("default_settings", &self.raw_default_settings)
 717            .field("user_settings", &self.raw_user_settings)
 718            .field("local_settings", &self.raw_local_settings)
 719            .finish_non_exhaustive()
 720    }
 721}
 722
 723impl<T: Settings> AnySettingValue for SettingValue<T> {
 724    fn key(&self) -> Option<&'static str> {
 725        T::KEY
 726    }
 727
 728    fn setting_type_name(&self) -> &'static str {
 729        type_name::<T>()
 730    }
 731
 732    fn load_setting(
 733        &self,
 734        values: SettingsSources<DeserializedSetting>,
 735        cx: &mut AppContext,
 736    ) -> Result<Box<dyn Any>> {
 737        Ok(Box::new(T::load(
 738            SettingsSources {
 739                default: values.default.0.downcast_ref::<T::FileContent>().unwrap(),
 740                extensions: values
 741                    .extensions
 742                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 743                user: values
 744                    .user
 745                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 746                release_channel: values
 747                    .release_channel
 748                    .map(|value| value.0.downcast_ref::<T::FileContent>().unwrap()),
 749                project: values
 750                    .project
 751                    .iter()
 752                    .map(|value| value.0.downcast_ref().unwrap())
 753                    .collect::<SmallVec<[_; 3]>>()
 754                    .as_slice(),
 755            },
 756            cx,
 757        )?))
 758    }
 759
 760    fn deserialize_setting(&self, mut json: &serde_json::Value) -> Result<DeserializedSetting> {
 761        if let Some(key) = T::KEY {
 762            if let Some(value) = json.get(key) {
 763                json = value;
 764            } else {
 765                let value = T::FileContent::default();
 766                return Ok(DeserializedSetting(Box::new(value)));
 767            }
 768        }
 769        let value = T::FileContent::deserialize(json)?;
 770        Ok(DeserializedSetting(Box::new(value)))
 771    }
 772
 773    fn value_for_path(&self, path: Option<SettingsLocation>) -> &dyn Any {
 774        if let Some(SettingsLocation { worktree_id, path }) = path {
 775            for (settings_root_id, settings_path, value) in self.local_values.iter().rev() {
 776                if worktree_id == *settings_root_id && path.starts_with(settings_path) {
 777                    return value;
 778                }
 779            }
 780        }
 781        self.global_value
 782            .as_ref()
 783            .unwrap_or_else(|| panic!("no default value for setting {}", self.setting_type_name()))
 784    }
 785
 786    fn set_global_value(&mut self, value: Box<dyn Any>) {
 787        self.global_value = Some(*value.downcast().unwrap());
 788    }
 789
 790    fn set_local_value(&mut self, root_id: usize, path: Arc<Path>, value: Box<dyn Any>) {
 791        let value = *value.downcast().unwrap();
 792        match self
 793            .local_values
 794            .binary_search_by_key(&(root_id, &path), |e| (e.0, &e.1))
 795        {
 796            Ok(ix) => self.local_values[ix].2 = value,
 797            Err(ix) => self.local_values.insert(ix, (root_id, path, value)),
 798        }
 799    }
 800
 801    fn json_schema(
 802        &self,
 803        generator: &mut SchemaGenerator,
 804        params: &SettingsJsonSchemaParams,
 805        cx: &AppContext,
 806    ) -> RootSchema {
 807        T::json_schema(generator, params, cx)
 808    }
 809}
 810
 811fn update_value_in_json_text<'a>(
 812    text: &mut String,
 813    key_path: &mut Vec<&'a str>,
 814    tab_size: usize,
 815    old_value: &'a serde_json::Value,
 816    new_value: &'a serde_json::Value,
 817    edits: &mut Vec<(Range<usize>, String)>,
 818) {
 819    // If the old and new values are both objects, then compare them key by key,
 820    // preserving the comments and formatting of the unchanged parts. Otherwise,
 821    // replace the old value with the new value.
 822    if let (serde_json::Value::Object(old_object), serde_json::Value::Object(new_object)) =
 823        (old_value, new_value)
 824    {
 825        for (key, old_sub_value) in old_object.iter() {
 826            key_path.push(key);
 827            let new_sub_value = new_object.get(key).unwrap_or(&serde_json::Value::Null);
 828            update_value_in_json_text(
 829                text,
 830                key_path,
 831                tab_size,
 832                old_sub_value,
 833                new_sub_value,
 834                edits,
 835            );
 836            key_path.pop();
 837        }
 838        for (key, new_sub_value) in new_object.iter() {
 839            key_path.push(key);
 840            if !old_object.contains_key(key) {
 841                update_value_in_json_text(
 842                    text,
 843                    key_path,
 844                    tab_size,
 845                    &serde_json::Value::Null,
 846                    new_sub_value,
 847                    edits,
 848                );
 849            }
 850            key_path.pop();
 851        }
 852    } else if old_value != new_value {
 853        let mut new_value = new_value.clone();
 854        if let Some(new_object) = new_value.as_object_mut() {
 855            new_object.retain(|_, v| !v.is_null());
 856        }
 857        let (range, replacement) = replace_value_in_json_text(text, key_path, tab_size, &new_value);
 858        text.replace_range(range.clone(), &replacement);
 859        edits.push((range, replacement));
 860    }
 861}
 862
 863fn replace_value_in_json_text(
 864    text: &str,
 865    key_path: &[&str],
 866    tab_size: usize,
 867    new_value: &serde_json::Value,
 868) -> (Range<usize>, String) {
 869    const LANGUAGE_OVERRIDES: &str = "language_overrides";
 870    const LANGUAGES: &str = "languages";
 871
 872    lazy_static! {
 873        static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
 874            &tree_sitter_json::language(),
 875            "(pair key: (string) @key value: (_) @value)",
 876        )
 877        .unwrap();
 878    }
 879
 880    let mut parser = tree_sitter::Parser::new();
 881    parser.set_language(&tree_sitter_json::language()).unwrap();
 882    let syntax_tree = parser.parse(text, None).unwrap();
 883
 884    let mut cursor = tree_sitter::QueryCursor::new();
 885
 886    let has_language_overrides = text.contains(LANGUAGE_OVERRIDES);
 887
 888    let mut depth = 0;
 889    let mut last_value_range = 0..0;
 890    let mut first_key_start = None;
 891    let mut existing_value_range = 0..text.len();
 892    let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
 893    for mat in matches {
 894        if mat.captures.len() != 2 {
 895            continue;
 896        }
 897
 898        let key_range = mat.captures[0].node.byte_range();
 899        let value_range = mat.captures[1].node.byte_range();
 900
 901        // Don't enter sub objects until we find an exact
 902        // match for the current keypath
 903        if last_value_range.contains_inclusive(&value_range) {
 904            continue;
 905        }
 906
 907        last_value_range = value_range.clone();
 908
 909        if key_range.start > existing_value_range.end {
 910            break;
 911        }
 912
 913        first_key_start.get_or_insert(key_range.start);
 914
 915        let found_key = text
 916            .get(key_range.clone())
 917            .map(|key_text| {
 918                if key_path[depth] == LANGUAGES && has_language_overrides {
 919                    key_text == format!("\"{}\"", LANGUAGE_OVERRIDES)
 920                } else {
 921                    key_text == format!("\"{}\"", key_path[depth])
 922                }
 923            })
 924            .unwrap_or(false);
 925
 926        if found_key {
 927            existing_value_range = value_range;
 928            // Reset last value range when increasing in depth
 929            last_value_range = existing_value_range.start..existing_value_range.start;
 930            depth += 1;
 931
 932            if depth == key_path.len() {
 933                break;
 934            }
 935
 936            first_key_start = None;
 937        }
 938    }
 939
 940    // We found the exact key we want, insert the new value
 941    if depth == key_path.len() {
 942        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
 943        (existing_value_range, new_val)
 944    } else {
 945        // We have key paths, construct the sub objects
 946        let new_key = if has_language_overrides && key_path[depth] == LANGUAGES {
 947            LANGUAGE_OVERRIDES
 948        } else {
 949            key_path[depth]
 950        };
 951
 952        // We don't have the key, construct the nested objects
 953        let mut new_value = serde_json::to_value(new_value).unwrap();
 954        for key in key_path[(depth + 1)..].iter().rev() {
 955            if has_language_overrides && key == &LANGUAGES {
 956                new_value = serde_json::json!({ LANGUAGE_OVERRIDES.to_string(): new_value });
 957            } else {
 958                new_value = serde_json::json!({ key.to_string(): new_value });
 959            }
 960        }
 961
 962        if let Some(first_key_start) = first_key_start {
 963            let mut row = 0;
 964            let mut column = 0;
 965            for (ix, char) in text.char_indices() {
 966                if ix == first_key_start {
 967                    break;
 968                }
 969                if char == '\n' {
 970                    row += 1;
 971                    column = 0;
 972                } else {
 973                    column += char.len_utf8();
 974                }
 975            }
 976
 977            if row > 0 {
 978                // depth is 0 based, but division needs to be 1 based.
 979                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
 980                let space = ' ';
 981                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
 982                (first_key_start..first_key_start, content)
 983            } else {
 984                let new_val = serde_json::to_string(&new_value).unwrap();
 985                let mut content = format!(r#""{new_key}": {new_val},"#);
 986                content.push(' ');
 987                (first_key_start..first_key_start, content)
 988            }
 989        } else {
 990            new_value = serde_json::json!({ new_key.to_string(): new_value });
 991            let indent_prefix_len = 4 * depth;
 992            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
 993            if depth == 0 {
 994                new_val.push('\n');
 995            }
 996
 997            (existing_value_range, new_val)
 998        }
 999    }
1000}
1001
1002fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
1003    const SPACES: [u8; 32] = [b' '; 32];
1004
1005    debug_assert!(indent_size <= SPACES.len());
1006    debug_assert!(indent_prefix_len <= SPACES.len());
1007
1008    let mut output = Vec::new();
1009    let mut ser = serde_json::Serializer::with_formatter(
1010        &mut output,
1011        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
1012    );
1013
1014    value.serialize(&mut ser).unwrap();
1015    let text = String::from_utf8(output).unwrap();
1016
1017    let mut adjusted_text = String::new();
1018    for (i, line) in text.split('\n').enumerate() {
1019        if i > 0 {
1020            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1021        }
1022        adjusted_text.push_str(line);
1023        adjusted_text.push('\n');
1024    }
1025    adjusted_text.pop();
1026    adjusted_text
1027}
1028
1029pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1030    Ok(serde_json_lenient::from_str(content)?)
1031}
1032
1033#[cfg(test)]
1034mod tests {
1035    use super::*;
1036    use serde_derive::Deserialize;
1037    use unindent::Unindent;
1038
1039    #[gpui::test]
1040    fn test_settings_store_basic(cx: &mut AppContext) {
1041        let mut store = SettingsStore::default();
1042        store.register_setting::<UserSettings>(cx);
1043        store.register_setting::<TurboSetting>(cx);
1044        store.register_setting::<MultiKeySettings>(cx);
1045        store
1046            .set_default_settings(
1047                r#"{
1048                    "turbo": false,
1049                    "user": {
1050                        "name": "John Doe",
1051                        "age": 30,
1052                        "staff": false
1053                    }
1054                }"#,
1055                cx,
1056            )
1057            .unwrap();
1058
1059        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1060        assert_eq!(
1061            store.get::<UserSettings>(None),
1062            &UserSettings {
1063                name: "John Doe".to_string(),
1064                age: 30,
1065                staff: false,
1066            }
1067        );
1068        assert_eq!(
1069            store.get::<MultiKeySettings>(None),
1070            &MultiKeySettings {
1071                key1: String::new(),
1072                key2: String::new(),
1073            }
1074        );
1075
1076        store
1077            .set_user_settings(
1078                r#"{
1079                    "turbo": true,
1080                    "user": { "age": 31 },
1081                    "key1": "a"
1082                }"#,
1083                cx,
1084            )
1085            .unwrap();
1086
1087        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1088        assert_eq!(
1089            store.get::<UserSettings>(None),
1090            &UserSettings {
1091                name: "John Doe".to_string(),
1092                age: 31,
1093                staff: false
1094            }
1095        );
1096
1097        store
1098            .set_local_settings(
1099                1,
1100                Path::new("/root1").into(),
1101                Some(r#"{ "user": { "staff": true } }"#),
1102                cx,
1103            )
1104            .unwrap();
1105        store
1106            .set_local_settings(
1107                1,
1108                Path::new("/root1/subdir").into(),
1109                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1110                cx,
1111            )
1112            .unwrap();
1113
1114        store
1115            .set_local_settings(
1116                1,
1117                Path::new("/root2").into(),
1118                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1119                cx,
1120            )
1121            .unwrap();
1122
1123        assert_eq!(
1124            store.get::<UserSettings>(Some(SettingsLocation {
1125                worktree_id: 1,
1126                path: Path::new("/root1/something"),
1127            })),
1128            &UserSettings {
1129                name: "John Doe".to_string(),
1130                age: 31,
1131                staff: true
1132            }
1133        );
1134        assert_eq!(
1135            store.get::<UserSettings>(Some(SettingsLocation {
1136                worktree_id: 1,
1137                path: Path::new("/root1/subdir/something")
1138            })),
1139            &UserSettings {
1140                name: "Jane Doe".to_string(),
1141                age: 31,
1142                staff: true
1143            }
1144        );
1145        assert_eq!(
1146            store.get::<UserSettings>(Some(SettingsLocation {
1147                worktree_id: 1,
1148                path: Path::new("/root2/something")
1149            })),
1150            &UserSettings {
1151                name: "John Doe".to_string(),
1152                age: 42,
1153                staff: false
1154            }
1155        );
1156        assert_eq!(
1157            store.get::<MultiKeySettings>(Some(SettingsLocation {
1158                worktree_id: 1,
1159                path: Path::new("/root2/something")
1160            })),
1161            &MultiKeySettings {
1162                key1: "a".to_string(),
1163                key2: "b".to_string(),
1164            }
1165        );
1166    }
1167
1168    #[gpui::test]
1169    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1170        let mut store = SettingsStore::default();
1171        store
1172            .set_default_settings(
1173                r#"{
1174                    "turbo": true,
1175                    "user": {
1176                        "name": "John Doe",
1177                        "age": 30,
1178                        "staff": false
1179                    },
1180                    "key1": "x"
1181                }"#,
1182                cx,
1183            )
1184            .unwrap();
1185        store
1186            .set_user_settings(r#"{ "turbo": false }"#, cx)
1187            .unwrap();
1188        store.register_setting::<UserSettings>(cx);
1189        store.register_setting::<TurboSetting>(cx);
1190
1191        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1192        assert_eq!(
1193            store.get::<UserSettings>(None),
1194            &UserSettings {
1195                name: "John Doe".to_string(),
1196                age: 30,
1197                staff: false,
1198            }
1199        );
1200
1201        store.register_setting::<MultiKeySettings>(cx);
1202        assert_eq!(
1203            store.get::<MultiKeySettings>(None),
1204            &MultiKeySettings {
1205                key1: "x".into(),
1206                key2: String::new(),
1207            }
1208        );
1209    }
1210
1211    #[gpui::test]
1212    fn test_setting_store_update(cx: &mut AppContext) {
1213        let mut store = SettingsStore::default();
1214        store.register_setting::<MultiKeySettings>(cx);
1215        store.register_setting::<UserSettings>(cx);
1216        store.register_setting::<LanguageSettings>(cx);
1217
1218        // entries added and updated
1219        check_settings_update::<LanguageSettings>(
1220            &mut store,
1221            r#"{
1222                "languages": {
1223                    "JSON": {
1224                        "language_setting_1": true
1225                    }
1226                }
1227            }"#
1228            .unindent(),
1229            |settings| {
1230                settings
1231                    .languages
1232                    .get_mut("JSON")
1233                    .unwrap()
1234                    .language_setting_1 = Some(false);
1235                settings.languages.insert(
1236                    "Rust".into(),
1237                    LanguageSettingEntry {
1238                        language_setting_2: Some(true),
1239                        ..Default::default()
1240                    },
1241                );
1242            },
1243            r#"{
1244                "languages": {
1245                    "Rust": {
1246                        "language_setting_2": true
1247                    },
1248                    "JSON": {
1249                        "language_setting_1": false
1250                    }
1251                }
1252            }"#
1253            .unindent(),
1254            cx,
1255        );
1256
1257        // weird formatting
1258        check_settings_update::<UserSettings>(
1259            &mut store,
1260            r#"{
1261                "user":   { "age": 36, "name": "Max", "staff": true }
1262            }"#
1263            .unindent(),
1264            |settings| settings.age = Some(37),
1265            r#"{
1266                "user":   { "age": 37, "name": "Max", "staff": true }
1267            }"#
1268            .unindent(),
1269            cx,
1270        );
1271
1272        // single-line formatting, other keys
1273        check_settings_update::<MultiKeySettings>(
1274            &mut store,
1275            r#"{ "one": 1, "two": 2 }"#.unindent(),
1276            |settings| settings.key1 = Some("x".into()),
1277            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1278            cx,
1279        );
1280
1281        // empty object
1282        check_settings_update::<UserSettings>(
1283            &mut store,
1284            r#"{
1285                "user": {}
1286            }"#
1287            .unindent(),
1288            |settings| settings.age = Some(37),
1289            r#"{
1290                "user": {
1291                    "age": 37
1292                }
1293            }"#
1294            .unindent(),
1295            cx,
1296        );
1297
1298        // no content
1299        check_settings_update::<UserSettings>(
1300            &mut store,
1301            r#""#.unindent(),
1302            |settings| settings.age = Some(37),
1303            r#"{
1304                "user": {
1305                    "age": 37
1306                }
1307            }
1308            "#
1309            .unindent(),
1310            cx,
1311        );
1312
1313        check_settings_update::<UserSettings>(
1314            &mut store,
1315            r#"{
1316            }
1317            "#
1318            .unindent(),
1319            |settings| settings.age = Some(37),
1320            r#"{
1321                "user": {
1322                    "age": 37
1323                }
1324            }
1325            "#
1326            .unindent(),
1327            cx,
1328        );
1329    }
1330
1331    fn check_settings_update<T: Settings>(
1332        store: &mut SettingsStore,
1333        old_json: String,
1334        update: fn(&mut T::FileContent),
1335        expected_new_json: String,
1336        cx: &mut AppContext,
1337    ) {
1338        store.set_user_settings(&old_json, cx).ok();
1339        let edits = store.edits_for_update::<T>(&old_json, update);
1340        let mut new_json = old_json;
1341        for (range, replacement) in edits.into_iter() {
1342            new_json.replace_range(range, &replacement);
1343        }
1344        pretty_assertions::assert_eq!(new_json, expected_new_json);
1345    }
1346
1347    #[derive(Debug, PartialEq, Deserialize)]
1348    struct UserSettings {
1349        name: String,
1350        age: u32,
1351        staff: bool,
1352    }
1353
1354    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1355    struct UserSettingsJson {
1356        name: Option<String>,
1357        age: Option<u32>,
1358        staff: Option<bool>,
1359    }
1360
1361    impl Settings for UserSettings {
1362        const KEY: Option<&'static str> = Some("user");
1363        type FileContent = UserSettingsJson;
1364
1365        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1366            sources.json_merge()
1367        }
1368    }
1369
1370    #[derive(Debug, Deserialize, PartialEq)]
1371    struct TurboSetting(bool);
1372
1373    impl Settings for TurboSetting {
1374        const KEY: Option<&'static str> = Some("turbo");
1375        type FileContent = Option<bool>;
1376
1377        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1378            sources.json_merge()
1379        }
1380    }
1381
1382    #[derive(Clone, Debug, PartialEq, Deserialize)]
1383    struct MultiKeySettings {
1384        #[serde(default)]
1385        key1: String,
1386        #[serde(default)]
1387        key2: String,
1388    }
1389
1390    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1391    struct MultiKeySettingsJson {
1392        key1: Option<String>,
1393        key2: Option<String>,
1394    }
1395
1396    impl Settings for MultiKeySettings {
1397        const KEY: Option<&'static str> = None;
1398
1399        type FileContent = MultiKeySettingsJson;
1400
1401        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1402            sources.json_merge()
1403        }
1404    }
1405
1406    #[derive(Debug, Deserialize)]
1407    struct JournalSettings {
1408        pub path: String,
1409        pub hour_format: HourFormat,
1410    }
1411
1412    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1413    #[serde(rename_all = "snake_case")]
1414    enum HourFormat {
1415        Hour12,
1416        Hour24,
1417    }
1418
1419    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1420    struct JournalSettingsJson {
1421        pub path: Option<String>,
1422        pub hour_format: Option<HourFormat>,
1423    }
1424
1425    impl Settings for JournalSettings {
1426        const KEY: Option<&'static str> = Some("journal");
1427
1428        type FileContent = JournalSettingsJson;
1429
1430        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1431            sources.json_merge()
1432        }
1433    }
1434
1435    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1436    struct LanguageSettings {
1437        #[serde(default)]
1438        languages: HashMap<String, LanguageSettingEntry>,
1439    }
1440
1441    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1442    struct LanguageSettingEntry {
1443        language_setting_1: Option<bool>,
1444        language_setting_2: Option<bool>,
1445    }
1446
1447    impl Settings for LanguageSettings {
1448        const KEY: Option<&'static str> = None;
1449
1450        type FileContent = Self;
1451
1452        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1453            sources.json_merge()
1454        }
1455    }
1456}