settings ui: Start work on creating the initial structure (#36904)
## Goal This PR creates the initial settings ui structure with the primary goal of making a settings UI that is - Comprehensive: All settings are available through the UI - Correct: Easy to understand the underlying JSON file from the UI - Intuitive - Easy to implement per setting so that UI is not a hindrance to future settings changes ### Structure The overall structure is settings layer -> data layer -> ui layer. The settings layer is the pre-existing settings definitions, that implement the `Settings` trait. The data layer is constructed from settings primarily through the `SettingsUi` trait, and it's associated derive macro. The data layer tracks the grouping of the settings, the json path of the settings, and a data representation of how to render the controls for the setting in the UI, that is either a marker value for the component to use (avoiding a dependency on the `ui` crate) or a custom render function. Abstracting the data layer from the ui layer allows crates depending on `settings` to implement their own UI without having to add additional UI dependencies, thus avoiding circular dependencies. In cases where custom UI is desired, and a creating a custom render function in the same crate is infeasible due to circular dependencies, the current solution is to implement a marker for the component in the `settings` crate, and then handle the rendering of that component in `settings_ui`. ### Foundation This PR creates a macro and a trait both called `SettingsUi`. The `SettingsUi` trait is added as a new trait bound on the `Settings` trait, this allows the type system to guarantee that all settings implement UI functionality. The macro is used to derived the trait for most types, and can be modified through attributes for unique cases as well. A derive-macro is used to generate the settings UI trait impl, allowing it the UI generation to be generated from the static information in our code base (`default.json`, Struct/Enum names, field names, `serde` attributes, etc). This allows the UI to be auto-generated for the most part, and ensures consistency across the UI. #### Immediate Follow ups - Add a new `SettingsPath` trait that will be a trait bound on `SettingsUi` and `Settings` - This trait will replace the `Settings::key` value to enable `SettingsUi` to infer the json path of it's derived type - Figure out how to render `Option<T> where T: SettingsUi` correctly - Handle `serde` attributes in the `SettingsUi` proc macro to correctly get json path from a type's field and identity Release Notes: - N/A --------- Co-authored-by: Ben Kunkle <ben@zed.dev>
This commit is contained in:
co-authored by
Ben Kunkle
parent
e9252a7a74
commit
f2c3f3b168
@@ -1,13 +1,17 @@
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
use crate::{Settings, SettingsSources, VsCodeSettings};
|
||||
use crate as settings;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use settings::{Settings, SettingsSources, VsCodeSettings};
|
||||
use settings_ui_macros::SettingsUi;
|
||||
|
||||
/// Base key bindings scheme. Base keymaps can be overridden with user keymaps.
|
||||
///
|
||||
/// Default: VSCode
|
||||
#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default)]
|
||||
#[derive(
|
||||
Copy, Clone, Debug, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Default, SettingsUi,
|
||||
)]
|
||||
pub enum BaseKeymap {
|
||||
#[default]
|
||||
VSCode,
|
||||
|
||||
@@ -4,6 +4,7 @@ mod keymap_file;
|
||||
mod settings_file;
|
||||
mod settings_json;
|
||||
mod settings_store;
|
||||
mod settings_ui;
|
||||
mod vscode_import;
|
||||
|
||||
use gpui::{App, Global};
|
||||
@@ -23,6 +24,9 @@ pub use settings_store::{
|
||||
InvalidSettingsError, LocalSettingsKind, Settings, SettingsLocation, SettingsSources,
|
||||
SettingsStore,
|
||||
};
|
||||
pub use settings_ui::*;
|
||||
// Re-export the derive macro
|
||||
pub use settings_ui_macros::SettingsUi;
|
||||
pub use vscode_import::{VsCodeSettings, VsCodeSettingsSource};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
||||
@@ -87,9 +87,9 @@ pub fn update_value_in_json_text<'a>(
|
||||
}
|
||||
|
||||
/// * `replace_key` - When an exact key match according to `key_path` is found, replace the key with `replace_key` if `Some`.
|
||||
fn replace_value_in_json_text(
|
||||
pub fn replace_value_in_json_text<T: AsRef<str>>(
|
||||
text: &str,
|
||||
key_path: &[&str],
|
||||
key_path: &[T],
|
||||
tab_size: usize,
|
||||
new_value: Option<&Value>,
|
||||
replace_key: Option<&str>,
|
||||
@@ -141,7 +141,7 @@ fn replace_value_in_json_text(
|
||||
let found_key = text
|
||||
.get(key_range.clone())
|
||||
.map(|key_text| {
|
||||
depth < key_path.len() && key_text == format!("\"{}\"", key_path[depth])
|
||||
depth < key_path.len() && key_text == format!("\"{}\"", key_path[depth].as_ref())
|
||||
})
|
||||
.unwrap_or(false);
|
||||
|
||||
@@ -226,13 +226,13 @@ fn replace_value_in_json_text(
|
||||
}
|
||||
} else {
|
||||
// We have key paths, construct the sub objects
|
||||
let new_key = key_path[depth];
|
||||
let new_key = key_path[depth].as_ref();
|
||||
|
||||
// We don't have the key, construct the nested objects
|
||||
let mut new_value =
|
||||
serde_json::to_value(new_value.unwrap_or(&serde_json::Value::Null)).unwrap();
|
||||
for key in key_path[(depth + 1)..].iter().rev() {
|
||||
new_value = serde_json::json!({ key.to_string(): new_value });
|
||||
new_value = serde_json::json!({ key.as_ref().to_string(): new_value });
|
||||
}
|
||||
|
||||
if let Some(first_key_start) = first_key_start {
|
||||
@@ -465,7 +465,7 @@ pub fn append_top_level_array_value_in_json_text(
|
||||
}
|
||||
|
||||
let (mut replace_range, mut replace_value) =
|
||||
replace_value_in_json_text("", &[], tab_size, Some(new_value), None);
|
||||
replace_value_in_json_text::<&str>("", &[], tab_size, Some(new_value), None);
|
||||
|
||||
replace_range.start = close_bracket_start;
|
||||
replace_range.end = close_bracket_start;
|
||||
|
||||
@@ -7,7 +7,7 @@ use futures::{
|
||||
channel::{mpsc, oneshot},
|
||||
future::LocalBoxFuture,
|
||||
};
|
||||
use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
|
||||
use gpui::{App, AsyncApp, BorrowAppContext, Global, SharedString, Task, UpdateGlobal};
|
||||
|
||||
use paths::{EDITORCONFIG_NAME, local_settings_file_relative_path, task_file_name};
|
||||
use schemars::JsonSchema;
|
||||
@@ -31,14 +31,15 @@ use util::{
|
||||
pub type EditorconfigProperties = ec4rs::Properties;
|
||||
|
||||
use crate::{
|
||||
ActiveSettingsProfileName, ParameterizedJsonSchema, SettingsJsonSchemaParams, VsCodeSettings,
|
||||
WorktreeId, parse_json_with_comments, update_value_in_json_text,
|
||||
ActiveSettingsProfileName, ParameterizedJsonSchema, SettingsJsonSchemaParams, SettingsUiEntry,
|
||||
VsCodeSettings, WorktreeId, parse_json_with_comments, replace_value_in_json_text,
|
||||
settings_ui::SettingsUi, update_value_in_json_text,
|
||||
};
|
||||
|
||||
/// A value that can be defined as a user setting.
|
||||
///
|
||||
/// Settings can be loaded from a combination of multiple JSON files.
|
||||
pub trait Settings: 'static + Send + Sync {
|
||||
pub trait Settings: SettingsUi + 'static + Send + Sync {
|
||||
/// The name of a key within the JSON file from which this setting should
|
||||
/// be deserialized. If this is `None`, then the setting will be deserialized
|
||||
/// from the root object.
|
||||
@@ -284,6 +285,7 @@ trait AnySettingValue: 'static + Send + Sync {
|
||||
text: &mut String,
|
||||
edits: &mut Vec<(Range<usize>, String)>,
|
||||
);
|
||||
fn settings_ui_item(&self) -> SettingsUiEntry;
|
||||
}
|
||||
|
||||
struct DeserializedSetting(Box<dyn Any>);
|
||||
@@ -480,6 +482,11 @@ impl SettingsStore {
|
||||
self.raw_global_settings.as_ref()
|
||||
}
|
||||
|
||||
/// Access the raw JSON value of the default settings.
|
||||
pub fn raw_default_settings(&self) -> &Value {
|
||||
&self.raw_default_settings
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn test(cx: &mut App) -> Self {
|
||||
let mut this = Self::new(cx);
|
||||
@@ -532,49 +539,10 @@ impl SettingsStore {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn update_settings_file<T: Settings>(
|
||||
fn update_settings_file_inner(
|
||||
&self,
|
||||
fs: Arc<dyn Fs>,
|
||||
update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
|
||||
) {
|
||||
self.setting_file_updates_tx
|
||||
.unbounded_send(Box::new(move |cx: AsyncApp| {
|
||||
async move {
|
||||
let old_text = Self::load_settings(&fs).await?;
|
||||
let new_text = cx.read_global(|store: &SettingsStore, cx| {
|
||||
store.new_text_for_update::<T>(old_text, |content| update(content, cx))
|
||||
})?;
|
||||
let settings_path = paths::settings_file().as_path();
|
||||
if fs.is_file(settings_path).await {
|
||||
let resolved_path =
|
||||
fs.canonicalize(settings_path).await.with_context(|| {
|
||||
format!("Failed to canonicalize settings path {:?}", settings_path)
|
||||
})?;
|
||||
|
||||
fs.atomic_write(resolved_path.clone(), new_text)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Failed to write settings to file {:?}", resolved_path)
|
||||
})?;
|
||||
} else {
|
||||
fs.atomic_write(settings_path.to_path_buf(), new_text)
|
||||
.await
|
||||
.with_context(|| {
|
||||
format!("Failed to write settings to file {:?}", settings_path)
|
||||
})?;
|
||||
}
|
||||
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.boxed_local()
|
||||
}))
|
||||
.ok();
|
||||
}
|
||||
|
||||
pub fn import_vscode_settings(
|
||||
&self,
|
||||
fs: Arc<dyn Fs>,
|
||||
vscode_settings: VsCodeSettings,
|
||||
update: impl 'static + Send + FnOnce(String, AsyncApp) -> Result<String>,
|
||||
) -> oneshot::Receiver<Result<()>> {
|
||||
let (tx, rx) = oneshot::channel::<Result<()>>();
|
||||
self.setting_file_updates_tx
|
||||
@@ -582,9 +550,7 @@ impl SettingsStore {
|
||||
async move {
|
||||
let res = async move {
|
||||
let old_text = Self::load_settings(&fs).await?;
|
||||
let new_text = cx.read_global(|store: &SettingsStore, _cx| {
|
||||
store.get_vscode_edits(old_text, &vscode_settings)
|
||||
})?;
|
||||
let new_text = update(old_text, cx)?;
|
||||
let settings_path = paths::settings_file().as_path();
|
||||
if fs.is_file(settings_path).await {
|
||||
let resolved_path =
|
||||
@@ -607,7 +573,6 @@ impl SettingsStore {
|
||||
format!("Failed to write settings to file {:?}", settings_path)
|
||||
})?;
|
||||
}
|
||||
|
||||
anyhow::Ok(())
|
||||
}
|
||||
.await;
|
||||
@@ -622,9 +587,67 @@ impl SettingsStore {
|
||||
}
|
||||
.boxed_local()
|
||||
}))
|
||||
.ok();
|
||||
.map_err(|err| anyhow::format_err!("Failed to update settings file: {}", err))
|
||||
.log_with_level(log::Level::Warn);
|
||||
return rx;
|
||||
}
|
||||
|
||||
rx
|
||||
pub fn update_settings_file_at_path(
|
||||
&self,
|
||||
fs: Arc<dyn Fs>,
|
||||
path: &[&str],
|
||||
new_value: serde_json::Value,
|
||||
) -> oneshot::Receiver<Result<()>> {
|
||||
let key_path = path
|
||||
.into_iter()
|
||||
.cloned()
|
||||
.map(SharedString::new)
|
||||
.collect::<Vec<_>>();
|
||||
let update = move |mut old_text: String, cx: AsyncApp| {
|
||||
cx.read_global(|store: &SettingsStore, _cx| {
|
||||
// todo(settings_ui) use `update_value_in_json_text` for merging new and old objects with comment preservation, needs old value though...
|
||||
let (range, replacement) = replace_value_in_json_text(
|
||||
&old_text,
|
||||
key_path.as_slice(),
|
||||
store.json_tab_size(),
|
||||
Some(&new_value),
|
||||
None,
|
||||
);
|
||||
old_text.replace_range(range, &replacement);
|
||||
old_text
|
||||
})
|
||||
};
|
||||
self.update_settings_file_inner(fs, update)
|
||||
}
|
||||
|
||||
pub fn update_settings_file<T: Settings>(
|
||||
&self,
|
||||
fs: Arc<dyn Fs>,
|
||||
update: impl 'static + Send + FnOnce(&mut T::FileContent, &App),
|
||||
) {
|
||||
_ = self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
|
||||
cx.read_global(|store: &SettingsStore, cx| {
|
||||
store.new_text_for_update::<T>(old_text, |content| update(content, cx))
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
pub fn import_vscode_settings(
|
||||
&self,
|
||||
fs: Arc<dyn Fs>,
|
||||
vscode_settings: VsCodeSettings,
|
||||
) -> oneshot::Receiver<Result<()>> {
|
||||
self.update_settings_file_inner(fs, move |old_text: String, cx: AsyncApp| {
|
||||
cx.read_global(|store: &SettingsStore, _cx| {
|
||||
store.get_vscode_edits(old_text, &vscode_settings)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub fn settings_ui_items(&self) -> impl IntoIterator<Item = SettingsUiEntry> {
|
||||
self.setting_values
|
||||
.values()
|
||||
.map(|item| item.settings_ui_item())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1520,6 +1543,10 @@ impl<T: Settings> AnySettingValue for SettingValue<T> {
|
||||
edits,
|
||||
);
|
||||
}
|
||||
|
||||
fn settings_ui_item(&self) -> SettingsUiEntry {
|
||||
<T as SettingsUi>::settings_ui_entry()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1527,7 +1554,10 @@ mod tests {
|
||||
use crate::VsCodeSettingsSource;
|
||||
|
||||
use super::*;
|
||||
// This is so the SettingsUi macro can still work properly
|
||||
use crate as settings;
|
||||
use serde_derive::Deserialize;
|
||||
use settings_ui_macros::SettingsUi;
|
||||
use unindent::Unindent;
|
||||
|
||||
#[gpui::test]
|
||||
@@ -2070,14 +2100,14 @@ mod tests {
|
||||
pretty_assertions::assert_eq!(new, expected);
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Deserialize)]
|
||||
#[derive(Debug, PartialEq, Deserialize, SettingsUi)]
|
||||
struct UserSettings {
|
||||
name: String,
|
||||
age: u32,
|
||||
staff: bool,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(Default, Clone, Serialize, Deserialize, JsonSchema, SettingsUi)]
|
||||
struct UserSettingsContent {
|
||||
name: Option<String>,
|
||||
age: Option<u32>,
|
||||
@@ -2097,7 +2127,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, PartialEq)]
|
||||
#[derive(Debug, Deserialize, PartialEq, SettingsUi)]
|
||||
struct TurboSetting(bool);
|
||||
|
||||
impl Settings for TurboSetting {
|
||||
@@ -2111,7 +2141,7 @@ mod tests {
|
||||
fn import_from_vscode(_vscode: &VsCodeSettings, _current: &mut Self::FileContent) {}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize)]
|
||||
#[derive(Clone, Debug, PartialEq, Deserialize, SettingsUi)]
|
||||
struct MultiKeySettings {
|
||||
#[serde(default)]
|
||||
key1: String,
|
||||
@@ -2144,7 +2174,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[derive(Debug, Deserialize, SettingsUi)]
|
||||
struct JournalSettings {
|
||||
pub path: String,
|
||||
pub hour_format: HourFormat,
|
||||
@@ -2245,7 +2275,7 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema, SettingsUi)]
|
||||
struct LanguageSettings {
|
||||
#[serde(default)]
|
||||
languages: HashMap<String, LanguageSettingEntry>,
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
use anyhow::Context as _;
|
||||
use fs::Fs;
|
||||
use gpui::{AnyElement, App, AppContext as _, ReadGlobal as _, Window};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::SettingsStore;
|
||||
|
||||
pub trait SettingsUi {
|
||||
fn settings_ui_item() -> SettingsUiItem {
|
||||
SettingsUiItem::None
|
||||
}
|
||||
fn settings_ui_entry() -> SettingsUiEntry;
|
||||
}
|
||||
|
||||
pub struct SettingsUiEntry {
|
||||
// todo(settings_ui): move this back here once there isn't a None variant
|
||||
// pub path: &'static str,
|
||||
// pub title: &'static str,
|
||||
pub item: SettingsUiEntryVariant,
|
||||
}
|
||||
|
||||
pub enum SettingsUiEntryVariant {
|
||||
Group {
|
||||
path: &'static str,
|
||||
title: &'static str,
|
||||
items: Vec<SettingsUiEntry>,
|
||||
},
|
||||
Item {
|
||||
path: &'static str,
|
||||
item: SettingsUiItemSingle,
|
||||
},
|
||||
// todo(settings_ui): remove
|
||||
None,
|
||||
}
|
||||
|
||||
pub enum SettingsUiItemSingle {
|
||||
SwitchField,
|
||||
NumericStepper,
|
||||
ToggleGroup(&'static [&'static str]),
|
||||
/// This should be used when toggle group size > 6
|
||||
DropDown(&'static [&'static str]),
|
||||
Custom(Box<dyn Fn(SettingsValue<serde_json::Value>, &mut Window, &mut App) -> AnyElement>),
|
||||
}
|
||||
|
||||
pub struct SettingsValue<T> {
|
||||
pub title: &'static str,
|
||||
pub path: SmallVec<[&'static str; 1]>,
|
||||
pub value: Option<T>,
|
||||
pub default_value: T,
|
||||
}
|
||||
|
||||
impl<T> SettingsValue<T> {
|
||||
pub fn read(&self) -> &T {
|
||||
match &self.value {
|
||||
Some(value) => value,
|
||||
None => &self.default_value,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SettingsValue<serde_json::Value> {
|
||||
pub fn write_value(path: &SmallVec<[&'static str; 1]>, value: serde_json::Value, cx: &mut App) {
|
||||
let settings_store = SettingsStore::global(cx);
|
||||
let fs = <dyn Fs>::global(cx);
|
||||
|
||||
let rx = settings_store.update_settings_file_at_path(fs.clone(), path.as_slice(), value);
|
||||
let path = path.clone();
|
||||
cx.background_spawn(async move {
|
||||
rx.await?
|
||||
.with_context(|| format!("Failed to update setting at path `{:?}`", path.join(".")))
|
||||
})
|
||||
.detach_and_log_err(cx);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: serde::Serialize> SettingsValue<T> {
|
||||
pub fn write(
|
||||
path: &SmallVec<[&'static str; 1]>,
|
||||
value: T,
|
||||
cx: &mut App,
|
||||
) -> Result<(), serde_json::Error> {
|
||||
SettingsValue::write_value(path, serde_json::to_value(value)?, cx);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub enum SettingsUiItem {
|
||||
Group {
|
||||
title: &'static str,
|
||||
items: Vec<SettingsUiEntry>,
|
||||
},
|
||||
Single(SettingsUiItemSingle),
|
||||
None,
|
||||
}
|
||||
|
||||
impl SettingsUi for bool {
|
||||
fn settings_ui_item() -> SettingsUiItem {
|
||||
SettingsUiItem::Single(SettingsUiItemSingle::SwitchField)
|
||||
}
|
||||
|
||||
fn settings_ui_entry() -> SettingsUiEntry {
|
||||
SettingsUiEntry {
|
||||
item: SettingsUiEntryVariant::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SettingsUi for u64 {
|
||||
fn settings_ui_item() -> SettingsUiItem {
|
||||
SettingsUiItem::Single(SettingsUiItemSingle::NumericStepper)
|
||||
}
|
||||
|
||||
fn settings_ui_entry() -> SettingsUiEntry {
|
||||
SettingsUiEntry {
|
||||
item: SettingsUiEntryVariant::None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ use anyhow::{Context as _, Result, anyhow};
|
||||
use fs::Fs;
|
||||
use paths::{cursor_settings_file_paths, vscode_settings_file_paths};
|
||||
use serde_json::{Map, Value};
|
||||
use std::{path::Path, rc::Rc, sync::Arc};
|
||||
use std::{path::Path, sync::Arc};
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
pub enum VsCodeSettingsSource {
|
||||
@@ -21,7 +21,7 @@ impl std::fmt::Display for VsCodeSettingsSource {
|
||||
|
||||
pub struct VsCodeSettings {
|
||||
pub source: VsCodeSettingsSource,
|
||||
pub path: Rc<Path>,
|
||||
pub path: Arc<Path>,
|
||||
content: Map<String, Value>,
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user