From 994654bf0dd259148420080335613ef4e462bf42 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 14 Nov 2026 16:34:30 +0100 Subject: [PATCH 1/3] Variables: Apply Data Set alerts when a replacement file is missing (#14500) A Pixel Replacement value naming a file that does not exist now fails with the reference application's alert text, followed by the file's name. Nothing of the set is applied, but one history state that changes nothing is added. The app shows the alert (without the file name) after the dialog closes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/variables_cmds.rs | 23 ++- .../cmd/variables_cmds/missing_file_tests.rs | 161 ++++++++++++++++++ crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/app.rs | 3 + .../app/apply_data_set_missing_file_tests.rs | 52 ++++++ crates/ui-egui/src/app/commands.rs | 12 +- .../ui-egui/tests/it/variables_data_sets.rs | 8 + 7 files changed, 255 insertions(+), 6 deletions(-) create mode 100644 crates/engine/src/cmd/variables_cmds/missing_file_tests.rs create mode 100644 crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs diff --git a/crates/engine/src/cmd/variables_cmds.rs b/crates/engine/src/cmd/variables_cmds.rs index 15c5f20c33e..6013c8b7db8 100644 --- a/crates/engine/src/cmd/variables_cmds.rs +++ b/crates/engine/src/cmd/variables_cmds.rs @@ -219,7 +219,11 @@ fn replace_pixels(doc: &mut Document, layer: LayerId, path: &str, method: PixelM let fmt = doc.pixel_format(); // The path is stored in the document's data sets. let file = crate::doc_path::resolve(path).map_err(|why| crate::doc_path::refusal("the image", path, why))?; - let bytes = std::fs::read(&file).map_err(|e| EngineError::Other(format!("read `{path}`: {e}")))?; + let bytes = std::fs::read(&file).map_err(|e| match e.kind() { + // The reference application's alert; the error also names the file (#14500). + std::io::ErrorKind::NotFound => EngineError::Other(format!("{DATA_SET_FILE_MISSING} ({path})")), + _ => EngineError::Other(format!("read `{path}`: {e}")), + })?; let src = crate::file_cmds::import(path, &bytes)?; let img = crate::file_cmds::flattened(&src, fmt); let (iw, ih) = (src.size.width.max(1) as f64, src.size.height.max(1) as f64); @@ -285,7 +289,15 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { s.edit(&label, |_, _| Ok(()))?; return Err(EngineError::Other(DATA_SET_LAYER_LOCKED.into())); } - s.edit(&label, |doc, _| apply_to_doc(doc, &vars, &set))?; + match s.edit(&label, |doc, _| apply_to_doc(doc, &vars, &set)) { + // A missing replacement file applies nothing of the set (the edit is dropped whole), but + // the attempt is still a history state that changes nothing, as for a locked layer (#14500). + Err(EngineError::Other(m)) if m.starts_with(DATA_SET_FILE_MISSING) => { + s.edit(&label, |_, _| Ok(()))?; + return Err(EngineError::Other(m)); + } + r => r?, + } set_vars(s, |v| v.active = Some(idx))?; Ok(json!({"applied": set.name, "index": idx})) } @@ -294,6 +306,10 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result { /// under Lock All. pub const DATA_SET_LAYER_LOCKED: &str = "Could not apply data set because the layer is locked."; +/// The reference application's alert when a Pixel Replacement value names a file that does not +/// exist. The command's error starts with it and names the file in parentheses. +pub const DATA_SET_FILE_MISSING: &str = "Could not apply data set because the replacement file was not found."; + /// Whether `set` has a Text value for a type layer with its own Lock All. Visibility and Pixel /// Replacement values still apply to locked layers, as in the reference application; partial /// locks and a locked group were not measured and keep applying (#14499). @@ -595,3 +611,6 @@ mod import_enabled_tests; #[cfg(test)] mod locked_text_layer_tests; + +#[cfg(test)] +mod missing_file_tests; diff --git a/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs b/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs new file mode 100644 index 00000000000..87d78575ce1 --- /dev/null +++ b/crates/engine/src/cmd/variables_cmds/missing_file_tests.rs @@ -0,0 +1,161 @@ +//! #14500: Apply Data Set with a Pixel Replacement value naming a file that does not exist fails +//! with the reference application's alert, the error naming the file. Nothing of the set is +//! applied, but one history state that changes nothing is still added. A file that exists but +//! cannot be decoded keeps an error naming the file (not measured). + +use super::*; +use photocraft_doc::{Layer, TextLayer}; +use photocraft_geom::Rect; + +const APPLY: &str = "image.applyDataSet"; + +/// A document with a grey raster "photo", a red raster "badge" and a text layer "title", bound to +/// the variables `photo` (pixels), `showBadge` (visibility) and `headline` (text). +fn session() -> (Session, LayerId, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48})).unwrap(); + let (photo, badge, title) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut photo = Layer::raster("photo", fmt); + photo.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 64, 48), &photocraft_raster::from_rgba(&fmt, [0.5, 0.5, 0.5, 1.0])); + let mut badge = Layer::raster("badge", fmt); + badge.surface_mut().unwrap().fill_rect(Rect::new(0, 0, 10, 10), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let title = Layer::new("title", LayerContent::Text(TextLayer { text: "Old".into(), ..Default::default() })); + let ids = (photo.id, badge.id, title.id); + doc.layers.extend([photo, badge, title]); + Ok(ids) + }) + .unwrap(); + s.execute( + "image.variables.define", + json!({"defs": [ + {"name": "photo", "layer": photo.0, "type": "pixelReplacement", "method": "conform"}, + {"name": "showBadge", "layer": badge.0, "type": "visibility"}, + {"name": "headline", "layer": title.0, "type": "textReplacement"}, + ]}), + ) + .unwrap(); + (s, photo, badge, title) +} + +/// A fresh scratch folder for one test. +fn scratch(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("pc-vars-{}-missing-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// The set "Two": hides the badge, replaces the headline and the photo with `png`. +fn set_two(s: &mut Session, png: &str) { + s.execute( + "image.variables.dataSets", + json!({"dataSets": [{"name": "Two", "values": [ + {"variable": "showBadge", "kind": "visibility", "value": false}, + {"variable": "headline", "kind": "text", "value": "New"}, + {"variable": "photo", "kind": "pixels", "value": png}, + ]}]}), + ) + .unwrap(); +} + +fn doc(s: &Session) -> &Document { + &s.active().unwrap().doc +} + +fn text_of(s: &Session, id: LayerId) -> String { + match &doc(s).layer(id).unwrap().content { + LayerContent::Text(t) => t.text.clone(), + _ => panic!("not a text layer"), + } +} + +fn history(s: &Session) -> (usize, Option) { + let h = &s.active().unwrap().history; + (h.past_len(), h.entries().last().map(|e| e.to_string())) +} + +#[test] +fn a_missing_replacement_file_fails_with_the_alert_text_and_names_the_file() { + let (mut s, ..) = session(); + let dir = scratch("text"); + let png = dir.join("renamed.png").to_string_lossy().into_owned(); + set_two(&mut s, &png); + + let r = s.execute(APPLY, json!({"name": "Two"})); + let Err(EngineError::Other(m)) = &r else { panic!("{r:?}") }; + assert_eq!(DATA_SET_FILE_MISSING, "Could not apply data set because the replacement file was not found."); + assert!(m.starts_with(DATA_SET_FILE_MISSING), "{m}"); + assert!(m.contains(&png), "the error names the file: {m}"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_missing_replacement_file_applies_nothing_but_adds_one_history_state() { + let (mut s, photo, badge, title) = session(); + let dir = scratch("nothing"); + set_two(&mut s, &dir.join("renamed.png").to_string_lossy()); + let before = doc(&s).clone(); + let (n, _) = history(&s); + + assert!(s.execute(APPLY, json!({"name": "Two"})).is_err()); + + // Nothing of the set: also not its valid Visibility and Text values. + assert!(doc(&s).layer(badge).unwrap().visible); + assert_eq!(text_of(&s, title), "Old"); + assert_eq!(doc(&s).layer(photo).unwrap().surface().unwrap().pixel(32, 24), before.layer(photo).unwrap().surface().unwrap().pixel(32, 24)); + assert_eq!(doc(&s).layers, before.layers); + assert_eq!(doc(&s).variables.active, None, "the set did not become the applied one"); + + // One history state for the attempt, which changes nothing. + let (after, label) = history(&s); + assert_eq!(after, n + 1); + assert!(label.as_deref().is_some_and(|l| l.starts_with("Apply Data Set")), "{label:?}"); + assert!(s.undo()); + assert_eq!(history(&s).0, n); + assert_eq!(doc(&s).layers, before.layers); + assert!(s.redo()); + assert_eq!(doc(&s).layers, before.layers, "the state changes nothing"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn a_file_that_cannot_be_decoded_keeps_an_error_naming_it_and_no_history_state() { + let (mut s, _photo, badge, _title) = session(); + let dir = scratch("garbage"); + let png = dir.join("broken.png"); + std::fs::write(&png, b"not an image at all").unwrap(); + let png = png.to_string_lossy().into_owned(); + set_two(&mut s, &png); + let (n, _) = history(&s); + + let r = s.execute(APPLY, json!({"name": "Two"})); + let Err(e) = &r else { panic!("{r:?}") }; + let m = e.to_string(); + assert!(!m.contains(DATA_SET_FILE_MISSING), "not the missing-file alert: {m}"); + assert!(m.contains("broken.png"), "the error names the file: {m}"); + assert!(doc(&s).layer(badge).unwrap().visible, "nothing applied"); + assert_eq!(history(&s).0, n, "today's behaviour: no history state"); + let _ = std::fs::remove_dir_all(dir); +} + +#[test] +fn the_same_set_applies_once_the_file_is_back() { + let (mut s, photo, badge, title) = session(); + let dir = scratch("back"); + let png = dir.join("blue.png"); + set_two(&mut s, &png.to_string_lossy()); + assert!(s.execute(APPLY, json!({"name": "Two"})).is_err()); + + let mut src = Session::new(); + src.execute("file.new", json!({"width": 8, "height": 8, "background": "#0000ff"})).unwrap(); + let bytes = photocraft_io::export(&src.active().unwrap().doc, "png", &photocraft_io::ExportOptions::default()).unwrap().bytes; + std::fs::write(&png, bytes).unwrap(); + s.execute(APPLY, json!({"name": "Two"})).unwrap(); + assert!(!doc(&s).layer(badge).unwrap().visible); + assert_eq!(text_of(&s, title), "New"); + assert_eq!(doc(&s).layer(photo).unwrap().surface().unwrap().pixel(32, 24), vec![0.0, 0.0, 1.0, 1.0]); + assert_eq!(doc(&s).variables.active, Some(0)); + let _ = std::fs::remove_dir_all(dir); +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8c770cd9b1b..58a740a4a54 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -45,7 +45,7 @@ pub mod select_mask_edits; pub mod shell_commands; pub mod shortcut_sets; pub mod snap; -pub use variables_cmds::{DATA_SET_LAYER_LOCKED, export_data_sets_with, import_data_sets_text}; +pub use variables_cmds::{DATA_SET_FILE_MISSING, DATA_SET_LAYER_LOCKED, 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/app.rs b/crates/ui-egui/src/app.rs index e35eda5b192..75f8d04f856 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -322,3 +322,6 @@ mod clipboard_tests; #[cfg(test)] mod apply_data_set_alert_tests; + +#[cfg(test)] +mod apply_data_set_missing_file_tests; diff --git a/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs new file mode 100644 index 00000000000..4d32ad8cb78 --- /dev/null +++ b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs @@ -0,0 +1,52 @@ +//! #14500: Apply Data Set with a missing replacement file closes the dialog and shows the +//! reference application's alert, which names no file; the status bar keeps the file's name. + +use super::*; +use serde_json::json; + +const MISSING: &str = "Could not apply data set because the replacement file was not found."; + +/// An app with a raster layer bound to a `photo` pixel variable and one data set `Two` whose +/// image is `missing.png` in a folder that has no such file. +fn app(name: &str) -> (PhotocraftApp, std::path::PathBuf) { + let dir = std::env::temp_dir().join(format!("pc-ui-vars-{}-{name}", std::process::id())); + let _ = std::fs::create_dir_all(&dir); + let png = dir.join("missing.png"); + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + app.session.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); + let id = app.session.execute("layer.new.layer", json!({})).unwrap()["layer"].clone(); + app.session.execute("image.variables.define", json!({"defs": [{"name": "photo", "layer": id, "type": "pixelReplacement"}]})).unwrap(); + app.session + .execute( + "image.variables.dataSets", + json!({"dataSets": [{"name": "Two", "values": [{"variable": "photo", "kind": "pixels", "value": png.to_string_lossy()}]}]}), + ) + .unwrap(); + app.sync_views(); + (app, png) +} + +fn alerts(app: &PhotocraftApp) -> Vec { + app.ui.dialogs.iter().filter(|d| d.kind == state::DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(String::from)).collect() +} + +#[test] +fn ok_in_the_apply_dialog_closes_it_and_shows_the_alert() { + let (mut app, png) = app("ok"); + crate::menus::invoke(&mut app, &egui::Context::default(), "image.applyDataSet", json!({})).unwrap(); + let dialog = app.ui.dialogs.last().unwrap().id; + assert!(crate::dialogs::confirm(&mut app, dialog).is_err()); + assert!(app.ui.dialogs.iter().all(|d| d.id != dialog), "the Apply Data Set dialog closed"); + assert_eq!(alerts(&app), [MISSING]); + assert!(app.ui.status.contains(&*png.to_string_lossy()), "the status names the file: {}", app.ui.status); + let _ = std::fs::remove_dir_all(png.parent().unwrap()); +} + +#[test] +fn the_command_shows_the_alert_without_the_file_name() { + let (mut app, png) = app("cmd"); + let e = app.run("image.applyDataSet", json!({"name": "Two"})).unwrap_err(); + assert!(e.starts_with(MISSING) && e.contains(&*png.to_string_lossy()), "{e}"); + assert_eq!(alerts(&app), [MISSING]); + let _ = std::fs::remove_dir_all(png.parent().unwrap()); +} diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index fe7281c182e..244a9e1fe23 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -213,9 +213,15 @@ impl PhotocraftApp { Err(e) => { self.ui.status = e.clone(); self.ui.status_error = true; - if id == "image.applyDataSet" && e == photocraft_engine::DATA_SET_LAYER_LOCKED { - // The reference application refuses a locked type layer with an alert (#14499). - let message = json!({"message": tl!(photocraft_engine::DATA_SET_LAYER_LOCKED)}); + // The reference application refuses a locked type layer (#14499) and a missing + // replacement file (#14500) with an alert; the alert names no layer or file. + let alert = [photocraft_engine::DATA_SET_LAYER_LOCKED, photocraft_engine::DATA_SET_FILE_MISSING] + .into_iter() + .find(|a| e == *a || e.strip_prefix(a).is_some_and(|rest| rest.starts_with(" ("))); + if id == "image.applyDataSet" + && let Some(alert) = alert + { + let message = json!({"message": tl!(alert)}); self.ui.open_dialog(state::DialogKind::Error, message.as_object().cloned().unwrap_or_default()); } } diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index aef56301991..8416231e108 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -327,6 +327,14 @@ fn failed_apply_can_be_corrected_without_retries_or_cancel_rollback() { h.get_by_label("Apply").click(); h.run_steps(3); assert!(h.state().ui.status.contains("missing.png"), "{}", h.state().ui.status); + // The missing file's alert opens on top (#14500); OK dismisses it. + let alert = h.state().ui.dialogs.last().unwrap(); + assert_eq!(alert.kind, DialogKind::Error); + assert_eq!(alert.fields["message"], json!("Could not apply data set because the replacement file was not found.")); + let alert = alert.id; + let _ = photocraft_ui_egui::dialogs::confirm(h.state_mut(), alert); + h.run_steps(3); + assert!(h.state().ui.dialogs.iter().all(|d| d.id != alert)); assert!(!h.state().ui.dialogs.last().unwrap().fields.contains_key("__apply")); assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0])); h.state_mut().ui.status.clear(); From 29af6689c70c121dc947195ed34d99f19d174133 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 16:13:14 +0100 Subject: [PATCH 2/3] Address CodeRabbit review: pin English in the data set alert test harness Co-Authored-By: Claude Opus 5.5 --- crates/ui-egui/tests/it/variables_data_sets.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index 8416231e108..ba123241b2d 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -68,6 +68,8 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, Harness<'static, Photocraf let path = dir.path().join("blue.png"); let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), photocraft_ui_egui::Services::default()); + // The alert assertions use English text; don't follow the system locale. + app.session.prefs.edit(|p| p.interface.language = "en".into()); app.run("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); let layer = app.session.active().unwrap().active_layer.unwrap(); photocraft_ui_egui::menus::invoke(&mut app, &egui::Context::default(), "image.variables.dataSets", json!({})).unwrap(); From e0113cb6187c1088fbf8d80f30926ce29c3964e0 Mon Sep 17 00:00:00 2001 From: David Mann Date: Thu, 19 Nov 2026 18:38:20 +0100 Subject: [PATCH 3/3] Address CodeRabbit review: missing-file alert tests use a fresh temp folder Each test gets its own tempfile folder that is removed when the test ends, also when an assertion fails, and the fixture checks that missing.png is absent before it builds the data set. Co-Authored-By: Claude Opus 5.5 --- .../app/apply_data_set_missing_file_tests.rs | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs index 5a1aa02a663..f36607d621b 100644 --- a/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs +++ b/crates/ui-egui/src/app/apply_data_set_missing_file_tests.rs @@ -7,11 +7,12 @@ use serde_json::json; const MISSING: &str = "Could not apply data set because the replacement file was not found."; /// An app with a raster layer bound to a `photo` pixel variable and one data set `Two` whose -/// image is `missing.png` in a folder that has no such file. -fn app(name: &str) -> (Box, std::path::PathBuf) { - let dir = std::env::temp_dir().join(format!("pc-ui-vars-{}-{name}", std::process::id())); - let _ = std::fs::create_dir_all(&dir); - let png = dir.join("missing.png"); +/// image is `missing.png` in a new, empty folder. The folder lives as long as the returned guard, +/// and is removed also when an assertion fails. +fn app() -> (Box, tempfile::TempDir, std::path::PathBuf) { + let dir = tempfile::tempdir().unwrap(); + let png = dir.path().join("missing.png"); + assert!(!png.exists()); let mut app = PhotocraftApp::new(Session::new(), Services::default()); app.session.execute("file.new", json!({"width": 16, "height": 16, "background": "white"})).unwrap(); let id = app.session.execute("layer.new.layer", json!({})).unwrap()["layer"].clone(); @@ -23,7 +24,7 @@ fn app(name: &str) -> (Box, std::path::PathBuf) { ) .unwrap(); app.sync_views(); - (app, png) + (app, dir, png) } /// The messages of the open framework alerts. @@ -33,7 +34,7 @@ fn alerts(app: &PhotocraftApp) -> Vec { #[test] fn ok_in_the_apply_dialog_closes_it_and_shows_the_alert() { - let (mut app, png) = app("ok"); + let (mut app, _dir, png) = app(); crate::menus::invoke(&mut app, &egui::Context::default(), "image.applyDataSet", json!({})).unwrap(); let dialog = app.top_dialog().expect("the Apply Data Set dialog is open"); // The hosted dialog reports the refusal through the status bar and the alert, not as OK's result. @@ -41,14 +42,12 @@ fn ok_in_the_apply_dialog_closes_it_and_shows_the_alert() { assert!(app.framework.dialogs.get_dyn(dialog).is_none(), "the Apply Data Set dialog closed"); assert_eq!(alerts(&app), [MISSING]); assert!(app.ui.status.contains(&*png.to_string_lossy()), "the status names the file: {}", app.ui.status); - let _ = std::fs::remove_dir_all(png.parent().unwrap()); } #[test] fn the_command_shows_the_alert_without_the_file_name() { - let (mut app, png) = app("cmd"); + let (mut app, _dir, png) = app(); let e = app.run("image.applyDataSet", json!({"name": "Two"})).unwrap_err(); assert!(e.starts_with(MISSING) && e.contains(&*png.to_string_lossy()), "{e}"); assert_eq!(alerts(&app), [MISSING]); - let _ = std::fs::remove_dir_all(png.parent().unwrap()); }