## 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>
144 lines
4.5 KiB
Rust
144 lines
4.5 KiB
Rust
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, sync::Arc};
|
|
|
|
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
|
pub enum VsCodeSettingsSource {
|
|
VsCode,
|
|
Cursor,
|
|
}
|
|
|
|
impl std::fmt::Display for VsCodeSettingsSource {
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
match self {
|
|
VsCodeSettingsSource::VsCode => write!(f, "VS Code"),
|
|
VsCodeSettingsSource::Cursor => write!(f, "Cursor"),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct VsCodeSettings {
|
|
pub source: VsCodeSettingsSource,
|
|
pub path: Arc<Path>,
|
|
content: Map<String, Value>,
|
|
}
|
|
|
|
impl VsCodeSettings {
|
|
#[cfg(any(test, feature = "test-support"))]
|
|
pub fn from_str(content: &str, source: VsCodeSettingsSource) -> Result<Self> {
|
|
Ok(Self {
|
|
source,
|
|
path: Path::new("/example-path/Code/User/settings.json").into(),
|
|
content: serde_json_lenient::from_str(content)?,
|
|
})
|
|
}
|
|
|
|
pub async fn load_user_settings(source: VsCodeSettingsSource, fs: Arc<dyn Fs>) -> Result<Self> {
|
|
let candidate_paths = match source {
|
|
VsCodeSettingsSource::VsCode => vscode_settings_file_paths(),
|
|
VsCodeSettingsSource::Cursor => cursor_settings_file_paths(),
|
|
};
|
|
let mut path = None;
|
|
for candidate_path in candidate_paths.iter() {
|
|
if fs.is_file(candidate_path).await {
|
|
path = Some(candidate_path.clone());
|
|
}
|
|
}
|
|
let Some(path) = path else {
|
|
return Err(anyhow!(
|
|
"No settings file found, expected to find it in one of the following paths:\n{}",
|
|
candidate_paths
|
|
.into_iter()
|
|
.map(|path| path.to_string_lossy().to_string())
|
|
.collect::<Vec<_>>()
|
|
.join("\n")
|
|
));
|
|
};
|
|
let content = fs.load(&path).await.with_context(|| {
|
|
format!(
|
|
"Error loading {} settings file from {}",
|
|
source,
|
|
path.display()
|
|
)
|
|
})?;
|
|
let content = serde_json_lenient::from_str(&content).with_context(|| {
|
|
format!(
|
|
"Error parsing {} settings file from {}",
|
|
source,
|
|
path.display()
|
|
)
|
|
})?;
|
|
Ok(Self {
|
|
source,
|
|
path: path.into(),
|
|
content,
|
|
})
|
|
}
|
|
|
|
pub fn read_value(&self, setting: &str) -> Option<&Value> {
|
|
if let Some(value) = self.content.get(setting) {
|
|
return Some(value);
|
|
}
|
|
// TODO: maybe check if it's in [platform] settings for current platform as a fallback
|
|
// TODO: deal with language specific settings
|
|
None
|
|
}
|
|
|
|
pub fn read_string(&self, setting: &str) -> Option<&str> {
|
|
self.read_value(setting).and_then(|v| v.as_str())
|
|
}
|
|
|
|
pub fn read_bool(&self, setting: &str) -> Option<bool> {
|
|
self.read_value(setting).and_then(|v| v.as_bool())
|
|
}
|
|
|
|
pub fn string_setting(&self, key: &str, setting: &mut Option<String>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_str) {
|
|
*setting = Some(s.to_owned())
|
|
}
|
|
}
|
|
|
|
pub fn bool_setting(&self, key: &str, setting: &mut Option<bool>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_bool) {
|
|
*setting = Some(s)
|
|
}
|
|
}
|
|
|
|
pub fn u32_setting(&self, key: &str, setting: &mut Option<u32>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_u64) {
|
|
*setting = Some(s as u32)
|
|
}
|
|
}
|
|
|
|
pub fn u64_setting(&self, key: &str, setting: &mut Option<u64>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_u64) {
|
|
*setting = Some(s)
|
|
}
|
|
}
|
|
|
|
pub fn usize_setting(&self, key: &str, setting: &mut Option<usize>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_u64) {
|
|
*setting = Some(s.try_into().unwrap())
|
|
}
|
|
}
|
|
|
|
pub fn f32_setting(&self, key: &str, setting: &mut Option<f32>) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_f64) {
|
|
*setting = Some(s as f32)
|
|
}
|
|
}
|
|
|
|
pub fn enum_setting<T>(
|
|
&self,
|
|
key: &str,
|
|
setting: &mut Option<T>,
|
|
f: impl FnOnce(&str) -> Option<T>,
|
|
) {
|
|
if let Some(s) = self.content.get(key).and_then(Value::as_str).and_then(f) {
|
|
*setting = Some(s)
|
|
}
|
|
}
|
|
}
|