From 5fc50313ee98bbd3e1ebe50ffec5fa10e2e8c40d Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 10:30:42 -0600 Subject: [PATCH 1/3] Layers to Files: one file per layer inside a group, none for the group (#13957) Groups are walked: each layer in a group gets _s_ _, repeated per level, art layers and groups counted separately at each level. A group gets no file; a layer's file keeps it inside its groups. With visibleOnly, a hidden group's layers are skipped and reported; without it they are exported. Nesting is bounded. --- crates/engine/src/cmd/file_cmds/export.rs | 108 +++++++++++-- .../file_cmds/layers_to_files_groups_tests.rs | 142 ++++++++++++++++++ crates/engine/src/cmd/file_cmds/tests.rs | 7 +- docs/control-protocol.md | 2 +- 4 files changed, 240 insertions(+), 19 deletions(-) create mode 100644 crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index 947513c920..f776dbfc58 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -42,9 +42,14 @@ pub struct LayerExportReport { pub skipped: Vec, } -/// The same export as [`export_layers_with`], with an explanation for every omitted top-level -/// layer. Groups export merged, so their children are not separate exports or skips. Encoding -/// and write failures remain errors, never successful skips. Existing numbering is preserved. +/// The same export as [`export_layers_with`], with an explanation for every omitted layer. +/// Groups are walked, as the reference walks them (#13957): a group gets no file, every layer in +/// it does, named `_s__` (one `s_` per level, +/// so two groups deep is `_0000s_0000s_0000_`). Art layers and groups are counted +/// separately at each level, top to bottom; a skipped layer keeps its number (#13959). With +/// `visibleOnly`, the layers of a hidden group are skipped; without it they are exported. A +/// layer's file keeps it inside its groups. Encoding and write failures remain errors, never +/// successful skips. pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(&str, &[u8]) -> Result<()>) -> Result { let cmd = "file.export.layersToFiles"; let format = p.get("format").and_then(Value::as_str).unwrap_or("png").trim_start_matches('.').to_ascii_lowercase(); @@ -62,21 +67,23 @@ 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(); - // Every layer takes its panel-order index, even one skipped as hidden or as an adjustment, - // so a file keeps the same number whether Visible Layers Only is on or off (#13959). - for (index, l) in doc.layers.iter().rev().enumerate() { - if !l.visible && visible_only { - report.skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); - continue; - } - 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 planned = Vec::new(); + plan_layer_exports(&doc.layers, &mut Vec::new(), "", visible_only, &mut planned, &mut report.skipped)?; + for PlannedLayer { l, groups, number } in planned { let mut one = (*doc).clone(); let mut only = l.clone(); only.visible = true; only.clipped = false; + // The layer stays inside its groups (each shown, holding only the next one in). + for group in groups.iter().rev() { + let mut g = (*group).clone(); + g.visible = true; + g.clipped = false; + if let Some(children) = g.children_mut() { + *children = vec![only]; + } + only = g; + } one.layers = vec![only]; if trim { let mut bounds = Rect::EMPTY; @@ -97,7 +104,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } // The prefix is optional; only the layer name needs the empty-name fallback. - let name = format!("{}_{:04}_{}.{format}", if prefix.is_empty() { String::new() } else { sanitize(&prefix) }, index, sanitize(&l.name)); + let name = format!("{}_{number}_{}.{format}", if prefix.is_empty() { String::new() } else { sanitize(&prefix) }, sanitize(&l.name)); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); @@ -105,6 +112,73 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& Ok(report) } +/// How deep [`plan_layer_exports`] follows groups before refusing the document. +const MAX_GROUP_DEPTH: usize = 128; + +/// One layer Layers to Files writes: the layer, its groups (outermost first) and its number +/// (`0000s_0001` for the second art layer of the first group). +struct PlannedLayer<'a> { + l: &'a Layer, + groups: Vec<&'a Layer>, + number: String, +} + +/// The layers of `layers` (one level, bottom first as stored) to write, top to bottom, with +/// their groups walked; skips go to `skipped`. `path` is the group part of the number so far. +fn plan_layer_exports<'a>( + layers: &'a [Layer], + groups: &mut Vec<&'a Layer>, + path: &str, + visible_only: bool, + planned: &mut Vec>, + skipped: &mut Vec, +) -> Result<()> { + if groups.len() > MAX_GROUP_DEPTH { + return Err(EngineError::Other(format!("Layers to Files: groups nested more than {MAX_GROUP_DEPTH} deep"))); + } + let (mut art, mut group) = (0usize, 0usize); + for l in layers.iter().rev() { + if let Some(children) = l.children() { + let number = group; + group += 1; + if !l.visible && visible_only { + skip_hidden_group(children, skipped); + continue; + } + groups.push(l); + let r = plan_layer_exports(children, groups, &format!("{path}{number:04}s_"), visible_only, planned, skipped); + groups.pop(); + r?; + continue; + } + // Every layer takes its index, even one skipped as hidden or as an adjustment, so a file + // keeps the same number whether Visible Layers Only is on or off (#13959). + let number = format!("{path}{art:04}"); + art += 1; + if !l.visible && visible_only { + skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); + continue; + } + if matches!(l.content, LayerContent::Adjustment(_)) { + skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); + continue; + } + planned.push(PlannedLayer { l, groups: groups.clone(), number }); + } + Ok(()) +} + +/// Every layer under a group hidden while Visible Layers Only is on, top to bottom, as skipped. +fn skip_hidden_group(layers: &[Layer], skipped: &mut Vec) { + let mut stack: Vec<&Layer> = layers.iter().collect(); + while let Some(l) = stack.pop() { + match l.children() { + Some(children) => stack.extend(children.iter()), + None => skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }), + } + } +} + /// Adjustment layers that can be represented as an RGB-only LUT, in document stack order. /// A LUT has no spatial coordinates, so masks and clipping geometry are deliberately stripped /// at bake time. Group adjustments need their enclosing group's compositing semantics and are @@ -268,3 +342,7 @@ pub(super) fn push_unique(v: &mut Vec, x: f64) { #[cfg(test)] #[path = "layers_to_files_prefix_tests.rs"] mod layers_to_files_prefix_tests; + +#[cfg(test)] +#[path = "layers_to_files_groups_tests.rs"] +mod layers_to_files_groups_tests; diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs new file mode 100644 index 0000000000..ef2daf2971 --- /dev/null +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs @@ -0,0 +1,142 @@ +//! #13957: Layers to Files walks groups: every layer in a group gets a file named +//! `_s__`, a group gets none, and art layers and groups +//! are counted separately at each level. + +use super::*; +use photocraft_doc::TextLayer; + +/// The issue's `l2f-test`, top to bottom: `Type` (text), group `Grp` holding `Inner`, `Hidden` +/// (hidden), `Blue Half`, `Red`, `Background`. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 15, "name": "l2f-test"})).unwrap(); + for name in ["Red", "Blue Half", "Hidden", "Inner"] { + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + if name == "Hidden" { + s.execute("layer.setProps", json!({"visible": false})).unwrap(); + } + } + s.edit("groups", |doc, _| { + let inner = doc.layers.pop().unwrap(); + doc.layers.push(Layer::group("Grp", vec![inner])); + doc.layers.push(Layer::new("Type", LayerContent::Text(TextLayer { text: "T".into(), ..Default::default() }))); + Ok(()) + }) + .unwrap(); + s +} + +/// Runs the export with `params` and returns the report and each file's bytes by name. +fn export(s: &Session, params: Value) -> (LayerExportReport, Vec<(String, Vec)>) { + let mut written = Vec::new(); + let report = export_layers_report_with(s, ¶ms, |name, bytes| { + written.push((name.to_string(), bytes.to_vec())); + Ok(()) + }) + .unwrap(); + (report, written) +} + +fn skipped(report: &LayerExportReport) -> Vec<&str> { + report.skipped.iter().map(|l| l.name.as_str()).collect() +} + +#[test] +fn layers_in_a_group_get_a_file_each_and_the_group_none() { + let (report, written) = export(&session(), json!({"format": "psd", "visibleOnly": false})); + let expected = [ + "l2f-test_0000_Type.psd", + "l2f-test_0000s_0000_Inner.psd", + "l2f-test_0001_Hidden.psd", + "l2f-test_0002_Blue Half.psd", + "l2f-test_0003_Red.psd", + "l2f-test_0004_Background.psd", + ]; + assert_eq!(report.files, expected); + assert_eq!(written.iter().map(|(n, _)| n.as_str()).collect::>(), expected); + assert!(report.skipped.is_empty()); + // Inner's PSD keeps it inside Grp (Pass Through), with nothing else in the file. + let (_, inner) = &written[1]; + let doc = photocraft_io::import("x.psd", inner).unwrap().document; + assert_eq!(doc.layers.len(), 1, "{:?}", doc.layers.iter().map(|l| &l.name).collect::>()); + let grp = &doc.layers[0]; + assert_eq!(grp.name, "Grp"); + assert_eq!(grp.blend, photocraft_doc::BlendMode::PassThrough); + let children: Vec<&str> = grp.children().unwrap().iter().map(|l| l.name.as_str()).collect(); + assert_eq!(children, ["Inner"]); +} + +#[test] +fn nested_groups_repeat_the_pattern_and_count_per_level() { + let mut s = session(); + // Inside Grp, above Inner: `Deep` holding `Leaf`, then a second top-level group `Second` + // holding `Other`, above Type. + s.edit("nest", |doc, _| { + let leaf = Layer::new("Leaf", LayerContent::Text(TextLayer { text: "L".into(), ..Default::default() })); + let other = Layer::new("Other", LayerContent::Text(TextLayer { text: "O".into(), ..Default::default() })); + let grp = doc.layers.iter_mut().find(|l| l.name == "Grp").unwrap(); + grp.children_mut().unwrap().push(Layer::group("Deep", vec![leaf])); + doc.layers.push(Layer::group("Second", vec![other])); + Ok(()) + }) + .unwrap(); + let (report, _) = export(&s, json!({"visibleOnly": false})); + assert_eq!( + report.files, + [ + "l2f-test_0000s_0000_Other.png", + "l2f-test_0000_Type.png", + "l2f-test_0001s_0000s_0000_Leaf.png", + "l2f-test_0001s_0000_Inner.png", + "l2f-test_0001_Hidden.png", + "l2f-test_0002_Blue Half.png", + "l2f-test_0003_Red.png", + "l2f-test_0004_Background.png", + ] + ); +} + +#[test] +fn a_hidden_groups_layers_follow_visible_layers_only() { + let mut s = session(); + s.edit("hide Grp", |doc, _| { + doc.layers.iter_mut().find(|l| l.name == "Grp").unwrap().visible = false; + Ok(()) + }) + .unwrap(); + let (report, written) = export(&s, json!({"visibleOnly": false})); + assert!(report.files.contains(&"l2f-test_0000s_0000_Inner.png".to_string()), "{:?}", report.files); + // Its file shows Inner although Grp is hidden in the document. + let (_, inner) = written.iter().find(|(n, _)| n.contains("Inner")).unwrap(); + let doc = photocraft_io::import("x.png", inner).unwrap().document; + assert_eq!((doc.size.width, doc.size.height), (20, 15)); + let (report, _) = export(&s, json!({"visibleOnly": true})); + assert_eq!(report.files, ["l2f-test_0000_Type.png", "l2f-test_0002_Blue Half.png", "l2f-test_0003_Red.png", "l2f-test_0004_Background.png"]); + assert_eq!(skipped(&report), ["Inner", "Hidden"]); +} + +#[test] +fn empty_and_deep_groups_never_panic() { + let mut s = session(); + s.edit("empty and deep", |doc, _| { + doc.layers.push(Layer::group("Empty", Vec::new())); + let mut deep = Layer::new("Bottom", LayerContent::Text(TextLayer { text: "B".into(), ..Default::default() })); + for i in 0..200 { + deep = Layer::group(format!("G{i}"), vec![deep]); + } + doc.layers.push(deep); + Ok(()) + }) + .unwrap(); + let e = export_layers_report_with(&s, &json!({"visibleOnly": false}), |_, _| Ok(())).unwrap_err(); + assert!(e.to_string().contains("nested more than"), "{e}"); + let mut s = session(); + s.edit("empty", |doc, _| { + doc.layers.push(Layer::group("Empty", Vec::new())); + Ok(()) + }) + .unwrap(); + let (report, _) = export(&s, json!({"visibleOnly": false})); + // The empty group still takes group number 0000, so Grp is 0001s. + assert_eq!(report.files[1], "l2f-test_0001s_0000_Inner.png"); +} diff --git a/crates/engine/src/cmd/file_cmds/tests.rs b/crates/engine/src/cmd/file_cmds/tests.rs index 6f58ca1dad..a0da907d8c 100644 --- a/crates/engine/src/cmd/file_cmds/tests.rs +++ b/crates/engine/src/cmd/file_cmds/tests.rs @@ -2721,7 +2721,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { } #[test] -fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { +fn layers_to_files_walks_groups_and_reports_failures_as_errors() { let mut s = session(4, 4, 8); s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); s.execute("layer.new.groupFromLayers", json!({"name": "Pack"})).unwrap(); @@ -2733,9 +2733,10 @@ fn layers_to_files_reports_groups_as_exports_and_failures_as_errors() { Ok(()) }) .unwrap(); - assert_eq!(names, vec!["doc_0000_Pack.png", "doc_0001_Background.png"]); + // Groups are walked (#13957): Pack gets no file, and its adjustment layer is skipped. + assert_eq!(names, vec!["doc_0000_Background.png"]); assert_eq!(report.files, names); - assert!(report.skipped.is_empty(), "a group's adjustment is not an omitted top-level layer"); + assert_eq!(report.skipped.iter().map(|l| l.reason).collect::>(), ["adjustment layer has no pixels of its own"]); assert_eq!(export_layers_with(&s, ¶ms, |_, _| Ok(())).unwrap(), names, "legacy Rust helper remains compatible"); assert!(export_layers_report_with(&s, ¶ms, |_, _| Err(EngineError::Other("disk full".into()))).unwrap_err().to_string().contains("disk full")); assert!(export_layers_report_with(&s, &json!({"format": "not-a-format"}), |_, _| panic!("must not write")).is_err()); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 1b5da09e98..9892acfad9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -551,7 +551,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 layer, named like `file.export.layersToFiles` names them: `__` at the top level and `_s__` inside a group (one `s_` per group level), art layers and groups counted separately at each level. `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 are walked: a group gets no file, each layer in it does (inside its groups in the file), and with `visibleOnly` the layers of a hidden group are skipped as `"hidden by visibleOnly"`. `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 fa9987a445713b7abc66cdae48847e206fcc2600 Mon Sep 17 00:00:00 2001 From: Hector Villarreal Date: Sun, 15 Nov 2026 22:00:52 -0600 Subject: [PATCH 2/3] Layers to Files: a file name longer than 255 bytes is refused before anything is written (CodeRabbit review on #15201) --- crates/engine/src/cmd/file_cmds/export.rs | 21 ++++++++++-- .../file_cmds/layers_to_files_groups_tests.rs | 33 +++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/file_cmds/export.rs b/crates/engine/src/cmd/file_cmds/export.rs index f776dbfc58..c137f96284 100644 --- a/crates/engine/src/cmd/file_cmds/export.rs +++ b/crates/engine/src/cmd/file_cmds/export.rs @@ -69,6 +69,21 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& let mut report = LayerExportReport::default(); let mut planned = Vec::new(); plan_layer_exports(&doc.layers, &mut Vec::new(), "", visible_only, &mut planned, &mut report.skipped)?; + // The prefix is optional; only the layer name needs the empty-name fallback. + let file_name = + |l: &Layer, number: &str| format!("{}_{number}_{}.{format}", if prefix.is_empty() { String::new() } else { sanitize(&prefix) }, sanitize(&l.name)); + // Every name is known before anything is encoded: one that no file system takes (each group level adds + // 6 bytes, so about 41 nested groups pass 255) fails the export before the first file is written. + for PlannedLayer { l, number, .. } in &planned { + let name = file_name(l, number); + if name.len() > MAX_FILE_NAME_BYTES { + return Err(EngineError::Other(format!( + "Layers to Files: the file name for layer \"{}\" is {} bytes, more than the {MAX_FILE_NAME_BYTES} a file name can hold; shorten the layer or prefix name or nest it in fewer groups", + l.name, + name.len() + ))); + } + } for PlannedLayer { l, groups, number } in planned { let mut one = (*doc).clone(); let mut only = l.clone(); @@ -103,8 +118,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } } - // The prefix is optional; only the layer name needs the empty-name fallback. - let name = format!("{}_{number}_{}.{format}", if prefix.is_empty() { String::new() } else { sanitize(&prefix) }, sanitize(&l.name)); + let name = file_name(l, &number); let (bytes, _warnings) = encode(&one, &name, save)?; write(&name, &bytes)?; report.files.push(name); @@ -115,6 +129,9 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& /// How deep [`plan_layer_exports`] follows groups before refusing the document. const MAX_GROUP_DEPTH: usize = 128; +/// The longest file name, in bytes, that common file systems (ext4, APFS, NTFS) take. +const MAX_FILE_NAME_BYTES: usize = 255; + /// One layer Layers to Files writes: the layer, its groups (outermost first) and its number /// (`0000s_0001` for the second art layer of the first group). struct PlannedLayer<'a> { diff --git a/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs b/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs index ef2daf2971..e72f47ff43 100644 --- a/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs +++ b/crates/engine/src/cmd/file_cmds/layers_to_files_groups_tests.rs @@ -140,3 +140,36 @@ fn empty_and_deep_groups_never_panic() { // The empty group still takes group number 0000, so Grp is 0001s. assert_eq!(report.files[1], "l2f-test_0001s_0000_Inner.png"); } + +/// CodeRabbit on #15201: a layer inside 42 groups gets a 264 byte file name (6 bytes per group level), +/// which common file systems refuse. The export fails with a clear error before any file is written; +/// 40 groups (252 bytes) still export. +#[test] +fn a_file_name_longer_than_255_bytes_is_refused_before_anything_is_written() { + let nested = |groups: usize| { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 4, "height": 4})).unwrap(); + s.edit("nested", |doc, _| { + doc.layers.clear(); + let mut deep = Layer::new("L", LayerContent::Text(TextLayer { text: "L".into(), ..Default::default() })); + for i in 0..groups { + deep = Layer::group(format!("G{i}"), vec![deep]); + } + doc.layers.push(Layer::new("Top", LayerContent::Text(TextLayer { text: "T".into(), ..Default::default() }))); + doc.layers.push(deep); + Ok(()) + }) + .unwrap(); + s + }; + let mut written = Vec::new(); + let e = export_layers_report_with(&nested(42), &json!({"prefix": "d", "visibleOnly": false}), |name, _| { + written.push(name.to_string()); + Ok(()) + }) + .unwrap_err(); + assert!(e.to_string().contains("264 bytes") && e.to_string().contains("255"), "{e}"); + assert!(written.is_empty(), "nothing written before the refusal: {written:?}"); + let (report, _) = export(&nested(40), json!({"prefix": "d", "visibleOnly": false})); + assert_eq!(report.files.iter().map(String::len).max(), Some(252), "40 groups: 252 bytes, accepted"); +} From 008aee718ee8b4a42c53c029fdb00dd56f7d4505 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 29 Nov 2026 00:52:59 +0100 Subject: [PATCH 3/3] Layers to Files groups test: the hidden group's Inner file shows Inner's pixels Inner is painted red over the canvas, and the visibleOnly:false export of a hidden Grp must decode to red pixels, not only the right size (CodeRabbit review on #15201). Co-Authored-By: Claude Opus 5.5 --- .../cmd/file_cmds/layers_to_files_groups_tests.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_groups_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_groups_tests.rs index 6eb30400d4..23c7b3f751 100644 --- a/crates/engine-core/src/cmd/file_cmds/layers_to_files_groups_tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_groups_tests.rs @@ -5,8 +5,11 @@ use super::*; use photocraft_doc::TextLayer; -/// The issue's `l2f-test`, top to bottom: `Type` (text), group `Grp` holding `Inner`, `Hidden` -/// (hidden), `Blue Half`, `Red`, `Background`. +/// The issue's `l2f-test`, top to bottom: `Type` (text), group `Grp` holding `Inner` (red over +/// the whole canvas), `Hidden` (hidden), `Blue Half`, `Red`, `Background`. +/// The colour `Inner` is painted with. +const INNER_RGBA: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; + fn session() -> Session { let mut s = crate::session(); s.execute("file.new", json!({"width": 20, "height": 15, "name": "l2f-test"})).unwrap(); @@ -17,7 +20,11 @@ fn session() -> Session { } } s.edit("groups", |doc, _| { - let inner = doc.layers.pop().unwrap(); + let mut inner = doc.layers.pop().unwrap(); + let LayerContent::Raster(surface) = &mut inner.content else { panic!("Inner is a pixel layer") }; + let mut px = [0.0f32; 8]; + let k = photocraft_raster::from_rgba_into(&surface.format(), INNER_RGBA, &mut px); + surface.write_region(Rect::new(0, 0, 20, 15), &px[..k].repeat(20 * 15)); doc.layers.push(Layer::group("Grp", vec![inner])); doc.layers.push(Layer::new("Type", LayerContent::Text(TextLayer { text: "T".into(), ..Default::default() }))); Ok(()) @@ -110,6 +117,8 @@ fn a_hidden_groups_layers_follow_visible_layers_only() { let (_, inner) = written.iter().find(|(n, _)| n.contains("Inner")).unwrap(); let doc = photocraft_io::import("x.png", inner).unwrap().document; assert_eq!((doc.size.width, doc.size.height), (20, 15)); + let red = |p: &[f32; 4]| p.iter().zip(INNER_RGBA).all(|(a, b)| (a - b).abs() < 0.01); + assert!(photocraft_compose::flatten(&doc).px.iter().any(red), "the Inner file shows Inner's red pixels"); let (report, _) = export(&s, json!({"visibleOnly": true})); assert_eq!(report.files, ["l2f-test_0000_Type.png", "l2f-test_0002_Blue-Half.png", "l2f-test_0003_Red.png", "l2f-test_0004_Background.png"]); assert_eq!(skipped(&report), ["Inner", "Hidden"]);