DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
M6: cover every placement when PDF layer choices are applied
skylar taylor-barrick1266ce8236f1
diff --git a/crates/doc/src/edit.rs b/crates/doc/src/edit.rsindex 617743840..9b0e8df2f 100644--- a/crates/doc/src/edit.rs+++ b/crates/doc/src/edit.rs@@ -642,9 +642,9 @@ 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`].+ /// 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) {@@ -653,13 +653,29 @@ impl Document {}}for st in self.stories.values() {- for o in &st.objects {- o.item.walk(&mut |i| v.push(i));- }+ 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()) {+ 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() {+ 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();@@ -754,6 +770,70 @@ 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 {+ o.item.walk(&mut |i| v.push(i));+ }+ 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 {+ let mut found = false;+ it.walk(&mut |i| found |= hit(i));+ found+}++/// [`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() {+ for c in &mut Arc::make_mut(t).cells {+ update_story_items(&mut c.text, depth + 1, hit, f, n);+ }+ }+ for note in st.notes.iter_mut().chain(st.endnotes.iter_mut()) {+ update_story_items(&mut Arc::make_mut(note).text, depth + 1, hit, f, n);+ }+}+/// 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 {diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rsindex bd1fba101..48b9099c5 100644--- a/crates/engine/src/cmd/export.rs+++ b/crates/engine/src/cmd/export.rs@@ -686,6 +686,10 @@ fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option<designcraf}).collect();if choices.is_empty() {+ // Fail closed: a choice this walk cannot reach must not become the file's defaults.+ if d.has_pdf_layer_overrides() {+ return Err(EngineError::Other("a placed PDF's layer choice sits where this raster export cannot apply it".into()));+ }return Ok((None, 0));}let mut out = d.clone();@@ -715,7 +719,7 @@ fn rasterize_layered(d: &designcraft_doc::Document) -> Result<(Option<designcrafimages.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(gg) = &mut it.contentdiff --git a/crates/engine/src/cmd/interchange.rs b/crates/engine/src/cmd/interchange.rsindex fbaaf21b5..eaf279ebc 100644--- a/crates/engine/src/cmd/interchange.rs+++ b/crates/engine/src/cmd/interchange.rs@@ -56,6 +56,11 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Documen}).collect();if choices.is_empty() {+ // A choice this walk cannot reach would silently become the file's defaults (a newer+ // nesting construct, say), so the copy is refused instead.+ if doc.has_pdf_layer_overrides() {+ return Err(EngineError::Other("a placed PDF's layer choice sits where this IDML export cannot apply it".into()));+ }return Ok(None);}if !embed {@@ -76,7 +81,7 @@ fn with_pdf_layer_variants(doc: &Document, embed: bool) -> Result<Option<Documen}// 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(+ out.update_placed_items(|it| variants.contains_key(&it.id),|it| {if let designcraft_doc::Content::Graphic(g) = &mut it.contentdiff --git a/crates/engine/src/cmd/pdflayers.rs b/crates/engine/src/cmd/pdflayers.rsindex ba4299d4f..b4c236a39 100644--- a/crates/engine/src/cmd/pdflayers.rs+++ b/crates/engine/src/cmd/pdflayers.rs@@ -512,6 +512,82 @@ pub(crate) mod tests {assert!(a2b["warnings"].as_array().unwrap().iter().any(|w| w.as_str().is_some_and(|w| w.contains("exported as images"))), "{a2b}");}+ /// A choice on a frame anchored inside a table cell or a footnote is a placement too: the+ /// save asks for the newer reader, the IDML copy gets a variant, an external-only copy is+ /// refused and PDF/A-2b rasterises it, rather than each quietly falling back to the file.+ #[test]+ fn nested_placements_keep_their_layer_choices_in_saves_and_exports() {+ use designcraft_doc::{AnchoredObject, Content, Graphic, Item, Shape, SpreadRef, Table};+ use designcraft_geom::{Affine, Rect, shapes};++ let pdf = designcraft_render::pdf_hide_layers(&two_layer_pdf(), &["Red".into()]).unwrap();+ for in_note in [false, true] {+ let mut d = designcraft_doc::Document::new(&Default::default());+ let asset = designcraft_doc::AssetId(d.alloc());+ d.add_asset(designcraft_doc::Asset {+ id: asset,+ name: "nested.pdf".into(),+ mime: "application/pdf".into(),+ data: std::sync::Arc::new(pdf.clone()),+ ..Default::default()+ });+ let mut item = Item::new(+ designcraft_doc::ItemId(d.alloc()),+ d.default_layer(),+ Shape::Rectangle,+ shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)),+ );+ item.pdf_layer_override = true;+ item.content = Content::Graphic(Graphic {+ asset,+ size: (100.0, 100.0),+ xf: Affine::IDENTITY,+ clip: None,+ auto_fit: Default::default(),+ fit_align: 4,+ crop: [0.0; 4],+ wrap: Default::default(),+ fill: Default::default(),+ layer_options: None,+ });+ let layer = d.default_layer();+ let (_, story) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(0.0, 0.0, 80.0, 80.0), layer, "Body", Default::default()).unwrap();+ let anchored = AnchoredObject { item, position: Default::default() };+ if in_note {+ let st = d.story_mut(story).unwrap();+ st.insert_note(0, "Note", Default::default()).unwrap();+ assert_eq!(st.notes.len(), 1);+ std::sync::Arc::make_mut(&mut st.notes[0]).text.insert_object(0, anchored);+ } else {+ let mut table = Table::new(1, 1, 1, 0, 0, 20.0);+ table.cells[0].text.insert_object(0, anchored);+ d.story_mut(story).unwrap().insert_table(0, table);+ }+ assert!(d.has_pdf_layer_overrides(), "the nested placement carries the choice");+ let mut s = Session::new();+ s.add_document(crate::DocState::new(d, None));+ // The save keeps it under the newer reader, as the detection walk says.+ let saved = designcraft_format::save(&s.doc().unwrap().doc).unwrap();+ let reopened = designcraft_format::load(&saved).unwrap();+ assert!(reopened.has_pdf_layer_overrides(), "in_note={in_note}");+ s.add_document(crate::DocState::new(reopened, None));+ // Embedded IDML carries a variant that shows every layer.+ 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 copies: Vec<_> = imported.assets.values().filter(|a| designcraft_render::is_pdf(&a.data)).collect();+ assert!(!copies.is_empty(), "in_note={in_note}: the anchored placement is exported");+ assert!(+ copies.iter().all(|a| designcraft_render::pdf_layers(&a.data).iter().all(|(_, on)| *on)),+ "in_note={in_note}: the embedded copy must not fall back to the file's defaults"+ );+ // An external-only copy would keep the original file's defaults.+ assert!(s.execute("file.exportIdml", &json!({"embedImages": false})).is_err(), "in_note={in_note}");+ // PDF/A-2b rasterises a placement with a choice, wherever it sits.+ let a2b = s.execute("file.exportPdf", &json!({"standard": "a2b"}));+ assert!(a2b.is_ok(), "in_note={in_note}: {a2b:?}");+ }+ }+#[test]fn layerless_pdf_rejects_overrides_without_breaking_idml_export() {let mut s = Session::new();