mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 01:18:43 +00:00
Merge #7170 Batch mapping into the current command modules
Preserve @HirthikBalaji's original ee4966260b history. Move its adapter and named-action support into the current layout while retaining the newer native Batch save snapshots, playback budget and output protections. Naming and descriptor extensions follow in the same source batch before combined validation.
This commit is contained in:
commit
d2b142eeec
8 files changed
+202
-23
No files matched your search
@@ -250,8 +250,10 @@ pub fn called_actions(list: &[Action], steps: &mut [(String, Value)]) -> Vec<Act
|
||||
fn targets(list: &[Action], steps: &mut [(String, Value)], depth: usize, queue: &mut Vec<(usize, usize)>) {
|
||||
for (id, params) in steps.iter_mut() {
|
||||
match id.as_str() {
|
||||
"actions.play" => {
|
||||
let Ok(i) = resolve(list, params, "actions.play") else { continue };
|
||||
"actions.play" | "file.automate.batch" => {
|
||||
let resolved =
|
||||
if id == "file.automate.batch" { crate::file_cmds::batch_action(list, params) } else { resolve(list, params, "actions.play") };
|
||||
let Ok(i) = resolved else { continue };
|
||||
if let (Some(action), Some(obj)) = (list.get(i), params.as_object_mut()) {
|
||||
obj.insert("action".into(), json!(action.name));
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ mod descriptors;
|
||||
mod events;
|
||||
mod fields;
|
||||
mod files;
|
||||
mod steps_batch;
|
||||
mod steps_calculations;
|
||||
mod steps_custom;
|
||||
mod steps_doc;
|
||||
|
||||
@@ -151,7 +151,7 @@ pub(super) fn export_item(id: &str, params: &Value, set: &str) -> Option<AtnItem
|
||||
return Some(AtnItem { event, dictionary: jstr(params, "name").unwrap_or("").as_bytes().to_vec(), 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)?;
|
||||
|
||||
@@ -639,6 +639,14 @@ pub(super) const EVENTS: &[Event] = &[
|
||||
Event { code: "save", name: "save", label: "Save", ids: &["file.save", "file.saveAs", "file.saveACopy"], from: save_from, to: save_to },
|
||||
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: super::steps_batch::batch_from,
|
||||
to: super::steps_batch::batch_to,
|
||||
},
|
||||
Event { code: "", name: "applyComp", label: "Apply Layer Comp", ids: &["layerComp.apply"], from: apply_comp_from, to: apply_comp_to },
|
||||
Event { code: "Stop", name: "stop", label: "Stop", ids: &[STOP_MESSAGE], from: stop_from, to: stop_to },
|
||||
];
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Batch mapping based on #7170 by @HirthikBalaji, adapted to the current modules.
|
||||
|
||||
use super::descriptors::{class, desc, enm, get_enum, get_list, get_num, get_obj, get_ref, get_text, jnum, jstr, long, path_text, path_value, text, trimmed};
|
||||
use super::fields::{Mapped, step};
|
||||
use super::{D, Descriptor, ReferenceItem, UnicodeString, Value, json};
|
||||
|
||||
fn naming_from(rules: &Descriptor) -> Option<String> {
|
||||
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))
|
||||
}
|
||||
|
||||
pub(super) 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)
|
||||
}
|
||||
|
||||
pub(super) fn batch_to(_: &str, p: &Value) -> Option<Descriptor> {
|
||||
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)
|
||||
}
|
||||
@@ -29,7 +29,7 @@ mod processing;
|
||||
mod save;
|
||||
|
||||
pub use batch_run::OutputClaims;
|
||||
pub(crate) use batch_run::{BatchInput, batch_inputs, batch_keeps_step, batch_save_point, process_files};
|
||||
pub(crate) use batch_run::{BatchInput, batch_action, batch_inputs, batch_keeps_step, batch_save_point, process_files};
|
||||
#[cfg(test)]
|
||||
pub(crate) use batch_run::{MAX_SUBFOLDER_DEPTH, list_images_tree};
|
||||
use batch_run::{batch, same_format};
|
||||
@@ -307,7 +307,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Batch…",
|
||||
&["File", "Automate"],
|
||||
None,
|
||||
r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"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?,"jpegFormat":"baseline|optimized|progressive"?,"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,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"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##"{"action":name|index? (instead of steps),"set":str?,"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action; a Save, Save As or Save a Copy step marks the document written to output, in this command's format and options: as the save found it if it was closed or another document is active at the end, else as the action leaves it; with no such step, the active document at the end),"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?,"jpegFormat":"baseline|optimized|progressive"?,"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,"tiffCompression":"none|lzw|zip"?,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"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
|
||||
),
|
||||
|
||||
@@ -244,19 +244,23 @@ pub(crate) fn batch_keeps_step(id: &str) -> bool {
|
||||
(batch_save_point(id) || !crate::actions_cmds::shell_save_command(id)) && !crate::actions_cmds::shell_view_command(id)
|
||||
}
|
||||
|
||||
/// Resolve Batch's recorded action and set without substituting an action from another set.
|
||||
pub(crate) fn batch_action(list: &[crate::actions_cmds::Action], p: &Value) -> Result<usize> {
|
||||
const CMD: &str = "file.automate.batch";
|
||||
if let Some(set) = p.get("set").filter(|v| !v.is_null()) {
|
||||
let set = set.as_str().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "set must be a string".into() })?;
|
||||
let name =
|
||||
p.get("action").and_then(Value::as_str).ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "a set needs a named action".into() })?;
|
||||
return list
|
||||
.iter()
|
||||
.position(|a| a.name == name && a.set.as_deref() == Some(set))
|
||||
.ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: format!("no action named `{name}` in set `{set}`") });
|
||||
}
|
||||
crate::actions_cmds::resolve(list, p, CMD)
|
||||
}
|
||||
|
||||
pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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: they only mark the result.
|
||||
steps.retain(|(id, _)| batch_keeps_step(id) && id != "file.export.quickExport");
|
||||
if let Some((id, _)) = steps.iter().find(|(id, _)| !batch_save_point(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") {
|
||||
@@ -271,6 +275,27 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
list
|
||||
}
|
||||
};
|
||||
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").filter(|v| v.is_array()) {
|
||||
parse_steps(act)?
|
||||
} else {
|
||||
let action = list.get(batch_action(&list, p)?).ok_or_else(|| EngineError::Other("batch action disappeared".into()))?;
|
||||
if s.actions.playback_stack.contains(&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, params))| (id.clone(), params.clone())).collect()
|
||||
};
|
||||
// Preserve the current Save snapshots and view-step policy while adding named actions.
|
||||
steps.retain(|(id, _)| batch_keeps_step(id) && id != "file.export.quickExport");
|
||||
if let Some((id, _)) = steps.iter().find(|(id, _)| !batch_save_point(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();
|
||||
// A batch inside a played action charges its inputs × steps (at least one each: an input is read,
|
||||
// decoded and saved even with no steps) to the playback tree it is in and
|
||||
// hands the count on, so a batch of batches can't multiply past the limit. A top-level batch
|
||||
@@ -283,13 +308,9 @@ pub(super) fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
s.actions.playback_steps = playback_steps;
|
||||
}
|
||||
let actions = crate::actions_cmds::ActionState {
|
||||
list,
|
||||
playing: s.actions.playing,
|
||||
playback_stack: s.actions.playback_stack.clone(),
|
||||
playback_steps,
|
||||
..Default::default()
|
||||
};
|
||||
let mut playback_stack = s.actions.playback_stack.clone();
|
||||
playback_stack.extend(called_name);
|
||||
let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack, playback_steps, ..Default::default() };
|
||||
let names = batch_naming::plan(&inputs, &output, &format, p)?;
|
||||
let save = SaveOpts::from_params(s, p, cmd)?;
|
||||
let authorize = s.authorize;
|
||||
|
||||
@@ -1,5 +1,29 @@
|
||||
use super::*;
|
||||
|
||||
// Named Batch action regression adapted from #7170 by @HirthikBalaji.
|
||||
#[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();
|
||||
let mut action = crate::actions_cmds::Action::new("Scale".into(), vec![("image.imageSize".into(), json!({"width":16,"height":16}))]);
|
||||
action.set = Some("Ops".into());
|
||||
s.actions.list.push(action);
|
||||
let result = s.execute("file.automate.batch", json!({"action":"Scale","set":"Ops","input":[input.clone()],"output":out})).unwrap();
|
||||
assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}");
|
||||
for p in [json!({"action":"Nonexistent"}), json!({"action":"Scale","set":"Wrong set"})] {
|
||||
let mut p = p;
|
||||
p["input"] = json!([input.clone()]);
|
||||
p["output"] = json!(out);
|
||||
assert!(s.execute("file.automate.batch", p).is_err());
|
||||
}
|
||||
s.actions.playback_stack.push("Scale".into());
|
||||
let err = s.execute("file.automate.batch", json!({"action":"Scale","input":[input],"output":out})).unwrap_err();
|
||||
assert!(err.to_string().contains("recursive action call"), "{err}");
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-file-cmds-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
|
||||
Reference in new issue
Block a user