Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Droplets: carry the actions their Play Action steps call (#2794) (#2800)

Valentin Kleinb7b3117aea8d
diff --git a/crates/engine/src/actions_cmds.rs b/crates/engine/src/actions_cmds.rs
index 55c7264de..3f96e4a56 100644
--- a/crates/engine/src/actions_cmds.rs
+++ b/crates/engine/src/actions_cmds.rs
@@ -105,6 +105,35 @@ pub fn playback_plan(s: &Session, p: &Value) -> Result<(Action, usize)> {
Ok((action, from))
}
+/// The actions that `steps` call through Play Action steps, followed transitively, in list order,
+/// so a droplet can run without the Actions panel that made it (#2794). Index references in
+/// `steps` and in the copies become names, which resolve without the rest of the list. A target
+/// 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<Action> {
+ 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") {
+ 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));
+ }
+ queue.push((i, depth));
+ }
+ }
+ let mut queue = Vec::new();
+ targets(list, steps, 1, &mut queue);
+ let mut found = std::collections::BTreeMap::new();
+ while let Some((i, depth)) = queue.pop() {
+ // Playback stops at 16 levels, so deeper calls never run.
+ if depth > 16 || found.contains_key(&i) {
+ continue;
+ }
+ let Some(mut action) = list.get(i).cloned() else { continue };
+ targets(list, &mut action.steps, depth + 1, &mut queue);
+ found.insert(i, action);
+ }
+ found.into_values().collect()
+}
+
fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs
index f26ba1add..a493cf1e4 100644
--- a/crates/engine/src/automate_cmds.rs
+++ b/crates/engine/src/automate_cmds.rs
@@ -295,6 +295,9 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
// The droplet's output folder replaces recorded saves, and view steps don't apply, as in batch.
steps.retain(|(id, _)| !crate::actions_cmds::shell_save_command(id) && !crate::actions_cmds::shell_view_command(id));
check_known(&steps, cmd)?;
+ // Play Action steps need their actions when the droplet runs on its own (#2794). Not under
+ // `actions`: the CLI reads that key as an action set.
+ let called = crate::actions_cmds::called_actions(&s.actions.list, &mut steps);
let path = if path.ends_with(".pcdroplet") || path.ends_with(".json") { path.to_string() } else { format!("{path}.pcdroplet") };
let name = p.get("name").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&path));
let steps_json: Vec<Value> = steps.iter().map(|(id, pr)| json!([id, pr])).collect();
@@ -304,12 +307,14 @@ fn create_droplet(s: &mut Session, p: &Value) -> Result<Value> {
options.insert(k.into(), v.clone());
}
}
- let droplet = json!({"photocraftDroplet": 1, "name": name, "action": {"name": name, "steps": steps_json}, "options": options});
+ let mut droplet = json!({"photocraftDroplet": 1, "name": name, "action": {"name": name, "steps": steps_json}, "options": options});
+ if !called.is_empty() {
+ droplet["calledActions"] = json!(called);
+ }
let text = serde_json::to_string_pretty(&droplet).unwrap_or_default();
write_file(&path, text.as_bytes())?;
let shim = p.get("shim").and_then(Value::as_bool).unwrap_or(cfg!(unix));
let shim_path = if shim { Some(write_shim(&path)?) } else { None };
- let _ = s;
Ok(json!({"path": path, "shim": shim_path, "steps": steps.len()}))
}
@@ -366,6 +371,9 @@ fn run_droplet(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(q) = opts.get("quality") {
bp["quality"] = q.clone();
}
+ if let Some(called) = v.get("calledActions") {
+ bp["calledActions"] = called.clone();
+ }
let r = s.execute("file.automate.batch", bp)?;
Ok(json!({"droplet": path, "output": output, "files": r["files"], "errors": r["errors"]}))
}
@@ -541,7 +549,7 @@ pub fn specs() -> Vec<CommandSpec> {
"file.automate.createDroplet",
"Create Droplet…",
&["File", "Automate"],
- r##"{"path":str (.pcdroplet),"steps":[[id,params]…] (the action),"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}"##,
+ r##"{"path":str (.pcdroplet),"steps":[[id,params]…] (the action),"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 steps call are saved in the droplet)"##,
native,
create_droplet
),
diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/automate_cmds/tests.rs
index 9259bdc8e..6bd8a3111 100644
--- a/crates/engine/src/automate_cmds/tests.rs
+++ b/crates/engine/src/automate_cmds/tests.rs
@@ -145,6 +145,55 @@ fn droplets_are_written_and_run() {
assert!(s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["bogus", {}]]})).is_err());
}
+#[test]
+fn droplets_carry_the_actions_their_play_steps_call() {
+ use crate::actions_cmds::Action;
+ let dir = tmp("droplet-called");
+ let inputs = images(&dir, 2, 40, 20);
+ let mut s = Session::new();
+ let act = |name: &str, steps: Value| -> Action { serde_json::from_value(json!({"name": name, "steps": steps})).unwrap() };
+ s.actions.list = vec![
+ act("Unrelated", json!([["image.imageRotation.180", {}]])),
+ act("Rotate", json!([["image.imageRotation.90cw", {}]])),
+ // Calls Rotate by index (as the panel records it) and itself (caught at run time).
+ act("Outer", json!([["actions.play", {"action": 1}]])),
+ act("Loop", json!([["actions.play", {"action": "Loop"}]])),
+ ];
+ let make = |s: &mut Session, name: &str, steps: Value| {
+ let path = format!("{dir}/{name}");
+ let out = format!("{dir}/out-{name}");
+ s.execute("file.automate.createDroplet", json!({"path": path, "steps": steps, "format": "png", "output": out, "shim": false})).unwrap()["path"]
+ .as_str()
+ .unwrap()
+ .to_string()
+ };
+ let dp = make(&mut s, "Outer", json!([["actions.play", {"action": "Outer"}]]));
+ let looping = make(&mut s, "Loop", json!([["actions.play", {"action": "Loop"}]]));
+ let v: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
+ assert!(v.get("actions").is_none(), "the CLI reads `actions` as an action set");
+ let names: Vec<&str> = v["calledActions"].as_array().unwrap().iter().map(|a| a["name"].as_str().unwrap()).collect();
+ assert_eq!(names, ["Rotate", "Outer"], "only the called actions, transitively");
+
+ // A fresh session, as `photocraft-cli droplet` and the droplet shim use.
+ let mut fresh = Session::new();
+ let r = fresh.execute("file.automate.runDroplet", json!({"droplet": dp, "input": [dir.clone()]})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
+ let out = photocraft_codecs::decode(&std::fs::read(format!("{dir}/out-Outer/img0.png")).unwrap()).unwrap();
+ assert_eq!(out.dimensions(), (20, 40));
+ let r = fresh.execute("file.automate.runDroplet", json!({"droplet": looping, "input": [dir.clone()]})).unwrap();
+ assert_eq!(r["errors"].as_array().unwrap().len(), inputs.len(), "a self-call fails instead of looping: {r}");
+
+ // Droplets written before `calledActions` still run.
+ let old = format!("{dir}/old.pcdroplet");
+ std::fs::write(
+ &old,
+ json!({"photocraftDroplet": 1, "action": {"steps": [["image.imageRotation.90cw", {}]]}, "options": {"output": format!("{dir}/out-old")}}).to_string(),
+ )
+ .unwrap();
+ let r = fresh.execute("file.automate.runDroplet", json!({"droplet": old, "input": [dir.clone()]})).unwrap();
+ assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
+}
+
#[test]
fn batch_and_droplets_skip_recorded_view_steps() {
let dir = tmp("view-steps");
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs
index 5b826915a..e806aabe2 100644
--- a/crates/engine/src/file_cmds.rs
+++ b/crates/engine/src/file_cmds.rs
@@ -893,12 +893,19 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
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 actions = crate::actions_cmds::ActionState {
- list: s.actions.list.clone(),
- playing: s.actions.playing,
- playback_stack: s.actions.playback_stack.clone(),
- ..Default::default()
+ let list = match p.get("calledActions") {
+ None | Some(Value::Null) => s.actions.list.clone(),
+ // A droplet brings the actions it calls (#2794) and runs with those alone.
+ Some(v) => {
+ let list: Vec<crate::actions_cmds::Action> =
+ serde_json::from_value(v.clone()).map_err(|e| EngineError::BadParams { cmd: cmd.into(), msg: format!("\"calledActions\": {e}") })?;
+ if list.len() > 4096 {
+ return Err(EngineError::BadParams { cmd: cmd.into(), msg: "\"calledActions\" holds more than 4096 actions".into() });
+ }
+ list
+ }
};
+ let actions = crate::actions_cmds::ActionState { list, playing: s.actions.playing, playback_stack: s.actions.playback_stack.clone(), ..Default::default() };
let r = process_files(&inputs, &output, &format, SaveOpts::from_params(p), "", &|scratch| {
scratch.actions = actions.clone();
for (id, params) in &steps {
@@ -1453,7 +1460,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Batch…",
&["File", "Automate"],
None,
- r##"{"steps":[[commandId,params]|{"command":id,"params":{}}…] (a recorded action),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"tiffLayers":bool=false} → {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),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"tiffLayers":bool=false,"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
),