Skip to content

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

M6: keep placed-PDF layer choices for parent-page and anchored placements

skylar taylor-barrickf09df5123e0e
diff --git a/crates/doc/src/assets.rs b/crates/doc/src/assets.rs
index c526c98ba..1533b8b4b 100644
--- a/crates/doc/src/assets.rs
+++ b/crates/doc/src/assets.rs
@@ -59,6 +59,15 @@ impl Document {
|| self.stories.values().any(|story| story_any(story, 0, &all_on))
}
+ /// Whether any placed PDF, on document or parent spreads, in groups or anchored, has an
+ /// Object Layer Options choice (hidden layers or explicit all-on). Exceeding the traversal
+ /// budget conservatively says yes.
+ pub fn has_pdf_layer_overrides(&self) -> bool {
+ let chosen = |it: &Item| it.has_pdf_layer_override();
+ self.spreads.iter().chain(&self.parents).flat_map(|spread| &spread.items).any(|item| item_any(item, 0, &chosen))
+ || self.stories.values().any(|story| story_any(story, 0, &chosen))
+ }
+
/// 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))
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs
index 53308e1b8..617743840 100644
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@ -642,6 +642,24 @@ impl Document {
found
}
+ /// Every item on document and parent spreads, in groups, and among the objects embedded in
+ /// stories (anchored objects, notes and table cells): walks that must cover every placement
+ /// use this, not [`Document::all_items`].
+ pub fn placed_items(&self) -> Vec<&Item> {
+ let mut v = Vec::new();
+ for sp in self.spreads.iter().chain(&self.parents) {
+ for it in &sp.items {
+ it.walk(&mut |i| v.push(i));
+ }
+ }
+ for st in self.stories.values() {
+ for o in &st.objects {
+ o.item.walk(&mut |i| v.push(i));
+ }
+ }
+ v
+ }
+
/// Every item id (pre-order) on document spreads.
pub fn all_items(&self) -> Vec<ItemId> {
let mut v = Vec::new();
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index f019976f2..bd1fba101 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -671,20 +671,27 @@ fn wrap_stand_in(it: &designcraft_doc::Item, depth: usize) -> designcraft_doc::I
}
/// A copy of `d` where placed PDFs with Object Layer Options hidden layers are 300 ppi images.
+///
+/// Every placement counts, including parent-page and anchored ones, so a choice is never
+/// silently replaced by the file's defaults.
fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option<designcraft_doc::Document>, usize)> {
- let ids: Vec<designcraft_doc::ItemId> =
- d.all_items().into_iter().filter(|id| d.item(*id).is_some_and(|it| it.has_pdf_layer_override() && it.graphic().is_some())).collect();
- if ids.is_empty() {
+ let choices: Vec<_> = d
+ .placed_items()
+ .into_iter()
+ .filter(|it| it.has_pdf_layer_override())
+ .filter_map(|it| {
+ let g = it.graphic()?;
+ let a = d.assets.get(&g.asset).filter(|a| designcraft_render::is_pdf(&a.data))?;
+ Some((it.id, g.clone(), a.clone(), it.pdf_hidden_layers.clone()))
+ })
+ .collect();
+ if choices.is_empty() {
return Ok((None, 0));
}
let mut out = d.clone();
+ let mut images = std::collections::HashMap::new();
let mut n = 0;
- for id in ids {
- let Some((g, hidden)) = out.item(id).and_then(|it| Some((it.graphic()?.clone(), it.pdf_hidden_layers.clone()))) else { continue };
- let Some(a) = out.assets.get(&g.asset).cloned() else { continue };
- if !designcraft_render::is_pdf(&a.data) {
- continue;
- }
+ for (id, g, a, hidden) in choices {
// The whole page at 300 ppi (the graphic may show only a box of it).
let shown = designcraft_render::shown_box(&a);
let [l, t, r, b] = shown.unwrap_or([0.0, 0.0, 1.0, 1.0]);
@@ -705,11 +712,19 @@ fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option<designcraf
..Default::default()
}),
);
- if let Some(designcraft_doc::Content::Graphic(gg)) = out.item_mut(id).map(|it| &mut it.content) {
- gg.asset = aid;
- }
+ images.insert(id, aid);
n += 1;
}
+ out.update_items(
+ |it| images.contains_key(&it.id),
+ |it| {
+ if let designcraft_doc::Content::Graphic(gg) = &mut it.content
+ && let Some(aid) = images.get(&it.id)
+ {
+ gg.asset = *aid;
+ }
+ },
+ );
Ok((Some(out), n))
}
diff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rs
index 048aa54d0..fbaaf21b5 100644
--- a/crates/engine/src/cmd/interchange.rs
+++ b/crates/engine/src/cmd/interchange.rs
@@ -42,28 +42,29 @@ fn export_idml(s: &mut Session, p: &Value) -> Result<Value> {
/// 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.
+///
+/// Every placement counts, including parent-page and anchored ones: a choice that the copy
+/// cannot carry is rejected rather than exported as the file's defaults.
fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Document>> {
- let ids: Vec<_> = doc
- .all_items()
+ let choices: Vec<_> = doc
+ .placed_items()
.into_iter()
- .filter(|id| {
- doc.item(*id).is_some_and(|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))
- })
+ .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 ids.is_empty() {
+ 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();
- for id in ids {
- let Some(it) = doc.item(id) else { continue };
- let Some(asset) = it.graphic().and_then(|g| doc.assets.get(&g.asset)) else { continue };
- let bytes = designcraft_render::pdf_hide_layers(&asset.data, &it.pdf_hidden_layers)
+ 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());
@@ -71,14 +72,22 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Documen
variant.link = None;
let aid = variant.id;
out.assets.insert(aid, std::sync::Arc::new(variant));
- if let Some(it) = out.item_mut(id) {
- if let designcraft_doc::Content::Graphic(g) = &mut it.content {
- g.asset = aid;
+ 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))
}
diff --git a/crates/engine/src/cmd/pdflayers.rs b/crates/engine/src/cmd/pdflayers.rs
index 4ca67f7c3..ba4299d4f 100644
--- a/crates/engine/src/cmd/pdflayers.rs
+++ b/crates/engine/src/cmd/pdflayers.rs
@@ -480,6 +480,38 @@ pub(crate) mod tests {
s.execute("object.layerOptions", &json!({"ids":[id],"useDefaults":true})).unwrap();
assert!(!visible(&mut s), "explicit reset restores defaults");
}
+ #[test]
+ fn parent_page_choices_reach_idml_variants_and_raster_export() {
+ // Red is hidden by the file itself, so "show every layer" is a visible difference.
+ let pdf = designcraft_render::pdf_hide_layers(&two_layer_pdf(), &["Red".into()]).unwrap();
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"width": 100, "height": 100, "pages": 1})).unwrap();
+ let id = s
+ .execute(
+ "file.place",
+ &json!({"base64": super::super::file::base64_encode(&pdf), "name": "on-parent.pdf", "spread": {"kind": "parent", "index": 0}, "x": 0.0, "y": 0.0, "width": 100}),
+ )
+ .unwrap()["id"]
+ .clone();
+ let item = designcraft_doc::ItemId(id.as_u64().unwrap());
+ assert!(
+ matches!(s.doc().unwrap().doc.find(item).unwrap().spread, designcraft_doc::SpreadRef::Parent(0)),
+ "the placement sits on a parent page"
+ );
+ s.execute("object.layerOptions", &json!({"ids": [id], "hidden": [], "useDefaults": false})).unwrap();
+ // Embedded IDML: the parent-page placement gets its own variant, like a document one.
+ let idml = s.execute("file.exportIdml", &json!({})).unwrap();
+ let imported = designcraft_idml::import_idml(&super::super::file::base64_decode(idml["base64"].as_str().unwrap())).unwrap();
+ let asset = imported.assets.values().find(|a| designcraft_render::is_pdf(&a.data)).unwrap();
+ assert!(designcraft_render::pdf_layers(&asset.data).iter().all(|(_, on)| *on), "the embedded copy shows every layer");
+ // An external-only copy would keep the original file's defaults: the choice is rejected.
+ let err = s.execute("file.exportIdml", &json!({"embedImages": false})).unwrap_err().to_string();
+ assert!(err.contains("embedded images"), "{err}");
+ // PDF/A-2b rasterises a placement with a choice wherever it sits, warnings included.
+ let a2b = s.execute("file.exportPdf", &json!({"standard": "a2b"})).unwrap();
+ assert!(a2b["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("exported as images"))), "{a2b}");
+ }
+
#[test]
fn layerless_pdf_rejects_overrides_without_breaking_idml_export() {
let mut s = Session::new();