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            if changed_local_path.is_none() {
 636                if let Some(value) = setting_value
 637                    .load_setting(
 638                        SettingsSources {
 639                            default: &default_settings,
 640                            extensions: extension_settings.as_ref(),
 641                            user: user_settings.as_ref(),
 642                            release_channel: release_channel_settings.as_ref(),
 643                            project: &[],
 644                        },
 645                        cx,
 646                    )
 647                    .log_err()
 648                {
 649                    setting_value.set_global_value(value);
 650                }
 651            }
 652
 653            // Reload the local values for the setting.
 654            paths_stack.clear();
 655            project_settings_stack.clear();
 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    lazy_static! {
 870        static ref PAIR_QUERY: tree_sitter::Query = tree_sitter::Query::new(
 871            &tree_sitter_json::language(),
 872            "(pair key: (string) @key value: (_) @value)",
 873        )
 874        .unwrap();
 875    }
 876
 877    let mut parser = tree_sitter::Parser::new();
 878    parser.set_language(&tree_sitter_json::language()).unwrap();
 879    let syntax_tree = parser.parse(text, None).unwrap();
 880
 881    let mut cursor = tree_sitter::QueryCursor::new();
 882
 883    let mut depth = 0;
 884    let mut last_value_range = 0..0;
 885    let mut first_key_start = None;
 886    let mut existing_value_range = 0..text.len();
 887    let matches = cursor.matches(&PAIR_QUERY, syntax_tree.root_node(), text.as_bytes());
 888    for mat in matches {
 889        if mat.captures.len() != 2 {
 890            continue;
 891        }
 892
 893        let key_range = mat.captures[0].node.byte_range();
 894        let value_range = mat.captures[1].node.byte_range();
 895
 896        // Don't enter sub objects until we find an exact
 897        // match for the current keypath
 898        if last_value_range.contains_inclusive(&value_range) {
 899            continue;
 900        }
 901
 902        last_value_range = value_range.clone();
 903
 904        if key_range.start > existing_value_range.end {
 905            break;
 906        }
 907
 908        first_key_start.get_or_insert(key_range.start);
 909
 910        let found_key = text
 911            .get(key_range.clone())
 912            .map(|key_text| key_text == format!("\"{}\"", key_path[depth]))
 913            .unwrap_or(false);
 914
 915        if found_key {
 916            existing_value_range = value_range;
 917            // Reset last value range when increasing in depth
 918            last_value_range = existing_value_range.start..existing_value_range.start;
 919            depth += 1;
 920
 921            if depth == key_path.len() {
 922                break;
 923            }
 924
 925            first_key_start = None;
 926        }
 927    }
 928
 929    // We found the exact key we want, insert the new value
 930    if depth == key_path.len() {
 931        let new_val = to_pretty_json(&new_value, tab_size, tab_size * depth);
 932        (existing_value_range, new_val)
 933    } else {
 934        // We have key paths, construct the sub objects
 935        let new_key = key_path[depth];
 936
 937        // We don't have the key, construct the nested objects
 938        let mut new_value = serde_json::to_value(new_value).unwrap();
 939        for key in key_path[(depth + 1)..].iter().rev() {
 940            new_value = serde_json::json!({ key.to_string(): new_value });
 941        }
 942
 943        if let Some(first_key_start) = first_key_start {
 944            let mut row = 0;
 945            let mut column = 0;
 946            for (ix, char) in text.char_indices() {
 947                if ix == first_key_start {
 948                    break;
 949                }
 950                if char == '\n' {
 951                    row += 1;
 952                    column = 0;
 953                } else {
 954                    column += char.len_utf8();
 955                }
 956            }
 957
 958            if row > 0 {
 959                // depth is 0 based, but division needs to be 1 based.
 960                let new_val = to_pretty_json(&new_value, column / (depth + 1), column);
 961                let space = ' ';
 962                let content = format!("\"{new_key}\": {new_val},\n{space:width$}", width = column);
 963                (first_key_start..first_key_start, content)
 964            } else {
 965                let new_val = serde_json::to_string(&new_value).unwrap();
 966                let mut content = format!(r#""{new_key}": {new_val},"#);
 967                content.push(' ');
 968                (first_key_start..first_key_start, content)
 969            }
 970        } else {
 971            new_value = serde_json::json!({ new_key.to_string(): new_value });
 972            let indent_prefix_len = 4 * depth;
 973            let mut new_val = to_pretty_json(&new_value, 4, indent_prefix_len);
 974            if depth == 0 {
 975                new_val.push('\n');
 976            }
 977
 978            (existing_value_range, new_val)
 979        }
 980    }
 981}
 982
 983fn to_pretty_json(value: &impl Serialize, indent_size: usize, indent_prefix_len: usize) -> String {
 984    const SPACES: [u8; 32] = [b' '; 32];
 985
 986    debug_assert!(indent_size <= SPACES.len());
 987    debug_assert!(indent_prefix_len <= SPACES.len());
 988
 989    let mut output = Vec::new();
 990    let mut ser = serde_json::Serializer::with_formatter(
 991        &mut output,
 992        serde_json::ser::PrettyFormatter::with_indent(&SPACES[0..indent_size.min(SPACES.len())]),
 993    );
 994
 995    value.serialize(&mut ser).unwrap();
 996    let text = String::from_utf8(output).unwrap();
 997
 998    let mut adjusted_text = String::new();
 999    for (i, line) in text.split('\n').enumerate() {
1000        if i > 0 {
1001            adjusted_text.push_str(str::from_utf8(&SPACES[0..indent_prefix_len]).unwrap());
1002        }
1003        adjusted_text.push_str(line);
1004        adjusted_text.push('\n');
1005    }
1006    adjusted_text.pop();
1007    adjusted_text
1008}
1009
1010pub fn parse_json_with_comments<T: DeserializeOwned>(content: &str) -> Result<T> {
1011    Ok(serde_json_lenient::from_str(content)?)
1012}
1013
1014#[cfg(test)]
1015mod tests {
1016    use super::*;
1017    use serde_derive::Deserialize;
1018    use unindent::Unindent;
1019
1020    #[gpui::test]
1021    fn test_settings_store_basic(cx: &mut AppContext) {
1022        let mut store = SettingsStore::default();
1023        store.register_setting::<UserSettings>(cx);
1024        store.register_setting::<TurboSetting>(cx);
1025        store.register_setting::<MultiKeySettings>(cx);
1026        store
1027            .set_default_settings(
1028                r#"{
1029                    "turbo": false,
1030                    "user": {
1031                        "name": "John Doe",
1032                        "age": 30,
1033                        "staff": false
1034                    }
1035                }"#,
1036                cx,
1037            )
1038            .unwrap();
1039
1040        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1041        assert_eq!(
1042            store.get::<UserSettings>(None),
1043            &UserSettings {
1044                name: "John Doe".to_string(),
1045                age: 30,
1046                staff: false,
1047            }
1048        );
1049        assert_eq!(
1050            store.get::<MultiKeySettings>(None),
1051            &MultiKeySettings {
1052                key1: String::new(),
1053                key2: String::new(),
1054            }
1055        );
1056
1057        store
1058            .set_user_settings(
1059                r#"{
1060                    "turbo": true,
1061                    "user": { "age": 31 },
1062                    "key1": "a"
1063                }"#,
1064                cx,
1065            )
1066            .unwrap();
1067
1068        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(true));
1069        assert_eq!(
1070            store.get::<UserSettings>(None),
1071            &UserSettings {
1072                name: "John Doe".to_string(),
1073                age: 31,
1074                staff: false
1075            }
1076        );
1077
1078        store
1079            .set_local_settings(
1080                1,
1081                Path::new("/root1").into(),
1082                Some(r#"{ "user": { "staff": true } }"#),
1083                cx,
1084            )
1085            .unwrap();
1086        store
1087            .set_local_settings(
1088                1,
1089                Path::new("/root1/subdir").into(),
1090                Some(r#"{ "user": { "name": "Jane Doe" } }"#),
1091                cx,
1092            )
1093            .unwrap();
1094
1095        store
1096            .set_local_settings(
1097                1,
1098                Path::new("/root2").into(),
1099                Some(r#"{ "user": { "age": 42 }, "key2": "b" }"#),
1100                cx,
1101            )
1102            .unwrap();
1103
1104        assert_eq!(
1105            store.get::<UserSettings>(Some(SettingsLocation {
1106                worktree_id: 1,
1107                path: Path::new("/root1/something"),
1108            })),
1109            &UserSettings {
1110                name: "John Doe".to_string(),
1111                age: 31,
1112                staff: true
1113            }
1114        );
1115        assert_eq!(
1116            store.get::<UserSettings>(Some(SettingsLocation {
1117                worktree_id: 1,
1118                path: Path::new("/root1/subdir/something")
1119            })),
1120            &UserSettings {
1121                name: "Jane Doe".to_string(),
1122                age: 31,
1123                staff: true
1124            }
1125        );
1126        assert_eq!(
1127            store.get::<UserSettings>(Some(SettingsLocation {
1128                worktree_id: 1,
1129                path: Path::new("/root2/something")
1130            })),
1131            &UserSettings {
1132                name: "John Doe".to_string(),
1133                age: 42,
1134                staff: false
1135            }
1136        );
1137        assert_eq!(
1138            store.get::<MultiKeySettings>(Some(SettingsLocation {
1139                worktree_id: 1,
1140                path: Path::new("/root2/something")
1141            })),
1142            &MultiKeySettings {
1143                key1: "a".to_string(),
1144                key2: "b".to_string(),
1145            }
1146        );
1147    }
1148
1149    #[gpui::test]
1150    fn test_setting_store_assign_json_before_register(cx: &mut AppContext) {
1151        let mut store = SettingsStore::default();
1152        store
1153            .set_default_settings(
1154                r#"{
1155                    "turbo": true,
1156                    "user": {
1157                        "name": "John Doe",
1158                        "age": 30,
1159                        "staff": false
1160                    },
1161                    "key1": "x"
1162                }"#,
1163                cx,
1164            )
1165            .unwrap();
1166        store
1167            .set_user_settings(r#"{ "turbo": false }"#, cx)
1168            .unwrap();
1169        store.register_setting::<UserSettings>(cx);
1170        store.register_setting::<TurboSetting>(cx);
1171
1172        assert_eq!(store.get::<TurboSetting>(None), &TurboSetting(false));
1173        assert_eq!(
1174            store.get::<UserSettings>(None),
1175            &UserSettings {
1176                name: "John Doe".to_string(),
1177                age: 30,
1178                staff: false,
1179            }
1180        );
1181
1182        store.register_setting::<MultiKeySettings>(cx);
1183        assert_eq!(
1184            store.get::<MultiKeySettings>(None),
1185            &MultiKeySettings {
1186                key1: "x".into(),
1187                key2: String::new(),
1188            }
1189        );
1190    }
1191
1192    #[gpui::test]
1193    fn test_setting_store_update(cx: &mut AppContext) {
1194        let mut store = SettingsStore::default();
1195        store.register_setting::<MultiKeySettings>(cx);
1196        store.register_setting::<UserSettings>(cx);
1197        store.register_setting::<LanguageSettings>(cx);
1198
1199        // entries added and updated
1200        check_settings_update::<LanguageSettings>(
1201            &mut store,
1202            r#"{
1203                "languages": {
1204                    "JSON": {
1205                        "language_setting_1": true
1206                    }
1207                }
1208            }"#
1209            .unindent(),
1210            |settings| {
1211                settings
1212                    .languages
1213                    .get_mut("JSON")
1214                    .unwrap()
1215                    .language_setting_1 = Some(false);
1216                settings.languages.insert(
1217                    "Rust".into(),
1218                    LanguageSettingEntry {
1219                        language_setting_2: Some(true),
1220                        ..Default::default()
1221                    },
1222                );
1223            },
1224            r#"{
1225                "languages": {
1226                    "Rust": {
1227                        "language_setting_2": true
1228                    },
1229                    "JSON": {
1230                        "language_setting_1": false
1231                    }
1232                }
1233            }"#
1234            .unindent(),
1235            cx,
1236        );
1237
1238        // weird formatting
1239        check_settings_update::<UserSettings>(
1240            &mut store,
1241            r#"{
1242                "user":   { "age": 36, "name": "Max", "staff": true }
1243            }"#
1244            .unindent(),
1245            |settings| settings.age = Some(37),
1246            r#"{
1247                "user":   { "age": 37, "name": "Max", "staff": true }
1248            }"#
1249            .unindent(),
1250            cx,
1251        );
1252
1253        // single-line formatting, other keys
1254        check_settings_update::<MultiKeySettings>(
1255            &mut store,
1256            r#"{ "one": 1, "two": 2 }"#.unindent(),
1257            |settings| settings.key1 = Some("x".into()),
1258            r#"{ "key1": "x", "one": 1, "two": 2 }"#.unindent(),
1259            cx,
1260        );
1261
1262        // empty object
1263        check_settings_update::<UserSettings>(
1264            &mut store,
1265            r#"{
1266                "user": {}
1267            }"#
1268            .unindent(),
1269            |settings| settings.age = Some(37),
1270            r#"{
1271                "user": {
1272                    "age": 37
1273                }
1274            }"#
1275            .unindent(),
1276            cx,
1277        );
1278
1279        // no content
1280        check_settings_update::<UserSettings>(
1281            &mut store,
1282            r#""#.unindent(),
1283            |settings| settings.age = Some(37),
1284            r#"{
1285                "user": {
1286                    "age": 37
1287                }
1288            }
1289            "#
1290            .unindent(),
1291            cx,
1292        );
1293
1294        check_settings_update::<UserSettings>(
1295            &mut store,
1296            r#"{
1297            }
1298            "#
1299            .unindent(),
1300            |settings| settings.age = Some(37),
1301            r#"{
1302                "user": {
1303                    "age": 37
1304                }
1305            }
1306            "#
1307            .unindent(),
1308            cx,
1309        );
1310    }
1311
1312    fn check_settings_update<T: Settings>(
1313        store: &mut SettingsStore,
1314        old_json: String,
1315        update: fn(&mut T::FileContent),
1316        expected_new_json: String,
1317        cx: &mut AppContext,
1318    ) {
1319        store.set_user_settings(&old_json, cx).ok();
1320        let edits = store.edits_for_update::<T>(&old_json, update);
1321        let mut new_json = old_json;
1322        for (range, replacement) in edits.into_iter() {
1323            new_json.replace_range(range, &replacement);
1324        }
1325        pretty_assertions::assert_eq!(new_json, expected_new_json);
1326    }
1327
1328    #[derive(Debug, PartialEq, Deserialize)]
1329    struct UserSettings {
1330        name: String,
1331        age: u32,
1332        staff: bool,
1333    }
1334
1335    #[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
1336    struct UserSettingsJson {
1337        name: Option<String>,
1338        age: Option<u32>,
1339        staff: Option<bool>,
1340    }
1341
1342    impl Settings for UserSettings {
1343        const KEY: Option<&'static str> = Some("user");
1344        type FileContent = UserSettingsJson;
1345
1346        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1347            sources.json_merge()
1348        }
1349    }
1350
1351    #[derive(Debug, Deserialize, PartialEq)]
1352    struct TurboSetting(bool);
1353
1354    impl Settings for TurboSetting {
1355        const KEY: Option<&'static str> = Some("turbo");
1356        type FileContent = Option<bool>;
1357
1358        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1359            sources.json_merge()
1360        }
1361    }
1362
1363    #[derive(Clone, Debug, PartialEq, Deserialize)]
1364    struct MultiKeySettings {
1365        #[serde(default)]
1366        key1: String,
1367        #[serde(default)]
1368        key2: String,
1369    }
1370
1371    #[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
1372    struct MultiKeySettingsJson {
1373        key1: Option<String>,
1374        key2: Option<String>,
1375    }
1376
1377    impl Settings for MultiKeySettings {
1378        const KEY: Option<&'static str> = None;
1379
1380        type FileContent = MultiKeySettingsJson;
1381
1382        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1383            sources.json_merge()
1384        }
1385    }
1386
1387    #[derive(Debug, Deserialize)]
1388    struct JournalSettings {
1389        pub path: String,
1390        pub hour_format: HourFormat,
1391    }
1392
1393    #[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
1394    #[serde(rename_all = "snake_case")]
1395    enum HourFormat {
1396        Hour12,
1397        Hour24,
1398    }
1399
1400    #[derive(Clone, Default, Debug, Serialize, Deserialize, JsonSchema)]
1401    struct JournalSettingsJson {
1402        pub path: Option<String>,
1403        pub hour_format: Option<HourFormat>,
1404    }
1405
1406    impl Settings for JournalSettings {
1407        const KEY: Option<&'static str> = Some("journal");
1408
1409        type FileContent = JournalSettingsJson;
1410
1411        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1412            sources.json_merge()
1413        }
1414    }
1415
1416    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1417    struct LanguageSettings {
1418        #[serde(default)]
1419        languages: HashMap<String, LanguageSettingEntry>,
1420    }
1421
1422    #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
1423    struct LanguageSettingEntry {
1424        language_setting_1: Option<bool>,
1425        language_setting_2: Option<bool>,
1426    }
1427
1428    impl Settings for LanguageSettings {
1429        const KEY: Option<&'static str> = None;
1430
1431        type FileContent = Self;
1432
1433        fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
1434            sources.json_merge()
1435        }
1436    }
1437}