Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

M6: merge current main and retain nested PDF/A placement traversal

skylar taylor-barrick53d9b6d7f8c7
diff --cc ROADMAP.md
index 4337c28d1,db6c5a868..b517f64e9
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@@ -11,6 -12,14 +12,17 @@@
DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web.
++- **2026-10-24** · PDF/A-2b preparation applies placed-PDF layer choices, including explicit all-on,
++ to anchors inside table-cell text, footnotes and endnotes in an export-only copy. The nested
++ IDML variant write pass remains separate work; no readiness percentage change.
+ - **2026-10-24** · Explicit PDF layer choices, including all-on, are checked with one actual
+ rewrite per distinct source before editing; reset to file defaults bypasses the check. Native
+ format 4 covers both explicit all-on PDF layers and retained graphic-layer options. No readiness percentage change.
+ - **2026-10-23** · Placed PDF layers can explicitly all be shown, separately from Use File Defaults.
+ Legacy commands keep their reset behavior; native saves require a capable reader only for
+ the new all-on state, and PDF/embedded IDML exports preserve the choice. No readiness percentage change.
+ - **2026-10-23** · IDML graphic-layer export rejects parents in already closed subtrees,
+ preserving native-edited layer order through round trips. Synthetic regression added.
- **2026-10-23** · PDF layer choices now validate before editing all targets; rejected rewrites
leave document/undo state intact. Null trailer entries remain unencrypted, and unsupported
all-content crops retain the whole page rather than silently clipping hidden layers.
diff --cc crates/engine/src/cmd/export.rs
index 011e3eb47,43bfceaae..a6dd964eb
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@@ -720,6 -708,10 +722,9 @@@ fn wrap_stand_in(it: &designcraft_doc::
}
/// A copy of `d` where placed PDFs with Object Layer Options hidden layers are 300 ppi images.
+ ///
-/// Parent-page and anchored placements count too, so a page that inherits the placement is not
-/// silently replaced by the file's defaults. A choice anchored inside a table cell's or a note's
-/// text keeps the source file's defaults (see `docs/pdf-layer-visibility.md`).
++/// Parent-page and anchored placements count too, including anchors inside table-cell,
++/// footnote and endnote text. Only the export copy is rewritten.
fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option<designcraft_doc::Document>, usize)> {
let choices: Vec<_> = d
.placed_items()
@@@ -769,13 -753,13 +766,13 @@@
images.insert(id, aid);
n += 1;
}
- out.update_items(
+ out.update_placed_items(
|it| images.contains_key(&it.id),
|it| {
- if let designcraft_doc::Content::Graphic(g) = &mut it.content
- && let Some(&aid) = images.get(&it.id)
+ if let designcraft_doc::Content::Graphic(gg) = &mut it.content
+ && let Some(aid) = images.get(&it.id)
{
- g.asset = aid;
+ gg.asset = *aid;
}
},
);
@@@ -896,176 -882,6 +897,184 @@@ fn export_pdf(s: &mut Session, p: &Valu
}
}
+#[cfg(test)]
+mod placed_layer_tests {
+ use std::sync::Arc;
+
+ use designcraft_doc::{AnchoredObject, Document, Item, ItemId, SpreadRef, StoryId, Table};
+ use designcraft_geom::Rect;
+ use serde_json::json;
+
+ use crate::Session;
+
+ fn two_layer_pdf() -> Vec<u8> {
+ let content = "/OC /a BDC 0 0 1 rg 0 0 50 100 re f EMC /OC /b BDC 1 0 0 rg 50 0 50 100 re f EMC";
+ let objs = [
+ "<</Type/Catalog/Lang(en-GB)/Pages 2 0 R/OCProperties<</OCGs[5 0 R 6 0 R]/D<</Order[5 0 R 6 0 R]/Name(Default)/Locked[5 0 R]>>>>>>"
+ .to_string(),
+ "<</Type/Pages/Kids[3 0 R]/Count 1>>".to_string(),
+ "<</Type/Page/Parent 2 0 R/MediaBox[0 0 100 100]/Resources<</Properties<</a 5 0 R/b 6 0 R>>>>/Contents 4 0 R>>".to_string(),
+ format!("<</Length {}>>\nstream\n{content}\nendstream", content.len()),
+ "<</Type/OCG/Name(Blue)>>".to_string(),
+ "<</Type/OCG/Name(Red)>>".to_string(),
+ ];
+ let mut out = b"%PDF-1.7\n".to_vec();
+ let mut offs = Vec::new();
+ for (i, o) in objs.iter().enumerate() {
+ offs.push(out.len());
+ out.extend_from_slice(format!("{} 0 obj\n{}\nendobj\n", i + 1, o).as_bytes());
+ }
+ let x = out.len();
+ let mut t = format!("xref\n0 {}\n0000000000 65535 f\r\n", objs.len() + 1);
+ for o in offs {
+ t.push_str(&format!("{o:010} 00000 n\r\n"));
+ }
+ t.push_str(&format!("trailer\n<</Size {}/Root 1 0 R>>\nstartxref\n{x}\n%%EOF\n", objs.len() + 1));
+ out.extend_from_slice(t.as_bytes());
+ out
+ }
+
+ fn placement<'a>(d: &'a Document, location: &str, id: ItemId, sid: StoryId) -> &'a Item {
+ match location {
+ "cell" => &d.story(sid).unwrap().tables.values().next().unwrap().cells[0].text.objects[0].item,
+ "footnote" => &d.story(sid).unwrap().notes[0].text.objects[0].item,
+ "endnote" => &d.story(sid).unwrap().endnotes[0].text.objects[0].item,
+ "anchor" => &d.story(sid).unwrap().objects[0].item,
+ _ => d.item(id).unwrap(),
+ }
+ }
+
+ #[test]
+ fn stale_layer_fields_on_non_pdf_placements_do_not_block_pdf_a() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ let result = s
+ .execute(
+ "file.place",
+ &json!({
+ "base64": super::super::file::base64_encode(&two_layer_pdf()), "name": "layers.pdf",
+ }),
+ )
+ .unwrap();
+ let id = ItemId(result["id"].as_u64().unwrap());
+ s.execute("object.layerOptions", &json!({"ids": [id.0], "hidden": ["Blue"]})).unwrap();
+ // Relinking to an ordinary image can leave legacy fields on the placement.
+ // They are not an actionable placed-PDF override and must not fail closed.
+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+ let aid = d.item(id).unwrap().graphic().unwrap().asset;
+ let asset = Arc::make_mut(d.assets.get_mut(&aid).unwrap());
+ asset.mime = "image/png".into();
+ asset.data = Arc::new(designcraft_render::Rendered { width: 1, height: 1, pixels: vec![0, 0, 0, 0] }.to_png());
+ let (copy, count) = super::rasterize_layered(d).unwrap();
+ assert_eq!(count, 0);
+ assert!(copy.is_none());
+ s.execute("file.exportPdf", &json!({"standard": "a2b"})).unwrap();
+ }
+
+ fn check_placement(location: &str) {
++ for all_on in [false, true] {
++ check_choice(location, all_on);
++ }
++ }
++
++ fn check_choice(location: &str, all_on: bool) {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1})).unwrap();
+ let placed = s
+ .execute(
+ "file.place",
+ &json!({
+ "base64": super::super::file::base64_encode(&two_layer_pdf()), "name": "layers.pdf",
+ "x": 0, "y": 0, "width": 100,
+ "spread": {"kind": if location == "parent" { "parent" } else { "doc" }, "index": 0}
+ }),
+ )
+ .unwrap();
+ let id = ItemId(placed["id"].as_u64().unwrap());
- s.execute("object.layerOptions", &json!({"ids": [id.0], "hidden": ["Blue"]})).unwrap();
++ let hidden = if all_on { vec![] } else { vec!["Blue"] };
++ s.execute("object.layerOptions", &json!({"ids": [id.0], "hidden": hidden, "useDefaults": false})).unwrap();
+ let sid = {
+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+ let layer = d.default_layer();
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 80.0), layer, "Body", Default::default()).unwrap();
+ if !matches!(location, "doc" | "parent") {
+ let item = (**d.spreads[0].items.iter().find(|it| it.id == id).unwrap()).clone();
+ Arc::make_mut(&mut d.spreads[0]).items.retain(|it| it.id != id);
+ let object = AnchoredObject { item, position: Default::default() };
+ let story = d.story_mut(sid).unwrap();
+ match location {
+ "cell" => {
+ let mut table = Table::new(1, 1, 1, 0, 0, 20.0);
+ table.cells[0].text.insert_object(0, object);
+ story.insert_table(0, table);
+ }
+ "footnote" => {
+ story.insert_note(0, "Note", Default::default()).unwrap();
+ Arc::make_mut(&mut story.notes[0]).text.insert_object(0, object);
+ }
+ "endnote" => {
+ story.insert_endnote(0, "Endnote", Default::default()).unwrap();
+ Arc::make_mut(&mut story.endnotes[0]).text.insert_object(0, object);
+ }
+ "anchor" => story.insert_object(0, object),
+ _ => assert!(matches!(location, "doc" | "parent")),
+ }
+ }
+ sid
+ };
+ // Exercise the real export command for each location, not just the traversal helper.
+ let result = s.execute("file.exportPdf", &json!({"standard": "a2b"})).unwrap();
+ assert!(
+ result["warnings"].as_array().unwrap().iter().any(|w| w.as_str().unwrap().contains("1 placed PDF(s)")),
+ "{location}: {}",
+ result["warnings"]
+ );
+ // Check the rewritten placement, including its pixels. Counting a placement without
+ // updating the nested object would still export the file's default layer visibility.
+ let source = &s.doc().unwrap().doc;
+ let (copy, count) = super::rasterize_layered(source).unwrap();
+ assert_eq!(count, 1, "{location}");
+ let copy = copy.unwrap();
+ let item = placement(&copy, location, id, sid);
+ let asset = &copy.assets[&item.graphic().unwrap().asset];
+ assert_eq!(asset.mime, "image/png", "{location}");
+ let image = designcraft_render::images::decoded(&asset.data, 0);
+ let image = image.unwrap();
+ let pixel = image.data()[usize::from(image.height()) / 2 * usize::from(image.width()) + usize::from(image.width()) / 4];
- assert_eq!(pixel.a, 0, "Blue must be hidden at {location}");
++ assert_eq!(pixel.a, if all_on { 255 } else { 0 }, "Blue visibility at {location}, all_on={all_on}");
+ // Export preparation must not change the open document's placement or source asset.
+ let original = placement(source, location, id, sid);
- assert_eq!(original.pdf_hidden_layers, vec!["Blue"]);
++ assert_eq!(original.pdf_hidden_layers, hidden);
++ assert!(original.pdf_layer_override);
+ assert_eq!(source.assets[&original.graphic().unwrap().asset].mime, "application/pdf");
+ }
+
+ #[test]
+ fn layered_pdf_a_document_placement() {
+ check_placement("doc");
+ }
+ #[test]
+ fn layered_pdf_a_parent_placement() {
+ check_placement("parent");
+ }
+ #[test]
+ fn layered_pdf_a_story_anchor() {
+ check_placement("anchor");
+ }
+ #[test]
+ fn layered_pdf_a_table_cell_anchor() {
+ check_placement("cell");
+ }
+ #[test]
+ fn layered_pdf_a_footnote_anchor() {
+ check_placement("footnote");
+ }
+ #[test]
+ fn layered_pdf_a_endnote_anchor() {
+ check_placement("endnote");
+ }
+}
+
#[cfg(not(target_arch = "wasm32"))]
fn write_file(path: &str, bytes: &[u8]) -> Result<()> {
crate::io::write_file(path, bytes).map_err(EngineError::Other)
diff --cc crates/engine/src/cmd/interchange.rs
index bf0e011a0,2c3d23b36..a7ce794ea
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@@ -39,6 -40,68 +40,68 @@@ fn export_idml(s: &mut Session, p: &Val
}
}
+ /// Whether a placement holds an Object Layer Options choice an export can still apply: a graphic
+ /// whose asset is a PDF. A choice left on an item that is no longer a placed PDF (its link was
+ /// replaced with another format) is not one, so the package report does not name it.
+ pub(crate) fn has_applicable_pdf_layer_overrides(doc: &Document) -> bool {
+ doc.placed_items().into_iter().any(|it| {
+ it.has_pdf_layer_override() && it.graphic().and_then(|g| doc.assets.get(&g.asset)).is_some_and(|a| designcraft_render::is_pdf(&a.data))
+ })
+ }
+
+ /// Each placement gets its own embedded variant so two frames sharing a PDF can
+ /// choose different layers. The live document and original linked bytes stay untouched.
+ ///
+ /// Parent-page and anchored placements count too, so a page that inherits the placement does not
-/// quietly fall back to the file's defaults. A choice anchored inside a table cell's or a note's
-/// text is not carried yet: this walk does not follow the stories nested there (see
-/// `docs/pdf-layer-visibility.md`).
++/// quietly fall back to the file's defaults. Choices inside table-cell and note text are found
++/// by the read walk, but the legacy update_items write pass below cannot apply their variants
++/// yet (see `docs/pdf-layer-visibility.md`).
+ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Document>> {
+ let choices: Vec<_> = doc
+ .placed_items()
+ .into_iter()
+ .filter(|it| it.has_pdf_layer_override())
+ .filter_map(|it| {
+ let asset = it.graphic().and_then(|g| doc.assets.get(&g.asset)).filter(|a| designcraft_render::is_pdf(&a.data))?;
+ Some((it.id, asset, it.pdf_hidden_layers.clone()))
+ })
+ .collect();
+ if choices.is_empty() {
+ return Ok(None);
+ }
+ if !embed {
+ return Err(EngineError::Other("PDF layer choices require embedded images in IDML export".into()));
+ }
+ let mut out = doc.clone();
+ let mut variants = std::collections::HashMap::new();
+ for (id, asset, hidden) in choices {
+ let bytes = designcraft_render::pdf_hide_layers(&asset.data, &hidden)
+ .ok_or_else(|| EngineError::Other(format!("{}: PDF layer choices could not be applied", asset.name)))?;
+ let mut variant = (**asset).clone();
+ variant.id = designcraft_doc::AssetId(out.alloc());
+ variant.data = std::sync::Arc::new(bytes);
+ variant.link = None;
+ let aid = variant.id;
+ out.assets.insert(aid, std::sync::Arc::new(variant));
+ variants.insert(id, aid);
+ }
+ // Anchored objects live in stories, and parent pages outside the document-spread walk, so
+ // the choice is cleared where the placement actually is.
+ out.update_items(
+ |it| variants.contains_key(&it.id),
+ |it| {
+ if let designcraft_doc::Content::Graphic(g) = &mut it.content
+ && let Some(aid) = variants.get(&it.id)
+ {
+ g.asset = *aid;
+ }
+ it.pdf_layer_override = false;
+ it.pdf_hidden_layers.clear();
+ },
+ );
+ Ok(Some(out))
+ }
+
/// [`designcraft_idml::import_idml`] with the linked images read through [`crate::io`] from
/// beside `package` (the package's file, if it has one), so the automation read root applies to
/// the paths the package names, and its PDF crops resolved.
diff --cc docs/gaps.md
index ad56bfc37,b41fc3217..8efd54bed
--- a/docs/gaps.md
+++ b/docs/gaps.md
@@@ -208,6 -210,11 +210,12 @@@ Kind: **F** feature · **U** UI/UX · *
- **Safety:** PDF visibility variants preserve catalog/configuration entries and nonzero-generation
references, redefining the existing catalog rather than choosing an arbitrary object number.
Encrypted, hybrid-reference and over-budget rewrites are rejected; no print-fidelity claim.
+ - **Layer choices:** placed PDFs distinguish explicit all-on visibility from file defaults;
+ choices survive native saves, raster/PDF output and embedded IDML export for the placements the
+ export walks reach: document and parent spreads, groups, and objects anchored in a story. A
- placement anchored inside table-cell or footnote/endnote text is not reached yet. IDML layer
- variants are embedded copies; external-only export is rejected when choices would be lost.
++ placement anchored inside table-cell or footnote/endnote text is also prepared for PDF/A-2b,
++ but the IDML variant write pass cannot update those nested placements yet. IDML layer variants
++ are embedded copies; external-only export is rejected when choices would be lost.
- **Missing:** EPS is shown through its preview only (no PostScript interpreter); PSD layer
comps beyond visibility; the Clipping Path Options dialog (tracing into a clip that keeps the
frame, Threshold/Tolerance/Inset Frame preview, picking an alpha channel or a path saved in a
diff --cc docs/pdf-layer-visibility.md
index 000000000,8fd71fa9d..48fbf1f5b
mode 000000,100644..100644
--- a/docs/pdf-layer-visibility.md
+++ b/docs/pdf-layer-visibility.md
@@@ -1,0 -1,9 +1,9 @@@
+ # Placed PDF layer visibility
+
+ Object Layer Options distinguishes a PDF's own default configuration from an explicit visibility choice, including showing every layer. Use File Defaults resets that choice. Only placed PDFs in a mixed selection are changed.
+
+ The engine command `object.layerOptions` accepts `hidden` names and optional `useDefaults`. Existing calls with `hidden: []` retain their reset behavior; pass `useDefaults: false` to explicitly show all layers. `useDefaults: true` resets defaults and cannot be combined with hidden names. Every explicit choice, including all-on (`useDefaults: false` with an empty `hidden` list), is checked with one actual visibility rewrite per distinct source before any target is edited or an undo step is recorded: a PDF can list readable layers yet refuse the rewrite (for example an over-budget cross-reference history), and PDFs without readable optional-content layers cannot be rewritten at all. Resetting to file defaults needs no rewrite and is always allowed. A stored choice whose source can no longer be rewritten still fails closed: the canvas does not draw the unmodified source and PDF export reports an error. With no explicit ID, a query selects the first placed PDF anywhere in the selection; an explicit non-PDF ID remains an error. Queries include `overridden` separately from each layer's `visible` and `default` states.
+
-Native saves use format 4 only for an explicit all-on override, on document or parent spreads, in groups or anchored: older readers would otherwise silently render file defaults. Format 4 is one reader capability shared with retained placed-graphic layer options (#1647, see [graphic-layer-options.md](graphic-layer-options.md)), so a version 4 reader understands both. Existing nonempty hidden lists retain their older semantics and format requirements. Raster and PDF export honor the choice; PDF export keeps its existing warned rasterization behavior. Embedded IDML export stores a separate PDF variant per placement and leaves original linked bytes untouched. The export walks cover the placements a page shows through its spreads and through its stories: parent-page and anchored ones too, so a page that inherits the placement does not quietly fall back to the file's defaults. They do not follow the stories nested in table cells or in footnotes and endnotes yet, so a placement anchored there keeps its choice on the document while the IDML copy is left at the file's defaults and the PDF/A-2b rasterisation pass does not flatten it; widening that traversal is separate work (gap 19). External-only IDML export rejects active PDF layer choices because the original external file would lose the choice. A package's IDML copy links the placed files, so it cannot carry a choice either; the package report says so for a placement the export walk reaches, and the packaged DesignCraft document keeps it.
++Native saves use format 4 only for an explicit all-on override, on document or parent spreads, in groups or anchored: older readers would otherwise silently render file defaults. Format 4 is one reader capability shared with retained placed-graphic layer options (#1647, see [graphic-layer-options.md](graphic-layer-options.md)), so a version 4 reader understands both. Existing nonempty hidden lists retain their older semantics and format requirements. Raster and PDF export honor the choice; PDF export keeps its existing warned rasterization behavior. Embedded IDML export stores a separate PDF variant per placement and leaves original linked bytes untouched. The export walks cover the placements a page shows through its spreads and through its stories: parent-page and anchored ones too, so a page that inherits the placement does not quietly fall back to the file's defaults. PDF/A-2b preparation also follows stories nested in table cells, footnotes and endnotes, applying both hidden-layer and explicit all-on choices to an export-only raster copy. The IDML reader finds those choices too, but its legacy write pass cannot update the nested placements yet: embedded IDML still leaves them at the file's defaults, while external-only IDML rejects the active choice. Fixing that IDML write pass remains separate work (gap 19). External-only IDML export rejects active PDF layer choices because the original external file would lose the choice. A package's IDML copy links the placed files, so it cannot carry a choice either; the package report says so for a placement the export walk reaches, and the packaged DesignCraft document keeps it.
+
+ This fixes visibility-state handling, not full InDesign layer/print parity. It does not implement editing the contents of placed PDFs or native INDD placement. Catalog/reference safety fixes landed in #1670.