PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Add filename templates to Batch export (#4466)
jonathanwxh-cell01b354a34059
diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rsindex 7470e7823..7689f3967 100644--- a/crates/engine/src/file_cmds.rs+++ b/crates/engine/src/file_cmds.rs@@ -20,6 +20,8 @@ use serde_json::{Value, json};use crate::commands::{CommandSpec, layer_param};use crate::{EngineError, Result, Session};+mod batch_naming;+// ---------- predicates ----------fn has_doc(s: &Session) -> std::result::Result<(), String> {@@ -931,19 +933,25 @@ pub(crate) fn batch_inputs(p: &Value, cmd: &str) -> Result<Vec<String>> {/// 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 {+ let outputs = inputs.iter().map(|path| {+ let ext =+ if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };+ (path.as_str(), join(output, &format!("{}{suffix}.{ext}", stem(path))))+ });+ process_outputs(outputs, save, f)+}++fn process_outputs<'a>(outputs: impl IntoIterator<Item = (&'a str, String)>, save: SaveOpts, f: &dyn Fn(&mut Session) -> Result<()>) -> Value {let mut files = Vec::new();let mut errors = Vec::new();let mut written = OutputClaims::default();- for path in inputs {- 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)));+ for (path, out) in outputs {let r = (|| -> Result<()> {written.check(&out).map_err(EngineError::Other)?;let bytes = read_file(path)?;let mut scratch = Session::new();let doc = import(&file_name(path), &bytes)?;- scratch.add_document(doc, Some(path.clone()));+ scratch.add_document(doc, Some(path.to_string()));f(&mut scratch)?;let d = scratch.active().ok_or(EngineError::NoDocument)?;save_doc(&d.doc, &out, save)?;@@ -1010,7 +1018,9 @@ 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| {+ let names = batch_naming::plan(&inputs, &output, &format, p)?;+ let save = SaveOpts::from_params(s, p, cmd)?;+ let run = |scratch: &mut Session| {scratch.actions = actions.clone();for (id, params) in &steps {let r = scratch.execute(id, params.clone())?;@@ -1020,7 +1030,11 @@ fn batch(s: &mut Session, p: &Value) -> Result<Value> {}}Ok(())- });+ };+ let r = match names {+ Some(names) => process_outputs(inputs.iter().map(String::as_str).zip(names), save, &run),+ None => process_files(&inputs, &output, &format, save, "", &run),+ };Ok(r)}@@ -1535,7 +1549,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),"input":folder|[paths],"output":folder,"format":"same|png|jpg|psd|tiff|…"="same","quality":0..12?,"naming":string? (blank keeps source names; {name}, {serial} padded to 3 digits, {date} as YYYY-MM-DD UTC; extension added automatically),"startingSerial":1..4294967295=1 (input position, including failed inputs),"tiffLayers":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"calledActions":[{"name","steps"}…]? (the actions Play Action steps call; default: the session's)} → {files, errors} (an input whose output name was already written in the run goes to errors)"##,native,batch),diff --git a/crates/engine/src/file_cmds/batch_naming.rs b/crates/engine/src/file_cmds/batch_naming.rsnew file mode 100644index 000000000..2a32f7132--- /dev/null+++ b/crates/engine/src/file_cmds/batch_naming.rs@@ -0,0 +1,123 @@+//! Batch output names are planned before opening or writing files. Names substituted from an+//! input are literal: braces in a source filename must never be interpreted as template tokens.++use super::{EngineError, Result, Value, join, stem};++fn bad(message: impl Into<String>) -> EngineError {+ EngineError::BadParams { cmd: "file.automate.batch".into(), msg: message.into() }+}++enum Part<'a> {+ Literal(&'a str),+ Name,+ Serial,+ Date,+}++fn parse(template: &str) -> Result<Vec<Part<'_>>> {+ let mut parts = Vec::new();+ let mut rest = template;+ while let Some(at) = rest.find(['{', '}']) {+ parts.push(Part::Literal(&rest[..at]));+ rest = &rest[at..];+ if rest.starts_with('}') {+ return Err(bad("naming: unmatched closing brace"));+ }+ let end = rest.find('}').ok_or_else(|| bad("naming: unclosed token"))?;+ parts.push(match &rest[1..end] {+ "name" => Part::Name,+ "serial" => Part::Serial,+ "date" => Part::Date,+ token => return Err(bad(format!("naming: unknown token {{{token}}}; use {{name}}, {{serial}} or {{date}}"))),+ });+ rest = &rest[end + 1..];+ }+ parts.push(Part::Literal(rest));+ Ok(parts)+}++fn expand(parts: &[Part<'_>], name: &str, serial: u32, date: &str) -> String {+ let mut out = String::new();+ for part in parts {+ match part {+ Part::Literal(s) => out.push_str(s),+ Part::Name => out.push_str(name),+ Part::Serial => out.push_str(&format!("{serial:03}")),+ Part::Date => out.push_str(date),+ }+ }+ out+}++/// An absent or empty template preserves the old filename path exactly. An explicit template+/// generates one component per input; the export format supplies the extension separately.+pub(super) fn plan(inputs: &[String], output: &str, format: &str, params: &Value) -> Result<Option<Vec<String>>> {+ let start = match params.get("startingSerial") {+ None => 1,+ Some(n) => {+ n.as_u64().and_then(|n| u32::try_from(n).ok()).filter(|&n| n > 0).ok_or_else(|| bad("startingSerial must be an integer from 1 to 4294967295"))?+ }+ };+ let template = match params.get("naming") {+ None => "",+ Some(Value::String(s)) => s,+ Some(_) => return Err(bad("naming must be a string")),+ };+ if template.is_empty() {+ return Ok(None);+ }+ if template.len() > 255 {+ return Err(bad("naming must be at most 255 bytes"));+ }+ let parts = parse(template)?;+ let has_serial = parts.iter().any(|p| matches!(p, Part::Serial));+ let timestamp = crate::analysis_cmds::now_iso();+ let date = timestamp.get(..10).unwrap_or("");+ if date.is_empty() && parts.iter().any(|p| matches!(p, Part::Date)) {+ return Err(bad("naming: the current UTC date is unavailable"));+ }+ let mut outputs = Vec::with_capacity(inputs.len());+ for (index, path) in inputs.iter().enumerate() {+ let serial = if has_serial {+ u32::try_from(index).ok().and_then(|index| start.checked_add(index)).ok_or_else(|| bad("startingSerial plus the input count exceeds 4294967295"))?+ } else {+ start+ };+ let base = expand(&parts, &stem(path), serial, date);+ if base.is_empty() || base.ends_with(['.', ' ']) {+ return Err(bad("naming must produce a nonempty filename stem without a trailing dot or space"));+ }+ let ext =+ if format == "same" { path.rsplit('.').next().unwrap_or("png").to_ascii_lowercase() } else { format.trim_start_matches('.').to_ascii_lowercase() };+ let name = format!("{base}.{ext}");+ if name.len() > 255 || name.chars().any(|c| c.is_control() || "/\\<>:\"|?*".contains(c)) {+ return Err(bad("naming must produce a filename of at most 255 bytes without path separators or reserved characters"));+ }+ outputs.push(join(output, &name));+ }+ // Renaming within the source folder could replace a later input before it is read. Resolve+ // existing paths so aliases such as `source/./001.png` cannot bypass the check. The default+ // (no template) path keeps its existing in-place behavior.+ #[cfg(not(target_arch = "wasm32"))]+ {+ let sources: std::collections::HashSet<_> = inputs.iter().filter_map(|p| std::fs::canonicalize(p).ok()).collect();+ for output in &outputs {+ if std::fs::canonicalize(output).ok().is_some_and(|p| sources.contains(&p)) {+ return Err(bad(format!("naming would replace an input file: {output}; choose a different destination or template")));+ }+ }+ }+ Ok(Some(outputs))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn substituted_names_are_literal_and_serials_do_not_wrap_or_truncate() {+ let parts = parse("{date}_{name}_{serial}").unwrap();+ assert_eq!(expand(&parts, "photo{serial}", 7, "2026-10-13"), "2026-10-13_photo{serial}_007");+ assert_eq!(expand(&parts, "photo", 1000, "2026-10-13"), "2026-10-13_photo_1000");+ }+}diff --git a/crates/engine/src/file_cmds/tests.rs b/crates/engine/src/file_cmds/tests.rsindex 73c09020a..99ddce15d 100644--- a/crates/engine/src/file_cmds/tests.rs+++ b/crates/engine/src/file_cmds/tests.rs@@ -946,6 +946,34 @@ fn templates_open_untitled_without_their_path() {assert_eq!(opened, [("Untitled-1", None), ("Untitled-2", None)]);}+#[test]+fn batch_naming_serial_keeps_same_named_inputs_and_their_pixels() {+ let dir = tmp("naming-serial");+ let first = join(&dir, "first");+ let second = join(&dir, "second");+ std::fs::create_dir_all(&first).unwrap();+ std::fs::create_dir_all(&second).unwrap();+ let inputs = [png(&first, "photo.png", 8, 8, "#ff0000"), png(&second, "photo.png", 8, 8, "#0000ff")];+ let out = join(&dir, "out");+ let mut s = Session::new();+ let result = s+ .execute(+ "file.automate.batch",+ json!({+ "input": inputs, "output": out, "steps": [], "format": "png",+ "naming": "{name}_{serial}", "startingSerial": 7+ }),+ )+ .unwrap();+ assert_eq!(result["errors"], json!([]), "{result}");+ assert_eq!(result["files"], json!([join(&out, "photo_007.png"), join(&out, "photo_008.png")]));+ for (name, expected) in [("photo_007.png", [1.0, 0.0, 0.0, 1.0]), ("photo_008.png", [0.0, 0.0, 1.0, 1.0])] {+ let saved = photocraft_io::import(name, &std::fs::read(join(&out, name)).unwrap()).unwrap().document;+ let pixel = photocraft_compose::render(&saved, Rect::new(1, 1, 2, 2)).px[0];+ assert_eq!(pixel, expected, "{name}");+ }+}+/// Two inputs with one output name: the first result is kept and the second is an error, never/// a silent overwrite listed as written (#422).#[test]@@ -1019,3 +1047,103 @@ fn reveal_in_finder_reveals_the_documents_saved_path() {assert_eq!(r["program"], json!(program));assert_eq!(r["args"], json!(args));}+#[test]+fn batch_naming_validates_the_whole_plan_before_writing() {+ let dir = tmp("naming-invalid");+ let input = png(&dir, "source.png", 8, 8, "#ff0000");+ let mut s = Session::new();+ for (index, extra) in [+ json!({"naming": "../{name}"}),+ json!({"naming": "sub\\{name}"}),+ json!({"naming": "C:{name}"}),+ json!({"naming": "{unknown}"}),+ json!({"naming": "{name"}),+ json!({"naming": "name}"}),+ json!({"naming": 42}),+ json!({"naming": "{serial}", "startingSerial": 0}),+ json!({"naming": "{serial}", "startingSerial": 1.5}),+ json!({"naming": "{serial}", "startingSerial": "1"}),+ json!({"naming": "{serial}", "startingSerial": 4294967295_u64}),+ json!({"naming": "x".repeat(256)}),+ ]+ .into_iter()+ .enumerate()+ {+ let out = join(&dir, &format!("out-{index}"));+ let mut params = json!({"input": [input, input], "output": out, "steps": []});+ params.as_object_mut().unwrap().extend(extra.as_object().unwrap().clone());+ let error = s.execute("file.automate.batch", params).unwrap_err();+ assert!(matches!(error, EngineError::BadParams { .. }), "{error}");+ assert!(!std::path::Path::new(&out).exists(), "invalid naming wrote outputs: {extra}");+ }+}++#[test]+fn batch_naming_keeps_serial_positions_after_errors_and_captures_the_utc_date() {+ let dir = tmp("naming-errors");+ let input = png(&dir, "good.png", 8, 8, "#0000ff");+ let out = join(&dir, "out");+ let before = crate::analysis_cmds::now_iso();+ let mut s = Session::new();+ let result = s+ .execute(+ "file.automate.batch",+ json!({+ "input": [join(&dir, "missing.png"), input], "output": out, "steps": [],+ "naming": "{date}_{serial}_{name}", "startingSerial": 9+ }),+ )+ .unwrap();+ let after = crate::analysis_cmds::now_iso();+ assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}");+ let files = result["files"].as_array().unwrap();+ assert_eq!(files.len(), 1, "{result}");+ let name = file_name(files[0].as_str().unwrap());+ assert!(+ name == format!("{}_010_good.png", &before[..10]) || name == format!("{}_010_good.png", &after[..10]),+ "the missing input still consumes its serial: {name}"+ );+}++#[test]+fn batch_naming_still_reports_collisions_instead_of_overwriting() {+ let dir = tmp("naming-collision");+ let red = png(&dir, "red.png", 8, 8, "#ff0000");+ let blue = png(&dir, "blue.png", 8, 8, "#0000ff");+ let out = join(&dir, "out");+ let mut s = Session::new();+ let result = s+ .execute(+ "file.automate.batch",+ json!({+ "input": [red, blue], "output": out, "steps": [], "naming": "constant"+ }),+ )+ .unwrap();+ assert_eq!(result["files"], json!([join(&out, "constant.png")]));+ assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}");+ assert!(result["errors"][0]["error"].as_str().unwrap().contains("not written"));+ let saved = photocraft_io::import("constant.png", &std::fs::read(join(&out, "constant.png")).unwrap()).unwrap().document;+ assert_eq!(photocraft_compose::render(&saved, Rect::new(1, 1, 2, 2)).px[0], [1.0, 0.0, 0.0, 1.0]);+}+#[test]+fn batch_naming_rejects_outputs_that_replace_inputs_before_processing() {+ let dir = tmp("naming-input-alias");+ let first = png(&dir, "002.png", 8, 8, "#ff0000");+ let second = png(&dir, "001.png", 8, 8, "#0000ff");+ let before = [std::fs::read(&first).unwrap(), std::fs::read(&second).unwrap()];+ let mut s = Session::new();+ // Without preflight, processing 002 first writes 001, so the next input's original pixels+ // are lost before it is read. The full plan must be rejected without writing either file.+ let error = s+ .execute(+ "file.automate.batch",+ json!({+ "input": [first, second], "output": join(&dir, "."), "steps": [], "naming": "{serial}"+ }),+ )+ .unwrap_err();+ assert!(error.to_string().contains("input"), "{error}");+ assert_eq!(std::fs::read(&first).unwrap(), before[0]);+ assert_eq!(std::fs::read(&second).unwrap(), before[1]);+}diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 41c4c0386..d730fae7a 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -3726,6 +3726,8 @@ navigator Zoom Zvětšení@plural Saved {n} action to {file}|Saved {n} actions to {file} Uložena {n} akce do souboru {file}|Uloženy {n} akce do souboru {file}|Uloženo {n} akcí do souboru {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Vynechán {n} krok bez obdoby v Photoshopu|Vynechány {n} kroky bez obdoby v Photoshopu|Vynecháno {n} kroků bez obdoby v Photoshopu+ File Naming Pojmenování souborů+ Starting serial Počáteční pořadové číslo# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Vložit zastavení…Save Set… Uložit sadu…diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 29b718c25..6b13188c7 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2760,6 +2760,8 @@ curves Smooth Glätten@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} Aktion in {file} gespeichert|{n} Aktionen in {file} gespeichert@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Schritt ohne Photoshop-Entsprechung ausgelassen|{n} Schritte ohne Photoshop-Entsprechung ausgelassen+ File Naming Dateibenennung+ Starting serial Startnummer# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Stopp einfügen…Save Set… Set speichern…diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 82f2a5de6..11590ca36 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -1027,7 +1027,6 @@Choose… Επιλογή…Select Folder… Επιλογή φακέλου…Override Action "Save" Commands Παράκαμψη εντολών αποθήκευσης της ενέργειας- File Naming Ονομασία αρχείωνCompatibility ΣυμβατότηταInclude ICC Profile Συμπερίληψη προφίλ ICCError File Αρχείο σφαλμάτων@@ -3815,6 +3814,8 @@ curves Smooth Εξομάλυνση@plural Saved {n} action to {file}|Saved {n} actions to {file} Αποθηκεύτηκε {n} ενέργεια στο {file}|Αποθηκεύτηκαν {n} ενέργειες στο {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Παραλείφθηκε {n} βήμα χωρίς αντίστοιχο στο Photoshop|Παραλείφθηκαν {n} βήματα χωρίς αντίστοιχο στο Photoshop+ File Naming Ονομασία αρχείων+ Starting serial Αρχικός αριθμός σειράς# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Εισαγωγή διακοπής…Save Set… Αποθήκευση συνόλου…diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex e47aa6cba..addcea851 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2801,6 +2801,8 @@ curves Smooth Suavizar@plural Saved {n} action to {file}|Saved {n} actions to {file} Se guardó {n} acción en {file}|Se guardaron {n} acciones en {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} paso sin equivalente en Photoshop omitido|{n} pasos sin equivalente en Photoshop omitidos+ File Naming Nombres de archivo+ Starting serial Número de serie inicial# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Insertar detención…Save Set… Guardar conjunto…diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex 8085f5fdf..1620ff821 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2470,7 +2470,6 @@Choose… Choisir…Select Folder… Sélectionner un dossier…Override Action "Save" Commands Ignorer les commandes « Enregistrer » de l'action- File Naming Dénomination des fichiersCompatibility CompatibilitéMac OS Mac OSUnix Unix@@ -3119,6 +3118,8 @@ curves Smooth Lisser@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} action enregistrée dans {file}|{n} actions enregistrées dans {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} étape sans équivalent Photoshop omise|{n} étapes sans équivalent Photoshop omises+ File Naming Dénomination des fichiers+ Starting serial Numéro de série initial# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Insérer un arrêt…Save Set… Enregistrer l’ensemble…diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex 57734795e..6a5c28999 100644--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@ -4020,6 +4020,7 @@ cameraRaw Yellow Sárga@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} művelet mentve. Cél: {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Photoshop-megfelelő nélküli lépés kihagyva+ Starting serial Kezdő sorszám# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Leállítás beszúrása…Save Set… Készlet mentése…diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex 95ebe980c..8b8802e98 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2461,7 +2461,6 @@Choose… Pilih…Select Folder… Pilih Folder…Override Action "Save" Commands Timpa Perintah Action "Save"- File Naming Penamaan BerkasCompatibility KompatibilitasMac OS Mac OSUnix Unix@@ -3106,6 +3105,8 @@ curves Smooth Haluskan@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} tindakan disimpan ke {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} langkah tanpa padanan Photoshop dilewati+ File Naming Penamaan Berkas+ Starting serial Nomor urut awal# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Sisipkan Berhenti…Save Set… Simpan Set…diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex db23b01e1..0034b37ba 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -3014,7 +3014,6 @@ curves Smooth LevigaChoose… Scegli…Select Folder… Seleziona cartella…Override Action "Save" Commands Sostituisci i comandi "Salva" dell'azione- File Naming Denominazione fileCompatibility CompatibilitàMac OS Mac OSUnix Unix@@ -4082,6 +4081,8 @@ navigator Zoom Zoom@plural Saved {n} action to {file}|Saved {n} actions to {file} Salvata {n} azione in {file}|Salvate {n} azioni in {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Omesso {n} passaggio senza equivalente in Photoshop|Omessi {n} passaggi senza equivalente in Photoshop+ File Naming Denominazione file+ Starting serial Numero di serie iniziale# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Inserisci interruzione…Save Set… Salva set…diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 040db7e8b..2e13e3df7 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -3306,7 +3306,6 @@ fontWeight Italic 斜体Exposure Program 露出プログラムExtra Bold エクストラボールドExtra Light エクストラライト- File Naming ファイル名の付け方Fill Light フィルライトFirst Color Readout 最初のカラー読み取りFlash フラッシュ@@ -3724,6 +3723,8 @@ curves Smooth スムーズ@plural Saved {n} action to {file}|Saved {n} actions to {file} {file} にアクション {n} 個を保存しました@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop に対応するもののない {n} 個のステップを省きました+ File Naming ファイル名の付け方+ Starting serial 開始番号# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… ストップを挿入…Save Set… セットを保存…diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 1c26d44ee..89b0c613d 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -3291,6 +3291,8 @@ curves Smooth 매끄럽게@plural Saved {n} action to {file}|Saved {n} actions to {file} {file}에 액션 {n}개를 저장했습니다@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop에 해당하는 기능이 없는 {n}개 단계를 제외했습니다+ File Naming 파일 이름 지정+ Starting serial 시작 일련번호# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… 정지 삽입…Save Set… 세트 저장…diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 35bad8fcd..4bb9d7cce 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2853,7 +2853,6 @@ cameraRaw Color KleurChoose… Kiezen…Select Folder… Map selecteren…Override Action "Save" Commands Opdrachten "Opslaan" in actie negeren- File Naming BestandsnamenCompatibility CompatibiliteitInclude ICC Profile ICC-profiel opnemenError File Foutbestand@@ -3877,6 +3876,8 @@ curves Smooth Vloeiend maken@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} handeling opgeslagen in {file}|{n} handelingen opgeslagen in {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} stap zonder Photoshop-equivalent weggelaten|{n} stappen zonder Photoshop-equivalent weggelaten+ File Naming Bestandsnamen+ Starting serial Beginnummer# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Stop invoegen…Save Set… Set opslaan…diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 2d63948d3..04797ddc2 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -2494,7 +2494,6 @@Choose… Wybierz…Select Folder… Wybierz folder…Override Action "Save" Commands Zastąp polecenia „Zapisz” w akcji- File Naming Nazewnictwo plikówCompatibility ZgodnośćMac OS Mac OSUnix Unix@@ -3715,6 +3714,8 @@ curves Smooth Wygładź@plural Saved {n} action to {file}|Saved {n} actions to {file} Zapisano {n} operację do {file}|Zapisano {n} operacje do {file}|Zapisano {n} operacji do {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Pominięto {n} krok bez odpowiednika w Photoshopie|Pominięto {n} kroki bez odpowiednika w Photoshopie|Pominięto {n} kroków bez odpowiednika w Photoshopie+ File Naming Nazewnictwo plików+ Starting serial Początkowy numer seryjny# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Wstaw zatrzymanie…Save Set… Zapisz zestaw…diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 7662e3f03..df6c092ba 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2466,7 +2466,6 @@Choose… Escolher…Select Folder… Selecionar pasta…Override Action "Save" Commands Substituir comandos "Salvar" da ação- File Naming Nomenclatura de arquivosCompatibility CompatibilidadeMac OS Mac OSUnix Unix@@ -3907,6 +3906,8 @@ layerLabel No Color Sem cor@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} ação salva em {file}|{n} ações salvas em {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} etapa sem equivalente no Photoshop foi omitida|{n} etapas sem equivalente no Photoshop foram omitidas+ File Naming Nomenclatura de arquivos+ Starting serial Número de série inicial# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Inserir parada…Save Set… Salvar conjunto…diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex ea320c153..3acd552a5 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -1403,7 +1403,6 @@Choose… Выбрать…Select Folder… Выбрать папку…Override Action "Save" Commands Переопределить команды «Сохранить» в операции- File Naming Именование файловCompatibility СовместимостьWindows WindowsMac OS Mac OS@@ -3063,6 +3062,8 @@ curves Smooth Сгладить@plural Saved {n} action to {file}|Saved {n} actions to {file} Сохранена {n} операция в {file}|Сохранены {n} операции в {file}|Сохранено {n} операций в {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущен {n} шаг без эквивалента в Photoshop|Пропущены {n} шага без эквивалента в Photoshop|Пропущено {n} шагов без эквивалента в Photoshop+ File Naming Именование файлов+ Starting serial Начальный порядковый номер# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Вставить остановку…Save Set… Сохранить набор…diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex a4dbb575d..5719f0bd8 100644--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@ -3831,6 +3831,7 @@ cameraData Lens Lens@plural Saved {n} action to {file}|Saved {n} actions to {file} {n} eylem {file} dosyasına kaydedildi@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop karşılığı olmayan {n} adım atlandı+ Starting serial Başlangıç sıra numarası# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Durdurma Ekle…Save Set… Seti Kaydet…diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 1367c4c79..6ec48d1dc 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -1382,7 +1382,6 @@Choose… Вибрати…Select Folder… Вибрати теку…Override Action "Save" Commands Перевизначити команди «Зберегти» в дії- File Naming Іменування файлівCompatibility СумісністьWindows WindowsMac OS Mac OS@@ -3816,6 +3815,8 @@ curves Smooth Згладити@plural Saved {n} action to {file}|Saved {n} actions to {file} Збережено {n} операцію до {file}|Збережено {n} операції до {file}|Збережено {n} операцій до {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Пропущено {n} крок без відповідника в Photoshop|Пропущено {n} кроки без відповідника в Photoshop|Пропущено {n} кроків без відповідника в Photoshop+ File Naming Іменування файлів+ Starting serial Початковий порядковий номер# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Вставити зупинку…Save Set… Зберегти набір…diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsvindex c1becf4b3..24b63ba61 100644--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@ -3599,6 +3599,8 @@ curves Smooth Làm mượt@plural Saved {n} action to {file}|Saved {n} actions to {file} Đã lưu {n} hành động vào {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Đã bỏ qua {n} bước không có chức năng tương ứng trong Photoshop+ File Naming Đặt tên tệp+ Starting serial Số thứ tự bắt đầu# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… Chèn điểm dừng…Save Set… Lưu bộ…diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 23843a8aa..bc729fb13 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2726,6 +2726,8 @@ curves Smooth 平滑@plural Saved {n} action to {file}|Saved {n} actions to {file} 已将 {n} 个动作存储到 {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已省略 {n} 个没有 Photoshop 对应功能的步骤+ File Naming 文件命名+ Starting serial 起始序号# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… 插入停止…Save Set… 存储组…diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex cbeba57d5..ff8465179 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2711,6 +2711,8 @@ curves Smooth 平滑@plural Saved {n} action to {file}|Saved {n} actions to {file} 已將 {n} 個動作儲存到 {file}@plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out 已略過 {n} 個沒有 Photoshop 對應功能的步驟+ File Naming 檔案命名+ Starting serial 起始序號# Actions panel: set folders, dialog toggle, Insert StopInsert Stop… 插入停止…Save Set… 儲存組合…diff --git a/crates/ui-egui/src/view_cmds.rs b/crates/ui-egui/src/view_cmds.rsindex f18c4730e..5e6d25233 100644--- a/crates/ui-egui/src/view_cmds.rs+++ b/crates/ui-egui/src/view_cmds.rs@@ -1060,6 +1060,16 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {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);+ if k == "naming" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") {+ let label = ui.label(tl!("File Naming"));+ let mut naming = v.as_str().unwrap_or_default().to_owned();+ ui.add(egui::TextEdit::singleline(&mut naming).desired_width(260.0).hint_text("{name}"))+ .labelled_by(label.id)+ .on_hover_text("{name} · {serial} · {date} (UTC)");+ f.insert(k, json!(naming));+ ui.end_row();+ continue;+ }if k == "quality" && f.get("__command").and_then(Value::as_str) == Some("file.automate.batch") {ui.label(label(&k));let mut custom = v.as_f64().is_some();@@ -1309,7 +1319,7 @@ fn front(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option<Result<Vallet name = action.name.clone();dialog(app,- json!({"action": name, "steps": steps, "input": dir, "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8}),+ json!({"action": name, "steps": steps, "input": dir, "output": format!("{dir}/batch"), "format": "same", "quality": null, "__batchQuality": 8, "naming": "", "startingSerial": 1}),json!({"format": ["same", "png", "jpg", "psd", "tiff", "webp"]}),)}diff --git a/crates/ui-egui/tests/batch_export_options.rs b/crates/ui-egui/tests/batch_export_options.rsindex 7de3b2869..5bf87909b 100644--- a/crates/ui-egui/tests/batch_export_options.rs+++ b/crates/ui-egui/tests/batch_export_options.rs@@ -281,6 +281,63 @@ fn batch_and_processor_real_controls_write_the_chosen_webp_quality() {assert_eq!(serde_json::to_value(&h.state().session.actions.list).unwrap(), actions);}+#[test]+fn batch_naming_controls_export_the_requested_names_and_reset_on_cancel() {+ let _gpu = photocraft_testkit::gpu_lock();+ let dir = Scratch::new();+ let input = dir.0.join("input");+ let output = dir.0.join("output");+ std::fs::create_dir(&input).unwrap();+ let source = pattern();+ let bytes = photocraft_codecs::encode(&source, Format::Png, &EncodeOptions::default()).unwrap();+ for name in ["first.png", "second.png"] {+ std::fs::write(input.join(name), &bytes).unwrap();+ }+ let mut h = harness();+ open(&mut h, "file.automate.batch");+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "File Naming").click();+ h.run_steps(2);+ replace_text(&mut h, "cancelled_{serial}");+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert!(!output.exists());+ open(&mut h, "file.automate.batch");+ let fields = &h.state().ui.dialogs.last().unwrap().fields;+ assert_eq!(fields["naming"], "");+ assert_eq!(fields["startingSerial"], 1);+ edit_path(&mut h, "Input", &input);+ edit_path(&mut h, "Output", &output);+ h.get_by_role_and_label(egui::accesskit::Role::TextInput, "File Naming").click();+ h.run_steps(2);+ replace_text(&mut h, "{serial}_{name}");+ let label = h.get_by_label("Starting serial").rect();+ h.query_all_by_role(egui::accesskit::Role::SpinButton)+ .find(|n| {+ let r = n.rect();+ r.left() >= label.right() && r.left() < label.right() + 100.0 && (r.center().y - label.center().y).abs() < 3.0+ })+ .expect("starting serial number control")+ .click();+ h.run_steps(2);+ h.event(egui::Event::Text("7".into()));+ h.run_steps(3);+ h.get_by_label("Starting serial").click();+ h.run_steps(3);+ assert_eq!(h.state().ui.dialogs.last().unwrap().fields["startingSerial"], 7, "typing changes the starting serial");+ evidence(&mut h, "batch-naming");+ h.get_by_label("OK").click();+ h.run_steps(5);+ assert!(h.state().ui.dialogs.is_empty());+ let expected: Vec<_> = source.data().iter().map(|v| 255 - v).collect();+ for name in ["007_first.png", "008_second.png"] {+ let bytes = std::fs::read(output.join(name)).expect("dialog naming reaches the exporter");+ let decoded = photocraft_codecs::decode_as(Format::Png, &bytes).unwrap();+ assert_eq!(decoded.data(), expected, "the recorded Invert action still runs");+ }+ assert!(!output.join("first.png").exists());+ assert!(!output.join("second.png").exists());+}+#[test]fn batch_default_quality_keeps_lossless_webp_and_existing_jpeg_bytes() {let _gpu = photocraft_testkit::gpu_lock();diff --git a/docs/batch-naming.md b/docs/batch-naming.mdnew file mode 100644index 000000000..a922803f8--- /dev/null+++ b/docs/batch-naming.md@@ -0,0 +1,41 @@+# Batch output naming++Select a recorded action, then open **File > Automate > Batch**. Set the input and output+folders. **File Naming** accepts a filename stem template; the selected export format supplies+the extension. Leave it blank to keep the existing source filenames and collision reporting.++| Token | Value |+| --- | --- |+| `{name}` | Input filename without its last extension |+| `{serial}` | Input position plus **Starting serial** (default 1), padded to at least three digits |+| `{date}` | UTC date at the start of the batch, in `YYYY-MM-DD` form |++For example, `{name}_{serial}` with starting serial 7 writes `photo_007.png` and+`photo_008.png` for two PNG inputs named `photo.png`. A serial after 999 becomes 1000;+it does not wrap. Folder inputs use the existing filename order, and an explicit input array+keeps its order. Failed inputs consume their position, so later filenames do not shift.+Braces in an input filename are literal text, not additional tokens.++Unknown tokens, unmatched braces, invalid parameter types, path separators, reserved filename+characters, excessive filename length (255 UTF-8 bytes), and serial overflow are rejected before+export writes begin. Starting serial must be an integer from 1 to 4,294,967,295.+A custom template that resolves to an existing input file is also rejected; choose a separate+destination or another template. Ordinary per-file read, action and save failures still appear+in the batch's `errors` result. When two results share a name, including a case-only difference,+the first successful result is kept and the later collision is reported.++The same options are available on `file.automate.batch` through the engine command interface:++```json+{+ "input": ["first/photo.png", "second/photo.png"],+ "output": "exports",+ "steps": [["image.adjustments.invert", {}]],+ "format": "png",+ "naming": "{name}_{serial}",+ "startingSerial": 7+}+```++The CLI can invoke this command with `run --cmd file.automate.batch --params ...`.+This option belongs to Batch; Image Processor and droplet options retain their existing behavior.diff --git a/docs/gaps.md b/docs/gaps.mdindex 9ad8fc851..a0edbaff7 100644--- a/docs/gaps.md+++ b/docs/gaps.md@@ -88,7 +88,10 @@ 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+- **2026-10-13 evidence:** Batch supports [output naming templates](batch-naming.md) using+ `{name}`, `{serial}` and a captured UTC `{date}`, with a starting serial number. Colliding+ names remain errors; custom output names cannot replace inputs. AUTO-219-5 stays partial.+- **Missing:** document-independent action recording (AUTO-219-1), Batch recursion, open-document inputs, progress/cancel and an error-log file(AUTO-219-5), ExtendScript/UXP compatibility. `.atn` steps outside themapped events (paths, scripts, Generative Fill, Filter Gallery effects other than Spatter,Duplicate Layers into a new document, Bitmap halftone screens…) load as kept Photoshop stepsdiff --git a/docs/scorecard.md b/docs/scorecard.mdindex 078ce21b2..92f9315eb 100644--- a/docs/scorecard.md+++ b/docs/scorecard.md@@ -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 | partial | [#219](https://github.com/storytold/photocraft/issues/219) | file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial; no recursion, open-documents source, cancel or error-log file || 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 |diff --git a/docs/target-app-parity.md b/docs/target-app-parity.mdindex f6209c58d..a7c802904 100644--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@ -184,6 +184,8 @@ parity for the area and are already contained in the dimension rows above.| Workspace, panels, preferences | 40% | 150–250 | 46 of 149 prefs do nothing; no floating/OS-window panel groups; Libraries, Comments, Contextual Task Bar missing || AI / generative | 10% | 300–600 | See the dimension row |+Batch supports [output naming templates](batch-naming.md); AUTO-219-5 remains partial.+## Remaining effort and calibration**Calibration.** The repository's history from the first commit (2026-09-30) to 2026-10-10: 1,152diff --git a/scorecard/automation.toml b/scorecard/automation.tomlindex 0de2ab3bd..7bec4ab44 100644--- a/scorecard/automation.toml+++ b/scorecard/automation.toml@@ -44,7 +44,7 @@ id = "AUTO-219-5"target = "Batch: subfolders, open documents, naming template, progress/cancel, error log, stop"status = "partial"issue = 219-note = "file_cmds.rs:590-631 folder/array input, per-file errors; no recursion, template or cancel"+note = "file_cmds.rs and file_cmds/batch_naming.rs: folder/array input, per-file errors, {name}/{serial}/{date} output templates and starting serial; no recursion, open-documents source, cancel or error-log file"[[item]]id = "AUTO-219-6"