From 9f1e7a50ccc2852ee8c628792e7f277161c45011 Mon Sep 17 00:00:00 2001 From: Tsieg Date: Tue, 10 Nov 2026 17:37:13 +0700 Subject: [PATCH 01/10] feat: support current and open documents in Image Processor --- contributors/people.toml | 3 + crates/engine/src/cmd/file_cmds.rs | 2 +- crates/engine/src/cmd/file_cmds/batch_run.rs | 51 ++++ .../cmd/file_cmds/image_processor_tests.rs | 225 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/processing.rs | 31 ++- crates/engine/src/cmd/float_cmds.rs | 12 +- crates/ui-egui/src/browse_field_tests.rs | 25 ++ crates/ui-egui/src/menus/view_cmds/dialogs.rs | 16 +- crates/ui-egui/src/menus/view_cmds/tests.rs | 41 ++++ .../ui-egui/tests/it/batch_export_options.rs | 4 + docs/batch-naming.md | 19 ++ docs/gaps.md | 4 +- docs/target-app-parity.md | 8 +- 13 files changed, 430 insertions(+), 11 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/image_processor_tests.rs diff --git a/contributors/people.toml b/contributors/people.toml index 618dda5608..8b3e707fad 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -329,3 +329,6 @@ sync_github_name = false [people.tomgardenart] display_name = "Nostella" sync_github_name = false + +[people.se343r] +display_name = "Tsieg" diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index b1ec4df7d6..6ecfa1bc39 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -370,7 +370,7 @@ pub fn specs() -> Vec { "Image Processor…", &["File", "Scripts"], None, - r##"{"input":folder|[paths],"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, + r##"{"source":"folder|current|open"="folder" (current processes a copy of the active document; open processes copies of all open documents, including unsaved edits; originals and history stay unchanged),"input":folder|[paths]? (required for folder source),"includeSubfolders":bool=false (a folder input also takes the images in its subfolders, up to 32 levels and 100000 files; each result keeps its subfolder under output),"output":folder,"format":"jpg|png|psd|tiff|…"="jpg","quality":0..12=8,"jpegFormat":"baseline|optimized|progressive"?,"tiffLayers":bool=false,"tiffCompression":"none|lzw|zip"?,"tiffTransparency":bool?,"tiffPyramid":bool=false,"tgaBits":24|32?,"dpxBits":8|10|12|16? (DPX: bits per sample; unset, 8 for an 8-bit document, else 16),"ddsCompression":"none|bc1|bc2|bc3"="none" (DDS: uncompressed, or block compression; BC1 keeps alpha on or off),"ddsMipmaps":bool=false (DDS: also write the full mip chain),"maximizeCompatibility":bool? (PSD/PSB: write the real merged image; unset, Preferences > File Handling > Maximize PSD and PSB File Compatibility),"width":px?,"height":px? (fit, never enlarge),"convertToSrgb":bool=false} → {files, errors} (an input whose output name was already written in the run goes to errors)"##, native, image_processor ), diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index 6af9a34e21..e7e27049cc 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -261,6 +261,57 @@ fn process_outputs<'a>( type PrepareInput<'a> = &'a dyn Fn(&mut Session, &str) -> Result<()>; +/// Process the current in-memory images in scratch sessions: unsaved edits are included and +/// resizing never touches the open documents' pixels, selection, history or save state. +pub(super) fn process_document_copies( + s: &Session, + documents: &[&crate::DocState], + output: &str, + format: &str, + save: SaveOpts, + f: &dyn Fn(&mut Session, &str) -> Result, +) -> Value { + let mut files = Vec::new(); + let mut errors = Vec::new(); + let mut written = OutputClaims::default(); + for state in documents { + // Export resolves stored links against this source, including non-active documents. + let _document = crate::doc_path::scope(state.path.as_deref().map(std::path::Path::new)); + let path = state.path.clone().unwrap_or_else(|| format!("{}.psd", state.doc.name)); + let ext = if format == "same" { same_format(&path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; + let out = join(output, &format!("{}.{ext}", stem(&path))); + // Copies must not overwrite any open source file, including aliases of its path. + if s.documents().iter().filter_map(|doc| doc.path.as_deref()).any(|source| super::paths::same_destination(source, &out)) { + errors.push(json!({"file": path, "error": format!("output would replace an open source file: {out}; choose a different output folder")})); + continue; + } + let prepare = |scratch: &mut Session, _: &str| { + scratch.authorize = s.authorize; + scratch.prefs.edit(|prefs| *prefs = s.prefs().clone()); + scratch.add_document(state.doc.as_ref().clone(), state.path.clone()); + // The moved selection belongs to the displayed image; commit it only in the copy. + if let Some(floating) = crate::float_cmds::floating(state).cloned() { + let copy = scratch.active_mut().ok_or(EngineError::NoDocument)?; + copy.floating = Some(crate::float_cmds::Floating { revision: copy.revision, ..floating }); + crate::float_cmds::drop_floating(scratch)?; + } + Ok(()) + }; + 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) }; + match process_one(s.prefs().raw_defaults.resolution, &path, &out, save, options, &run) { + Ok(()) => { + written.record(&out, &path); + files.push(out); + } + Err(error) => errors.push(error.value("file", &path)), + } + } + json!({"files": files, "errors": errors}) +} + struct InputPolicy<'a> { prepare: PrepareInput<'a>, notices: &'a std::cell::RefCell>, diff --git a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs new file mode 100644 index 0000000000..6e1f6d963c --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs @@ -0,0 +1,225 @@ +use crate::Session; +use photocraft_doc::Document; +use photocraft_geom::Rect; +use serde_json::{Value, json}; +use std::sync::Arc; + +fn add(s: &mut Session, name: &str, depth: u32, background: &str) -> crate::Result { + s.execute("file.new", json!({"name": name, "width": 40, "height": 20, "depth": depth, "background": background})) +} + +fn pixel(doc: &Document) -> [f32; 4] { + photocraft_compose::render(doc, Rect::new(1, 1, 2, 2)).px[0] +} + +fn exported(result: &Value, index: usize) -> std::result::Result> { + let path = result["files"][index].as_str().ok_or("export result has no filename")?; + Ok(photocraft_io::import(path, &std::fs::read(path)?)?.document) +} + +#[test] +fn image_processor_current_uses_unsaved_edits_at_several_depths_without_changing_the_source() { + for depth in [8, 16, 32] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("source.psd"); + let output = dir.path().join("processed"); + let mut s = Session::new(); + add(&mut s, "Other", depth, "#0000ff").unwrap(); + add(&mut s, "Current", depth, "#ff0000").unwrap(); + s.execute("file.saveACopy", json!({"path": path})).unwrap(); + let st = s.active_mut().unwrap(); + st.path = Some(path.to_string_lossy().into_owned()); + st.saved_revision = st.revision; + let source_bytes = std::fs::read(&path).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + s.execute("select.all", json!({})).unwrap(); + let st = s.active().unwrap(); + let before = st.doc.clone(); + let history = st.history.past_len(); + let layer = st.active_layer; + let selection = st.selected_layers(); + let active = s.active_index(); + assert!(st.is_dirty()); + let result = + s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": output, "format": "psd", "width": 20, "height": 20})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + let copy = exported(&result, 0).unwrap(); + assert_eq!((copy.size.width, copy.size.height), (20, 10)); + assert_eq!(copy.depth, s.active().unwrap().doc.depth); + let px = pixel(©); + assert!(px[0] < 0.01 && px[1] > 0.99 && px[2] > 0.99, "the unsaved cyan image is processed: {px:?}"); + let st = s.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &before), "the source document remains the same snapshot"); + assert_eq!(st.history.past_len(), history); + assert_eq!(st.active_layer, layer); + assert_eq!(st.selected_layers(), selection); + assert!(st.is_dirty()); + assert_eq!(s.active_index(), active); + assert_eq!(s.documents().len(), 2); + assert_eq!(std::fs::read(&path).unwrap(), source_bytes); + } +} + +#[test] +fn image_processor_current_accepts_an_untitled_document() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + add(&mut s, "Untitled-1", 8, "#ff0000").unwrap(); + let result = s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": dir.path(), "format": "png"})).unwrap(); + assert_eq!(result["files"], json!([dir.path().join("Untitled-1.png")])); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(exported(&result, 0).unwrap().size, s.active().unwrap().doc.size, "no dimensions means no resize"); +} + +#[test] +fn image_processor_open_copies_every_document_and_reports_collisions_without_overwriting() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + add(&mut s, "Same", 8, "#ff0000").unwrap(); + add(&mut s, "Same", 8, "#0000ff").unwrap(); + add(&mut s, "Other", 8, "#00ff00").unwrap(); + let before: Vec<_> = s.documents().iter().map(|st| (st.doc.clone(), st.history.past_len(), st.path.clone())).collect(); + let active = s.active_index(); + let result = s.execute("file.scripts.imageProcessor", json!({"source": "open", "output": dir.path(), "format": "png", "width": 20})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 2, "{result}"); + assert_eq!(result["errors"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"][0]["error"].as_str().unwrap().contains("same output name")); + let first = exported(&result, 0).unwrap(); + assert_eq!((first.size.width, first.size.height), (20, 10)); + assert!(pixel(&first)[0] > 0.99, "the first result stays red"); + assert!(pixel(&exported(&result, 1).unwrap())[1] > 0.99, "processing continues after the collision"); + assert_eq!(s.documents().len(), before.len()); + for (st, (doc, history, path)) in s.documents().iter().zip(&before) { + assert!(Arc::ptr_eq(&st.doc, doc)); + assert_eq!(st.history.past_len(), *history); + assert_eq!(&st.path, path); + } + assert_eq!(s.active_index(), active); +} + +#[test] +fn image_processor_current_cannot_replace_an_open_source_file() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("source.png"); + let mut s = Session::new(); + add(&mut s, "Source", 8, "#ff0000").unwrap(); + s.execute("file.saveACopy", json!({"path": path})).unwrap(); + let st = s.active_mut().unwrap(); + st.path = Some(path.to_string_lossy().into_owned()); + st.saved_revision = st.revision; + let bytes = std::fs::read(&path).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let result = s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": dir.path(), "format": "png"})).unwrap(); + assert!(result["files"].as_array().unwrap().is_empty(), "{result}"); + assert!(result["errors"][0]["error"].as_str().unwrap().contains("open source file")); + assert_eq!(std::fs::read(path).unwrap(), bytes); +} + +#[test] +fn image_processor_open_sources_fail_gracefully_with_no_documents_or_bad_source_params() { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + for source in [json!("current"), json!("open"), json!("unknown"), json!(true), json!(7), json!([])] { + assert!(s.execute("file.scripts.imageProcessor", json!({"source": source, "output": dir.path()})).is_err()); + } + add(&mut s, "Untitled", 8, "#ffffff").unwrap(); + for format in ["", "../png", "png/escape", "png\\escape", "png\n"] { + assert!(s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": dir.path(), "format": format})).is_err()); + } + assert!(s.execute("file.scripts.imageProcessor", json!({"source": "current"})).is_err()); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); +} + +#[test] +fn image_processor_current_preserves_authorization_for_resize_commands() { + fn deny_resize(id: &str, _: &Value) -> crate::Result<()> { + if id == "image.imageSize" { Err(crate::EngineError::Other("resize denied".into())) } else { Ok(()) } + } + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + add(&mut s, "Untitled", 8, "#ffffff").unwrap(); + s.authorize = Some(deny_resize); + let result = s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": dir.path(), "width": 20})).unwrap(); + assert_eq!(result["files"], json!([])); + assert!(result["errors"][0]["error"].as_str().unwrap().contains("resize denied")); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); + assert_eq!(s.active().unwrap().doc.size.width, 40); +} + +#[test] +fn image_processor_open_sources_export_a_moved_selection_without_committing_it_in_the_original() { + for source in ["current", "open"] { + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + add(&mut s, "Moved", 8, "#ff0000").unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("select.float", json!({"dx": 10, "dy": 0})).unwrap(); + let st = s.active().unwrap(); + let original = st.doc.clone(); + let history = st.history.past_len(); + let revision = st.revision; + let floating = crate::float_cmds::floating(st).unwrap().clone(); + let expected = floating.parts.moved(&original, floating.offset.0, floating.offset.1).unwrap(); + assert_ne!(pixel(&expected), pixel(&original), "moving the selection changes the displayed source pixel"); + let result = s.execute("file.scripts.imageProcessor", json!({"source": source, "output": dir.path(), "format": "png"})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(pixel(&exported(&result, 0).unwrap()), pixel(&expected)); + let st = s.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &original)); + assert_eq!(st.history.past_len(), history); + assert_eq!(st.revision, revision); + let still_floating = crate::float_cmds::floating(st).unwrap(); + assert_eq!(still_floating.offset, floating.offset); + assert!(Arc::ptr_eq(&still_floating.parts, &floating.parts)); + } +} + +#[test] +fn image_processor_open_embeds_relative_links_from_each_documents_own_folder() { + use photocraft_doc::{LayerContent, SmartSource}; + + let dir = tempfile::tempdir().unwrap(); + let mut s = Session::new(); + let mut sources = Vec::new(); + for (name, color) in [("First", "#ff0000"), ("Second", "#0000ff")] { + let folder = dir.path().join(name); + std::fs::create_dir(&folder).unwrap(); + let asset = folder.join("asset.png"); + add(&mut s, name, 8, color).unwrap(); + s.execute("file.saveACopy", json!({"path": asset})).unwrap(); + sources.push(std::fs::read(&asset).unwrap()); + s.active_mut().unwrap().path = Some(folder.join(format!("{name}.pcraft")).to_string_lossy().into_owned()); + s.execute("file.placeLinked", json!({"path": asset})).unwrap(); + let layer = s.active().unwrap().active_layer.unwrap(); + s.edit("Relative link", |doc, _| { + if let Some(LayerContent::Smart(smart)) = doc.layer_mut(layer).map(|layer| &mut layer.content) { + smart.source = SmartSource::Linked { path: "asset.png".into() }; + } + Ok(()) + }) + .unwrap(); + } + let originals: Vec<_> = s.documents().iter().map(|state| state.doc.clone()).collect(); + let result = s.execute("file.scripts.imageProcessor", json!({"source": "open", "output": dir.path().join("processed"), "format": "psd"})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert_eq!(result["files"].as_array().unwrap().len(), sources.len()); + for (index, expected) in sources.iter().enumerate() { + let copy = exported(&result, index).unwrap(); + let bytes = copy + .layers + .iter() + .find_map(|layer| match &layer.content { + LayerContent::Smart(smart) => match &smart.source { + SmartSource::Embedded { bytes, .. } => Some(bytes.as_slice()), + SmartSource::Linked { path } => photocraft_io::linked::embedded_payload(©.metadata, path).map(|(_, bytes)| bytes), + }, + _ => None, + }) + .expect("the exported PSD embeds its linked asset"); + assert_eq!(bytes, expected, "each document resolves asset.png from its own folder"); + } + for (state, original) in s.documents().iter().zip(&originals) { + assert!(Arc::ptr_eq(&state.doc, original)); + } +} diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index 3388f4d7a9..f9af9c37df 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::{batch_inputs_tree, process_tree}; +use super::batch_run::{batch_inputs_tree, process_document_copies, process_tree}; use super::open::import_opened; use super::paths::{file_name, list_images, read_file, stem}; use super::save::SaveOpts; @@ -7,6 +7,10 @@ use super::{ str_param, }; +#[cfg(all(test, not(target_arch = "wasm32")))] +#[path = "image_processor_tests.rs"] +mod image_processor_tests; + // ---------- Automate ---------- pub(super) fn fit_image(s: &mut Session, p: &Value) -> Result { @@ -86,15 +90,24 @@ pub(super) fn parse_steps(v: &Value) -> Result> { pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { let cmd = "file.scripts.imageProcessor"; + let source = match p.get("source") { + None | Some(Value::Null) => "folder", + Some(Value::String(source)) if matches!(source.as_str(), "folder" | "current" | "open") => source.as_str(), + _ => return Err(EngineError::BadParams { cmd: cmd.into(), msg: "source must be folder, current or open".into() }), + }; let output = str_param(p, "output", cmd)?.to_string(); - let inputs = batch_inputs_tree(p, cmd, &output)?; let format = p.get("format").and_then(Value::as_str).unwrap_or("jpg").to_string(); + // The format becomes a filename extension, never a path supplied by a caller. + if format.trim_start_matches('.').is_empty() || format.contains(['/', '\\']) || format.chars().any(char::is_control) { + return Err(EngineError::BadParams { cmd: cmd.into(), msg: "format must be a filename extension".into() }); + } let fit = match (size_param(p, "width"), size_param(p, "height")) { (None, None) => None, (w, h) => Some(json!({"width": w.unwrap_or(1e9), "height": h.unwrap_or(1e9), "dontEnlarge": true})), }; let to_srgb = p.get("convertToSrgb").and_then(Value::as_bool).unwrap_or(false); - let r = process_tree(s, &inputs, &output, &format, SaveOpts::from_params(s, p, cmd)?.or_quality(8.0), "", &|scratch, _| { + let save = SaveOpts::from_params(s, p, cmd)?.or_quality(8.0); + let process = |scratch: &mut Session, _: &str| { if to_srgb && scratch.active().is_some_and(|d| d.doc.mode != ColorMode::Rgb) { scratch.execute("image.mode.rgb", json!({}))?; } @@ -102,7 +115,17 @@ pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { fit_image(scratch, fp)?; } Ok(false) - }); + }; + let r = if source == "folder" { + let inputs = batch_inputs_tree(p, cmd, &output)?; + process_tree(s, &inputs, &output, &format, save, "", &process) + } else { + let documents = if source == "current" { vec![s.active().ok_or(EngineError::NoDocument)?] } else { s.documents().iter().collect() }; + if documents.is_empty() { + return Err(EngineError::NoDocument); + } + process_document_copies(s, &documents, &output, &format, save, &process) + }; Ok(r) } diff --git a/crates/engine/src/cmd/float_cmds.rs b/crates/engine/src/cmd/float_cmds.rs index 1406f59ba8..9cfa5d3f96 100644 --- a/crates/engine/src/cmd/float_cmds.rs +++ b/crates/engine/src/cmd/float_cmds.rs @@ -350,8 +350,16 @@ pub fn drop_floating(s: &mut Session) -> Result { /// Commands that leave a floating piece floating: its own, and ones that don't touch documents. fn keeps_floating(id: &str) -> bool { - matches!(id, "select.float" | "select.drop" | "layer.copyToDocument" | "brush.mixer.sample" | "brush.mixer.load" | "brush.mixer.clean") - || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p)) + matches!( + id, + "select.float" + | "select.drop" + | "layer.copyToDocument" + | "file.scripts.imageProcessor" + | "brush.mixer.sample" + | "brush.mixer.load" + | "brush.mixer.clean" + ) || ["view.", "window.", "help.", "prefs."].iter().any(|p| id.starts_with(p)) } /// Before any command (`Session::dispatch`): Undo puts a floating piece back (and is used up: diff --git a/crates/ui-egui/src/browse_field_tests.rs b/crates/ui-egui/src/browse_field_tests.rs index c42b296a95..0fbe1475cf 100644 --- a/crates/ui-egui/src/browse_field_tests.rs +++ b/crates/ui-egui/src/browse_field_tests.rs @@ -99,3 +99,28 @@ fn data_sets_as_files_folder_is_chosen_with_browse() { assert!(matches!(asked.borrow().as_slice(), [FileDialogRequest::Folder { .. }])); assert_eq!(field(&h, "dir"), Some(json!("/tmp/dataset-exports"))); } + +#[test] +fn image_processor_source_picker_hides_folder_fields_for_open_documents() { + let (mut h, _) = harness(vec![]); + h.state_mut().run("file.new", json!({"width": 40, "height": 20})).unwrap(); + let ctx = h.ctx.clone(); + crate::menus::invoke(h.state_mut(), &ctx, "file.scripts.imageProcessor", json!({})).unwrap(); + h.run_steps(4); + assert_eq!(field(&h, "source"), Some(json!("current"))); + assert_eq!(h.query_all_by_label("Browse…").count(), 1, "only the output folder is needed"); + assert_eq!(h.query_all_by_label("Include All Subfolders").count(), 0); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Source").click(); + h.run_steps(4); + h.get_by_label("Folder").click(); + h.run_steps(4); + assert_eq!(field(&h, "source"), Some(json!("folder"))); + assert_eq!(h.query_all_by_label("Browse…").count(), 2); + assert_eq!(h.query_all_by_label("Include All Subfolders").count(), 1); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Source").click(); + h.run_steps(4); + h.get_by_label("All open documents").click(); + h.run_steps(4); + assert_eq!(field(&h, "source"), Some(json!("open"))); + assert_eq!(h.query_all_by_label("Browse…").count(), 1); +} diff --git a/crates/ui-egui/src/menus/view_cmds/dialogs.rs b/crates/ui-egui/src/menus/view_cmds/dialogs.rs index b2b7d56158..02d232cf06 100644 --- a/crates/ui-egui/src/menus/view_cmds/dialogs.rs +++ b/crates/ui-egui/src/menus/view_cmds/dialogs.rs @@ -154,6 +154,12 @@ pub fn form_body(ui: &mut egui::Ui, f: &mut Map) { let mut browse: Option = None; egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { for k in keys { + if f.get("__command").and_then(Value::as_str) == Some("file.scripts.imageProcessor") + && f.get("source").and_then(Value::as_str).is_some_and(|source| source != "folder") + && matches!(k.as_str(), "input" | "includeSubfolders") + { + continue; + } 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")); @@ -547,8 +553,14 @@ pub(super) fn front(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, para ), "file.scripts.imageProcessor" => dialog( app, - json!({"input": dir, "includeSubfolders": false, "__labels": subfolders_label(), "output": format!("{dir}/processed"), "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true}), - json!({"format": ["jpg", "png", "psd", "tiff", "webp"]}), + json!({ + "source": if doc.is_some() { "current" } else { "folder" }, + "input": dir, "includeSubfolders": false, "output": format!("{dir}/processed"), + "format": "jpg", "quality": 8, "width": 0, "height": 0, "convertToSrgb": true, + "__labels": {"current": tl!("Current document"), "open": tl!("All open documents"), "folder": tl!("Folder"), "includeSubfolders": tl!("Include All Subfolders")}, + "__order": ["source", "input", "includeSubfolders", "output", "format", "quality", "width", "height", "convertToSrgb"] + }), + json!({"source": ["current", "open", "folder"], "format": ["jpg", "png", "psd", "tiff", "webp"]}), ), "file.automate.batch" => { let Some(action) = crate::actions::selected_action(app) else { diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 3170183d77..5cbe9b9462 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -14,6 +14,46 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option { menu_items(app).into_iter().find(|i| i.id == id).and_then(|i| i.checked) } +#[test] +fn image_processor_source_choices_include_current_and_all_open_documents() { + for n in [0, 2] { + let (mut app, ctx) = app_with(n); + menu(&mut app, &ctx, "file.scripts.imageProcessor", json!({})).unwrap(); + let fields = &app.ui.dialogs.last().unwrap().fields; + assert_eq!(fields["source"], json!(if n == 0 { "folder" } else { "current" })); + assert_eq!(fields["__choices"]["source"], json!(["current", "open", "folder"])); + assert_eq!(fields["__labels"]["current"], json!("Current document")); + assert_eq!(fields["__labels"]["open"], json!("All open documents")); + assert_eq!(form_keys(fields).first().map(String::as_str), Some("source")); + } +} + +#[test] +fn image_processor_dialog_confirms_open_document_sources_without_reading_the_input_folder() { + for source in ["current", "open"] { + let dir = tempfile::tempdir().unwrap(); + let (mut app, ctx) = app_with(0); + for name in ["First", "Second"] { + app.run("file.new", json!({"name": name, "width": 100, "height": 80})).unwrap(); + } + let before: Vec<_> = app.session.documents().iter().map(|st| st.doc.clone()).collect(); + let id = menu(&mut app, &ctx, "file.scripts.imageProcessor", json!({})).unwrap()["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("source".into(), json!(source)); + fields.insert("input".into(), json!(dir.path().join("missing-input"))); + fields.insert("output".into(), json!(dir.path())); + fields.insert("format".into(), json!("png")); + fields.insert("width".into(), json!(50)); + fields.insert("height".into(), json!(50)); + let result = crate::dialogs::confirm(&mut app, id).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), if source == "current" { 1 } else { 2 }, "{result}"); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + for (st, original) in app.session.documents().iter().zip(&before) { + assert!(std::sync::Arc::ptr_eq(&st.doc, original)); + } + } +} + /// #1209: the browser picker supplies bytes even when the engine cannot read native paths. #[test] fn place_embedded_enablement_does_not_require_native_doc() { @@ -688,6 +728,7 @@ fn batch_dialogs_include_all_subfolders() { assert_eq!(fields["stopOnError"], json!(false)); assert_eq!(fields["errorLog"], json!("")); } + fields.insert("source".into(), json!("folder")); fields.insert("input".into(), json!(input)); fields.insert("output".into(), json!(dir.join(out).to_string_lossy())); fields.insert("includeSubfolders".into(), json!(true)); diff --git a/crates/ui-egui/tests/it/batch_export_options.rs b/crates/ui-egui/tests/it/batch_export_options.rs index 1890f6dd9e..bcbdcf9472 100644 --- a/crates/ui-egui/tests/it/batch_export_options.rs +++ b/crates/ui-egui/tests/it/batch_export_options.rs @@ -233,6 +233,10 @@ fn batch_and_processor_real_controls_write_the_chosen_webp_quality() { assert_eq!(fields["width"], json!(0)); assert_eq!(fields["height"], json!(0)); assert_eq!(fields["convertToSrgb"], json!(true)); + h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Source").click(); + h.run_steps(3); + h.get_by_label("Folder").click(); + h.run_steps(3); } choose_webp(&mut h); edit_path(&mut h, "Input", &input); diff --git a/docs/batch-naming.md b/docs/batch-naming.md index 02e4d10f04..6424056e34 100644 --- a/docs/batch-naming.md +++ b/docs/batch-naming.md @@ -58,6 +58,25 @@ The same options are available on `file.automate.batch` through the engine comma The CLI has matching `batch --recursive`, `--naming`, `--start-serial`, `--stop-on-error`, and `--error-log` flags. Droplets use Batch's flat output and naming behavior. +## Image Processor sources + +**File > Scripts > Image Processor…** has a **Source** selector: **Current document**, +**All open documents**, or **Folder**. It defaults to the current document when one is open. +Open-document sources include unsaved edits and untitled images. Resizing and export run on +copies; the open documents, their history and their source files remain intact. Choose a +separate output folder. Duplicate output names appear in the per-file errors instead of +replacing an earlier result. + +Agents can use the same engine command: + +```json +{"source": "current", "output": "exports", "format": "jpg", "width": 1920, "height": 1080} +``` + +Pass this to `file.scripts.imageProcessor`. Use `"source": "open"` for all open documents; +`"source": "folder"` (the command default) takes `"input"` as before. The input folder and +**Include All Subfolders** controls appear only for the folder source. + ## Reference behavior and conformance The [Photoshop 2026 Batch measurements](https://github.com/davidmann4/photocraft/blob/docs/atn-event-reference/docs/atn.md#batch-behaviour) diff --git a/docs/gaps.md b/docs/gaps.md index 5b31b6f254..6b4f13626b 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,6 @@ # Where PhotoCraft falls short of Photoshop -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-07 · **Change:** minor (Image Processor accepts copies of the current or all open documents, including unsaved edits; G5: Warp mode edits Photoshop's Cylinder warp, #4112: the Warp menu lists it, five handles set its seven values as in the reference, and a smart object's stored cylinder opens in Warp mode as one; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; G4: Both Axes on Scatter headers, #3825 partial; G4: combined Spacing checkbox and percentage header, #3825 partial; G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; G4: Angle/Roundness fields left of the Brush Tip Shape widget, #3825 partial; G12: the eraser end of flipped pens selects the Eraser on Windows with Windows Ink on, #2285; no estimate changed; RGB and CMYK documents preview their spot inks as an overprint on the canvas and in the PSD thumbnail, FILE-215-17 narrows to PDF Separation, #10249; G2: compositor compilation moved off the first document refresh, with startup measurements pending, #9157; G11: Playback Options dialog with Step by Step and Pause For, #5212; G11: Stop step messages with Continue/Stop and nested resume, #8386; adjustment-layer Make keeps name, blend mode and clipping, #8384; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; G8: Type › OpenType › Stylistic Sets submenu, Set 1–20, #10285; G8: PhotoCraft-native PSDs keep stylistic sets and other Txt2-only OpenType flags through save/reopen, #10308; G10: TIFF Options dialog on Save As and Save a Copy, compression, Save Image Pyramid, Save Transparency, #8827; G11: Batch Esc Continue/Stop and read-only input previews; full live tabs remain open, #4579; G11: action recording folds Move-tool nudges, records relative keyboard document switches and scales point text placement; paragraph boxes remain open, #4514; G11: Batch measured output naming and UTF-16 log corrections; remaining progress and cancel prompt parity tracked, #4579; G11: Render ATN events mapped; Stylize/Pixelate ATN events mapped, current counts 128 supported/89 unmapped; G9: 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; G11: `.atn` document offsets preserve opening order after tab reordering, #7103; embedded AI/PDF/EPS save-back retains native format with a source-bound SVG display preview; Smooth and Feather command masks cropped to selection bounds plus blur reach; G1: Halftone Pattern Filter Gallery settings survive PSD/PSB saves (#8940); cropped selection morphology and command mask conversion performance evidence added; G6: Art History Brush landed as partial, TOOL-213-20, #1610, so no toolbar tool is missing; G4: five hard-round built-in presets use 5% spacing to remove stacked-tip outlines and reduce pressure-opacity bands, #8842; G9: Crop tool canvas menu, #6561; G2: Content-Aware Scale seam carving 1.65–3.6× faster with unchanged output, P28 row 3.3 → 1.6 s on a 4-core VM, #5236; G9: UI scale presets done, 105–120% steps, #3222; G14: lossy DNG, raw sidecars, Camera Raw Defaults live, Calibration and Auto, CR3 assessed as not clean-room feasible; G8: PSD type on a path opens on its path and saves back into the file's `Txt2`, #7962; G11: a recorded Save As imports with its format and file (`file.saveAs`, `file.saveACopy` for As a Copy) instead of as a plain Save that wrote over the played file, #7102; folder destinations stop playback until #5430; adjustment clipping stays visible in compact Properties, #5231; G9: Color panel modes, ramp and copy commands, the same in every theme, UI-217-17, #6000; G17: Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; G10: `.asl` style libraries landed, #1051; G8: area type (TYPE-218-10); G1: smart objects keep Photoshop's Cylinder warp, #4112; G8: paragraph direction buttons in the Paragraph panel and options bar, TYPE-218-2 partial; G1: 32-bit Hue/Saturation and Colorize as Photoshop does them, Photoshop-oracle floor 190/258, #5781; G11: compound layer properties export as separate Photoshop Set events, rename last, #8304; G11: Batch and droplets take the result at the action's Save step, so actions ending in Save As and Close work; G11: `.atn` steps that switch to another open document import, play and save back, #7103; G14: the Nikon D4 white level follows the sample depth, so 12-bit D4 NEFs no longer open 2.6 stops dark, #5978; G14: a Nikon NEF's Adobe RGB preview is read as Adobe RGB (maker-note ColorSpace 0x001E), #5987; Apply Layer Comp action mapping, #7101; G10: JPEG Options dialog landed, FILE-215-19 partial (no Matte, progressive Scans or size preview); G10: Cineon write; G10: DPX read and write, #1049, Cineon and Amiga IFF read; Classical Object Finder improvement; learned segmentation remains open; G4: named, stateful section locks and visible keyboard focus in Brush Settings; G4: independent Brush Pose tilt-axis overrides, #3825 partial; G4: Transfer Mixer-only controls, #3825 partial; G9: Preferences › File Handling › Save in Background takes effect, #6207, 24 of 169 preferences do nothing; G7: Content-Aware Move previews every selection the command takes, coarse then exact, TOOL-213-4 done, #6680; G4: Pattern Stamp and Background Eraser draw live, TOOL-213-7; G9: Animated Zoom pref read: holding the Zoom tool zooms continuously, #6210, prefs that do nothing 25 of 166; G2: a cancelled 24 MP Gaussian Blur job stops in at most 44 ms, P25 under its 200 ms budget in local runs, baseline not re-run, #6205; G1: generated large-file fixtures, a 4.38 GB PSB opens on Windows through io, FILE-216-2 done, #5107; G9: fill and adjustment layers copy and paste whole, #2344; G1: smart filter masks show on PSD open, Photoshop-oracle floor 188/258; G10: DPX read and write, #1049, Cineon read; G1: CMYK Hue/Saturation and Color Balance keep the black ink; G1: CMYK Posterize on the stored values, psd-tools oracle floor 242/309; G1: CMYK adjustment layers composite on the document's inks, Photoshop-oracle floor 165/258; G1: CMYK Brightness/Contrast on the inks, CMYK Threshold's luma; G1: modern Brightness/Contrast's brightness curve matches Photoshop, Photoshop-oracle floor 151/258; G1: Lab documents composite on their stored L, a, b, Photoshop-oracle floor 152/258; G1: Levels on whole levels at every step, Photoshop-oracle floor 146/258, psd-tools 238/309; G1: 32-bit Brightness/Contrast legacy, Channel Mixer, Photo Filter and Black & White tint unclipped as in Photoshop, Photoshop-oracle floor 149/258; G1: mask feathers blur with their exact variance, psd-tools oracle floor 240/309; G1: Threshold splits on Photoshop's luminosity, psd-tools oracle floor 241/309; G1: pass-through clipping base with an adjustment renders isolated, psd-tools oracle floor 240/309; G1: 16-bit Posterize as Photoshop bins it, psd-tools oracle floor 241/309; G1: Gradient Map driven by the W3C luminosity, Photoshop-oracle floor 147/258; G7: Field Blur's on-canvas pins, #3373; G4: Hue Jitter amount track, #3825 partial; G4: minimum field interaction, #3825 partial; G1: CMYK Invert, Posterize and Threshold on the inks, 16-bit Lab Invert; Photoshop-oracle floor 145/258; G11: `.atn` import maps 112 events: Select and Mask, Filter Gallery Spatter, Ripple, Crystallize, Pattern Fill layers, mask targeting, Step Backward, nudges in points, Bitmap mode; G5: Free Transform H/V skew fields; G9: toolbar tool shortcut editing; refreshed against main: G2, G5, G7, G9, G10, G13, G14, G17 items that landed; G10: DPX read and write, #1049; G4: checkbox-only Brush Settings rows; G11: Load/Save Actions `.atn` landed, AUTO-219-2 partial; G5: hold-a-key spring-loaded tools landed, #2672; G1: #2465 fixed; stale missing-tool rows corrected: Color Replacement, Red Eye and Add/Delete Anchor Point are live tools, so only Art History Brush is missing; no estimate changed; G10: Amiga IFF write; G10: PSD spot channels in Photoshop's polarity, earlier PhotoCraft PSDs keep their ink, #7415 split; G10: TIFF alpha and spot channels written and read as extra samples, FILE-215-7 done, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026) Every known shortfall against Photoshop 2026 (27.11.0), one entry each, ranked by user impact on the way to beta. This is the work list agents pick from: take the highest-ranked entry that @@ -116,6 +116,7 @@ what an agent can't finish alone. - **Estimate:** 120–200 h. ### G11. Actions and scripting +- **Done 2026-11-10:** Image Processor accepts the current document or all open documents as its source, including unsaved edits and untitled documents. Resize/export runs on copies; original pixels, history and source files stay intact. Folder processing is still available. - **Partial 2026-11-02 (#4579):** Batch accepts recursive folders with flat output and last-result-wins names, as measured in Photoshop 2026. It also accepts live open documents, extended naming components, stop-on-error, UTF-16 LE logs, and job cancellation. The CLI @@ -490,6 +491,7 @@ what an agent can't finish alone. | 2026-11-07 | minor | G14: Hasselblad 3FR/FFF, the X2D II 100C's uncompressed CFA, decodes; compressed 3FR still opens as the embedded preview | | 2026-11-06 | minor | G12: eraser end of flipped pens on Windows (Windows Ink on) selects the Eraser (#2285); no estimate changed | | 2026-10-29 | minor | G17: web build memory handling (#10024): up-front memory checks for Place, Image Size, smart-object re-render and Save; a low-memory warning; a stopped message when the module traps; PSD save reserves its whole output; no estimate changed | +| 2026-11-10 | minor | Image Processor: current-document and all-open-document sources process in-memory copies, preserving originals and history; folder input remains available; percentages and estimates unchanged | | 2026-11-02 | minor | G11: Batch Esc Continue/Stop, one plan and error log across interruptions, and read-only input previews without a progress bar (#4579); live tab parity remains open, AUTO-219-5 partial; readiness and estimate unchanged | | 2026-11-02 | minor | Action recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and places point text by canvas percentage; paragraph boxes remain absolute (AUTO-219-1, #4514); parity percentages unchanged | | 2026-11-01 | minor | Action recording stores portable layer targets and whole-text Type steps where unambiguous (AUTO-219-1, #4514); duplicate names remain ambiguous; parity percentages unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 16d0a79e8c..f54ad66dc3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # PhotoCraft vs Adobe Photoshop: target-app parity -> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-02 · **Change:** minor (Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; +> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-10 · **Change:** minor (Image Processor accepts copies of the current or all open documents, including unsaved edits; Average executes through shared filters on Smart Objects and imported PSD records; Average preserves per-pixel alpha and includes hidden RGB in its mean; RGB8 observations against Photoshop 26.6.1, see average-filter.md; RGB and CMYK documents preview their spot inks as an overprint, FILE-215-17 narrows to PDF Separation, #10249; tile-sparse Select and Mask outputs and preview coverage, #8822; classical Select › Sky can seed substantial high-confidence components beneath an obstructed top band; learned segmentation remains open; Art History Brush Opacity on the options bar, #10263; no estimate changed; Automation Batch Esc Continue/Stop and read-only input previews now follow the measured cancellation flow; full live tabs remain partial, AUTO-219-5, #4579; Automation recording folds Move-tool nudge runs, records keyboard document switches by opening-order offset and scales point text placement; paragraph boxes remain open, #4514; Automation Batch output naming and UTF-16 logs now follow measured Photoshop behavior; progress and cancel prompt remain partial, AUTO-219-5, #4579; 11 of 183 preferences do nothing: startup reads Graphics Adapter through the typed Performance section, so the scorecard audit sees it; selected colour sets edit drawing, tone and supported filters; geometry remains open; Smooth and Feather command masks cropped to selection bounds plus blur reach; Equalize with a selection asks Selected Area Only or Entire Image Based On Selected Area; cropped selection morphology and command mask conversion performance evidence added; the Camera Raw row names per-camera colour for non-DNG cameras as missing, not the Calibration panel, which landed 2026-10-13; Content-Aware Scale measurements added, #5236; Help › Check for Updates and an opt-out check once per launch, DIST-220-1 partial, #5485; area type, TYPE-218-10 partial, Type scorecard 5 / 5 / 0; compound layer properties export as separate Photoshop Set events, #8304; JPEG Options dialog landed, FILE-215-19 partial; Print › Functions › Bleed through `file.print`; Content-Aware Move live preview for every selection size, TOOL-213-4 done, #6680; retouching evidence: Pattern Stamp and Background Eraser draw live, only the Mixer Brush is left of TOOL-213-7; fill and adjustment layers copy and paste whole, UI-217-23 partial, #2344; shape layers take Density and Feather, TOOL-214-12 done, #5846; on-canvas corner radius widgets, TOOL-214-12; `.atn` import maps 112 events; Free Transform H/V skew fields; stale rows corrected against `main` and the scorecard, estimates unchanged; Photoshop Actions `.atn` load and save; 2026-10-10: Tilt-Shift measurements added; earlier the same day: major, full re-measure against Photoshop 2026 27.11.0; merged `parity-estimate.md` and the roadmap's honest assessment; stale missing-tool rows corrected: Color Replacement and Red Eye are live toolbar tools, Frame landed; percentages unchanged; PSD spot plates in Photoshop's polarity, #7415 split; TIFF spot plates, FILE-215-17's TIFF part, #7415) · **Target:** Adobe Photoshop 2026; Print: Japanese paper sizes — はがき, 往復はがき, JIS B5/B4, A6, L判, 2L判, KG判, 六切, 四切; The authoritative answer to "how close is PhotoCraft to Photoshop, and how much work is left". The one-page summary is [`ROADMAP.md`](../ROADMAP.md); the ranked work list is [`gaps.md`](gaps.md); @@ -195,6 +195,11 @@ UTF-16 logs match Photoshop 2026. The desktop shows each folder input as a read- snapshot while its action runs, with no progress bar. Full live tabs and Layers panel content for those inputs remain different. AUTO-219-5 is partial (#4579). +Image Processor also accepts the current document or all open documents as its source +(2026-11-10). It processes in-memory copies, including unsaved edits and untitled images, +without changing the open documents or overwriting their source files. Folder input stays +available. This does not change the overall automation estimate. + ## Remaining effort and calibration **Calibration.** The repository's history from the first commit (2026-09-30) to 2026-10-10: 1,152 @@ -595,6 +600,7 @@ See [method, raw measurements and reproduction](five-algorithm-performance.md). | Date | Change | Summary | |---|---|---| +| 2026-11-10 | minor | Image Processor: current-document and all-open-document sources process in-memory copies, preserving originals and history; folder input remains available; percentages and estimates unchanged | | 2026-11-02 | minor | Automation Batch: Esc Continue/Stop preserves one file plan and error log; a read-only input preview replaces the progress bar; full live tabs remain open, AUTO-219-5 partial (#4579); percentages and estimates unchanged | | 2026-11-02 | minor | AUTO-219-1: action recording folds Move-tool nudges, records relative document switches and scales point text placement to the playback canvas; duplicate names and paragraph box placement remain open; Automation parity estimate unchanged | | 2026-11-01 | minor | AUTO-219-1: action recording uses implicit or uniquely named layers and folds Type keystrokes into whole-text steps; duplicate names remain ambiguous; Automation parity estimate unchanged | From 2be02a8b04b894ff2c94bb89d33700e1591e52d2 Mon Sep 17 00:00:00 2001 From: Tsieg Date: Tue, 10 Nov 2026 19:22:57 +0700 Subject: [PATCH 02/10] docs: document Image Processor contracts and regression coverage --- crates/engine/src/cmd/file_cmds.rs | 2 ++ .../cmd/file_cmds/image_processor_tests.rs | 19 +++++++++++++++++++ crates/engine/src/cmd/file_cmds/processing.rs | 4 ++++ crates/ui-egui/src/browse_field_tests.rs | 2 ++ crates/ui-egui/src/menus/view_cmds/tests.rs | 3 +++ .../ui-egui/tests/it/batch_export_options.rs | 2 ++ 6 files changed, 32 insertions(+) diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 6ecfa1bc39..b2f14ada17 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -235,6 +235,8 @@ fn clear_canvas_guides(s: &mut Session) -> Result { // ---------- registry ---------- +/// Register File-menu commands with their parameter contracts and enablement predicates. +/// Filesystem operations are native-only; document operations remain available on the web. pub fn specs() -> Vec { macro_rules! spec { ($id:expr, $label:expr, $menu:expr, $sc:expr, $params:expr, $enabled:expr, $run:expr) => { diff --git a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs index 6e1f6d963c..40e71512eb 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs @@ -1,22 +1,28 @@ +//! Regression coverage for Image Processor document sources and preservation of open work. use crate::Session; use photocraft_doc::Document; use photocraft_geom::Rect; use serde_json::{Value, json}; use std::sync::Arc; +/// Create a small document with explicit color and bit depth for export comparisons. fn add(s: &mut Session, name: &str, depth: u32, background: &str) -> crate::Result { s.execute("file.new", json!({"name": name, "width": 40, "height": 20, "depth": depth, "background": background})) } +/// Sample the same interior pixel before and after processing through the CPU compositor. fn pixel(doc: &Document) -> [f32; 4] { photocraft_compose::render(doc, Rect::new(1, 1, 2, 2)).px[0] } +/// Reimport a reported output so assertions examine encoded pixels and document metadata. fn exported(result: &Value, index: usize) -> std::result::Result> { let path = result["files"][index].as_str().ok_or("export result has no filename")?; Ok(photocraft_io::import(path, &std::fs::read(path)?)?.document) } +/// Resizing must use unsaved pixels at every supported depth while leaving the source +/// snapshot, selected layers, history, dirty state and saved file intact. #[test] fn image_processor_current_uses_unsaved_edits_at_several_depths_without_changing_the_source() { for depth in [8, 16, 32] { @@ -61,6 +67,7 @@ fn image_processor_current_uses_unsaved_edits_at_several_depths_without_changing } } +/// Untitled documents need no source path, and omitted dimensions must preserve their size. #[test] fn image_processor_current_accepts_an_untitled_document() { let dir = tempfile::tempdir().unwrap(); @@ -72,6 +79,8 @@ fn image_processor_current_accepts_an_untitled_document() { assert_eq!(exported(&result, 0).unwrap().size, s.active().unwrap().doc.size, "no dimensions means no resize"); } +/// A duplicate output name must preserve the first result and allow later documents to +/// finish without changing any open document or the active tab. #[test] fn image_processor_open_copies_every_document_and_reports_collisions_without_overwriting() { let dir = tempfile::tempdir().unwrap(); @@ -98,6 +107,7 @@ fn image_processor_open_copies_every_document_and_reports_collisions_without_ove assert_eq!(s.active_index(), active); } +/// Exporting back to an open source path must report an error and preserve its disk bytes. #[test] fn image_processor_current_cannot_replace_an_open_source_file() { let dir = tempfile::tempdir().unwrap(); @@ -116,6 +126,8 @@ fn image_processor_current_cannot_replace_an_open_source_file() { assert_eq!(std::fs::read(path).unwrap(), bytes); } +/// Missing documents, malformed source values, unsafe extensions and absent output paths +/// must fail without creating files. #[test] fn image_processor_open_sources_fail_gracefully_with_no_documents_or_bad_source_params() { let dir = tempfile::tempdir().unwrap(); @@ -131,8 +143,11 @@ fn image_processor_open_sources_fail_gracefully_with_no_documents_or_bad_source_ assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); } +/// A scratch copy must obey the initiating session's resize authorization and write +/// nothing when that nested command is denied. #[test] fn image_processor_current_preserves_authorization_for_resize_commands() { + /// Reject only the nested resize so the test can distinguish inherited authorization. fn deny_resize(id: &str, _: &Value) -> crate::Result<()> { if id == "image.imageSize" { Err(crate::EngineError::Other("resize denied".into())) } else { Ok(()) } } @@ -147,6 +162,8 @@ fn image_processor_current_preserves_authorization_for_resize_commands() { assert_eq!(s.active().unwrap().doc.size.width, 40); } +/// Both document-source modes must export the displayed floating selection while keeping +/// the original floating parts, offset, revision and history unchanged. #[test] fn image_processor_open_sources_export_a_moved_selection_without_committing_it_in_the_original() { for source in ["current", "open"] { @@ -175,6 +192,8 @@ fn image_processor_open_sources_export_a_moved_selection_without_committing_it_i } } +/// Same-named relative assets must resolve against each source document's folder and +/// survive PSD export as the corresponding embedded payload. #[test] fn image_processor_open_embeds_relative_links_from_each_documents_own_folder() { use photocraft_doc::{LayerContent, SmartSource}; diff --git a/crates/engine/src/cmd/file_cmds/processing.rs b/crates/engine/src/cmd/file_cmds/processing.rs index f9af9c37df..dbfd094880 100644 --- a/crates/engine/src/cmd/file_cmds/processing.rs +++ b/crates/engine/src/cmd/file_cmds/processing.rs @@ -88,6 +88,10 @@ pub(super) fn parse_steps(v: &Value) -> Result> { .collect() } +/// Resize and export folder inputs or copies of the current/all open documents. +/// An omitted `source` keeps the folder-input contract; document sources include unsaved +/// edits without modifying the original documents. Invalid parameters and missing documents +/// return an error; processing failures and output-name collisions appear in per-file errors. pub(super) fn image_processor(s: &mut Session, p: &Value) -> Result { let cmd = "file.scripts.imageProcessor"; let source = match p.get("source") { diff --git a/crates/ui-egui/src/browse_field_tests.rs b/crates/ui-egui/src/browse_field_tests.rs index 0fbe1475cf..fe0ffe36cb 100644 --- a/crates/ui-egui/src/browse_field_tests.rs +++ b/crates/ui-egui/src/browse_field_tests.rs @@ -100,6 +100,8 @@ fn data_sets_as_files_folder_is_chosen_with_browse() { assert_eq!(field(&h, "dir"), Some(json!("/tmp/dataset-exports"))); } +/// Switching Source through the actual dropdown must show input-folder controls only for +/// Folder, while retaining the output-folder picker for every source. #[test] fn image_processor_source_picker_hides_folder_fields_for_open_documents() { let (mut h, _) = harness(vec![]); diff --git a/crates/ui-egui/src/menus/view_cmds/tests.rs b/crates/ui-egui/src/menus/view_cmds/tests.rs index 5cbe9b9462..81e90bfab2 100644 --- a/crates/ui-egui/src/menus/view_cmds/tests.rs +++ b/crates/ui-egui/src/menus/view_cmds/tests.rs @@ -14,6 +14,7 @@ fn checked(app: &PhotocraftApp, id: &str) -> Option { menu_items(app).into_iter().find(|i| i.id == id).and_then(|i| i.checked) } +/// The form must list every source first and default to Current only when a document exists. #[test] fn image_processor_source_choices_include_current_and_all_open_documents() { for n in [0, 2] { @@ -28,6 +29,8 @@ fn image_processor_source_choices_include_current_and_all_open_documents() { } } +/// Confirming either document source must ignore a stale input-folder field, export the +/// expected number of copies and retain the open documents' original snapshots. #[test] fn image_processor_dialog_confirms_open_document_sources_without_reading_the_input_folder() { for source in ["current", "open"] { diff --git a/crates/ui-egui/tests/it/batch_export_options.rs b/crates/ui-egui/tests/it/batch_export_options.rs index bcbdcf9472..0e8b65a1aa 100644 --- a/crates/ui-egui/tests/it/batch_export_options.rs +++ b/crates/ui-egui/tests/it/batch_export_options.rs @@ -204,6 +204,8 @@ fn batch_custom_quality_is_bounded_dialog_local_and_reversible() { assert!(h.state().ui.dialogs.last().unwrap().fields["quality"].is_null(), "reopening returns to the existing default"); } +/// Actual folder-mode controls must pass both WebP quality endpoints to the encoder while +/// preserving the active document, history, preferences and recorded actions. #[test] fn batch_and_processor_real_controls_write_the_chosen_webp_quality() { let _gpu = photocraft_testkit::gpu_lock(); From e191f5e41e36f9f65b5524a7e5f3308a3b3532a8 Mon Sep 17 00:00:00 2001 From: Tsieg Date: Tue, 10 Nov 2026 21:48:31 +0700 Subject: [PATCH 03/10] fix: sanitize untitled Image Processor export names --- contributors/people.toml | 1 + crates/engine/src/cmd/file_cmds/batch_run.rs | 6 ++-- .../cmd/file_cmds/image_processor_tests.rs | 36 +++++++++++++++++++ docs/batch-naming.md | 3 ++ 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/contributors/people.toml b/contributors/people.toml index 8b3e707fad..a7a74fa5e1 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -332,3 +332,4 @@ sync_github_name = false [people.se343r] display_name = "Tsieg" +sync_github_name = true diff --git a/crates/engine/src/cmd/file_cmds/batch_run.rs b/crates/engine/src/cmd/file_cmds/batch_run.rs index e7e27049cc..b8ad5a137d 100644 --- a/crates/engine/src/cmd/file_cmds/batch_run.rs +++ b/crates/engine/src/cmd/file_cmds/batch_run.rs @@ -1,5 +1,5 @@ use super::open::import_at_raw_ppi; -use super::paths::{extension, file_name, join, list_files, list_images, read_file, stem, write_file}; +use super::paths::{extension, file_name, join, list_files, list_images, read_file, sanitize, stem, write_file}; use super::processing::parse_steps; use super::save::{SaveOpts, encode, save_doc, save_doc_as}; use super::{Arc, Document, EngineError, Result, Session, Value, batch_naming, json, str_param}; @@ -263,6 +263,7 @@ type PrepareInput<'a> = &'a dyn Fn(&mut Session, &str) -> Result<()>; /// Process the current in-memory images in scratch sessions: unsaved edits are included and /// resizing never touches the open documents' pixels, selection, history or save state. +/// Untitled names use the shared filename sanitizer before becoming output stems. pub(super) fn process_document_copies( s: &Session, documents: &[&crate::DocState], @@ -277,7 +278,8 @@ pub(super) fn process_document_copies( for state in documents { // Export resolves stored links against this source, including non-active documents. let _document = crate::doc_path::scope(state.path.as_deref().map(std::path::Path::new)); - let path = state.path.clone().unwrap_or_else(|| format!("{}.psd", state.doc.name)); + // An untitled document's name is a label, not a path: keep it as one portable component. + let path = state.path.clone().unwrap_or_else(|| format!("{}.psd", sanitize(&state.doc.name))); let ext = if format == "same" { same_format(&path) } else { format.trim_start_matches('.').to_ascii_lowercase() }; let out = join(output, &format!("{}.{ext}", stem(&path))); // Copies must not overwrite any open source file, including aliases of its path. diff --git a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs index 40e71512eb..49c19bcf99 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs @@ -242,3 +242,39 @@ fn image_processor_open_embeds_relative_links_from_each_documents_own_folder() { assert!(Arc::ptr_eq(&state.doc, original)); } } + +/// Untitled names are labels rather than paths: preserve the full name through the shared +/// sanitizer, keep the original document untouched and use PSD for the `same` format. +#[test] +fn image_processor_untitled_names_use_the_shared_filename_sanitizer() { + for source in ["current", "open"] { + for (format, extension) in [("png", "png"), ("same", "psd")] { + for (name, safe_name) in [ + ("foo/bar", "foo_bar"), + (r"foo\bar", "foo_bar"), + ("../outside", "_outside"), + ("../../outside", "_.._outside"), + ("..", "layer"), + ("CON", "CON_"), + ("nul.v2", "nul_.v2"), + ("trailing. ", "trailing"), + ("chapter.v2", "chapter.v2"), + ] { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("processed"); + let mut s = Session::new(); + add(&mut s, name, 8, "#ff0000").unwrap(); + let original = s.active().unwrap().doc.clone(); + let result = s.execute("file.scripts.imageProcessor", json!({"source": source, "output": output, "format": format})).unwrap(); + assert!(result["errors"].as_array().unwrap().is_empty(), "{source}, {format}, {name:?}: {result}"); + assert_eq!(result["files"], json!([output.join(format!("{safe_name}.{extension}"))]), "{source}, {format}, {name:?}"); + assert_eq!(exported(&result, 0).unwrap().size, original.size); + let state = s.active().unwrap(); + assert!(Arc::ptr_eq(&state.doc, &original)); + assert_eq!(state.doc.name, name); + assert!(state.path.is_none()); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1, "only the output folder is created"); + } + } + } +} diff --git a/docs/batch-naming.md b/docs/batch-naming.md index 6424056e34..c6e488d4fd 100644 --- a/docs/batch-naming.md +++ b/docs/batch-naming.md @@ -67,6 +67,9 @@ copies; the open documents, their history and their source files remain intact. separate output folder. Duplicate output names appear in the per-file errors instead of replacing an earlier result. +Untitled document names follow the portable filename rules used for layer exports: for +example, `foo/bar` becomes `foo_bar`. The document's displayed name stays unchanged. + Agents can use the same engine command: ```json From 1f64c7e8af45d92e7ab479a5b2d5fec6808ae90d Mon Sep 17 00:00:00 2001 From: Tsieg Date: Tue, 10 Nov 2026 22:15:42 +0700 Subject: [PATCH 04/10] test: compare Image Processor output paths portably --- .../engine/src/cmd/file_cmds/image_processor_tests.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs index 49c19bcf99..129f02e317 100644 --- a/crates/engine/src/cmd/file_cmds/image_processor_tests.rs +++ b/crates/engine/src/cmd/file_cmds/image_processor_tests.rs @@ -74,7 +74,8 @@ fn image_processor_current_accepts_an_untitled_document() { let mut s = Session::new(); add(&mut s, "Untitled-1", 8, "#ff0000").unwrap(); let result = s.execute("file.scripts.imageProcessor", json!({"source": "current", "output": dir.path(), "format": "png"})).unwrap(); - assert_eq!(result["files"], json!([dir.path().join("Untitled-1.png")])); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert_eq!(std::path::Path::new(result["files"][0].as_str().unwrap()), dir.path().join("Untitled-1.png").as_path()); assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); assert_eq!(exported(&result, 0).unwrap().size, s.active().unwrap().doc.size, "no dimensions means no resize"); } @@ -267,7 +268,12 @@ fn image_processor_untitled_names_use_the_shared_filename_sanitizer() { let original = s.active().unwrap().doc.clone(); let result = s.execute("file.scripts.imageProcessor", json!({"source": source, "output": output, "format": format})).unwrap(); assert!(result["errors"].as_array().unwrap().is_empty(), "{source}, {format}, {name:?}: {result}"); - assert_eq!(result["files"], json!([output.join(format!("{safe_name}.{extension}"))]), "{source}, {format}, {name:?}"); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{source}, {format}, {name:?}: {result}"); + assert_eq!( + std::path::Path::new(result["files"][0].as_str().unwrap()), + output.join(format!("{safe_name}.{extension}")).as_path(), + "{source}, {format}, {name:?}" + ); assert_eq!(exported(&result, 0).unwrap().size, original.size); let state = s.active().unwrap(); assert!(Arc::ptr_eq(&state.doc, &original)); From 06650357d85e04e0b2475d510574b0b6fc0883c8 Mon Sep 17 00:00:00 2001 From: Tanish Manku Date: Wed, 11 Nov 2026 00:41:27 -0700 Subject: [PATCH 05/10] Fix main: drop the TIFF tag constants #9781 and #10983 both added, split prepare #9781 and #10983 each defined TAG_JPEG_TABLES and TAG_PREDICTOR in tiff/decode.rs and merged minutes apart, so main stopped compiling (E0428). Keep one definition, and move the structural-tag checks and the held-bytes sum out of prepare, whose cognitive complexity the two changes together pushed past clippy's limit. --- crates/codecs/src/codecs/tiff/decode.rs | 54 +++++++++++++------------ 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/crates/codecs/src/codecs/tiff/decode.rs b/crates/codecs/src/codecs/tiff/decode.rs index e7956ad9b1..f47b3c90c0 100644 --- a/crates/codecs/src/codecs/tiff/decode.rs +++ b/crates/codecs/src/codecs/tiff/decode.rs @@ -775,23 +775,42 @@ fn prepared_warnings(p: &Prepared) -> Vec { warnings } -/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one -/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here. Chunk -/// tables larger than `limits.max_alloc` are refused before the `tiff` crate reads them. -fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result { - // The values the `tiff` crate reads must exist: a count past the end of the file is - // neither allocated nor read. +/// The structural tags the `tiff` crate reads must exist (a count past the end of the file is +/// neither allocated nor read) and appear once: this parser reads the first entry of a tag and +/// the `tiff` crate the last, so a repeated structural tag (a small SamplesPerPixel first, a +/// large one last) would be checked here with one value and sized by the crate with another. +fn check_structural_tags(f: &File<'_>, dir: &Ifd) -> Result<(), CodecError> { if let Some(e) = dir.entries.iter().find(|e| ifd::STRUCTURAL_TAGS.contains(&e.tag) && f.data(e).is_none()) { return Err(err(format!("tag {} points past the end of the file", e.tag))); } - // This parser reads the first entry of a tag and the `tiff` crate the last, so a repeated - // structural tag (a small SamplesPerPixel first, a large one last) would be checked here with - // one value and sized by the crate with another. let mut structural: Vec = dir.entries.iter().map(|e| e.tag).filter(|t| ifd::STRUCTURAL_TAGS.contains(t)).collect(); structural.sort_unstable(); if let Some(w) = structural.windows(2).find(|w| w[0] == w[1]) { return Err(err(format!("tag {} appears more than once", w[0]))); } + Ok(()) +} + +/// The bytes the first `expected` strips or tiles hold inside the file, never more than the file. +fn held_bytes(f: &File<'_>, (offsets, sizes): (&ifd::Entry, &ifd::Entry), expected: u64) -> u64 { + let len = f.b.len() as u64; + let mut held = 0u64; + for i in 0..expected { + if held >= len { + break; + } + if let (Some(at), Some(n)) = (f.uint(offsets, i), f.uint(sizes, i)) { + held = held.saturating_add(n.min(len.saturating_sub(at))); + } + } + held.min(len) +} + +/// Checks one directory and lays it out for decoding. `whole`: the image is decoded into one +/// buffer, which `limits.max_alloc` bounds; otherwise only its size is checked here. Chunk +/// tables larger than `limits.max_alloc` are refused before the `tiff` crate reads them. +fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result { + check_structural_tags(f, dir)?; let need = |tag: u16, name: &str| f.tag_uint(dir, tag).ok_or_else(|| err(format!("missing or unreadable {name}"))); let w = u32::try_from(need(ifd::TAG_WIDTH, "ImageWidth")?).map_err(|_| err("ImageWidth out of range"))?; let h = u32::try_from(need(ifd::TAG_HEIGHT, "ImageLength")?).map_err(|_| err("ImageLength out of range"))?; @@ -934,21 +953,11 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result cw.clamp(4096, 65_535), _ => 4096, }; - let len = f.b.len() as u64; let (offsets, sizes) = ( dir.get(offsets_tag).ok_or_else(|| err("missing strip or tile offsets"))?, dir.get(counts_tag).ok_or_else(|| err("missing strip or tile byte counts"))?, ); - let mut held = 0u64; - for i in 0..expected { - if held >= len { - break; - } - if let (Some(at), Some(n)) = (f.uint(offsets, i), f.uint(sizes, i)) { - held = held.saturating_add(n.min(len.saturating_sub(at))); - } - } - let held = held.min(len); + let held = held_bytes(f, (offsets, sizes), expected); if stored > held.saturating_mul(ratio).saturating_add(1 << 20) { return Err(err(format!("the strips or tiles in this file hold {held} bytes, too few for a {w}x{h} image"))); } @@ -1074,11 +1083,6 @@ fn prepare(f: &File<'_>, dir: &Ifd, limits: &Limits, whole: bool) -> Result Date: Wed, 11 Nov 2026 00:49:15 -0700 Subject: [PATCH 06/10] Fix main: clippy after the 11-11 merges - io: drop the no-op drop(tick) in psd_export (clippy::drop_non_drop). - automation: split the Windows UNC helper test from #10323 into three, each under the cognitive-complexity limit. - ui-egui: RangeInclusive::contains in the pen cursor and the dash test. --- crates/automation/src/workspace/tests.rs | 18 +++++++++++++++++- crates/io/src/psd_export/document.rs | 1 - crates/ui-egui/src/canvas/paint.rs | 2 +- crates/ui-egui/src/canvas/tool_cursor/pen.rs | 2 +- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/workspace/tests.rs b/crates/automation/src/workspace/tests.rs index 219ca6c9b4..59bd768bc5 100644 --- a/crates/automation/src/workspace/tests.rs +++ b/crates/automation/src/workspace/tests.rs @@ -449,7 +449,7 @@ fn windows_unc_root_writes_and_exports_when_supported() { #[cfg(windows)] #[test] fn windows_handle_relative_helpers_match_the_capability_operations() { - let (inside, outside, workspace) = roots("unc-helpers"); + let (inside, _outside, workspace) = roots("unc-helpers"); let root = workspace.write.as_ref().unwrap(); assert!(!is_unc_root(root)); @@ -464,7 +464,15 @@ fn windows_handle_relative_helpers_match_the_capability_operations() { std::fs::create_dir(inside.join("dir")).unwrap(); assert!(delete_on_close(&root.dir, Path::new("dir")).is_err()); assert!(inside.join("dir").is_dir()); +} +/// The ambient rename that stands in for the capability's below a UNC root (#10317). +#[cfg(windows)] +#[test] +fn windows_rename_unc_matches_the_capability_rename() { + let (inside, outside, workspace) = roots("unc-rename"); + let root = workspace.write.as_ref().unwrap(); + std::fs::create_dir(inside.join("dir")).unwrap(); // The ambient rename on the canonical root path behaves like the capability's: it creates, // replaces a file, replaces a link instead of writing through it, and refuses a directory. std::fs::write(inside.join("plain.tmp"), b"the longer first version").unwrap(); @@ -487,7 +495,15 @@ fn windows_handle_relative_helpers_match_the_capability_operations() { assert_eq!(std::fs::read(outside.join("target.png")).unwrap(), b"outside"); } let _ = std::fs::remove_file(inside.join("plain.tmp")); +} +/// The directory walk that stands in for the capability's `create_dir_all` below a UNC root +/// (#10317) creates, refuses files on the way and never follows a junction outside. +#[cfg(windows)] +#[test] +fn windows_create_dir_all_unc_matches_the_capability_operation() { + let (inside, outside, workspace) = roots("unc-dirs"); + let root = workspace.write.as_ref().unwrap(); create_dir_all_unc(root, Path::new("a/b/c")).unwrap(); assert!(inside.join("a/b/c").is_dir()); create_dir_all_unc(root, Path::new("a/b/c")).unwrap(); diff --git a/crates/io/src/psd_export/document.rs b/crates/io/src/psd_export/document.rs index f4a118b003..fb09a54ffc 100644 --- a/crates/io/src/psd_export/document.rs +++ b/crates/io/src/psd_export/document.rs @@ -127,7 +127,6 @@ fn export_supported_document( }; let space = photocraft_compose::cmyk_space(doc); photocraft_color::convert::with_cmyk_space(space.as_ref(), || ex.emit(&doc.layers, &mut tick)); - drop(tick); ctl.progress(layers_share); let merged = prepare_merged_planes(doc, &mut ex, opts, ctl, fmt, duotone_inks.is_some(), layers_share); diff --git a/crates/ui-egui/src/canvas/paint.rs b/crates/ui-egui/src/canvas/paint.rs index 07e507d935..af38b54dbc 100644 --- a/crates/ui-egui/src/canvas/paint.rs +++ b/crates/ui-egui/src/canvas/paint.rs @@ -741,7 +741,7 @@ mod clip_segment_tests { assert!(!starts.is_empty(), "the view at {left} shows dashes"); for d in starts { let off = d % (2.0 * DASH); - assert!(off < 0.01 || off > 2.0 * DASH - 0.01, "view at {left}: a dash starts {d} from the corner, off the pattern by {off}"); + assert!(!(0.01..=2.0 * DASH - 0.01).contains(&off), "view at {left}: a dash starts {d} from the corner, off the pattern by {off}"); } } } diff --git a/crates/ui-egui/src/canvas/tool_cursor/pen.rs b/crates/ui-egui/src/canvas/tool_cursor/pen.rs index fc7d968af4..302f92e8c2 100644 --- a/crates/ui-egui/src/canvas/tool_cursor/pen.rs +++ b/crates/ui-egui/src/canvas/tool_cursor/pen.rs @@ -92,7 +92,7 @@ pub fn rasterize(variant: PenVariant, scale: f32) -> Option { return None; } let icon_px_f = (LOGICAL_SIZE * scale).round(); - if icon_px_f < 1.0 || icon_px_f > 512.0 { + if !(1.0..=512.0).contains(&icon_px_f) { return None; } let icon_px = icon_px_f as u32; From cb5243bf785b9ea3814101a88976cf6c5cad23c3 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 11 Nov 2026 09:27:55 +0100 Subject: [PATCH 07/10] =?UTF-8?q?=EF=BB=BFFix=20main:=20SVG=20raster=20dep?= =?UTF-8?q?th=20test=20after=20#11009=20and=20#10953?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #11009 added a check that rasterize_rgba8 renders 500 nested opacity groups. #10953, merged after it, refuses whole-drawing rasterisation past 200 nested layers. The test now expects that refusal as an error, and still renders a drawing within the limit on the same 512 KiB stack. --- crates/io/tests/it/svg.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/crates/io/tests/it/svg.rs b/crates/io/tests/it/svg.rs index fc398796cb..7402bf290d 100644 --- a/crates/io/tests/it/svg.rs +++ b/crates/io/tests/it/svg.rs @@ -448,7 +448,16 @@ fn retained_deep_svg_groups_lower_render_and_drop_on_a_bounded_worker() { let (preview, _) = svg::import_svg_preview_with_work("retained.svg", source.as_bytes(), u64::MAX).unwrap(); assert_eq!(preview.document.max_group_depth(), 100); assert!(pixel(&preview.document)[3] > 0.5); - let (w, h, pixels) = svg::rasterize_rgba8(source.as_bytes()).unwrap(); + // Whole-drawing rasterisation refuses more than 200 nested layers (#10953) with an + // error, not a crash; a drawing within that limit still renders on this small stack. + let refused = svg::rasterize_rgba8(source.as_bytes()).unwrap_err().to_string(); + assert!(refused.contains("layers are nested too deeply"), "{refused}"); + let within = format!( + "{}{}", + "".repeat(150), + "".repeat(150) + ); + let (w, h, pixels) = svg::rasterize_rgba8(within.as_bytes()).unwrap(); assert_eq!((w, h), (8, 8)); assert!(pixels[3] > 127); }) From 9d0363f189edf8ca8cdbdb73c0d782f763cb4924 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 11 Nov 2026 10:14:43 +0100 Subject: [PATCH 08/10] Fix main: Apply Data Set test after #10597 and #10203 #10203 gates image.applyDataSet on a document having data sets. #10597, merged later from an older base, expected the engine's index error for an empty list. The command now refuses earlier with the gate's message, so the test expects that. --- crates/ui-egui/tests/it/variables_data_sets.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-egui/tests/it/variables_data_sets.rs b/crates/ui-egui/tests/it/variables_data_sets.rs index 4e02322313..aef5630199 100644 --- a/crates/ui-egui/tests/it/variables_data_sets.rs +++ b/crates/ui-egui/tests/it/variables_data_sets.rs @@ -159,7 +159,7 @@ fn apply_menu_ok_requires_a_row_but_not_variable_definitions() { assert!(h.state().ui.dialogs.is_empty()); assert_eq!(h.state().session.active().unwrap().doc.variables.active, expected); if explicit { - assert!(h.state().ui.status.contains("no data set at index 0")); + assert!(h.state().ui.status.contains("no data sets in document")); } else { assert!(h.state().ui.status.is_empty(), "{}", h.state().ui.status); } From a572185694567dd69a5a752825aca736efe1cb84 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 11 Nov 2026 11:29:58 +0100 Subject: [PATCH 09/10] Fix main: gradient alert expectation and heading glyph bearings --- crates/ui-egui/src/canvas/tests.rs | 10 +++++----- crates/ui-egui/src/widgets/panel.rs | 10 +++++++++- crates/ui-egui/src/widgets/tests.rs | 28 ++++++++++++++++++++++++++++ 3 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 5e3dc5ae09..6506b65987 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -1921,11 +1921,11 @@ fn painting_a_group_is_refused_at_the_press_with_a_message() { app.ui.dialogs.clear(); app.ui.tool = tool; tool_event(&mut app, ToolEvent::Down { x: 10.0, y: 10.0, pressure: 1.0 }, egui::Modifiers::NONE); - // The Brush has its own measured alert, tested in `brush_refusal_alert_tests` (#11898). - let want = if tool == Tool::Brush { - "Could not use the brush tool because the pixels in a group cannot be edited without merging the group.".to_string() - } else { - format!("Could not use the {} because the target layer is a group.", tool.label()) + // Brush and Classic gradient use the measured alerts (#11898, #12017). + let want = match tool { + Tool::Brush => "Could not use the brush tool because the pixels in a group cannot be edited without merging the group.".to_string(), + Tool::Gradient => "Could not use the gradient tool because the pixels in a group cannot be edited without merging the group.".to_string(), + _ => format!("Could not use the {} because the target layer is a group.", tool.label()), }; assert_eq!(errors(&app), [want], "{tool:?}"); assert!(app.drag.is_none() && app.live_stroke.is_none(), "{tool:?} starts no stroke"); diff --git a/crates/ui-egui/src/widgets/panel.rs b/crates/ui-egui/src/widgets/panel.rs index 7833edc2bc..1d012a8423 100644 --- a/crates/ui-egui/src/widgets/panel.rs +++ b/crates/ui-egui/src/widgets/panel.rs @@ -125,7 +125,15 @@ pub fn pill_tab(ui: &mut Ui, label: &str, selected: bool) -> Response { /// Small caps section label. pub fn section_label(ui: &mut Ui, text: &str) { let t = Tokens::get(ui.ctx()); - ui.label(egui::RichText::new(tl!(text)).font(theme::medium(11.5)).color(t.text_faint)); + let text = tl!(text); + let font = theme::medium(11.5); + let galley = ui.painter().layout(text.to_owned(), font.clone(), t.text_faint, ui.available_width()); + // A glyph can start before its logical advance (the Urdu Stroke heading does). Reserve + // that bearing in the layout instead of clipping the glyph or relaxing dialog bounds. + let left = (galley.rect.left() - galley.mesh_bounds.left()).max(0.0).ceil() as i8; + egui::Frame::NONE.inner_margin(egui::Margin { left, ..Default::default() }).show(ui, |ui| { + ui.label(egui::RichText::new(text).font(font).color(t.text_faint)); + }); } /// Hairline separator. diff --git a/crates/ui-egui/src/widgets/tests.rs b/crates/ui-egui/src/widgets/tests.rs index a48873abce..6a02717e58 100644 --- a/crates/ui-egui/src/widgets/tests.rs +++ b/crates/ui-egui/src/widgets/tests.rs @@ -196,6 +196,34 @@ fn drawn_texts(out: &egui::FullOutput) -> Vec<(String, egui::Rect, bool)> { texts } +/// The Urdu Stroke heading has a negative left glyph bearing with the shipped fonts. Its ink +/// must stay inside the panel at every scale, even though its logical advance starts at zero. +#[test] +fn section_labels_keep_glyph_bearings_inside_the_panel() { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + for kind in crate::theme::ThemeKind::ALL { + crate::theme::apply(&ctx, kind); + for ppp in [1.0, 1.25, 2.0] { + ctx.set_pixels_per_point(ppp); + for label in ["Stroke", "\u{644}\u{6a9}\u{6cc}\u{631}", "Location"] { + let mut room = egui::Rect::NOTHING; + let mut out = ctx.run_ui(Default::default(), |ui| { + ui.set_max_width(440.0); + room = ui.max_rect(); + super::section_label(ui, label); + }); + out.textures_delta.clear(); + let texts = drawn_texts(&out); + assert_eq!(texts.len(), 1, "{kind:?} @{ppp}x: {label}"); + let (_, ink, _) = &texts[0]; + assert!(ink.left() >= room.left() - 0.01, "{kind:?} @{ppp}x: {label} ink {ink:?} in {room:?}"); + assert!(ink.right() <= room.right() + 0.01, "{kind:?} @{ppp}x: {label} ink {ink:?} in {room:?}"); + } + } + } +} + /// #9635: the shared dialog label column is as wide as its widest label, between the English /// width and a cap, and a label wider than the column elides inside it. #[test] From 12a38e5fd5ff85745e5c3979b60bc5365eaae468 Mon Sep 17 00:00:00 2001 From: FredApps Date: Wed, 11 Nov 2026 11:32:22 +0100 Subject: [PATCH 10/10] fix(ui): guard Image Processor document sources during transforms --- crates/ui-egui/src/app/commands.rs | 12 +++ .../ui-egui/src/tools/transform_tool/tests.rs | 90 +++++++++++++++++++ 2 files changed, 102 insertions(+) diff --git a/crates/ui-egui/src/app/commands.rs b/crates/ui-egui/src/app/commands.rs index cafda1362e..1aa81115d4 100644 --- a/crates/ui-egui/src/app/commands.rs +++ b/crates/ui-egui/src/app/commands.rs @@ -93,6 +93,18 @@ impl PhotocraftApp { if let Some(result) = smart_svg_ui::intercept(self, id, ¶ms) { return result; } + // Document exports read committed pixels, not the pending Free Transform preview. + // Check on execution (also dialog OK and automation), leaving Folder processing usable. + if id == "file.scripts.imageProcessor" + && self.ui.transform.is_some() + && match params.get("source").and_then(Value::as_str) { + Some("open") => true, + Some("current") => self.transform_preview.as_ref().is_none_or(|preview| self.session.active().is_some_and(|st| st.doc.id == preview.doc.id)), + _ => false, + } + { + return Err("Commit or cancel the transform first".into()); + } if let Some(r) = transform_tool::intercept(self, id) { return r; } diff --git a/crates/ui-egui/src/tools/transform_tool/tests.rs b/crates/ui-egui/src/tools/transform_tool/tests.rs index 3c40b1712f..544d00ee37 100644 --- a/crates/ui-egui/src/tools/transform_tool/tests.rs +++ b/crates/ui-egui/src/tools/transform_tool/tests.rs @@ -1132,6 +1132,96 @@ fn a_refused_commit_keeps_the_box_open() { assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "another tool ends it"); } +/// Image Processor must not silently export the pixels from before the visible transform. +/// Both direct commands and dialog OK preserve the box and write nothing until it is settled. +#[test] +fn image_processor_document_sources_wait_for_the_transform() { + for source in ["current", "open"] { + for through_dialog in [false, true] { + for apply in [false, true] { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let output = tempfile::tempdir().unwrap(); + begin(&mut app, &ctx).unwrap(); + let t = app.ui.transform.as_mut().unwrap(); + t.quad = t.quad.map(|[x, y]| [x + 6.0, y]); + let quad = t.quad; + let before = app.session.active().unwrap().doc.clone(); + let revision = app.session.active().unwrap().revision; + let history = app.session.active().unwrap().history.past_len(); + let params = json!({"source": source, "output": output.path(), "format": "png"}); + let result = if through_dialog { + let reply = crate::menus::invoke(&mut app, &ctx, "file.scripts.imageProcessor", json!({})).unwrap(); + let id = reply["dialog"].as_u64().unwrap(); + let fields = &mut app.ui.dialog_mut(id).unwrap().fields; + fields.insert("source".into(), json!(source)); + fields.insert("output".into(), json!(output.path())); + fields.insert("format".into(), json!("png")); + crate::dialogs::confirm(&mut app, id) + } else { + app.run("file.scripts.imageProcessor", params.clone()) + }; + assert_eq!(result.unwrap_err(), "Commit or cancel the transform first"); + assert_eq!(std::fs::read_dir(output.path()).unwrap().count(), 0); + assert_eq!(app.ui.transform.as_ref().unwrap().quad, quad); + let st = app.session.active().unwrap(); + assert!(Arc::ptr_eq(&st.doc, &before)); + assert_eq!((st.revision, st.history.past_len()), (revision, history)); + if apply { + commit(&mut app); + } else { + cancel(&mut app); + } + assert!(app.ui.transform.is_none()); + let result = app.run("file.scripts.imageProcessor", params).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + } + } + } +} + +/// Folder input, including the legacy omitted source, does not read the open transform. +#[test] +fn image_processor_folder_source_keeps_working_during_a_transform() { + for source in [None, Some("folder")] { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + let input = tempfile::tempdir().unwrap(); + let output = tempfile::tempdir().unwrap(); + app.run("file.saveACopy", json!({"path": input.path().join("source.png")})).unwrap(); + begin(&mut app, &ctx).unwrap(); + let before = app.session.active().unwrap().doc.clone(); + let mut params = json!({"input": input.path(), "output": output.path(), "format": "png"}); + if let Some(source) = source { + params["source"] = json!(source); + } + let result = app.run("file.scripts.imageProcessor", params).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); + assert!(app.ui.transform.is_some()); + assert!(Arc::ptr_eq(&app.session.active().unwrap().doc, &before)); + } +} + +/// All open documents includes a transform in another tab; Current only reads its own tab. +#[test] +fn image_processor_checks_the_transform_document_for_each_source() { + let ctx = egui::Context::default(); + let mut app = app_with_square(64, photocraft_geom::Rect::new(8, 8, 24, 24)); + app.run("file.new", json!({"name": "Other", "width": 16, "height": 16})).unwrap(); + assert!(app.session.set_active(0)); + begin(&mut app, &ctx).unwrap(); + assert!(app.session.set_active(1)); + let output = tempfile::tempdir().unwrap(); + let result = app.run("file.scripts.imageProcessor", json!({"source": "open", "output": output.path(), "format": "png"})); + assert_eq!(result.unwrap_err(), "Commit or cancel the transform first"); + assert_eq!(std::fs::read_dir(output.path()).unwrap().count(), 0); + let result = app.run("file.scripts.imageProcessor", json!({"source": "current", "output": output.path(), "format": "png"})).unwrap(); + assert_eq!(result["files"].as_array().unwrap().len(), 1, "{result}"); + assert!(result["errors"].as_array().unwrap().is_empty(), "{result}"); +} + /// #6737: Save for Web exports the committed document, so it is off while a box is pending. #[test] fn save_for_web_is_off_under_a_pending_transform() {