M1.9a: engine dirs and settings backend

EngineConfig and Engine::with_config; the desktop resolves Tauri's app
config and data dirs. Settings model (appearance.theme, editor.fontSize,
ui.language) with typed validation, persistence in settings.json via
write_atomic (1 MiB cap, unknown keys kept, corrupt file backed up with a
warning notification), settings.list/get/set/reset, settingsChanged and
notification events. Property test over random settings.json content,
control-channel test for persistence and corrupt-file recovery.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-16 15:23:43 +02:00
parent 851d438e2a
commit f9357ee4b5
17 changed files with 1406 additions and 41 deletions

View file

@ -5,6 +5,7 @@ mod buffer;
mod file;
mod params;
mod project;
mod settings;
use crate::{EngineError, Registry};
@ -25,5 +26,9 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(buffer::Get))?;
registry.register(Box::new(buffer::Edit))?;
registry.register(Box::new(buffer::Close))?;
registry.register(Box::new(settings::List))?;
registry.register(Box::new(settings::Get))?;
registry.register(Box::new(settings::Set))?;
registry.register(Box::new(settings::Reset))?;
Ok(())
}

View file

@ -0,0 +1,159 @@
//! Settings commands: `settings.list`, `settings.get`, `settings.set` and
//! `settings.reset`. Changes of an effective value emit `settingsChanged`.
use serde::Deserialize;
use serde_json::{Map, Value, json};
use crate::cmd::params::parse;
use crate::settings::{self, DEFS, SetError};
use crate::{Command, CommandSpec, EngineError, Event, Outcome, State};
/// `settings.list`: describes every known setting.
pub struct List;
impl Command for List {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "settings.list",
label: "List Settings",
menu_path: None,
default_shortcut: None,
params: "none; returns [{ key, type: enum|int, default, enumValues?, min?, max?, labelKey, descriptionKey, section }]",
}
}
fn run(&self, _state: &mut State, _params: Value) -> Result<Outcome, EngineError> {
let list: Vec<_> = DEFS.iter().map(settings::Def::info).collect();
let value = serde_json::to_value(list).map_err(|e| EngineError::Internal(e.to_string()))?;
Ok(Outcome::value(value))
}
}
/// Params of `settings.get`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct GetParams {
/// Keys to read; every known key when absent.
keys: Option<Vec<String>>,
}
/// `settings.get`: effective values of known settings.
pub struct Get;
impl Command for Get {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "settings.get",
label: "Get Settings",
menu_path: None,
default_shortcut: None,
params: "{ keys?: string[] }; returns { values: { key: value } }, every setting without keys",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: GetParams = parse(id, params)?;
let keys: Vec<String> = match p.keys {
Some(keys) => keys,
None => DEFS.iter().map(|d| d.key.to_string()).collect(),
};
let mut values = Map::new();
for key in keys {
let value = state.settings.get(&key).ok_or_else(|| {
EngineError::invalid_params(id, format!("unknown setting: {key}"))
})?;
values.insert(key, value);
}
Ok(Outcome::value(json!({ "values": values })))
}
}
/// Params of `settings.set`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SetParams {
/// Setting key.
key: String,
/// New value.
value: Value,
}
/// `settings.set`: validates and stores a value.
pub struct Set;
impl Command for Set {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "settings.set",
label: "Change Setting",
menu_path: None,
default_shortcut: None,
params: "{ key, value }; returns { value }; invalid_params for an unknown key or a bad value",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: SetParams = parse(id, params)?;
let changed = state
.settings
.set(&p.key, p.value)
.map_err(|e| set_error(id, e))?;
finish(state, &p.key, changed)
}
}
/// Params of `settings.reset`.
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ResetParams {
/// Setting key.
key: String,
}
/// `settings.reset`: returns a setting to its default.
pub struct Reset;
impl Command for Reset {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "settings.reset",
label: "Reset Setting",
menu_path: None,
default_shortcut: None,
params: "{ key }; returns { value } (the default); invalid_params for an unknown key",
}
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let id = self.spec().id;
let p: ResetParams = parse(id, params)?;
let changed = state.settings.reset(&p.key).map_err(|e| set_error(id, e))?;
finish(state, &p.key, changed)
}
}
/// Maps a settings error to the command error.
fn set_error(command: &str, error: SetError) -> EngineError {
match error {
SetError::Invalid(message) => EngineError::invalid_params(command, message),
SetError::Save(message) => {
EngineError::Failed(format!("cannot save the settings: {message}"))
}
}
}
/// Emits `settingsChanged` if the value changed and returns `{ value }`.
fn finish(state: &mut State, key: &str, changed: bool) -> Result<Outcome, EngineError> {
if changed {
state.emit(Event::SettingsChanged {
keys: vec![key.to_string()],
});
}
let value = state
.settings
.get(key)
.ok_or_else(|| EngineError::Internal(format!("setting vanished: {key}")))?;
Ok(Outcome::value(json!({ "value": value })))
}

View file

@ -1,9 +1,24 @@
//! The engine: registry plus state, and the one entry point that runs
//! commands.
use std::path::PathBuf;
use serde_json::Value;
use crate::{Command, CommandInfo, EngineError, Outcome, Registry, State, cmd, guard};
use crate::settings::Settings;
use crate::{
Command, CommandInfo, EngineError, NotificationLevel, Outcome, Registry, State, cmd, guard,
};
/// Where an engine stores its files. The desktop passes Tauri's app config
/// and app data directories; tests pass temp directories.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EngineConfig {
/// User configuration: `settings.json`.
pub config_dir: PathBuf,
/// Application data, such as the crash-recovery journal.
pub data_dir: PathBuf,
}
/// The command registry together with the workspace state.
///
@ -18,7 +33,33 @@ pub struct Engine {
}
impl Engine {
/// An engine with the built-in commands.
/// An engine with the built-in commands that stores its files in
/// `config`'s directories, and loads the settings. A missing settings
/// file gives the defaults. A corrupt or unreadable one never fails
/// construction: the defaults are used and a warning
/// [`crate::Event::Notification`] is queued; hosts take it with
/// [`Engine::take_events`].
///
/// # Errors
/// Returns [`EngineError::Internal`] if two built-in commands share an id.
pub fn with_config(config: EngineConfig) -> Result<Self, EngineError> {
let mut engine = Self::new()?;
let (settings, problem) = Settings::load(&config.config_dir);
engine.state.settings = settings;
engine.state.config = Some(config);
if let Some(problem) = problem {
engine.state.notify(
NotificationLevel::Warning,
Some(problem.message_key()),
Some(problem.message()),
Some(problem.params()),
);
}
Ok(engine)
}
/// An engine with the built-in commands and no persistence: settings
/// live in memory only. For tests and the control-channel test backend.
///
/// # Errors
/// Returns [`EngineError::Internal`] if two built-in commands share an id.
@ -242,6 +283,10 @@ mod tests {
"project.close",
"project.open",
"project.openDialog",
"settings.get",
"settings.list",
"settings.reset",
"settings.set",
"test.disabled",
]
);

View file

@ -11,6 +11,7 @@
//! Paths are project-relative with `/` separators, the root is `""`.
use serde::Serialize;
use serde_json::{Map, Value};
/// A state change.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
@ -76,13 +77,48 @@ pub enum Event {
/// Why.
message: String,
},
/// The effective value of settings changed; refetch them with
/// `settings.get`.
SettingsChanged {
/// The changed keys.
keys: Vec<String>,
},
/// A message for the user, shown as a toast.
Notification {
/// Unique id of this notification, for dismissing it.
id: String,
/// Severity.
level: NotificationLevel,
/// Message-catalog key of the text.
#[serde(skip_serializing_if = "Option::is_none")]
message_key: Option<String>,
/// English text, for messages without a catalog key and as a
/// fallback.
#[serde(skip_serializing_if = "Option::is_none")]
message: Option<String>,
/// Interpolation params for the catalog text.
#[serde(skip_serializing_if = "Option::is_none")]
params: Option<Map<String, Value>>,
},
}
/// Severity of an [`Event::Notification`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum NotificationLevel {
/// Information; dismissed automatically.
Info,
/// Something went wrong but Lutra kept working.
Warning,
/// An action failed.
Error,
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::Event;
use super::{Event, NotificationLevel};
#[test]
fn serialises_with_kind_and_camel_case_fields() {
@ -100,4 +136,34 @@ mod tests {
json!({"kind": "projectClosed"})
);
}
#[test]
fn notification_and_settings_shapes() {
let mut params = serde_json::Map::new();
params.insert("backup".into(), json!("settings.json.bad-x"));
let n = Event::Notification {
id: "n1".into(),
level: NotificationLevel::Warning,
message_key: Some("notification.settings.corrupt".into()),
message: None,
params: Some(params),
};
assert_eq!(
serde_json::to_value(n).unwrap(),
json!({
"kind": "notification",
"id": "n1",
"level": "warning",
"messageKey": "notification.settings.corrupt",
"params": {"backup": "settings.json.bad-x"},
})
);
assert_eq!(
serde_json::to_value(Event::SettingsChanged {
keys: vec!["editor.fontSize".into()]
})
.unwrap(),
json!({"kind": "settingsChanged", "keys": ["editor.fontSize"]})
);
}
}

View file

@ -13,14 +13,15 @@ mod error;
mod event;
pub mod guard;
mod registry;
pub mod settings;
mod state;
pub mod theme;
pub mod workspace;
pub use buffers::{BufferId, LineEndingName, OpenBuffer};
pub use command::{Command, CommandInfo, CommandSpec, Effect, Outcome};
pub use engine::Engine;
pub use engine::{Engine, EngineConfig};
pub use error::{EngineError, ErrorPayload};
pub use event::Event;
pub use event::{Event, NotificationLevel};
pub use registry::Registry;
pub use state::State;

View file

@ -0,0 +1,669 @@
//! 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,
},
}
/// The default value of a setting.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DefaultValue {
/// A string, for [`Kind::Enum`].
Str(&'static str),
/// An integer, for [`Kind::Int`].
Int(i64),
}
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),
}
}
}
/// 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
)),
},
}
}
/// 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.to_vec()), None, None),
Kind::Int { min, max } => ("int", None, Some(min), Some(max)),
};
SettingInfo {
key: self.key,
kind,
default: self.default.to_value(),
enum_values,
min,
max,
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` or `int`.
#[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<&'static str>>,
/// 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>,
/// 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::Enum(&["lutra-dark", "lutra-light", "system"]),
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: "ui.language",
kind: Kind::Enum(&["en"]),
default: DefaultValue::Str("en"),
label_key: "settings.ui.language.label",
description_key: "settings.ui.language.description",
section: "appearance",
},
];
/// 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")),
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 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", "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());
}
}

View file

@ -1,8 +1,11 @@
//! Workspace state that commands read and change.
use crate::Event;
use serde_json::{Map, Value};
use crate::buffers::Buffers;
use crate::settings::Settings;
use crate::workspace::Workspace;
use crate::{EngineConfig, Event, NotificationLevel};
/// Everything the engine knows about the running session.
#[derive(Debug, Default)]
@ -13,6 +16,13 @@ pub struct State {
pub project: Option<Workspace>,
/// Open buffers. Empty whenever no project is open.
pub buffers: Buffers,
/// Settings, saved to the config directory when the engine has one.
pub settings: Settings,
/// Where the engine stores its files; `None` for an engine without
/// persistence ([`crate::Engine::new`]).
pub config: Option<EngineConfig>,
/// Number of notifications emitted, for their ids.
notifications: u64,
/// Events queued for the host, oldest first.
events: Vec<Event>,
}
@ -23,6 +33,24 @@ impl State {
self.events.push(event);
}
/// Queues an [`Event::Notification`] with a fresh id (`n1`, `n2`…).
pub fn notify(
&mut self,
level: NotificationLevel,
message_key: Option<&str>,
message: Option<String>,
params: Option<Map<String, Value>>,
) {
self.notifications = self.notifications.saturating_add(1);
self.emit(Event::Notification {
id: format!("n{}", self.notifications),
level,
message_key: message_key.map(str::to_string),
message,
params,
});
}
/// Takes the queued events, oldest first.
pub fn take_events(&mut self) -> Vec<Event> {
std::mem::take(&mut self.events)