Closing: answers hold for the document state they were given for

Quit's Don't Save deleted recovery files at once, so a later Cancel left the
presentation open with nothing to recover; recovery now goes when the Quit
commits. A presentation changed while Quit's questions were open (a script)
is asked about before the window closes, and one still in its answered state
is not asked again. Close on the web no longer closes a presentation edited
after its download started.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dylan M. Taylor
2026-11-30 16:54:06 +00:00
co-authored by Claude Opus 5.5
parent 6f80bf8bcb
commit f22922ec5a
+150 -13
View File
@@ -1,8 +1,11 @@
//! Coordinates document save questions with the root window's close decision.
use std::sync::Arc;
use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep};
use craft::ui::dialog::{DialogHost, DialogId, StackDialog, UnsavedChangesDialog};
use craft::ui::runtime::windows::{WindowAction, WindowHost};
use deckcraft_model::Presentation;
use egui::{Context, ViewportId};
use serde_json::json;
@@ -54,6 +57,7 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
step = match step {
GuardStep::Save(uid) => {
closing.pending_uid = Some(uid);
closing.pending_snapshot = live_snapshot(app, uid);
app.dialogs.closing = Some(closing);
let outcome = app.save_document(uid);
app.save_settled(uid, outcome);
@@ -64,14 +68,13 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
next
}
GuardStep::Discard(uid) => {
let result = if closing.scope == CloseScope::Close {
close_document(app, uid)
} else if app.session.recovery_dir.is_some() {
app.session.execute("file.recovery.discard", &json!({"uid": uid})).map(|_| ()).map_err(|error| error.to_string())
} else {
Ok(())
};
if let Err(reason) = result {
if closing.scope != CloseScope::Close {
// Recovery stays until the Quit commits: a later Cancel keeps this presentation open.
if let Some(doc) = live_snapshot(app, uid) {
closing.answered.push(Answered { uid, doc, discard: true });
}
closing.guard.discarded()
} else if let Err(reason) = close_document(app, uid) {
app.set_status(reason);
closing.guard.save_failed()
} else {
@@ -100,6 +103,27 @@ pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) {
if closing.scope != CloseScope::Quit {
return;
}
// A presentation changed while the questions were open (a script, another window) gets its own
// question; one still in the state it was answered for is not asked again.
let unanswered: Vec<u64> = app
.session
.documents()
.iter()
.filter(|doc| doc.is_dirty() && !closing.answered.iter().any(|a| a.uid == doc.uid && Arc::ptr_eq(&a.doc, &doc.doc)))
.map(|doc| doc.uid)
.collect();
if !unanswered.is_empty() {
closing.guard = CloseGuard::new(CloseScope::Quit, unanswered);
step = closing.guard.current().copied().map_or(GuardStep::Finished, GuardStep::Ask);
continue;
}
if app.session.recovery_dir.is_some() {
for uid in closing.answered.iter().filter(|a| a.discard).map(|a| a.uid) {
if let Err(error) = app.session.execute("file.recovery.discard", &json!({"uid": uid})) {
app.set_status(error.to_string());
}
}
}
// Retain permission after issuing Close, without issuing it again next pass.
closing.asked = true;
app.dialogs.closing = Some(closing);
@@ -117,8 +141,20 @@ pub(crate) struct Closing {
scope: CloseScope,
asked: bool,
pending_uid: Option<u64>,
/// The document state the pending save serialized: its outcome covers that state, not a later edit.
pending_snapshot: Option<Arc<Presentation>>,
completion: Option<(u64, SaveOutcome)>,
reason: Option<String>,
/// Quit's settled answers, each for the document state it was given for.
answered: Vec<Answered>,
}
/// A Quit answer that lets a document close while it stays in the answered state.
struct Answered {
uid: u64,
doc: Arc<Presentation>,
/// Don't Save: its recovery files go when the Quit commits.
discard: bool,
}
impl SlideApp {
@@ -129,8 +165,16 @@ impl SlideApp {
return;
}
self.show = None;
self.dialogs.closing =
Some(Closing { guard: CloseGuard::new(scope, uids), scope, asked: false, pending_uid: None, completion: None, reason: None });
self.dialogs.closing = Some(Closing {
guard: CloseGuard::new(scope, uids),
scope,
asked: false,
pending_uid: None,
pending_snapshot: None,
completion: None,
reason: None,
answered: Vec::new(),
});
}
/// Whether clean documents or a completed, uncancelled Quit guard allow the window to close.
@@ -156,11 +200,12 @@ impl Closing {
fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardStep<u64>> {
let (uid, outcome) = closing.completion.take()?;
closing.pending_uid = None;
let snapshot = closing.pending_snapshot.take();
Some(match outcome {
SaveOutcome::Saved | SaveOutcome::Downloaded => {
let doc = app.session.documents().iter().find(|doc| doc.uid == uid);
if matches!(outcome, SaveOutcome::Saved) && doc.is_some_and(|doc| doc.is_dirty()) {
// Saved refers to the serialized snapshot; a later edit still needs an answer.
let live = live_snapshot(app, uid);
if live.as_ref().is_some_and(|live| snapshot.as_ref().is_none_or(|snapshot| !Arc::ptr_eq(live, snapshot))) {
// The file or download holds the serialized snapshot; a later edit still needs an answer.
closing.guard.retry_after_failure()
} else if closing.scope == CloseScope::Close {
match close_document(app, uid) {
@@ -171,6 +216,9 @@ fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardSte
}
}
} else {
if let Some(doc) = live {
closing.answered.push(Answered { uid, doc, discard: false });
}
closing.guard.saved()
}
}
@@ -183,6 +231,11 @@ fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option<GuardSte
})
}
/// The document's current state, absent once it is closed.
fn live_snapshot(app: &SlideApp, uid: u64) -> Option<Arc<Presentation>> {
app.session.documents().iter().find(|doc| doc.uid == uid).map(|doc| doc.doc.clone())
}
fn close_document(app: &mut SlideApp, uid: u64) -> Result<(), String> {
let Some(index) = app.session.documents().iter().position(|doc| doc.uid == uid) else { return Ok(()) };
let previous = app.session.active().map(|doc| doc.uid);
@@ -263,6 +316,90 @@ mod tests {
assert_eq!(h.state_mut().close_decision(), CloseDecision::Close);
}
fn two_unsaved() -> (Session, Vec<u64>) {
let mut session = Session::new();
for title in ["First", "Second"] {
session.execute("file.new", &json!({})).unwrap();
session.execute("file.properties", &json!({"title": title})).unwrap();
}
let uids = session.documents().iter().map(|doc| doc.uid).collect();
(session, uids)
}
/// The bug this prevents: Don't Save for the first presentation deleted its recovery files at once, so a Cancel
/// for the second left it open with nothing to recover after a crash.
#[test]
fn a_cancelled_quit_keeps_the_recovery_of_a_presentation_answered_dont_save() {
let (mut session, uids) = two_unsaved();
let dir = std::env::temp_dir().join(format!("deckcraft-closing-recovery-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
session.recovery_dir = Some(dir.clone());
deckcraft_engine::recovery::save(&session, &dir).unwrap();
let recoverable = || deckcraft_engine::recovery::list(&dir).into_iter().map(|(uid, _)| uid).collect::<Vec<_>>();
let mut h = harness(session, Services::default());
h.state_mut().start_closing(CloseScope::Quit, uids.clone());
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
answer(&h, None);
h.run_steps(4);
assert!(recoverable().contains(&uids[0]), "the Quit was cancelled, so the presentation stays recoverable");
h.state_mut().start_closing(CloseScope::Quit, uids.clone());
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(h.state().quit_allowed());
assert!(!uids.iter().any(|uid| recoverable().contains(uid)), "a Quit that goes through discards what was not saved");
let _ = std::fs::remove_dir_all(&dir);
}
/// The bug this prevents: a presentation changed by a script while Quit's question about another one was open
/// closed with its changes, never asked about.
#[test]
fn a_presentation_changed_during_quit_is_asked_about() {
let (mut session, uids) = two_unsaved();
let second = session.documents()[1].doc.clone();
deckcraft_engine::cmd::file::mark_saved_snapshot(&mut session, uids[1], second, None).unwrap();
session.set_active(1);
let mut h = harness(session, Services::default());
h.state_mut().start_closing(CloseScope::Quit, vec![uids[0]]);
h.run_steps(4);
h.state_mut().session.execute("file.properties", &json!({"title": "Changed"})).unwrap();
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(!h.state().quit_allowed(), "the changed presentation has not been answered for");
assert_eq!(h.state().dialogs.closing.as_ref().unwrap().guard.current(), Some(&uids[1]));
answer(&h, Some(CloseAnswer::DontSave));
h.run_steps(4);
assert!(h.state().quit_allowed(), "the first answer still holds for the unchanged presentation");
}
/// The bug this prevents: Save in the Close question on the web closed the presentation when its download
/// finished, losing an edit made while the download was pending.
#[test]
fn a_download_does_not_close_a_presentation_edited_after_it_started() {
let files = Arc::new(craft::host::ScriptedFiles::held().in_browser());
let installed = files.clone();
let mut h = crate::test_harness::harness_with(Session::with_new(), Services::default(), egui_kittest::Harness::builder(), move |platform| {
platform.host = platform.host.with_files(installed)
});
h.state_mut().session.execute("slide.new", &json!({})).unwrap();
let uid = h.state().session.active().unwrap().uid;
h.state_mut().start_closing(CloseScope::Close, vec![uid]);
h.run_steps(4);
answer(&h, Some(CloseAnswer::Save));
h.run_steps(4);
let ticket = h.state().pending_files.last().expect("the download waits").ticket;
h.state_mut().session.execute("slide.new", &json!({})).unwrap();
files.answer_to(ticket, craft::host::Picked::Downloaded("Presentation.deckcraft".into()));
h.run_steps(4);
assert!(h.state().session.documents().iter().any(|doc| doc.uid == uid), "the later edit keeps the presentation open");
assert!(crate::dialogs::top_dialog(&h.ctx).is_some(), "the later edit is asked about");
}
/// The `close` dialog key asks about the active presentation alone, and only when it has unsaved changes.
#[test]
fn the_close_key_asks_about_the_active_unsaved_presentation() {