GitCorner

Code

ossartcraftphotocraft🌐
856f865cf98d
use super::*;
use crate::actions_cmds::{Action, ActionList, ActionStep, ActionsFile};

/// An `ActionList` holding `actions` in order.
fn list_of(actions: Vec<Action>) -> ActionList {
    ActionList::from_file(ActionsFile::new(actions, Vec::new()))
}

pub(super) fn tmp(name: &str) -> String {
    let d = std::env::temp_dir().join(format!("photocraft-automate-{}-{name}", std::process::id()));
    let _ = std::fs::remove_dir_all(&d);
    std::fs::create_dir_all(&d).unwrap();
    d.to_string_lossy().into_owned()
}

/// Writes `n` small PNGs (w×h, grey level i·40) into `dir`.
pub(super) fn images(dir: &str, n: usize, w: u32, h: u32) -> Vec<String> {
    (0..n)
        .map(|i| {
            let mut s = Session::new();
            let v = (i as f32 * 40.0 + 20.0) / 255.0;
            s.execute(
                "file.new",
                json!({"width": w, "height": h, "background": format!("#{:02x}{:02x}{:02x}", (v * 255.0) as u8, (v * 255.0) as u8, (v * 255.0) as u8)}),
            )
            .unwrap();
            let path = format!("{dir}/img{i}.png");
            crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap();
            path
        })
        .collect()
}

#[test]
fn scripts_parse_json_and_lines() {
    let a = parse_script(r#"[["file.new", {"width": 10}], {"command": "layer.flattenImage"}, "edit.undo"]"#).unwrap();
    assert_eq!(a.len(), 3);
    assert_eq!(a[0].1["width"], 10);
    let b = parse_script("# make a doc\nfile.new {\"width\": 12, \"height\": 8}\n\nimage.imageRotation.90cw\n").unwrap();
    assert_eq!(b.len(), 2);
    assert_eq!(b[1].0, "image.imageRotation.90cw");
    let c = parse_script(r#"{"photocraftDroplet":1,"action":{"steps":[["file.new",{}]]}}"#).unwrap();
    assert_eq!(c.len(), 1);
    assert!(parse_script("file.new {bad json").is_err());
}

#[test]
fn browse_runs_a_script_file() {
    let dir = tmp("browse");
    let path = format!("{dir}/make.txt");
    std::fs::write(&path, "file.new {\"width\": 30, \"height\": 20}\nimage.imageRotation.90cw\n").unwrap();
    let mut s = Session::new();
    let r = s.execute("file.scripts.browse", json!({"path": path})).unwrap();
    assert_eq!(r["ok"], true);
    let d = &s.active().unwrap().doc;
    assert_eq!((d.size.width, d.size.height), (20, 30));
    assert!(s.execute("file.scripts.browse", json!({"script": "no.such.command"})).is_err());
    // A failing step stops the script and is reported.
    let r = s.execute("file.scripts.browse", json!({"steps": [["layer.delete", {"layer": u64::MAX}], ["image.imageRotation.90cw", {}]]})).unwrap();
    assert_eq!(r["results"].as_array().unwrap().len(), 1);
}

#[test]
fn browse_rejects_photoshop_extendscript() {
    let dir = tmp("jsx");
    let jsx = format!("{dir}/hello.jsx");
    std::fs::write(&jsx, "alert('hi');\n").unwrap();
    let mut s = Session::new();
    let err = s.execute("file.scripts.browse", json!({"path": jsx})).unwrap_err().to_string();
    assert!(err.contains("not Photoshop ExtendScript"), "{err}");
    assert!(err.contains("JSON"), "{err}");
    let js = format!("{dir}/hello.js");
    std::fs::write(&js, "alert('hi');\n").unwrap();
    assert!(s.execute("file.scripts.browse", json!({"path": js})).is_err());
    let err = s.execute("file.scripts.browse", json!({"name": "Resize.jsx", "script": "alert(1);"})).unwrap_err().to_string();
    assert!(err.contains(".js/.jsx"), "{err}");
    // A JSON script still runs even if the file name is not a Photoshop suffix.
    let json = format!("{dir}/rotate.json");
    std::fs::write(&json, r#"[["file.new", {"width": 8, "height": 8}]]"#).unwrap();
    let r = s.execute("file.scripts.browse", json!({"path": json})).unwrap();
    assert_eq!(r["ok"], true);
}

#[test]
fn recording_browse_script_captures_each_effect_once() {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 12, "height": 8})).unwrap();
    s.execute("actions.record", json!({"name": "Rotate script"})).unwrap();
    let run = s.execute("file.scripts.browse", json!({"steps": [["image.imageRotation.90cw", {}]]})).unwrap();
    assert_eq!(run["ok"], true);
    assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
    let done = s.execute("actions.stop", json!({})).unwrap();
    assert_eq!(done["steps"], 1, "Browse must not be recorded a second time");
    let recorded = s.execute("actions.get", json!({"action": "Rotate script"})).unwrap();
    assert_eq!(recorded["steps"], json!([["image.imageRotation.90cw", {}]]));

    s.execute("image.imageRotation.90ccw", json!({})).unwrap();
    assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (12, 8));
    let replay = s.execute("actions.play", json!({"action": "Rotate script"})).unwrap();
    assert_eq!(replay["ran"], 1);
    assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
}

#[test]
fn standalone_browse_script_still_runs_and_journals_concrete_commands() {
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 12, "height": 8})).unwrap();
    let start = s.journal.len();
    let result = s.execute("file.scripts.browse", json!({"steps": [["image.imageRotation.90cw", {}]]})).unwrap();
    assert_eq!(result["ok"], true);
    assert_eq!(s.journal.len(), start + 2, "the child and Browse retain their diagnostic journal entries");
    assert_eq!(s.journal[start].0, "image.imageRotation.90cw");
    assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
}

#[test]
fn script_events_fire_on_new_and_close() {
    let mut s = Session::new();
    let r = s
        .execute("file.scripts.scriptEventsManager", json!({"add": {"event": "newDocument", "steps": [["image.imageRotation.90cw", {}]], "name": "Rotate"}}))
        .unwrap();
    assert_eq!(r["enabled"], true);
    assert_eq!(r["bindings"].as_array().unwrap().len(), 1);
    assert!(s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "nope", "steps": []}})).is_err());
    assert!(s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "print", "steps": [["no.such", {}]]}})).is_err());
    s.execute("file.new", json!({"width": 40, "height": 10})).unwrap();
    let d = &s.active().unwrap().doc;
    assert_eq!((d.size.width, d.size.height), (10, 40), "the New Document action rotated it");
    assert_eq!(s.file_menu.event_log.len(), 1);
    // Events don't re-enter: the script's own commands fire nothing.
    s.execute("file.scripts.scriptEventsManager", json!({"add": {"event": "closeDocument", "steps": [["file.new", {"width": 5, "height": 5}]]}})).unwrap();
    s.execute("file.close", json!({})).unwrap();
    assert_eq!(s.documents().len(), 1, "closing ran the script, which made a new document");
    assert_eq!(s.documents()[0].doc.size.width, 5, "…without the New Document rotation");
    // Disabled: nothing fires.
    s.execute("file.scripts.scriptEventsManager", json!({"enabled": false})).unwrap();
    s.execute("file.new", json!({"width": 40, "height": 10})).unwrap();
    assert_eq!(s.active().unwrap().doc.size.width, 40);
    let r = s.execute("file.scripts.scriptEventsManager", json!({"removeAll": true})).unwrap();
    assert!(r["bindings"].as_array().unwrap().is_empty());
    assert_eq!(r["events"].as_array().unwrap().len(), EVENTS.len());
}

#[test]
fn droplets_are_written_and_run() {
    let dir = tmp("droplet");
    let inputs = images(&dir, 2, 40, 20);
    let mut s = Session::new();
    let path = format!("{dir}/Rotate");
    let r = s
        .execute(
            "file.automate.createDroplet",
            json!({"path": path, "steps": [["image.imageRotation.90cw", {}]], "format": "png", "output": format!("{dir}/out")}),
        )
        .unwrap();
    let dp = r["path"].as_str().unwrap().to_string();
    assert!(dp.ends_with("Rotate.pcdroplet"));
    let v: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
    assert_eq!(v["photocraftDroplet"], 1);
    #[cfg(unix)]
    {
        let shim = r["shim"].as_str().unwrap();
        let text = std::fs::read_to_string(shim).unwrap();
        assert!(text.starts_with("#!/bin/sh") && text.contains("droplet"));
        assert!(text.contains("/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli"));
        assert!(text.contains("${PHOTOCRAFT_CLI:-}"), "an explicit CLI path must take priority");
        use std::os::unix::fs::PermissionsExt;
        assert_ne!(std::fs::metadata(shim).unwrap().permissions().mode() & 0o111, 0, "executable");
    }
    let r = s.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/img0.png")).unwrap()).unwrap();
    assert_eq!(out.dimensions(), (20, 40));
    assert!(s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["bogus", {}]]})).is_err());
}

/// Names and indices choose the same action and omit its disabled steps.
#[test]
fn batch_and_droplets_use_the_named_actions_enabled_steps() {
    let dir = tmp("named-actions");
    let inputs = images(&dir, 1, 2, 1);
    let mut s = Session::new();
    let invert = crate::actions_cmds::Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))]);
    let mut rotate =
        crate::actions_cmds::Action::new("Rotate", vec![ActionStep::new("image.imageRotation.90cw", json!({})), ActionStep::new("file.close", json!({}))]);
    rotate.disabled.insert(1);
    s.actions.list = list_of(vec![invert, rotate]);
    for command in ["file.automate.batch", "file.automate.createDroplet"] {
        for (i, action) in [json!("Rotate"), json!(1)].into_iter().enumerate() {
            let output = format!("{dir}/{command}-{i}");
            let p = json!({"action": action, "input": inputs, "output": output, "path": format!("{output}.pcdroplet"), "format": "png", "shim": false});
            let mut result = s.execute(command, p).unwrap();
            if command == "file.automate.createDroplet" {
                let droplet: Value = serde_json::from_slice(&std::fs::read(result["path"].as_str().unwrap()).unwrap()).unwrap();
                assert_eq!(droplet["action"]["steps"], json!([["image.imageRotation.90cw", {}]]));
                // A droplet carries its chosen steps into a session with no saved actions.
                result = Session::new().execute("file.automate.runDroplet", json!({"droplet": result["path"], "input": inputs})).unwrap();
            }
            assert_eq!(result["errors"], json!([]), "{command}: {result}");
            let image = photocraft_codecs::decode(&std::fs::read(result["files"][0].as_str().unwrap()).unwrap()).unwrap();
            assert_eq!(image.dimensions(), (1, 2), "{command}: Rotate runs and the disabled Close does not");
        }
    }
}

/// Explicit steps retain precedence, and invalid choices fail before any output is written.
#[test]
fn batch_and_droplets_keep_explicit_steps_and_reject_invalid_sources_before_writing() {
    let dir = tmp("action-sources");
    let inputs = images(&dir, 1, 2, 1);
    let mut s = Session::new();
    s.actions.list.push(crate::actions_cmds::Action::new("Invert", vec![ActionStep::new("image.adjustments.invert", json!({}))])).unwrap();
    for command in ["file.automate.batch", "file.automate.createDroplet"] {
        for (i, source) in [
            json!({"steps": [["image.imageRotation.90cw", {}]], "action": "Missing"}),
            json!({"action": [["image.imageRotation.90cw", {}]]}),
            json!({"steps": [], "action": "Invert"}),
        ]
        .into_iter()
        .enumerate()
        {
            let output = format!("{dir}/{command}-inline-{i}");
            let mut p = json!({"input": inputs, "output": output, "path": format!("{output}.pcdroplet"), "format": "png", "shim": false});
            p.as_object_mut().unwrap().extend(source.as_object().unwrap().clone());
            let mut result = s.execute(command, p).unwrap();
            if command == "file.automate.createDroplet" {
                result = Session::new().execute("file.automate.runDroplet", json!({"droplet": result["path"], "input": inputs})).unwrap();
            }
            assert_eq!(result["errors"], json!([]), "{command}: {result}");
            let image = photocraft_codecs::decode(&std::fs::read(result["files"][0].as_str().unwrap()).unwrap()).unwrap();
            assert_eq!(image.dimensions(), if i == 2 { (2, 1) } else { (1, 2) });
        }
        for (i, source) in [
            json!({"action": "Deleted"}),
            json!({"action": 9}),
            json!({"action": -1}),
            json!({"steps": null, "action": "Invert"}),
            json!({"steps": {}, "action": "Invert"}),
            json!({"steps": [["bogus", {}]], "action": "Invert"}),
        ]
        .into_iter()
        .enumerate()
        {
            let output = format!("{dir}/{command}-rejected-{i}");
            let path = format!("{output}.pcdroplet");
            let mut p = json!({"input": inputs, "output": output, "path": path, "format": "png", "shim": false});
            p.as_object_mut().unwrap().extend(source.as_object().unwrap().clone());
            assert!(s.execute(command, p).is_err(), "{command}: {source}");
            assert!(!std::path::Path::new(&output).exists(), "{command}: no output directory on rejection");
            assert!(!std::path::Path::new(&path).exists(), "{command}: no droplet on rejection");
        }
    }
}

/// A droplet keeps the action's recorded saves, which mark the result as in Batch, so one made from
/// an action ending in Save As and Close writes its files instead of failing on every one.
#[test]
fn droplets_keep_the_recorded_save_that_marks_the_result() {
    let dir = tmp("droplet-save-close");
    let inputs = images(&dir, 1, 4, 2);
    let mut s = Session::new();
    let steps = json!([["image.adjustments.invert", {}], ["file.saveAs", {}], ["file.close", {}]]);
    let p = json!({"path": format!("{dir}/Invert"), "steps": steps, "format": "png", "output": format!("{dir}/out"), "shim": false});
    let dp = s.execute("file.automate.createDroplet", p).unwrap()["path"].as_str().unwrap().to_string();
    let r = s.execute("file.automate.runDroplet", json!({"droplet": dp, "input": [dir.clone()]})).unwrap();
    assert_eq!(r["errors"], json!([]), "{r}");
    assert_eq!(r["files"].as_array().unwrap().len(), inputs.len(), "{r}");
    let out = photocraft_io::import("img0.png", &std::fs::read(format!("{dir}/out/img0.png")).unwrap()).unwrap().document;
    let px = photocraft_compose::render(&out, photocraft_geom::Rect::new(1, 1, 2, 2)).px[0];
    assert!((px[0] - 235.0 / 255.0).abs() < 1e-3, "img0's gray 20 inverted: {px:?}");
}

#[cfg(unix)]
#[test]
fn droplet_shim_passes_shell_metacharacters_as_a_literal_path() {
    use std::os::unix::fs::PermissionsExt;

    let dir = tmp("droplet-shell-quote");
    let path = format!("{dir}/Droplet's \"quote\" $HOME `printf expanded` $(touch shim-injected) \\\nline");
    let mut session = Session::new();
    let result = session.execute("file.automate.createDroplet", json!({"path": path, "steps": [["file.new", {}]]})).unwrap();
    let droplet = result["path"].as_str().unwrap();
    let shim = result["shim"].as_str().unwrap();

    let cli = format!("{dir}/cli stub");
    let capture = format!("{dir}/captured path");
    let marker = format!("{dir}/shim-injected");
    let input = format!("{dir}/input file");
    std::fs::write(
        &cli,
        "#!/bin/sh\nif [ \"$#\" -ne 3 ] || [ \"$1\" != droplet ] || [ \"$3\" != \"$PHOTOCRAFT_EXPECTED_INPUT\" ]; then exit 90; fi\nprintf '%s' \"$2\" > \"$PHOTOCRAFT_CAPTURE\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
    let output = std::process::Command::new(shim)
        .arg(&input)
        .current_dir(&dir)
        .env("PHOTOCRAFT_CLI", &cli)
        .env("PHOTOCRAFT_CAPTURE", &capture)
        .env("PHOTOCRAFT_EXPECTED_INPUT", &input)
        .output()
        .unwrap();

    assert!(output.status.success(), "shim exited {:?}: {}", output.status, String::from_utf8_lossy(&output.stderr));
    assert!(!std::path::Path::new(&marker).exists(), "filename command substitution ran");
    let expected = std::fs::canonicalize(droplet).unwrap();
    assert_eq!(std::fs::read(&capture).unwrap(), expected.to_string_lossy().as_bytes());
}

/// Droplets retain transitive calls and effective Batch references across fresh or different sessions.
#[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 = list_of(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}");

    // Retain the copied action's flags as well as its steps.
    s.actions.list.append_recorded(1, [ActionStep::new("file.close", json!({}))]).unwrap();
    s.actions.list.set_step(1, 1, false).unwrap();
    s.actions.list.set_dialog(1, 0, true).unwrap();
    s.actions.list.assign_set(1, Some("Captured".into())).unwrap();
    s.actions
        .list
        .push(act(
            "BatchLoop",
            json!([["file.automate.batch", {"action": "BatchLoop", "input": [inputs[0]], "output": format!("{dir}/loop"), "format": "png"}]]),
        ))
        .unwrap();
    for (name, source, expected_names, error) in [
        ("batch-name", json!({"action": "Rotate"}), &["Rotate"][..], None),
        ("batch-index", json!({"action": 1}), &["Rotate"][..], None),
        ("batch-transitive", json!({"action": "Outer"}), &["Rotate", "Outer"][..], None),
        ("batch-explicit", json!({"steps": [["actions.play", {"action": 1, "note": "keep"}, "tail"]], "action": 3}), &["Rotate"][..], None),
        ("batch-legacy", json!({"action": [{"id": "actions.play", "params": {"action": 1}, "tag": "keep"}]}), &["Rotate"][..], None),
        (
            "batch-objects",
            json!({"steps": [
            {"command": "actions.play", "id": "ignored", "params": {"action": 1}, "tag": "keep"},
            "image.imageRotation.180", ["image.imageRotation.180"], {"id": "image.imageRotation.180"},
            {"command": "image.imageRotation.180", "id": "actions.play", "params": {"action": 3}}
        ], "action": 3}),
            &["Rotate"][..],
            None,
        ),
        ("batch-empty", json!({"steps": [], "action": 1}), &[][..], None),
        ("batch-null", json!({"steps": null, "action": 1}), &[][..], Some("steps")),
        ("batch-invalid", json!({"steps": {}, "action": 1}), &[][..], Some("steps")),
        ("batch-invalid-command", json!({"steps": [{"command": null, "id": "actions.play", "params": {"action": 1}}]}), &[][..], Some("command")),
        ("batch-missing", json!({"action": "Missing"}), &[][..], Some("no action named")),
        ("batch-cycle", json!({"action": "BatchLoop"}), &["BatchLoop"][..], Some("recursive action call")),
    ] {
        let inner = format!("{dir}/inner-{name}");
        let mut params = json!({"input": [inputs[0]], "output": inner, "format": "png", "note": {"action": 3}});
        params.as_object_mut().unwrap().extend(source.as_object().unwrap().clone());
        let mut expected = params.clone();
        match name {
            "batch-index" => expected["action"] = json!("Rotate"),
            "batch-explicit" => expected["steps"][0][1]["action"] = json!("Rotate"),
            "batch-legacy" => expected["action"][0]["params"]["action"] = json!("Rotate"),
            "batch-objects" => expected["steps"][0]["params"]["action"] = json!("Rotate"),
            _ => {}
        }
        let dp = make(&mut s, name, json!([["file.automate.batch", params]]));
        let saved: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
        assert_eq!(saved["action"]["steps"][0][1], expected, "{name}: keep the effective source's shape and unrelated fields");
        let names: Vec<&str> =
            saved["calledActions"].as_array().map(|actions| actions.iter().map(|a| a["name"].as_str().unwrap()).collect()).unwrap_or_default();
        assert_eq!(names, expected_names, "{name}: capture only effective dependencies in original list order");
        if expected_names.is_empty() {
            assert!(saved.get("calledActions").is_none(), "{name}: preserve deferred missing-target and legacy policy");
        }
        if let Some(captured) = saved["calledActions"].as_array().and_then(|actions| actions.iter().find(|a| a["name"] == "Rotate")) {
            assert_eq!(*captured, json!(s.actions.list.actions()[1]), "{name}: preserve disabled/dialog/set flags");
        }
        for different in [false, true] {
            let mut replay = Session::new();
            if different {
                replay.actions.list = list_of(vec![Action::new("Unrelated", Vec::new()), Action::new("Rotate", Vec::new())]);
            }
            let r = replay
                .execute("file.automate.runDroplet", json!({"droplet": dp, "input": [inputs[0]], "output": format!("{dir}/outer-{name}-{different}")}))
                .unwrap();
            if let Some(error) = error {
                assert_eq!(r["files"], json!([]), "{name}: {r}");
                assert!(r["errors"][0]["error"].as_str().unwrap().contains(error), "{name}: {r}");
            } else {
                assert_eq!(r["errors"], json!([]), "{name}/{different}: {r}");
                let out = photocraft_codecs::decode(&std::fs::read(format!("{inner}/img0.png")).unwrap()).unwrap();
                assert_eq!(out.dimensions(), if name == "batch-empty" { (40, 20) } else { (20, 40) }, "{name}/{different}");
            }
        }
    }

    // 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}");
}

/// Embedded Batch lists own their references; a named source is still selected from the caller.
#[test]
fn droplets_preserve_batch_action_namespaces() {
    use crate::actions_cmds::Action;
    let dir = tmp("droplet-scopes");
    let input = images(&dir, 1, 40, 20).remove(0);
    for kind in ["inline", "named", "named-set", "mixed", "mixed-two", "caller-null"] {
        let mut maker = Session::new();
        let mut source = Action::new("Source", vec![ActionStep::new("actions.play", json!({"action": 1})), ActionStep::new("file.close", json!({}))]);
        source.disabled.insert(1);
        source.dialogs.insert(0);
        source.set = Some("Captured".into());
        maker.actions.list = list_of(vec![Action::new("Gap", Vec::new()), Action::new("Outside", Vec::new()), source.clone()]);
        let embedded = vec![
            Action::new("LocalGap", Vec::new()),
            Action::new("Inside", vec![ActionStep::new("image.imageRotation.90cw", json!({}))]),
            Action::new("Outside", Vec::new()),
        ];
        let inner = format!("{dir}/{kind}-inner");
        let mut batch = json!({"input": [input], "output": inner, "format": "png", "calledActions": embedded});
        if kind == "inline" || kind == "caller-null" {
            batch["steps"] = json!([["actions.play", {"action": 1}]]);
        } else {
            batch["action"] = json!("Source");
            if kind == "named-set" {
                batch["set"] = json!("Captured");
            }
        }
        if kind == "caller-null" {
            maker.actions.list.append_recorded(1, [ActionStep::new("image.imageRotation.90cw", json!({}))]).unwrap();
            batch["calledActions"] = Value::Null;
        }
        let mut steps = Vec::new();
        if kind.starts_with("mixed") {
            steps.push(json!(["actions.play", {"action": "Source"}]));
        }
        steps.push(json!(["file.automate.batch", batch]));
        let other = format!("{dir}/{kind}-other");
        if kind == "mixed-two" {
            let mut second = batch.clone();
            second["output"] = json!(other);
            second["calledActions"][1]["steps"] = json!([]);
            steps.push(json!(["file.automate.batch", second]));
        }
        let path = maker
            .execute(
                "file.automate.createDroplet",
                json!({"path": format!("{dir}/{kind}"), "steps": steps, "format": "png", "output": format!("{dir}/{kind}-out"), "shim": false}),
            )
            .unwrap()["path"]
            .clone();
        let saved: Value = serde_json::from_slice(&std::fs::read(path.as_str().unwrap()).unwrap()).unwrap();
        if kind == "inline" {
            assert_eq!(saved["action"]["steps"][0][1], batch, "embedded inline steps are unchanged");
            assert!(saved.get("calledActions").is_none(), "embedded references do not capture enclosing actions");
        } else if kind != "caller-null" {
            let captured: Vec<Action> = serde_json::from_value(saved["calledActions"].clone()).unwrap();
            assert_eq!(captured.last(), Some(&source), "one untouched source retains its references and flags");
            assert_eq!(captured.len(), if kind.starts_with("mixed") { 3 } else { 1 });
        }
        let r = Session::new().execute("file.automate.runDroplet", json!({"droplet": path, "input": [input]})).unwrap();
        assert_eq!(r["errors"], json!([]), "{kind}: {r}");
        let out = photocraft_codecs::decode(&std::fs::read(format!("{inner}/img0.png")).unwrap()).unwrap();
        assert_eq!(out.dimensions(), (20, 40), "{kind}");
        if kind == "mixed-two" {
            assert_eq!(photocraft_codecs::decode(&std::fs::read(format!("{other}/img0.png")).unwrap()).unwrap().dimensions(), (40, 20));
        }
    }
}

/// Untouched scoped variants count toward the existing 4096-record playback limit.
#[test]
fn droplet_scoped_variants_keep_the_existing_action_limit() {
    use crate::actions_cmds::Action;
    let dir = tmp("droplet-scope-limit");
    let input = images(&dir, 1, 2, 1).remove(0);
    for count in [4095, 4096] {
        let mut maker = Session::new();
        maker.actions.list = list_of((0..count).map(|i| Action::new(format!("A{i}"), Vec::new())).collect());
        let mut steps: Vec<_> = (0..count).map(|i| json!(["actions.play", {"action": i}])).collect();
        steps.push(
            json!(["file.automate.batch", {"action": 0, "calledActions": [], "input": [input], "output": format!("{dir}/{count}-inner"), "format": "png"}]),
        );
        let output = format!("{dir}/{count}-out");
        let path = maker
            .execute("file.automate.createDroplet", json!({"path": format!("{dir}/{count}"), "steps": steps, "output": output, "format": "png", "shim": false}))
            .unwrap()["path"]
            .clone();
        let result = Session::new().execute("file.automate.runDroplet", json!({"droplet": path, "input": [input]}));
        if count == 4095 {
            assert_eq!(result.unwrap()["errors"], json!([]));
            assert!(std::path::Path::new(&output).exists());
        } else {
            assert!(result.unwrap_err().to_string().contains("4096"));
            assert!(!std::path::Path::new(&output).exists());
        }
    }
}

#[test]
fn droplets_carry_the_actions_their_conditional_steps_call() {
    use crate::actions_cmds::Action;
    let dir = tmp("droplet-conditional");
    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 = list_of(vec![
        act("Unrelated", json!([["image.imageRotation.180", {}]])),
        act("Rotate", json!([["image.imageRotation.90cw", {}]])),
        // The then branch calls Rotate by index, as the panel records it.
        act("Wide", json!([["actions.play", {"action": 1}]])),
        act("Tall", json!([["image.imageRotation.180", {}]])),
    ]);
    let steps = json!([["actions.conditional", {"if": "landscape", "then": "Wide", "else": "Tall"}]]);
    let out = format!("{dir}/out");
    let r = s
        .execute("file.automate.createDroplet", json!({"path": format!("{dir}/Cond"), "steps": steps, "format": "png", "output": out, "shim": false}))
        .unwrap();
    let dp = r["path"].as_str().unwrap().to_string();
    let v: Value = serde_json::from_slice(&std::fs::read(&dp).unwrap()).unwrap();
    let names: Vec<&str> = v["calledActions"].as_array().unwrap().iter().map(|a| a["name"].as_str().unwrap()).collect();
    assert_eq!(names, ["Rotate", "Wide", "Tall"], "both branches and what they call");

    // 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 img = photocraft_codecs::decode(&std::fs::read(format!("{out}/img0.png")).unwrap()).unwrap();
    assert_eq!(img.dimensions(), (20, 40), "the landscape input took the then branch");
}

#[test]
fn batch_and_droplets_skip_recorded_view_steps() {
    let dir = tmp("view-steps");
    images(&dir, 1, 40, 20);
    let steps = json!([["view.zoomIn", {}], ["image.imageRotation.90cw", {}], ["view.fitOnScreen", {}]]);
    let mut s = Session::new();
    let r = s.execute("file.automate.batch", json!({"steps": steps, "input": dir.clone(), "output": format!("{dir}/batch"), "format": "png"})).unwrap();
    assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
    let out = photocraft_codecs::decode(&std::fs::read(format!("{dir}/batch/img0.png")).unwrap()).unwrap();
    assert_eq!(out.dimensions(), (20, 40));
    let r = s.execute("file.automate.createDroplet", json!({"path": format!("{dir}/Rotate"), "steps": steps})).unwrap();
    let v: Value = serde_json::from_slice(&std::fs::read(r["path"].as_str().unwrap()).unwrap()).unwrap();
    assert_eq!(v["action"]["steps"], json!([["image.imageRotation.90cw", {}]]));
}

#[test]
fn statistics_makes_a_stack_mode_smart_object() {
    let dir = tmp("stats");
    let files = images(&dir, 3, 16, 12);
    let mut s = Session::new();
    let r = s.execute("file.scripts.statistics", json!({"mode": "mean", "input": files})).unwrap();
    assert_eq!(r["images"], 3);
    let d = &s.active().unwrap().doc;
    assert_eq!(d.layers.len(), 1);
    let LayerContent::Smart(so) = &d.layers[0].content else { panic!("not a smart object") };
    assert_eq!(so.stack_mode, Some(photocraft_doc::StackMode::Mean));
    // Mean of 20, 60, 100 = 60.
    let px = photocraft_compose::flatten(d).px[0];
    assert!((px[0] * 255.0 - 60.0).abs() < 1.5, "{px:?}");
    assert!(s.execute("file.scripts.statistics", json!({"mode": "average", "input": dir})).is_err());
}

#[test]
fn stacked_smart_object_holds_the_loaded_layers_at_its_top_level() {
    // Like Photoshop, Load Files into Stack › Create Smart Object (Statistics without alignment) and
    // Statistics with alignment embed one layer per file, bottom to top, with no wrapper group.
    let dir = tmp("stack-top");
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap();
    s.edit("texture", |doc, active| {
        let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?;
        for k in 0..40 {
            let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0);
            surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]);
        }
        Ok(())
    })
    .unwrap();
    let source = photocraft_compose::flatten(&s.active().unwrap().doc);
    let files: Vec<String> = (0..3)
        .map(|i| {
            let path = format!("{dir}/img{i}.png");
            crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap();
            path
        })
        .collect();
    for align in [false, true] {
        let mut s = Session::new();
        s.execute("file.scripts.statistics", json!({"mode": "median", "input": files, "align": align})).unwrap();
        let d = &s.active().unwrap().doc;
        let LayerContent::Smart(so) = &d.layers[0].content else { panic!("not a smart object") };
        let photocraft_doc::SmartSource::Embedded { file_name, bytes } = &so.source else { panic!("not embedded") };
        let inner = crate::smart_cmds::decode_source(file_name, bytes).unwrap();
        let names: Vec<&str> = inner.layers.iter().map(|l| l.name.as_str()).collect();
        assert_eq!(names, ["img0.png", "img1.png", "img2.png"], "align {align}");
        assert_eq!(photocraft_compose::flatten(d).px, source.px, "align {align}");
    }
}

#[test]
fn contact_sheet_places_thumbnails_with_captions() {
    let dir = tmp("contact");
    images(&dir, 5, 60, 30);
    for depth in [8, 16] {
        let mut s = Session::new();
        let r = s
            .execute("file.automate.contactSheetII", json!({"input": dir, "units": "pixels", "width": 400, "height": 300, "resolution": 72, "columns": 2, "rows": 2, "depth": depth, "fontSize": 10, "rotateForBestFit": true}))
            .unwrap();
        assert_eq!(r["pages"], 2, "5 images on 2×2 sheets");
        assert_eq!(r["images"], 5);
        let first = r["documents"][0].as_u64().unwrap() as usize;
        let d = &s.documents()[first].doc;
        assert_eq!((d.size.width, d.size.height), (400, 300));
        let names: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect();
        assert!(names.contains(&"img0") && names.contains(&"img3"), "{names:?}");
        let texts = d.layers.iter().filter(|l| matches!(l.content, LayerContent::Text(_))).count();
        assert_eq!(texts, 4, "a caption per image");
        let thumb = d.layers.iter().find(|l| l.name == "img0" && matches!(l.content, LayerContent::Raster(_))).unwrap();
        let b = thumb.surface().unwrap().content_bounds();
        assert!(b.width() <= 200 && b.height() < 150, "fits its cell: {b:?}");
        // Flattened variant.
        let r = s
            .execute(
                "file.automate.contactSheetII",
                json!({"input": dir, "units": "pixels", "width": 200, "height": 200, "columns": 3, "rows": 2, "caption": false, "flatten": true}),
            )
            .unwrap();
        let d = &s.documents()[r["documents"][0].as_u64().unwrap() as usize].doc;
        assert_eq!(d.layers.len(), 1);
    }
}

#[test]
fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() {
    use crate::actions_cmds::Action;
    let dir = tmp("nested-failure");
    images(&dir, 1, 8, 4);
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 8, "height": 6})).unwrap();
    s.actions
        .list
        .push(Action {
            name: "Rotate".into(),
            steps: vec![ActionStep::new("image.imageRotation.90cw", json!({}))],
            disabled: Default::default(),
            ..Default::default()
        })
        .unwrap();
    s.actions
        .list
        .push(Action {
            name: "Bad".into(),
            steps: vec![ActionStep::new("layer.delete", json!({"layer": u64::MAX}))],
            disabled: Default::default(),
            ..Default::default()
        })
        .unwrap();
    // A script stops at the failed call and reports it.
    let r = s.execute("file.scripts.browse", json!({"steps": [["actions.play", {"action": "Bad"}], ["image.imageRotation.90cw", {}]]})).unwrap();
    assert_eq!(r["ok"], false, "{r}");
    assert_eq!(r["results"].as_array().unwrap().len(), 1);
    // Batch plays called actions, and a failure inside one is a file error, not a saved result.
    let batch = |s: &mut Session, action: &str| {
        let p = json!({"steps": [["actions.play", {"action": action}]], "input": dir.clone(), "output": format!("{dir}/{action}"), "format": "png"});
        s.execute("file.automate.batch", p).unwrap()
    };
    let r = batch(&mut s, "Rotate");
    assert!(r["errors"].as_array().unwrap().is_empty(), "{r}");
    let r = batch(&mut s, "Bad");
    assert_eq!(r["files"], json!([]), "{r}");
    assert!(r["errors"][0]["error"].as_str().unwrap().contains("no such layer"), "{r}");
    // An action that batches itself stops as a recursive call instead of overflowing the stack.
    let inner = json!({"steps": [["actions.play", {"action": "Loop"}]], "input": dir.clone(), "output": format!("{dir}/inner"), "format": "png"});
    s.actions
        .list
        .push(Action { name: "Loop".into(), steps: vec![ActionStep::new("file.automate.batch", inner)], disabled: Default::default(), ..Default::default() })
        .unwrap();
    batch(&mut s, "Loop");
}

/// #4671: Load Files into Stack's Attempt to Automatically Align Source Images runs Auto-Align
/// Layers on the loaded layers, then (with Create Smart Object) puts them in one smart object;
/// without the smart object they stay loose layers, selected.
#[test]
fn load_files_into_stack_aligns_before_the_smart_object() {
    let dir = tmp("stack-align");
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 96, "height": 72, "background": "#606060"})).unwrap();
    s.edit("texture", |doc, active| {
        let surf = doc.layer_mut(active.ok_or(EngineError::NoDocument)?).and_then(Layer::surface_mut).ok_or(EngineError::NoDocument)?;
        for k in 0..40 {
            let (x, y, v) = ((k * 37) % 88, (k * 23) % 66, (k % 7) as f32 / 6.0);
            surf.fill_rect(photocraft_geom::Rect::new(x, y, x + 3 + k % 5, y + 2 + k % 4), &[v, 1.0 - v, 0.5, 1.0]);
        }
        Ok(())
    })
    .unwrap();
    let files: Vec<String> = (0..2)
        .map(|i| {
            let path = format!("{dir}/img{i}.png");
            crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap();
            path
        })
        .collect();
    let mut s = Session::new();
    let r = s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true})).unwrap();
    assert_eq!(r["layers"], 2);
    let st = s.active().unwrap();
    assert_eq!(st.doc.layers.len(), 2, "loose layers");
    assert!(st.doc.layers.iter().all(|l| matches!(l.content, LayerContent::Raster(_))));
    assert_eq!(st.selected_layers().len(), 2, "Auto-Align ran on them all");
    let mut s = Session::new();
    s.execute("file.scripts.loadFilesIntoStack", json!({"paths": files, "align": true, "createSmartObject": true})).unwrap();
    let d = &s.active().unwrap().doc;
    assert_eq!(d.layers.len(), 1);
    let LayerContent::Smart(_) = &d.layers[0].content else { panic!("not a smart object") };
    // A single file has nothing to align with: it just loads.
    let mut s = Session::new();
    s.execute("file.scripts.loadFilesIntoStack", json!({"paths": [files[0].clone()], "align": true})).unwrap();
    assert_eq!(s.active().unwrap().doc.layers.len(), 1);
}

/// A script file of `lines` (one `file.scripts.browse` call per entry) in `dir`.
fn script_calling(dir: &str, name: &str, callees: &[String]) -> String {
    let path = format!("{dir}/{name}.txt");
    let body: String = callees.iter().map(|c| format!("file.scripts.browse {}\n", json!({"path": c}))).collect();
    std::fs::write(&path, body).unwrap();
    path
}

#[test]
fn scripts_calling_scripts_share_one_step_budget() {
    let dir = tmp("fanout");
    // Eight levels, each calling the one below six times: 6^8 (1.7 million) calls of the leaf.
    let mut below = script_calling(&dir, "leaf", &[]);
    std::fs::write(&below, "select.deselect {}\n").unwrap();
    for level in 0..8 {
        below = script_calling(&dir, &format!("level{level}"), &vec![below; 6]);
    }
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
    let started = std::time::Instant::now();
    let r = s.execute("file.scripts.browse", json!({"path": below})).unwrap();
    assert_eq!(r["ok"], false, "the budget stops the run: {r}");
    assert!(started.elapsed().as_secs() < 60, "{:?}", started.elapsed());
    // The budget restarts with the next top-level script.
    s.execute("file.scripts.browse", json!({"script": "select.deselect {}"})).unwrap();
}

#[test]
fn scripts_nested_deeper_than_the_limit_fail() {
    let dir = tmp("deep");
    let mut below = script_calling(&dir, "leaf", &[]);
    std::fs::write(&below, "select.deselect {}\n").unwrap();
    for level in 0..20 {
        below = script_calling(&dir, &format!("level{level}"), &[below]);
    }
    let mut s = Session::new();
    s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
    let r = s.execute("file.scripts.browse", json!({"path": below})).unwrap();
    assert_eq!(r["ok"], false, "{r}");
    assert!(r.to_string().contains("nested more than"), "{r}");
    assert_eq!(s.actions.script_depth, 0, "the depth is released");
}

/// A droplet captures only the actions its enabled steps can call: a disabled Play step in a
/// called action does not add its target (nor count against the 4096-action limit).
#[test]
fn droplets_skip_actions_called_only_from_disabled_steps() {
    let dir = tmp("droplet-disabled-calls");
    let mut s = Session::new();
    let mut top = crate::actions_cmds::Action::new(
        "Top",
        vec![ActionStep::new("actions.play", json!({"action": "Skipped"})), ActionStep::new("actions.play", json!({"action": "Used"}))],
    );
    top.disabled.insert(0);
    let used = crate::actions_cmds::Action::new("Used", vec![ActionStep::new("image.adjustments.invert", json!({}))]);
    let skipped = crate::actions_cmds::Action::new("Skipped", vec![ActionStep::new("image.imageRotation.90cw", json!({}))]);
    s.actions.list = list_of(vec![skipped, top, used]);
    let r =
        s.execute("file.automate.createDroplet", json!({"path": format!("{dir}/D"), "steps": [["actions.play", {"action": "Top"}]], "shim": false})).unwrap();
    let droplet: Value = serde_json::from_slice(&std::fs::read(r["path"].as_str().unwrap()).unwrap()).unwrap();
    let names: Vec<&str> = droplet["calledActions"].as_array().unwrap().iter().map(|a| a["name"].as_str().unwrap()).collect();
    assert_eq!(names, ["Top", "Used"], "{droplet}");
    // The droplet still runs on its own: the enabled call resolves, the disabled one never plays.
    let inputs = images(&dir, 1, 3, 2);
    let run = Session::new().execute("file.automate.runDroplet", json!({"droplet": r["path"], "input": inputs, "output": format!("{dir}/out")})).unwrap();
    assert_eq!(run["errors"], json!([]), "{run}");
    let out = photocraft_codecs::decode(&std::fs::read(format!("{dir}/out/img0.png")).unwrap()).unwrap();
    assert_eq!(out.dimensions(), (3, 2), "the disabled Rotate must not run");
}

/// A droplet saved with Override Open reads each dropped input through its recorded Open,
/// not the file the Open recorded.
#[test]
fn droplets_forward_override_open_to_batch() {
    let dir = tmp("droplet-override-open");
    let inputs = images(&dir, 1, 6, 4);
    let recorded = {
        let mut s = Session::new();
        s.execute("file.new", json!({"width": 2, "height": 3, "background": "#00ff00"})).unwrap();
        let path = format!("{dir}/recorded.png");
        crate::file_cmds::save_doc(&s.active().unwrap().doc, &path, None).unwrap();
        path
    };
    for (override_open, size) in [(true, (6, 4)), (false, (2, 3))] {
        let mut s = Session::new();
        let out = format!("{dir}/out-{override_open}");
        let r = s
            .execute(
                "file.automate.createDroplet",
                json!({"path": format!("{dir}/D-{override_open}"), "steps": [["file.openAs", {"path": recorded, "as": "png"}]],
                    "format": "png", "output": out, "overrideOpen": override_open, "shim": false}),
            )
            .unwrap();
        let run = Session::new().execute("file.automate.runDroplet", json!({"droplet": r["path"], "input": [inputs[0]]})).unwrap();
        assert_eq!(run["errors"], json!([]), "{run}");
        let image = photocraft_codecs::decode(&std::fs::read(format!("{out}/img0.png")).unwrap()).unwrap();
        assert_eq!(image.dimensions(), size, "overrideOpen {override_open}: {run}");
    }
}