use std::{collections::BTreeMap, sync::OnceLock};
use crate::BuiltinFont;
mod metrics;
pub(crate) struct Metrics {
pub font_name: &'static str,
pub full_name: &'static str,
pub family_name: &'static str,
pub version: &'static str,
pub notice: &'static str,
pub italic_angle: f32,
pub is_fixed_pitch: bool,
pub font_bbox: [i16; 4],
pub underline_position: i16,
pub underline_thickness: i16,
pub widths: [u16; 256],
}
impl BuiltinFont {
pub(crate) fn metrics(&self) -> &'static Metrics {
use BuiltinFont::*;
match self {
TimesRoman => &metrics::TIMES_ROMAN,
TimesBold => &metrics::TIMES_BOLD,
TimesItalic => &metrics::TIMES_ITALIC,
TimesBoldItalic => &metrics::TIMES_BOLDITALIC,
Helvetica => &metrics::HELVETICA,
HelveticaBold => &metrics::HELVETICA_BOLD,
HelveticaOblique => &metrics::HELVETICA_OBLIQUE,
HelveticaBoldOblique => &metrics::HELVETICA_BOLDOBLIQUE,
Courier => &metrics::COURIER,
CourierOblique => &metrics::COURIER_OBLIQUE,
CourierBold => &metrics::COURIER_BOLD,
CourierBoldOblique => &metrics::COURIER_BOLDOBLIQUE,
Symbol => &metrics::SYMBOL,
ZapfDingbats => &metrics::ZAPFDINGBATS,
}
}
pub(crate) fn code_width(&self, code: u8) -> Option<u16> {
self.metrics()
.widths
.get(usize::from(code))
.copied()
.filter(|w| *w != 0)
}
pub(crate) fn code_of_glyph(&self, gid: u16) -> u8 {
u8::try_from(gid)
.ok()
.filter(|code| *code != 0 && self.code_width(*code).is_some())
.unwrap_or(b'?')
}
pub(crate) fn char_of_glyph(&self, gid: u16) -> char {
win_ansi_char(self.code_of_glyph(gid)).unwrap_or('?')
}
fn regular_of_family(&self) -> BuiltinFont {
use BuiltinFont::*;
match self {
TimesRoman | TimesBold | TimesItalic | TimesBoldItalic => TimesRoman,
Helvetica | HelveticaBold | HelveticaOblique | HelveticaBoldOblique => Helvetica,
Courier | CourierOblique | CourierBold | CourierBoldOblique => Courier,
Symbol => Symbol,
ZapfDingbats => ZapfDingbats,
}
}
}
pub(crate) fn win_ansi_char(code: u8) -> Option<char> {
let c = crate::text::win_ansi_char(code);
(c != '\u{FFFD}' && !c.is_control()).then_some(c)
}
pub(crate) fn metrics_face(font: BuiltinFont) -> &'static [u8] {
static FACES: [OnceLock<Vec<u8>>; 14] = [const { OnceLock::new() }; 14];
match FACES.get(font.get_num()) {
Some(face) => face.get_or_init(|| build_metrics_face(font)),
None => &[],
}
}
#[cfg(feature = "text_layout")]
pub(crate) fn builtin_for_font_hash(hash: u64) -> Option<BuiltinFont> {
static HASHES: OnceLock<Vec<(u64, BuiltinFont)>> = OnceLock::new();
HASHES
.get_or_init(|| {
BuiltinFont::all_ids()
.into_iter()
.filter_map(|font| Some((font.get_parsed_font()?.hash, font)))
.collect()
})
.iter()
.find(|(h, _)| *h == hash)
.map(|(_, font)| *font)
}
#[cfg(feature = "text_layout")]
pub(crate) fn layout_font_handle(font_hash: u64) -> crate::ops::PdfFontHandle {
match builtin_for_font_hash(font_hash) {
Some(builtin) => crate::ops::PdfFontHandle::Builtin(builtin),
None => crate::ops::PdfFontHandle::External(crate::FontId(format!("F{font_hash}"))),
}
}
#[cfg(feature = "include_base_fonts")]
pub(crate) fn bundled_font(font: BuiltinFont) -> Option<crate::ParsedFont> {
crate::ParsedFont::from_bytes(bundled_font_bytes(font), 0, &mut Vec::new())
}
#[cfg(feature = "include_base_fonts")]
fn bundled_font_bytes(font: BuiltinFont) -> &'static [u8] {
use BuiltinFont::*;
match font {
TimesRoman => include_bytes!("../../third_party/foxit-fonts/FoxitSerif.ttf"),
TimesBold => include_bytes!("../../third_party/foxit-fonts/FoxitSerifBold.ttf"),
TimesItalic => include_bytes!("../../third_party/foxit-fonts/FoxitSerifItalic.ttf"),
TimesBoldItalic => include_bytes!("../../third_party/foxit-fonts/FoxitSerifBoldItalic.ttf"),
Helvetica => include_bytes!("../../third_party/foxit-fonts/FoxitSans.ttf"),
HelveticaBold => include_bytes!("../../third_party/foxit-fonts/FoxitSansBold.ttf"),
HelveticaOblique => include_bytes!("../../third_party/foxit-fonts/FoxitSansItalic.ttf"),
HelveticaBoldOblique => include_bytes!("../../third_party/foxit-fonts/FoxitSansBoldItalic.ttf"),
Courier => include_bytes!("../../third_party/foxit-fonts/FoxitFixed.ttf"),
CourierOblique => include_bytes!("../../third_party/foxit-fonts/FoxitFixedItalic.ttf"),
CourierBold => include_bytes!("../../third_party/foxit-fonts/FoxitFixedBold.ttf"),
CourierBoldOblique => include_bytes!("../../third_party/foxit-fonts/FoxitFixedBoldItalic.ttf"),
Symbol => include_bytes!("../../third_party/foxit-fonts/FoxitSymbol.ttf"),
ZapfDingbats => include_bytes!("../../third_party/foxit-fonts/FoxitDingbats.ttf"),
}
}
const TRUETYPE: [u8; 4] = [0, 1, 0, 0];
const MIN_LINE_HEIGHT: i32 = 1150;
fn build_metrics_face(font: BuiltinFont) -> Vec<u8> {
let metrics = font.metrics();
let bold = font.get_font_weight() == "bold";
let italic = font.get_font_style() == "italic";
let mut advances = metrics.widths;
if let (Some(notdef), Some(question)) = (advances.first_mut(), metrics.widths.get(usize::from(b'?'))) {
*notdef = *question;
}
let num_glyphs = advances.len() as u16;
let cmap: BTreeMap<u16, u16> = (0..=255u8)
.filter(|code| font.code_width(*code).is_some())
.filter_map(|code| {
let c = win_ansi_char(code)?;
Some((u16::try_from(u32::from(c)).ok()?, u16::from(code)))
})
.collect();
let mut cmap_table = Vec::new();
cmap_table.extend_from_slice(&0u16.to_be_bytes()); cmap_table.extend_from_slice(&1u16.to_be_bytes()); cmap_table.extend_from_slice(&3u16.to_be_bytes()); cmap_table.extend_from_slice(&1u16.to_be_bytes()); cmap_table.extend_from_slice(&12u32.to_be_bytes()); cmap_table.extend_from_slice(&super::cmap_format4(&cmap));
let [x_min, y_min, x_max, y_max] = metrics.font_bbox;
let mut mac_style = 0u16;
if bold {
mac_style |= 1;
}
if italic {
mac_style |= 1 << 1;
}
let mut head = Vec::with_capacity(54);
head.extend_from_slice(&0x0001_0000u32.to_be_bytes()); head.extend_from_slice(&0x0001_0000u32.to_be_bytes()); head.extend_from_slice(&0u32.to_be_bytes()); head.extend_from_slice(&0x5F0F_3CF5u32.to_be_bytes()); head.extend_from_slice(&0x000Bu16.to_be_bytes()); head.extend_from_slice(&1000u16.to_be_bytes()); head.extend_from_slice(&0i64.to_be_bytes()); head.extend_from_slice(&0i64.to_be_bytes()); for v in [x_min, y_min, x_max, y_max] {
head.extend_from_slice(&v.to_be_bytes());
}
head.extend_from_slice(&mac_style.to_be_bytes());
head.extend_from_slice(&8u16.to_be_bytes()); head.extend_from_slice(&2i16.to_be_bytes()); head.extend_from_slice(&0i16.to_be_bytes()); head.extend_from_slice(&0i16.to_be_bytes());
let [_, family_y_min, _, family_y_max] = font.regular_of_family().metrics().font_bbox;
let extent = i32::from(family_y_max) - i32::from(family_y_min);
let line_gap = i16::try_from((MIN_LINE_HEIGHT - extent).max(0)).unwrap_or(0);
let (caret_rise, caret_run) = if metrics.italic_angle == 0.0 {
(1i16, 0i16)
} else {
let run = (-f64::from(metrics.italic_angle).to_radians().tan() * 1000.0).round();
(1000, run as i16)
};
let mut hhea = Vec::with_capacity(36);
hhea.extend_from_slice(&0x0001_0000u32.to_be_bytes()); hhea.extend_from_slice(&family_y_max.to_be_bytes()); hhea.extend_from_slice(&family_y_min.to_be_bytes()); hhea.extend_from_slice(&line_gap.to_be_bytes());
hhea.extend_from_slice(&advances.iter().copied().max().unwrap_or(0).to_be_bytes()); hhea.extend_from_slice(&0i16.to_be_bytes()); hhea.extend_from_slice(&0i16.to_be_bytes()); hhea.extend_from_slice(&0i16.to_be_bytes()); hhea.extend_from_slice(&caret_rise.to_be_bytes());
hhea.extend_from_slice(&caret_run.to_be_bytes());
hhea.extend_from_slice(&[0u8; 10]); hhea.extend_from_slice(&0i16.to_be_bytes()); hhea.extend_from_slice(&num_glyphs.to_be_bytes());
let mut hmtx = Vec::with_capacity(advances.len() * 4);
for advance in advances {
hmtx.extend_from_slice(&advance.to_be_bytes());
hmtx.extend_from_slice(&0i16.to_be_bytes()); }
let loca = vec![0u8; (advances.len() + 1) * 2];
let glyf: Vec<u8> = Vec::new();
let mut maxp = Vec::with_capacity(32);
maxp.extend_from_slice(&0x0001_0000u32.to_be_bytes()); maxp.extend_from_slice(&num_glyphs.to_be_bytes());
for value in [0u16, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0] {
maxp.extend_from_slice(&value.to_be_bytes());
}
let subfamily = match (bold, italic) {
(false, false) => "Regular",
(true, false) => "Bold",
(false, true) => "Italic",
(true, true) => "Bold Italic",
};
let family = format!("PDF {}", metrics.family_name);
let full_name = format!("PDF {}", metrics.full_name);
let unique = format!("printpdf: metrics of {}", metrics.font_name);
let version = format!("Version {}", metrics.version);
let description = format!(
"The metrics of the standard PDF font {}, measured from a Foxit font of PDFium, without \
glyph outlines. printpdf measures text with this face and writes it with the standard \
font.",
metrics.font_name
);
let name = name_table(&[
(0, metrics.notice),
(1, &family),
(2, subfamily),
(3, &unique),
(4, &full_name),
(5, &version),
(6, metrics.font_name),
(10, &description),
]);
let mut post = Vec::with_capacity(32);
post.extend_from_slice(&0x0003_0000u32.to_be_bytes()); let italic_angle = (f64::from(metrics.italic_angle) * 65536.0).round() as i32;
post.extend_from_slice(&italic_angle.to_be_bytes());
post.extend_from_slice(&metrics.underline_position.to_be_bytes());
post.extend_from_slice(&metrics.underline_thickness.to_be_bytes());
post.extend_from_slice(&u32::from(metrics.is_fixed_pitch).to_be_bytes());
post.extend_from_slice(&[0u8; 16]);
super::build_sfnt(
TRUETYPE,
&[
(*b"cmap", &cmap_table),
(*b"glyf", &glyf),
(*b"head", &head),
(*b"hhea", &hhea),
(*b"hmtx", &hmtx),
(*b"loca", &loca),
(*b"maxp", &maxp),
(*b"name", &name),
(*b"post", &post),
],
)
}
fn name_table(records: &[(u16, &str)]) -> Vec<u8> {
let count = records.len() as u16;
let mut table = Vec::new();
table.extend_from_slice(&0u16.to_be_bytes()); table.extend_from_slice(&count.to_be_bytes());
table.extend_from_slice(&(6 + 12 * count).to_be_bytes()); let mut strings: Vec<u8> = Vec::new();
for (id, text) in records {
let utf16: Vec<u8> = text.encode_utf16().flat_map(u16::to_be_bytes).collect();
table.extend_from_slice(&3u16.to_be_bytes()); table.extend_from_slice(&1u16.to_be_bytes()); table.extend_from_slice(&0x0409u16.to_be_bytes()); table.extend_from_slice(&id.to_be_bytes());
table.extend_from_slice(&(utf16.len() as u16).to_be_bytes());
table.extend_from_slice(&(strings.len() as u16).to_be_bytes());
strings.extend_from_slice(&utf16);
}
table.extend_from_slice(&strings);
table
}
#[cfg(test)]
mod tests {
use crate::{BuiltinFont, ParsedFont};
const FOXIT_FILES: [(BuiltinFont, &str); 14] = [
(BuiltinFont::TimesRoman, "FoxitSerif"),
(BuiltinFont::TimesBold, "FoxitSerifBold"),
(BuiltinFont::TimesItalic, "FoxitSerifItalic"),
(BuiltinFont::TimesBoldItalic, "FoxitSerifBoldItalic"),
(BuiltinFont::Helvetica, "FoxitSans"),
(BuiltinFont::HelveticaBold, "FoxitSansBold"),
(BuiltinFont::HelveticaOblique, "FoxitSansItalic"),
(BuiltinFont::HelveticaBoldOblique, "FoxitSansBoldItalic"),
(BuiltinFont::Courier, "FoxitFixed"),
(BuiltinFont::CourierOblique, "FoxitFixedItalic"),
(BuiltinFont::CourierBold, "FoxitFixedBold"),
(BuiltinFont::CourierBoldOblique, "FoxitFixedBoldItalic"),
(BuiltinFont::Symbol, "FoxitSymbol"),
(BuiltinFont::ZapfDingbats, "FoxitDingbats"),
];
fn foxit_font(file: &str) -> Vec<u8> {
let path = format!("{}/third_party/foxit-fonts/{file}.ttf", env!("CARGO_MANIFEST_DIR"));
std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
}
fn advances(font: &[u8]) -> Vec<u16> {
let maxp = find(font, b"maxp");
let num_glyphs = usize::from(u16::from_be_bytes([maxp[4], maxp[5]]));
let hhea = find(font, b"hhea");
let long_metrics = usize::from(u16::from_be_bytes([hhea[34], hhea[35]]));
let hmtx = find(font, b"hmtx");
(0..num_glyphs)
.map(|gid| {
let i = gid.min(long_metrics - 1);
u16::from_be_bytes([hmtx[4 * i], hmtx[4 * i + 1]])
})
.collect()
}
#[test]
fn the_tables_match_the_foxit_fonts() {
for (font, file) in FOXIT_FILES {
let metrics = font.metrics();
assert_eq!(metrics.font_name, font.get_id());
let bytes = foxit_font(file);
let head = find(&bytes, b"head");
assert_eq!(u16::from_be_bytes([head[18], head[19]]), 1000, "{font:?}: units per em");
let latin = !matches!(font, BuiltinFont::Symbol | BuiltinFont::ZapfDingbats);
if latin {
assert_eq!(font.code_width(0xA0), font.code_width(b' '), "{font:?}");
assert_eq!(font.code_width(0xAD), font.code_width(b'-'), "{font:?}");
}
let expected: Vec<u16> = (0..=255u8)
.filter(|code| !(latin && (*code == 0xA0 || *code == 0xAD)))
.filter_map(|code| font.code_width(code))
.collect();
let actual = advances(&bytes);
assert_eq!(actual.get(1..), Some(expected.as_slice()), "{font:?}: advance widths");
let post = find(&bytes, b"post");
let angle = i32::from_be_bytes([post[4], post[5], post[6], post[7]]);
let want = (f64::from(metrics.italic_angle) * 65536.0).round() as i32;
assert!((angle - want).abs() <= 1, "{font:?}: italic angle {angle} {want}");
let underline = |at: usize| i16::from_be_bytes([post[at], post[at + 1]]);
assert_eq!(underline(8), metrics.underline_position, "{font:?}");
assert_eq!(underline(10), metrics.underline_thickness, "{font:?}");
let fixed = u32::from_be_bytes([post[12], post[13], post[14], post[15]]);
assert_eq!(fixed != 0, metrics.is_fixed_pitch, "{font:?}");
let face = super::metrics_face(font);
assert_eq!(find(&bytes, b"hhea")[4..10], find(face, b"hhea")[4..10], "{font:?}: line height");
}
}
#[test]
fn every_latin_font_has_every_win_ansi_glyph() {
for font in BuiltinFont::all_ids() {
if matches!(font, BuiltinFont::Symbol | BuiltinFont::ZapfDingbats) {
continue;
}
for code in 0..=255u8 {
assert_eq!(
font.code_width(code).is_some(),
super::win_ansi_char(code).is_some(),
"{font:?} code {code:#04x}"
);
}
}
}
#[test]
fn metrics_faces_measure_like_the_tables() {
for font in BuiltinFont::all_ids() {
let parsed = ParsedFont::from_bytes(super::metrics_face(font), 0, &mut Vec::new())
.unwrap_or_else(|| panic!("{font:?}: the metrics face does not parse"));
for code in 0..=255u8 {
let Some(c) = super::win_ansi_char(code) else {
continue;
};
let gid = parsed.lookup_glyph_index(u32::from(c));
match font.code_width(code) {
Some(width) => {
assert_eq!(gid, Some(u16::from(code)), "{font:?} {c:?}");
let advance = crate::ops::glyph_advance_em(&parsed, u16::from(code));
assert_eq!((advance * 1000.0).round() as u16, width, "{font:?} {c:?}");
}
None => assert_eq!(gid, None, "{font:?} {c:?}"),
}
}
}
}
#[test]
fn metrics_faces_have_no_outlines() {
for font in BuiltinFont::all_ids() {
let face = super::metrics_face(font);
let count = usize::from(u16::from_be_bytes([face[4], face[5]]));
for i in 0..count {
let record = &face[12 + 16 * i..28 + 16 * i];
let length = u32::from_be_bytes([record[12], record[13], record[14], record[15]]);
assert_ne!(&record[..4], b"CFF ", "{font:?}");
if &record[..4] == b"glyf" {
assert_eq!(length, 0, "{font:?}: glyf must be empty");
}
}
}
}
#[test]
fn a_family_has_one_line_height() {
for family in [
[BuiltinFont::TimesRoman, BuiltinFont::TimesBold, BuiltinFont::TimesItalic, BuiltinFont::TimesBoldItalic],
[BuiltinFont::Helvetica, BuiltinFont::HelveticaBold, BuiltinFont::HelveticaOblique, BuiltinFont::HelveticaBoldOblique],
[BuiltinFont::Courier, BuiltinFont::CourierBold, BuiltinFont::CourierOblique, BuiltinFont::CourierBoldOblique],
] {
let heights: Vec<(i32, i32, i32)> = family
.iter()
.map(|font| {
let face = super::metrics_face(*font);
let hhea = find(face, b"hhea");
let v = |at: usize| i32::from(i16::from_be_bytes([hhea[at], hhea[at + 1]]));
(v(4), v(6), v(8))
})
.collect();
assert!(heights.windows(2).all(|w| w[0] == w[1]), "{family:?}: {heights:?}");
let (ascender, descender, gap) = heights[0];
assert!(ascender - descender + gap >= super::MIN_LINE_HEIGHT, "{family:?}");
}
}
#[test]
fn check_if_matches_finds_the_metrics_faces() {
for font in BuiltinFont::all_ids() {
assert_eq!(BuiltinFont::check_if_matches(super::metrics_face(font)), Some(font));
}
assert_eq!(BuiltinFont::check_if_matches(b"not a font"), None);
}
#[cfg(feature = "include_base_fonts")]
#[test]
fn the_bundled_fonts_have_the_glyphs_and_widths_of_the_metrics() {
for font in BuiltinFont::all_ids() {
let bundled = super::bundled_font(font)
.unwrap_or_else(|| panic!("{font:?}: the bundled font does not parse"));
for code in 0..=255u8 {
let Some(c) = super::win_ansi_char(code) else {
continue;
};
let gid = bundled.lookup_glyph_index(u32::from(c));
match font.code_width(code) {
Some(width) => {
let gid = gid.unwrap_or_else(|| panic!("{font:?} {c:?}: no glyph"));
let advance = crate::ops::glyph_advance_em(&bundled, gid);
assert_eq!((advance * 1000.0).round() as u16, width, "{font:?} {c:?}");
}
None => assert_eq!(gid, None, "{font:?} {c:?}"),
}
}
}
}
#[cfg(feature = "include_base_fonts")]
#[test]
fn the_bundled_fonts_have_outlines_and_the_license() {
let license: Vec<u8> = "Copyright 2014 PDFium Authors"
.encode_utf16()
.flat_map(u16::to_be_bytes)
.collect();
for font in BuiltinFont::all_ids() {
let bytes = super::bundled_font_bytes(font);
let name = find(bytes, b"name");
assert!(name.windows(license.len()).any(|w| w == license.as_slice()), "{font:?}");
let head = find(bytes, b"head");
let long = i16::from_be_bytes([head[50], head[51]]) == 1;
let loca = find(bytes, b"loca");
let offset = |gid: usize| -> usize {
if long {
u32::from_be_bytes([loca[4 * gid], loca[4 * gid + 1], loca[4 * gid + 2], loca[4 * gid + 3]]) as usize
} else {
2 * usize::from(u16::from_be_bytes([loca[2 * gid], loca[2 * gid + 1]]))
}
};
let glyphs = loca.len() / if long { 4 } else { 2 } - 1;
let empty = (1..glyphs).filter(|gid| offset(*gid) == offset(gid + 1)).count();
assert_eq!(empty, 1, "{font:?}: one empty glyph, space");
}
}
fn find<'a>(face: &'a [u8], tag: &[u8; 4]) -> &'a [u8] {
let count = usize::from(u16::from_be_bytes([face[4], face[5]]));
for i in 0..count {
let record = &face[12 + 16 * i..28 + 16 * i];
if &record[..4] == tag {
let offset = u32::from_be_bytes([record[8], record[9], record[10], record[11]]) as usize;
let length = u32::from_be_bytes([record[12], record[13], record[14], record[15]]) as usize;
return &face[offset..offset + length];
}
}
panic!("no {} table", String::from_utf8_lossy(tag));
}
}