Skip to content

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

FONT1: preserve composite font references and unify usage checks

Shao Wenbin2dbbf989002c
diff --git a/ROADMAP.md b/ROADMAP.md
index aa4c17396..b301f41c0 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -3,6 +3,7 @@
- AR1.1: Kashida justification tests verify space fallback without Tatweel fonts using an isolated font database, while retaining elongation assertions when fonts support it.
- AR1: Arabic IDML controls now retain character direction, kashida switches, diacritic offsets/forms, paragraph policy values and independent story/table directions. Shaping preserves joining context and script/language selection; paragraph-level bidi, contextual digit conversion, mark-safe elongation, RTL columns/tables and physical column insertion have regression coverage. Vendor-specific justification and diacritic presets remain explicit preflight warnings; see docs/arabic-typography.md.
+- FONT1: composite-font references resolve by resource identity, retain literal display names, and export as object references. Font inventory and preflight share the character-selected component fonts, including nested notes and cells.
- CJK1: IDML composite fonts now retain character mappings and metrics; explicit aki, tsume, jidori, em alignment/leading, named/custom kinsoku boundaries, hanging punctuation, tate-chu-yoko offsets and kenten symbols flow through composition and IDML export. Automatic kerning no longer imports inactive numeric values as enormous manual spacing. Composite definitions are editable through commands with undo/cache invalidation. Mojikumi definitions are retained and unsupported spacing-table / push-in-push-out policies are reported by preflight. Full InDesign CJK composition parity, frame-grid layout and detailed ruby/warichu remain unfinished.
DesignCraft aims at full Adobe InDesign parity — and to be better: faster, open (documented JSON format + IDML), scriptable by agents (MCP), and available on the web.
diff --git a/crates/compose/src/shape.rs b/crates/compose/src/shape.rs
index 41583b0a9..fa38901dd 100644
--- a/crates/compose/src/shape.rs
+++ b/crates/compose/src/shape.rs
@@ -234,8 +234,7 @@ pub(crate) fn shape_para(
None => para_chars,
};
let props = styles.resolve_char(para_chars, fmt);
- let family = props.font_family.trim_start_matches("CompositeFont/");
- if let Some(font) = styles.composite_fonts.iter().find(|f| f.name == family) {
+ if let Some(font) = styles.composite_font(&props.font_family) {
let mut start = a;
let mut selected = None;
for (offset, c) in story.text.get(a..b).unwrap_or("").char_indices() {
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 549e7bccf..fe779d053 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -1877,3 +1877,42 @@ fn vertical_lines_fit_the_em_box() {
assert!((l.baseline - col.y0 - ascent).abs() < 1e-9, "{family}: {} {}", l.baseline, col.y0);
}
}
+
+#[test]
+fn composite_metrics_and_character_mappings_apply_inside_footnotes() {
+ use designcraft_doc::cjk::{CompositeFont, CompositeFontEntry};
+ let (mut d, sid, _) = doc_with("Body", Rect::new(0.0, 0.0, 300.0, 300.0), ParaAttrs::default());
+ d.styles_mut().composite_fonts.push(CompositeFont {
+ name: "Mixed".into(),
+ entries: vec![
+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },
+ CompositeFontEntry {
+ characters: "12".into(),
+ family: "Source Sans 3".into(),
+ relative_size: 0.8,
+ horizontal_scale: 0.9,
+ vertical_scale: 1.1,
+ baseline_shift: 0.1,
+ scale_option: false,
+ ..Default::default()
+ },
+ CompositeFontEntry { characters: "2".into(), family: "Inter".into(), ..Default::default() },
+ ],
+ });
+ let story = d.story_mut(sid).unwrap();
+ story.insert_note(4, "A12", ParaFormat::default());
+ let note = Arc::make_mut(&mut story.notes[0]);
+ note.text.format_chars(0..3, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));
+ let cs = compose_story(&d, sid, &ComposeOptions::default());
+ let note = &cs.frames[0].notes[0];
+ let glyphs = &note.text.frames[0].lines[0].glyphs;
+ let a = glyphs.iter().find(|g| g.byte == 0 && g.len > 0).unwrap();
+ let one = glyphs.iter().find(|g| g.byte == 1 && g.len > 0).unwrap();
+ let two = glyphs.iter().find(|g| g.byte == 2 && g.len > 0).unwrap();
+ assert_eq!(a.face.family, "Source Serif 4");
+ assert_eq!(one.face.family, "Source Sans 3");
+ assert_eq!(two.face.family, "Inter");
+ let style = &note.text.styles[one.style as usize];
+ assert!((style.size - 9.6).abs() < 1e-8);
+ assert!(!note.text.styles.iter().any(|s| s.missing_font));
+}
diff --git a/crates/doc/src/styles.rs b/crates/doc/src/styles.rs
index 478cf0452..d6cd3cbfb 100644
--- a/crates/doc/src/styles.rs
+++ b/crates/doc/src/styles.rs
@@ -94,6 +94,12 @@ pub struct ExportTag {
}
impl Styles {
+ /// Resolve either a display name or a normalized IDML composite-font reference.
+ pub fn composite_font(&self, family: &str) -> Option<&crate::cjk::CompositeFont> {
+ let name = family.strip_prefix("CompositeFont/").unwrap_or(family);
+ self.composite_fonts.iter().find(|f| f.name == name)
+ }
+
/// Export tagging of a paragraph (`character` false) or character style.
pub fn export_tag(&self, name: &str, character: bool) -> Option<&ExportTag> {
self.export_tags.get(&format!("{}:{name}", if character { "c" } else { "p" }))
diff --git a/crates/engine/src/cmd/fonts.rs b/crates/engine/src/cmd/fonts.rs
index ef7eb9313..ebd60e988 100644
--- a/crates/engine/src/cmd/fonts.rs
+++ b/crates/engine/src/cmd/fonts.rs
@@ -30,20 +30,31 @@ pub fn specs() -> Vec<CommandSpec> {
/// Every story's text, including table cells and footnotes.
fn for_each_story(d: &Document, f: &mut dyn FnMut(&Story)) {
- for st in d.stories.values() {
+ let mut pending: Vec<&Story> = d.stories.values().map(AsRef::as_ref).collect();
+ while let Some(st) = pending.pop() {
f(st);
- for t in st.tables.values() {
- for c in &t.cells {
- f(&c.text);
- }
- }
- for n in &st.notes {
- f(&n.text);
- }
+ pending.extend(st.tables.values().flat_map(|t| t.cells.iter().map(|c| &c.text)));
+ pending.extend(st.notes.iter().chain(&st.endnotes).map(|n| &n.text));
}
}
+/// Effective document font use shared by the command layer and preflight.
+#[derive(serde::Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(super) struct UsedFont {
+ pub family: String,
+ pub style: String,
+ pub characters: usize,
+ pub missing: bool,
+ pub style_missing: bool,
+ pub source: Option<&'static str>,
+}
+
fn list(d: &Document) -> Vec<Value> {
+ used_fonts(d).into_iter().map(|font| json!(font)).collect()
+}
+
+pub(super) fn used_fonts(d: &Document) -> Vec<UsedFont> {
let db = designcraft_fonts::FontDb::global().scoped(d.font_scope);
let mut used: BTreeMap<(String, String), usize> = BTreeMap::new();
for_each_story(d, &mut |st| {
@@ -56,7 +67,7 @@ fn list(d: &Document) -> Vec<Value> {
continue;
}
let p = d.styles.resolve_char(&base, fmt);
- if let Some(f) = d.styles.composite_fonts.iter().find(|f| f.name == p.font_family.trim_start_matches("CompositeFont/")) {
+ if let Some(f) = d.styles.composite_font(&p.font_family) {
let text = st.text.get(rr.start.max(r.start)..rr.end.min(r.end).max(rr.start.max(r.start))).unwrap_or("");
for c in text.chars() {
if let Some(e) = f.entry(c) {
@@ -69,7 +80,7 @@ fn list(d: &Document) -> Vec<Value> {
}
}
});
- let mut out: Vec<(bool, Value)> = used
+ let mut out: Vec<UsedFont> = used
.into_iter()
.map(|((family, style), n)| {
let missing = !db.has_family(&family);
@@ -80,14 +91,11 @@ fn list(d: &Document) -> Vec<Value> {
FontSource::Document(_) => "document",
FontSource::Memory => "added",
});
- (
- missing || style_missing,
- json!({"family": family, "style": style, "characters": n, "missing": missing, "styleMissing": style_missing, "source": source}),
- )
+ UsedFont { family, style, characters: n, missing, style_missing, source }
})
.collect();
- out.sort_by_key(|(m, _)| !*m);
- out.into_iter().map(|(_, v)| v).collect()
+ out.sort_by_key(|font| !(font.missing || font.style_missing));
+ out
}
/// Replace the font in a sparse attribute set (only where the family is set); true when it changed.
@@ -191,3 +199,68 @@ mod tests {
assert_eq!(s.doc().unwrap().doc.styles.para("Odd").unwrap().chars.font_family.as_deref(), Some(avail.as_str()));
}
}
+
+#[cfg(test)]
+mod composite_tests {
+ use super::*;
+ use designcraft_doc::{
+ ParaFormat,
+ cjk::{CompositeFont, CompositeFontEntry},
+ };
+
+ #[test]
+ fn inventory_resolves_composites_in_nested_cell_notes() {
+ use designcraft_doc::{StoryId, Table, build::NewDocument};
+ let mut d = Document::new(&NewDocument::default());
+ d.styles_mut().composite_fonts.push(CompositeFont {
+ name: "Mixed".into(),
+ entries: vec![
+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },
+ CompositeFontEntry { characters: "1".into(), family: "Source Sans 3".into(), ..Default::default() },
+ ],
+ });
+ let mut story = Story::new(StoryId(d.alloc()));
+ let mut table = Table::new(1, 1, 1, 0, 0, 100.0);
+ let cell = &mut table.cells[0].text;
+ cell.insert_note(0, "1", ParaFormat::default());
+ Arc::make_mut(&mut cell.notes[0]).text.format_chars(0..1, |f| f.over.font_family = Some("Mixed".into()));
+ story.insert_table(0, table);
+ d.stories.insert(story.id, Arc::new(story));
+ let fonts = list(&d);
+ assert!(fonts.iter().any(|f| f["family"] == "Source Sans 3" && f["characters"] == 1));
+ assert!(!fonts.iter().any(|f| f["family"] == "Mixed"));
+ }
+
+ #[test]
+ fn preflight_and_font_list_follow_used_composite_entries_in_notes() {
+ let mut s = Session::new();
+ s.execute("file.new", &json!({})).unwrap();
+ s.execute("frame.create", &json!({"rect": [20,20,400,600], "content":"text", "text":"Body"})).unwrap();
+ let d = Arc::make_mut(&mut s.doc_mut().unwrap().doc);
+ d.styles_mut().composite_fonts.push(CompositeFont {
+ name: "Mixed".into(),
+ entries: vec![
+ CompositeFontEntry { family: "Source Serif 4".into(), ..Default::default() },
+ CompositeFontEntry { characters: "1".into(), family: "Missing Note Digits".into(), ..Default::default() },
+ CompositeFontEntry { characters: "2".into(), family: "Unused Missing Digits".into(), ..Default::default() },
+ ],
+ });
+ let sid = *d.stories.keys().next().unwrap();
+ let st = d.story_mut(sid).unwrap();
+ st.insert_note(4, "A1", ParaFormat::default());
+ Arc::make_mut(&mut st.notes[0]).text.format_chars(0..2, |f| f.over.font_family = Some("CompositeFont/Mixed".into()));
+ let list = s.execute("font.list", &json!({})).unwrap();
+ assert!(list.as_array().unwrap().iter().any(|f| f["family"] == "Missing Note Digits" && f["characters"] == 1));
+ assert!(!list.to_string().contains("Unused Missing Digits"));
+ let issues = s.execute("preflight.run", &json!({})).unwrap();
+ let fonts: Vec<_> = issues["issues"].as_array().unwrap().iter().filter(|i| i["kind"] == "missingFont").collect();
+ assert_eq!(fonts.len(), 1, "{issues}");
+ assert!(fonts[0]["message"].as_str().unwrap().contains("Missing Note Digits"));
+ s.execute("font.replace", &json!({"family":"Missing Note Digits", "toFamily":"Source Sans 3", "toStyle":"Regular"})).unwrap();
+ let issues = s.execute("preflight.run", &json!({})).unwrap();
+ assert!(issues["issues"].as_array().unwrap().iter().all(|i| i["kind"] != "missingFont"));
+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].characters, "1");
+ s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(s.doc().unwrap().doc.styles.composite_fonts[0].entries[1].family, "Missing Note Digits");
+ }
+}
diff --git a/crates/engine/src/cmd/preflight.rs b/crates/engine/src/cmd/preflight.rs
index 3fc061d7d..7e603206d 100644
--- a/crates/engine/src/cmd/preflight.rs
+++ b/crates/engine/src/cmd/preflight.rs
@@ -76,7 +76,6 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
let d = &st.doc;
let mut out = Vec::new();
// Stories: overset and fonts.
- let db = designcraft_fonts::FontDb::global().scoped(d.font_scope);
let mut missing_fonts: Vec<String> = Vec::new();
let mut unsupported_typography = std::collections::BTreeSet::new();
let mut missing: Vec<(FaceRef, Vec<char>)> = Vec::new();
@@ -113,7 +112,6 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
unsupported_typography
.insert(format!("Kinsoku priority `{}` is preserved, but push-in/push-out priority is not applied", para.kinsoku_type));
}
- let mut fams = vec![base.font_family.clone()];
for (run, f) in story.runs().filter(|(run, _)| run.start < range.end && run.end > range.start) {
let props = d.styles.resolve_char(&base, f);
if has_rtl
@@ -130,19 +128,16 @@ pub fn check(s: &Session, min_ppi: f64) -> Vec<Issue> {
unsupported_typography.insert(format!("Unknown positional form `{}` is preserved but not applied", props.positional_form));
}
}
- fams.push(props.font_family);
- }
- for fam in fams {
- let composite = d.styles.composite_fonts.iter().find(|f| f.name == fam.trim_start_matches("CompositeFont/"));
- let families: Vec<&str> = composite.map_or_else(|| vec![fam.as_str()], |f| f.entries.iter().map(|e| e.family.as_str()).collect());
- for family in families {
- if !db.has_family(family) && !missing_fonts.iter().any(|f| f == family) {
- missing_fonts.push(family.to_string());
- }
- }
}
}
}
+ // Use the same effective character-to-font mapping as Find Font, including
+ // anonymous note/cell stories. Unused composite entries are not missing text.
+ for font in super::fonts::used_fonts(d) {
+ if font.missing && !missing_fonts.contains(&font.family) {
+ missing_fonts.push(font.family);
+ }
+ }
for f in missing_fonts {
out.push(Issue { severity: "error", kind: "missingFont", message: format!("Missing font: {f}"), item: None, page: None });
}
diff --git a/crates/idml/src/export.rs b/crates/idml/src/export.rs
index 919991eb0..8dd965473 100644
--- a/crates/idml/src/export.rs
+++ b/crates/idml/src/export.rs
@@ -1021,9 +1021,13 @@ impl<'a> Ex<'a> {
el.set("CharacterAlignment", crate::cjk::alignment_out(v));
}
if let Some(f) = &a.font_family {
- props.push(p("AppliedFont", "string", f.clone()));
- let style = a.font_style.clone().unwrap_or_else(|| "Regular".into());
- self.note_font(f, &style);
+ if let Some(composite) = self.d.styles.composite_font(f) {
+ props.push(p("AppliedFont", "object", format!("CompositeFont/{}", escape_id(&composite.name))));
+ } else {
+ props.push(p("AppliedFont", "string", f.clone()));
+ let style = a.font_style.clone().unwrap_or_else(|| "Regular".into());
+ self.note_font(f, &style);
+ }
}
if let Some(v) = &a.font_style {
el.set("FontStyle", v);
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index 3e1c17e28..ba1f3d245 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -104,6 +104,7 @@ struct Importer<'r> {
inks: designcraft_doc::InkManager,
stroke_styles: Vec<designcraft_doc::StrokeStyleDef>,
styles: Styles,
+ composite_names: HashMap<String, String>,
kinsoku: HashMap<String, designcraft_doc::cjk::Kinsoku>,
para_names: HashMap<String, String>,
char_names: HashMap<String, String>,
@@ -188,6 +189,7 @@ impl<'r> Importer<'r> {
inks: Default::default(),
stroke_styles: Vec::new(),
styles,
+ composite_names: HashMap::new(),
kinsoku: HashMap::new(),
para_names: HashMap::new(),
char_names: HashMap::new(),
@@ -273,6 +275,11 @@ impl<'r> Importer<'r> {
}
}
for e in top.iter().filter(|e| e.local() == "CompositeFont") {
+ let name =
+ e.get("Name").map(str::to_string).unwrap_or_else(|| unescape_id(e.get("Self").unwrap_or("").trim_start_matches("CompositeFont/")));
+ if let Some(id) = e.get("Self") {
+ self.composite_names.insert(id.to_string(), format!("CompositeFont/{name}"));
+ }
let entries = e
.find_all("CompositeFontEntry")
.map(|c| designcraft_doc::cjk::CompositeFontEntry {
@@ -287,7 +294,7 @@ impl<'r> Importer<'r> {
scale_option: c.boolean("ScaleOption").unwrap_or(true),
})
.collect();
- self.styles.composite_fonts.push(designcraft_doc::cjk::CompositeFont { name: unescape_id(e.get("Name").unwrap_or("")), entries });
+ self.styles.composite_fonts.push(designcraft_doc::cjk::CompositeFont { name, entries });
}
for e in top.iter().filter(|e| e.local() == "KinsokuTable") {
if e.get("CantBeginLineChars").is_some() || e.get("CantEndLineChars").is_some() {
@@ -1050,7 +1057,7 @@ impl<'r> Importer<'r> {
// 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(fam.to_string());
+ a.font_family = Some(self.composite_names.get(fam).cloned().unwrap_or_else(|| fam.to_string()));
}
}
a.font_style = e.prop("FontStyle");
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index b636a2ac1..956a5f19f 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -857,3 +857,40 @@ fn arabic_story_and_table_directions_survive_idml_export() {
assert_eq!(st.direction, designcraft_doc::TextDirection::RightToLeft);
assert_eq!(st.tables.values().next().unwrap().options.direction, designcraft_doc::TextDirection::RightToLeft);
}
+
+#[test]
+fn composite_references_resolve_by_identity_and_export_as_objects() {
+ let map = DESIGNMAP.replace("</Document>", r#"
+ <CompositeFont Self="CompositeFont/opaque%3a17" Name="Mixed%3a literal">
+ <CompositeFontEntry Name="Base" FontStyle="$ID/Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>
+ <CompositeFontEntry Name="Digits" CustomCharacters="0123456789" FontStyle="$ID/Bold" RelativeSize="80" HorizontalScale="90" VerticalScale="110" BaselineShift="5" ScaleOption="false"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry>
+ </CompositeFont></Document>"#);
+ let styles = STYLES
+ .replace("<AppliedFont type=\"string\">Source Serif 4</AppliedFont>", "<AppliedFont type=\"object\">CompositeFont/opaque%3a17</AppliedFont>");
+ let story = r#"<idPkg:Story xmlns:idPkg="http://ns.adobe.com/AdobeInDesign/idml/1.0/packaging"><Story Self="s1"><ParagraphStyleRange><CharacterStyleRange><Content>A1</Content><Footnote><ParagraphStyleRange><CharacterStyleRange><Content>B2</Content></CharacterStyleRange></ParagraphStyleRange></Footnote></CharacterStyleRange></ParagraphStyleRange></Story></idPkg:Story>"#;
+ let bytes = zip_files(&[
+ ("designmap.xml", &map),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", story),
+ ]);
+ let d = import_idml(&bytes).unwrap();
+ let f = &d.styles.composite_fonts[0];
+ assert_eq!(f.name, "Mixed%3a literal", "display names are not encoded identifiers");
+ let body = d.stories.values().find(|s| !s.notes.is_empty()).unwrap();
+ for text in [body.as_ref(), &body.notes[0].text] {
+ let (_, base) = d.styles.resolve_para(&text.paras[0]);
+ let p = d.styles.resolve_char(&base, &text.chars[0].format);
+ assert_eq!(d.styles.composite_font(&p.font_family), Some(f));
+ }
+ let output = export_idml(&d);
+ let mut zip = zip::ZipArchive::new(std::io::Cursor::new(&output)).unwrap();
+ let mut xml = String::new();
+ std::io::Read::read_to_string(&mut zip.by_name("Resources/Styles.xml").unwrap(), &mut xml).unwrap();
+ assert!(xml.contains("<AppliedFont type=\"object\">CompositeFont/Mixed%253a literal</AppliedFont>"), "{xml}");
+ let back = import_idml(&output).unwrap();
+ assert_eq!(back.styles.composite_fonts, d.styles.composite_fonts);
+}