PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Recovered documents keep their recovery data until saved or closed (#444) (#549)
BFlatbd1322a5e467
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rsindex a3ab7a503..009622921 100644--- a/apps/photocraft/src/services.rs+++ b/apps/photocraft/src/services.rs@@ -3,11 +3,10 @@use photocraft_codecs::{ChannelLayout, EncodeOptions, Image, SampleType as CS};use photocraft_color::{ColorMode, SampleType};use photocraft_doc::{Document, Layer, Size};-use photocraft_format::Autosaver;+use photocraft_format::RecoveryStore;use photocraft_geom::Rect;-use photocraft_ui_egui::Services;+use photocraft_ui_egui::{Recovered, Services};use std::cell::RefCell;-use std::collections::HashMap;use std::path::{Path, PathBuf};use std::rc::Rc;use std::sync::Arc;@@ -71,9 +70,40 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {photocraft_format::atomic_write(path, bytes).map_err(|e| e.to_string())}+type SharedRecovery = Rc<RefCell<Option<RecoveryStore>>>;++/// Run `f` on the recovery store (`Err` without a config directory). The service closures never+/// call each other, so the store is never borrowed twice.+fn with_store<R>(store: &SharedRecovery, f: impl FnOnce(&mut RecoveryStore) -> R) -> Result<R, String> {+ let mut slot = store.try_borrow_mut().map_err(|_| "crash recovery is busy".to_string())?;+ Ok(f(slot.as_mut().ok_or("no config directory")?))+}++/// Crash recovery: background incremental .pcraft autosaves into `dir` (`None`: no config+/// directory, so autosaves fail and nothing is recovered). Recovered documents keep their entries+/// until a newer autosave replaces them or they're saved or closed (see [`RecoveryStore`]).+fn recovery_services(dir: Option<PathBuf>) -> Services {+ let store: SharedRecovery = Rc::new(RefCell::new(dir.map(RecoveryStore::new)));+ let (s1, s2, s3) = (store.clone(), store.clone(), store.clone());+ Services {+ autosave: Some(Box::new(move |doc: &Arc<Document>, revision: u64, path: Option<&str>| {+ with_store(&s1, |s| s.autosave(doc, revision, path.map(str::to_string)))+ })),+ discard_autosave: Some(Box::new(move |id: u64| {+ let _ = with_store(&s2, |s| s.discard(id));+ })),+ recover: Some(Box::new(move || {+ let found = with_store(&s3, |s| s.recover()).unwrap_or_default();+ found.into_iter().map(|(e, doc)| Recovered { key: e.info.key, path: e.info.original_path, doc }).collect()+ })),+ adopt_autosave: Some(Box::new(move |id: u64, key: &str| {+ let _ = with_store(&store, |s| s.adopt(id, key));+ })),+ ..Default::default()+ }+}+pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) -> Services {- let savers: Rc<RefCell<HashMap<u64, Autosaver>>> = Rc::default();- let savers2 = savers.clone();let clip: Rc<RefCell<Option<arboard::Clipboard>>> = Rc::default();let automation_read = automation.clone().map(|workspace| {Box::new(move |path: &str| {@@ -152,31 +182,6 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->}),load_prefs: Some(Box::new(|| std::fs::read_to_string(prefs_file()?).ok())),save_prefs: Some(Box::new(|text: &str| write_atomic(&prefs_file().ok_or("no config directory")?, text.as_bytes()))),- // Crash recovery: background incremental .pcraft saves into the recovery directory.- autosave: Some(Box::new(move |doc: &Arc<Document>, revision: u64, path: Option<&str>| {- let dir = recovery_dir().ok_or("no config directory")?;- let mut map = savers.borrow_mut();- let saver = map.entry(doc.id.0).or_insert_with(|| Autosaver::new(&dir, &format!("doc-{}", doc.id.0)));- saver.request(doc.clone(), revision, path.map(str::to_string), Default::default());- Ok(())- })),- discard_autosave: Some(Box::new(move |id: u64| {- if let Some(s) = savers2.borrow_mut().remove(&id) {- let _ = s.discard();- }- })),- recover: Some(Box::new(|| {- let Some(dir) = recovery_dir() else { return Vec::new() };- let mut out = Vec::new();- for entry in photocraft_format::list_recovery(&dir) {- if let Ok(doc) = photocraft_format::recover(&entry) {- out.push((entry.info.original_path.clone(), doc));- }- // Recovered documents autosave again under their new ids.- let _ = photocraft_format::discard_recovery(&dir, &entry);- }- out- })),append_text: Some(Box::new(|path: &str, text: &str| {use std::io::Write;let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| e.to_string())?;@@ -186,6 +191,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->os_events: None,// Set by main, which starts loading the store before the window opens.preset_store: None,+ ..recovery_services(recovery_dir())}}@@ -250,3 +256,94 @@ pub fn export_flat(doc: &Document, path: &str) -> Result<Vec<u8>, String> {};photocraft_codecs::encode(&img, format, &EncodeOptions::default()).map_err(|e| e.to_string())}++#[cfg(test)]+mod tests {+ use super::*;+ use photocraft_engine::Session;+ use photocraft_format::list_recovery;+ use photocraft_ui_egui::{PhotocraftApp, prefs_ui};+ use serde_json::json;++ const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];+ const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];+ const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];++ /// One app launch with crash recovery in `dir` (dropping it is the crash: background writes+ /// already queued finish, nothing else runs).+ fn launch(dir: &Path) -> PhotocraftApp {+ PhotocraftApp::new(Session::new(), recovery_services(Some(dir.to_path_buf())))+ }++ /// The first pixel of each open document, and whether it's unsaved.+ fn open_docs(app: &PhotocraftApp) -> Vec<([f32; 4], bool)> {+ app.session.documents().iter().map(|d| (photocraft_compose::flatten(&d.doc).px.first().copied().unwrap_or_default(), d.is_dirty())).collect()+ }++ fn index_of(app: &PhotocraftApp, color: [f32; 4]) -> usize {+ open_docs(app).iter().position(|(c, _)| *c == color).unwrap()+ }++ fn new_doc(app: &mut PhotocraftApp, color: &str) {+ app.run("file.new", json!({"width": 4, "height": 4})).unwrap();+ app.run("edit.fill", json!({"color": color})).unwrap();+ }++ fn autosave(app: &mut PhotocraftApp, ctx: &egui::Context) {+ prefs_ui::autosave_now(app);+ prefs_ui::tick(app, ctx);+ }++ #[test]+ fn recovered_documents_survive_a_second_crash_until_saved_or_closed() {+ let dir = std::env::temp_dir().join(format!("photocraft-recovery-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ let ctx = egui::Context::default();+ // Launch 1: two unsaved documents are autosaved, then the app crashes.+ {+ let mut app = launch(&dir);+ new_doc(&mut app, "#ff0000");+ new_doc(&mut app, "#0000ff");+ autosave(&mut app, &ctx);+ }+ assert_eq!(list_recovery(&dir).len(), 2);+ // Launch 2 recovers both and crashes again before its first autosave (#444).+ {+ let mut app = launch(&dir);+ let mut docs = open_docs(&app);+ docs.sort_by(|a, b| a.0[0].total_cmp(&b.0[0]));+ assert_eq!(docs, [(BLUE, true), (RED, true)], "recovered and still unsaved");+ prefs_ui::tick(&mut app, &ctx);+ }+ assert_eq!(list_recovery(&dir).len(), 2, "recovering keeps the entries on disk");+ // Launch 3 has both again; autosaving unchanged documents adds nothing, a new document+ // (whose id may repeat one from an earlier launch) gets an entry of its own.+ {+ let mut app = launch(&dir);+ assert_eq!(app.session.documents().len(), 2);+ autosave(&mut app, &ctx);+ new_doc(&mut app, "#00ff00");+ autosave(&mut app, &ctx);+ }+ assert_eq!(list_recovery(&dir).len(), 3);+ // Launch 4: closing and saving recovered documents removes their entries, no duplicates.+ let mut app = launch(&dir);+ assert_eq!(app.session.documents().len(), 3);+ let red = index_of(&app, RED);+ app.run("file.close", json!({"document": red})).unwrap();+ // Saving marks the revision saved (the file write itself is the save service's job).+ assert!(app.session.set_active(index_of(&app, BLUE)));+ let st = app.session.active_mut().unwrap();+ st.saved_revision = st.revision;+ prefs_ui::tick(&mut app, &ctx);+ let left = list_recovery(&dir);+ assert_eq!(left.len(), 1);+ assert_eq!(photocraft_compose::flatten(&photocraft_format::recover(&left[0]).unwrap()).px.first().copied(), Some(GREEN));+ let green = index_of(&app, GREEN);+ app.run("file.close", json!({"document": green})).unwrap();+ prefs_ui::tick(&mut app, &ctx);+ assert!(list_recovery(&dir).is_empty());+ drop(app);+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/format/src/autosave.rs b/crates/format/src/autosave.rsindex cd8929046..91c22e393 100644--- a/crates/format/src/autosave.rs+++ b/crates/format/src/autosave.rs@@ -5,7 +5,12 @@//! Layout: `<recovery_dir>/<key>.pcraft/` (directory bundles, so repeated//! autosaves write only changed tiles) plus `<key>.json` with//! [`RecoveryInfo`]. Native targets only (threads and a filesystem).+//!+//! [`RecoveryStore`] is the app-facing lifecycle: an entry is only deleted once+//! the document is saved or closed, never just because it was recovered.+#[cfg(not(target_arch = "wasm32"))]+use std::collections::HashMap;use std::path::{Path, PathBuf};use std::sync::mpsc::{self, Receiver, Sender};use std::sync::{Arc, Mutex};@@ -141,7 +146,8 @@ fn worker(rx: Receiver<Job>, bundle: PathBuf, sidecar: PathBuf, last: Arc<Mutex<}}-/// Recoverable documents in `recovery_dir`, newest first.+/// Recoverable documents in `recovery_dir`, newest first. A sidecar must be named after its own+/// (sanitized) key, so a stray or hand-edited one can never point outside the directory.pub fn list_recovery(recovery_dir: &Path) -> Vec<RecoveryEntry> {let mut out = Vec::new();let Ok(rd) = std::fs::read_dir(recovery_dir) else {@@ -152,6 +158,8 @@ pub fn list_recovery(recovery_dir: &Path) -> Vec<RecoveryEntry> {if p.extension().is_some_and(|x| x == "json")&& let Ok(bytes) = std::fs::read(&p)&& let Ok(info) = serde_json::from_slice::<RecoveryInfo>(&bytes)+ && sanitize(&info.key) == info.key+ && p.file_stem().is_some_and(|stem| *stem == *info.key){let bundle = recovery_dir.join(format!("{}.pcraft", info.key));if bundle.join(crate::store::MANIFEST).is_file() {@@ -173,6 +181,64 @@ pub fn discard_recovery(recovery_dir: &Path, entry: &RecoveryEntry) -> Result<()remove_entry(recovery_dir, &entry.info.key)}+/// The crash-recovery autosaves of one app session, keyed by document id (the `DocId` value).+///+/// New documents save under `doc-<session>-<id>`, with a `<session>` unique to this store: ids+/// restart every launch, so a new document must never overwrite an entry an earlier launch left.+/// A recovered document [adopts](Self::adopt) the entry it was loaded from. Its autosaves replace+/// that entry in place (each save is atomic, so the old copy stays loadable until the new one is+/// complete), and saving or closing it removes the entry. Nothing is deleted just because it was+/// recovered, so a second crash before the next autosave loses nothing.+#[cfg(not(target_arch = "wasm32"))]+pub struct RecoveryStore {+ dir: PathBuf,+ session: String,+ savers: HashMap<u64, Autosaver>,+ adopted: HashMap<u64, String>,+}++#[cfg(not(target_arch = "wasm32"))]+impl RecoveryStore {+ pub fn new(recovery_dir: impl Into<PathBuf>) -> Self {+ use std::sync::atomic::{AtomicU64, Ordering};+ static STORES: AtomicU64 = AtomicU64::new(0);+ let t = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);+ let session = format!("{t:x}_{:x}_{:x}", std::process::id(), STORES.fetch_add(1, Ordering::Relaxed));+ RecoveryStore { dir: recovery_dir.into(), session, savers: HashMap::new(), adopted: HashMap::new() }+ }++ /// Load every recoverable document, newest first, with the entry it came from. Nothing is+ /// deleted: [`adopt`](Self::adopt) each document the app opens. Entries that fail to load stay+ /// on disk untouched.+ pub fn recover(&self) -> Vec<(RecoveryEntry, Document)> {+ list_recovery(&self.dir).into_iter().filter_map(|e| recover(&e).ok().map(|doc| (e, doc))).collect()+ }++ /// Document `doc_id` was opened from the recovery entry `key`: its autosaves now replace that+ /// entry, and [`discard`](Self::discard) removes it.+ pub fn adopt(&mut self, doc_id: u64, key: &str) {+ self.adopted.insert(doc_id, sanitize(key));+ }++ /// Queue an autosave of `doc` (returns immediately; see [`Autosaver::request`]).+ pub fn autosave(&mut self, doc: &Arc<Document>, revision: u64, original_path: Option<String>) {+ let id = doc.id.0;+ let saver = self.savers.entry(id).or_insert_with(|| {+ let key = self.adopted.get(&id).cloned().unwrap_or_else(|| format!("doc-{}-{id}", self.session));+ Autosaver::new(&self.dir, &key)+ });+ saver.request(doc.clone(), revision, original_path, SaveOptions::default());+ }++ /// Document `doc_id` was saved or closed: remove its recovery data, both its own autosaves+ /// and the entry it adopted.+ pub fn discard(&mut self, doc_id: u64) -> Result<()> {+ let own = self.savers.remove(&doc_id).map_or(Ok(()), Autosaver::discard);+ let adopted = self.adopted.remove(&doc_id).map_or(Ok(()), |key| remove_entry(&self.dir, &key));+ own.and(adopted)+ }+}+fn remove_entry(dir: &Path, key: &str) -> Result<()> {let bundle = dir.join(format!("{key}.pcraft"));if bundle.exists() {diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rsindex 5a40f3299..815851b0f 100644--- a/crates/format/src/lib.rs+++ b/crates/format/src/lib.rs@@ -34,6 +34,8 @@ use photocraft_doc::Document;use photocraft_raster::Rgba8Image;pub use atomic::atomic_write;+#[cfg(not(target_arch = "wasm32"))]+pub use autosave::RecoveryStore;pub use autosave::{Autosaver, RecoveryEntry, discard_recovery, list_recovery, recover};pub use manifest::{FORMAT_VERSION, Manifest};pub use store::{PcraftWriter, SaveStats};diff --git a/crates/format/tests/autosave.rs b/crates/format/tests/autosave.rsindex a055fc714..bf601fb85 100644--- a/crates/format/tests/autosave.rs+++ b/crates/format/tests/autosave.rs@@ -5,6 +5,7 @@ use std::sync::Arc;use common::*;use photocraft_color::{ColorMode, SampleType};+use photocraft_doc::{DocId, Document};use photocraft_format::*;#[test]@@ -66,3 +67,136 @@ fn list_ignores_junk() {assert!(list_recovery(&dir.join("missing")).is_empty());std::fs::remove_dir_all(dir).unwrap();}++/// `doc` as document `id` with pixel (x, 0) of its paint layer set, so versions are told apart.+fn edit(mut doc: Document, id: u64, x: i32) -> Document {+ doc.id = DocId(id);+ let layer = doc.layers[1].id;+ doc.layer_mut(layer).unwrap().surface_mut().unwrap().write_pixel(x, 0, &[1.0, 0.0, 0.0, 1.0]);+ doc+}++fn version(id: u64, x: i32, mode: ColorMode) -> Document {+ edit(rich_doc(mode, SampleType::U8), id, x)+}++/// Save one snapshot under `key` and wait for it.+fn save_once(dir: &std::path::Path, key: &str, doc: Document) {+ let saver = Autosaver::new(dir, key);+ saver.request(Arc::new(doc), 1, None, SaveOptions::default());+ saver.flush().unwrap().unwrap();+}++/// The recovered documents by entry key, ids cleared (they're reassigned on open).+fn recovered(store: &RecoveryStore) -> std::collections::BTreeMap<String, Document> {+ store+ .recover()+ .into_iter()+ .map(|(e, mut doc)| {+ doc.id = DocId(0);+ (e.info.key, doc)+ })+ .collect()+}++fn same(mut doc: Document) -> Document {+ doc.id = DocId(0);+ doc+}++#[test]+fn recovered_entries_survive_a_second_crash_until_saved_or_closed() {+ let dir = temp_dir("second-crash");+ let (a, b) = (version(1, 3, ColorMode::Rgb), version(2, 5, ColorMode::Grayscale));+ // Launch 1 autosaves two unsaved documents, then crashes (dropping waits for the writes).+ {+ let mut launch = RecoveryStore::new(&dir);+ launch.autosave(&Arc::new(a.clone()), 4, None);+ launch.autosave(&Arc::new(b.clone()), 6, Some("/work/b.pcraft".into()));+ }+ assert_eq!(list_recovery(&dir).len(), 2);+ // Launch 2 recovers both and crashes before its first autosave: nothing may be lost.+ let keys: Vec<String> = {+ let mut launch = RecoveryStore::new(&dir);+ let docs = recovered(&launch);+ assert_eq!(docs.len(), 2);+ assert_eq!(list_recovery(&dir).len(), 2, "recovering must not delete the entries");+ for (i, key) in docs.keys().enumerate() {+ launch.adopt(10 + i as u64, key);+ }+ docs.into_keys().collect()+ };+ // Launch 3 still has both, pixels intact; one is edited and autosaved, the other closed.+ let edited = edit(a.clone(), 20, 9);+ {+ let mut launch = RecoveryStore::new(&dir);+ let docs = recovered(&launch);+ assert_eq!(docs.values().cloned().collect::<Vec<_>>(), vec![same(a.clone()), same(b.clone())]);+ launch.adopt(20, &keys[0]);+ launch.adopt(21, &keys[1]);+ launch.autosave(&Arc::new(edited.clone()), 9, None);+ launch.discard(21).unwrap();+ assert_eq!(list_recovery(&dir).len(), 1, "closing removes the adopted entry");+ }+ // The autosave replaced the adopted entry in place: no duplicate, newest content.+ let entries = list_recovery(&dir);+ assert_eq!(entries.len(), 1);+ assert_eq!((entries[0].info.key.as_str(), entries[0].info.revision), (keys[0].as_str(), 9));+ // Launch 4 recovers it once more and saves it: the entry goes.+ let mut launch = RecoveryStore::new(&dir);+ assert_eq!(recovered(&launch).into_values().collect::<Vec<_>>(), vec![same(edited)]);+ launch.adopt(30, &keys[0]);+ launch.discard(30).unwrap();+ assert!(list_recovery(&dir).is_empty());+ drop(launch);+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn new_documents_never_overwrite_surviving_entries() {+ let dir = temp_dir("collision");+ // An earlier launch (including builds that keyed entries by bare document id) left `doc-1`.+ let old = version(1, 3, ColorMode::Rgb);+ save_once(&dir, "doc-1", old.clone());+ // A store from another launch left an entry for its own document 1 too.+ let other = version(1, 6, ColorMode::Grayscale);+ RecoveryStore::new(&dir).autosave(&Arc::new(other.clone()), 2, None);+ assert_eq!(list_recovery(&dir).len(), 2);+ // This launch adopts `doc-1` for its document 5, and its own new document 1 autosaves.+ let fresh = version(1, 8, ColorMode::Rgb);+ {+ let mut launch = RecoveryStore::new(&dir);+ launch.adopt(5, "doc-1");+ launch.autosave(&Arc::new(fresh.clone()), 3, None);+ }+ let docs = recovered(&RecoveryStore::new(&dir));+ assert_eq!(docs.len(), 3, "the new document got an entry of its own");+ assert_eq!(docs.get("doc-1"), Some(&same(old)), "the adopted entry is untouched");+ assert!(docs.values().any(|d| *d == same(other.clone())));+ assert!(docs.values().any(|d| *d == same(fresh.clone())));+ // Closing the new document removes only its own entry.+ let mut launch = RecoveryStore::new(&dir);+ launch.adopt(5, "doc-1");+ launch.autosave(&Arc::new(fresh), 3, None);+ launch.discard(1).unwrap();+ assert_eq!(list_recovery(&dir).len(), 3);+ launch.discard(5).unwrap();+ assert_eq!(list_recovery(&dir).len(), 2);+ drop(launch);+ std::fs::remove_dir_all(dir).unwrap();+}++#[test]+fn sidecars_cannot_point_at_other_bundles() {+ let dir = temp_dir("sidecar-key");+ let inner = dir.join("Recovery");+ save_once(&dir, "outside", rich_doc(ColorMode::Rgb, SampleType::U8));+ save_once(&inner, "k", rich_doc(ColorMode::Rgb, SampleType::U8));+ let info = std::fs::read_to_string(inner.join("k.json")).unwrap();+ // A copied sidecar (its name isn't its key) and one whose key leaves the directory.+ std::fs::write(inner.join("copy.json"), &info).unwrap();+ std::fs::write(inner.join("escape.json"), info.replace("\"k\"", "\"../outside\"")).unwrap();+ let entries = list_recovery(&inner);+ assert_eq!(entries.iter().map(|e| e.info.key.as_str()).collect::<Vec<_>>(), ["k"]);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex ac58525af..644741663 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -171,8 +171,21 @@ pub type SaveTextFn = Box<dyn FnMut(&str) -> Result<(), String>>;pub type AutosaveFn = Box<dyn FnMut(&std::sync::Arc<Document>, u64, Option<&str>) -> Result<(), String>>;/// Drop the recovery data of a document (by `DocId` value) once it is saved or closed.pub type DiscardAutosaveFn = Box<dyn FnMut(u64)>;-/// Load recoverable documents left by a previous session: (original path, document).-pub type RecoverFn = Box<dyn FnMut() -> Vec<(Option<String>, Document)>>;+/// Load recoverable documents left by a previous session. Their recovery data stays until the+/// documents are saved or closed.+pub type RecoverFn = Box<dyn FnMut() -> Vec<Recovered>>;+/// A recovered document (by `DocId` value, once open) takes over its recovery entry (by key):+/// its autosaves replace the entry, and saving or closing it drops the entry.+pub type AdoptAutosaveFn = Box<dyn FnMut(u64, &str)>;++/// A document [`RecoverFn`] found.+pub struct Recovered {+ /// The recovery entry it was loaded from (see [`AdoptAutosaveFn`]).+ pub key: String,+ /// Where the user last saved it, if anywhere.+ pub path: Option<String>,+ pub doc: Document,+}/// Append text to a file (History Log).pub type AppendTextFn = Box<dyn FnMut(&str, &str) -> Result<(), String>>;/// Requests from the operating system since the last call (see [`OsEvent`]).@@ -214,6 +227,7 @@ pub struct Services {pub autosave: Option<AutosaveFn>,pub discard_autosave: Option<DiscardAutosaveFn>,pub recover: Option<RecoverFn>,+ pub adopt_autosave: Option<AdoptAutosaveFn>,/// History Log text file output.pub append_text: Option<AppendTextFn>,/// OS requests (macOS open-documents / quit Apple events), polled every frame.diff --git a/crates/ui-egui/src/prefs_ui.rs b/crates/ui-egui/src/prefs_ui.rsindex 8f3ff6a7b..15e7bcf0c 100644--- a/crates/ui-egui/src/prefs_ui.rs+++ b/crates/ui-egui/src/prefs_ui.rs@@ -109,11 +109,17 @@ pub fn load(app: &mut PhotocraftApp) {{let docs = recover();let n = docs.len();- for (path, doc) in docs {- app.session.add_document(doc, path);+ for r in docs {+ app.session.add_document(r.doc, r.path);// Recovered documents are unsaved.- if let Some(st) = app.session.active_mut() {- st.saved_revision = 0;+ let Some(st) = app.session.active_mut() else { continue };+ st.saved_revision = 0;+ // Their entry already holds this revision: it stays until a newer autosave replaces+ // it or the document is saved or closed (see `autosave`).+ let (id, revision) = (st.doc.id, st.revision);+ app.prefs_rt.autosaved.insert(id, revision);+ if let Some(adopt) = app.services.adopt_autosave.as_mut() {+ adopt(id.0, &r.key);}}if n > 0 {@@ -1608,6 +1614,42 @@ mod tests {assert_eq!(saved.lock().unwrap().len(), 2, "autosave off");}+ #[test]+ fn recovered_documents_adopt_their_entries_until_saved_or_closed() {+ type Log = Arc<Mutex<Vec<String>>>;+ let log: Log = Arc::default();+ let (l1, l2, l3) = (log.clone(), log.clone(), log.clone());+ use photocraft_doc::{Color, ColorMode, Document, SampleType, Size};+ let doc = || Document::with_background("R", Size::new(4, 4), ColorMode::Rgb, SampleType::U8, Color::WHITE);+ let services = crate::Services {+ autosave: Some(Box::new(move |d: &Arc<Document>, _: u64, _: Option<&str>| {+ l1.lock().unwrap().push(format!("save {}", d.id.0));+ Ok(())+ })),+ discard_autosave: Some(Box::new(move |id: u64| l2.lock().unwrap().push(format!("discard {id}")))),+ recover: Some(Box::new(move || ["a", "b"].map(|key| crate::Recovered { key: key.into(), path: None, doc: doc() }).into())),+ adopt_autosave: Some(Box::new(move |id: u64, key: &str| l3.lock().unwrap().push(format!("adopt {id} {key}")))),+ ..Default::default()+ };+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);+ let ctx = egui::Context::default();+ let ids: Vec<u64> = app.session.documents().iter().map(|d| d.doc.id.0).collect();+ assert!(app.session.documents().iter().all(|d| d.is_dirty()), "recovered documents are unsaved");+ let take = || std::mem::take(&mut *log.lock().unwrap());+ assert_eq!(take(), [format!("adopt {} a", ids[0]), format!("adopt {} b", ids[1])]);+ // Their entries are current: nothing to autosave until they change.+ tick(&mut app, &ctx);+ autosave_now(&mut app);+ tick(&mut app, &ctx);+ assert!(take().is_empty());+ // Closing one drops its entry; editing the other autosaves over its own.+ app.run("file.close", json!({"document": 0})).unwrap();+ app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();+ autosave_now(&mut app);+ tick(&mut app, &ctx);+ assert_eq!(take(), [format!("discard {}", ids[0]), format!("save {}", ids[1])]);+ }+#[test]fn edit_dialogs_open() {let (mut app, _) = app_with_store();diff --git a/docs/development.md b/docs/development.mdindex 5865f6e83..b94202c1a 100644--- a/docs/development.md+++ b/docs/development.md@@ -110,7 +110,7 @@ cargo run -p photocraft-cli -- commands --filter blur # the c- `tiles/<blake3>.zst` and `blobs/<blake3>.zst`: zstd-compressed objects, content-addressed by the BLAKE3 hash of their uncompressed bytes.- `thumb.png` and `composite/preview.png`: previews.-Keep one `PcraftWriter` per open document: re-saving then only compresses and writes tiles that changed, and directory bundles garbage-collect unreferenced objects. `format::Autosaver` writes snapshots into a recovery directory on a background thread. `list_recovery` / `recover` / `discard_recovery` implement crash recovery.+Keep one `PcraftWriter` per open document: re-saving then only compresses and writes tiles that changed, and directory bundles garbage-collect unreferenced objects. `format::Autosaver` writes snapshots into a recovery directory on a background thread. `list_recovery` / `recover` / `discard_recovery` implement crash recovery, and `format::RecoveryStore` is the lifecycle the desktop app uses: new documents autosave under per-launch keys (document ids restart every launch, so they never overwrite an older entry), and a recovered document adopts the entry it came from. That entry is replaced in place by the next autosave and removed only when the document is saved or closed, never just because it was recovered, so a second crash loses nothing. The web build has no crash recovery (no autosave services).`photocraft-io` routes `.pcraft` through this crate in `import`/`export`, detecting it by magic or by extension.