diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index e6a9f306c56..680d5e404fa 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,16 @@ 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(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); } @@ -311,9 +328,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 +350,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 +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 { @@ -364,7 +382,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 +391,12 @@ fn process_one( } } let d = scratch.active().ok_or(EngineError::NoDocument)?; + if options.unique { + 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 { 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 +404,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()); @@ -388,6 +412,47 @@ fn process_one( result } +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]) -> 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(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}"))), + } + } + Err(EngineError::Other(format!("{out}: no free output name through suffix _100000"))) +} + +#[cfg(target_arch = "wasm32")] +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> { @@ -561,7 +626,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() { @@ -608,7 +673,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..9d9576a4764 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/image_processor_unique_names_tests.rs @@ -0,0 +1,160 @@ +use std::{ + fs, + path::{Path, PathBuf}, + sync::Barrier, + thread, +}; + +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(); + 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!(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!(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()); + } + 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!(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!(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!(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")); +} + +#[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!(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")); + 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().as_slice(), std::slice::from_ref(&out)); + assert_eq!(result["errors"], json!([])); + assert!(photocraft_io::import("Current.png", &fs::read(out).unwrap()).is_ok()); + } +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 5438a52a73b..00caffe5089 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) { diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 9671a4ccf91..6d9f3b1018a 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -3626,8 +3626,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"); @@ -3639,11 +3638,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.scripts.imageProcessor", json!({})), - ("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);