diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 8081a180dd..991e6c0fb1 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -624,9 +624,12 @@ fn doc_export_layers_writes_only_beneath_the_write_root() { std::fs::create_dir_all(&root).unwrap(); let mut h = Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&root), Some(&root)).unwrap()); h.handle("doc.new", json!({"width": 12, "height": 8, "background": "white", "name": "card"})).unwrap(); - h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); - let out = root.join("out"); + let refused = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy()})).unwrap_err().to_string(); + assert!(refused.contains("Layers to Files needs a document with multiple layers."), "{refused}"); + assert!(!out.exists() || std::fs::read_dir(&out).unwrap().next().is_none(), "the refusal wrote no files"); + + h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Badge"}})).unwrap(); let exported = h.handle("doc.exportLayers", json!({"dir": out.to_string_lossy(), "format": "png", "prefix": "card"})).unwrap(); assert_eq!(exported["count"].as_u64(), Some(2), "{exported}"); let mut names: Vec = std::fs::read_dir(&out).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect(); diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index b407e6e3fe..dffd1e59e7 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -546,16 +546,21 @@ async fn headless_doc_save_takes_maximize_compatibility() { async fn headless_doc_export_layers_takes_maximize_compatibility() { let dir = tmp("export-layers-maximize-compat"); let client = connect(headless_in(&dir)).await; - call(&client, "doc_new", json!({"width": 16, "height": 16, "background": "white", "name": "card"})).await; + json_of(&call(&client, "doc_new", json!({"width": 16, "height": 16, "background": "white", "name": "card"})).await); + json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Ink"}})).await); for (sub, params, real) in [("on", json!({"dir": "on", "format": "psd"}), true), ("off", json!({"dir": "off", "format": "psd", "maximizeCompatibility": false}), false)] { let result = json_of(&call(&client, "doc_export_layers", params.clone()).await); - assert_eq!(result["count"], 1, "{params}: {result}"); - let file = result["files"][0].as_str().unwrap(); - assert!(file.starts_with(sub), "{file}"); - let bytes = std::fs::read(dir.join(file)).unwrap(); - assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}"); + assert_eq!(result["count"], 2, "{params}: {result}"); + let files = result["files"].as_array().unwrap(); + assert_eq!(files.len(), 2, "{params}: {result}"); + for file in files { + let file = file.as_str().unwrap(); + assert!(file.starts_with(sub), "{file}"); + let bytes = std::fs::read(dir.join(file)).unwrap(); + assert_eq!(craft_psd::PsdFile::from_bytes(&bytes).unwrap().has_real_merged_data(), Some(real), "{params}: {file}"); + } } let r = call(&client, "doc_export_layers", json!({"dir": "bad", "format": "psd", "maximizeCompatibility": "no"})).await; assert_eq!(r.is_error, Some(true), "{}", text(&r)); @@ -924,10 +929,18 @@ async fn doc_exports_and_data_set_import_are_capability_scoped() { .await, ); - let layers = call(&client, "doc_export_layers", json!({"dir": "layers", "prefix": "card"})).await; + let params = json!({"dir": "layers", "prefix": "card"}); + let refused = call(&client, "doc_export_layers", params.clone()).await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert!(text(&refused).contains("Layers to Files needs a document with multiple layers."), "{}", text(&refused)); + let layers_dir = root.join("layers"); + assert!(!layers_dir.exists() || std::fs::read_dir(&layers_dir).unwrap().next().is_none()); + + json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Ink"}})).await); + let layers = call(&client, "doc_export_layers", params).await; assert_ne!(layers.is_error, Some(true), "{}", text(&layers)); - assert_eq!(json_of(&layers)["count"], 1, "{}", text(&layers)); - assert_eq!(std::fs::read_dir(root.join("layers")).unwrap().count(), 1); + assert_eq!(json_of(&layers)["count"], 2, "{}", text(&layers)); + assert_eq!(std::fs::read_dir(layers_dir).unwrap().count(), 2); let sets = call(&client, "doc_export_data_sets", json!({"dir": "sets", "format": "png"})).await; assert_ne!(sets.is_error, Some(true), "{}", text(&sets)); assert_eq!(json_of(&sets)["count"], 2, "{}", text(&sets)); diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index 1ef2885afd..d5d8209fc9 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -42,7 +42,7 @@ pub use batch_run::{BatchInput, OutputClaims, encode_batch_error_log, list_image #[cfg(test)] pub(crate) use batch_run::{MAX_SUBFOLDER_DEPTH, list_files_tree}; pub(crate) use batch_run::{batch_action, batch_inputs, batch_keeps_step, batch_save_point, process_files}; -pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with}; +pub use export::{LayerExportReport, SkippedExportLayer, bake_cube, export_layers_report_with, export_layers_with, layers_to_files_needs_more_layers}; use export::{color_lookup_tables, layers_to_files, push_unique}; use info::file_info; pub use info::{CAMERA_FIELDS, camera_data, copyright_marked, read_file_info, write_file_info}; @@ -477,6 +477,10 @@ mod batch_log_format_tests; #[path = "file_cmds/export_clut_cube_header_tests.rs"] mod export_clut_cube_header_tests; +#[cfg(test)] +#[path = "file_cmds/layers_to_files_single_layer_tests.rs"] +mod layers_to_files_single_layer_tests; + #[cfg(test)] #[path = "file_cmds/layers_to_files_png_names_tests.rs"] mod layers_to_files_png_names_tests; diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index c150566296..b563a5be13 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -8,6 +8,11 @@ mod layers_to_files_index_tests; // ---------- Export ---------- +/// Layers to Files requires another layer when the document only contains a Background. +pub fn layers_to_files_needs_more_layers(doc: &Document) -> bool { + doc.layers.len() == 1 && doc.background().is_some() +} + pub(super) fn layers_to_files(s: &mut Session, p: &Value) -> Result { let cmd = "file.export.layersToFiles"; let dir = str_param(p, "dir", cmd).or_else(|_| str_param(p, "output", cmd))?.to_string(); @@ -59,6 +64,9 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let _authorization = crate::jobs::render_authorization_scope(s.authorize); let save = SaveOpts::from_params(s, p, cmd)?; let d = s.active().ok_or(EngineError::NoDocument)?; + if layers_to_files_needs_more_layers(&d.doc) { + return Err(EngineError::Other("Layers to Files needs a document with multiple layers.".into())); + } let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut report = LayerExportReport::default(); diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_single_layer_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_single_layer_tests.rs new file mode 100644 index 0000000000..fd766f5fbc --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_single_layer_tests.rs @@ -0,0 +1,47 @@ +use super::*; + +const COMMAND: &str = "file.export.layersToFiles"; +const MESSAGE: &str = "Layers to Files needs a document with multiple layers."; + +#[test] +fn layers_to_files_refuses_a_background_only_document_without_writing() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 50, "height": 40, "background": "white"})).unwrap(); + s.edit("Use an imported Background name", |doc, _| { + doc.background_mut().unwrap().name = "Hintergrund".into(); + Ok(()) + }) + .unwrap(); + let dir = tempfile::tempdir().unwrap(); + + let error = s.execute(COMMAND, json!({"dir": dir.path()})).unwrap_err(); + assert_eq!(error.to_string(), MESSAGE); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); +} + +#[test] +fn layers_to_files_refuses_a_background_only_document_before_streaming() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 50, "height": 40, "background": "white"})).unwrap(); + + let mut writes = 0; + let error = export_layers_report_with(&s, &json!({"visibleOnly": false}), |_, _| { + writes += 1; + Ok(()) + }) + .unwrap_err(); + assert_eq!(error.to_string(), MESSAGE); + assert_eq!(writes, 0); +} + +#[test] +fn layers_to_files_still_exports_a_single_normal_layer_named_background() { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 50, "height": 40, "background": "transparent"})).unwrap(); + s.execute("layer.setProps", json!({"name": "Background"})).unwrap(); + let dir = tempfile::tempdir().unwrap(); + + let result = s.execute(COMMAND, json!({"dir": dir.path(), "prefix": "doc"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1); + assert!(dir.path().join("doc_0000_Background.png").is_file()); +} diff --git a/crates/engine-core/src/cmd/file_cmds/tests.rs b/crates/engine-core/src/cmd/file_cmds/tests.rs index d742671e68..e77ffd2bc6 100644 --- a/crates/engine-core/src/cmd/file_cmds/tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/tests.rs @@ -1864,6 +1864,7 @@ fn save_a_copy_writes_the_jpeg_format_asked_for() { assert_eq!(photocraft_io::import("a.jpg", &bytes).unwrap().document.size.width, 40, "{params}"); } // Layers to Files takes it too. + s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap(); s.execute("file.export.layersToFiles", json!({"dir": dir, "format": "jpg", "jpegFormat": "progressive"})).unwrap(); let layers: Vec<_> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.path()).filter(|p| !p.ends_with("a.jpg")).collect(); assert!(!layers.is_empty()); diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 7c8095e8b9..476be83615 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -712,6 +712,10 @@ pub(crate) fn batch_check(app: &mut PhotocraftApp, result: &ParamResult) -> Resu #[path = "batch_ok_validation_tests.rs"] mod batch_ok_validation_tests; +#[cfg(test)] +#[path = "layers_to_files_tests.rs"] +mod layers_to_files_tests; + /// Handle menu commands that need a shell action or a parameter dialog before execution. pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &Value) -> Option> { if id == "file.closeAll" || id == "file.closeOthers" { @@ -747,6 +751,14 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para if !no_params(params) { return None; } + if id == "file.export.layersToFiles" + && let Some(st) = app.session.active() + && photocraft_engine::file_cmds::layers_to_files_needs_more_layers(&st.doc) + { + let message = tl!("Layers to Files needs a document with multiple layers."); + crate::dialogs::alerts::alert(app, message); + return Some(Err(message.to_owned())); + } let label = photocraft_engine::commands::find(id).map_or(id, |c| c.label); match id { "file.openAs" => Some(app.open_dialog_file()), diff --git a/crates/ui-egui/src/menus/view_cmds/layers_to_files_tests.rs b/crates/ui-egui/src/menus/view_cmds/layers_to_files_tests.rs new file mode 100644 index 0000000000..b20a21d813 --- /dev/null +++ b/crates/ui-egui/src/menus/view_cmds/layers_to_files_tests.rs @@ -0,0 +1,40 @@ +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +use super::*; + +const COMMAND: &str = "file.export.layersToFiles"; + +#[test] +fn layers_to_files_menu_alerts_for_background_only_and_opens_for_multilayer() { + crate::i18n::with_language(crate::i18n::Lang::EN, || { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); + assert!(!crate::menus::is_enabled(&app, COMMAND)); + + app.run("file.new", json!({"width": 50, "height": 40, "background": "white"})).unwrap(); + assert!(crate::menus::is_enabled(&app, COMMAND), "the menu must be reachable to show the alert"); + let error = crate::menus::invoke(&mut app, &ctx, COMMAND, json!({})).unwrap_err(); + assert_eq!(error, "Layers to Files needs a document with multiple layers."); + + let dialogs = app.framework.dialogs.open_dialogs(); + assert_eq!(dialogs.len(), 1); + assert_eq!(dialogs[0].key.as_deref(), Some("alert")); + assert_eq!(dialogs[0].fields.as_ref().unwrap()["message"], error.as_str()); + + let mut h = + Harness::builder().with_context(ctx.clone()).with_size(egui::vec2(900.0, 700.0)).build_ui_state(|ui, app| crate::dialogs::run(app, ui), app); + h.run_steps(4); + h.get_by_role_and_label(egui::accesskit::Role::Button, "OK"); + h.key_press(egui::Key::Enter); + h.run_steps(4); + assert!(h.state().framework.dialogs.open_dialogs().is_empty()); + + let app = h.state_mut(); + app.run("layer.new.layer", json!({"name": "Ink"})).unwrap(); + crate::menus::invoke(app, &ctx, COMMAND, json!({})).unwrap(); + let dialogs = app.framework.dialogs.open_dialogs(); + assert_eq!(dialogs.len(), 1); + assert_eq!(dialogs[0].key.as_deref(), Some(COMMAND)); + }); +}