405 lines
18 KiB
Rust
405 lines
18 KiB
Rust
//! User preferences in one file: `<app config dir>/settings.json`.
|
|
//!
|
|
//! The file holds a `schema` number, a `revision` number, and one value for each section.
|
|
//! The host does not interpret the section values. The frontend normalizes them.
|
|
//! Every write replaces the complete file atomically and sends `settings-changed` to all windows.
|
|
//! Plugin settings stay in the app data folder (see `plugins.rs`).
|
|
|
|
use std::io;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::Mutex;
|
|
use std::time::{SystemTime, UNIX_EPOCH};
|
|
|
|
use serde::Serialize;
|
|
use serde_json::{Map, Value};
|
|
use tauri::{AppHandle, Emitter, Manager};
|
|
|
|
use crate::error::{Error, Result};
|
|
use crate::fsutil;
|
|
|
|
pub const FILE_NAME: &str = "settings.json";
|
|
pub const SCHEMA: u64 = 1;
|
|
/// The known sections. `customThemesLegacy` keeps the original version 1 themes from before their conversion.
|
|
/// `features` holds the switches of the native features. `background` and `terminal` hold the settings of the Background and Terminal features.
|
|
pub const SECTIONS: [&str; 9] = ["general", "appearance", "customThemes", "customThemesLegacy", "language", "features", "background", "terminal", "projectManagement"];
|
|
/// The appearance section can hold an image data URL of up to 3,000,000 characters.
|
|
pub const MAX_FILE_BYTES: usize = 8 * 1024 * 1024;
|
|
pub const CHANGED_EVENT: &str = "settings-changed";
|
|
|
|
/// All sections, as the frontend reads them at startup.
|
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Snapshot {
|
|
/// False when no settings file exists yet. The frontend then migrates its old values.
|
|
pub exists: bool,
|
|
pub revision: u64,
|
|
pub sections: Map<String, Value>,
|
|
/// A message for the user, sent once after the host replaced a damaged file.
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub notice: Option<String>,
|
|
}
|
|
|
|
/// The payload of `settings-changed`.
|
|
#[derive(Serialize, Clone, Debug, PartialEq)]
|
|
pub struct Change {
|
|
pub section: String,
|
|
pub revision: u64,
|
|
pub value: Value,
|
|
}
|
|
|
|
struct Loaded {
|
|
document: Map<String, Value>,
|
|
exists: bool,
|
|
notice: Option<String>,
|
|
}
|
|
|
|
/// The settings file and its in-memory copy. One lock serializes all reads and writes.
|
|
pub struct Store {
|
|
path: PathBuf,
|
|
loaded: Option<Loaded>,
|
|
}
|
|
|
|
fn empty_document() -> Map<String, Value> {
|
|
let mut document = Map::new();
|
|
document.insert("schema".into(), SCHEMA.into());
|
|
document.insert("revision".into(), 0.into());
|
|
document
|
|
}
|
|
|
|
fn revision(document: &Map<String, Value>) -> u64 {
|
|
document.get("revision").and_then(Value::as_u64).unwrap_or(0)
|
|
}
|
|
|
|
fn check_section(section: &str) -> Result<()> {
|
|
if SECTIONS.contains(§ion) { Ok(()) } else { Err(Error::new(format!("Unknown settings section: {section}"))) }
|
|
}
|
|
|
|
/// Parse the file. `None` means that the file is damaged.
|
|
fn parse(bytes: &[u8]) -> Option<Map<String, Value>> {
|
|
if bytes.len() > MAX_FILE_BYTES { return None; }
|
|
let Value::Object(document) = serde_json::from_slice(bytes).ok()? else { return None };
|
|
let schema = document.get("schema").and_then(Value::as_u64)?;
|
|
if schema == 0 { return None; }
|
|
if document.get("revision").is_some_and(|value| value.as_u64().is_none()) { return None; }
|
|
Some(document)
|
|
}
|
|
|
|
fn encode(document: &Map<String, Value>) -> Result<Vec<u8>> {
|
|
let mut bytes = serde_json::to_vec_pretty(document)?;
|
|
bytes.push(b'\n');
|
|
if bytes.len() > MAX_FILE_BYTES {
|
|
return Err(Error::new("The settings are larger than 8 MiB. Remove the background image data or some custom themes, then try again."));
|
|
}
|
|
Ok(bytes)
|
|
}
|
|
|
|
fn temp_path(path: &Path) -> Result<PathBuf> {
|
|
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
|
|
Ok(parent.join(format!(".settings-{}.tmp", uuid::Uuid::new_v4())))
|
|
}
|
|
|
|
/// Move a damaged file aside to `settings.corrupt-<seconds>.json`, with a counter if that name exists.
|
|
fn keep_damaged_copy(path: &Path) -> Result<PathBuf> {
|
|
let seconds = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
|
|
let parent = path.parent().ok_or_else(|| Error::new("The settings file has no folder."))?;
|
|
for attempt in 0..100u32 {
|
|
let name = if attempt == 0 { format!("settings.corrupt-{seconds}.json") } else { format!("settings.corrupt-{seconds}-{attempt}.json") };
|
|
let copy = parent.join(name);
|
|
match fsutil::rename_no_replace(path, ©) {
|
|
Ok(()) => return Ok(copy),
|
|
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => continue,
|
|
Err(reason) => return Err(reason.into()),
|
|
}
|
|
}
|
|
Err(Error::new("Could not keep a copy of the damaged settings file."))
|
|
}
|
|
|
|
impl Store {
|
|
pub fn new(path: PathBuf) -> Self {
|
|
Self { path, loaded: None }
|
|
}
|
|
|
|
fn load(&mut self) -> Result<&mut Loaded> {
|
|
if self.loaded.is_none() {
|
|
self.loaded = Some(self.read_file()?);
|
|
}
|
|
Ok(self.loaded.as_mut().expect("loaded above"))
|
|
}
|
|
|
|
fn read_file(&self) -> Result<Loaded> {
|
|
let bytes = match fsutil::open_entry(&self.path) {
|
|
Ok(file) => fsutil::read_to_limit(file, MAX_FILE_BYTES as u64)?,
|
|
Err(reason) if reason.kind() == io::ErrorKind::NotFound => {
|
|
return Ok(Loaded { document: empty_document(), exists: false, notice: None });
|
|
}
|
|
Err(reason) => return Err(Error::new(format!("Could not read the settings file {}: {reason}", self.path.display()))),
|
|
};
|
|
if let Some(document) = bytes.as_deref().and_then(parse) {
|
|
return Ok(Loaded { document, exists: true, notice: None });
|
|
}
|
|
// Keep the damaged file for the user, then start again from the defaults.
|
|
let copy = keep_damaged_copy(&self.path)?;
|
|
let document = empty_document();
|
|
fsutil::create_file(&self.path, &temp_path(&self.path)?, &encode(&document)?)?;
|
|
let notice = format!(
|
|
"RuneStone could not read your settings file, so the default settings apply. A copy of the damaged file is at {}.",
|
|
copy.display()
|
|
);
|
|
Ok(Loaded { document, exists: true, notice: Some(notice) })
|
|
}
|
|
|
|
/// All known sections. The notice of a replaced file goes to the first reader only.
|
|
pub fn read(&mut self) -> Result<Snapshot> {
|
|
let loaded = self.load()?;
|
|
let sections = SECTIONS.iter()
|
|
.filter_map(|name| loaded.document.get(*name).map(|value| ((*name).to_owned(), value.clone())))
|
|
.collect();
|
|
Ok(Snapshot { exists: loaded.exists, revision: revision(&loaded.document), sections, notice: loaded.notice.take() })
|
|
}
|
|
|
|
/// Replace one section. `null` removes it. Unknown top-level keys stay in the file.
|
|
pub fn write(&mut self, section: &str, value: Value) -> Result<Change> {
|
|
check_section(section)?;
|
|
let path = self.path.clone();
|
|
let loaded = self.load()?;
|
|
let mut document = loaded.document.clone();
|
|
let next = revision(&document) + 1;
|
|
if value.is_null() { document.remove(section); } else { document.insert(section.into(), value.clone()); }
|
|
document.insert("revision".into(), next.into());
|
|
if document.get("schema").and_then(Value::as_u64).is_none_or(|schema| schema < SCHEMA) {
|
|
document.insert("schema".into(), SCHEMA.into());
|
|
}
|
|
let bytes = encode(&document)?;
|
|
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
|
|
fsutil::replace_file(&path, &temp_path(&path)?, &bytes)
|
|
.map_err(|reason| Error::new(format!("Could not save the settings file {}: {reason}", path.display())))?;
|
|
loaded.document = document;
|
|
loaded.exists = true;
|
|
Ok(Change { section: section.into(), revision: next, value })
|
|
}
|
|
|
|
/// Write the first file from the migrated values. When a file exists, keep it and return it unchanged.
|
|
pub fn migrate(&mut self, sections: Map<String, Value>) -> Result<Snapshot> {
|
|
for name in sections.keys() { check_section(name)?; }
|
|
let path = self.path.clone();
|
|
if self.load()?.exists { return self.read(); }
|
|
let mut document = empty_document();
|
|
document.insert("revision".into(), 1.into());
|
|
for (name, value) in sections {
|
|
if !value.is_null() { document.insert(name, value); }
|
|
}
|
|
let bytes = encode(&document)?;
|
|
if let Some(parent) = path.parent() { std::fs::create_dir_all(parent)?; }
|
|
match fsutil::create_file(&path, &temp_path(&path)?, &bytes) {
|
|
Ok(()) => {
|
|
let loaded = self.load()?;
|
|
loaded.document = document;
|
|
loaded.exists = true;
|
|
}
|
|
// Another process wrote the file first. Use its values.
|
|
Err(reason) if reason.kind() == io::ErrorKind::AlreadyExists => self.loaded = None,
|
|
Err(reason) => return Err(Error::new(format!("Could not create the settings file {}: {reason}", path.display()))),
|
|
}
|
|
self.read()
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct PreferencesState(Mutex<Option<Store>>);
|
|
|
|
fn settings_path(app: &AppHandle) -> Result<PathBuf> {
|
|
Ok(app.path().app_config_dir().map_err(|reason| Error::new(format!("app config dir: {reason}")))?.join(FILE_NAME))
|
|
}
|
|
|
|
/// Run `task` with the store on a blocking thread, because it reads and writes files.
|
|
async fn with_store<T: Send + 'static>(app: &AppHandle, task: impl FnOnce(&mut Store) -> Result<T> + Send + 'static) -> Result<T> {
|
|
let app = app.clone();
|
|
tauri::async_runtime::spawn_blocking(move || {
|
|
let state = app.state::<PreferencesState>();
|
|
let mut guard = state.0.lock()?;
|
|
if guard.is_none() { *guard = Some(Store::new(settings_path(&app)?)); }
|
|
task(guard.as_mut().expect("set above"))
|
|
}).await?
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn settings_read(app: AppHandle) -> Result<Snapshot> {
|
|
with_store(&app, Store::read).await
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn settings_write(app: AppHandle, section: String, value: Value) -> Result<Change> {
|
|
let change = with_store(&app, move |store| store.write(§ion, value)).await?;
|
|
// Every window shows the same preferences, so the change goes to all of them.
|
|
let _ = app.emit(CHANGED_EVENT, &change);
|
|
Ok(change)
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub async fn settings_migrate(app: AppHandle, sections: Map<String, Value>) -> Result<Snapshot> {
|
|
with_store(&app, move |store| store.migrate(sections)).await
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use serde_json::json;
|
|
use std::fs;
|
|
|
|
fn fixture(name: &str) -> (PathBuf, PathBuf) {
|
|
let dir = std::env::temp_dir().join(format!("rs-preferences-{name}-{}", uuid::Uuid::new_v4()));
|
|
fs::create_dir(&dir).unwrap();
|
|
let path = dir.join(FILE_NAME);
|
|
(dir, path)
|
|
}
|
|
|
|
fn on_disk(path: &Path) -> Value {
|
|
serde_json::from_slice(&fs::read(path).unwrap()).unwrap()
|
|
}
|
|
|
|
fn files(dir: &Path) -> Vec<String> {
|
|
let mut names: Vec<_> = fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
|
|
names.sort();
|
|
names
|
|
}
|
|
|
|
#[test]
|
|
fn a_missing_file_reads_as_empty_and_does_not_exist() {
|
|
let (dir, path) = fixture("missing");
|
|
let snapshot = Store::new(path.clone()).read().unwrap();
|
|
assert_eq!(snapshot, Snapshot { exists: false, revision: 0, sections: Map::new(), notice: None });
|
|
assert!(!path.exists());
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn writes_replace_one_section_and_increase_the_revision() {
|
|
let (dir, path) = fixture("write");
|
|
let mut store = Store::new(path.clone());
|
|
let first = store.write("general", json!({ "autosaveSeconds": 7 })).unwrap();
|
|
assert_eq!(first, Change { section: "general".into(), revision: 1, value: json!({ "autosaveSeconds": 7 }) });
|
|
let second = store.write("language", json!("fr")).unwrap();
|
|
assert_eq!(second.revision, 2);
|
|
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 2, "general": { "autosaveSeconds": 7 }, "language": "fr" }));
|
|
// A new store reads the same values from the file.
|
|
let snapshot = Store::new(path.clone()).read().unwrap();
|
|
assert!(snapshot.exists);
|
|
assert_eq!(snapshot.revision, 2);
|
|
assert_eq!(Value::Object(snapshot.sections), json!({ "general": { "autosaveSeconds": 7 }, "language": "fr" }));
|
|
store.write("language", Value::Null).unwrap();
|
|
assert!(on_disk(&path).get("language").is_none());
|
|
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()], "No temporary files remain");
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn writes_reject_unknown_sections_and_values_above_the_limit() {
|
|
let (dir, path) = fixture("limits");
|
|
let mut store = Store::new(path.clone());
|
|
assert!(store.write("plugins", json!({})).is_err());
|
|
assert!(store.write("../general", json!({})).is_err());
|
|
// A data URL of 3,000,000 characters fits.
|
|
let image = format!("data:image/png;base64,{}", "A".repeat(3_000_000));
|
|
store.write("appearance", json!({ "newTabBackground": { "image": image } })).unwrap();
|
|
let before = fs::read(&path).unwrap();
|
|
let error = store.write("customThemes", json!(["x".repeat(MAX_FILE_BYTES)])).unwrap_err();
|
|
assert!(error.to_string().contains("8 MiB"), "{error}");
|
|
assert_eq!(fs::read(&path).unwrap(), before, "A refused write leaves the file unchanged");
|
|
assert_eq!(store.read().unwrap().revision, 1);
|
|
assert_eq!(files(&dir), vec![FILE_NAME.to_owned()]);
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn writes_keep_unknown_top_level_keys() {
|
|
let (dir, path) = fixture("unknown");
|
|
fs::write(&path, r#"{ "schema": 1, "revision": 4, "future": { "a": 1 }, "general": {} }"#).unwrap();
|
|
let mut store = Store::new(path.clone());
|
|
assert_eq!(store.read().unwrap().sections.keys().collect::<Vec<_>>(), vec!["general"]);
|
|
assert_eq!(store.write("language", json!("ja")).unwrap().revision, 5);
|
|
assert_eq!(on_disk(&path)["future"], json!({ "a": 1 }));
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn a_damaged_file_is_kept_aside_and_reported_once() {
|
|
for (name, contents) in [("syntax", "{ broken".as_bytes()), ("array", b"[1, 2]"), ("schema", br#"{ "revision": 1 }"#), ("revision", br#"{ "schema": 1, "revision": "x" }"#)] {
|
|
let (dir, path) = fixture(name);
|
|
fs::write(&path, contents).unwrap();
|
|
let mut store = Store::new(path.clone());
|
|
let snapshot = store.read().unwrap();
|
|
assert!(snapshot.exists, "{name}: no migration after a damaged file");
|
|
assert_eq!(snapshot.revision, 0);
|
|
assert!(snapshot.sections.is_empty());
|
|
let notice = snapshot.notice.expect("The first read reports the damaged file");
|
|
let copies: Vec<_> = files(&dir).into_iter().filter(|file| file.starts_with("settings.corrupt-")).collect();
|
|
assert_eq!(copies.len(), 1, "{name}");
|
|
assert!(notice.contains(&copies[0]), "{notice}");
|
|
assert_eq!(fs::read(dir.join(&copies[0])).unwrap(), contents, "{name}: the copy keeps the damaged bytes");
|
|
assert_eq!(on_disk(&path), json!({ "schema": SCHEMA, "revision": 0 }));
|
|
assert_eq!(store.read().unwrap().notice, None, "Report the damaged file once");
|
|
assert_eq!(Store::new(path.clone()).read().unwrap().notice, None, "The new file is valid");
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_file_above_the_limit_counts_as_damaged() {
|
|
let (dir, path) = fixture("large");
|
|
fs::write(&path, vec![b' '; MAX_FILE_BYTES + 1]).unwrap();
|
|
assert!(Store::new(path.clone()).read().unwrap().notice.is_some());
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn migration_writes_the_first_file_only() {
|
|
let (dir, path) = fixture("migrate");
|
|
let mut store = Store::new(path.clone());
|
|
let sections = json!({ "general": { "autosaveEnabled": false }, "language": "fr", "customThemes": [] });
|
|
let Value::Object(sections) = sections else { unreachable!() };
|
|
let snapshot = store.migrate(sections.clone()).unwrap();
|
|
assert!(snapshot.exists);
|
|
assert_eq!(snapshot.revision, 1);
|
|
assert_eq!(snapshot.sections, sections);
|
|
assert_eq!(on_disk(&path)["language"], json!("fr"));
|
|
// A second migration, for example from a second window, keeps the existing file.
|
|
store.write("language", json!("ja")).unwrap();
|
|
let mut other = Store::new(path.clone());
|
|
let again = other.migrate(Map::from_iter([("language".to_owned(), json!("en"))])).unwrap();
|
|
assert_eq!(again.sections["language"], json!("ja"));
|
|
assert_eq!(on_disk(&path)["language"], json!("ja"));
|
|
let Value::Object(unknown) = json!({ "plugins": {} }) else { unreachable!() };
|
|
assert!(Store::new(dir.join("other.json")).migrate(unknown).is_err());
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn migration_uses_a_file_that_another_writer_created_first() {
|
|
let (dir, path) = fixture("race");
|
|
let mut store = Store::new(path.clone());
|
|
assert!(!store.read().unwrap().exists);
|
|
fs::write(&path, r#"{ "schema": 1, "revision": 3, "language": "ja" }"#).unwrap();
|
|
let snapshot = store.migrate(Map::from_iter([("language".to_owned(), json!("fr"))])).unwrap();
|
|
assert_eq!(snapshot.revision, 3);
|
|
assert_eq!(snapshot.sections["language"], json!("ja"));
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn writes_create_a_missing_config_folder() {
|
|
let (dir, _) = fixture("folder");
|
|
let path = dir.join("nested").join(FILE_NAME);
|
|
Store::new(path.clone()).write("language", json!("fr")).unwrap();
|
|
assert_eq!(on_disk(&path)["language"], json!("fr"));
|
|
fs::remove_dir_all(dir).unwrap();
|
|
}
|
|
|
|
#[test]
|
|
fn the_change_event_carries_the_section_revision_and_value() {
|
|
let change = Change { section: "language".into(), revision: 9, value: json!("fr") };
|
|
assert_eq!(serde_json::to_value(&change).unwrap(), json!({ "section": "language", "revision": 9, "value": "fr" }));
|
|
let snapshot = Snapshot { exists: true, revision: 2, sections: Map::new(), notice: None };
|
|
assert_eq!(serde_json::to_value(&snapshot).unwrap(), json!({ "exists": true, "revision": 2, "sections": {} }));
|
|
}
|
|
}
|