Skip to content

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

M6: preserve nested placed-PDF layer choices in PDF/A export

skylar taylor-barrick9f6cb08591e6
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rs
index 53308e1b8..1bdd088fb 100644
--- a/crates/doc/src/edit.rs
+++ b/crates/doc/src/edit.rs
@@ -87,7 +87,9 @@ impl Document {
/// The horizontal ruler of spread `r` in pieces `(from x, to x, base)`, spread coordinates,
/// covering every x: one piece, or one per page for a page origin.
pub fn ruler_pieces(&self, r: SpreadRef) -> Vec<(f64, f64, Point)> {
- let Some(sp) = self.spread(r) else { return Vec::new() };
+ let Some(sp) = self.spread(r) else {
+ return Vec::new();
+ };
if self.settings.ruler_origin != crate::RulerOrigin::Page || sp.pages.len() < 2 {
return self.ruler_base(r, 0.0).map(|o| (f64::NEG_INFINITY, f64::INFINITY, o)).into_iter().collect();
}
@@ -365,7 +367,9 @@ impl Document {
let from_empty = fs.is_none_or(|fs| self.story(fs).is_some_and(|s| s.text.is_empty() && s.frames == [from]));
let ts = self.frame_story(to)?;
let to_first = ts.and_then(|ts| self.story(ts)).is_some_and(|s| s.frames.first() == Some(&to));
- let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else { return self.thread(from, to) };
+ let (Some(ts), true, true) = (ts, from_empty, to_first && from != to) else {
+ return self.thread(from, to);
+ };
self.check_thread_links(from, to, true)?;
if let Some(fs) = fs {
self.stories.remove(&fs);
@@ -468,7 +472,9 @@ impl Document {
return Err(DocError::Invalid(format!("{id} is locked or on a locked layer")));
}
}
- let (Some(fl), Some(tl)) = (self.find(from), self.find(to)) else { return Err(DocError::NoItem(to)) };
+ let (Some(fl), Some(tl)) = (self.find(from), self.find(to)) else {
+ return Err(DocError::NoItem(to));
+ };
let same_place = match (fl.spread, tl.spread) {
(SpreadRef::Doc(_), SpreadRef::Doc(_)) => true,
(a, b) => a == b,
@@ -642,6 +648,45 @@ impl Document {
found
}
+ /// Every item on document and parent spreads, in groups, and among the objects anchored in
+ /// stories, including the stories in table cells and in notes: 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 {
+ placed_item(it, 0, &mut v);
+ }
+ }
+ for st in self.stories.values() {
+ placed_story_items(st, 0, &mut v);
+ }
+ v
+ }
+
+ /// Applies `f` to every placed item `hit` selects, wherever it sits: on document or parent
+ /// spreads, in groups, and anchored in a story (also inside table cells and notes).
+ /// Returns how many items `f` saw.
+ pub fn update_placed_items(&mut self, hit: impl Fn(&Item) -> bool, mut f: impl FnMut(&mut Item)) -> usize {
+ let mut n = 0;
+ for sp in self.spreads.iter_mut().chain(self.parents.iter_mut()) {
+ if !sp.items.iter().any(|it| has_hit(it, &hit)) {
+ continue;
+ }
+ for it in Arc::make_mut(sp).items.iter_mut() {
+ if has_hit(it, &hit) {
+ update_placed_item(Arc::make_mut(it), 0, &hit, &mut f, &mut n);
+ }
+ }
+ }
+ for st in self.stories.values_mut() {
+ if story_has_hit(st, 0, &hit) {
+ update_story_items(Arc::make_mut(st), 0, &hit, &mut f, &mut n);
+ }
+ }
+ n
+ }
+
/// Every item id (pre-order) on document spreads.
pub fn all_items(&self) -> Vec<ItemId> {
let mut v = Vec::new();
@@ -736,6 +781,91 @@ impl Document {
}
}
+/// How deep nested stories (a cell's text, a footnote's text, an endnote's text) are followed
+/// when every placement is visited. A document nested deeper is left alone.
+const MAX_PLACEMENT_DEPTH: usize = 64;
+
+/// The items anchored in `st`, and in the stories nested in its cells and notes, pre-order.
+fn placed_story_items<'a>(st: &'a Story, depth: usize, v: &mut Vec<&'a Item>) {
+ if depth > MAX_PLACEMENT_DEPTH {
+ return;
+ }
+ for o in &st.objects {
+ placed_item(&o.item, 0, v);
+ }
+ for c in st.tables.values().flat_map(|t| &t.cells) {
+ placed_story_items(&c.text, depth + 1, v);
+ }
+ for n in st.notes.iter().chain(&st.endnotes) {
+ placed_story_items(&n.text, depth + 1, v);
+ }
+}
+
+/// Whether `it` or anything in it is selected by `hit`.
+fn has_hit(it: &Item, hit: &impl Fn(&Item) -> bool) -> bool {
+ fn check(it: &Item, depth: usize, hit: &impl Fn(&Item) -> bool) -> bool {
+ hit(it) || (depth < MAX_PLACEMENT_DEPTH && it.children().iter().any(|child| check(child, depth + 1, hit)))
+ }
+ check(it, 0, hit)
+}
+
+/// [`Document::update_placed_items`] for one item: only the branches holding a hit are copied.
+fn update_placed_item(it: &mut Item, depth: usize, hit: &impl Fn(&Item) -> bool, f: &mut impl FnMut(&mut Item), n: &mut usize) {
+ if hit(it) {
+ f(it);
+ *n += 1;
+ }
+ if depth >= MAX_PLACEMENT_DEPTH {
+ return;
+ }
+ if let Some(children) = it.children_mut() {
+ for c in children.iter_mut().filter(|c| has_hit(c, hit)) {
+ update_placed_item(Arc::make_mut(c), depth + 1, hit, f, n);
+ }
+ }
+}
+
+/// [`Document::update_placed_items`] for the placements of one story, and of the stories nested
+/// in its cells and notes.
+fn update_story_items(st: &mut Story, depth: usize, hit: &impl Fn(&Item) -> bool, f: &mut impl FnMut(&mut Item), n: &mut usize) {
+ if depth > MAX_PLACEMENT_DEPTH {
+ return;
+ }
+ for o in st.objects.iter_mut() {
+ if has_hit(&o.item, hit) {
+ update_placed_item(&mut Arc::make_mut(o).item, 0, hit, f, n);
+ }
+ }
+ for t in st.tables.values_mut().filter(|t| t.cells.iter().any(|c| story_has_hit(&c.text, depth + 1, hit))) {
+ for c in &mut Arc::make_mut(t).cells {
+ if story_has_hit(&c.text, depth + 1, hit) {
+ update_story_items(&mut c.text, depth + 1, hit, f, n);
+ }
+ }
+ }
+ for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {
+ if story_has_hit(&note.text, depth + 1, hit) {
+ update_story_items(&mut Arc::make_mut(note).text, depth + 1, hit, f, n);
+ }
+ }
+}
+
+fn placed_item<'a>(it: &'a Item, depth: usize, v: &mut Vec<&'a Item>) {
+ v.push(it);
+ if depth < MAX_PLACEMENT_DEPTH {
+ for child in it.children() {
+ placed_item(child, depth + 1, v);
+ }
+ }
+}
+
+fn story_has_hit(st: &Story, depth: usize, hit: &impl Fn(&Item) -> bool) -> bool {
+ depth <= MAX_PLACEMENT_DEPTH
+ && (st.objects.iter().any(|o| has_hit(&o.item, hit))
+ || st.tables.values().flat_map(|t| &t.cells).any(|c| story_has_hit(&c.text, depth + 1, hit))
+ || st.notes.iter().chain(&st.endnotes).any(|n| story_has_hit(&n.text, depth + 1, hit)))
+}
+
/// Does `p` (in the item's parent space) hit `it`?
pub fn item_hit(it: &Item, p: Point, tol: f64) -> bool {
if let Content::Group { items } = &it.content {
@@ -780,3 +910,71 @@ pub fn hit_descendant(it: &Item, p: Point, tol: f64, want: &dyn Fn(&Item) -> boo
/// How far from its path type on a path is hit (points): about a cap height of 12–18 pt type,
/// either side (the type may sit on or under the path).
const PATH_TYPE_REACH: f64 = 12.0;
+#[cfg(test)]
+mod placed_item_tests {
+ use super::*;
+
+ #[test]
+ fn exhaustive_placements_keep_unselected_branches_shared() {
+ let mut d = Document::new(&Default::default());
+ 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();
+ let id = ItemId(d.alloc());
+ let mut item = Item::new(id, layer, Shape::Rectangle, Default::default());
+ item.content = Content::Group { items: vec![Arc::new(Item::new(ItemId(d.alloc()), layer, Shape::Rectangle, Default::default()))] };
+ let child = item.children()[0].id;
+ let mut table = crate::Table::new(1, 1, 1, 0, 0, 20.0);
+ table.cells[0].text.insert_object(0, crate::AnchoredObject { item, position: Default::default() });
+ d.story_mut(sid).unwrap().insert_table(0, table);
+ let untouched = StoryId(d.alloc());
+ d.stories.insert(untouched, Arc::new(Story::new(untouched)));
+ let snapshot = d.clone();
+ assert!(d.placed_items().iter().any(|i| i.id == child));
+ assert_eq!(d.update_placed_items(|i| i.id == child, |i| i.hidden = true), 1);
+ assert!(d.placed_items().iter().find(|i| i.id == child).unwrap().hidden);
+ assert!(!snapshot.placed_items().iter().find(|i| i.id == child).unwrap().hidden);
+ assert!(Arc::ptr_eq(&d.stories[&untouched], &snapshot.stories[&untouched]));
+ assert!(Arc::ptr_eq(&d.spreads[0], &snapshot.spreads[0]));
+ let unchanged = d.clone();
+ let mut calls = 0;
+ assert_eq!(d.update_placed_items(|_| false, |_| calls += 1), 0);
+ assert_eq!(calls, 0);
+ assert!(d.spreads.iter().zip(&unchanged.spreads).all(|(a, b)| Arc::ptr_eq(a, b)));
+ assert!(d.parents.iter().zip(&unchanged.parents).all(|(a, b)| Arc::ptr_eq(a, b)));
+ assert!(d.stories.iter().all(|(id, st)| Arc::ptr_eq(st, &unchanged.stories[id])));
+ }
+ #[test]
+ fn exhaustive_placements_bound_nested_stories_and_groups() {
+ let mut d = Document::new(&Default::default());
+ let layer = d.default_layer();
+ let target = ItemId(d.alloc());
+ let mut item = Item::new(target, layer, Shape::Rectangle, Default::default());
+ for _ in 0..MAX_PLACEMENT_DEPTH + 2 {
+ let mut group = Item::new(ItemId(d.alloc()), layer, Shape::Rectangle, Default::default());
+ group.content = Content::Group { items: vec![Arc::new(item)] };
+ item = group;
+ }
+ d.insert_item(SpreadRef::Doc(0), item, None).unwrap();
+ assert!(!d.placed_items().iter().any(|i| i.id == target));
+ let mut calls = 0;
+ assert_eq!(d.update_placed_items(|i| i.id == target, |_| calls += 1), 0);
+ assert_eq!(calls, 0);
+
+ let nested = ItemId(d.alloc());
+ let sid = StoryId(d.alloc());
+ let mut story = Story::new(sid);
+ story.insert_object(
+ 0,
+ crate::AnchoredObject { item: Item::new(nested, layer, Shape::Rectangle, Default::default()), position: Default::default() },
+ );
+ for _ in 0..MAX_PLACEMENT_DEPTH + 2 {
+ let mut outer = Story::new(sid);
+ outer.notes.push(Arc::new(crate::Footnote { id: 1, text: story }));
+ story = outer;
+ }
+ d.stories.insert(sid, Arc::new(story));
+ assert!(!d.placed_items().iter().any(|i| i.id == nested));
+ assert_eq!(d.update_placed_items(|i| i.id == nested, |_| calls += 1), 0);
+ assert_eq!(calls, 0);
+ }
+}
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index 908814809..011e3eb47 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -62,7 +62,9 @@ fn print_booklet(s: &mut Session, p: &Value) -> Result<Value> {
let kind = match str_param(p, "type").unwrap_or("saddleStitch") {
"saddleStitch" => designcraft_pdf::BookletKind::SaddleStitch,
"twoUpConsecutive" | "twoUp" => designcraft_pdf::BookletKind::TwoUpConsecutive,
- t => return Err(bad(ID, format!("unknown type `{t}` (saddleStitch, twoUpConsecutive)"))),
+ t => {
+ return Err(bad(ID, format!("unknown type `{t}` (saddleStitch, twoUpConsecutive)")));
+ }
};
let opts = designcraft_pdf::BookletOptions { kind, space_between: p.get("spaceBetween").and_then(Value::as_f64).unwrap_or(0.0), title: None };
let st = s.doc()?;
@@ -84,9 +86,13 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu
// in the document: unused or hidden graphics must not prevent an export.
let mut used = std::collections::BTreeSet::new();
for block in designcraft_epub::reading_order(d) {
- let designcraft_epub::Block::Image(id) = block else { continue };
+ let designcraft_epub::Block::Image(id) = block else {
+ continue;
+ };
let Some(it) = d.item(id) else { continue };
- let designcraft_doc::Content::Graphic(g) = &it.content else { continue };
+ let designcraft_doc::Content::Graphic(g) = &it.content else {
+ continue;
+ };
used.insert(g.asset);
if d.assets.get(&g.asset).is_some_and(|a| designcraft_doc::media_kind(&a.mime).is_some())
&& let Some(poster) = it.media.as_ref().and_then(|m| m.poster)
@@ -97,7 +103,9 @@ fn eps_previews(d: &designcraft_doc::Document) -> (Cow<'_, designcraft_doc::Docu
let mut out = Cow::Borrowed(d);
let mut warnings = Vec::new();
for id in used {
- let Some(a) = d.assets.get(&id).filter(|a| designcraft_images::is_eps(&a.data)) else { continue };
+ let Some(a) = d.assets.get(&id).filter(|a| designcraft_images::is_eps(&a.data)) else {
+ continue;
+ };
let png = designcraft_images::eps_png(&a.data);
if png.is_none() {
warnings.push(format!("{}: unusable EPS preview; graphic omitted", a.name));
@@ -323,9 +331,13 @@ fn export_epub(s: &mut Session, p: &Value) -> Result<Value> {
let d = &st.doc;
let mut pages = Vec::new();
for i in 0..d.page_count() {
- let Some((si, pi)) = d.page_loc(i) else { continue };
+ let Some((si, pi)) = d.page_loc(i) else {
+ continue;
+ };
let b = d.spreads[si].pages[pi].bounds();
- let Some(img) = rr.render_page(d, &s.cache, i, 2.0, false, &ropts) else { continue };
+ let Some(img) = rr.render_page(d, &s.cache, i, 2.0, false, &ropts) else {
+ continue;
+ };
pages.push(designcraft_epub::FixedPage { png: img.to_png(), width: b.width(), height: b.height(), text: page_text(d, &s.cache, i) });
}
let bytes = designcraft_epub::export_fixed_epub(d, &pages, &opts).map_err(|e| crate::EngineError::Other(e.to_string()))?;
@@ -539,7 +551,9 @@ fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, pp
);
let new = image_item(&mut out, reach, img, it.layer);
let osp = std::sync::Arc::make_mut(&mut out.spreads[si]);
- let Some(pos) = osp.items.iter().position(|x| x.id == it.id) else { continue };
+ let Some(pos) = osp.items.iter().position(|x| x.id == it.id) else {
+ continue;
+ };
if threaded(d, it) {
// Keep the frame (its story flows on) under the image.
osp.items.insert(pos + 1, std::sync::Arc::new(new));
@@ -707,16 +721,28 @@ 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.
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.pdf_hidden_layers.is_empty() && it.graphic().is_some())).collect();
- if ids.is_empty() {
+ let choices: Vec<_> = d
+ .placed_items()
+ .into_iter()
+ .filter_map(|it| {
+ if it.pdf_hidden_layers.is_empty() {
+ return None;
+ }
+ let graphic = it.graphic()?;
+ let asset = d.assets.get(&graphic.asset)?;
+ designcraft_render::is_pdf(&asset.data).then(|| (it.id, graphic.clone(), it.pdf_hidden_layers.clone()))
+ })
+ .collect();
+ if choices.is_empty() {
return Ok((None, 0));
}
let mut out = d.clone();
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 };
+ let mut images = std::collections::BTreeMap::new();
+ for (id, g, hidden) in choices {
+ let Some(a) = out.assets.get(&g.asset).cloned() else {
+ continue;
+ };
if !designcraft_render::is_pdf(&a.data) {
continue;
}
@@ -740,11 +766,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_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)
+ {
+ g.asset = aid;
+ }
+ },
+ );
Ok((Some(out), n))
}
@@ -810,7 +844,9 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
"fitPage" => "/Fit",
"fitWidth" => "/FitH null",
"actual" => "/XYZ null null 1",
- o => return Err(bad("file.exportPdf", format!("unknown view `{o}` (fitPage, fitWidth, actual)"))),
+ o => {
+ return Err(bad("file.exportPdf", format!("unknown view `{o}` (fitPage, fitWidth, actual)")));
+ }
};
if let Some(first) = first_page_ref(&r.bytes) {
cat.push_str(&format!("/OpenAction[{first} 0 R{dest}]"));
@@ -860,6 +896,176 @@ fn export_pdf(s: &mut Session, p: &Value) -> Result<Value> {
}
}
+#[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) {
+ 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 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}");
+ // 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!(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)
@@ -1175,7 +1381,9 @@ mod variable_font_tests {
#[test]
fn variable_font_instance_exports_to_pdf() {
- let Ok(data) = std::fs::read("/System/Library/Fonts/Supplemental/Skia.ttf") else { return };
+ let Ok(data) = std::fs::read("/System/Library/Fonts/Supplemental/Skia.ttf") else {
+ return;
+ };
designcraft_fonts::FontDb::global().add_font(data);
let mut s = Session::new();
s.execute("file.new", &json!({})).unwrap();