Keep every saved state that cannot be read, and save only states that read back

This commit is contained in:
Rebornim authored and Chris Hassebrook committed 2026-11-08 08:58:03 +00:00
1 parent a3f7fbc741
commit b2be7c32db
1 file changed
+114 -32
+114 -32
View File
@@ -8,16 +8,16 @@ use crate::UiState;
/// eframe storage key of the UI state as JSON, where there is no file
const STORAGE_KEY: &str = "ui.json";
/// Name of the UI state in eframe's storage, before the extension, for the copies of unreadable states kept there
const STORAGE_STEM: &str = "ui";
/// eframe storage key under which earlier builds kept the UI state, as RON
const RON_STORAGE_KEY: &str = "ui";
/// eframe storage key of a saved state this build could not fully read, where there is no file
const UNREADABLE_STORAGE_KEY: &str = "ui.unreadable.json";
/// Largest UI state file read; a saved state is a few kilobytes
const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;
/// Copies of unreadable saved states kept beside the file before saving stops
/// Copies of unreadable saved states kept before saving stops
const MAX_UNREADABLE_COPIES: u32 = 10;
/// The desktop's `ui.json`, set by the app before its window opens; unset, the state stays in eframe's storage
@@ -27,8 +27,9 @@ pub static FILE: OnceLock<PathBuf> = OnceLock::new();
#[derive(Default)]
pub struct UiStateStore {
file: Option<PathBuf>,
unreadable: Option<Vec<u8>>,
/// The unreadable state could not be kept, so the saved one is left as it is
/// A saved state this build could not fully read and its file extension, kept by the next save
unreadable: Option<(Vec<u8>, &'static str)>,
/// A saved state could not be read or kept, so it is left as it is
frozen: bool,
}
@@ -45,30 +46,51 @@ impl UiStateStore {
self.frozen = true;
return None;
}
Some(file) => std::fs::read(file).ok(),
Some(file) => match std::fs::read(file) {
Ok(bytes) => Some(bytes),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
Err(_) => {
self.frozen = true;
return None;
}
},
None => storage.and_then(|storage| storage.get_string(STORAGE_KEY)).map(String::into_bytes),
};
let Some(bytes) = saved else {
return storage.and_then(|storage| eframe::get_value::<UiState>(storage, RON_STORAGE_KEY));
};
let Some(bytes) = saved else { return self.load_ron(storage?) };
let ui = serde_json::from_slice::<UiState>(&bytes).ok();
if !ui.as_ref().is_some_and(fully_read) {
self.unreadable = Some(bytes);
self.unreadable = Some((bytes, "json"));
}
ui
}
/// The RON state an earlier build saved; its docks never read back, so only text that does not parse is kept
fn load_ron(&mut self, storage: &dyn eframe::Storage) -> Option<UiState> {
let text = storage.get_string(RON_STORAGE_KEY)?;
let ui = eframe::get_value::<UiState>(storage, RON_STORAGE_KEY);
if ui.is_none() {
self.unreadable = Some((text.into_bytes(), "ron"));
}
ui
}
/// Save `ui` as JSON once an unreadable saved state is kept, and drop the RON copy of earlier builds
pub fn save(&mut self, ui: &UiState, storage: &mut dyn eframe::Storage) {
if let Some(bytes) = self.unreadable.take() {
self.frozen = !self.keep_unreadable(&bytes, storage);
if let Some((bytes, extension)) = self.unreadable.take() {
self.frozen = !self.keep_unreadable(&bytes, extension, storage);
}
if self.frozen {
return;
}
let Ok(json) = serde_json::to_string_pretty(ui) else { return };
// JSON writes a non-finite number as null, which would not read back
if serde_json::from_str::<UiState>(&json).is_err() {
log::warn!("the UI state was not saved: it would not read back");
return;
}
let saved = match &self.file {
Some(file) => write_file(file, json.as_bytes()),
None => {
@@ -81,12 +103,15 @@ impl UiStateStore {
}
}
/// Keep a saved state this build could not fully read, beside the file or under its own storage key
fn keep_unreadable(&self, bytes: &[u8], storage: &mut dyn eframe::Storage) -> bool {
/// Keep a saved state this build could not fully read under the first free copy name, beside the file or in storage
fn keep_unreadable(&self, bytes: &[u8], extension: &str, storage: &mut dyn eframe::Storage) -> bool {
match &self.file {
Some(file) => keep_file_copy(file, bytes),
Some(file) => keep_file_copy(file, bytes, extension),
None => {
storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned());
let free = (1..=MAX_UNREADABLE_COPIES).map(|n| unreadable_name(STORAGE_STEM, n, extension)).find(|key| storage.get_string(key).is_none());
let Some(key) = free else { return false };
storage.set_string(&key, String::from_utf8_lossy(bytes).into_owned());
true
}
}
@@ -112,6 +137,11 @@ fn too_large(file: &Path) -> bool {
std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES)
}
/// The `n`th copy name of an unreadable state: `<stem>.unreadable.<extension>`, then `<stem>.unreadable-N.<extension>`
fn unreadable_name(stem: &str, n: u32, extension: &str) -> String {
if n == 1 { format!("{stem}.unreadable.{extension}") } else { format!("{stem}.unreadable-{n}.{extension}") }
}
#[cfg(not(target_arch = "wasm32"))]
fn write_file(file: &Path, bytes: &[u8]) -> bool {
if let Some(folder) = file.parent() {
@@ -126,14 +156,14 @@ fn write_file(_file: &Path, _bytes: &[u8]) -> bool {
false
}
/// Copy `bytes` beside `file` as the first free `<stem>.unreadable.json` or `<stem>.unreadable-N.json`
fn keep_file_copy(file: &Path, bytes: &[u8]) -> bool {
/// Copy `bytes` beside `file` under the first free copy name
fn keep_file_copy(file: &Path, bytes: &[u8], extension: &str) -> bool {
use std::io::Write as _;
let stem = file.file_stem().map(|stem| stem.to_string_lossy().into_owned()).unwrap_or_default();
for n in 1..=MAX_UNREADABLE_COPIES {
let name = if n == 1 { format!("{stem}.unreadable.json") } else { format!("{stem}.unreadable-{n}.json") };
match std::fs::OpenOptions::new().write(true).create_new(true).open(file.with_file_name(name)) {
let copy_file = file.with_file_name(unreadable_name(&stem, n, extension));
match std::fs::OpenOptions::new().write(true).create_new(true).open(copy_file) {
Ok(mut copy) => return copy.write_all(bytes).is_ok(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(_) => return false,
@@ -257,7 +287,7 @@ pub(crate) mod tests {
}
store.save(&loaded.unwrap_or_default(), &mut storage);
let copy = if n == 0 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{}.json", n + 1) };
let copy = unreadable_name("ui", n as u32 + 1, "json");
assert_eq!(std::fs::read_to_string(folder.join(copy)).unwrap(), *text);
assert_ne!(std::fs::read_to_string(&file).unwrap(), *text, "the next save replaces it once kept");
}
@@ -269,8 +299,7 @@ pub(crate) mod tests {
let folder = test_folder("frozen");
let file = folder.join("ui.json");
for n in 1..=MAX_UNREADABLE_COPIES {
let name = if n == 1 { "ui.unreadable.json".to_owned() } else { format!("ui.unreadable-{n}.json") };
std::fs::write(folder.join(name), "").unwrap();
std::fs::write(folder.join(unreadable_name("ui", n, "json")), "").unwrap();
}
std::fs::write(&file, "not json").unwrap();
@@ -298,17 +327,70 @@ pub(crate) mod tests {
}
#[test]
fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() {
fn unreadable_layouts_in_storage_are_each_kept_under_a_key_of_their_own() {
let mut storage = MemoryStorage::default();
UiStateStore::default().save(&UiState { dock: moved_panels(), ..UiState::default() }, &mut storage);
let bogus = storage.0[STORAGE_KEY].replacen("\"Assets\"", "\"Bogus\"", 1);
storage.0.insert(STORAGE_KEY.to_owned(), bogus.clone());
let saved = storage.0[STORAGE_KEY].clone();
for (n, panel) in [(1, "\"Bogus\""), (2, "\"Other\"")] {
let unreadable = saved.replacen("\"Assets\"", panel, 1);
storage.0.insert(STORAGE_KEY.to_owned(), unreadable.clone());
let mut store = UiStateStore::default();
let loaded = store.load(Some(&storage)).unwrap();
assert_eq!(loaded.dock, Dock::default());
store.save(&loaded, &mut storage);
assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, n, "json")], unreadable);
assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded);
}
assert_eq!(storage.0[&unreadable_name(STORAGE_STEM, 1, "json")], saved.replacen("\"Assets\"", "\"Bogus\"", 1), "the first copy stays");
}
#[test]
fn an_earlier_state_that_does_not_parse_is_kept_before_its_entry_goes() {
let folder = test_folder("ron");
for file in [None, Some(folder.join("ui.json"))] {
let mut storage = MemoryStorage::default();
storage.0.insert(RON_STORAGE_KEY.to_owned(), "(not ron".to_owned());
let mut store = UiStateStore::new(file.clone());
assert!(store.load(Some(&storage)).is_none());
store.save(&UiState::default(), &mut storage);
let copy = match &file {
Some(_) => std::fs::read_to_string(folder.join(unreadable_name("ui", 1, "ron"))).unwrap(),
None => storage.0[&unreadable_name(STORAGE_STEM, 1, "ron")].clone(),
};
assert_eq!(copy, "(not ron", "{file:?}");
assert!(!storage.0.contains_key(RON_STORAGE_KEY), "{file:?}");
}
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_file_that_exists_but_cannot_be_read_is_not_saved_over() {
let folder = test_folder("read-error");
let file = folder.join("ui.json");
// A folder in the file's place fails to read with an error other than not found
std::fs::create_dir_all(&file).unwrap();
let mut storage = MemoryStorage::default();
eframe::set_value(&mut storage, RON_STORAGE_KEY, &UiState::default());
let mut store = UiStateStore::new(Some(file.clone()));
assert!(store.load(Some(&storage)).is_none(), "the earlier state is not loaded in its place");
store.save(&UiState::default(), &mut storage);
assert!(file.is_dir());
assert!(storage.0.contains_key(RON_STORAGE_KEY));
std::fs::remove_dir_all(&folder).unwrap();
}
#[test]
fn a_state_that_would_not_read_back_is_not_saved() {
let mut storage = MemoryStorage::default();
let mut store = UiStateStore::default();
let loaded = store.load(Some(&storage)).unwrap();
assert_eq!(loaded.dock, Dock::default());
store.save(&loaded, &mut storage);
assert_eq!(storage.0[UNREADABLE_STORAGE_KEY], bogus);
assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded);
store.save(&UiState { split_ratio: 0.3, ..UiState::default() }, &mut storage);
let saved = storage.0[STORAGE_KEY].clone();
store.save(&UiState { uv_pan: [f32::NAN, 0.0], ..UiState::default() }, &mut storage);
assert_eq!(storage.0[STORAGE_KEY], saved);
}
}