diff --git a/crates/idml/src/export/spread.rs b/crates/idml/src/export/spread.rs index b876ecc03..0b0d0b9d4 100644 --- a/crates/idml/src/export/spread.rs +++ b/crates/idml/src/export/spread.rs @@ -64,10 +64,48 @@ impl<'a> Ex<'a> { }, ); let based_on = sp.parent.as_ref().and_then(|i| i.based_on); + // The spread's local copies of parent items: (parent item, copy, page the copy is on). + let mut copies = Vec::new(); + collect_copies(sp, &mut copies); + let mut used = vec![false; copies.len()]; + // Each page's own copies are paired first, for every page, so one page's spread-wide fallback + // can't take the copy another page overrides with. + let mut own: Vec>> = Vec::with_capacity(sp.pages.len()); + for (i, pg) in sp.pages.iter().enumerate() { + let mut row = Vec::with_capacity(pg.overridden.len()); + for parent in &pg.overridden { + let k = (0..copies.len()).find(|k| !used[*k] && copies[*k].0 == *parent && copies[*k].2 == Some(i)); + if let Some(k) = k { + used[k] = true; + } + row.push(k); + } + own.push(row); + } for (i, pg) in sp.pages.iter().enumerate() { let name = if master { sp.parent.as_ref().map(|i| i.prefix.clone()).unwrap_or_default() } else { d.page_name(first_page + i) }; let applied = if master { based_on } else { pg.parent }; - let overrides: Vec = pg.overridden.iter().map(|i| uid(i.0)).collect(); + // InDesign reads OverrideList two ids at a time: the parent item, then the item that + // overrides it, and a list of parent items alone crashed it on open (#2896). The copy is + // the one on this page paired in the first pass, else any on the spread not yet paired; a + // parent item whose override was deleted pairs with an id nothing else uses, as + // InDesign's own files do. + let mut overrides: Vec = Vec::with_capacity(pg.overridden.len() * 2); + for (j, parent) in pg.overridden.iter().enumerate() { + let k = own.get(i).and_then(|r| r.get(j)).copied().flatten().or_else(|| { + let k = (0..copies.len()).find(|k| !used[*k] && copies[*k].0 == *parent); + if let Some(k) = k { + used[k] = true; + } + k + }); + let copy = match k.and_then(|k| copies.get(k)) { + Some(c) => uid(c.1.0), + None => self.fresh(), + }; + overrides.push(uid(parent.0)); + overrides.push(copy); + } let pe = El::new("Page") .attr("Self", uid(pg.id.0)) .attr("Name", name) @@ -136,3 +174,89 @@ fn push_page_guides(d: &Document, sp: &Spread, pg: &designcraft_doc::Page, pe: & pe.push(crate::xml::from_craft(ge)); } } + +/// The items on the spread that override a parent item, in the order they are written: (parent +/// item, item, page). A copy's page is the one under its own centre, a nested copy's through the +/// groups it sits in. The walk keeps its own stack, so it reaches every copy the writer writes, +/// however deep, and asks for the bounds of copies only. +fn collect_copies(sp: &Spread, out: &mut Vec<(designcraft_doc::ItemId, designcraft_doc::ItemId, Option)>) { + let mut stack: Vec<(&designcraft_doc::Item, Affine)> = sp.items.iter().rev().map(|it| (&**it, Affine::IDENTITY)).collect(); + while let Some((it, outer)) = stack.pop() { + if let Some(parent) = it.overrides { + let centre = bounds_under(it, outer).map_or_else(|| outer * designcraft_geom::Point::ZERO, |r| r.center()); + out.push((parent, it.id, sp.page_at_x(centre.x))); + } + let inner = outer * it.xf; + stack.extend(it.children().iter().rev().map(|c| (&**c, inner))); + } +} + +/// `it`'s bounds under `outer`, as `Item::bounds` measures them (a group's are its children's +/// outlines under the full transform), with a stack of its own: a copy that is a group can hold +/// groups nested deeper than a recursive walk should go (#2940 review). `None` for a group with +/// nothing in it. +fn bounds_under(it: &designcraft_doc::Item, outer: Affine) -> Option { + let mut stack = vec![(it, outer)]; + let mut out: Option = None; + while let Some((it, outer)) = stack.pop() { + let xf = outer * it.xf; + if it.shape == designcraft_doc::Shape::Group + && let designcraft_doc::Content::Group { items } = &it.content + { + stack.extend(items.iter().map(|c| (&**c, xf))); + continue; + } + if let Some(r) = it.path.transformed(xf).bounds() { + out = Some(out.map_or(r, |o| o.union(r))); + } + } + out +} + +#[cfg(test)] +mod bounds_tests { + use designcraft_doc::{Content, Item, ItemId, LayerId, Shape}; + use designcraft_geom::{Affine, Rect, shapes}; + use std::sync::Arc; + + fn rect(id: u64, r: Rect) -> Item { + Item::new(ItemId(id), LayerId(0), Shape::Rectangle, shapes::rectangle(r)) + } + + fn group(id: u64, items: Vec, xf: Affine) -> Item { + let mut g = Item::new(ItemId(id), LayerId(0), Shape::Group, Default::default()); + g.content = Content::Group { items: items.into_iter().map(Arc::new).collect() }; + g.xf = xf; + g + } + + /// The same bounds as `Item::bounds`, for a plain item, nested and turned groups, a frame + /// with items pasted into it (its own outline) and an empty group. + #[test] + fn bounds_match_the_items_own() { + let inner = group(3, vec![rect(1, Rect::new(0.0, 0.0, 10.0, 20.0)), rect(2, Rect::new(30.0, 5.0, 40.0, 8.0))], Affine::rotate(0.4)); + let outer = group(4, vec![inner.clone(), rect(5, Rect::new(-5.0, -5.0, 0.0, 0.0))], Affine::translate((100.0, 50.0)) * Affine::scale(2.0)); + let mut frame = rect(6, Rect::new(0.0, 0.0, 50.0, 50.0)); + frame.content = Content::Group { items: vec![Arc::new(rect(7, Rect::new(-100.0, -100.0, 200.0, 200.0)))] }; + for it in [rect(8, Rect::new(1.0, 2.0, 3.0, 4.0)), inner, outer, frame] { + let (want, got) = (it.bounds(), super::bounds_under(&it, Affine::IDENTITY).unwrap()); + for (a, b) in [(want.x0, got.x0), (want.y0, got.y0), (want.x1, got.x1), (want.y1, got.y1)] { + assert!((a - b).abs() < 1e-9, "{want:?} vs {got:?}"); + } + } + assert_eq!(super::bounds_under(&group(9, vec![], Affine::IDENTITY), Affine::IDENTITY), None); + } + + /// A group 100,000 deep is measured without recursion. It is leaked rather than dropped, + /// since dropping it recurses. + #[test] + fn a_deep_group_is_measured_without_recursion() { + let mut it = rect(0, Rect::new(10.0, 20.0, 30.0, 40.0)); + for i in 1..=100_000 { + it = group(i, vec![it], Affine::translate((1.0, 0.0))); + } + let r = super::bounds_under(&it, Affine::IDENTITY); + std::mem::forget(it); + assert_eq!(r, Some(Rect::new(100_010.0, 20.0, 100_030.0, 40.0))); + } +} diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs index 2c06368d6..217e2c7f4 100644 --- a/crates/idml/src/tests.rs +++ b/crates/idml/src/tests.rs @@ -1233,6 +1233,169 @@ fn round_trips_overridden_parent_items() { assert_eq!(shown_parent + local.len(), 1); } +/// #2896: InDesign reads a page's `OverrideList` two ids at a time, the parent item and then the +/// item that overrides it; a list of parent items alone crashed InDesign when it opened the file. +/// Each overridden parent item is paired with its local copy on that page, and one whose +/// override was deleted with an id nothing else in the package uses. +#[test] +fn override_lists_pair_each_parent_item_with_its_override() { + // Page 1 on a spread of its own, pages 2 and 3 facing. + let mut d = Document::new(&NewDocument { pages: 3, facing_pages: true, ..Default::default() }); + let lid = d.default_layer(); + let (ppi, ppage) = d.parent_page_for(0).unwrap(); + let px = d.parents[ppi].pages[ppage].x; + let parent = |d: &mut Document, y: f64| { + let id = designcraft_doc::ItemId(d.alloc()); + let item = designcraft_doc::Item::new(id, lid, Shape::Rectangle, shapes::rectangle(Rect::new(px + 40.0, y, px + 200.0, y + 60.0))); + d.insert_item(SpreadRef::Parent(ppi), item.clone(), None).unwrap(); + item + }; + let (kept, deleted) = (parent(&mut d, 40.0), parent(&mut d, 200.0)); + // Each page overrides the first parent item with a copy of its own; page 1 also overrides the + // second and deleted its copy. + // The facing spread lists page 3's copy before page 2's, so a page that took the first copy + // on the spread instead of its own would get the other page's. + let mut copies = vec![String::new(); 3]; + for (si, pi) in [(0, 0), (1, 1), (1, 0)] { + let mut copy = kept.clone(); + copy.id = designcraft_doc::ItemId(d.alloc()); + copy.xf = designcraft_geom::Affine::translate((d.spreads[si].pages[pi].x - px, 0.0)) * copy.xf; + copy.overrides = Some(kept.id); + copies[si + pi] = format!("u{:x}", copy.id.0); + d.insert_item(SpreadRef::Doc(si), copy, None).unwrap(); + std::sync::Arc::make_mut(&mut d.spreads[si]).pages[pi].overridden.push(kept.id); + } + std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0].overridden.push(deleted.id); + + let bytes = export_idml(&d); + let (masters, spreads) = (zip_text(&bytes, "MasterSpreads/"), zip_text(&bytes, "Spreads/")); + let lists: Vec> = spreads + .split(">(), [4, 2, 2], "pairs: {lists:?}"); + // The element whose Self is `id` (its start tag). + let element = |xml: &str, id: &str| xml.split('<').find(|e| e.contains(&format!("Self=\"{id}\""))).map(str::to_owned); + for list in &lists { + for pair in list.chunks(2) { + assert!(element(&masters, &pair[0]).is_some(), "{} is a parent item: {list:?}", pair[0]); + } + } + // Each page pairs the first parent item with its own copy, which names it as the item it + // overrides. + for ((list, copy), page) in lists.iter().zip(&copies).zip(1..) { + assert_eq!(&list[1], copy, "page {page}: {lists:?}"); + let e = element(&spreads, copy).unwrap_or_else(|| panic!("page {page}: {copy} is an item on the spread")); + assert!(e.contains(&format!("OverriddenPageItem=\"{}\"", list[0])), "page {page}: {e}"); + } + // The deleted override's id is used nowhere else in the package. + let all = zip_text(&bytes, ""); + let orphan = &lists[0][3]; + assert_eq!(all.matches(orphan.as_str()).count(), 1, "{orphan} appears only in the list"); + + // Read back, each page lists its parent items, as before. + let back = import_idml(&bytes).unwrap(); + let ids: Vec<_> = back.parents[ppi].items.iter().map(|i| i.id).collect(); + assert_eq!(back.spreads[0].pages[0].overridden, ids); + assert_eq!(back.spreads[1].pages[0].overridden, ids[..1]); + assert_eq!(back.spreads[1].pages[1].overridden, ids[..1]); +} + +/// #2896: a copy inside a group is paired on the page under its own centre, not the group's, and a +/// copy nested deeper than 64 groups is still paired with its parent item. +#[test] +fn override_lists_pair_nested_copies_on_their_own_pages() { + use designcraft_doc::{Content, Item, ItemId}; + use designcraft_geom::Affine; + use std::sync::Arc; + let mut d = Document::new(&NewDocument { pages: 3, facing_pages: true, ..Default::default() }); + let lid = d.default_layer(); + let (ppi, _) = d.parent_page_for(0).unwrap(); + let parent = |d: &mut Document, y: f64| { + let item = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, y, 200.0, y + 60.0))); + d.insert_item(SpreadRef::Parent(ppi), item.clone(), None).unwrap(); + item + }; + let (kept, deep) = (parent(&mut d, 40.0), parent(&mut d, 200.0)); + let copy = |d: &mut Document, of: &Item, r: Rect| { + let mut c = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(r)); + c.overrides = Some(of.id); + c + }; + let group = |d: &mut Document, items: Vec, xf: Affine| { + let mut g = Item::new(ItemId(d.alloc()), lid, Shape::Group, Default::default()); + g.content = Content::Group { items: items.into_iter().map(Arc::new).collect() }; + g.xf = xf; + g + }; + let (left, right) = (d.spreads[1].pages[0].clone(), d.spreads[1].pages[1].clone()); + assert!(left.x + left.width <= right.x + 1e-9, "page 2 is left of page 3"); + // One group holds page 3's small copy first and page 2's wide one, so its centre is on page 2. + // The group is moved 300 pt right and its items drawn 300 pt left of where they show, so a page + // read from an item's own coordinates, not through its group, would be wrong. + let shift = 300.0; + let to_left = Affine::translate((left.x + shift, 0.0)); + let on_right = copy(&mut d, &kept, Rect::new(right.x - left.x - shift + 10.0, 40.0, right.x - left.x - shift + 40.0, 80.0)); + let on_left = copy(&mut d, &kept, Rect::new(10.0 - shift, 40.0, left.width - 10.0 - shift, 80.0)); + let (right_id, left_id) = (format!("u{:x}", on_right.id.0), format!("u{:x}", on_left.id.0)); + let g = group(&mut d, vec![on_right, on_left], to_left); + assert!(g.bounds().center().x < left.x + left.width, "the group's centre is on page 2"); + d.insert_item(SpreadRef::Doc(1), g, None).unwrap(); + // Page 3 also overrides the second parent item with a copy 70 groups deep. + let mut nested = copy(&mut d, &deep, Rect::new(right.x + 10.0, 200.0, right.x + 100.0, 260.0)); + let deep_id = format!("u{:x}", nested.id.0); + for _ in 0..70 { + nested = group(&mut d, vec![nested], Affine::IDENTITY); + } + d.insert_item(SpreadRef::Doc(1), nested, None).unwrap(); + let sp = Arc::make_mut(&mut d.spreads[1]); + sp.pages[0].overridden.push(kept.id); + sp.pages[1].overridden.extend([kept.id, deep.id]); + + let spreads = zip_text(&export_idml(&d), "Spreads/"); + // Each page's OverrideList, from its start tag. + let lists: Vec> = spreads + .split("').next().unwrap_or_default(); + tag.split("OverrideList=\"").nth(1).and_then(|l| l.split('"').next()).unwrap_or_default().split_whitespace().map(str::to_owned).collect() + }) + .collect(); + let (k, dp) = (format!("u{:x}", kept.id.0), format!("u{:x}", deep.id.0)); + assert_eq!(lists, [vec![], vec![k.clone(), left_id], vec![k, right_id, dp, deep_id]]); +} + +/// A page overriding 20,000 parent items, each with its copy: every parent item pairs with its own +/// copy, in order, and the export takes about a second (#2940 review asked about the cost of the +/// search for each entry at this size). +#[test] +fn many_overrides_pair_with_their_own_copies() { + use designcraft_doc::{Item, ItemId}; + let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() }); + let lid = d.default_layer(); + let (ppi, _) = d.parent_page_for(0).unwrap(); + let n = 20_000; + let mut copies = Vec::with_capacity(n); + for i in 0..n { + let y = (i % 500) as f64; + let parent = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, y, 60.0, y + 1.0))); + let mut copy = parent.clone(); + copy.id = ItemId(d.alloc()); + copy.overrides = Some(parent.id); + copies.push((format!("u{:x}", parent.id.0), format!("u{:x}", copy.id.0))); + std::sync::Arc::make_mut(&mut d.spreads[0]).pages[0].overridden.push(parent.id); + std::sync::Arc::make_mut(&mut d.parents[ppi]).items.push(std::sync::Arc::new(parent)); + std::sync::Arc::make_mut(&mut d.spreads[0]).items.push(std::sync::Arc::new(copy)); + } + let spreads = zip_text(&export_idml(&d), "Spreads/"); + let list = spreads.split("OverrideList=\"").nth(1).and_then(|l| l.split('"').next()).unwrap_or_default(); + let ids: Vec<&str> = list.split_whitespace().collect(); + assert_eq!(ids.len(), 2 * n); + assert!(ids.chunks(2).zip(&copies).all(|(pair, (p, c))| pair[0] == p && pair[1] == c), "each parent item pairs with its own copy"); +} + #[test] fn uri_and_base64_helpers() { assert_eq!(import::uri_to_path("file:/a%20b/c.png"), "/a b/c.png");