From a62036a919ee177db2c654d0c97f313d780fbdd0 Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 16:12:28 -0500 Subject: [PATCH 1/4] Layers to Files: an adjustment layer gets its own file, like an empty layer (#13966) export_layers_report_with no longer skips an adjustment layer. It is numbered in panel order and exported like an empty layer: a fully transparent full-canvas PNG with Trim on, a white full-canvas JPEG. A hidden one with visibleOnly is still skipped. Tests that pinned the old skip are updated. Co-Authored-By: Claude Sonnet 5.5 Model-Effort: Opus 5.5 drove; Opus 5.5 briefed; Sonnet 5.5 wrote at medium --- crates/automation/src/rpc/tests.rs | 15 ++-- crates/automation/tests/it/mcp.rs | 16 ++--- crates/engine/src/cmd/file_cmds.rs | 4 ++ crates/engine/src/cmd/file_cmds/export.rs | 8 +-- .../layers_to_files_adjustment_tests.rs | 69 +++++++++++++++++++ crates/engine/src/cmd/file_cmds/tests.rs | 18 ++--- docs/control-protocol.md | 2 +- 7 files changed, 97 insertions(+), 35 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 6598d5d9c0..698d627e0b 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -547,7 +547,7 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { let mut h = if trusted { Headless::trusted_local() } else { Headless::with_workspace(crate::AuthorizedWorkspace::new(Some(&base), Some(&base)).unwrap()) }; h.handle("doc.new", json!({"width": 4, "height": 4, "background": "white", "name": "card"})).unwrap(); - let adjustment = h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap()["layer"].clone(); + h.handle("engine.execute", json!({"command": "layer.newAdjustmentLayer.levels"})).unwrap(); h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"name": "Levels"}})).unwrap(); let hidden = h.handle("engine.execute", json!({"command": "layer.new.layer", "params": {"name": "Hidden"}})).unwrap()["layer"].clone(); h.handle("engine.execute", json!({"command": "layer.setProps", "params": {"visible": false}})).unwrap(); @@ -560,23 +560,22 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { let reply: Value = serde_json::from_slice(&output).unwrap(); assert_eq!(reply["id"], 8491); assert_eq!(reply["ok"], true, "{reply}"); - assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Background.png")])); + assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0000_Levels.png"), format!("{out_dir}/card_0001_Background.png")])); if !trusted { - assert_eq!(reply["result"]["count"], 1); + assert_eq!(reply["result"]["count"], 2); } assert_eq!( reply["result"]["skipped"], json!([ - {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels", "reason": "adjustment layer has no pixels of its own"} + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"} ]) ); - assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); + assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 2); let mut h = h.into_inner().unwrap(); let all_dir = base.join("all").to_string_lossy().into_owned(); let all = h.export_layers(None, &all_dir, &json!({"visibleOnly": false})).unwrap(); - assert_eq!(all["files"].as_array().unwrap().len(), 2); - assert_eq!(all["skipped"].as_array().unwrap().len(), 1); + assert_eq!(all["files"].as_array().unwrap().len(), 3); + assert_eq!(all["skipped"].as_array().unwrap().len(), 0); // Workspace no-overwrite errors still fail and remove only newly created files. if !trusted { let collision = base.join("collision"); diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index e901ee6a37..dae703f1bf 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -970,22 +970,22 @@ async fn doc_export_layers_reports_skipped_layers() { let hidden = json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Hidden"}})).await)["layer"].clone(); json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"visible": false}})).await); let result = json_of(&call(&client, "doc_export_layers", json!({"dir": "layers"})).await); - assert_eq!(result["count"], 1); - assert_eq!(result["files"], json!(["layers/card_0001_Background.png"])); + assert_eq!(result["count"], 2); + assert_eq!(result["files"], json!(["layers/card_0000_Levels_α.png", "layers/card_0001_Background.png"])); assert_eq!( result["skipped"], json!([ - {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"} ]) ); let all = json_of(&call(&client, "doc_export_layers", json!({"dir": "all", "visible_only": false})).await); - assert_eq!(all["count"], 2); - assert_eq!(all["skipped"].as_array().unwrap().len(), 1); - assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 1); - assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 2); + assert_eq!(all["count"], 3); + assert_eq!(all["skipped"].as_array().unwrap().len(), 0); + assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 2); + assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 3); // Every top-level layer is still accounted for when none can be exported. json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": background, "visible": false}})).await); + json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": adjustment, "visible": false}})).await); let none = json_of(&call(&client, "doc_export_layers", json!({"dir": "none"})).await); assert_eq!(none["files"], json!([])); assert_eq!(none["count"], 0); diff --git a/crates/engine/src/cmd/file_cmds.rs b/crates/engine/src/cmd/file_cmds.rs index 633b25ff11..e9f3aa6e17 100644 --- a/crates/engine/src/cmd/file_cmds.rs +++ b/crates/engine/src/cmd/file_cmds.rs @@ -440,6 +440,10 @@ mod tests; #[path = "file_cmds/export_clut_cube_header_tests.rs"] mod export_clut_cube_header_tests; +#[cfg(test)] +#[path = "file_cmds/layers_to_files_adjustment_tests.rs"] +mod layers_to_files_adjustment_tests; + #[cfg(test)] #[path = "file_cmds/place_job_tests.rs"] mod place_job_tests; diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 404930f917..307f90040e 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -58,8 +58,8 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut report = LayerExportReport::default(); - // Hidden layers never consumed a filename index; adjustments that pass the visibility - // filter did. Keep those filenames stable while reporting both kinds of omission. + // Hidden layers never consumed a filename index; every other layer does, an adjustment layer + // included: it has no pixels of its own, so it exports like an empty layer (#13966). let mut i = 0usize; for l in doc.layers.iter().rev() { if !l.visible && visible_only { @@ -68,10 +68,6 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } let index = i; i += 1; - if matches!(l.content, LayerContent::Adjustment(_)) { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); - continue; - } let mut one = (*doc).clone(); let mut only = l.clone(); only.visible = true; diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs new file mode 100644 index 0000000000..dbbb22a540 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs @@ -0,0 +1,69 @@ +//! Layers to Files writes a file for an adjustment layer, like an empty layer (#13966). + +use super::*; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-l2f-adjustment-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +/// A 100 x 80 document: `Background`, then `Empty`, then a Levels adjustment layer named `Levels 1`. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + s.execute("layer.setProps", json!({"name": "Levels 1"})).unwrap(); + s +} + +fn decode_file(dir: &str, name: &str) -> photocraft_codecs::Image { + photocraft_codecs::decode(&std::fs::read(std::path::Path::new(dir).join(name)).unwrap()).unwrap() +} + +#[test] +fn png_with_trim_writes_a_full_canvas_transparent_file_for_the_adjustment() { + let dir = tmp("png"); + let mut s = session(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "trim": true})).unwrap(); + assert_eq!(r["skipped"], json!([])); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect(); + assert_eq!(names, ["doc_0000_Levels 1.png", "doc_0001_Empty.png", "doc_0002_Background.png"]); + let img = decode_file(&dir, "doc_0000_Levels 1.png"); + assert_eq!((img.width(), img.height()), (100, 80)); + let rgba = img.to_rgba8(); + assert!(rgba.chunks(4).all(|p| p[3] == 0), "every pixel is fully transparent"); + let empty = decode_file(&dir, "doc_0001_Empty.png"); + assert_eq!((empty.width(), empty.height()), (100, 80)); +} + +#[test] +fn jpeg_writes_a_white_full_canvas_image_for_the_adjustment() { + let dir = tmp("jpeg"); + let mut s = session(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap(); + assert_eq!(r["skipped"], json!([])); + let img = decode_file(&dir, "doc_0000_Levels 1.jpg"); + assert_eq!((img.width(), img.height()), (100, 80)); + let rgba = img.to_rgba8(); + assert!(rgba.chunks(4).all(|p| p[..3].iter().all(|&c| c >= 253)), "white"); + let empty = decode_file(&dir, "doc_0001_Empty.jpg").to_rgba8(); + assert_eq!(rgba, empty, "the same as the empty layer"); +} + +#[test] +fn a_hidden_adjustment_is_skipped_by_visible_only() { + let dir = tmp("hidden"); + let mut s = session(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + s.execute("layer.setProps", json!({"visible": false})).unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "hidden by visibleOnly"}])); + assert_eq!(r["files"].as_array().unwrap().len(), 2); + let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap(); + assert_eq!(all["skipped"], json!([])); + assert_eq!(all["files"].as_array().unwrap().len(), 3); +} diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 9b3207a8ee..9291e3de25 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2620,7 +2620,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { for depth in [8, 16, 32] { let dir = tmp(&format!("skipped-layers-{depth}")); let mut s = session(4, 4, depth); - let adjustment = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].clone(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); s.execute("layer.setProps", json!({"name": "Levels/α"})).unwrap(); let hidden = s.execute("layer.new.layer", json!({"name": "Levels/α"})).unwrap()["layer"].clone(); s.execute("layer.setProps", json!({"visible": false})).unwrap(); @@ -2629,22 +2629,16 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { assert_eq!( result["skipped"], json!([ - {"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} + {"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"} ]) ); - assert_eq!(result["files"], json!([join(&dir, "doc_0001_Background.png")])); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + assert_eq!(result["files"], json!([join(&dir, "doc_0000_Levels_α.png"), join(&dir, "doc_0001_Background.png")])); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2); assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len()); assert!(!s.active().unwrap().doc.layer(LayerId(hidden.as_u64().unwrap())).unwrap().visible); let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap(); - assert_eq!( - all["skipped"], - json!([ - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} - ]) - ); - assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0002_Background.png")])); + assert_eq!(all["skipped"], json!([])); + assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0001_Levels_α.png"), join(&dir, "all_0002_Background.png")])); } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6db4685f2e..f3c92ab9bc 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -549,7 +549,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) | | `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean | | `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) | -| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | +| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"`. `visibleOnly:false` exports hidden layers. An adjustment layer is exported like an empty layer. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | | `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | From ded27776e72a435c0f9cfab19a048307382d9b0e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Fri, 13 Nov 2026 19:51:11 -0500 Subject: [PATCH 2/4] Layers to Files: other formats still skip an adjustment layer (#13966) Only PNG and JPEG were measured; the issue keeps today's behaviour for the other formats (PSD, TIFF, BMP, Targa, PDF), so the skip with "adjustment layer has no pixels of its own" stays for them, the layer keeping its number. New test other_formats_still_skip_the_adjustment_and_keep_its_number (PSD). docs/control-protocol.md says which formats skip it (CodeRabbit on #14041). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/file_cmds/export.rs | 9 +++++++-- .../layers_to_files_adjustment_tests.rs | 16 +++++++++++++++- docs/control-protocol.md | 2 +- 3 files changed, 23 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 307f90040e..bb90f268aa 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -58,8 +58,9 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let prefix = p.get("prefix").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| stem(&d.doc.name)); let doc = d.doc.clone(); let mut report = LayerExportReport::default(); - // Hidden layers never consumed a filename index; every other layer does, an adjustment layer - // included: it has no pixels of its own, so it exports like an empty layer (#13966). + // Hidden layers never consumed a filename index; every other layer does. An adjustment layer + // has no pixels of its own: for PNG and JPEG it exports like an empty layer, as measured + // (#13966); the other formats were not measured and still skip it, keeping its number. let mut i = 0usize; for l in doc.layers.iter().rev() { if !l.visible && visible_only { @@ -68,6 +69,10 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } let index = i; i += 1; + if matches!(l.content, LayerContent::Adjustment(_)) && !matches!(format.as_str(), "png" | "jpg" | "jpeg") { + report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); + continue; + } let mut one = (*doc).clone(); let mut only = l.clone(); only.visible = true; diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs index dbbb22a540..0289a2df56 100644 --- a/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs @@ -1,4 +1,5 @@ -//! Layers to Files writes a file for an adjustment layer, like an empty layer (#13966). +//! Layers to Files writes a file for an adjustment layer, like an empty layer, for PNG and JPEG +//! (#13966); the formats that were not measured still skip it. use super::*; @@ -67,3 +68,16 @@ fn a_hidden_adjustment_is_skipped_by_visible_only() { assert_eq!(all["skipped"], json!([])); assert_eq!(all["files"].as_array().unwrap().len(), 3); } + +#[test] +fn other_formats_still_skip_the_adjustment_and_keep_its_number() { + // Only PNG and JPEG were measured; PSD (like TIFF, BMP, Targa and PDF) keeps today's skip. + let dir = tmp("psd"); + let mut s = session(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "psd"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect(); + assert_eq!(names, ["doc_0001_Empty.psd", "doc_0002_Background.psd"]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 2c6b4a17fc..73250cdda6 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -549,7 +549,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) | | `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean | | `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) | -| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"`. `visibleOnly:false` exports hidden layers. An adjustment layer is exported like an empty layer. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | +| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported top-level layer, named like `file.export.layersToFiles` names them. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or, for formats other than PNG and JPEG, `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden layers. For PNG and JPEG an adjustment layer is exported like an empty layer. Groups export merged; their children are not separate exports or skips. Existing filenames/numbering are unchanged. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | | `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty | From df7ffd62449a3365e96531b7ce5bd9074b4df71e Mon Sep 17 00:00:00 2001 From: Trevor Brown Date: Sun, 15 Nov 2026 17:43:19 -0500 Subject: [PATCH 3/4] Layers to Files: an adjustment whose mask hides something keeps today's skip (#13966) Only an adjustment with the white mask every new one gets was measured. One whose layer mask hides something (painted, or made from a selection) or that has a vector mask is skipped in every format, as before this PR. Co-Authored-By: Claude Opus 5.5 Model-Effort: Opus 5.5 driver, no subagent --- crates/engine/src/cmd/file_cmds/export.rs | 9 ++++++- .../layers_to_files_adjustment_tests.rs | 26 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index b008525d52..9b41035157 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -72,7 +72,14 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); continue; } - if matches!(l.content, LayerContent::Adjustment(_)) && !matches!(format.as_str(), "png" | "jpg" | "jpeg") { + // Only an adjustment whose mask hides nothing was measured: the white mask every new one + // gets. One whose mask hides something (painted, or made from a selection) or that has a + // vector mask was not, so it keeps today's skip in every format. + let masked = l.vector_mask.is_some() + || l.mask + .as_ref() + .is_some_and(|m| m.enabled && (m.surface.default_pixel().first().is_some_and(|v| *v < 1.0) || !m.surface.content_bounds().is_empty())); + if matches!(l.content, LayerContent::Adjustment(_)) && (masked || !matches!(format.as_str(), "png" | "jpg" | "jpeg")) { report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); continue; } diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs index 0289a2df56..a78c2eb631 100644 --- a/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs @@ -81,3 +81,29 @@ fn other_formats_still_skip_the_adjustment_and_keep_its_number() { let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect(); assert_eq!(names, ["doc_0001_Empty.psd", "doc_0002_Background.psd"]); } + +#[test] +fn an_adjustment_whose_mask_hides_part_of_it_is_still_skipped() { + // Not measured: a mask that hides something (here made from a selection) keeps today's skip. + let dir = tmp("masked"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); + assert_eq!(r["files"].as_array().unwrap().len(), 1, "only the Background"); +} + +#[test] +fn an_adjustment_with_a_vector_mask_is_still_skipped() { + let dir = tmp("vector-masked"); + let mut s = Session::new(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + let path = json!({"subpaths": [{"closed": true, "knots": [[0, 0], [50, 0], [50, 80], [0, 80]]}]}); + s.execute("layer.newAdjustmentLayer.levels", json!({"path": path})).unwrap(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); +} From f55005ce12ad4116a4ec3bbb84f14574ca0597d2 Mon Sep 17 00:00:00 2001 From: Dan Date: Sun, 29 Nov 2026 12:34:29 +0000 Subject: [PATCH 4/4] Name the Transform Again history step (#17860) --- crates/engine-core/src/cmd/edit_cmds.rs | 3 +- crates/engine-core/src/cmd/transform_cmds.rs | 9 ++- crates/engine/tests/it/main.rs | 1 + .../it/transform_again_history_name_tests.rs | 80 +++++++++++++++++++ 4 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 crates/engine/tests/it/transform_again_history_name_tests.rs diff --git a/crates/engine-core/src/cmd/edit_cmds.rs b/crates/engine-core/src/cmd/edit_cmds.rs index 63278e0f8f..5849b59bfd 100644 --- a/crates/engine-core/src/cmd/edit_cmds.rs +++ b/crates/engine-core/src/cmd/edit_cmds.rs @@ -887,7 +887,8 @@ fn toggle_last_state(s: &mut Session) -> Result { /// Edit › Transform › Again: replay the last `edit.transform` on the selected layers (#6501). fn transform_again(s: &mut Session) -> Result { let ids = s.active().map(crate::transform_cmds::selection_targets).unwrap_or_default(); - let p = transform_again_params(s, &ids)?; + let mut p = transform_again_params(s, &ids)?; + p["stepName"] = json!(crate::transform_cmds::TRANSFORM_AGAIN); s.execute("edit.transform", p) } diff --git a/crates/engine-core/src/cmd/transform_cmds.rs b/crates/engine-core/src/cmd/transform_cmds.rs index 803c3ab8ef..9f1990ce71 100644 --- a/crates/engine-core/src/cmd/transform_cmds.rs +++ b/crates/engine-core/src/cmd/transform_cmds.rs @@ -19,6 +19,7 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> { /// The History step name of a shape-tool bounding box scale (`edit.transform` `stepName`). pub const TRANSFORM_PATH: &str = "Transform Path"; +pub(crate) const TRANSFORM_AGAIN: &str = "Transform Again"; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() } @@ -858,12 +859,12 @@ fn with_panel_target(s: &Session, p: &Value) -> Value { } fn transform(s: &mut Session, p: &Value) -> Result { - // The shape tools' bounding box scales live shapes with this command and names the step as - // the reference does. Passed in, not renamed after: the edit may land later as a job. + // Pass the history label to the edit job so it is used when the transform lands. let step_name = match p.get("stepName") { None | Some(Value::Null) => "Free Transform", Some(Value::String(n)) if n == TRANSFORM_PATH => TRANSFORM_PATH, - Some(_) => return Err(bad("`stepName` must be \"Transform Path\"")), + Some(Value::String(n)) if n == TRANSFORM_AGAIN => TRANSFORM_AGAIN, + Some(_) => return Err(bad("`stepName` must be \"Transform Path\" or \"Transform Again\"")), }; let p = &with_panel_target(s, p); let st = s.active().ok_or(EngineError::NoDocument)?; @@ -1037,7 +1038,7 @@ pub fn specs() -> Vec { label: "Free Transform", menu: &[], shortcut: None, - params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path"? (History step name; the shape tools' bounding box sends it; default "Free Transform"; any other value is refused),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, + params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path|Transform Again"? (History step name; default "Free Transform"),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, enabled: has_layer, journal: true, run: transform, diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index e0a43b071c..75b7e9dd06 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -193,6 +193,7 @@ mod smart_rerender_fallback; mod style_and_align; mod svg_smart_object; mod tone_target_picker; +mod transform_again_history_name_tests; mod transform_budget_unclamped; mod type_format_targets; mod type_postscript_font; diff --git a/crates/engine/tests/it/transform_again_history_name_tests.rs b/crates/engine/tests/it/transform_again_history_name_tests.rs new file mode 100644 index 0000000000..1a12667cfd --- /dev/null +++ b/crates/engine/tests/it/transform_again_history_name_tests.rs @@ -0,0 +1,80 @@ +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use serde_json::json; + +fn skewed_document(layer_count: usize) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1000, "height": 700})).unwrap(); + let mut layers = Vec::new(); + for (name, rect, color) in + [("A", Rect::new(100, 100, 300, 300), [1.0, 0.0, 0.0, 1.0]), ("B", Rect::new(500, 300, 800, 500), [0.0, 0.0, 1.0, 1.0])].into_iter().take(layer_count) + { + let made = s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + s.edit("Paint rectangle", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(rect, &color); + Ok(()) + }) + .unwrap(); + layers.push(id); + } + s.execute("layer.select", json!({"layer": layers[0].0})).unwrap(); + for id in &layers[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); + } + s.execute("edit.transform", json!({"rect": [100, 100, 800, 500], "quad": [[200, 100], [900, 100], [800, 500], [100, 500]], "interpolation": "nearest"})) + .unwrap(); + (s, layers) +} + +fn bounds(s: &Session, layers: &[LayerId]) -> Vec { + let doc = &s.active().unwrap().doc; + layers.iter().map(|id| doc.layer(*id).unwrap().surface().unwrap().content_bounds()).collect() +} + +#[test] +fn transform_again_adds_one_named_undo_step_for_single_and_multiple_layers() { + for layer_count in [1, 2] { + let (mut s, layers) = skewed_document(layer_count); + let state = s.active().unwrap(); + let before = state.doc.clone(); + let previous_steps = state.history.past_len(); + assert_eq!(state.history.undo_label(), Some("Free Transform")); + + s.execute("edit.transform.again", json!({})).unwrap(); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), previous_steps + 1); + assert_eq!(state.history.undo_label(), Some("Transform Again")); + assert_eq!(bounds(&s, &layers), [Rect::new(200, 100, 500, 300), Rect::new(500, 300, 900, 500)][..layer_count]); + + assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true)); + let state = s.active().unwrap(); + assert_eq!(state.doc, before); + assert_eq!(state.history.past_len(), previous_steps); + assert_eq!(state.history.redo_label(), Some("Transform Again")); + } +} + +#[test] +fn recorded_transform_again_plays_the_concrete_transform_once() { + let (mut s, layers) = skewed_document(2); + s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap(); + s.execute("actions.record", json!({"name": "Repeat skew"})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let repeated_bounds = bounds(&s, &layers); + let recorded = s.execute("actions.get", json!({"action": "Repeat skew"})).unwrap(); + let [step] = recorded["steps"].as_array().unwrap().as_slice() else { panic!("expected a single recorded step: {recorded}") }; + assert_eq!(step[0], "edit.transform"); + + assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true)); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Repeat skew"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(bounds(&s, &layers), repeated_bounds); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), before + 1); + assert_eq!(state.history.undo_label(), Some("Transform Again")); +}