From ee4966260b08506336b2d8aac64488a754ca5171 Mon Sep 17 00:00:00 2001 From: HirthikBalaji Date: Sun, 18 Oct 2026 01:11:07 +0530 Subject: [PATCH] feat(atn): map Batch steps inside actions to file.automate.batch (#7104) --- crates/engine/src/actions_cmds.rs | 2 +- crates/engine/src/atn_cmds.rs | 128 ++++++++++++++++++++++++++- crates/engine/src/atn_cmds/tests.rs | 72 ++++++++++++++- crates/engine/src/file_cmds.rs | 58 +++++++++--- crates/engine/src/file_cmds/tests.rs | 57 ++++++++++++ docs/file-format-parity.md | 1 + docs/gaps.md | 5 ++ 7 files changed, 306 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs index d881a6112b..3b78aa23f6 100644 --- a/crates/engine/src/actions_cmds.rs +++ b/crates/engine/src/actions_cmds.rs @@ -157,7 +157,7 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> { /// that doesn't resolve is left alone: it fails at playback, as it would have before. pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec { fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) { - for (_, params) in steps.iter_mut().filter(|(id, _)| id == "actions.play") { + for (_, params) in steps.iter_mut().filter(|(id, _)| id == "actions.play" || id == "file.automate.batch") { let Ok(i) = resolve(list, params, "actions.play") else { continue }; if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) { obj.insert("action".into(), json!(action.name)); diff --git a/crates/engine/src/atn_cmds.rs b/crates/engine/src/atn_cmds.rs index ebeda48687..c4ec4c8d1a 100644 --- a/crates/engine/src/atn_cmds.rs +++ b/crates/engine/src/atn_cmds.rs @@ -1973,6 +1973,131 @@ fn play_to(_: &str, p: &Value) -> Option { Some(desc("null").with("null", D::Reference(items))) } +fn naming_from(rules: &Descriptor) -> Option { + let comps = get_list(rules, "fileNamingComponents")?; + let mut naming = String::new(); + for item in comps { + let (D::Descriptor(c) | D::GlobalObject(c)) = item else { continue }; + if let Some(txt) = get_text(c, "Txt ").or_else(|| get_text(c, "Txt")) { + naming.push_str(&txt); + } else if let Some(comp) = get_enum(c, "component") + .or_else(|| get_text(c, "component")) + .or_else(|| match c.get("component") { + Some(D::Class(cl)) => Some(trimmed(&cl.class_id)), + _ => None, + }) + { + let comp_clean = comp.trim(); + if comp_clean == "Nm" || comp_clean == "documentName" { + naming.push_str("{name}"); + } else if comp_clean.contains("Serial") || comp_clean.starts_with("Srl") || comp_clean == "serialNumber" { + naming.push_str("{serial}"); + } else if comp_clean.contains("Date") + || comp_clean == "mmddyy" + || comp_clean == "mmddyyyy" + || comp_clean == "yymmdd" + || comp_clean == "yyyymmdd" + || comp_clean == "ddmmyy" + || comp_clean == "ddmmyyyy" + { + naming.push_str("{date}"); + } + } + } + (!naming.is_empty()).then_some(naming) +} + +fn naming_to(template: &str) -> Descriptor { + let mut comps = Vec::new(); + let mut rest = template; + while let Some(at) = rest.find(['{', '}']) { + let literal = &rest[..at]; + if !literal.is_empty() { + comps.push(D::Descriptor(desc("fileNamingComponent").with("Txt ", text(literal)))); + } + rest = &rest[at..]; + if rest.starts_with('}') { + break; + } + if let Some(end) = rest.find('}') { + match &rest[1..end] { + "name" => comps.push(D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "Nm")))), + "serial" => comps.push(D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "3DigitSerial")))), + "date" => comps.push(D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "yyyymmdd")))), + _ => {} + } + rest = &rest[end + 1..]; + } else { + break; + } + } + if !rest.is_empty() { + comps.push(D::Descriptor(desc("fileNamingComponent").with("Txt ", text(rest)))); + } + comps.push(D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "lowerCaseExtension")))); + desc("fileNamingRules").with("fileNamingComponents", D::List(comps)) +} + +fn batch_from(d: &Descriptor) -> Mapped { + let unsupported = Mapped::Unsupported { harmless: false }; + let Some(input) = d.get("null").and_then(path_text) else { return unsupported }; + let Some(output) = d.get("T ").or_else(|| d.get("T")).and_then(path_text) else { return unsupported }; + let Some(r) = get_ref(d, "Usng") else { return unsupported }; + let mut action_name = None; + let mut set_name = None; + for item in r { + if let ReferenceItem::Name { class, name } = item { + match trimmed(&class.class_id).as_str() { + "Actn" => action_name = Some(name.to_string_lossy()), + "ASet" => set_name = Some(name.to_string_lossy()), + _ => {} + } + } + } + let Some(action) = action_name else { return unsupported }; + let mut p = json!({ + "input": input, + "output": output, + "action": action, + }); + if let Some(set) = set_name { + p["set"] = json!(set); + } + if let Some(rules) = get_obj(d, "fileNamingRules") { + if let Some(naming) = naming_from(rules) { + p["naming"] = json!(naming); + } + } + if let Some(start) = get_num(d, "Strt") { + if let Some(s) = u32::try_from(start.round() as i64).ok().filter(|&n| n > 0) { + p["startingSerial"] = json!(s); + } + } + step("file.automate.batch", p) +} + +fn batch_to(_: &str, p: &Value) -> Option { + let input = jstr(p, "input").or_else(|| jstr(p, "folder"))?; + let output = jstr(p, "output")?; + let action = jstr(p, "action")?; + let mut items = vec![ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul(action) }]; + if let Some(set) = jstr(p, "set") { + items.push(ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul(set) }); + } + let mut d = desc("Btch") + .with("null", path_value(input)) + .with("Usng", D::Reference(items)) + .with("T ", path_value(output)) + .with("Ovrd", D::Boolean(true)); + if let Some(naming) = jstr(p, "naming") { + d = d.with("fileNamingRules", D::Descriptor(naming_to(naming))); + } + if let Some(serial) = jnum(p, "startingSerial") { + d = d.with("Strt", long(serial)); + } + Some(d) +} + fn fill_from(d: &Descriptor) -> Mapped { if let Some(from) = get_obj(d, "From") { // The Paint Bucket tool's click: its point is in pixels, or in percent of the canvas @@ -2914,6 +3039,7 @@ const EVENTS: &[Event] = &[ ev!("save", "save", "Save", "file.save", &[]), ev!("Rvrt", "revert", "Revert", "file.revert", &[]), Event { code: "Ply ", name: "play", label: "Play", ids: &["actions.play"], from: play_from, to: play_to }, + Event { code: "Btch", name: "batch", label: "Batch", ids: &["file.automate.batch"], from: batch_from, to: batch_to }, Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to }, ]; @@ -3047,7 +3173,7 @@ fn export_item(id: &str, params: &Value, set: &str) -> Option { return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").to_string(), descriptor, ..Default::default() }); } let mut params = params.clone(); - if (id == "actions.play" || id == "actions.conditional") && params.get("set").is_none() { + if (id == "actions.play" || id == "actions.conditional" || id == "file.automate.batch") && params.get("set").is_none() { params["set"] = json!(set); } let (e, descriptor) = event_and_descriptor(id, ¶ms)?; diff --git a/crates/engine/src/atn_cmds/tests.rs b/crates/engine/src/atn_cmds/tests.rs index 871300372c..dce5094475 100644 --- a/crates/engine/src/atn_cmds/tests.rs +++ b/crates/engine/src/atn_cmds/tests.rs @@ -321,6 +321,7 @@ fn every_mapped_command_exports_and_imports_back() { ("image.mode.bitmap", json!({"method": "threshold"})), ("image.imageSize", json!({"resolution": 1200, "resample": "preserveDetails", "keepPrintSize": true})), ("layer.new.layerFromBackground", json!({"ifPresent": true, "select": false})), + ("file.automate.batch", json!({"input": "/input", "output": "/output", "action": "Make icon", "set": "S", "naming": "{name}Raw", "startingSerial": 1})), ]; for (id, params) in &cases { let item = export_item(id, params, "S").unwrap_or_else(|| panic!("{id} does not export")); @@ -336,7 +337,7 @@ fn every_mapped_command_exports_and_imports_back() { assert_eq!(steps[0].0, *id, "{id} came back as another command"); let mut back = steps[0].1.clone(); normalise(&mut back); - if *id == "actions.play" || *id == "actions.conditional" { + if *id == "actions.play" || *id == "actions.conditional" || *id == "file.automate.batch" { back["set"] = json!("S"); } assert_eq!(back, *params, "{id}"); @@ -956,3 +957,72 @@ fn remove_white_clears_the_targeted_layer_not_the_converted_background() { assert!(!st.doc.is_background(bottom.id), "the Background became a normal layer"); assert!(bottom.surface().unwrap().sample_channel(2, 2, 1) > 0.99, "and kept its pixels"); } + +#[test] +fn batch_step_imports_plays_and_round_trips() { + let mut s = Session::new(); + s.actions.list.push(Action { + name: "Make Icon".into(), + steps: vec![("image.imageSize".into(), json!({"width": 16, "height": 16}))], + disabled: Default::default(), + dialogs: Default::default(), + set: Some("Icons".into()), + color: String::new(), + }); + + let naming_rules = desc("fileNamingRules").with( + "fileNamingComponents", + D::List(vec![ + D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "Nm"))), + D::Descriptor(desc("fileNamingComponent").with("Txt ", text("Raw"))), + D::Descriptor(desc("fileNamingComponent").with("component", enm("fileNamingComponent", "lowerCaseExtension"))), + ]), + ); + let btch_desc = desc("Btch") + .with("null", path_value("/test/input")) + .with( + "Usng", + D::Reference(vec![ + ReferenceItem::Name { class: class("Actn"), name: UnicodeString::new_nul("Make Icon") }, + ReferenceItem::Name { class: class("ASet"), name: UnicodeString::new_nul("Icons") }, + ]), + ) + .with("T ", path_value("/test/output")) + .with("Ovrd", D::Boolean(true)) + .with("fileNamingRules", D::Descriptor(naming_rules)) + .with("Strt", D::Integer(1)); + + let file = AtnFile { + name: UnicodeString::new_nul("Icons"), + expanded: true, + actions: vec![AtnAction { + name: UnicodeString::new_nul("Batch Driver"), + items: vec![item("Btch", "Batch", Some(btch_desc))], + ..Default::default() + }], + warnings: Vec::new(), + }; + let data = b64(&atn::write(&file).unwrap()); + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + + let driver = s.actions.list.iter().find(|a| a.name == "Batch Driver").expect("Batch Driver imported"); + assert_eq!(driver.steps.len(), 1); + assert_eq!(driver.steps[0].0, "file.automate.batch"); + assert_eq!(driver.steps[0].1["input"], "/test/input"); + assert_eq!(driver.steps[0].1["output"], "/test/output"); + assert_eq!(driver.steps[0].1["action"], "Make Icon"); + assert_eq!(driver.steps[0].1["set"], "Icons"); + assert_eq!(driver.steps[0].1["naming"], "{name}Raw"); + assert_eq!(driver.steps[0].1["startingSerial"], 1); + + let saved = s.execute("actions.save", json!({"action": "Batch Driver"})).unwrap(); + let saved_bytes = photocraft_paint::tile::b64_decode(saved["data"].as_str().unwrap()).unwrap(); + let parsed = atn::parse(&saved_bytes).unwrap(); + assert_eq!(parsed.actions[0].items[0].event.id(), "Btch"); + let d = parsed.actions[0].items[0].descriptor.as_ref().unwrap(); + assert_eq!(d.get("null").and_then(path_text), Some("/test/input".into())); + assert_eq!(d.get("T ").and_then(path_text), Some("/test/output".into())); + assert_eq!(get_num(d, "Strt"), Some(1.0)); +} + diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index bfaca603de..840aa3497e 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -1122,18 +1122,6 @@ impl OutputClaims { fn batch(s: &mut Session, p: &Value) -> Result { let cmd = "file.automate.batch"; - let mut steps = - parse_steps(p.get("steps").or_else(|| p.get("action")).ok_or_else(|| EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() })?)?; - // Each result goes to the destination folder, which overrides the action's recorded Save / - // Save As steps (Photoshop's "Override Action 'Save As' Commands"). Recorded view steps - // (zoom, fit) don't change the output, so they are skipped (#2752). - steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id) && !crate::actions_cmds::shell_view_command(id) && id != "file.export.quickExport"); - if let Some((id, _)) = steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) { - return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") }); - } - let output = str_param(p, "output", cmd)?.to_string(); - let inputs = batch_inputs_tree(p, cmd, &output)?; - let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string(); // Steps that call another action play it from the caller's actions; the playback stack comes // along so an action that batches itself is caught as a recursive call. let list = match p.get("calledActions") { @@ -1148,7 +1136,49 @@ fn batch(s: &mut Session, p: &Value) -> Result { list } }; - let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), ..Default::default() }; + let mut called_name = None; + let mut steps = if let Some(st) = p.get("steps") { + parse_steps(st)? + } else if let Some(act) = p.get("action") { + if act.is_array() { + parse_steps(act)? + } else { + let action = if let (Some(set), Some(name)) = (p.get("set").and_then(Value::as_str), act.as_str()) { + list.iter().find(|a| a.name == name && a.set.as_deref() == Some(set)) + } else { + None + }; + let action = match action { + Some(a) => a, + None => { + let idx = crate::actions_cmds::resolve(&list, p, cmd)?; + &list[idx] + } + }; + if s.actions.playback_stack.iter().any(|n| n == &action.name) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("recursive action call to `{}`", action.name) }); + } + called_name = Some(action.name.clone()); + action.enabled_steps().map(|(_, (id, pr))| (id.clone(), pr.clone())).collect() + } + } else { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"steps\"".into() }); + }; + // Each result goes to the destination folder, which overrides the action's recorded Save / + // Save As steps (Photoshop's "Override Action 'Save As' Commands"). Recorded view steps + // (zoom, fit) don't change the output, so they are skipped (#2752). + steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id) && !crate::actions_cmds::shell_view_command(id) && id != "file.export.quickExport"); + if let Some((id, _)) = steps.iter().find(|(id, _)| crate::commands::find(id).is_none()) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown command `{id}` in the action") }); + } + let output = str_param(p, "output", cmd)?.to_string(); + let inputs = batch_inputs_tree(p, cmd, &output)?; + let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string(); + let mut playback_stack = s.actions.playback_stack.clone(); + if let Some(name) = called_name { + playback_stack.push(name); + } + let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack, ..Default::default() }; let names = batch_naming::plan(&inputs, &output, &format, p)?; let save = SaveOpts::from_params(s, p, cmd)?; let run = |scratch: &mut Session| { @@ -1680,7 +1710,7 @@ pub fn specs() -> Vec { "Batch…", &["File", "Automate"], None, - r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action)|"action":string (action name in the session or calledActions; optional "set":string),"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, batch ), diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rs index 3cc72c30c4..6eb88fef80 100644 --- a/crates/engine/src/file_cmds/tests.rs +++ b/crates/engine/src/file_cmds/tests.rs @@ -1248,3 +1248,60 @@ fn batch_naming_rejects_outputs_that_replace_inputs_before_processing() { assert_eq!(std::fs::read(&first).unwrap(), before[0]); assert_eq!(std::fs::read(&second).unwrap(), before[1]); } + +#[test] +fn batch_resolves_action_by_name_and_detects_recursion() { + let dir = tmp("batch-action-name"); + let input = png(&dir, "in.png", 8, 8, "#ff0000"); + let out = join(&dir, "out"); + std::fs::create_dir_all(&out).unwrap(); + + let mut s = Session::new(); + s.actions.list.push(crate::actions_cmds::Action { + name: "Scale".into(), + steps: vec![("image.imageSize".into(), json!({"width": 16, "height": 16}))], + disabled: Default::default(), + dialogs: Default::default(), + set: Some("Ops".into()), + color: String::new(), + }); + + let res = s + .execute( + "file.automate.batch", + json!({ + "action": "Scale", + "set": "Ops", + "input": [input.clone()], + "output": out, + }), + ) + .unwrap(); + assert_eq!(res["files"].as_array().unwrap().len(), 1, "{res}"); + + let err = s + .execute( + "file.automate.batch", + json!({ + "action": "Nonexistent", + "input": [input.clone()], + "output": out, + }), + ) + .unwrap_err(); + assert!(err.to_string().contains("no action named `Nonexistent`"), "{err}"); + + s.actions.playback_stack.push("Scale".into()); + let cyc_err = s + .execute( + "file.automate.batch", + json!({ + "action": "Scale", + "input": [input], + "output": out, + }), + ) + .unwrap_err(); + assert!(cyc_err.to_string().contains("recursive action call to `Scale`"), "{cyc_err}"); +} + diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index ba74623709..7567fe87b4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -142,6 +142,7 @@ remaining gaps in #1606 stay tracked with per-sample corpus ceilings. | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | `.atn`: Batch (`Btch`) steps map to `file.automate.batch` and export back (#7104) | | 2026-10-14 | minor | PSD smart filter masks: Photoshop stores a smart object's filtered pixels without its filter mask and mixes the unfiltered ones (`FEid`) back in; import now mixes them and export writes them that way, so sf-filter-mask-hard, -gradient and sf-stack-blend-and-mask pass; Photoshop-oracle floor 185 → 188 of 258 | | 2026-10-13 | minor | Lossy DNG (compression 34892) decodes: 8-bit baseline JPEG tiles and strips, CFA and LinearRaw, partial edge tiles; the stored values take the normal levels and LinearizationTable (FILE-215-11, lossy DNG part) | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 | diff --git a/docs/gaps.md b/docs/gaps.md index faf0884c89..c39aa13a99 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -90,6 +90,10 @@ what an agent can't finish alone. - **Estimate:** 120–200 h. ### G11. Actions and scripting +- **Done 2026-10-18 (#7104):** `.atn` Batch steps (`Btch`) import as `file.automate.batch` and + export to the same event. Input/output paths, action references, starting serial and file + naming rules (`{name}`, `{serial}`, `{date}`, literals) are preserved. Batch can resolve + called actions by name from the session or droplet list. AUTO-219-2 remains partial. - **2026-10-13 evidence:** Batch supports [output naming templates](batch-naming.md) using `{name}`, `{serial}` and a captured UTC `{date}`, with a starting serial number. Colliding names remain errors; custom output names cannot replace inputs. AUTO-219-5 stays partial. @@ -270,6 +274,7 @@ what an agent can't finish alone. | Date | Change | Summary | |---|---|---| +| 2026-10-18 | minor | G11: `.atn` Batch (`Btch`) steps map to `file.automate.batch` and export back (#7104) | | 2026-10-14 | minor | G1: a PSD smart object's filter mask shows when the file opens (Photoshop stores the filtered pixels unmasked); export stores them that way too; Photoshop-oracle floor 185 → 188 of 258 | | 2026-10-13 | minor | G14: D90 image area measured (4288 × 2848 at (10, 10)); gap remains open | | 2026-10-14 | minor | Corpus floors raised to the measured results of the CMYK, Lab, 32-bit, Levels, Threshold, Posterize, feather and pass-through fixes landed together: Photoshop-authored 165 → 185 of 258, io 146 → 148 of 170, psd-tools 242 → 249 of 309 |