DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
IDML: frames inherit their object style's corners and text frame options
aiongg572799b8834a
diff --git a/ROADMAP.md b/ROADMAP.mdindex 8bd7fb234..63ad7275e 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -12,7 +12,7 @@ DesignCraft aims at full Adobe InDesign parity — and to be better: faster, ope- Pen tool, Direct Selection anchor/handle editing, rotate from corners, Rotate/Scale/Shear tools, Eyedropper, snapping & smart guides, Align/Distribute, Find/Change (text + GREP), Story Editor, Paragraph Style Options, Effects panel, hidden characters, native macOS menu bar, measured InDesign 2026 look (Medium Dark): Properties sections per selection state, 21 pt spinner fields with arithmetic, Contextual Task Bar, inverse (black) text selection, Pages panel with drag-and-drop reorder / parent apply, Layers panel with per-object rows.- Tools: Selection (click, marquee, move, Alt-duplicate, resize handles), Direct Selection, Type (draw frame, click caret, select, type), Rectangle/Ellipse/Polygon (+ frame variants), Line, Hand, Zoom.- PDF export (krilla): real selectable text with embedded font subsets, DeviceCMYK/RGB + spot Separations, bleed boxes, crop/bleed marks + page info, pages or spreads, PDF/A-2b (PDF/X-4 output intent pending) — `file.exportPdf`, File › Export PDF…, `designcraft-cli run --export out.pdf`.-- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).+- IDML interchange (`designcraft-idml`): export and import of swatches, styles, fonts, preferences, parent spreads, spreads/pages, frames, groups, images (embedded or linked), formatted threaded stories; attributes a file leaves unset take InDesign's defaults (Keep Lines Together at start/end of paragraph, 12 pt corners, paragraph rules in Text Color, auto-sizing from the centre, numbered lists restarting in each story, alternating table fills Black 20 % / None; a tint of −1 is the colour's own; frames take the fill, stroke, corners and Text Frame Options they don't write from their object style chain, then [None]) — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`).- Tables (M8): tables anchored in stories (header/footer/body rows, merged cells, per-edge strokes, fills + alternating fills, insets, vertical justification, at-least/exact row heights); composed into the text column (columns scale to fit, rows break across columns/frames with repeating headers/footers, overset); rendered, exported to PDF (real text) and IDML (export + import); Table menu, Table panel, Create Table dialog, caret/typing/Tab navigation and cell selection in cells; `table.*` commands.- Hyperlinks (text or frames → URL / e-mail / page) and bookmarks, exported as PDF link annotations and outline.- EPUB 3 (reflowable) export: stories in reading order, CSS from paragraph/character styles, images, navigation (`file.exportEpub`, CLI `--export x.epub`).diff --git a/crates/geom/src/corners.rs b/crates/geom/src/corners.rsindex df1fd0fa9..bcbdf9005 100644--- a/crates/geom/src/corners.rs+++ b/crates/geom/src/corners.rs@@ -185,6 +185,32 @@ mod tests {assert!((a - std::f64::consts::PI * 100.0).abs() < 1.0, "{a}");}+ /// InDesign draws a 28.35 pt radius on a 51.02 pt tall frame as 25.51 (half the shorter side),+ /// as a circular arc (handles 0.5523 × the radius).+ #[test]+ fn radius_is_clamped_to_half_the_shorter_side() {+ let r = rectangle(Rect::new(0.0, 0.0, 200.0, 51.02));+ let bp = apply(&r, &CornerOptions::uniform(CornerShape::Rounded, 28.35));+ let half = 51.02 / 2.0;+ let mut arcs = 0;+ let mut last = Point::ZERO;+ for el in bp.elements() {+ match *el {+ kurbo::PathEl::MoveTo(p) | kurbo::PathEl::LineTo(p) => last = p,+ kurbo::PathEl::CurveTo(c1, c2, p) => {+ assert!(((p - last).x.abs() - half).abs() < 1e-9 && ((p - last).y.abs() - half).abs() < 1e-9, "{last:?} → {p:?}");+ assert!(((c1 - last).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ assert!(((c2 - p).hypot() - half * crate::shapes::KAPPA).abs() < 1e-9);+ arcs += 1;+ last = p;+ }+ _ => {}+ }+ }+ assert_eq!(arcs, 4);+ assert!((crate::shapes::KAPPA - 0.5523).abs() < 1e-4);+ }+#[test]fn size_is_clamped_to_half_edge() {let r = rectangle(Rect::new(0.0, 0.0, 10.0, 10.0));diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rsindex b6ce33f4a..d2624ace9 100644--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@ -837,8 +837,11 @@ impl<'r> Importer<'r> {let paragraph_style = enabled("EnableParagraphStyle", "AppliedParagraphStyle").then(|| e.get("AppliedParagraphStyle").map(|r| self.para_style_ref(r))).flatten();- let text_frame =- if e.get("EnableTextFrameGeneralOptions") == Some("true") { e.find("TextFramePreference").map(text_frame_options) } else { None };+ let text_frame = if e.get("EnableTextFrameGeneralOptions") == Some("true") {+ e.find("TextFramePreference").map(|t| text_frame_options(&[t]))+ } else {+ None+ };let s = ObjectStyle { name: name.clone(), based_on, fill, stroke, paragraph_style, text_frame };match self.styles.object.iter_mut().find(|o| o.name == name) {Some(slot) => *slot = s,@@ -1715,25 +1718,33 @@ impl<'r> Importer<'r> {})}- /// Resolve an item attribute, falling back to its object style chain.- fn attr_or_style(&self, e: &El, k: &str) -> Option<String> {- if let Some(v) = e.get(k) {- return Some(v.to_string());- }+ /// An item's object style chain: its applied style, the styles that one is based on, then+ /// `[None]` (cycle-safe).+ fn object_style_chain(&self, e: &El) -> Vec<&El> {+ let mut chain: Vec<&El> = Vec::new();let mut os = e.get("AppliedObjectStyle").map(str::to_string);- let mut depth = 0;while let Some(id) = os {- depth += 1;- if depth > 16 {- break;- }let Some(s) = self.object_els.get(&id) else { break };- if let Some(v) = s.get(k) {- return Some(v.to_string());+ if chain.len() >= 16 || chain.iter().any(|c| std::ptr::eq(*c, s)) {+ break;}- os = s.prop("BasedOn").map(|b| if b.starts_with("ObjectStyle/") { b } else { format!("ObjectStyle/{}", names::escape_id(&b)) });+ chain.push(s);+ os = s.prop("BasedOn").map(|b| {+ let b = b.trim();+ if b.starts_with("ObjectStyle/") { b.to_string() } else { format!("ObjectStyle/{}", names::escape_id(b)) }+ });}- None+ if let Some(none) = self.object_els.get("ObjectStyle/$ID/[None]")+ && !chain.iter().any(|c| std::ptr::eq(*c, none))+ {+ chain.push(none);+ }+ chain+ }++ /// Resolve an item attribute, falling back to its object style chain.+ fn attr_or_style(&self, e: &El, k: &str) -> Option<String> {+ e.get(k).or_else(|| self.object_style_chain(e).into_iter().find_map(|s| s.get(k))).map(str::to_string)}fn stroke_from(&mut self, e: &El, item: Option<&El>) -> Stroke {@@ -1839,19 +1850,21 @@ impl<'r> Importer<'r> {it.stroke.weight = 1.0;}}- // Corners.- let cn = crate::export::corner_names(&it.path);- // The legacy all-corners attributes apply only when no per-corner attribute is present.- let per_corner = cn.iter().any(|n| e.get(&format!("{n}CornerOption")).is_some());- let legacy = if per_corner { (None, None) } else { (e.get("CornerOption"), e.num("CornerRadius")) };- let mut corners = CornerOptions::default();- for (i, n) in cn.iter().enumerate() {- let shape = e.get(&format!("{n}CornerOption")).or(legacy.0).map(names::corner_in).unwrap_or_default();- let size = e.num(&format!("{n}CornerRadius")).or(legacy.1).unwrap_or(INDESIGN_CORNER_SIZE);- corners.corners[i] = Corner { shape, size };- }- if !corners.is_none() {- it.corners = corners;+ // Corners: each corner's shape and radius come from the item, then its object style chain;+ // at each level a per-corner attribute wins over the legacy all-corners one.+ if tag != "Group" {+ let levels: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).collect();+ let corner =+ |n: &str, what: &str| levels.iter().find_map(|s| s.get(&format!("{n}Corner{what}")).or_else(|| s.get(&format!("Corner{what}"))));+ let mut corners = CornerOptions::default();+ for (i, n) in crate::export::corner_names(&it.path).iter().enumerate() {+ let shape = corner(n, "Option").map(names::corner_in).unwrap_or_default();+ let size = corner(n, "Radius").and_then(|v| v.trim().parse::<f64>().ok()).filter(|v| v.is_finite()).unwrap_or(INDESIGN_CORNER_SIZE);+ corners.corners[i] = Corner { shape, size };+ }+ if !corners.is_none() {+ it.corners = corners;+ }}// Transparency.if let Some(t) = e.find("TransparencySetting") {@@ -1931,7 +1944,9 @@ impl<'r> Importer<'r> {sid}};- let mut options = e.find("TextFramePreference").map(text_frame_options).unwrap_or_default();+ // Options the frame doesn't set come from its object style chain.+ let prefs: Vec<&El> = std::iter::once(e).chain(self.object_style_chain(e)).filter_map(|s| s.find("TextFramePreference")).collect();+ let mut options = text_frame_options(&prefs);options.vertical = self.vertical_stories.contains(&story);if let Some(g) = e.find("BaselineFrameGridOption")&& g.get("UseCustomBaselineFrameGrid") == Some("true")@@ -2221,7 +2236,9 @@ fn margins_of(m: &El) -> (Margins, Columns) {)}-fn text_frame_options(e: &El) -> TextFrameOptions {+/// Text Frame Options from `TextFramePreference` elements: each attribute from the first that sets it.+fn text_frame_options(prefs: &[&El]) -> TextFrameOptions {+ let e = Prefs(prefs);let mut o = TextFrameOptions::default();if let Some(v) = e.num("TextColumnCount") {o.columns = v.max(1.0) as u32;@@ -2242,13 +2259,15 @@ fn text_frame_options(e: &El) -> TextFrameOptions {o.column_width = v;}o.balance_columns = e.get("VerticalBalanceColumns") == Some("true");- if let Some(l) = e.prop_el("InsetSpacing") {- let v: Vec<f64> = l.find_all("ListItem").filter_map(|i| i.text_content().trim().parse().ok()).collect();- if v.len() == 4 {- o.inset = [v[0], v[1], v[2], v[3]];+ if let Some(p) = prefs.iter().find(|p| p.prop("InsetSpacing").is_some()) {+ if let Some(l) = p.prop_el("InsetSpacing") {+ let v: Vec<f64> = l.find_all("ListItem").filter_map(|i| i.text_content().trim().parse().ok()).collect();+ if let [t, l, b, r] = v[..] {+ o.inset = [t, l, b, r];+ }+ } else if let Some(v) = p.num("InsetSpacing") {+ o.inset = [v; 4];}- } else if let Some(v) = e.num("InsetSpacing") {- o.inset = [v; 4];}if let Some(v) = e.get("VerticalJustification") {o.vertical_justification = names::vj_in(v);@@ -2272,6 +2291,18 @@ fn text_frame_options(e: &El) -> TextFrameOptions {o}+/// Attribute lookup over several elements: the first that has it.+struct Prefs<'a>(&'a [&'a El]);++impl Prefs<'_> {+ fn get(&self, k: &str) -> Option<&str> {+ self.0.iter().find_map(|e| e.get(k))+ }+ fn num(&self, k: &str) -> Option<f64> {+ self.get(k).and_then(|v| v.trim().parse().ok())+ }+}+fn path_of(pg: &El) -> PathData {let mut subs = Vec::new();for g in pg.find_all("GeometryPathType") {diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rsindex 7e130c4a9..6f6b9f0ff 100644--- a/crates/idml/src/tests.rs+++ b/crates/idml/src/tests.rs@@ -986,3 +986,75 @@ fn drop_caps_import_and_round_trip() {check(&d);check(&import_idml(&export_idml(&d)).unwrap());}++/// Frames take the corners and Text Frame Options they don't write from their object style chain,+/// then `[None]`. Per-corner attributes win over the legacy all-corners pair, at each level; a+/// corner shape without a radius takes the chain's radius.+#[test]+fn frames_inherit_object_style_corners_and_text_frame_options() {+ use designcraft_doc::{AutoSize, FirstBaseline, VerticalJustification};+ use designcraft_geom::corners::CornerShape as C;+ // Anchors in the order top-left, bottom-left, bottom-right, top-right.+ let path = |x: f64| {+ let pts: String = [(x, 0.0), (x, 50.0), (x + 50.0, 50.0), (x + 50.0, 0.0)]+ .iter()+ .map(|(x, y)| format!(r#"<PathPointType Anchor="{x} {y}" LeftDirection="{x} {y}" RightDirection="{x} {y}"/>"#))+ .collect();+ format!(+ r#"<Properties><PathGeometry><GeometryPathType PathOpen="false"><PathPointArray>{pts}</PathPointArray></GeometryPathType></PathGeometry></Properties>"#+ )+ };+ let corners = |opt: &str, r: &str| {+ ["TopLeft", "TopRight", "BottomLeft", "BottomRight"].map(|n| format!(r#"{n}CornerOption="{opt}" {n}CornerRadius="{r}""#)).join(" ")+ };+ let inset = |v: f64| {+ format!(+ r#"<Properties><InsetSpacing type="list">{}</InsetSpacing></Properties>"#,+ r#"<ListItem type="unit">V</ListItem>"#.replace('V', &v.to_string()).repeat(4)+ )+ };+ let designmap = format!(+ r#"<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<Document xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging" DOMVersion="20.2" Self="d">+<RootObjectStyleGroup Self="ro">+ <ObjectStyle Self="ObjectStyle/$ID/[None]" Name="$ID/[None]" {none}>+ <TextFramePreference TextColumnCount="1" TextColumnGutter="12" AutoSizingReferencePoint="CenterPoint" AutoSizingType="Off"/>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Rounded" Name="Rounded" TopLeftCornerOption="RoundedCorner" TopRightCornerOption="RoundedCorner" BottomLeftCornerOption="RoundedCorner" BottomRightCornerOption="RoundedCorner" TopLeftCornerRadius="6">+ <Properties><BasedOn type="object">ObjectStyle/$ID/[None]</BasedOn></Properties>+ <TextFramePreference TextColumnCount="2" TextColumnGutter="18" VerticalJustification="CenterAlign" FirstBaselineOffset="LeadingOffset" MinimumFirstBaselineOffset="4" IgnoreWrap="true" AutoSizingType="HeightOnly">{inset}</TextFramePreference>+ </ObjectStyle>+ <ObjectStyle Self="ObjectStyle/Child" Name="Child" TopRightCornerOption="BevelCorner">+ <Properties><BasedOn type="object">ObjectStyle/Rounded</BasedOn></Properties>+ </ObjectStyle>+</RootObjectStyleGroup>+<Story Self="s1"/>+<Spread Self="sp1"><Page Self="p1"/>+<TextFrame Self="tf" ParentStory="s1" AppliedObjectStyle="ObjectStyle/Child" BottomRightCornerOption="InverseRoundedCorner" BottomRightCornerRadius="11.34">{p0}<TextFramePreference TextColumnCount="3"/></TextFrame>+<Rectangle Self="legacy" AppliedObjectStyle="ObjectStyle/Rounded" CornerOption="BevelCorner" CornerRadius="5" TopLeftCornerOption="InsetCorner">{p1}</Rectangle>+<Rectangle Self="one" TopRightCornerOption="RoundedCorner" TopRightCornerRadius="11.34">{p2}</Rectangle>+<Rectangle Self="plain" AppliedObjectStyle="ObjectStyle/Rounded">{p3}</Rectangle>+</Spread>+</Document>"#,+ none = corners("None", "12"),+ inset = inset(3.0),+ p0 = path(0.0),+ p1 = path(100.0),+ p2 = path(200.0),+ p3 = path(300.0),+ );+ let d = import_idml_with(&zip_files(&[("designmap.xml", &designmap)]), &|_| None).unwrap();+ let item = |n: usize| d.spreads[0].items[n].clone();+ // Path order: top-left, bottom-left, bottom-right, top-right.+ let shapes = |n: usize| item(n).corners.corners.map(|c| (c.shape, c.size));+ assert_eq!(shapes(0), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::InverseRounded, 11.34), (C::Bevel, 12.0)]);+ assert_eq!(shapes(1), [(C::Inset, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0), (C::Bevel, 5.0)]);+ assert!(item(2).corners.corners.iter().enumerate().all(|(i, c)| (c.shape == C::Rounded) == (i == 3)));+ assert_eq!(item(2).corners.corners[3].size, 11.34);+ assert_eq!(shapes(3), [(C::Rounded, 6.0), (C::Rounded, 12.0), (C::Rounded, 12.0), (C::Rounded, 12.0)]);+ let tf = item(0);+ let o = &tf.text_frame().unwrap().options;+ assert_eq!((o.columns, o.gutter, o.inset), (3, 18.0, [3.0; 4]));+ assert_eq!((o.vertical_justification, o.first_baseline, o.first_baseline_min), (VerticalJustification::Center, FirstBaseline::Leading, 4.0));+ assert_eq!((o.ignore_wrap, o.auto_size, o.auto_size_ref), (true, AutoSize::HeightOnly, 4));+}diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex e86478c3d..ed24f75c8 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -1237,6 +1237,37 @@ mod tests {assert!(r.stats.glyphs >= 15);}+ /// An inside-aligned stroke is the stroke of the path inset by half its weight: a band from the+ /// edge inwards, its rounded corners concentric with the frame's.+ #[test]+ fn inside_strokes_are_inset_by_half_the_weight() {+ let mut d = Document::new(&NewDocument::default());+ let lid = d.default_layer();+ let id = designcraft_doc::ItemId(d.alloc());+ let mut it =+ Item::new(id, lid, designcraft_doc::Shape::Rectangle, designcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)));+ it.stroke = designcraft_doc::Stroke {+ swatch: designcraft_color::swatch::BLACK.into(),+ weight: 10.0,+ align: designcraft_doc::StrokeAlign::Inside,+ ..Default::default()+ };+ it.corners = designcraft_geom::corners::CornerOptions::uniform(designcraft_geom::corners::CornerShape::Rounded, 20.0);+ d.insert_item(SpreadRef::Doc(0), it, None).unwrap();+ let cache = Cache::new();+ let mut r = Renderer::new();+ r.threads = 0;+ let img = r.render_page(&d, &cache, 0, 1.0, false, &RenderOptions::default()).unwrap();+ let ink = |x: u32, y: u32| img.pixel(x, y)[0] < 64;+ let paper = |x: u32, y: u32| img.pixel(x, y)[0] > 192;+ // Straight edges: ink from the edge to 10 pt inside, nothing outside.+ assert!(paper(97, 200) && ink(101, 200) && ink(108, 200) && paper(112, 200));+ assert!(ink(298, 200) && paper(302, 200) && paper(288, 200));+ // Rounded corner centred at (120, 120): ink between radii 10 and 20, paper outside the arc+ // and inside the band.+ assert!(paper(103, 103) && ink(108, 108) && paper(114, 114));+ }+#[test]fn arrowheads_draw_at_line_ends() {let mut d = Document::new(&NewDocument::default());