settings_store.rs

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