printpdf 0.13.1

Rust library for reading and writing PDF files
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! The metrics of the 14 standard fonts.
//!
//! Measuring and laying out text needs the advance widths and a few values of the whole font.
//! `scripts/gen_base14_fonts.py` writes them into the tables of `metrics.rs`.
//! See [`BuiltinFont`] for where they come from.
//!
//! The HTML layout and the text boxes measure text with a [`ParsedFont`](super::ParsedFont).
//! For a standard font they get a *metrics face* ([`metrics_face`]).
//!
//! - It is a TrueType font built from the numbers of the tables.
//! - It has 256 glyphs and no outlines. Glyph id `n` is the glyph that the one-byte code `n`
//!   selects.
//! - printpdf never writes it into a PDF. Text measured with it is written with the standard font.

use std::{collections::BTreeMap, sync::OnceLock};

use crate::BuiltinFont;

mod metrics;

/// The values of a standard font that printpdf uses. Lengths are in thousandths of an em.
pub(crate) struct Metrics {
    /// The PostScript name and the `/BaseFont` of the font.
    pub font_name: &'static str,
    /// The full name of the font.
    pub full_name: &'static str,
    /// The family name.
    pub family_name: &'static str,
    /// The version of the Foxit font that the metrics are measured from.
    pub version: &'static str,
    /// The copyright notice.
    pub notice: &'static str,
    /// The italic angle, in degrees counter-clockwise from the vertical.
    pub italic_angle: f32,
    /// Whether all glyphs have the same advance width.
    pub is_fixed_pitch: bool,
    /// The bounding box of all glyphs: x min, y min, x max, y max.
    pub font_bbox: [i16; 4],
    /// The position of the underline.
    pub underline_position: i16,
    /// The thickness of the underline.
    pub underline_thickness: i16,
    /// The advance width of the glyph that each one-byte code selects. It is 0 where a code
    /// selects none. The Latin fonts use `WinAnsiEncoding` codes. `Symbol` and `ZapfDingbats` use
    /// the codes of their built-in encoding.
    pub widths: [u16; 256],
}

impl BuiltinFont {
    /// The metrics of this font.
    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,
        }
    }

    /// The advance width of the glyph that the one-byte code `code` selects, in thousandths of an
    /// em. The Latin fonts use `WinAnsiEncoding` codes. `Symbol` and `ZapfDingbats` use the codes
    /// of their own encoding. `None` when the code selects no glyph.
    pub(crate) fn code_width(&self, code: u8) -> Option<u16> {
        self.metrics()
            .widths
            .get(usize::from(code))
            .copied()
            .filter(|w| *w != 0)
    }

    /// The one-byte code that shows glyph `gid` of the metrics face. It is the glyph id itself.
    /// A glyph id that is not a code of the font gives `?`. Glyph 0 stands for a missing character.
    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'?')
    }

    /// The character that the one-byte code of glyph `gid` stands for in `WinAnsiEncoding`.
    /// printpdf writes the standard fonts with this encoding.
    pub(crate) fn char_of_glyph(&self, gid: u16) -> char {
        win_ansi_char(self.code_of_glyph(gid)).unwrap_or('?')
    }

    /// The regular face of the family. Its bounding box sets the line height of all four faces.
    /// Bold or italic words then do not change the line spacing.
    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,
        }
    }
}

/// The character of a `WinAnsiEncoding` code (ISO 32000-1, Annex D.2).
/// printpdf writes the standard fonts with this encoding. `None` for the codes that it leaves
/// undefined.
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)
}

/// The TrueType file of the metrics face of `font`, built on first use.
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)),
        // `get_num` is below 14.
        None => &[],
    }
}

/// The standard font whose metrics face has the font hash `hash`.
/// azul-layout computes the hash for the faces it lays text out with.
#[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)
}

/// The font that a glyph run of a layout is written with. The run uses the face with the hash
/// `font_hash`.
///
/// - A metrics face has no glyphs. Its text is written with the standard font, which the viewer
///   supplies. Its glyph ids are the one-byte codes of that font.
/// - Any other face is the embedded font `F<hash>`. The HTML renderer gives this id to the fonts
///   of a layout.
#[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}"))),
    }
}

/// The font that printpdf embeds in place of `font`. It is used where every font must be embedded
/// (PDF/A, PDF/X) and the document has no replacement for it.
///
/// It is a TrueType subset of the Foxit font for this font (see [`BuiltinFont`]).
/// `scripts/gen_base14_fonts.py` makes it.
///
/// - It has a glyph for every one-byte code of the standard font.
/// - It has the advance widths of the metrics and the `cmap` of the metrics face.
///
/// The text is then drawn where the layout put it.
#[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"),
    }
}

/// The TrueType version tag of the table directory.
const TRUETYPE: [u8; 4] = [0, 1, 0, 0];

/// The smallest height of a line (`line-height: normal`) of a metrics face, in thousandths of an
/// em. Browsers give Arial, Times New Roman and Courier New about this height. They draw these
/// fonts for the standard names.
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";

    // Glyph `n` is the glyph of code `n`. Glyph 0 (`.notdef`) stands for a character that the
    // font lacks. printpdf writes that character as `?`, so glyph 0 is as wide as the question mark.
    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;

    // Every character that a code of the font encodes, to the glyph of that code.
    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()); // version
    cmap_table.extend_from_slice(&1u16.to_be_bytes()); // numTables
    cmap_table.extend_from_slice(&3u16.to_be_bytes()); // platformID: Windows
    cmap_table.extend_from_slice(&1u16.to_be_bytes()); // encodingID: Unicode BMP
    cmap_table.extend_from_slice(&12u32.to_be_bytes()); // offset of the subtable
    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()); // version
    head.extend_from_slice(&0x0001_0000u32.to_be_bytes()); // fontRevision
    head.extend_from_slice(&0u32.to_be_bytes()); // checkSumAdjustment
    head.extend_from_slice(&0x5F0F_3CF5u32.to_be_bytes()); // magicNumber
    head.extend_from_slice(&0x000Bu16.to_be_bytes()); // flags: baseline and left side bearing at 0, integer scaling
    head.extend_from_slice(&1000u16.to_be_bytes()); // unitsPerEm
    head.extend_from_slice(&0i64.to_be_bytes()); // created
    head.extend_from_slice(&0i64.to_be_bytes()); // modified
    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()); // lowestRecPPEM
    head.extend_from_slice(&2i16.to_be_bytes()); // fontDirectionHint
    head.extend_from_slice(&0i16.to_be_bytes()); // indexToLocFormat: short offsets
    head.extend_from_slice(&0i16.to_be_bytes()); // glyphDataFormat

    // The line height comes from the regular face of the family. It is at least `MIN_LINE_HEIGHT`.
    // The ascender and descender are the top and bottom of its bounding box.
    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 {
        // A negative angle leans to the right, where the caret runs in positive x.
        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()); // version
    hhea.extend_from_slice(&family_y_max.to_be_bytes()); // ascender
    hhea.extend_from_slice(&family_y_min.to_be_bytes()); // descender
    hhea.extend_from_slice(&line_gap.to_be_bytes());
    hhea.extend_from_slice(&advances.iter().copied().max().unwrap_or(0).to_be_bytes()); // advanceWidthMax
    hhea.extend_from_slice(&0i16.to_be_bytes()); // minLeftSideBearing
    hhea.extend_from_slice(&0i16.to_be_bytes()); // minRightSideBearing
    hhea.extend_from_slice(&0i16.to_be_bytes()); // xMaxExtent
    hhea.extend_from_slice(&caret_rise.to_be_bytes());
    hhea.extend_from_slice(&caret_run.to_be_bytes());
    hhea.extend_from_slice(&[0u8; 10]); // caretOffset, 4 reserved
    hhea.extend_from_slice(&0i16.to_be_bytes()); // metricDataFormat
    hhea.extend_from_slice(&num_glyphs.to_be_bytes()); // numberOfHMetrics

    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()); // left side bearing
    }

    // No glyph has an outline: every `loca` offset is 0, and `glyf` is empty.
    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()); // version 1.0
    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] {
        // maxPoints, maxContours, maxCompositePoints, maxCompositeContours, maxZones,
        // maxTwilightPoints, maxStorage, maxFunctionDefs, maxInstructionDefs, maxStackElements,
        // maxSizeOfInstructions, maxComponentElements, maxComponentDepth
        maxp.extend_from_slice(&value.to_be_bytes());
    }

    // The family name gets the prefix `PDF `. So azul-layout does not apply its macOS ascent to
    // the families `Times`, `Helvetica` and `Courier`.
    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()); // version 3: no glyph names
    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]); // memory usage of Type 42 and Type 1 downloads

    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),
        ],
    )
}

/// A `name` table with the `(name id, text)` records, for Windows, Unicode BMP, English (US).
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()); // format
    table.extend_from_slice(&count.to_be_bytes());
    table.extend_from_slice(&(6 + 12 * count).to_be_bytes()); // offset of the strings
    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()); // platformID: Windows
        table.extend_from_slice(&1u16.to_be_bytes()); // encodingID: Unicode BMP
        table.extend_from_slice(&0x0409u16.to_be_bytes()); // languageID: English (US)
        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};

    /// The file in `third_party/foxit-fonts` that `include_base_fonts` embeds for each standard
    /// font.
    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}"))
    }

    /// The advance width of every glyph of a TrueType font, in font units.
    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| {
                // The glyphs after the last long metric have the advance of the last one.
                let i = gid.min(long_metrics - 1);
                u16::from_be_bytes([hmtx[4 * i], hmtx[4 * i + 1]])
            })
            .collect()
    }

    /// The generator writes the tables and the fonts in `third_party/foxit-fonts` together.
    /// The files must have the widths and the font-wide values of the tables.
    #[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");

            // The glyphs of a file are `.notdef` and then the glyph of each code, in code order.
            // WinAnsiEncoding draws `space` and `hyphen` for 0xA0 and 0xAD. The glyphs of 0x20
            // and 0x2D are those already.
            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");

            // The font-wide values.
            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:?}");

            // The line height of the file is that of the metrics face of the 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:?}");
            // Every glyph but `.notdef` and `space` has an outline.
            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));
    }
}