diff --git a/crates/engine/src/cmd/actions_cmds.rs b/crates/engine/src/cmd/actions_cmds.rs index 69b1156726..3f27d91137 100644 --- a/crates/engine/src/cmd/actions_cmds.rs +++ b/crates/engine/src/cmd/actions_cmds.rs @@ -330,12 +330,10 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { let Ok(i) = target(list, params, id) else { return }; + // The reference is rewritten by `remap` once the exported list is known. if own_actions { scoped.insert(i); } else { - if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) { - obj.insert("action".into(), json!(action.name)); - } queue.push_back((i, depth)); } } @@ -368,7 +366,10 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec = found.keys().enumerate().map(|(at, &i)| (i, at)).collect(); let mut found: Vec<_> = found.into_values().collect(); + let names: Vec = found.iter().map(|a| a.name.clone()).collect(); let mut originals = Vec::new(); let mut slots = std::collections::BTreeMap::new(); for i in scoped { @@ -395,6 +396,22 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec 1 => { + params["action"] = json!(at); + if let Some(object) = params.as_object_mut() { + object.remove("set"); + } + } + _ => params["action"] = json!(name), + } + return; + } // Appended source copies must not make an originally missing numeric target valid. if let Some(i) = params.get("action").and_then(num).and_then(|i| usize::try_from(i).ok()) && i >= list.len() diff --git a/crates/engine/src/cmd/actions_cmds/tests.rs b/crates/engine/src/cmd/actions_cmds/tests.rs index 0e5cfce8e3..08d5a178d7 100644 --- a/crates/engine/src/cmd/actions_cmds/tests.rs +++ b/crates/engine/src/cmd/actions_cmds/tests.rs @@ -1401,6 +1401,33 @@ fn record_keeps_an_empty_loaded_sets_exact_name() { assert_eq!(s.execute("actions.save", json!({"set": " Web "})).unwrap()["actions"], json!(["First"])); } +/// A droplet capturing two actions of one name (sets A and B) keeps each call on the action it +/// reached: an index or set-qualified call to B's action still reaches B's copy, a name-only call +/// still reaches A's, and a call to a uniquely named action stays a name. +#[test] +fn captured_calls_keep_their_target_among_same_named_actions() { + let mut list = Vec::new(); + for (set, step) in [("A", "image.adjustments.invert"), ("B", "image.imageRotation.180")] { + let mut a = Action::new("Retouch", vec![(step.into(), json!({}))]); + a.set = Some(set.into()); + list.push(a); + } + list.push(Action::new("Other", vec![("image.imageRotation.90cw".into(), json!({}))])); + let mut steps: Vec<(String, Value)> = vec![ + ("actions.play".into(), json!({"action": 1})), + ("actions.play".into(), json!({"action": "Retouch"})), + ("file.automate.batch".into(), json!({"action": "Retouch", "set": "B", "input": [], "output": "/out"})), + ("actions.play".into(), json!({"action": 2})), + ]; + let called = crate::actions_cmds::called_actions(&list, &mut steps); + assert_eq!(called.len(), 3, "{called:?}"); + let set_of = |i: usize| called[i].set.clone(); + assert_eq!(set_of(resolve(&called, &steps[0].1, "t").unwrap()), Some("B".into()), "{}", steps[0].1); + assert_eq!(set_of(resolve(&called, &steps[1].1, "t").unwrap()), Some("A".into()), "{}", steps[1].1); + assert_eq!(set_of(crate::file_cmds::batch_action(&called, &steps[2].1).unwrap()), Some("B".into()), "{}", steps[2].1); + assert_eq!(steps[3].1["action"], "Other", "a unique name stays a name"); +} + /// Two actions of one name in different sets (a loaded library): renaming the second by index /// leaves the unqualified calls, which reach the first, and a Batch with explicit steps alone; /// only the Batch qualified with the second's set follows. Renaming the first moves them all. diff --git a/crates/engine/src/cmd/automate_cmds.rs b/crates/engine/src/cmd/automate_cmds.rs index 1a92114c96..9a5f94f68c 100644 --- a/crates/engine/src/cmd/automate_cmds.rs +++ b/crates/engine/src/cmd/automate_cmds.rs @@ -336,9 +336,21 @@ pub fn document_saved(s: &mut Session, doc: photocraft_doc::DocId) -> Option Result> { - let index = crate::actions_cmds::resolve(&s.actions.list, p, cmd)?; + let index = match p.get("set").filter(|v| !v.is_null()) { + Some(set) => { + let set = set.as_str().ok_or_else(|| bad(cmd, "\"set\" must be a string"))?; + let name = p.get("action").and_then(Value::as_str).ok_or_else(|| bad(cmd, "a set needs a named action"))?; + s.actions + .list + .iter() + .position(|a| a.name == name && a.set.as_deref() == Some(set)) + .ok_or_else(|| bad(cmd, format!("no action named `{name}` in set `{set}`")))? + } + None => crate::actions_cmds::resolve(&s.actions.list, p, cmd)?, + }; let action = s.actions.list.get(index).ok_or_else(|| bad(cmd, "the selected action no longer exists"))?; Ok(action.enabled_steps().map(|(_, step)| step.clone()).collect()) } @@ -617,7 +629,7 @@ pub fn specs() -> Vec { "file.automate.createDroplet", "Create Droplet…", &["File", "Automate"], - r##"{"path":str (.pcdroplet),"steps":[[id,params]…]?,"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"name":str?,"output":folder?,"format":"same|png|jpg|…"?,"quality":0..12?,"shim":bool=true on Unix (writes .command calling `photocraft-cli droplet`)} → {path, shim} (the actions its Play Action and Conditional steps call are saved in the droplet)"##, + r##"{"path":str (.pcdroplet),"steps":[[id,params]…]?,"action":name|index|[steps]? (used only when steps is absent; named actions exclude disabled steps),"set":str? (with a named action: that set's action of the name),"name":str?,"output":folder?,"format":"same|png|jpg|…"?,"quality":0..12?,"shim":bool=true on Unix (writes .command calling `photocraft-cli droplet`)} → {path, shim} (the actions its Play Action and Conditional steps call are saved in the droplet)"##, native, create_droplet ), diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 3f65384e16..6af9a34e21 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -908,10 +908,14 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result { .or_else(|| scratch.active().and_then(|state| state.path.clone())) .unwrap_or_default(); let encode_format = if format == "same" { same_format(&source_path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; + // Save and Close writes over the source, so its bytes must be the source's own + // format: a source PhotoCraft reads but saves as PSD (Cineon, whose extension has + // a writer elsewhere) would otherwise get PSD bytes under its own name. if save_and_close && !extension(out).is_some_and(|ext| { - matches!(ext.as_str(), "psd" | "psb" | "pcraft" | "ora") - || photocraft_codecs::from_extension(&ext).is_some_and(|format| format.caps().write) + ext == encode_format + && (matches!(ext.as_str(), "psd" | "psb" | "pcraft" | "ora") + || photocraft_codecs::from_extension(&ext).is_some_and(|format| format.caps().write)) }) { return Err(EngineError::Other(format!("Save and Close needs Save As for this source format: {out}")).into()); diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 5678d84453..6f97374126 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3672,6 +3672,28 @@ fn folder_listing_takes_every_format_photocraft_opens() { assert!(!super::openable_name("a.avif")); } +/// Save and Close never writes a source in a format other than its own: a Cineon source, which +/// Batch saves as PSD, is refused and left as it was, while a PNG next to it is saved in place. +#[test] +fn batch_save_and_close_refuses_a_source_it_would_save_in_another_format() { + let dir = tmp("batch-save-close-cin"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "#ff0000"})).unwrap(); + let cin = join(&dir, "a.cin"); + save_doc(doc(&s), &cin, None).unwrap(); + let png_path = png(&dir, "b.png", 8, 8, "#ff0000"); + let (cin_before, png_before) = (std::fs::read(&cin).unwrap(), std::fs::read(&png_path).unwrap()); + let r = Session::new() + .execute("file.automate.batch", json!({"input": dir, "destination": "saveAndClose", "steps": [["image.adjustments.invert", {}]]})) + .unwrap(); + let errors = r["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1, "{r}"); + assert!(errors[0]["file"].as_str().unwrap().ends_with("a.cin"), "{r}"); + assert!(errors[0]["error"].as_str().unwrap().contains("needs Save As"), "{r}"); + assert_eq!(std::fs::read(&cin).unwrap(), cin_before, "the Cineon source keeps its bytes"); + assert_ne!(std::fs::read(&png_path).unwrap(), png_before, "the PNG is saved in place"); +} + /// A batch over a folder processes PAM, PFM and DDS files instead of skipping them. #[test] fn batch_folder_processes_netpbm_and_dds_files() { diff --git a/crates/ui-egui/src/dialogs/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index 70be4ffbc7..c29299fd26 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -106,15 +106,15 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V let Some(action) = crate::actions::selected_action(app) else { return Some(Err("record an action in the Actions panel first".into())); }; - let name = action.name.clone(); - let names: Vec<_> = app.session.actions.list.iter().map(|action| action.name.clone()).collect(); - form( - app, - id, - tl!("Create Droplet"), - json!({"path": format!("{dir}/{name}.pcdroplet"), "name": name, "action": name, "output": format!("{dir}/droplet-output"), "format": "same"}), - json!({"action": names, "format": ["same", "png", "jpg", "psd", "tiff"]}), - ) + let (name, set) = (action.name.clone(), action.set.clone()); + let (names, sets) = crate::actions::action_form_choices(app); + let mut fields = + json!({"path": format!("{dir}/{name}.pcdroplet"), "name": name, "action": name, "output": format!("{dir}/droplet-output"), "format": "same"}); + // The Set dropdown picks between same-named actions; an action outside any set has none. + if let Some(set) = set { + fields["set"] = json!(set); + } + form(app, id, tl!("Create Droplet"), fields, json!({"set": sets, "action": names, "format": ["same", "png", "jpg", "psd", "tiff"]})) } "file.scripts.statistics" => json!({"dialog": crate::stack_dialog::open_statistics(app)}), "file.scripts.browse" => { diff --git a/crates/ui-egui/src/dialogs/file_ui/tests.rs b/crates/ui-egui/src/dialogs/file_ui/tests.rs index 44508e65aa..050e730bf5 100644 --- a/crates/ui-egui/src/dialogs/file_ui/tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/tests.rs @@ -238,6 +238,34 @@ fn droplet_folder_follows_the_document_or_uses_a_safe_fallback() { assert_eq!(droplet_default_dir(&app), "/tmp/photocraft"); } +/// Two actions of one name in sets A and B: Create Droplet starts on the selected action's set +/// and saves that set's steps, not the first action of the name. +#[test] +fn create_droplet_saves_the_selected_sets_action_among_same_named_ones() { + let (mut app, ctx) = app(); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("b.pcdroplet").to_string_lossy().into_owned(); + app.run("file.new", json!({"width": 2, "height": 1})).unwrap(); + let mut list = Vec::new(); + for (set, step) in [("A", "image.adjustments.invert"), ("B", "image.imageRotation.90cw")] { + let mut action = photocraft_engine::actions_cmds::Action::new("Retouch", vec![(step.into(), json!({}))]); + action.set = Some(set.into()); + list.push(action); + } + app.session.actions.list = list; + app.ui.actions.selected = Some(1); + let id = crate::menus::invoke(&mut app, &ctx, "file.automate.createDroplet", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(fields["__choices"]["set"], json!(["A", "B"])); + assert_eq!(fields["set"], "B"); + fields.insert("path".into(), json!(path)); + fields.insert("output".into(), json!(dir.path().join("out").to_string_lossy())); + fields.insert("shim".into(), json!(false)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let saved: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); + assert_eq!(saved["action"]["steps"], json!([["image.imageRotation.90cw", {}]])); +} + /// The droplet contains the form's chosen action; cancelling writes nothing. #[test] fn create_droplet_uses_the_action_selected_in_the_form() { diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index 52e65a34a0..5c501fc2e9 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -191,7 +191,8 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { let mut s = s.clone(); match choices.get(&k).and_then(Value::as_array) { Some(opts) => { - let action_names = k == "action" + // Action and set names are the user's own text, never catalogue entries. + let action_names = matches!(k.as_str(), "action" | "set") && matches!(f.get("__command").and_then(Value::as_str), Some("file.automate.batch" | "file.automate.createDroplet")); let opts: Vec<(String, String)> = opts.iter().filter_map(Value::as_str).map(|o| (o.to_string(), if action_names { o.to_string() } else { label(o) })).collect(); @@ -508,20 +509,21 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para let Some(action) = crate::actions::selected_action(app) else { return Some(Err("record an action in the Actions panel first".into())); }; - let name = action.name.clone(); - let names: Vec<_> = app.session.actions.list.iter().map(|action| action.name.clone()).collect(); - dialog( - app, - json!({ - "action": name, "source": "folder", "input": dir, - "includeSubfolders": false, "__labels": subfolders_label(), - "output": format!("{dir}/batch"), "format": "same", "quality": null, - "__batchQuality": 8, "naming": "", "startingSerial": 1, - "stopOnError": false, "errorLog": "", - "__order": ["action", "source", "input", "includeSubfolders", "output", "format", "naming", "startingSerial", "quality", "stopOnError", "errorLog"] - }), - json!({"action": names, "format": ["same", "png", "jpg", "psd", "tiff", "webp"], "source": ["folder", "open"]}), - ) + let (name, set) = (action.name.clone(), action.set.clone()); + let (names, sets) = crate::actions::action_form_choices(app); + let mut fields = json!({ + "action": name, "source": "folder", "input": dir, + "includeSubfolders": false, "__labels": subfolders_label(), + "output": format!("{dir}/batch"), "format": "same", "quality": null, + "__batchQuality": 8, "naming": "", "startingSerial": 1, + "stopOnError": false, "errorLog": "", + "__order": ["set", "action", "source", "input", "includeSubfolders", "output", "format", "naming", "startingSerial", "quality", "stopOnError", "errorLog"] + }); + // The Set dropdown picks between same-named actions; an action outside any set has none. + if let Some(set) = set { + fields["set"] = json!(set); + } + dialog(app, fields, json!({"set": sets, "action": names, "format": ["same", "png", "jpg", "psd", "tiff", "webp"], "source": ["folder", "open"]})) } // Channel workflow dialogs (see channels_panel.rs for the channel references). "select.saveSelection" | "select.loadSelection" | "image.applyImage" | "image.calculations" => { diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index d45b696334..52df38d96c 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -332,6 +332,37 @@ fn batch_menu_requires_a_recorded_action() { assert_eq!(app.ui.dialog_mut(dialog).unwrap().fields["action"], "Invert"); } +/// Two actions of one name in sets A and B (a loaded library): the Batch form lists the name once +/// and both sets, starts on the selected action's set, and runs that set's action. +#[test] +fn batch_menu_runs_the_selected_sets_action_among_same_named_ones() { + let (mut app, ctx) = app_with(0); + let dir = tempfile::tempdir().unwrap(); + let input = dir.path().join("source.png").to_string_lossy().into_owned(); + let output = dir.path().join("out").to_string_lossy().into_owned(); + app.run("file.new", json!({"width": 2, "height": 1})).unwrap(); + app.run("file.saveACopy", json!({"path": input})).unwrap(); + let mut list = Vec::new(); + for (set, step) in [("A", "image.adjustments.invert"), ("B", "image.imageRotation.90cw")] { + let mut action = photocraft_engine::actions_cmds::Action::new("Retouch", vec![(step.into(), json!({}))]); + action.set = Some(set.into()); + list.push(action); + } + app.session.actions.list = list; + app.ui.actions.selected = Some(1); + let id = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + assert_eq!(fields["__choices"]["action"], json!(["Retouch"])); + assert_eq!(fields["__choices"]["set"], json!(["A", "B"])); + assert_eq!((&fields["action"], &fields["set"]), (&json!("Retouch"), &json!("B"))); + fields.insert("input".into(), json!([input.clone()])); + fields.insert("output".into(), json!(output)); + crate::dialogs::confirm(&mut app, id).unwrap(); + let saved = std::fs::read_dir(&output).unwrap().next().unwrap().unwrap().path(); + let image = photocraft_io::import("out.png", &std::fs::read(saved).unwrap()).unwrap().document; + assert_eq!((image.size.width, image.size.height), (1, 2), "set B's action (a rotation) ran"); +} + /// Choosing a different action changes the output; cancelled or deleted choices write nothing. #[test] fn batch_menu_runs_the_action_chosen_in_the_form() { diff --git a/crates/ui-egui/src/panels/actions.rs b/crates/ui-egui/src/panels/actions.rs index 02ddb35e87..ea549885d7 100644 --- a/crates/ui-egui/src/panels/actions.rs +++ b/crates/ui-egui/src/panels/actions.rs @@ -74,6 +74,22 @@ pub fn selected_action(app: &PhotocraftApp) -> Option<&Action> { idx.and_then(|i| list.get(i)).or_else(|| selected_set_actions(app).first().and_then(|i| list.get(*i))).or_else(|| list.first()) } +/// The Set and Action dropdowns of the Batch and Create Droplet dialogs, as in the reference +/// application: each action name once and each set once, in list order. A loaded library can hold +/// one name in two sets, so the dialog sends the set too and the command picks that set's action. +pub fn action_form_choices(app: &PhotocraftApp) -> (Vec, Vec) { + let (mut names, mut sets) = (Vec::new(), Vec::new()); + for action in &app.session.actions.list { + if !names.contains(&action.name) { + names.push(action.name.clone()); + } + if let Some(set) = action.set.as_ref().filter(|set| !sets.contains(*set)) { + sets.push(set.clone()); + } + } + (names, sets) +} + /// The selected set folder, if no action is selected and the set still exists. fn selected_set(app: &PhotocraftApp) -> Option<&str> { if app.ui.actions.selected.is_some_and(|i| i < app.session.actions.list.len()) {