diff --git a/crates/ui-egui/src/dialogs/closing.rs b/crates/ui-egui/src/dialogs/closing.rs index ef84f1ba4..88f478b15 100644 --- a/crates/ui-egui/src/dialogs/closing.rs +++ b/crates/ui-egui/src/dialogs/closing.rs @@ -1,56 +1,265 @@ -/// Opens this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w5): dl.A10 -pub(crate) fn open( - app: &mut crate::SlideApp, - ctx: &egui::Context, - host: &mut craft::ui::dialog::DialogHost, - params: &serde_json::Value, -) -> Result, String> { - let _ = (app, ctx, host, params); - todo!("dl.A10") +//! Coordinates document save questions with the root window's close decision. + +use craft::quit::{CloseAnswer, CloseGuard, CloseScope, GuardStep}; +use craft::ui::dialog::{DialogHost, DialogId, StackDialog, UnsavedChangesDialog}; +use craft::ui::runtime::windows::{WindowAction, WindowHost}; +use egui::{Context, ViewportId}; +use serde_json::{Value, json}; + +use crate::SlideApp; +use crate::app::files::SaveOutcome; + +/// Opens the quit guard's current document question, if one is needed. +pub(crate) fn open(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost, _params: &Value) -> Result, String> { + let uids = app.session.documents().iter().filter(|doc| doc.is_dirty()).map(|doc| doc.uid).collect(); + app.start_closing(CloseScope::Quit, uids); + pump(app, ctx, host); + Ok(host.get::().map(StackDialog::id)) } -/// Advances this typed dialog in the host. -#[allow(dead_code)] // P3(dialogs-w5): dl.A10 -pub(crate) fn pump(app: &mut crate::SlideApp, ctx: &egui::Context, host: &mut craft::ui::dialog::DialogHost) { - let _ = (app, ctx, host); - todo!("dl.A10") +/// Advances closing from consumed dialog answers and terminal save completions. +pub(crate) fn pump(app: &mut SlideApp, ctx: &Context, host: &mut DialogHost) { + let answer = host.take::(); + let Some(mut closing) = app.dialogs.closing.take() else { return }; + if closing.asked && closing.guard.is_finished() { + app.dialogs.closing = Some(closing); + return; + } + let mut step = if closing.pending_uid.is_some() { + let Some(step) = completion_step(app, &mut closing) else { + app.dialogs.closing = Some(closing); + return; + }; + step + } else if closing.asked { + let Some(answer) = answer else { + app.dialogs.closing = Some(closing); + return; + }; + closing.asked = false; + match answer.ok() { + Some(answer) if answer.apply_to_all => closing.guard.answer_all(answer.answer), + Some(answer) => closing.guard.answer(answer.answer), + None => closing.guard.answer(CloseAnswer::Cancel), + } + } else { + closing.guard.current().copied().map_or(GuardStep::Finished, GuardStep::Ask) + }; + + loop { + step = match step { + GuardStep::Save(uid) => { + closing.pending_uid = Some(uid); + app.dialogs.closing = Some(closing); + let outcome = app.save_document(uid); + app.save_settled(uid, outcome); + let Some(mut waiting) = app.dialogs.closing.take() else { return }; + let next = completion_step(app, &mut waiting); + closing = waiting; + let Some(next) = next else { break }; + 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 { + app.set_status(reason); + closing.guard.save_failed() + } else { + closing.guard.discarded() + } + } + GuardStep::Ask(uid) => { + let Some(doc) = app.session.documents().iter().find(|doc| doc.uid == uid) else { + // An independently closed UID must never redirect the decision to another tab. + step = GuardStep::Discard(uid); + continue; + }; + let mut prompt = UnsavedChangesDialog::new(closing.scope, doc.title()) + .document_wording(true) + .remaining(closing.guard.remaining()) + .note("Your changes will be lost if you don't save them."); + if let Some(reason) = closing.reason.take() { + prompt = prompt.reason(reason); + } + host.open(prompt); + closing.asked = true; + break; + } + GuardStep::Cancelled => return, + GuardStep::Finished => { + if closing.scope != CloseScope::Quit { + return; + } + // Retain permission after issuing Close, without issuing it again next pass. + closing.asked = true; + app.dialogs.closing = Some(closing); + WindowHost::of(ctx).act(ViewportId::ROOT, WindowAction::Close); + return; + } + }; + } + app.dialogs.closing = Some(closing); } -/// The closing guard, its scope and prompt state. -#[allow(dead_code)] // P3(dialogs-w5): dl.A11 +/// The guard and the outstanding prompt or save that may advance it. pub(crate) struct Closing { - guard: craft::quit::CloseGuard, - scope: craft::quit::CloseScope, + guard: CloseGuard, + scope: CloseScope, asked: bool, pending_uid: Option, - completion: Option<(u64, super::super::app::files::SaveOutcome)>, + completion: Option<(u64, SaveOutcome)>, reason: Option, } -impl crate::SlideApp { - /// Starts the closing prompt for the named documents. - #[allow(dead_code)] // P3(dialogs-w5): dl.A11 - pub(crate) fn start_closing(&mut self, scope: craft::quit::CloseScope, uids: Vec) { - let _ = (scope, uids); - todo!("dl.A11") +impl SlideApp { + /// Starts closing the named documents without entering the dialog host's lock. + pub(crate) fn start_closing(&mut self, scope: CloseScope, uids: Vec) { + // A live question or file ticket belongs to its guard until it settles. + if self.dialogs.closing.as_ref().is_some_and(|closing| !closing.guard.is_finished()) { + return; + } + self.show = None; + self.dialogs.closing = Some(Closing { + guard: CloseGuard::new(scope, uids), + scope, + asked: false, + pending_uid: None, + completion: None, + reason: None, + }); } -} -impl crate::SlideApp { - /// Whether the closing guard allows quitting. - #[allow(dead_code)] // P3(dialogs-w5): dl.A11 + /// Whether clean documents or a completed, uncancelled Quit guard allow the window to close. pub(crate) fn quit_allowed(&self) -> bool { - todo!("dl.A11") + !self.session.documents().iter().any(|doc| doc.is_dirty()) + || self.dialogs.closing.as_ref().is_some_and(|closing| { + closing.scope == CloseScope::Quit && closing.guard.is_finished() && !closing.guard.is_cancelled() + }) } } impl Closing { - /// Records a terminal save outcome for the closing pump. - /// Pending outcomes do not settle a close. - #[allow(dead_code)] // P3(dialogs-w5): dl.A11 - pub(crate) fn settle(&mut self, uid: u64, outcome: crate::app::files::SaveOutcome) { - let _ = (uid, outcome); - todo!("dl.A11") + /// Records the matching save's terminal outcome once for the closing pump. + pub(crate) fn settle(&mut self, uid: u64, outcome: SaveOutcome) { + if self.pending_uid == Some(uid) && self.completion.is_none() && !matches!(outcome, SaveOutcome::Pending) { + self.completion = Some((uid, outcome)); + } + } +} + +fn completion_step(app: &mut SlideApp, closing: &mut Closing) -> Option> { + let (uid, outcome) = closing.completion.take()?; + closing.pending_uid = None; + 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. + closing.guard.retry_after_failure() + } else if closing.scope == CloseScope::Close { + match close_document(app, uid) { + Ok(()) => closing.guard.saved(), + Err(reason) => { + closing.reason = Some(reason); + closing.guard.retry_after_failure() + } + } + } else { + closing.guard.saved() + } + } + SaveOutcome::Failed(reason) => { + closing.reason = Some(reason); + closing.guard.retry_after_failure() + } + SaveOutcome::Cancelled => closing.guard.save_failed(), + SaveOutcome::Pending => return None, + }) +} + +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); + app.session.execute("window.next", &json!({"index": index})).map_err(|error| error.to_string())?; + let result = app.session.execute("file.close", &json!({})).map(|_| ()).map_err(|error| error.to_string()); + if let Some(index) = app.session.documents().iter().position(|doc| Some(doc.uid) == previous) { + app.session.execute("window.next", &json!({"index": index})).map_err(|error| error.to_string())?; + } + result +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use craft::ui::shell::embed::CloseDecision; + use deckcraft_engine::Session; + + use super::*; + use crate::Services; + use crate::test_harness::harness; + + /// Answers the open prompt through the host's programmatic answer, `None` being Cancel. + fn answer(h: &egui_kittest::Harness<'static, SlideApp>, answer: Option) { + let dialogs = craft::ui::shell::WindowDialogs::of(&h.ctx, &craft::ui::runtime::env::WindowKey::main()); + dialogs.with(|host| match answer { + Some(answer) => { + let id = host.stack().top().expect("a prompt is open"); + host.get_dyn_mut(id).and_then(|dialog| dialog.downcast_mut::()).expect("the prompt").set_answer(answer); + assert!(host.confirm::(&h.ctx)); + } + None => assert!(host.cancel::(&h.ctx)), + }); + } + + #[test] + fn a_quit_asks_for_each_unsaved_document_and_lets_the_window_close_only_after_the_last_answer() { + 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: Vec<_> = session.documents().iter().map(|doc| doc.uid).collect(); + let mut h = harness(session, Services::default()); + h.ctx.on_begin_pass( + "closing answer replay", + Arc::new(|ui| { + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("exercise closing across both passes"); + } + }), + ); + h.state_mut().start_closing(CloseScope::Quit, uids.clone()); + h.run_steps(4); + assert!(!h.state().quit_allowed()); + assert_eq!(h.state_mut().close_decision(), CloseDecision::Hold); + answer(&h, Some(CloseAnswer::DontSave)); + h.run_steps(4); + assert!(!h.state().quit_allowed()); + assert_eq!(h.state().dialogs.closing.as_ref().unwrap().guard.current(), uids.last()); + assert!(crate::dialogs::top_dialog(&h.ctx).is_some()); + answer(&h, None); + h.run_steps(4); + assert!(!h.state().quit_allowed()); + assert!(h.state().dialogs.closing.is_none()); + assert!(crate::dialogs::top_dialog(&h.ctx).is_none()); + assert_eq!(h.state().session.documents().iter().map(|doc| doc.uid).collect::>(), uids); + + h.state_mut().start_closing(CloseScope::Quit, uids); + h.run_steps(4); + answer(&h, Some(CloseAnswer::DontSave)); + h.run_steps(4); + assert!(!h.state().quit_allowed()); + answer(&h, Some(CloseAnswer::DontSave)); + h.run_steps(4); + assert!(h.state().quit_allowed()); + assert!(crate::dialogs::top_dialog(&h.ctx).is_none()); + assert_eq!(h.state_mut().close_decision(), CloseDecision::Close); } }