// SPDX-FileCopyrightText: 2026 Jandira Technologies, LLC
//
// SPDX-License-Identifier: Apache-2.0
//! Bundled metric-compatible faces (Carlito = Calibri, Liberation Sans =
//! Arial, Liberation Serif = Times New Roman, Liberation Mono = Courier
//! New) plus glyph advances for wrap and PDF embedding.
//!
//! The public surface is the conversion's font report: the
//! [`FontStep`] a face was reached from, one [`FontReportEntry`] per
//! distinct family + style the run used, and a JSON dump
//! ([`font_report_json`]). The bundled catalogue itself is internal.
use std::cell::RefCell;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Write as _};
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::{Arc, LazyLock, Mutex, OnceLock};
/// `w:noBreakHyphen` in run text: the line breaker never splits at it.
pub(crate) const NO_BREAK_HYPHEN: char = '\u{2011}';
/// The character a face paints for `ch`. Word paints a non-breaking hyphen
/// as the face's hyphen-minus (0x2D in its PDFs): most faces (Arial,
/// Calibri, Aptos) have no U+2011 glyph.
fn painted_char(ch: char) -> char {
if ch == NO_BREAK_HYPHEN { '-' } else { ch }
}
/// The Unicode character behind a Symbol face's code (the low byte of its
/// U+F0xx character), by Adobe's Symbol encoding: U+F0B7 is the bullet,
/// U+F061 alpha. `None` for the codes Unicode has no character for (the
/// bracket and radical pieces). Where Adobe's table names a character a
/// text face never has, the one it does have stands: Greek Δ and Ω for the
/// increment and ohm signs, ® © ™ for the corporate-use serif and sans
/// marks, 〈 〉 for the deprecated angle brackets, and € at 0xA0 as Apple's
/// Symbol has it. A code whose character the face lacks paints nothing
/// (the card suits in Carlito, ℵ ℑ ℜ ℘ in every bundled face).
fn symbol_unicode(low: u8) -> Option<char> {
Some(match low {
0x22 => '∀',
0x24 => '∃',
0x27 => '∋',
0x2A => '∗',
0x2D => '−',
0x40 => '≅',
0x41 => 'Α',
0x42 => 'Β',
0x43 => 'Χ',
0x44 => 'Δ',
0x45 => 'Ε',
0x46 => 'Φ',
0x47 => 'Γ',
0x48 => 'Η',
0x49 => 'Ι',
0x4A => 'ϑ',
0x4B => 'Κ',
0x4C => 'Λ',
0x4D => 'Μ',
0x4E => 'Ν',
0x4F => 'Ο',
0x50 => 'Π',
0x51 => 'Θ',
0x52 => 'Ρ',
0x53 => 'Σ',
0x54 => 'Τ',
0x55 => 'Υ',
0x56 => 'ς',
0x57 => 'Ω',
0x58 => 'Ξ',
0x59 => 'Ψ',
0x5A => 'Ζ',
0x5C => '∴',
0x5E => '⊥',
0x60 => return None,
0x61 => 'α',
0x62 => 'β',
0x63 => 'χ',
0x64 => 'δ',
0x65 => 'ε',
0x66 => 'φ',
0x67 => 'γ',
0x68 => 'η',
0x69 => 'ι',
0x6A => 'ϕ',
0x6B => 'κ',
0x6C => 'λ',
0x6D => 'µ', // the micro sign, as `symbol_font_text` reads it back
0x6E => 'ν',
0x6F => 'ο',
0x70 => 'π',
0x71 => 'θ',
0x72 => 'ρ',
0x73 => 'σ',
0x74 => 'τ',
0x75 => 'υ',
0x76 => 'ϖ',
0x77 => 'ω',
0x78 => 'ξ',
0x79 => 'ψ',
0x7A => 'ζ',
0x7E => '∼',
0x20..=0x7D => char::from(low),
0xA0 => '€',
0xA1 => 'ϒ',
0xA2 => '′',
0xA3 => '≤',
0xA4 => '⁄',
0xA5 => '∞',
0xA6 => 'ƒ',
0xA7 => '♣',
0xA8 => '♦',
0xA9 => '♥',
0xAA => '♠',
0xAB => '↔',
0xAC => '←',
0xAD => '↑',
0xAE => '→',
0xAF => '↓',
0xB0 => '°',
0xB1 => '±',
0xB2 => '″',
0xB3 => '≥',
0xB4 => '×',
0xB5 => '∝',
0xB6 => '∂',
0xB7 => '•',
0xB8 => '÷',
0xB9 => '≠',
0xBA => '≡',
0xBB => '≈',
0xBC => '…',
0xBF => '↵',
0xC0 => 'ℵ',
0xC1 => 'ℑ',
0xC2 => 'ℜ',
0xC3 => '℘',
0xC4 => '⊗',
0xC5 => '⊕',
0xC6 => '∅',
0xC7 => '∩',
0xC8 => '∪',
0xC9 => '⊃',
0xCA => '⊇',
0xCB => '⊄',
0xCC => '⊂',
0xCD => '⊆',
0xCE => '∈',
0xCF => '∉',
0xD0 => '∠',
0xD1 => '∇',
0xD2 | 0xE2 => '®',
0xD3 | 0xE3 => '©',
0xD4 | 0xE4 => '™',
0xD5 => '∏',
0xD6 => '√',
0xD7 => '⋅',
0xD8 => '¬',
0xD9 => '∧',
0xDA => '∨',
0xDB => '⇔',
0xDC => '⇐',
0xDD => '⇑',
0xDE => '⇒',
0xDF => '⇓',
0xE0 => '◊',
0xE1 => '〈',
0xE5 => '∑',
0xF1 => '〉',
0xF2 => '∫',
_ => return None,
})
}
/// The Unicode characters that can stand for a Wingdings code, nearest
/// first: the bullets, boxes, arrows and ticks lists are drawn with. A
/// text face rarely has the dingbat itself (Liberation has no ➢ or ✓), so
/// each code lists plainer shapes after it.
fn wingdings_unicode(low: u8) -> &'static [char] {
match low {
0x6C | 0xA4 | 0xA5 => &['●'],
0x6D | 0xA1 | 0xA2 => &['○'],
0x6E => &['■'],
0x6F | 0x70 | 0x71 | 0x72 | 0xA8 => &['□'],
0x73 | 0x74 | 0x75 | 0x77 => &['◆', '♦'],
0x76 => &['❖', '♦'],
0x9E => &['·'],
0x9F => &['•'],
0xA0 | 0xA7 => &['▪', '■'],
0xD8 => &['➢', '►', '>'],
0xDF => &['←'],
0xE0 | 0xE8 | 0xF0 => &['→'],
0xE1 => &['↑'],
0xE2 => &['↓'],
0xFB => &['✗', '×'],
0xFC => &['✓', '√'],
0xFD => &['☒', '□'],
0xFE => &['☑', '□'],
_ => &[],
}
}
thread_local! {
static ACTIVE_FONT_TABLE: RefCell<super::font_table::FontTable> =
RefCell::new(super::font_table::FontTable::default());
}
/// Puts the previous thread-local value back when dropped, so a scope
/// that unwinds (a panicking conversion caught by a test harness or a
/// long-lived host) cannot leak its state into the next conversion.
struct RestoreOnDrop<'a, T> {
slot: &'a RefCell<T>,
prev: Option<T>,
}
impl<T> Drop for RestoreOnDrop<'_, T> {
fn drop(&mut self) {
if let Some(prev) = self.prev.take() {
self.slot.replace(prev);
}
}
}
/// Install `table` for the duration of `f` so `Fonts::resolve` honours altName.
pub(crate) fn with_font_table<T>(table: super::font_table::FontTable, f: impl FnOnce() -> T) -> T {
ACTIVE_FONT_TABLE.with(|slot| {
let _restore = RestoreOnDrop {
slot,
prev: Some(slot.replace(table)),
};
f()
})
}
thread_local! {
static FONT_REPORT: RefCell<Option<Vec<FontReportEntry>>> = const { RefCell::new(None) };
}
/// Collect distinct [`FontReportEntry`] rows produced by `Fonts::resolve`
/// inside `f` (plan Step 2f).
pub(crate) fn with_font_report<T>(f: impl FnOnce() -> T) -> (T, Vec<FontReportEntry>) {
FONT_REPORT.with(|slot| {
let mut restore = RestoreOnDrop {
slot,
prev: Some(slot.replace(Some(Vec::new()))),
};
let out = f();
let prev = restore.prev.take().flatten();
let report = slot.replace(prev).unwrap_or_default();
(out, report)
})
}
fn record_font_resolution(entry: FontReportEntry) {
FONT_REPORT.with(|slot| {
let mut slot = slot.borrow_mut();
let Some(report) = slot.as_mut() else {
return;
};
if report.iter().any(|existing| {
existing.requested == entry.requested
&& existing.bold == entry.bold
&& existing.italic == entry.italic
}) {
return;
}
report.push(entry);
});
}
/// How the conversion resolved the physical face for a run (plan Step
/// 2f). Determines whether [`FontReportEntry::substituted`] reports a
/// substitution.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum FontStep {
/// Document-embedded `.odttf` for this family + style.
Embedded,
/// Requested family is installed (or in the catalogue overlay).
Explicit,
/// `w:altName` from `fontTable.xml`.
AltName,
/// Theme slot with no explicit `w:ascii` (reserved; apply_rfonts today
/// writes the slot name before resolve).
Theme,
/// Word-substitution evidence table (plan Step 2d).
WordSubstitution,
/// Bundled metric-compatible face; the requested family is not on disk.
OpenFallback,
/// `w:family` / `w:pitch` generic (roman / swiss / modern / fixed).
Generic,
/// Unknown family; evidence-table last resort (Cambria).
Unknown,
}
impl FontStep {
/// The stable token this step uses in JSON and CLI output (`"embedded"`,
/// `"explicit"`, `"altName"`, `"theme"`, `"word_substitution"`,
/// `"open_fallback"`, `"generic"`, `"unknown"`).
#[must_use]
pub fn as_str(self) -> &'static str {
match self {
Self::Embedded => "embedded",
Self::Explicit => "explicit",
Self::AltName => "altName",
Self::Theme => "theme",
Self::WordSubstitution => "word_substitution",
Self::OpenFallback => "open_fallback",
Self::Generic => "generic",
Self::Unknown => "unknown",
}
}
}
impl fmt::Display for FontStep {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// One distinct requested family + style from a conversion (plan Step
/// 2f). One entry per `(requested, bold, italic)` the layout saw, not per
/// run: every run asking for the same triple shares one entry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FontReportEntry {
/// Family string the run asked for (opaque; quotes and commas
/// preserved).
pub requested: String,
/// Which resolve step selected the physical face.
pub step: FontStep,
/// Physical face actually used (its PDF PostScript name).
pub physical: String,
/// Requested bold.
pub bold: bool,
/// Requested italic.
pub italic: bool,
/// True when the physical face does not provide the requested style
/// and the writer faked it (synthesized bold or italic).
pub synthetic: bool,
}
impl FontReportEntry {
/// True when the requested family was not drawn with its own face (or
/// its `w:altName`): Word's substitution table, a bundled open fallback
/// for another family, a generic family, or the last resort. A bundled
/// face of the requested family itself (`Carlito` drawn with Carlito) is
/// not a substitution. A faked style (`synthetic`) alone is not one
/// either.
#[must_use]
pub fn substituted(&self) -> bool {
match self.step {
FontStep::Embedded | FontStep::Explicit | FontStep::AltName | FontStep::Theme => false,
FontStep::OpenFallback => !self.physical_is_requested_family(),
FontStep::WordSubstitution | FontStep::Generic | FontStep::Unknown => true,
}
}
/// The physical face's family (its PostScript name before any `-Style`
/// suffix) is the requested family, ignoring case, spaces and hyphens.
fn physical_is_requested_family(&self) -> bool {
let squash = |s: &str| {
s.chars()
.filter(|c| !matches!(c, ' ' | '-'))
.flat_map(char::to_lowercase)
.collect::<String>()
};
let family = self.physical.split('-').next().unwrap_or_default();
let requested = squash(family_token(&self.requested));
!requested.is_empty() && requested == squash(family)
}
/// One JSON object matching
/// `{requested, step, physical, bold, italic, synthetic, substituted}`:
/// one JSON object with every public field and the resolved
/// `substituted` flag.
#[must_use]
pub fn to_json(&self) -> String {
format!(
"{{\"requested\":{},\"step\":{},\"physical\":{},\"bold\":{},\"italic\":{},\"synthetic\":{},\"substituted\":{}}}",
json_string(&self.requested),
json_string(self.step.as_str()),
json_string(&self.physical),
json_bool(self.bold),
json_bool(self.italic),
json_bool(self.synthetic),
json_bool(self.substituted()),
)
}
}
/// The entries as a JSON array of [`FontReportEntry::to_json`] objects,
/// joined with `,` between objects. The empty input returns `"[]"`.
#[must_use]
pub fn font_report_json(entries: &[FontReportEntry]) -> String {
let mut out = String::from("[");
for (i, entry) in entries.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&entry.to_json());
}
out.push(']');
out
}
fn json_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() => {
let _ = write!(out, "\\u{:04x}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn json_bool(v: bool) -> &'static str {
if v { "true" } else { "false" }
}
/// A character Unicode lays out wide (East_Asian_Width W or F): CJK
/// ideographs, kana, CJK punctuation, Hangul and the full-width forms.
/// Every East Asian face draws them one em wide.
fn east_asian_wide(c: char) -> bool {
matches!(
c,
'\u{1100}'..='\u{115F}'
| '\u{2E80}'..='\u{303E}'
| '\u{3041}'..='\u{33FF}'
| '\u{3400}'..='\u{4DBF}'
| '\u{4E00}'..='\u{9FFF}'
| '\u{A960}'..='\u{A97F}'
| '\u{AC00}'..='\u{D7A3}'
| '\u{F900}'..='\u{FAFF}'
| '\u{FE30}'..='\u{FE4F}'
| '\u{FF01}'..='\u{FF60}'
| '\u{FFE0}'..='\u{FFE6}'
| '\u{20000}'..='\u{3FFFD}'
)
}
/// Word Quartz Save-as-PDF writes a small `Tc` at 300dpi body sizes so
/// linear hmtx does not sit ~1pt wide of the oracle (color_sim wipe).
/// 11.04 → Tc≈-0.0015; 16.08 → Tc≈-0.0018. Other sizes keep hmtx.
pub(crate) fn word_device_track(size: f32) -> f32 {
if (size - 11.04).abs() < 0.02 {
-0.0015 * size
} else if (size - 16.08).abs() < 0.02 {
-0.0018 * size
} else {
0.0
}
}
/// Word Quartz paints snapped body sizes as `ppem Tf` inside a `0.24`
/// cm (300 dpi). MuPDF then hints at 46/67ppem like the oracle, not at
/// 11.04/16.08 in user space (file_151 color_sim / ΔE).
pub(crate) fn word_device_paint(size: f32) -> Option<(f32, f32)> {
if (size - 11.04).abs() < 0.02 {
Some((46.0, -0.0015))
} else if (size - 16.08).abs() < 0.02 {
Some((67.0, -0.0018))
} else {
None
}
}
/// A bundled face used by the DOCX→PDF writer.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum FaceId {
CarlitoRegular,
CarlitoBold,
CarlitoItalic,
CarlitoBoldItalic,
SansRegular,
SansBold,
SansItalic,
SansBoldItalic,
SerifRegular,
SerifBold,
SerifItalic,
SerifBoldItalic,
MonoRegular,
MonoBold,
MonoItalic,
MonoBoldItalic,
AptosRegular,
AptosBold,
AptosItalic,
AptosBoldItalic,
AptosDisplayRegular,
AptosDisplayBold,
AptosDisplayItalic,
AptosDisplayBoldItalic,
CalibriLightRegular,
CalibriLightItalic,
VerdanaRegular,
VerdanaBold,
VerdanaItalic,
VerdanaBoldItalic,
CambriaRegular,
CambriaBold,
CambriaItalic,
CambriaBoldItalic,
ConsolasRegular,
ConsolasBold,
ConsolasItalic,
ConsolasBoldItalic,
GeorgiaRegular,
GeorgiaBold,
GeorgiaItalic,
GeorgiaBoldItalic,
BookAntiquaRegular,
BookAntiquaBold,
BookAntiquaItalic,
BookAntiquaBoldItalic,
Symbol,
}
/// Physical family + style. Catalogue `FaceId` values map here so call sites
/// can migrate off the closed enum (plan Step 2e) without a behaviour change.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct FaceKey {
pub family: String,
pub bold: bool,
pub italic: bool,
}
/// Catalogue slot or a per-document embedded face (plan xml 3.1 ckpt 4).
///
/// Copy-sized so `Op::Text` can keep a font identity without a `String`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub(crate) enum FaceRef {
Catalogue(FaceId),
Embedded(u16),
}
impl From<FaceId> for FaceRef {
fn from(id: FaceId) -> Self {
Self::Catalogue(id)
}
}
impl PartialEq<FaceId> for FaceRef {
fn eq(&self, other: &FaceId) -> bool {
matches!(self, Self::Catalogue(id) if id == other)
}
}
impl FaceId {
fn index(self) -> usize {
self as usize
}
pub(crate) fn key(self) -> FaceKey {
FaceKey {
family: self.logical_family().to_string(),
bold: self.is_bold_style(),
italic: self.is_italic_style(),
}
}
fn logical_family(self) -> &'static str {
match self {
Self::CarlitoRegular
| Self::CarlitoBold
| Self::CarlitoItalic
| Self::CarlitoBoldItalic => "Calibri",
Self::SansRegular | Self::SansBold | Self::SansItalic | Self::SansBoldItalic => "Arial",
Self::SerifRegular | Self::SerifBold | Self::SerifItalic | Self::SerifBoldItalic => {
"Times New Roman"
}
Self::MonoRegular | Self::MonoBold | Self::MonoItalic | Self::MonoBoldItalic => {
"Courier New"
}
Self::AptosRegular | Self::AptosBold | Self::AptosItalic | Self::AptosBoldItalic => {
"Aptos"
}
Self::AptosDisplayRegular
| Self::AptosDisplayBold
| Self::AptosDisplayItalic
| Self::AptosDisplayBoldItalic => "Aptos Display",
Self::CalibriLightRegular | Self::CalibriLightItalic => "Calibri Light",
Self::VerdanaRegular
| Self::VerdanaBold
| Self::VerdanaItalic
| Self::VerdanaBoldItalic => "Verdana",
Self::CambriaRegular
| Self::CambriaBold
| Self::CambriaItalic
| Self::CambriaBoldItalic => "Cambria",
Self::ConsolasRegular
| Self::ConsolasBold
| Self::ConsolasItalic
| Self::ConsolasBoldItalic => "Consolas",
Self::GeorgiaRegular
| Self::GeorgiaBold
| Self::GeorgiaItalic
| Self::GeorgiaBoldItalic => "Georgia",
Self::BookAntiquaRegular
| Self::BookAntiquaBold
| Self::BookAntiquaItalic
| Self::BookAntiquaBoldItalic => "Book Antiqua",
Self::Symbol => "Symbol",
}
}
fn is_bold_style(self) -> bool {
matches!(
self,
Self::CarlitoBold
| Self::CarlitoBoldItalic
| Self::SansBold
| Self::SansBoldItalic
| Self::SerifBold
| Self::SerifBoldItalic
| Self::MonoBold
| Self::MonoBoldItalic
| Self::AptosBold
| Self::AptosBoldItalic
| Self::AptosDisplayBold
| Self::AptosDisplayBoldItalic
| Self::VerdanaBold
| Self::VerdanaBoldItalic
| Self::CambriaBold
| Self::CambriaBoldItalic
| Self::ConsolasBold
| Self::ConsolasBoldItalic
| Self::GeorgiaBold
| Self::GeorgiaBoldItalic
| Self::BookAntiquaBold
| Self::BookAntiquaBoldItalic
)
}
fn is_italic_style(self) -> bool {
matches!(
self,
Self::CarlitoItalic
| Self::CarlitoBoldItalic
| Self::SansItalic
| Self::SansBoldItalic
| Self::SerifItalic
| Self::SerifBoldItalic
| Self::MonoItalic
| Self::MonoBoldItalic
| Self::AptosItalic
| Self::AptosBoldItalic
| Self::AptosDisplayItalic
| Self::AptosDisplayBoldItalic
| Self::CalibriLightItalic
| Self::VerdanaItalic
| Self::VerdanaBoldItalic
| Self::CambriaItalic
| Self::CambriaBoldItalic
| Self::ConsolasItalic
| Self::ConsolasBoldItalic
| Self::GeorgiaItalic
| Self::GeorgiaBoldItalic
| Self::BookAntiquaItalic
| Self::BookAntiquaBoldItalic
)
}
}
/// The 16 embedded font programs, one static each: every alias of a
/// face (Aptos, Verdana, Cambria, ...) shares its bytes and its one
/// read-only data entry instead of re-including the file per arm.
static CARLITO_REGULAR: &[u8] = include_bytes!("../../assets/fonts/Carlito-Regular.ttf");
static CARLITO_BOLD: &[u8] = include_bytes!("../../assets/fonts/Carlito-Bold.ttf");
static CARLITO_ITALIC: &[u8] = include_bytes!("../../assets/fonts/Carlito-Italic.ttf");
static CARLITO_BOLD_ITALIC: &[u8] = include_bytes!("../../assets/fonts/Carlito-BoldItalic.ttf");
static SANS_REGULAR: &[u8] = include_bytes!("../../assets/fonts/LiberationSans-Regular.ttf");
static SANS_BOLD: &[u8] = include_bytes!("../../assets/fonts/LiberationSans-Bold.ttf");
static SANS_ITALIC: &[u8] = include_bytes!("../../assets/fonts/LiberationSans-Italic.ttf");
static SANS_BOLD_ITALIC: &[u8] = include_bytes!("../../assets/fonts/LiberationSans-BoldItalic.ttf");
static SERIF_REGULAR: &[u8] = include_bytes!("../../assets/fonts/LiberationSerif-Regular.ttf");
static SERIF_BOLD: &[u8] = include_bytes!("../../assets/fonts/LiberationSerif-Bold.ttf");
static SERIF_ITALIC: &[u8] = include_bytes!("../../assets/fonts/LiberationSerif-Italic.ttf");
static SERIF_BOLD_ITALIC: &[u8] =
include_bytes!("../../assets/fonts/LiberationSerif-BoldItalic.ttf");
static MONO_REGULAR: &[u8] = include_bytes!("../../assets/fonts/LiberationMono-Regular.ttf");
static MONO_BOLD: &[u8] = include_bytes!("../../assets/fonts/LiberationMono-Bold.ttf");
static MONO_ITALIC: &[u8] = include_bytes!("../../assets/fonts/LiberationMono-Italic.ttf");
static MONO_BOLD_ITALIC: &[u8] = include_bytes!("../../assets/fonts/LiberationMono-BoldItalic.ttf");
impl FaceId {
pub(crate) fn all() -> [Self; 47] {
[
Self::CarlitoRegular,
Self::CarlitoBold,
Self::CarlitoItalic,
Self::CarlitoBoldItalic,
Self::SansRegular,
Self::SansBold,
Self::SansItalic,
Self::SansBoldItalic,
Self::SerifRegular,
Self::SerifBold,
Self::SerifItalic,
Self::SerifBoldItalic,
Self::MonoRegular,
Self::MonoBold,
Self::MonoItalic,
Self::MonoBoldItalic,
Self::AptosRegular,
Self::AptosBold,
Self::AptosItalic,
Self::AptosBoldItalic,
Self::AptosDisplayRegular,
Self::AptosDisplayBold,
Self::AptosDisplayItalic,
Self::AptosDisplayBoldItalic,
Self::CalibriLightRegular,
Self::CalibriLightItalic,
Self::VerdanaRegular,
Self::VerdanaBold,
Self::VerdanaItalic,
Self::VerdanaBoldItalic,
Self::CambriaRegular,
Self::CambriaBold,
Self::CambriaItalic,
Self::CambriaBoldItalic,
Self::ConsolasRegular,
Self::ConsolasBold,
Self::ConsolasItalic,
Self::ConsolasBoldItalic,
Self::GeorgiaRegular,
Self::GeorgiaBold,
Self::GeorgiaItalic,
Self::GeorgiaBoldItalic,
Self::BookAntiquaRegular,
Self::BookAntiquaBold,
Self::BookAntiquaItalic,
Self::BookAntiquaBoldItalic,
Self::Symbol,
]
}
pub(crate) fn bytes(self) -> &'static [u8] {
match self {
Self::CarlitoRegular => CARLITO_REGULAR,
Self::CarlitoBold => CARLITO_BOLD,
Self::CarlitoItalic => CARLITO_ITALIC,
Self::CarlitoBoldItalic => CARLITO_BOLD_ITALIC,
Self::SansRegular => SANS_REGULAR,
Self::SansBold => SANS_BOLD,
Self::SansItalic => SANS_ITALIC,
Self::SansBoldItalic => SANS_BOLD_ITALIC,
Self::SerifRegular => SERIF_REGULAR,
Self::SerifBold => SERIF_BOLD,
Self::SerifItalic => SERIF_ITALIC,
Self::SerifBoldItalic => SERIF_BOLD_ITALIC,
Self::MonoRegular => MONO_REGULAR,
Self::MonoBold => MONO_BOLD,
Self::MonoItalic => MONO_ITALIC,
Self::MonoBoldItalic => MONO_BOLD_ITALIC,
Self::AptosRegular => CARLITO_REGULAR,
Self::AptosBold => CARLITO_BOLD,
Self::AptosItalic => CARLITO_ITALIC,
Self::AptosBoldItalic => CARLITO_BOLD_ITALIC,
// System/Word CloudFonts Aptos Display overlays these.
Self::AptosDisplayRegular => CARLITO_REGULAR,
Self::AptosDisplayBold => CARLITO_BOLD,
Self::AptosDisplayItalic => CARLITO_ITALIC,
Self::AptosDisplayBoldItalic => CARLITO_BOLD_ITALIC,
// System calibril.ttf overlays these.
Self::CalibriLightRegular => CARLITO_REGULAR,
Self::CalibriLightItalic => CARLITO_ITALIC,
// System Verdana overlays these; Liberation Sans is the
// Arial-metric fallback when Word DFonts are absent.
Self::VerdanaRegular => SANS_REGULAR,
Self::VerdanaBold => SANS_BOLD,
Self::VerdanaItalic => SANS_ITALIC,
Self::VerdanaBoldItalic => SANS_BOLD_ITALIC,
// System Cambria overlays these; Liberation Serif is the
// fallback when Word DFonts are absent.
Self::CambriaRegular => SERIF_REGULAR,
Self::CambriaBold => SERIF_BOLD,
Self::CambriaItalic => SERIF_ITALIC,
Self::CambriaBoldItalic => SERIF_BOLD_ITALIC,
// System Consolas overlays these; Liberation Mono is the
// fallback when Word DFonts are absent.
Self::ConsolasRegular => MONO_REGULAR,
Self::ConsolasBold => MONO_BOLD,
Self::ConsolasItalic => MONO_ITALIC,
Self::ConsolasBoldItalic => MONO_BOLD_ITALIC,
// System Georgia overlays these; Liberation Serif is the
// fallback when Georgia.ttf is absent.
Self::GeorgiaRegular => SERIF_REGULAR,
Self::GeorgiaBold => SERIF_BOLD,
Self::GeorgiaItalic => SERIF_ITALIC,
Self::GeorgiaBoldItalic => SERIF_BOLD_ITALIC,
// Word DFonts Book Antiqua / Palatino Linotype overlay these;
// Liberation Serif is the fallback when those faces are absent.
Self::BookAntiquaRegular => SERIF_REGULAR,
Self::BookAntiquaBold => SERIF_BOLD,
Self::BookAntiquaItalic => SERIF_ITALIC,
Self::BookAntiquaBoldItalic => SERIF_BOLD_ITALIC,
// System Symbol overlays this; Liberation Sans U+2022 is the
// fallback when Symbol.ttf is absent.
Self::Symbol => SANS_REGULAR,
}
}
pub(crate) fn postscript(self) -> &'static str {
match self {
Self::CarlitoRegular => "Carlito",
Self::CarlitoBold => "Carlito-Bold",
Self::CarlitoItalic => "Carlito-Italic",
Self::CarlitoBoldItalic => "Carlito-BoldItalic",
Self::SansRegular => "LiberationSans",
Self::SansBold => "LiberationSans-Bold",
Self::SansItalic => "LiberationSans-Italic",
Self::SansBoldItalic => "LiberationSans-BoldItalic",
Self::SerifRegular => "LiberationSerif",
Self::SerifBold => "LiberationSerif-Bold",
Self::SerifItalic => "LiberationSerif-Italic",
Self::SerifBoldItalic => "LiberationSerif-BoldItalic",
Self::MonoRegular => "LiberationMono",
Self::MonoBold => "LiberationMono-Bold",
Self::MonoItalic => "LiberationMono-Italic",
Self::MonoBoldItalic => "LiberationMono-BoldItalic",
Self::AptosRegular => "Aptos",
Self::AptosBold => "Aptos-Bold",
Self::AptosItalic => "Aptos-Italic",
Self::AptosBoldItalic => "Aptos-BoldItalic",
Self::AptosDisplayRegular => "AptosDisplay",
Self::AptosDisplayBold => "AptosDisplay-Bold",
Self::AptosDisplayItalic => "AptosDisplay-Italic",
Self::AptosDisplayBoldItalic => "AptosDisplay-BoldItalic",
Self::CalibriLightRegular => "Calibri-Light",
Self::CalibriLightItalic => "Calibri-LightItalic",
Self::VerdanaRegular => "Verdana",
Self::VerdanaBold => "Verdana-Bold",
Self::VerdanaItalic => "Verdana-Italic",
Self::VerdanaBoldItalic => "Verdana-BoldItalic",
Self::CambriaRegular => "Cambria",
Self::CambriaBold => "Cambria-Bold",
Self::CambriaItalic => "Cambria-Italic",
Self::CambriaBoldItalic => "Cambria-BoldItalic",
Self::ConsolasRegular => "Consolas",
Self::ConsolasBold => "Consolas-Bold",
Self::ConsolasItalic => "Consolas-Italic",
Self::ConsolasBoldItalic => "Consolas-BoldItalic",
Self::GeorgiaRegular => "Georgia",
Self::GeorgiaBold => "Georgia-Bold",
Self::GeorgiaItalic => "Georgia-Italic",
Self::GeorgiaBoldItalic => "Georgia-BoldItalic",
Self::BookAntiquaRegular => "BookAntiqua",
Self::BookAntiquaBold => "BookAntiqua-Bold",
Self::BookAntiquaItalic => "BookAntiqua-Italic",
Self::BookAntiquaBoldItalic => "BookAntiqua-BoldItalic",
Self::Symbol => "Symbol",
}
}
}
/// Parsed metrics + cmap for one bundled, system-overlaid or embedded face.
///
/// `bytes` outlives the face: bundled faces are `include_bytes!` data,
/// system-override files are leaked once into the process-lifetime
/// catalogue (one per slot), and a document's embedded fonts are borrowed
/// from the conversion that loaded them, so the pre-parsed
/// `rustybuzz::Face` below can borrow them without a self-referential
/// struct and nothing untrusted outlives its document.
pub(crate) struct Face<'a> {
bytes: &'a [u8],
/// Parsed once here; `shape` runs per text run and must not re-parse
/// the font table directory each call.
buzz: Option<rustybuzz::Face<'a>>,
pdf_name: String,
pub upem: f32,
pub descent: f32,
/// Word's single line in font units: hhea ascender − descender +
/// lineGap (typo when USE_TYPO_METRICS is set). GDI reaches the same
/// total as win height + external leading.
line_height: f32,
/// hhea descender (typo with USE_TYPO_METRICS): `line_height`'s part
/// below the baseline.
line_descent: f32,
/// Win ascent when USE_TYPO_METRICS is unset (Liberation ↔ Arial).
paint_ascent: f32,
/// OS/2 strikeout line in font units: Word draws a note separator as
/// the separator run's strikeout (Word 16 probes 2026-10-03: Calibri
/// 11 a 0.72 rule with its top 2.75 over the baseline, a 20pt run 1.2
/// at 5.0; Aptos 11 0.48 at 3.93).
strike_pos: f32,
strike_size: f32,
/// An East Asian face (OS/2 code pages 932/936/949/950/1361).
east_asian: bool,
/// OS/2 PANOSE says Latin text with serifs (MS Mincho, Times New
/// Roman), not sans (MS Gothic, Arial, Calibri).
pub serif: bool,
/// OS/2 xAvgCharWidth over the em (half an em without one).
pub avg_char_width: f32,
pub bbox: [i16; 4],
pub widths: Vec<u16>,
/// The cmap's Unicode subtables, asked per character: the first one
/// that maps it wins. Enumerating every mapped codepoint up front was
/// a tenth of a one-page conversion (samply, fixtures_500 0081ba58).
cmap: Vec<ttf_parser::cmap::Subtable<'a>>,
/// The catalogue's Symbol slot: its U+F0xx characters are Symbol's
/// codes, any other face's are read as Wingdings' (`symbol_stand_in`).
symbol_slot: bool,
/// Shape plans by segment (direction, script, language) and kerning:
/// building one was a fifth of a conversion when every run built its
/// own (redline 0006f790: 21% of samples in `ShapePlan::new`).
plans: Mutex<HashMap<PlanKey, Arc<rustybuzz::ShapePlan>>>,
/// Shaped text in font units by (text, kern); see `shaped_units`.
shaped: Mutex<BoundedCache<(String, bool), ShapedUnits>>,
}
/// Glyph ids and x advances in font units.
/// (glyph id, x advance in font units, cluster = byte offset of its text).
type ShapedUnits = Arc<[(u16, i32, u32)]>;
type PlanKey = (
rustybuzz::Direction,
rustybuzz::Script,
Option<rustybuzz::Language>,
bool,
);
impl<'a> Face<'a> {
pub(crate) fn bytes(&self) -> &[u8] {
self.bytes
}
pub(crate) fn pdf_name(&self) -> &str {
&self.pdf_name
}
fn load(id: FaceId) -> Self {
Self::from_bytes(id, id.bytes(), id.postscript().to_string()).expect("bundled TTF is valid")
}
/// The slot's bundled face, whatever this machine has installed.
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
pub(crate) fn bundled(id: FaceId) -> Self {
Self::load(id)
}
fn from_path(id: FaceId, path: &Path) -> Option<Self> {
let bytes = fs::read(path).ok()?;
let ps = ttf_postscript_name(&bytes).unwrap_or_else(|| id.postscript().to_string());
// Leaked once per process: `Fonts` lives in a LazyLock, and the
// pre-parsed rustybuzz face needs 'static bytes.
let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
Self::from_bytes(id, bytes, sanitize_pdf_name(&ps))
}
/// `None` when the bytes are not a parseable TTF/TTC face — a truncated
/// or unsupported *system* font file must fall back to the bundled face,
/// never panic (a panic here poisons the process-wide `Fonts` LazyLock).
fn from_bytes(id: FaceId, bytes: &'a [u8], pdf_name: String) -> Option<Self> {
let face = ttf_parser::Face::parse(bytes, 0).ok()?;
let upem = f32::from(face.units_per_em());
let ascent = f32::from(
face.typographic_ascender()
.unwrap_or_else(|| face.ascender()),
);
let descent = f32::from(
face.typographic_descender()
.unwrap_or_else(|| face.descender()),
);
// ttf-parser's ascender/descender/line_gap are hhea unless the font
// sets USE_TYPO_METRICS. Typo metrics under-size Courier (0.80 em
// vs 1.13) and Arial (1.09 vs 1.15) against Word's line.
let mut line_height =
f32::from(face.ascender()) - f32::from(face.descender()) + f32::from(face.line_gap());
// The line's part below the baseline, from the same table as its
// height (Courier's typo descender under-sizes it).
let mut line_descent = f32::from(face.descender()).abs();
// Word gives an East Asian face (OS/2 code pages 932/936/949/950/
// 1361) 1.3 times its hhea ascent + descent, lineGap aside, the
// extra split above and below the text. Live Word at 12pt: SimSun
// and MS Mincho step 15.6, YaHei 20.7, Meiryo 23.3, Yu Gothic 17.0.
// A face from Word's own Office 365 font service takes its head box
// instead (Word 16 probes lg4–lg6 at 20pt: STFangsong 33.84 and
// STXihei 35.88, 1.3 times their 1.301 and 1.377 em boxes; DFonts'
// DengXian and Yu Mincho, boxes 1.207 and 1.655, keep hhea).
let east_asian_line = cjk_code_pages(&face).then(|| {
let (top, bottom) = if office_365_face(&face) {
let bbox = face.global_bounding_box();
(f32::from(bbox.y_max), f32::from(bbox.y_min))
} else {
(f32::from(face.ascender()), f32::from(face.descender()))
};
let half = (top - bottom) * 0.3 / 2.0;
(top, bottom.abs(), half)
});
if let Some((top, bottom, half)) = east_asian_line {
line_height = top + bottom + 2.0 * half;
line_descent = bottom + half;
}
// macOS Helvetica: Word's single line is 1.2 em, not its 1.0 em
// hhea body, with the win descent below the baseline (English part
// a 18f71536: 14.40pt lines at 12pt). Futura and Palatino follow
// their hhea lines, so the rule is Helvetica's own.
let helvetica = pdf_name == "Helvetica" || pdf_name.starts_with("Helvetica-");
if helvetica && let Some(os2) = face.tables().os2 {
line_height = upem * 1.2;
line_descent = f32::from(os2.windows_descender()).abs();
}
// GDI puts the external leading (hhea total − win total) above the
// text: Word's first TNR 12 baseline is winAscent + 0.51pt down.
// A win box taller than the line (macOS Palatino: 3396 units over a
// 2253 hhea line) does not push the text down: Word sets 009df71a's
// Palatino at its hhea ascent, 9.05pt under the margin at 11pt.
let paint_ascent = face
.tables()
.os2
.filter(|os2| !os2.use_typographic_metrics())
.filter(|os2| os2.windows_ascender() > 0)
.map(|os2| {
let win_asc = f32::from(os2.windows_ascender());
let win_total = win_asc + f32::from(os2.windows_descender()).abs();
if win_total > line_height {
line_height - line_descent
} else {
win_asc + (line_height - win_total)
}
})
.unwrap_or(ascent);
// A USE_TYPO_METRICS face sets its typo lineGap above the text:
// live Word puts 16pt Gabriola's baseline 22.08 under the margin
// (ascent 10.94 + lineGap 11.20), Poppins 12's at 13.92.
let typo_line = face
.tables()
.os2
.is_some_and(|os2| os2.use_typographic_metrics());
let paint_ascent = if typo_line {
line_height - line_descent
} else {
paint_ascent
};
let paint_ascent = match east_asian_line {
Some((top, _, half)) => top + half,
None => paint_ascent,
};
let glyph_count = face.number_of_glyphs();
let mut widths = vec![0u16; glyph_count as usize];
for (gid, slot) in widths.iter_mut().enumerate() {
let glyph = ttf_parser::GlyphId(gid as u16);
*slot = face.glyph_hor_advance(glyph).unwrap_or(0);
}
let cmap = face
.tables()
.cmap
.map(|table| {
table
.subtables
.into_iter()
.filter(|sub| sub.is_unicode())
.collect()
})
.unwrap_or_default();
let bbox = face.global_bounding_box();
let buzz = rustybuzz::Face::from_slice(bytes, 0);
let (strike_pos, strike_size) = face
.strikeout_metrics()
.map_or((upem * 0.25, upem * 0.065), |m| {
(f32::from(m.position), f32::from(m.thickness))
});
Some(Self {
bytes,
buzz,
plans: Mutex::new(HashMap::new()),
shaped: Mutex::new(BoundedCache::new(
MAX_SHAPED_CACHE_BYTES,
shaped_payload_bytes,
)),
pdf_name,
upem,
descent,
line_height,
line_descent,
paint_ascent,
strike_pos,
strike_size,
east_asian: east_asian_line.is_some(),
serif: panose_serif(&face),
avg_char_width: avg_char_width(&face).map_or(0.5, |w| w / upem),
bbox: [bbox.x_min, bbox.y_min, bbox.x_max, bbox.y_max],
widths,
cmap,
symbol_slot: id == FaceId::Symbol,
})
}
pub(crate) fn glyph(&self, ch: char) -> u16 {
self.cmap_glyph(self.painted(ch))
}
/// The cmap's glyph for `ch` itself, 0 without one.
fn cmap_glyph(&self, ch: char) -> u16 {
self.cmap
.iter()
.find_map(|sub| sub.glyph_index(u32::from(ch)))
.map_or(0, |gid| gid.0)
}
/// The character this face paints for `ch`: `painted_char`'s, and for a
/// symbol code the face has no glyph for, the Unicode character that
/// stands for it.
fn painted(&self, ch: char) -> char {
let ch = painted_char(ch);
self.symbol_stand_in(ch).unwrap_or(ch)
}
/// A symbol face's U+F020..U+F0FF character on a text face. Word's
/// bullets are U+F0B7 in Symbol and U+F0A7 in Wingdings; where those
/// faces are absent (a browser's WASM build, a host without Word's
/// fonts) the slot holds a text face whose cmap has neither, and the
/// bullet painted nothing. The Symbol slot reads the code by Adobe's
/// Symbol encoding, any other face as Wingdings; the first stand-in the
/// face has a glyph for wins. A face that has the code keeps it.
///
/// The face does not know the family it was resolved for, so a code of
/// Webdings or Wingdings 2 and 3 on a face without it is read as
/// Wingdings' too, and may paint another dingbat than Word's.
pub(crate) fn symbol_stand_in(&self, ch: char) -> Option<char> {
let low = u8::try_from(u32::from(ch).checked_sub(0xF000)?).ok()?;
if low < 0x20 || self.cmap_glyph(ch) != 0 {
return None;
}
if self.symbol_slot {
symbol_unicode(low).filter(|&c| self.cmap_glyph(c) != 0)
} else {
wingdings_unicode(low)
.iter()
.copied()
.find(|&c| self.cmap_glyph(c) != 0)
}
}
pub(crate) fn advance_pt(&self, ch: char, size: f32) -> f32 {
let gid = self.glyph(ch);
let adv = if gid == 0 && east_asian_wide(ch) {
self.upem
} else {
f32::from(self.widths.get(usize::from(gid)).copied().unwrap_or(0))
};
adv * size / self.upem + word_device_track(size)
}
pub(crate) fn width_pt(&self, text: &str, size: f32) -> f32 {
self.shape_kern(text, size, false)
.into_iter()
.map(|(_, a)| a)
.sum()
}
pub(crate) fn width_pt_kern(&self, text: &str, size: f32, kern: bool) -> f32 {
self.shape_kern(text, size, kern)
.into_iter()
.map(|(_, a)| a)
.sum()
}
pub(crate) fn ascent_pt(&self, size: f32) -> f32 {
// Official no_comments Word oracles place Calibri with usWinAscent
// (11pt → 82.56 from top). Typo 1536 sits 2.2pt high and tanks the
// randomized Calibri cluster (file_71 91→72).
self.paint_ascent * size / self.upem
}
pub(crate) fn descent_pt(&self, size: f32) -> f32 {
self.descent.abs() * size / self.upem
}
pub(crate) fn single_line_pt(&self, size: f32) -> f32 {
self.line_height * size / self.upem
}
/// The single line's part below the baseline (hhea descender, the same
/// table as `single_line_pt`).
pub(crate) fn line_descent_pt(&self, size: f32) -> f32 {
self.line_descent * size / self.upem
}
/// The strikeout line's top over the baseline.
pub(crate) fn strike_pos_pt(&self, size: f32) -> f32 {
self.strike_pos * size / self.upem
}
/// The strikeout line's thickness.
pub(crate) fn strike_size_pt(&self, size: f32) -> f32 {
self.strike_size * size / self.upem
}
pub(crate) fn glyphs(&self, text: &str) -> Vec<u16> {
// Only the glyph ids are kept; ids are size-independent, so the
// shaping size passed here is arbitrary.
self.shape(text, 11.0).into_iter().map(|(g, _)| g).collect()
}
/// HarfBuzz-compatible glyph ids + advances in points.
pub(crate) fn shape(&self, text: &str, size: f32) -> Vec<(u16, f32)> {
self.shape_kern(text, size, false)
}
pub(crate) fn shape_kern(&self, text: &str, size: f32, kern: bool) -> Vec<(u16, f32)> {
let Some(face) = self.buzz.as_ref() else {
return text
.chars()
.map(|ch| (self.glyph(ch), self.advance_pt(ch, size)))
.collect();
};
let units = self.shaped_units(face, text, kern);
units
.iter()
.map(|&(gid, x_advance, _)| {
let adv = x_advance as f32 / self.upem * size + word_device_track(size);
(gid, adv)
})
.collect()
}
/// The text behind each glyph `shape_kern(text, _, kern)` returns: its
/// cluster's characters on the cluster's first glyph, empty on the
/// rest. A glyph shaped from several characters (`e` + U+0301 composed
/// to `é`, a lam-alef) carries all of them, for `/ToUnicode`.
pub(crate) fn glyph_texts(&self, text: &str, kern: bool) -> Vec<String> {
let Some(face) = self.buzz.as_ref() else {
return text.chars().map(|c| self.painted(c).to_string()).collect();
};
let units = self.shaped_units(face, text, kern);
let mut starts: Vec<usize> = units.iter().map(|u| u.2 as usize).collect();
starts.sort_unstable();
starts.dedup();
let mut seen = std::collections::HashSet::new();
units
.iter()
.map(|u| {
let at = u.2 as usize;
if !seen.insert(at) {
return String::new();
}
let end = starts
.iter()
.find(|&&s| s > at)
.copied()
.unwrap_or(text.len());
text.get(at..end)
.unwrap_or_default()
.chars()
.map(|c| self.painted(c))
.collect()
})
.collect()
}
/// `text` shaped in font units (glyph id, x advance), remembered per
/// face: documents repeat their words, and shaping each again was a
/// fifth of a conversion.
fn shaped_units(&self, face: &rustybuzz::Face, text: &str, kern: bool) -> ShapedUnits {
let memo = (text.to_string(), kern);
if let Some(hit) = self.shaped.lock().ok().and_then(|c| c.get(&memo).cloned()) {
return hit;
}
let mut buf = rustybuzz::UnicodeBuffer::new();
// Clusters stay byte offsets into `text`, as `push_str` makes them.
for (at, ch) in text.char_indices() {
buf.add(self.painted(ch), at as u32);
}
// Word Quartz WinAnsi PDFs do not ligate Calibri and place glyphs
// on hmtx (T=5.38pt), not GPOS/kern (T+e shrinks ~1pt and wipes
// official color_sim). Title `w:kern val=28` (potpourri 28pt)
// is the exception: Word "Pot-Pourri" is 108.6 vs hmtx 111.0.
// docDefaults/Normal kern=2 stays off.
buf.guess_segment_properties();
let key = (buf.direction(), buf.script(), buf.language(), kern);
let cached = self.plans.lock().ok().and_then(|p| p.get(&key).cloned());
let plan = cached.unwrap_or_else(|| {
let feature = |tag: &[u8; 4], value| {
rustybuzz::Feature::new(rustybuzz::ttf_parser::Tag::from_bytes(tag), value, ..)
};
let word_pdf = [
feature(b"liga", 0),
feature(b"clig", 0),
feature(b"dlig", 0),
feature(b"kern", u32::from(kern)),
feature(b"ccmp", 0),
];
// Word paints a precomposed Latin, Greek or Cyrillic letter as
// its own glyph. Cambria's ccmp splits "ě" into e + a caron
// mark, which also leaves the shared "e" glyph unable to say
// "ě" in /ToUnicode (3509b16c7d's Czech; Word's PDF holds ě, č,
// ů whole). Complex scripts keep ccmp (the plan key holds the
// script).
let precomposed = [
rustybuzz::script::LATIN,
rustybuzz::script::GREEK,
rustybuzz::script::CYRILLIC,
rustybuzz::script::COMMON,
rustybuzz::script::INHERITED,
]
.contains(&key.1);
let features = if precomposed {
&word_pdf[..]
} else {
&word_pdf[..4]
};
let plan = Arc::new(rustybuzz::ShapePlan::new(
face,
key.0,
Some(key.1),
key.2.as_ref(),
features,
));
if let Ok(mut plans) = self.plans.lock() {
plans.insert(key.clone(), Arc::clone(&plan));
}
plan
});
let out = rustybuzz::shape_with_plan(face, &plan, buf);
let mut glyphs: Vec<(u16, i32, u32)> = out
.glyph_infos()
.iter()
.zip(out.glyph_positions())
.map(|(info, p)| (info.glyph_id as u16, p.x_advance, info.cluster))
.collect();
// rustybuzz 0.20 reverses an RTL buffer for a legacy `kern` table
// and, with kerning off, skips the reverse back: Arial's Persian
// came out in logical order, each word mirrored (00205272).
// Visual RTL order runs from the last cluster to the first.
if key.0 == rustybuzz::Direction::RightToLeft
&& glyphs
.first()
.zip(glyphs.last())
.is_some_and(|(a, z)| a.2 < z.2)
{
glyphs.reverse();
}
// East Asian wide text the face lacks measures one em, as in every
// face Word falls back to for it: a Latin .notdef (0.75 em in
// Liberation Sans) packed CJK lines where Word wraps them.
let em = self.upem.round() as i32;
for glyph in glyphs.iter_mut().filter(|g| g.0 == 0) {
let ch = text.get(glyph.2 as usize..).and_then(|t| t.chars().next());
if ch.is_some_and(east_asian_wide) {
glyph.1 = em;
}
}
let units: ShapedUnits = glyphs.into();
if let Ok(mut cache) = self.shaped.lock() {
// A long-lived caller (Python / WASM) converts many documents
// through one face. The entry count still clears past 50_000,
// and the glyph payloads stay inside the byte budget. The
// greatest key is the one that goes. This cache belongs to the
// face, so it ends when that face's bytes do.
if cache.len() > 50_000 {
cache.clear();
}
cache.insert(memo, Arc::clone(&units));
}
units
}
pub(crate) fn pdf_widths_1000(&self) -> Vec<i32> {
self.widths
.iter()
.map(|&w| ((i32::from(w) * 1000) / self.upem as i32).max(0))
.collect()
}
pub(crate) fn width_1000(&self, ch: char) -> i32 {
let gid = self.glyph(ch) as usize;
let adv = self.widths.get(gid).copied().unwrap_or(0);
((i32::from(adv) * 1000) / self.upem as i32).max(0)
}
fn scale_1000(&self, units: f32) -> i32 {
(units * 1000.0 / self.upem).round() as i32
}
/// PDF simple TrueType glyph space is 1000 units (Word Quartz).
/// Emitting raw 2048-UPM Ascent made fitz title boxes sit at y=44
/// instead of Word's pgMar top (file_146 / 175 / 176 = 65pt).
pub(crate) fn pdf_ascent_1000(&self) -> i32 {
self.scale_1000(self.paint_ascent)
}
pub(crate) fn pdf_descent_1000(&self) -> i32 {
self.scale_1000(self.descent)
}
pub(crate) fn pdf_bbox_1000(&self) -> [i32; 4] {
[
self.scale_1000(f32::from(self.bbox[0])),
self.scale_1000(f32::from(self.bbox[1])),
self.scale_1000(f32::from(self.bbox[2])),
self.scale_1000(f32::from(self.bbox[3])),
]
}
}
/// Process-lifetime catalogue (one slot per `FaceId::all()` member).
/// Faces load on first `get` so a conversion that uses three families
/// does not parse the other forty-four (plan Step 2e).
///
/// `OnceLock<Box<Face>>` so the array is pointer-sized. `[OnceLock<Face>; 47]`
/// overflowed the Windows CLI stack (`jubarte convert` in convert_docx_to_pdf).
struct Catalogue {
faces: [OnceLock<Box<Face<'static>>>; 47],
}
fn catalogue() -> &'static Catalogue {
static CATALOGUE: LazyLock<Catalogue> = LazyLock::new(|| {
debug_assert_eq!(FaceId::all().len(), 47);
Catalogue {
faces: std::array::from_fn(|_| OnceLock::new()),
}
});
&CATALOGUE
}
impl Catalogue {
fn get(&self, id: FaceId) -> &Face<'static> {
self.faces[id.index()]
.get_or_init(|| {
Box::new(
system_override(id)
.and_then(|path| Face::from_path(id, &path))
.unwrap_or_else(|| Face::load(id)),
)
})
.as_ref()
}
}
/// A document's decoded embedded fonts (`.odttf`), keyed by
/// (family, bold, italic). The conversion owns them; [`Fonts`] borrows.
/// Values are shared: installed faces come from a process-wide cache and
/// one face can answer to a family and its altName.
pub(crate) type EmbeddedFonts = HashMap<(String, bool, bool), Arc<[u8]>>;
/// Bundled catalogue plus per-document embedded faces (`.odttf`).
pub(crate) struct Fonts<'a> {
extra: Vec<Face<'a>>,
extra_index: HashMap<FaceKey, u16>,
/// Where each catalogue face lands: an embedded face of its family or
/// the slot its family maps to. Every glyph asks, and answering took
/// string matching (a quarter of fixtures_500 88b46971's conversion).
catalogue_slots: Mutex<HashMap<FaceId, FaceRef>>,
}
impl<'a> Fonts<'a> {
pub(crate) fn new() -> Self {
Self {
extra: Vec::new(),
extra_index: HashMap::new(),
catalogue_slots: Mutex::new(HashMap::new()),
}
}
/// Faces for one document, borrowing its embedded font bytes: they are
/// dropped with the conversion (#11: they were leaked process-wide).
pub(crate) fn for_document(embedded: &'a EmbeddedFonts) -> Self {
let mut fonts = Self::new();
for ((family, bold, italic), bytes) in embedded {
fonts.insert_embedded(family, *bold, *italic, bytes.as_ref());
}
fonts
}
pub(crate) fn insert_embedded(
&mut self,
family: &str,
bold: bool,
italic: bool,
bytes: &'a [u8],
) {
// PDF FontFile2 carries TrueType outlines only: a CFF face (an .otf
// or a CFF .odttf) would reach the writer unembeddable. Such a family
// resolves as if the face were absent.
if ttf_parser::Face::parse(bytes, 0)
.ok()
.is_none_or(|face| face.tables().glyf.is_none())
{
return;
}
let ps = ttf_postscript_name(bytes).unwrap_or_else(|| family.to_string());
let Some(face) = Face::from_bytes(FaceId::CarlitoRegular, bytes, sanitize_pdf_name(&ps))
else {
return;
};
let Ok(idx) = u16::try_from(self.extra.len()) else {
return;
};
self.extra.push(face);
if let Ok(slots) = self.catalogue_slots.get_mut() {
slots.clear();
}
self.extra_index.insert(
FaceKey {
family: family.to_ascii_lowercase(),
bold,
italic,
},
idx,
);
}
/// Word's face for an East Asian family it does not have: Microsoft
/// YaHei for Chinese (0025b0d3's absent 標楷體, the 方正 families),
/// Yu Gothic for Japanese (font-table charset 80 or kana in the name),
/// and for Korean (charset 81 or Hangul in the name) Batang when the
/// table calls the family roman, else Malgun Gothic (ko_fonts_0930).
fn cjk_fallback_index(
&self,
family: &str,
bold: bool,
table: &super::font_table::FontTable,
) -> Option<u16> {
let charset = table.get(family).and_then(|e| e.charset.as_deref());
let east_asian_charset = matches!(charset, Some("80" | "86" | "88" | "81"));
if !east_asian_charset && !family.chars().any(is_cjk_name_char) {
return None;
}
let japanese = charset == Some("80")
|| family.chars().any(|c| {
('\u{3040}'..='\u{30FF}').contains(&c) || ('\u{FF66}'..='\u{FF9F}').contains(&c)
});
let korean = charset == Some("81")
|| family.chars().any(|c| {
('\u{AC00}'..='\u{D7A3}').contains(&c) || ('\u{1100}'..='\u{11FF}').contains(&c)
});
let roman = table
.get(family)
.is_some_and(|e| e.family == super::font_table::FontFamilyClass::Roman);
let key = if japanese {
CJK_FALLBACK_JA
} else if korean && roman {
CJK_FALLBACK_KO_SERIF
} else if korean {
CJK_FALLBACK_KO
} else {
CJK_FALLBACK
};
self.embedded_index(key, bold, false)
}
/// The face `add_script_fallback` loaded under `key`.
pub(crate) fn script_fallback(&self, key: &str, bold: bool) -> Option<FaceRef> {
self.embedded_index(key, bold, false).map(FaceRef::Embedded)
}
/// Word's Thaana face (MV Boli) for Dhivehi the resolved face lacks.
pub(crate) fn thaana_glyph_fallback(&self, bold: bool) -> Option<FaceRef> {
self.embedded_index(THAANA_FALLBACK, bold, false)
.map(FaceRef::Embedded)
}
/// The CJK face for a glyph the run's East Asian face lacks: MS Gothic
/// for Times New Roman, which `ea` falls back to when the run names
/// none, else MS Mincho, whatever the language (Word 16 probes jf and
/// 33g, 2026-10-02: Verdana, Arial, Calibri and absent faces are all
/// MS Mincho; zh-CN and ko-KR text too). YaHei only stands in when
/// those two are not installed.
pub(crate) fn cjk_glyph_fallback(&self, bold: bool, ea: Option<&str>) -> Option<FaceRef> {
let key = if ea.is_none_or(|f| fold_family(f) == "timesnewroman") {
CJK_FALLBACK_GOTHIC
} else {
CJK_FALLBACK_MINCHO
};
self.embedded_index(key, bold, false)
.or_else(|| self.embedded_index(CJK_FALLBACK, bold, false))
.map(FaceRef::Embedded)
}
/// Word's Hangul face (Malgun Gothic) for a glyph the resolved face
/// lacks: YaHei, the CJK fallback, has no Hangul.
pub(crate) fn hangul_glyph_fallback(&self, bold: bool) -> Option<FaceRef> {
self.embedded_index(CJK_FALLBACK_KO, bold, false)
.map(FaceRef::Embedded)
}
fn embedded_index(&self, family: &str, bold: bool, italic: bool) -> Option<u16> {
let exact = FaceKey {
family: family.to_ascii_lowercase(),
bold,
italic,
};
if let Some(&idx) = self.extra_index.get(&exact) {
return Some(idx);
}
// Then the regular face, then any face at all: Word paints Segoe
// Print, installed only as Bold, in that Bold (probe my5).
[
(false, false),
(bold, !italic),
(!bold, italic),
(!bold, !italic),
]
.into_iter()
.find_map(|(bold, italic)| {
self.extra_index
.get(&FaceKey {
family: exact.family.clone(),
bold,
italic,
})
.copied()
})
}
/// `family` is present and not an East Asian face: Calibri, not SimSun
/// (or a CJK name that is not installed, whose substitute says nothing).
pub(crate) fn family_is_latin_only(&self, family: &str) -> bool {
if !family.is_ascii() || !cjk_file_stems(family).is_empty() {
return false;
}
let present =
self.embedded_index(family, false, false).is_some() || catalogue_paints_family(family);
present && !self.get(self.resolve(family, false, false)).east_asian
}
/// Whether `family` is an East Asian face: a name written in CJK or
/// one we know as CJK, or a present face whose code pages are East
/// Asian. An absent Latin name, accented or not, is not.
pub(crate) fn family_is_east_asian(&self, family: &str) -> bool {
if family.chars().any(super::is_cjk_break_char) || !cjk_file_stems(family).is_empty() {
return true;
}
let present =
self.embedded_index(family, false, false).is_some() || catalogue_paints_family(family);
present && self.get(self.resolve(family, false, false)).east_asian
}
/// An installed or embedded eastAsia face's average character width
/// as an em fraction (Word 16 probe sp2: MS Mincho and MS Gothic
/// 0.5em), the width a balanced space takes under
/// `w:balanceSingleByteDoubleByteWidth`; `None` for an absent name.
pub(crate) fn east_asia_avg_em(&self, family: &str) -> Option<f32> {
self.east_asia_face(family).map(|face| face.avg_char_width)
}
/// `family`'s face when installed or embedded.
pub(crate) fn east_asia_face(&self, family: &str) -> Option<&Face<'a>> {
let present =
self.embedded_index(family, false, false).is_some() || catalogue_paints_family(family);
present.then(|| self.get(self.resolve(family, false, false)))
}
pub(crate) fn get(&self, id: impl Into<FaceRef>) -> &Face<'a> {
match id.into() {
FaceRef::Catalogue(id) => match self.catalogue_slot(id) {
FaceRef::Catalogue(id) => catalogue().get(id),
FaceRef::Embedded(i) => self
.extra
.get(usize::from(i))
.unwrap_or_else(|| catalogue().get(FaceId::CarlitoRegular)),
},
FaceRef::Embedded(i) => self
.extra
.get(usize::from(i))
.unwrap_or_else(|| catalogue().get(FaceId::CarlitoRegular)),
}
}
/// `get_key(&id.key())`'s face, remembered per face.
fn catalogue_slot(&self, id: FaceId) -> FaceRef {
if let Some(slot) = self
.catalogue_slots
.lock()
.ok()
.and_then(|slots| slots.get(&id).copied())
{
return slot;
}
let key = id.key();
let slot = match self.embedded_index(&key.family, key.bold, key.italic) {
Some(idx) => FaceRef::Embedded(idx),
None => FaceRef::Catalogue(Self::id_from_key(&key)),
};
if let Ok(mut slots) = self.catalogue_slots.lock() {
slots.insert(id, slot);
}
slot
}
/// The unremembered lookup `catalogue_slot` must agree with.
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
pub(crate) fn get_key(&self, key: &FaceKey) -> &Face<'a> {
if let Some(idx) = self.embedded_index(&key.family, key.bold, key.italic) {
return self
.extra
.get(usize::from(idx))
.unwrap_or_else(|| catalogue().get(FaceId::CarlitoRegular));
}
catalogue().get(Self::id_from_key(key))
}
/// Unknown families fall back to the Cambria face of the same style,
/// as [`Self::face_from_physical`] does (not always Cambria Regular).
fn id_from_key(key: &FaceKey) -> FaceId {
Self::face_from_physical(&key.family, key.bold, key.italic)
}
pub(crate) fn resolve(&self, family: &str, bold: bool, italic: bool) -> FaceRef {
let (face, entry) =
ACTIVE_FONT_TABLE.with(|slot| self.classify_in(family, bold, italic, &slot.borrow()));
record_font_resolution(entry);
face
}
/// Resolve `family` and classify the step without recording a report row.
pub(crate) fn classify_in(
&self,
family: &str,
bold: bool,
italic: bool,
table: &super::font_table::FontTable,
) -> (FaceRef, FontReportEntry) {
let primary = family_token(family);
if let Some(idx) = self.embedded_index(primary, bold, italic) {
let face = FaceRef::Embedded(idx);
let exact = self.extra_index.contains_key(&FaceKey {
family: primary.to_ascii_lowercase(),
bold,
italic,
});
return (
face,
FontReportEntry {
requested: family.to_string(),
step: FontStep::Embedded,
physical: self.get(face).pdf_name().to_string(),
bold,
italic,
synthetic: (bold || italic) && !exact,
},
);
}
if let Some(idx) = self.cjk_fallback_index(primary, bold, table) {
let face = FaceRef::Embedded(idx);
return (
face,
FontReportEntry {
requested: family.to_string(),
step: FontStep::Generic,
physical: self.get(face).pdf_name().to_string(),
bold,
italic,
synthetic: false,
},
);
}
let mut visited = HashSet::new();
let (id, step) = self.resolve_walk(family, bold, italic, table, &mut visited);
// `mapped_face` also places families by their name's class (`Fake
// Serif` on the serif face, `Helvetica` on Arial): the face is
// installed, but it is not the family asked for.
let step = match step {
FontStep::Explicit if !names_family(primary, id.logical_family()) => FontStep::Generic,
step => step,
};
let face = FaceRef::Catalogue(id);
(
face,
FontReportEntry {
requested: family.to_string(),
step,
physical: self.get(face).pdf_name().to_string(),
bold,
italic,
synthetic: (bold && !id.is_bold_style()) || (italic && !id.is_italic_style()),
},
)
}
/// Resolve `family` using Word's font table. Installed faces win;
/// otherwise `w:altName`, then the Word-substitution evidence table,
/// then the entry's generic. Unknown names use the evidence table's
/// Cambria row (plan Step 2d).
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
pub(crate) fn resolve_in(
&self,
family: &str,
bold: bool,
italic: bool,
table: &super::font_table::FontTable,
) -> FaceId {
self.resolve_in_step(family, bold, italic, table).0
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
fn resolve_in_step(
&self,
family: &str,
bold: bool,
italic: bool,
table: &super::font_table::FontTable,
) -> (FaceId, FontStep) {
let mut visited = HashSet::new();
self.resolve_walk(family, bold, italic, table, &mut visited)
}
/// Follow `family` through the font table. Iterative: an altName chain
/// is bounded by the table's size, never by the call stack.
fn resolve_walk(
&self,
family: &str,
bold: bool,
italic: bool,
table: &super::font_table::FontTable,
visited: &mut HashSet<String>,
) -> (FaceId, FontStep) {
let mut current = family;
let mut via_alt = false;
// The generic of the first entry the altName chain passed through:
// a chain that dead-ends in an absent altName keeps it.
let mut chain_generic = "";
let (id, step) = loop {
// Word splits rFonts on comma but does not CSS-unquote. Evidence
// (Quartz PDFs): `Verdana, Geneva, sans-serif` → Verdana;
// `"Times New Roman", Times, serif` → Cambria, because the first
// token still carries the quote characters and is not TNR.
let primary = family_token(current);
let quoted = primary.starts_with('"') || primary.starts_with('\'');
if !quoted {
let key = primary
.to_ascii_lowercase()
.replace([' ', '-'], "")
.replace("mt", "");
if let Some(id) = Self::mapped_face(&key, bold, italic) {
break (id, Self::catalogue_step(id));
}
}
let visit_key = primary.to_ascii_lowercase();
if !visited.insert(visit_key) {
break (
Self::face_from_physical(&super::word_subst::unknown_physical(), bold, italic),
FontStep::Unknown,
);
}
// Word records its substitution against the whole `w:name`, so a
// CSS-style list row (`"Foo", Bar, serif`) is keyed by the full
// string, not by its first token.
let whole = current.trim();
// Every entry stands for a generic, whatever its panose and
// pitch say (Word 16 probes my6/my7): roman is Cambria, any
// other family Calibri.
if chain_generic.is_empty()
&& let Some(entry) = table.get(primary)
{
chain_generic = super::word_subst::entry_generic(entry);
}
let alt = table
.alt_name(primary)
.or_else(|| (whole != primary).then(|| table.alt_name(whole)).flatten());
if let Some(alt) = alt {
current = alt;
via_alt = true;
continue;
}
if let Some(physical) = super::word_subst::lookup_physical(primary) {
break (
Self::face_from_physical(&physical, bold, italic),
FontStep::WordSubstitution,
);
}
if !chain_generic.is_empty() {
break (
Self::face_from_physical(chain_generic, bold, italic),
FontStep::Generic,
);
}
break (
Self::face_from_physical(&super::word_subst::unknown_physical(), bold, italic),
FontStep::Unknown,
);
};
(id, if via_alt { FontStep::AltName } else { step })
}
/// `family` names an installed catalogue face directly (the report's
/// `explicit` step, no altName / substitution / generic hop).
pub(crate) fn is_installed_family(family: &str) -> bool {
let primary = family_token(family);
if primary.starts_with('"') || primary.starts_with('\'') {
return false;
}
let key = primary
.to_ascii_lowercase()
.replace([' ', '-'], "")
.replace("mt", "");
Self::mapped_face(&key, false, false)
.is_some_and(|id| Self::catalogue_step(id) == FontStep::Explicit)
}
fn catalogue_step(id: FaceId) -> FontStep {
if system_override(id).is_some() {
FontStep::Explicit
} else {
FontStep::OpenFallback
}
}
fn face_from_physical(physical: &str, bold: bool, italic: bool) -> FaceId {
let key = physical
.to_ascii_lowercase()
.replace([' ', '-'], "")
.replace("mt", "");
Self::mapped_face(&key, bold, italic).unwrap_or(match (bold, italic) {
(false, false) => FaceId::CambriaRegular,
(true, false) => FaceId::CambriaBold,
(false, true) => FaceId::CambriaItalic,
(true, true) => FaceId::CambriaBoldItalic,
})
}
}
/// `requested` is `family` itself, ignoring case, spaces, hyphens and an
/// `MT` or `PS MT` suffix (`Arial MT`, `Times New Roman PS MT`), or one of its metric-identical
/// open twins the catalogue bundles (`Carlito` for Calibri).
fn names_family(requested: &str, family: &str) -> bool {
let squash = |s: &str| {
let key = s.to_ascii_lowercase().replace([' ', '-'], "");
// "Times New Roman PS MT" and "Arial MT": a trailing "PS MT" or
// "MT", never a lone "ps" ("Warps" is not "War").
key.strip_suffix("psmt")
.or_else(|| key.strip_suffix("mt"))
.unwrap_or(&key)
.to_string()
};
let (requested, family) = (squash(requested), squash(family));
let twins: &[&str] = match family.as_str() {
"calibri" => &["carlito"],
"cambria" => &["caladea"],
"arial" => &["liberationsans", "arimo"],
"timesnewroman" => &["liberationserif", "tinos"],
"couriernew" => &["liberationmono", "cousine"],
_ => &[],
};
requested == family || twins.contains(&requested.as_str())
}
fn family_token(family: &str) -> &str {
let (token, listed) = match family.split_once(',') {
Some((first, _)) => (first.trim(), true),
None => (family.trim(), false),
};
if listed {
token
} else {
strip_outer_quotes(token)
}
}
fn strip_outer_quotes(s: &str) -> &str {
let t = s.trim();
let bytes = t.as_bytes();
match (bytes.first(), bytes.last()) {
(Some(b'"'), Some(b'"')) | (Some(b'\''), Some(b'\'')) if bytes.len() >= 2 => {
t[1..t.len() - 1].trim()
}
_ => t,
}
}
impl Fonts<'_> {
fn carlito(bold: bool, italic: bool) -> FaceId {
match (bold, italic) {
(false, false) => FaceId::CarlitoRegular,
(true, false) => FaceId::CarlitoBold,
(false, true) => FaceId::CarlitoItalic,
(true, true) => FaceId::CarlitoBoldItalic,
}
}
/// Known catalogue faces. `None` means "not in the 47-face table" so
/// `resolve_in` can try `altName` before the Carlito last resort.
fn mapped_face(key: &str, bold: bool, italic: bool) -> Option<FaceId> {
let mono = key.contains("courier")
|| key.contains("monaco")
|| key.contains("menlo")
|| key.contains("cousine")
|| key.contains("nimbusmono")
|| (key.ends_with("mono") && !key.contains("dejavu"));
let aptos_display = key.starts_with("aptosdisplay")
|| (key.starts_with("aptos") && key.contains("display"));
let aptos = key.starts_with("aptos") && !aptos_display;
let verdana = key.starts_with("verdana");
// Official Word Quartz substitutes missing Inter with Cambria
// (sample_document / eigenpal). Times overlay on the serif slot
// left that cluster at ITT ~44.
if key.contains("symbol") {
return Some(FaceId::Symbol);
}
// Strict01 Title/Heading1/2 are major=Calibri Light. Do not fall
// through to Calibri Regular (Carlito).
if key.contains("calibrilight") || (key.contains("calibri") && key.contains("light")) {
return Some(if italic {
FaceId::CalibriLightItalic
} else {
FaceId::CalibriLightRegular
});
}
// Calibri/Carlito is the catalogue default, not the unknown-family
// last resort — otherwise altName on Calibri would steal Cambria.
if key.contains("calibri") || key.contains("carlito") {
return Some(Self::carlito(bold, italic));
}
if key.contains("cambria") || key == "inter" {
return Some(match (bold, italic) {
(false, false) => FaceId::CambriaRegular,
(true, false) => FaceId::CambriaBold,
(false, true) => FaceId::CambriaItalic,
(true, true) => FaceId::CambriaBoldItalic,
});
}
if key.contains("consolas") {
return Some(match (bold, italic) {
(false, false) => FaceId::ConsolasRegular,
(true, false) => FaceId::ConsolasBold,
(false, true) => FaceId::ConsolasItalic,
(true, true) => FaceId::ConsolasBoldItalic,
});
}
if key.contains("georgia") {
return Some(match (bold, italic) {
(false, false) => FaceId::GeorgiaRegular,
(true, false) => FaceId::GeorgiaBold,
(false, true) => FaceId::GeorgiaItalic,
(true, true) => FaceId::GeorgiaBoldItalic,
});
}
// file_22 / sd_2517 live period run is Book Antiqua. Folding it
// into Carlito (or Times) missed Word Quartz's BookAntiqua embed.
if key.contains("bookantiqua") || key.contains("palatino") {
return Some(match (bold, italic) {
(false, false) => FaceId::BookAntiquaRegular,
(true, false) => FaceId::BookAntiquaBold,
(false, true) => FaceId::BookAntiquaItalic,
(true, true) => FaceId::BookAntiquaBoldItalic,
});
}
let sans = key.contains("arial")
|| key.contains("helvetica")
|| key.contains("liberationsans")
|| key.contains("opensans")
|| key.contains("roboto")
|| key.contains("tahoma")
|| key.contains("trebuchet")
|| key.contains("geneva")
|| key == "sansserif";
let serif = key.contains("times")
|| key.contains("caladea")
|| key.contains("liberationserif")
|| (key.contains("serif") && !key.contains("sans"));
match (
mono,
aptos_display,
aptos,
verdana,
sans,
serif,
bold,
italic,
) {
(true, _, _, _, _, _, false, false) => Some(FaceId::MonoRegular),
(true, _, _, _, _, _, true, false) => Some(FaceId::MonoBold),
(true, _, _, _, _, _, false, true) => Some(FaceId::MonoItalic),
(true, _, _, _, _, _, true, true) => Some(FaceId::MonoBoldItalic),
(_, true, _, _, _, _, false, false) => Some(FaceId::AptosDisplayRegular),
(_, true, _, _, _, _, true, false) => Some(FaceId::AptosDisplayBold),
(_, true, _, _, _, _, false, true) => Some(FaceId::AptosDisplayItalic),
(_, true, _, _, _, _, true, true) => Some(FaceId::AptosDisplayBoldItalic),
(_, _, true, _, _, _, false, false) => Some(FaceId::AptosRegular),
(_, _, true, _, _, _, true, false) => Some(FaceId::AptosBold),
(_, _, true, _, _, _, false, true) => Some(FaceId::AptosItalic),
(_, _, true, _, _, _, true, true) => Some(FaceId::AptosBoldItalic),
(_, _, _, true, _, _, false, false) => Some(FaceId::VerdanaRegular),
(_, _, _, true, _, _, true, false) => Some(FaceId::VerdanaBold),
(_, _, _, true, _, _, false, true) => Some(FaceId::VerdanaItalic),
(_, _, _, true, _, _, true, true) => Some(FaceId::VerdanaBoldItalic),
(_, _, _, _, true, _, false, false) => Some(FaceId::SansRegular),
(_, _, _, _, true, _, true, false) => Some(FaceId::SansBold),
(_, _, _, _, true, _, false, true) => Some(FaceId::SansItalic),
(_, _, _, _, true, _, true, true) => Some(FaceId::SansBoldItalic),
(_, _, _, _, _, true, false, false) => Some(FaceId::SerifRegular),
(_, _, _, _, _, true, true, false) => Some(FaceId::SerifBold),
(_, _, _, _, _, true, false, true) => Some(FaceId::SerifItalic),
(_, _, _, _, _, true, true, true) => Some(FaceId::SerifBoldItalic),
_ => None,
}
}
}
/// `system_override_uncached`, remembered for the process: font
/// resolution asks for every run, and each ask was up to eight `stat`s
/// (a fifth of a conversion's samples).
fn system_override(id: FaceId) -> Option<PathBuf> {
static CACHE: LazyLock<Mutex<HashMap<FaceId, Option<PathBuf>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.get(&id).cloned()) {
return hit;
}
let found = system_override_uncached(id);
if let Ok(mut cache) = CACHE.lock() {
cache.insert(id, found.clone());
}
found
}
fn system_override_uncached(id: FaceId) -> Option<PathBuf> {
let names: &[&str] = match id {
FaceId::CarlitoRegular => &["Calibri.ttf", "calibri.ttf"],
FaceId::CarlitoBold => &["Calibrib.ttf", "Calibri Bold.ttf", "calibrib.ttf"],
FaceId::CarlitoItalic => &["Calibrii.ttf", "Calibri Italic.ttf", "calibrii.ttf"],
FaceId::CarlitoBoldItalic => &["Calibriz.ttf", "Calibri Bold Italic.ttf", "calibriz.ttf"],
FaceId::SansRegular => &["Arial.ttf", "arial.ttf"],
FaceId::SansBold => &["Arial Bold.ttf", "arialbd.ttf"],
FaceId::SansItalic => &["Arial Italic.ttf", "ariali.ttf"],
FaceId::SansBoldItalic => &["Arial Bold Italic.ttf", "arialbi.ttf"],
FaceId::SerifRegular => &["Times New Roman.ttf", "times.ttf"],
FaceId::SerifBold => &["Times New Roman Bold.ttf", "timesbd.ttf"],
FaceId::SerifItalic => &["Times New Roman Italic.ttf", "timesi.ttf"],
FaceId::SerifBoldItalic => &["Times New Roman Bold Italic.ttf", "timesbi.ttf"],
FaceId::MonoRegular => &["Courier New.ttf", "cour.ttf"],
FaceId::MonoBold => &["Courier New Bold.ttf", "courbd.ttf"],
FaceId::MonoItalic => &["Courier New Italic.ttf", "couri.ttf"],
FaceId::MonoBoldItalic => &["Courier New Bold Italic.ttf", "courbi.ttf"],
FaceId::AptosRegular => &["Aptos.ttf"],
FaceId::AptosBold => &["Aptos-Bold.ttf"],
FaceId::AptosItalic => &["Aptos-Italic.ttf"],
FaceId::AptosBoldItalic => &["Aptos-Bold-Italic.ttf"],
FaceId::AptosDisplayRegular => &["AptosDisplay-Regular.ttf", "AptosDisplay.ttf"],
FaceId::AptosDisplayBold => &["AptosDisplay-Bold.ttf"],
FaceId::AptosDisplayItalic => &["AptosDisplay-Italic.ttf"],
FaceId::AptosDisplayBoldItalic => &["AptosDisplay-BoldItalic.ttf"],
FaceId::CalibriLightRegular => &["calibril.ttf", "Calibri Light.ttf", "CalibriL.ttf"],
FaceId::CalibriLightItalic => &["calibrili.ttf", "Calibri Light Italic.ttf"],
FaceId::VerdanaRegular => &["Verdana.ttf"],
FaceId::VerdanaBold => &["Verdana Bold.ttf", "Verdanab.ttf"],
FaceId::VerdanaItalic => &["Verdana Italic.ttf", "Verdanai.ttf"],
FaceId::VerdanaBoldItalic => &["Verdana Bold Italic.ttf", "Verdanaz.ttf"],
FaceId::CambriaRegular => &["Cambria.ttf", "Cambria.ttc"],
FaceId::CambriaBold => &["Cambriab.ttf", "Cambria Bold.ttf"],
FaceId::CambriaItalic => &["Cambriai.ttf", "Cambria Italic.ttf"],
FaceId::CambriaBoldItalic => &["Cambriaz.ttf", "Cambria Bold Italic.ttf"],
FaceId::ConsolasRegular => &["Consola.ttf", "Consolas.ttf", "consola.ttf"],
FaceId::ConsolasBold => &["Consolab.ttf", "Consolas Bold.ttf", "consolab.ttf"],
FaceId::ConsolasItalic => &["Consolai.ttf", "Consolas Italic.ttf", "consolai.ttf"],
FaceId::ConsolasBoldItalic => &["Consolaz.ttf", "Consolas Bold Italic.ttf", "consolaz.ttf"],
FaceId::GeorgiaRegular => &["Georgia.ttf", "georgia.ttf"],
FaceId::GeorgiaBold => &["Georgia Bold.ttf", "georgiab.ttf"],
FaceId::GeorgiaItalic => &["Georgia Italic.ttf", "georgiai.ttf"],
FaceId::GeorgiaBoldItalic => &["Georgia Bold Italic.ttf", "georgiaz.ttf"],
FaceId::BookAntiquaRegular => &["Book Antiqua.ttf", "pala.ttf"],
FaceId::BookAntiquaBold => &["Book Antiqua Bold.ttf", "palab.ttf"],
FaceId::BookAntiquaItalic => &["Book Antiqua Italic.ttf", "palai.ttf"],
FaceId::BookAntiquaBoldItalic => &["Book Antiqua Bold Italic.ttf", "palabi.ttf"],
FaceId::Symbol => &["Symbol.ttf", "symbol.ttf"],
};
// Deliberately macOS-only: these overrides exist to match the
// Word-on-macOS oracles this converter is calibrated against. On other
// platforms no override is found and the bundled metric-compatible
// faces are used.
// Arial/Verdana/Georgia live in Supplemental; Calibri/Cambria/Aptos in
// DFonts. Symbol is DFonts/Microsoft only: Apple's `Symbol.ttf` (system
// or Supplemental on GitHub macOS runners) is not Word SymbolMT.
const WORD_DIRS: &[&str] = &[
"/Applications/Microsoft Word.app/Contents/Resources/DFonts",
"/Library/Fonts/Microsoft",
];
const DIRS: &[&str] = &[
"/Applications/Microsoft Word.app/Contents/Resources/DFonts",
"/Library/Fonts/Microsoft",
"/System/Library/Fonts/Supplemental",
"/Library/Fonts",
];
// Times New Roman: Word draws the installed macOS face (5.01, hhea
// lineGap 87 → 13.8pt at 12) over its private DFonts copy (7.0,
// lineGap 0 → 13.29); fixtures_500 014babb2 double lines are 27.6pt.
const INSTALLED_FIRST: &[&str] = &[
"/System/Library/Fonts/Supplemental",
"/Library/Fonts",
"/Applications/Microsoft Word.app/Contents/Resources/DFonts",
"/Library/Fonts/Microsoft",
];
let dirs = match id {
FaceId::Symbol => WORD_DIRS,
FaceId::SerifRegular
| FaceId::SerifBold
| FaceId::SerifItalic
| FaceId::SerifBoldItalic => INSTALLED_FIRST,
_ => DIRS,
};
for dir in dirs {
for name in names {
let path = Path::new(dir).join(name);
if path.is_file() {
return Some(path);
}
}
}
cloud_font_override(id)
}
/// Installed faces for a family the catalogue has no slot for, keyed by
/// (bold, italic). Word draws these with the real file (fixtures_500:
/// Tahoma in 158 documents, Segoe UI from Word's cloud-font cache,
/// Century Gothic in DFonts); we painted them as Arial or Calibri.
/// Candidates are files whose normalised name starts with the family's,
/// confirmed against the font's own family name.
/// Word's cloud-font folder for `family`, when the name is one plain path
/// component: `w:name` is document data, and "../.." or an absolute name
/// would read fonts from anywhere (PR #167 review).
fn cloud_font_dir(home: &Path, family: &str) -> Option<PathBuf> {
let mut parts = Path::new(family).components();
match (parts.next(), parts.next()) {
(Some(std::path::Component::Normal(_)), None) => Some(
home.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts")
.join(family),
),
_ => None,
}
}
/// A font folder's entries, sorted, listed once per process: every
/// family lookup walks the same system folders (hundreds of entries).
fn sorted_dir_listing(dir: &Path) -> Arc<Vec<PathBuf>> {
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Arc<Vec<PathBuf>>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.get(dir).cloned()) {
return hit;
}
let read = fs::read_dir(dir);
// Permission can be granted later without a new directory mtime
// (macOS privacy, or chmod). Caching the empty denial would hide the
// fonts for the rest of the process (#2051).
if matches!(&read, Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied) {
return Arc::new(Vec::new());
}
let mut paths: Vec<PathBuf> = read
.map(|entries| entries.flatten().map(|e| e.path()).collect())
.unwrap_or_default();
paths.sort();
let paths = Arc::new(paths);
if let Ok(mut cache) = CACHE.lock() {
cache.insert(dir.to_path_buf(), Arc::clone(&paths));
}
paths
}
pub(crate) fn installed_family_faces(family: &str) -> Vec<((bool, bool), Vec<u8>)> {
let stems = cjk_file_stems(family);
if !stems.is_empty() {
return cjk_family_faces(family, stems);
}
let user = user_font_dir();
let cloud_root = std::env::var_os("HOME")
.and_then(|home| cloud_font_dir(Path::new(&home), "x"))
.and_then(|d| d.parent().map(Path::to_path_buf));
let key = format!(
"family\u{1f}{family}\u{1f}{}\u{1f}{}",
user.as_deref().unwrap_or(Path::new("")).display(),
cloud_root.as_deref().unwrap_or(Path::new("")).display()
);
indexed_faces(&FONT_INDEX, &key, || {
let (faces, mut dirs) = scan_family_faces(family, user.as_deref());
dirs.extend(cloud_root.clone());
(faces, dirs)
})
}
/// `family`'s faces from the system, Word and cloud-font folders and
/// jubarte's own, with the folders the search listed.
fn scan_family_faces(family: &str, user: Option<&Path>) -> (SourcedFaces, Vec<PathBuf>) {
const DIRS: &[&str] = &[
"/System/Library/Fonts/Supplemental",
"/Library/Fonts",
"/Applications/Microsoft Word.app/Contents/Resources/DFonts",
"/Library/Fonts/Microsoft",
"/System/Library/Fonts",
];
let norm = |s: &str| -> String {
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect()
};
// A name with no Latin key (华文仿宋) can only match a cloud folder by
// the family names inside its fonts; file names say nothing about it.
let latin = norm(family).len() >= 3;
// (dir, whole folder is the family): Word's cloud-font cache keeps each
// family in its own folder under numeric file names (Poppins/2397….ttf).
let mut dirs: Vec<(PathBuf, bool)> = if latin {
DIRS.iter()
.map(PathBuf::from)
.chain(windows_font_dirs())
.map(|d| (d, false))
.collect()
} else {
Vec::new()
};
dirs.extend(cloud_font_dirs(family));
let mut listed: Vec<PathBuf> = dirs.iter().map(|(d, _)| d.clone()).collect();
listed.extend(user.map(Path::to_path_buf));
if dirs.is_empty() {
return (Vec::new(), listed);
}
(faces_with_user_fonts(family, &dirs, user), listed)
}
/// Word's cloud-font folders that may hold `family`, each a whole-family
/// folder: its own or, when it has none, any whose name starts it. Word files a style
/// family under its parent (fixtures_500 001d945a: "Script MT Bold" in
/// "Script MT/", 01838a08: "Roboto Condensed" in "Roboto/"); the faces
/// still answer only to their own family name. Parent names come from the
/// cache's own listing, never from the document.
fn cloud_font_dirs(family: &str) -> Vec<(PathBuf, bool)> {
let home = std::env::var_os("HOME");
cloud_font_dirs_with(
family,
home.as_deref().map(Path::new),
&sorted_dir_listing,
&Path::is_dir,
&cloud_folder_names,
)
}
fn cloud_font_dirs_with(
family: &str,
home: Option<&Path>,
listing: &impl Fn(&Path) -> Arc<Vec<PathBuf>>,
is_dir: &impl Fn(&Path) -> bool,
folder_names: &impl Fn(&Path) -> Arc<FolderNames>,
) -> Vec<(PathBuf, bool)> {
let Some(home) = home else {
return Vec::new();
};
let own = cloud_font_dir(home, family);
if let Some(dir) = own.as_ref().filter(|d| is_dir(d)) {
return vec![(dir.clone(), true)];
}
let mut out: Vec<(PathBuf, bool)> = own.map(|dir| (dir, true)).into_iter().collect();
let Some(root) = cloud_font_dir(home, "x").and_then(|d| d.parent().map(Path::to_path_buf))
else {
return out;
};
let want = fold_family(family);
for dir in listing(&root).iter() {
let Some(name) = dir.file_name().and_then(|n| n.to_str()) else {
continue;
};
let parent = fold_family(name);
if parent.len() >= 3 && parent.len() < want.len() && want.starts_with(&parent) {
out.push((dir.clone(), true));
}
}
let latin = want.chars().filter(char::is_ascii_alphanumeric).count() >= 3;
if !latin && out.iter().all(|(d, _)| !is_dir(d)) {
// Word files a family under its English name and answers to its
// localized one too: 华文仿宋 lives in CloudFonts/STFangsong/, whose
// name table carries 华文仿宋 for zh-CN (fixtures_500 004599833e).
out.extend(
folder_names(&root)
.iter()
.filter(|(_, names)| names.contains(&want))
.map(|(dir, _)| (dir.clone(), true)),
);
}
out
}
/// Cloud-font folders, each with the folded family names its fonts carry.
type FolderNames = Vec<(PathBuf, Vec<String>)>;
/// Each cloud-font folder with the family names (IDs 1 and 16, every
/// language, folded) of its first font, read once per process: a folder
/// holds one family, and the cache is ~60 MB, too much to read whole.
fn cloud_folder_names(root: &Path) -> Arc<FolderNames> {
static CACHE: LazyLock<Mutex<HashMap<PathBuf, Arc<FolderNames>>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.get(root).cloned()) {
return hit;
}
let out = cloud_folder_names_with(root, &sorted_dir_listing, &Path::is_dir, &|file| {
fs::read(file).ok()
});
let out = Arc::new(out);
if let Ok(mut cache) = CACHE.lock() {
cache.insert(root.to_path_buf(), Arc::clone(&out));
}
out
}
fn cloud_folder_names_with(
root: &Path,
listing: &impl Fn(&Path) -> Arc<Vec<PathBuf>>,
is_dir: &impl Fn(&Path) -> bool,
read: &impl Fn(&Path) -> Option<Vec<u8>>,
) -> FolderNames {
let mut out = Vec::new();
for dir in listing(root).iter().filter(|d| is_dir(d)) {
let mut names = Vec::new();
let first = listing(dir).iter().find_map(|file| read(file));
if let Some(bytes) = first
&& let Ok(face) = ttf_parser::Face::parse(&bytes, 0)
{
names.extend(face_family_names(&face, ttf_parser::name_id::FAMILY));
names.extend(face_family_names(
&face,
ttf_parser::name_id::TYPOGRAPHIC_FAMILY,
));
}
names.sort();
names.dedup();
out.push((dir.clone(), names));
}
out
}
/// `family`'s faces from `dirs`, then from jubarte's own font folder
/// (`scripts/install.sh` fills it), then an open stand-in from that folder
/// when the real face is nowhere (Selawik for Segoe UI).
fn faces_with_user_fonts(
family: &str,
dirs: &[(PathBuf, bool)],
user: Option<&Path>,
) -> SourcedFaces {
let mut all = dirs.to_vec();
if let Some(user) = user {
all.push((user.to_path_buf(), false));
}
let found = family_faces_in(family, &all);
if !found.is_empty() {
return found;
}
match (open_stand_in(family), user) {
(Some(stand_in), Some(user)) => family_faces_in(stand_in, &[(user.to_path_buf(), false)]),
_ => Vec::new(),
}
}
/// The open family that stands in for a Microsoft one jubarte cannot ship:
/// Selawik is Microsoft's own metric-compatible Segoe UI substitute (with
/// Word's cloud cache hidden, 010ec7df 0.442 -> 0.447 and 015beda9 gets
/// Word's 4 pages). EB Garamond for Garamond was tried and dropped: its
/// metrics are further from Monotype's than the Times fallback (00dd36c7
/// 0.181 -> 0.079); Word's own GARA*.ttf is now found by family name. Cooper Black and Script MT have no open equivalent.
fn open_stand_in(family: &str) -> Option<&'static str> {
(fold_family(family) == "segoeui").then_some("Selawik")
}
/// `family`'s faces in `dirs` ((folder, whole folder is the family)).
fn family_faces_in(family: &str, dirs: &[(PathBuf, bool)]) -> SourcedFaces {
family_faces_in_with(
family,
dirs,
sorted_dir_listing,
|path| fs::read(path),
font_name_index,
)
}
/// The discovery policy, with directory/cache reads supplied by the caller.
/// Production forwards its existing sorted listings and cached name index;
/// memory callers can supply the same records without reading host fonts.
fn family_faces_in_with(
family: &str,
dirs: &[(PathBuf, bool)],
mut list: impl FnMut(&Path) -> Arc<Vec<PathBuf>>,
mut read: impl FnMut(&Path) -> std::io::Result<Vec<u8>>,
mut names: impl FnMut(&Path) -> FontNameIndex,
) -> SourcedFaces {
let norm = |s: &str| -> String {
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect()
};
let key = norm(family);
// Without a Latin key only a whole-family folder can answer; its faces
// still have to carry the requested name.
let latin = key.len() >= 3;
if !latin && dirs.iter().all(|(_, family_folder)| !family_folder) {
return Vec::new();
}
let mut found: Vec<(u8, (bool, bool), SourcedBytes)> = Vec::new();
// Faces from collections rank after single-face files: Word draws its
// own DFonts Rockwell (hhea 1.174em) over macOS's Rockwell.ttc (1.0em
// plus a gap), fixtures_500 0071d504's 15.6pt sidebar lines.
let mut collected: Vec<(u8, (bool, bool), SourcedBytes)> = Vec::new();
for (dir, family_folder) in dirs {
let family_folder = *family_folder;
for path in list(dir).iter() {
let path = path.clone();
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
let is_font = ext.eq_ignore_ascii_case("ttf") || ext.eq_ignore_ascii_case("otf");
let stem = path.file_stem().and_then(|s| s.to_str()).map(norm);
// A collection is named for its whole family (Avenir.ttc holds
// "Avenir Book"); its faces answer to their own names.
if ext.eq_ignore_ascii_case("ttc")
&& latin
&& stem
.as_deref()
.is_some_and(|s| s.len() >= 3 && key.starts_with(s))
{
let Ok(bytes) = read(&path) else {
continue;
};
let count = ttf_parser::fonts_in_collection(&bytes).unwrap_or(0);
for index in 0..count {
let Some(data) = ttc_face_bytes(&bytes, index) else {
continue;
};
if let Some((pass, style)) = face_family_style(&data, family) {
collected.push((pass, style, (FaceSource::new(&path, Some(index)), data)));
}
}
continue;
}
// A system file may be named short of its family ("Arial
// Unicode.ttf" holds "Arial Unicode MS", which Word draws in
// international_terrorism_thesis's header); its own name decides.
// Word's DFonts keep the name-index path below: Word paints
// 012128d3's regular TH SarabunPSK runs in its thsarabun-bold.
let short_ok = !dir.ends_with("DFonts");
let named = latin
&& stem.is_some_and(|s| {
s.starts_with(&key) || (short_ok && s.len() >= 5 && key.starts_with(&s))
});
if !is_font || !(family_folder || named) {
continue;
}
let Ok(bytes) = read(&path) else {
continue;
};
let Some((pass, style)) = face_family_style(&bytes, family) else {
continue;
};
found.push((pass, style, (FaceSource::new(&path, None), bytes)));
}
}
// Windows abbreviates its file names (times.ttf, timesbd.ttf,
// cour.ttf): a stem catches at most the regular face, so its folders
// also answer by the family name inside each file.
for (dir, _) in dirs.iter().filter(|(d, _)| latin && windows_fonts_dir(d)) {
for (path, names) in names(dir).iter() {
let source = FaceSource::new(path, None);
if !names.contains(&key) || found.iter().any(|(_, _, (s, _))| *s == source) {
continue;
}
let Ok(bytes) = read(path) else {
continue;
};
if let Some((pass, style)) = face_family_style(&bytes, family) {
found.push((pass, style, (source, bytes)));
}
}
}
found.append(&mut collected);
if found.is_empty() && latin {
// Word's own fonts carry abbreviated file names (Garamond is
// GARA.ttf / GARAIT.ttf): match its folder by internal family name
// (fixtures_500 00dd36c7 painted Garamond Italic as Times).
for (dir, _) in dirs.iter().filter(|(d, _)| d.ends_with("DFonts")) {
for (path, names) in names(dir).iter() {
if !names.contains(&key) {
continue;
}
let Ok(bytes) = read(path) else {
continue;
};
if let Some((pass, style)) = face_family_style(&bytes, family) {
found.push((pass, style, (FaceSource::new(path, None), bytes)));
}
}
}
}
sourced(pick_ranked_faces(found))
}
/// Font files with their normalised family names.
type FontNameIndex = Arc<Vec<(PathBuf, Vec<String>)>>;
/// Each `.ttf`/`.otf` in `dir` with its normalised family names (name IDs
/// 1 and 16), read once per process.
fn font_name_index(dir: &Path) -> FontNameIndex {
static CACHE: LazyLock<Mutex<HashMap<PathBuf, FontNameIndex>>> =
LazyLock::new(|| Mutex::new(HashMap::new()));
if let Some(hit) = CACHE.lock().ok().and_then(|c| c.get(dir).cloned()) {
return hit;
}
let norm = |s: &str| -> String {
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect()
};
let mut out = Vec::new();
for path in sorted_dir_listing(dir).iter() {
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
if !(ext.eq_ignore_ascii_case("ttf") || ext.eq_ignore_ascii_case("otf")) {
continue;
}
let Ok(bytes) = fs::read(path) else {
continue;
};
let Ok(face) = ttf_parser::Face::parse(&bytes, 0) else {
continue;
};
let names: Vec<String> = face
.names()
.into_iter()
.filter(|n| matches!(n.name_id, 1 | 16) && n.is_unicode())
.filter_map(|n| n.to_string())
.map(|n| norm(&n))
.collect();
out.push((path.clone(), names));
}
let out = Arc::new(out);
if let Ok(mut cache) = CACHE.lock() {
cache.insert(dir.to_path_buf(), Arc::clone(&out));
}
out
}
/// jubarte's own font folder: `$JUBARTE_FONT_DIR`, else the platform's
/// per-user data folder (`~/Library/Application Support/jubarte/fonts`,
/// `$XDG_DATA_HOME/jubarte/fonts` or `~/.local/share/jubarte/fonts`,
/// `%APPDATA%\jubarte\fonts`). Fonts live there, not in the binary.
pub(crate) fn user_font_dir() -> Option<PathBuf> {
if let Some(dir) = std::env::var_os("JUBARTE_FONT_DIR").filter(|d| !d.is_empty()) {
return Some(PathBuf::from(dir));
}
if cfg!(target_os = "windows") {
return std::env::var_os("APPDATA").map(|a| PathBuf::from(a).join("jubarte").join("fonts"));
}
let home = PathBuf::from(std::env::var_os("HOME")?);
let data = if cfg!(target_os = "macos") {
home.join("Library/Application Support")
} else {
std::env::var_os("XDG_DATA_HOME")
.filter(|d| !d.is_empty())
.map_or_else(|| home.join(".local/share"), PathBuf::from)
};
Some(data.join("jubarte").join("fonts"))
}
/// A family name folded for comparison: full-width Latin to ASCII (the
/// Japanese "MS 明朝" is MS Mincho's own name), ASCII lowercase, and no
/// spaces, underscores or hyphens.
fn fold_family(name: &str) -> String {
name.chars()
.map(|c| match c {
'\u{FF01}'..='\u{FF5E}' => char::from_u32(c as u32 - 0xFEE0).unwrap_or(c),
_ => c,
})
.filter(|c| !c.is_whitespace() && *c != '_' && *c != '-')
.map(|c| c.to_ascii_lowercase())
.collect()
}
/// East Asian families Word ships in its DFonts, by every name documents
/// use for them, and the file stems that hold them. Word draws these real
/// faces (fixtures_500: MS Mincho in 21 documents, YaHei 16, JhengHei 12,
/// Yu Gothic 11); we had no face for them and their text vanished.
const CJK_FAMILIES: &[(&[&str], &[&str])] = &[
(
&["msmincho", "ms明朝", "mspmincho", "msp明朝"],
&["msmincho"],
),
(
&[
"msgothic",
"msゴシック",
"mspgothic",
"mspゴシック",
"msuigothic",
],
&["msgothic"],
),
(
&[
"yugothic",
"游ゴシック",
"yugothicui",
"yugothicmedium",
"yugothiclight",
"游ゴシックmedium",
"游ゴシックlight",
],
&["yugothr", "yugothm", "yugothb", "yugothl"],
),
(
&[
"yumincho",
"游明朝",
"yuminchodemibold",
"yumincholight",
"游明朝demibold",
"游明朝light",
],
&["yumin", "yumindb", "yuminl"],
),
(&["meiryo", "メイリオ", "meiryoui"], &["meiryo", "meiryob"]),
(
&[
"microsoftyahei",
"微软雅黑",
"microsoftyaheiui",
"microsoftyaheilight",
],
&["msyh", "msyhbd", "msyhl"],
),
(
&["microsoftjhenghei", "微軟正黑體", "microsoftjhengheiui"],
&["msjh", "msjhbd"],
),
(&["simsun", "宋体", "nsimsun", "新宋体"], &["simsun"]),
(&["simhei", "黑体"], &["simhei"]),
(
&["fangsong", "仿宋", "fangsonggb2312", "仿宋gb2312"],
&["fangsong"],
),
(&["kaiti", "楷体", "kaitigb2312", "楷体gb2312"], &["kaiti"]),
(
&["mingliu", "細明體", "pmingliu", "新細明體", "mingliuhkscs"],
&["mingliu", "mingliub"],
),
(
&["batang", "바탕", "batangche", "gungsuh", "궁서"],
&["batang"],
),
(
&["gulim", "굴림", "gulimche", "dotum", "돋움", "dotumche"],
&["gulim"],
),
(&["malgungothic", "맑은고딕"], &["malgun", "malgunbd"]),
(
&["dengxian", "等线", "dengxianlight"],
&["deng", "dengb", "dengl"],
),
(
&[
"hg創英角ゴシックub",
"hgp創英角ゴシックub",
"hgs創英角ゴシックub",
"hgsoeikakugothicub",
"hgpsoeikakugothicub",
"hgssoeikakugothicub",
],
&["hgrsgu"],
),
(
&[
"hgゴシックe",
"hgpゴシックe",
"hgsゴシックe",
"hggothice",
"hgpgothice",
"hgsgothice",
],
&["hgrge"],
),
(
&[
"hg明朝e",
"hgp明朝e",
"hgs明朝e",
"hgminchoe",
"hgpminchoe",
"hgsminchoe",
],
&["hgrme"],
),
];
fn cjk_file_stems(family: &str) -> &'static [&'static str] {
let key = fold_family(family);
CJK_FAMILIES
.iter()
.find(|(names, _)| names.contains(&key.as_str()))
.map_or(&[], |(_, stems)| stems)
}
/// Family names (name IDs `id`) of one face, folded, in every language.
fn face_family_names(face: &ttf_parser::Face<'_>, id: u16) -> Vec<String> {
face.names()
.into_iter()
.filter(|n| n.name_id == id)
.filter_map(|n| name_text(&n))
.map(|n| fold_family(&n))
.collect()
}
/// The faces of an East Asian family from Word's DFonts. A collection
/// (`.ttc`) holds several families (MS Mincho / MS PMincho); the face whose
/// own family name is the requested one wins, name ID 1 before the
/// typographic ID 16 (Yu Gothic Medium is ID 1 "Yu Gothic Medium"). A name
/// no face carries (FangSong_GB2312) takes the group's first face.
fn cjk_family_faces(family: &str, stems: &[&str]) -> Vec<((bool, bool), Vec<u8>)> {
let key = format!("east-asian\u{1f}{family}\u{1f}{}", stems.join(","));
indexed_faces(&FONT_INDEX, &key, || {
(scan_cjk_family_faces(family, stems), cjk_dirs())
})
}
/// The folders Word for Mac keeps its East Asian faces in.
const CJK_DIRS: &[&str] = &[
"/Applications/Microsoft Word.app/Contents/Resources/DFonts",
"/Library/Fonts/Microsoft",
"/Library/Fonts",
];
/// The folders Word's East Asian faces live in: Word for Mac's, then
/// Windows' own (msgothic.ttc, msyh.ttc and malgun.ttf ship there).
fn cjk_dirs() -> Vec<PathBuf> {
CJK_DIRS
.iter()
.map(PathBuf::from)
.chain(windows_font_dirs())
.collect()
}
/// Windows' font folders: the system's and the per-user one fonts
/// installed without administrator rights land in. Empty elsewhere.
fn windows_font_dirs() -> Vec<PathBuf> {
if cfg!(target_os = "windows") {
windows_font_dirs_from(|key| std::env::var_os(key))
} else {
Vec::new()
}
}
/// A Windows font folder, the system's (`C:\WINDOWS\Fonts`) or the
/// per-user one (`…\Microsoft\Windows\Fonts`): both end in
/// `Windows\Fonts`, in any case.
fn windows_fonts_dir(dir: &Path) -> bool {
let mut tail = dir
.components()
.rev()
.map(|c| c.as_os_str().to_string_lossy());
tail.next().is_some_and(|c| c.eq_ignore_ascii_case("fonts"))
&& tail
.next()
.is_some_and(|c| c.eq_ignore_ascii_case("windows"))
}
fn windows_font_dirs_from(env: impl Fn(&str) -> Option<std::ffi::OsString>) -> Vec<PathBuf> {
let set = |key: &str| env(key).filter(|v| !v.is_empty()).map(PathBuf::from);
let root = set("WINDIR")
.or_else(|| set("SystemRoot"))
.unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
let mut dirs = vec![root.join("Fonts")];
dirs.extend(set("LOCALAPPDATA").map(|d| d.join("Microsoft").join("Windows").join("Fonts")));
dirs
}
/// `cjk_family_faces` read from disk.
fn scan_cjk_family_faces(family: &str, stems: &[&str]) -> SourcedFaces {
scan_cjk_family_faces_with(
family,
stems,
&cjk_dirs(),
&|dir| {
fs::read_dir(dir)
.ok()
.map(|entries| entries.flatten().map(|entry| entry.path()).collect())
},
&|path| fs::read(path).ok(),
)
}
/// The discovery policy shared by disk and deterministic in-memory font sources.
fn scan_cjk_family_faces_with(
family: &str,
stems: &[&str],
dirs: &[PathBuf],
listing: &impl Fn(&Path) -> Option<Vec<PathBuf>>,
read: &impl Fn(&Path) -> Option<Vec<u8>>,
) -> SourcedFaces {
let want = fold_family(family);
let mut files: Vec<(usize, PathBuf)> = Vec::new();
for dir in dirs {
let Some(entries) = listing(dir) else {
continue;
};
for path in entries {
let ext_ok = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
["ttf", "otf", "ttc"]
.iter()
.any(|x| e.eq_ignore_ascii_case(x))
});
let stem = path.file_stem().and_then(|s| s.to_str()).map(fold_family);
if let (true, Some(stem)) = (ext_ok, stem)
&& let Some(rank) = stems.iter().position(|s| *s == stem)
&& files.iter().all(|(_, p)| p.file_name() != path.file_name())
{
files.push((rank, path));
}
}
}
files.sort();
// (pass, style, bytes): pass 0 = ID 1 match, 1 = ID 16, 2 = fallback.
let mut found: Vec<(u8, (bool, bool), SourcedBytes)> = Vec::new();
for (rank, path) in &files {
let Some(bytes) = read(path) else {
continue;
};
let count = ttf_parser::fonts_in_collection(&bytes).unwrap_or(1);
for index in 0..count {
let Ok(face) = ttf_parser::Face::parse(&bytes, index) else {
continue;
};
if face.tables().glyf.is_none() {
continue;
}
let pass = if face_family_names(&face, ttf_parser::name_id::FAMILY).contains(&want) {
0
} else if face_family_names(&face, ttf_parser::name_id::TYPOGRAPHIC_FAMILY)
.contains(&want)
{
1
} else if *rank == 0 && index == 0 {
2
} else {
continue;
};
let style = (face.is_bold(), face.is_italic());
let (data, at) = if count > 1 {
match ttc_face_bytes(&bytes, index) {
Some(data) => (data, Some(index)),
None => continue,
}
} else {
(bytes.clone(), None)
};
found.push((pass, style, (FaceSource::new(path, at), data)));
}
}
sourced(pick_ranked_faces(found))
}
/// One face of a TrueType collection as a standalone sfnt: the face's
/// table directory with its tables copied after it (PDF `FontFile2`
/// cannot hold a collection).
fn ttc_face_bytes(ttc: &[u8], index: u32) -> Option<Vec<u8>> {
let u32_at = |at: usize| -> Option<u32> {
ttc.get(at..at + 4)
.map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
};
if ttc.get(0..4)? != b"ttcf" {
return None;
}
let dir = usize::try_from(u32_at(12 + 4 * usize::try_from(index).ok()?)?).ok()?;
let num_tables = usize::from(u16::from_be_bytes([*ttc.get(dir + 4)?, *ttc.get(dir + 5)?]));
let header_len = 12 + 16 * num_tables;
let mut out = ttc.get(dir..dir + 12)?.to_vec();
let mut records = Vec::with_capacity(16 * num_tables);
let mut data: Vec<u8> = Vec::new();
for t in 0..num_tables {
let rec = dir + 12 + 16 * t;
let offset = usize::try_from(u32_at(rec + 8)?).ok()?;
let length = usize::try_from(u32_at(rec + 12)?).ok()?;
let new_offset = u32::try_from(header_len + data.len()).ok()?;
records.extend_from_slice(ttc.get(rec..rec + 8)?);
records.extend_from_slice(&new_offset.to_be_bytes());
records.extend_from_slice(ttc.get(rec + 12..rec + 16)?);
data.extend_from_slice(ttc.get(offset..offset + length)?);
while !data.len().is_multiple_of(4) {
data.push(0);
}
}
out.extend_from_slice(&records);
out.extend_from_slice(&data);
Some(out)
}
/// Embedded-map keys of the East Asian fallback faces (see
/// `Fonts::cjk_fallback_index`); no document family can be named this.
pub(crate) const CJK_FALLBACK: &str = "@cjk";
pub(crate) const CJK_FALLBACK_JA: &str = "@cjk-ja";
pub(crate) const CJK_FALLBACK_KO: &str = "@cjk-ko";
pub(crate) const CJK_FALLBACK_KO_SERIF: &str = "@cjk-ko-serif";
pub(crate) const CJK_FALLBACK_GOTHIC: &str = "@cjk-gothic";
pub(crate) const CJK_FALLBACK_MINCHO: &str = "@cjk-mincho";
/// Embedded-map key of the Thaana fallback face.
pub(crate) const THAANA_FALLBACK: &str = "@thaana";
/// Embedded-map key of the Thai fallback face.
pub(crate) const THAI_FALLBACK: &str = "@thai";
/// Embedded-map key of the Devanagari fallback face.
pub(crate) const DEVANAGARI_FALLBACK: &str = "@devanagari";
/// Loads the face Word paints a script in when the run's font has none:
/// the first of `families` installed (Word 16 probe scripts 1001: Calibri's
/// Thai is Leelawadee UI, its Devanagari Mangal).
pub(crate) fn add_script_fallback(embedded: &mut EmbeddedFonts, key: &str, families: &[&str]) {
let faces = cached_faces(key, || {
families
.iter()
.map(|family| installed_family_faces(family))
.find(|faces| !faces.is_empty())
.unwrap_or_default()
});
for ((bold, italic), bytes) in faces {
embedded.insert((key.to_string(), bold, italic), bytes);
}
}
/// Loads the face Word paints Dhivehi in when the document's font is
/// missing: MV Boli from Office's cloud fonts (fixtures_500 0003fc93's
/// Faruma), else the system's Noto Sans Thaana.
pub(crate) fn add_thaana_fallback(embedded: &mut EmbeddedFonts) {
let faces = cached_faces(THAANA_FALLBACK, || {
let faces = installed_family_faces("MV Boli");
if faces.is_empty() {
installed_family_faces("Noto Sans Thaana")
} else {
faces
}
});
for ((bold, italic), bytes) in faces {
embedded.insert((THAANA_FALLBACK.to_string(), bold, italic), bytes);
}
}
fn is_cjk_name_char(c: char) -> bool {
matches!(c as u32, 0x2E80..=0x9FFF | 0xAC00..=0xD7AF | 0xF900..=0xFAFF | 0xFF66..=0xFF9F)
}
type SharedFaces = Vec<((bool, bool), Arc<[u8]>)>;
/// Face bytes the process cache will hold. A larger face is not stored.
/// Past this, the greatest key is dropped until the next face fits.
const MAX_FACE_CACHE_BYTES: usize = 64 * 1024 * 1024;
/// Glyph payloads kept on one face. The entry-count clear still applies.
/// A larger shaped entry is not stored.
const MAX_SHAPED_CACHE_BYTES: usize = 4 * 1024 * 1024;
fn shared_payload(faces: &SharedFaces) -> usize {
faces
.iter()
.fold(0usize, |sum, (_, bytes)| sum.saturating_add(bytes.len()))
}
fn shaped_payload_bytes(units: &ShapedUnits) -> usize {
units
.len()
.saturating_mul(std::mem::size_of::<(u16, i32, u32)>())
}
fn face_cache() -> &'static Mutex<BoundedCache<String, SharedFaces>> {
static CACHE: Mutex<BoundedCache<String, SharedFaces>> =
Mutex::new(BoundedCache::new(MAX_FACE_CACHE_BYTES, shared_payload));
&CACHE
}
/// A map whose values' bytes stay inside `max`. It keeps the running
/// total, so a store costs a lookup and not a walk over every entry. Past
/// the budget the greatest key goes first, so what stays does not depend
/// on hash order.
struct BoundedCache<K, V> {
map: BTreeMap<K, V>,
bytes: usize,
max: usize,
size: fn(&V) -> usize,
}
impl<K: Ord, V> BoundedCache<K, V> {
const fn new(max: usize, size: fn(&V) -> usize) -> Self {
Self {
map: BTreeMap::new(),
bytes: 0,
max,
size,
}
}
fn get<Q>(&self, key: &Q) -> Option<&V>
where
K: std::borrow::Borrow<Q>,
Q: Ord + ?Sized,
{
self.map.get(key)
}
fn len(&self) -> usize {
self.map.len()
}
fn clear(&mut self) {
self.map.clear();
self.bytes = 0;
}
/// Store `value` under `key`, replacing what the key held. The
/// greatest keys go until it fits. A value larger than the whole
/// budget is not stored, and the key is then absent.
fn insert(&mut self, key: K, value: V) {
if let Some(old) = self.map.remove(&key) {
self.bytes = self.bytes.saturating_sub((self.size)(&old));
}
let add = (self.size)(&value);
if add > self.max {
return;
}
while self.bytes.saturating_add(add) > self.max {
let Some((_, gone)) = self.map.pop_last() else {
break;
};
self.bytes = self.bytes.saturating_sub((self.size)(&gone));
}
self.bytes = self.bytes.saturating_add(add);
self.map.insert(key, value);
}
}
/// Installed-face lookups, cached for the process: a long-lived caller
/// (the Python and WASM bindings) would otherwise re-read 10-20 MB font
/// collections for every conversion. The cache holds at most
/// [`MAX_FACE_CACHE_BYTES`] of those bytes. A face that would pass the
/// budget drops the greatest key until it fits. A face larger than the
/// budget is returned and not stored. A caller that does not use this
/// cache is not limited by it.
fn cached_faces(key: &str, load: impl FnOnce() -> Vec<((bool, bool), Vec<u8>)>) -> SharedFaces {
if let Ok(cache) = face_cache().lock()
&& let Some(faces) = cache.get(key)
{
return faces.clone();
}
let faces: SharedFaces = load()
.into_iter()
.map(|(style, bytes)| (style, Arc::from(bytes)))
.collect();
let add = shared_payload(&faces);
if add > MAX_FACE_CACHE_BYTES {
return faces;
}
if let Ok(mut cache) = face_cache().lock() {
cache.insert(key.to_string(), faces.clone());
}
faces
}
/// Where an installed face came from: its file and, inside a collection,
/// its index.
#[derive(Clone, Debug, PartialEq)]
struct FaceSource {
path: PathBuf,
index: Option<u32>,
}
impl FaceSource {
fn new(path: &Path, index: Option<u32>) -> Self {
Self {
path: path.to_path_buf(),
index,
}
}
}
/// A face's bytes with the file they came from.
type SourcedBytes = (FaceSource, Vec<u8>);
/// Picked faces with their files.
type SourcedFaces = Vec<((bool, bool), FaceSource, Vec<u8>)>;
fn sourced(picked: Vec<((bool, bool), SourcedBytes)>) -> SourcedFaces {
picked
.into_iter()
.map(|(style, (source, bytes))| (style, source, bytes))
.collect()
}
/// The on-disk font index: every family a conversion looked up, with the
/// files its faces came from. A later process reads those files directly
/// instead of listing and opening every candidate in the system, Word and
/// cloud-font folders; the full search runs only for a family the index
/// does not hold or whose folders or files changed since.
static FONT_INDEX: LazyLock<Mutex<FontIndex>> =
LazyLock::new(|| Mutex::new(FontIndex::load(font_index_path())));
/// `$JUBARTE_FONT_INDEX` (empty or `off` disables it), else
/// `font-index.tsv` beside jubarte's font folder.
fn font_index_path() -> Option<PathBuf> {
match std::env::var_os("JUBARTE_FONT_INDEX") {
Some(path) if path.is_empty() || path == "off" => None,
Some(path) => Some(PathBuf::from(path)),
None => user_font_dir()?
.parent()
.map(|dir| dir.join("font-index.tsv")),
}
}
/// Bump when the family search's matching rules change, or when a recorded
/// answer would stay wrong for the same folder mtime. Generation 3 drops
/// misses recorded while a folder could not be listed (#2051): permission
/// does not change the directory's mtime. The crate version drops the
/// answers another release recorded.
const FONT_INDEX_HEADER: &str = concat!("jubarte-font-index\t3\t", env!("CARGO_PKG_VERSION"));
/// Families one persistent font index keeps. A miss past this bound is not
/// recorded: recording it would rewrite the whole index once per name.
const MAX_FONT_INDEX_ENTRIES: usize = 256;
/// A modification time in nanoseconds, `None` for a missing path.
fn mtime_of(path: &Path) -> Option<u128> {
let modified = fs::metadata(path).ok()?.modified().ok()?;
Some(
modified
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_nanos(),
)
}
/// A file's (length, modification time).
fn file_stamp(path: &Path) -> Option<(u64, u128)> {
let meta = fs::metadata(path).ok()?;
let modified = meta.modified().ok()?;
let nanos = modified
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_nanos();
Some((meta.len(), nanos))
}
/// Faces by (bold, italic), read from their files.
type LoadedFaces = Vec<((bool, bool), Vec<u8>)>;
#[derive(Clone, Debug, PartialEq)]
struct IndexedFace {
style: (bool, bool),
source: FaceSource,
stamp: Option<(u64, u128)>,
}
/// One looked-up family: the folders its search listed, stamped, and the
/// faces it found (none is an answer too).
#[derive(Clone, Debug, PartialEq)]
struct IndexEntry {
dirs: Vec<(PathBuf, Option<u128>)>,
faces: Vec<IndexedFace>,
}
impl IndexEntry {
/// The faces, when no listed folder and no face file changed.
fn load(&self) -> Option<LoadedFaces> {
if self.dirs.iter().any(|(dir, mtime)| mtime_of(dir) != *mtime) {
return None;
}
let mut out = Vec::with_capacity(self.faces.len());
for face in &self.faces {
if face.stamp.is_none() || file_stamp(&face.source.path) != face.stamp {
return None;
}
let bytes = fs::read(&face.source.path).ok()?;
let bytes = match face.source.index {
Some(index) => ttc_face_bytes(&bytes, index)?,
None => bytes,
};
out.push((face.style, bytes));
}
Some(out)
}
}
#[derive(Debug, Default)]
struct FontIndex {
path: Option<PathBuf>,
entries: HashMap<String, IndexEntry>,
}
impl FontIndex {
fn load(path: Option<PathBuf>) -> Self {
let mut entries = path
.as_deref()
.and_then(|p| fs::read_to_string(p).ok())
.map(|text| parse_font_index(&text))
.unwrap_or_default();
if entries.len() > MAX_FONT_INDEX_ENTRIES {
entries = entries.into_iter().take(MAX_FONT_INDEX_ENTRIES).collect();
}
Self { path, entries }
}
fn record(&mut self, key: &str, dirs: &[PathBuf], faces: &SourcedFaces) {
if !self.entries.contains_key(key) && self.entries.len() >= MAX_FONT_INDEX_ENTRIES {
return;
}
let entry = IndexEntry {
dirs: dirs
.iter()
.map(|dir| (dir.clone(), mtime_of(dir)))
.collect(),
faces: faces
.iter()
.map(|(style, source, _)| IndexedFace {
style: *style,
source: source.clone(),
stamp: file_stamp(&source.path),
})
.collect(),
};
self.entries.insert(key.to_string(), entry);
self.persist(key);
}
/// Appends one family while the file is this release's index and holds
/// fewer than [`MAX_FONT_INDEX_ENTRIES`] families. Otherwise (missing,
/// stale, full, or a line another writer tore) the file is rewritten
/// once, merged and capped, so it stays bounded however many processes
/// append to it.
fn persist(&self, key: &str) {
let Some(path) = self.path.as_deref() else {
return;
};
if index_file_takes_appends(path) {
self.append_key(path, key);
} else {
self.save();
}
}
fn append_key(&self, path: &Path, key: &str) {
let Some(entry) = self.entries.get(key) else {
return;
};
let formatted = format_font_index(&HashMap::from([(key.to_string(), entry.clone())]));
let Some(line) = formatted.lines().nth(1).filter(|line| !line.is_empty()) else {
return;
};
let Ok(mut file) = fs::OpenOptions::new().append(true).open(path) else {
return;
};
// One write: another process's append cannot land between a line
// and its newline.
let _ = std::io::Write::write_all(&mut file, format!("{line}\n").as_bytes());
}
/// Writes the index, merged over what other processes wrote since it
/// was read, through a rename so a reader never sees half a file.
fn save(&self) {
let Some(path) = self.path.as_deref() else {
return;
};
let mut merged = fs::read_to_string(path)
.map(|text| parse_font_index(&text))
.unwrap_or_default();
merged.extend(self.entries.iter().map(|(k, v)| (k.clone(), v.clone())));
if merged.len() > MAX_FONT_INDEX_ENTRIES {
let mut kept = HashMap::with_capacity(MAX_FONT_INDEX_ENTRIES);
for (k, v) in &self.entries {
if kept.len() == MAX_FONT_INDEX_ENTRIES {
break;
}
kept.insert(k.clone(), v.clone());
}
for (k, v) in &merged {
if kept.len() == MAX_FONT_INDEX_ENTRIES {
break;
}
kept.entry(k.clone()).or_insert(v.clone());
}
merged = kept;
}
let text = format_font_index(&merged);
let tmp = path.with_extension(format!("tsv.{}.tmp", std::process::id()));
let written = path
.parent()
.is_some_and(|dir| fs::create_dir_all(dir).is_ok())
&& fs::write(&tmp, text).is_ok()
&& fs::rename(&tmp, path).is_ok();
if !written {
let _ = fs::remove_file(&tmp);
}
}
}
/// The on-disk index starts with this release's header and holds fewer
/// than [`MAX_FONT_INDEX_ENTRIES`] family lines, all readable, so one family
/// can be appended without rewriting the families already stored.
fn index_file_takes_appends(path: &Path) -> bool {
let Ok(file) = fs::File::open(path) else {
return false;
};
let mut lines = std::io::BufRead::lines(std::io::BufReader::new(file));
if !matches!(lines.next(), Some(Ok(header)) if header == FONT_INDEX_HEADER) {
return false;
}
let mut families = 0;
for line in lines {
match line {
Ok(line) if line.is_empty() => {}
// A torn or foreign line: rewrite the file rather than append
// after it, so `save` drops it.
Ok(line) if parse_index_line(&line).is_none() => return false,
Ok(_) => {
families += 1;
if families >= MAX_FONT_INDEX_ENTRIES {
return false;
}
}
Err(_) => return false,
}
}
true
}
/// `read_dir` failed because the process may not list `dir` (EACCES/EPERM).
fn dir_listing_denied(dir: &Path) -> bool {
matches!(
fs::read_dir(dir),
Err(err) if err.kind() == std::io::ErrorKind::PermissionDenied
)
}
/// `key`'s faces from the index when still current, else from `scan`
/// (faces and the folders it listed), which the index then records.
fn indexed_faces(
index: &Mutex<FontIndex>,
key: &str,
scan: impl FnOnce() -> (SourcedFaces, Vec<PathBuf>),
) -> Vec<((bool, bool), Vec<u8>)> {
indexed_faces_with(index, key, scan, dir_listing_denied)
}
/// [`indexed_faces`] with the denial check passed in, so the rule that a
/// denied listing is never recorded is testable where the process can list
/// any folder (root).
fn indexed_faces_with(
index: &Mutex<FontIndex>,
key: &str,
scan: impl FnOnce() -> (SourcedFaces, Vec<PathBuf>),
denied: impl Fn(&Path) -> bool,
) -> Vec<((bool, bool), Vec<u8>)> {
let entry = index.lock().ok().and_then(|i| i.entries.get(key).cloned());
if let Some(faces) = entry.and_then(|e| e.load()) {
return faces;
}
let (faces, dirs) = scan();
// A denial is not an answer. The directory mtime does not change when
// the folder becomes readable, so recording the miss would serve it
// from then on (#2051).
if !dirs.iter().any(|dir| denied(dir))
&& let Ok(mut index) = index.lock()
{
index.record(key, &dirs, &faces);
}
faces
.into_iter()
.map(|(style, _, bytes)| (style, bytes))
.collect()
}
// The index file: a header line, then one family per line, tab-separated
// key, folders and faces; list items split by U+001E, fields by U+001F.
const ITEM_SEP: char = '\u{1e}';
const FIELD_SEP: char = '\u{1f}';
fn opt_text<T: ToString>(v: Option<T>) -> String {
v.map_or_else(|| "-".to_string(), |v| v.to_string())
}
fn format_font_index(entries: &HashMap<String, IndexEntry>) -> String {
let clean = |s: &str| !s.contains(['\t', '\n', '\r', ITEM_SEP]);
let mut lines: Vec<String> = Vec::with_capacity(entries.len());
for (key, entry) in entries {
let mut paths = entry
.dirs
.iter()
.map(|(d, _)| d)
.chain(entry.faces.iter().map(|f| &f.source.path))
.map(|p| p.to_str());
if !clean(key) || !paths.all(|p| p.is_some_and(|p| clean(p) && !p.contains(FIELD_SEP))) {
continue;
}
let dirs: Vec<String> = entry
.dirs
.iter()
.map(|(d, m)| format!("{}{FIELD_SEP}{}", d.display(), opt_text(*m)))
.collect();
let faces: Vec<String> = entry
.faces
.iter()
.map(|f| {
let (len, mtime) = f.stamp.unzip();
[
f.source.path.display().to_string(),
opt_text(f.source.index),
u8::from(f.style.0).to_string(),
u8::from(f.style.1).to_string(),
opt_text(len),
opt_text(mtime),
]
.join(&FIELD_SEP.to_string())
})
.collect();
lines.push(format!(
"{key}\t{}\t{}",
dirs.join(&ITEM_SEP.to_string()),
faces.join(&ITEM_SEP.to_string())
));
}
lines.sort();
let mut text = String::from(FONT_INDEX_HEADER);
for line in lines {
text.push('\n');
text.push_str(&line);
}
text.push('\n');
text
}
fn parse_font_index(text: &str) -> HashMap<String, IndexEntry> {
let mut lines = text.lines();
if lines.next() != Some(FONT_INDEX_HEADER) {
return HashMap::new();
}
lines.filter_map(parse_index_line).collect()
}
/// One family line of the index (`key`, folders, faces), or `None` for a
/// line another writer tore or an older release wrote.
fn parse_index_line(line: &str) -> Option<(String, IndexEntry)> {
let opt = |s: &str| (s != "-").then(|| s.parse().ok()).flatten();
let items = |s: &'_ str| -> Vec<Vec<String>> {
s.split(ITEM_SEP)
.filter(|i| !i.is_empty())
.map(|i| i.split(FIELD_SEP).map(str::to_string).collect())
.collect()
};
let mut cols = line.split('\t');
let (Some(key), Some(dirs), Some(faces), None) =
(cols.next(), cols.next(), cols.next(), cols.next())
else {
return None;
};
let dirs: Option<Vec<(PathBuf, Option<u128>)>> = items(dirs)
.into_iter()
.map(|f| match f.as_slice() {
[d, m] => Some((PathBuf::from(d), opt(m))),
_ => None,
})
.collect();
let faces: Option<Vec<IndexedFace>> = items(faces)
.into_iter()
.map(|f| match f.as_slice() {
[path, index, bold, italic, len, mtime] => Some(IndexedFace {
style: (bold == "1", italic == "1"),
source: FaceSource {
path: PathBuf::from(path),
index: opt(index).and_then(|i: u128| u32::try_from(i).ok()),
},
stamp: opt(len)
.and_then(|l: u128| u64::try_from(l).ok())
.zip(opt(mtime)),
}),
_ => None,
})
.collect();
Some((
key.to_string(),
IndexEntry {
dirs: dirs?,
faces: faces?,
},
))
}
/// Loads Word's East Asian fallback faces (YaHei, Yu Gothic, Malgun
/// Gothic, Batang, MS Gothic, MS Mincho) for a document that has East
/// Asian text.
pub(crate) fn add_cjk_fallbacks(embedded: &mut EmbeddedFonts) {
for (key, family, stems) in [
(CJK_FALLBACK, "Microsoft YaHei", &["msyh", "msyhbd"][..]),
(CJK_FALLBACK_JA, "Yu Gothic", &["yugothr", "yugothb"][..]),
(
CJK_FALLBACK_KO,
"Malgun Gothic",
&["malgun", "malgunbd"][..],
),
(CJK_FALLBACK_KO_SERIF, "Batang", &["batang"][..]),
(CJK_FALLBACK_GOTHIC, "MS Gothic", &["msgothic"][..]),
(CJK_FALLBACK_MINCHO, "MS Mincho", &["msmincho"][..]),
] {
for ((bold, italic), bytes) in cached_faces(key, || cjk_family_faces(family, stems)) {
embedded.insert((key.to_string(), bold, italic), bytes);
}
}
}
/// Adds the installed faces of every font-table family that the catalogue
/// does not cover and the document does not embed.
///
/// `extra` are the families styles and the theme name; `run_faces` those
/// runs paint non-East-Asian text in (ascii / hAnsi / cs, theme latin).
/// A theme lists ~45 script fonts (Mangal, Sylfaen, 游明朝…): loading each
/// from disk was a third of every conversion, so an East Asian family
/// loads only for East Asian text or a run that paints in it, and any
/// other family only when a run paints in it.
pub(crate) fn add_installed_faces(
embedded: &mut EmbeddedFonts,
table: &super::font_table::FontTable,
extra: &[String],
run_faces: &[String],
has_cjk: bool,
) {
// East Asian families named only in styles or the theme ("宋体" as the
// theme's Hans font) are not in the font table but Word draws them.
for name in extra {
let lower = name.to_ascii_lowercase();
let painted = run_faces.iter().any(|n| n == name);
let wanted = if cjk_file_stems(name).is_empty() {
painted && !catalogue_paints_family(name)
} else {
has_cjk || painted
};
if !wanted || table.get(name).is_some() || embedded.keys().any(|(f, _, _)| *f == lower) {
continue;
}
// A family runs name but the table omits (015beda9 has no table
// part; Word still draws its Segoe UI) loads like a table family.
let mut faces = cached_faces(name, || installed_family_faces(name));
if faces.is_empty()
&& let Some(sub) = super::word_subst::word_name_substitute(name)
{
faces = cached_faces(sub, || installed_family_faces(sub));
}
for ((bold, italic), bytes) in faces {
embedded.insert((lower.clone(), bold, italic), bytes);
}
}
for entry in table.iter() {
let lower = entry.name.to_ascii_lowercase();
if catalogue_paints_family(&entry.name) || embedded.keys().any(|(f, _, _)| *f == lower) {
continue;
}
let mut faces = cached_faces(&entry.name, || installed_family_faces(&entry.name));
// Word's own stand-in for a family it knows beats the altName:
// "Myriad Pro" with altName Arial is Segoe UI.
if faces.is_empty()
&& let Some(sub) = super::word_subst::word_name_substitute(&entry.name)
{
faces = cached_faces(sub, || installed_family_faces(sub));
}
// An absent family draws in its installed altName (b88ac900's
// "BernhardFashion BT" → Gabriola in Word's PDF).
if faces.is_empty()
&& let Some(alt) = entry.alt_name.as_deref()
&& cjk_file_stems(&entry.name).is_empty()
&& !catalogue_paints_family(alt)
{
faces = cached_faces(alt, || installed_family_faces(alt));
}
// Then the script its sig claims (Faruma's Thaana → MV Boli),
// unless the altName is a catalogue face Word draws instead.
if faces.is_empty()
&& cjk_file_stems(&entry.name).is_empty()
&& !entry
.alt_name
.as_deref()
.is_some_and(catalogue_paints_family)
&& let Some(face) = super::word_subst::script_face(entry)
{
faces = cached_faces(face, || installed_family_faces(face));
}
// Runs may name the family by its altName ("MS Mincho" for the
// table's "MS 明朝"); the same faces answer to both.
if let Some(alt) = entry.alt_name.as_deref()
&& !cjk_file_stems(&entry.name).is_empty()
{
let alt = alt.to_ascii_lowercase();
if embedded.keys().all(|(f, _, _)| *f != alt) {
for ((bold, italic), bytes) in &faces {
embedded.insert((alt.clone(), *bold, *italic), Arc::clone(bytes));
}
}
}
for ((bold, italic), bytes) in faces {
embedded.insert((lower.clone(), bold, italic), bytes);
}
}
}
/// The catalogue slot for `family` really is that family, not a stand-in
/// (Tahoma, Trebuchet and Roboto all fold into the Arial slot).
pub(crate) fn catalogue_paints_family(family: &str) -> bool {
let norm = |s: &str| -> String {
s.chars()
.filter(|c| c.is_ascii_alphanumeric())
.map(|c| c.to_ascii_lowercase())
.collect()
};
let key = FaceKey {
family: family.to_ascii_lowercase(),
bold: false,
italic: false,
};
let face = catalogue().get(Fonts::id_from_key(&key));
// A name with no ASCII letters ("MS 明朝") folds to "", which every
// catalogue name starts with; no catalogue slot is that family.
let want = norm(family);
!want.is_empty() && norm(face.pdf_name()).starts_with(&want)
}
/// (bold, italic) when the font's own family name is `family`.
/// One face per (bold, italic): the best-ranked candidate (lower pass),
/// path order breaking ties. A typographic-family (ID 16) match never
/// takes a style an ID 1 match fills (Roboto Black vs Roboto Regular).
fn pick_ranked_faces<T>(mut found: Vec<(u8, (bool, bool), T)>) -> Vec<((bool, bool), T)> {
found.sort_by_key(|(pass, _, _)| *pass);
let mut out: Vec<((bool, bool), T)> = Vec::new();
for (_, style, bytes) in found {
if out.iter().all(|(s, _)| *s != style) {
out.push((style, bytes));
}
}
out
}
/// (pass, (bold, italic)) when the font's own family name is `family`:
/// pass 0 for name ID 1, 4 for the typographic ID 16 only, plus 2 for a
/// face that is not normal width and 1 for one off its style's weight. A face without
/// TrueType outlines is skipped: PDF FontFile2 cannot carry CFF.
/// OS/2 `ulCodePageRange1` names a Japanese, Chinese or Korean code page
/// (bits 17-21).
/// A copy from Word's Office 365 font service: its name-table version
/// says so ("Version 1.03;O365"). macOS's own SinoType faces and Word's
/// bundled DFonts (but MingLiU-ExtB) carry none.
fn office_365_face(face: &ttf_parser::Face) -> bool {
face.names()
.into_iter()
.filter(|n| n.name_id == ttf_parser::name_id::VERSION)
.filter_map(|n| n.to_string())
.any(|v| v.contains(";O365"))
}
fn cjk_code_pages(face: &ttf_parser::Face) -> bool {
face.raw_face()
.table(ttf_parser::Tag::from_bytes(b"OS/2"))
.and_then(|os2| os2.get(78..82))
.map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
.is_some_and(|range| range & (0b1_1111 << 17) != 0)
}
/// OS/2 xAvgCharWidth in font units, when positive.
/// PANOSE family type 2 (Latin text) with a serif style of 2 (cove)
/// through 10 (triangle); 11-13 are the sans styles.
fn panose_serif(face: &ttf_parser::Face) -> bool {
face.raw_face()
.table(ttf_parser::Tag::from_bytes(b"OS/2"))
.and_then(|os2| os2.get(32..34))
.is_some_and(|p| p[0] == 2 && (2..=10).contains(&p[1]))
}
fn avg_char_width(face: &ttf_parser::Face) -> Option<f32> {
face.raw_face()
.table(ttf_parser::Tag::from_bytes(b"OS/2"))
.and_then(|os2| os2.get(2..4))
.map(|b| f32::from(i16::from_be_bytes([b[0], b[1]])))
.filter(|&w| w > 0.0)
}
/// A name record's text: Unicode records as ttf-parser decodes them, and
/// Macintosh Roman ones when plain ASCII. Apple's Futura.ttc names its
/// family only in a Mac Roman record, which `to_string` leaves undecoded.
fn name_text(n: &ttf_parser::name::Name) -> Option<String> {
n.to_string().or_else(|| {
(n.platform_id == ttf_parser::PlatformId::Macintosh
&& n.encoding_id == 0
&& n.name.is_ascii())
.then(|| n.name.iter().map(|&b| char::from(b)).collect())
})
}
fn face_family_style(bytes: &[u8], family: &str) -> Option<(u8, (bool, bool))> {
let face = ttf_parser::Face::parse(bytes, 0).ok()?;
face.tables().glyf?;
let has = |id: u16| {
face.names().into_iter().any(|n| {
n.name_id == id && name_text(&n).is_some_and(|f| f.eq_ignore_ascii_case(family))
})
};
let named = if has(ttf_parser::name_id::FAMILY) {
0
} else if has(ttf_parser::name_id::TYPOGRAPHIC_FAMILY) {
4
} else {
return None;
};
// A normal-width face ranks before a condensed or expanded one of the
// same style (Papyrus.ttc holds Condensed ahead of Regular; Word draws
// the Regular, English corpus 469e5710), and a face at its style's
// weight before a SemiBold or Light one (20c18b4b's Open Sans).
let target = if face.is_bold() { 700 } else { 400 };
let pass = named
+ 2 * u8::from(face.width() != ttf_parser::Width::Normal)
+ u8::from(face.weight().to_number().abs_diff(target) > 50);
// A slant alone is not italic: MV Boli leans -16 degrees but is the
// Regular face. Apple's Avenir Next Bold Italic sets no italic bit,
// so a slanted face whose subfamily says so still counts.
let slanted_name = face.names().into_iter().any(|n| {
matches!(n.name_id, 2 | 17)
&& name_text(&n).is_some_and(|f| {
let f = f.to_ascii_lowercase();
f.contains("italic") || f.contains("oblique")
})
});
let italic = face.style() != ttf_parser::Style::Normal
|| (face.italic_angle() != 0.0 && (slanted_name || face.tables().os2.is_none()));
Some((pass, (face.is_bold(), italic)))
}
fn cloud_font_override(id: FaceId) -> Option<PathBuf> {
// Scanned once per process: `Fonts::new` probes every FaceId, and each
// probe would otherwise re-read the directory and re-parse every font
// file in it just to recover PostScript names.
static CLOUD_FONTS: LazyLock<Vec<(String, PathBuf)>> = LazyLock::new(|| {
let mut found = Vec::new();
let Some(home) = std::env::var_os("HOME") else {
return found;
};
let dir = PathBuf::from(home).join(
"Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts/Aptos Display",
);
let Ok(entries) = fs::read_dir(&dir) else {
return found;
};
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some("ttf") {
continue;
}
let Ok(bytes) = fs::read(&path) else {
continue;
};
if let Some(ps) = ttf_postscript_name(&bytes) {
found.push((ps, path));
}
}
found
});
let want = id.postscript();
CLOUD_FONTS
.iter()
.find(|(ps, _)| ps == want)
.map(|(_, path)| path.clone())
}
fn ttf_postscript_name(bytes: &[u8]) -> Option<String> {
let face = ttf_parser::Face::parse(bytes, 0).ok()?;
let name = face.tables().name?;
let records: Vec<_> = name
.names
.into_iter()
.filter(|n| n.name_id == ttf_parser::name_id::POST_SCRIPT_NAME)
.collect();
records
.iter()
.find_map(|n| if n.is_unicode() { n.to_string() } else { None })
.or_else(|| records.iter().find_map(|n| ascii_record_name(n.name)))
}
/// Name ID 6 is printable ASCII by definition (OpenType `name`), so a
/// Macintosh-Roman or other 8-bit record decodes byte for byte.
fn ascii_record_name(raw: &[u8]) -> Option<String> {
(!raw.is_empty() && raw.iter().all(|b| (0x21..=0x7e).contains(b)))
.then(|| String::from_utf8_lossy(raw).into_owned())
}
fn sanitize_pdf_name(name: &str) -> String {
name.chars()
.map(|ch| {
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '+' {
ch
} else {
'-'
}
})
.collect()
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::*;
#[test]
fn an_accented_latin_name_is_not_an_east_asian_face() {
// PR #304 review: a non-ASCII Latin family is no East Asian face,
// while a CJK name stays one even when absent (ee79137dd5's 標楷體).
let fonts = Fonts::new();
assert!(!fonts.family_is_east_asian("Café Prb Absent"));
assert!(fonts.family_is_east_asian("標楷體"));
assert!(fonts.family_is_east_asian("MS 明朝"));
assert!(!fonts.family_is_east_asian("Prb Absent"));
}
#[test]
fn windows_fonts_are_searched_in_the_system_and_user_folders() {
let env = |pairs: &'static [(&'static str, &'static str)]| {
move |key: &str| {
pairs
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| std::ffi::OsString::from(v))
}
};
let user = |root: &str| {
PathBuf::from(root)
.join("Microsoft")
.join("Windows")
.join("Fonts")
};
assert_eq!(
windows_font_dirs_from(env(&[
("WINDIR", r"D:\Win"),
("LOCALAPPDATA", r"C:\Users\a\AppData\Local")
])),
vec![
PathBuf::from(r"D:\Win").join("Fonts"),
user(r"C:\Users\a\AppData\Local")
]
);
// SystemRoot stands in for WINDIR; an empty value counts as unset.
assert_eq!(
windows_font_dirs_from(env(&[("WINDIR", ""), ("SystemRoot", r"E:\W")])),
vec![PathBuf::from(r"E:\W").join("Fonts")]
);
assert_eq!(
windows_font_dirs_from(env(&[])),
vec![PathBuf::from(r"C:\Windows").join("Fonts")]
);
// The East Asian search reads them after Word for Mac's folders.
let dirs = cjk_dirs();
assert_eq!(
&dirs[..CJK_DIRS.len()],
CJK_DIRS.iter().map(PathBuf::from).collect::<Vec<_>>()
);
assert_eq!(dirs.len() > CJK_DIRS.len(), cfg!(target_os = "windows"));
}
#[test]
fn an_ideograph_a_face_lacks_still_measures_one_em() {
// Without Word's East Asian faces (Linux, Windows CI, WASM) CJK
// text shapes to the Latin face's .notdef, ~0.6 em: a cell that
// wraps "J漢字漢字漢字" + "Q漢字漢字漢字" in Word fitted both on
// one line. Every face Word falls back to draws them one em wide;
// half-width katakana stay narrow.
let mut face = Face::load(FaceId::SansRegular);
let em = 11.0 + word_device_track(11.0);
for text in ["漢字", "かな", ",。", "한글", "AB"] {
assert!(
face.shape(text, 11.0).iter().all(|(gid, _)| *gid == 0),
"{text}"
);
let w = face.width_pt(text, 11.0);
assert!((w - 2.0 * em).abs() < 0.01, "{text}: {w}");
}
assert!(face.width_pt("カナ", 11.0) < 2.0 * em - 1.0);
face.buzz = None;
assert!((face.width_pt("漢字", 11.0) - 2.0 * em).abs() < 0.01);
}
#[test]
fn a_non_breaking_hyphen_reads_as_a_hyphen_with_or_without_shaping() {
// Word's PDFs carry 0x2D for w:noBreakHyphen; the /ToUnicode text
// says so too, whether or not the face shapes through rustybuzz.
let mut face = Face::load(FaceId::CarlitoRegular);
let text = format!("a{NO_BREAK_HYPHEN}b");
assert_eq!(face.glyph_texts(&text, false).concat(), "a-b");
face.buzz = None;
assert_eq!(face.glyph_texts(&text, false), ["a", "-", "b"]);
assert_eq!(face.glyph(NO_BREAK_HYPHEN), face.glyph('-'));
}
#[test]
fn the_font_index_reads_recorded_files_until_a_folder_or_file_changes() {
let tmp = tempfile::tempdir().expect("tempdir");
let fonts = tmp.path().join("fonts");
fs::create_dir(&fonts).expect("fonts dir");
let carlito = fonts.join("Carlito-Regular.ttf");
fs::write(
&carlito,
include_bytes!("../../assets/fonts/Carlito-Regular.ttf"),
)
.expect("font");
let index_path = tmp.path().join("font-index.tsv");
let scans = std::cell::Cell::new(0);
let scan = || {
scans.set(scans.get() + 1);
let bytes = fs::read(&carlito).expect("read");
(
vec![((false, false), FaceSource::new(&carlito, None), bytes)],
vec![fonts.clone()],
)
};
let first = indexed_faces(
&Mutex::new(FontIndex::load(Some(index_path.clone()))),
"k",
scan,
);
assert_eq!(scans.get(), 1);
// A new process: the file index answers without a scan.
let index = Mutex::new(FontIndex::load(Some(index_path.clone())));
assert_eq!(indexed_faces(&index, "k", scan), first);
assert_eq!(scans.get(), 1, "an indexed family is not searched again");
// A family nobody has: the empty answer is indexed too.
let none = || {
scans.set(scans.get() + 1);
(Vec::new(), vec![fonts.clone()])
};
assert!(indexed_faces(&index, "absent", none).is_empty());
let index = Mutex::new(FontIndex::load(Some(index_path.clone())));
assert!(indexed_faces(&index, "absent", none).is_empty());
assert_eq!(scans.get(), 2);
// A face file rewritten in place, then a font added to the folder:
// each sends the family back to the search.
fs::write(
&carlito,
include_bytes!("../../assets/fonts/Carlito-Bold.ttf"),
)
.expect("font");
let index = Mutex::new(FontIndex::load(Some(index_path.clone())));
indexed_faces(&index, "k", scan);
assert_eq!(scans.get(), 3);
fs::write(fonts.join("New.ttf"), b"x").expect("new font");
let index = Mutex::new(FontIndex::load(Some(index_path)));
indexed_faces(&index, "absent", none);
assert_eq!(scans.get(), 4);
}
/// A persistent index used to rewrite every family on each miss. Misses
/// append, and the index keeps at most 256 families.
#[cfg(unix)]
#[test]
fn many_font_index_misses_do_not_rewrite_the_growing_index() {
use std::os::unix::fs::MetadataExt;
const BOUND: usize = 256;
let tmp = tempfile::tempdir().expect("tempdir");
let index_path = tmp.path().join("font-index.tsv");
let index = Mutex::new(FontIndex::load(Some(index_path.clone())));
let miss = || (Vec::new(), Vec::new());
indexed_faces(&index, "family-0", miss);
let inode = fs::metadata(&index_path).expect("index").ino();
for i in 1..8 {
indexed_faces(&index, &format!("family-{i}"), miss);
}
assert_eq!(
fs::metadata(&index_path).expect("index").ino(),
inode,
"each miss rewrote the whole font index"
);
for i in 8..=BOUND {
indexed_faces(&index, &format!("family-{i}"), miss);
}
let text = fs::read_to_string(&index_path).expect("read index");
let families = text.lines().skip(1).filter(|line| !line.is_empty()).count();
assert!(families <= BOUND, "index kept {families} families");
}
/// Two processes that read one index each append their own misses. The
/// file on disk still keeps at most 256 families: past that a miss
/// rewrites it, merged and capped, instead of appending.
#[test]
fn two_indexes_appending_to_one_file_keep_it_bounded() {
const BOUND: usize = 256;
let tmp = tempfile::tempdir().expect("tempdir");
let index_path = tmp.path().join("font-index.tsv");
let first = Mutex::new(FontIndex::load(Some(index_path.clone())));
let second = Mutex::new(FontIndex::load(Some(index_path.clone())));
let miss = || (Vec::new(), Vec::new());
for i in 0..200 {
indexed_faces(&first, &format!("first-{i}"), miss);
indexed_faces(&second, &format!("second-{i}"), miss);
}
let text = fs::read_to_string(&index_path).expect("read index");
let families = text.lines().skip(1).filter(|line| !line.is_empty()).count();
assert!(families <= BOUND, "index kept {families} families");
assert!(text.ends_with('\n'), "a family line lost its newline");
}
/// A cloud-font folder that could not be listed (macOS privacy, or any
/// permission denial) must not poison the index: chmod does not change
/// the directory mtime, so a recorded miss would be served after the
/// folder becomes readable (#2051).
#[cfg(unix)]
#[test]
fn a_font_index_miss_while_a_folder_is_unreadable_is_not_reused() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().expect("tempdir");
let fonts = tmp.path().join("cloud");
fs::create_dir(&fonts).expect("fonts dir");
let carlito = fonts.join("Carlito-Regular.ttf");
fs::write(
&carlito,
include_bytes!("../../assets/fonts/Carlito-Regular.ttf"),
)
.expect("font");
let index_path = tmp.path().join("font-index.tsv");
let scan = || {
let listing = sorted_dir_listing(&fonts);
let faces = listing
.iter()
.filter(|path| path.extension().is_some_and(|ext| ext == "ttf"))
.filter_map(|path| {
let bytes = fs::read(path).ok()?;
Some(((false, false), FaceSource::new(path, None), bytes))
})
.collect();
(faces, vec![fonts.clone()])
};
let readable = fs::metadata(&fonts).expect("stat").permissions();
let mut denied = readable.clone();
denied.set_mode(0o0);
fs::set_permissions(&fonts, denied).expect("deny");
// Root (the self-hosted CI runners) lists a mode-000 folder anyway,
// so the denial this test needs cannot happen there.
if fs::read_dir(&fonts).is_ok() {
fs::set_permissions(&fonts, readable).expect("restore");
eprintln!("skipped: this user can list a mode-000 folder");
return;
}
let index = Mutex::new(FontIndex::load(Some(index_path.clone())));
assert!(
indexed_faces(&index, "cloud", scan).is_empty(),
"an unreadable folder lists no faces"
);
fs::set_permissions(&fonts, readable).expect("restore");
let again = indexed_faces(&index, "cloud", scan);
assert!(
!again.is_empty(),
"the folder is readable; a miss recorded while it was not must not be served"
);
let reloaded = Mutex::new(FontIndex::load(Some(index_path)));
assert!(
!indexed_faces(&reloaded, "cloud", scan).is_empty(),
"reloading the index must not keep the unreadable-folder miss"
);
}
/// The #2051 rule without the file system: a scan whose folder listing
/// was denied is served but never recorded, so it holds under root too,
/// where the mode-000 test above cannot produce the denial.
#[test]
fn a_miss_from_a_denied_listing_is_served_but_never_recorded() {
let tmp = tempfile::tempdir().expect("tempdir");
let dir = tmp.path().join("cloud");
let index = Mutex::new(FontIndex::load(None));
let miss = || (Vec::new(), vec![dir.clone()]);
let denied = std::cell::Cell::new(true);
let faces = indexed_faces_with(&index, "cloud", miss, |_| denied.get());
assert!(faces.is_empty(), "a denied folder lists no faces");
assert!(
!index.lock().expect("index").entries.contains_key("cloud"),
"a miss recorded while the listing was denied would be served from then on"
);
denied.set(false);
indexed_faces_with(&index, "cloud", miss, |_| denied.get());
assert!(
index.lock().expect("index").entries.contains_key("cloud"),
"a readable folder's miss is a real answer and is recorded"
);
}
#[test]
fn the_font_index_file_round_trips_and_rejects_other_versions() {
let mut entries = HashMap::new();
entries.insert(
"family\u{1f}Poppins\u{1f}/u\u{1f}/c".to_string(),
IndexEntry {
dirs: vec![
(PathBuf::from("/Library/Fonts"), Some(17)),
(PathBuf::from("/nope"), None),
],
faces: vec![IndexedFace {
style: (true, false),
source: FaceSource::new(Path::new("/f/a b.ttc"), Some(2)),
stamp: Some((10, 20)),
}],
},
);
let text = format_font_index(&entries);
assert_eq!(parse_font_index(&text), entries);
assert!(parse_font_index(&text.replacen("\t3\t", "\t0\t", 1)).is_empty());
}
#[test]
fn another_release_drops_the_font_index() {
// The index caches search answers, not only the fonts on disk: a
// release that changes the matching rules must not reuse them.
let entries = HashMap::from([(
"family\u{1f}Poppins\u{1f}/u\u{1f}/c".to_string(),
IndexEntry {
dirs: vec![(PathBuf::from("/Library/Fonts"), Some(17))],
faces: vec![],
},
)]);
let text = format_font_index(&entries);
assert_eq!(parse_font_index(&text), entries);
let header = text.lines().next().unwrap();
assert!(header.ends_with(&format!("\t{}", env!("CARGO_PKG_VERSION"))));
assert!(parse_font_index(&text.replace(env!("CARGO_PKG_VERSION"), "0.0.0")).is_empty());
// Generation 3 drops an unreadable-folder miss (#2051). An index
// this release wrote under generation 2 is not reused: permission
// does not change the directory mtime those entries were stamped with.
assert!(header.starts_with("jubarte-font-index\t3\t"));
assert!(parse_font_index(&text.replacen("\t3\t", "\t2\t", 1)).is_empty());
}
#[test]
fn an_east_asian_face_takes_word_s_taller_line() {
// Live Word at 12pt: SimSun lines step 15.6 (1.3 x its 1.0 em
// hhea body), not the hhea 13.7 with its lineGap; the extra splits
// around the text (baseline 84.2 under a 72pt margin).
let path =
Path::new("/Applications/Microsoft Word.app/Contents/Resources/DFonts/Simsun.ttc");
let Ok(bytes) = fs::read(path) else {
return;
};
let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let face = Face::from_bytes(FaceId::SansRegular, bytes, "SimSun".into()).expect("SimSun");
assert!(
(face.single_line_pt(12.0) - 15.6).abs() < 0.05,
"{}",
face.single_line_pt(12.0)
);
assert!(
(face.ascent_pt(12.0) - 12.11).abs() < 0.1,
"{}",
face.ascent_pt(12.0)
);
}
#[test]
fn an_office_365_east_asian_face_takes_its_box_for_the_line() {
// Word 16 probes lg4/lg5: 华文仿宋 (STFangsong from Word's cloud
// cache, version "1.03;O365", hhea 860/-260, head box 986/-315)
// steps 33.84 at 20pt (1.3 x the 1.301 em box, not 1.3 x the 1.12
// em hhea body) with its 10pt baseline 11.76 under the margin.
let Some(home) = std::env::var_os("HOME") else {
return;
};
let path = Path::new(&home).join(
"Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts/STFangsong/32515377567.ttf",
);
let Ok(bytes) = fs::read(&path) else {
return;
};
let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let face =
Face::from_bytes(FaceId::SansRegular, bytes, "STFangsong".into()).expect("STFangsong");
assert!(
(face.single_line_pt(20.0) - 33.83).abs() < 0.05,
"{}",
face.single_line_pt(20.0)
);
assert!(
(face.ascent_pt(10.0) - 11.81).abs() < 0.1,
"{}",
face.ascent_pt(10.0)
);
}
#[test]
fn a_typo_metrics_face_sets_its_line_gap_above_the_text() {
// Live Word, 16pt Gabriola (USE_TYPO_METRICS, typo lineGap 2867 of
// 4096) under a 72pt margin: baseline 94.08, the typo ascent plus
// the whole lineGap (22.13), not the ascent alone (10.94). Poppins
// 12 follows too (13.92 = 1.05 + 0.10 em); Candara (no flag) not.
let path =
Path::new("/Applications/Microsoft Word.app/Contents/Resources/DFonts/Gabriola.ttf");
let Ok(bytes) = fs::read(path) else {
return;
};
let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let face =
Face::from_bytes(FaceId::SansRegular, bytes, "Gabriola".into()).expect("Gabriola");
assert!(
(face.ascent_pt(16.0) - 22.13).abs() < 0.1,
"{}",
face.ascent_pt(16.0)
);
}
#[test]
fn a_slanted_regular_face_is_the_upright_one() {
// MV Boli (Word's Thaana face) leans -16 degrees yet is the family's
// Regular: Word files it by its style bits, not the angle.
let Some(home) = std::env::var_os("HOME") else {
return;
};
let path = Path::new(&home).join(
"Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts/MV Boli/29162370688.ttf",
);
let Ok(bytes) = fs::read(&path) else {
return;
};
assert_eq!(
face_family_style(&bytes, "MV Boli"),
Some((0, (false, false)))
);
}
#[test]
fn right_to_left_text_shapes_in_visual_order() {
// HarfBuzz returns an RTL run left to right on the page: the last
// letter first. Word draws "متن" with its initial meem rightmost.
let fonts = Fonts::new();
let face = fonts.get(FaceId::SansRegular);
let buzz = face.buzz.as_ref().expect("bundled face shapes");
let clusters: Vec<u32> = face
.shaped_units(buzz, "متن", false)
.iter()
.map(|u| u.2)
.collect();
assert_eq!(clusters, vec![4, 2, 0]);
}
/// Word's bullet is U+F0B7 in Symbol. Without that face the slot holds
/// Liberation Sans, whose cmap has no U+F0B7: the bullet painted
/// nothing in a WASM build's PDF (parity check 2026-10-03, 7 of 12
/// pairs). The stand-in face paints, measures and reads back "•".
#[test]
fn a_text_face_in_the_symbol_slot_paints_symbol_codes_as_unicode() {
let face = Face::load(FaceId::Symbol);
assert_eq!(face.cmap_glyph('\u{F0B7}'), 0, "Liberation has no U+F0B7");
let bullet = face.cmap_glyph('•');
assert_ne!(bullet, 0);
assert_eq!(face.glyph('\u{F0B7}'), bullet);
assert_eq!(face.glyphs("\u{F0B7} "), face.glyphs("• "));
assert_eq!(face.glyph_texts("\u{F0B7} ", false), ["•", " "]);
assert_eq!(
face.advance_pt('\u{F0B7}', 11.0),
face.advance_pt('•', 11.0)
);
// Adobe's Symbol encoding, not the low byte: U+F061 is alpha.
assert_eq!(face.glyph('\u{F061}'), face.cmap_glyph('α'));
assert_eq!(face.glyph('\u{F0AE}'), face.cmap_glyph('→'));
// Text that is already Unicode is left alone.
assert_eq!(face.glyph('a'), face.cmap_glyph('a'));
assert_eq!(face.glyph('•'), bullet);
}
/// Wingdings' bullets on a text face: U+F0A7 is the small square of
/// Word's third list level, U+F0D8 the arrowhead, U+F0FC the tick. The
/// nearest shape the face has stands for each.
#[test]
fn a_text_face_paints_wingdings_bullets_with_its_nearest_shape() {
let face = Face::load(FaceId::SansRegular);
assert_eq!(face.glyph('\u{F0A7}'), face.cmap_glyph('▪'));
assert_eq!(face.glyph('\u{F06C}'), face.cmap_glyph('●'));
assert_eq!(face.glyph('\u{F06E}'), face.cmap_glyph('■'));
assert_eq!(face.cmap_glyph('➢'), 0, "Liberation has no ➢");
assert_eq!(face.glyph('\u{F0D8}'), face.cmap_glyph('►'));
assert_eq!(face.glyph('\u{F0FC}'), face.cmap_glyph('√'));
assert_eq!(face.glyph_texts("\u{F0A7} ", false), ["▪", " "]);
// A code no list is drawn with stays what it was.
assert_eq!(face.glyph('\u{F021}'), 0);
}
/// A face that has the symbol code keeps its own glyph: Word's Symbol,
/// where this machine has it, is not stood in for.
#[test]
fn a_symbol_face_keeps_its_own_codes() {
let Some(path) = system_override(FaceId::Symbol) else {
eprintln!("skipped: Word's Symbol face is not installed on this machine");
return;
};
let face = Face::from_path(FaceId::Symbol, &path).expect("Symbol parses");
let own = face.cmap_glyph('\u{F0B7}');
assert_ne!(own, 0);
assert_eq!(face.glyph('\u{F0B7}'), own);
assert_eq!(face.glyph_texts("\u{F0B7}", false), ["\u{F0B7}"]);
}
#[test]
fn symbol_codes_follow_adobes_symbol_encoding() {
assert_eq!(symbol_unicode(0xB7), Some('•'));
assert_eq!(symbol_unicode(0x61), Some('α'));
assert_eq!(symbol_unicode(0x57), Some('Ω'));
assert_eq!(symbol_unicode(0x31), Some('1'));
assert_eq!(symbol_unicode(0xB3), Some('≥'));
assert_eq!(symbol_unicode(0x60), None);
assert_eq!(symbol_unicode(0xF0), None);
// µ is the micro sign U+00B5, the character a real Symbol face's
// text reads back as, not the Greek letter U+03BC.
assert_eq!(symbol_unicode(0x6D), Some('\u{B5}'));
// The stand-ins for characters a text face never has.
assert_eq!(symbol_unicode(0x44), Some('Δ'));
assert_eq!(symbol_unicode(0xD2), Some('®'));
assert_eq!(symbol_unicode(0xA0), Some('€'));
}
#[test]
fn apple_system_symbol_is_not_the_word_overlay() {
if let Some(path) = system_override(FaceId::Symbol) {
let s = path.to_string_lossy();
assert!(
s.contains("DFonts") || s.contains("Microsoft"),
"Symbol overlay must be Word DFonts/Microsoft, not Apple: {s}"
);
}
}
#[test]
fn faceid_key_is_unique_for_every_catalogue_slot() {
let fonts = Fonts::new();
let mut seen = HashSet::new();
for id in FaceId::all() {
let key = id.key();
assert!(
seen.insert(key.clone()),
"duplicate FaceKey for {id:?}: {key:?}"
);
assert_eq!(
fonts.get_key(&key).pdf_name(),
fonts.get(id).pdf_name(),
"shim get_key must match get({id:?})"
);
}
}
#[test]
fn faceid_key_calibri_bold_italic() {
let key = FaceId::CarlitoBoldItalic.key();
assert_eq!(key.family, "Calibri");
assert!(key.bold && key.italic);
}
#[test]
fn fonts_get_is_idempotent() {
let fonts = Fonts::new();
let a = fonts.get(FaceId::CarlitoRegular) as *const Face;
let b = fonts.get(FaceId::CarlitoRegular) as *const Face;
assert_eq!(a, b);
}
#[test]
fn calibri_gpos_kerns_av_at_28pt() {
let fonts = Fonts::new();
let face = fonts.get(FaceId::CarlitoRegular);
let off = face.width_pt_kern("AVAVAV", 28.0, false);
let on = face.width_pt_kern("AVAVAV", 28.0, true);
assert!(
off - on > 0.8,
"GPOS kern must tighten AV at 28pt; on={on} off={off}"
);
}
#[test]
fn calibri_gpos_kern_off_at_body_size_matches_hmtx() {
let fonts = Fonts::new();
let face = fonts.get(FaceId::CarlitoRegular);
let hmtx = face.width_pt("The", 11.0);
let shaped = face.width_pt_kern("The", 11.0, false);
assert!(
(hmtx - shaped).abs() < 0.05,
"body kern=false must stay hmtx; hmtx={hmtx} shaped={shaped}"
);
}
#[test]
fn aptos_twelve_stays_unligated_after_mini_727() {
// Word potpourri / file_170 Aptos 12 "flour" is U+FB02. Aptos≥12
// liga (mini 727) was ITT-neg: file_170 −0.0036 / potpourri
// −0.0002. Quartz prefers f+l. Do not retry.
let fonts = Fonts::new();
let face = fonts.get(FaceId::AptosRegular);
let g = face.shape("fl", 12.0);
assert_eq!(g.len(), 2, "mini 727 Aptos 12 liga ITT-neg; glyphs={g:?}");
}
#[test]
fn calibri_eleven_does_not_ligate_fl() {
let fonts = Fonts::new();
let face = fonts.get(FaceId::CarlitoRegular);
let g = face.shape("fl", 11.0);
assert_eq!(
g.len(),
2,
"Word Quartz WinAnsi Calibri does not ligate; glyphs={g:?}"
);
}
#[test]
fn aptos_ten_five_does_not_ligate_fl() {
// comments-lots / I_am_sharing Aptos 10.56 keeps fi/ff/fl as two
// chars (60+ hits, 0 U+FB02). Ungated Aptos liga would ITT-neg.
let fonts = Fonts::new();
let face = fonts.get(FaceId::AptosRegular);
let g = face.shape("fl", 10.5);
assert_eq!(g.len(), 2, "Word Aptos 10.5 does not ligate; glyphs={g:?}");
}
#[test]
fn resolve_uses_altname_when_requested_face_missing() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRare"><w:altName w:val="Cambria"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("SomeRare", false, false, &table),
FaceId::CambriaRegular,
"missing face must follow font-table altName"
);
}
#[test]
fn resolve_keeps_installed_face_over_altname() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Calibri"><w:altName w:val="Cambria"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("Calibri", false, false, &table),
FaceId::CarlitoRegular,
"installed Calibri (Carlito) wins over altName Cambria"
);
}
#[test]
fn resolve_keeps_quoted_css_list_intact() {
let fonts = Fonts::new();
let id = fonts.resolve(r#""Times New Roman", Times, serif"#, false, false);
assert_ne!(
id,
FaceId::SerifRegular,
"quoted first token is not Times New Roman; Word Quartz used Cambria"
);
assert_eq!(
id,
FaceId::CambriaRegular,
"unknown quoted CSS list is the evidence-table unknown row (Cambria)"
);
assert_eq!(
fonts.resolve("Verdana, Geneva, sans-serif", false, false),
FaceId::VerdanaRegular,
"unquoted first token Verdana is installed"
);
}
#[test]
fn resolve_quoted_cambria_still_finds_cambria() {
let fonts = Fonts::new();
assert_eq!(
fonts.resolve(r#""Cambria""#, false, false),
FaceId::CambriaRegular
);
assert_eq!(
fonts.resolve("Cambria", false, false),
FaceId::CambriaRegular
);
}
#[test]
fn resolve_dejavu_sans_mono_follows_word_subst_verdana() {
let fonts = Fonts::new();
assert_eq!(
fonts.resolve("DejaVu Sans Mono", false, false),
FaceId::VerdanaRegular,
"Word Quartz substituted Verdana, not Courier, for DejaVu Sans Mono"
);
}
#[test]
fn resolve_unknown_family_is_cambria_not_calibri() {
let fonts = Fonts::new();
assert_eq!(
fonts.resolve("DefinitelyNotAFont", false, false),
FaceId::CambriaRegular
);
}
#[test]
fn a_missing_script_family_is_calibri_not_the_unknown_cambria() {
// docxide suite handels_messiah_biblical_analysis: Vivaldi (script,
// panose 03…) is not installed. Word 16 probe script_missing_0930
// (the same font-table entry under a made-up name) paints it in
// Calibri; our Cambria Bold 100pt "Messiah" wrapped and cost a page.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Zqvaldi Script"><w:panose1 w:val="03020602050506090804"/><w:charset w:val="00"/><w:family w:val="script"/><w:pitch w:val="variable"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
for bold in [false, true] {
let (face, _) = fonts.classify_in("Zqvaldi Script", bold, false, &table);
let name = fonts.get(face).pdf_name().to_string();
assert!(
name.starts_with("Calibri") || name.starts_with("Carlito"),
"bold={bold}: {name}"
);
}
}
#[test]
fn resolve_wide_latin_stays_calibri_mini_505() {
let fonts = Fonts::new();
assert_eq!(
fonts.resolve("Wide Latin", false, false),
FaceId::CarlitoRegular,
"mini 505 ITT-neg WideLatin overlay; keep Calibri"
);
}
#[test]
fn resolve_empty_family_is_times_new_roman() {
let fonts = Fonts::new();
assert_eq!(
fonts.resolve("", false, false),
FaceId::SerifRegular,
"no docDefaults font: Word used Times New Roman"
);
}
#[test]
fn a_missing_swiss_entry_is_calibri_not_arial() {
// Word 16 probe my7 (this exact entry, fresh session): Calibri. The
// swiss → Arial generic was an older Word build's.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeSwiss"><w:panose1 w:val="020B0604020202020204"/><w:family w:val="swiss"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("SomeSwiss", false, false, &table),
FaceId::CarlitoRegular
);
}
#[test]
fn a_missing_roman_entry_is_cambria_not_times() {
// Word 16 probes my6/my7: any roman entry (TNR, Georgia, zero or no
// panose, even fixed pitch) is Cambria.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRoman"><w:panose1 w:val="02020603050405020304"/><w:family w:val="roman"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("SomeRoman", false, false, &table),
FaceId::CambriaRegular
);
}
#[test]
fn a_missing_fixed_pitch_entry_is_calibri_not_courier() {
// Word 16 probe my7 (this exact entry, both orders): Calibri; pitch
// and panose play no part.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeFixed"><w:panose1 w:val="02070309020205020404"/><w:pitch w:val="fixed"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("SomeFixed", false, false, &table),
FaceId::CarlitoRegular
);
}
#[test]
fn a_bare_missing_entry_takes_the_default_not_its_generic() {
// fixtures_500 01177cdf: theme "Museo Sans 300" is absent; its entry
// says modern/variable with panose 0200…0 and no altName. Word
// paints it in Calibri, not the modern generic Courier New (live
// Word gives Calibri for bare modern/roman/swiss entries alike).
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Museo Sans 300"><w:panose1 w:val="02000000000000000000"/>
<w:family w:val="modern"/><w:notTrueType/><w:pitch w:val="variable"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("Museo Sans 300", false, false, &table),
FaceId::CarlitoRegular
);
}
#[test]
fn a_missing_entry_with_an_absent_alt_name_keeps_its_generic() {
// Word 16 probe my6: a swiss entry whose altName is absent is
// Calibri. (019d9ee6's Arial reference came from Word's cloud-font
// download race; today's Word draws its Myriad Pro in Segoe UI.)
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Qwmyr Pro"><w:altName w:val="Qwertzu Absent"/>
<w:panose1 w:val="00000000000000000000"/><w:family w:val="swiss"/>
<w:notTrueType/><w:pitch w:val="variable"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("Qwmyr Pro", false, false, &table),
FaceId::CarlitoRegular
);
}
#[test]
fn installed_faces_are_read_once_per_process() {
// #166: every conversion re-read the 10-20 MB collections.
let first = cached_faces("@test-cache-key", || {
vec![((false, false), b"face".to_vec())]
});
let second = cached_faces("@test-cache-key", || panic!("loaded twice"));
assert!(
Arc::ptr_eq(&first[0].1, &second[0].1),
"one shared allocation"
);
}
fn repo_font_dir() -> PathBuf {
// The supplemental font folder stays at the repository root
// (release.yml and install.sh read it there), three up from
// this crate.
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts/extra")
}
#[test]
fn jubartes_own_font_folder_is_searched() {
// fixtures_500 01838a08: Word embeds RobotoCondensed-Regular/-Bold
// from its cloud cache; install.sh puts the same Apache-2.0 files in
// jubarte's font folder instead of growing the binary.
let faces = faces_with_user_fonts("Roboto Condensed", &[], Some(&repo_font_dir()));
for style in [(false, false), (true, false)] {
assert!(
faces.iter().any(|(s, _, _)| *s == style),
"Roboto Condensed {style:?} face"
);
}
}
#[test]
fn an_open_stand_in_answers_for_an_absent_microsoft_face() {
// Segoe UI (015beda9) is Microsoft's; without it we fell to
// Cambria. Selawik is Microsoft's open Segoe UI stand-in.
let faces = faces_with_user_fonts("Segoe UI", &[], Some(&repo_font_dir()));
assert!(
faces.iter().any(|(s, _, _)| *s == (false, false)),
"a regular Selawik for Segoe UI"
);
}
#[test]
fn a_theme_script_font_no_run_paints_is_not_loaded() {
// A theme lists ~45 per-script faces; reading each from disk was a
// third of every conversion though no run paints in them.
let mut embedded = EmbeddedFonts::new();
let table = super::super::font_table::FontTable::default();
let names = ["Roboto Condensed".to_string()];
add_installed_faces(&mut embedded, &table, &names, &[], false);
assert!(embedded.is_empty(), "nothing painted, nothing loaded");
}
#[test]
fn a_run_family_missing_from_the_font_table_still_loads_its_faces() {
// fixtures_500 015beda9 has no fontTable part; its runs name
// Segoe UI, which Word draws, and only table families were loaded.
if !Path::new("/System/Library/Fonts/HelveticaNeue.ttc").is_file() {
return;
}
let mut embedded = EmbeddedFonts::new();
let table = super::super::font_table::FontTable::default();
let names = ["Helvetica Neue".to_string()];
add_installed_faces(&mut embedded, &table, &names, &names, false);
assert!(embedded.contains_key(&("helvetica neue".to_string(), false, false)));
}
#[test]
fn word_s_own_stand_in_for_an_absent_family_beats_its_alt_name() {
// Word 16 probe my3: "Myriad Pro" with altName Arial is Segoe UI.
if installed_family_faces("Segoe UI").is_empty() {
return;
}
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Myriad Pro"><w:altName w:val="Arial"/><w:family w:val="auto"/></w:font>
</w:fonts>"#,
);
let mut embedded = EmbeddedFonts::new();
let names = ["Myriad Pro".to_string(), "Myriad Pro Light".to_string()];
add_installed_faces(&mut embedded, &table, &names, &names, false);
let fonts = Fonts::for_document(&embedded);
let physical = |family: &str| {
let (face, _) = fonts.classify_in(family, false, false, &table);
fonts.get(face).pdf_name().to_string()
};
assert!(physical("Myriad Pro").starts_with("SegoeUI"));
assert!(physical("Myriad Pro Light").starts_with("SegoeUI"));
}
#[test]
fn an_absent_face_claiming_thaana_draws_in_mv_boli() {
// 55fcbe9086: Word draws all of Faruma's runs, Latin ones too, in
// MV Boli; we drew Cambria and ran a page long.
if installed_family_faces("MV Boli").is_empty() {
return;
}
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="Qzaruma"><w:panose1 w:val="02000500030200090000"/><w:family w:val="auto"/>
<w:sig w:usb0="00000003" w:usb1="00000000" w:usb2="00000100" w:usb3="00000000" w:csb0="00000001" w:csb1="00000000"/></w:font>
</w:fonts>"#,
);
let mut embedded = EmbeddedFonts::new();
let names = ["Qzaruma".to_string()];
add_installed_faces(&mut embedded, &table, &names, &names, false);
let fonts = Fonts::for_document(&embedded);
let (face, _) = fonts.classify_in("Qzaruma", false, false, &table);
assert!(fonts.get(face).pdf_name().starts_with("MVBoli"));
}
#[test]
fn a_family_installed_only_in_bold_paints_regular_text_in_that_bold() {
// Word 16 probe my5: Segoe Print and Segoe Script, installed only as
// Bold, draw their regular runs in Bold, not in Cambria.
let mut fonts = Fonts::new();
fonts.insert_embedded("Qx Print", true, false, FaceId::MonoBold.bytes());
let table = super::super::font_table::FontTable::default();
for (bold, italic) in [(false, false), (false, true), (true, false)] {
let (face, entry) = fonts.classify_in("Qx Print", bold, italic, &table);
assert_eq!(entry.step, FontStep::Embedded, "{bold} {italic}");
assert_eq!(fonts.get(face).pdf_name(), "LiberationMono-Bold");
}
}
#[test]
fn a_cloud_face_filed_under_its_parent_family_is_found() {
// fixtures_500 001d945a: Word embeds ScriptMTBold, which its cloud
// cache files under "Script MT/"; we looked only in
// "Script MT Bold/" and drew Cambria.
let Some(home) = std::env::var_os("HOME") else {
return;
};
let dir = PathBuf::from(home)
.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts/Script MT");
if !dir.is_dir() {
return;
}
let faces =
faces_with_user_fonts("Script MT Bold", &cloud_font_dirs("Script MT Bold"), None);
assert!(
!faces.is_empty(),
"Script MT Bold from the Script MT folder"
);
}
#[test]
fn word_cloud_fonts_are_found_despite_numeric_file_names() {
// fixtures_500 014b42f2 / 01635d97: Poppins and Lato live in Word's
// cloud-font cache as <family>/<number>.ttf; the file-stem prefix
// filter rejected them and the text fell to Cambria.
let Some(home) = std::env::var_os("HOME") else {
return;
};
let dir = PathBuf::from(home)
.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts/Poppins");
if !dir.is_dir() {
return;
}
let faces = installed_family_faces("Poppins");
assert!(
faces.iter().any(|(style, _)| *style == (false, false)),
"a regular Poppins face from the cloud cache"
);
}
#[test]
fn a_system_collection_face_is_found_by_its_family() {
// fixtures_500 00d0925f: Word draws "Avenir Book" from macOS's
// /System/Library/Fonts/Avenir.ttc (hhea 1.366em: 15.1pt lines at
// 11pt). Only loose .ttf/.otf were searched; the text fell to Arial.
if !Path::new("/System/Library/Fonts/Avenir.ttc").is_file() {
return;
}
let faces = installed_family_faces("Avenir Book");
assert!(
faces.iter().any(|(style, _)| *style == (false, false)),
"a regular Avenir Book face from the system collection"
);
}
#[test]
fn macos_helvetica_takes_word_s_one_point_two_em_line() {
// English part a 18f71536 (12pt, line=248 auto): Word's lines step
// 14.88, a 14.40pt single line, 1.2 em, where Helvetica's hhea body
// is 1.0 em; the first baseline sits 0.975 em down (win ascent 0.95
// plus the 0.025 em the win box leaves of that line).
if !Path::new("/System/Library/Fonts/Helvetica.ttc").is_file() {
return;
}
let faces = installed_family_faces("Helvetica");
let (_, bytes) = faces
.into_iter()
.find(|(style, _)| *style == (false, false))
.expect("regular Helvetica");
let bytes: &'static [u8] = Box::leak(bytes.into_boxed_slice());
let ps = ttf_postscript_name(bytes).expect("postscript name");
let face = Face::from_bytes(FaceId::SansRegular, bytes, sanitize_pdf_name(&ps))
.expect("Helvetica");
assert!(
(face.single_line_pt(12.0) - 14.4).abs() < 0.02,
"{}",
face.single_line_pt(12.0)
);
assert!(
(face.ascent_pt(12.0) - 11.7).abs() < 0.02,
"{}",
face.ascent_pt(12.0)
);
}
#[test]
fn a_collection_whose_upright_face_is_medium_is_the_regular() {
// English corpus 87098dc3: Word draws "Futura" from macOS's
// Futura.ttc, whose upright face is "Futura Medium" (weight 500,
// no Regular). The text fell to Arial.
if !Path::new("/System/Library/Fonts/Supplemental/Futura.ttc").is_file() {
return;
}
let faces = installed_family_faces("Futura");
assert!(
faces.iter().any(|(style, _)| *style == (false, false)),
"a regular Futura face from the system collection"
);
}
#[test]
fn a_collection_prefers_its_normal_width_face() {
// English corpus 469e5710: macOS's Papyrus.ttc holds "Papyrus
// Condensed" before "Papyrus Regular", both family "Papyrus". Word
// draws the regular; we took the condensed face.
if !Path::new("/System/Library/Fonts/Supplemental/Papyrus.ttc").is_file() {
return;
}
let faces = installed_family_faces("Papyrus");
let regular = faces
.iter()
.find(|(style, _)| *style == (false, false))
.expect("a regular Papyrus face");
let face = ttf_parser::Face::parse(®ular.1, 0).expect("face");
assert_eq!(face.width(), ttf_parser::Width::Normal);
}
#[test]
fn a_cff_face_is_not_embedded() {
// #166: the PDF writer emits FontFile2 (TrueType); a CFF
// .otf would be embedded as an unreadable program. It is refused.
let otf = "/System/Library/Fonts/Supplemental/STIXSizOneSymBol.otf";
let Ok(bytes) = fs::read(otf) else {
return;
};
let parsed = ttf_parser::Face::parse(&bytes, 0).expect("STIX parses");
assert!(parsed.tables().glyf.is_none(), "a CFF face");
let mut fonts = Fonts::new();
fonts.insert_embedded("stix", false, false, &bytes);
assert!(fonts.embedded_index("stix", false, false).is_none());
}
#[test]
fn a_family_name_match_outranks_a_typographic_one_per_style() {
// #166: Roboto-Black.ttf (ID 1 "Roboto Black", ID 16
// "Roboto") sorts before Roboto-Regular.ttf and took the regular
// slot. Pass 0 (ID 1) beats pass 1 (ID 16) per style; path order
// decides within a pass.
let found = vec![
(1, (false, false), b"black".to_vec()),
(1, (true, false), b"heavy".to_vec()),
(0, (false, false), b"regular".to_vec()),
(0, (false, false), b"regular2".to_vec()),
];
let picked = pick_ranked_faces(found);
assert_eq!(
picked,
vec![
((false, false), b"regular".to_vec()),
((true, false), b"heavy".to_vec()),
]
);
}
#[test]
fn fold_family_maps_full_width_names_to_their_ascii_key() {
assert_eq!(fold_family("MS 明朝"), "ms明朝");
assert_eq!(fold_family("MS Mincho"), "msmincho");
assert_eq!(fold_family("FangSong_GB2312"), "fangsonggb2312");
assert_eq!(cjk_file_stems("MS ゴシック"), &["msgothic"]);
assert!(cjk_file_stems("Calibri").is_empty());
}
#[test]
fn cjk_family_takes_its_own_face_out_of_word_s_collection() {
// fixtures_500 0016d88a: "MS 明朝" text vanished (no face held
// its glyphs). Word draws msmincho.ttc face 0, MS Mincho.
let ttc = "/Applications/Microsoft Word.app/Contents/Resources/DFonts/msmincho.ttc";
if !Path::new(ttc).is_file() {
return;
}
let faces = installed_family_faces("MS 明朝");
let (_, bytes) = faces
.iter()
.find(|(style, _)| *style == (false, false))
.expect("a regular MS Mincho face");
let face = ttf_parser::Face::parse(bytes, 0).expect("standalone sfnt");
assert!(
face_family_names(&face, ttf_parser::name_id::FAMILY).contains(&"msmincho".to_string())
);
assert!(face.glyph_index('明').is_some(), "CJK glyphs present");
let pfaces = installed_family_faces("MS PMincho");
let (_, pbytes) = pfaces.first().expect("MS PMincho face");
let pface = ttf_parser::Face::parse(pbytes, 0).expect("standalone sfnt");
assert!(
face_family_names(&pface, ttf_parser::name_id::FAMILY)
.contains(&"mspmincho".to_string()),
"the collection's second face, not the first"
);
}
#[test]
fn missing_east_asian_family_falls_to_word_s_cjk_face() {
// fixtures_500 0025b0d3: 標楷體 (charset 88) is not installed;
// Word draws it in Microsoft YaHei. A Japanese family Word lacks
// (0041d394's HGP行書体, charset 80) is Yu Gothic.
let dfonts = "/Applications/Microsoft Word.app/Contents/Resources/DFonts";
if !Path::new(dfonts).join("msyh.ttc").is_file()
|| !Path::new(dfonts).join("YuGothR.ttc").is_file()
{
return;
}
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="標楷體"><w:charset w:val="88"/><w:family w:val="script"/><w:pitch w:val="fixed"/></w:font>
<w:font w:name="HGP行書体"><w:charset w:val="80"/><w:family w:val="script"/></w:font>
<w:font w:name="SomeLatin"><w:panose1 w:val="020B0604020202020204"/><w:family w:val="swiss"/></w:font>
</w:fonts>"#,
);
let mut embedded = EmbeddedFonts::new();
add_cjk_fallbacks(&mut embedded);
let fonts = Fonts::for_document(&embedded);
let physical = |family: &str| {
let (face, _) = fonts.classify_in(family, false, false, &table);
fonts.get(face).pdf_name().to_string()
};
assert_eq!(physical("標楷體"), "MicrosoftYaHei");
assert!(physical("HGP行書体").starts_with("YuGothic"));
assert!(
physical("SomeLatin").starts_with("Calibri"),
"Latin families keep their own generic"
);
}
#[test]
fn missing_korean_family_falls_to_batang_or_malgun_gothic_by_class() {
// docxide suite korean_japanese_conference_form: HY헤드라인M,
// 함초롬바탕 and 새굴림 (charset 81, roman) are not installed. Word 16
// probes (ko_fonts_0930, ko_fonts2_0930) paint an absent roman
// Korean family in Batang and a swiss/modern/auto one in Malgun
// Gothic; YaHei, our Chinese face, has no Hangul.
let dfonts = "/Applications/Microsoft Word.app/Contents/Resources/DFonts";
if !Path::new(dfonts).join("batang.ttc").is_file()
|| !Path::new(dfonts).join("malgun.ttf").is_file()
{
return;
}
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="HY헤드라인M"><w:charset w:val="81"/><w:family w:val="roman"/></w:font>
<w:font w:name="SomeKoSans"><w:charset w:val="81"/><w:family w:val="swiss"/></w:font>
<w:font w:name="SomeKoMono"><w:charset w:val="81"/><w:family w:val="modern"/></w:font>
</w:fonts>"#,
);
let mut embedded = EmbeddedFonts::new();
add_cjk_fallbacks(&mut embedded);
let fonts = Fonts::for_document(&embedded);
let face = |family: &str, bold: bool| {
let (face, _) = fonts.classify_in(family, bold, false, &table);
fonts.get(face)
};
assert_eq!(face("HY헤드라인M", false).pdf_name(), "Batang");
assert!(face("HY헤드라인M", false).glyph('한') != 0);
assert!(
face("SomeKoSans", false)
.pdf_name()
.starts_with("MalgunGothic")
);
assert!(face("SomeKoMono", false).glyph('한') != 0);
assert!(
face("SomeKoMono", true)
.pdf_name()
.starts_with("MalgunGothic")
);
assert_ne!(
face("SomeKoMono", true).pdf_name(),
face("SomeKoMono", false).pdf_name(),
"Malgun Gothic's own bold face"
);
}
#[test]
fn resolve_dead_end_altname_keeps_the_original_generic() {
// An altName that is neither installed nor in the table leaves the
// first entry's generic: Word 16 probe my6 paints a swiss entry with
// an absent altName in Calibri, not the unknown-family Cambria.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeMyriad"><w:altName w:val="SomeSegoe"/><w:family w:val="swiss"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("SomeMyriad", false, false, &table),
FaceId::CarlitoRegular
);
}
#[test]
fn resolve_altname_cycle_falls_back() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="GhostA"><w:altName w:val="GhostB"/></w:font>
<w:font w:name="GhostB"><w:altName w:val="GhostA"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
assert_eq!(
fonts.resolve_in("GhostA", false, false, &table),
FaceId::CambriaRegular,
"altName cycle uses the unknown-family evidence row"
);
}
#[test]
fn resolve_prefers_embedded_unknown_family() {
let mut fonts = Fonts::new();
assert_eq!(
fonts.resolve("Press Start 2P", false, false),
FaceId::CambriaRegular,
"without an embed, the unknown family is Cambria"
);
fonts.insert_embedded("Press Start 2P", false, false, FaceId::MonoRegular.bytes());
let face = fonts.resolve("Press Start 2P", false, false);
assert!(
matches!(face, FaceRef::Embedded(_)),
"embedded face must win over the unknown-family row; got {face:?}"
);
assert_eq!(fonts.get(face).pdf_name(), "LiberationMono");
assert_eq!(
fonts.resolve("Press Start 2P", true, false),
face,
"missing bold embed falls back to the regular embed"
);
}
#[test]
fn embedded_faces_borrow_the_conversion_bytes() {
// #11: embedded payloads were copied into a process-global intern
// table and Box::leak-ed, so a long-lived caller kept every
// document's fonts. The face now borrows the conversion's buffer
// (same allocation), which the compiler ties to the Fonts value.
let embedded: EmbeddedFonts = HashMap::from([(
("Press Start 2P".to_string(), false, false),
Arc::from(FaceId::MonoRegular.bytes()),
)]);
let fonts = Fonts::for_document(&embedded);
let face = fonts.resolve("Press Start 2P", false, false);
assert!(matches!(face, FaceRef::Embedded(_)));
let owned = &embedded[&("Press Start 2P".to_string(), false, false)];
assert_eq!(fonts.get(face).bytes().as_ptr(), owned.as_ptr());
assert_eq!(fonts.get(face).pdf_name(), "LiberationMono");
}
#[test]
fn resolve_embedded_does_not_steal_unrelated_families() {
let mut fonts = Fonts::new();
fonts.insert_embedded("Press Start 2P", false, false, FaceId::MonoRegular.bytes());
assert_eq!(
fonts.resolve("Calibri", false, false),
FaceId::CarlitoRegular
);
assert_eq!(
fonts.resolve("Cambria", false, false),
FaceId::CambriaRegular
);
}
fn obfuscated_embed_docx(family: &str, guid: &str, ttf: &[u8]) -> Vec<u8> {
use std::io::{Cursor, Write};
let mut odttf = ttf.to_vec();
let key = super::super::font_table::parse_font_key(guid).expect("guid");
super::super::font_table::deobfuscate_font(&mut odttf, &key);
let mut buf = Vec::new();
{
let mut z = zip::ZipWriter::new(Cursor::new(&mut buf));
let opt = zip::write::SimpleFileOptions::default();
z.start_file("[Content_Types].xml", opt).unwrap();
z.write_all(
br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/><Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/></Types>"#,
)
.unwrap();
z.start_file("_rels/.rels", opt).unwrap();
z.write_all(
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdM" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
)
.unwrap();
z.start_file("word/document.xml", opt).unwrap();
let doc = format!(
r#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:rPr><w:rFonts w:ascii="{family}" w:hAnsi="{family}"/></w:rPr><w:t>HELLO</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>"#
);
z.write_all(doc.as_bytes()).unwrap();
z.start_file("word/fontTable.xml", opt).unwrap();
let table = format!(
r#"<?xml version="1.0"?><w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><w:font w:name="{family}"><w:embedRegular r:id="rId1" w:fontKey="{guid}"/></w:font></w:fonts>"#
);
z.write_all(table.as_bytes()).unwrap();
z.start_file("word/_rels/fontTable.xml.rels", opt).unwrap();
z.write_all(
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/font" Target="fonts/font1.odttf"/></Relationships>"#,
)
.unwrap();
z.start_file("word/fonts/font1.odttf", opt).unwrap();
z.write_all(&odttf).unwrap();
z.finish().unwrap();
}
buf
}
#[test]
fn convert_emits_embedded_postscript_name() {
let guid = "{00000000-0000-0000-0000-000000000001}";
let docx = obfuscated_embed_docx("Press Start 2P", guid, FaceId::MonoRegular.bytes());
let pdf = super::super::docx_to_pdf(&docx).expect("convert");
let text = String::from_utf8_lossy(&pdf);
assert!(
text.contains("/LiberationMono"),
"embedded physical PostScript name must be a PDF font; snippet={}",
text.chars().take(800).collect::<String>()
);
}
fn simple_docx_with_ascii_font(family: &str) -> Vec<u8> {
use std::io::{Cursor, Write};
let mut buf = Vec::new();
{
let mut z = zip::ZipWriter::new(Cursor::new(&mut buf));
let opt = zip::write::SimpleFileOptions::default();
z.start_file("[Content_Types].xml", opt).unwrap();
z.write_all(
br#"<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>"#,
)
.unwrap();
z.start_file("_rels/.rels", opt).unwrap();
z.write_all(
br#"<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rIdM" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>"#,
)
.unwrap();
z.start_file("word/document.xml", opt).unwrap();
let doc = format!(
r#"<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body><w:p><w:r><w:rPr><w:rFonts w:ascii="{family}" w:hAnsi="{family}"/></w:rPr><w:t>HELLO</w:t></w:r></w:p><w:sectPr><w:pgSz w:w="12240" w:h="15840"/><w:pgMar w:top="1440" w:right="1440" w:bottom="1440" w:left="1440"/></w:sectPr></w:body></w:document>"#
);
z.write_all(doc.as_bytes()).unwrap();
z.finish().unwrap();
}
buf
}
#[test]
fn docx_to_pdf_report_includes_requested_unknown_family() {
let docx = simple_docx_with_ascii_font("DefinitelyNotAFont");
let out = super::super::docx_to_pdf_report(&docx, super::super::PdfOptions::default())
.expect("convert");
assert!(out.pdf.starts_with(b"%PDF"));
let row = out
.font_report
.iter()
.find(|e| e.requested == "DefinitelyNotAFont")
.expect("unknown family must appear in the report");
assert_eq!(row.step, FontStep::Unknown);
let json = font_report_json(&out.font_report);
assert!(json.starts_with('['), "{json}");
assert!(json.contains("\"step\":\"unknown\""), "{json}");
}
#[test]
fn classify_unknown_family_is_unknown_step() {
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
let (_, entry) = fonts.classify_in("DefinitelyNotAFont", false, false, &table);
assert_eq!(entry.step, FontStep::Unknown);
assert_eq!(entry.requested, "DefinitelyNotAFont");
assert!(!entry.physical.is_empty());
assert!(!entry.synthetic);
}
#[test]
fn classify_dejavu_sans_mono_is_word_substitution() {
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
let (_, entry) = fonts.classify_in("DejaVu Sans Mono", false, false, &table);
assert_eq!(entry.step, FontStep::WordSubstitution);
assert_eq!(entry.requested, "DejaVu Sans Mono");
}
#[test]
fn classify_empty_family_is_word_substitution() {
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
let (face, entry) = fonts.classify_in("", false, false, &table);
assert_eq!(entry.step, FontStep::WordSubstitution);
assert_eq!(face, FaceId::SerifRegular);
}
#[test]
fn classify_quoted_css_list_is_unknown() {
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
let (_, entry) =
fonts.classify_in(r#""Times New Roman", Times, serif"#, false, false, &table);
assert_eq!(entry.step, FontStep::Unknown);
assert_eq!(entry.requested, r#""Times New Roman", Times, serif"#);
}
#[test]
fn classify_altname_step_is_altname() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRare"><w:altName w:val="Cambria"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
let (_, entry) = fonts.classify_in("SomeRare", false, false, &table);
assert_eq!(entry.step, FontStep::AltName);
assert_eq!(entry.requested, "SomeRare");
}
#[test]
fn classify_swiss_generic_step_is_generic() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeSwiss"><w:panose1 w:val="020B0604020202020204"/><w:family w:val="swiss"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
let (_, entry) = fonts.classify_in("SomeSwiss", false, false, &table);
assert_eq!(entry.step, FontStep::Generic);
}
#[test]
fn a_family_placed_by_its_name_class_is_substituted() {
// `--fail-on-substitution` must see an absent family whose name says
// serif, though it is drawn with the installed serif face.
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
for family in ["Jubarte Absent Serif", "Helvetica"] {
let (_, entry) = fonts.classify_in(family, false, false, &table);
assert!(
entry.substituted(),
"{family}: {:?} -> {}",
entry.step,
entry.physical
);
}
let (_, entry) = fonts.classify_in("Times New Roman", false, false, &table);
assert!(
!entry.substituted() || entry.step == FontStep::OpenFallback,
"{entry:?}"
);
assert!(names_family("Arial MT", "Arial"));
assert!(names_family("TimesNewRoman", "Times New Roman"));
assert!(!names_family("Times", "Times New Roman"));
// Monotype's PostScript-style names in older documents.
assert!(names_family("Times New Roman PS MT", "Times New Roman"));
assert!(names_family("Arial PS MT", "Arial"));
// Only the "PS MT" pair goes, never a lone trailing "ps".
assert!(!names_family("War", "Warps"));
assert!(!names_family("PS", "MT"));
}
#[test]
fn classify_calibri_is_explicit_or_open_fallback() {
let fonts = Fonts::new();
let table = super::super::font_table::FontTable::default();
let (_, entry) = fonts.classify_in("Calibri", false, false, &table);
assert!(
matches!(entry.step, FontStep::Explicit | FontStep::OpenFallback),
"Calibri must be installed or bundled, got {:?}",
entry.step
);
assert!(!entry.physical.is_empty());
}
#[test]
fn classify_embedded_unknown_family_is_embedded_step() {
let mut fonts = Fonts::new();
fonts.insert_embedded("Press Start 2P", false, false, FaceId::MonoRegular.bytes());
let table = super::super::font_table::FontTable::default();
let (_, regular) = fonts.classify_in("Press Start 2P", false, false, &table);
assert_eq!(regular.step, FontStep::Embedded);
assert_eq!(regular.physical, "LiberationMono");
assert!(!regular.synthetic);
let (_, bold) = fonts.classify_in("Press Start 2P", true, false, &table);
assert_eq!(bold.step, FontStep::Embedded);
assert!(bold.synthetic, "missing bold embed is synthetic");
}
#[test]
fn an_unknown_auto_family_is_calibri_even_beside_an_embedded_default() {
// Word 16 probe my6: the document's default font plays no part; a
// bare family="auto" entry is Calibri in a styled and a bare doc.
let mut fonts = Fonts::new();
fonts.insert_embedded("Press Start 2P", false, false, FaceId::MonoRegular.bytes());
let table = super::super::font_table::parse_font_table_xml(
"<w:fonts xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\">\
<w:font w:name=\"Serenity\"><w:family w:val=\"auto\"/></w:font></w:fonts>",
);
let (face, entry) = fonts.classify_in("Serenity", false, false, &table);
assert_eq!(entry.step, FontStep::Generic);
assert_eq!(face, FaceRef::Catalogue(FaceId::CarlitoRegular));
}
#[test]
fn a_family_name_cannot_leave_the_cloud_font_cache() {
// PR #167 review: w:name is document data; joining "../.." or an
// absolute name onto the cache path read fonts from anywhere.
let home = std::path::Path::new("/Users/someone");
assert!(cloud_font_dir(home, "Poppins").is_some());
assert!(cloud_font_dir(home, "Roboto Condensed").is_some());
for bad in ["../../../../etc", "/Library/Fonts", "a/b", "..", ".", ""] {
assert!(
cloud_font_dir(home, bad).is_none(),
"{bad:?} must not map to a folder"
);
}
}
#[test]
fn font_report_json_shape() {
let entry = FontReportEntry {
requested: r#"Calibri "body""#.to_string(),
step: FontStep::Explicit,
physical: "Calibri".to_string(),
bold: false,
italic: true,
synthetic: false,
};
let json = font_report_json(std::slice::from_ref(&entry));
assert_eq!(
json,
r#"[{"requested":"Calibri \"body\"","step":"explicit","physical":"Calibri","bold":false,"italic":true,"synthetic":false,"substituted":false}]"#
);
}
#[test]
fn with_font_report_records_distinct_requests_only() {
let fonts = Fonts::new();
let ((), report) = with_font_report(|| {
let _ = fonts.resolve("DefinitelyNotAFont", false, false);
let _ = fonts.resolve("DefinitelyNotAFont", false, false);
let _ = fonts.resolve("Calibri", true, false);
});
assert_eq!(
report.len(),
2,
"same requested+style must collapse: {report:?}"
);
assert_eq!(report[0].requested, "DefinitelyNotAFont");
assert_eq!(report[0].step, FontStep::Unknown);
assert_eq!(report[1].requested, "Calibri");
assert!(report[1].bold);
}
#[test]
fn resolve_follows_altname_chain_and_preserves_style() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="GhostA"><w:altName w:val="GhostB"/></w:font>
<w:font w:name="GhostB"><w:altName w:val="Cambria"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
for (bold, italic, expected) in [
(false, false, FaceId::CambriaRegular),
(true, false, FaceId::CambriaBold),
(false, true, FaceId::CambriaItalic),
(true, true, FaceId::CambriaBoldItalic),
] {
assert_eq!(
fonts.resolve_in("ghosta", bold, italic, &table),
expected,
"style must survive a case-insensitive multi-hop altName lookup"
);
}
}
#[test]
fn times_new_roman_uses_the_installed_face_word_uses() {
// fixtures_500 014babb2: Word's double-spaced Times 12 lines are
// 27.6pt apart (13.8 single). macOS Supplemental Times New Roman
// 5.01 has hhea lineGap 87 (13.80); Word's private DFonts copy 7.0
// has lineGap 0 (13.29). Word draws with the installed face.
if !Path::new("/System/Library/Fonts/Supplemental/Times New Roman.ttf").is_file() {
return;
}
let fonts = Fonts::new();
let times = fonts.get(FaceId::SerifRegular);
assert!(
(times.single_line_pt(12.0) - 13.8).abs() < 0.02,
"Times 12 single line {}",
times.single_line_pt(12.0)
);
}
#[test]
fn a_precomposed_czech_letter_paints_as_its_own_glyph() {
// 3509b16c7d: Cambria's ccmp splits "ě" into e + a caron mark;
// Word's PDF draws ě, č, ů whole, and the shared "e" glyph could
// not carry "ě" in /ToUnicode.
if !Fonts::is_installed_family("Cambria") {
return;
}
let fonts = Fonts::new();
let cambria = fonts.get(fonts.resolve("Cambria", false, false));
for letter in ["ě", "č", "ů", "ž"] {
assert_eq!(cambria.glyph_texts(letter, false), [letter]);
}
}
#[test]
fn single_line_is_the_hhea_line_not_the_typo_line() {
// Word's single line is hhea ascender - descender + lineGap (GDI:
// win height + external leading). Typo metrics differ for Courier
// (0.80 em) and Arial (1.09 em); Word's file_146 Courier 9.5 lines
// are 10.8pt apart (1.133 em), and Arial 11 is 12.65pt.
let fonts = Fonts::new();
let mono = fonts.get(FaceId::MonoRegular);
assert!((mono.single_line_pt(9.5) - 9.5 * 2320.0 / 2048.0).abs() < 0.02);
let sans = fonts.get(FaceId::SansRegular);
assert!((sans.single_line_pt(11.0) - 11.0 * 2355.0 / 2048.0).abs() < 0.02);
let carlito = fonts.get(FaceId::CarlitoRegular);
assert!(
(carlito.single_line_pt(11.0) - 11.0 * 2500.0 / 2048.0).abs() < 0.02,
"Calibri/Carlito hhea equals typo: unchanged at 13.43"
);
}
#[test]
fn postscript_name_decodes_eight_bit_records() {
assert_eq!(
ascii_record_name(b"PressStart2P-Regular").as_deref(),
Some("PressStart2P-Regular")
);
assert_eq!(ascii_record_name(b""), None);
assert_eq!(
ascii_record_name(b"Has Space"),
None,
"PostScript names have no spaces"
);
assert_eq!(ascii_record_name(&[0xC3, 0xA9]), None);
assert_eq!(
ttf_postscript_name(FaceId::MonoRegular.bytes()).as_deref(),
Some("LiberationMono"),
"Unicode records still win"
);
}
#[test]
fn font_table_scope_is_restored_after_a_panicking_conversion() {
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRare"><w:altName w:val="Arial"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
with_font_table(table, || panic!("conversion failed mid-document"))
}));
assert!(caught.is_err());
assert_eq!(
fonts.resolve("SomeRare", false, false),
FaceId::CambriaRegular,
"a panicking conversion must not leave its altName table installed"
);
}
#[test]
fn font_report_scope_is_restored_after_a_panic() {
let fonts = Fonts::new();
let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
with_font_report(|| {
let _ = fonts.resolve("Calibri", false, false);
panic!("conversion failed mid-document")
})
}));
assert!(caught.is_err());
assert!(
FONT_REPORT.with(|slot| slot.borrow().is_none()),
"a panicking conversion must not leave a report collector installed"
);
}
#[test]
fn long_alt_name_chain_resolves_without_deep_recursion() {
// 20k chained rows; a recursive walk needs megabytes of stack.
let mut xml = String::from(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">"#,
);
for i in 0..20_000 {
write!(
xml,
r#"<w:font w:name="Chain{i}"><w:altName w:val="Chain{}"/></w:font>"#,
i + 1
)
.unwrap();
}
xml.push_str(
r#"<w:font w:name="Chain20000"><w:altName w:val="Consolas"/></w:font></w:fonts>"#,
);
let table = super::super::font_table::parse_font_table_xml(&xml);
let face = std::thread::Builder::new()
.stack_size(256 * 1024)
.spawn(move || Fonts::new().resolve_in("Chain0", false, false, &table))
.unwrap()
.join()
.expect("resolution must not overflow a 256 KiB stack");
assert_eq!(face, FaceId::ConsolasRegular);
}
#[test]
fn css_list_row_is_found_by_its_full_name() {
// Word writes the altName against the whole w:name, quotes and all.
let table = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name=""Unheard Of", Other, serif"><w:altName w:val="Consolas"/></w:font>
</w:fonts>"#,
);
let (face, step) =
Fonts::new().resolve_in_step(r#""Unheard Of", Other, serif"#, false, false, &table);
assert_eq!(face, FaceId::ConsolasRegular);
assert_eq!(step, FontStep::AltName);
}
#[test]
fn unknown_face_key_keeps_its_style() {
for (bold, italic, expected) in [
(false, false, FaceId::CambriaRegular),
(true, false, FaceId::CambriaBold),
(false, true, FaceId::CambriaItalic),
(true, true, FaceId::CambriaBoldItalic),
] {
let key = FaceKey {
family: "Definitely Not A Font".into(),
bold,
italic,
};
assert_eq!(
Fonts::id_from_key(&key),
expected,
"bold={bold} italic={italic}"
);
}
}
#[test]
fn nested_font_table_scope_restores_outer_table() {
// Three distinct answers: outer altName Arial, inner altName
// Consolas, and the default table's unknown-family row (Cambria).
let outer = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRare"><w:altName w:val="Arial"/></w:font>
</w:fonts>"#,
);
let inner = super::super::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="SomeRare"><w:altName w:val="Consolas"/></w:font>
</w:fonts>"#,
);
let fonts = Fonts::new();
with_font_table(outer, || {
assert_eq!(fonts.resolve("SomeRare", false, false), FaceId::SansRegular);
with_font_table(inner, || {
assert_eq!(
fonts.resolve("SomeRare", false, false),
FaceId::ConsolasRegular
);
});
assert_eq!(
fonts.resolve("SomeRare", false, false),
FaceId::SansRegular,
"leaving an inner conversion must restore the outer font table"
);
});
assert_eq!(
fonts.resolve("SomeRare", false, false),
FaceId::CambriaRegular,
"leaving all conversion scopes must restore the default table"
);
}
mod regression_tests {
use super::*;
#[test]
fn shortened_font_filenames_still_use_the_internal_family_name() {
let dir = tempfile::tempdir().unwrap();
let bytes = include_bytes!("../../assets/fonts/LiberationSans-Regular.ttf");
fs::write(dir.path().join("Liberation.ttf"), bytes).unwrap();
// The name resembles several families; only the file's own family wins.
let dirs = [(dir.path().to_path_buf(), false)];
let found = family_faces_in("Liberation Sans", &dirs);
assert_eq!(found.len(), 1);
assert_eq!(found[0].0, (false, false));
assert_eq!(
found[0].1,
FaceSource::new(&dir.path().join("Liberation.ttf"), None)
);
assert_eq!(found[0].2, bytes);
assert!(family_faces_in("Liberation Serif", &dirs).is_empty());
}
#[test]
fn windows_font_folders_find_every_style_by_its_internal_name() {
// Windows abbreviates: times.ttf, timesbd.ttf, timesi.ttf,
// cour.ttf. The regular file's stem is a prefix of the family
// key, the bold one's is not, and "cour" is too short to match.
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("WINDOWS").join("Fonts");
fs::create_dir_all(&dir).unwrap();
let regular = include_bytes!("../../assets/fonts/LiberationSerif-Regular.ttf");
let bold = include_bytes!("../../assets/fonts/LiberationSerif-Bold.ttf");
let mono = include_bytes!("../../assets/fonts/LiberationMono-Regular.ttf");
fs::write(dir.join("liberat.ttf"), regular).unwrap();
fs::write(dir.join("liberatbd.ttf"), bold).unwrap();
fs::write(dir.join("lmo.ttf"), mono).unwrap();
let dirs = [(dir.clone(), false)];
let found = family_faces_in("Liberation Serif", &dirs);
let styles: Vec<_> = found.iter().map(|(style, _, _)| *style).collect();
assert_eq!(styles, vec![(false, false), (true, false)]);
assert!(found.iter().any(|(_, _, b)| b == bold));
assert_eq!(family_faces_in("Liberation Mono", &dirs).len(), 1);
// Other folders keep matching by file name alone.
let other = root.path().join("Fonts");
fs::create_dir(&other).unwrap();
fs::write(other.join("liberat.ttf"), regular).unwrap();
fs::write(other.join("liberatbd.ttf"), bold).unwrap();
assert_eq!(
family_faces_in("Liberation Serif", &[(other, false)]).len(),
1
);
}
#[test]
fn dfonts_index_finds_abbreviated_names_and_ignores_corrupt_fonts() {
let root = tempfile::tempdir().unwrap();
let dir = root.path().join("DFonts");
fs::create_dir(&dir).unwrap();
let regular = include_bytes!("../../assets/fonts/LiberationSerif-Regular.ttf");
let italic = include_bytes!("../../assets/fonts/LiberationSerif-Italic.ttf");
fs::write(dir.join("LS.TTF"), regular).unwrap();
fs::write(dir.join("LSI.ttf"), italic).unwrap();
fs::write(dir.join("broken.ttf"), b"not a font").unwrap();
fs::write(dir.join("ignored.txt"), regular).unwrap();
let found = family_faces_in("Liberation Serif", &[(dir, false)]);
assert_eq!(found.len(), 2);
assert!(
found
.iter()
.any(|(style, _, bytes)| *style == (false, false) && bytes == regular)
);
assert!(
found
.iter()
.any(|(style, _, bytes)| *style == (false, true) && bytes == italic)
);
}
#[test]
fn absent_arabic_and_hebrew_fonts_keep_the_requested_style_in_arial() {
let fonts = Fonts::new();
for charset in ["B1", "B2", "b1", "b2"] {
let xml = format!(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="PR168 Missing RTL"><w:charset w:val="{charset}"/></w:font></w:fonts>"#
);
let table = crate::convert::font_table::parse_font_table_xml(&xml);
for (bold, italic, expected) in [
(false, false, FaceId::SansRegular),
(true, false, FaceId::SansBold),
(false, true, FaceId::SansItalic),
(true, true, FaceId::SansBoldItalic),
] {
assert_eq!(
fonts.resolve_in_step("PR168 Missing RTL", bold, italic, &table),
(expected, FontStep::Generic),
"charset {charset}"
);
}
}
}
#[test]
fn a_missing_default_font_terminates_at_calibri_without_losing_style() {
let table = crate::convert::font_table::parse_font_table_xml(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:font w:name="PR168 Missing Face"/><w:font w:name="PR168 Missing Default"/></w:fonts>"#,
);
assert_eq!(
Fonts::new().resolve_in("PR168 Missing Face", true, true, &table),
FaceId::CarlitoBoldItalic
);
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod pure_font_boundary_tests {
use super::*;
#[test]
fn family_aliases_keep_all_four_requested_styles() {
let groups: &[(&[&str], [FaceId; 4])] = &[
(
&[
"courier",
"monaco",
"menlo",
"cousine",
"nimbusmono",
"custommono",
],
[
FaceId::MonoRegular,
FaceId::MonoBold,
FaceId::MonoItalic,
FaceId::MonoBoldItalic,
],
),
(
&[
"arial",
"helvetica",
"liberationsans",
"opensans",
"roboto",
"tahoma",
"trebuchet",
"geneva",
"sansserif",
],
[
FaceId::SansRegular,
FaceId::SansBold,
FaceId::SansItalic,
FaceId::SansBoldItalic,
],
),
(
&["times", "caladea", "liberationserif", "customserif"],
[
FaceId::SerifRegular,
FaceId::SerifBold,
FaceId::SerifItalic,
FaceId::SerifBoldItalic,
],
),
(
&["aptosdisplay", "aptoscustomdisplay"],
[
FaceId::AptosDisplayRegular,
FaceId::AptosDisplayBold,
FaceId::AptosDisplayItalic,
FaceId::AptosDisplayBoldItalic,
],
),
(
&["aptos"],
[
FaceId::AptosRegular,
FaceId::AptosBold,
FaceId::AptosItalic,
FaceId::AptosBoldItalic,
],
),
(
&["verdana"],
[
FaceId::VerdanaRegular,
FaceId::VerdanaBold,
FaceId::VerdanaItalic,
FaceId::VerdanaBoldItalic,
],
),
(
&["cambria", "inter"],
[
FaceId::CambriaRegular,
FaceId::CambriaBold,
FaceId::CambriaItalic,
FaceId::CambriaBoldItalic,
],
),
(
&["consolas"],
[
FaceId::ConsolasRegular,
FaceId::ConsolasBold,
FaceId::ConsolasItalic,
FaceId::ConsolasBoldItalic,
],
),
(
&["georgia"],
[
FaceId::GeorgiaRegular,
FaceId::GeorgiaBold,
FaceId::GeorgiaItalic,
FaceId::GeorgiaBoldItalic,
],
),
(
&["bookantiqua", "palatino"],
[
FaceId::BookAntiquaRegular,
FaceId::BookAntiquaBold,
FaceId::BookAntiquaItalic,
FaceId::BookAntiquaBoldItalic,
],
),
(
&["calibri", "carlito"],
[
FaceId::CarlitoRegular,
FaceId::CarlitoBold,
FaceId::CarlitoItalic,
FaceId::CarlitoBoldItalic,
],
),
];
for (families, expected) in groups {
for family in *families {
for (index, (bold, italic)) in
[(false, false), (true, false), (false, true), (true, true)]
.into_iter()
.enumerate()
{
assert_eq!(
Fonts::mapped_face(family, bold, italic),
Some(expected[index]),
"{family} {bold} {italic}"
);
}
}
}
for family in ["calibrilight", "calibricustomlight"] {
assert_eq!(
Fonts::mapped_face(family, true, false),
Some(FaceId::CalibriLightRegular)
);
assert_eq!(
Fonts::mapped_face(family, false, true),
Some(FaceId::CalibriLightItalic)
);
}
assert_eq!(
Fonts::mapped_face("symbol", false, true),
Some(FaceId::Symbol)
);
assert_eq!(Fonts::mapped_face("dejavumono", false, false), None);
assert_eq!(Fonts::mapped_face("unknownsans", false, false), None);
}
#[test]
fn font_without_shaping_support_preserves_unicode_and_uses_glyph_advances() {
let mut face = Face::from_bytes(
FaceId::SansRegular,
FaceId::SansRegular.bytes(),
"BoundarySans".into(),
)
.unwrap();
face.buzz = None;
let text = "A\u{2011}é";
let shaped = face.shape_kern(text, 12.0, true);
assert_eq!(shaped.len(), 3);
assert_eq!(shaped[1].0, face.glyph('-'));
for (ch, (_, width)) in text.chars().zip(&shaped) {
assert_eq!(*width, face.advance_pt(ch, 12.0));
}
assert_eq!(face.glyph_texts(text, true), ["A", "-", "é"]);
assert_eq!(face.shape("", 12.0), []);
assert_eq!(face.glyph_texts("", false), Vec::<String>::new());
assert_eq!(
face.width_pt_kern(text, 12.0, true),
shaped.iter().map(|(_, w)| *w).sum::<f32>()
);
assert_eq!(face.advance_pt('漢', 12.0), 12.0 + word_device_track(12.0));
assert_eq!(face.symbol_stand_in('A'), None);
assert_eq!(face.symbol_stand_in('\u{f001}'), None);
assert_eq!(face.symbol_stand_in('\u{f09f}'), Some('•'));
face.symbol_slot = true;
assert_eq!(face.symbol_stand_in('\u{f061}'), Some('α'));
assert_eq!(face.symbol_stand_in('\u{f060}'), None);
assert!(Face::from_bytes(FaceId::SansRegular, b"not a font", "bad".into()).is_none());
}
#[test]
fn extraction_refuses_invalid_collection_offsets_and_preserves_table_padding() {
assert_eq!(ttc_face_bytes(b"", 0), None);
assert_eq!(ttc_face_bytes(b"not a collection", 0), None);
let mut ttc = b"ttcf".to_vec();
ttc.extend_from_slice(&0x00010000u32.to_be_bytes());
ttc.extend_from_slice(&1u32.to_be_bytes());
ttc.extend_from_slice(&16u32.to_be_bytes());
ttc.extend_from_slice(&0x00010000u32.to_be_bytes());
ttc.extend_from_slice(&1u16.to_be_bytes());
ttc.extend_from_slice(&[0; 6]);
ttc.extend_from_slice(b"test");
ttc.extend_from_slice(&0u32.to_be_bytes());
ttc.extend_from_slice(&44u32.to_be_bytes());
ttc.extend_from_slice(&3u32.to_be_bytes());
ttc.extend_from_slice(&[1, 2, 3]);
let extracted = ttc_face_bytes(&ttc, 0).unwrap();
assert_eq!(&extracted[12..16], b"test");
assert_eq!(
u32::from_be_bytes(extracted[20..24].try_into().unwrap()),
28
);
assert_eq!(&extracted[28..], &[1, 2, 3, 0]);
assert_eq!(ttc_face_bytes(&ttc[..46], 0), None);
ttc[12..16].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(ttc_face_bytes(&ttc, 0), None);
}
#[test]
fn windows_font_directories_use_injected_environment_and_ignore_empty_values() {
use std::ffi::OsString;
assert_eq!(
windows_font_dirs_from(|_| None),
[PathBuf::from(r"C:\Windows").join("Fonts")]
);
let env = |key: &str| match key {
"WINDIR" => Some(OsString::new()),
"SystemRoot" => Some(OsString::from("system")),
"LOCALAPPDATA" => Some(OsString::from("user")),
_ => None,
};
assert_eq!(
windows_font_dirs_from(env),
[
PathBuf::from("system/Fonts"),
PathBuf::from("user/Microsoft/Windows/Fonts")
]
);
assert!(windows_fonts_dir(Path::new("some/WINDOWS/fonts")));
assert!(!windows_fonts_dir(Path::new("some/fonts")));
assert!(!windows_fonts_dir(Path::new("Windows/Other")));
assert!(!windows_fonts_dir(Path::new("")));
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod deeper_boundary_tests {
use super::*;
// Coverage: not measured for lines or branches (execution prohibited).
// Missed outcomes targeted in the supplied audit, after summing duplicate rows:
// 356:F, 400:T, 1002/29:F, 1137/34:F, 1235:T, 1348:T,
// 1514/35:F, 1519:T, 1523:T, 1611:T, 1623:T, 1624:T, 1682:T,
// 1878/12:T, 1878/40:T, 1952:F, 3076/16:T, 3188/12:T,
// 3188/27:T, 3188/60:F, 3271:F, 3478:F, 3494:T, 3518/44:T,
// 3582/46:F, 3582/59:T, 3582/59:F. These are targets, not measured gains.
// These fixtures mutate bundled bytes in memory; no catalogue or file lookup.
pub(super) fn table_record(bytes: &[u8], tag: &[u8; 4]) -> usize {
let count = usize::from(u16::from_be_bytes(bytes[4..6].try_into().unwrap()));
(0..count)
.map(|i| 12 + 16 * i)
.find(|&at| &bytes[at..at + 4] == tag)
.expect("bundled fixture table")
}
fn table_offset(bytes: &[u8], tag: &[u8; 4]) -> usize {
let at = table_record(bytes, tag);
u32::from_be_bytes(bytes[at + 8..at + 12].try_into().unwrap()) as usize
}
fn replace_table(bytes: &mut Vec<u8>, tag: &[u8; 4], data: &[u8]) {
let at = table_record(bytes, tag);
while !bytes.len().is_multiple_of(4) {
bytes.push(0);
}
let offset = u32::try_from(bytes.len()).unwrap();
bytes.extend_from_slice(data);
bytes[at + 8..at + 12].copy_from_slice(&offset.to_be_bytes());
bytes[at + 12..at + 16].copy_from_slice(&u32::try_from(data.len()).unwrap().to_be_bytes());
}
fn utf16(text: &str) -> Vec<u8> {
text.encode_utf16().flat_map(u16::to_be_bytes).collect()
}
// OpenType name records use the dependency's documented UTF-16BE encoding.
pub(super) fn set_names(bytes: &mut Vec<u8>, records: &[(u16, u16, u16, Vec<u8>)]) {
let mut table = vec![0, 0];
table.extend_from_slice(&u16::try_from(records.len()).unwrap().to_be_bytes());
table.extend_from_slice(&u16::try_from(6 + 12 * records.len()).unwrap().to_be_bytes());
let mut strings = Vec::new();
for (platform, encoding, id, text) in records {
for value in [
*platform,
*encoding,
0,
*id,
u16::try_from(text.len()).unwrap(),
u16::try_from(strings.len()).unwrap(),
] {
table.extend_from_slice(&value.to_be_bytes());
}
strings.extend_from_slice(text);
}
table.extend_from_slice(&strings);
replace_table(bytes, b"name", &table);
}
fn metric_fixture() -> Vec<u8> {
let mut bytes = FaceId::SansRegular.bytes().to_vec();
let head = table_offset(&bytes, b"head");
bytes[head + 18..head + 20].copy_from_slice(&1000u16.to_be_bytes());
for (offset, value) in [(36, 0i16), (38, -300), (40, 1100), (42, 1400)] {
bytes[head + offset..head + offset + 2].copy_from_slice(&value.to_be_bytes());
}
let hhea = table_offset(&bytes, b"hhea");
for (offset, value) in [(4, 1000i16), (6, -200), (8, 100)] {
bytes[hhea + offset..hhea + offset + 2].copy_from_slice(&value.to_be_bytes());
}
let os2 = table_offset(&bytes, b"OS/2");
for (offset, value) in [
(0, 4u16),
(2, 500),
(4, 400),
(6, 5),
(62, 64),
(68, 900),
(70, (-100i16) as u16),
(72, 50),
(74, 900),
(76, 200),
] {
bytes[os2 + offset..os2 + offset + 2].copy_from_slice(&value.to_be_bytes());
}
bytes[os2 + 78..os2 + 82].copy_from_slice(&0u32.to_be_bytes());
let post = table_offset(&bytes, b"post");
bytes[post + 4..post + 8].copy_from_slice(&0i32.to_be_bytes());
set_names(
&mut bytes,
&[
(3, 1, 1, utf16("BoundaryFamily")),
(3, 1, 2, utf16("Regular")),
(3, 1, 6, utf16("BoundaryFamily-Regular")),
],
);
bytes
}
fn report(requested: &str, physical: &str, step: FontStep) -> FontReportEntry {
FontReportEntry {
requested: requested.into(),
physical: physical.into(),
step,
bold: false,
italic: false,
synthetic: false,
}
}
#[test]
fn open_fallback_reports_require_a_nonempty_matching_family() {
for (requested, physical, substituted) in [
("", "Carlito", true),
(" - ", "Carlito", true),
("''", "Carlito", true),
("Carlito", "LiberationSans-Regular", true),
(" ' CaR LiTo ' ", "Carlito-BoldItalic", false),
("Carlito, serif", "Carlito-Regular", false),
("\"Carlito\", serif", "Carlito-Regular", true),
("Carlito", "", true),
] {
let entry = report(requested, physical, FontStep::OpenFallback);
assert_eq!(
entry.substituted(),
substituted,
"{requested:?} {physical:?}"
);
assert_eq!(entry.physical_is_requested_family(), !substituted);
}
}
#[test]
fn json_escapes_controls_without_corrupting_unicode_or_punctuation() {
assert_eq!(
json_string("\0\u{0008}\u{000b}\u{000c}\u{001f}\u{007f}\u{0085}\"\\\n\r\t漢"),
r#""\u0000\u0008\u000b\u000c\u001f\u007f\u0085\"\\\n\r\t漢""#,
);
assert_eq!(sanitize_pdf_name("A-Z+9 /#é\0"), "A-Z+9-----");
let entries = [
report("\u{001f}", "A+B", FontStep::OpenFallback),
report("\n", "X-Y", FontStep::Embedded),
];
assert_eq!(
font_report_json(&entries),
concat!(
"[{\"requested\":\"\\u001f\",\"step\":\"open_fallback\",\"physical\":\"A+B\",",
"\"bold\":false,\"italic\":false,\"synthetic\":false,\"substituted\":true},",
"{\"requested\":\"\\n\",\"step\":\"embedded\",\"physical\":\"X-Y\",",
"\"bold\":false,\"italic\":false,\"synthetic\":false,\"substituted\":false}]",
)
);
}
#[test]
fn unmatched_single_quotes_and_quoted_lists_stop_before_font_discovery() {
for (input, token) in [
("'", "'"),
("\"", "\""),
(" '' ", ""),
("\"\"", ""),
("'Arial\", serif", "'Arial\""),
("\"Arial', serif", "\"Arial'"),
] {
assert_eq!(family_token(input), token, "{input:?}");
}
for input in ["'", "\"", "'Arial', serif", "\"Arial\", serif"] {
assert!(!Fonts::is_installed_family(input), "{input:?}");
}
}
#[test]
fn east_asian_width_ranges_include_only_their_documented_endpoints() {
for (start, end) in [
(0x1100, 0x115f),
(0x2e80, 0x303e),
(0x3041, 0x33ff),
(0x3400, 0x4dbf),
(0x4e00, 0x9fff),
(0xa960, 0xa97f),
(0xac00, 0xd7a3),
(0xf900, 0xfaff),
(0xfe30, 0xfe4f),
(0xff01, 0xff60),
(0xffe0, 0xffe6),
(0x20000, 0x3fffd),
] {
assert!(east_asian_wide(char::from_u32(start).unwrap()));
assert!(east_asian_wide(char::from_u32(end).unwrap()));
}
// 33ff/3400 touch, so their shared boundary is deliberately wide.
for outside in [
0x10ff, 0x1160, 0x2e7f, 0x303f, 0x3040, 0x4dc0, 0x4dff, 0xa000, 0xa95f, 0xa980, 0xabff,
0xd7a4, 0xf8ff, 0xfb00, 0xfe2f, 0xfe50, 0xff00, 0xff61, 0xffdf, 0xffe7, 0x1ffff,
0x3fffe,
] {
assert!(
!east_asian_wide(char::from_u32(outside).unwrap()),
"{outside:x}"
);
}
let face = Face::bundled(FaceId::SansRegular);
assert_eq!(face.glyph('🦀'), 0);
assert_eq!(
face.advance_pt('🦀', 12.0),
f32::from(face.widths[0]) * 12.0 / face.upem
);
}
#[test]
fn repeated_shaping_clusters_attach_text_to_the_first_glyph_only() {
let face = Face::bundled(FaceId::SansRegular);
let a = face.glyph('A');
let e = face.glyph('é');
let units: ShapedUnits = vec![(e, 100, 0), (a, 0, 0), (a, 100, 2)].into();
face.shaped
.lock()
.unwrap()
.insert(("éA".into(), false), units);
assert_eq!(face.glyph_texts("éA", false), ["é", "", "A"]);
let rtl: ShapedUnits = vec![(a, 100, 2), (e, 100, 0), (a, 0, 0)].into();
face.shaped.lock().unwrap().insert(("éA".into(), true), rtl);
assert_eq!(face.glyph_texts("éA", true), ["A", "é", ""]);
}
#[test]
fn shaping_cache_clears_only_above_fifty_thousand_entries() {
for (initial, expected) in [(49_999, 50_000), (50_000, 50_001), (50_001, 1)] {
let face = Face::bundled(FaceId::SansRegular);
let empty: ShapedUnits = Vec::new().into();
let entries =
(0..initial).map(|i| ((format!("reserved-{i}"), false), Arc::clone(&empty)));
let mut cache = face.shaped.lock().unwrap();
for (key, units) in entries {
cache.insert(key, units);
}
drop(cache);
let shaped = face.shape("A", 12.0);
assert_eq!(
shaped,
vec![(
face.glyph('A'),
f32::from(face.widths[usize::from(face.glyph('A'))]) / face.upem * 12.0
)]
);
let cache = face.shaped.lock().unwrap();
assert_eq!(cache.len(), expected, "initial={initial}");
assert_eq!(
cache.get(&("reserved-0".to_string(), false)).is_some(),
initial <= 50_000
);
assert_eq!(cache.get(&("A".to_string(), false)).unwrap().len(), 1);
}
}
#[test]
fn name_record_decoding_obeys_the_library_platform_and_encoding_contract() {
for (platform, encoding, bytes, expected) in [
(
ttf_parser::PlatformId::Macintosh,
0,
b"Boundary".as_slice(),
Some("Boundary"),
),
(
ttf_parser::PlatformId::Macintosh,
1,
b"Boundary".as_slice(),
None,
),
(ttf_parser::PlatformId::Macintosh, 0, &[0x80], None),
(
ttf_parser::PlatformId::Windows,
1,
&[0, b'A', 0x6f, 0x22],
Some("A漢"),
),
(ttf_parser::PlatformId::Unicode, 0, &[0, b'B'], Some("B")),
(ttf_parser::PlatformId::Windows, 1, &[0xd8, 0], None),
(
ttf_parser::PlatformId::Windows,
2,
b"Boundary".as_slice(),
None,
),
] {
let record = ttf_parser::name::Name {
platform_id: platform,
encoding_id: encoding,
language_id: 0,
name_id: ttf_parser::name_id::FAMILY,
name: bytes,
};
assert_eq!(name_text(&record).as_deref(), expected);
}
}
#[test]
fn family_ranking_distinguishes_typographic_names_and_weight_boundaries() {
for (weight, bold, width, expected) in [
(349, false, 5, 1),
(350, false, 5, 0),
(450, false, 5, 0),
(451, false, 5, 1),
(649, true, 5, 1),
(650, true, 5, 0),
(750, true, 5, 0),
(751, true, 5, 1),
(400, false, 4, 2),
(400, false, 6, 2),
(451, false, 4, 3),
] {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 4..os2 + 6].copy_from_slice(&u16::to_be_bytes(weight));
bytes[os2 + 6..os2 + 8].copy_from_slice(&u16::to_be_bytes(width));
bytes[os2 + 62..os2 + 64]
.copy_from_slice(&(if bold { 32u16 } else { 64 }).to_be_bytes());
set_names(
&mut bytes,
&[
(3, 1, 1, utf16("BoundaryFamily")),
(3, 1, 16, utf16("TypographicBoundary")),
],
);
assert_eq!(
face_family_style(&bytes, "boundaryfamily"),
Some((expected, (bold, false)))
);
assert_eq!(
face_family_style(&bytes, "TypographicBoundary"),
Some((expected + 4, (bold, false)))
);
assert_eq!(face_family_style(&bytes, "MissingBoundary"), None);
}
}
#[test]
fn slant_requires_an_italic_name_or_absent_os2_when_style_bits_are_clear() {
for (name, angle, os2_present, italic) in [
("Regular", 0i32, true, false),
("Regular", -16, true, false),
("Italic", 0, true, false),
("Italic", -16, true, true),
("OBLIQUE", -16, true, true),
("Regular", -16, false, true),
("Regular", 0, false, false),
] {
let mut bytes = metric_fixture();
let post = table_offset(&bytes, b"post");
bytes[post + 4..post + 8].copy_from_slice(&(angle * 65_536).to_be_bytes());
if !os2_present {
replace_table(&mut bytes, b"OS/2", &[]);
}
set_names(
&mut bytes,
&[(3, 1, 1, utf16("BoundaryFamily")), (3, 1, 17, utf16(name))],
);
assert_eq!(
face_family_style(&bytes, "BoundaryFamily"),
Some((0, (false, italic))),
"{name} {angle} {os2_present}"
);
}
}
#[test]
fn metric_tables_select_hhea_typo_helvetica_and_east_asian_lines() {
for (name, os2_present, typo, page, cloud, expected) in [
(
"BoundaryFamily",
true,
false,
0,
false,
(1300.0, 200.0, 1100.0),
),
("Helvetica", false, false, 0, false, (1300.0, 200.0, 1000.0)),
(
"Helvetica-Bold",
true,
false,
0,
false,
(1200.0, 200.0, 1000.0),
),
(
"BoundaryFamily",
true,
true,
0,
false,
(1050.0, 100.0, 950.0),
),
(
"BoundaryFamily",
true,
false,
1 << 17,
false,
(1560.0, 380.0, 1180.0),
),
(
"BoundaryFamily",
true,
false,
1 << 17,
true,
(2210.0, 555.0, 1655.0),
),
] {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 62..os2 + 64]
.copy_from_slice(&(if typo { 192u16 } else { 64 }).to_be_bytes());
bytes[os2 + 78..os2 + 82].copy_from_slice(&u32::to_be_bytes(page));
if cloud {
set_names(&mut bytes, &[(3, 1, 5, utf16("Version 1.03;O365"))]);
}
if !os2_present {
replace_table(&mut bytes, b"OS/2", &[]);
}
let face = Face::from_bytes(FaceId::SansRegular, &bytes, name.into()).unwrap();
assert_eq!(
(
face.single_line_pt(1000.0),
face.line_descent_pt(1000.0),
face.ascent_pt(1000.0)
),
expected,
"{name} {os2_present} {typo} {page} {cloud}"
);
assert_eq!(face.east_asian, page != 0);
assert_eq!(face.pdf_bbox_1000(), [0, -300, 1100, 1400]);
assert_eq!(face.pdf_ascent_1000(), expected.2 as i32);
}
}
#[test]
fn panose_average_width_and_code_pages_have_exact_numeric_boundaries() {
for (family, serif, expected) in [
(1, 2, false),
(2, 1, false),
(2, 2, true),
(2, 10, true),
(2, 11, false),
(3, 10, false),
] {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 32..os2 + 34].copy_from_slice(&[family, serif]);
let parsed = ttf_parser::Face::parse(&bytes, 0).unwrap();
assert_eq!(panose_serif(&parsed), expected);
}
for (width, expected) in [
(-1i16, None),
(0, None),
(1, Some(1.0)),
(i16::MAX, Some(32767.0)),
] {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 2..os2 + 4].copy_from_slice(&width.to_be_bytes());
assert_eq!(
avg_char_width(&ttf_parser::Face::parse(&bytes, 0).unwrap()),
expected
);
let face =
Face::from_bytes(FaceId::SansRegular, &bytes, "BoundaryFamily".into()).unwrap();
assert_eq!(face.avg_char_width, expected.map_or(0.5, |w| w / 1000.0));
}
for bit in [16, 17, 18, 19, 20, 21, 22] {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 78..os2 + 82].copy_from_slice(&(1u32 << bit).to_be_bytes());
assert_eq!(
cjk_code_pages(&ttf_parser::Face::parse(&bytes, 0).unwrap()),
(17..=21).contains(&bit)
);
}
}
#[test]
fn embedded_faces_answer_family_properties_and_invalidate_catalogue_slots() {
let mut bytes = metric_fixture();
let os2 = table_offset(&bytes, b"OS/2");
bytes[os2 + 78..os2 + 82].copy_from_slice(&(1u32 << 17).to_be_bytes());
let mut fonts = Fonts::new();
fonts.insert_embedded("LatinBoundary", false, false, FaceId::SansRegular.bytes());
fonts.insert_embedded("AsianBoundary", false, false, &bytes);
assert!(fonts.family_is_latin_only("LatinBoundary"));
assert!(!fonts.family_is_east_asian("LatinBoundary"));
assert!(!fonts.family_is_latin_only("AsianBoundary"));
assert!(fonts.family_is_east_asian("AsianBoundary"));
assert_eq!(fonts.east_asia_avg_em("AsianBoundary"), Some(0.5));
let key = FaceKey {
family: "ASIANBOUNDARY".into(),
bold: true,
italic: true,
};
assert_eq!(fonts.get_key(&key).pdf_name(), "BoundaryFamily-Regular");
fonts
.catalogue_slots
.lock()
.unwrap()
.insert(FaceId::CarlitoRegular, FaceRef::Embedded(0));
fonts.insert_embedded("Calibri", false, false, &bytes);
assert!(fonts.catalogue_slots.lock().unwrap().is_empty());
assert_eq!(
fonts.catalogue_slot(FaceId::CarlitoRegular),
FaceRef::Embedded(2)
);
assert_eq!(
fonts.catalogue_slot(FaceId::CarlitoRegular),
FaceRef::Embedded(2)
);
assert_eq!(
fonts.get(FaceId::CarlitoRegular).pdf_name(),
"BoundaryFamily-Regular"
);
}
#[test]
fn cjk_name_boundaries_and_charsets_choose_the_matching_in_memory_fallback() {
let mut fonts = Fonts::new();
for (i, family) in [
CJK_FALLBACK,
CJK_FALLBACK_JA,
CJK_FALLBACK_KO,
CJK_FALLBACK_KO_SERIF,
]
.into_iter()
.enumerate()
{
fonts.extra_index.insert(
FaceKey {
family: family.into(),
bold: false,
italic: false,
},
u16::try_from(i).unwrap(),
);
}
let empty = super::super::font_table::FontTable::default();
for (family, expected) in [
("LatinBoundary", None),
("漢", Some(0)),
("漢\u{303f}", Some(0)),
("漢\u{3040}", Some(1)),
("漢\u{30ff}", Some(1)),
("漢\u{3100}", Some(0)),
("漢\u{ff65}", Some(0)),
("漢\u{ff66}", Some(1)),
("漢\u{ff9f}", Some(1)),
("漢\u{ffa0}", Some(0)),
("漢\u{abff}", Some(0)),
("漢\u{ac00}", Some(2)),
("漢\u{d7a3}", Some(2)),
("漢\u{d7a4}", Some(0)),
("漢\u{10ff}", Some(0)),
("漢\u{1100}", Some(2)),
("漢\u{11ff}", Some(2)),
("漢\u{1200}", Some(0)),
("漢\u{3040}\u{ac00}", Some(1)),
] {
assert_eq!(
fonts.cjk_fallback_index(family, false, &empty),
expected,
"{family}"
);
assert_eq!(
fonts.cjk_fallback_index(family, true, &empty),
expected,
"bold {family}"
);
}
for (charset, class, expected) in [
("80", "roman", 1),
("81", "roman", 3),
("81", "swiss", 2),
("86", "roman", 0),
("88", "swiss", 0),
] {
let xml = format!(
r#"<w:fonts xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:font w:name="LatinBoundary"><w:charset w:val="{charset}"/><w:family w:val="{class}"/></w:font></w:fonts>"#
);
let table = super::super::font_table::parse_font_table_xml(&xml);
assert_eq!(
fonts.cjk_fallback_index("LatinBoundary", false, &table),
Some(expected)
);
}
}
fn empty_entry() -> IndexEntry {
IndexEntry {
dirs: Vec::new(),
faces: Vec::new(),
}
}
#[test]
fn index_serialization_rejects_unrepresentable_keys_and_paths() {
let header = format!("{FONT_INDEX_HEADER}\n");
for bad in ['\t', '\n', '\r', ITEM_SEP] {
let entries = HashMap::from([(format!("a{bad}b"), empty_entry())]);
assert_eq!(format_font_index(&entries), header);
}
for bad in ['\t', '\n', '\r', ITEM_SEP, FIELD_SEP] {
let path = PathBuf::from(format!("a{bad}b"));
for entry in [
IndexEntry {
dirs: vec![(path.clone(), None)],
faces: Vec::new(),
},
IndexEntry {
dirs: Vec::new(),
faces: vec![IndexedFace {
style: (false, false),
source: FaceSource {
path: path.clone(),
index: None,
},
stamp: None,
}],
},
] {
assert_eq!(
format_font_index(&HashMap::from([("clean".into(), entry)])),
header
);
}
}
let entries = HashMap::from([("z".into(), empty_entry()), ("a".into(), empty_entry())]);
assert_eq!(
format_font_index(&entries),
format!("{FONT_INDEX_HEADER}\na\t\t\nz\t\t\n")
);
}
#[cfg(unix)]
#[test]
fn index_serialization_omits_non_unicode_paths_instead_of_lossy_encoding() {
use std::os::unix::ffi::OsStringExt;
let path = PathBuf::from(std::ffi::OsString::from_vec(vec![b'a', 0xff]));
let entries = HashMap::from([(
"clean".into(),
IndexEntry {
dirs: vec![(path, None)],
faces: Vec::new(),
},
)]);
assert_eq!(
format_font_index(&entries),
format!("{FONT_INDEX_HEADER}\n")
);
}
#[test]
fn malformed_index_records_do_not_discard_other_valid_records() {
for malformed in [
"bad",
"bad\t",
"bad\t\t\textra",
"bad\tdir\t",
"bad\tdir\u{1f}1\u{1f}extra\t",
"bad\t\tfile\u{1f}0",
"bad\t\tfile\u{1f}0\u{1f}1\u{1f}0\u{1f}10\u{1f}20\u{1f}extra",
] {
let text = format!("{FONT_INDEX_HEADER}\n{malformed}\ngood\t\t\n");
assert_eq!(
parse_font_index(&text),
HashMap::from([("good".into(), empty_entry())]),
"{malformed:?}"
);
}
for (index, length, time, expected_index, expected_stamp) in [
(
"4294967295",
"18446744073709551615",
"20",
Some(u32::MAX),
Some((u64::MAX, 20)),
),
("4294967296", "10", "20", None, Some((10, 20))),
("-", "18446744073709551616", "20", None, None),
("bad", "10", "bad", None, None),
] {
let text = format!(
"{FONT_INDEX_HEADER}\nk\t\tf\u{1f}{index}\u{1f}1\u{1f}0\u{1f}{length}\u{1f}{time}\n"
);
let entries = parse_font_index(&text);
assert_eq!(
entries["k"].faces,
vec![IndexedFace {
style: (true, false),
source: FaceSource {
path: "f".into(),
index: expected_index
},
stamp: expected_stamp,
}]
);
}
}
#[test]
fn unstamped_index_faces_are_rejected_before_any_filesystem_access() {
let entry = IndexEntry {
dirs: Vec::new(),
faces: vec![IndexedFace {
style: (true, true),
source: FaceSource {
path: "never-accessed.ttf".into(),
index: None,
},
stamp: None,
}],
};
assert_eq!(entry.load(), None);
assert_eq!(empty_entry().load(), Some(Vec::new()));
let mut index = FontIndex::load(None);
index.record("empty", &[], &Vec::new());
assert_eq!(index.path, None);
assert_eq!(
index.entries,
HashMap::from([("empty".into(), empty_entry())])
);
}
#[test]
fn embedded_rejection_preserves_existing_faces_and_slot_cache() {
let mut fonts = Fonts::new();
fonts.insert_embedded("KeepBoundary", false, false, FaceId::SansRegular.bytes());
fonts
.catalogue_slots
.lock()
.unwrap()
.insert(FaceId::CarlitoRegular, FaceRef::Embedded(0));
let mut missing_outlines = metric_fixture();
let record = table_record(&missing_outlines, b"glyf");
missing_outlines[record + 8..record + 12].copy_from_slice(&u32::MAX.to_be_bytes());
for rejected in [b"invalid sfnt".as_slice(), missing_outlines.as_slice()] {
fonts.insert_embedded("RejectedBoundary", true, true, rejected);
assert_eq!(fonts.extra.len(), 1);
assert_eq!(fonts.extra_index.len(), 1);
assert_eq!(fonts.embedded_index("RejectedBoundary", true, true), None);
assert_eq!(
fonts
.catalogue_slots
.lock()
.unwrap()
.get(&FaceId::CarlitoRegular),
Some(&FaceRef::Embedded(0))
);
}
}
#[test]
fn absent_name_table_uses_the_embedded_family_as_a_sanitized_pdf_name() {
let mut bytes = metric_fixture();
replace_table(&mut bytes, b"name", &[]);
assert_eq!(ttf_postscript_name(&bytes), None);
let mut fonts = Fonts::new();
fonts.insert_embedded("Boundary + Face", false, false, &bytes);
assert_eq!(
fonts.embedded_index("Boundary + Face", false, false),
Some(0)
);
assert_eq!(fonts.extra[0].pdf_name(), "Boundary-+-Face");
assert_eq!(fonts.extra[0].bytes(), bytes.as_slice());
}
#[test]
fn poisoned_shape_caches_do_not_change_glyphs_or_character_ownership() {
for poison_plan in [false, true] {
for poison_shape in [false, true] {
let face = Face::bundled(FaceId::SansRegular);
if poison_plan {
assert!(
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = face.plans.lock().unwrap();
panic!("interrupted plan insertion");
}))
.is_err()
);
}
if poison_shape {
assert!(
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let _guard = face.shaped.lock().unwrap();
panic!("interrupted shape insertion");
}))
.is_err()
);
}
for text in ["ABC", "éßΩ", "A漢🙂Z"] {
for kern in [false, true] {
let expected =
Face::bundled(FaceId::SansRegular).shape_kern(text, 12.0, kern);
assert_eq!(face.shape_kern(text, 12.0, kern), expected);
assert_eq!(face.shape_kern(text, 12.0, kern), expected);
assert_eq!(face.glyph_texts(text, kern).concat(), text);
}
}
}
}
}
#[test]
fn collections_preserve_independent_tables_and_reject_truncated_directories() {
let mut collection = b"ttcf".to_vec();
collection.extend_from_slice(&0x00010000u32.to_be_bytes());
collection.extend_from_slice(&2u32.to_be_bytes());
collection.extend_from_slice(&20u32.to_be_bytes());
collection.extend_from_slice(&64u32.to_be_bytes());
// Two sfnt records share an odd-length table; extraction must align
// each standalone result without changing its original bytes.
for offset in [20usize, 64] {
collection.resize(offset, 0);
collection.extend_from_slice(&0x00010000u32.to_be_bytes());
collection.extend_from_slice(&1u16.to_be_bytes());
collection.extend_from_slice(&[0; 6]);
collection.extend_from_slice(b"test");
collection.extend_from_slice(&123u32.to_be_bytes());
collection.extend_from_slice(&100u32.to_be_bytes());
collection.extend_from_slice(&3u32.to_be_bytes());
}
collection.resize(100, 0);
collection.extend_from_slice(&[8, 9, 10]);
for index in [0, 1] {
let out = ttc_face_bytes(&collection, index).unwrap();
assert_eq!(out.len(), 32);
assert_eq!(&out[12..20], b"test\0\0\0{");
assert_eq!(&out[20..24], &28u32.to_be_bytes());
assert_eq!(&out[28..], &[8, 9, 10, 0]);
}
for length in [0, 3, 12, 15, 19, 23, 25, 31, 39, 43, 47, 99, 100, 102] {
assert_eq!(
ttc_face_bytes(&collection[..length], 0),
None,
"truncated at {length}"
);
}
let mut bad = collection.clone();
bad[40..44].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(ttc_face_bytes(&bad, 0), None);
assert!(
ttc_face_bytes(&bad, 1).is_some(),
"a corrupt neighboring face must not prevent extracting a valid face"
);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod residual_embedded_style_contract_tests {
use super::*;
#[test]
fn quartz_device_size_windows_keep_linear_glyph_advance_outside_the_window() {
let bytes = FaceId::CarlitoRegular.bytes();
let raw = ttf_parser::Face::parse(bytes, 0).unwrap();
let face = Face::from_bytes(FaceId::CarlitoRegular, bytes, "MemoryCarlito".into()).unwrap();
let gid = raw.glyph_index('M').unwrap();
let units = f32::from(raw.glyph_hor_advance(gid).unwrap());
for (center, ppem, tracking) in [(11.04_f32, 46.0, -0.0015), (16.08, 67.0, -0.0018)] {
for offset in [-0.03_f32, -0.01, 0.0, 0.01, 0.03] {
let size = center + offset;
let inside = offset.abs() < 0.02;
let expected_track = if inside { tracking * size } else { 0.0 };
assert_eq!(word_device_track(size), expected_track);
assert_eq!(word_device_paint(size), inside.then_some((ppem, tracking)));
let expected = units * size / f32::from(raw.units_per_em()) + expected_track;
assert!((face.advance_pt('M', size) - expected).abs() < 0.00001);
}
}
assert_eq!(face.pdf_name(), "MemoryCarlito");
assert_eq!(face.glyph('M'), gid.0);
assert_eq!(bytes, FaceId::CarlitoRegular.bytes());
}
#[test]
fn four_embedded_style_slots_preserve_requested_names_and_physical_font_identity() {
let mut fonts = Fonts::new();
let styles = [
(false, false, FaceId::CarlitoRegular, "Carlito"),
(true, false, FaceId::CarlitoBold, "Carlito-Bold"),
(false, true, FaceId::CarlitoItalic, "Carlito-Italic"),
(true, true, FaceId::CarlitoBoldItalic, "Carlito-BoldItalic"),
];
for &(bold, italic, id, _) in &styles {
fonts.insert_embedded("Memory Stylist", bold, italic, id.bytes());
}
let table = super::super::font_table::FontTable::default();
for (index, &(bold, italic, id, physical)) in styles.iter().enumerate() {
let requested = "MeMoRy StYlIsT, ignored-family";
let (slot, report) = fonts.classify_in(requested, bold, italic, &table);
assert_eq!(slot, FaceRef::Embedded(index as u16));
assert_eq!(
report,
FontReportEntry {
requested: requested.into(),
step: FontStep::Embedded,
physical: physical.into(),
bold,
italic,
synthetic: false,
}
);
let quoted = "\"MeMoRy StYlIsT\"";
let (quoted_slot, quoted_report) = fonts.classify_in(quoted, bold, italic, &table);
assert_eq!(quoted_slot, slot);
assert_eq!(
quoted_report,
FontReportEntry {
requested: quoted.into(),
..report.clone()
}
);
assert_eq!(
family_token("\"MeMoRy StYlIsT\", ignored-family"),
"\"MeMoRy StYlIsT\""
);
assert!(!report.substituted());
let raw = ttf_parser::Face::parse(id.bytes(), 0).unwrap();
assert_eq!(fonts.get(slot).glyph('g'), raw.glyph_index('g').unwrap().0);
assert_eq!(
face_family_style(id.bytes(), "carlito"),
Some((0, (bold, italic)))
);
assert!(face_family_style(id.bytes(), "Unrelated Family").is_none());
}
}
#[test]
fn a_single_embedded_style_answers_every_requested_style_without_host_lookup() {
let styles = [
(false, false, FaceId::MonoRegular, "LiberationMono"),
(true, false, FaceId::MonoBold, "LiberationMono-Bold"),
(false, true, FaceId::MonoItalic, "LiberationMono-Italic"),
(
true,
true,
FaceId::MonoBoldItalic,
"LiberationMono-BoldItalic",
),
];
let table = super::super::font_table::FontTable::default();
for &(available_bold, available_italic, id, physical) in &styles {
let mut fonts = Fonts::new();
fonts.insert_embedded("Only Memory", available_bold, available_italic, id.bytes());
for &(bold, italic, _, _) in &styles {
let (slot, report) = fonts.classify_in("Only Memory", bold, italic, &table);
assert_eq!(slot, FaceRef::Embedded(0));
assert_eq!(
report,
FontReportEntry {
requested: "Only Memory".into(),
step: FontStep::Embedded,
physical: physical.into(),
bold,
italic,
synthetic: (bold || italic)
&& (bold, italic) != (available_bold, available_italic),
}
);
assert!(!report.substituted());
assert_eq!(fonts.get(slot).pdf_name(), physical);
}
// This pure lookup deliberately declines the unknown family;
// resolving it instead would enter the filesystem catalogue.
assert_eq!(fonts.embedded_index("Absent Memory", false, false), None);
}
}
/// Two shaped entries that cannot both fit leave only the later one,
/// an entry larger than the whole budget is not stored, and the next
/// word still fits beside what stays. A face payload that no longer
/// fits is read again; a face inside the budget stays.
#[test]
fn a_cache_past_its_byte_budget_drops_what_no_longer_fits() {
let face = Face::bundled(FaceId::SansRegular);
let glyph = std::mem::size_of::<(u16, i32, u32)>();
let half: ShapedUnits =
vec![(0u16, 0i32, 0u32); MAX_SHAPED_CACHE_BYTES / glyph / 2 + 1].into();
let oversized: ShapedUnits =
vec![(0u16, 0i32, 0u32); MAX_SHAPED_CACHE_BYTES / glyph + 1].into();
let mut cache = face.shaped.lock().unwrap();
cache.insert(("zzzz-a".into(), false), Arc::clone(&half));
cache.insert(("zzzz-b".into(), false), Arc::clone(&half));
cache.insert(("zzzz-c".into(), false), oversized);
drop(cache);
let _ = face.shape("A", 12.0);
let cache = face.shaped.lock().unwrap();
let retained = cache
.map
.values()
.map(shaped_payload_bytes)
.fold(0, usize::saturating_add);
assert_eq!(cache.bytes, retained, "the running total drifted");
assert!(
retained <= MAX_SHAPED_CACHE_BYTES,
"shaped cache kept {retained} bytes past {MAX_SHAPED_CACHE_BYTES}"
);
let held = |key: &str| cache.get(&(key.to_string(), false)).is_some();
assert!(!held("zzzz-a"), "the entry that no longer fit stayed");
assert!(held("zzzz-b"), "the entry that still fits was dropped");
assert!(!held("zzzz-c"), "the oversized shaped entry was stored");
assert!(held("A"), "the next word was not stored");
drop(cache);
let half = MAX_FACE_CACHE_BYTES / 2 + 1;
cached_faces("zzzz-byte-a", || vec![((false, false), vec![1u8; half])]);
cached_faces("zzzz-byte-b", || vec![((false, false), vec![2u8; half])]);
let reloaded = cached_faces("zzzz-byte-a", || {
vec![((false, false), b"reloaded".to_vec())]
});
assert_eq!(
reloaded[0].1.as_ref(),
b"reloaded",
"a face that no longer fit stayed in the cache"
);
let kept = cached_faces("zzzz-byte-b", || {
panic!("a face inside the budget was read again")
});
assert_eq!(kept[0].1.len(), half);
let faces = face_cache().lock().unwrap();
let face_bytes = faces
.map
.values()
.map(shared_payload)
.fold(0, usize::saturating_add);
assert_eq!(faces.bytes, face_bytes, "the running total drifted");
assert!(
face_bytes <= MAX_FACE_CACHE_BYTES,
"face cache kept {face_bytes} bytes"
);
}
/// Replacing a key and clearing keep the running total equal to the
/// bytes the map holds.
#[test]
fn a_bounded_cache_counts_replacements_and_clears() {
let mut cache: BoundedCache<u8, Vec<u8>> = BoundedCache::new(10, Vec::len);
let held =
|cache: &BoundedCache<u8, Vec<u8>>| cache.map.values().map(Vec::len).sum::<usize>();
cache.insert(1, vec![0; 4]);
cache.insert(2, vec![0; 4]);
cache.insert(1, vec![0; 2]);
assert_eq!((cache.bytes, held(&cache)), (6, 6));
cache.insert(3, vec![0; 6]);
assert_eq!(cache.map.keys().copied().collect::<Vec<_>>(), [1, 3]);
assert_eq!((cache.bytes, held(&cache)), (8, 8));
cache.insert(4, vec![0; 11]);
assert_eq!((cache.bytes, cache.get(&4)), (8, None));
cache.clear();
assert_eq!((cache.bytes, cache.len()), (0, 0));
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod memory_discovery_policy_contract_tests {
use super::*;
use std::cell::RefCell;
#[derive(Clone, Debug, Default, PartialEq)]
struct MemoryFiles {
listings: HashMap<PathBuf, Arc<Vec<PathBuf>>>,
bytes: HashMap<PathBuf, Vec<u8>>,
names: HashMap<PathBuf, FontNameIndex>,
}
impl MemoryFiles {
fn directory(&mut self, dir: &str, files: &[&str]) {
let mut paths: Vec<_> = files.iter().map(|f| Path::new(dir).join(f)).collect();
paths.sort();
self.listings.insert(dir.into(), Arc::new(paths));
}
fn font(&mut self, dir: &str, file: &str, id: FaceId) {
self.bytes
.insert(Path::new(dir).join(file), id.bytes().to_vec());
}
fn indexed(&mut self, dir: &str, files: &[(&str, &[&str])]) {
self.names.insert(
dir.into(),
Arc::new(
files
.iter()
.map(|(f, n)| {
(
Path::new(dir).join(f),
n.iter().map(|s| s.to_string()).collect(),
)
})
.collect(),
),
);
}
fn discover(&self, family: &str, dirs: &[(&str, bool)]) -> (SourcedFaces, Vec<PathBuf>) {
let before = self.clone();
let reads = RefCell::new(Vec::new());
let dirs: Vec<_> = dirs
.iter()
.map(|(d, whole)| (PathBuf::from(d), *whole))
.collect();
let result = family_faces_in_with(
family,
&dirs,
|dir| self.listings.get(dir).cloned().unwrap_or_default(),
|path| {
reads.borrow_mut().push(path.to_path_buf());
self.bytes
.get(path)
.cloned()
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::PermissionDenied))
},
|dir| self.names.get(dir).cloned().unwrap_or_default(),
);
assert_eq!(
self, &before,
"discovery mutated source records or payloads"
);
(result, reads.into_inner())
}
}
fn expected(
dir: &str,
file: &str,
id: FaceId,
style: (bool, bool),
) -> ((bool, bool), FaceSource, Vec<u8>) {
(
style,
FaceSource::new(&Path::new(dir).join(file), None),
id.bytes().to_vec(),
)
}
#[test]
fn whole_family_folders_accept_numeric_names_but_still_validate_the_font_family() {
let mut fs = MemoryFiles::default();
fs.directory(
"/memory/cloud",
&["001.TTF", "002.oTf", "003.ttf", "004.bin"],
);
fs.font("/memory/cloud", "001.TTF", FaceId::CarlitoRegular);
fs.font("/memory/cloud", "002.oTf", FaceId::CarlitoBold);
fs.font("/memory/cloud", "003.ttf", FaceId::MonoItalic);
fs.font("/memory/cloud", "004.bin", FaceId::CarlitoItalic);
let (result, reads) = fs.discover("Carlito", &[("/memory/cloud", true)]);
assert_eq!(
result,
vec![
expected(
"/memory/cloud",
"001.TTF",
FaceId::CarlitoRegular,
(false, false)
),
expected(
"/memory/cloud",
"002.oTf",
FaceId::CarlitoBold,
(true, false)
)
]
);
assert_eq!(
reads,
["001.TTF", "002.oTf", "003.ttf"].map(|f| Path::new("/memory/cloud").join(f))
);
let (result, reads) = fs.discover("Carlito", &[("/memory/cloud", false)]);
assert!(result.is_empty());
assert!(reads.is_empty());
let (result, reads) = fs.discover("漢字", &[("/memory/cloud", false)]);
assert!(result.is_empty());
assert!(reads.is_empty());
let (result, reads) = fs.discover("漢字", &[("/memory/cloud", true)]);
assert!(result.is_empty());
assert_eq!(reads.len(), 3);
}
#[test]
fn short_filename_matching_is_allowed_outside_word_but_not_inside_dfonts() {
for dir in ["/memory/system", "/memory/DFonts"] {
let mut fs = MemoryFiles::default();
fs.directory(dir, &["carl.ttf", "carli.ttf", "CarlitoMore.ttf"]);
for file in ["carl.ttf", "carli.ttf", "CarlitoMore.ttf"] {
fs.font(dir, file, FaceId::CarlitoRegular);
}
let (result, reads) = fs.discover("Carlito", &[(dir, false)]);
// Uppercase sorts first; a full key prefix remains eligible in
// Word's folder, whereas only the short candidate is excluded.
assert_eq!(
result,
vec![expected(
dir,
"CarlitoMore.ttf",
FaceId::CarlitoRegular,
(false, false)
)]
);
let mut expected_reads = vec![Path::new(dir).join("CarlitoMore.ttf")];
if dir.ends_with("system") {
expected_reads.push(Path::new(dir).join("carli.ttf"));
}
assert_eq!(reads, expected_reads);
}
}
#[test]
fn unreadable_malformed_and_foreign_fonts_cannot_displace_the_first_valid_style() {
let mut fs = MemoryFiles::default();
fs.directory(
"/memory/system",
&[
"Carlito0.ttf",
"Carlito1.ttf",
"Carlito2.ttf",
"Carlito3.ttf",
"Carlito4.ttf",
],
);
fs.bytes.insert(
"/memory/system/Carlito1.ttf".into(),
b"deliberately invalid sfnt".to_vec(),
);
fs.font("/memory/system", "Carlito2.ttf", FaceId::MonoRegular);
fs.font("/memory/system", "Carlito3.ttf", FaceId::CarlitoRegular);
fs.font("/memory/system", "Carlito4.ttf", FaceId::CarlitoRegular);
let (result, reads) = fs.discover("Carlito", &[("/memory/system", false)]);
assert_eq!(
result,
vec![expected(
"/memory/system",
"Carlito3.ttf",
FaceId::CarlitoRegular,
(false, false)
)]
);
assert_eq!(
reads,
(0..5)
.map(|i| PathBuf::from(format!("/memory/system/Carlito{i}.ttf")))
.collect::<Vec<_>>()
);
}
#[test]
fn windows_name_records_add_abbreviated_styles_without_rereading_direct_matches() {
let dir = "/memory/Windows/Fonts";
let mut fs = MemoryFiles::default();
fs.directory(dir, &["Carlito.ttf", "cltbd.ttf", "notthis.ttf"]);
fs.font(dir, "Carlito.ttf", FaceId::CarlitoRegular);
fs.font(dir, "cltbd.ttf", FaceId::CarlitoBold);
fs.font(dir, "notthis.ttf", FaceId::MonoRegular);
fs.bytes
.insert(Path::new(dir).join("broken.ttf"), b"invalid font".to_vec());
fs.font(dir, "foreign.ttf", FaceId::MonoItalic);
fs.indexed(
dir,
&[
("Carlito.ttf", &["carlito"]),
("cltbd.ttf", &["carlito"]),
("notthis.ttf", &["liberationmono"]),
("denied.ttf", &["carlito"]),
("broken.ttf", &["carlito"]),
("foreign.ttf", &["carlito"]),
],
);
let (result, reads) = fs.discover("Carlito", &[(dir, false)]);
assert_eq!(
result,
vec![
expected(dir, "Carlito.ttf", FaceId::CarlitoRegular, (false, false)),
expected(dir, "cltbd.ttf", FaceId::CarlitoBold, (true, false))
]
);
assert_eq!(
reads,
[
"Carlito.ttf",
"cltbd.ttf",
"denied.ttf",
"broken.ttf",
"foreign.ttf"
]
.map(|f| Path::new(dir).join(f))
);
}
#[test]
fn word_name_index_fallback_runs_only_after_all_direct_discovery_is_empty() {
let word = "/memory/DFonts";
let mut fs = MemoryFiles::default();
fs.directory(word, &["CLT.ttf"]);
fs.font(word, "CLT.ttf", FaceId::CarlitoBold);
fs.font(word, "FOREIGN.ttf", FaceId::MonoRegular);
fs.bytes
.insert(Path::new(word).join("BROKEN.ttf"), b"invalid font".to_vec());
fs.indexed(
word,
&[
("CLT.ttf", &["carlito"]),
("FOREIGN.ttf", &["carlito"]),
("DENIED.ttf", &["carlito"]),
("BROKEN.ttf", &["carlito"]),
("OTHER.ttf", &["unrelated"]),
],
);
let (result, reads) = fs.discover("Carlito", &[(word, false)]);
assert_eq!(
result,
vec![expected(
word,
"CLT.ttf",
FaceId::CarlitoBold,
(true, false)
)]
);
assert_eq!(
reads,
["CLT.ttf", "FOREIGN.ttf", "DENIED.ttf", "BROKEN.ttf"].map(|f| Path::new(word).join(f))
);
fs.directory("/memory/system", &["Carlito.ttf"]);
fs.font("/memory/system", "Carlito.ttf", FaceId::CarlitoRegular);
let (result, reads) = fs.discover("Carlito", &[("/memory/system", false), (word, false)]);
assert_eq!(
result,
vec![expected(
"/memory/system",
"Carlito.ttf",
FaceId::CarlitoRegular,
(false, false)
)]
);
assert_eq!(reads, vec![PathBuf::from("/memory/system/Carlito.ttf")]);
}
pub(super) fn collection(faces: &[FaceId]) -> Vec<u8> {
let mut out = b"ttcf".to_vec();
out.extend_from_slice(&0x00010000_u32.to_be_bytes());
out.extend_from_slice(&(faces.len() as u32).to_be_bytes());
out.resize(12 + 4 * faces.len(), 0);
for (index, id) in faces.iter().enumerate() {
while !out.len().is_multiple_of(4) {
out.push(0);
}
let start = out.len();
out[12 + 4 * index..16 + 4 * index].copy_from_slice(&(start as u32).to_be_bytes());
let mut sfnt = id.bytes().to_vec();
let count = u16::from_be_bytes([sfnt[4], sfnt[5]]) as usize;
for i in 0..count {
let at = 12 + 16 * i + 8;
let old = u32::from_be_bytes(sfnt[at..at + 4].try_into().unwrap());
sfnt[at..at + 4].copy_from_slice(&(old + start as u32).to_be_bytes());
}
out.extend_from_slice(&sfnt);
}
out
}
#[test]
fn collection_faces_keep_indices_and_rank_after_equivalent_single_face_files() {
let dir = "/memory/system";
let mut fs = MemoryFiles::default();
fs.directory(
dir,
&[
"Carlito.ttc",
"CarlitoRegular.ttf",
"Unrelated.ttc",
"Car.ttc",
"Carli.ttc",
],
);
let ttc = collection(&[FaceId::CarlitoRegular, FaceId::CarlitoBold]);
assert_eq!(ttf_parser::fonts_in_collection(&ttc), Some(2));
for (i, id) in [FaceId::CarlitoRegular, FaceId::CarlitoBold]
.iter()
.enumerate()
{
let raw = ttf_parser::Face::parse(&ttc, i as u32).unwrap();
let bundled = ttf_parser::Face::parse(id.bytes(), 0).unwrap();
for ch in ['A', 'g', 'Ω'] {
assert_eq!(raw.glyph_index(ch), bundled.glyph_index(ch));
assert_eq!(
raw.glyph_hor_advance(raw.glyph_index(ch).unwrap()),
bundled.glyph_hor_advance(bundled.glyph_index(ch).unwrap())
);
}
}
fs.bytes
.insert(Path::new(dir).join("Carlito.ttc"), ttc.clone());
fs.bytes.insert(
Path::new(dir).join("Car.ttc"),
b"ttcf\0\x01\0\0\0\0\0\x01\xff\xff\xff\xff".to_vec(),
);
fs.font(dir, "CarlitoRegular.ttf", FaceId::CarlitoRegular);
let bold = ttc_face_bytes(&ttc, 1).unwrap();
let (result, reads) = fs.discover("Carlito", &[(dir, false)]);
assert_eq!(
result,
vec![
expected(
dir,
"CarlitoRegular.ttf",
FaceId::CarlitoRegular,
(false, false)
),
(
(true, false),
FaceSource::new(&Path::new(dir).join("Carlito.ttc"), Some(1)),
bold.clone()
)
]
);
assert_eq!(
reads,
["Car.ttc", "Carli.ttc", "Carlito.ttc", "CarlitoRegular.ttf"]
.map(|f| Path::new(dir).join(f))
);
fs.bytes.remove(&Path::new(dir).join("CarlitoRegular.ttf"));
let (result, _) = fs.discover("Carlito", &[(dir, false)]);
assert_eq!(
result,
vec![
(
(false, false),
FaceSource::new(&Path::new(dir).join("Carlito.ttc"), Some(0)),
ttc_face_bytes(&ttc, 0).unwrap()
),
(
(true, false),
FaceSource::new(&Path::new(dir).join("Carlito.ttc"), Some(1)),
bold
)
]
);
assert_eq!(fs.bytes[&Path::new(dir).join("Carlito.ttc")], ttc);
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod cloud_font_memory_owner_tests {
use super::*;
use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
#[test]
fn cloud_folder_selection_preserves_own_parent_and_localized_source_owners() {
let home = Path::new("/memory/cloud-owner");
let root = home.join("Library/Group Containers/UBF8T346G9.Office/FontCache/4/CloudFonts");
let own = root.join("Script MT Bold");
let entries = Arc::new(vec![
root.join("Sc"),
root.join("Script"),
root.join("Script MT"),
own.clone(),
root.join("Unrelated"),
]);
let scans = RefCell::new(Vec::new());
let listing = |path: &Path| {
scans.borrow_mut().push(path.to_path_buf());
Arc::clone(&entries)
};
let names = |_: &Path| Arc::new(Vec::new());
let no_dirs = |_: &Path| false;
assert_eq!(
cloud_font_dirs_with("Script MT Bold", Some(home), &listing, &no_dirs, &names),
vec![
(own.clone(), true),
(root.join("Script"), true),
(root.join("Script MT"), true)
]
);
assert_eq!(*scans.borrow(), vec![root.clone()]);
scans.borrow_mut().clear();
assert_eq!(
cloud_font_dirs_with(
"Script MT Bold",
Some(home),
&listing,
&|path| path == own,
&names
),
vec![(own, true)]
);
assert!(scans.borrow().is_empty());
assert!(
cloud_font_dirs_with("Script MT Bold", None, &listing, &no_dirs, &names).is_empty()
);
assert!(scans.borrow().is_empty());
let local_own = root.join("华文仿宋");
let local_names = Arc::new(vec![
(
root.join("STFangsong"),
vec!["华文仿宋".into(), "stfangsong".into()],
),
(root.join("Other"), vec!["different".into()]),
]);
let names_scans = RefCell::new(Vec::new());
let local_lookup = |path: &Path| {
names_scans.borrow_mut().push(path.to_path_buf());
Arc::clone(&local_names)
};
assert_eq!(
cloud_font_dirs_with("华文仿宋", Some(home), &listing, &no_dirs, &local_lookup),
vec![(local_own.clone(), true), (root.join("STFangsong"), true)]
);
assert_eq!(*names_scans.borrow(), vec![root.clone()]);
names_scans.borrow_mut().clear();
assert_eq!(
cloud_font_dirs_with(
"华文仿宋",
Some(home),
&listing,
&|path| path == local_own,
&local_lookup
),
vec![(local_own, true)]
);
assert!(names_scans.borrow().is_empty());
assert!(
cloud_font_dirs_with(
"Script MT Bold",
Some(home),
&listing,
&no_dirs,
&local_lookup
)
.iter()
.all(|(p, whole)| *whole && p.starts_with(&root))
);
assert!(
names_scans.borrow().is_empty(),
"Latin family lookup never searches localized name records"
);
}
#[test]
fn cloud_name_scan_uses_first_readable_font_and_keeps_each_folder_source() {
let root = PathBuf::from("/memory/cloud-owner/fonts");
let empty = root.join("Empty");
let invalid = root.join("Invalid");
let denied = root.join("ReadDenied");
let valid = root.join("Valid");
let mono = root.join("ValidMono");
let ignored = root.join("plain-file");
let folders = vec![
empty.clone(),
invalid.clone(),
denied.clone(),
valid.clone(),
mono.clone(),
ignored.clone(),
];
let dirs = HashSet::from([
empty.clone(),
invalid.clone(),
denied.clone(),
valid.clone(),
mono.clone(),
]);
let listing = BTreeMap::from([
(root.clone(), folders.clone()),
(empty.clone(), vec![]),
(
invalid.clone(),
vec![invalid.join("bad.ttf"), invalid.join("later.ttf")],
),
(
denied.clone(),
vec![denied.join("unreadable.ttf"), denied.join("readable.ttf")],
),
(valid.clone(), vec![valid.join("face.ttf")]),
(mono.clone(), vec![mono.join("face.ttf")]),
]);
let carlito = include_bytes!("../../assets/fonts/Carlito-Regular.ttf").to_vec();
let mono_bytes = include_bytes!("../../assets/fonts/LiberationMono-Regular.ttf").to_vec();
let bytes = BTreeMap::from([
(invalid.join("bad.ttf"), vec![0, 1, 2]),
(invalid.join("later.ttf"), carlito.clone()),
(denied.join("readable.ttf"), carlito.clone()),
(valid.join("face.ttf"), carlito),
(mono.join("face.ttf"), mono_bytes),
]);
let frozen = bytes.clone();
let reads = RefCell::new(Vec::new());
let scan = cloud_folder_names_with(
&root,
&|p| Arc::new(listing.get(p).cloned().unwrap_or_default()),
&|p| dirs.contains(p),
&|p| {
reads.borrow_mut().push(p.to_path_buf());
bytes.get(p).cloned()
},
);
assert_eq!(
scan,
vec![
(empty, vec![]),
(invalid.clone(), vec![]),
(denied.clone(), vec!["carlito".into()]),
(valid.clone(), vec!["carlito".into()]),
(mono.clone(), vec!["liberationmono".into()])
]
);
assert_eq!(
*reads.borrow(),
vec![
invalid.join("bad.ttf"),
denied.join("unreadable.ttf"),
denied.join("readable.ttf"),
valid.join("face.ttf"),
mono.join("face.ttf")
]
);
assert_eq!(
bytes, frozen,
"font name extraction retains every owned font byte"
);
assert_eq!(listing[&root], folders, "no folder is reordered or renamed");
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod cjk_memory_discovery_source_contract_tests {
use super::*;
#[test]
fn cjk_font_discovery_preserves_ranked_source_faces_without_host_fonts() {
for (names, family, expected) in [
(vec![(1, "Owned CJK")], "Owned CJK", true),
(vec![(1, "Other"), (16, "Owned CJK")], "Owned CJK", true),
(vec![(1, "Other")], "Owned CJK", false),
] {
for rank in [0, 1] {
for available in [false, true] {
let dir = PathBuf::from("/memory/cjk");
let path = dir.join(if rank == 0 {
"primary.ttf"
} else {
"secondary.OTF"
});
let mut bytes = FaceId::CarlitoBoldItalic.bytes().to_vec();
let records: Vec<_> = names
.iter()
.map(|&(id, text)| {
(
3,
1,
id,
text.encode_utf16().flat_map(u16::to_be_bytes).collect(),
)
})
.collect();
deeper_boundary_tests::set_names(&mut bytes, &records);
let frozen = bytes.clone();
let listing = |folder: &Path| (folder == dir).then(|| vec![path.clone()]);
let read = |source: &Path| (available && source == path).then(|| bytes.clone());
let faces = scan_cjk_family_faces_with(
family,
&["primary", "secondary"],
std::slice::from_ref(&dir),
&listing,
&read,
);
if available && (expected || rank == 0) {
assert_eq!(
faces,
vec![((true, true), FaceSource::new(&path, None), bytes.clone())]
);
let raw = ttf_parser::Face::parse(&faces[0].2, 0).unwrap();
let authored = ttf_parser::Face::parse(&frozen, 0).unwrap();
for character in ['A', 'g', 'Ω'] {
assert_eq!(raw.glyph_index(character), authored.glyph_index(character));
}
} else {
assert!(faces.is_empty());
}
assert_eq!(bytes, frozen);
}
}
}
}
#[test]
fn cjk_collection_discovery_keeps_face_indices_and_skips_invalid_duplicate_sources() {
let first = PathBuf::from("/memory/first");
let second = PathBuf::from("/memory/second");
let missing = PathBuf::from("/memory/missing");
let collection = memory_discovery_policy_contract_tests::collection(&[
FaceId::CarlitoRegular,
FaceId::CarlitoBold,
]);
let mut no_outlines = FaceId::CarlitoItalic.bytes().to_vec();
let offset = deeper_boundary_tests::table_record(&no_outlines, b"glyf");
no_outlines[offset..offset + 4].copy_from_slice(b"none");
let paths = [
first.join("fallback.ttc"),
first.join("corrupt.ttf"),
first.join("missing.ttf"),
first.join("nooutline.ttf"),
first.join("unrelated.ttf"),
first.join("fallback.bin"),
second.join("fallback.ttc"),
];
let bytes = HashMap::from([
(paths[0].clone(), collection.clone()),
(paths[1].clone(), b"invalid sfnt".to_vec()),
(paths[3].clone(), no_outlines),
(paths[4].clone(), FaceId::MonoRegular.bytes().to_vec()),
(paths[5].clone(), FaceId::CarlitoRegular.bytes().to_vec()),
(paths[6].clone(), FaceId::MonoRegular.bytes().to_vec()),
]);
let reads = std::cell::RefCell::new(Vec::new());
let listing = |dir: &Path| {
if dir == missing {
None
} else {
Some(
paths
.iter()
.filter(|path| path.parent() == Some(dir))
.cloned()
.collect(),
)
}
};
let read = |path: &Path| {
reads.borrow_mut().push(path.to_path_buf());
bytes.get(path).cloned()
};
let found = scan_cjk_family_faces_with(
"Carlito",
&["fallback", "corrupt", "missing", "nooutline"],
&[missing.clone(), first, second],
&listing,
&read,
);
assert_eq!(
found,
vec![
(
(false, false),
FaceSource::new(&paths[0], Some(0)),
ttc_face_bytes(&collection, 0).unwrap()
),
(
(true, false),
FaceSource::new(&paths[0], Some(1)),
ttc_face_bytes(&collection, 1).unwrap()
),
]
);
assert_eq!(*reads.borrow(), paths[..4]);
assert_eq!(bytes[&paths[0]], collection);
}
}