mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-21 01:18:43 +00:00
Batch: subfolders, open documents, file naming, stop on error, error log, progress and cancel (#219)
File › Automate › Batch now covers Photoshop's dialog (AUTO-219-5):
- Source: a folder with Include All Subfolders (the output mirrors the
folder tree, so same-named files in different subfolders don't
collide), or the open documents (`"source": "open"`: the steps run on
every open document as history steps; with an output folder a copy of
each is saved there).
- File Naming: a template with Photoshop's fields as tokens: {name}
{NAME} {Name}, {serial} to {serial:4} from startSerial, {letter}
{LETTER}, {date:mmddyy|mmdd|yyyymmdd|yymmdd|yyddmm|ddmmyy}, {ext}
{EXT}, other text literal. Default {name}.{ext}, the old naming.
- Errors: stopOnError stops at the first failing file and reports the
skipped ones; errorLog writes the failures to a text file.
- The command runs as a job: the status bar shows "n of total: file"
and Cancel stops after the current file.
The options live in the new engine module `batch` and are shared by
Image Processor, the Lens Correction batch and the CLI's `batch`
(--recursive --naming --start-serial --stop-on-error --error-log).
The generic form dialog takes an `__order` hint so the Batch dialog is
grouped as Photoshop's (Play, Source, Destination, Errors). chrono
(clock, native only) supplies the local date for the date tokens.
Tests: 9 in batch/tests.rs (tokens and rejected templates, recursive
listing, mirrored output, stop/skip/log, cancelled context, background
job, open-documents source), one CLI test, one form-order test. The
batch_export_options helpers pick the nearest field on a label's row,
since the taller dialog's Quality row now shares a height with the
Layers panel's opacity field. Scorecard AUTO-219-5 done; gaps, parity
and development docs updated.
This commit is contained in:
1 parent
6f85054288
commit
bc08629d29
15 files changed
+972
-61
No files matched your search
Generated
+1
@@ -4360,6 +4360,7 @@ name = "photocraft-engine"
|
||||
version = "0.8.2"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"chrono",
|
||||
"craft-print",
|
||||
"exr",
|
||||
"flate2",
|
||||
|
||||
+136
-10
@@ -27,8 +27,13 @@ USAGE:
|
||||
photocraft-cli run (<file> | --new <json>) --cmd <id> [--params <json>] [--cmd …] [--out <file>] [--format <ext>] [--quality <1-100>] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Open a file, run engine commands in order, save the result. Each --params
|
||||
applies to the preceding --cmd. Prints each command's JSON result.
|
||||
photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Apply an action list to every image in a directory. A Photoshop Actions file (.atn) is a
|
||||
photocraft-cli batch --actions <actions.json|set.atn> [--action <name>] --in <dir> --out <dir> [--recursive] [--naming <template>] [--start-serial <n>] [--stop-on-error] [--error-log <file>] [--format <ext>] [--quality <1-100>] [--in-place] [--tiff-layers] [--tga-bits <24|32>] [--dpx-bits <8|10|12|16>]
|
||||
Apply an action list to every image in a directory (--recursive: its subfolders too, mirrored
|
||||
under --out). --naming names the results, default {name}.{ext}; tokens: {name} {NAME} {Name},
|
||||
{serial} {serial:2} {serial:3} {serial:4} (from --start-serial, default 1), {letter} {LETTER},
|
||||
{date:mmddyy|mmdd|yyyymmdd|yymmdd|yyddmm|ddmmyy}, {ext} {EXT}; other text is literal.
|
||||
--stop-on-error stops at the first failing file (the rest are skipped) instead of going on;
|
||||
--error-log writes the failures to a text file. A Photoshop Actions file (.atn) is a
|
||||
set: its action --action names plays, as below. JSON steps are [id, params] pairs,
|
||||
{\"command\": id, \"params\": {…}} objects or bare ids, as a recorded action or droplet stores them
|
||||
(a list, or wrapped in {\"actions\": …}, {\"steps\": …} or a droplet). An Actions set (the Actions
|
||||
@@ -79,8 +84,8 @@ const SUBCOMMANDS: &[Subcommand] = &[
|
||||
},
|
||||
Subcommand {
|
||||
name: "batch",
|
||||
values: &["--actions", "--action", "--in", "--out", "--format", "--quality", "--tga-bits", "--dpx-bits"],
|
||||
bare: &["--in-place", "--tiff-layers"],
|
||||
values: &["--actions", "--action", "--in", "--out", "--naming", "--start-serial", "--error-log", "--format", "--quality", "--tga-bits", "--dpx-bits"],
|
||||
bare: &["--in-place", "--tiff-layers", "--recursive", "--stop-on-error"],
|
||||
run: batch,
|
||||
},
|
||||
Subcommand { name: "droplet", values: &["--out"], bare: &[], run: droplet },
|
||||
@@ -462,20 +467,32 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
));
|
||||
}
|
||||
std::fs::create_dir_all(&out_dir).map_err(|e| e.to_string())?;
|
||||
let mut inputs: Vec<PathBuf> =
|
||||
std::fs::read_dir(&in_dir).map_err(|e| format!("{}: {e}", in_dir.display()))?.flatten().map(|e| e.path()).filter(|p| is_input(p)).collect();
|
||||
inputs.sort();
|
||||
let start = match a.get("--start-serial") {
|
||||
Some(n) => n.parse::<u64>().map_err(|_| format!("--start-serial {n}: not a non-negative integer"))?,
|
||||
None => 1,
|
||||
};
|
||||
let naming = photocraft_engine::batch::Naming::parse(a.get("--naming").unwrap_or(photocraft_engine::batch::Naming::DEFAULT), start)
|
||||
.map_err(|e| format!("--naming: {e}"))?;
|
||||
let date = photocraft_engine::batch::Date::today();
|
||||
let stop_on_error = a.has("--stop-on-error");
|
||||
// (file, subfolder relative to --in, mirrored under --out)
|
||||
let inputs: Vec<(PathBuf, PathBuf)> = if a.has("--recursive") { list_inputs_recursive(&in_dir)? } else { list_inputs(&in_dir)? };
|
||||
let (mut ok, mut failed) = (0, 0);
|
||||
let mut failures = Vec::new();
|
||||
let mut skipped = 0;
|
||||
let mut written = photocraft_engine::file_cmds::OutputClaims::default();
|
||||
// `--format .jpg` names outputs `<stem>.jpg`, as `--format jpg` does (#490).
|
||||
let format = a.get("--format").map(|f| f.strip_prefix('.').unwrap_or(f));
|
||||
for input in &inputs {
|
||||
for (i, (input, sub)) in inputs.iter().enumerate() {
|
||||
let ext = format.map(str::to_owned).or_else(|| input.extension().map(|e| e.to_string_lossy().into_owned())).unwrap_or_else(|| "png".into());
|
||||
let stem = input.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let target = out_dir.join(format!("{stem}.{ext}"));
|
||||
let target = out_dir.join(sub).join(naming.file_name(&stem, &ext, i as u64, date));
|
||||
let target_text = target.to_string_lossy();
|
||||
let r = (|| -> Result<Vec<String>, String> {
|
||||
written.check(&target_text)?;
|
||||
if !sub.as_os_str().is_empty() {
|
||||
std::fs::create_dir_all(out_dir.join(sub)).map_err(|e| format!("{}: {e}", out_dir.join(sub).display()))?;
|
||||
}
|
||||
let mut h = Headless::trusted_local();
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
@@ -504,13 +521,70 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
let _ = writeln!(err, "FAIL {}: {e}", input.display());
|
||||
failures.push(format!("{}: {e}", input.display()));
|
||||
if stop_on_error {
|
||||
skipped = inputs.len() - i - 1;
|
||||
let _ = writeln!(err, "stopped at the first error (--stop-on-error); {skipped} file(s) skipped");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out, "{ok} succeeded, {failed} failed");
|
||||
if let Some(log) = a.get("--error-log")
|
||||
&& !failures.is_empty()
|
||||
{
|
||||
let text = format!("PhotoCraft Batch: {} error(s)\n{}\n", failures.len(), failures.join("\n"));
|
||||
std::fs::write(log, text).map_err(|e| format!("--error-log {log}: {e}"))?;
|
||||
}
|
||||
if skipped > 0 {
|
||||
let _ = writeln!(out, "{ok} succeeded, {failed} failed, {skipped} skipped");
|
||||
} else {
|
||||
let _ = writeln!(out, "{ok} succeeded, {failed} failed");
|
||||
}
|
||||
if failed > 0 { Err(format!("{failed} file(s) failed")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
/// The input images of `dir`, sorted by name, at the top (an empty subfolder).
|
||||
fn list_inputs(dir: &Path) -> Result<Vec<(PathBuf, PathBuf)>, String> {
|
||||
let mut inputs: Vec<PathBuf> =
|
||||
std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().map(|e| e.path()).filter(|p| is_input(p)).collect();
|
||||
inputs.sort();
|
||||
Ok(inputs.into_iter().map(|p| (p, PathBuf::new())).collect())
|
||||
}
|
||||
|
||||
/// The input images of `dir` and its subfolders (each folder's files sorted by name, then its
|
||||
/// subfolders), with the subfolder relative to `dir`. Links to folders are not followed; a tree
|
||||
/// deeper than the engine's limit is an error.
|
||||
fn list_inputs_recursive(dir: &Path) -> Result<Vec<(PathBuf, PathBuf)>, String> {
|
||||
fn walk(root: &Path, sub: &Path, depth: usize, out: &mut Vec<(PathBuf, PathBuf)>) -> Result<(), String> {
|
||||
let dir = root.join(sub);
|
||||
let mut entries: Vec<std::fs::DirEntry> = std::fs::read_dir(&dir).map_err(|e| format!("{}: {e}", dir.display()))?.flatten().collect();
|
||||
entries.sort_by_key(std::fs::DirEntry::file_name);
|
||||
let mut folders = Vec::new();
|
||||
for e in entries {
|
||||
let Ok(ft) = e.file_type() else { continue };
|
||||
if ft.is_dir() {
|
||||
folders.push(e.file_name());
|
||||
} else if is_input(&e.path()) {
|
||||
if out.len() >= photocraft_engine::batch::MAX_FILES {
|
||||
return Err(format!("{}: more than {} images", root.display(), photocraft_engine::batch::MAX_FILES));
|
||||
}
|
||||
out.push((e.path(), sub.to_path_buf()));
|
||||
}
|
||||
}
|
||||
for name in folders {
|
||||
if depth >= photocraft_engine::batch::MAX_DEPTH {
|
||||
return Err(format!("{}: folders nested deeper than {} levels", dir.join(&name).display(), photocraft_engine::batch::MAX_DEPTH));
|
||||
}
|
||||
walk(root, &sub.join(name), depth + 1, out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, Path::new(""), 0, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn droplet(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
|
||||
let (file, inputs) = a.positional.split_first().ok_or("droplet needs <file.pcdroplet> and inputs")?;
|
||||
if inputs.is_empty() {
|
||||
@@ -753,4 +827,56 @@ mod batch_action_set_tests {
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// `--recursive` mirrors the subfolders under `--out`, `--naming` names the results,
|
||||
/// `--stop-on-error` skips the rest after a failure and `--error-log` records the failures.
|
||||
#[test]
|
||||
fn batch_recursive_naming_stop_and_log() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-cli-batch-opts-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let path = |name: &str| dir.join(name).to_string_lossy().to_string();
|
||||
std::fs::create_dir_all(dir.join("in/sub")).unwrap();
|
||||
for name in ["in/a", "in/sub/a", "in/sub/c"] {
|
||||
let (code, _, stderr) = invoke(&["run", "--new", r#"{"width":8,"height":6}"#, "--out", &path(&format!("{name}.png"))]);
|
||||
assert_eq!(code, 0, "{stderr}");
|
||||
}
|
||||
std::fs::write(dir.join("in/sub/b.png"), b"not a png").unwrap();
|
||||
std::fs::write(dir.join("steps.json"), r#"[["image.imageRotation.90cw", {}]]"#).unwrap();
|
||||
let (code, stdout, stderr) = invoke(&[
|
||||
"batch",
|
||||
"--actions",
|
||||
&path("steps.json"),
|
||||
"--in",
|
||||
&path("in"),
|
||||
"--out",
|
||||
&path("out"),
|
||||
"--recursive",
|
||||
"--naming",
|
||||
"{name}-{serial:2}.{ext}",
|
||||
"--start-serial",
|
||||
"5",
|
||||
"--error-log",
|
||||
&path("errors.txt"),
|
||||
]);
|
||||
assert_ne!(code, 0, "{stdout}");
|
||||
assert!(dir.join("out/a-05.png").is_file() && dir.join("out/sub/a-06.png").is_file() && dir.join("out/sub/c-08.png").is_file(), "{stdout}\n{stderr}");
|
||||
assert!(stdout.contains("3 succeeded, 1 failed"), "{stdout}");
|
||||
let log = std::fs::read_to_string(dir.join("errors.txt")).unwrap();
|
||||
assert!(log.contains("1 error(s)") && log.contains("b.png"), "{log}");
|
||||
|
||||
let (code, stdout, stderr) =
|
||||
invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("out2"), "--recursive", "--stop-on-error"]);
|
||||
assert_ne!(code, 0, "{stdout}");
|
||||
assert!(stdout.contains("2 succeeded, 1 failed, 1 skipped"), "{stdout}");
|
||||
assert!(stderr.contains("--stop-on-error"), "{stderr}");
|
||||
assert!(!dir.join("out2/sub/c.png").exists(), "c comes after the failure and is skipped");
|
||||
|
||||
let (code, _, stderr) = invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("out3"), "--naming", "{nope}"]);
|
||||
assert_ne!(code, 0);
|
||||
assert!(stderr.contains("--naming"), "{stderr}");
|
||||
let (code, _, stderr) = invoke(&["batch", "--actions", &path("steps.json"), "--in", &path("in"), "--out", &path("out3"), "--start-serial", "x"]);
|
||||
assert_ne!(code, 0);
|
||||
assert!(stderr.contains("--start-serial"), "{stderr}");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,8 @@ roxmltree = "0.20"
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
tempfile = "3"
|
||||
# Batch file naming: the local date for the `{date:…}` tokens.
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock"] }
|
||||
|
||||
[dev-dependencies]
|
||||
photocraft-affinity = { workspace = true, features = ["synth"] }
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
//! Batch options (#219): files in subfolders, file naming, stop on error, an error log, and
|
||||
//! progress with cancel. Shared by File › Automate › Batch (which also takes the open
|
||||
//! documents as its source), Image Processor, the Lens Correction batch and the CLI's `batch`.
|
||||
//!
|
||||
//! The naming template follows Photoshop's File Naming fields as tokens in one string:
|
||||
//! `{name}` / `{NAME}` / `{Name}` (the document name as is, upper case, capitalised),
|
||||
//! `{serial}` to `{serial:4}` (a serial number, padded to that many digits, from
|
||||
//! `startSerial`), `{letter}` / `{LETTER}` (a serial letter: a, b … z, aa, ab …),
|
||||
//! `{date:mmddyy}`, `{date:mmdd}`, `{date:yyyymmdd}`, `{date:yymmdd}`, `{date:yyddmm}`,
|
||||
//! `{date:ddmmyy}` (today's date), `{ext}` / `{EXT}` (the output extension), and any other
|
||||
//! text literally. The default is `{name}.{ext}`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// One input of a batch: a file, and the folder it was found in relative to the input folder
|
||||
/// (`""` at the top). The output mirrors that folder, so files of the same name in different
|
||||
/// subfolders don't collide.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Input {
|
||||
pub path: String,
|
||||
pub subdir: String,
|
||||
}
|
||||
|
||||
impl Input {
|
||||
pub fn file(path: &str) -> Self {
|
||||
Self { path: path.to_string(), subdir: String::new() }
|
||||
}
|
||||
}
|
||||
|
||||
fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
|
||||
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
|
||||
}
|
||||
|
||||
/// The inputs of a batch command: `"input"` is a folder (with `"includeSubfolders"`, its
|
||||
/// subfolders too) or an array of files.
|
||||
pub(crate) fn inputs(p: &Value, cmd: &str) -> Result<Vec<Input>> {
|
||||
let recurse = p.get("includeSubfolders").and_then(Value::as_bool).unwrap_or(false);
|
||||
match p.get("input").or_else(|| p.get("files")) {
|
||||
Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(Input::file).collect()),
|
||||
Some(Value::String(dir)) if recurse => list_images_recursive(dir),
|
||||
Some(Value::String(dir)) => Ok(crate::file_cmds::list_images(dir)?.into_iter().map(|path| Input::file(&path)).collect()),
|
||||
_ => Err(bad(cmd, "missing \"input\" (folder or array of files)")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Deepest subfolder a recursive listing enters; deeper trees are refused rather than walked
|
||||
/// forever (a loop of symbolic links is not followed either: links to folders are skipped).
|
||||
pub const MAX_DEPTH: usize = 32;
|
||||
/// Most files a recursive listing returns.
|
||||
pub const MAX_FILES: usize = 100_000;
|
||||
|
||||
/// The images of `dir` and its subfolders: each folder's files sorted by name, then its
|
||||
/// subfolders sorted by name.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn list_images_recursive(dir: &str) -> Result<Vec<Input>> {
|
||||
fn walk(root: &str, sub: &str, depth: usize, out: &mut Vec<Input>) -> Result<()> {
|
||||
let dir = if sub.is_empty() { root.to_string() } else { crate::file_cmds::join(root, sub) };
|
||||
let rd = std::fs::read_dir(&dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))?;
|
||||
let mut entries: Vec<std::fs::DirEntry> = rd.filter_map(|e| e.ok()).collect();
|
||||
entries.sort_by_key(std::fs::DirEntry::file_name);
|
||||
let mut folders = Vec::new();
|
||||
for e in entries {
|
||||
// `file_type` does not follow symbolic links, so a linked folder is not entered.
|
||||
let Ok(ft) = e.file_type() else { continue };
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
let path = e.path();
|
||||
if ft.is_dir() {
|
||||
folders.push(name);
|
||||
} else if path.is_file() && crate::file_cmds::openable_name(&name) {
|
||||
if out.len() >= MAX_FILES {
|
||||
return Err(EngineError::Other(format!("{root}: more than {MAX_FILES} images")));
|
||||
}
|
||||
out.push(Input { path: path.to_string_lossy().into_owned(), subdir: sub.to_string() });
|
||||
}
|
||||
}
|
||||
for name in folders {
|
||||
if depth >= MAX_DEPTH {
|
||||
return Err(EngineError::Other(format!("{dir}/{name}: folders nested deeper than {MAX_DEPTH} levels")));
|
||||
}
|
||||
let sub = if sub.is_empty() { name } else { format!("{sub}/{name}") };
|
||||
walk(root, &sub, depth + 1, out)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
walk(dir, "", 0, &mut out)?;
|
||||
Ok(out)
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
pub fn list_images_recursive(dir: &str) -> Result<Vec<Input>> {
|
||||
Err(EngineError::Other(format!("cannot list {dir}: no file system on the web")))
|
||||
}
|
||||
|
||||
/// Today's date, for the naming template's date tokens.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Date {
|
||||
pub year: i32,
|
||||
pub month: u32,
|
||||
pub day: u32,
|
||||
}
|
||||
|
||||
impl Date {
|
||||
/// The local date. On the web (where the batch commands don't run) the epoch.
|
||||
pub fn today() -> Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use chrono::Datelike;
|
||||
let now = chrono::Local::now();
|
||||
Self { year: now.year(), month: now.month(), day: now.day() }
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
Self { year: 1970, month: 1, day: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
fn format(self, fmt: DateFmt) -> String {
|
||||
let (y, m, d) = (self.year.rem_euclid(10_000), self.month, self.day);
|
||||
let yy = y % 100;
|
||||
match fmt {
|
||||
DateFmt::Mmddyy => format!("{m:02}{d:02}{yy:02}"),
|
||||
DateFmt::Mmdd => format!("{m:02}{d:02}"),
|
||||
DateFmt::Yyyymmdd => format!("{y:04}{m:02}{d:02}"),
|
||||
DateFmt::Yymmdd => format!("{yy:02}{m:02}{d:02}"),
|
||||
DateFmt::Yyddmm => format!("{yy:02}{d:02}{m:02}"),
|
||||
DateFmt::Ddmmyy => format!("{d:02}{m:02}{yy:02}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum DateFmt {
|
||||
Mmddyy,
|
||||
Mmdd,
|
||||
Yyyymmdd,
|
||||
Yymmdd,
|
||||
Yyddmm,
|
||||
Ddmmyy,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Case {
|
||||
AsIs,
|
||||
Upper,
|
||||
Title,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Seg {
|
||||
Lit(String),
|
||||
Name(Case),
|
||||
/// A serial number padded to this many digits.
|
||||
Serial(usize),
|
||||
/// A serial letter, upper case when true.
|
||||
Letter(bool),
|
||||
Date(DateFmt),
|
||||
/// The output extension, upper case when true.
|
||||
Ext(bool),
|
||||
}
|
||||
|
||||
/// A parsed file naming template (see the module doc).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Naming {
|
||||
segs: Vec<Seg>,
|
||||
start: u64,
|
||||
}
|
||||
|
||||
impl Naming {
|
||||
/// The template every batch uses unless told otherwise: `<document name>.<extension>`.
|
||||
pub const DEFAULT: &'static str = "{name}.{ext}";
|
||||
|
||||
/// Parse `template`; serial numbers count from `start`.
|
||||
pub fn parse(template: &str, start: u64) -> std::result::Result<Self, String> {
|
||||
let mut segs = Vec::new();
|
||||
let mut lit = String::new();
|
||||
let mut rest = template;
|
||||
while let Some(i) = rest.find('{') {
|
||||
lit.push_str(rest.get(..i).unwrap_or_default());
|
||||
let after = rest.get(i + 1..).unwrap_or_default();
|
||||
let Some(j) = after.find('}') else { return Err("unclosed `{`".into()) };
|
||||
let token = after.get(..j).unwrap_or_default();
|
||||
let seg = match token {
|
||||
"name" => Seg::Name(Case::AsIs),
|
||||
"NAME" => Seg::Name(Case::Upper),
|
||||
"Name" => Seg::Name(Case::Title),
|
||||
"serial" => Seg::Serial(1),
|
||||
"letter" => Seg::Letter(false),
|
||||
"LETTER" => Seg::Letter(true),
|
||||
"ext" => Seg::Ext(false),
|
||||
"EXT" => Seg::Ext(true),
|
||||
"date:mmddyy" => Seg::Date(DateFmt::Mmddyy),
|
||||
"date:mmdd" => Seg::Date(DateFmt::Mmdd),
|
||||
"date:yyyymmdd" => Seg::Date(DateFmt::Yyyymmdd),
|
||||
"date:yymmdd" => Seg::Date(DateFmt::Yymmdd),
|
||||
"date:yyddmm" => Seg::Date(DateFmt::Yyddmm),
|
||||
"date:ddmmyy" => Seg::Date(DateFmt::Ddmmyy),
|
||||
_ => match token.strip_prefix("serial:").and_then(|n| n.parse::<usize>().ok()) {
|
||||
Some(n) if (1..=4).contains(&n) => Seg::Serial(n),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"unknown token `{{{token}}}` (tokens: {{name}}, {{NAME}}, {{Name}}, {{serial}}, {{serial:2}}, {{serial:3}}, {{serial:4}}, {{letter}}, {{LETTER}}, {{date:mmddyy}}, {{date:mmdd}}, {{date:yyyymmdd}}, {{date:yymmdd}}, {{date:yyddmm}}, {{date:ddmmyy}}, {{ext}}, {{EXT}})"
|
||||
));
|
||||
}
|
||||
},
|
||||
};
|
||||
if !lit.is_empty() {
|
||||
segs.push(Seg::Lit(std::mem::take(&mut lit)));
|
||||
}
|
||||
segs.push(seg);
|
||||
rest = after.get(j + 1..).unwrap_or_default();
|
||||
}
|
||||
if rest.contains('}') {
|
||||
return Err("stray `}`".into());
|
||||
}
|
||||
lit.push_str(rest);
|
||||
if !lit.is_empty() {
|
||||
segs.push(Seg::Lit(lit));
|
||||
}
|
||||
if segs.is_empty() {
|
||||
return Err("empty".into());
|
||||
}
|
||||
let text: String = segs.iter().filter_map(|s| if let Seg::Lit(t) = s { Some(t.as_str()) } else { None }).collect();
|
||||
if text.contains(['/', '\\', ':']) || text.split('.').any(|part| part == "..") {
|
||||
return Err("file names can't contain path separators or `..`".into());
|
||||
}
|
||||
Ok(Self { segs, start })
|
||||
}
|
||||
|
||||
/// `<name><suffix>.<ext>`, the naming of the commands without a template.
|
||||
pub fn plain(suffix: &str) -> Self {
|
||||
let mut segs = vec![Seg::Name(Case::AsIs)];
|
||||
if !suffix.is_empty() {
|
||||
segs.push(Seg::Lit(suffix.to_string()));
|
||||
}
|
||||
segs.extend([Seg::Lit(".".into()), Seg::Ext(false)]);
|
||||
Self { segs, start: 1 }
|
||||
}
|
||||
|
||||
/// The file name of the `index`-th (0-based) output named `stem` with extension `ext`.
|
||||
pub fn file_name(&self, stem: &str, ext: &str, index: u64, date: Date) -> String {
|
||||
let serial = self.start.saturating_add(index);
|
||||
let mut out = String::new();
|
||||
for seg in &self.segs {
|
||||
match seg {
|
||||
Seg::Lit(t) => out.push_str(t),
|
||||
Seg::Name(Case::AsIs) => out.push_str(stem),
|
||||
Seg::Name(Case::Upper) => out.push_str(&stem.to_uppercase()),
|
||||
Seg::Name(Case::Title) => {
|
||||
let mut chars = stem.chars();
|
||||
if let Some(first) = chars.next() {
|
||||
out.extend(first.to_uppercase());
|
||||
out.push_str(&chars.as_str().to_lowercase());
|
||||
}
|
||||
}
|
||||
Seg::Serial(digits) => out.push_str(&format!("{serial:0width$}", width = *digits)),
|
||||
Seg::Letter(upper) => out.push_str(&letters(serial, *upper)),
|
||||
Seg::Date(fmt) => out.push_str(&date.format(*fmt)),
|
||||
Seg::Ext(false) => out.push_str(&ext.to_lowercase()),
|
||||
Seg::Ext(true) => out.push_str(&ext.to_uppercase()),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Serial letters: 1 → a, 26 → z, 27 → aa, 28 → ab … (0 → an empty string).
|
||||
fn letters(mut n: u64, upper: bool) -> String {
|
||||
let mut out = Vec::new();
|
||||
while n > 0 {
|
||||
n -= 1;
|
||||
let c = b'a' + (n % 26) as u8;
|
||||
out.push(if upper { c.to_ascii_uppercase() } else { c });
|
||||
n /= 26;
|
||||
}
|
||||
out.reverse();
|
||||
String::from_utf8(out).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// How a batch run names its files and handles errors.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Options {
|
||||
pub naming: Naming,
|
||||
/// Stop at the first file that fails (the rest are reported as skipped) instead of going
|
||||
/// on with the next.
|
||||
pub stop_on_error: bool,
|
||||
/// Write the errors of the run to this text file (Photoshop's "Log Errors to File").
|
||||
pub error_log: Option<String>,
|
||||
}
|
||||
|
||||
impl Options {
|
||||
/// `naming`, `startSerial`, `stopOnError` and `errorLog` from command `cmd`'s params.
|
||||
pub(crate) fn from_params(p: &Value, cmd: &str) -> Result<Self> {
|
||||
let template = p.get("naming").and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).unwrap_or(Naming::DEFAULT);
|
||||
let start = match p.get("startSerial") {
|
||||
None | Some(Value::Null) => 1,
|
||||
Some(v) => v.as_u64().ok_or_else(|| bad(cmd, "\"startSerial\" must be a non-negative integer"))?,
|
||||
};
|
||||
let naming = Naming::parse(template, start).map_err(|m| bad(cmd, format!("\"naming\": {m}")))?;
|
||||
let stop_on_error = p.get("stopOnError").and_then(Value::as_bool).unwrap_or(false);
|
||||
let error_log = p.get("errorLog").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string);
|
||||
Ok(Self { naming, stop_on_error, error_log })
|
||||
}
|
||||
|
||||
/// The options of the commands without them: `<name><suffix>.<ext>`, every file, no log.
|
||||
pub fn plain(suffix: &str) -> Self {
|
||||
Self { naming: Naming::plain(suffix), stop_on_error: false, error_log: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the errors of a run to `path`, one per line.
|
||||
pub(crate) fn write_error_log(path: &str, errors: &[Value], date: Date) -> Result<()> {
|
||||
let mut text = format!("PhotoCraft Batch: {} error(s) on {}\n", errors.len(), date.format(DateFmt::Yyyymmdd));
|
||||
for e in errors {
|
||||
let what = e.get("file").or_else(|| e.get("document")).and_then(Value::as_str).unwrap_or("?");
|
||||
let why = e.get("error").and_then(Value::as_str).unwrap_or("?");
|
||||
text.push_str(&format!("{what}: {why}\n"));
|
||||
}
|
||||
crate::file_cmds::write_file(path, text.as_bytes()).map_err(|e| EngineError::Other(format!("error log: {e}")))
|
||||
}
|
||||
|
||||
/// The outcome of a run, the shape every batch command returns.
|
||||
pub(crate) fn outcome(files: Vec<String>, errors: Vec<Value>, stopped: Option<(String, Vec<String>)>, error_log: Option<&str>) -> Value {
|
||||
let logged = !errors.is_empty();
|
||||
let mut r = json!({"files": files, "errors": errors});
|
||||
if let Some((at, skipped)) = stopped {
|
||||
r["stopped"] = json!(at);
|
||||
r["skipped"] = json!(skipped);
|
||||
}
|
||||
if let (Some(log), true) = (error_log, logged) {
|
||||
r["errorLog"] = json!(log);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,248 @@
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::*;
|
||||
use crate::Session;
|
||||
use crate::file_cmds::{join, save_doc};
|
||||
use crate::jobs::{JobCtx, Started};
|
||||
|
||||
fn tmp(name: &str) -> String {
|
||||
let d = std::env::temp_dir().join(format!("photocraft-batch-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn png(dir: &str, name: &str, color: &str) -> String {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 6, "background": color})).unwrap();
|
||||
let path = join(dir, name);
|
||||
std::fs::create_dir_all(std::path::Path::new(&path).parent().unwrap()).unwrap();
|
||||
save_doc(&s.active().unwrap().doc, &path, None).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
const DATE: Date = Date { year: 2026, month: 10, day: 12 };
|
||||
|
||||
fn name(template: &str, start: u64, stem: &str, ext: &str, index: u64) -> String {
|
||||
Naming::parse(template, start).unwrap().file_name(stem, ext, index, DATE)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_tokens() {
|
||||
assert_eq!(name("{name}.{ext}", 1, "Photo", "jpg", 0), "Photo.jpg");
|
||||
assert_eq!(name("{NAME}_{Name}.{EXT}", 1, "my Photo", "JPG", 0), "MY PHOTO_My photo.JPG");
|
||||
assert_eq!(name("{name}-{serial}.{ext}", 1, "a", "png", 0), "a-1.png");
|
||||
assert_eq!(name("{name}-{serial:3}.{ext}", 7, "a", "png", 2), "a-009.png");
|
||||
assert_eq!(name("{serial:2}", 1, "a", "png", 150), "151", "a serial longer than its width keeps every digit");
|
||||
assert_eq!(name("{letter}{LETTER}", 1, "a", "png", 0), "aA");
|
||||
assert_eq!(name("{letter}", 1, "a", "png", 25), "z");
|
||||
assert_eq!(name("{letter}", 1, "a", "png", 26), "aa");
|
||||
assert_eq!(name("{LETTER}", 1, "a", "png", 27), "AB");
|
||||
assert_eq!(
|
||||
name("{date:mmddyy} {date:mmdd} {date:yyyymmdd} {date:yymmdd} {date:yyddmm} {date:ddmmyy}", 1, "a", "png", 0),
|
||||
"101226 1012 20261012 261012 261210 121026"
|
||||
);
|
||||
assert_eq!(name("final copy.{ext}", 1, "a", "png", 0), "final copy.png", "literal text");
|
||||
assert_eq!(Naming::plain("-x").file_name("a", "PNG", 0, DATE), "a-x.png");
|
||||
assert_eq!(Naming::plain("").file_name("a", "jpg", 0, DATE), "a.jpg");
|
||||
assert_eq!(Naming::parse(Naming::DEFAULT, 1).unwrap(), Naming::plain(""), "the default template is the plain naming");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_rejects_bad_templates() {
|
||||
for (t, why) in [
|
||||
("{name", "unclosed"),
|
||||
("{name}}", "stray"),
|
||||
("{nope}.{ext}", "unknown token"),
|
||||
("{serial:5}", "unknown token"),
|
||||
("{serial:0}", "unknown token"),
|
||||
("{date:yyyy}", "unknown token"),
|
||||
("", "empty"),
|
||||
("../{name}.{ext}", "separators"),
|
||||
("sub/{name}", "separators"),
|
||||
("{name}\\x", "separators"),
|
||||
] {
|
||||
let e = Naming::parse(t, 1).unwrap_err();
|
||||
assert!(e.contains(why), "{t:?}: {e}");
|
||||
}
|
||||
assert_eq!(name("v1.2.{ext}", 1, "a", "png", 0), "v1.2.png", "dots inside a name are fine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_from_params() {
|
||||
let o = Options::from_params(&json!({}), "x").unwrap();
|
||||
assert_eq!(o, Options::plain(""));
|
||||
let o =
|
||||
Options::from_params(&json!({"naming": " {name}-{serial:2}.{ext} ", "startSerial": 5, "stopOnError": true, "errorLog": "/tmp/log.txt"}), "x").unwrap();
|
||||
assert!(o.stop_on_error && o.error_log.as_deref() == Some("/tmp/log.txt"));
|
||||
assert_eq!(o.naming.file_name("a", "png", 0, DATE), "a-05.png");
|
||||
let e = Options::from_params(&json!({"naming": "{bad}"}), "x").unwrap_err();
|
||||
assert!(e.to_string().contains("naming"), "{e}");
|
||||
assert!(Options::from_params(&json!({"startSerial": -1}), "x").is_err());
|
||||
assert!(Options::from_params(&json!({"startSerial": 1.5}), "x").is_err());
|
||||
assert_eq!(Options::from_params(&json!({"naming": "", "errorLog": " "}), "x").unwrap(), Options::plain(""), "empty strings mean the defaults");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_listing_mirrors_folders() {
|
||||
let dir = tmp("list");
|
||||
png(&dir, "b.png", "#ffffff");
|
||||
png(&dir, "a.png", "#ffffff");
|
||||
png(&dir, "sub/z.png", "#ffffff");
|
||||
png(&dir, "sub/inner/y.png", "#ffffff");
|
||||
png(&dir, "zsub/x.png", "#ffffff");
|
||||
std::fs::write(join(&dir, "sub/notes.txt"), "no").unwrap();
|
||||
let flat = inputs(&json!({"input": dir}), "x").unwrap();
|
||||
assert_eq!(flat.iter().map(|i| crate::file_cmds::file_name(&i.path)).collect::<Vec<_>>(), ["a.png", "b.png"], "without the flag, only the top folder");
|
||||
let all = inputs(&json!({"input": dir, "includeSubfolders": true}), "x").unwrap();
|
||||
let got: Vec<(String, &str)> = all.iter().map(|i| (crate::file_cmds::file_name(&i.path), i.subdir.as_str())).collect();
|
||||
assert_eq!(
|
||||
got,
|
||||
[("a.png".to_string(), ""), ("b.png".into(), ""), ("z.png".into(), "sub"), ("y.png".into(), "sub/inner"), ("x.png".into(), "zsub")],
|
||||
"each folder's files, then its subfolders, sorted by name"
|
||||
);
|
||||
assert!(list_images_recursive(&join(&dir, "missing")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_into_subfolders_with_a_naming_template() {
|
||||
let dir = tmp("batch");
|
||||
let input = join(&dir, "in");
|
||||
png(&input, "a.png", "#ff0000");
|
||||
png(&input, "sub/a.png", "#00ff00");
|
||||
let out = join(&dir, "out");
|
||||
let mut s = Session::new();
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"steps": [["image.adjustments.invert", {}]], "input": input, "includeSubfolders": true, "output": out, "format": "png", "naming": "{name}_{serial:2}.{ext}", "startSerial": 10}),
|
||||
)
|
||||
.unwrap();
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(files, [join(&out, "a_10.png"), join(&out, "sub/a_11.png")], "{r}");
|
||||
assert!(r["errors"].as_array().unwrap().is_empty() && r.get("stopped").is_none(), "{r}");
|
||||
for f in files {
|
||||
assert!(std::path::Path::new(f).is_file(), "{f} written");
|
||||
}
|
||||
// Without the mirrored folders the two a.png would collide: the second is reported.
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"steps": [], "input": [join(&input, "a.png"), join(&input, "sub/a.png")], "output": join(&dir, "flat"), "format": "png"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["files"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stop_on_error_skips_the_rest_and_logs() {
|
||||
let dir = tmp("stop");
|
||||
let input = join(&dir, "in");
|
||||
png(&input, "a.png", "#ff0000");
|
||||
std::fs::write(join(&input, "b.png"), b"not a png").unwrap();
|
||||
png(&input, "c.png", "#0000ff");
|
||||
let out = join(&dir, "out");
|
||||
let log = join(&dir, "errors.txt");
|
||||
let mut s = Session::new();
|
||||
let p = json!({"steps": [], "input": input, "output": out, "format": "png", "errorLog": log});
|
||||
let r = s.execute("file.automate.batch", p.clone()).unwrap();
|
||||
assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (2, 1), "every file is tried: {r}");
|
||||
assert!(r.get("stopped").is_none());
|
||||
assert_eq!(r["errorLog"], json!(log));
|
||||
let text = std::fs::read_to_string(&log).unwrap();
|
||||
assert!(text.starts_with("PhotoCraft Batch: 1 error(s)") && text.contains("b.png: "), "{text}");
|
||||
|
||||
let mut p = p;
|
||||
p["stopOnError"] = json!(true);
|
||||
p["output"] = json!(join(&dir, "out2"));
|
||||
let r = s.execute("file.automate.batch", p).unwrap();
|
||||
assert_eq!((r["files"].as_array().unwrap().len(), r["errors"].as_array().unwrap().len()), (1, 1), "{r}");
|
||||
// Folder listings carry the platform's separators (`\` on Windows): compare the file names.
|
||||
let name = |v: &Value| crate::file_cmds::file_name(v.as_str().unwrap());
|
||||
assert_eq!(name(&r["stopped"]), "b.png", "{r}");
|
||||
assert_eq!(r["skipped"].as_array().unwrap().iter().map(name).collect::<Vec<_>>(), ["c.png"], "{r}");
|
||||
assert!(!std::path::Path::new(&join(&dir, "out2/c.png")).exists(), "c was not processed");
|
||||
|
||||
// No errors: no log is written (an old one is not touched either).
|
||||
std::fs::remove_file(&log).unwrap();
|
||||
let r = s
|
||||
.execute("file.automate.batch", json!({"steps": [], "input": [join(&input, "a.png")], "output": join(&dir, "out3"), "format": "png", "errorLog": log}))
|
||||
.unwrap();
|
||||
assert!(r.get("errorLog").is_none() && !std::path::Path::new(&log).exists(), "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cancelled_run_stops_and_still_logs() {
|
||||
let dir = tmp("cancel");
|
||||
let input = join(&dir, "in");
|
||||
let a = png(&input, "a.png", "#ff0000");
|
||||
let log = join(&dir, "errors.txt");
|
||||
let ctx = JobCtx::new();
|
||||
ctx.cancel();
|
||||
let options = Options { naming: Naming::plain(""), stop_on_error: false, error_log: Some(log.clone()) };
|
||||
let r = crate::file_cmds::process_files(&[Input::file(&a)], &join(&dir, "out"), "png", Default::default(), &options, Some(&ctx), &|_| Ok(()));
|
||||
assert!(matches!(r, Err(crate::EngineError::Cancelled)), "{r:?}");
|
||||
assert!(!std::path::Path::new(&join(&dir, "out/a.png")).exists(), "nothing was written after the cancel");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_runs_as_a_background_job_with_progress() {
|
||||
let dir = tmp("job");
|
||||
let input = join(&dir, "in");
|
||||
png(&input, "a.png", "#ff0000");
|
||||
png(&input, "b.png", "#00ff00");
|
||||
let out = join(&dir, "out");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
|
||||
let r = s.start("file.automate.batch", json!({"steps": [["image.adjustments.invert", {}]], "input": input, "output": out, "format": "png"})).unwrap();
|
||||
let Started::Job(id) = r else { panic!("expected a job: {r:?}") };
|
||||
let v = s.wait_job(id).unwrap();
|
||||
assert_eq!(v["files"].as_array().unwrap().len(), 2, "{v}");
|
||||
assert!(s.active().is_some_and(|d| d.doc.size.width == 4), "the open document is untouched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_open_runs_the_steps_on_every_open_document() {
|
||||
let dir = tmp("open");
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 6, "background": "white", "name": "First"})).unwrap();
|
||||
s.execute("file.new", json!({"width": 8, "height": 6, "background": "white", "name": "Second"})).unwrap();
|
||||
s.set_active(0);
|
||||
let out = join(&dir, "out");
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"steps": [["image.adjustments.invert", {}]], "source": "open", "output": out, "format": "png", "naming": "{serial:2}-{name}.{ext}"}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["documents"], 2);
|
||||
let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect();
|
||||
assert_eq!(files, [join(&out, "01-First.png"), join(&out, "02-Second.png")], "{r}");
|
||||
assert_eq!(s.active_index(), Some(0), "the active document is restored");
|
||||
for d in s.documents() {
|
||||
let px = photocraft_compose::render(&d.doc, photocraft_geom::Rect::new(1, 1, 2, 2)).px[0];
|
||||
assert!(px[0] < 0.01, "both documents were inverted: {px:?}");
|
||||
assert!(d.history.can_undo(), "as undoable steps");
|
||||
}
|
||||
// Destination None: no output, the documents just change.
|
||||
let r = s.execute("file.automate.batch", json!({"steps": [["image.adjustments.invert", {}]], "source": "open"})).unwrap();
|
||||
assert!(r["files"].as_array().unwrap().is_empty() && r["errors"].as_array().unwrap().is_empty(), "{r}");
|
||||
// "same" on an untitled document saves a PSD.
|
||||
let r = s.execute("file.automate.batch", json!({"steps": [], "source": "open", "output": join(&dir, "same")})).unwrap();
|
||||
assert!(r["files"][0].as_str().unwrap().ends_with("First.psd"), "{r}");
|
||||
// A failing step with stop on error.
|
||||
let r = s
|
||||
.execute(
|
||||
"file.automate.batch",
|
||||
json!({"steps": [["layer.delete", {"layer": 999_999}]], "source": "open", "stopOnError": true, "errorLog": join(&dir, "log.txt")}),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(r["errors"].as_array().unwrap().len(), 1, "{r}");
|
||||
assert_eq!(r["stopped"], "First");
|
||||
assert_eq!(r["skipped"], json!(["Second"]));
|
||||
assert!(std::fs::read_to_string(join(&dir, "log.txt")).unwrap().contains("First: "));
|
||||
assert!(s.execute("file.automate.batch", json!({"steps": [], "source": "nope"})).is_err());
|
||||
let mut empty = Session::new();
|
||||
assert!(empty.execute("file.automate.batch", json!({"steps": [], "source": "open"})).is_err());
|
||||
}
|
||||
+183
-30
@@ -96,6 +96,12 @@ pub(crate) fn write_file(path: &str, _bytes: &[u8]) -> Result<()> {
|
||||
Err(EngineError::Other(format!("cannot write {path}: no file system on the web")))
|
||||
}
|
||||
|
||||
/// Whether a file name's extension is one the batch commands open.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn openable_name(name: &str) -> bool {
|
||||
name.rsplit_once('.').is_some_and(|(_, ext)| OPENABLE.contains(&ext.to_ascii_lowercase().as_str()))
|
||||
}
|
||||
|
||||
/// Files of a folder that look like images we can open, sorted by name.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn list_images(dir: &str) -> Result<Vec<String>> {
|
||||
@@ -919,25 +925,57 @@ fn parse_steps(v: &Value) -> Result<Vec<(String, Value)>> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Inputs of a batch command: `"input"` is a folder or an array of files.
|
||||
pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {
|
||||
match p.get("input").or_else(|| p.get("files")) {
|
||||
Some(Value::Array(a)) => Ok(a.iter().filter_map(Value::as_str).map(str::to_string).collect()),
|
||||
Some(Value::String(dir)) => list_images(dir),
|
||||
_ => Err(EngineError::BadParams { cmd: cmd.into(), msg: "missing \"input\" (folder or array of files)".into() }),
|
||||
}
|
||||
/// Inputs of a batch command: `"input"` is a folder (with `"includeSubfolders"`, its subfolders
|
||||
/// too) or an array of files. See [`crate::batch::inputs`].
|
||||
pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<crate::batch::Input>> {
|
||||
crate::batch::inputs(p, cmd)
|
||||
}
|
||||
|
||||
/// Opens each input in a scratch session, runs `f` on it and saves it to `output` as `format`
|
||||
/// (`"same"` keeps the input's extension). Errors per file are collected, not fatal.
|
||||
pub(crate) fn process_files(inputs: &[String], output: &str, format: &str, save: SaveOpts, suffix: &str, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn ensure_dir(dir: &str) -> Result<()> {
|
||||
std::fs::create_dir_all(dir).map_err(|e| EngineError::Other(format!("{dir}: {e}")))
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn ensure_dir(dir: &str) -> Result<()> {
|
||||
Err(EngineError::Other(format!("cannot create {dir}: no file system on the web")))
|
||||
}
|
||||
|
||||
/// Opens each input in a scratch session, runs `f` on it and saves it to `output` (in the
|
||||
/// input's subfolder, mirrored) as `format` (`"same"` keeps the input's extension), named by
|
||||
/// `options.naming`. Errors per file are collected, not fatal, unless `options.stop_on_error`;
|
||||
/// they also go to `options.error_log` when set. With a job context, progress is reported per
|
||||
/// file and a cancel stops after the current file (`Err(Cancelled)`; the files written so far
|
||||
/// stay, the log is still written).
|
||||
pub(crate) fn process_files(
|
||||
inputs: &[crate::batch::Input],
|
||||
output: &str,
|
||||
format: &str,
|
||||
save: SaveOpts,
|
||||
options: &crate::batch::Options,
|
||||
ctx: Option<&crate::jobs::JobCtx>,
|
||||
f: &dyn Fn(&mut Session) -> Result<()>,
|
||||
) -> Result<Value> {
|
||||
let mut files = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut written = OutputClaims::default();
|
||||
for path in inputs {
|
||||
let date = crate::batch::Date::today();
|
||||
let total = inputs.len();
|
||||
let mut stopped = None;
|
||||
let mut cancelled = false;
|
||||
let mut done = 0;
|
||||
for (i, input) in inputs.iter().enumerate() {
|
||||
if let Some(ctx) = ctx {
|
||||
if ctx.cancelled() {
|
||||
cancelled = true;
|
||||
break;
|
||||
}
|
||||
ctx.progress(i as f32 / total.max(1) as f32, &format!("{} of {total}: {}", i + 1, file_name(&input.path)));
|
||||
}
|
||||
let path = &input.path;
|
||||
let ext =
|
||||
if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };
|
||||
let out = join(output, &format!("{}{suffix}.{ext}", stem(path)));
|
||||
let dir = if input.subdir.is_empty() { output.to_string() } else { join(output, &input.subdir) };
|
||||
let out = join(&dir, &options.naming.file_name(&stem(path), &ext, i as u64, date));
|
||||
let r = (|| -> Result<()> {
|
||||
written.check(&out).map_err(EngineError::Other)?;
|
||||
let bytes = read_file(path)?;
|
||||
@@ -946,18 +984,38 @@ pub(crate) fn process_files(inputs: &[String], output: &str, format: &str, save:
|
||||
scratch.add_document(doc, Some(path.clone()));
|
||||
f(&mut scratch)?;
|
||||
let d = scratch.active().ok_or(EngineError::NoDocument)?;
|
||||
ensure_dir(&dir)?;
|
||||
save_doc(&d.doc, &out, save)?;
|
||||
Ok(())
|
||||
})();
|
||||
done = i + 1;
|
||||
match r {
|
||||
Ok(()) => {
|
||||
written.record(&out, path);
|
||||
files.push(out);
|
||||
}
|
||||
Err(e) => errors.push(json!({"file": path, "error": e.to_string()})),
|
||||
Err(e) => {
|
||||
errors.push(json!({"file": path, "error": e.to_string()}));
|
||||
if options.stop_on_error {
|
||||
stopped = Some(path.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
json!({"files": files, "errors": errors})
|
||||
if let Some(log) = &options.error_log
|
||||
&& !errors.is_empty()
|
||||
{
|
||||
crate::batch::write_error_log(log, &errors, date)?;
|
||||
}
|
||||
if cancelled {
|
||||
return Err(EngineError::Cancelled);
|
||||
}
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.progress(1.0, "");
|
||||
}
|
||||
let skipped = || inputs.iter().skip(done).map(|i| i.path.clone()).collect();
|
||||
Ok(crate::batch::outcome(files, errors, stopped.map(|at| (at, skipped())), options.error_log.as_deref()))
|
||||
}
|
||||
|
||||
/// The output paths a batch run has written, so a later input whose output name matches an
|
||||
@@ -992,9 +1050,12 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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 inputs = batch_inputs(p, cmd)?;
|
||||
let output = str_param(p, "output", cmd)?.to_string();
|
||||
let options = crate::batch::Options::from_params(p, cmd)?;
|
||||
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
|
||||
let source = p.get("source").and_then(Value::as_str).unwrap_or("folder");
|
||||
if !matches!(source, "folder" | "open") {
|
||||
return Err(EngineError::BadParams { cmd: cmd.into(), msg: format!("unknown source `{source}` (folder or open)") });
|
||||
}
|
||||
// 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") {
|
||||
@@ -1010,17 +1071,109 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
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(s, p, cmd)?, "", &|scratch| {
|
||||
scratch.actions = actions.clone();
|
||||
for (id, params) in &steps {
|
||||
let r = scratch.execute(id, params.clone())?;
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(error) = crate::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(EngineError::Other(error));
|
||||
let save = SaveOpts::from_params(s, p, cmd)?;
|
||||
if source == "open" {
|
||||
return batch_open_documents(s, &steps, p, &options, &format, save, cmd);
|
||||
}
|
||||
let inputs = batch_inputs(p, cmd)?;
|
||||
let output = str_param(p, "output", cmd)?.to_string();
|
||||
// The files are processed on a worker when started as a job (the UI does): the status bar
|
||||
// shows "n of total: file" and Cancel stops after the current file.
|
||||
crate::jobs::run(
|
||||
s,
|
||||
"Batch",
|
||||
false,
|
||||
move |ctx| {
|
||||
process_files(&inputs, &output, &format, save, &options, Some(ctx), &|scratch| {
|
||||
scratch.actions = actions.clone();
|
||||
for (id, params) in &steps {
|
||||
let r = scratch.execute(id, params.clone())?;
|
||||
// A failed step inside a called action makes this file an error, not a saved result.
|
||||
if let Some(error) = crate::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(EngineError::Other(error));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
},
|
||||
|_, v| Ok(v),
|
||||
)
|
||||
}
|
||||
|
||||
/// Batch with Source: Opened Files. The steps run on every open document in turn (as history
|
||||
/// steps of each); with `"output"` a copy of each is saved there, named by the template from
|
||||
/// the document's name (an untitled document saved as `"same"` becomes a PSD, as it would in
|
||||
/// Photoshop); without, the documents just stay changed (Destination: None).
|
||||
fn batch_open_documents(
|
||||
s: &mut Session,
|
||||
steps: &[(String, Value)],
|
||||
p: &Value,
|
||||
options: &crate::batch::Options,
|
||||
format: &str,
|
||||
save: SaveOpts,
|
||||
cmd: &str,
|
||||
) -> Result<Value> {
|
||||
let n = s.documents().len();
|
||||
if n == 0 {
|
||||
return Err(EngineError::NoDocument);
|
||||
}
|
||||
let output = p.get("output").and_then(Value::as_str).map(str::trim).filter(|o| !o.is_empty()).map(str::to_string);
|
||||
let date = crate::batch::Date::today();
|
||||
let prev = s.active_index();
|
||||
let mut files = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let mut written = OutputClaims::default();
|
||||
let mut stopped = None;
|
||||
let mut done = 0;
|
||||
let names: Vec<String> = s.documents().iter().map(|d| d.path.clone().unwrap_or_else(|| d.doc.name.clone())).collect();
|
||||
for (i, name) in names.iter().enumerate() {
|
||||
if !s.set_active(i) {
|
||||
break;
|
||||
}
|
||||
let r = (|| -> Result<()> {
|
||||
for (id, params) in steps {
|
||||
let r = s.execute(id, params.clone())?;
|
||||
if let Some(error) = crate::actions_cmds::nested_failure(id, &r) {
|
||||
return Err(EngineError::Other(error));
|
||||
}
|
||||
}
|
||||
let Some(output) = &output else { return Ok(()) };
|
||||
let ext = if format == "same" {
|
||||
let d = s.documents().get(i).ok_or(EngineError::NoDocument)?;
|
||||
d.path.as_deref().and_then(|p| p.rsplit_once('.')).map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_else(|| "psd".into())
|
||||
} else {
|
||||
format.trim_start_matches('.').to_ascii_lowercase()
|
||||
};
|
||||
let out = join(output, &options.naming.file_name(&stem(name), &ext, i as u64, date));
|
||||
written.check(&out).map_err(EngineError::Other)?;
|
||||
ensure_dir(output)?;
|
||||
let d = s.documents().get(i).ok_or(EngineError::NoDocument)?;
|
||||
save_doc(&d.doc, &out, save)?;
|
||||
written.record(&out, name);
|
||||
files.push(out);
|
||||
Ok(())
|
||||
})();
|
||||
done = i + 1;
|
||||
if let Err(e) = r {
|
||||
errors.push(json!({"document": name, "error": e.to_string()}));
|
||||
if options.stop_on_error {
|
||||
stopped = Some(name.clone());
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
if let Some(i) = prev {
|
||||
s.set_active(i);
|
||||
}
|
||||
if let Some(log) = &options.error_log
|
||||
&& !errors.is_empty()
|
||||
{
|
||||
crate::batch::write_error_log(log, &errors, date)?;
|
||||
}
|
||||
let _ = cmd;
|
||||
let skipped = || names.iter().skip(done).cloned().collect();
|
||||
let mut r = crate::batch::outcome(files, errors, stopped.map(|at| (at, skipped())), options.error_log.as_deref());
|
||||
r["documents"] = json!(n);
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -1034,7 +1187,8 @@ fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
(w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})),
|
||||
};
|
||||
let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false);
|
||||
let r = process_files(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch| {
|
||||
let options = crate::batch::Options::from_params(p, cmd)?;
|
||||
process_files(&inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), &options, None, &|scratch| {
|
||||
if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) {
|
||||
scratch.execute("image.mode.rgb", json!({}))?;
|
||||
}
|
||||
@@ -1042,8 +1196,7 @@ fn image_processor(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
fit_image(scratch, fp)?;
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
Ok(r)
|
||||
})
|
||||
}
|
||||
|
||||
fn load_files_into_stack(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -1535,7 +1688,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,"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),"source":"folder|open"="folder" (open: the steps run on every open document; "input" is ignored, "output" optional: a copy of each is saved there, else they just stay changed),"input":folder|[paths],"includeSubfolders":bool=false (the output mirrors the subfolders),"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","naming":"{name}.{ext}"? (template: {name} {NAME} {Name} {serial} {serial:2..4} {letter} {LETTER} {date:mmddyy|mmdd|yyyymmdd|yymmdd|yyddmm|ddmmyy} {ext} {EXT}, other text literal),"startSerial":int=1,"stopOnError":bool=false (else every file is tried),"errorLog":path? (the errors, one per line),"quality":0..12?,"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, stopped?, skipped?, errorLog?} (an input whose output name was already written in the run goes to errors). Runs as a job: progress per file, Cancel stops after the current one"##,
|
||||
native,
|
||||
batch
|
||||
),
|
||||
@@ -1544,7 +1697,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Image Processor…",
|
||||
&["File", "Scripts"],
|
||||
None,
|
||||
r##"{"input":folder|[paths],"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,
|
||||
r##"{"input":folder|[paths],"includeSubfolders":bool=false,"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","naming":"{name}.{ext}"? (as file.automate.batch),"startSerial":int=1,"stopOnError":bool=false,"errorLog":path?,"quality":0..12=8,"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors, stopped?, skipped?, errorLog?} (an input whose output name was already written in the run goes to errors)"##,
|
||||
native,
|
||||
image_processor
|
||||
),
|
||||
|
||||
@@ -418,20 +418,20 @@ fn lens_batch(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let format = p.get("format").and_then(Value::as_str).unwrap_or("same").to_string();
|
||||
let mut params = p.clone();
|
||||
if let Value::Object(m) = &mut params {
|
||||
for k in ["input", "files", "output", "format", "quality"] {
|
||||
for k in ["input", "files", "includeSubfolders", "output", "format", "naming", "startSerial", "stopOnError", "errorLog", "quality"] {
|
||||
m.remove(k);
|
||||
}
|
||||
// Batch default: the EXIF-driven profile, as Photoshop's dialog suggests.
|
||||
m.entry("profile").or_insert(json!("auto"));
|
||||
}
|
||||
let r = crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::SaveOpts::from_params(s, p, LENS_BATCH)?, "", &|scratch| {
|
||||
let options = crate::batch::Options::from_params(p, LENS_BATCH)?;
|
||||
crate::file_cmds::process_files(&inputs, &output, &format, crate::file_cmds::SaveOpts::from_params(s, p, LENS_BATCH)?, &options, None, &|scratch| {
|
||||
if scratch.active().is_some_and(|d| d.doc.layers.len() > 1) {
|
||||
scratch.execute("layer.flattenImage", json!({}))?;
|
||||
}
|
||||
scratch.execute(LENS, params.clone())?;
|
||||
Ok(())
|
||||
});
|
||||
Ok(r)
|
||||
})
|
||||
}
|
||||
|
||||
const LENS_DOC: &str = r##"{"profile":"none|auto|generic","focalLength":mm=0,"correctDistortion":bool=true,"correctVignette":bool=true,"correctCA":bool=true,"autoScale":bool=false,"distortion":-100..100=0,"redCyan":-100..100=0,"blueYellow":-100..100=0,"vignetteAmount":-100..100=0,"vignetteMidpoint":0..100=50,"vertical":-100..100=0,"horizontal":-100..100=0,"angle":-180..180=0,"scale":50..150=100,"edge":"transparency|edgeExtension|black|white","straighten":[[x,y],[x,y]]?}"##;
|
||||
|
||||
@@ -18,6 +18,7 @@ pub mod artboard_cmds;
|
||||
pub mod atn_cmds;
|
||||
pub mod automate_cmds;
|
||||
pub mod background_cmds;
|
||||
pub mod batch;
|
||||
pub mod brush_cmds;
|
||||
pub mod brush_key_cmds;
|
||||
pub mod brush_preset_cmds;
|
||||
|
||||
@@ -1049,6 +1049,31 @@ mod form_reset_tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The fields a `__form` dialog shows, in order: as `__order` lists them (a dialog's grouping,
|
||||
/// such as Batch's Play / Source / Destination / Errors), the rest alphabetically after them.
|
||||
fn form_keys(f: &Map<String, Value>) -> Vec<String> {
|
||||
let mut keys: Vec<String> = f.keys().filter(|k| !k.starts_with("__")).cloned().collect();
|
||||
if let Some(order) = f.get("__order").and_then(Value::as_array) {
|
||||
let order: Vec<&str> = order.iter().filter_map(Value::as_str).collect();
|
||||
keys.sort_by_key(|k| order.iter().position(|o| o == k).unwrap_or(usize::MAX));
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod form_order_tests {
|
||||
use super::form_keys;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn order_hint_puts_listed_fields_first_and_the_rest_alphabetically() {
|
||||
let f = json!({"zeta": 1, "alpha": 2, "mid": 3, "__order": ["mid", "zeta"], "__form": true});
|
||||
assert_eq!(form_keys(f.as_object().unwrap()), ["mid", "zeta", "alpha"]);
|
||||
let f = json!({"b": 1, "a": 2});
|
||||
assert_eq!(form_keys(f.as_object().unwrap()), ["a", "b"], "without a hint, alphabetical as before");
|
||||
}
|
||||
}
|
||||
|
||||
/// Body of a `__form` dialog: text fields, number fields, checkboxes and `__choices` dropdowns.
|
||||
pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
let choices = f.get("__choices").cloned().unwrap_or(Value::Null);
|
||||
@@ -1056,7 +1081,7 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
// come from `__labels` verbatim; everything else goes through the catalogue.
|
||||
let labels = f.get("__labels").cloned().unwrap_or(Value::Null);
|
||||
let label = |k: &str| labels.get(k).and_then(Value::as_str).map_or_else(|| label_of(k), str::to_string);
|
||||
let keys: Vec<String> = f.keys().filter(|k| !k.starts_with("__")).cloned().collect();
|
||||
let keys = form_keys(f);
|
||||
egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| {
|
||||
for k in keys {
|
||||
let v = f.get(&k).cloned().unwrap_or(Value::Null);
|
||||
@@ -1307,10 +1332,17 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Val
|
||||
};
|
||||
let steps = crate::actions::action_steps(action);
|
||||
let name = action.name.clone();
|
||||
// Photoshop's Batch dialog: Source (folder with Include All Subfolders, or the open
|
||||
// documents), Destination, File Naming, Errors (stop, or log to a file).
|
||||
dialog(
|
||||
app,
|
||||
json!({"action": name, "steps": steps, "input": dir, "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8}),
|
||||
json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"]}),
|
||||
json!({
|
||||
"action": name, "steps": steps, "source": "folder", "input": dir, "includeSubfolders": false,
|
||||
"output": format!("{dir}/batch"), "format": "same", "naming": photocraft_engine::batch::Naming::DEFAULT, "startSerial": 1,
|
||||
"stopOnError": false, "errorLog": "", "quality": null, "__batchQuality": 8,
|
||||
"__order": ["action", "source", "input", "includeSubfolders", "output", "format", "naming", "startSerial", "quality", "stopOnError", "errorLog"],
|
||||
}),
|
||||
json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"], "source": ["folder", "open"]}),
|
||||
)
|
||||
}
|
||||
// Channel workflow dialogs (see channels_panel.rs for the channel references).
|
||||
|
||||
@@ -71,10 +71,11 @@ fn replace_text(h: &mut Harness, value: &str) {
|
||||
fn edit_path(h: &mut Harness, name: &str, value: &Path) {
|
||||
let label = h.get_by_label(name).rect();
|
||||
h.query_all_by_role(egui::accesskit::Role::TextInput)
|
||||
.find(|n| {
|
||||
.filter(|n| {
|
||||
let r = n.rect();
|
||||
r.left() >= label.right() && (r.center().y - label.center().y).abs() < 3.0
|
||||
})
|
||||
.min_by_key(|n| n.rect().left() as i32)
|
||||
.expect("path text field beside its label")
|
||||
.click();
|
||||
h.run_steps(2);
|
||||
@@ -85,11 +86,14 @@ fn edit_path(h: &mut Harness, name: &str, value: &Path) {
|
||||
|
||||
fn edit_quality(h: &mut Harness, value: &str) {
|
||||
let label = h.get_by_label("Quality").rect();
|
||||
// The nearest numeric field to the right on the label's row: a panel's field (the Layers
|
||||
// panel's opacity) can share the row's height now that the dialog is taller.
|
||||
h.query_all_by_role(egui::accesskit::Role::SpinButton)
|
||||
.find(|n| {
|
||||
.filter(|n| {
|
||||
let r = n.rect();
|
||||
r.left() >= label.right() && (r.center().y - label.center().y).abs() < 3.0
|
||||
})
|
||||
.min_by_key(|n| n.rect().left() as i32)
|
||||
.expect("quality numeric field beside its label")
|
||||
.click();
|
||||
h.run_steps(2);
|
||||
|
||||
+1
-1
@@ -161,7 +161,7 @@ cargo run -p photocraft-cli -- batch --actions actions.json --in photos/ --out d
|
||||
cargo run -p photocraft-cli -- commands --filter blur # the command registry
|
||||
```
|
||||
|
||||
`actions.json` holds the steps of a recorded action: `[["<id>", {…}], …]`, `[{"command": "<id>", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. It can also be an Actions set (the Actions panel's `actions.json`, `{"actions": [{"name": …, "steps": […]}, …]}`): `--action <name>` picks the action to play (optional when the set holds one), and the whole set is loaded for each file, so a step that plays another action of the set works. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `run` prints one JSON line per command result.
|
||||
`actions.json` holds the steps of a recorded action: `[["<id>", {…}], …]`, `[{"command": "<id>", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. It can also be an Actions set (the Actions panel's `actions.json`, `{"actions": [{"name": …, "steps": […]}, …]}`): `--action <name>` picks the action to play (optional when the set holds one), and the whole set is loaded for each file, so a step that plays another action of the set works. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `--recursive` takes the subfolders too and mirrors them under `--out`; `--naming <template>` names the results (default `{name}.{ext}`; tokens `{name}` `{NAME}` `{Name}`, `{serial}` to `{serial:4}` counting from `--start-serial`, `{letter}` `{LETTER}`, `{date:mmddyy|mmdd|yyyymmdd|yymmdd|yyddmm|ddmmyy}`, `{ext}` `{EXT}`, other text literal); `--stop-on-error` stops at the first failing file and `--error-log <file>` writes the failures to a text file. The same options are `includeSubfolders`, `naming`, `startSerial`, `stopOnError` and `errorLog` on `file.automate.batch` (which also takes `"source": "open"` for the open documents, and reports progress and takes Cancel as a job), Image Processor and the lens batch. `run` prints one JSON line per command result.
|
||||
|
||||
## Native format (.pcraft)
|
||||
|
||||
|
||||
+11
-6
@@ -1,6 +1,6 @@
|
||||
# Where PhotoCraft falls short of Photoshop
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (G11: Batch subfolders, naming, stop/log, cancel landed, AUTO-219-5 done; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact
|
||||
on the way to beta. This is the work list agents pick from: take the highest-ranked entry that
|
||||
@@ -88,11 +88,15 @@ what an agent can't finish alone.
|
||||
- **Estimate:** 120–200 h.
|
||||
|
||||
### G11. Actions and scripting
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), Batch recursion and naming
|
||||
(AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside the
|
||||
mapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,
|
||||
Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop steps
|
||||
that fail at playback by name.
|
||||
- **Missing:** document-independent action recording (AUTO-219-1), ExtendScript/UXP compatibility.
|
||||
`.atn` steps outside the mapped events (paths, scripts, Generative Fill, Filter Gallery effects
|
||||
other than Spatter, Duplicate Layers into a new document, Bitmap halftone screens…) load as kept
|
||||
Photoshop steps that fail at playback by name.
|
||||
- **Done 2026-10-12:** Batch (AUTO-219-5): Include All Subfolders (the output mirrors the
|
||||
tree), the open documents as the source, a File Naming template (`{name}`, serial numbers and
|
||||
letters, dates, `{ext}`), Stop For Errors with the skipped files reported, Log Errors To File;
|
||||
it runs as a job with per-file progress and Cancel. The Batch dialog, Image Processor, the
|
||||
lens batch and the CLI's `batch` share the options.
|
||||
- **Done 2026-10-12:** Load/Save Actions `.atn` in the panel menu, `batch --actions set.atn`
|
||||
and `actions.load`/`actions.save`; 112 Photoshop events map to commands both ways (Transform,
|
||||
Apply Image, Save for Web, smart-object edits, Gradient Map, Quick Mask, polygon selections,
|
||||
@@ -266,6 +270,7 @@ what an agent can't finish alone.
|
||||
| 2026-10-12 | minor | G4: checkbox-only Brush Settings rows preserve the open controls and Smoothing settings (#4283); no readiness percentage or estimate changed |
|
||||
| 2026-10-12 | minor | G11: Load/Save Actions `.atn` landed (AUTO-219-2 partial); remaining panel work listed |
|
||||
| 2026-10-12 | minor | Refreshed against main: G5 items fixed by #2480, #2327, #2609, #2684, #2675, #2556, #2396, #2527, #2625 and TOOL-214-5/#2442; G7 TOOL-214-7 and Transform On Drop done; G2 #2377 fixed (#2417); G9 UI scale (UI-217-9) and Stamp Visible (UI-217-22) done, prefs 27 of 156; G10 #2225 done (#2482); G13 Khmer, Lao, Myanmar fallback (#3259); G14 CR3 line; G17 Windows ARM64 done (DIST-220-2) |
|
||||
| 2026-10-12 | minor | G11: Batch subfolders, open documents, naming template, stop/log, progress and cancel landed (AUTO-219-5 done) |
|
||||
| 2026-10-11 | minor | D5100 image area and Camera Raw tuning validation; G14 remains open |
|
||||
| 2026-10-11 | minor | G13: Czech dynamic UI text localized; engine messages and native review remain open |
|
||||
| 2026-10-11 | minor | G8: triple/quadruple/five-click type selection done (TYPE-218-8, #3493); Type evidence recounted |
|
||||
|
||||
+2
-2
@@ -11,7 +11,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| [Tools](#tools) | 28 | 14 | 1 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 13 | 6 | 4 | settings that do nothing: 26 of 156 (target 0) |
|
||||
| [Type](#type) | 4 | 3 | 2 | |
|
||||
| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) |
|
||||
| [Automation](#automation) | 6 | 1 | 4 | 631 of 631 menu items live (100.0%) |
|
||||
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |
|
||||
| [Distribution](#distribution) | 5 | 4 | 2 | |
|
||||
| [Open bugs](#open-bugs) | 29 | 2 | 1 | |
|
||||
@@ -231,7 +231,7 @@ Menu wiring (`docs/parity-checklist.md`): 631 of 631 menu items live (100.0%). T
|
||||
| AUTO-219-2 | Actions panel: step and dialog toggles, reorder, delete a step, Stop, sets, .atn import | done | [#219](https://github.com/storytold/photocraft/issues/219) | 2026-10-12: set folders (collapsible, drag between sets, actions.assignSet), dialog toggle column (playback opens the step's dialog seeded with its values and resumes on OK; actions.dialog), Insert Stop… (actions.insert), step toggles, reorder, delete a step; Load/Save Actions (.atn) in the panel menu, CLI batch and actions.load/save (atn_cmds.rs): 90 Photoshop events map to commands both ways, the rest are kept verbatim and fail at playback by name; step toggles, reorder and delete a step done; Stop steps play (actions.stopMessage) but there is no Insert Stop menu item; sets and dialog toggles are stored and round-trip but the panel neither groups by set nor edits the dialog toggle |
|
||||
| AUTO-219-3 | actions.record/stop/play/list commands for agents and the CLI | done | [#219](https://github.com/storytold/photocraft/issues/219) | actions.list/get/record/stop/play/delete in actions_cmds.rs; the panel, CLI and MCP share them. Nested steps pass the session authorize hook. |
|
||||
| AUTO-219-4 | Replay tests for crop, filters, selections and styled text on a second document | done | [#219](https://github.com/storytold/photocraft/issues/219) | actions_cmds.rs: a_recorded_edit_run_replays_on_a_second_document records a crop, a Gaussian Blur, a selection fill and faux-bold type on one document and replays all of them onto a second (plus the original layer/select/fill replay) |
|
||||
| AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel |
|
||||
| AUTO-219-5 | Batch: subfolders, open documents, naming template, progress/cancel, error log, stop | done | [#219](https://github.com/storytold/photocraft/issues/219) | batch.rs + file_cmds.rs: includeSubfolders (output mirrors the tree), source open (the open documents), naming template ({name} {serial:n} {letter} {date:…} {ext}, startSerial), stopOnError with the skipped files, errorLog file; runs as a job with per-file progress and Cancel; the Batch dialog, Image Processor, the lens batch and the CLI (--recursive --naming --start-serial --stop-on-error --error-log) share it |
|
||||
| AUTO-219-6 | Plug-in ABI v2: panel kind, progress/cancel calls, read other layers, Last Filter repeats | missing | [#219](https://github.com/storytold/photocraft/issues/219) | runtime.rs:15 ABI_VERSION = 1; manifest.rs:18 Kind::Filter only |
|
||||
| AUTO-219-7 | Local ONNX models behind a flag, managed in Preferences; subject select, background removal | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No ONNX runtime dependency |
|
||||
| AUTO-219-8 | xtask check that every panel button routes through a command id | missing | [#219](https://github.com/storytold/photocraft/issues/219) | No such xtask check |
|
||||
|
||||
@@ -177,7 +177,7 @@ parity for the area and are already contained in the dimension rows above.
|
||||
| Vector shapes and paths | 55% | 80–140 | Pen, Direct/Path Selection, shapes, shape strokes. Freeform and Curvature Pen (#1054). Add/Delete Anchor Point and Convert Point tools exist (`Tool` enum); missing on-canvas corner radius (TOOL-214-12), path-point nudge; shape parity tracking issue #2496 |
|
||||
| Colour management and modes | 70% | 60–100 | Own ICC engine, soft proof, CMYK/Lab/Indexed/Duotone/Multichannel; no Adobe CMYK profiles, no spot plates (FILE-215-17), monitor profile only at launch |
|
||||
| Camera Raw and computational photo (Photomerge, HDR, lens) | 45% | 120–200 | Raw for DNG/CR2/NEF/ARW/RW2/ORF/RAF(uncompressed)/PEF; no CR3; ACR dialog partial (no masking, calibration); generic lens profiles only |
|
||||
| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2); `.atn` load/save since 2026-10-12 (112 events mapped, the rest kept verbatim); no ExtendScript/UXP |
|
||||
| Automation, actions, batch, scripting | 45% | 120–200 | CLI/MCP/control channel ahead of Photoshop; Actions panel and recording not document-independent (AUTO-219-1/2); `.atn` load/save since 2026-10-12 (112 events mapped, the rest kept verbatim); Batch complete since 2026-10-12 (subfolders, open documents, naming, stop/log, cancel); no ExtendScript/UXP |
|
||||
| File I/O | 60% | 300–500 | See [file-format-parity.md](file-format-parity.md) |
|
||||
| Print, export, Save for Web | 50% | 60–100 | JPEG Options dialog missing (FILE-215-19), no Photoshop PDF, no separations, Save for Web settings not remembered |
|
||||
| Video / timeline, data-driven graphics | 30% | 100–200 | Menu items live; frame model persists in `.pcraft`; no PSD video-layer mapping |
|
||||
@@ -567,6 +567,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md).
|
||||
| 2026-10-12 | minor | `.atn` import: 112 events mapped (TrueGrit Texture Supply sets play end to end); percentages unchanged |
|
||||
| 2026-10-12 | minor | Photoshop Actions `.atn` load and save (90 events mapped both ways); percentages unchanged |
|
||||
| 2026-10-12 | minor | Rows checked against `main` and the regenerated scorecard: menu count 631, Workspace checklist and preference count, transform context menu, Puppet Warp mesh, Select and Mask, anchor-point tools, Smart Object conversion, Stamp Visible, mask targeting, Free Transform commit/cancel, Vietnamese catalog, Windows ARM64; percentages, weights and hours not re-measured |
|
||||
| 2026-10-12 | minor | Batch: subfolders, open documents, naming template, stop/log, progress and cancel (AUTO-219-5); percentages unchanged |
|
||||
| 2026-10-10 | minor | Added measured Tilt-Shift computation/filtered-proxy gains and inconclusive cases; parity percentages and budgets unchanged |
|
||||
| 2026-10-10 | minor | Readiness-by-audience table: percent and hours for full, mainstream and essentials; full number confirmed as the additive weighted sum over dimensions (46%, reported ~45%) |
|
||||
| 2026-10-10 | minor | Added mainstream-practitioner (~43%) and essentials-user (~61%) numbers with written weights and discounts; full ready-for-real-work rechecked against its written weights (46%, reported ~45%), unchanged |
|
||||
|
||||
@@ -42,9 +42,9 @@ note = "actions_cmds.rs: a_recorded_edit_run_replays_on_a_second_document record
|
||||
[[item]]
|
||||
id = "AUTO-219-5"
|
||||
target = "Batch: subfolders, open documents, naming template, progress/cancel, error log, stop"
|
||||
status = "partial"
|
||||
status = "done"
|
||||
issue = 219
|
||||
note = "file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel"
|
||||
note = "batch.rs + file_cmds.rs: includeSubfolders (output mirrors the tree), source open (the open documents), naming template ({name} {serial:n} {letter} {date:…} {ext}, startSerial), stopOnError with the skipped files, errorLog file; runs as a job with per-file progress and Cancel; the Batch dialog, Image Processor, the lens batch and the CLI (--recursive --naming --start-serial --stop-on-error --error-log) share it"
|
||||
|
||||
[[item]]
|
||||
id = "AUTO-219-6"
|
||||
|
||||
Reference in new issue
Block a user