DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge fix/idml-interchange: $ID/ font names, placed PDF page and crop, packaged IDML links (#338, #339, #340)
aionggc3c24a0be8f5
diff --cc ROADMAP.mdindex d5f74103d,a53591ed9..ea860f0f7--- a/ROADMAP.md+++ b/ROADMAP.md@@@ -47,8 -20,7 +47,8 @@@ DesignCraft aims at full Adobe InDesig- 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`. File › Export PDF… now opens an "Export PDF" options dialog (General / Compression / Marks and Bleeds / Advanced) and remembers the last-used settings across exports and sessions.- - 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`).-- 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 — opens in InDesign 2026 and round-trips InDesign-exported files (`file.exportIdml`, `file.openIdml`, File → Export IDML…, CLI `--in x.idml` / `--export x.idml`). Placed PDFs keep their page (`PDFAttribute`), font names with the `$ID/` prefix resolve, and the IDML in a package links the images in its Links folder without embedding them.++- 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`). Placed PDFs keep their page (`PDFAttribute`), font names with the `$ID/` prefix resolve, and the IDML in a package links the images in its Links folder without embedding them.+- INDD import through indd-utils (#114): File › Open, drop, `file.open`/`file.openBytes` and the CLI open InDesign documents and templates (.indd, .indt) by converting them to IDML in memory and importing that; the converter's warnings join the open result's `warnings`.- 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 --cc crates/engine/src/tests_idml.rsindex ca18b8147,e0fa0e2d4..81582808e--- a/crates/engine/src/tests_idml.rs+++ b/crates/engine/src/tests_idml.rs@@@ -338,29 -252,108 +338,135 @@@ fn named_lists_round_trip_through_idml(assert_eq!(st.paras[0].para.start_at, Some(Some(5)));}+#[test]+fn type_para_sets_a_drop_cap_that_survives_idml() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("style.character.create", &json!({"name": "Initial", "chars": {"fontStyle": "Bold"}})).unwrap();+ let text = "Once upon a time there was a paragraph long enough to run beside its drop cap for a few lines and then some more.";+ let r = s.execute("frame.create", &json!({"rect": [72, 72, 300, 400], "content": "text", "text": text})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ s.execute("text.select", &json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();+ s.execute("type.para", &json!({"attrs": {"dropCapLines": 3, "dropCapChars": 1, "dropCapStyle": "Initial", "dropCapAlignLeft": false}})).unwrap();+ let d = s.doc().unwrap().doc.clone();+ let cs = designcraft_compose::compose_story(&d, designcraft_doc::StoryId(sid), &Default::default());+ let lines = &cs.frames[0].lines;+ let dc = &lines[0].glyphs[0];+ assert_eq!(dc.byte, 0);+ assert!((lines[0].baseline + dc.y - lines[2].baseline).abs() < 1e-6, "on line 3's baseline");+ assert!(lines[0].drop_cap.is_some_and(|b| b.end == 1));+ let p = &d.story(designcraft_doc::StoryId(sid)).unwrap().paras[0].para;+ assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_style.as_deref()), (Some(3), Some(1), Some("Initial")));+ let back = designcraft_idml::import_idml(&designcraft_idml::export_idml(&d)).unwrap();+ let p = &back.stories.values().find(|st| st.text.starts_with("Once")).unwrap().paras[0].para;+ assert_eq!((p.drop_cap_lines, p.drop_cap_chars, p.drop_cap_align_left), (Some(3), Some(1), Some(false)));+ // The drop cap's character style goes through IDML as a leading Dropcap nested style.+ assert_eq!(p.drop_cap_style.as_deref(), Some("Initial"));+ assert_eq!(p.nested_styles, Some(vec![designcraft_doc::NestedStyle::drop_cap("Initial")]));+}+++ /// IDML says which page of a placed PDF shows and which box its graphic spans, so InDesign opens+ /// it at the same size and position; importing it back gives the same page, crop and geometry.+ #[test]+ fn placed_pdf_page_and_crop_round_trip_through_idml() {+ let mut s = Session::new();+ s.execute("file.new", &json!({"pages": 2})).unwrap();+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();+ let mut t = Session::new();+ t.execute("file.new", &json!({})).unwrap();+ // Page 2, cropped to its trim box: the frame is smaller than the page with its bleed.+ let place = json!({"base64": b64, "name": "a.pdf", "pdfPage": 2, "pdfCrop": "trim", "width": 315, "x": 20, "y": 30});+ let r = t.execute("file.place", &place).unwrap();+ let d = t.doc().unwrap().doc.clone();+ let item = d.item(ItemId(r["id"].as_u64().unwrap())).unwrap();+ let (bounds, g) = (item.bounds(), item.graphic().unwrap().clone());+ assert_eq!(d.assets[&g.asset].page, 1);+ assert_eq!(d.assets[&g.asset].pdf_crop, designcraft_doc::PdfCrop::Trim);++ let bytes = designcraft_idml::export_idml(&d);+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut spreads = String::new();+ for i in 0..zip.len() {+ let mut f = zip.by_index(i).unwrap();+ if f.name().starts_with("Spreads/") {+ std::io::Read::read_to_string(&mut f, &mut spreads).unwrap();+ }+ }+ let attr = spreads.split("<PDFAttribute ").nth(1).and_then(|a| a.split("/>").next()).expect("a PDFAttribute");+ assert!(attr.contains(r#"PageNumber="2""#) && attr.contains(r#"PDFCrop="CropTrim""#), "{attr}");+ assert!(spreads.contains(r#"<GraphicBounds Left="0" Top="0" Right="612" Bottom="792"/>"#), "the trim box");++ let back = crate::cmd::interchange::import(&bytes, None).unwrap();+ let bi = back.spreads.iter().flat_map(|sp| sp.items.iter()).find(|i| i.graphic().is_some()).unwrap();+ let bg = bi.graphic().unwrap();+ let ba = &back.assets[&bg.asset];+ assert_eq!((ba.page, ba.pdf_crop), (1, designcraft_doc::PdfCrop::Trim));+ let (want, got) = (d.assets[&g.asset].shown_box().unwrap(), ba.shown_box().expect("the trim box found on the page"));+ assert!(want.iter().zip(got).all(|(a, b)| (a - b).abs() < 1e-9), "{got:?} vs {want:?}");+ let bb = bi.bounds();+ assert!([bb.x0 - bounds.x0, bb.y0 - bounds.y0, bb.x1 - bounds.x1, bb.y1 - bounds.y1].iter().all(|v| v.abs() < 1e-3), "{bb:?} vs {bounds:?}");+ assert!((bg.size.0 - g.size.0).abs() < 1e-3 && (bg.size.1 - g.size.1).abs() < 1e-3);+ let (a, b) = ((bi.xf * bg.xf).as_coeffs(), (item.xf * g.xf).as_coeffs());+ assert!(a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3), "{a:?} vs {b:?}");++ // A page the PDF doesn't have imports, and the PDF export leaves it out with a warning.+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));+ for i in 0..zip.len() {+ let mut f = zip.by_index(i).unwrap();+ let mut body = String::new();+ std::io::Read::read_to_string(&mut f, &mut body).unwrap();+ out.start_file(f.name(), zip::write::SimpleFileOptions::default()).unwrap();+ std::io::Write::write_all(&mut out, body.replace(r#"PageNumber="2""#, r#"PageNumber="4294967295""#).as_bytes()).unwrap();+ }+ let hostile = designcraft_idml::import_idml(&out.finish().unwrap().into_inner()).unwrap();+ assert_eq!(hostile.assets.values().map(|a| a.page).collect::<Vec<_>>(), [u32::MAX - 1]);+ t.edit(|doc, _| {+ *doc = hostile;+ Ok(())+ })+ .unwrap();+ let r = t.execute("file.exportPdf", &json!({})).unwrap();+ assert!(r["warnings"].to_string().contains("has no page 4294967295"), "{r}");+ }++ /// An IDML placed PDF cropped to its media box, without `GraphicBounds`: the graphic takes the+ /// media box (the page with its 9 pt bleed).+ #[test]+ fn idml_placed_pdf_cropped_to_its_media_box_gets_media_box_bounds() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ s.execute("layout.documentSetup", &json!({"bleed": 9})).unwrap();+ let b64 = s.execute("file.exportPdf", &json!({"bleed": true})).unwrap()["base64"].as_str().unwrap().to_string();+ let mut t = Session::new();+ t.execute("file.new", &json!({})).unwrap();+ t.execute("file.place", &json!({"base64": b64, "name": "a.pdf", "pdfCrop": "trim", "width": 630, "x": 0, "y": 0})).unwrap();+ let bytes = designcraft_idml::export_idml(&t.doc().unwrap().doc);++ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes.as_slice())).unwrap();+ let mut out = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));+ let mut edited = false;+ for i in 0..zip.len() {+ let mut f = zip.by_index(i).unwrap();+ let mut body = Vec::new();+ std::io::Read::read_to_end(&mut f, &mut body).unwrap();+ if f.name().starts_with("Spreads/") {+ let text = String::from_utf8(body).unwrap().replace(r#"PDFCrop="CropTrim""#, r#"PDFCrop="CropMedia""#);+ let start = text.find("<GraphicBounds ").unwrap();+ let end = start + text[start..].find("/>").unwrap() + 2;+ body = format!("{}{}", &text[..start], &text[end..]).into_bytes();+ edited = true;+ }+ out.start_file(f.name(), zip::write::SimpleFileOptions::default()).unwrap();+ std::io::Write::write_all(&mut out, &body).unwrap();+ }+ assert!(edited);+ let back = crate::cmd::interchange::import(&out.finish().unwrap().into_inner(), None).unwrap();+ let g = back.spreads.iter().flat_map(|sp| sp.items.iter()).find_map(|i| i.graphic().cloned()).unwrap();+ let a = &back.assets[&g.asset];+ assert_eq!(a.pdf_crop, designcraft_doc::PdfCrop::Media);+ assert!((g.size.0 - 630.0).abs() < 1e-3 && (g.size.1 - 810.0).abs() < 1e-3, "{:?}", g.size);+ let b = a.shown_box().unwrap_or([0.0, 0.0, 1.0, 1.0]);+ assert!(b.iter().zip([0.0, 0.0, 1.0, 1.0]).all(|(x, y)| (x - y).abs() < 1e-6), "{b:?}");+ }diff --cc crates/fonts/src/fontdb.rsindex da2e4f00b,279379ca6..a06df8d24--- a/crates/fonts/src/fontdb.rs+++ b/crates/fonts/src/fontdb.rs@@@ -760,52 -712,12 +760,58 @@@ fn make_face(bytes: FontBytes, source:})}+/// A font's height above the baseline (font units) if it is plausible: above 0 and at most 4 em.+fn plausible(v: Option<f64>, upem: f64) -> Option<f64> {+ v.filter(|v| *v > 0.0 && *v <= 4.0 * upem)+}++/// The top of the first of `chars` the font has a non-empty outline for, in font units: the+/// highest point of its unhinted outline at `location`, if [`plausible`]. For flat-topped letters+/// that is the cap height (`H`) or x-height (`x`).+fn measured_top(f: &skrifa::FontRef<'_>, location: &Location, chars: &[char], upem: f64) -> Option<f64> {+ struct Top(f32);+ impl OutlinePen for Top {+ fn move_to(&mut self, _x: f32, y: f32) {+ self.0 = self.0.max(y);+ }+ fn line_to(&mut self, _x: f32, y: f32) {+ self.0 = self.0.max(y);+ }+ fn quad_to(&mut self, _cx: f32, _cy: f32, _x: f32, y: f32) {+ self.0 = self.0.max(y);+ }+ fn curve_to(&mut self, _cx0: f32, _cy0: f32, _cx1: f32, _cy1: f32, _x: f32, y: f32) {+ self.0 = self.0.max(y);+ }+ fn close(&mut self) {}+ }+ let cmap = f.charmap();+ let glyphs = f.outline_glyphs();+ chars.iter().find_map(|&c| {+ let g = glyphs.get(cmap.map(c)?)?;+ let mut pen = Top(f32::NEG_INFINITY);+ g.draw(DrawSettings::unhinted(Size::unscaled(), location), &mut pen).ok()?;+ plausible(Some(f64::from(pen.0)), upem)+ })+}++/// The OS/2 typographic ascender in font units at `location`, if the font has an OS/2 table and+/// the value is [`plausible`].+fn typo_ascent(f: &skrifa::FontRef<'_>, location: &Location, upem: f64) -> Option<f64> {+ use skrifa::raw::TableProvider;+ let mut v = f.os2().ok()?.s_typo_ascender() as f64;+ if !location.coords().is_empty()+ && let Ok(mvar) = f.mvar()+ {+ v += mvar.metric_delta(skrifa::raw::tables::mvar::tags::HASC, location.coords()).map_or(0.0, |d| d.to_f64());+ }+ plausible(Some(v), upem)+ /// `family` without what layout apps add to a family name, if it has any: InDesign's `$ID/`+ /// prefix (`$ID/Arial` → `Arial`) and the font-format suffix appended when a family is installed+ /// in several formats (`Minion Pro (OTF)` → `Minion Pro`).+ fn plain_family(family: &str) -> Option<&str> {+ let unprefixed = family.trim_start().strip_prefix("$ID/").map(str::trim).filter(|f| !f.is_empty());+ without_format_suffix(unprefixed.unwrap_or(family)).or(unprefixed)}/// `family` without the font-format suffix layout apps append when a family is installed in@@@ -1445,54 -1235,9 +1451,54 @@@ impl ScopedFonts<'_>/// Style names available for `family` (Regular first, then by weight).pub fn styles(&self, family: &str) -> Vec<String> {- let v = self.exact_styles(family);+ self.style_traits(family).into_iter().map(|t| t.2).collect()+ }++ /// Weight and italic of a style of `family`: from the font when it is known, else from the+ /// style's name.+ pub fn traits_of(&self, family: &str, style: &str) -> (f32, bool) {+ let base = base_style(style);+ self.style_traits(family)+ .into_iter()+ .find(|t| t.2.eq_ignore_ascii_case(base))+ .map_or((style_weight(base), style_italic(base)), |(italic, weight, _)| (weight, italic))+ }++ /// Style linking: the style of `family` that sets bold (`bold`) and italic (`italic`) as asked+ /// and keeps the other from `current` (Bold from Italic is Bold Italic). `None` when the+ /// family has no such style.+ pub fn linked_style(&self, family: &str, current: &str, bold: Option<bool>, italic: Option<bool>) -> Option<String> {+ let (weight, cur_italic) = self.traits_of(family, current);+ let want_italic = italic.unwrap_or(cur_italic);+ let want_weight = match bold {+ Some(true) => 700.0,+ Some(false) => 400.0,+ None => weight,+ };+ // Width words (Condensed, Extended…) of the current style are kept when the family allows.+ const WIDTHS: &[&str] = &["condensed", "compressed", "narrow", "extended", "expanded", "wide"];+ let widths = |s: &str| {+ let n = norm(s);+ WIDTHS.iter().filter(|w| n.contains(*w)).count()+ };+ let cur_widths = widths(current);+ self.style_traits(family)+ .into_iter()+ .filter(|(i, w, _)| *i == want_italic && bold.is_none_or(|b| b == (*w >= 600.0)))+ .min_by(|a, b| {+ let key = |t: &(bool, f32, String)| ((t.1 - want_weight).abs(), usize::from(widths(&t.2) != cur_widths), t.2.len());+ let (ka, kb) = (key(a), key(b));+ ka.0.total_cmp(&kb.0).then(ka.1.cmp(&kb.1)).then(ka.2.cmp(&kb.2))+ })+ .map(|t| t.2)+ }++ /// `(italic, weight, name)` of each style of `family` (the document's, loaded, or installed),+ /// Regular first, then by weight.+ fn style_traits(&self, family: &str) -> Vec<(bool, f32, String)> {+ let v = self.exact_style_traits(family);- match without_format_suffix(family) {+ match plain_family(family) {- Some(base) if v.is_empty() => self.exact_styles(base),+ Some(base) if v.is_empty() => self.exact_style_traits(base),_ => v,}}@@@ -1520,13 -1263,10 +1526,14 @@@/// Resolve a family + style to a face, falling back to the closest style of the family, then to/// Source Sans 3 Regular. Installed system fonts are found by name whatever ran before. A- /// family with a format suffix (`Minion Pro (OTF)`) that isn't found is looked up without it.+ /// family with InDesign's `$ID/` prefix or a format suffix (`Minion Pro (OTF)`) that isn't+ /// found is looked up without them.pub fn face(&self, family: &str, style: &str) -> Arc<FontFace> {- if let Some(f) = self.find_or_load(family, style).or_else(|| plain_family(family).and_then(|base| self.find_or_load(base, style))) {+ let canonical = self+ .canonical_family(family)- .or_else(|| without_format_suffix(family).and_then(|base| self.canonical_family(base)))- .unwrap_or_else(|| self.substitute_family(without_format_suffix(family).unwrap_or(family)));++ .or_else(|| plain_family(family).and_then(|base| self.canonical_family(base)))++ .unwrap_or_else(|| self.substitute_family(plain_family(family).unwrap_or(family)));+ if let Some(f) = self.find_or_load(&canonical, style) {return f;}self.find(FALLBACK_FAMILY, style)@@@ -1547,9 -1287,20 +1554,9 @@@}/// Is `family` available (the document's, loaded, or installed on the system), as named or- /// without a format suffix (see [`ScopedFonts::face`])?+ /// without an `$ID/` prefix or a format suffix (see [`ScopedFonts::face`])?pub fn has_family(&self, family: &str) -> bool {- self.canonical_family(family).is_some() || without_format_suffix(family).is_some_and(|base| self.canonical_family(base).is_some())- self.has_exact_family(family) || plain_family(family).is_some_and(|base| self.has_exact_family(base))- }-- fn has_exact_family(&self, family: &str) -> bool {- if self.own().iter().any(|f| f.family.eq_ignore_ascii_case(family)) || self.db.is_loaded(family) {- return true;- }- #[cfg(not(target_arch = "wasm32"))]- if self.db.read_catalog().iter().any(|c| c.family.eq_ignore_ascii_case(family)) {- return true;- }- false++ self.canonical_family(family).is_some() || plain_family(family).is_some_and(|base| self.canonical_family(base).is_some())}/// A variable font's axes: (tag, name, min, default, max), empty for static fonts.diff --cc crates/idml/src/import.rsindex 2607d1fb5,3535ef024..a983992f4--- a/crates/idml/src/import.rs+++ b/crates/idml/src/import.rs@@@ -1218,15 -1064,7 +1218,13 @@@ impl<'r> Importer<'r>}fn char_attrs(&mut self, e: &El) -> CharAttrs {- let mut a = CharAttrs { font_family: e.prop("AppliedFont").as_deref().and_then(names::font_family_in), ..Default::default() };+ let mut a = CharAttrs::default();+ if let Some(f) = e.prop("AppliedFont") {+ let f = f.trim();+ // Some writers append the style after a tab.+ let fam = f.split('\t').next().unwrap_or(f);- if !fam.is_empty() && fam != "$ID/" {- a.font_family = Some(self.composite_names.get(fam).cloned().unwrap_or_else(|| fam.to_string()));- }++ a.font_family = self.composite_names.get(fam).cloned().or_else(|| names::font_family_in(fam));+ }a.font_style = e.prop("FontStyle");a.size = e.num("PointSize");a.leading = e.prop("Leading").and_then(|l| names::leading_in(l.trim()));