diff --git a/Cargo.lock b/Cargo.lock index f9720b738e..7fe5379529 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -9291,6 +9291,7 @@ dependencies = [ "rustix 1.1.6", "serde", "serde_json", + "sha2 0.10.9", "toml", "vectorcraft-apischema", "vectorcraft-brush", diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 72657ef6ae..d0953f6e0b 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -87,6 +87,9 @@ craft = { workspace = true, features = ["dialogs", "update", "automation-agents" # The local date and time the status bar's Date and Time readout shows (`chrono::Local`). Already in # Cargo.lock with the time-zone crates `clock` uses. chrono = { workspace = true, features = ["clock"] } +# The digest of each open document's file, which Save compares with the file before asking whether to replace it +# (`src/io/saved_contents.rs`). Already in Cargo.lock (the engine's and the plug-ins' digests). +sha2 = { version = "0.10", default-features = false } [target.'cfg(target_arch = "wasm32")'.dependencies] # The status bar's Date and Time readout reads the page's clock with this crate in the web build. It diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 162d1867ef..8a32a68af5 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -671,6 +671,7 @@ impl VectorcraftApp { if !self.background.jobs.is_empty() || !self.opening.pending.is_empty() || !self.opening.converting.is_empty() + || io::save::checks_pending(self) || plugin_runs::any_pending(self) || !self.placing.pending.is_empty() || !self.trace_runs.running.is_empty() @@ -792,6 +793,7 @@ impl VectorcraftApp { self.handle_input(&ctx); self.ui_frame(ui); self.window_keys(&ctx); + io::save::after_ui(self, &ctx); // What the canvas, a panel, a dialog or a window key changed in this pass reaches // the plug-ins that react to it now, since an idle app draws no further frame; a // line a handler wrote shows in the next one. The handlers' time counts toward the diff --git a/crates/ui-egui/src/io.rs b/crates/ui-egui/src/io.rs index 5d08bbf110..75f3091f6a 100644 --- a/crates/ui-egui/src/io.rs +++ b/crates/ui-egui/src/io.rs @@ -16,6 +16,8 @@ pub(crate) mod export; mod open; mod read_only_save; pub(crate) mod save; +#[cfg(not(target_arch = "wasm32"))] +mod saved_contents; #[cfg(test)] mod tests_read_only_save; diff --git a/crates/ui-egui/src/io/open.rs b/crates/ui-egui/src/io/open.rs index 7aec797157..f6de26a38b 100644 --- a/crates/ui-egui/src/io/open.rs +++ b/crates/ui-egui/src/io/open.rs @@ -180,7 +180,7 @@ pub(crate) fn opened(app: &mut VectorcraftApp, r: &Value) { if let Some(st) = index.and_then(|i| app.session.documents().get(i)) && let Some(path) = &st.path { - app.saves.watch.known_now(st.uid, Path::new(path)); + app.saves.known_now(st.uid, Path::new(path)); } let notes = open_notes(app, r); crate::dialogs::missing_links::after_open(app, r, notes); diff --git a/crates/ui-egui/src/io/save.rs b/crates/ui-egui/src/io/save.rs index fc42da3c77..3fd847f4db 100644 --- a/crates/ui-egui/src/io/save.rs +++ b/crates/ui-egui/src/io/save.rs @@ -1,14 +1,16 @@ use std::collections::HashMap; -use std::path::PathBuf; -// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads. +use std::path::{Path, PathBuf}; #[cfg(not(target_arch = "wasm32"))] -use std::path::Path; +use std::sync::mpsc::{Receiver, TryRecvError}; +// The save panel's flow is the desktop's (craft-dialogs is native only); the web downloads. #[cfg(not(target_arch = "wasm32"))] use craft::dialogs::save::{SAVE_IN_PROGRESS, SaveDocument, SaveFlow, SaveStep, SaveTarget}; #[cfg(not(target_arch = "wasm32"))] use craft::host::Files; use craft::host::{FileFilter, PickRequest, Picked, Wake}; +#[cfg(not(target_arch = "wasm32"))] +use craft::platform::watch::FileStamp; use craft::platform::watch::FileWatch; use craft::ui::dialog::DialogId; #[cfg(not(target_arch = "wasm32"))] @@ -48,12 +50,31 @@ struct SaveDone { then: Option, } +/// A save whose flow would ask whether to replace its document's file, waiting for the file to be +/// compared with the bytes the app last read or wrote. +#[cfg(not(target_arch = "wasm32"))] +struct Checking { + path: PathBuf, + /// The file's version when it holds those bytes, else `None`. + answer: Receiver>, +} + /// The saves of the app: one [`SaveFlow`] per document, and what the flows need to ask and write. pub(crate) struct Saves { #[cfg(not(target_arch = "wasm32"))] flows: HashMap>, /// The version of each document's file the app last read or wrote. pub(crate) watch: FileWatch, + /// The digest of the bytes of each document's file, as the app last read or wrote them. + #[cfg(not(target_arch = "wasm32"))] + contents: super::saved_contents::SavedContents, + /// The saves waiting for a comparison of their document's file with those bytes. + #[cfg(not(target_arch = "wasm32"))] + checks: HashMap, + /// A comparison's save waited in the last pass for a dialog, a file picker or a gesture in + /// another document: [`after_ui`] asks for a frame once it no longer has to. + #[cfg(not(target_arch = "wasm32"))] + held: bool, /// The files written beside each document's file, which its next save replaces. pub(crate) written_beside: HashMap>, /// The files the OK of the replace question allows the save it runs again to replace. @@ -68,6 +89,12 @@ impl Saves { Self { #[cfg(not(target_arch = "wasm32"))] flows: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + contents: super::saved_contents::SavedContents::new(), + #[cfg(not(target_arch = "wasm32"))] + checks: HashMap::new(), + #[cfg(not(target_arch = "wasm32"))] + held: false, watch: FileWatch::new(wake), written_beside: HashMap::new(), replace_files_ok: Vec::new(), @@ -76,12 +103,55 @@ impl Saves { } } + /// The app just read document `uid`'s file at `path`: that version is not a change on disk. + pub(crate) fn known_now(&mut self, uid: u64, path: &Path) { + self.watch.known_now(uid, path); + #[cfg(not(target_arch = "wasm32"))] + self.note_contents(uid, path); + } + + /// Takes the digest of document `uid`'s file at `path`, the version the watcher just recorded. + #[cfg(not(target_arch = "wasm32"))] + fn note_contents(&mut self, uid: u64, path: &Path) { + match FileStamp::at(path) { + // Not differing from the watcher's version: the file has not changed since it was recorded. + Some(stamp) if !self.watch.disk_differs(&uid, path, None) => self.contents.note(uid, path, stamp), + _ => self.contents.forget(uid), + } + } + + /// Stops tracking document `uid`'s file (the document closed). + #[cfg(not(target_arch = "wasm32"))] + fn forget(&mut self, uid: u64) { + self.watch.forget(&uid); + self.contents.forget(uid); + self.checks.remove(&uid); + } + #[cfg(not(target_arch = "wasm32"))] fn start(&mut self, files: &dyn Files, document: SaveDocument, target: SaveTarget) -> SaveStep { let Self { flows, watch, .. } = self; flows.entry(document.key).or_default().start(files, watch, document, target) } + /// The answer of document `uid`'s file comparison, once it has come (with `wait`, once it + /// comes): the file's version when it holds the bytes the app last read or wrote, and the + /// file's path. `None` while there is no answer yet, or no comparison. + #[cfg(not(target_arch = "wasm32"))] + fn answer(&mut self, uid: u64, wait: bool) -> Option<(Option, PathBuf)> { + let check = self.checks.get(&uid)?; + let same = if wait { + check.answer.recv().ok().flatten() + } else { + match check.answer.try_recv() { + Ok(same) => same, + Err(TryRecvError::Empty) => return None, + Err(TryRecvError::Disconnected) => None, + } + }; + self.checks.remove(&uid).map(|c| (same, c.path)) + } + /// Frees the document's flow after a write that wrote nothing. #[cfg(not(target_arch = "wasm32"))] pub(super) fn release(&mut self, uid: u64) { @@ -91,6 +161,63 @@ impl Saves { } } +/// Whether file comparisons need another frame to collect their answers. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn checks_pending(app: &VectorcraftApp) -> bool { + // A save waiting for a dialog or a gesture goes on in the frame after the one that ends it ([`after_ui`]). + app.saves.checks.keys().any(|uid| !held(app, *uid)) +} + +/// Whether document `uid`'s save has to wait: the document shows a dialog's preview or a drag not +/// yet committed, which the save would write (typing in progress is saved, as by any Save), or +/// writing it activates its document, which would put it under an open dialog or file picker of +/// another document, cancel a drag in progress in the active one, or fail while a script runs. +#[cfg(not(target_arch = "wasm32"))] +fn held(app: &VectorcraftApp, uid: u64) -> bool { + if app.session.documents().iter().any(|d| d.uid == uid && d.interaction.as_ref().is_some_and(|it| it.label != "Typing")) { + return true; + } + let active = app.session.active(); + active.map(|d| d.uid) != Some(uid) + && (app.any_dialog_open() + || app.file_dialog_open() + || active.is_some_and(|d| d.interaction.is_some()) + || app.canvas.grab.is_some() + || app.session.script_running()) +} + +/// Whether document `uid`'s save waits for the comparison of its file. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn checking(app: &VectorcraftApp, uid: u64) -> bool { + app.saves.checks.contains_key(&uid) +} + +/// The web has no file comparisons. +#[cfg(target_arch = "wasm32")] +pub(crate) fn checking(_: &VectorcraftApp, _: u64) -> bool { + false +} + +/// Asks for one frame when a save waited in the last pass and this pass's UI closed what it +/// waited for: the dialog pumps and the canvas run after [`pump`], so nothing else would. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn after_ui(app: &mut VectorcraftApp, ctx: &egui::Context) { + if app.saves.held && app.saves.checks.keys().any(|uid| !held(app, *uid)) { + app.saves.held = false; + ctx.request_repaint(); + } +} + +/// The web has no saves that wait. +#[cfg(target_arch = "wasm32")] +pub(crate) fn after_ui(_: &mut VectorcraftApp, _: &egui::Context) {} + +/// The web has no file comparisons to collect. +#[cfg(target_arch = "wasm32")] +pub(crate) fn checks_pending(_: &VectorcraftApp) -> bool { + false +} + /// Calls the `then` of the document's save, once. #[cfg(not(target_arch = "wasm32"))] fn terminate(app: &mut VectorcraftApp, uid: u64, r: Result) { @@ -107,10 +234,24 @@ fn finish(app: &mut VectorcraftApp, uid: u64, retargets: bool, out: &Result flow.written(&mut app.saves.watch, uid, Path::new(path)), + Some(path) if flow.is_busy() || retargets => { + flow.written(&mut app.saves.watch, uid, Path::new(path)); + // The document's own file (not a copy's): its digest goes with the version the watcher took. + if app.session.documents().iter().any(|d| d.uid == uid && d.path.as_deref() == Some(path)) { + app.saves.note_contents(uid, Path::new(path)); + } + } _ => flow.failed(&uid), } if !matches!(out, Ok(v) if v.get("pending").is_some()) { + // A comparison still pending belongs to the save this one ends (a save with an explicit path + // ran meanwhile): it is dropped and its flow freed, since its answer would ask about the file + // with no save left to apply the answer. + if app.saves.checks.remove(&uid).is_some() + && let Some(flow) = app.saves.flows.get_mut(&uid) + { + let _ = flow.cancel(app.host.files()); + } terminate(app, uid, out.clone()); } } @@ -124,10 +265,12 @@ pub(crate) fn allow_replacing(app: &mut VectorcraftApp, files: &[String]) { } } -/// Takes what the flows and their questions have answered since the last pass: the pick, the -/// changed-on-disk question's answer. A save whose document closed is cancelled and forgotten. +/// Takes what the flows and their questions have answered since the last pass: the comparison of +/// a document's file, the pick, the changed-on-disk question's answer. A save whose document +/// closed is cancelled and forgotten. Closed documents' digest state is dropped on every pass. #[cfg(not(target_arch = "wasm32"))] pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { + resume_checked(app, false); let busy: Vec = app.saves.flows.iter().filter(|(_, f)| f.is_busy()).map(|(uid, _)| *uid).collect(); for uid in busy { if !app.session.documents().iter().any(|d| d.uid == uid) { @@ -136,7 +279,7 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { if let Some(mut flow) = app.saves.flows.remove(&uid) { flow.cancel(app.host.files()); } - app.saves.watch.forget(&uid); + app.saves.forget(uid); continue; } let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); @@ -152,6 +295,83 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) { app.status(e); } } + app.saves.contents.retain_open(app.session.documents().iter().map(|d| d.uid)); +} + +/// Goes on with the saves whose file comparison has answered (with `wait`, every one, once it +/// answers): an unchanged file is written over, and a changed one is asked about. +#[cfg(not(target_arch = "wasm32"))] +fn resume_checked(app: &mut VectorcraftApp, wait: bool) { + let checking: Vec = app.saves.checks.keys().copied().collect(); + for uid in checking { + // A closed document's save is cancelled with its flow, in [`pump`]. + let Some(file) = app.session.documents().iter().find(|d| d.uid == uid).map(|d| d.path.clone()) else { + continue; + }; + // Writing activates the save's document: while a dialog or file picker of another document + // is open, a drag goes on in it, or a script runs, the answer stays in its channel for a + // later pass. + if !wait && held(app, uid) { + app.saves.held = true; + continue; + } + let (scope, automated) = app.saves.done.get(&uid).map_or_else(|| (ScopeHandle::capture(), app.automation_asked()), |d| d.asked.clone()); + let r = scope.run(|| { + file_asks::as_automated(app, automated, |app| { + // The document now uses another file (a Save As finished meanwhile): the comparison + // is dropped and its save cancelled, without asking about the old file. + if app.saves.checks.get(&uid).is_some_and(|c| file.as_deref().map(Path::new) != Some(c.path.as_path())) { + app.saves.checks.remove(&uid); + let step = app.saves.flows.get_mut(&uid).and_then(|f| f.cancel(app.host.files())); + return step.map(|step| run_step(app, uid, step)); + } + let (same, path) = app.saves.answer(uid, wait)?; + // Still that version: a change made since the comparison is asked about. + let Some(stamp) = same.filter(|stamp| FileStamp::at(&path) == Some(*stamp)) else { + let asked = ask_changed_on_disk(app, uid, &path); + return Some(settle(app, uid, asked)); + }; + // The same bytes: the file's version now is the document's, and the flow writes over it. + app.saves.watch.known_as(uid, &path, Some(stamp)); + let step = app.saves.flows.get_mut(&uid).map_or(SaveStep::Busy, SaveFlow::replace); + Some(run_step(app, uid, step)) + }) + }); + if let Some(Err(e)) = r + && e != "cancelled" + { + app.status(e); + } + } +} + +/// Waits for every save's file comparison and goes on with those saves. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_checks(app: &mut VectorcraftApp) { + resume_checked(app, true); +} + +/// Waits for every save's file comparison to answer and its thread to end (its wake included), +/// leaving each answer for the next [`pump`]. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_answers(app: &mut VectorcraftApp) { + for check in app.saves.checks.values_mut() { + let (send, answer) = std::sync::mpsc::channel(); + if let Ok(same) = check.answer.recv() { + let _ = send.send(same); + } + // The thread drops its sender as it ends, after its wake. + let _ = check.answer.recv(); + check.answer = answer; + } +} + +/// Waits for the active document's baseline digest and compares it with the file. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn wait_for_contents(app: &VectorcraftApp) -> Option { + let document = app.session.active()?; + let path = Path::new(document.path.as_deref()?); + app.saves.contents.check(document.uid, path, Wake::none())?.recv().ok().flatten() } /// The web has no save flows: nothing answers between passes. @@ -182,6 +402,12 @@ fn next_step(app: &mut VectorcraftApp, uid: u64) -> Option> { /// Runs `step` of the document `uid`'s save; a failure frees the flow and tells the caller. fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep) -> Result { let r = proceed(app, step); + settle(app, uid, r) +} + +#[cfg(not(target_arch = "wasm32"))] +/// The result `r` of a step of document `uid`'s save; a failure frees the flow and tells the caller. +fn settle(app: &mut VectorcraftApp, uid: u64, r: Result) -> Result { if r.is_err() { app.saves.release(uid); terminate(app, uid, r.clone()); @@ -189,19 +415,40 @@ fn run_step(app: &mut VectorcraftApp, uid: u64, step: SaveStep) -> Result Result { + let name = fileio::file_name(&path.to_string_lossy()); + let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key)); + let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt)); + if let Some(done) = app.saves.done.get_mut(&key) { + done.question = Some(id); + } + Ok(json!({ "pending": "changedOnDisk" })) +} + +#[cfg(not(target_arch = "wasm32"))] +/// Asks the window for a frame, from any thread; does nothing without a window. +fn ui_wake(app: &VectorcraftApp) -> Wake { + app.ui_ctx.clone().map_or_else(Wake::none, |ctx| Wake::new(move || ctx.request_repaint())) +} + #[cfg(not(target_arch = "wasm32"))] fn proceed(app: &mut VectorcraftApp, step: SaveStep) -> Result { match step { SaveStep::Picking => Ok(json!({ "pending": "fileDialog" })), - SaveStep::AskChangedOnDisk { key, path } => { - let name = fileio::file_name(&path.to_string_lossy()); - let prompt = StandardPrompt::changed_on_disk(name).instance(("changed-on-disk", key)); - let id = app.dialogs().ok_or("no window to ask in")?.with(|host| host.open(prompt)); - if let Some(done) = app.saves.done.get_mut(&key) { - done.question = Some(id); + // Before asking, the file is compared with the bytes the app last read or wrote: a file + // whose metadata alone changed (a cloud-sync folder sets attributes on it, or puts the same + // bytes back as a new file) is written over without asking (#10734). [`pump`] goes on. + // The comparison's thread asks for a frame once it answers: a save started from the UI comes + // after this frame's repaint decision. + SaveStep::AskChangedOnDisk { key, path } => match app.saves.contents.check(key, &path, ui_wake(app)) { + Some(answer) => { + app.saves.checks.insert(key, Checking { path, answer }); + Ok(json!({ "pending": "checkingFile" })) } - Ok(json!({ "pending": "changedOnDisk" })) - } + None => ask_changed_on_disk(app, key, &path), + }, SaveStep::Write { key, path, target, file_type } => write_step(app, key, &path.to_string_lossy(), target, file_type), SaveStep::Cancelled { key } => { terminate(app, key, Err("cancelled".into())); diff --git a/crates/ui-egui/src/io/saved_contents.rs b/crates/ui-egui/src/io/saved_contents.rs new file mode 100644 index 0000000000..2ff6ab92fd --- /dev/null +++ b/crates/ui-egui/src/io/saved_contents.rs @@ -0,0 +1,224 @@ +//! The bytes of each open document's file as the app last read or wrote them, kept as a SHA-256 +//! digest (#10734). Save asks before replacing a file another app changed, and the save flow +//! counts a new change time or a new inode as a change. A cloud-sync folder sets +//! attributes on a file after uploading it, or puts the same bytes back as a new file. When the +//! file on disk still holds the bytes the app wrote, Save writes without asking. +//! +//! Files are read and digested on threads of their own: a file in a cloud folder may have to be +//! downloaded first. Each thread reads under the file-access scope of the call that started it: a +//! file that scope may not read leaves no digest, and Save asks as it does on a change. + +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; +use std::thread::JoinHandle; + +use craft::host::Wake; +use craft::platform::watch::FileStamp; +use sha2::{Digest, Sha256}; +use vectorcraft_engine::file_access::{self, ScopeHandle}; + +/// A version of a document's file: its path, its stamp when read, and the digest of its bytes. +#[derive(Clone)] +struct Version { + path: PathBuf, + stamp: FileStamp, + digest: [u8; 32], +} + +#[derive(Default)] +struct State { + versions: HashMap, + /// Counts the notes of each document: a digest taken for an older note is dropped. + notes: HashMap, + /// The digest being taken for each document's newest note. + pending: HashMap>, +} + +/// The digests of the open documents' files. +pub(crate) struct SavedContents { + state: Arc>, +} + +fn lock(state: &Mutex) -> MutexGuard<'_, State> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +impl SavedContents { + /// No digests yet. + pub(crate) fn new() -> Self { + Self { state: Arc::default() } + } + + /// The app just read or wrote document `key`'s file at `path`, and `stamp` is that version. + /// The file is opened and its digest taken on a thread of its own. Any stamp change + /// before or during the read leaves no digest, so Save asks on a change. + pub(crate) fn note(&self, key: u64, path: &Path, stamp: FileStamp) { + let note = { + let mut state = lock(&self.state); + state.versions.remove(&key); + state.pending.remove(&key); + let note = state.notes.entry(key).or_default(); + *note = note.wrapping_add(1); + *note + }; + let state = Arc::clone(&self.state); + let path = path.to_path_buf(); + let scope = ScopeHandle::capture_now(); + let work = move || { + if !readable(scope, &path) { + return; + } + let Ok(file) = File::open(&path) else { return }; + let Some(digest) = digest_of(file, stamp) else { return }; + let mut state = lock(&state); + if state.notes.get(&key) == Some(¬e) { + state.versions.insert(key, Version { path, stamp, digest }); + } + }; + // Without a thread nothing is recorded, and Save asks on any change, as before. + if let Ok(handle) = std::thread::Builder::new().name("vectorcraft-file-digest".into()).spawn(work) { + lock(&self.state).pending.insert(key, handle); + } + } + + /// Starts comparing document `key`'s file at `path` with the version the app last read or + /// wrote, on a thread of its own that first waits for that version's digest. The answer is + /// the file's version now when it holds the same bytes, and `None` when the bytes differ, the + /// file can't be read (or the caller's scope may not read it), or no digest of `path` was + /// taken. `wake` runs once the answer is sent, so a frame collects it. `None` here when no + /// thread starts. + pub(crate) fn check(&self, key: u64, path: &Path, wake: Wake) -> Option>> { + let pending = lock(&self.state).pending.remove(&key); + let state = Arc::clone(&self.state); + let path = path.to_path_buf(); + let scope = ScopeHandle::capture_now(); + let (send, answer) = mpsc::channel(); + let work = move || { + if let Some(handle) = pending { + // A digest thread that panicked recorded nothing. + let _ = handle.join(); + } + let same = if readable(scope, &path) { unchanged(&state, key, &path) } else { None }; + // The caller may be gone (its document closed): the answer is dropped. + let _ = send.send(same); + wake.wake(); + }; + std::thread::Builder::new().name("vectorcraft-file-check".into()).spawn(work).ok().map(|_| answer) + } + + /// Document `key` closed: its digest is dropped, and one still being taken is not recorded. + pub(crate) fn forget(&self, key: u64) { + let mut state = lock(&self.state); + state.versions.remove(&key); + state.pending.remove(&key); + let note = state.notes.entry(key).or_default(); + *note = note.wrapping_add(1); + } + + /// Drops closed documents' versions, pending handles and note counters only when needed. + /// Removing a note counter prevents its digest thread from recording a version later. + pub(crate) fn retain_open(&self, open: impl Iterator + Clone) { + let mut state = lock(&self.state); + let is_open = |key: &u64| open.clone().any(|uid| uid == *key); + if state.notes.keys().any(|key| !is_open(key)) { + state.versions.retain(|key, _| is_open(key)); + state.pending.retain(|key, _| is_open(key)); + state.notes.retain(|key, _| is_open(key)); + } + } +} + +/// May `scope`, the file-access scope of the call that started a thread, read `path`? +fn readable(scope: ScopeHandle, path: &Path) -> bool { + scope.run(|| file_access::check_read(&path.to_string_lossy()).is_ok()) +} + +/// [`SavedContents::check`]'s answer, on its thread. +fn unchanged(state: &Mutex, key: u64, path: &Path) -> Option { + let version = lock(state).versions.get(&key).filter(|v| v.path == path).cloned()?; + let now = FileStamp::at(path)?; + if now.len() != version.stamp.len() || digest_of(File::open(path).ok()?, now)? != version.digest || FileStamp::at(path) != Some(now) { + return None; + } + if let Some(v) = lock(state).versions.get_mut(&key).filter(|v| v.digest == version.digest) { + v.stamp = now; + } + Some(now) +} + +/// The digest of `file`, read while its full stamp stays at `stamp`; `None` when the stamp +/// differs or the file can't be read. A Unix change time alone can also signal changed bytes. +fn digest_of(mut file: File, stamp: FileStamp) -> Option<[u8; 32]> { + if !file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp) { + return None; + } + let mut hasher = Sha256::new(); + let mut buffer = vec![0u8; 64 * 1024]; + loop { + let n = file.read(&mut buffer).ok()?; + if n == 0 { + break; + } + hasher.update(buffer.get(..n)?); + } + file.metadata().is_ok_and(|m| FileStamp::of(&m) == stamp).then(|| hasher.finalize().into()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retaining_open_documents_drops_closed_documents_state() { + let folder = crate::tests_folder::Folder::new("saved-contents-retain"); + let file = folder.file("document", b"saved contents"); + let path = Path::new(&file); + let stamp = FileStamp::at(path).unwrap(); + let contents = SavedContents::new(); + for uid in [1, 2] { + contents.note(uid, path, stamp); + assert!(contents.check(uid, path, Wake::none()).unwrap().recv().unwrap().is_some()); + } + // A third document closes while its digest handle is still retained. + contents.note(3, path, stamp); + contents.retain_open([2].into_iter()); + + { + let state = lock(&contents.state); + for uid in [1, 3] { + assert!(!state.versions.contains_key(&uid)); + assert!(!state.pending.contains_key(&uid)); + assert!(!state.notes.contains_key(&uid)); + } + } + assert!(contents.check(1, path, Wake::none()).unwrap().recv().unwrap().is_none()); + assert!(contents.check(3, path, Wake::none()).unwrap().recv().unwrap().is_none()); + assert!(contents.check(2, path, Wake::none()).unwrap().recv().unwrap().is_some()); + } + + /// A file in a folder the caller may write but not read is neither digested nor compared. + #[test] + fn a_file_the_callers_scope_may_not_read_is_not_read() { + let folder = crate::tests_folder::Folder::new("saved-contents-write-only"); + let file = folder.file("document", b"saved contents"); + let path = Path::new(&file); + let stamp = FileStamp::at(path).unwrap(); + let roots = file_access::AutomationRoots::new(&[], &[path.parent().unwrap()]).unwrap(); + let contents = SavedContents::new(); + + file_access::confine(roots.as_ref(), || contents.note(1, path, stamp)); + let noted_confined = contents.check(1, path, Wake::none()).unwrap().recv().unwrap(); + + contents.note(2, path, stamp); + let confined = file_access::confine(roots.as_ref(), || contents.check(2, path, Wake::none())).unwrap().recv().unwrap(); + let unconfined = contents.check(2, path, Wake::none()).unwrap().recv().unwrap(); + + assert!(noted_confined.is_none(), "no digest is taken of a file the scope may not read"); + assert!(confined.is_none(), "a comparison in a scope that may not read the file does not read it"); + assert!(unconfined.is_some(), "the digest taken outside that scope still compares"); + } +} diff --git a/crates/ui-egui/src/tests/save.rs b/crates/ui-egui/src/tests/save.rs index b1fa7cb347..8fb9c4446e 100644 --- a/crates/ui-egui/src/tests/save.rs +++ b/crates/ui-egui/src/tests/save.rs @@ -593,3 +593,327 @@ fn acknowledging_import_loss_does_not_overwrite_the_source_with_another_drawing( assert!(after_switch == saved, "drawing B must never overwrite A's file"); assert!(after_original != saved, "approval in drawing A must still save A"); } + +/// Puts `bytes` at `path` as a new file, as a cloud-sync folder puts a file back after uploading +/// it: the file gets a new inode and new change and modification times. +fn put_back(path: &str, bytes: &[u8]) { + let next = format!("{path}.sync"); + std::fs::write(&next, bytes).unwrap(); + std::fs::rename(&next, path).unwrap(); +} + +/// Once its baseline digest is recorded, Save writes without asking while the file holds the +/// bytes the app last read or wrote (#10734), and asks once they differ, even at the same length. +#[test] +fn save_asks_about_a_changed_file_only_when_its_bytes_changed() { + let d = dir("same-bytes"); + let path = d.join("a.vectorcraft").to_string_lossy().to_string(); + let mut writer = app(); + writer.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + rect(&mut writer); + writer.run("file.saveAs", json!({"path": path})).unwrap(); + crate::background::wait_all(&mut writer); + let mut app = app(); + io::open_path(&mut app, &path).unwrap(); + assert!(io::save::wait_for_contents(&app).is_some(), "the opened file's baseline is recorded before sync"); + + let saved = |app: &VectorcraftApp| vectorcraft_format::load(&std::fs::read(&path).unwrap()).unwrap().node_count() == objects(app); + // File › Save, once the file has been compared: did it ask? + let save = |app: &mut VectorcraftApp| { + rect(app); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + io::save::wait_for_checks(app); + crate::background::wait_all(app); + if !app.any_dialog_open() { + assert!(io::save::wait_for_contents(app).is_some(), "the written file's baseline is recorded before sync"); + } + app.any_dialog_open() + }; + + // Read from the file: the same bytes put back. + put_back(&path, &std::fs::read(&path).unwrap()); + assert!(!save(&mut app)); + assert!(saved(&app)); + + // Written by that save: the same bytes put back. + put_back(&path, &std::fs::read(&path).unwrap()); + assert!(!save(&mut app)); + assert!(saved(&app)); + + // Other bytes of the same length. + let mut other = std::fs::read(&path).unwrap(); + let last = other.last_mut().unwrap(); + *last ^= 0xff; + put_back(&path, &other); + assert!(save(&mut app), "asks whether to replace the file"); + assert_eq!(std::fs::read(&path).unwrap(), other, "nothing is written before the answer"); + let _ = std::fs::remove_dir_all(d); +} + +/// Opens a file saved by another app, with the file then put back (with other bytes of the same +/// length unless `same`), and one more object: File › Save compares the file before it writes. +fn opened_then_put_back(tag: &str, same: bool) -> (std::path::PathBuf, String, VectorcraftApp) { + let d = dir(tag); + let path = d.join("a.vectorcraft").to_string_lossy().to_string(); + let mut writer = app(); + writer.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + rect(&mut writer); + writer.run("file.saveAs", json!({"path": path})).unwrap(); + crate::background::wait_all(&mut writer); + let mut app = app(); + io::open_path(&mut app, &path).unwrap(); + assert!(io::save::wait_for_contents(&app).is_some(), "the opened file's baseline is recorded"); + let mut other = std::fs::read(&path).unwrap(); + if !same { + let last = other.last_mut().unwrap(); + *last ^= 0xff; + } + put_back(&path, &other); + rect(&mut app); + (d, path, app) +} + +/// A comparison that answers after the document took another file does not ask about the old one. +#[test] +fn a_comparison_for_a_file_the_document_no_longer_uses_asks_nothing() { + let (d, path, mut app) = opened_then_put_back("compare-retargeted", false); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + let other = d.join("b.vectorcraft").to_string_lossy().to_string(); + app.session.doc_mut().unwrap().path = Some(other.clone()); + let before = std::fs::read(&path).unwrap(); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + let asked = app.any_dialog_open(); + let pending = io::save::checks_pending(&app); + let after = std::fs::read(&path).unwrap(); + // The dropped save freed the flow: the next File › Save writes the new file. + let next = app.run("file.save", json!({})); + crate::background::wait_all(&mut app); + let wrote_new = std::path::Path::new(&other).exists(); + let _ = std::fs::remove_dir_all(d); + assert!(next.is_ok(), "the next save starts: {next:?}"); + assert!(wrote_new, "the next save writes the document's new file"); + assert!(!asked, "no changed-on-disk question about a file the document no longer uses"); + assert!(!pending, "the comparison is dropped"); + assert_eq!(after, before, "the old file is not written"); +} + +/// A comparison that answers while a dialog is open over another document waits for it to close, +/// so the save does not activate its own document under the dialog. +#[test] +fn a_comparison_waits_while_a_dialog_is_open_over_another_document() { + let (d, path, mut app) = opened_then_put_back("compare-under-dialog", true); + let before = std::fs::read(&path).unwrap(); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let prompt = craft::ui::dialog::StandardPrompt::changed_on_disk("other"); + app.dialogs().unwrap().with(|h| h.open(prompt)); + io::save::wait_for_answers(&mut app); + let ctx = egui::Context::default(); + io::save::pump(&mut app, &ctx); + let active = app.session.active_index(); + let pending = io::save::checks_pending(&app); + let unwritten = std::fs::read(&path).unwrap() == before; + // Once the dialog closes, the save goes on and writes the file. + answer_top(&mut app, false); + io::save::pump(&mut app, &ctx); + crate::background::wait_all(&mut app); + let written = std::fs::read(&path).unwrap() != before; + let _ = std::fs::remove_dir_all(d); + assert_eq!(active, Some(1), "the document under the dialog stays active"); + assert!(!pending, "no frames are asked for while the save waits for the dialog"); + assert!(unwritten, "nothing is written while the dialog is open"); + assert!(written, "the save finishes once the dialog closes"); +} + +/// A context whose first frames have run, so it asks for no more frames of its own. +fn settled() -> egui::Context { + let ctx = egui::Context::default(); + for _ in 0..10 { + if !ctx.has_requested_repaint() { + break; + } + ctx.run_ui(egui::RawInput::default(), |_| {}).textures_delta.clear(); + } + assert!(!ctx.has_requested_repaint(), "the context settled"); + ctx +} + +/// A save that waited for a dialog asks for a frame in the pass whose UI closes the dialog, since +/// its pump ran earlier in that pass and an idle app draws no other frame. +#[test] +fn a_comparison_held_by_a_dialog_asks_for_a_frame_once_the_dialog_closes() { + let (d, _path, mut app) = opened_then_put_back("compare-wake", true); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let prompt = craft::ui::dialog::StandardPrompt::changed_on_disk("other"); + app.dialogs().unwrap().with(|h| h.open(prompt)); + io::save::wait_for_answers(&mut app); + io::save::pump(&mut app, &egui::Context::default()); + let open = settled(); + io::save::after_ui(&mut app, &open); + let while_open = open.has_requested_repaint(); + // The dialog's own pump, which runs after the save's, takes its answer. + let id = open_dialogs(&app).pop().map(|d| d.id).expect("a dialog is open"); + let window = app.ui_ctx.clone().expect("a window context"); + app.dialogs().unwrap().with(|h| { + assert!(h.cancel_by_id(&window, id)); + let _ = h.take_by_id::(id); + }); + let closed = settled(); + io::save::after_ui(&mut app, &closed); + let after_close = closed.has_requested_repaint(); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + let _ = std::fs::remove_dir_all(d); + assert!(!while_open, "no frame is asked for while the dialog is open"); + assert!(after_close, "a frame is asked for once the dialog has closed"); +} + +/// A comparison that answers while a drag goes on in another document waits for the drag to end, +/// so making the save's document active does not cancel the drag. +#[test] +fn a_comparison_waits_while_a_drag_goes_on_in_another_document() { + let (d, path, mut app) = opened_then_put_back("compare-under-drag", true); + let before = std::fs::read(&path).unwrap(); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.begin_interaction("drag").unwrap(); + io::save::wait_for_answers(&mut app); + let ctx = egui::Context::default(); + io::save::pump(&mut app, &ctx); + let active = app.session.active_index(); + let dragging = app.session.active().is_some_and(|d| d.interaction.is_some()); + let unwritten = std::fs::read(&path).unwrap() == before; + // Once the drag ends, the save goes on and writes the file. + app.session.commit_interaction().unwrap(); + io::save::pump(&mut app, &ctx); + crate::background::wait_all(&mut app); + let written = std::fs::read(&path).unwrap() != before; + let _ = std::fs::remove_dir_all(d); + assert_eq!(active, Some(1), "the document with the drag stays active"); + assert!(dragging, "the drag is not canceled"); + assert!(unwritten, "nothing is written while the drag goes on"); + assert!(written, "the save finishes once the drag ends"); +} + +/// A comparison's thread asks for a frame once it answers: a save started from the UI comes after +/// that frame's repaint decision, and an idle app draws no other frame. +#[test] +fn a_comparison_asks_for_a_frame_once_it_answers() { + let (d, _path, mut app) = opened_then_put_back("compare-answer-wake", true); + let ctx = settled(); + app.ui_ctx = Some(ctx.clone()); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + io::save::wait_for_answers(&mut app); + let woke = ctx.has_requested_repaint(); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + let _ = std::fs::remove_dir_all(d); + assert!(woke, "the answer asks for a frame"); +} + +/// A comparison that answers while a dialog previews a change in the save's own document waits for +/// the preview to end, so the file never holds a change the dialog's Cancel takes back. +#[test] +fn a_comparison_waits_while_its_own_document_shows_a_preview() { + let (d, path, mut app) = opened_then_put_back("compare-own-preview", true); + let before = std::fs::read(&path).unwrap(); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.begin_interaction("Move").unwrap(); + io::save::wait_for_answers(&mut app); + let ctx = egui::Context::default(); + io::save::pump(&mut app, &ctx); + crate::background::wait_all(&mut app); + let unwritten = std::fs::read(&path).unwrap() == before; + let previewing = app.session.active().is_some_and(|d| d.interaction.is_some()); + // Once the preview is canceled, the save goes on and writes the file. + app.session.cancel_interaction().unwrap(); + io::save::pump(&mut app, &ctx); + crate::background::wait_all(&mut app); + let written = std::fs::read(&path).unwrap() != before; + let _ = std::fs::remove_dir_all(d); + assert!(previewing, "the preview stays open"); + assert!(unwritten, "nothing is written while the preview is shown"); + assert!(written, "the save finishes once the preview ends"); +} + +/// A save with an explicit path that ends while a comparison is pending drops the comparison: its +/// answer would ask about the file with no save left to apply the answer. +#[test] +fn a_save_that_ends_first_drops_the_pending_comparison() { + let (d, path, mut app) = opened_then_put_back("compare-overtaken", true); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.run("file.saveAs", json!({"path": path})).unwrap(); + crate::background::wait_all(&mut app); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + let asked = app.any_dialog_open(); + let pending = io::save::checks_pending(&app); + rect(&mut app); + let next = app.run("file.save", json!({})); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + let _ = std::fs::remove_dir_all(d); + assert!(!asked, "no changed-on-disk question without a save to answer it"); + assert!(!pending, "the comparison is dropped"); + assert!(next.is_ok(), "the next save starts: {next:?}"); +} + +/// A comparison that answers while a script runs waits for the script to end, since writing +/// activates the save's document and the engine refuses that while a script runs. +#[test] +fn a_comparison_waits_while_a_script_runs() { + let (d, path, mut app) = opened_then_put_back("compare-under-script", true); + let before = std::fs::read(&path).unwrap(); + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.session.execute("script.run", &json!({"source": "1", "name": "t.js"})).unwrap(); + io::save::wait_for_answers(&mut app); + let ctx = egui::Context::default(); + io::save::pump(&mut app, &ctx); + let running = app.session.script_running(); + let pending = io::save::checks_pending(&app); + let unwritten = std::fs::read(&path).unwrap() == before; + // Once the script ends, the save goes on and writes the file. + for _ in 0..10_000 { + if app.session.script_pump().is_some() { + break; + } + } + let ended = !app.session.script_running(); + io::save::pump(&mut app, &ctx); + crate::background::wait_all(&mut app); + let written = std::fs::read(&path).unwrap() != before; + let _ = std::fs::remove_dir_all(d); + assert!(running, "the script runs while the comparison answers"); + assert!(!pending, "no frames are asked for while the save waits for the script"); + assert!(unwritten, "nothing is written while the script runs"); + assert!(ended, "the script ended"); + assert!(written, "the save finishes once the script ends"); +} + +/// Close with Save waits while the save compares the document's file, then closes the document +/// once the save has written it. +#[test] +fn close_waits_while_its_save_compares_the_file() { + let (d, path, mut app) = opened_then_put_back("compare-close", true); + let before = std::fs::read(&path).unwrap(); + let uid = app.session.active().unwrap().uid; + assert_eq!(app.run("file.save", json!({})).unwrap()["pending"], "checkingFile"); + crate::unsaved::saving_for_test(&mut app, uid); + let ctx = egui::Context::default(); + crate::unsaved::pump(&mut app, &ctx); + let waiting = app.closing.is_some(); + let open = app.session.documents().len(); + io::save::wait_for_checks(&mut app); + crate::background::wait_all(&mut app); + crate::unsaved::pump(&mut app, &ctx); + let closed = app.session.documents().is_empty(); + let written = std::fs::read(&path).unwrap() != before; + let _ = std::fs::remove_dir_all(d); + assert!(waiting, "Close waits for the comparison"); + assert_eq!(open, 1, "the document stays open while its file is compared"); + assert!(written, "the save writes the file"); + assert!(closed, "the document closes once it is saved"); +} diff --git a/crates/ui-egui/src/unsaved.rs b/crates/ui-egui/src/unsaved.rs index 466413484f..5c1c8dbfd4 100644 --- a/crates/ui-egui/src/unsaved.rs +++ b/crates/ui-egui/src/unsaved.rs @@ -200,13 +200,14 @@ pub(crate) fn pump(app: &mut VectorcraftApp, ctx: &egui::Context) { } /// The save of document `uid` that a Save answer started and that waited on a later frame: once the -/// document is saved it closes and the operation goes on; while its dialog or write is still running -/// it waits; given up (its Save As cancelled) the document stays open and the operation stops. +/// document is saved it closes and the operation goes on; while its dialog, the comparison of its +/// file or its write is still running it waits; given up (its Save As cancelled) the document stays +/// open and the operation stops. fn finish_save(app: &mut VectorcraftApp, uid: u64) { let doc = app.session.documents().iter().find(|d| d.uid == uid); let saved = doc.is_none_or(|d| !d.is_dirty()); let asking = app.dialogs().is_some_and(|d| d.with(|h| !h.open_dialogs().is_empty())); - if !saved && (app.file_dialog_open() || asking || app.background.busy_with(uid)) { + if !saved && (app.file_dialog_open() || asking || app.background.busy_with(uid) || io::save::checking(app, uid)) { return; } let title = doc.map(|d| d.title()).unwrap_or_default(); @@ -291,6 +292,15 @@ pub(crate) fn ready_for_test(app: &mut VectorcraftApp) -> egui::Context { ctx } +/// Close of document `uid` answered with Save, and the save already started on its own (as the OK +/// of the import-loss question starts it): the operation waits for that save. +#[cfg(test)] +pub(crate) fn saving_for_test(app: &mut VectorcraftApp, uid: u64) { + let mut guard = CloseGuard::new(Then::Close.scope(), vec![uid]); + let _ = guard.answer(CloseAnswer::Save); + app.closing = Some(Closing { guard, front: None, then: Then::Close, saving: Some(uid) }); +} + #[cfg(test)] mod tests { use super::*;