Address CodeRabbit: same-named actions in Batch/Droplet, Save and Close format

- Batch and Create Droplet dialogs get a Set dropdown (each set once, each
  action name once) and send the selected action's set, so a loaded library
  with one name in two sets runs the chosen set's action; createDroplet now
  honours `set` with a named action (dialogs.rs:512 finding).
- Droplet capture rewrites an ordinary call to the action's name only while
  that name is unique in the exported list; otherwise it keeps the exported
  index, so a call to the second of two same-named actions still reaches it
  (outside-diff finding on actions_cmds.rs:337).
- Save and Close refuses a source whose bytes Batch would write in another
  format (a Cineon source is encoded as PSD), instead of writing PSD bytes
  under the source's .cin name (batch_run.rs:918 finding).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
David MannandClaude Opus 5.5 committed 2026-11-05 14:11:29 +01:00
1 parent 4e0d487568
commit 88beb84064
10 files changed
+191 -32

No files matched your search

+20 -3
View File
@@ -330,12 +330,10 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
visit_calls(steps, &mut |id, params, own_actions| match id {
"actions.play" | "file.automate.batch" => {
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<Act
}
found.insert(i, action);
}
// Where each captured source action lands in the exported list (source order).
let exported: std::collections::BTreeMap<usize, usize> = found.keys().enumerate().map(|(at, &i)| (i, at)).collect();
let mut found: Vec<_> = found.into_values().collect();
let names: Vec<String> = 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<Act
}
return;
}
// An ordinary call becomes the captured action's name, which reads well and resolves to
// it while the name is unique in the exported list. Two captured actions of one name (in
// different sets) would both resolve to the first, so such a call keeps its exported index.
if !scoped && let Ok(i) = target(list, params, id) {
let Some(name) = list.get(i).map(|a| a.name.clone()) else { return };
match exported.get(&i) {
Some(&at) if names.iter().filter(|n| **n == name).count() > 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()
@@ -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.
+15 -3
View File
@@ -336,9 +336,21 @@ pub fn document_saved(s: &mut Session, doc: photocraft_doc::DocId) -> Option<Val
// ---------- Create Droplet ----------
/// Resolve the enabled steps of the saved action chosen for Batch or a droplet.
/// Resolve the enabled steps of the saved action chosen for a droplet: by name within `set` when
/// one is given (a loaded library can hold one name in two sets), else by name or index.
pub(crate) fn named_action_steps(s: &Session, p: &Value, cmd: &str) -> Result<Vec<(String, Value)>> {
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<CommandSpec> {
"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 <name>.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 <name>.command calling `photocraft-cli droplet`)} → {path, shim} (the actions its Play Action and Conditional steps call are saved in the droplet)"##,
native,
create_droplet
),
+6 -2
View File
@@ -908,10 +908,14 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
.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());
+22
View File
@@ -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() {
+9 -9
View File
@@ -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" => {
@@ -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() {
+17 -15
View File
@@ -191,7 +191,8 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
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" => {
@@ -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() {
+16
View File
@@ -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<String>, Vec<String>) {
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()) {