Skip to content

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

IDML: font names with the $ID/ prefix resolve

aiongg580db95c7140
diff --git a/crates/fonts/src/fontdb.rs b/crates/fonts/src/fontdb.rs
index 14441e144..279379ca6 100644
--- a/crates/fonts/src/fontdb.rs
+++ b/crates/fonts/src/fontdb.rs
@@ -712,6 +712,14 @@ fn make_face(bytes: FontBytes, source: FontSource, index: u32, family: String, s
})
}
+/// `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
/// several formats (`Minion Pro (OTF)` → `Minion Pro`), if it has one.
fn without_format_suffix(family: &str) -> Option<&str> {
@@ -1228,7 +1236,7 @@ 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);
- match without_format_suffix(family) {
+ match plain_family(family) {
Some(base) if v.is_empty() => self.exact_styles(base),
_ => v,
}
@@ -1255,9 +1263,10 @@ impl ScopedFonts<'_> {
/// 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(|| without_format_suffix(family).and_then(|base| self.find_or_load(base, style))) {
+ if let Some(f) = self.find_or_load(family, style).or_else(|| plain_family(family).and_then(|base| self.find_or_load(base, style))) {
return f;
}
self.find(FALLBACK_FAMILY, style)
@@ -1278,9 +1287,9 @@ impl ScopedFonts<'_> {
}
/// 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.has_exact_family(family) || without_format_suffix(family).is_some_and(|base| self.has_exact_family(base))
+ 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 {
diff --git a/crates/fonts/src/lib.rs b/crates/fonts/src/lib.rs
index c1d744780..70ec8cf19 100644
--- a/crates/fonts/src/lib.rs
+++ b/crates/fonts/src/lib.rs
@@ -437,6 +437,20 @@ mod tests {
assert!(!db.has_family("DC Test Suffix"));
}
+ /// IDML files from InDesign can name a family with its `$ID/` prefix (`$ID/Arial`).
+ #[test]
+ fn an_indesign_id_prefix_names_the_plain_family() {
+ let db = FontDb::with_font_dirs(Vec::new());
+ db.set_system_fallback(false);
+ let prefixed = format!("$ID/{DEFAULT_FAMILY}");
+ assert_eq!(db.face(&prefixed, "Bold").family, DEFAULT_FAMILY);
+ assert!(db.has_family(&prefixed));
+ assert_eq!(db.styles(&prefixed), db.styles(DEFAULT_FAMILY));
+ assert!(db.has_family(&format!("$ID/{DEFAULT_FAMILY} (OTF)")));
+ assert!(!db.has_family("$ID/"));
+ assert!(!db.has_family("$ID/DC No Such Family"));
+ }
+
#[test]
fn outlines_and_metrics() {
let db = FontDb::global();
diff --git a/crates/idml/src/import.rs b/crates/idml/src/import.rs
index d85d9ee02..5276f74cb 100644
--- a/crates/idml/src/import.rs
+++ b/crates/idml/src/import.rs
@@ -291,7 +291,7 @@ impl<'r> Importer<'r> {
.map(|c| designcraft_doc::cjk::CompositeFontEntry {
name: c.get("Name").unwrap_or("").into(),
characters: c.get("CustomCharacters").unwrap_or("").into(),
- family: c.prop("AppliedFont").unwrap_or_default(),
+ family: c.prop("AppliedFont").as_deref().and_then(names::font_family_in).unwrap_or_default(),
style: c.get("FontStyle").unwrap_or("Regular").trim_start_matches("$ID/").into(),
relative_size: c.num("RelativeSize").unwrap_or(100.0) / 100.0,
horizontal_scale: c.num("HorizontalScale").unwrap_or(100.0) / 100.0,
@@ -1064,15 +1064,7 @@ impl<'r> Importer<'r> {
}
fn char_attrs(&mut self, e: &El) -> CharAttrs {
- 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(fam.to_string());
- }
- }
+ let mut a = CharAttrs { font_family: e.prop("AppliedFont").as_deref().and_then(names::font_family_in), ..Default::default() };
a.font_style = e.prop("FontStyle");
a.size = e.num("PointSize");
a.leading = e.prop("Leading").and_then(|l| names::leading_in(l.trim()));
diff --git a/crates/idml/src/names.rs b/crates/idml/src/names.rs
index 1df0f56d5..bba20370b 100644
--- a/crates/idml/src/names.rs
+++ b/crates/idml/src/names.rs
@@ -81,6 +81,15 @@ pub fn unescape_id(s: &str) -> String {
s.replace("%3a", ":").replace("%3A", ":").replace("%25", "%")
}
+/// An `AppliedFont` value → font family. InDesign can write the family with its `$ID/` prefix
+/// (`$ID/Arial`), and `$ID/` alone for no font; some writers append the style after a tab.
+pub fn font_family_in(v: &str) -> Option<String> {
+ let v = v.trim();
+ let family = v.split('\t').next().unwrap_or(v);
+ let family = family.strip_prefix("$ID/").unwrap_or(family).trim();
+ (!family.is_empty()).then(|| family.to_string())
+}
+
/// Built-in style names: (ours, IDML `Name`).
pub const PARA_BUILTINS: &[(&str, &str)] = &[("[No Paragraph Style]", "$ID/[No paragraph style]"), ("[Basic Paragraph]", "$ID/NormalParagraphStyle")];
pub const CHAR_BUILTINS: &[(&str, &str)] = &[("[None]", "$ID/[No character style]")];
diff --git a/crates/idml/src/tests.rs b/crates/idml/src/tests.rs
index 7b747587a..ce98f6e8c 100644
--- a/crates/idml/src/tests.rs
+++ b/crates/idml/src/tests.rs
@@ -838,7 +838,7 @@ fn cjk_composite_fonts_and_custom_kinsoku_are_document_resources() {
let map = DESIGNMAP.replace("</Document>", r#"
<KinsokuTable Self="KinsokuTable/Test" Name="Test" CantBeginLineChars="乙" CantEndLineChars="甲" CantBeSeparatedChars="—" HangingPunctuationChars="。"/>
<CompositeFont Self="CompositeFont/Mixed" Name="Mixed"><CompositeFontEntry Self="cf1" Name="Base" FontStyle="Regular"><Properties><AppliedFont type="string">Source Serif 4</AppliedFont></Properties></CompositeFontEntry>
- <CompositeFontEntry Self="cf2" Name="Digits" CustomCharacters="0123456789" FontStyle="Regular" RelativeSize="80" BaselineShift="10"><Properties><AppliedFont type="string">Source Sans 3</AppliedFont></Properties></CompositeFontEntry></CompositeFont>
+ <CompositeFontEntry Self="cf2" Name="Digits" CustomCharacters="0123456789" FontStyle="Regular" RelativeSize="80" BaselineShift="10"><Properties><AppliedFont type="string">$ID/Source Sans 3</AppliedFont></Properties></CompositeFontEntry></CompositeFont>
</Document>"#);
let story = STORY.replace("<ParagraphStyleRange ", "<ParagraphStyleRange KinsokuSet=\"KinsokuTable/Test\" ");
let bytes = zip_files(&[
@@ -1399,3 +1399,41 @@ fn list_numbering_format_expression_and_bullet_import_and_round_trip() {
check(&d);
check(&import_idml(&export_idml(&d)).unwrap());
}
+
+/// InDesign can write `AppliedFont` with its `$ID/` prefix (`$ID/Source Serif 4`). The text is
+/// set in that family instead of counting as a missing font drawn in the fallback.
+#[test]
+fn applied_font_with_an_id_prefix_names_the_family() {
+ let styles = STYLES.replace(">Source Serif 4</AppliedFont>", ">$ID/Source Serif 4</AppliedFont>");
+ let story = STORY.replace(
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14">"#,
+ r#"<CharacterStyleRange AppliedCharacterStyle="CharacterStyle/Strong" PointSize="14"><Properties><AppliedFont type="string">$ID/Source Serif 4</AppliedFont></Properties>"#,
+ );
+ let bytes = zip_files(&[
+ ("designmap.xml", DESIGNMAP),
+ ("Resources/Graphic.xml", GRAPHIC),
+ ("Resources/Styles.xml", &styles),
+ ("Resources/Preferences.xml", PREFS),
+ ("MasterSpreads/MasterSpread_m1.xml", MASTER),
+ ("Spreads/Spread_sp1.xml", SPREAD),
+ ("Stories/Story_s1.xml", &story),
+ ]);
+ let d = import_idml_with(&bytes, &|_| None).unwrap();
+ let fonts: Vec<&str> = d.styles.paragraph.iter().filter_map(|s| s.chars.font_family.as_deref()).collect();
+ assert!(!fonts.is_empty() && fonts.iter().all(|f| *f == "Source Serif 4"), "{fonts:?}");
+ let (sid, story) = d.stories.iter().next().unwrap();
+ let bold = story.runs().find(|(r, _)| story.text[r.clone()].starts_with("bold")).unwrap().1;
+ assert_eq!(bold.over.font_family.as_deref(), Some("Source Serif 4"));
+ // The bundled family draws the text (an unknown family would fall back to Source Sans 3).
+ let cs = designcraft_compose::compose_story(&d, *sid, &Default::default());
+ let first_para = story.text.find('\n').unwrap();
+ let families: Vec<&str> = cs
+ .frames
+ .iter()
+ .flat_map(|f| &f.lines)
+ .flat_map(|l| &l.glyphs)
+ .filter(|g| g.visible && g.len > 0 && g.byte < first_para)
+ .map(|g| g.face.get().family.as_str())
+ .collect();
+ assert!(!families.is_empty() && families.iter().all(|f| *f == "Source Serif 4"), "{families:?}");
+}