DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
M6: preserve nested graphic layers and retain export diagnostics
andeecollard3d362d0bdfda
diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rsindex ed7679ee5..872d15ba8 100644--- a/crates/doc/src/assets.rs+++ b/crates/doc/src/assets.rs@@ -39,6 +39,12 @@ impl Document {|| self.stories.values().any(|story| story_layer_options(story, 0, false))}+ /// Placements outside the ordinary document-spread frame walk used by preflight.+ pub fn has_unwalked_graphic_layer_visibility_overrides(&self) -> bool {+ self.parents.iter().flat_map(|spread| &spread.items).any(|item| item_layer_options(item, 0, true))+ || self.stories.values().any(|story| story_layer_options(story, 0, true))+ }+/// Includes parent items, anchored objects, graphic cells and nested notes.pub fn has_graphic_layer_visibility_overrides(&self) -> bool {self.spreads.iter().chain(&self.parents).flat_map(|spread| &spread.items).any(|item| item_layer_options(item, 0, true))diff --git a/crates/doc/src/item.rs b/crates/doc/src/item.rsindex 9c4169fe4..586358f1d 100644--- a/crates/doc/src/item.rs+++ b/crates/doc/src/item.rs@@ -604,6 +604,9 @@ pub enum Fitting {pub struct GraphicLayerOptions {pub attributes: std::collections::BTreeMap<String, String>,pub layers: Vec<std::collections::BTreeMap<String, String>>,+ /// Parent indices in pre-order; absent entries are top-level layers (older native files).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub parents: Vec<Option<usize>>,}pub const GRAPHIC_LAYER_RENDERING_WARNING: &str =diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rsindex 3797a9bf6..c2ca1e317 100644--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@ -745,6 +745,10 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {let doc: &designcraft_doc::Document = &boxed;let r = designcraft_pdf::export_pdf_with_report(doc, &s.cache, &opts).map_err(|e| EngineError::Other(e.to_string()))?;let mut r = r;+ // Flattening and effect rasterization replace placements, so inspect the source too.+ if st.doc.has_graphic_layer_visibility_overrides() && !r.warnings.iter().any(|w| w == designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING) {+ r.warnings.push(designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING.into());+ }// Transparency Blend Space: the page group of pages with transparency.let spreads = designcraft_pdf::sheet_spreads(doc, &opts);let blended: Vec<bool> = spreads.iter().map(|si| doc.spreads.get(*si).is_some_and(|sp| sp.items.iter().any(|it| transparent(it)))).collect();diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rsindex c69050ace..a0c1a6da1 100644--- a/crates/engine/src/cmd/preflight.rs+++ b/crates/engine/src/cmd/preflight.rs@@ -320,7 +320,7 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {}// Nested graphic cells and anchored/parent items may not have a page frame// in the walk above. Keep the warning visible after a native save/reopen.- if !out.iter().any(|issue| issue.kind == "unsupportedGraphicLayers") && d.has_graphic_layer_visibility_overrides() {+ if d.has_unwalked_graphic_layer_visibility_overrides() {out.push(Issue {severity: "warning",kind: "unsupportedGraphicLayers",diff --git a/crates/engine/tests/graphic_layer_options.rs b/crates/engine/tests/graphic_layer_options.rsindex 8699a4a66..117517002 100644--- a/crates/engine/tests/graphic_layer_options.rs+++ b/crates/engine/tests/graphic_layer_options.rs@@ -13,7 +13,7 @@ fn fixture() -> Vec<u8> {<Properties><GraphicBounds Left="0" Top="0" Right="20" Bottom="20"/></Properties><Link Self="lk" LinkResourceURI="file:/definitely-missing/synthetic.psd"/><GraphicLayerOption UpdateLinkOption="KeepOverrides">- <GraphicLayer Self="g1" Id="1" Name="Hidden" OriginalVisibility="true" CurrentVisibility="false"/>+ <GraphicLayer Self="g0" Id="0" Name="Group"><GraphicLayer Self="g1" Id="1" Name="Hidden" OriginalVisibility="true" CurrentVisibility="false"/></GraphicLayer><GraphicLayer Self="g2" Id="2" Name="Shown" OriginalVisibility="false" CurrentVisibility="true"/></GraphicLayerOption></Image></Rectangle></Spread></Document>"#;let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));@@ -64,7 +64,7 @@ fn graphic_layer_options_in_cells_require_the_new_native_reader() {_ => None,}).unwrap();- std::sync::Arc::make_mut(&mut doc.spreads[0]).items.clear();+ // Keep the original spread graphic too: its warning must not hide the cell warning.let layer = doc.default_layer();let (_, story) = doc.add_text_frame(designcraft_doc::SpreadRef::Doc(0), designcraft_geom::Rect::new(0.0, 0.0, 80.0, 80.0), layer, "Body", Default::default())@@ -78,5 +78,20 @@ fn graphic_layer_options_in_cells_require_the_new_native_reader() {let mut s = Session::new();s.add_document(DocState::new(reopened, None));let preflight = s.execute("preflight.run", &json!({})).unwrap();- assert!(preflight["issues"].as_array().unwrap().iter().any(|i| i["kind"] == "unsupportedGraphicLayers"));+ let warnings: Vec<_> = preflight["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "unsupportedGraphicLayers").collect();+ assert!(warnings.iter().any(|i| i["item"].is_null()), "the cell needs an independent document-level warning");+ assert!(warnings.iter().any(|i| !i["item"].is_null()), "the spread retains its item warning");+}++#[test]+fn pdf_layer_warning_survives_soft_effects_and_flattening() {+ for flatten in [false, true] {+ let doc = designcraft_idml::import_idml(&fixture()).unwrap();+ let id = doc.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id.0;+ let mut session = Session::new();+ session.add_document(DocState::new(doc, None));+ session.execute("object.feather", &json!({"ids":[id], "width":2})).unwrap();+ let out = session.execute("file.exportPdf", &json!({"flatten":flatten})).unwrap();+ assert!(out["warnings"].as_array().unwrap().iter().any(|w| w == GRAPHIC_LAYER_RENDERING_WARNING), "{out}");+ }}diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rsindex fa25914ad..0e338c4b6 100644--- a/crates/idml/src/export.rs+++ b/crates/idml/src/export.rs@@ -25,6 +25,7 @@ const NO_CHAR_ID: &str = "CharacterStyle/$ID/[No character style]";fn graphic_layer_attribute_name(key: &str) -> bool {!key.is_empty()&& key != "Self"+ && key != "xmlns"&& key.bytes().enumerate().all(|(i, b)| b.is_ascii_alphabetic() || b == b'_' || (i > 0 && (b.is_ascii_digit() || matches!(b, b'.' | b'-'))))}@@ -2076,13 +2077,36 @@ impl<'a> Ex<'a> {option.set(key, value);}}- for attributes in &options.layers {+ // Parent indices must precede their children. Ignore invalid parents and bound DOM depth+ // even when a native file has been edited independently of the IDML importer.+ let mut depths = Vec::with_capacity(options.layers.len());+ let mut parents = Vec::with_capacity(options.layers.len());+ for i in 0..options.layers.len() {+ let parent = options.parents.get(i).copied().flatten().filter(|p| *p < i && depths.get(*p).is_some_and(|d| *d < 240));+ depths.push(parent.and_then(|p| depths.get(p)).copied().unwrap_or(0) + 1);+ parents.push(parent);+ }+ let mut children: Vec<Vec<El>> = vec![Vec::new(); options.layers.len()];+ let mut roots = Vec::new();+ for (i, attributes) in options.layers.iter().enumerate().rev() {let mut layer = El::new("GraphicLayer").attr("Self", self.fresh());for (key, value) in attributes {if graphic_layer_attribute_name(key) {layer.set(key, value);}}+ if let Some(nested) = children.get_mut(i) {+ for child in std::mem::take(nested).into_iter().rev() {+ layer.push(child);+ }+ }+ if let Some(nested) = parents.get(i).copied().flatten().and_then(|parent| children.get_mut(parent)) {+ nested.push(layer);+ } else {+ roots.push(layer);+ }+ }+ for layer in roots.into_iter().rev() {option.push(layer);}el.push(option);diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex 9e1c01520..3db03576f 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -3045,7 +3045,20 @@ impl<'r> Importer<'r> {fn graphic(&mut self, g: &El) -> Content {let layer_options = g.find("GraphicLayerOption").map(|options| {let attrs = |e: &El| e.attrs.iter().filter(|(key, _)| key != "Self").cloned().collect();- designcraft_doc::GraphicLayerOptions { attributes: attrs(options), layers: options.find_all("GraphicLayer").map(attrs).collect() }+ let mut out = designcraft_doc::GraphicLayerOptions { attributes: attrs(options), ..Default::default() };+ let mut pending: Vec<_> = options.find_all("GraphicLayer").map(|e| (e, None)).collect();+ pending.reverse();+ while let Some((layer, parent)) = pending.pop() {+ let index = out.layers.len();+ out.layers.push(attrs(layer));+ out.parents.push(parent);+ let children: Vec<_> = layer.find_all("GraphicLayer").collect();+ pending.extend(children.into_iter().rev().map(|e| (e, Some(index))));+ }+ if out.parents.iter().all(Option::is_none) {+ out.parents.clear();+ }+ out});if layer_options.as_ref().is_some_and(designcraft_doc::GraphicLayerOptions::has_visibility_overrides) {self.warnings.push(format!("graphic {}: {}", g.get("Self").unwrap_or("(unnamed)"), designcraft_doc::GRAPHIC_LAYER_RENDERING_WARNING));diff --git a/crates/idml/src/tests/assets.rs b/crates/idml/src/tests/assets.rsindex 9372c3adf..71c01ff0b 100644--- a/crates/idml/src/tests/assets.rs+++ b/crates/idml/src/tests/assets.rs@@ -70,6 +70,23 @@ fn package(frames: &[String]) -> Vec<u8> {])}+#[test]+fn nested_graphic_layers_preserve_hierarchy_on_roundtrip() {+ let option = r#"<GraphicLayerOption UpdateLinkOption="KeepOverrides">+ <GraphicLayer Self="a" Id="1" Name="Group"><GraphicLayer Self="b" Id="2" Name="Nested" OriginalVisibility="true" CurrentVisibility="false"/></GraphicLayer>+ <GraphicLayer Self="c" Id="3" Name="Sibling"/>+ </GraphicLayerOption>"#;+ let image = image(1, PHOTO, None).replace("</Image>", &format!("{option}</Image>"));+ let d = import_idml(&package(&[frame(1, 0.0, 0.0, &image)])).unwrap();+ let options = |d: &Document| d.spreads[0].items[0].graphic().unwrap().layer_options.clone().unwrap();+ let expected = options(&d);+ assert_eq!(expected.layers.len(), 3);+ assert_eq!(expected.parents, [None, Some(0), None]);+ assert!(expected.has_visibility_overrides());+ let reopened = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(options(&reopened), expected);+}+#[test]fn graphic_layer_options_survive_for_each_placement_of_a_shared_asset() {let option = |n: usize, visible: &str| {@@ -121,6 +138,23 @@ fn graphic_layer_options_survive_for_each_placement_of_a_shared_asset() {assert_eq!(twice.matches("<GraphicLayer ").count(), 2);}+#[test]+fn malformed_native_graphic_layer_parents_cannot_cycle_or_overflow_xml_depth() {+ let mut d = import_idml(&package(&[frame(1, 0.0, 0.0, &image(1, PHOTO, None))])).unwrap();+ let Content::Graphic(g) = &mut std::sync::Arc::make_mut(&mut std::sync::Arc::make_mut(&mut d.spreads[0]).items[0]).content else {+ panic!("graphic")+ };+ let mut options = designcraft_doc::GraphicLayerOptions::default();+ for i in 0..300usize {+ options.layers.push(std::collections::BTreeMap::from([("Name".into(), format!("Layer {i}"))]));+ options.parents.push(Some(i.saturating_sub(1)));+ }+ options.parents[1] = Some(usize::MAX);+ g.layer_options = Some(options);+ let reopened = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(reopened.spreads[0].items[0].graphic().unwrap().layer_options.as_ref().unwrap().layers.len(), 300);+}+#[test]fn graphic_layer_attributes_from_native_data_cannot_inject_xml_or_self_ids() {let mut d = import_idml(&package(&[frame(1, 0.0, 0.0, &image(1, PHOTO, None))])).unwrap();@@ -130,12 +164,13 @@ fn graphic_layer_attributes_from_native_data_cannot_inject_xml_or_self_ids() {let attributes = std::collections::BTreeMap::from([("Name".into(), "A < B & C".into()),("Self".into(), "injected-id".into()),+ ("xmlns".into(), "urn:injected".into()),("bad\" injected=\"true".into(), "invalid".into()),]);- g.layer_options = Some(designcraft_doc::GraphicLayerOptions { attributes: attributes.clone(), layers: vec![attributes] });+ g.layer_options = Some(designcraft_doc::GraphicLayerOptions { attributes: attributes.clone(), layers: vec![attributes], ..Default::default() });let out = export_idml(&d);let xml = zip_text(&out, "Spreads/");- assert!(!xml.contains("injected-id") && !xml.contains("injected="));+ assert!(!xml.contains("injected-id") && !xml.contains("injected=") && !xml.contains("urn:injected"));let back = import_idml(&out).unwrap();let Content::Graphic(g) = &back.spreads[0].items[0].content else { panic!("graphic") };assert_eq!(g.layer_options.as_ref().unwrap().layers[0]["Name"], "A < B & C");diff --git a/docs/graphic-layer-options.md b/docs/graphic-layer-options.mdindex 953995839..7668f42f3 100644--- a/docs/graphic-layer-options.md+++ b/docs/graphic-layer-options.md@@ -3,17 +3,23 @@IDML `GraphicLayerOption` / `GraphicLayer` settings are retained on each`Graphic.layer_options`, not on the shared asset. Two placements of one linkedfile can therefore keep different layer choices while sharing image bytes.-Scalar option/layer attributes, layer order, layer IDs/names, original/current+Scalar option/layer attributes, layer order and parent-child relationships, layer IDs/names, original/currentvisibility, link-update policy and view/export/print flags survive import,native save/reopen and IDML export. XML Self IDs are regenerated. Native-edited-attribute maps cannot inject XML syntax or override those Self IDs.+attribute maps cannot inject XML syntax, declare namespaces or override those Self IDs.+Parent indices are optional in native files; missing entries retain the older+flat representation. Invalid/cyclic parent indices and over-budget nesting+are emitted as top-level layers, retaining their scalar metadata without+unbounded XML recursion.This is preservation, **not layer-aware rendering**. The current renderer andPDF exporter use the asset's composite/default appearance and do not applythese per-placement choices. Changed visibility and explicit view/export/printstates produce an import warning, a persistent `unsupportedGraphicLayers`preflight issue, and a PDF export warning. Nested graphic cells, anchored-objects and parent items remain detectable after native reopening.+objects and parent items remain detectable after native reopening, including+when spread items also produce warnings. PDF warnings inspect the source+document so effect rasterization and transparency flattening cannot hide them.Native files containing these settings require format version 4. Earlierreaders reject that version instead of loading and silently discarding the new@@ -23,7 +29,8 @@ requirements. Older graphics without `layerOptions` still deserialize withSynthetic regressions cover independent overrides on two placements sharingone asset, metadata round trips, native reader requirements, nested cells,-preflight/PDF warnings and invalid native attribute names. Private originals+nested layer hierarchy, preflight/PDF warnings after rasterization and flattening,+and invalid native attribute names and parent indices. Private originalsand artwork are not repository fixtures; any collection results are localmetadata checks, not an independent reference-rendering or fidelity oracle.