DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge parent-based-on: Parents: a parent can be based on another parent (#652)
aionggebae0c7805b8
diff --cc ROADMAP.mdindex 1f03c6367,6881d5ec5..2a2408b3d--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -128,11 -129,13 +128,12 @@@ list) · [roadmap.md](docs/roadmap.md)Newest first.+ - **2026-10-13** · A parent can be based on another parent (`layout.parents.options`). Pages draw the base parent's items, then the parent's, then their own, on screen and in PDF and image export; chains work, cycles are refused, overrides reach base items, `document.inspect` reports `basedOn`, and IDML round-trips it. No readiness percentage change.-- **2026-10-12** · macOS Dock Quit uses the same unsaved-document prompts as window and menu Quit. Repeated requests keep the current answers; Cancel retains every tab and unsaved recovery checkpoint, and completed Save/Don't Save answers exit through the ordinary event loop. No readiness percentage change.-- **2026-10-12** · Orderly native exit writes the latest recovery state after finalizing current quit approvals; incomplete or stale plans keep their documents, and Undo to the saved state clears stale recovery. Unavailable or failed recovery is reported. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.-- **2026-10-12** · Recovered documents keep a checkpoint until saved, closed or reverted, including a second crash before autosave. Restarted document IDs and explicit recovery folders preserve other snapshots; failed republishing retains the original. No readiness percentage change.-- **2026-10-12** · Book numbering and style updates prepare every chapter before saving. Only closed native chapters are changed; imported IDML remains a read-only style/PDF source. If a later disk write fails, the error names the completed chapters; the batch is not a whole-book transaction. No readiness percentage change.-- **2026-10-12** · Desktop write callbacks and CLI raster exports use the atomic writer too; open readers retain the original bytes, while private Unix modes and symlink targets survive replacement. Permanent tests cover both actual callers. No readiness percentage change.-- **2026-10-12** · Save As, library edits and book collection edits persist prospective values before changing live state; failed writes preserve the document and existing collections. Save a Copy rebases data-source paths for its destination without changing the open document. No readiness percentage change.+- **2026-10-12** · The Effects dialog, as in InDesign: Object › Effects (Transparency…, Drop Shadow… and the rest, and their shortcuts) and the Effects panel's fx button open it on the chosen effect, turned on. Transparency and every effect in one window, in the document's units, with X/Y offsets, Preview on the page, Cancel putting things back, and OK as one undo step (`object.effects`). Shadows default to InDesign's 120° light angle. No readiness percentage change.+- **2026-10-12** · Editing type on a path: the Type tool clicks, drags and double-clicks along the curve (the character under the pointer, not one on the straightened line), a click on the letters themselves hits the frame, and the caret and highlight bend with the path. No readiness percentage change.+- **2026-10-12** · Type on a path has start and end brackets, as in InDesign: selected path type shows them across the path, and dragging either with the Selection or Direct Selection tool moves where the text starts or ends (text past the end bracket is overset). `type.pathOptions {end}`; IDML reads and writes EndBracket. No readiness percentage change.+- **2026-10-12** · The Pen tool continues an open path from either end point, as in InDesign: the cursor shows it over an end point, a click there carries on drawing that path, a drag first reshapes the end point's direction lines, and the other end closes it. Object › Paths › Reverse Path (`path.reverse`); `path.setAnchor`; `path.appendAnchor` and `path.close` take a subpath. No readiness percentage change.+- **2026-10-12** · The Eyedropper puts a colour sampled from an image on the stroke when the toolbox's Stroke box is in front, as in InDesign (a line takes it on its stroke). No readiness percentage change.- **2026-10-12** · Window close and application/menu Quit ask about unsaved documents; later Cancel keeps every tab open, including earlier Don't Save choices. Approvals are rechecked after edits. Cancelable macOS Dock Quit remains open (#544). No readiness percentage change.- **2026-10-12** · Each running app keeps recovery data in its own locked folder; current folder and lock ownership are checked before writes and cleanup. Failed isolation disables recovery with a warning instead of sharing document IDs. No readiness percentage change.- **2026-10-12** · Native engine saves and exports replace files atomically; failed writes retain the original, private staging preserves Unix permissions, and valid long filenames work. Desktop Services and CLI raster exports remain separate follow-ups. No readiness percentage change.diff --cc crates/compose/src/cache.rsindex 5f59af967,7388a9aed..0632e1b66--- a/crates/compose/src/cache.rs+++ b/crates/compose/src/cache.rs@@@ -14,9 -13,28 +14,29 @@@ use designcraft_doc::{Document, Item, Suse crate::vars::RunningIndex;use crate::{ComposeOptions, ComposedStory};- /// A story, composed for one absolute page (parent-page items) or for its own frames (`None`),- /// with other stories' anchored objects wrapping it (`true`) or not.- type Key = (StoryId, Option<usize>, bool);+ /// Where a story's frames are shown, which decides what its page-number markers and variables+ /// read.+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+ pub enum ShownOn {+ /// In its own frames.+ #[default]+ Own,+ /// As a parent item on this absolute document page.+ Page(usize),+ /// As a base parent's item on this parent spread (index into `parents`): markers show that+ /// parent's prefix.+ Parent(usize),+ }++ impl From<Option<usize>> for ShownOn {+ fn from(page: Option<usize>) -> Self {+ page.map_or(ShownOn::Own, ShownOn::Page)+ }+ }+-/// A story, composed for where it is shown.-type Key = (StoryId, ShownOn);++/// A story, composed for where it is shown, with other stories' anchored objects wrapping it++/// (`true`) or not.++type Key = (StoryId, ShownOn, bool);struct Entry {sig: Vec<usize>,@@@ -63,29 -81,21 +83,38 @@@ impl Cache/// `None` for a story's own frames. Pages are identified by index, not name: names repeat when/// sections restart their numbering.pub fn get(&self, doc: &Document, sid: StoryId, page: Option<usize>) -> Arc<ComposedStory> {- self.get_with(doc, sid, page, true)+ self.get_on(doc, sid, page.into())+ }++ /// [`Cache::get`] for any [`ShownOn`].+ pub fn get_on(&self, doc: &Document, sid: StoryId, on: ShownOn) -> Arc<ComposedStory> {++ self.get_with(doc, sid, on, true)+ }+- /// [`Cache::get`], wrapped by other stories' anchored objects only when `cross` is set.- fn get_with(&self, doc: &Document, sid: StoryId, page: Option<usize>, cross: bool) -> Arc<ComposedStory> {++ /// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set.++ fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool) -> Arc<ComposedStory> {let Some(story) = doc.stories.get(&sid) else { return Arc::new(ComposedStory { story: sid, ..Default::default() }) };- let (mut sig, keep_items) = signature(doc, story);- let key = (sid, on);+ let (mut sig, mut keep_items) = signature(doc, story);+ let neighbours = if cross { crate::wrap::neighbours(doc, sid) } else { Vec::new() };+ let mut keep_stories = Vec::new();+ for n in &neighbours {+ if let Some(ns) = doc.stories.get(n) {+ let (s, k) = signature(doc, ns);+ sig.push(usize::MAX - 1);+ sig.extend(s);+ keep_items.extend(k);+ keep_stories.push(ns.clone());+ }+ }- let key = (sid, page, !neighbours.is_empty());++ let key = (sid, on, !neighbours.is_empty());// The key holds the page's index, which a renumbering doesn't change: its name (section// start number, style, prefix) is part of the signature.- let page_name = page.map(|p| doc.page_name(p));+ let (page_name, page) = match on {+ ShownOn::Own => (None, None),+ ShownOn::Page(p) => (Some(doc.page_name(p)), Some(p)),+ ShownOn::Parent(pi) => (doc.parents.get(pi).and_then(|sp| sp.parent.as_ref()).map(|i| i.prefix.clone()), None),+ };+ let section_marker = page.map(|p| crate::section_marker(doc, p));if let Some(name) = &page_name {use std::hash::{Hash, Hasher};let mut h = std::collections::hash_map::DefaultHasher::new();@@@ -181,11 -180,9 +210,11 @@@if g.0.len() > 4096 {g.0.retain(|_, e| stamp - e.stamp < 64);}- let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items), out: out.clone(), stamp });+ let replaced = g.0.insert(key, Entry { sig, _keep: (story.clone(), doc.styles.clone(), keep_items, keep_stories), out: out.clone(), stamp });drop(g);+ // Only the composition that is shown (not one made for another story's wrap).- if key.1.is_none()+ if key.1 == ShownOn::Own+ && cross&& let Some(old) = replaced{self.previous.lock().unwrap_or_else(|e| e.into_inner()).insert(sid, (old.sig, old.out));@@@ -202,12 -199,10 +231,12 @@@let matches = |s: &[usize]| s.len() >= sig.len() && s[..sig.len()] == sig[..];{let g = self.map.lock().unwrap_or_else(|e| e.into_inner());- if let Some(e) = g.0.get(&(sid, ShownOn::Own))- && matches(&e.sig)- {- return Some(e.out.clone());+ for cross in [true, false] {- if let Some(e) = g.0.get(&(sid, None, cross))++ if let Some(e) = g.0.get(&(sid, ShownOn::Own, cross))+ && matches(&e.sig)+ {+ return Some(e.out.clone());+ }}}let g = self.previous.lock().unwrap_or_else(|e| e.into_inner());@@@ -252,15 -247,6 +281,15 @@@out}+ /// Story `sid` composed for the wrap of its anchored objects in other stories: without other+ /// stories' anchored objects (no cycles), and outside the cache when it needs the document-wide+ /// indexes (they compose every story).+ fn neighbour(&self, doc: &Document, sid: StoryId) -> Arc<ComposedStory> {+ let indexed =+ doc.stories.get(&sid).is_some_and(|st| crate::xref::has_xrefs(st) || (crate::vars::has_vars(st) && crate::vars::has_running(doc, st)));- if indexed { Arc::new(crate::wrap::compose_among(doc, sid, &ComposeOptions::default(), &[])) } else { self.get_with(doc, sid, None, false) }++ if indexed { Arc::new(crate::wrap::compose_among(doc, sid, &ComposeOptions::default(), &[])) } else { self.get_with(doc, sid, ShownOn::Own, false) }+ }+pub fn clear(&self) {self.map.lock().unwrap_or_else(|e| e.into_inner()).0.clear();*self.running.lock().unwrap_or_else(|e| e.into_inner()) = None;diff --cc crates/compose/src/lib.rsindex 23a0938bc,91ea88d47..bb6c59fdb--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@@ -38,20 -29,18 +38,20 @@@ use std::rc::Rcuse std::sync::{Arc, Mutex};use designcraft_doc::{- Align, Composer, Document, FirstBaseline, GridAlign, ItemId, ParaProps, SpanColumns, StartParagraph, Story, StoryId, TabAlign, TextFrameOptions,- VerticalJustification, WrapMode, story,+ Align, Content, Document, FirstBaseline, GridAlign, Item, ItemId, ListAlign, ListCounter, ParaProps, SpanColumns, StartParagraph, Story, StoryId,+ TabAlign, TextFrameOptions, VerticalJustification, WrapMode, WrapSide, story,};use designcraft_fonts::{FontDb, ScopedFonts};-use designcraft_geom::{Point, Rect};+use designcraft_geom::{Affine, Point, Rect};use crate::breaker::{Break, Spacing};- pub use crate::cache::Cache;+ pub use crate::cache::{Cache, ShownOn};use crate::notes::Notes;-pub use crate::notes::{find_note, hit_note, note_caret};+pub use crate::notes::{find_note, hit_note, hit_note_with, note_caret};+pub use crate::outline::FrameOutline;+use crate::parabox::ParaBox;use crate::shape::{Glyph, StyleTable, SubstCtx};-pub use crate::table::{PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_cell};+pub use crate::table::{BorderHit, PlacedCell, StrokeSeg, TableFrag, cell_caret, find_cell, hit_border, hit_cell, hit_cell_with};/// Character appearance shared by many glyphs (indexed from [`PlacedGlyph::style`]).#[derive(Clone, Debug, PartialEq)]diff --cc crates/doc/src/build.rsindex 3d47abc7e,ff510b41a..b5bc56ff5--- a/crates/doc/src/build.rs+++ b/crates/doc/src/build.rs@@@ -564,88 -545,99 +564,168 @@@ impl Document/// Parent page (spread index, page index) to show behind document page `abs`.pub fn parent_page_for(&self, abs: usize) -> Option<(usize, usize)> {- let page = self.page(abs)?;+ self.parent_page_of(self.page(abs)?)+ }++ /// Parent page (spread index, page index) applied to `page`: the page on its side of its+ /// parent spread.+ pub fn parent_page_of(&self, page: &Page) -> Option<(usize, usize)> {let pi = self.parent_index(page.parent?)?;- Some((pi, shown_parent_page(self.parents.get(pi)?.pages.len(), page.side)?))+ // A parent spread can come without pages from a file.+ Some((pi, self.parents.get(pi)?.parent_page_for_side(page.side)?))+ }++ /// The parent page applied to `page`.+ pub fn parent_page(&self, page: &Page) -> Option<&Page> {+ let (pi, qi) = self.parent_page_of(page)?;+ self.parents.get(pi)?.pages.get(qi)+ }++ /// Ruler guides `page` shows from its parent page, moved from the parent page's place in its+ /// spread to `page`'s place in its own. They stay stored on the parent page.+ pub fn parent_guides<'a>(&'a self, page: &Page) -> impl Iterator<Item = Guide> + 'a {+ let src = self.parent_page(page);+ let dx = src.map_or(0.0, |q| page.x - q.x);+ src.into_iter().flat_map(|q| q.guides.iter()).map(move |g| {+ let mut g = g.clone();+ if g.orientation == Orientation::Vertical {+ g.position += dx;+ }+ g+ })+ }++ /// Give every document page without local margins its parent page's margins and columns.+ pub fn sync_parent_margins(&mut self) {+ for si in 0..self.spreads.len() {+ for pi in 0..self.spreads[si].pages.len() {+ let Some(page) = self.spreads[si].pages.get(pi) else { continue };+ if page.local_margins {+ continue;+ }+ let Some(src) = self.parent_page(page).filter(|q| !q.same_margins(page)).map(|q| (q.margins, q.columns.clone())) else {+ continue;+ };+ if let Some(page) = Arc::make_mut(&mut self.spreads[si]).pages.get_mut(pi) {+ (page.margins, page.columns) = src;+ }+ }+ }+ }++ /// Mark document pages whose margins or columns differ from their parent page's as local, so+ /// that a later sync keeps them (documents saved before pages tracked local margins).+ pub fn mark_differing_margins_local(&mut self) {+ for si in 0..self.spreads.len() {+ for pi in 0..self.spreads[si].pages.len() {+ let Some(page) = self.spreads[si].pages.get(pi) else { continue };+ if page.local_margins || self.parent_page(page).is_none_or(|q| q.same_margins(page)) {+ continue;+ }+ if let Some(page) = Arc::make_mut(&mut self.spreads[si]).pages.get_mut(pi) {+ page.local_margins = true;+ }+ }+ }+ }++ /// Let document pages whose margins and columns match their parent page's follow it again,+ /// after an edit that set every page and parent page alike (Document Setup's margins).+ pub fn unmark_matching_local_margins(&mut self) {+ for si in 0..self.spreads.len() {+ for pi in 0..self.spreads[si].pages.len() {+ let Some(page) = self.spreads[si].pages.get(pi) else { continue };+ if !page.local_margins || !self.parent_page(page).is_some_and(|q| q.same_margins(page)) {+ continue;+ }+ if let Some(page) = Arc::make_mut(&mut self.spreads[si]).pages.get_mut(pi) {+ page.local_margins = false;+ }+ }+ }}++ /// Parent `pi` and the parents it is based on, base first: `[A, B]` for B based on A.+ /// A dangling id, a repeated parent or [`MAX_PARENT_DEPTH`] ends the walk.+ pub fn parent_chain(&self, pi: usize) -> Vec<usize> {+ let mut out = Vec::new();+ let mut cur = Some(pi);+ while let Some(i) = cur {+ let Some(ps) = self.parents.get(i) else { break };+ if out.contains(&i) || out.len() >= MAX_PARENT_DEPTH {+ break;+ }+ out.push(i);+ cur = ps.parent.as_ref().and_then(|info| info.based_on).and_then(|b| self.parent_index(b));+ }+ out.reverse();+ out+ }++ /// Parent pages drawn behind page `page` of spread `sr`, back to front, as (parent index,+ /// parent page index). A document page shows its parent and that parent's bases; a parent page+ /// shows the parents its spread is based on.+ pub fn shown_parent_pages(&self, sr: SpreadRef, page: usize) -> Vec<(usize, usize)> {+ let Some(pg) = self.spread(sr).and_then(|sp| sp.pages.get(page)) else { return Vec::new() };+ let chain = match sr {+ SpreadRef::Doc(_) => pg.parent.and_then(|id| self.parent_index(id)).map(|pi| self.parent_chain(pi)).unwrap_or_default(),+ SpreadRef::Parent(pi) => {+ let mut c = self.parent_chain(pi);+ // The spread's own items are not part of what shows behind it.+ if c.last() == Some(&pi) {+ c.pop();+ }+ c+ }+ };- chain.into_iter().filter_map(|i| Some((i, shown_parent_page(self.parents.get(i)?.pages.len(), pg.side)?))).collect()++ chain.into_iter().filter_map(|i| Some((i, self.parents.get(i)?.parent_page_for_side(pg.side)?))).collect()+ }++ /// Whether basing parent `pi` on `base` would make a `based_on` cycle (or names no parent).+ pub fn parent_base_cycles(&self, pi: usize, base: SpreadId) -> bool {+ let Some(mut cur) = self.parent_index(base) else { return true };+ // Not `parent_chain`: its depth cap would miss a long cycle. Every parent is visited at most once.+ let mut seen = std::collections::HashSet::new();+ loop {+ if cur == pi {+ return true;+ }+ if !seen.insert(cur) || seen.len() > self.parents.len() {+ return false;+ }+ let next = self.parents.get(cur).and_then(|ps| ps.parent.as_ref()).and_then(|info| info.based_on).and_then(|b| self.parent_index(b));+ let Some(n) = next else { return false };+ cur = n;+ }+ }++ /// Clear `based_on` links that name a missing parent or close a cycle (hand-edited or damaged+ /// files). Returns one warning per link cleared.+ pub fn fix_parent_bases(&mut self) -> Vec<String> {+ let mut warnings = Vec::new();+ for pi in 0..self.parents.len() {+ let Some(ps) = self.parents.get(pi) else { continue };+ let Some(base) = ps.parent.as_ref().and_then(|info| info.based_on) else { continue };+ let label = ps.parent.as_ref().map(ParentInfo::label).unwrap_or_default();+ let why = if self.parent_index(base).is_none() {+ "names a missing parent"+ } else if self.parent_base_cycles(pi, base) {+ "makes a cycle"+ } else {+ continue;+ };+ if let Some(info) = self.parents.get_mut(pi).map(Arc::make_mut).and_then(|ps| ps.parent.as_mut()) {+ info.based_on = None;+ }+ warnings.push(format!("parent {label}: Based on Parent {why}; it was set to [None]"));+ }+ warnings+ }}+ /// Deepest `based_on` chain followed.+ pub const MAX_PARENT_DEPTH: usize = 64;+-/// The page of a parent spread with `count` pages that shows behind a page on `side`: the left-/// page of a facing parent for a left page, otherwise the last page. A parent spread can come-/// without pages from a file.-fn shown_parent_page(count: usize, side: PageSide) -> Option<usize> {- if count >= 2 && side == PageSide::Left { Some(0) } else { count.checked_sub(1) }-}-#[cfg(test)]mod tests {use super::*;diff --cc crates/engine/src/cmd/file.rsindex 7f1936dc1,7cc0fe8e2..f35549562--- a/crates/engine/src/cmd/file.rs+++ b/crates/engine/src/cmd/file.rs@@@ -13,40 -13,18 +13,40 @@@ use crate::{DocState, EngineError, Resupub fn specs() -> Vec<CommandSpec> {vec![cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"),- "{preset?: \"Letter\"|\"A4\"|…, width?, height?, pages?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, title?}",+ "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?}",always, file_new),cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample),- cmd!(query "file.presets", "Document Presets", [], None, "{}", always, |_, _| Ok(serde_json::to_value(PRESETS).unwrap_or_default())),+ cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true`)", always, |s, _| {+ let mut presets: Vec<Value> = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect();+ presets.extend(+ s.prefs+ .document_presets+ .iter()+ .map(|p| json!({"name": p.title, "intent": p.intent, "width": p.width, "height": p.height, "units": p.units, "saved": true})),+ );+ Ok(Value::Array(presets))+ }),+ cmd!(noundo "file.savePreset", "Save Document Preset", [], None,+ "{name, …the settings file.new takes} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused",+ always, save_preset),+ cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| {+ let name = str_param(p, "name").unwrap_or_default().trim().to_string();+ let before = s.prefs.document_presets.len();+ s.prefs.document_presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if s.prefs.document_presets.len() == before {+ return Err(bad("file.deletePreset", format!("no saved preset `{name}`")));+ }+ ok()+ }),cmd!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),- "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile and, for IDML and InDesign files, package parts missing}",- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, Based on Parent links cleared (and, for .idml, package parts missing)}",++ "{path} — a DesignCraft or IDML file (recognised by its content, so the extension may be missing), or an InDesign .indd/.indt (recognised by its signature or extension, converted to IDML; its conversion warnings join `warnings`); the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped, GREP styles whose pattern can't compile, Based on Parent links cleared and, for IDML and InDesign files, package parts missing}",always, file_open),- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt", always, file_open_bytes),- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package → {index, warnings}", always, file_open_bytes),- cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?}", has_doc, file_save),- cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path}", has_doc, file_save),- cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state", has_doc, |s, p| {- let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?.to_string();++ cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON, an IDML package or an InDesign .indd/.indt → {index, warnings}", always, file_open_bytes),+ cmd!(noundo "file.save", "Save", ["File"], Some("Cmd+S"), "{path?} — a `path` without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveAs", "Save As…", ["File"], Some("Cmd+Shift+S"), "{path} — a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, file_save),+ cmd!(noundo "file.saveACopy", "Save a Copy…", ["File"], None, "{path} — writes the document without changing which file it is or its unsaved state; a path without the .designcraft extension gets it → {path: the file written, bytes}", has_doc, |s, p| {+ let path = str_param(p, "path").ok_or_else(|| bad("file.saveACopy", "missing `path`"))?;+ let path = with_document_extension(path);let mut copy = (*s.doc()?.doc).clone();super::datamerge::refresh_relative_paths(&mut copy, std::path::Path::new(&path));let bytes = to_bytes(©);@@@ -135,85 -113,23 +135,93 @@@ pub fn to_bytes(d: &Document) -> Vec<u8designcraft_format::save(d).unwrap_or_default()}+/// `path` ending in `.designcraft`: the extension is added when it is missing or another one, so+/// the file opens from the file manager. A path without a file name is left for the write to fail.+pub fn with_document_extension(path: &str) -> String {+ let p = std::path::Path::new(path);+ let ext = p.extension().and_then(|e| e.to_str());+ if p.file_name().is_none() || ext.is_some_and(|e| e.eq_ignore_ascii_case(designcraft_format::EXTENSION)) {+ return path.to_string();+ }+ format!("{path}.{}", designcraft_format::EXTENSION)+}++/// Whether `bytes` are a document `file.open` reads: a DesignCraft package or an IDML package.+pub fn is_document(bytes: &[u8]) -> bool {+ designcraft_idml::is_idml(bytes) || designcraft_format::is_designcraft(bytes)+}+pub fn from_bytes(b: &[u8]) -> Result<Document> {- designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))+ load_bytes(b).map(|(d, _)| d)+ }++ /// Read `.designcraft` bytes and repair what a hand-edited file can get wrong without failing the+ /// open, with a warning for each repair.+ fn load_bytes(b: &[u8]) -> Result<(Document, Vec<String>)> {+ let mut d = designcraft_format::load(b).map_err(|e| EngineError::Other(e.to_string()))?;+ let warnings = d.fix_parent_bases();+ Ok((d, warnings))}+/// The longest saved preset name, and how many presets are kept.+const MAX_PRESET_NAME: usize = 100;+const MAX_PRESETS: usize = 500;++/// A built-in document preset or a saved one, by name (case ignored).+fn find_preset(s: &Session, name: &str) -> Option<NewDocument> {+ NewDocument::from_preset(name).or_else(|| s.prefs.document_presets.iter().find(|p| p.title.eq_ignore_ascii_case(name.trim())).cloned())+}+fn file_new(s: &mut Session, p: &Value) -> Result<Value> {let mut nd = match str_param(p, "preset") {- Some(name) => NewDocument::from_preset(name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,+ Some(name) => find_preset(s, name).ok_or_else(|| bad("file.new", format!("unknown preset `{name}`")))?,None => NewDocument::default(),};+ apply_settings(&mut nd, p);+ check_size("file.new", &nd)?;+ s.untitled += 1;+ nd.title = str_param(p, "title").map(str::to_string).unwrap_or_else(|| format!("Untitled-{}", s.untitled));+ let d = Document::new(&nd);+ let i = s.add_document(DocState::new(d, None));+ Ok(json!({"index": i}))+}++fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {+ let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("file.savePreset", "missing `name`"))?.to_string();+ if name.chars().count() > MAX_PRESET_NAME {+ return Err(bad("file.savePreset", format!("a preset name has at most {MAX_PRESET_NAME} characters")));+ }+ if NewDocument::from_preset(&name).is_some() {+ return Err(bad("file.savePreset", format!("`{name}` is a built-in preset")));+ }+ let mut nd = NewDocument::default();+ apply_settings(&mut nd, p);+ check_size("file.savePreset", &nd)?;+ nd.title = name.clone();+ let presets = &mut s.prefs.document_presets;+ presets.retain(|x| !x.title.eq_ignore_ascii_case(&name));+ if presets.len() >= MAX_PRESETS {+ return Err(bad("file.savePreset", format!("at most {MAX_PRESETS} saved presets")));+ }+ presets.push(nd);+ Ok(json!({"name": name}))+}++fn check_size(cmd: &str, nd: &NewDocument) -> Result<()> {+ if !(nd.width > 0.0 && nd.height > 0.0 && nd.width <= 15552.0 && nd.height <= 15552.0) {+ return Err(bad(cmd, "page size out of range (0 < size ≤ 216 in)"));+ }+ Ok(())+}++/// The document settings in `p` (as file.new takes them) over `nd`.+fn apply_settings(nd: &mut NewDocument, p: &Value) {+ if let Some(intent) = p.get("intent").and_then(|v| serde_json::from_value(v.clone()).ok()) {+ nd.intent = intent;+ }+ if let Some(units) = p.get("units").and_then(|v| serde_json::from_value(v.clone()).ok()) {+ nd.units = units;+ }nd.width = f64_or(p, "width", nd.width);nd.height = f64_or(p, "height", nd.height);nd.pages = p.get("pages").and_then(Value::as_u64).map(|v| v as usize).unwrap_or(nd.pages).clamp(1, 9999);@@@ -261,22 -169,15 +269,23 @@@ fn file_open(s: &mut Session, p: &Valuelet path = str_param(p, "path").ok_or_else(|| bad("file.open", "missing `path`"))?;#[cfg(not(target_arch = "wasm32"))]{- if path.to_ascii_lowercase().ends_with(".idml") {+ let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ // The content decides first: a file's extension may be missing or wrong. The extension+ // then routes files whose content isn't recognised to the reader that explains why.+ let ext = std::path::Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase();+ let native = designcraft_format::is_designcraft(&bytes) || bytes.trim_ascii_start().starts_with(b"{");+ if designcraft_idml::is_idml(&bytes) || (!native && (super::interchange::is_indd(path, &bytes) || ext == "idml")) {return super::interchange::open_idml(s, p);}- let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;+ if !native && ext != designcraft_format::EXTENSION {+ return Err(bad("file.open", format!("{path}: not a DesignCraft or IDML file")));+ }- let mut d = from_bytes(&bytes)?;+ let (mut d, mut warnings) = load_bytes(&bytes)?;super::interchange::resolve_packaged_links(&mut d, std::path::Path::new(path).parent());super::datamerge::resolve_sources_on_open(&mut d, Some(std::path::Path::new(path)));- let (fonts, faces, mut warnings) = load_document_fonts(&mut d, path);+ let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path);+ warnings.extend(font_warnings);+ warnings.extend(super::style::grep_style_warnings(&d));let mut st = DocState::new(d, Some(path.to_string()));st.fonts = fonts;let i = s.add_document(st);@@@ -328,12 -229,11 +337,12 @@@ fn document_fonts_folder(dir: &std::patfn file_open_bytes(s: &mut Session, p: &Value) -> Result<Value> {let b = base64_decode(str_param(p, "base64").unwrap_or(""));- // IDML packages are recognised by their stored `mimetype` first entry.- if designcraft_idml::is_idml(&b) {+ // IDML packages are recognised by their stored `mimetype` first entry, INDD files by their+ // signature (or their name).+ if designcraft_idml::is_idml(&b) || super::interchange::is_indd(str_param(p, "name").unwrap_or_default(), &b) {return super::interchange::open_idml(s, p);}- let mut d = from_bytes(&b)?;+ let (mut d, warnings) = load_bytes(&b)?;super::datamerge::resolve_sources_on_open(&mut d, None);if let Some(n) = str_param(p, "name") {d.title = n.to_string();diff --cc crates/engine/src/cmd/layout.rsindex b0fa92b23,6a8519353..8f2488091--- a/crates/engine/src/cmd/layout.rs+++ b/crates/engine/src/cmd/layout.rs@@@ -196,42 -179,22 +196,51 @@@ pub fn specs() -> Vec<CommandSpec>Ok(json!({"id": id.0, "prefix": prefix}))})}),+ cmd!(+ noundo "layout.parents.edit",+ "Edit Parents",+ [],+ None,+ "{on?: bool, parent?: id|\"A-Parent\"|\"A\"} — show parent spreads on the canvas; `parent` shows that parent (and implies on). Turning on without `parent` shows the first parent",+ has_doc,+ |s, p| {+ const ID: &str = "layout.parents.edit";+ let doc = s.doc()?.doc.clone();+ let parent = match p.get("parent") {+ None | Some(Value::Null) => None,+ v => match parent_ref(ID, &doc, v)? {+ Some(Some(id)) => Some(id),+ _ => return Err(bad(ID, "`parent` names a parent to show")),+ },+ };+ let st = s.doc_mut()?;+ let was = st.editing_parents;+ let on = p.get("on").and_then(Value::as_bool).unwrap_or(parent.is_some() || !was);+ st.editing_parents = on;+ st.selection = Default::default();+ st.bump_revision();+ // The parent to show: the one asked for, or the first when editing starts.+ let index = match parent {+ Some(id) => doc.parent_index(id),+ None if !was && !doc.parents.is_empty() => Some(0),+ None => None,+ };+ let shown = index.filter(|_| on);+ if let Some(i) = shown {+ s.ui_requests.push(crate::UiRequest::View { params: json!({"showSpread": designcraft_doc::SpreadRef::Parent(i)}) });+ }+ Ok(json!({"on": on, "parent": shown.and_then(|i| doc.parents.get(i)).map(|x| x.id.0)}))+ }+ ),+ cmd!(+ "layout.parents.options",+ "Parent Options…",+ [],+ None,- "{parent: \"B\" (prefix or label), basedOn: \"A\" | null (= [None])} — the parent shows its base's items under its own, and so do the pages that use it → {parent, basedOn}",++ "{parent: id|\"B-Parent\"|\"B\", basedOn: id|\"A-Parent\"|\"A\"|null (= [None])} — the parent shows its base's items under its own, and so do the pages that use it → {parent, basedOn}",+ has_doc,+ parent_options+ ),- cmd!(noundo "layout.parents.edit", "Edit Parents", [], None, "{on: bool} — show parent spreads on the canvas", has_doc, |s, p| {- let st = s.doc_mut()?;- st.editing_parents = p.get("on").and_then(Value::as_bool).unwrap_or(!st.editing_parents);- st.selection = Default::default();- st.revision += 1;- ok()- }),cmd!("layout.marginsAndColumns","Margins and Columns…",@@@ -707,37 -628,41 +716,62 @@@ fn parent_spread_index(d: &designcraft_}}+/// A parent named by a command parameter: its id (a number), its full label (`"A-Parent"`), or+/// its prefix (`"A"`) when only one parent has it. `null` or `"[None]"` → `Some(None)` (no parent);+/// missing → `None` (the command's default). Unknown or ambiguous names are errors, so a typo never+/// clears a page's parent.+fn parent_ref(cmd: &str, d: &designcraft_doc::Document, v: Option<&Value>) -> Result<Option<Option<SpreadId>>> {+ let Some(v) = v else { return Ok(None) };+ match v {+ Value::Null => Ok(Some(None)),+ Value::String(s) if s == "[None]" => Ok(Some(None)),+ Value::Number(n) => {+ let id = n.as_u64().ok_or_else(|| bad(cmd, format!("no parent with id {n}")))?;+ d.parents.iter().find(|p| p.id.0 == id).map(|p| Some(Some(p.id))).ok_or_else(|| bad(cmd, format!("no parent with id {id}")))+ }+ Value::String(s) => {+ let by = |f: &dyn Fn(&designcraft_doc::ParentInfo) -> bool| -> Vec<SpreadId> {+ d.parents.iter().filter(|p| p.parent.as_ref().is_some_and(f)).map(|p| p.id).collect()+ };+ let mut hits = by(&|i| i.label() == *s);+ if hits.is_empty() {+ hits = by(&|i| i.prefix == *s);+ }+ match hits.as_slice() {+ [id] => Ok(Some(Some(*id))),+ [] => Err(bad(cmd, format!("no parent named `{s}`"))),+ _ => Err(bad(cmd, format!("more than one parent is named `{s}`: give its id"))),+ }+ }+ _ => Err(bad(cmd, "`parent` is a parent id, a parent name or null")),+ }+}++ /// Layout › Pages › Parent Options: Based on Parent. A base that would make a cycle is refused.+ fn parent_options(s: &mut crate::Session, p: &Value) -> Result<Value> {+ const CMD: &str = "layout.parents.options";+ let d = &s.doc()?.doc;- let find = |name: &str| d.parents.iter().position(|x| x.parent.as_ref().is_some_and(|i| i.prefix == name || i.label() == name));- let name = str_param(p, "parent").ok_or_else(|| bad(CMD, "missing `parent`"))?;- let pi = find(name).ok_or_else(|| bad(CMD, format!("no parent `{name}`")))?;- let base = match p.get("basedOn") {- None => return Err(bad(CMD, "missing `basedOn` (a parent, or null for [None])")),- Some(Value::Null) => None,- Some(Value::String(b)) if b == "[None]" => None,- Some(Value::String(b)) => {- let bi = find(b).ok_or_else(|| bad(CMD, format!("no parent `{b}`")))?;- Some(d.parents.get(bi).map(|x| x.id).ok_or_else(|| bad(CMD, format!("no parent `{b}`")))?)- }- Some(v) => return Err(bad(CMD, format!("`basedOn` must be a parent name or null, not {v}"))),- };++ let Some(Some(id)) = parent_ref(CMD, d, p.get("parent"))? else { return Err(bad(CMD, "`parent` names the parent to change")) };++ let pi = d.parent_index(id).ok_or_else(|| bad(CMD, format!("no parent with id {}", id.0)))?;++ let base = parent_ref(CMD, d, p.get("basedOn"))?.ok_or_else(|| bad(CMD, "missing `basedOn` (a parent, or null for [None])"))?;+ let label = |d: &designcraft_doc::Document, i: usize| d.parents.get(i).and_then(|x| x.parent.as_ref()).map(|i| i.label());+ if let Some(b) = base+ && d.parent_base_cycles(pi, b)+ {- let b = str_param(p, "basedOn").unwrap_or_default();++ let (name, b) = (label(d, pi).unwrap_or_default(), d.parent_index(b).and_then(|i| label(d, i)).unwrap_or_default());+ return Err(bad(CMD, format!("{name} cannot be based on {b}: that would make a cycle")));+ }+ let out = json!({"parent": label(d, pi), "basedOn": base.and_then(|b| d.parent_index(b)).and_then(|i| label(d, i))});+ if d.parents.get(pi).and_then(|x| x.parent.as_ref()).and_then(|i| i.based_on) == base {+ return Ok(out);+ }+ s.edit(|d, _| {+ let info = d.parents.get_mut(pi).map(std::sync::Arc::make_mut).and_then(|x| x.parent.as_mut()).ok_or_else(|| bad(CMD, "no such parent"))?;+ info.based_on = base;+ Ok(out)+ })+ }+#[allow(dead_code)]fn _r(_: Result<()>) {}@@@ -1410,192 -966,104 +1444,294 @@@ mod adjust_tests}}+#[cfg(test)]+mod spread_rotation_input_tests {+ use serde_json::json;++ #[test]+ fn quarter_turns_work_and_other_angles_are_rejected_without_mutation() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let rotation = |s: &crate::Session| s.doc().unwrap().doc.spreads[0].pages[0].view_rotation;+ for bad in [json!(45), json!(-45), json!(91), json!("90"), json!(0.5)] {+ assert!(s.execute("layout.rotateSpreadView", &json!({"angle": bad})).is_err(), "{bad}");+ assert_eq!(rotation(&s), 0, "invalid input must not change the view");+ }+ s.execute("layout.rotateSpreadView", &json!({"angle": 90})).unwrap();+ assert_eq!(rotation(&s), 1);+ s.execute("layout.rotateSpreadView", &json!({"angle": -90})).unwrap();+ assert_eq!(rotation(&s), 0);+ s.execute("layout.rotateSpreadView", &json!({"angle": 180})).unwrap();+ assert_eq!(rotation(&s), 2);+ s.execute("layout.rotateSpreadView", &json!({"angle": 0})).unwrap();+ assert_eq!(rotation(&s), 0, "zero resets the spread view");+ }+}++#[cfg(test)]+mod layer_options_tests {+ use serde_json::json;++ #[test]+ fn layer_set_sets_every_field_and_rejects_bad_names() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let first = s.doc().unwrap().doc.layers[0].id.0;+ let id = s.execute("layer.new", &json!({"name": "Art"})).unwrap()["id"].as_u64().unwrap();+ let all = json!({"id": id, "name": " Artwork ", "color": "Gold", "visible": false, "locked": true, "printable": false,+ "showGuides": false, "suppressWrapWhenHidden": true});+ s.execute("layer.set", &all).unwrap();+ let l = s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).cloned().unwrap();+ assert_eq!(l.name, "Artwork");+ assert_eq!(l.color, [255, 153, 0]);+ assert!(!l.visible && l.locked && !l.printable && !l.show_guides && l.suppress_wrap_when_hidden);+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(s.doc().unwrap().doc.layer(designcraft_doc::LayerId(id)).unwrap().name, "Art", "one undo step");+ let first_name = s.doc().unwrap().doc.layers.iter().find(|l| l.id.0 == first).unwrap().name.clone();+ let before = s.doc().unwrap().doc.layers.clone();+ for p in [+ json!({"id": id, "name": ""}),+ json!({"id": id, "name": " "}),+ json!({"id": id, "name": first_name}),+ json!({"id": id, "name": "Fine", "color": "Plaid"}),+ json!({"id": id, "color": [300, 0, 0]}),+ json!({"id": id, "visible": "yes"}),+ json!({"id": 999_999, "name": "Ghost"}),+ ] {+ assert!(s.execute("layer.set", &p).is_err(), "{p}");+ }+ assert_eq!(s.doc().unwrap().doc.layers, before);+ // Keeping its own name is fine.+ s.execute("layer.set", &json!({"id": id, "name": "Art", "color": [1, 2, 3]})).unwrap();+ }+}++#[cfg(test)]+mod parent_margin_tests {+ use designcraft_doc::{Document, Margins};+ use serde_json::json;++ use crate::Session;++ fn margins(d: &Document) -> Vec<(Margins, u32, bool)> {+ (0..d.page_count()).filter_map(|i| d.page(i)).map(|p| (p.margins, p.columns.count, p.local_margins)).collect()+ }++ #[test]+ fn document_setup_margins_let_pages_follow_their_parent_page_again() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [1], "margins": 100})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100, "columns": 3})).unwrap();+ s.execute("layout.documentSetup", &json!({"margins": 20})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ let twenty = Margins::uniform(20.0);+ assert_eq!(m, vec![(twenty, 1, false), (twenty, 1, false), (twenty, 3, true)], "own columns stay local");+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (Margins::uniform(50.0), 1, false), "page 2 follows the parent page again");+ assert_eq!(m[2], (twenty, 3, true));+ }++ #[test]+ fn pages_follow_their_parent_pages_margins_unless_set_locally() {+ let mut s = Session::new();+ // Facing: [1] [2 3]; page 3 gets its own margins.+ s.execute("file.new", &json!({"pages": 3})).unwrap();+ s.execute("layout.marginsAndColumns", &json!({"pages": [2], "margins": 100})).unwrap();+ // A's left page: only the left document page follows.+ let left = json!({"top": 10, "bottom": 20, "inside": 30, "outside": 40});+ s.execute("layout.marginsAndColumns", &json!({"parent": "A", "pages": [0], "margins": left, "columns": 2})).unwrap();+ let l = Margins { top: 10.0, bottom: 20.0, inside: 30.0, outside: 40.0 };+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(36.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A's right page: page 1 follows, page 3 keeps its own.+ s.execute("layout.marginsAndColumns", &json!({"parent": "A-Parent", "pages": [1], "margins": 50})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m, vec![(Margins::uniform(50.0), 1, false), (l, 2, false), (Margins::uniform(100.0), 1, true)]);+ // A page inserted after page 1 pushes page 2 to the right: it takes the right parent page's.+ s.execute("layout.pages.insert", &json!({"after": 0, "count": 1, "parent": "A"})).unwrap();+ let m = margins(&s.doc().unwrap().doc);+ assert_eq!(m[1], (l, 2, false), "the new left page");+ assert_eq!(m[2], (Margins::uniform(50.0), 1, false), "old page 2, now a right page");+ assert_eq!(m[3], (Margins::uniform(100.0), 1, true));+ assert!(s.execute("layout.marginsAndColumns", &json!({"parent": "Z", "margins": 10})).is_err());+ }++ #[test]+ fn parent_guides_show_on_pages_but_stay_on_the_parent() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ // A vertical guide 100 pt into A's right page (x = 612 in the parent spread).+ s.execute("guide.add", &json!({"spread": {"kind": "parent", "index": 0}, "page": 1, "orientation": "vertical", "position": 712})).unwrap();+ let d = &s.doc().unwrap().doc;+ let right = d.page(0).unwrap();+ let shown: Vec<f64> = d.parent_guides(right).map(|g| g.position).collect();+ assert_eq!(shown, vec![100.0], "moved to the document page's place");+ assert_eq!(d.parent_guides(d.page(1).unwrap()).count(), 0, "the left page shows A's left page's guides");+ // Not the document page's own: not listed, moved or deleted from there.+ assert_eq!(s.execute("guide.list", &json!({"spread": 0})).unwrap(), json!([]));+ assert!(s.execute("guide.move", &json!({"spread": 0, "page": 0, "index": 0, "position": 50})).is_err());+ assert!(s.execute("guide.delete", &json!({"spread": 0, "page": 0, "index": 0})).is_err());+ }+}++#[cfg(test)]+mod parent_tests {+ use serde_json::json;++ fn parent_of(s: &crate::Session, page: usize) -> Option<u64> {+ s.doc().unwrap().doc.page(page).unwrap().parent.map(|p| p.0)+ }++ #[test]+ fn parents_with_one_prefix_stay_distinct() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ let a = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Parent"})).unwrap()["id"].as_u64().unwrap();+ let b = s.execute("layout.parents.new", &json!({"prefix": "IMG", "name": "Half"})).unwrap()["id"].as_u64().unwrap();+ s.execute("layout.pages.applyParent", &json!({"pages": [0], "parent": b})).unwrap();+ assert_eq!(parent_of(&s, 0), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Half"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(b));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG-Parent"})).unwrap();+ assert_eq!(parent_of(&s, 1), Some(a));+ // A prefix two parents share, or a name no parent has, is an error and changes nothing.+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "IMG"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "Nope"})).is_err());+ assert!(s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": 999_999})).is_err());+ assert_eq!(parent_of(&s, 1), Some(a));+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "[None]"})).unwrap();+ assert_eq!(parent_of(&s, 1), None);+ }++ #[test]+ fn edit_parents_shows_the_named_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let ids: Vec<u64> =+ ["B", "C", "D"].iter().map(|p| s.execute("layout.parents.new", &json!({"prefix": p})).unwrap()["id"].as_u64().unwrap()).collect();+ s.ui_requests.clear();+ let r = s.execute("layout.parents.edit", &json!({"parent": ids[2]})).unwrap();+ assert_eq!(r, json!({"on": true, "parent": ids[2]}));+ assert!(s.doc().unwrap().editing_parents);+ let n = s.doc().unwrap().doc.parent_index(designcraft_doc::SpreadId(ids[2])).unwrap();+ let shown: Vec<_> = s+ .ui_requests+ .iter()+ .filter_map(|r| match r {+ crate::UiRequest::View { params } => params.get("showSpread").cloned(),+ _ => None,+ })+ .collect();+ assert_eq!(shown, vec![json!({"kind": "parent", "index": n})]);+ let r = s.execute("layout.parents.edit", &json!({"on": true, "parent": "C-Parent"})).unwrap();+ assert_eq!(r["parent"], ids[1]);+ assert!(s.execute("layout.parents.edit", &json!({"parent": "Z-Parent"})).is_err());+ let r = s.execute("layout.parents.edit", &json!({"on": false})).unwrap();+ assert_eq!(r, json!({"on": false, "parent": null}));+ assert!(!s.doc().unwrap().editing_parents);+ }+}+++ #[cfg(test)]+ mod parent_base_tests {+ use serde_json::{Value, json};++ fn rect(s: &mut crate::Session, spread: Value, r: [f64; 4], swatch: &str) -> u64 {+ let id = s.execute("frame.create", &json!({"spread": spread, "rect": r, "content": "unassigned"})).unwrap()["id"].as_u64().unwrap();+ s.execute("object.fill", &json!({"ids": [id], "swatch": swatch})).unwrap();+ id+ }++ fn page(s: &crate::Session, abs: usize) -> designcraft_render::Rendered {+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ rr.render_page(&s.doc().unwrap().doc, &s.cache, abs, 1.0, false, &Default::default()).unwrap()+ }++ /// Parent A (black), parent B based on A (cyan, half over A's square), and a page item (paper)+ /// over B's: the page draws A, then B, then its own items.+ #[test]+ fn based_on_parent_draws_base_items_under_parent_items() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"width": 400, "height": 400, "pages": 2, "facingPages": false, "margins": 0})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B", "name": "Opening"})).unwrap();+ rect(&mut s, json!({"kind": "parent", "index": 0}), [0.0, 0.0, 200.0, 200.0], "[Black]");+ rect(&mut s, json!({"kind": "parent", "index": 1}), [100.0, 0.0, 300.0, 200.0], "C=100 M=0 Y=0 K=0");+ rect(&mut s, json!(1), [150.0, 0.0, 190.0, 40.0], "[Paper]");+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();+ let black = |p: [u8; 4]| p[0] < 80 && p[1] < 80 && p[2] < 80;+ let cyan = |p: [u8; 4]| p[0] < 80 && p[1] > 120 && p[2] > 180;+ let paper = |p: [u8; 4]| p[0] > 240 && p[1] > 240 && p[2] > 240;+ assert!(paper(page(&s, 1).pixel(50, 100)), "B alone does not show A's items");++ let r = s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "A"})).unwrap();+ assert_eq!(r, json!({"parent": "B-Opening", "basedOn": "A-Parent"}));+ let img = page(&s, 1);+ assert!(black(img.pixel(50, 100)), "A's item: {:?}", img.pixel(50, 100));+ assert!(cyan(img.pixel(150, 150)), "B's item over A's: {:?}", img.pixel(150, 150));+ assert!(paper(img.pixel(170, 20)), "the page's item over B's: {:?}", img.pixel(170, 20));+ assert!(black(page(&s, 0).pixel(50, 100)) && !cyan(page(&s, 0).pixel(250, 100)), "page 1 uses A only");+ // Parent B itself shows A's items under its own.+ let mut rr = designcraft_render::Renderer::new();+ rr.threads = 0;+ let placed = [designcraft_render::Placed { spread: designcraft_doc::SpreadRef::Parent(1), xf: designcraft_geom::Affine::IDENTITY }];+ let opts = designcraft_render::RenderOptions { background: Some([255, 255, 255, 255]), ..Default::default() };+ let img = rr.render(&s.doc().unwrap().doc, &s.cache, &placed, 400, 400, designcraft_geom::Affine::IDENTITY, &opts);+ assert!(black(img.pixel(50, 100)) && cyan(img.pixel(150, 150)), "{:?} {:?}", img.pixel(50, 100), img.pixel(150, 150));+ let inspect = s.execute("document.inspect", &json!({})).unwrap();+ assert_eq!(inspect["parents"][1]["basedOn"], "A-Parent");+ assert_eq!(inspect["parents"][0]["basedOn"], Value::Null);++ // Cycles are refused.+ assert!(s.execute("layout.parents.options", &json!({"parent": "A", "basedOn": "B"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "B-Opening"})).is_err());+ assert!(s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "Z"})).is_err());++ s.execute("edit.undo", &json!({})).unwrap();+ assert!(paper(page(&s, 1).pixel(50, 100)), "undo clears Based on Parent");+ s.execute("edit.redo", &json!({})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": null})).unwrap();+ assert_eq!(s.execute("document.inspect", &json!({})).unwrap()["parents"][1]["basedOn"], Value::Null);+ }++ /// A's page-number marker shown on parent XYZ (based on A) reads XYZ, as markers on XYZ's own items do.+ #[test]+ fn base_parent_markers_read_the_showing_parent() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1, "facingPages": false})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "XYZ"})).unwrap();+ s.execute("layout.parents.options", &json!({"parent": "XYZ", "basedOn": "A"})).unwrap();+ let marker = designcraft_doc::story::PAGE_NUMBER.to_string();+ let r = s+ .execute("frame.create", &json!({"spread": {"kind": "parent", "index": 0}, "rect": [72, 30, 500, 60], "content": "text", "text": marker}))+ .unwrap();+ let d = s.doc().unwrap().doc.clone();+ let sid = d.item(designcraft_doc::ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story;+ let glyphs = |on| -> usize {+ let cs = s.cache.get_on(&d, sid, on);+ cs.frames.iter().flat_map(|f| f.lines.iter()).map(|l| l.glyphs.iter().filter(|g| g.visible && g.adv > 0.0).count()).sum()+ };+ assert_eq!(glyphs(designcraft_compose::ShownOn::Own), 1, "A");+ assert_eq!(glyphs(designcraft_compose::ShownOn::Parent(1)), 3, "XYZ");+ }++ /// A file whose parents are based on each other opens, with the cycle broken and reported.+ #[test]+ fn opening_a_parent_cycle_breaks_it_with_a_warning() {+ let mut s = crate::Session::new();+ s.execute("file.new", &json!({"pages": 1})).unwrap();+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();+ let mut d = s.doc().unwrap().doc.as_ref().clone();+ let (a, b) = (d.parents[0].id, d.parents[1].id);+ std::sync::Arc::make_mut(&mut d.parents[0]).parent.as_mut().unwrap().based_on = Some(b);+ std::sync::Arc::make_mut(&mut d.parents[1]).parent.as_mut().unwrap().based_on = Some(a);+ let b64 = crate::cmd::base64_encode(&crate::cmd::to_bytes(&d));+ let r = s.execute("file.openBytes", &json!({"name": "cycle", "base64": b64})).unwrap();+ assert!(r["warnings"].to_string().contains("cycle"), "{r}");+ let d = &s.doc().unwrap().doc;+ assert_eq!(d.parents[0].parent.as_ref().unwrap().based_on, None);+ assert_eq!(d.parents[1].parent.as_ref().unwrap().based_on, Some(a));+ }+ }diff --cc crates/idml/src/import.rsindex ae64f00b1,5e42004f4..87daf3955--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -114,22 -106,9 +114,23 @@@ pub fn import_idml_report(bytes: &[u8]}}let mut im = Importer::new(read_link);+ if let Some(m) = files.get("META-INF/metadata.xml") {+ let m = String::from_utf8_lossy(m);+ im.created = xmp_date(&m, "xmp:CreateDate");+ im.modified = xmp_date(&m, "xmp:ModifyDate");+ }im.run(&root, &top)?;+ if im.repaired_tab_lists > 0 {+ warnings.push(format!(+ "tab lists repaired to fit the limits (at most {} stops, finite positions up to {} in, leaders of at most {} characters, one stop per position): {}",+ designcraft_doc::MAX_TAB_STOPS,+ designcraft_doc::MAX_TAB_POSITION / 72.0,+ designcraft_doc::MAX_TAB_LEADER,+ im.repaired_tab_lists,+ ));+ }- let document = im.finish(&root).map_err(|e| match e {+ warnings.append(&mut im.warnings);+ let mut document = im.finish(&root).map_err(|e| match e {// Without its spread parts there is nothing to open: say which parts were missing.IdmlError::Invalid(msg) if !warnings.is_empty() => IdmlError::Invalid(format!("{msg} ({})", warnings.join("; "))),e => e,diff --cc crates/idml/src/tests.rsindex b08348259,667312d40..473ab7298--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@@ -2608,851 -1455,26 +2608,875 @@@ fn list_numbering_format_expression_andcheck(&import_idml(&export_idml(&d)).unwrap());}+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is+/// set in that family instead of counting as a missing font drawn in the fallback.+#[test]+fn applied_font_with_an_id_prefix_names_the_family() {+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");+ let story = STORY.replace(+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,+ );+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", &styles),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", SPREAD),+ ("Stories/Story_s1.xml", &story),+ ]);+ let d = import_idml_with(&bytes, &|_| None).unwrap();+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");+ let (sid, story) = d.stories.iter().next().unwrap();+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());+ let first_para = story.text.find('\n').unwrap();+ let families: Vec<&str> = cs+ .frames+ .iter()+ .flat_map(|f| &f.lines)+ .flat_map(|l| &l.glyphs)+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)+ .map(|g| g.face.get().family.as_str())+ .collect();+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");+}++#[test]+fn list_tab_position_round_trips_as_a_tab_stop() {+ use designcraft_doc::{ListType, ParaAttrs, ParagraphStyle, TabAlign, TabStop};+ let stop = |position, align| TabStop { position, align, leader: String::new(), align_on: String::new() };+ let mut d = Document::new(&NewDocument::default());+ std::sync::Arc::make_mut(&mut d.styles).paragraph.push(ParagraphStyle {+ name: "List".into(),+ based_on: None,+ next_style: None,+ para: ParaAttrs { list_type: Some(ListType::Bullets), list_tab: Some(Some(24.0)), ..Default::default() },+ chars: CharAttrs::default(),+ shortcut: String::new(),+ });+ let local = ParaAttrs {+ list_type: Some(ListType::Bullets),+ list_tab: Some(Some(36.0)),+ tabs: Some(vec![stop(100.0, TabAlign::Right)]),+ ..Default::default()+ };+ let ended = ParaAttrs { list_type: Some(ListType::None), ..Default::default() };+ let lid = d.default_layer();+ for (i, (text, style, para)) in+ [("Local\tx", "", local), ("Styled\ty", "List", ParaAttrs::default()), ("Ended\tz", "List", ended)].into_iter().enumerate()+ {+ let pf = ParaFormat { style: if style.is_empty() { ParaFormat::default().style } else { style.into() }, para, ..Default::default() };+ let y = 40.0 + 100.0 * i as f64;+ d.add_text_frame(SpreadRef::Doc(0), Rect::new(40.0, y, 300.0, y + 80.0), lid, text, pf).unwrap();+ }+ let back = import_idml(&export_idml(&d)).unwrap();+ let tabs = |prefix: &str| {+ let s = back.stories.values().find(|s| s.text.starts_with(prefix)).unwrap();+ back.styles.resolve_para(&s.paras[0]).0.tabs+ };+ assert_eq!(tabs("Local"), vec![stop(36.0, TabAlign::Left), stop(100.0, TabAlign::Right)]);+ assert_eq!(tabs("Styled"), vec![stop(24.0, TabAlign::Left)]);+ assert_eq!(tabs("Ended"), vec![], "a paragraph that ends the list has no list tab stop");+}++#[test]+fn round_trips_the_zero_point_and_ruler_origin() {+ let mut d = Document::new(&NewDocument { pages: 3, ..Default::default() });+ d.settings.zero_point = [36.0, 18.5];+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(back.settings.zero_point, [36.0, 18.5]);+ for origin in [designcraft_doc::RulerOrigin::Page, designcraft_doc::RulerOrigin::Spine, designcraft_doc::RulerOrigin::Spread] {+ d.settings.ruler_origin = origin;+ assert_eq!(import_idml(&export_idml(&d)).unwrap().settings.ruler_origin, origin);+ }+ // A hostile ZeroPoint lands on the pasteboard; a malformed one is ignored.+ let fixture = |zp: &str| {+ let designmap = format!(+ r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d" ZeroPoint="{zp}">+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#+ );+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s"><Page Self="p" GeometricBounds="0 0 100 100" ItemTransform="1 0 0 1 0 0"/></Spread>+ </idPkg:Spread>"#;+ import_idml(&zip_files(&[("designmap.xml", &designmap), ("Spreads/Spread_s.xml", spread)])).unwrap()+ };+ let [x, y] = fixture("1e300 -1e300").settings.zero_point;+ assert!(x.is_finite() && y.is_finite() && x < 1e4 && y > -1e4, "{x} {y}");+ assert_eq!(fixture("12").settings.zero_point, [0.0, 0.0]);+ assert_eq!(fixture("NaN 4").settings.zero_point, [0.0, 0.0]);+}++#[test]+fn kenten_shatai_and_grid_settings_import_and_round_trip() {+ use designcraft_doc::cjk::CharacterAlignment;+ use designcraft_doc::cjk_settings::{AdornmentOverprint, KentenAlignment, KentenKind, KentenPosition};+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" AutoTcy="3" AutoTcyIncludeRoman="true" RotateSingleByteCharacters="true" AllowArbitraryHyphenation="true" GridAlignment="AlignEmCenter" GridAlignFirstLineOnly="true" GridGyoudori="2" ParagraphGyoudori="true">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="KentenSmallBlackCircle" KentenFontSize="6" KentenXScale="80" KentenYScale="120" KentenPlacement="1.5" KentenPosition="BelowLeft" KentenAlignment="AlignKentenLeft" KentenCharacterSet="CharacterInput" KentenTint="50" KentenStrokeTint="-1" KentenWeight="0.5" KentenOverprintFill="OverprintOn" KentenOverprintStroke="Auto" ShataiMagnification="20" ShataiDegreeAngle="6000" ShataiAdjustRotation="true" ShataiAdjustTsume="false"><Properties><KentenFont type="string">$ID/</KentenFont><KentenFontStyle type="enumeration">Nothing</KentenFontStyle><KentenFillColor type="string">Text Color</KentenFillColor></Properties><Content>甲乙</Content></CharacterStyleRange>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" KentenKind="Custom" KentenCustomCharacter="★"><Content>丙</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let st = doc.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let runs: Vec<CharAttrs> = st.runs().map(|(_, f)| f.over.clone()).collect();+ let a = &runs[0];+ assert_eq!((a.kenten, a.kenten_kind, a.kenten_character.as_deref()), (Some(true), Some(KentenKind::SmallBlackCircle), Some("\u{2022}")));+ assert_eq!((a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance), (Some(Some(6.0)), Some(0.8), Some(1.2), Some(1.5)));+ assert_eq!((a.kenten_position, a.kenten_alignment), (Some(KentenPosition::BelowLeft), Some(KentenAlignment::Start)));+ assert_eq!((a.kenten_font.as_deref(), a.kenten_font_style.as_deref(), a.kenten_fill.as_deref()), (Some(""), Some(""), Some("")));+ assert_eq!((a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight), (Some(Some(0.5)), Some(None), Some(Some(0.5))));+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (Some(AdornmentOverprint::On), Some(AdornmentOverprint::Auto)));+ assert_eq!(a.kenten_character_set.as_deref(), Some("CharacterInput"));+ assert_eq!(+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),+ (Some(20.0), Some(60.0), Some(true), Some(false))+ );+ let custom = runs.iter().find(|r| r.kenten_kind == Some(KentenKind::Custom)).unwrap();+ assert_eq!(custom.kenten_character.as_deref(), Some("★"));+ let p = &st.paras[0].para;+ assert_eq!((p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break), (Some(3), Some(true), Some(true), Some(true)));+ assert_eq!((p.grid_align, p.grid_reference), (Some(designcraft_doc::GridAlign::FirstLineOnly), Some(CharacterAlignment::EmCenter)));+ assert_eq!((p.grid_gyoudori, p.paragraph_gyoudori), (Some(2), Some(true)));++ let back = import_idml(&export_idml(&doc)).unwrap();+ let st2 = back.stories.values().find(|s| s.text.contains("甲乙")).unwrap();+ let runs2: Vec<CharAttrs> = st2.runs().map(|(_, f)| f.over.clone()).collect();+ for (a, b) in runs.iter().zip(&runs2) {+ assert_eq!((a.kenten, a.kenten_kind, &a.kenten_character), (b.kenten, b.kenten_kind, &b.kenten_character));+ assert_eq!(+ (a.kenten_size, a.kenten_x_scale, a.kenten_y_scale, a.kenten_distance),+ (b.kenten_size, b.kenten_x_scale, b.kenten_y_scale, b.kenten_distance)+ );+ assert_eq!(+ (a.kenten_position, a.kenten_alignment, &a.kenten_character_set),+ (b.kenten_position, b.kenten_alignment, &b.kenten_character_set)+ );+ assert_eq!((&a.kenten_font, &a.kenten_font_style, &a.kenten_fill), (&b.kenten_font, &b.kenten_font_style, &b.kenten_fill));+ assert_eq!(+ (a.kenten_fill_tint, a.kenten_stroke_tint, a.kenten_stroke_weight),+ (b.kenten_fill_tint, b.kenten_stroke_tint, b.kenten_stroke_weight)+ );+ assert_eq!((a.kenten_overprint_fill, a.kenten_overprint_stroke), (b.kenten_overprint_fill, b.kenten_overprint_stroke));+ assert_eq!(+ (a.shatai_magnification, a.shatai_angle, a.shatai_adjust_rotation, a.shatai_adjust_tsume),+ (b.shatai_magnification, b.shatai_angle, b.shatai_adjust_rotation, b.shatai_adjust_tsume)+ );+ }+ let p2 = &st2.paras[0].para;+ assert_eq!(+ (p.auto_tcy, p.auto_tcy_include_roman, p.rotate_roman, p.roman_word_break),+ (p2.auto_tcy, p2.auto_tcy_include_roman, p2.rotate_roman, p2.roman_word_break)+ );+ assert_eq!(+ (p.grid_align, p.grid_reference, p.grid_gyoudori, p.paragraph_gyoudori),+ (p2.grid_align, p2.grid_reference, p2.grid_gyoudori, p2.paragraph_gyoudori)+ );+}++#[test]+fn ruby_settings_import_from_idml_and_round_trip() {+ use designcraft_doc::cjk_settings::AdornmentOverprint;+ use designcraft_doc::ruby::{RubyAlignment, RubyOverhang, RubyParentSpacing, RubyPosition, RubyType};+ // InDesign's names: RubyFlag is a number, colours and fonts are properties.+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" RubyFlag="1" RubyString="かん じ" RubyType="PerCharacterRuby" RubyAlignment="RubyCenter" RubyPosition="BelowLeft" RubyYOffset="-1.4173228" RubyFontSize="-1" RubyXScale="90" RubyParentOverhangAmount="RubyOverhangNoLimit" RubyParentSpacing="RubyParentBothSides" RubyAutoAlign="false" RubyAutoScaling="true" RubyParentScalingPercent="40" RubyAutoTcyDigits="2" RubyTint="-1" RubyOverprintFill="Auto"><Properties><RubyFont type="string">$ID/</RubyFont><RubyFontStyle type="enumeration">Nothing</RubyFontStyle><RubyFill type="string">Text Color</RubyFill></Properties><Content>漢字</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let doc = import_idml(&fixture_with_story(story)).unwrap();+ let a = doc.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();+ assert_eq!(a.ruby.as_deref(), Some("かん じ"));+ assert_eq!(a.ruby_type, Some(RubyType::PerCharacter));+ assert_eq!(a.ruby_alignment, Some(RubyAlignment::Center));+ assert_eq!(a.ruby_position, Some(RubyPosition::BelowLeft));+ assert_eq!(a.ruby_y_offset, Some(-1.4173228));+ assert_eq!(a.ruby_font_size, Some(None));+ assert_eq!(a.ruby_x_scale, Some(0.9));+ assert_eq!(a.ruby_overhang_amount, Some(RubyOverhang::NoLimit));+ assert_eq!(a.ruby_parent_spacing, Some(RubyParentSpacing::BothSides));+ assert_eq!((a.ruby_auto_align, a.ruby_auto_scaling, a.ruby_scaling_min), (Some(false), Some(true), Some(0.4)));+ assert_eq!(a.ruby_auto_tcy_digits, Some(2));+ assert_eq!((a.ruby_font.as_deref(), a.ruby_font_style.as_deref(), a.ruby_fill.as_deref()), (Some(""), Some(""), Some("")));+ assert_eq!((a.ruby_fill_tint, a.ruby_overprint_fill), (Some(None), Some(AdornmentOverprint::Auto)));++ // Every setting survives export and import.+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(72.0, 72.0, 300.0, 200.0), lid, "漢字", ParaFormat::default()).unwrap();+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {+ let o = &mut f.over;+ o.ruby = Some("かん じ".into());+ o.ruby_type = Some(RubyType::PerCharacter);+ o.ruby_alignment = Some(RubyAlignment::OneAki);+ o.ruby_position = Some(RubyPosition::BelowLeft);+ o.ruby_x_offset = Some(1.5);+ o.ruby_y_offset = Some(-1.25);+ o.ruby_font = Some("Source Sans 3".into());+ o.ruby_font_style = Some("Bold".into());+ o.ruby_font_size = Some(Some(7.0));+ o.ruby_x_scale = Some(0.9);+ o.ruby_y_scale = Some(1.1);+ o.ruby_open_type_pro = Some(false);+ o.ruby_auto_tcy_digits = Some(3);+ o.ruby_auto_tcy_include_roman = Some(true);+ o.ruby_auto_tcy_auto_scale = Some(false);+ o.ruby_overhang = Some(true);+ o.ruby_overhang_amount = Some(RubyOverhang::HalfChar);+ o.ruby_parent_spacing = Some(RubyParentSpacing::EqualAki);+ o.ruby_auto_align = Some(false);+ o.ruby_auto_scaling = Some(true);+ o.ruby_scaling_min = Some(0.5);+ o.ruby_fill = Some("[Black]".into());+ o.ruby_fill_tint = Some(Some(0.5));+ o.ruby_stroke = Some(String::new());+ o.ruby_stroke_tint = Some(None);+ o.ruby_stroke_weight = Some(Some(0.25));+ o.ruby_overprint_fill = Some(AdornmentOverprint::On);+ o.ruby_overprint_stroke = Some(AdornmentOverprint::Off);+ });+ let a = d.stories[&sid].runs().next().unwrap().1.over.clone();+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains("漢字")).unwrap().runs().next().unwrap().1.over.clone();+ macro_rules! same {+ ($($f:ident),*) => { $( assert_eq!(a.$f, b.$f, stringify!($f)); )* };+ }+ same!(+ ruby,+ ruby_type,+ ruby_alignment,+ ruby_position,+ ruby_x_offset,+ ruby_y_offset,+ ruby_font,+ ruby_font_style,+ ruby_font_size,+ ruby_x_scale,+ ruby_y_scale,+ ruby_open_type_pro,+ ruby_auto_tcy_digits,+ ruby_auto_tcy_include_roman,+ ruby_auto_tcy_auto_scale,+ ruby_overhang,+ ruby_overhang_amount,+ ruby_parent_spacing,+ ruby_auto_align,+ ruby_auto_scaling,+ ruby_scaling_min,+ ruby_fill,+ ruby_fill_tint,+ ruby_stroke,+ ruby_stroke_tint,+ ruby_stroke_weight,+ ruby_overprint_fill,+ ruby_overprint_stroke+ );+}++/// A file's tab list is sanitized as the Tabs commands check theirs: a hostile one imports+/// within the limits instead of failing the import.+#[test]+fn hostile_tab_lists_import_within_the_limits() {+ let item = |position: &str, leader: &str| {+ format!(+ r#"<ListItem type="record"><Alignment type="enumeration">LeftAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string">{leader}</Leader><Position type="unit">{position}</Position></ListItem>"#+ )+ };+ let mut items: String = (0..500).rev().map(|i| item(&(i * 3).to_string(), "")).collect();+ items.push_str(&item("NaN", ""));+ items.push_str(&item("1e300", "0123456789"));+ let story = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <Properties><TabList type="list">{items}</TabList></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Many tabs</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#+ );+ let report = import_idml_report(&fixture_with_story(&story), &|_| None).unwrap();+ assert!(report.warnings.iter().any(|w| w.starts_with("tab lists repaired to fit the limits") && w.ends_with("): 1")), "{:?}", report.warnings);+ let doc = report.document;+ let tabs = doc.stories.values().find(|s| s.text.contains("Many tabs")).unwrap().paras[0].para.tabs.clone().unwrap();+ assert_eq!(tabs.len(), designcraft_doc::MAX_TAB_STOPS);+ assert!(tabs.iter().all(|t| t.position.is_finite() && t.leader.chars().count() <= designcraft_doc::MAX_TAB_LEADER));+ assert!(tabs.windows(2).all(|w| w[0].position < w[1].position), "sorted");+ assert_eq!((tabs[0].position, tabs[99].position), (0.0, 297.0), "the first stops by position");+ // A list within the limits, unsorted and with a char stop on `.`, imports without a warning.+ let fine = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]">+ <Properties><TabList type="list">{}{}<ListItem type="record"><Alignment type="enumeration">CharacterAlign</Alignment><AlignmentCharacter type="string">.</AlignmentCharacter><Leader type="string"></Leader><Position type="unit">40</Position></ListItem></TabList></Properties>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Few tabs</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#,+ item("90", "."),+ item("12", "")+ );+ let report = import_idml_report(&fixture_with_story(&fine), &|_| None).unwrap();+ assert!(report.warnings.is_empty(), "{:?}", report.warnings);+}++#[test]+fn cell_edge_gap_colours_and_tints_import_and_round_trip_per_edge() {+ let styles = CASCADE_STYLES.replace(+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed""#,+ r#"TopEdgeStrokeType="StrokeStyle/$ID/Dashed" TopEdgeStrokeGapColor="Color/Paper" TopEdgeStrokeGapTint="60" BottomEdgeStrokeGapColor="Color/Brand""#,+ );+ let story = CASCADE_STORY.replace(+ r#"<Cell Name="1:1">"#,+ r#"<Cell Name="1:1" LeftEdgeStrokeType="StrokeStyle/$ID/Dotted" LeftEdgeStrokeGapColor="Color/Brand" LeftEdgeStrokeGapTint="30" RightEdgeStrokeGapColor="Color/Paper">"#,+ );+ let gaps = |d: &Document| {+ let base = d.styles.cell.iter().find(|s| s.name == "Base").unwrap().strokes.clone();+ let table = d.stories.values().flat_map(|s| s.tables.values()).next().unwrap();+ let cell = table.cell(1, 1).unwrap().strokes.clone();+ (base.map(|e| (e.gap_color, e.gap_tint)), cell.map(|e| (e.gap_color, e.gap_tint)))+ };+ let d = import_idml(&fixture_with_table_styles(&styles, &story)).unwrap();+ d.check().unwrap();+ let (style, cell) = gaps(&d);+ assert_eq!(style[0], (Some("[Paper]".to_string()), Some(0.6)));+ assert_eq!(style[2], (Some("Brand".to_string()), None));+ assert_eq!((style[1].clone(), style[3].clone()), ((None, None), (None, None)));+ assert_eq!(cell[1], ("Brand".to_string(), 0.3), "left");+ assert_eq!(cell[3], ("[Paper]".to_string(), 1.0), "right");+ assert_eq!(cell[0].0, "[Paper]", "the Base style's top gap colour reaches the cell");+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(gaps(&back), (style, cell));+}++#[test]+fn em_box_first_baseline_offset_round_trips() {+ use designcraft_doc::FirstBaseline;+ let first = |d: &Document| d.spreads[0].items[0].text_frame().unwrap().options.first_baseline;+ let d = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="EmboxHeight"/>"#, "");+ assert_eq!(first(&d), FirstBaseline::EmboxHeight);+ assert_eq!(first(&import_idml(&export_idml(&d)).unwrap()), FirstBaseline::EmboxHeight);+ let unknown = inset_fixture(r#"<TextFramePreference FirstBaselineOffset="SomethingElse"/>"#, "");+ assert_eq!(first(&unknown), FirstBaseline::Ascent);+}++#[test]+fn imports_and_round_trips_text_wrap_side_and_contour_type() {+ let wrap = r#"<TextWrapPreference TextWrapMode="Contour" TextWrapSide="LeftSide"><ContourOption ContourType="BoundingBox" IncludeInsideEdges="false"/></TextWrapPreference><Image Self="im""#;+ let spread = SPREAD.replace(r#"<Image Self="im""#, wrap);+ assert_ne!(spread, SPREAD);+ let bytes = zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", STYLES),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", &spread),+ ("Stories/Story_s1.xml", STORY),+ ]);+ let mut d = import_idml(&bytes).unwrap();+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;+ let w = d.item(id).unwrap().wrap.clone();+ assert_eq!(+ (w.mode, w.side, w.contour),+ (designcraft_doc::WrapMode::Contour, designcraft_doc::WrapSide::LeftSide, designcraft_doc::ContourType::BoundingBox)+ );+ // Every side and contour type survives export and import (detected edges included, which+ // composition follows as the frame's path).+ d.item_mut(id).unwrap().wrap.side = designcraft_doc::WrapSide::AwayFromSpine;+ d.item_mut(id).unwrap().wrap.contour = designcraft_doc::ContourType::DetectEdges;+ let back = import_idml(&export_idml(&d)).unwrap();+ let w = back.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().wrap.clone();+ assert_eq!((w.side, w.contour), (designcraft_doc::WrapSide::AwayFromSpine, designcraft_doc::ContourType::DetectEdges));+}++fn feather_fixture(transparency: &str) -> Document {+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ </Document>"#;+ let rect = |id: &str, inner: &str| {+ format!(+ r#"<Rectangle Self="{id}" ItemTransform="1 0 0 1 0 0">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 100"/>+ <PathPointType Anchor="100 100"/><PathPointType Anchor="100 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ {inner}+ </Rectangle>"#+ )+ };+ let spread = format!(+ r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 200 200" ItemTransform="1 0 0 1 0 0"/>+ {}{}+ </Spread>+ </idPkg:Spread>"#,+ rect("a", transparency),+ rect("b", "")+ );+ import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", &spread)])).unwrap()+}++#[test]+fn imports_gradient_and_directional_feathers() {+ let d = feather_fixture(+ r#"<TransparencySetting>+ <GradientFeatherSetting Applied="true" Type="Linear" Angle="0" Length="50" GradientStart="10 20">+ <OpacityGradientStop Self="s0" Opacity="90" Location="20"/>+ <OpacityGradientStop Self="s2" Opacity="10" Location="80" Midpoint="40"/>+ <OpacityGradientStop Self="s1" Opacity="55" Location="50" Midpoint="50"/>+ </GradientFeatherSetting>+ <DirectionalFeatherSetting Applied="true" LeftWidth="3" RightWidth="4" TopWidth="5" BottomWidth="6" Angle="0" Noise="0" ChokeAmount="0"/>+ </TransparencySetting>"#,+ );+ let items = &d.spreads[0].items;+ let gf = &items[0].effects.gradient_feather;+ assert!(gf.on && !gf.radial);+ assert!((gf.start - 0.9).abs() < 1e-6 && (gf.end - 0.1).abs() < 1e-6, "{gf:?}");+ let v = gf.vector.unwrap();+ for (a, b) in v.iter().zip([20.0, 20.0, 50.0, 20.0]) {+ assert!((a - b).abs() < 1e-9, "{v:?}");+ }+ let df = &items[0].effects.directional_feather;+ assert!(df.on);+ assert_eq!(df.widths, [5.0, 3.0, 6.0, 4.0]);+ assert_eq!(items[1].effects, designcraft_doc::Effects::default());++ // Not applied: the settings stay off.+ let off = feather_fixture(+ r#"<TransparencySetting>+ <GradientFeatherSetting Applied="false" Length="50" GradientStart="10 20"/>+ <DirectionalFeatherSetting Applied="false" LeftWidth="3"/>+ </TransparencySetting>"#,+ );+ assert_eq!(off.spreads[0].items[0].effects, designcraft_doc::Effects::default());+}++#[test]+fn gradient_and_directional_feathers_round_trip() {+ use designcraft_doc::{DirectionalFeather, GradientFeather, Item, ItemId};+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let add = |d: &mut Document, effects: designcraft_doc::Effects| {+ let mut it = Item::new(ItemId(d.alloc()), lid, Shape::Rectangle, shapes::rectangle(Rect::new(40.0, 40.0, 140.0, 120.0)));+ it.effects = effects;+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ };+ let linear = designcraft_doc::Effects {+ gradient_feather: GradientFeather { on: true, radial: false, angle: 0.0, start: 0.75, end: 0.25, vector: Some([50.0, 60.0, 110.0, 60.0]) },+ directional_feather: DirectionalFeather { on: true, widths: [1.0, 2.0, 3.0, 4.0] },+ ..Default::default()+ };+ let radial = designcraft_doc::Effects {+ gradient_feather: GradientFeather { on: true, radial: true, angle: 30.0, start: 0.0, end: 1.0, vector: None },+ ..Default::default()+ };+ add(&mut d, linear.clone());+ add(&mut d, radial.clone());+ add(&mut d, designcraft_doc::Effects::default());+ let back = import_idml(&export_idml(&d)).unwrap();+ let effects: Vec<_> = back.spreads[0].items.iter().map(|i| i.effects.clone()).collect();+ assert_eq!(effects, [linear, radial, designcraft_doc::Effects::default()]);+}++/// One single-column text frame at (0, 0)-(300, 200) on page 1, beside a 100 pt wide rectangle+/// with a bounding-box wrap and `wrap_props` inside its `TextWrapPreference/Properties`.+fn custom_wrap_fixture(wrap_props: &str) -> Vec<u8> {+ let rect = |w: f64, h: f64| {+ format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0"/><PathPointType Anchor="0 {h}"/><PathPointType Anchor="{w} {h}"/><PathPointType Anchor="{w} 0"/></PathPointArray></GeometryPathType></PathGeometry>"#+ )+ };+ let spread = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Spread Self="sp1" PageCount="2" ItemTransform="1 0 0 1 0 0">+ <Page Self="p1" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 -500 -350"/>+ <Page Self="p2" AppliedMaster="m1" GeometricBounds="0 0 700 500" ItemTransform="1 0 0 1 0 -350"/>+ <TextFrame Self="t1" ParentStory="s1" PreviousTextFrame="n" NextTextFrame="n" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{frame}</Properties>+ </TextFrame>+ <Rectangle Self="w" ItemLayer="L1" ItemTransform="1 0 0 1 -450 -300">+ <Properties>{obj}</Properties>+ <TextWrapPreference TextWrapMode="BoundingBoxTextWrap" TextWrapSide="BothSides"><Properties>{wrap_props}<TextWrapOffset Top="0" Left="0" Bottom="0" Right="0"/></Properties></TextWrapPreference>+ </Rectangle>+ </Spread>+</idPkg:Spread>"#,+ frame = rect(300.0, 200.0),+ obj = rect(100.0, 200.0),+ );+ let words = "wrap ".repeat(120);+ let story = format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1"><ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{words}</Content></CharacterStyleRange></ParagraphStyleRange></Story>+</idPkg:Story>"#+ );+ zip_files(&[+ ("designmap.xml", DESIGNMAP),+ ("Resources/Graphic.xml", GRAPHIC),+ ("Resources/Styles.xml", STYLES),+ ("Resources/Preferences.xml", PREFS),+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),+ ("Spreads/Spread_sp1.xml", &spread),+ ("Stories/Story_s1.xml", &story),+ ])+}++/// The custom boundary: 40 pt wide, the full height of the 100 pt wide rectangle.+const NARROW_WRAP_PATH: &str = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray><PathPointType Anchor="0 0" LeftDirection="0 0" RightDirection="0 0"/><PathPointType Anchor="0 200" LeftDirection="0 200" RightDirection="0 200"/><PathPointType Anchor="40 200" LeftDirection="40 200" RightDirection="40 200"/><PathPointType Anchor="40 0" LeftDirection="40 0" RightDirection="40 0"/></PathPointArray></GeometryPathType></PathGeometry>"#;++fn wrapping_item(d: &Document) -> &designcraft_doc::Item {+ d.spreads[0].items.iter().find(|i| i.wrap.mode != designcraft_doc::WrapMode::None).unwrap()+}++/// Leftmost line start in the frame.+fn first_line_x(d: &Document) -> f64 {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ assert!(cs.frames[0].lines.len() > 3);+ cs.frames[0].lines.iter().map(|l| l.x0).fold(f64::INFINITY, f64::min)+}++#[test]+fn custom_wrap_boundary_imports_composes_and_round_trips() {+ let plain = import_idml_with(&custom_wrap_fixture(""), &|_| None).unwrap();+ assert_eq!(wrapping_item(&plain).wrap.path, None);+ assert!(first_line_x(&plain) >= 100.0 - 1e-6, "the frame's bounds push text to x = 100");++ let d = import_idml_with(&custom_wrap_fixture(NARROW_WRAP_PATH), &|_| None).unwrap();+ let path = wrapping_item(&d).wrap.path.clone().unwrap();+ assert_eq!(path.bounds(), Some(Rect::new(0.0, 0.0, 40.0, 200.0)));+ let x = first_line_x(&d);+ assert!((40.0 - 1e-6..100.0).contains(&x), "lines start at the custom boundary's edge, not the frame's: {x}");++ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(wrapping_item(&back).wrap.path, Some(path));+}++#[test]+fn hostile_custom_wrap_boundary_is_dropped() {+ let nan = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="NaN 200""#, 1);+ let inf = NARROW_WRAP_PATH.replacen(r#"Anchor="40 200""#, r#"Anchor="inf 200""#, 1);+ let huge = format!(+ r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{}</PathPointArray></GeometryPathType></PathGeometry>"#,+ r#"<PathPointType Anchor="1 1"/>"#.repeat(50_000)+ );+ let empty = r#"<PathGeometry><GeometryPathType PathOpen="false"><PathPointArray/></GeometryPathType></PathGeometry>"#;+ for props in [nan.as_str(), inf.as_str(), huge.as_str(), empty] {+ let d = import_idml_with(&custom_wrap_fixture(props), &|_| None).unwrap();+ let it = wrapping_item(&d);+ assert_eq!(it.wrap.mode, designcraft_doc::WrapMode::BoundingBox);+ assert_eq!(it.wrap.path, None);+ assert!(first_line_x(&d) >= 100.0 - 1e-6);+ }+}++/// A family name keeps its spaces ("Minion Pro " is a font of its own) and `FontStyle="Nothing"`+/// leaves the style to the paragraph, also after an export.+#[test]+fn applied_font_keeps_spaces_and_font_style_nothing_inherits() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/Text%3aBody" FontStyle="Bold">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="Nothing"><Properties><AppliedFont type="string">DC Space </AppliedFont></Properties><Content>Spaced</Content></CharacterStyleRange>+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" FontStyle="$ID/Nothing"><Content> plain</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let check = |d: &Document| {+ let s = d.stories.values().find(|s| s.text.contains("Spaced")).unwrap();+ let (_, base) = d.styles.resolve_para(&s.paras[0]);+ let runs: Vec<_> = s.runs().map(|(_, f)| f.clone()).collect();+ assert_eq!(runs[0].over.font_family.as_deref(), Some("DC Space "));+ for f in &runs {+ assert_eq!(d.styles.resolve_char(&base, f).font_style, "Bold", "the enclosing range's style");+ }+ };+ let d = import_idml(&fixture_with_story(story)).unwrap();+ check(&d);+ check(&import_idml(&export_idml(&d)).unwrap());+}++fn tracked_story(body: &str) -> String {+ format!(+ r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <Story Self="s1">{body}</Story>+</idPkg:Story>"#+ )+}++const CSR: &str = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]">"#;++#[test]+fn tracked_deleted_text_takes_no_room_and_round_trips() {+ let psr = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;+ let kwn = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle" KeepWithNext="2">"#;+ let tracked = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a </Content><Change Self="c1" ChangeType="DeletedText"><Content>deleted </Content></Change><Content>word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{kwn}{CSR}<Change Self="c2" ChangeType="DeletedText"><Br/></Change></CharacterStyleRange></ParagraphStyleRange>+{psr}{CSR}<Change Self="c3" ChangeType="InsertedText"><Content>New </Content></Change><Content>second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let plain = tracked_story(&format!(+ r#"{psr}{CSR}<Content>The first paragraph keeps a word.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{psr}{CSR}<Content>New second paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let lines = |d: &Document| {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect::<Vec<_>>()+ };+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();+ let story = d.stories.values().next().unwrap();+ assert_eq!(story.text, "The first paragraph keeps a deleted word.\n\nNew second paragraph.");+ let marks = |s: &designcraft_doc::Story| s.runs().map(|(r, f)| (s.text[r].to_string(), f.over.change)).collect::<Vec<_>>();+ use designcraft_doc::ChangeMark::{Deleted, Inserted};+ let want = vec![+ ("The first paragraph keeps a ".to_string(), None),+ ("deleted ".to_string(), Some(Deleted)),+ ("word.\n".to_string(), None),+ ("\n".to_string(), Some(Deleted)),+ ("New ".to_string(), Some(Inserted)),+ ("second paragraph.".to_string(), None),+ ];+ assert_eq!(marks(story), want);+ let reference = import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap();+ let expected = lines(&reference);+ assert!(expected.len() >= 2);+ assert_eq!(lines(&d), expected);+ // Export writes the changes back as `Change` elements.+ let back = import_idml(&export_idml(&d)).unwrap();+ assert_eq!(marks(back.stories.values().next().unwrap()), want);+}++#[test]+fn same_para_style_spacing_imports_and_round_trips() {+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="0">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Gap</Content><Br/></CharacterStyleRange>+ </ParagraphStyleRange>+ <ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/[No paragraph style]" SameParaStyleSpacing="Nothing">+ <CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>Ignore</Content></CharacterStyleRange>+ </ParagraphStyleRange></Story></idPkg:Story>"#;+ let d = import_idml(&fixture_with_story(story)).unwrap();+ let st = d.stories.values().find(|s| s.text.contains("Gap")).unwrap();+ assert_eq!(st.paras[0].para.same_para_style_spacing, Some(Some(0.0)));+ // Ignore is an explicit "off", not an unset value.+ assert_eq!(st.paras[1].para.same_para_style_spacing, Some(None));+ let back = import_idml(&export_idml(&d)).unwrap();+ let b = back.stories.values().find(|s| s.text.contains("Gap")).unwrap();+ assert_eq!(b.paras[0].para.same_para_style_spacing, Some(Some(0.0)));+ // The explicit Ignore survives the round trip too.+ assert_eq!(b.paras[1].para.same_para_style_spacing, Some(None));+}++/// SameParaStyleSpacing set as a `Properties` element on the based-on style (`Normal`) reaches+/// the headings: consecutive headings sit one leading apart. SetIgnore keeps the usual spacing.+#[test]+fn same_para_style_spacing_from_a_based_on_style_element_closes_the_gap() {+ let styles = r#"<?xml version="1.0" encoding="UTF-8"?>+<idPkg:Styles xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="16.0">+ <RootCharacterStyleGroup Self="rc">+ <CharacterStyle Self="CharacterStyle/$ID/[No character style]" Name="$ID/[No character style]"/>+ </RootCharacterStyleGroup>+ <RootParagraphStyleGroup Self="rp">+ <ParagraphStyle Self="ParagraphStyle/$ID/[No paragraph style]" Name="$ID/[No paragraph style]" PointSize="12">+ <Properties><AppliedFont type="string">Source Serif 4</AppliedFont><Leading type="unit">13</Leading></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/$ID/NormalParagraphStyle" Name="$ID/NormalParagraphStyle">+ <Properties><BasedOn type="string">$ID/[No paragraph style]</BasedOn><SameParaStyleSpacing type="unit">0</SameParaStyleSpacing></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Heading" Name="Heading" SpaceBefore="18" SpaceAfter="4.5">+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn></Properties>+ </ParagraphStyle>+ <ParagraphStyle Self="ParagraphStyle/Loose" Name="Loose" SpaceBefore="18" SpaceAfter="4.5">+ <Properties><BasedOn type="object">ParagraphStyle/$ID/NormalParagraphStyle</BasedOn><SameParaStyleSpacing type="enumeration">SetIgnore</SameParaStyleSpacing></Properties>+ </ParagraphStyle>+ </RootParagraphStyleGroup>+</idPkg:Styles>"#;+ let para = |style: &str, text: &str| {+ format!(+ r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/{style}"><CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]"><Content>{text}</Content><Br/></CharacterStyleRange></ParagraphStyleRange>"#+ )+ };+ let story = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">{}{}{}{}</Story></idPkg:Story>"#,+ para("Heading", "One"),+ para("Heading", "Two"),+ para("Loose", "Three"),+ para("Loose", "Four")+ );+ let d = import_idml(&fixture_with_table_styles(styles, &story)).unwrap();+ let sid = d.stories.iter().find(|(_, s)| s.text.contains("One")).map(|(id, _)| *id).unwrap();+ let cs = designcraft_compose::compose_story(&d, sid, &Default::default());+ let baseline = |para: usize| cs.frames[0].lines.iter().find(|l| l.para == para).unwrap().baseline;+ assert!((baseline(1) - baseline(0) - 13.0).abs() < 1e-6, "{} {}", baseline(0), baseline(1));+ assert!((baseline(3) - baseline(2) - 13.0 - 4.5 - 18.0).abs() < 1e-6, "{} {}", baseline(2), baseline(3));+}++/// Composed lines (baseline, left, right) of the only story.+fn story_lines(d: &Document) -> Vec<(f64, f64, f64)> {+ let sid = *d.stories.keys().next().unwrap();+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ cs.frames.iter().flat_map(|f| f.lines.iter().map(|l| (l.baseline, l.x0, l.end_x))).collect()+}++const PSR: &str = r#"<ParagraphStyleRange AppliedParagraphStyle="ParagraphStyle/$ID/NormalParagraphStyle">"#;++/// Lays out like the same story without the deleted paragraph.+fn assert_deleted_para_takes_no_room(deleted: &str, deleted_text: &str) {+ let tracked = tracked_story(&format!(+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{deleted}+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let plain = tracked_story(&format!(+ r#"{PSR}{CSR}<Content>First live paragraph.</Content><Br/></CharacterStyleRange></ParagraphStyleRange>+{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#+ ));+ let d = import_idml_with(&fixture_with_story(&tracked), &|_| None).unwrap();+ let story = d.stories.values().next().unwrap();+ let marks: Vec<_> = story.runs().map(|(r, f)| (story.text[r].to_string(), f.over.change)).collect();+ let want = vec![+ ("First live paragraph.\n".to_string(), None),+ (deleted_text.to_string(), Some(designcraft_doc::ChangeMark::Deleted)),+ ("Second live paragraph.".to_string(), None),+ ];+ assert_eq!(marks, want);+ let expected = story_lines(&import_idml_with(&fixture_with_story(&plain), &|_| None).unwrap());+ assert_eq!(expected.len(), 2);+ assert_eq!(story_lines(&d), expected);+}++#[test]+fn tracked_deleted_paragraph_range_stays_deleted() {+ assert_deleted_para_takes_no_room(+ &format!(+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Deleted text</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#+ ),+ "Deleted text\n",+ );+}++#[test]+fn tracked_deleted_frame_break_does_not_break() {+ let fb = "\u{E003}";+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;+ // The change around the paragraph range.+ assert_deleted_para_takes_no_room(+ &format!(+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#+ ),+ &format!("Gone{fb}\n"),+ );+ // The change inside the character range.+ assert_deleted_para_takes_no_room(+ &format!(+ r#"{PSR}{nf}<Change Self="c1" ChangeType="DeletedText"><Content>Gone</Content><Br/></Change></CharacterStyleRange></ParagraphStyleRange>"#+ ),+ &format!("Gone{fb}\n"),+ );+}++#[test]+fn live_frame_break_before_deleted_paragraph_still_breaks() {+ let nf = r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/$ID/[No character style]" ParagraphBreakType="NextFrame">"#;+ let first =+ format!(r#"{PSR}{CSR}<Content>First live paragraph.</Content></CharacterStyleRange>{nf}<Br/></CharacterStyleRange></ParagraphStyleRange>"#);+ let second = format!(r#"{PSR}{CSR}<Content>Second live paragraph.</Content></CharacterStyleRange></ParagraphStyleRange>"#);+ let deleted = format!(+ r#"<Change Self="c1" ChangeType="DeletedText">{PSR}{CSR}<Content>Gone</Content><Br/></CharacterStyleRange></ParagraphStyleRange></Change>"#+ );+ let import = |body: String| import_idml_with(&fixture_with_story(&tracked_story(&body)), &|_| None).unwrap();+ let reference = import(format!("{first}\n{second}"));+ let sid = *reference.stories.keys().next().unwrap();+ let per_frame: Vec<usize> =+ designcraft_compose::compose_story(&reference, sid, &Default::default()).frames.iter().map(|f| f.lines.len()).collect();+ assert!(per_frame.first() == Some(&1) && per_frame.get(1).is_some_and(|n| *n > 0), "the break sends the second paragraph on");+ let expected = story_lines(&reference);+ assert_eq!(story_lines(&import(format!("{first}\n{deleted}\n{second}"))), expected);+}++#[test]+fn vertical_balance_columns_balances_the_imported_frame() {+ let text = "Balanced columns end at about the same depth when the story ends in the frame. ".repeat(4);+ let designmap = r#"<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" Self="d">+ <idPkg:Spread src="Spreads/Spread_s.xml"/>+ <idPkg:Story src="Stories/Story_s1.xml"/>+ </Document>"#;+ let spread = r#"<idPkg:Spread xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging">+ <Spread Self="s">+ <Page Self="p" GeometricBounds="0 0 400 400" ItemTransform="1 0 0 1 0 0"/>+ <TextFrame Self="f" ParentStory="s1">+ <Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>+ <PathPointType Anchor="0 0"/><PathPointType Anchor="0 150"/>+ <PathPointType Anchor="300 150"/><PathPointType Anchor="300 0"/>+ </PathPointArray></GeometryPathType></PathGeometry></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="12" VerticalBalanceColumns="true"/>+ </TextFrame>+ </Spread>+ </idPkg:Spread>"#;+ let story = format!(+ r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1">+ <ParagraphStyleRange><CharacterStyleRange><Content>{text}</Content></CharacterStyleRange></ParagraphStyleRange>+ </Story></idPkg:Story>"#+ );+ let mut d = import_idml(&zip_files(&[("designmap.xml", designmap), ("Spreads/Spread_s.xml", spread), ("Stories/Story_s1.xml", &story)])).unwrap();+ let sid = *d.stories.keys().next().unwrap();+ let per_column = |d: &Document| {+ let cs = designcraft_compose::compose_story(d, sid, &Default::default());+ assert!(!cs.is_overset());+ let ft = &cs.frames[0];+ [0, 1].map(|c| ft.lines.iter().filter(|l| l.column == c).count())+ };+ let on = per_column(&d);+ assert!(on[1] > 0 && on[0] - on[1] <= 1, "balanced: {on:?}");+ let fid = d.stories[&sid].frames[0];+ d.item_mut(fid).unwrap().text_frame_mut().unwrap().options.balance_columns = false;+ let off = per_column(&d);+ assert!(off[0] > off[1] + 1, "unbalanced: {off:?}");+}++#[test]+fn type_on_a_path_keeps_its_start_and_end_brackets() {+ use designcraft_geom::{Anchor, PathData, Point, SubPath};+ for end in [Some(250.0), None] {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let id = designcraft_doc::ItemId(d.alloc());+ let line = PathData::single(SubPath::new(vec![Anchor::corner(Point::new(100.0, 300.0)), Anchor::corner(Point::new(500.0, 300.0))], false));+ let mut it = designcraft_doc::Item::new(id, lid, Shape::GraphicLine, line);+ let sid = designcraft_doc::StoryId(d.alloc());+ let mut tf = designcraft_doc::TextFrame { story: sid, options: Default::default() };+ tf.options.path = Some(designcraft_doc::PathType { start: 30.0, end, ..Default::default() });+ it.content = designcraft_doc::Content::Text(tf);+ let mut story = designcraft_doc::Story::with_text(sid, "Along", Default::default());+ story.frames = vec![id];+ d.stories.insert(sid, std::sync::Arc::new(story));+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let back = import_idml(&export_idml(&d)).unwrap();+ let pt = back.spreads[0].items[0].text_frame().unwrap().options.path.clone().unwrap();+ assert!((pt.start - 30.0).abs() < 1e-6, "{pt:?}");+ assert_eq!(pt.end.map(|e| e.round()), end, "an end bracket at the path's end is no end bracket");+ }+}+++ /// Based on Parent travels as the parent pages' `AppliedMaster`; a cycle in a file is broken on+ /// import with a warning.+ #[test]+ fn parent_based_on_round_trips_and_cycles_are_broken() {+ let mut d = Document::new(&NewDocument { pages: 2, ..Default::default() });+ let a = d.parents[0].id;+ let b = d.add_parent("B", "Opening", 2, 12.0, designcraft_doc::Margins::uniform(36.0));+ d.add_parent("C", "Closing", 2, 12.0, designcraft_doc::Margins::uniform(36.0));+ let set = |d: &mut Document, pi: usize, on| std::sync::Arc::make_mut(&mut d.parents[pi]).parent.as_mut().unwrap().based_on = on;+ set(&mut d, 1, Some(a));+ set(&mut d, 2, Some(b));+ let back = import_idml(&export_idml(&d)).unwrap();+ let base_of = |d: &Document, pi: usize| {+ let b = d.parents[pi].parent.as_ref().unwrap().based_on?;+ d.parents.iter().find(|p| p.id == b).and_then(|p| p.parent.as_ref()).map(|i| i.prefix.clone())+ };+ assert_eq!((base_of(&back, 0), base_of(&back, 1), base_of(&back, 2)), (None, Some("A".into()), Some("B".into())));++ set(&mut d, 0, Some(b));+ let r = import_idml_report(&export_idml(&d), &|_| None).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("A-Parent") && w.contains("cycle")), "{:?}", r.warnings);+ assert_eq!((base_of(&r.document, 0), base_of(&r.document, 1)), (None, Some("A".into())));+ }diff --cc crates/pdf/src/tests.rsindex 35c1ab81b,609a4b8d3..06e722a80--- a/crates/pdf/src/tests.rs+++ b/crates/pdf/src/tests.rs@@@ -550,87 -447,24 +550,109 @@@ fn column_rules_are_drawn()assert!(rules(false).is_empty());}+#[test]+fn ruby_overprint_is_reported_as_not_exported() {+ use designcraft_doc::cjk_settings::AdornmentOverprint;+ let mut d = doc_with_text("漢字です");+ let sid = *d.stories.keys().next().unwrap();+ let clean = export_pdf_with_report(&d, &Cache::new(), &PdfOptions::default()).unwrap();+ assert!(!clean.warnings.iter().any(|w| w.contains("overprint")), "{:?}", clean.warnings);+ d.story_mut(sid).unwrap().format_chars(0.."漢字".len(), |f| {+ f.over.ruby = Some("かんじ".into());+ f.over.ruby_overprint_fill = Some(AdornmentOverprint::On);+ });+ let r = export_pdf_with_report(&d, &Cache::new(), &PdfOptions::default()).unwrap();+ assert!(r.warnings.iter().any(|w| w.contains("overprint is not exported yet")), "{:?}", r.warnings);+}++#[test]+fn small_caps_and_small_cap_figures_extract_as_typed() {+ // Source Sans 3 substitutes letters and figures under `smcp` / `c2sc` (`one` → `one.s`),+ // in typed text, in a page number and in a list label alike (each with its own figures, so+ // one's mapping can't stand in for another's).+ use designcraft_doc::{Capitalization, ListType, story::PAGE_NUMBER};+ for caps in [Capitalization::SmallCaps, Capitalization::OpenTypeAllSmallCaps] {+ let text = format!("Abc 234 x{PAGE_NUMBER}\nItem");+ let mut d = doc_with_text(&text);+ let sid = *d.stories.keys().next().unwrap();+ let st = d.story_mut(sid).unwrap();+ st.format_paras(0..text.len(), |f| {+ f.chars.font_family = Some("Source Sans 3".into());+ f.chars.capitalization = Some(caps);+ });+ st.format_paras(text.len() - 1..text.len(), |f| {+ f.para.list_type = Some(ListType::Numbers);+ f.para.start_at = Some(Some(5));+ });+ let got = extract_text(&export_pdf(&d, &Cache::new(), &PdfOptions::default()).unwrap()).concat();+ assert!(!got.contains('\u{FFFD}'), "{caps:?}: {got:?}");+ assert_eq!(got.split_whitespace().collect::<Vec<_>>(), ["Abc", "234", "x15.Item"], "{caps:?}: {got:?}");+ }+ // All small caps draws `A` and `a` with one glyph, which one ToUnicode entry can't cover: the+ // second spelling goes out as ActualText (which this extractor doesn't read).+ let mut d = doc_with_text("Aa");+ let sid = *d.stories.keys().next().unwrap();+ d.story_mut(sid).unwrap().format_chars(0..2, |f| {+ f.over.font_family = Some("Source Sans 3".into());+ f.over.capitalization = Some(Capitalization::OpenTypeAllSmallCaps);+ });+ assert!(uncompressed(&d, PdfOptions::default()).contains("/ActualText"));+}++/// A clipping path on a placed image becomes a clip in the page content, inside the frame's.+#[test]+fn clipping_path_clips_the_image() {+ let png = |d: &mut Document| {+ let mut b = Vec::new();+ image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 0, 0, 255]))+ .write_to(&mut std::io::Cursor::new(&mut b), image::ImageFormat::Png)+ .unwrap();+ place(d, b, (4, 4));+ };+ let clips = |s: &str| s.lines().filter(|l| matches!(l.trim(), "W" | "W*")).count();+ let mut d = doc_with_text("x");+ png(&mut d);+ let plain = uncompressed(&d, PdfOptions::default());+ let id = d.spreads[0].items.iter().find(|i| i.graphic().is_some()).unwrap().id;+ let triangle = designcraft_geom::PathData::single(designcraft_geom::path::SubPath::polyline(+ &[designcraft_geom::Point::new(0.0, 4.0), designcraft_geom::Point::new(2.0, 0.0), designcraft_geom::Point::new(4.0, 4.0)],+ true,+ ));+ let mut clip = designcraft_doc::ClippingPath::new(designcraft_doc::ClippingKind::DetectEdges, triangle);+ let set = |d: &mut Document, c: &designcraft_doc::ClippingPath| {+ if let Some(designcraft_doc::Content::Graphic(g)) = d.item_mut(id).map(|it| &mut it.content) {+ g.clip = Some(std::sync::Arc::new(c.clone()));+ }+ };+ set(&mut d, &clip);+ let clipped = uncompressed(&d, PdfOptions::default());+ assert_eq!(clips(&clipped), clips(&plain) + 1, "{clipped}");+ // The triangle's apex: graphic (2, 0) → page (172, 72) → PDF y = page height − 72.+ let apex_y = d.spreads[0].pages[0].height - 72.0;+ assert!(clipped.contains(&format!("172 {apex_y} l")), "{clipped}");+ clip.invert = true;+ set(&mut d, &clip);+ assert!(uncompressed(&d, PdfOptions::default()).lines().any(|l| l.trim() == "W*"), "an inverted clip is even-odd");+}+++ /// A page whose parent B is based on A carries A's items, then B's.+ #[test]+ fn based_on_parent_items_export_base_first() {+ let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..NewDocument::default() });+ d.swatches.push(Swatch::color("Base Cyan", Color::cmyk(1.0, 0.0, 0.0, 0.0)));+ d.swatches.push(Swatch::color("Parent Magenta", Color::cmyk(0.0, 1.0, 0.0, 0.0)));+ let a = d.parents[0].id;+ let b = d.add_parent("B", "Opening", 1, 12.0, designcraft_doc::Margins::uniform(36.0));+ std::sync::Arc::make_mut(&mut d.parents[1]).parent.as_mut().unwrap().based_on = Some(a);+ d.apply_parent(&[0], Some(b)).unwrap();+ let lid = d.default_layer();+ for (pi, swatch, r) in [(0, "Base Cyan", Rect::new(36.0, 36.0, 136.0, 136.0)), (1, "Parent Magenta", Rect::new(200.0, 36.0, 300.0, 136.0))] {+ let mut it = Item::new(ItemId(d.alloc()), lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(r));+ it.fill = Fill::swatch(swatch);+ d.insert_item(SpreadRef::Parent(pi), it, None).unwrap();+ }+ let s = uncompressed(&d, PdfOptions::default());+ let (cyan, magenta) = (s.find("1 0 0 0 k"), s.find("0 1 0 0 k"));+ assert!(cyan.is_some() && magenta.is_some(), "both parents' items are on the page");+ assert!(cyan < magenta, "the base parent's item is drawn first");+ }diff --cc crates/render/src/fx.rsindex dab2e3ad0,b52f7c28d..d68816657--- a/crates/render/src/fx.rs+++ b/crates/render/src/fx.rs@@@ -64,31 -65,9 +65,31 @@@ fn shadow(sigma: f64, color: peniko::Co})}+/// Keep what was drawn in the current layer as much as `it`'s gradient feather says. Cover the+/// whole viewport: strokes, text and child effects can extend arbitrarily past the geometry,+/// and past the gradient's ends its end opacities carry on.+pub(crate) fn gradient_feather_mask(ctx: &mut RenderContext, f: &Frame, it: &Item, xf: Affine) {+ let gf = &it.effects.gradient_feather;+ let (p0, p1) = gf.points(it.feather_bounds());+ let stop = |o: f32, a: f32| peniko::ColorStop::from((o, peniko::Color::from_rgba8(0, 0, 0, (a.clamp(0.0, 1.0) * 255.0).round() as u8)));+ let stops = [stop(0.0, gf.start), stop(1.0, gf.end)];+ let grad = if gf.radial {+ peniko::Gradient::new_radial(p0, (p1 - p0).hypot().max(1e-3) as f32).with_stops(stops.as_slice())+ } else {+ peniko::Gradient::new_linear(p0, p1).with_stops(stops.as_slice())+ };+ ctx.set_transform(Affine::IDENTITY);+ ctx.push_layer(None, Some(BlendMode::new(Mix::Normal, Compose::DestIn)), None, None, None);+ ctx.set_paint(grad);+ ctx.set_paint_transform(f.view * xf);+ ctx.fill_rect(&Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height())));+ ctx.reset_paint_transform();+ ctx.pop_layer();+}+impl Renderer {/// Draw an item with soft effects: below-effects, the (feathered) body, inner shadow.- pub(crate) fn draw_item_fx(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: Option<usize>) {+ pub(crate) fn draw_item_fx(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, bp: &BezPath, xf: Affine, page: ShownOn) {let doc = f.doc;let e = &it.effects;let sw = if it.stroke.is_none() { 0.0 } else { it.stroke.extent() };diff --cc crates/render/src/lib.rsindex 26b75cb24,4c9c5e4b6..f7e9170ac--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@@ -223,8 -216,7 +223,8 @@@ pub struct Rendererresources: Resources,glyphs: text::GlyphCache,/// Composed stories looked up during the current render.- stories: HashMap<(StoryId, Option<usize>), Arc<ComposedStory>>,+ stories: HashMap<(StoryId, ShownOn), Arc<ComposedStory>>,+ drawing_items: Vec<designcraft_doc::ItemId>,pub threads: u16,pub stats: FrameStats,}@@@ -403,19 -394,7 +403,19 @@@ impl Renderer}}}+ let grid_area = f.opts.document_grid.iter().find(|(r, _)| *r == sr).map(|(_, a)| *a);+ let grid = &doc.settings.grid;+ if let Some(area) = grid_area.filter(|_| grid.in_back) {+ grid::draw(ctx, f, sp, grid, area);+ }+ // Blend modes blend with the objects below, not with the paper (as in InDesign and in PDF,+ // where the page's group starts transparent): a Color Dodge or Screen object over blank paper+ // shows as it is. So the items are drawn in their own group, laid over the paper once.+ let isolate = f.opts.paper && spread_blends(doc, sp);+ if isolate {+ ctx.push_layer(None, None, None, None, None);+ }- // Layers back to front; within each layer parent items first (document spreads only).+ // Layers back to front; within each layer parent items first.for layer in doc.layers.iter().rev() {if !layer.visible || f.opts.printing_only && !layer.printable {continue;@@@ -449,24 -436,9 +457,24 @@@}}}+ if isolate {+ ctx.pop_layer();+ }+ if let Some(area) = grid_area.filter(|_| !grid.in_back) {+ grid::draw(ctx, f, sp, grid, area);+ }}- fn draw_item(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, parent: Affine, page: Option<usize>) {+ fn draw_item(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, parent: Affine, page: ShownOn) {+ if self.drawing_items.len() >= 64 || self.drawing_items.contains(&it.id) {+ return;+ }+ self.drawing_items.push(it.id);+ self.draw_item_inner(ctx, f, it, parent, page);+ self.drawing_items.pop();+ }+- fn draw_item_inner(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, parent: Affine, page: Option<usize>) {++ fn draw_item_inner(&mut self, ctx: &mut RenderContext, f: &Frame, it: &Item, parent: Affine, page: ShownOn) {if it.hidden || f.opts.hidden.contains(&it.id) || f.opts.printing_only && it.nonprinting {return;}diff --cc crates/render/src/text.rsindex 8dbc115b6,e3d367889..7abee870e--- a/crates/render/src/text.rs+++ b/crates/render/src/text.rs@@@ -7,9 -7,9 +7,9 @@@//! the greeking threshold become grey bars without touching any outline.use std::collections::HashMap;-use std::sync::Arc;+use std::sync::{Arc, Weak};- use designcraft_compose::{ComposedStory, FrameText, Line};+ use designcraft_compose::{ComposedStory, FrameText, Line, ShownOn};use designcraft_doc::ItemId;use designcraft_fonts::FontDb;use designcraft_geom::{Affine, BezPath, Rect, Shape};@@@ -407,8 -405,14 +407,8 @@@ impl Renderer}}// Anchored objects ride on their lines.- if !ft.objects.is_empty()- && let Some(st) = doc.story(cs.story)- {- for o in &ft.objects {- if let Some(obj) = st.objects.get(o.index) {- self.draw_item(ctx, f, &obj.item, xf * Affine::translate(o.origin.to_vec2()), ShownOn::Own);- }- }+ for o in &ft.objects {- self.draw_item(ctx, f, &o.object.item, xf * Affine::translate(o.origin.to_vec2()), None);++ self.draw_item(ctx, f, &o.object.item, xf * Affine::translate(o.origin.to_vec2()), ShownOn::Own);}}}diff --cc crates/tools/src/snap.rsindex 89a26a33d,4471abcea..910f41492--- a/crates/tools/src/snap.rs+++ b/crates/tools/src/snap.rs@@@ -1450,7 -1323,7 +1342,7 @@@ mod testsuse designcraft_compose::Cache;use designcraft_doc::build::NewDocument;-- use designcraft_doc::{Document, Guide, Item, Margins, Selection, Shape, Stroke};++ use designcraft_doc::{Document, Guide, Item, Margins, PageSide, Selection, Shape, Stroke};use designcraft_geom::shapes;use designcraft_geom::{Affine, Unit};diff --cc docs/gaps.mdindex 6e4e66b00,b00ddfb83..49f82aefe--- a/docs/gaps.md+++ b/docs/gaps.md@@@ -1,6 -1,6 +1,6 @@@# Where DesignCraft falls short of InDesign- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety) · **Target:** Adobe InDesign 2026 (21.6)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Based on Parent leftovers) · **Target:** Adobe InDesign 2026 (21.6)++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (gap 0 shrunk: text threads by hand; threading gaps added; Optical kerning from outlines (#181); gap 6: macOS lists fonts that font services and managers activate; shared print spooler; image clipping paths from IDML; Tabs panel listed as present (#343); book chapter update safety; gap 16: Based on Parent leftovers) · **Target:** Adobe InDesign 2026 (21.6)Every known shortfall against InDesign 2026, one entry each, ranked by how much it stops anInDesign professional from doing real work. This is the work list: agents pick from the top.@@@ -244,6 -229,6 +246,7 @@@ Cue. These are excluded from every perc| Date | Change | Summary ||---|---|---|+ | 2026-10-13 | minor | Gap 16: Parent Options dialog and overrides of base items on a parent spread |+| 2026-10-12 | minor | Gap 0 shrunk to the Primary Text Frame page fixes (#165): text threads by hand; gaps added for autoflow onto existing pages and threading into grouped frames || 2026-10-10 | minor | Gap 0 added and marked alpha blocker: manual text threading is missing (stage re-normalized to pre-alpha) || 2026-10-10 | major | Created: 25 ranked gaps from the full re-measure against InDesign 2026 21.6 and issues #1–#352 |diff --cc docs/target-app-parity.mdindex f958a8732,e6eed73eb..2d918d8ad--- a/docs/target-app-parity.md+++ b/docs/target-app-parity.md@@@ -1,6 -1,6 +1,6 @@@# DesignCraft parity with Adobe InDesign- > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (Based on Parent) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)++> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-13 · **Change:** minor (text threads by hand; image clipping paths from IDML; anchored objects wrap text; Tabs panel listed as present (#343); spring-loaded Zoom navigation; recovery checkpoint retention; cancelable macOS Dock Quit; Based on Parent) · **Target:** Adobe InDesign 2026 (21.6.0.57, macOS)The authoritative assessment of how close DesignCraft is to Adobe InDesign. [ROADMAP.md](../ROADMAP.md)summarizes it; [gaps.md](gaps.md) lists every known shortfall one at a time; the feature-by-feature