From 0f0047ae7b4f3427b7278a7cb28fac560aa0601b Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:27:43 +0000 Subject: [PATCH 1/2] Panel layouts survive a restart The UI state was saved as RON through eframe's storage, and a dock read through a JSON value lost RON's enum variant names, so every saved layout loaded as the default. The UI state is now saved as JSON in a store of its own: ui.json beside eframe's settings on the desktop, a storage key on the web. A saved state this build cannot fully read is kept beside it before the next save, and the state earlier builds saved still loads. --- apps/texturecraft/src/main.rs | 60 +++-- crates/ui-egui/src/lib.rs | 21 +- crates/ui-egui/src/state.rs | 24 +- crates/ui-egui/src/ui_state_store.rs | 314 ++++++++++++++++++++++++++ crates/ui-egui/tests/split_divider.rs | 14 +- 5 files changed, 373 insertions(+), 60 deletions(-) create mode 100644 crates/ui-egui/src/ui_state_store.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 377b2e52..694e8826 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -11,6 +11,7 @@ mod window_frame; use texturecraft_engine::Session; use texturecraft_ui_egui::titlebar::TitleBar; +use texturecraft_ui_egui::ui_state_store; use texturecraft_ui_egui::{TextureCraftApp, UiState}; /// The app name eframe keeps the settings under (`eframe::storage_dir`). @@ -115,13 +116,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read from the saved settings before the window opens -/// (eframe hands the app its storage only afterwards). Missing or unreadable: off. -fn saved_system_title_bar(persistence_path: Option<&std::path::Path>) -> bool { - let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|d| d.join("app.ron"))); - let saved = file.and_then(|f| std::fs::read_to_string(f).ok()); - let kv = saved.and_then(|s| ron::from_str::>(&s).ok()); - kv.and_then(|kv| ron::from_str::(kv.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) +/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off +fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { + if let Some(ui) = ui_file.and_then(ui_state_store::read) { + return ui.prefs.system_title_bar; + } + + let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); + let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); + let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -170,20 +174,24 @@ fn main() { std::process::exit(2); } }; - // Errors before the window opens speak the system's language; the app then applies the saved one. + // Errors before the window opens speak the system's language; the app then applies the saved one texturecraft_ui_egui::i18n::set_language(texturecraft_ui_egui::i18n::os_language()); let prev = std::panic::take_hook(); std::panic::set_hook(Box::new(move |info| { - // A message box needs the main thread on macOS; other threads' panics are only logged. + // A message box needs the main thread on macOS; other threads' panics are only logged fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); let session = initial_session(&args); - // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS so they neither read nor - // overwrite the user's saved UI layout and settings: state goes to a throwaway folder. + // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); - let title_bar = TitleBar::decide(saved_system_title_bar(persistence_path.as_deref())); + let ui_file = + persistence_path.as_ref().map(|path| path.with_extension("json")).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("ui.json"))); + if let Some(file) = &ui_file { + let _ = ui_state_store::FILE.set(file.clone()); + } + let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -195,7 +203,7 @@ fn main() { std::process::exit(2); } let control = args.control; - // The start window offers new, open and recent projects, unless a file was given or a script drives the app. + // The start window offers new, open and recent projects, unless a file was given or a script drives the app let start = args.file.is_none() && control.is_none(); let r = eframe::run_native( APP_NAME, @@ -296,19 +304,27 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_eframes_settings_file() { - let path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); + let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; - // Written as eframe writes it: a pretty RON map of RON strings. + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); - std::fs::write(&path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&path)), on); + std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + ui.prefs.system_title_bar = !on; + std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); + assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); } - std::fs::write(&path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&path))); - std::fs::remove_file(&path).unwrap(); - assert!(!saved_system_title_bar(Some(&path))); + + std::fs::write(&json_path, "not json").unwrap(); + std::fs::write(&ron_path, "not ron").unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + std::fs::remove_file(&json_path).unwrap(); + std::fs::remove_file(&ron_path).unwrap(); + assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..2a586519 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -32,6 +32,7 @@ pub mod theme; pub mod thumbs; pub mod titlebar; pub mod toolbar; +pub mod ui_state_store; pub mod viewport; pub mod web_files; pub mod widgets; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { /// A smooth move to a saved camera in progress. camera_glide: Option, pub ui: UiState, + /// Where `ui` is saved between runs + ui_store: ui_state_store::UiStateStore, pub gpu: Option, pub control: Option>, pub toasts: Vec, @@ -132,12 +135,13 @@ pub struct TextureCraftApp { impl TextureCraftApp { pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp { theme::install(&cc.egui_ctx); - // Bakes cast their rays on a GPU device of their own (created on the first bake). + // Bakes cast their rays on a GPU device of their own (created on the first bake) #[cfg(not(target_arch = "wasm32"))] texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new())); - let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx)); - // The first run speaks the OS (or browser) language. - let ui = cc.storage.and_then(|s| eframe::get_value::(s, "ui")).unwrap_or_else(|| { + let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx)); + // The first run speaks the OS (or browser) language + let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned()); + let ui = ui_store.load(cc.storage).unwrap_or_else(|| { let mut ui = UiState::default(); ui.prefs.language = i18n::os_language().into(); ui @@ -147,6 +151,7 @@ impl TextureCraftApp { camera_glide: None, session, ui, + ui_store, gpu, control: None, toasts: Vec::new(), @@ -179,14 +184,14 @@ impl TextureCraftApp { export_templates::load_library(&mut app, cc.storage); #[cfg(not(target_arch = "wasm32"))] { - // The first window of the process fixes it; a new folder applies on restart. + // The first window of the process fixes it; a new folder applies on restart let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder)); - // An export folder still at the default follows the data folder. + // An export folder still at the default follows the data folder if app.ui.export.dir == data_folder("").join("export").display().to_string() { app.ui.export.dir = user_dir("export").display().to_string(); } let skipped = app.session.load_templates(user_dir("templates")); - app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}"))); + app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}"))); } app } @@ -477,7 +482,7 @@ impl eframe::App for TextureCraftApp { } fn save(&mut self, storage: &mut dyn eframe::Storage) { - eframe::set_value(storage, "ui", &self.ui); + self.ui_store.save(&self.ui, storage); export_templates::save_library(self, storage); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..2aaab049 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -429,35 +429,13 @@ mod tests { } } - /// The app's own settings store: eframe keeps `UiState` as RON text under a key - #[derive(Default)] - struct MemoryStorage(std::collections::HashMap); - - impl eframe::Storage for MemoryStorage { - fn get_string(&self, key: &str) -> Option { - self.0.get(key).cloned() - } - - fn set_string(&mut self, key: &str, value: String) { - self.0.insert(key.to_string(), value); - } - - fn remove_string(&mut self, key: &str) { - self.0.remove(key); - } - - fn flush(&mut self) {} - } - #[test] fn the_bake_layout_survives_a_restart_whichever_mode_was_open() { for mode in [Mode::Painting, Mode::Baking] { let mut ui = UiState { mode, ..UiState::default() }; ui.sync_mode_dock(); - let mut storage = MemoryStorage::default(); - eframe::set_value(&mut storage, "ui", &ui); - let mut restarted: UiState = eframe::get_value(&storage, "ui").unwrap(); + let mut restarted = crate::ui_state_store::tests::restart(&ui); restarted.sync_mode_dock(); let bake_dock = if mode == Mode::Baking { &restarted.dock } else { &restarted.inactive_mode_dock }; assert_eq!(*bake_dock, Dock::for_baking(), "{mode:?}"); diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs new file mode 100644 index 00000000..467dad78 --- /dev/null +++ b/crates/ui-egui/src/ui_state_store.rs @@ -0,0 +1,314 @@ +//! The UI state kept between runs as JSON: `ui.json` beside eframe's settings on the desktop, a key of eframe's storage on the web + +use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + +use crate::UiState; + +/// eframe storage key of the UI state as JSON, where there is no file +const STORAGE_KEY: &str = "ui.json"; + +/// 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 +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 +pub static FILE: OnceLock = OnceLock::new(); + +/// Where the UI state is saved, holding a saved state this build could not fully read until it is kept beside it +#[derive(Default)] +pub struct UiStateStore { + file: Option, + unreadable: Option>, + /// The unreadable state could not be kept, so the saved one is left as it is + frozen: bool, +} + +impl UiStateStore { + /// The store at `file`, or in eframe's storage without one + pub fn new(file: Option) -> Self { + UiStateStore { file, unreadable: None, frozen: false } + } + + /// The saved UI state, else the one an earlier build saved; a state not fully read is kept for the next save + pub fn load(&mut self, storage: Option<&dyn eframe::Storage>) -> Option { + let saved = match &self.file { + Some(file) if too_large(file) => { + self.frozen = true; + return None; + } + Some(file) => std::fs::read(file).ok(), + 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::(storage, RON_STORAGE_KEY)); + }; + + let ui = serde_json::from_slice::(&bytes).ok(); + if !ui.as_ref().is_some_and(fully_read) { + self.unreadable = Some(bytes); + } + 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 self.frozen { + return; + } + + let Ok(json) = serde_json::to_string_pretty(ui) else { return }; + let saved = match &self.file { + Some(file) => write_file(file, json.as_bytes()), + None => { + storage.set_string(STORAGE_KEY, json); + true + } + }; + if saved { + storage.remove_string(RON_STORAGE_KEY); + } + } + + /// 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 { + match &self.file { + Some(file) => keep_file_copy(file, bytes), + None => { + storage.set_string(UNREADABLE_STORAGE_KEY, String::from_utf8_lossy(bytes).into_owned()); + true + } + } + } +} + +/// The UI state saved in `file`, if it reads +pub fn read(file: &Path) -> Option { + if too_large(file) { + return None; + } + + serde_json::from_slice(&std::fs::read(file).ok()?).ok() +} + +/// Whether both docks were read rather than replaced by a default +fn fully_read(ui: &UiState) -> bool { + !ui.dock.replaced_unreadable() && !ui.inactive_mode_dock.replaced_unreadable() +} + +/// Whether `file` is too large to be a saved UI state, so it is neither read nor saved over +fn too_large(file: &Path) -> bool { + std::fs::metadata(file).is_ok_and(|metadata| metadata.len() > MAX_FILE_BYTES) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_file(file: &Path, bytes: &[u8]) -> bool { + if let Some(folder) = file.parent() { + let _ = std::fs::create_dir_all(folder); + } + + texturecraft_engine::formats::write_atomic(file, bytes).is_ok() +} + +#[cfg(target_arch = "wasm32")] +fn write_file(_file: &Path, _bytes: &[u8]) -> bool { + false +} + +/// Copy `bytes` beside `file` as the first free `.unreadable.json` or `.unreadable-N.json` +fn keep_file_copy(file: &Path, bytes: &[u8]) -> 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)) { + Ok(mut copy) => return copy.write_all(bytes).is_ok(), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {} + Err(_) => return false, + } + } + false +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::docking::{Dock, Panel, default_workspace, permissions}; + use craft_ui::docking::{Action, Placement}; + + /// eframe's storage held in memory + #[derive(Default)] + pub(crate) struct MemoryStorage(pub(crate) std::collections::HashMap); + + impl eframe::Storage for MemoryStorage { + fn get_string(&self, key: &str) -> Option { + self.0.get(key).cloned() + } + + fn set_string(&mut self, key: &str, value: String) { + self.0.insert(key.to_owned(), value); + } + + fn remove_string(&mut self, key: &str) { + self.0.remove(key); + } + + fn flush(&mut self) {} + } + + /// Save `ui` and load it back, as closing and reopening the app does + pub(crate) fn restart(ui: &UiState) -> UiState { + let mut storage = MemoryStorage::default(); + UiStateStore::default().save(ui, &mut storage); + UiStateStore::default().load(Some(&storage)).unwrap_or_else(|| panic!("the saved state loads: {:?}", storage.0)) + } + + /// An empty folder of its own for one test + fn test_folder(name: &str) -> PathBuf { + let folder = std::env::temp_dir().join(format!("texturecraft-ui-store-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&folder); + std::fs::create_dir_all(&folder).unwrap(); + folder + } + + /// The painting default with Layers moved into a tab beside Assets and Properties floating + fn moved_panels() -> Dock { + let mut workspace = default_workspace(); + let actions = [ + Action::Move { panel: Panel::Layers, anchor: Panel::Assets, placement: Placement::Tab { before: None } }, + Action::Float { panel: Panel::Properties, rect: [900.0, 120.0, 320.0, 400.0] }, + ]; + workspace.apply_all(actions, permissions).unwrap(); + + let dock = Dock::from_value(serde_json::to_value(&workspace).unwrap()); + assert!(!dock.replaced_unreadable(), "the moved layout is valid"); + dock + } + + #[test] + fn panel_layouts_survive_a_restart_in_the_file_and_in_storage() { + let folder = test_folder("layouts"); + for dock in [Dock::default(), moved_panels()] { + let ui = UiState { dock, split_ratio: 0.3, ..UiState::default() }; + for file in [None, Some(folder.join("ui.json"))] { + let mut storage = MemoryStorage::default(); + UiStateStore::new(file.clone()).save(&ui, &mut storage); + + let restarted = UiStateStore::new(file.clone()).load(Some(&storage)).unwrap(); + assert!(fully_read(&restarted), "{file:?}"); + assert_eq!(restarted, ui, "{file:?}"); + } + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn the_state_an_earlier_build_saved_loads_and_its_copy_goes_on_the_next_save() { + let mut storage = MemoryStorage::default(); + let earlier = UiState { split_ratio: 0.3, ..UiState::default() }; + eframe::set_value(&mut storage, RON_STORAGE_KEY, &earlier); + + let mut store = UiStateStore::default(); + let loaded = store.load(Some(&storage)).expect("the earlier state loads"); + assert_eq!(loaded.split_ratio, 0.3); + + store.save(&loaded, &mut storage); + assert!(!storage.0.contains_key(RON_STORAGE_KEY)); + assert_eq!(UiStateStore::default().load(Some(&storage)).unwrap(), loaded); + } + + #[test] + fn an_unreadable_layout_loads_the_default_and_is_kept_beside_the_file() { + let folder = test_folder("unreadable"); + let file = folder.join("ui.json"); + let ui = UiState { dock: moved_panels(), split_ratio: 0.3, ..UiState::default() }; + let mut storage = MemoryStorage::default(); + UiStateStore::new(Some(file.clone())).save(&ui, &mut storage); + let saved = std::fs::read_to_string(&file).unwrap(); + assert!(saved.contains("\"Assets\"") && saved.contains("\"version\": 2"), "{saved}"); + + let unreadable = [ + // A panel this build does not know + saved.replacen("\"Assets\"", "\"Bogus\"", 1), + // A layout from a newer format + saved.replacen("\"version\": 2", "\"version\": 99", 1), + // Not a saved state + "not json".to_owned(), + ]; + for (n, text) in unreadable.iter().enumerate() { + std::fs::write(&file, text).unwrap(); + let mut store = UiStateStore::new(Some(file.clone())); + let loaded = store.load(Some(&storage)); + if let Some(loaded) = &loaded { + assert_eq!(loaded.dock, Dock::default(), "{text}"); + assert_eq!(loaded.split_ratio, 0.3, "{text}"); + } + + 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) }; + 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"); + } + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_state_that_cannot_be_kept_is_not_saved_over() { + 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(&file, "not json").unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::read_to_string(&file).unwrap(), "not json"); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn a_file_too_large_to_read_is_not_saved_over() { + let folder = test_folder("too-large"); + let file = folder.join("ui.json"); + std::fs::write(&file, vec![b' '; MAX_FILE_BYTES as usize + 1]).unwrap(); + + let mut store = UiStateStore::new(Some(file.clone())); + let mut storage = MemoryStorage::default(); + assert!(store.load(Some(&storage)).is_none()); + store.save(&UiState::default(), &mut storage); + assert_eq!(std::fs::metadata(&file).unwrap().len(), MAX_FILE_BYTES + 1); + std::fs::remove_dir_all(&folder).unwrap(); + } + + #[test] + fn an_unreadable_layout_in_storage_is_kept_under_its_own_key() { + 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 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); + } +} diff --git a/crates/ui-egui/tests/split_divider.rs b/crates/ui-egui/tests/split_divider.rs index d5af8c8f..e0a487fc 100644 --- a/crates/ui-egui/tests/split_divider.rs +++ b/crates/ui-egui/tests/split_divider.rs @@ -5,6 +5,7 @@ use egui_kittest::Harness; use texturecraft_engine::core::Channel; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::state::UiState; +use texturecraft_ui_egui::ui_state_store::UiStateStore; /// Narrowest a split view may get, as in `viewport.rs` const MIN_VIEW_WIDTH: f32 = 16.0; @@ -144,16 +145,15 @@ fn the_divider_position_survives_a_restart_and_old_saved_states_load_centred() { let mut storage = MemoryStorage::default(); let mut ui_state = UiState::default(); ui_state.split_ratio = 0.3; - eframe::set_value(&mut storage, "ui", &ui_state); - let restored = eframe::get_value::(&storage, "ui").expect("saved state loads"); + UiStateStore::default().save(&ui_state, &mut storage); + let restored = UiStateStore::default().load(Some(&storage)).expect("saved state loads"); assert_eq!(restored.split_ratio, 0.3); // A state saved before the divider existed has no ratio - let saved = storage.0.get("ui").cloned().unwrap(); - let without_ratio = saved.replace("split_ratio:0.3,", ""); - assert_ne!(without_ratio, saved, "the saved state names the ratio: {saved}"); - storage.0.insert("ui".to_owned(), without_ratio); - let restored = eframe::get_value::(&storage, "ui").expect("an older saved state loads"); + let mut saved: serde_json::Value = serde_json::from_str(&storage.0["ui.json"]).unwrap(); + assert!(saved.as_object_mut().unwrap().remove("split_ratio").is_some(), "the saved state names the ratio: {saved}"); + storage.0.insert("ui.json".to_owned(), saved.to_string()); + let restored = UiStateStore::default().load(Some(&storage)).expect("an older saved state loads"); assert_eq!(restored.split_ratio, 0.5); } From a626af86bb7f9e3009968b3c77be0444c6d883e0 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 00:10:23 +0000 Subject: [PATCH 2/2] Keep every saved state that cannot be read, and save only states that read back --- crates/ui-egui/src/ui_state_store.rs | 146 +++++++++++++++++++++------ 1 file changed, 114 insertions(+), 32 deletions(-) diff --git a/crates/ui-egui/src/ui_state_store.rs b/crates/ui-egui/src/ui_state_store.rs index 467dad78..4535817d 100644 --- a/crates/ui-egui/src/ui_state_store.rs +++ b/crates/ui-egui/src/ui_state_store.rs @@ -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 = OnceLock::new(); #[derive(Default)] pub struct UiStateStore { file: Option, - unreadable: Option>, - /// 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, &'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::(storage, RON_STORAGE_KEY)); - }; + let Some(bytes) = saved else { return self.load_ron(storage?) }; let ui = serde_json::from_slice::(&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 { + let text = storage.get_string(RON_STORAGE_KEY)?; + let ui = eframe::get_value::(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::(&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: `.unreadable.`, then `.unreadable-N.` +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 `.unreadable.json` or `.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); } }