Skip to content

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

feat(parents): a parent can be based on another parent (#652)

aiongg80803e3ae3d5
diff --git a/ROADMAP.md b/ROADMAP.md
index 91a951616..6881d5ec5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -129,6 +129,7 @@ list) · [roadmap.md](docs/roadmap.md) (milestones, plan) · [parity-checklist.m
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.
diff --git a/crates/doc/src/build.rs b/crates/doc/src/build.rs
index c274f2130..4045819b5 100644
--- a/crates/doc/src/build.rs
+++ b/crates/doc/src/build.rs
@@ -547,13 +547,84 @@ impl Document {
pub fn parent_page_for(&self, abs: usize) -> Option<(usize, usize)> {
let page = self.page(abs)?;
let pi = self.parent_index(page.parent?)?;
- let ps = &self.parents[pi];
- // A parent spread can come without pages from a file.
- let idx = if ps.pages.len() >= 2 && page.side == PageSide::Left { 0 } else { ps.pages.len().checked_sub(1)? };
- Some((pi, idx))
+ Some((pi, shown_parent_page(self.parents.get(pi)?.pages.len(), page.side)?))
+ }
+
+ /// 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()
+ }
+
+ /// 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 {
+ self.parent_index(base).is_none_or(|bi| bi == pi || self.parent_chain(bi).contains(&pi))
+ }
+
+ /// 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::*;
@@ -631,4 +702,49 @@ mod tests {
d.apply_parent(&[0], None).unwrap();
assert_eq!(d.parent_page_for(0), None);
}
+
+ fn base(d: &mut Document, pi: usize, on: Option<SpreadId>) {
+ Arc::make_mut(&mut d.parents[pi]).parent.as_mut().unwrap().based_on = on;
+ }
+
+ /// C based on B based on A: pages using C show A, then B, then C; C itself shows A and B.
+ #[test]
+ fn parent_chain_is_base_first() {
+ let mut d = Document::new(&NewDocument { pages: 2, facing_pages: false, ..Default::default() });
+ let a = d.parents[0].id;
+ let b = d.add_parent("B", "Parent", 1, 12.0, Margins::uniform(36.0));
+ let c = d.add_parent("C", "Parent", 1, 12.0, Margins::uniform(36.0));
+ base(&mut d, 1, Some(a));
+ base(&mut d, 2, Some(b));
+ d.apply_parent(&[1], Some(c)).unwrap();
+ assert_eq!(d.parent_chain(2), vec![0, 1, 2]);
+ assert_eq!(d.shown_parent_pages(SpreadRef::Doc(1), 0), vec![(0, 0), (1, 0), (2, 0)]);
+ assert_eq!(d.shown_parent_pages(SpreadRef::Doc(0), 0), vec![(0, 0)]);
+ assert_eq!(d.shown_parent_pages(SpreadRef::Parent(2), 0), vec![(0, 0), (1, 0)]);
+ assert!(d.parent_base_cycles(0, c), "A on C closes C → B → A");
+ assert!(d.parent_base_cycles(0, a));
+ assert!(!d.parent_base_cycles(2, a));
+ assert!(d.fix_parent_bases().is_empty());
+ }
+
+ /// A cycle or a dangling base from a file is cleared with a warning; walks stay bounded before that.
+ #[test]
+ fn fix_parent_bases_breaks_cycles_and_dangling_ids() {
+ let mut d = Document::new(&NewDocument { pages: 1, facing_pages: false, ..Default::default() });
+ let a = d.parents[0].id;
+ let b = d.add_parent("B", "Parent", 1, 12.0, Margins::uniform(36.0));
+ d.add_parent("C", "Parent", 1, 12.0, Margins::uniform(36.0));
+ base(&mut d, 0, Some(b));
+ base(&mut d, 1, Some(a));
+ base(&mut d, 2, Some(SpreadId(99_999)));
+ assert_eq!(d.parent_chain(0), vec![1, 0]);
+ assert_eq!(d.parent_chain(2), vec![2]);
+ let w = d.fix_parent_bases();
+ assert_eq!(w.len(), 2, "{w:?}");
+ assert!(w[0].contains("A-Parent") && w[0].contains("cycle"), "{w:?}");
+ assert!(w[1].contains("C-Parent") && w[1].contains("missing"), "{w:?}");
+ 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));
+ assert_eq!(d.parents[2].parent.as_ref().unwrap().based_on, None);
+ }
}
diff --git a/crates/engine/src/cmd/export.rs b/crates/engine/src/cmd/export.rs
index 8e0f04d69..b7891d512 100644
--- a/crates/engine/src/cmd/export.rs
+++ b/crates/engine/src/cmd/export.rs
@@ -239,7 +239,8 @@ fn flatten(d: &designcraft_doc::Document, cache: &designcraft_compose::Cache, pp
rr.threads = designcraft_render::default_threads();
let k = ppi / 72.0;
let parent_transparent = |pid: Option<designcraft_doc::SpreadId>| {
- pid.and_then(|id| d.parents.iter().find(|p| p.id == id)).is_some_and(|p| p.items.iter().any(|it| transparent(it)))
+ pid.and_then(|id| d.parent_index(id))
+ .is_some_and(|pi| d.parent_chain(pi).iter().filter_map(|&i| d.parents.get(i)).any(|p| p.items.iter().any(|it| transparent(it))))
};
// An opaque image item showing `img` over `r`.
let image_item =
diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs
index 692c363e8..7cc0fe8e2 100644
--- a/crates/engine/src/cmd/file.rs
+++ b/crates/engine/src/cmd/file.rs
@@ -18,9 +18,9 @@ pub fn specs() -> Vec<CommandSpec> {
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!(noundo "file.open", "Open…", ["File"], Some("Cmd+O"),
- "{path} — .designcraft or .idml; the fonts in a `Document Fonts` folder beside it load first → {index, documentFonts: faces loaded, warnings: font files skipped (and, for .idml, 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)}",
always, file_open),
- cmd!(noundo "file.openBytes", "Open Bytes", [], None, "{name, base64} — DesignCraft JSON or an IDML package", 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| {
@@ -114,7 +114,15 @@ pub fn to_bytes(d: &Document) -> Vec<u8> {
}
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))
}
fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
@@ -165,10 +173,11 @@ fn file_open(s: &mut Session, p: &Value) -> Result<Value> {
return super::interchange::open_idml(s, p);
}
let bytes = std::fs::read(path).map_err(|e| EngineError::Other(format!("{path}: {e}")))?;
- 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, warnings) = load_document_fonts(&mut d, path);
+ let (fonts, faces, font_warnings) = load_document_fonts(&mut d, path);
+ warnings.extend(font_warnings);
let mut st = DocState::new(d, Some(path.to_string()));
st.fonts = fonts;
let i = s.add_document(st);
@@ -224,13 +233,13 @@ fn file_open_bytes(s: &mut Session, p: &Value) -> Result<Value> {
if designcraft_idml::is_idml(&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();
}
let i = s.add_document(DocState::new(d, None));
- Ok(json!({"index": i}))
+ Ok(json!({"index": i, "warnings": warnings}))
}
fn file_save(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index f3c273368..4b960ad27 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -92,7 +92,10 @@ fn inspect(s: &mut Session, _p: &Value) -> Result<Value> {
"title": st.title(), "path": st.path, "dirty": st.is_dirty(), "pageCount": d.page_count(),
"settings": {"pageWidth": d.settings.page_width, "pageHeight": d.settings.page_height, "facingPages": d.settings.facing_pages, "intent": d.settings.intent},
"spreads": spreads,
- "parents": d.parents.iter().map(|p| json!({"id": p.id.0, "label": p.parent.as_ref().map(|i| i.label()), "items": p.items.len()})).collect::<Vec<_>>(),
+ "parents": d.parents.iter().map(|p| {
+ let based_on = p.parent.as_ref().and_then(|i| i.based_on).and_then(|b| d.parents.iter().find(|x| x.id == b)).and_then(|x| x.parent.as_ref()).map(|i| i.label());
+ json!({"id": p.id.0, "label": p.parent.as_ref().map(|i| i.label()), "basedOn": based_on, "items": p.items.len()})
+ }).collect::<Vec<_>>(),
"layers": d.layers,
"stories": stories,
"paragraphStyles": d.styles.paragraph.iter().map(|p| &p.name).collect::<Vec<_>>(),
diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs
index bd5320799..7ff43c5d9 100644
--- a/crates/engine/src/cmd/layout.rs
+++ b/crates/engine/src/cmd/layout.rs
@@ -179,6 +179,15 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"id": id.0, "prefix": prefix}))
})
}),
+ 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}",
+ 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);
@@ -619,6 +628,41 @@ fn parent_ref(d: &designcraft_doc::Document, v: Option<&Value>) -> Option<Option
}
}
+/// 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 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();
+ 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<()>) {}
@@ -921,3 +965,77 @@ mod adjust_tests {
assert_eq!(b, b2);
}
}
+
+#[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");
+ 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 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 --git a/crates/engine/src/cmd/overrides.rs b/crates/engine/src/cmd/overrides.rs
index 39d453948..ac96b8e48 100644
--- a/crates/engine/src/cmd/overrides.rs
+++ b/crates/engine/src/cmd/overrides.rs
@@ -54,35 +54,49 @@ fn page_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
Ok(page)
}
-/// The parent items that show on a document page, with the offset from parent spread to
-/// document spread.
-fn parent_items(d: &Document, page: usize) -> Option<(Vec<ItemId>, Vec2)> {
+/// The parent items that show on a document page (its parent's and that parent's bases', back to
+/// front), each with the offset from its parent spread to the document spread.
+fn parent_items(d: &Document, page: usize) -> Option<Vec<(ItemId, Vec2)>> {
let (si, pi) = d.page_loc(page)?;
- let pg = &d.spreads[si].pages[pi];
- let (ppi, ppage) = d.parent_page_for(page)?;
- let parent = d.parents.get(ppi)?;
- let dx = pg.x - parent.pages.get(ppage)?.x;
- let ids =
- parent.items.iter().filter(|it| parent.pages.len() <= 1 || parent.page_at_x(it.bounds().center().x) == Some(ppage)).map(|it| it.id).collect();
- Some((ids, Vec2::new(dx, 0.0)))
+ let pg = d.spreads.get(si)?.pages.get(pi)?;
+ let shown = d.shown_parent_pages(SpreadRef::Doc(si), pi);
+ if shown.is_empty() {
+ return None;
+ }
+ let mut out = Vec::new();
+ for (ppi, ppage) in shown {
+ let Some(parent) = d.parents.get(ppi) else { continue };
+ let Some(ppg) = parent.pages.get(ppage) else { continue };
+ let off = Vec2::new(pg.x - ppg.x, 0.0);
+ out.extend(
+ parent
+ .items
+ .iter()
+ .filter(|it| parent.pages.len() <= 1 || parent.page_at_x(it.bounds().center().x) == Some(ppage))
+ .map(|it| (it.id, off)),
+ );
+ }
+ Some(out)
}
fn override_items(s: &mut Session, p: &Value) -> Result<Value> {
let page = page_param(s, p, "layout.overrideParentItems")?;
let wanted: Option<Vec<ItemId>> = super::ids_param(p, "ids");
s.edit(|d, sel| {
- let (all, off) = parent_items(d, page).ok_or_else(|| bad("layout.overrideParentItems", "the page has no parent"))?;
+ let all = parent_items(d, page).ok_or_else(|| bad("layout.overrideParentItems", "the page has no parent"))?;
let (si, pi) = d.page_loc(page).ok_or_else(|| bad("layout.overrideParentItems", "no such page"))?;
let already = d.spreads[si].pages[pi].overridden.clone();
- let ids: Vec<ItemId> = all.into_iter().filter(|i| wanted.as_ref().is_none_or(|w| w.contains(i)) && !already.contains(i)).collect();
- if ids.is_empty() {
+ let picked: Vec<(ItemId, Vec2)> =
+ all.into_iter().filter(|(i, _)| wanted.as_ref().is_none_or(|w| w.contains(i)) && !already.contains(i)).collect();
+ if picked.is_empty() {
return Ok(json!({"ids": []}));
}
+ let ids: Vec<ItemId> = picked.iter().map(|(i, _)| *i).collect();
let src = d.clone();
- // Copies on the document spread (stories and images come along).
+ // Copies on the document spread (stories and images come along), base parents' first.
let mut new = Vec::new();
- for id in &ids {
- let copy = super::object::duplicate_from(d, &src, &[*id], SpreadRef::Doc(si), off)?;
+ for (id, off) in &picked {
+ let copy = super::object::duplicate_from(d, &src, &[*id], SpreadRef::Doc(si), *off)?;
if let Some(nid) = copy.first() {
if let Some(it) = d.item_mut(*nid) {
it.overrides = Some(*id);
@@ -173,4 +187,33 @@ mod tests {
assert!(d.spreads[si].pages[pi].overridden.is_empty());
d.check().unwrap();
}
+
+ /// On a page whose parent B is based on A, A's items can be overridden too.
+ #[test]
+ fn override_items_from_a_base_parent() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({"pages": 2, "facingPages": false})).unwrap();
+ s.execute("layout.parents.new", &json!({"prefix": "B"})).unwrap();
+ let on = |s: &mut Session, index: usize, rect: [f64; 4]| {
+ let r = s.execute("frame.create", &json!({"spread": {"kind": "parent", "index": index}, "rect": rect, "content": "unassigned"})).unwrap();
+ ItemId(r["id"].as_u64().unwrap())
+ };
+ let a_item = on(&mut s, 0, [72.0, 72.0, 200.0, 200.0]);
+ let b_item = on(&mut s, 1, [300.0, 72.0, 400.0, 200.0]);
+ s.execute("layout.parents.options", &json!({"parent": "B", "basedOn": "A"})).unwrap();
+ s.execute("layout.pages.applyParent", &json!({"pages": [1], "parent": "B"})).unwrap();
+ let r = s.execute("layout.overrideParentItems", &json!({"page": 1, "ids": [a_item.0]})).unwrap();
+ let copy = ItemId(r["ids"][0].as_u64().unwrap());
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(d.item(copy).unwrap().overrides, Some(a_item));
+ assert_eq!(d.page_of_item(copy), Some(1));
+ let b = d.item(copy).unwrap().bounds();
+ assert!((b.x0 - 72.0).abs() < 1e-9 && (b.y0 - 72.0).abs() < 1e-9, "{b:?}");
+ // Overriding the rest picks up B's item only.
+ let r = s.execute("layout.overrideParentItems", &json!({"page": 1})).unwrap();
+ let rest: Vec<ItemId> = r["ids"].as_array().unwrap().iter().map(|v| ItemId(v.as_u64().unwrap())).collect();
+ let d = s.doc().unwrap().doc.clone();
+ assert_eq!(rest.iter().map(|i| d.item(*i).unwrap().overrides).collect::<Vec<_>>(), vec![Some(b_item)]);
+ d.check().unwrap();
+ }
}
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 46c3253b6..949abf3f4 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -107,11 +107,12 @@ pub fn import_idml_report(bytes: &[u8], read_link: &dyn Fn(&str) -> Option<Vec<u
}
let mut im = Importer::new(read_link);
im.run(&root, &top)?;
- let document = im.finish(&root).map_err(|e| match e {
+ 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,
})?;
+ warnings.extend(document.fix_parent_bases());
document.check().map_err(|e| IdmlError::Invalid(e.to_string()))?;
Ok(Imported { document, warnings })
}
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 23ec99bdf..667312d40 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -1454,3 +1454,27 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {
check(&d);
check(&import_idml(&export_idml(&d)).unwrap());
}
+
+/// 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 --git a/crates/pdf/src/export.rs b/crates/pdf/src/export.rs
index dcf8abb83..1da8c5de0 100644
--- a/crates/pdf/src/export.rs
+++ b/crates/pdf/src/export.rs
@@ -6,7 +6,7 @@ use std::sync::Arc;
use designcraft_color::swatch::{ColorType, SwatchValue};
use designcraft_color::{BlendMode as DcBlend, Color, GradientKind};
use designcraft_compose::Cache;
-use designcraft_doc::{AssetId, Content, Document, Item, PageSide, Spread, StrokeAlign, StrokeType};
+use designcraft_doc::{AssetId, Content, Document, Item, PageSide, Spread, SpreadRef, StrokeAlign, StrokeType};
use designcraft_geom::kurbo::{PathEl, Shape as _};
use designcraft_geom::{Affine, BezPath, Rect, Vec2, corners};
use krilla::color::{cmyk, luma, rgb};
@@ -627,18 +627,21 @@ impl Exporter<'_> {
if !page.show_parent_items {
continue;
}
- let Some((ppi, ppage)) = doc.parent_page_for(first + pi) else { continue };
- let parent = &doc.parents[ppi];
- let dx = page.x - parent.pages[ppage].x;
- for it in &parent.items {
- if it.layer != layer.id || page.overridden.contains(&it.id) {
- continue;
- }
- // Parent items belong to the parent page they sit on.
- if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 {
- continue;
+ // The parent's bases first, then the parent.
+ for (ppi, ppage) in doc.shown_parent_pages(SpreadRef::Doc(si), pi) {
+ let Some(parent) = doc.parents.get(ppi) else { continue };
+ let Some(ppg) = parent.pages.get(ppage) else { continue };
+ let dx = page.x - ppg.x;
+ for it in &parent.items {
+ if it.layer != layer.id || page.overridden.contains(&it.id) {
+ continue;
+ }
+ // Parent items belong to the parent page they sit on.
+ if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 {
+ continue;
+ }
+ self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true);
}
- self.top_item(s, it, Affine::translate((dx, 0.0)), Some(first + pi), true);
}
}
for it in &sp.items {
diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs
index 2cc5c548f..7b42dcbb1 100644
--- a/crates/render/src/lib.rs
+++ b/crates/render/src/lib.rs
@@ -394,21 +394,24 @@ impl Renderer {
}
}
}
- // 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;
}
- if let SpreadRef::Doc(si) = sr {
- let first = doc.first_page_of_spread(si);
- for (pi, page) in sp.pages.iter().enumerate() {
- if !page.show_parent_items {
- continue;
- }
- let Some((ppi, ppage)) = doc.parent_page_for(first + pi) else { continue };
- let parent = &doc.parents[ppi];
- let dx = page.x - parent.pages[ppage].x;
- let pr = parent.pages[ppage].bounds();
+ // Document pages show their parent and its bases; a parent spread shows its bases.
+ let first = match sr {
+ SpreadRef::Doc(si) => Some(doc.first_page_of_spread(si)),
+ SpreadRef::Parent(_) => None,
+ };
+ for (pi, page) in sp.pages.iter().enumerate() {
+ if !page.show_parent_items {
+ continue;
+ }
+ for (ppi, ppage) in doc.shown_parent_pages(sr, pi) {
+ let Some(parent) = doc.parents.get(ppi) else { continue };
+ let Some(ppg) = parent.pages.get(ppage) else { continue };
+ let dx = page.x - ppg.x;
for it in &parent.items {
if it.layer != layer.id || page.overridden.contains(&it.id) {
continue;
@@ -417,8 +420,7 @@ impl Renderer {
if parent.page_at_x(it.bounds().center().x) != Some(ppage) && parent.pages.len() > 1 {
continue;
}
- let _ = pr;
- self.draw_item(ctx, f, it, Affine::translate((dx, 0.0)), Some(first + pi));
+ self.draw_item(ctx, f, it, Affine::translate((dx, 0.0)), first.map(|a| a + pi));
}
}
}
diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs
index 247494f84..e58be7508 100644
--- a/crates/tools/src/lib.rs
+++ b/crates/tools/src/lib.rs
@@ -223,16 +223,18 @@ impl ToolContext<'_> {
let spread = self.doc.spreads.get(si)?;
let pi = spread.page_at_x(sp.x)?;
let page = self.doc.first_page_of_spread(si) + pi;
- let (ppi, ppg) = self.doc.parent_page_for(page)?;
- let parent = &self.doc.parents[ppi];
- let pg = &spread.pages[pi];
- let at = sp - designcraft_geom::Vec2::new(pg.x - parent.pages[ppg].x, 0.0);
- parent
- .items
- .iter()
- .rev()
- .find(|it| !it.locked && !pg.overridden.contains(&it.id) && designcraft_doc::edit_hit(it, at, self.tol(4.0)))
- .map(|it| (page, it.id))
+ let pg = spread.pages.get(pi)?;
+ // Front to back: the page's parent, then the parents it is based on.
+ self.doc.shown_parent_pages(SpreadRef::Doc(si), pi).into_iter().rev().find_map(|(ppi, ppg)| {
+ let parent = self.doc.parents.get(ppi)?;
+ let at = sp - designcraft_geom::Vec2::new(pg.x - parent.pages.get(ppg)?.x, 0.0);
+ parent
+ .items
+ .iter()
+ .rev()
+ .find(|it| !it.locked && !pg.overridden.contains(&it.id) && designcraft_doc::edit_hit(it, at, self.tol(4.0)))
+ .map(|it| (page, it.id))
+ })
}
fn hit_parent(&self, sr: SpreadRef, sp: Point) -> Option<(SpreadRef, ItemId)> {
diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs
index 4c7313e61..dbfe4d2c2 100644
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@ -700,13 +700,12 @@ fn draw_frames(app: &DesignApp, painter: &egui::Painter, xf: &Xf, doc: &Document
for slot in &layout.slots {
let Some(sp) = doc.spread(slot.spread) else { continue };
let a = slot.xf;
- // Parent items on document pages: dotted edges.
- if let SpreadRef::Doc(si) = slot.spread {
- let first = doc.first_page_of_spread(si);
- for (pi, page) in sp.pages.iter().enumerate() {
- let Some((ppi, ppg)) = doc.parent_page_for(first + pi) else { continue };
- let parent = &doc.parents[ppi];
- let dx = page.x - parent.pages[ppg].x;
+ // Parent items on document pages, and base parents' items on a parent spread: dotted edges.
+ for (pi, page) in sp.pages.iter().enumerate() {
+ for (ppi, ppg) in doc.shown_parent_pages(slot.spread, pi) {
+ let Some(parent) = doc.parents.get(ppi) else { continue };
+ let Some(ppage) = parent.pages.get(ppg) else { continue };
+ let dx = page.x - ppage.x;
for it in &parent.items {
if (parent.pages.len() > 1 && parent.page_at_x(it.bounds().center().x) != Some(ppg)) || page.overridden.contains(&it.id) {
continue;
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index 78e968dcf..e6eed73eb 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -1,6 +1,6 @@
# DesignCraft parity with Adobe InDesign
-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-12 · **Change:** minor (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)
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
@@ -426,6 +426,7 @@ It is evidence of breadth: each item exists. It is not a claim of InDesign-level
- Stroke panel: cap, join, miter limit, alignment, type, Start/End arrowheads (12 kinds, drawn on screen and in PDF; the path is shortened under pointed heads) and gap colour under dashes and dots.
- Preferences (⌘K: General, Type, Units & Increments, Grids, Guides & Pasteboard, Display Performance) backed by `prefs.set` (application) and `document.preferences` (units, increments, grids — undoable, saved with the document; right-click a ruler to pick its units, the horizontal and vertical rulers each have their own); scaling applies to content and scales stroke weights (Include Stroke Weight), and X/Y/W/H measure the stroke's outer edge (Dimensions Include Stroke Weight). Quick Apply (⌘Return) finds paragraph, character and object styles as well as commands.
- Parent item overrides: Cmd+Shift-click a parent item on a page (or Override All Parent Page Items, ⌥⇧⌘L) makes an editable local copy that hides the parent's; Remove All Local Overrides and Detach All Objects from Parent in the Pages panel menu.
+- Based on Parent (`layout.parents.options {parent, basedOn}`): a parent shows its base parent's items under its own, on its pages and on the parent itself; chains work, cycles are refused, and items from any parent in the chain can be overridden. IDML carries it as the parent pages' `AppliedMaster`; a cycle or missing base in a file is cleared with a warning on open. The Pages panel has no Parent Options dialog yet.
- Place PDF: placed PDF pages are sized by their crop box, drawn on screen through hayro (with mip levels) and embedded in exported PDFs as vector form XObjects (krilla), `<PDF>` in IDML.
- Menus expose the engine's features (TOC, numbering & sections, text variables, hyperlinks, cross-references, footnotes, step and repeat, spelling, fitting/content, effects, Data Merge, Preflight, EPUB); any menu command with parameters gets a dialog generated from its parameter documentation.
- Table of contents (generate/update, dot leaders) and text variables (running headers, last page number, chapter number, file name, dates, custom) resolved per page.