From c3be9f094fa1baee182cc9868371e71275ca31df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A2n=20Minh=20Ngh=C4=A9a?= Date: Wed, 18 Nov 2026 16:28:30 +0700 Subject: [PATCH] #2702: a missing font is drawn in its font table's altName, as Word does A missing font is drawn in its font table altName, as Word does. The DOCX reader half lives in craft-libs#1426; this is the fonts, layout and settings half. Originally authored by @Nghiathan13 in #2711. --- crates/doc/src/settings.rs | 11 +++ crates/fonts/src/word.rs | 82 +++++++++++++++--- crates/layout/src/para/builder.rs | 32 ++++--- crates/layout/src/para/chars.rs | 62 ++++++++++---- crates/layout/src/tests.rs | 133 +++++++++++++++++++++++++++++ crates/layout/src/tests/complex.rs | 51 +++++++++++ 6 files changed, 330 insertions(+), 41 deletions(-) diff --git a/crates/doc/src/settings.rs b/crates/doc/src/settings.rs index b97019351c..1fd4e598dd 100644 --- a/crates/doc/src/settings.rs +++ b/crates/doc/src/settings.rs @@ -128,6 +128,15 @@ pub struct Settings { /// draws one that isn't installed in a serif face. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub roman_fonts: Vec, + /// Fonts the font table classes as modern (fixed pitch, `w:family w:val="modern"`): Word draws + /// one that isn't installed, and whose alternate isn't either, in a serif face (#2702). Not + /// the East Asian ones (`w:charset` 80, 81, 86, 88: MS Gothic, SimHei…). + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub modern_fonts: Vec, + /// Alternate names the document's font table gives its fonts (`w:font/w:altName`), as (font, + /// alternate): Word draws a font that isn't installed in its alternate when that one is. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub font_alt_names: Vec<(String, String)>, /// `w:doNotUseHTMLParagraphAutoSpacing`: the space between two paragraphs is the first's space /// after plus the second's space before, not the larger of the two. #[serde(default, skip_serializing_if = "std::ops::Not::not")] @@ -325,6 +334,8 @@ impl Default for Settings { protect_hash: Vec::new(), compat_mode: COMPAT_MODE_CURRENT, roman_fonts: Vec::new(), + modern_fonts: Vec::new(), + font_alt_names: Vec::new(), sum_paragraph_spacing: false, do_not_expand_shift_return: false, allow_space_of_same_style_in_table: false, diff --git a/crates/fonts/src/word.rs b/crates/fonts/src/word.rs index 4860faf5a0..f9352a95bf 100644 --- a/crates/fonts/src/word.rs +++ b/crates/fonts/src/word.rs @@ -40,6 +40,23 @@ pub fn has_named_substitutes(family: &str) -> bool { const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"]; +/// Serif faces known by name with no open clone of their own (lowercase): they take the generic +/// serif list, but as fonts we know, not by a guess from the name ([`has_own_substitutes`]). +const KNOWN_SERIFS: &[&str] = &[ + "cambria", + "cambria math", + "georgia", + "garamond", + "constantia", + "baskerville old face", + "century", + "century schoolbook", + "bookman old style", + "sitka text", + "sitka", + "aptos serif", +]; + /// [`substitutes`], and whether they were chosen for this family by name. fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) { if family.contains(';') { @@ -149,18 +166,7 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) { "courier new" | "courier" | "consolas" | "lucida console" | "cascadia code" | "cascadia mono" => (MONO, true), "symbol" | "wingdings" | "wingdings 2" | "wingdings 3" | "segoe ui symbol" | "webdings" => (SYMBOL, true), // Serif faces with no open clone of their own: the generic serif list, as for any font. - "cambria" - | "cambria math" - | "georgia" - | "garamond" - | "constantia" - | "baskerville old face" - | "century" - | "century schoolbook" - | "bookman old style" - | "sitka text" - | "sitka" - | "aptos serif" => (SERIF, false), + _ if KNOWN_SERIFS.contains(&f.as_str()) => (SERIF, false), _ if f.contains("mono") || f.contains("code") => (MONO, false), _ if f.contains("serif") && !f.contains("sans") => (SERIF, false), _ => (SANS, false), @@ -207,6 +213,22 @@ pub fn charset_base_family(family: &str) -> &str { .map_or(family, str::trim_end) } +/// Whether `family` (or the font its charset name stands for) has substitutes of its own: Times +/// New Roman, Book Antiqua, Courier New, the symbol, Hebrew and Persian fonts, or a serif face we +/// know (Georgia, Garamond…), rather than the generic list a font we don't know gets, also when +/// its name only suggests one ("… Mono", "… Serif"). +pub fn has_own_substitutes(family: &str) -> bool { + let base = charset_base_family(family); + has_named_substitutes(base) || KNOWN_SERIFS.contains(&base.to_ascii_lowercase().as_str()) +} + +/// Whether `family` has substitutes of its own ([`has_own_substitutes`]) and one of them is +/// installed, so [`resolve`] draws it in a face chosen for it rather than the generic fallback. +pub fn has_installed_substitute(family: &str) -> bool { + let base = charset_base_family(family); + has_own_substitutes(base) && substitute(FontDb::global(), base).is_some() +} + /// Fonts made to measure alike (the same advance widths and line height), so text drawn in one /// wraps and paginates as in the others: Carlito for Calibri, Caladea for Cambria, Liberation and /// Croscore fonts for Arial, Times New Roman and Courier New, the Palatino look-alikes for Palatino @@ -848,6 +870,42 @@ mod tests { assert_eq!(substitutes(charset_base_family("Times New Roman Cyr")), substitutes("Times New Roman")); } + /// #2702 review: an alternate counts as drawable only when one of its own substitutes is + /// installed; a font without a list of its own never does. + #[test] + fn installed_substitutes_are_the_fonts_own_and_installed() { + let db = FontDb::global(); + for f in ["Times New Roman", "Wingdings", "Courier New", "Book Antiqua"] { + let any = substitutes(f).iter().any(|s| db.has_family(s)); + assert_eq!(has_installed_substitute(f), any, "{f}"); + } + for f in ["No Such Brand Font", ""] { + assert!(!has_installed_substitute(f), "{f}"); + } + } + + #[test] + fn fonts_known_by_name_have_their_own_substitutes() { + for f in [ + "Times New Roman", + "times", + "Times New Roman Cyr", + "Book Antiqua", + "Palatino Linotype", + "Courier New", + "Arial", + "Georgia", + "Wingdings", + "David", + ] { + assert!(has_own_substitutes(f), "{f}"); + } + // A name that only suggests a list ("… Mono", "… Serif") isn't a font we know. + for f in ["No Such Brand Font", "NewCenturySchlbk", "", "Brand Serif", "Foo Mono", "Source Code Pro"] { + assert!(!has_own_substitutes(f), "{f}"); + } + } + #[test] fn pcl6_symbol_has_symbols_line_metrics() { assert_eq!(symbol_font_metrics("Symbol (PCL6)"), symbol_font_metrics("Symbol")); diff --git a/crates/layout/src/para/builder.rs b/crates/layout/src/para/builder.rs index 99ae60f6f3..927887baba 100644 --- a/crates/layout/src/para/builder.rs +++ b/crates/layout/src/para/builder.rs @@ -214,7 +214,9 @@ impl<'a> Builder<'a> { if let Some(f) = missing.latin.filter(|_| asks_latin) { self.note_substituted(f, drawn); } - if let Some(f) = missing.east_asian.filter(|_| !in_ea_font && sub.chars().any(east_asian)) { + // A missing East Asian font has no face of its own: CJK text drawn in the East Asian + // face is in its font table alternate (#2702) and still asks for it. + if let Some(f) = missing.east_asian.filter(|_| sub.chars().any(east_asian)) { self.note_substituted(f, drawn); } } @@ -248,25 +250,29 @@ impl<'a> Builder<'a> { let rc_cs: Option> = text.chars().any(|c| rc.uses_complex(c)).then(|| Arc::new(rc.complex())); let family = lookup_family(self.env.doc, &rc.font); let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic); + // The requested font is missing when it was substituted, or when another family stands in + // for it: its font table alternate (#2702), which may itself be installed. + let requested_missing = resolved.substituted || !family.eq_ignore_ascii_case(&rc.font); let primary = resolved.face; // Symbol-font characters are laid out as their Unicode equivalents. let sym = SymbolRun::of(&rc.font, &resolved); let show = |c: char| sym.map_or(c, |m| m.show(c)); - // A font isn't installed when it was substituted, or looked up as a missing roman font. + // A font isn't installed when it was substituted, or looked up as a missing roman font or + // its font table alternate (#2702). let resolved_cs = rc_cs.as_ref().map(|r| { let family = lookup_family(self.env.doc, &r.font); let resolved = wordcraft_fonts::word::resolve(family, r.bold, r.italic); - (resolved.face, resolved.substituted || family != r.font) + (resolved.face, resolved.substituted || !family.eq_ignore_ascii_case(&r.font)) }); let primary_cs = resolved_cs.map(|(face, _)| face); // Chinese, Japanese and Korean characters use the run's East Asian font (`w:eastAsia`) when - // it is installed and has them. - let wanted_ea = rc - .font_ea - .as_deref() - .filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)) - .map(|f| (f, wordcraft_fonts::word::resolve(f, rc.bold, rc.italic))); - let primary_ea = wanted_ea.filter(|(_, r)| !r.substituted).map(|(_, r)| r.face); + // it, or the font table alternate it is drawn in (#2702), is installed and has them. + let wanted_ea = rc.font_ea.as_deref().filter(|f| !f.eq_ignore_ascii_case(&rc.font) && text.chars().any(east_asian)).map(|f| { + let family = lookup_family(self.env.doc, f); + let resolved = wordcraft_fonts::word::resolve(family, rc.bold, rc.italic); + (f, resolved, resolved.substituted || !family.eq_ignore_ascii_case(f)) + }); + let primary_ea = wanted_ea.filter(|(_, r, _)| !r.substituted).map(|(_, r, _)| r.face); // The levels by byte of `text`, from `lbase` on. let (levels, lbase): (&[u8], usize) = match dir { Dir::Para => (&self.levels, base), @@ -278,7 +284,7 @@ impl<'a> Builder<'a> { // A missing Thai font: one face for the run's Thai and Latin text (#1549). A run with its // own complex-script font keeps that font for the Thai letters. let run_face: Option = if primary_cs.is_none_or(|f| f.id() == primary.id()) { - thai_run_face(&rc.font, resolved.substituted, primary, text, rc.bold, rc.italic) + thai_run_face(&rc.font, requested_missing, primary, text, rc.bold, rc.italic) } else { None }; @@ -314,9 +320,9 @@ impl<'a> Builder<'a> { context: &context, }); let missing = MissingFonts { - latin: (resolved.substituted || family != rc.font).then_some(rc.font.as_str()), + latin: requested_missing.then_some(rc.font.as_str()), complex: rc_cs.as_ref().filter(|_| resolved_cs.is_some_and(|(_, missing)| missing)).map(|r| r.font.as_str()), - east_asian: wanted_ea.filter(|(_, r)| r.substituted).map(|(f, _)| f), + east_asian: wanted_ea.filter(|(_, _, missing)| *missing).map(|(f, _, _)| f), names_east_asian: wanted_ea.is_some(), }; self.note_missing_fonts(text, &segs, (primary, primary_cs, primary_ea), &missing); diff --git a/crates/layout/src/para/chars.rs b/crates/layout/src/para/chars.rs index b68d578287..d8c0bec822 100644 --- a/crates/layout/src/para/chars.rs +++ b/crates/layout/src/para/chars.rs @@ -124,23 +124,52 @@ pub(crate) fn remap_range(map_starts: &[usize], orig_of: &[usize], orig_len: usi /// as roman (measured in Word; Calibri otherwise, which our own substitutes already match). pub(super) const MISSING_ROMAN_FONT: &str = "Cambria"; -/// The family to look `font` up as: [`MISSING_ROMAN_FONT`] for a missing roman font, else `font`. -/// A missing Thai font keeps its name: it is drawn in a Thai face, not in Cambria (#1549). -/// A font with substitutes of its own keeps them: Times New Roman is roman in every font table, -/// and where it isn't installed Liberation Serif has its metrics; Word never meets it missing. -pub(super) fn lookup_family<'f>(doc: &Document, font: &'f str) -> &'f str { +/// The family to look `font` up as. A font that isn't installed is drawn, as Word draws it +/// (measured in Word 2024, #2702): +/// 1. in the alternate the font table names for it (`w:altName`), when that one can be drawn: +/// installed, or a font one of whose own substitutes is installed. That comes before the +/// family class: a roman font with an installed alternate is drawn in the alternate; +/// 2. in [`MISSING_ROMAN_FONT`] when the font table classes it as roman, or as modern with an +/// alternate that can't be drawn either (a modern font with no alternate, and a swiss one with +/// or without, take the generic substitutes, as Calibri does in Word). Not for a Thai font +/// (drawn in a Thai face, #1549), a symbol font, or a font with substitutes of its own (Times +/// New Roman is roman in every font table, and where it isn't installed Liberation Serif has +/// its metrics; Word never meets it missing); +/// 3. else as `font`, which [`wordcraft_fonts::word::resolve`] substitutes. +pub(super) fn lookup_family<'f>(doc: &'f Document, font: &'f str) -> &'f str { + let settings = &doc.settings; + // A fallback list (`Liberation Serif;Times New Roman`) is in a class when one of its + // candidates is. + let listed = |list: &[String]| { + !list.is_empty() && font.split(';').map(str::trim).filter(|f| !f.is_empty()).any(|f| list.iter().any(|r| r.eq_ignore_ascii_case(f))) + }; + let alternate = settings.font_alt_names.iter().find(|(f, _)| f.eq_ignore_ascii_case(font)).map(|(_, alt)| alt.as_str()); + let roman = listed(&settings.roman_fonts); + if alternate.is_none() && !roman { + return font; + } let db = wordcraft_fonts::FontDb::global(); - let roman = !doc.settings.roman_fonts.is_empty() - && font.split(';').map(str::trim).filter(|f| !f.is_empty()).any(|f| doc.settings.roman_fonts.iter().any(|r| r.eq_ignore_ascii_case(f))); - if roman + let installed = |f: &str| db.has_family(f) || db.has_family(wordcraft_fonts::word::charset_base_family(f)); + // A fallback list is there when one of its candidates is. + let missing = if font.contains(';') { wordcraft_fonts::word::resolve(font, false, false).substituted } else { !installed(font) }; + if !missing { + return font; + } + // Calibri has no list of its own because the generic sans list is its (Carlito first). + let drawable = + |f: &&str| !f.is_empty() && (installed(f) || wordcraft_fonts::word::has_installed_substitute(f) || f.eq_ignore_ascii_case("Calibri")); + // ECMA-376 calls the alternate a comma-separated list, but Word reads the whole value as one + // name (MS-OE376 2.1.264), so a value with a comma names a font that isn't there. + if let Some(alt) = alternate.map(str::trim).filter(drawable) { + return alt; + } + let modern_alternate_missing = alternate.is_some() && listed(&settings.modern_fonts); + // Thai, symbol and fonts with substitutes of their own keep their name: those substitutes + // draw them, Cambria wouldn't. + if (roman || modern_alternate_missing) && !wordcraft_fonts::word::is_thai_family(font) && !wordcraft_doc::symbol_fonts::is_symbol_font(font) && !wordcraft_fonts::word::has_named_substitutes(font) - && if font.contains(';') { - wordcraft_fonts::word::resolve(font, false, false).substituted - } else { - !db.has_family(font) && !db.has_family(wordcraft_fonts::word::charset_base_family(font)) - } { MISSING_ROMAN_FONT } else { @@ -150,9 +179,10 @@ pub(super) fn lookup_family<'f>(doc: &Document, font: &'f str) -> &'f str { /// One face for a run in a Thai font that isn't installed (#1549): Word substitutes one font /// (Cordia New) for the whole run, so the Latin letters, digits and ฿ keep the Thai letters' face -/// and size. `None` unless `font` is a Thai family, it was substituted, and its substitute -/// `primary` lacks some of the run's Thai or Latin characters; then the first face covering all of -/// them, if one does. Other families keep Latin text in their own substitute, as Word does. +/// and size. `None` unless `font` is a Thai family, it was substituted (or drawn in its font +/// table alternate, #2702), and its stand-in `primary` lacks some of the run's Thai or Latin +/// characters; then the first face covering all of them, if one does. Other families keep Latin +/// text in their own substitute, as Word does. pub(crate) fn thai_run_face(font: &str, substituted: bool, primary: FaceRef, text: &str, bold: bool, italic: bool) -> Option { if !substituted || !wordcraft_fonts::word::is_thai_family(font) { return None; diff --git a/crates/layout/src/tests.rs b/crates/layout/src/tests.rs index 7566437088..ff3b0a9274 100644 --- a/crates/layout/src/tests.rs +++ b/crates/layout/src/tests.rs @@ -1429,6 +1429,93 @@ fn a_missing_roman_font_is_drawn_as_word_draws_it() { assert_ne!(face(false), cambria); } +#[test] +fn a_missing_font_is_drawn_in_its_font_table_alternate() { + crate::test_fonts(); + // Measured in Word 2024 and Word for Windows 16.0.20527 (#2702): a font that isn't installed is + // drawn in the alternate its font table names (`w:altName`), before the roman rule; an + // alternate that can't be drawn either leaves the family class in charge: Cambria for a roman + // or modern font, the generic substitutes (Calibri in Word) for a swiss one. + #[derive(Clone, Copy)] + enum Family { + Swiss, + Roman, + Modern, + } + let face_of = |alt: Option<&str>, family: Family| { + let mut d = Document::from_text("Lanterns"); + if let Some(alt) = alt { + d.settings.font_alt_names = vec![("No Such Brand Font".into(), alt.into())]; + } + match family { + Family::Roman => d.settings.roman_fonts = vec!["No Such Brand Font".into()], + Family::Modern => d.settings.modern_fonts = vec!["No Such Brand Font".into()], + Family::Swiss => {} + } + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some("No Such Brand Font".into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + para.styles[first.style as usize].face + }; + let face = |alt: Option<&str>, roman: bool| face_of(alt, if roman { Family::Roman } else { Family::Swiss }); + let resolve = |f: &str| wordcraft_fonts::word::resolve(f, false, false).face; + let (courier, times, calibri, cambria) = (resolve("Courier New"), resolve("Times New Roman"), resolve("Calibri"), resolve("Cambria")); + let generic = face(None, false); + // Serif and sans faces are bundled, so these differ on any machine. + assert_ne!(times, generic); + assert_ne!(cambria, generic); + // A, B: a missing font with an alternate. + assert_eq!(face(Some("Times New Roman"), false), times); + assert_eq!(face(Some("Courier New"), false), courier); + // go_math (docxide-pdf corpus): Museo Sans 300 → Calibri. + assert_eq!(face(Some("Calibri"), false), calibri); + // D: the alternate beats the roman rule. + assert_eq!(face(Some("Times New Roman"), true), times); + assert_eq!(face(Some("Courier New"), true), courier); + // E: an alternate that is missing too, with no substitutes of its own: the roman rule, or the + // generic substitutes for a font that isn't roman. + assert_eq!(face(Some("No Such Alternate"), true), cambria); + assert_eq!(face(Some("No Such Alternate"), false), generic); + // Word reads a value with a comma as one name, not a list (MS-OE376 2.1.264): no font is + // called that, so the roman rule or the generic substitutes draw it. + assert_eq!(face(Some("No Such Alternate, Times New Roman"), false), generic); + assert_eq!(face(Some("No Such Alternate, Times New Roman"), true), cambria); + // A modern font: its installed alternate draws it, a missing alternate leaves it in Cambria, + // and with no alternate at all it takes the generic substitutes (Calibri in Word). + assert_eq!(face_of(Some("Courier New"), Family::Modern), courier); + assert_eq!(face_of(Some("No Such Alternate"), Family::Modern), cambria); + assert_eq!(face_of(None, Family::Modern), generic); + // An alternate that names another missing font with an alternate of its own: the chain isn't + // followed. + let mut d = Document::from_text("Lanterns"); + d.settings.font_alt_names = vec![("No Such Brand Font".into(), "No Such Alternate".into()), ("No Such Alternate".into(), "Courier New".into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some("No Such Brand Font".into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + assert_eq!(para.styles[first.style as usize].face, generic, "the chain isn't followed"); +} + +#[test] +fn an_installed_font_ignores_its_font_table_alternate() { + // The alternate is only for a font that isn't there: an installed (here bundled) font keeps its + // own face. + let font = wordcraft_fonts::FALLBACK_FAMILY; + let mut d = Document::from_text("Lanterns"); + d.settings.font_alt_names = vec![(font.into(), "Times New Roman".into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some(font.into()); + let l = lay(&d); + let Some(Placed::Lines { para, .. }) = l.pages[0].items.iter().find(|i| matches!(i, Placed::Lines { .. })) else { panic!("no text") }; + let first = para.clusters.first().expect("a cluster"); + let own = wordcraft_fonts::word::resolve(font, false, false).face; + assert_ne!(own, wordcraft_fonts::word::resolve("Times New Roman", false, false).face); + assert_eq!(para.styles[first.style as usize].face, own); +} + #[test] fn a_missing_roman_font_with_its_own_substitute_keeps_it() { crate::test_fonts(); @@ -10634,6 +10721,52 @@ fn east_asian_text_takes_the_asian_font_and_latin_text_the_latin_font() { } } +#[test] +fn a_missing_east_asian_font_is_drawn_in_its_font_table_alternate() { + crate::test_fonts(); + // #2702 for the run's East Asian font (`w:eastAsia`): one that isn't installed is drawn in the + // alternate its font table names, when that one is installed and has the characters. Take an + // installed CJK font other than the one fallback would pick anyway, so the test tells them apart. + let resolve = |f: &str| wordcraft_fonts::word::resolve(f, false, false); + let fallback = wordcraft_fonts::FontDb::global().fallback_for('你', 0).map(|f| f.family.clone()); + let Some(asian) = wordcraft_fonts::FontDb::global().east_asian_families().into_iter().find(|f| { + let r = resolve(f); + Some(f) != fallback.as_ref() && !r.substituted && r.face.covers('你') && r.face.covers('好') + }) else { + eprintln!("skipped: no second Chinese font installed"); + return; + }; + let missing = "No Such East Asian Font 2702"; + let text = "Hello 你好"; + let faces = |alternate: bool| { + let mut d = Document::from_text(text); + if alternate { + d.settings.font_alt_names = vec![(missing.into(), asian.clone())]; + } + d.format_range(&Pos::body(0, 0), &Pos::body(0, text.len()), &|c| { + c.font = Some(wordcraft_doc::styles::BODY_FONT.into()); + c.font_ea = Some(missing.into()); + }) + .unwrap(); + let l = lay(&d); + let para = + l.pages.iter().flat_map(|p| p.items.iter()).find_map(|it| if let Placed::Lines { para, .. } = it { Some(para) } else { None }).unwrap(); + let drawn = para + .clusters + .iter() + .filter(|c| text.get(c.start..c.end).and_then(|s| s.chars().next()).is_some_and(|ch| !ch.is_ascii())) + .map(|c| para.styles[c.style as usize].face.id()) + .collect::>(); + (drawn, l.substituted_fonts()) + }; + let asian_face = resolve(&asian).face.id(); + let (with, reported) = faces(true); + assert!(!with.is_empty() && with.iter().all(|f| *f == asian_face), "你好 in the alternate {asian}"); + // Drawn in an installed alternate, the font asked for is still missing (#4770). + assert!(reported.iter().any(|(f, _)| f == missing), "{reported:?}"); + assert!(faces(false).0.iter().all(|f| *f != asian_face), "without the alternate, fallback picks another font"); +} + /// A page total in the footer ("Page X of Y") is filled in after pagination, so it doesn't make /// the body lay out a second time; one in the body still does. #[test] diff --git a/crates/layout/src/tests/complex.rs b/crates/layout/src/tests/complex.rs index 206f48875a..31fc2576cc 100644 --- a/crates/layout/src/tests/complex.rs +++ b/crates/layout/src/tests/complex.rs @@ -167,6 +167,57 @@ fn a_missing_thai_font_draws_the_whole_run_in_one_thai_face() { } } +/// Body paragraph 0 of `text` at 16 pt, its run set in `font` whose font table alternate +/// (`w:altName`) is `alt`, and the face of every cluster: (cluster start, face). +fn cluster_faces_with_alternate(text: &str, font: &str, alt: &str) -> Vec<(usize, wordcraft_fonts::FaceRef)> { + let mut d = Document::from_text(text); + d.settings.font_alt_names = vec![(font.into(), alt.into())]; + let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap(); + p.runs[0].props.font = Some(font.into()); + p.runs[0].props.size = Some(16.0); + let l = lay(&d); + let pl = para_layout(&l, 0); + pl.clusters.iter().map(|c| (c.start, pl.styles[c.style as usize].face)).collect() +} + +#[test] +fn a_missing_thai_font_with_a_latin_alternate_still_draws_the_run_in_one_face() { + if !thai_font_installed() { + eprintln!("skipped: no Thai font installed"); + return; + } + // #2702 draws a missing font in its font table alternate. When the font is Thai and the + // installed alternate has no Thai letters, the run still takes one face for its Thai and + // Latin text (#1549), not the alternate for the Latin and per-letter fallback for the Thai. + let alt = "Source Sans 3"; + let alt_face = wordcraft_fonts::word::resolve(alt, false, false).face; + assert!(!alt_face.covers('\u{0E19}'), "{} has no Thai, so the run must move", alt_face.family); + let db = wordcraft_fonts::FontDb::global(); + // One face for the run needs a Thai font with Latin letters and digits too. + let thai_latin = thai_latin_font_installed(); + if !thai_latin { + eprintln!("skipped the one-face cases: no Thai font with Latin letters installed"); + } + for font in ["TH Sarabun New", "Angsana New"] { + if !thai_latin || db.has_family(font) { + continue; + } + let faces = cluster_faces_with_alternate(THAI_RUN, font, alt); + let first = faces[0].1; + let names: Vec<&str> = faces.iter().map(|(_, f)| f.family.as_str()).collect(); + assert!(faces.iter().all(|(_, f)| f.id() == first.id()), "{font} (alternate {alt}): one face for the run, not {names:?}"); + assert!(first.covers('\u{0E19}') && first.covers('D') && first.covers('1') && first.covers('\u{0E3F}'), "{font} → {}", first.family); + // A Latin-only run in the same font is drawn in the alternate, as #2702 has it. + let latin = cluster_faces_with_alternate("Lanterns 1,250", font, alt); + assert!(latin.iter().all(|(_, f)| f.id() == alt_face.id()), "{font}: Latin text in {alt}"); + } + // A missing Latin font with the same alternate isn't Thai: its Latin text stays in the + // alternate and only the Thai letters fall back. + let faces = cluster_faces_with_alternate("Hello \u{0E2A}\u{0E27}\u{0E31}\u{0E2A}\u{0E14}\u{0E35}", "No Such Latin Font 2702", alt); + assert!(faces.iter().filter(|(at, _)| *at < 5).all(|(_, f)| f.id() == alt_face.id()), "Hello stays in {alt}"); + assert!(faces.iter().any(|(at, f)| *at >= 6 && f.id() != alt_face.id()), "the Thai letters fall back"); +} + #[test] fn a_thai_substitute_without_latin_hands_the_run_to_one_face_covering_it() { crate::test_fonts();