Plum Night, River, Paper and Reed (designed by Amy, approved by Daniel) join the brand pair. theme.list/current/select/import, a picker with live preview (view.selectTheme) and "Import Theme…" (view.importTheme); imported themes are validated and stored in <data_dir>/themes. Editor font family and line height settings apply live. Docs: docs/themes.md. Gate: fmt, clippy and the rest pass up to cargo test, where only the unrelated lutra-terminal PTY test a_full_buffer_stops_the_shell timed out under load; to be re-run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1018 lines
36 KiB
Rust
1018 lines
36 KiB
Rust
//! Settings: the known keys with their types and defaults, typed
|
||
//! validation, and persistence in `<config_dir>/settings.json`.
|
||
//!
|
||
//! The file is a flat JSON object (`{"editor.fontSize": 16}`). It is
|
||
//! untrusted: it is read with a size cap of [`MAX_FILE_SIZE`], a value that
|
||
//! fails validation counts as unset, and keys Lutra does not know are kept
|
||
//! untouched when the file is written again. A file that cannot be parsed is
|
||
//! moved aside to `settings.json.bad-<timestamp>` and the defaults are used,
|
||
//! so a broken file never blocks startup.
|
||
|
||
use std::fs::{self, File};
|
||
use std::io::{self, Read};
|
||
use std::path::{Path, PathBuf};
|
||
use std::time::{SystemTime, UNIX_EPOCH};
|
||
|
||
use serde::Serialize;
|
||
use serde_json::{Map, Value};
|
||
|
||
/// Name of the settings file inside the config directory.
|
||
pub const FILE_NAME: &str = "settings.json";
|
||
|
||
/// Largest settings file that is read; a larger one counts as corrupt.
|
||
pub const MAX_FILE_SIZE: u64 = 1024 * 1024;
|
||
|
||
/// The type of a setting and what values it accepts.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum Kind {
|
||
/// One of a fixed list of strings.
|
||
Enum(&'static [&'static str]),
|
||
/// An integer in `min..=max`.
|
||
Int {
|
||
/// Smallest allowed value.
|
||
min: i64,
|
||
/// Largest allowed value.
|
||
max: i64,
|
||
},
|
||
/// `true` or `false`.
|
||
Bool,
|
||
/// Any string of at most `max_len` bytes without NUL.
|
||
Str {
|
||
/// Longest accepted value in bytes.
|
||
max_len: usize,
|
||
},
|
||
/// A file path, or empty for "detect it": a string checked by
|
||
/// [`check_path`], the one validator for `settings.set` and the
|
||
/// settings dialog (which shows its message).
|
||
Path {
|
||
/// Longest accepted value in bytes.
|
||
max_len: usize,
|
||
},
|
||
/// A theme id or `system`: any well-formed id
|
||
/// ([`crate::theme::valid_id`]), so an imported theme's id survives a
|
||
/// restart. `settings.set` also requires the theme to exist; listed as
|
||
/// an enum of the built-in ids and `system`, which `settings.list`
|
||
/// extends with the imported ones.
|
||
Theme,
|
||
/// A font family list for CSS, such as `"Fira Code", monospace`: at
|
||
/// most `max_len` bytes without control characters or `;{}<>\`, so it
|
||
/// cannot leave the `font-family` value. Empty means the theme's font.
|
||
FontFamily {
|
||
/// Longest accepted value in bytes.
|
||
max_len: usize,
|
||
},
|
||
}
|
||
|
||
/// Checks a path setting's text: at most `max_len` bytes, no control
|
||
/// characters (U+0000–U+001F, U+007F), not wrapped in quotes (as copied
|
||
/// from a shell or the file manager) and no spaces at either end. Values
|
||
/// are refused, never trimmed, so what is stored is what was typed.
|
||
///
|
||
/// # Errors
|
||
/// What to change, as a sentence the dialog shows under the field.
|
||
pub fn check_path(text: &str, max_len: usize) -> Result<(), String> {
|
||
if text.len() > max_len {
|
||
return Err(format!("Enter at most {max_len} bytes"));
|
||
}
|
||
if text.chars().any(|c| c < ' ' || c == '\u{7f}') {
|
||
return Err("Remove tabs, line breaks and other control characters".into());
|
||
}
|
||
let trimmed = text.trim();
|
||
let quoted = trimmed.len() >= 2
|
||
&& ['"', '\'']
|
||
.iter()
|
||
.any(|q| trimmed.starts_with(*q) && trimmed.ends_with(*q));
|
||
if quoted {
|
||
return Err("Remove the quotes around the path".into());
|
||
}
|
||
if trimmed != text {
|
||
return Err("Remove the spaces at the start or end of the path".into());
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// The default value of a setting.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub enum DefaultValue {
|
||
/// A string, for [`Kind::Enum`] and [`Kind::Str`].
|
||
Str(&'static str),
|
||
/// An integer, for [`Kind::Int`].
|
||
Int(i64),
|
||
/// A boolean, for [`Kind::Bool`].
|
||
Bool(bool),
|
||
}
|
||
|
||
impl DefaultValue {
|
||
/// The default as JSON.
|
||
pub fn to_value(self) -> Value {
|
||
match self {
|
||
Self::Str(s) => Value::from(s),
|
||
Self::Int(i) => Value::from(i),
|
||
Self::Bool(b) => Value::from(b),
|
||
}
|
||
}
|
||
}
|
||
|
||
/// A known setting.
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||
pub struct Def {
|
||
/// Dotted key, e.g. `editor.fontSize`.
|
||
pub key: &'static str,
|
||
/// Type and accepted values.
|
||
pub kind: Kind,
|
||
/// Value used while the setting is unset or its stored value is invalid.
|
||
pub default: DefaultValue,
|
||
/// Message-catalog key of the label.
|
||
pub label_key: &'static str,
|
||
/// Message-catalog key of the description.
|
||
pub description_key: &'static str,
|
||
/// Section id; the UI shows it with the catalog key
|
||
/// `settings.section.<section>`.
|
||
pub section: &'static str,
|
||
}
|
||
|
||
impl Def {
|
||
/// Whether `value` is valid for this setting.
|
||
pub fn accepts(&self, value: &Value) -> bool {
|
||
self.check(value).is_ok()
|
||
}
|
||
|
||
/// Checks `value` against the setting's type.
|
||
///
|
||
/// # Errors
|
||
/// A message saying what is wrong with the value, for `invalid_params`.
|
||
pub fn check(&self, value: &Value) -> Result<(), String> {
|
||
match self.kind {
|
||
Kind::Enum(values) => match value.as_str() {
|
||
Some(s) if values.contains(&s) => Ok(()),
|
||
_ => Err(format!(
|
||
"{} must be one of {}, got {value}",
|
||
self.key,
|
||
values.join(", ")
|
||
)),
|
||
},
|
||
Kind::Int { min, max } => match value.as_i64() {
|
||
Some(i) if (min..=max).contains(&i) => Ok(()),
|
||
_ => Err(format!(
|
||
"{} must be an integer from {min} to {max}, got {value}",
|
||
self.key
|
||
)),
|
||
},
|
||
Kind::Bool => match value {
|
||
Value::Bool(_) => Ok(()),
|
||
_ => Err(format!("{} must be true or false, got {value}", self.key)),
|
||
},
|
||
Kind::Str { max_len } => match value.as_str() {
|
||
Some(s) if s.len() <= max_len && !s.contains(char::from(0)) => Ok(()),
|
||
_ => Err(format!(
|
||
"{} must be a string of at most {max_len} bytes without NUL",
|
||
self.key
|
||
)),
|
||
},
|
||
Kind::Path { max_len } => match value.as_str() {
|
||
Some(s) => {
|
||
check_path(s, max_len).map_err(|reason| format!("{}: {reason}", self.key))
|
||
}
|
||
None => Err(format!("{} must be a path string, got {value}", self.key)),
|
||
},
|
||
Kind::Theme => match value.as_str() {
|
||
Some(s) if crate::theme::valid_id(s) => Ok(()),
|
||
_ => Err(format!(
|
||
"{} must be a theme id (lowercase letters, digits and dashes) or system, got {value}",
|
||
self.key
|
||
)),
|
||
},
|
||
Kind::FontFamily { max_len } => match value.as_str() {
|
||
Some(s)
|
||
if s.len() <= max_len
|
||
&& !s.chars().any(|c| c.is_control() || ";{}<>\\".contains(c)) =>
|
||
{
|
||
Ok(())
|
||
}
|
||
_ => Err(format!(
|
||
"{} must be a font family list of at most {max_len} bytes without control characters or ; {{ }} < > \\",
|
||
self.key
|
||
)),
|
||
},
|
||
}
|
||
}
|
||
|
||
/// The description for `settings.list`.
|
||
pub fn info(&self) -> SettingInfo {
|
||
let (kind, enum_values, min, max) = match self.kind {
|
||
Kind::Enum(values) => (
|
||
"enum",
|
||
Some(values.iter().map(|v| (*v).to_string()).collect()),
|
||
None,
|
||
None,
|
||
),
|
||
Kind::Int { min, max } => ("int", None, Some(min), Some(max)),
|
||
Kind::Bool => ("bool", None, None, None),
|
||
Kind::Str { .. } | Kind::Path { .. } | Kind::FontFamily { .. } => {
|
||
("string", None, None, None)
|
||
}
|
||
Kind::Theme => {
|
||
let mut ids: Vec<_> = crate::theme::BUILTIN
|
||
.iter()
|
||
.map(|t| t.id.to_string())
|
||
.collect();
|
||
ids.push(crate::theme::SYSTEM.to_string());
|
||
("enum", Some(ids), None, None)
|
||
}
|
||
};
|
||
SettingInfo {
|
||
key: self.key,
|
||
kind,
|
||
default: self.default.to_value(),
|
||
enum_values,
|
||
value_names: None,
|
||
min,
|
||
max,
|
||
path: matches!(self.kind, Kind::Path { .. }),
|
||
label_key: self.label_key,
|
||
description_key: self.description_key,
|
||
section: self.section,
|
||
}
|
||
}
|
||
}
|
||
|
||
/// One entry of `settings.list`.
|
||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||
#[serde(rename_all = "camelCase")]
|
||
pub struct SettingInfo {
|
||
/// Dotted key.
|
||
pub key: &'static str,
|
||
/// `enum`, `int`, `bool` or `string`.
|
||
#[serde(rename = "type")]
|
||
pub kind: &'static str,
|
||
/// Default value.
|
||
pub default: Value,
|
||
/// Accepted values of an enum.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub enum_values: Option<Vec<String>>,
|
||
/// Display names of enum values that have no catalog key, such as
|
||
/// imported themes, by value.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub value_names: Option<std::collections::BTreeMap<String, String>>,
|
||
/// Smallest value of an int.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub min: Option<i64>,
|
||
/// Largest value of an int.
|
||
#[serde(skip_serializing_if = "Option::is_none")]
|
||
pub max: Option<i64>,
|
||
/// Whether a string is a file path ([`Kind::Path`]): the dialog adds
|
||
/// "Browse…" and shows [`check_path`]'s refusals.
|
||
#[serde(skip_serializing_if = "std::ops::Not::not")]
|
||
pub path: bool,
|
||
/// Catalog key of the label.
|
||
pub label_key: &'static str,
|
||
/// Catalog key of the description.
|
||
pub description_key: &'static str,
|
||
/// Section id.
|
||
pub section: &'static str,
|
||
}
|
||
|
||
/// Every known setting, in display order.
|
||
pub const DEFS: &[Def] = &[
|
||
Def {
|
||
key: "appearance.theme",
|
||
kind: Kind::Theme,
|
||
default: DefaultValue::Str("system"),
|
||
label_key: "settings.appearance.theme.label",
|
||
description_key: "settings.appearance.theme.description",
|
||
section: "appearance",
|
||
},
|
||
Def {
|
||
key: "editor.fontSize",
|
||
kind: Kind::Int { min: 8, max: 48 },
|
||
default: DefaultValue::Int(14),
|
||
label_key: "settings.editor.fontSize.label",
|
||
description_key: "settings.editor.fontSize.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.fontFamily",
|
||
kind: Kind::FontFamily { max_len: 256 },
|
||
default: DefaultValue::Str(""),
|
||
label_key: "settings.editor.fontFamily.label",
|
||
description_key: "settings.editor.fontFamily.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.lineHeight",
|
||
kind: Kind::Int { min: 100, max: 300 },
|
||
default: DefaultValue::Int(150),
|
||
label_key: "settings.editor.lineHeight.label",
|
||
description_key: "settings.editor.lineHeight.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "ui.language",
|
||
kind: Kind::Enum(&["en"]),
|
||
default: DefaultValue::Str("en"),
|
||
label_key: "settings.ui.language.label",
|
||
description_key: "settings.ui.language.description",
|
||
section: "appearance",
|
||
},
|
||
Def {
|
||
key: "php.executable",
|
||
kind: Kind::Path { max_len: 4096 },
|
||
default: DefaultValue::Str(""),
|
||
label_key: "settings.php.executable.label",
|
||
description_key: "settings.php.executable.description",
|
||
section: "php",
|
||
},
|
||
Def {
|
||
key: "phpactor.path",
|
||
kind: Kind::Path { max_len: 4096 },
|
||
default: DefaultValue::Str(""),
|
||
label_key: "settings.phpactor.path.label",
|
||
description_key: "settings.phpactor.path.description",
|
||
section: "php",
|
||
},
|
||
Def {
|
||
key: "phpactor.autoDownload",
|
||
kind: Kind::Bool,
|
||
default: DefaultValue::Bool(true),
|
||
label_key: "settings.phpactor.autoDownload.label",
|
||
description_key: "settings.phpactor.autoDownload.description",
|
||
section: "php",
|
||
},
|
||
Def {
|
||
key: "editor.autosave.onBlur",
|
||
kind: Kind::Bool,
|
||
default: DefaultValue::Bool(true),
|
||
label_key: "settings.editor.autosave.onBlur.label",
|
||
description_key: "settings.editor.autosave.onBlur.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.autosave.onTabSwitch",
|
||
kind: Kind::Bool,
|
||
default: DefaultValue::Bool(true),
|
||
label_key: "settings.editor.autosave.onTabSwitch.label",
|
||
description_key: "settings.editor.autosave.onTabSwitch.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.autosave.idleSeconds",
|
||
kind: Kind::Int { min: 0, max: 600 },
|
||
default: DefaultValue::Int(15),
|
||
label_key: "settings.editor.autosave.idleSeconds.label",
|
||
description_key: "settings.editor.autosave.idleSeconds.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.completion.autoPopup",
|
||
kind: Kind::Bool,
|
||
default: DefaultValue::Bool(true),
|
||
label_key: "settings.editor.completion.autoPopup.label",
|
||
description_key: "settings.editor.completion.autoPopup.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.completion.delayMs",
|
||
kind: Kind::Int { min: 0, max: 2000 },
|
||
default: DefaultValue::Int(0),
|
||
label_key: "settings.editor.completion.delayMs.label",
|
||
description_key: "settings.editor.completion.delayMs.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "editor.hover.delayMs",
|
||
kind: Kind::Int {
|
||
min: 100,
|
||
max: 3000,
|
||
},
|
||
default: DefaultValue::Int(350),
|
||
label_key: "settings.editor.hover.delayMs.label",
|
||
description_key: "settings.editor.hover.delayMs.description",
|
||
section: "editor",
|
||
},
|
||
Def {
|
||
key: "git.executable",
|
||
kind: Kind::Path { max_len: 4096 },
|
||
default: DefaultValue::Str(""),
|
||
label_key: "settings.git.executable.label",
|
||
description_key: "settings.git.executable.description",
|
||
section: "git",
|
||
},
|
||
Def {
|
||
key: "git.pull.mode",
|
||
kind: Kind::Enum(&["merge", "rebase"]),
|
||
default: DefaultValue::Str("merge"),
|
||
label_key: "settings.git.pull.mode.label",
|
||
description_key: "settings.git.pull.mode.description",
|
||
section: "git",
|
||
},
|
||
];
|
||
|
||
/// Looks a known setting up by key.
|
||
pub fn def(key: &str) -> Option<&'static Def> {
|
||
DEFS.iter().find(|d| d.key == key)
|
||
}
|
||
|
||
/// Why loading the settings file did not give the stored values.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum LoadProblem {
|
||
/// The file was unreadable as settings and was moved to `backup`.
|
||
Corrupt {
|
||
/// What was wrong with it.
|
||
reason: String,
|
||
/// File name of the backup in the config directory.
|
||
backup: String,
|
||
},
|
||
/// The file was unreadable as settings and could not be moved aside;
|
||
/// it is left alone and settings are not saved this session.
|
||
CorruptNotMoved {
|
||
/// What was wrong with it.
|
||
reason: String,
|
||
/// Why it could not be moved.
|
||
error: String,
|
||
},
|
||
/// The file or the config directory could not be accessed; settings
|
||
/// are not saved this session.
|
||
Unavailable {
|
||
/// The I/O error.
|
||
error: String,
|
||
},
|
||
}
|
||
|
||
impl LoadProblem {
|
||
/// English text for logs and for notifications without a catalog entry.
|
||
pub fn message(&self) -> String {
|
||
match self {
|
||
Self::Corrupt { reason, backup } => format!(
|
||
"settings.json could not be read ({reason}); it was moved to {backup} and the defaults are used"
|
||
),
|
||
Self::CorruptNotMoved { reason, error } => format!(
|
||
"settings.json could not be read ({reason}) or moved aside ({error}); the defaults are used and changes are not saved"
|
||
),
|
||
Self::Unavailable { error } => format!(
|
||
"settings cannot be loaded ({error}); the defaults are used and changes are not saved"
|
||
),
|
||
}
|
||
}
|
||
|
||
/// Message-catalog key for the notification.
|
||
pub fn message_key(&self) -> &'static str {
|
||
match self {
|
||
Self::Corrupt { .. } => "notification.settings.corrupt",
|
||
Self::CorruptNotMoved { .. } => "notification.settings.corruptNotMoved",
|
||
Self::Unavailable { .. } => "notification.settings.unavailable",
|
||
}
|
||
}
|
||
|
||
/// Interpolation params for the catalog message.
|
||
pub fn params(&self) -> Map<String, Value> {
|
||
let mut params = Map::new();
|
||
match self {
|
||
Self::Corrupt { reason, backup } => {
|
||
params.insert("reason".into(), Value::from(reason.as_str()));
|
||
params.insert("backup".into(), Value::from(backup.as_str()));
|
||
}
|
||
Self::CorruptNotMoved { reason, error } => {
|
||
params.insert("reason".into(), Value::from(reason.as_str()));
|
||
params.insert("error".into(), Value::from(error.as_str()));
|
||
}
|
||
Self::Unavailable { error } => {
|
||
params.insert("error".into(), Value::from(error.as_str()));
|
||
}
|
||
}
|
||
params
|
||
}
|
||
}
|
||
|
||
/// The settings of the running engine.
|
||
#[derive(Debug, Clone, PartialEq, Default)]
|
||
pub struct Settings {
|
||
/// The settings file; `None` keeps settings in memory only.
|
||
file: Option<PathBuf>,
|
||
/// The stored object, unknown keys and invalid values included.
|
||
stored: Map<String, Value>,
|
||
}
|
||
|
||
impl Settings {
|
||
/// Settings kept in memory only, all at their defaults.
|
||
pub fn in_memory() -> Self {
|
||
Self::default()
|
||
}
|
||
|
||
/// Loads `<config_dir>/settings.json`, creating the directory if needed.
|
||
/// A missing file gives the defaults. Never fails: every problem is
|
||
/// returned next to settings that work (the defaults, in memory only
|
||
/// when the file cannot safely be written).
|
||
pub fn load(config_dir: &Path) -> (Self, Option<LoadProblem>) {
|
||
if let Err(e) = fs::create_dir_all(config_dir) {
|
||
return (
|
||
Self::in_memory(),
|
||
Some(LoadProblem::Unavailable {
|
||
error: format!("{}: {e}", config_dir.display()),
|
||
}),
|
||
);
|
||
}
|
||
let file = config_dir.join(FILE_NAME);
|
||
let bytes = match read_capped(&file) {
|
||
Ok(Some(bytes)) => bytes,
|
||
Ok(None) => return (Self::persistent(file, Map::new()), None),
|
||
Err(ReadError::TooLarge) => {
|
||
return Self::recover(file, format!("larger than {MAX_FILE_SIZE} bytes"));
|
||
}
|
||
Err(ReadError::Io(e)) => {
|
||
return (
|
||
Self::in_memory(),
|
||
Some(LoadProblem::Unavailable {
|
||
error: format!("{}: {e}", file.display()),
|
||
}),
|
||
);
|
||
}
|
||
};
|
||
match parse(&bytes) {
|
||
Ok(stored) => (Self::persistent(file, stored), None),
|
||
Err(reason) => Self::recover(file, reason),
|
||
}
|
||
}
|
||
|
||
/// Settings backed by `file` with the given stored object.
|
||
fn persistent(file: PathBuf, stored: Map<String, Value>) -> Self {
|
||
Self {
|
||
file: Some(file),
|
||
stored,
|
||
}
|
||
}
|
||
|
||
/// Moves a corrupt file aside and returns the defaults: persistent if
|
||
/// the move worked, in memory otherwise so the file is not overwritten.
|
||
fn recover(file: PathBuf, reason: String) -> (Self, Option<LoadProblem>) {
|
||
match backup(&file) {
|
||
Ok(backup) => (
|
||
Self::persistent(file, Map::new()),
|
||
Some(LoadProblem::Corrupt { reason, backup }),
|
||
),
|
||
Err(e) => (
|
||
Self::in_memory(),
|
||
Some(LoadProblem::CorruptNotMoved {
|
||
reason,
|
||
error: e.to_string(),
|
||
}),
|
||
),
|
||
}
|
||
}
|
||
|
||
/// The settings file, if settings are saved.
|
||
pub fn file(&self) -> Option<&Path> {
|
||
self.file.as_deref()
|
||
}
|
||
|
||
/// The effective value of a known key: the stored value if it is valid,
|
||
/// otherwise the default. `None` for an unknown key.
|
||
pub fn get(&self, key: &str) -> Option<Value> {
|
||
let def = def(key)?;
|
||
Some(
|
||
self.stored
|
||
.get(key)
|
||
.filter(|v| def.accepts(v))
|
||
.cloned()
|
||
.unwrap_or_else(|| def.default.to_value()),
|
||
)
|
||
}
|
||
|
||
/// Stores `value` for `key` and saves the file. Nothing changes if
|
||
/// validation or saving fails.
|
||
///
|
||
/// Returns whether the effective value changed.
|
||
///
|
||
/// # Errors
|
||
/// [`SetError::Invalid`] for an unknown key or a bad value,
|
||
/// [`SetError::Save`] if the file cannot be written.
|
||
pub fn set(&mut self, key: &str, value: Value) -> Result<bool, SetError> {
|
||
let def = def(key).ok_or_else(|| SetError::Invalid(format!("unknown setting: {key}")))?;
|
||
def.check(&value).map_err(SetError::Invalid)?;
|
||
let mut stored = self.stored.clone();
|
||
stored.insert(key.to_string(), value);
|
||
self.commit(key, stored)
|
||
}
|
||
|
||
/// Removes the stored value of `key`, so the default applies, and saves
|
||
/// the file. Returns whether the effective value changed.
|
||
///
|
||
/// # Errors
|
||
/// [`SetError::Invalid`] for an unknown key, [`SetError::Save`] if the
|
||
/// file cannot be written.
|
||
pub fn reset(&mut self, key: &str) -> Result<bool, SetError> {
|
||
if def(key).is_none() {
|
||
return Err(SetError::Invalid(format!("unknown setting: {key}")));
|
||
}
|
||
if !self.stored.contains_key(key) {
|
||
return Ok(false);
|
||
}
|
||
let mut stored = self.stored.clone();
|
||
stored.remove(key);
|
||
self.commit(key, stored)
|
||
}
|
||
|
||
/// Saves `stored` and makes it current; returns whether `key`'s
|
||
/// effective value changed.
|
||
fn commit(&mut self, key: &str, stored: Map<String, Value>) -> Result<bool, SetError> {
|
||
let before = self.get(key);
|
||
if let Some(file) = &self.file {
|
||
let mut text =
|
||
serde_json::to_string_pretty(&stored).map_err(|e| SetError::Save(e.to_string()))?;
|
||
text.push('\n');
|
||
lutra_vfs::write_atomic(file, text.as_bytes())
|
||
.map_err(|e| SetError::Save(e.to_string()))?;
|
||
}
|
||
self.stored = stored;
|
||
Ok(self.get(key) != before)
|
||
}
|
||
}
|
||
|
||
/// Why `set` or `reset` failed.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum SetError {
|
||
/// Unknown key or bad value.
|
||
Invalid(String),
|
||
/// The file could not be written.
|
||
Save(String),
|
||
}
|
||
|
||
/// Why reading the file failed.
|
||
enum ReadError {
|
||
/// Larger than [`MAX_FILE_SIZE`].
|
||
TooLarge,
|
||
/// Any other I/O error.
|
||
Io(io::Error),
|
||
}
|
||
|
||
/// Reads at most [`MAX_FILE_SIZE`] bytes of `file`; `None` if it does not
|
||
/// exist.
|
||
fn read_capped(file: &Path) -> Result<Option<Vec<u8>>, ReadError> {
|
||
let handle = match File::open(file) {
|
||
Ok(handle) => handle,
|
||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
|
||
Err(e) => return Err(ReadError::Io(e)),
|
||
};
|
||
let mut bytes = Vec::new();
|
||
handle
|
||
.take(MAX_FILE_SIZE.saturating_add(1))
|
||
.read_to_end(&mut bytes)
|
||
.map_err(ReadError::Io)?;
|
||
if u64::try_from(bytes.len()).unwrap_or(u64::MAX) > MAX_FILE_SIZE {
|
||
return Err(ReadError::TooLarge);
|
||
}
|
||
Ok(Some(bytes))
|
||
}
|
||
|
||
/// Parses the file content into the stored object.
|
||
///
|
||
/// # Errors
|
||
/// Why the content is not a JSON object.
|
||
fn parse(bytes: &[u8]) -> Result<Map<String, Value>, String> {
|
||
match serde_json::from_slice::<Value>(bytes) {
|
||
Ok(Value::Object(map)) => Ok(map),
|
||
Ok(_) => Err("not a JSON object".into()),
|
||
Err(e) => Err(format!("invalid JSON: {e}")),
|
||
}
|
||
}
|
||
|
||
/// Renames `file` to `settings.json.bad-<UTC timestamp>` next to it, adding
|
||
/// `-1`, `-2`… if that name is taken. Returns the new file name.
|
||
fn backup(file: &Path) -> io::Result<String> {
|
||
let stamp = timestamp(SystemTime::now());
|
||
for n in 0..100u32 {
|
||
let name = if n == 0 {
|
||
format!("{FILE_NAME}.bad-{stamp}")
|
||
} else {
|
||
format!("{FILE_NAME}.bad-{stamp}-{n}")
|
||
};
|
||
let target = file.with_file_name(&name);
|
||
if target.exists() {
|
||
continue;
|
||
}
|
||
fs::rename(file, &target)?;
|
||
return Ok(name);
|
||
}
|
||
Err(io::Error::new(
|
||
io::ErrorKind::AlreadyExists,
|
||
"too many backups with the same timestamp",
|
||
))
|
||
}
|
||
|
||
/// Formats a time as `YYYYMMDDTHHMMSSZ` in UTC; times before 1970 count as
|
||
/// 1970-01-01.
|
||
fn timestamp(time: SystemTime) -> String {
|
||
let secs = time
|
||
.duration_since(UNIX_EPOCH)
|
||
.map(|d| d.as_secs())
|
||
.unwrap_or(0);
|
||
let days = i64::try_from(secs / 86_400).unwrap_or(0);
|
||
let rem = secs % 86_400;
|
||
let (y, m, d) = civil_from_days(days);
|
||
format!(
|
||
"{y:04}{m:02}{d:02}T{:02}{:02}{:02}Z",
|
||
rem / 3600,
|
||
rem % 3600 / 60,
|
||
rem % 60
|
||
)
|
||
}
|
||
|
||
/// Converts days since 1970-01-01 to a proleptic Gregorian date
|
||
/// (H. Hinnant's `civil_from_days`).
|
||
fn civil_from_days(days: i64) -> (i64, i64, i64) {
|
||
let z = days + 719_468;
|
||
let era = z.div_euclid(146_097);
|
||
let doe = z.rem_euclid(146_097);
|
||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||
let mp = (5 * doy + 2) / 153;
|
||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||
let y = yoe + era * 400 + i64::from(m <= 2);
|
||
(y, m, d)
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use std::time::Duration;
|
||
|
||
use serde_json::json;
|
||
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn defaults_and_validation() {
|
||
let mut s = Settings::in_memory();
|
||
assert_eq!(s.get("appearance.theme"), Some(json!("system")));
|
||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
||
assert_eq!(s.get("ui.language"), Some(json!("en")));
|
||
assert_eq!(s.get("nope"), None);
|
||
assert_eq!(s.set("editor.fontSize", json!(16)), Ok(true));
|
||
assert_eq!(s.set("editor.fontSize", json!(16)), Ok(false));
|
||
for bad in [json!(7), json!(49), json!(16.5), json!("16"), json!(null)] {
|
||
assert!(matches!(
|
||
s.set("editor.fontSize", bad),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
}
|
||
assert!(matches!(
|
||
s.set("appearance.theme", json!("Dark Mode")),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
assert_eq!(s.set("appearance.theme", json!("my-import")), Ok(true));
|
||
assert_eq!(s.get("editor.fontFamily"), Some(json!("")));
|
||
assert_eq!(s.get("editor.lineHeight"), Some(json!(150)));
|
||
assert_eq!(
|
||
s.set("editor.fontFamily", json!("\"Fira Code\", monospace")),
|
||
Ok(true)
|
||
);
|
||
for bad in ["a; color: red", "x{", "</style>", "a\\b", "tab\there"] {
|
||
assert!(
|
||
matches!(
|
||
s.set("editor.fontFamily", json!(bad)),
|
||
Err(SetError::Invalid(_))
|
||
),
|
||
"{bad}"
|
||
);
|
||
}
|
||
for bad in [json!(99), json!(301), json!(1.5)] {
|
||
assert!(matches!(
|
||
s.set("editor.lineHeight", bad),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
}
|
||
assert!(matches!(s.set("x.y", json!(1)), Err(SetError::Invalid(_))));
|
||
assert_eq!(s.get("editor.fontSize"), Some(json!(16)));
|
||
assert_eq!(s.reset("editor.fontSize"), Ok(true));
|
||
assert_eq!(s.reset("editor.fontSize"), Ok(false));
|
||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
||
}
|
||
|
||
#[test]
|
||
fn path_settings_refuse_quotes_padding_and_control_characters() {
|
||
let mut s = Settings::in_memory();
|
||
for key in ["php.executable", "phpactor.path", "git.executable"] {
|
||
for good in ["", r"C:\php\php.exe", "/opt/my php/php", "'"] {
|
||
assert!(s.set(key, json!(good)).is_ok(), "{key} {good:?}");
|
||
}
|
||
for (bad, reason) in [
|
||
(" php", "spaces"),
|
||
("php ", "spaces"),
|
||
(r#""C:\Program Files\php\php.exe""#, "quotes"),
|
||
("'/opt/php'", "quotes"),
|
||
(r#" "/opt/php" "#, "quotes"),
|
||
("/opt/php\t", "control"),
|
||
("/opt/\u{7f}php", "control"),
|
||
] {
|
||
let Err(SetError::Invalid(message)) = s.set(key, json!(bad)) else {
|
||
panic!("{key} accepted {bad:?}");
|
||
};
|
||
assert!(message.starts_with(&format!("{key}: ")), "{message}");
|
||
assert!(message.contains(reason), "{message}");
|
||
}
|
||
assert!(s.set(key, json!("x".repeat(4097))).is_err());
|
||
assert!(s.set(key, json!(1)).is_err());
|
||
assert!(DEFS.iter().any(|d| d.key == key && d.info().path));
|
||
}
|
||
assert!(
|
||
!DEFS
|
||
.iter()
|
||
.any(|d| d.key == "editor.fontSize" && d.info().path)
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn a_stored_padded_path_counts_as_unset() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
fs::write(dir.path().join(FILE_NAME), r#"{"php.executable": " php"}"#).unwrap();
|
||
let (s, problem) = Settings::load(dir.path());
|
||
assert!(problem.is_none());
|
||
assert_eq!(s.get("php.executable"), Some(json!("")));
|
||
}
|
||
|
||
#[test]
|
||
fn autosave_defaults_and_validation() {
|
||
let mut s = Settings::in_memory();
|
||
assert_eq!(s.get("editor.autosave.onBlur"), Some(json!(true)));
|
||
assert_eq!(s.get("editor.autosave.onTabSwitch"), Some(json!(true)));
|
||
assert_eq!(s.get("editor.autosave.idleSeconds"), Some(json!(15)));
|
||
assert_eq!(s.set("editor.autosave.onBlur", json!(false)), Ok(true));
|
||
for bad in [json!(0), json!("false"), json!(null)] {
|
||
assert!(matches!(
|
||
s.set("editor.autosave.onTabSwitch", bad),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
}
|
||
assert_eq!(s.set("editor.autosave.idleSeconds", json!(0)), Ok(true));
|
||
assert_eq!(s.set("editor.autosave.idleSeconds", json!(600)), Ok(true));
|
||
for bad in [json!(-1), json!(601), json!(true)] {
|
||
assert!(matches!(
|
||
s.set("editor.autosave.idleSeconds", bad),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn assist_defaults_and_validation() {
|
||
let mut s = Settings::in_memory();
|
||
assert_eq!(s.get("editor.completion.autoPopup"), Some(json!(true)));
|
||
assert_eq!(s.get("editor.completion.delayMs"), Some(json!(0)));
|
||
assert_eq!(s.get("editor.hover.delayMs"), Some(json!(350)));
|
||
assert_eq!(s.set("editor.completion.autoPopup", json!(false)), Ok(true));
|
||
assert!(matches!(
|
||
s.set("editor.completion.autoPopup", json!("false")),
|
||
Err(SetError::Invalid(_))
|
||
));
|
||
for (key, min, max) in [
|
||
("editor.completion.delayMs", 0, 2000),
|
||
("editor.hover.delayMs", 100, 3000),
|
||
] {
|
||
assert!(s.set(key, json!(min)).is_ok(), "{key}");
|
||
assert_eq!(s.get(key), Some(json!(min)));
|
||
assert_eq!(s.set(key, json!(max)), Ok(true), "{key}");
|
||
for bad in [json!(min - 1), json!(max + 1), json!(500.5), json!("500")] {
|
||
assert!(
|
||
matches!(s.set(key, bad), Err(SetError::Invalid(_))),
|
||
"{key}"
|
||
);
|
||
}
|
||
let info = serde_json::to_value(def(key).unwrap().info()).unwrap();
|
||
assert_eq!(info["type"], json!("int"));
|
||
assert_eq!(
|
||
(info["min"].clone(), info["max"].clone()),
|
||
(json!(min), json!(max))
|
||
);
|
||
assert_eq!(info["section"], json!("editor"));
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn every_default_is_valid() {
|
||
for d in DEFS {
|
||
assert!(d.accepts(&d.default.to_value()), "{}", d.key);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn list_info_shape() {
|
||
let theme = serde_json::to_value(DEFS[0].info()).unwrap();
|
||
assert_eq!(
|
||
theme,
|
||
json!({
|
||
"key": "appearance.theme",
|
||
"type": "enum",
|
||
"default": "system",
|
||
"enumValues": ["lutra-dark", "lutra-light", "lutra-plum-night", "lutra-river", "lutra-paper", "lutra-reed", "system"],
|
||
"labelKey": "settings.appearance.theme.label",
|
||
"descriptionKey": "settings.appearance.theme.description",
|
||
"section": "appearance",
|
||
})
|
||
);
|
||
let size = serde_json::to_value(DEFS[1].info()).unwrap();
|
||
assert_eq!(size["min"], 8);
|
||
assert_eq!(size["max"], 48);
|
||
assert!(size.get("enumValues").is_none());
|
||
}
|
||
|
||
#[test]
|
||
fn formats_utc_timestamps() {
|
||
assert_eq!(timestamp(UNIX_EPOCH), "19700101T000000Z");
|
||
let t = UNIX_EPOCH + Duration::from_secs(1_760_554_920);
|
||
assert_eq!(timestamp(t), "20251015T190200Z");
|
||
let leap = UNIX_EPOCH + Duration::from_secs(951_782_400);
|
||
assert_eq!(timestamp(leap), "20000229T000000Z");
|
||
}
|
||
|
||
#[test]
|
||
fn keeps_unknown_keys_and_ignores_invalid_values() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let file = dir.path().join(FILE_NAME);
|
||
fs::write(
|
||
&file,
|
||
r#"{"future.key": [1, 2], "editor.fontSize": 400, "appearance.theme": "lutra-light"}"#,
|
||
)
|
||
.unwrap();
|
||
let (mut s, problem) = Settings::load(dir.path());
|
||
assert_eq!(problem, None);
|
||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
||
assert_eq!(s.get("appearance.theme"), Some(json!("lutra-light")));
|
||
assert_eq!(s.set("editor.fontSize", json!(20)), Ok(true));
|
||
let saved: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||
assert_eq!(
|
||
saved,
|
||
json!({"future.key": [1, 2], "editor.fontSize": 20, "appearance.theme": "lutra-light"})
|
||
);
|
||
}
|
||
|
||
#[test]
|
||
fn corrupt_file_is_moved_aside() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let file = dir.path().join(FILE_NAME);
|
||
fs::write(&file, "{not json").unwrap();
|
||
let (mut s, problem) = Settings::load(dir.path());
|
||
let Some(LoadProblem::Corrupt { backup, .. }) = problem else {
|
||
panic!("expected Corrupt, got {problem:?}");
|
||
};
|
||
assert!(backup.starts_with("settings.json.bad-"));
|
||
assert_eq!(
|
||
fs::read_to_string(dir.path().join(&backup)).unwrap(),
|
||
"{not json"
|
||
);
|
||
assert!(!file.exists());
|
||
assert_eq!(s.get("editor.fontSize"), Some(json!(14)));
|
||
s.set("editor.fontSize", json!(9)).unwrap();
|
||
assert!(file.exists());
|
||
}
|
||
|
||
#[test]
|
||
fn non_objects_and_huge_files_are_corrupt() {
|
||
for content in [
|
||
b"[1,2]".to_vec(),
|
||
b"\xff\xfe".to_vec(),
|
||
vec![b' '; 1024 * 1024 + 1],
|
||
] {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
fs::write(dir.path().join(FILE_NAME), &content).unwrap();
|
||
let (s, problem) = Settings::load(dir.path());
|
||
assert!(
|
||
matches!(problem, Some(LoadProblem::Corrupt { .. })),
|
||
"{problem:?}"
|
||
);
|
||
assert!(s.file().is_some());
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn second_backup_in_the_same_second_gets_a_suffix() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let file = dir.path().join(FILE_NAME);
|
||
fs::write(&file, "1").unwrap();
|
||
let first = backup(&file).unwrap();
|
||
fs::write(&file, "2").unwrap();
|
||
let second = backup(&file).unwrap();
|
||
assert_ne!(first, second);
|
||
assert!(dir.path().join(first).exists());
|
||
assert!(dir.path().join(second).exists());
|
||
}
|
||
|
||
#[test]
|
||
fn unusable_config_dir_keeps_settings_in_memory() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
let blocker = dir.path().join("file");
|
||
fs::write(&blocker, "x").unwrap();
|
||
let (mut s, problem) = Settings::load(&blocker.join("config"));
|
||
assert!(matches!(problem, Some(LoadProblem::Unavailable { .. })));
|
||
assert_eq!(s.file(), None);
|
||
assert_eq!(s.set("editor.fontSize", json!(30)), Ok(true));
|
||
}
|
||
|
||
#[test]
|
||
fn a_directory_in_place_of_the_file_is_not_touched() {
|
||
let dir = tempfile::tempdir().unwrap();
|
||
fs::create_dir(dir.path().join(FILE_NAME)).unwrap();
|
||
let (s, problem) = Settings::load(dir.path());
|
||
assert!(problem.is_some(), "{problem:?}");
|
||
assert_eq!(s.file(), None);
|
||
assert!(dir.path().join(FILE_NAME).is_dir());
|
||
}
|
||
}
|