From 2fc63aee8f287a79264dba3437387c5f51dfd578 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:45:23 +0000 Subject: [PATCH 1/8] Keep existing Image Processor folder outputs --- crates/engine/src/cmd/file_cmds/batch_run.rs | 86 ++++++++++--- .../image_processor_unique_names_tests.rs | 113 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/processing.rs | 9 +- 3 files changed, 191 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 5085b47f214..288a0b07f61 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -140,27 +140,36 @@ pub(crate) fn process_files( f: &dyn Fn(&mut Session) -> Result<()>, ) -> Value { let inputs: Vec = inputs.iter().map(|path| BatchInput { path: path.clone(), rel_dir: String::new() }).collect(); - process_tree(s, &inputs, output, format, save, suffix, &|scratch, _| f(scratch).map(|()| false)) + process_tree(s, &inputs, output, format, save, TreeNaming::Suffix(suffix), &|scratch, _| f(scratch).map(|()| false)) +} + +pub(super) enum TreeNaming<'a> { + Suffix(&'a str), + Unique, } /// [`process_files`] for inputs from subfolders: each result goes to its input's relative folder /// under `output` (created as needed), so `a/x.png` and `b/x.png` don't collide. `f` gets the /// output path and returns `true` when it wrote the result there itself (Batch writes what a /// recorded save marked); otherwise the active document is saved after it. -pub(crate) fn process_tree( +pub(super) fn process_tree( s: &Session, inputs: &[BatchInput], output: &str, format: &str, save: SaveOpts, - suffix: &str, + naming: TreeNaming<'_>, f: &dyn Fn(&mut Session, &str) -> Result, ) -> Value { + let (suffix, unique) = match naming { + TreeNaming::Suffix(suffix) => (suffix, false), + TreeNaming::Unique => ("", true), + }; let outputs = inputs.iter().map(|BatchInput { path, rel_dir }| { let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; (path.as_str(), join(&join(output, rel_dir), &format!("{}{suffix}.{ext}", stem(path)))) }); - process_outputs(s, outputs, save, f) + process_outputs(s, outputs, save, unique, f) } /// The extension a batch output takes with Format "Same": the input's own, except for formats @@ -240,6 +249,7 @@ fn process_outputs<'a>( s: &Session, outputs: impl IntoIterator, save: SaveOpts, + unique: bool, f: &dyn Fn(&mut Session, &str) -> Result, ) -> Value { // The scratch sessions have default preferences; a raw opens at the user's Raw Defaults. @@ -256,9 +266,11 @@ fn process_outputs<'a>( f(scratch, out).map_err(FileFailure::from) }; for (path, out) in outputs { - let r = process_one(raw_ppi, path, &out, save, ProcessOptions { format: None, written: Some(&written), ctx: None, input: None }, &run); + let options = ProcessOptions { format: None, written: (!unique).then_some(&written), ctx: None, input: None, unique }; + let r = process_one(raw_ppi, path, &out, save, options, &run); match r { - Ok(()) => { + Ok(Some(out)) => files.push(out), + Ok(None) => { written.record(&out, path); files.push(out); } @@ -311,9 +323,9 @@ pub(super) fn process_document_copies( let notices = std::cell::RefCell::new(Vec::new()); let input = InputPolicy { prepare: &prepare, notices: ¬ices }; let run = |scratch: &mut Session, out: &str| f(scratch, out).map_err(FileFailure::from); - let options = ProcessOptions { format: Some(&ext), written: Some(&written), ctx: None, input: Some(&input) }; + let options = ProcessOptions { format: Some(&ext), written: Some(&written), ctx: None, input: Some(&input), unique: false }; match process_one(s.prefs().raw_defaults.resolution, &path, &out, save, options, &run) { - Ok(()) => { + Ok(_) => { written.record(&out, &path); files.push(out); } @@ -333,6 +345,7 @@ struct ProcessOptions<'a> { written: Option<&'a OutputClaims>, ctx: Option<&'a crate::jobs::JobCtx>, input: Option<&'a InputPolicy<'a>>, + unique: bool, } /// Open and process one scratch input, collecting opening diagnostics even on failure. @@ -344,12 +357,12 @@ fn process_one( save: SaveOpts, options: ProcessOptions<'_>, f: &dyn Fn(&mut Session, &str) -> std::result::Result, -) -> std::result::Result<(), FileFailure> { +) -> std::result::Result, FileFailure> { if let Some(written) = options.written { written.check(out).map_err(EngineError::Other)?; } let mut scratch = Session::new(); - let result = (|| -> std::result::Result<(), FileFailure> { + let result = (|| -> std::result::Result, FileFailure> { if let Some(input) = options.input { (input.prepare)(&mut scratch, path)?; } else { @@ -364,7 +377,7 @@ fn process_one( if saved_by_action { // The action's saved snapshot is already written: a cancel or Esc arriving now stops the // inputs after this one, not this result. - return Ok(()); + return Ok(None); } if let Some(ctx) = options.ctx { ctx.check()?; @@ -373,6 +386,12 @@ fn process_one( } } let d = scratch.active().ok_or(EngineError::NoDocument)?; + if options.unique { + let (bytes, mut warnings) = encode(&d.doc, out, save)?; + let actual = save_unique_output(out, &bytes, &mut warnings)?; + record_export_warnings(&mut scratch, &actual, warnings); + return Ok(Some(actual)); + } let warnings = if let Some(format) = options.format { let ext = if format == "same" { same_format(path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; if let Some(ctx) = options.ctx { save_batch_doc(&d.doc, out, &ext, save, ctx)? } else { save_doc_as(&d.doc, out, &ext, save)? } @@ -380,7 +399,7 @@ fn process_one( save_doc(&d.doc, out, save)? }; record_export_warnings(&mut scratch, out, warnings); - Ok(()) + Ok(None) })(); if let Some(input) = options.input { input.notices.borrow_mut().extend(scratch.batch_open_notices.take().unwrap_or_default()); @@ -390,6 +409,45 @@ fn process_one( /// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore /// leaves the current destination untouched; the worker owns the write once the checkpoint passes. +/// Claim a destination atomically so another process creating it during export cannot lose its file. +#[cfg(not(target_arch = "wasm32"))] +fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Result { + use std::{fs, io::ErrorKind, path::Path}; + + let path = Path::new(out); + let dir = path.parent().filter(|dir| !dir.as_os_str().is_empty()).unwrap_or_else(|| Path::new(".")); + fs::create_dir_all(dir).map_err(|error| EngineError::Other(format!("{}: {error}", dir.display())))?; + let name = file_name(out); + let prefix = out.strip_suffix(&name).unwrap_or_default(); + let (stem, extension) = name.rsplit_once('.').unwrap_or((&name, "")); + for suffix in 0..=100_000 { + let candidate = if suffix == 0 { out.to_owned() } else { format!("{prefix}{stem}_{suffix}.{extension}") }; + let path = Path::new(&candidate); + // Avoid staging encoded bytes when the name is already visibly occupied, including + // directories and dangling symlinks. The publication still checks the name atomically. + match fs::symlink_metadata(path) { + Ok(_) => continue, + Err(error) if error.kind() == ErrorKind::NotFound => {} + Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), + } + match photocraft_format::write_noreplace(path, bytes) { + Ok(()) => return Ok(candidate), + Err(error) if error.published => { + warnings.push(error.to_string()); + return Ok(candidate); + } + Err(error) if error.error.kind() == ErrorKind::AlreadyExists => {} + Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), + } + } + Err(EngineError::Other(format!("{out}: no free output name through suffix _100000"))) +} + +#[cfg(target_arch = "wasm32")] +fn save_unique_output(out: &str, _bytes: &[u8], _warnings: &mut Vec) -> Result { + Err(EngineError::Other(format!("cannot write {out}: no file system on the web"))) +} + fn save_batch_doc(doc: &Document, out: &str, format: &str, save: SaveOpts, ctx: &crate::jobs::JobCtx) -> Result> { let (bytes, warnings) = encode(doc, format, save)?; ctx.batch_before_write()?; @@ -548,7 +606,7 @@ fn process_batch_outputs_with( path, out, save, - ProcessOptions { format: Some(format), written: check_duplicates.then_some(&written), ctx: Some(ctx), input }, + ProcessOptions { format: Some(format), written: check_duplicates.then_some(&written), ctx: Some(ctx), input, unique: false }, f, ); if result.is_ok() { @@ -595,7 +653,7 @@ fn process_batch_outputs_with( ctx.publish_batch_preview(path, None); done = index + 1; match result { - Ok(()) => { + Ok(_) => { files.push(out.clone()); } Err(error) => { diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs new file mode 100644 index 00000000000..296426eb8ba --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -0,0 +1,113 @@ +use std::{fs, path::Path, sync::Barrier, thread}; + +use serde_json::json; + +use crate::Session; + +const COMMAND: &str = "file.scripts.imageProcessor"; +const PIXELS: &[u8] = b"P6\n2 1\n255\n\xff\0\0\0\xff\0"; + +#[test] +fn selects_the_first_free_suffix_and_reports_every_written_format() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("a.b.ppm"); + fs::write(&source, PIXELS).unwrap(); + let output = root.path().join("out"); + fs::create_dir(&output).unwrap(); + for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { + fs::write(output.join(name), name.as_bytes()).unwrap(); + } + let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"jpeg":{},"psd":{},"tiff":{}})).unwrap(); + let expected = ["a.b_2.jpg", "a.b.psd", "a.b_1.tif"]; + assert_eq!(result, json!({"files":expected.map(|name| output.join(name)), "errors":[]})); + let next = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"jpg"})).unwrap(); + assert_eq!(next, json!({"files":[output.join("a.b_4.jpg")], "errors":[]})); + for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { + assert_eq!(fs::read(output.join(name)).unwrap(), name.as_bytes()); + } + assert_eq!(fs::read(&source).unwrap(), PIXELS); + for name in expected { + let file = output.join(name); + let result = photocraft_io::import(name, &fs::read(file).unwrap()).unwrap(); + assert_eq!((result.document.size.width, result.document.size.height), (2, 1)); + } +} + +#[test] +fn same_stem_inputs_get_separate_results_without_changing_shared_processing() { + let source = tempfile::tempdir().unwrap(); + let output = source.path().join("output"); + let a = source.path().join("a/same.ppm"); + let b = source.path().join("b/same.ppm"); + for path in [&a, &b] { + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, PIXELS).unwrap(); + } + let mut session = Session::new(); + let result = session.execute(COMMAND, json!({"input":[a,b],"output":output,"format":"png"})).unwrap(); + assert_eq!(result, json!({"files":[output.join("same.png"),output.join("same_1.png")],"errors":[]})); + + let result = session.execute(COMMAND, json!({"input":source.path(),"output":output,"format":"png","includeSubfolders":true})).unwrap(); + assert_eq!(result, json!({"files":[output.join("a/same.png"),output.join("b/same.png")],"errors":[]})); + + let legacy = source.path().join("legacy"); + let inputs = [a.to_string_lossy().into_owned(), b.to_string_lossy().into_owned()]; + let result = super::super::batch_run::process_files(&session, &inputs, &legacy.to_string_lossy(), "png", Default::default(), "", &|_| Ok(())); + assert_eq!(result["files"], json!([legacy.join("same.png")])); + let errors = result["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1); + assert!(errors[0]["error"].as_str().unwrap().contains("same output name")); +} + +#[test] +fn concurrent_folder_runs_cannot_replace_each_others_results() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("same.ppm"); + let output = root.path().join("out"); + fs::write(&source, PIXELS).unwrap(); + let params = json!({"input": [source], "output": output, "format": "png"}); + let gate = Barrier::new(4); + let results = thread::scope(|scope| { + let workers: Vec<_> = (0..4) + .map(|_| { + scope.spawn(|| { + let mut session = Session::new(); + gate.wait(); + session.execute(COMMAND, params.clone()) + }) + }) + .collect(); + workers.into_iter().map(|worker| worker.join()).collect::>() + }); + let mut written = Vec::new(); + for result in results { + let result = result.unwrap().unwrap(); + assert_eq!(result["errors"], json!([])); + written.push(result["files"][0].as_str().unwrap().to_owned()); + } + written.sort(); + let expected = ["same.png", "same_1.png", "same_2.png", "same_3.png"].map(|file| output.join(file)); + assert_eq!(written.iter().map(Path::new).collect::>(), expected.iter().map(|path| path.as_path()).collect::>()); + assert_eq!(fs::read_dir(&output).unwrap().count(), 4); + for path in &expected { + assert!(photocraft_io::import(&path.to_string_lossy(), &fs::read(path).unwrap()).is_ok()); + } +} + +#[test] +fn directory_and_dangling_symlink_names_stay_occupied() { + let root = tempfile::tempdir().unwrap(); + let source = root.path().join("example.ppm"); + fs::write(&source, PIXELS).unwrap(); + let output = root.path().join("out"); + fs::create_dir_all(output.join("example.png")).unwrap(); + let counter = if cfg!(unix) { 2 } else { 1 }; + #[cfg(unix)] + std::os::unix::fs::symlink(output.join("missing.png"), output.join("example_1.png")).unwrap(); + let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"png"})).unwrap(); + assert_eq!(result, json!({"files":[output.join(format!("example_{counter}.png"))],"errors":[]})); + assert!(output.join("example.png").is_dir()); + #[cfg(unix)] + assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); + assert!(!output.join("missing.png").exists()); +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5e0d6b2ddb7..de1da878091 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -1,4 +1,4 @@ -use super::batch_run::{BatchInput, batch_inputs_tree, process_document_copies, process_tree}; +use super::batch_run::{BatchInput, TreeNaming, batch_inputs_tree, process_document_copies, process_tree}; use super::open::import_opened; use super::paths::{file_name, list_images, read_file, stem, untitled_name}; use super::save::SaveOpts; @@ -13,6 +13,9 @@ mod image_processor_formats_tests; #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "image_processor_tests.rs"] mod image_processor_tests; +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "image_processor_unique_names_tests.rs"] +mod image_processor_unique_names_tests; #[cfg(all(test, not(target_arch = "wasm32")))] #[path = "load_stack_name_tests.rs"] @@ -132,7 +135,7 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { }; let r = if source == "folder" { let inputs = batch_inputs_tree(p, cmd, &output)?; - process_tree(s, &inputs, &output, format, save, "", &process) + process_tree(s, &inputs, &output, format, save, TreeNaming::Unique, &process) } else { let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() }; if documents.is_empty() { @@ -246,7 +249,7 @@ fn image_processor_formats(s: &Session, p: &Value, source: &str, output: &str) - Ok(false) }; let mut result = match &inputs { - ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, "", &process), + ProcessorInputs::Folder(inputs) => process_tree(s, inputs, output, format.extension, format.save, TreeNaming::Unique, &process), ProcessorInputs::Documents(documents) => process_document_copies(s, documents, output, format.extension, format.save, &process), }; if let Some(Value::Array(written)) = result.get_mut("files").map(Value::take) { From 147ae5c04c1b3c792fb61f74e241da9690f9d9b6 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:46:01 +0000 Subject: [PATCH 2/8] Compare Image Processor paths using native path semantics --- .../image_processor_unique_names_tests.rs | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 296426eb8ba..25d0a15f271 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -1,12 +1,21 @@ -use std::{fs, path::Path, sync::Barrier, thread}; +use std::{ + fs, + path::{Path, PathBuf}, + sync::Barrier, + thread, +}; -use serde_json::json; +use serde_json::{Value, json}; use crate::Session; const COMMAND: &str = "file.scripts.imageProcessor"; const PIXELS: &[u8] = b"P6\n2 1\n255\n\xff\0\0\0\xff\0"; +fn files(result: &Value) -> Result, serde_json::Error> { + serde_json::from_value(result["files"].clone()) +} + #[test] fn selects_the_first_free_suffix_and_reports_every_written_format() { let root = tempfile::tempdir().unwrap(); @@ -19,9 +28,11 @@ fn selects_the_first_free_suffix_and_reports_every_written_format() { } let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"jpeg":{},"psd":{},"tiff":{}})).unwrap(); let expected = ["a.b_2.jpg", "a.b.psd", "a.b_1.tif"]; - assert_eq!(result, json!({"files":expected.map(|name| output.join(name)), "errors":[]})); + assert_eq!(files(&result).unwrap(), expected.map(|name| output.join(name))); + assert_eq!(result["errors"], json!([])); let next = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"jpg"})).unwrap(); - assert_eq!(next, json!({"files":[output.join("a.b_4.jpg")], "errors":[]})); + assert_eq!(files(&next).unwrap(), [output.join("a.b_4.jpg")]); + assert_eq!(next["errors"], json!([])); for name in ["a.b.jpg", "a.b_1.jpg", "a.b_3.jpg", "a.b.tif"] { assert_eq!(fs::read(output.join(name)).unwrap(), name.as_bytes()); } @@ -45,15 +56,17 @@ fn same_stem_inputs_get_separate_results_without_changing_shared_processing() { } let mut session = Session::new(); let result = session.execute(COMMAND, json!({"input":[a,b],"output":output,"format":"png"})).unwrap(); - assert_eq!(result, json!({"files":[output.join("same.png"),output.join("same_1.png")],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join("same.png"), output.join("same_1.png")]); + assert_eq!(result["errors"], json!([])); let result = session.execute(COMMAND, json!({"input":source.path(),"output":output,"format":"png","includeSubfolders":true})).unwrap(); - assert_eq!(result, json!({"files":[output.join("a/same.png"),output.join("b/same.png")],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join("a/same.png"), output.join("b/same.png")]); + assert_eq!(result["errors"], json!([])); let legacy = source.path().join("legacy"); let inputs = [a.to_string_lossy().into_owned(), b.to_string_lossy().into_owned()]; let result = super::super::batch_run::process_files(&session, &inputs, &legacy.to_string_lossy(), "png", Default::default(), "", &|_| Ok(())); - assert_eq!(result["files"], json!([legacy.join("same.png")])); + assert_eq!(files(&result).unwrap(), [legacy.join("same.png")]); let errors = result["errors"].as_array().unwrap(); assert_eq!(errors.len(), 1); assert!(errors[0]["error"].as_str().unwrap().contains("same output name")); @@ -105,7 +118,8 @@ fn directory_and_dangling_symlink_names_stay_occupied() { #[cfg(unix)] std::os::unix::fs::symlink(output.join("missing.png"), output.join("example_1.png")).unwrap(); let result = Session::new().execute(COMMAND, json!({"input":[source],"output":output,"format":"png"})).unwrap(); - assert_eq!(result, json!({"files":[output.join(format!("example_{counter}.png"))],"errors":[]})); + assert_eq!(files(&result).unwrap(), [output.join(format!("example_{counter}.png"))]); + assert_eq!(result["errors"], json!([])); assert!(output.join("example.png").is_dir()); #[cfg(unix)] assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); From 8138cccaa307153043ec1209fa9f06bf083a24d8 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:47:11 +0000 Subject: [PATCH 3/8] Report completed publications and cover failed inputs --- crates/engine/src/cmd/file_cmds/batch_run.rs | 37 +++++++++++-------- .../image_processor_unique_names_tests.rs | 33 +++++++++++++++++ 2 files changed, 55 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 288a0b07f61..c19e6f9c1ff 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -269,7 +269,12 @@ fn process_outputs<'a>( let options = ProcessOptions { format: None, written: (!unique).then_some(&written), ctx: None, input: None, unique }; let r = process_one(raw_ppi, path, &out, save, options, &run); match r { - Ok(Some(out)) => files.push(out), + Ok(Some(PublishedOutput { path: out, warning })) => { + if let Some(warning) = warning { + errors.push(json!({"file": path, "output": out, "error": warning})); + } + files.push(out); + } Ok(None) => { written.record(&out, path); files.push(out); @@ -357,12 +362,12 @@ fn process_one( save: SaveOpts, options: ProcessOptions<'_>, f: &dyn Fn(&mut Session, &str) -> std::result::Result, -) -> std::result::Result, FileFailure> { +) -> std::result::Result, FileFailure> { if let Some(written) = options.written { written.check(out).map_err(EngineError::Other)?; } let mut scratch = Session::new(); - let result = (|| -> std::result::Result, FileFailure> { + let result = (|| -> std::result::Result, FileFailure> { if let Some(input) = options.input { (input.prepare)(&mut scratch, path)?; } else { @@ -387,9 +392,9 @@ fn process_one( } let d = scratch.active().ok_or(EngineError::NoDocument)?; if options.unique { - let (bytes, mut warnings) = encode(&d.doc, out, save)?; - let actual = save_unique_output(out, &bytes, &mut warnings)?; - record_export_warnings(&mut scratch, &actual, warnings); + let (bytes, warnings) = encode(&d.doc, out, save)?; + let actual = save_unique_output(out, &bytes)?; + record_export_warnings(&mut scratch, &actual.path, warnings); return Ok(Some(actual)); } let warnings = if let Some(format) = options.format { @@ -407,11 +412,14 @@ fn process_one( result } -/// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore -/// leaves the current destination untouched; the worker owns the write once the checkpoint passes. +struct PublishedOutput { + path: String, + warning: Option, +} + /// Claim a destination atomically so another process creating it during export cannot lose its file. #[cfg(not(target_arch = "wasm32"))] -fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Result { +fn save_unique_output(out: &str, bytes: &[u8]) -> Result { use std::{fs, io::ErrorKind, path::Path}; let path = Path::new(out); @@ -431,11 +439,8 @@ fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Re Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), } match photocraft_format::write_noreplace(path, bytes) { - Ok(()) => return Ok(candidate), - Err(error) if error.published => { - warnings.push(error.to_string()); - return Ok(candidate); - } + Ok(()) => return Ok(PublishedOutput { path: candidate, warning: None }), + Err(error) if error.published => return Ok(PublishedOutput { path: candidate, warning: Some(error.to_string()) }), Err(error) if error.error.kind() == ErrorKind::AlreadyExists => {} Err(error) => return Err(EngineError::Other(format!("{candidate}: {error}"))), } @@ -444,10 +449,12 @@ fn save_unique_output(out: &str, bytes: &[u8], warnings: &mut Vec) -> Re } #[cfg(target_arch = "wasm32")] -fn save_unique_output(out: &str, _bytes: &[u8], _warnings: &mut Vec) -> Result { +fn save_unique_output(out: &str, _bytes: &[u8]) -> Result { Err(EngineError::Other(format!("cannot write {out}: no file system on the web"))) } +/// Encode before the Batch write checkpoint. Esc accepted during an action or encode therefore +/// leaves the current destination untouched; the worker owns the write once the checkpoint passes. fn save_batch_doc(doc: &Document, out: &str, format: &str, save: SaveOpts, ctx: &crate::jobs::JobCtx) -> Result> { let (bytes, warnings) = encode(doc, format, save)?; ctx.batch_before_write()?; diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 25d0a15f271..7f37fa827a4 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -125,3 +125,36 @@ fn directory_and_dangling_symlink_names_stay_occupied() { assert_eq!(fs::read_link(output.join("example_1.png")).unwrap(), output.join("missing.png")); assert!(!output.join("missing.png").exists()); } + +#[test] +fn failed_input_does_not_claim_an_output_name() { + let root = tempfile::tempdir().unwrap(); + let corrupt = root.path().join("broken/same.ppm"); + let valid = root.path().join("good/same.ppm"); + fs::create_dir_all(corrupt.parent().unwrap()).unwrap(); + fs::create_dir_all(valid.parent().unwrap()).unwrap(); + fs::write(&corrupt, b"not an image").unwrap(); + fs::write(&valid, PIXELS).unwrap(); + let output = root.path().join("out"); + let result = Session::new().execute(COMMAND, json!({"input":[corrupt,valid],"output":output,"format":"png"})).unwrap(); + assert_eq!(files(&result).unwrap(), [output.join("same.png")]); + let errors = result["errors"].as_array().unwrap(); + assert_eq!(errors.len(), 1); + assert_eq!(errors[0]["file"], json!(corrupt)); + assert_eq!(fs::read_dir(&output).unwrap().count(), 1); +} + +#[test] +fn current_and_open_document_sources_keep_their_output_naming() { + let root = tempfile::tempdir().unwrap(); + let mut session = Session::new(); + session.execute("file.new", json!({"name":"Current", "width":2, "height":2})).unwrap(); + for source in ["current", "open"] { + let out = root.path().join("Current.png"); + fs::write(&out, b"old output").unwrap(); + let result = session.execute(COMMAND, json!({"source":source,"output":root.path(),"format":"png"})).unwrap(); + assert_eq!(files(&result).unwrap(), [out.clone()]); + assert_eq!(result["errors"], json!([])); + assert!(photocraft_io::import("Current.png", &fs::read(out).unwrap()).is_ok()); + } +} From 207d6882e50df03c0098f086f3b3fb8e76e28c67 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 19:53:39 +0000 Subject: [PATCH 4/8] Avoid cloning the expected output path --- .../src/cmd/file_cmds/image_processor_unique_names_tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs index 7f37fa827a4..9d9576a4764 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -153,7 +153,7 @@ fn current_and_open_document_sources_keep_their_output_naming() { let out = root.path().join("Current.png"); fs::write(&out, b"old output").unwrap(); let result = session.execute(COMMAND, json!({"source":source,"output":root.path(),"format":"png"})).unwrap(); - assert_eq!(files(&result).unwrap(), [out.clone()]); + assert_eq!(files(&result).unwrap().as_slice(), std::slice::from_ref(&out)); assert_eq!(result["errors"], json!([])); assert!(photocraft_io::import("Current.png", &fs::read(out).unwrap()).is_ok()); } From fd11847db35212639ab933fd5df679b1809e3c9d Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 20:01:43 +0000 Subject: [PATCH 5/8] Keep the shared collision regression scoped to unchanged commands --- crates/engine/src/cmd/file_cmds/tests.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index f5fd3abe653..09f4ca1f069 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3382,8 +3382,7 @@ fn batch_naming_serial_keeps_same_named_inputs_and_their_pixels() { } } -/// Batch follows Photoshop's later-file-wins behavior. Image Processor and lens correction -/// keep their existing collision error so their outputs are never silently replaced. +/// Batch follows Photoshop's later-file-wins behavior. Lens correction reports collisions. #[test] fn batch_reports_inputs_that_share_an_output_name() { let dir = tmp("collide"); @@ -3397,7 +3396,6 @@ fn batch_reports_inputs_that_share_an_output_name() { png(&input, "b.tif", 8, 8, "#00ff00"); for (cmd, extra) in [ ("file.automate.batch", json!({"steps": [], "format": "jpg"})), - ("file.scripts.imageProcessor", json!({})), ("file.automate.lensCorrection", json!({"format": "jpg"})), ] { let out = join(&dir, cmd); From 25ea9a96ca20266fe2e68b655e52d8714f1931d4 Mon Sep 17 00:00:00 2001 From: Dan Date: Sat, 14 Nov 2026 20:11:01 +0000 Subject: [PATCH 6/8] Format the updated Batch collision regression --- crates/engine/src/cmd/file_cmds/tests.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 09f4ca1f069..51bde7b41a8 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3394,10 +3394,7 @@ fn batch_reports_inputs_that_share_an_output_name() { save_doc(doc(&s), &join(&input, "a.jpg"), None).unwrap(); png(&input, "B.png", 8, 8, "#00ff00"); png(&input, "b.tif", 8, 8, "#00ff00"); - for (cmd, extra) in [ - ("file.automate.batch", json!({"steps": [], "format": "jpg"})), - ("file.automate.lensCorrection", json!({"format": "jpg"})), - ] { + for (cmd, extra) in [("file.automate.batch", json!({"steps": [], "format": "jpg"})), ("file.automate.lensCorrection", json!({"format": "jpg"}))] { let out = join(&dir, cmd); let mut p = extra; p["input"] = json!(input); From 91bde3617103085d46af637bb260a45a860b08a9 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 15 Nov 2026 16:41:17 +0100 Subject: [PATCH 7/8] Artboards to Files order test: expect the file names (#15170) #13641 renamed the exported files to with spaces as hyphens; the order test from #13670 still expected the old p_0000_Empty Board.png names and failed on main. Assert all three names in top-first order. (cherry picked from commit 42e9467bf9d746140a7ecd7a8b7b6382b1b5769b) --- crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs index 49356105a65..0541f8e4566 100644 --- a/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs +++ b/crates/engine/src/cmd/artboard_cmds/pdf_page_order_tests.rs @@ -54,5 +54,7 @@ fn artboards_to_files_keeps_its_top_first_order() { let r = s.execute("file.export.artboardsToFiles", json!({"dir": dir.to_string_lossy(), "prefix": "p"})).unwrap(); let _ = std::fs::remove_dir_all(&dir); let files: Vec<&str> = r["files"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); - assert!(files[0].ends_with("p_0000_Empty Board.png") && files[2].ends_with("p_0002_Red Board.png"), "{files:?}"); + // Files are named , spaces as hyphens (#13633); top artboard first. + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap_or(f)).collect(); + assert_eq!(names, ["pEmpty-Board.png", "pBlue-Board.png", "pRed-Board.png"], "{files:?}"); } From a76326467cdac7a31b44b90482aa438abdff7ff8 Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 15 Nov 2026 16:22:47 +0000 Subject: [PATCH 8/8] Use an action row in the shortcut set switch test --- .../src/prefs/prefs_ui/shortcut_set_switch_tests.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs index dafa8be560f..7512acee99e 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/shortcut_set_switch_tests.rs @@ -165,7 +165,13 @@ fn an_unmodified_set_switches_at_once() { fn an_action_function_key_is_no_edit() { let (mut h, first) = dialog(); h.state_mut().ui.dialogs.retain(|d| d.id != first); - crate::actions::assign_shortcut(h.state_mut(), "Sepia", "F2").unwrap(); + let app = h.state_mut(); + app.run("actions.record", json!({"name": "Sepia"})).unwrap(); + app.run("actions.stop", json!({})).unwrap(); + let row = app.session.actions.list.iter().position(|action| action.name == "Sepia").unwrap(); + crate::actions::assign_shortcut(app, row, "F2").unwrap(); + let action_id = app.session.actions.list[row].action_id.as_deref().unwrap(); + let shortcut_id = photocraft_engine::actions_cmds::occurrence_key(action_id); let ctx = h.ctx.clone(); let id = crate::menus::invoke(h.state_mut(), &ctx, "edit.keyboardShortcuts", json!({})).unwrap()["dialog"].as_u64().unwrap(); h.run_steps(4); @@ -173,6 +179,7 @@ fn an_action_function_key_is_no_edit() { pick_set(&mut h, "PhotoCraft Defaults"); assert!(!asking(&h)); assert_eq!(field(&h, id, "activeSet"), json!("")); + assert_eq!(field(&h, id, "overrides")[shortcut_id], "F2"); } #[test]