mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-03 06:31:42 +01:00
This commit is contained in:
commit
7ea2c5bbb4
7 files changed
+266
-6
No files matched your search
@@ -222,7 +222,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);
|
||||
@@ -289,7 +293,15 @@ fn apply_data_set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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}))
|
||||
}
|
||||
@@ -317,6 +329,10 @@ pub fn data_set_preview(s: &Session, index: usize) -> Result<Document> {
|
||||
/// 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).
|
||||
@@ -626,5 +642,8 @@ mod import_enabled_tests;
|
||||
#[cfg(test)]
|
||||
mod locked_text_layer_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod missing_file_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_history_name_tests;
|
||||
@@ -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<String>) {
|
||||
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);
|
||||
}
|
||||
@@ -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, data_set_preview, export_data_sets_with, import_data_sets_text};
|
||||
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 video_cmds::render_video_with;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -340,3 +340,6 @@ mod clipboard_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_data_set_alert_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod apply_data_set_missing_file_tests;
|
||||
@@ -0,0 +1,53 @@
|
||||
//! #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 new, empty folder. The folder lives as long as the returned guard,
|
||||
/// and is removed also when an assertion fails.
|
||||
fn app() -> (Box<PhotocraftApp>, 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();
|
||||
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, dir, png)
|
||||
}
|
||||
|
||||
/// The messages of the open framework alerts.
|
||||
fn alerts(app: &PhotocraftApp) -> Vec<String> {
|
||||
app.framework.dialogs.open_dialogs().iter().filter_map(|d| d.fields.as_ref()?.get("message")?.as_str().map(String::from)).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ok_in_the_apply_dialog_closes_it_and_shows_the_alert() {
|
||||
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.
|
||||
let _ = crate::dialogs::testing::confirm(&mut app, dialog);
|
||||
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);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_command_shows_the_alert_without_the_file_name() {
|
||||
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]);
|
||||
}
|
||||
@@ -223,9 +223,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 _ = crate::dialogs::alerts::alert(self, 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 _ = crate::dialogs::alerts::alert(self, tl!(alert));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,6 +52,17 @@ fn inspect(h: &mut H, id: &str) -> Value {
|
||||
listed["result"]["dialogs"].as_array().into_iter().flatten().find(|d| d["id"] == json!(id)).map(|d| d["fields"].clone()).expect("the dialog is listed")
|
||||
}
|
||||
|
||||
/// The id of the open dialog whose message is `message`, as `ui.inspect` lists it.
|
||||
fn alert_id(h: &mut H, message: &str) -> Option<String> {
|
||||
let listed = control(h, "ui.inspect", json!({}));
|
||||
listed["result"]["dialogs"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.find(|d| d["fields"]["message"] == json!(message))
|
||||
.and_then(|d| d["id"].as_str().map(str::to_owned))
|
||||
}
|
||||
|
||||
fn confirm(h: &mut H, id: &str) {
|
||||
assert!(!refused(&control(h, "ui.dialog.confirm", json!({"dialog": id}))));
|
||||
h.run_steps(3);
|
||||
@@ -82,6 +93,8 @@ fn pixel_replacement_harness() -> (tempfile::TempDir, H, String) {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
photocraft_raster::spill::use_test_volume_space();
|
||||
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();
|
||||
let mut h = harness(app);
|
||||
@@ -149,6 +162,11 @@ 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 = alert_id(&mut h, "Could not apply data set because the replacement file was not found.").expect("the missing-file alert is open");
|
||||
confirm(&mut h, &alert);
|
||||
assert_eq!(alert_id(&mut h, "Could not apply data set because the replacement file was not found."), None);
|
||||
|
||||
assert_eq!(read_pixel(&mut h), json!([1.0, 1.0, 1.0, 1.0]));
|
||||
h.state_mut().ui.status.clear();
|
||||
h.run_steps(3);
|
||||
|
||||
Reference in new issue
Block a user