diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 34455d56222..8ec269bb4b1 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -334,10 +334,23 @@ impl Headless { _ => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())), }; let mut outputs = workspace.export_sequence(dir)?; - let written = photocraft_engine::export_data_sets_with(&this.session, params, |name, bytes| { + let report = photocraft_engine::export_data_sets_report_with(&this.session, params, |name, bytes| { outputs.write(name, bytes).map_err(|e| photocraft_engine::EngineError::Other(e.to_string())) }); - exported(dir, written, &mut outputs) + // The sets a missing replacement image left out or stopped at, as the command says (#13767). + let (written, report) = match report { + Ok(report) => (Ok(report.files.clone()), Some(report)), + Err(error) => (Err(error), None), + }; + let mut result = exported(dir, written, &mut outputs)?; + if let Some(report) = report { + let full = report.json(Vec::new()); + result["skipped"] = full["skipped"].clone(); + if let Some(stopped) = full.get("stopped") { + result["stopped"] = stopped.clone(); + } + } + Ok(result) }) } diff --git a/crates/engine-core/src/cmd/variables_cmds.rs b/crates/engine-core/src/cmd/variables_cmds.rs index 4fe4c3fccc5..ee3059fa6b0 100644 --- a/crates/engine-core/src/cmd/variables_cmds.rs +++ b/crates/engine-core/src/cmd/variables_cmds.rs @@ -465,22 +465,65 @@ fn split_csv(line: &str, delim: u8) -> Vec { } /// Apply each data set in turn and export the flattened document, restoring the original after. -/// `{dir, format?("png"), dataSets?[names]}` → `{files:[…],count}`. +/// `{dir, format?("png"), dataSets?[names], missingImage?, start?}` → `{files:[…],count,skipped,stopped?}`. fn export_as_files(s: &mut Session, p: &Value) -> Result { let dir = p.get("dir").and_then(Value::as_str).ok_or_else(|| bad("file.export.dataSetsAsFiles", "need `dir`"))?.to_string(); // The directory appears only once the batch has been planned, as it always did, so a batch // rejected for colliding names still leaves no directory behind. let mut made_dir = false; - let names = export_data_sets_with(s, p, |name, bytes| { + let report = export_data_sets_report_with(s, p, |name, bytes| { if !made_dir { std::fs::create_dir_all(&dir).map_err(|e| EngineError::Other(format!("mkdir `{dir}`: {e}")))?; made_dir = true; } crate::file_cmds::write_file(&format!("{dir}/{name}"), bytes) })?; - let files: Vec = names.iter().map(|name| format!("{dir}/{name}")).collect(); - let count = files.len(); - Ok(json!({"files": files, "count": count})) + let files: Vec = report.files.iter().map(|name| format!("{dir}/{name}")).collect(); + Ok(report.json(files)) +} + +/// What a data-set export with a `missingImage` mode does when a set's Pixel Replacement image +/// does not exist (#13767). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MissingImage { + /// The export ends with the missing-file error; the files written before it stay (the default). + Error, + /// The set is left out, listed in `skipped`, and the export goes on. + Skip, + /// The export ends without an error at that set; the result names it in `stopped`. + Stop, +} + +/// The data set a `missingImage: "stop"` export stopped at: its name, its 0-based position in the +/// batch (the `start` that resumes after it is `index + 1`), how many sets come after it and the +/// missing-file error it would have ended with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StoppedDataSet { + pub name: String, + pub index: usize, + pub remaining: usize, + pub error: String, +} + +/// What a data-set export did: the filenames written, in order, the sets left out for a missing +/// replacement image (`missingImage: "skip"`) and the set a `"stop"` export stopped at. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DataSetsExportReport { + pub files: Vec, + pub skipped: Vec, + pub stopped: Option, +} + +impl DataSetsExportReport { + /// The command's result, with `files` as the caller names them (joined to its folder). + pub fn json(&self, files: Vec) -> Value { + let count = files.len(); + let mut out = json!({"files": files, "count": count, "skipped": self.skipped}); + if let Some(stop) = &self.stopped { + out["stopped"] = json!({"name": stop.name, "index": stop.index, "remaining": stop.remaining, "error": stop.error}); + } + out + } } /// The bodies of `file.export.dataSetsAsFiles`, streamed to `write` as a single-component @@ -488,8 +531,30 @@ fn export_as_files(s: &mut Session, p: &Value) -> Result { /// so colliding names are rejected before any file is written, and automation writes exactly /// these bytes beneath its write root (#3216) — the two paths cannot drift. Returns the /// filenames written, in order. -pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { +pub fn export_data_sets_with(s: &Session, p: &Value, write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result> { + export_data_sets_report_with(s, p, write).map(|report| report.files) +} + +/// [`export_data_sets_with`] that also says which sets a missing replacement image left out or +/// stopped at (`missingImage`, #13767). `start` resumes a batch at that 0-based position: the +/// sets before it are not written, and `{index}` keeps counting from the first set. +pub fn export_data_sets_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let format = p.get("format").and_then(Value::as_str).unwrap_or("png"); + let missing = match p.get("missingImage") { + None | Some(Value::Null) => MissingImage::Error, + Some(v) => match v.as_str() { + Some("error") => MissingImage::Error, + Some("skip") => MissingImage::Skip, + Some("stop") => MissingImage::Stop, + _ => return Err(bad("file.export.dataSetsAsFiles", "`missingImage` must be \"error\", \"skip\" or \"stop\"")), + }, + }; + let start = match p.get("start") { + None | Some(Value::Null) => 0, + Some(v) => { + v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or_else(|| bad("file.export.dataSetsAsFiles", "`start` must be a whole number from 0"))? + } + }; let st = s.active().ok_or(EngineError::NoDocument)?; let original = st.doc.clone(); let vars = original.variables.clone(); @@ -498,6 +563,9 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, if sets.is_empty() { return Err(bad("file.export.dataSetsAsFiles", "no data sets to export")); } + if start >= sets.len() { + return Err(bad("file.export.dataSetsAsFiles", format!("`start` {start} is past the last of {} data sets", sets.len()))); + } // Judge every image path before anything is written, as Apply Data Set does. for set in &sets { authorize_pixel_paths(s, set)?; @@ -538,17 +606,30 @@ pub fn export_data_sets_with(s: &Session, p: &Value, mut write: impl FnMut(&str, } names.push(name); } - let mut written = Vec::new(); - for (set, name) in sets.iter().zip(&names) { + let mut report = DataSetsExportReport::default(); + for (n, (set, name)) in sets.iter().zip(&names).enumerate().skip(start) { let mut doc = (*original).clone(); - apply_to_doc(&mut doc, &vars, set)?; + match apply_to_doc(&mut doc, &vars, set) { + Ok(()) => {} + // Only a replacement file that does not exist: one that can't be read or decoded is + // still an error in every mode. + Err(EngineError::Other(m)) if missing != MissingImage::Error && m.starts_with(DATA_SET_FILE_MISSING) => { + if missing == MissingImage::Skip { + report.skipped.push(set.name.clone()); + continue; + } + report.stopped = Some(StoppedDataSet { name: set.name.clone(), index: n, remaining: sets.len() - n - 1, error: m }); + break; + } + Err(e) => return Err(e), + } // An untrusted session's PSD export embeds no file a linked smart object names. let opts = photocraft_io::ExportOptions { read_linked_files: s.authorize.is_none(), ..Default::default() }; let bytes = photocraft_io::export(&doc, format, &opts).map(|r| r.bytes).map_err(|e| EngineError::Other(format!("export `{}`: {e}", set.name)))?; write(name, &bytes)?; - written.push(name.clone()); + report.files.push(name.clone()); } - Ok(written) + Ok(report) } fn list(s: &mut Session) -> Result { @@ -612,7 +693,7 @@ pub fn specs() -> Vec { "file.export.dataSetsAsFiles", "Data Sets as Files…", &["File", "Export"], - "{dir, format?:png, dataSets?[names], naming?:\"{name}|{index}|{document}\"} → {files,count}: apply each data set and export the flattened document; colliding filenames are rejected before writing (include {index} to disambiguate)", + "{dir, format?:png, dataSets?[names], naming?:\"{name}|{index}|{document}\", missingImage?:error|skip|stop, start?:n} → {files,count,skipped,stopped?:{name,index,remaining,error}}: apply each data set and export the flattened document; colliding filenames are rejected before writing (include {index} to disambiguate). A set whose Pixel Replacement image does not exist ends the export with an error (missingImage error, the default), is left out and listed in `skipped` (skip), or ends the export without an error, named in `stopped` (stop); `start` resumes at that 0-based set, keeping {index}", has_data_sets, |s, p| export_as_files(s, p) ), diff --git a/crates/engine-core/src/lib.rs b/crates/engine-core/src/lib.rs index c58ebac5ae7..e063e016fb2 100644 --- a/crates/engine-core/src/lib.rs +++ b/crates/engine-core/src/lib.rs @@ -55,7 +55,10 @@ pub mod shortcut_sets; mod slots; pub mod snap; mod state; -pub use variables_cmds::{DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, data_set_preview, export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{ + DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, DataSetsExportReport, StoppedDataSet, data_set_preview, export_data_sets_report_with, export_data_sets_with, + import_data_sets_text, +}; pub use video_cmds::render_video_with; use std::sync::Arc; diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 62884471a45..4fda8e47948 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -138,6 +138,10 @@ pub(crate) mod params { ..ParamFamily::new(|key| key == "file.automate.batch", filter_dialog::run) }, ParamFamily { document: Some(file_info_document), ..ParamFamily::new(|key| key == "file.fileInfo", run_file_info) }, + ParamFamily { + cancel: Some(filter_dialog::cancel), + ..ParamFamily::new(|key| key == crate::view_cmds::dialogs::DATA_SETS, crate::view_cmds::dialogs::data_sets_run) + }, ParamFamily { cancel: Some(filter_dialog::cancel), ..ParamFamily::new(crate::view_cmds::dialogs::is_form, filter_dialog::run) }, crate::prefs_ui::PRESETS_FAMILY, crate::swatches_ui::SWATCH_NAME_FAMILY, @@ -449,6 +453,7 @@ pub(crate) const PROMPTS: &[PromptRow] = &[ preset_group_prompt::answer, open_prompt::answer_prompt, alerts::answer, + crate::view_cmds::dialogs::data_sets_answer, crate::jobs_ui::answer, crate::gpu_status::answer, crate::actions::library::answer, diff --git a/crates/ui-egui/src/export_data_sets_missing_image_tests.rs b/crates/ui-egui/src/export_data_sets_missing_image_tests.rs new file mode 100644 index 00000000000..9085ee0464a --- /dev/null +++ b/crates/ui-egui/src/export_data_sets_missing_image_tests.rs @@ -0,0 +1,198 @@ +//! #13767: File › Export › Data Sets as Files with a data set whose Pixel Replacement image is +//! missing. The form asks, naming the set, whether to export the remaining sets: Yes leaves that +//! set out and goes on (asking again at the next missing image), No stops with the files written +//! so far. A missing image in the last set keeps today's error (not measured). Agents get the same +//! choice without a prompt through the command's `missingImage` and `start` parameters, and the +//! result lists the sets left out (`skipped`) or stopped at (`stopped`). +use crate::PhotocraftApp; +use craft::ui::dialog::{DialogId, StandardPrompt}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +const EXPORT: &str = "file.export.dataSetsAsFiles"; + +/// A fresh scratch folder for one test, holding `ok.png` (a real image) and an `out` folder to come. +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("pc-13767-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + let png = photocraft_io::export(&s.active().unwrap().doc, "png", &Default::default()).unwrap().bytes; + std::fs::write(dir.join("ok.png"), png).unwrap(); + dir +} + +/// A document whose raster layer `photo` is bound to a Pixel Replacement variable, with one data +/// set per entry of `images` ("Data Set 1", …): `true` names `ok.png`, `false` a file that is not there. +fn app(dir: &Path, images: &[bool]) -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 16, "height": 16})).unwrap(); + app.run("layer.new.layer", json!({"name": "photo"})).unwrap(); + let layer = app.session.active().unwrap().active_layer.unwrap().0; + app.run("image.variables.define", json!({"defs": [{"name": "photo", "layer": layer, "type": "pixelReplacement"}]})).unwrap(); + let sets: Vec = images + .iter() + .enumerate() + .map(|(i, ok)| { + let file = if *ok { dir.join("ok.png") } else { dir.join(format!("missing-{}.png", i + 1)) }; + json!({"name": format!("Data Set {}", i + 1), "values": [{"variable": "photo", "kind": "pixels", "value": file}]}) + }) + .collect(); + app.run("image.variables.dataSets", json!({"dataSets": sets})).unwrap(); + app.sync_views(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +/// The files in `dir`, by name, sorted. +fn files(dir: &Path) -> Vec { + let mut names: Vec = std::fs::read_dir(dir).map(|r| r.map(|e| e.unwrap().file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + names.sort(); + names +} + +/// Opens the form through the menu and confirms it with `out` as the destination. +fn export_from_form(app: &mut PhotocraftApp, ctx: &egui::Context, out: &Path) { + let reply = crate::menus::invoke(app, ctx, EXPORT, json!({})).unwrap(); + let want = reply["dialog"].as_str().unwrap().to_owned(); + let dialog = app.framework.dialogs.open_dialogs().into_iter().map(|d| d.id).find(|d| d.value().to_string() == want).unwrap(); + app.framework.dialogs.set_json_field(ctx, dialog, "dir", json!(out)).unwrap(); + crate::dialogs::confirm(app, ctx, dialog).unwrap(); +} + +/// The open missing-image question and its message. +fn question(app: &PhotocraftApp) -> Option<(DialogId, String)> { + let id = crate::dialogs::alerts::prompt_tagged::(app)?; + let prompt = app.framework.dialogs.get::()?; + let host = app.framework.host(); + let buttons: Vec = prompt.shown_buttons(host).into_iter().map(|(_, label)| label).collect(); + Some((id, format!("{} | {} | {}", prompt.shown_title(host), prompt.shown_message(host), buttons.join(" / ")))) +} + +fn answer(app: &mut PhotocraftApp, ctx: &egui::Context, id: DialogId, yes: bool) { + if !yes { + app.framework.dialogs.set_json_field(ctx, id, "choice", json!("cancel")).unwrap(); + } + crate::dialogs::confirm(app, ctx, id).unwrap(); +} + +#[test] +fn the_form_asks_yes_no_naming_the_set_and_yes_exports_the_others() { + let dir = scratch("yes"); + let out = dir.join("out"); + let (mut app, ctx) = app(&dir, &[true, false, true]); + export_from_form(&mut app, &ctx, &out); + + let (id, message) = question(&app).expect("a missing image asks"); + assert!(message.contains("Data Set 2"), "{message}"); + assert_eq!(files(&out), ["Data_Set_1.png"], "the sets before it are written before the question"); + assert!(message.ends_with("| Yes / No"), "Yes and No: {message}"); + + answer(&mut app, &ctx, id, true); + assert!(question(&app).is_none()); + assert_eq!(files(&out), ["Data_Set_1.png", "Data_Set_3.png"], "Yes leaves set 2 out and writes set 3"); + assert!(app.ui.status.contains("Data Set 2") && !app.ui.status_error, "the status lists the skipped set: {}", app.ui.status); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn no_stops_with_the_files_written_so_far() { + let dir = scratch("no"); + let out = dir.join("out"); + let (mut app, ctx) = app(&dir, &[true, false, true]); + export_from_form(&mut app, &ctx, &out); + let (id, _) = question(&app).unwrap(); + answer(&mut app, &ctx, id, false); + assert!(question(&app).is_none()); + assert_eq!(files(&out), ["Data_Set_1.png"], "No writes nothing more"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn several_missing_images_in_a_row_ask_once_each_in_every_combination() { + for (answers, want) in + [(vec![true, true], vec!["Data_Set_1.png", "Data_Set_4.png"]), (vec![true, false], vec!["Data_Set_1.png"]), (vec![false], vec!["Data_Set_1.png"])] + { + let dir = scratch(&format!("row-{answers:?}").replace([' ', ',', '[', ']'], "")); + let out = dir.join("out"); + let (mut app, ctx) = app(&dir, &[true, false, false, true]); + export_from_form(&mut app, &ctx, &out); + let mut asked = Vec::new(); + for yes in &answers { + let (id, message) = question(&app).expect("asked"); + asked.push(message); + answer(&mut app, &ctx, id, *yes); + } + assert!(question(&app).is_none(), "{answers:?}: no further question"); + assert_eq!(files(&out), want, "{answers:?}"); + assert!(asked[0].contains("Data Set 2"), "{asked:?}"); + if let Some(second) = asked.get(1) { + assert!(second.contains("Data Set 3"), "{asked:?}"); + } + let _ = std::fs::remove_dir_all(dir); + } +} + +#[test] +fn a_missing_image_in_the_last_set_keeps_todays_error() { + let dir = scratch("last"); + let out = dir.join("out"); + let (mut app, ctx) = app(&dir, &[true, false]); + export_from_form(&mut app, &ctx, &out); + assert!(question(&app).is_none(), "not measured: no question for the last set"); + assert_eq!(files(&out), ["Data_Set_1.png"]); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_command_reports_skipped_and_stopped_sets_without_a_prompt() { + let dir = scratch("cmd"); + let (mut app, _) = app(&dir, &[true, false, true]); + let out = |n: &str| dir.join(n).to_string_lossy().into_owned(); + + // Default: today's error, after Data Set 1. + let e = app.run(EXPORT, json!({"dir": out("error")})).unwrap_err(); + assert!(e.starts_with(photocraft_engine::DATA_SET_FILE_MISSING), "{e}"); + assert_eq!(files(&dir.join("error")), ["Data_Set_1.png"]); + + let r = app.run(EXPORT, json!({"dir": out("skip"), "missingImage": "skip"})).unwrap(); + assert_eq!(r["skipped"], json!(["Data Set 2"])); + assert_eq!(r["count"], json!(2)); + assert!(r.get("stopped").is_none()); + assert_eq!(files(&dir.join("skip")), ["Data_Set_1.png", "Data_Set_3.png"]); + + let r = app.run(EXPORT, json!({"dir": out("stop"), "missingImage": "stop", "naming": "{index}"})).unwrap(); + assert_eq!(r["stopped"]["name"], json!("Data Set 2")); + assert_eq!(r["stopped"]["index"], json!(1)); + assert_eq!(r["stopped"]["remaining"], json!(1)); + assert!(r["stopped"]["error"].as_str().unwrap().starts_with(photocraft_engine::DATA_SET_FILE_MISSING)); + assert_eq!(r["skipped"], json!([])); + assert_eq!(files(&dir.join("stop")), ["001.png"]); + + // `start` resumes after the stop and keeps the numbering of the whole batch. + let r = app.run(EXPORT, json!({"dir": out("stop"), "missingImage": "stop", "naming": "{index}", "start": 2})).unwrap(); + assert_eq!(r["count"], json!(1)); + assert_eq!(files(&dir.join("stop")), ["001.png", "003.png"]); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn bad_missing_image_and_start_params_are_errors_not_panics() { + let dir = scratch("bad"); + let (mut app, _) = app(&dir, &[true, false]); + let out = dir.join("out").to_string_lossy().into_owned(); + for params in [ + json!({"dir": out, "missingImage": "maybe"}), + json!({"dir": out, "missingImage": 3}), + json!({"dir": out, "start": 2}), + json!({"dir": out, "start": -1}), + json!({"dir": out, "start": 1.5}), + json!({"dir": out, "start": "1"}), + json!({"dir": out, "start": u64::MAX}), + ] { + assert!(app.run(EXPORT, params.clone()).is_err(), "{params}"); + } + assert!(files(&dir.join("out")).is_empty(), "a refused batch writes nothing"); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7e6cc44d0c4..499201db99d 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1080,6 +1080,8 @@ mod artboards_to_pdf_reverse_tests; #[cfg(test)] mod browse_field_tests; #[cfg(test)] +mod export_data_sets_missing_image_tests; +#[cfg(test)] mod export_quality_tests; #[cfg(test)] mod select_and_mask_button_tests; diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 9a81a77de55..38a6eedd406 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -1076,6 +1076,89 @@ pub(crate) fn batch_check(app: &mut PhotocraftApp, result: &ParamResult) -> Resu Err(Label::from(message)) } +/// File › Export › Data Sets as Files (#13767). +pub(crate) const DATA_SETS: &str = "file.export.dataSetsAsFiles"; + +/// The Data Sets as Files form's OK: runs the export with `missingImage: "stop"`, so a data set +/// whose replacement image is missing asks whether to export the remaining sets. +pub(crate) fn data_sets_run(app: &mut PhotocraftApp, ctx: &egui::Context, mut result: ParamResult) { + result.fields.set("missingImage", FieldValue::Text("stop".into())); + let doc = app.session.active().map(|st| st.doc.id); + let params = crate::dialogs::filter_dialog::command_params(DATA_SETS, &result.fields); + match crate::dialogs::filter_dialog::run_command(app, ctx, DATA_SETS, result) { + Ok(reply) => data_sets_went_on(app, doc, params, Vec::new(), &reply), + Err(error) => crate::notices::error(app, error), + } +} + +/// The question a missing replacement image asks: the document, the export's parameters, the set +/// it stopped at and where the batch resumes, and the sets skipped so far. +pub(crate) struct DataSetsMissingImage { + pub(crate) doc: Option, + pub(crate) params: Value, + pub(crate) name: String, + pub(crate) resume: usize, + pub(crate) skipped: Vec, +} + +/// After one run of the export: a set it stopped at asks Yes / No, unless it was the last set +/// (not measured: today's error stands). A finished export lists the sets skipped in the status bar. +fn data_sets_went_on(app: &mut PhotocraftApp, doc: Option, params: Value, skipped: Vec, reply: &Value) { + let Some(stopped) = reply.get("stopped").filter(|s| s.is_object()) else { + if !skipped.is_empty() { + app.ui.status = crate::i18n::fmt(tl!("Data sets not exported (replacement file not found): {names}"), &[("names", &skipped.join(", "))]); + app.ui.status_error = false; + } + return; + }; + let name = stopped.get("name").and_then(Value::as_str).unwrap_or_default().to_owned(); + let index = stopped.get("index").and_then(Value::as_u64).and_then(|n| usize::try_from(n).ok()); + let remaining = stopped.get("remaining").and_then(Value::as_u64).unwrap_or(0); + let (Some(index), true) = (index, remaining > 0) else { + let error = stopped.get("error").and_then(Value::as_str).unwrap_or(photocraft_engine::DATA_SET_FILE_MISSING).to_owned(); + crate::notices::error(app, error); + return; + }; + let message = crate::i18n::fmt(tl!("“{name}” was not exported: its replacement file was not found. Export the remaining data sets?"), &[("name", &name)]); + let tag = DataSetsMissingImage { doc, params, name, resume: index.saturating_add(1), skipped }; + let prompt = craft::ui::dialog::StandardPrompt::custom(message) + .title(tl!("Data Sets as Files")) + .icon(craft::behavior::IconId::new("info")) + .button(craft::ui::dialog::PromptChoice::Proceed, tl!("Yes")) + .button(craft::ui::dialog::PromptChoice::Cancel, tl!("No")) + .tag(tag); + if crate::dialogs::alerts::open_prompt(app, prompt).is_err() { + crate::dialogs::alerts::report_error(app, tl!("Data Sets as Files stopped: another question is open")); + } +} + +/// The `PROMPTS` entry of the missing-image question: Yes skips that set and exports the rest +/// (asking again at the next missing image), No stops with the files written so far. +pub(crate) fn data_sets_answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut craft::ui::dialog::PromptAnswer) -> bool { + let Some(mut pending) = answer.take_tag::() else { return false }; + pending.skipped.push(pending.name.clone()); + if answer.choice != craft::ui::dialog::PromptChoice::Proceed { + app.ui.status = crate::i18n::fmt(tl!("Data Sets as Files stopped at “{name}”"), &[("name", &pending.name)]); + app.ui.status_error = false; + return true; + } + let mut params = pending.params.clone(); + if let Some(map) = params.as_object_mut() { + map.insert("start".into(), json!(pending.resume)); + map.insert("missingImage".into(), json!("stop")); + } + let run = |app: &mut PhotocraftApp| app.run(DATA_SETS, params.clone()); + let outcome = match pending.doc { + Some(doc) => app.with_document(doc, run), + None => run(app), + }; + match outcome { + Ok(reply) => data_sets_went_on(app, pending.doc, pending.params, pending.skipped, &reply), + Err(error) => crate::notices::error(app, error), + } + true +} + #[cfg(test)] #[path = "batch_ok_validation_tests.rs"] mod batch_ok_validation_tests;