PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Save/Close: finish layered TIFF writes before discarding documents (#1723)
Harrison O'Connor-Hoover18bb712f4393
diff --git a/crates/ui-egui/src/discard_ui.rs b/crates/ui-egui/src/discard_ui.rsindex d20bae748..eddf2341d 100644--- a/crates/ui-egui/src/discard_ui.rs+++ b/crates/ui-egui/src/discard_ui.rs@@ -144,16 +144,13 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool {let ctx = ctx.clone();app.after_file_dialog(move |app, saved| {let saved = saved.map_err(couldnt_save)?;- // Still the prompt that asked (quitting may have replaced it meanwhile).- if app.discard.as_ref().and_then(|p| p.docs.first()) == Some(&doc) {- advance(app, &ctx);- }+ saved_document(app, &ctx, doc);Ok(saved)});return false;}match saved {- Ok(_) => true,+ Ok(_) => app.tiff_options.is_none(),// Backing out of the file dialog is the user's choice, not an error.Err(e) if e == crate::file_dialog::CANCELLED => false,Err(e) => {@@ -164,14 +161,26 @@ fn save(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) -> bool {}}+/// A completed save may release the close prompt. Choosing a path only starts a layered TIFF+/// save; TIFF Options calls this after the write. Copies and failed writes leave the doc dirty.+pub(crate) fn saved_document(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId) {+ // Still the prompt that asked (quitting may have replaced it meanwhile).+ if app.tiff_options.is_none()+ && app.discard.as_ref().and_then(|p| p.docs.first()) == Some(&doc)+ && index_of(app, doc).is_some_and(|i| !app.session.documents()[i].is_dirty())+ {+ advance(app, ctx);+ }+}+/// A save failure as reported ("cancelled" stays as it is: it isn't reported).fn couldnt_save(e: String) -> String {if e == crate::file_dialog::CANCELLED { e } else { format!("Couldn't save: {e}") }}pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {- // Hidden while Save's file dialog is up; it's back if that is cancelled.- if app.file_dialog_open() {+ // Save can ask for a path and then TIFF Options. Wait for both; cancellation brings us back.+ if app.file_dialog_open() || app.tiff_options.is_some() {return;}let Some(p) = &app.discard else { return };@@ -525,6 +534,9 @@ mod tests {assert!(h.state().session.documents().is_empty());}+ #[path = "tiff_tests.rs"]+ mod tiff_tests;+/// One frame with the window's close button pressed; the commands the guard sent.fn window_close_commands(app: &mut PhotocraftApp) -> Vec<egui::ViewportCommand> {let mut info = egui::ViewportInfo::default();diff --git a/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rsnew file mode 100644index 000000000..78dc06310--- /dev/null+++ b/crates/ui-egui/src/discard_ui/tests/tiff_tests.rs@@ -0,0 +1,155 @@+//! The two-modal save/close workflow, including the writer's success/failure boundary.+use super::*;+use crate::{FileDialogAnswer, tiff_options_ui};+use egui_kittest::kittest::Queryable;+use std::{cell::RefCell, rc::Rc};++type Writes = Rc<RefCell<Vec<(String, Vec<u8>)>>>;++fn tiff_prompt(command: &str) -> (Prompted, Writes, DocId, DocId) {+ let mut app = app_with_docs(2);+ make_dirty(&mut app, 0);+ let (saved, other) = (doc_id(&app, 0), doc_id(&app, 1));+ app.session.active_mut().unwrap().path = Some("original.tif".into());+ let writes: Writes = Rc::default();+ let written = writes.clone();+ app.services.file_dialog = Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo("kept.tif".into()))]).0);+ app.services.export = Some(Box::new(move |doc, _, settings| Ok((serde_json::to_vec(&(doc.id, settings.tiff_layers)).unwrap(), Vec::new()))));+ app.services.write = Some(Box::new(move |path, bytes| {+ written.borrow_mut().push((path.to_string(), bytes.to_vec()));+ Ok(())+ }));+ let builder = egui_kittest::Harness::builder().with_size(egui::vec2(800.0, 600.0));+ let builder = if std::env::var_os("PHOTOCRAFT_TIFF_SNAPSHOTS").is_some() { builder.wgpu() } else { builder };+ let mut h = builder.build_ui_state(+ |ui, app| {+ show(app, ui.ctx());+ tiff_options_ui::show(app, ui.ctx());+ app.poll_file_dialog(ui.ctx(), None);+ },+ app,+ );+ PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);+ h.ctx.set_os(egui::os::OperatingSystem::Windows);+ assert!(intercept(h.state_mut(), command, &Value::Null));+ h.run_steps(2);+ (h, writes, saved, other)+}++fn capture(h: &mut Prompted, name: &str) {+ if let Some(dir) = std::env::var_os("PHOTOCRAFT_TIFF_SNAPSHOTS") {+ let dir = std::path::PathBuf::from(dir);+ std::fs::create_dir_all(&dir).unwrap();+ h.render().unwrap().save(dir.join(format!("{name}.png"))).unwrap();+ }+}++#[test]+fn closing_after_tiff_save_waits_for_options_and_writes_the_requested_document() {+ for command in ["file.close", "file.closeAll", EXIT] {+ let (mut h, writes, saved, other) = tiff_prompt(command);+ capture(&mut h, "01-unsaved");+ h.key_press(Key::Y);+ h.run_steps(3);+ capture(&mut h, "02-tiff-options");+ assert!(h.state().tiff_options.is_some());+ assert_eq!(h.state().session.documents().len(), 2, "nothing closes before TIFF Options saves");+ assert_eq!(docs_left(&h), Some(1));+ assert!(!h.state().allow_close);+ assert!(writes.borrow().is_empty());+ assert!(h.query_by_label("(Y)es").is_none(), "the close prompt waits behind TIFF Options");+ // Another window or a control request can change the active tab while the modal is up.+ h.state_mut().refocus(other).unwrap();+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert_eq!(writes.borrow().as_slice(), &[("kept.tif".into(), serde_json::to_vec(&(saved, true)).unwrap())]);+ assert!(h.state().discard.is_none());+ assert!(h.state().tiff_options.is_none());+ match command {+ EXIT => assert!(h.state().allow_close),+ "file.closeAll" => assert!(h.state().session.documents().is_empty()),+ _ => {+ assert_eq!(h.state().session.documents().len(), 1);+ assert_eq!(doc_id(h.state(), 0), other);+ }+ }+ }+}++#[test]+fn cancelling_failing_or_copying_a_tiff_keeps_the_original_unsaved() {+ for outcome in ["cancel", "export error", "write error", "copy"] {+ let (mut h, writes, saved, _) = tiff_prompt("file.close");+ h.key_press(Key::Y);+ h.run_steps(3);+ match outcome {+ "export error" => h.state_mut().services.export = Some(Box::new(|_, _, _| Err("cannot encode".into()))),+ "write error" => h.state_mut().services.write = Some(Box::new(|_, _| Err("disk full".into()))),+ "copy" => {+ h.get_by_label("Discard Layers and Save a Copy").click();+ h.run_steps(2);+ }+ _ => {}+ }+ h.key_press(if outcome == "cancel" { Key::Escape } else { Key::Enter });+ h.run_steps(3);+ if outcome == "cancel" {+ capture(&mut h, "03-cancelled");+ }+ assert!(h.state().tiff_options.is_none());+ assert_eq!(h.state().session.documents().len(), 2, "{outcome}");+ assert_eq!(docs_left(&h), Some(1), "{outcome}");+ assert!(h.query_by_label("(Y)es").is_some());+ let original = &h.state().session.documents()[0];+ assert!(original.is_dirty());+ assert_eq!(original.path.as_deref(), Some("original.tif"));+ if outcome == "copy" {+ assert_eq!(writes.borrow().as_slice(), &[("kept.tif".into(), serde_json::to_vec(&(saved, false)).unwrap())]);+ } else {+ assert!(writes.borrow().is_empty());+ }+ if outcome.ends_with("error") {+ assert!(h.state().ui.status_error);+ }+ }+}++#[test]+fn tiff_options_cannot_be_replaced_or_retarget_a_closed_document() {+ let (mut h, writes, _, other) = tiff_prompt("file.close");+ h.key_press(Key::Y);+ h.run_steps(3);+ assert!(h.state_mut().save_as(Some("replacement.tif".into())).is_err());+ assert_eq!(h.state().tiff_options.as_ref().unwrap().path, "kept.tif");+ // A direct engine command bypasses the UI close guard. Never fall through to the next tab.+ h.state_mut().run("file.close", json!({"document": 0})).unwrap();+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert!(writes.borrow().is_empty());+ assert_eq!(h.state().session.documents().len(), 1);+ assert_eq!(doc_id(h.state(), 0), other);+ assert!(h.state().ui.status_error);+}++#[test]+fn close_all_waits_for_each_layered_tiff_write() {+ let (mut h, writes, first, second) = tiff_prompt("file.closeAll");+ make_dirty(h.state_mut(), 1);+ // Rebuild the prompt after making the second document dirty.+ h.state_mut().discard = None;+ assert!(intercept(h.state_mut(), "file.closeAll", &Value::Null));+ h.state_mut().services.file_dialog =+ Some(crate::file_dialog::fake(vec![Some(FileDialogAnswer::SaveTo("first.tif".into())), Some(FileDialogAnswer::SaveTo("second.tif".into()))]).0);+ for (i, doc) in [first, second].into_iter().enumerate() {+ h.key_press(Key::Y);+ h.run_steps(3);+ assert_eq!(h.state().session.documents().len(), 2);+ assert_eq!(writes.borrow().len(), i);+ assert_eq!(docs_left(&h), Some(2 - i));+ h.key_press(Key::Enter);+ h.run_steps(3);+ assert_eq!(writes.borrow()[i].1, serde_json::to_vec(&(doc, true)).unwrap());+ }+ assert!(h.state().session.documents().is_empty());+ assert!(h.state().discard.is_none());+}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 9910e4e6e..7d4f994ac 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -885,6 +885,9 @@ impl PhotocraftApp {/// continues on a later frame, see `file_dialog`). Returns `{"path", "warnings"}` (the export/// warnings are also shown to the user).pub fn save_as(&mut self, path: Option<String>) -> Result<Value, String> {+ if self.tiff_options.is_some() {+ return Err("Answer TIFF Options before starting another save".into());+ }// Edit Contents documents save back into their smart object.if path.is_none() && self.session.is_enabled("layer.smartObjects.saveContents") {self.run("layer.smartObjects.saveContents", serde_json::json!({}))?;@@ -915,28 +918,30 @@ impl PhotocraftApp {// A layered TIFF asks about its layers first (Preferences › File Handling); the save// continues from the prompt.if tiff_options_ui::wants_prompt(self, &path) {- tiff_options_ui::park(self, path.clone());+ tiff_options_ui::park(self, path.clone())?;return Ok(serde_json::json!({"path": path, "warnings": []}));}- let (path, warnings) = self.write_document(path, &ExportSettings::default())?;+ let (path, warnings) = self.write_document(path, &ExportSettings::default(), false)?;Ok(serde_json::json!({"path": path, "warnings": warnings}))}/// Encodes the active document with `settings` and writes it to `path`, which becomes the- /// document's path. Returns the path and the export warnings (also shown to the user).- pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings) -> Result<(String, Vec<String>), String> {+ /// document's path unless saving a copy. A copy leaves the original's path and unsaved+ /// changes intact. Returns the path and the export warnings (also shown to the user).+ pub(crate) fn write_document(&mut self, path: String, settings: &ExportSettings, copy: bool) -> Result<(String, Vec<String>), String> {let st = self.session.active().ok_or("no document")?;let export = self.services.export.as_ref().ok_or("no exporter configured")?;let (bytes, warnings) = export(&st.doc, &path, settings)?;let write = self.services.write.as_mut().ok_or("no writer configured")?;write(&path, &bytes)?;- if let Some(st) = self.session.active_mut() {+ if !copy && let Some(st) = self.session.active_mut() {st.path = Some(path.clone());st.saved_revision = st.revision;}self.ui.status = format!("Saved {path}");// "Save Document" script events and File › Generate › Image Assets.- if let Some(i) = self.session.active_index()+ if !copy+ && let Some(i) = self.session.active_index()&& let Some(r) = photocraft_engine::automate_cmds::document_saved(&mut self.session, i){self.ui.status = format!("Saved {path}; {} image assets in {}", r["files"].as_array().map_or(0, Vec::len), r["dir"].as_str().unwrap_or(""));diff --git a/crates/ui-egui/src/tiff_options_ui.rs b/crates/ui-egui/src/tiff_options_ui.rsindex 550961e71..0d868db1d 100644--- a/crates/ui-egui/src/tiff_options_ui.rs+++ b/crates/ui-egui/src/tiff_options_ui.rs@@ -9,6 +9,8 @@ use crate::{ExportSettings, PhotocraftApp};/// A save waiting on the TIFF Options answer.pub struct Prompt {+ /// The document that requested the save, even if tabs change while this is open.+ doc: photocraft_doc::DocId,/// Where the document goes.pub path: String,/// "Discard Layers and Save a Copy".@@ -33,8 +35,10 @@ pub fn wants_prompt(app: &PhotocraftApp, path: &str) -> bool {}/// Parks the save behind the prompt.-pub fn park(app: &mut PhotocraftApp, path: String) {- app.tiff_options = Some(Prompt { path, discard_layers: false, dont_ask_again: false });+pub fn park(app: &mut PhotocraftApp, path: String) -> Result<(), String> {+ let doc = app.active_doc_id()?;+ app.tiff_options = Some(Prompt { doc, path, discard_layers: false, dont_ask_again: false });+ Ok(())}pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {@@ -61,15 +65,17 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {cancel |= modal.should_close();p.discard_layers = discard;p.dont_ask_again = dont_ask;- if ok || ctx.input(|i| i.key_pressed(egui::Key::Enter)) {+ if ok || ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)) {let Some(p) = app.tiff_options.take() else { return };if p.dont_ask_again {app.session.edit_prefs(|prefs| prefs.file_handling.ask_before_saving_layered_tiff = false);}let settings = ExportSettings { tiff_layers: !p.discard_layers, ..Default::default() };- if let Err(e) = app.write_document(p.path.clone(), &settings) {+ if let Err(e) = app.refocus(p.doc).and_then(|()| app.write_document(p.path, &settings, p.discard_layers)) {app.ui.status = crate::i18n::fmt(tl!("Save failed: {error}"), &[("error", &e)]);app.ui.status_error = true;+ } else if !p.discard_layers {+ crate::discard_ui::saved_document(app, ctx, p.doc);}} else if cancel {app.tiff_options = None;