Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Bound layer-group nesting at import and Group Layers (stack-overflow guard) (#796)

Elvis33LE57452bfd2224
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 5d038b1c4..9d11abb67 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -163,6 +163,14 @@ pub struct Effects {
pub reference: Option<(f64, f64)>,
}
+/// Deepest group nesting a document may hold: a layer inside this many nested groups is the
+/// deepest legal one. Everything that walks the layer tree (engine lookups, the layers panel,
+/// PSD export, `.pcraft` save and load) recurses once per level, so deeper trees risk
+/// overflowing the 1 MiB main-thread stacks of Windows and wasm. PSD import and the engine
+/// commands that nest layers (`layer.groupLayers`, `layer.moveTo`, Artboard from Layers) enforce
+/// this up front; `photocraft-format` refuses to save deeper trees.
+pub const MAX_GROUP_DEPTH: usize = 100;
+
#[derive(Clone, Debug, PartialEq)]
pub struct Group {
pub children: Vec<Layer>,
@@ -743,6 +751,27 @@ impl Document {
Rect::from_size(self.size)
}
+ /// Nesting depth of the deepest layer: 0 for a root-level layer, 1 inside one group, and so
+ /// on. Computed over an explicit stack, so it cannot overflow on any tree it measures.
+ pub fn max_group_depth(&self) -> usize {
+ let mut max = 0;
+ let mut stack: Vec<(&[Layer], usize)> = vec![(&self.layers, 0)];
+ while let Some((layers, depth)) = stack.pop() {
+ if layers.is_empty() {
+ continue;
+ }
+ max = max.max(depth);
+ for l in layers {
+ if let Some(ch) = l.children()
+ && !ch.is_empty()
+ {
+ stack.push((ch, depth + 1));
+ }
+ }
+ }
+ max
+ }
+
/// Depth-first walk yielding `(path, depth, layer)` bottom-to-top.
pub fn walk(&self) -> Vec<(LayerPath, usize, &Layer)> {
fn rec<'a>(layers: &'a [Layer], prefix: &mut LayerPath, out: &mut Vec<(LayerPath, usize, &'a Layer)>) {
@@ -869,6 +898,21 @@ mod tests {
assert_eq!(s.pixel(100, 0), vec![0.0; 4]);
}
+ #[test]
+ fn max_group_depth_counts_nesting_without_recursing() {
+ let mut d = doc();
+ let bg = d.layers[0].id;
+ let mut chain = Layer::raster("L", d.pixel_format());
+ for _ in 0..3 {
+ chain = Layer::group("G", vec![chain]);
+ }
+ d.insert_above(Some(bg), chain);
+ assert_eq!(d.max_group_depth(), 3);
+ // An unfilled group does not add a level (nothing lives inside it).
+ d.insert_above(Some(bg), Layer::group("empty", vec![]));
+ assert_eq!(d.max_group_depth(), 3);
+ }
+
#[test]
fn pixel_format_follows_mode_and_depth() {
let d = Document::new("c", Size::new(1, 1), ColorMode::Cmyk, SampleType::U16);
diff --git a/crates/engine/src/artboard_cmds.rs b/crates/engine/src/artboard_cmds.rs
index 16368d81c..93a1ad5bf 100644
--- a/crates/engine/src/artboard_cmds.rs
+++ b/crates/engine/src/artboard_cmds.rs
@@ -226,6 +226,7 @@ fn artboard_from_layers(s: &mut Session, p: &Value) -> Result<Value> {
let mut g = Layer::group(name.unwrap_or_else(|| next_artboard_name(doc)), children);
set_artboard(&mut g, Artboard { rect, background, preset: String::new() });
let gid = doc.insert_above(None, g);
+ crate::layer_multi_cmds::check_group_depth(doc, "Artboard from Layers")?;
fit_canvas(doc);
*active = Some(gid);
Ok((gid, rect))
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 2b8377510..0f64de72d 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -702,6 +702,8 @@ fn build() -> Vec<CommandSpec> {
sib.insert(at.min(sib.len()), layer);
}
}
+ // Moving a group into (or beside) a deeply nested layer can pass the nesting cap.
+ crate::layer_multi_cmds::check_group_depth(doc, "Reorder Layer")?;
*active = Some(id);
Ok(())
})?;
diff --git a/crates/engine/src/layer_multi_cmds.rs b/crates/engine/src/layer_multi_cmds.rs
index 0d8a0c748..4302df500 100644
--- a/crates/engine/src/layer_multi_cmds.rs
+++ b/crates/engine/src/layer_multi_cmds.rs
@@ -612,6 +612,16 @@ fn reverse(s: &mut Session) -> Result<Value> {
Ok(Value::Null)
}
+/// Refuses an edit that left `doc` nested deeper than [`photocraft_doc::MAX_GROUP_DEPTH`]
+/// groups. Called at the end of a `Session::edit` closure, so an `Err` leaves the document and
+/// history untouched.
+pub(crate) fn check_group_depth(doc: &Document, what: &str) -> Result<()> {
+ if doc.max_group_depth() > photocraft_doc::MAX_GROUP_DEPTH {
+ return Err(EngineError::Other(format!("{what} would nest layers deeper than {} groups", photocraft_doc::MAX_GROUP_DEPTH)));
+ }
+ Ok(())
+}
+
/// Group Layers (⌘G) / Group from Layers: the explicit layer, or every selected layer, moves
/// into a new group placed where the top-most of them was. Bottom-to-top order is preserved.
pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
@@ -633,6 +643,7 @@ pub fn group_layers(s: &mut Session, p: &Value) -> Result<Value> {
children.push(doc.remove(*id).ok_or(EngineError::NoLayer(*id))?);
}
*doc.layer_mut(gid).and_then(Layer::children_mut).ok_or(EngineError::NoLayer(gid))? = children;
+ check_group_depth(doc, "Group Layers")?;
*active = Some(gid);
Ok(gid)
})?;
@@ -1132,6 +1143,24 @@ mod tests {
assert_eq!(doc(&s).layers.len(), 4);
}
+ #[test]
+ fn grouping_is_capped_at_the_document_nesting_limit() {
+ let mut s = session(8);
+ let a = rect_layer(&mut s, Rect::new(0, 0, 5, 5));
+ select_all(&mut s, &[a]);
+ for _ in 0..photocraft_doc::MAX_GROUP_DEPTH {
+ s.execute("layer.groupLayers", json!({})).unwrap();
+ }
+ assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH);
+ // One more wrapping group would pass the cap: rejected, document untouched.
+ let err = s.execute("layer.groupLayers", json!({})).unwrap_err();
+ assert!(err.to_string().contains("deeper than 100"), "{err}");
+ assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH);
+ // The rejected call recorded no history step: undo still lands one grouping earlier.
+ s.undo();
+ assert_eq!(doc(&s).max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1);
+ }
+
#[test]
fn select_linked_layers_excludes_an_unlinked_active_layer() {
for depth in [8, 16, 32] {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 9b3c7f4cb..36940424f 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -423,6 +423,47 @@ fn integer_params_accept_json_floats() {
s.execute("layer.translate", json!({"dx": 2.0, "dy": -1.0})).unwrap();
}
+#[test]
+fn move_to_refuses_to_nest_past_the_group_depth_cap() {
+ let mut s = session_with_doc();
+ let deep = s.execute("layer.new.layer", json!({"name": "Deep"})).unwrap()["layer"].as_u64().unwrap();
+ for _ in 0..photocraft_doc::MAX_GROUP_DEPTH - 1 {
+ s.execute("layer.groupLayers", json!({"layer": deep})).unwrap();
+ }
+ // `Deep` sits inside MAX - 1 groups. Moving a two-level group (G2 > G1 > Leaf) beside it
+ // would put `Leaf` at MAX + 1.
+ let path = s.active().unwrap().doc.path_of(photocraft_doc::LayerId(deep)).unwrap();
+ assert_eq!(path.len() - 1, photocraft_doc::MAX_GROUP_DEPTH - 1);
+ let leaf = s.execute("layer.new.layer", json!({"name": "Leaf"})).unwrap()["layer"].as_u64().unwrap();
+ let g1 = s.execute("layer.groupLayers", json!({"layer": leaf})).unwrap()["layer"].as_u64().unwrap();
+ let g = s.execute("layer.groupLayers", json!({"layer": g1})).unwrap()["layer"].as_u64().unwrap();
+ let past = s.active().unwrap().history.past_len();
+ let err = s.execute("layer.moveTo", json!({"layer": g, "target": deep, "position": "above"})).unwrap_err();
+ assert!(err.to_string().contains("deeper than"), "{err}");
+ assert!(s.active().unwrap().doc.max_group_depth() <= photocraft_doc::MAX_GROUP_DEPTH);
+ assert_eq!(s.active().unwrap().history.past_len(), past, "no history step recorded");
+ // A plain layer beside the deepest one still fits.
+ s.execute("layer.moveTo", json!({"layer": leaf, "target": deep, "position": "above"})).unwrap();
+ assert_eq!(s.active().unwrap().doc.max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH - 1);
+}
+
+#[test]
+fn artboard_from_layers_refuses_to_nest_past_the_group_depth_cap() {
+ let mut s = session_with_doc();
+ let leaf = s.execute("layer.new.layer", json!({"name": "Leaf"})).unwrap()["layer"].as_u64().unwrap();
+ let mut top = leaf;
+ for _ in 0..photocraft_doc::MAX_GROUP_DEPTH {
+ top = s.execute("layer.groupLayers", json!({"layer": top})).unwrap()["layer"].as_u64().unwrap();
+ }
+ assert_eq!(s.active().unwrap().doc.max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH);
+ s.execute("layer.select", json!({"layer": top})).unwrap();
+ let past = s.active().unwrap().history.past_len();
+ let err = s.execute("layer.new.artboardFromLayers", json!({})).unwrap_err();
+ assert!(err.to_string().contains("deeper than"), "{err}");
+ assert_eq!(s.active().unwrap().doc.max_group_depth(), photocraft_doc::MAX_GROUP_DEPTH);
+ assert_eq!(s.active().unwrap().history.past_len(), past, "no history step recorded");
+}
+
#[test]
fn move_to_reorders_and_nests() {
let mut s = session_with_doc();
diff --git a/crates/format/src/convert.rs b/crates/format/src/convert.rs
index 9bfeaa88a..086f03d26 100644
--- a/crates/format/src/convert.rs
+++ b/crates/format/src/convert.rs
@@ -14,10 +14,9 @@ use photocraft_raster::{Surface, Tile, decode_pixel, encode_pixel};
use crate::manifest::*;
use crate::{FormatError, Result};
-/// Deepest group nesting a bundle may hold (a layer inside this many nested groups is the deepest).
-/// Saving and loading recurse once per level; at this depth both stay within a few hundred KiB of
-/// stack, well inside the 1 MiB main-thread stacks of Windows and wasm.
-pub const MAX_GROUP_DEPTH: usize = 100;
+/// Deepest group nesting a bundle may hold — the one nesting limit every consumer of the layer
+/// tree shares; see [`photocraft_doc::MAX_GROUP_DEPTH`].
+pub use photocraft_doc::MAX_GROUP_DEPTH;
fn too_deep() -> FormatError {
FormatError::LimitExceeded(format!("layer groups nested deeper than {MAX_GROUP_DEPTH}"))
diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs
index 4ea5c2f4d..895d02ec3 100644
--- a/crates/io/src/lib.rs
+++ b/crates/io/src/lib.rs
@@ -162,6 +162,11 @@ fn import_stages(name: &str, bytes: &[u8], ctl: &photocraft_raster::Interrupt) -
}
if is_psd(bytes) {
let file = PsdFile::from_bytes(bytes)?;
+ // Nesting past the document model's cap could never be saved (.pcraft refuses it) and
+ // would overflow the importer's recursion; reject the file with the actionable limit.
+ if psd_import::group_depth(&file) > photocraft_doc::MAX_GROUP_DEPTH {
+ return Err(IoError::Unsupported(format!("layer groups nested deeper than {}", photocraft_doc::MAX_GROUP_DEPTH)));
+ }
ctl.check().map_err(|_| IoError::Cancelled)?;
ctl.progress(0.05);
let (mut document, warnings) = psd_import::psd_to_document_with(&file, ctl).ok_or(IoError::Cancelled)?;
diff --git a/crates/io/src/psd_import.rs b/crates/io/src/psd_import.rs
index 3307cd3cb..2b1ab3f0c 100644
--- a/crates/io/src/psd_import.rs
+++ b/crates/io/src/psd_import.rs
@@ -371,7 +371,7 @@ impl Ctx<'_> {
l.vector_mask = Some(vm);
}
- fn build(&mut self, nodes: &[LayerNode]) -> Vec<Layer> {
+ fn build(&mut self, nodes: &[LayerNode], depth: usize) -> Vec<Layer> {
let layers = self.file.layers();
let ctl = self.ctl;
nodes
@@ -388,7 +388,18 @@ impl Ctx<'_> {
}
LayerNode::Group { index, children, .. } => {
let rec = &layers[*index];
- let children = self.build(children);
+ // The recursion here (and in every later consumer of the tree) is bounded by
+ // the document model's nesting cap; a deeper subtree is not imported.
+ let children = if depth >= photocraft_doc::MAX_GROUP_DEPTH {
+ self.warn(format!(
+ "group `{}` nests deeper than {} groups; its contents were not imported",
+ rec.name(),
+ photocraft_doc::MAX_GROUP_DEPTH
+ ));
+ Vec::new()
+ } else {
+ self.build(children, depth + 1)
+ };
let sd = rec.section_divider();
let expanded = sd.is_none_or(|s| s.kind != photocraft_psd::SectionType::ClosedFolder);
let artboard = crate::comps_map::ARTBOARD_KEYS.iter().find_map(|k| rec.block(k)).and_then(|b| crate::comps_map::parse_artboard(&b.data));
@@ -405,18 +416,42 @@ impl Ctx<'_> {
/// Sets `Layer::link_group` from resource 1026's per-record ids (`nodes` and `layers` correspond).
fn apply_link_groups(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16]) {
- for (n, l) in nodes.iter().zip(layers.iter_mut()) {
- let index = match n {
- LayerNode::Layer { index } => *index,
- LayerNode::Group { index, children, .. } => {
- if let LayerContent::Group(g) = &mut l.content {
- apply_link_groups(children, &mut g.children, ids);
+ fn rec(nodes: &[LayerNode], layers: &mut [Layer], ids: &[u16], depth: usize) {
+ for (n, l) in nodes.iter().zip(layers.iter_mut()) {
+ let index = match n {
+ LayerNode::Layer { index } => *index,
+ LayerNode::Group { index, children, .. } => {
+ // Matches the importer's nesting cap: deeper children were not imported.
+ if depth < photocraft_doc::MAX_GROUP_DEPTH
+ && let LayerContent::Group(g) = &mut l.content
+ {
+ rec(children, &mut g.children, ids, depth + 1);
+ }
+ *index
}
- *index
+ };
+ l.link_group = ids.get(index).copied().filter(|&g| g != 0).map(u64::from);
+ }
+ }
+ rec(nodes, layers, ids, 0);
+}
+
+/// Deepest group nesting of the file's layer records (a layer inside this many groups is the
+/// deepest), computed like `layer_tree`'s stack — iteratively, so no file can make it recurse.
+pub(crate) fn group_depth(file: &PsdFile) -> usize {
+ use photocraft_psd::tagged::SectionType;
+ let (mut open, mut depth) = (0usize, 0usize);
+ for rec in file.layers() {
+ match rec.section_type() {
+ SectionType::BoundingDivider => {
+ open += 1;
+ depth = depth.max(open);
}
- };
- l.link_group = ids.get(index).copied().filter(|&g| g != 0).map(u64::from);
+ SectionType::OpenFolder | SectionType::ClosedFolder => open = open.saturating_sub(1),
+ _ => {}
+ }
}
+ depth
}
fn preserved_blocks(rec: &LayerRecord) -> Vec<([u8; 4], Arc<Vec<u8>>)> {
@@ -585,7 +620,7 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
}
} else if layered {
let tree = file.layer_tree();
- doc.layers = cx.build(&tree);
+ doc.layers = cx.build(&tree, 0);
// Layer › Link Layers: resource 1026 holds one group id per layer record (0 = unlinked).
if let Some(Ok(photocraft_psd::resources::ResourceData::LayerGroupInfo(groups))) =
file.resources.iter().find(|r| r.id == ids::LAYER_GROUP_INFO).and_then(photocraft_psd::resources::ImageResource::parsed)
diff --git a/crates/io/tests/psd_structure.rs b/crates/io/tests/psd_structure.rs
index 2660461da..9cc3e48f9 100644
--- a/crates/io/tests/psd_structure.rs
+++ b/crates/io/tests/psd_structure.rs
@@ -253,6 +253,43 @@ fn builder_psd_imports() {
assert!(matches!(&d.layers[1].content, LayerContent::Group(g) if !g.expanded && g.children.len() == 1));
}
+#[test]
+fn group_nesting_past_the_cap_is_rejected() {
+ use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder};
+ let mut b = PsdBuilder::new(4, 4);
+ for _ in 0..101 {
+ b.begin_group(GroupSpec::new("g"));
+ }
+ b.push_layer(LayerSpec::new("deep", 0, 0, 1, 1, PixelData::Rgba8(vec![1, 2, 3, 4])));
+ for _ in 0..101 {
+ b.end_group().unwrap();
+ }
+ let bytes = b.to_bytes().unwrap();
+ let err = import("deep.psd", &bytes).unwrap_err();
+ assert!(err.to_string().contains("nested deeper than 100"), "{err}");
+ // The never-fail converter still returns a document — capped, with a warning
+ // about the part that was not imported (it used to recurse to the file's depth).
+ let (d, warnings) = psd_to_document(&photocraft_psd::PsdFile::from_bytes(&bytes).unwrap());
+ assert_eq!(d.max_group_depth(), 100);
+ assert!(warnings.iter().any(|w| w.contains("deeper than 100")), "{warnings:?}");
+}
+
+#[test]
+fn group_nesting_at_the_cap_imports() {
+ use photocraft_psd::{GroupSpec, LayerSpec, PixelData, PsdBuilder};
+ let mut b = PsdBuilder::new(4, 4);
+ for _ in 0..100 {
+ b.begin_group(GroupSpec::new("g"));
+ }
+ b.push_layer(LayerSpec::new("deep", 0, 0, 1, 1, PixelData::Rgba8(vec![1, 2, 3, 4])));
+ for _ in 0..100 {
+ b.end_group().unwrap();
+ }
+ let r = import("hundred.psd", &b.to_bytes().unwrap()).unwrap();
+ assert_eq!(r.document.max_group_depth(), 100);
+ assert!(!r.warnings.iter().any(|w| w.contains("deeper")), "{:?}", r.warnings);
+}
+
#[test]
fn locks_and_labels_from_psd() {
use photocraft_psd::TaggedBlock;