pdf2-render 1.6.0

Rasteriser for the pdf2 crate: paths, clips, images, text, fonts, shadings and patterns, with a report of what it cannot draw.
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
//! Fonts for text rendering: a provider trait, a built-in base-14 fallback,
//! TrueType outlines through `ttf-parser`, and CFF outlines — CID-keyed or
//! plain — by wrapping the bare CFF program in the smallest OpenType container
//! `ttf-parser` will read.
//!
//! The wrapper exists because PDF carries two shapes of CFF: `/Subtype
//! /OpenType` (already an sfnt, read directly) and `/Subtype /CIDFontType0C` or
//! `/Type1C` (a bare CFF table, which `ttf-parser` refuses: "Invalid sfnt
//! version"). Five synthesised tables — `head`, `hhea`, `maxp`, `hmtx` and the
//! program itself — are enough, and the decision, its measurements and what it
//! refuses are in `docs/adr/0003-cff-without-a-dependency.md`.

use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

use pdf2::Encoding;

use crate::geom::Point;

/// A font's parsed answers, shared by its clones.
///
/// `ttf-parser` borrows the program, so a parsed face cannot outlive the call
/// that made it — but its answers can. Two maps memoise the expensive steps:
/// character → glyph id (the `cmap` lookup) and glyph id → outline. Measured on
/// `book.pdf` at scale 0.25, where the rasteriser is not the bottleneck, this
/// halves the page: 5.4 ms → 3.9 ms.
#[derive(Debug, Default)]
pub struct Cache {
    /// Character → glyph id, `None` when the `cmap` does not cover it.
    cmap: BTreeMap<char, Option<u16>>,
    /// Code → glyph id through a Macintosh Roman `(1,0)` subtable, when there is one.
    mac: BTreeMap<u8, Option<u16>>,
    /// Glyph id → outline and advance.
    glyphs: BTreeMap<u16, Option<Glyph>>,
}

/// The shared cache behind a font's clones.
pub type GlyphCache = Rc<RefCell<Cache>>;

/// One glyph's outline in em units: y grows upwards, the baseline is y = 0 and
/// one em is 1.0.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Glyph {
    /// Closed contours of the outline.
    pub contours: Vec<Vec<Point>>,
    /// Advance width in em units.
    pub advance: f64,
}

/// A resolved font ready to place glyphs.
#[derive(Debug, Clone)]
pub enum Font {
    /// The built-in fallback: a 5×7 bitmap alphabet, used when the document
    /// carries no usable font program (all of the base-14 cases).
    Builtin {
        /// Code → character table.
        encoding: Encoding,
    },
    /// An embedded Type 1 program (`/FontFile`), whose glyphs are charstrings
    /// (`crate::type1`). A simple font's code reaches a glyph through its
    /// encoding's *name*, so the program is indexed by the character each name
    /// stands for.
    Type1 {
        /// Code → character table.
        encoding: Encoding,
        /// The parsed program, shared with the clones of this font.
        program: Rc<crate::type1::Program>,
        /// Character → glyph name, for the names the library can resolve.
        names: std::collections::HashMap<char, Vec<u8>>,
    },
    /// An embedded CFF program, wrapped so the outlines come out of the same
    /// code path as TrueType. CID-keyed fonts select glyphs through their
    /// charset, not by using the CID as a glyph id.
    Cff {
        /// Code → character table, for the (rare) simple CFF font.
        encoding: Encoding,
        /// The program as sfnt bytes.
        data: Vec<u8>,
        /// CID → glyph id from the CFF charset, empty when the font is not
        /// CID-keyed.
        cid_to_gid: Vec<(u16, u16)>,
        /// A **simple** (non-CID) CFF font selects its glyphs by name: the
        /// charset names each glyph, and a code reaches one through the
        /// encoding's character. A bare CFF carries no `cmap`, so this is the
        /// only route to its outlines.
        names: std::collections::HashMap<char, u16>,
        /// Parsed answers, shared by clones.
        cache: GlyphCache,
    },
    /// An embedded TrueType program.
    TrueType {
        /// Code → character table.
        encoding: Encoding,
        /// The font program, still compressed in the PDF sense is not our
        /// business: this is the decoded `/FontFile2`.
        data: Vec<u8>,
        /// Whether the program carries a `cmap` table at all: when it does not,
        /// a simple font's code is the glyph id.
        has_cmap: bool,
        /// Whether a Macintosh Roman `(1,0)` subtable is present, which is the one
        /// a writer's own codes can be looked up in when the Unicode map is absent.
        has_mac_cmap: bool,
        /// Parsed answers, shared by clones.
        cache: GlyphCache,
    },
}

impl Font {
    /// The built-in fallback with an encoding.
    pub fn builtin(encoding: Encoding) -> Self {
        Self::Builtin { encoding }
    }

    /// An embedded CFF program, bare or already wrapped in OpenType.
    ///
    /// `/CIDFontType0C` and `/Type1C` programs are a CFF table with no container;
    /// they are wrapped here so the same outline code reads them.
    pub fn cff(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
        let wrapped = data.starts_with(b"OTTO");
        let table: Vec<u8> = if wrapped {
            cff_table_of_sfnt(&data)?.to_vec()
        } else {
            data.clone()
        };
        let (charset_at, glyphs) = cff_layout(&table)?;
        // A CID-keyed font's Top DICT declares an ROS; without one the charset
        // holds *names* (SIDs), which is what a simple font selects by.
        let cid_to_gid = if top_dict_declares_ros(&table) {
            cff_charset(&table, charset_at, glyphs)
        } else {
            Vec::new()
        };
        let program = if wrapped {
            data
        } else {
            wrap_cff(&table, glyphs)?
        };
        // Parse once here so a program that cannot be read is rejected at load,
        // not at the first glyph.
        let face = ttf_parser::Face::parse(&program, 0).ok()?;
        let names = if cid_to_gid.is_empty() {
            glyph_names(&face)
        } else {
            std::collections::HashMap::new()
        };
        Some(Self::Cff {
            encoding,
            data: program,
            cid_to_gid,
            names,
            cache: GlyphCache::default(),
        })
    }

    /// A Type 1 program, indexed by the character each glyph name stands for.
    ///
    /// `None` when the program has no usable glyphs, which is what makes the
    /// caller fall back rather than draw nothing.
    pub fn type1(encoding: Encoding, program: crate::type1::Program) -> Option<Self> {
        if !program.is_usable() {
            return None;
        }
        let mut names = std::collections::HashMap::new();
        for name in program.names() {
            if let Some(character) = pdf2::encoding::glyph_name_character(name) {
                names.entry(character).or_insert_with(|| name.to_vec());
            }
        }
        Some(Self::Type1 {
            encoding,
            program: Rc::new(program),
            names,
        })
    }

    /// An embedded TrueType program, rejected when it cannot be parsed.
    pub fn true_type(encoding: Encoding, data: Vec<u8>) -> Option<Self> {
        let face = ttf_parser::Face::parse(&data, 0).ok()?;
        if face.units_per_em() == 0 {
            return None;
        }
        // A `cmap` *table* is not the same as a `cmap` we can consult: the CV this
        // renderer was chasing carries one with a single **Mac Roman** (1,0)
        // subtable, and a Unicode-only lookup found nothing in it — every glyph
        // resolved to `None`, the page drew air, and no report fired because the
        // table existed. Both flavours count as usable now; neither, and the font
        // is reported (`font:TrueType-without-cmap`) rather than looking blank.
        let mut has_cmap = false;
        let mut has_mac_cmap = false;
        if let Some(cmap) = face.tables().cmap {
            for subtable in cmap.subtables {
                if subtable.is_unicode() {
                    has_cmap = true;
                }
                if subtable.platform_id == ttf_parser::PlatformId::Macintosh
                    && subtable.encoding_id == 0
                {
                    has_cmap = true;
                    has_mac_cmap = true;
                }
            }
        }
        Some(Self::TrueType {
            encoding,
            data,
            has_cmap,
            has_mac_cmap,
            cache: GlyphCache::default(),
        })
    }

    /// The outline and advance for a byte code, or `None` when there is no
    /// glyph for it.
    ///
    /// A simple font's code goes through its encoding to a character, and the
    /// character through the program's `cmap` to a glyph id. A program with **no
    /// `cmap` table at all** cannot be consulted that way, and the files that
    /// lack one mean the code *is* the glyph id — pdf.js's
    /// `TrueType_without_cmap.pdf` is the case, and refusing to guess drew a
    /// blank page while reporting nothing at all.
    pub fn glyph(&self, code: u8) -> Option<Glyph> {
        match self {
            Self::Builtin { encoding } => builtin_glyph(encoding.character(code)?),
            Self::Type1 {
                encoding,
                program,
                names,
            } => {
                let character = encoding.character(code)?;
                program.glyph(names.get(&character)?)
            }
            Self::TrueType {
                encoding,
                data,
                cache,
                has_mac_cmap,
                ..
            } => {
                let character = encoding.character(code)?;
                let id = glyph_id(data, cache, character).or_else(|| {
                    has_mac_cmap
                        .then(|| mac_glyph_id(data, cache, code))
                        .flatten()
                })?;
                cached_glyph(data, cache, id)
            }
            Self::Cff {
                encoding,
                data,
                names,
                cache,
                ..
            } => {
                let character = encoding.character(code)?;
                // A simple (non-CID) CFF font reaches its glyphs through the
                // charset's names; a CID-keyed one through the CID it is asked
                // for, which is the composite path.
                let id = if names.is_empty() {
                    glyph_id(data, cache, character)?
                } else {
                    ttf_parser::GlyphId(*names.get(&character)?)
                };
                cached_glyph(data, cache, id)
            }
        }
    }

    /// Whether glyphs are selectable at all — the name map of a simple CFF, a
    /// `cmap` of a TrueType program.
    pub fn has_glyph_names(&self) -> bool {
        match self {
            Self::Type1 { names, .. } => !names.is_empty(),
            Self::Cff { names, .. } => !names.is_empty(),
            Self::TrueType { has_cmap, .. } => *has_cmap,
            Self::Builtin { .. } => false,
        }
    }

    /// Whether this font has a character map at all.
    ///
    /// A simple TrueType program with none cannot be decoded from its codes, so
    /// the caller reports the page instead of drawing an empty one.
    pub fn has_character_map(&self) -> bool {
        match self {
            Self::Builtin { .. } | Self::Cff { .. } | Self::Type1 { .. } => true,
            Self::TrueType { has_cmap, .. } => *has_cmap,
        }
    }

    /// The advance of a code in em units, falling back to the built-in metric.
    pub fn advance(&self, code: u8) -> f64 {
        self.glyph(code)
            .map_or(BUILTIN_ADVANCE, |glyph| glyph.advance)
    }

    /// The outline for a glyph id, which is how composite (Type 0) fonts select
    /// glyphs: a CID maps to an id through `/CIDToGIDMap`, not through a cmap.
    ///
    /// The built-in bitmap alphabet has no glyph ids, so it has no answer here.
    pub fn glyph_by_id(&self, id: u16) -> Option<Glyph> {
        match self {
            Self::Builtin { .. } => None,
            Self::TrueType { data, cache, .. } => {
                cached_glyph(data, cache, ttf_parser::GlyphId(id))
            }
            Self::Type1 { .. } => None,
            Self::Cff {
                data,
                cid_to_gid,
                cache,
                ..
            } => {
                // In a CID-keyed CFF the charset maps glyph ids to CIDs, so a
                // CID has to be looked up rather than used as the glyph id.
                let glyph = cid_to_gid
                    .iter()
                    .find(|(cid, _)| *cid == id)
                    .map_or(id, |(_, gid)| *gid);
                cached_glyph(data, cache, ttf_parser::GlyphId(glyph))
            }
        }
    }
}

/// The character each glyph of a simple CFF font is named for.
///
/// A name that is not a character name (`/uni20AC` style is handled by the
/// library's table) simply does not appear, and the code that would have
/// selected it draws nothing rather than a wrong glyph.
fn glyph_names(face: &ttf_parser::Face<'_>) -> std::collections::HashMap<char, u16> {
    let mut map = std::collections::HashMap::new();
    for id in 0..face.number_of_glyphs() {
        let Some(name) = face.glyph_name(ttf_parser::GlyphId(id)) else {
            continue;
        };
        if let Some(character) = pdf2::encoding::glyph_name_character(name.as_bytes()) {
            map.entry(character).or_insert(id);
        }
    }
    map
}

/// A character's glyph id, memoised: the `cmap` lookup needs a parsed face.
fn glyph_id(data: &[u8], cache: &GlyphCache, character: char) -> Option<ttf_parser::GlyphId> {
    if let Some(cached) = cache.borrow().cmap.get(&character) {
        return cached.map(ttf_parser::GlyphId);
    }
    let face = ttf_parser::Face::parse(data, 0).ok()?;
    let found = face.glyph_index(character).map(|id| id.0);
    cache.borrow_mut().cmap.insert(character, found);
    found.map(ttf_parser::GlyphId)
}

/// A glyph through the font's Macintosh Roman `(1,0)` subtable, by the code.
///
/// A PDF code for a simple font *is* a byte of the font's encoding, and when the
/// program's own `cmap` is Mac Roman that byte is the subtable's code — no Unicode
/// step, which is exactly the step that was failing.
fn mac_glyph_id(data: &[u8], cache: &GlyphCache, code: u8) -> Option<ttf_parser::GlyphId> {
    if let Some(cached) = cache.borrow().mac.get(&code) {
        return cached.map(ttf_parser::GlyphId);
    }
    let face = ttf_parser::Face::parse(data, 0).ok()?;
    let found = face.tables().cmap.and_then(|cmap| {
        cmap.subtables
            .into_iter()
            .find(|subtable| {
                subtable.platform_id == ttf_parser::PlatformId::Macintosh
                    && subtable.encoding_id == 0
            })
            .and_then(|subtable| subtable.glyph_index(u32::from(code)))
            .map(|id| id.0)
    });
    cache.borrow_mut().mac.insert(code, found);
    found.map(ttf_parser::GlyphId)
}

/// An outline and advance, memoised: the parse is the expensive part.
fn cached_glyph(data: &[u8], cache: &GlyphCache, id: ttf_parser::GlyphId) -> Option<Glyph> {
    if let Some(cached) = cache.borrow().glyphs.get(&id.0) {
        return cached.clone();
    }
    let glyph = glyph_from_face(data, id);
    cache.borrow_mut().glyphs.insert(id.0, glyph.clone());
    glyph
}

/// Wrap a bare CFF table in the smallest OpenType container `ttf-parser` reads.
///
/// The synthesised tables say only what outlines need: 1000 units per em (CFF's
/// default `/FontMatrix` is 0.001), the glyph count from the CFF `CharStrings`
/// INDEX, and zero advances, because a CID font's advances come from `/W` in the
/// PDF. Checksums are left zero: `ttf-parser` does not read them, and inventing
/// them would be a claim nobody checks.
fn wrap_cff(cff: &[u8], glyphs: u16) -> Option<Vec<u8>> {
    let mut head = [0_u8; 54];
    head[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
    head[4..8].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
    head[12..16].copy_from_slice(&0x5F0F_3CF5_u32.to_be_bytes());
    head[18..20].copy_from_slice(&1000_u16.to_be_bytes());
    let mut hhea = [0_u8; 36];
    hhea[0..4].copy_from_slice(&0x0001_0000_u32.to_be_bytes());
    hhea[34..36].copy_from_slice(&glyphs.to_be_bytes());
    let mut maxp = [0_u8; 6];
    maxp[0..4].copy_from_slice(&0x0000_5000_u32.to_be_bytes());
    maxp[4..6].copy_from_slice(&glyphs.to_be_bytes());
    let hmtx = vec![0_u8; usize::from(glyphs) * 4];

    let tables: [(&[u8; 4], &[u8]); 5] = [
        (b"CFF ", cff),
        (b"head", &head),
        (b"hhea", &hhea),
        (b"hmtx", &hmtx),
        (b"maxp", &maxp),
    ];
    let count = u16::try_from(tables.len()).ok()?;
    let mut out = Vec::with_capacity(cff.len() + 256);
    out.extend_from_slice(&0x4F54_544F_u32.to_be_bytes());
    out.extend_from_slice(&count.to_be_bytes());
    let pow2 = 1_u32 << u32::from(count).ilog2();
    #[allow(clippy::cast_possible_truncation)]
    let search_range = pow2 * 16;
    out.extend_from_slice(&u16::try_from(search_range).ok()?.to_be_bytes());
    #[allow(clippy::cast_possible_truncation)]
    let entry_selector = count.trailing_zeros() as u16;
    out.extend_from_slice(&entry_selector.to_be_bytes());
    #[allow(clippy::cast_possible_truncation)]
    let range_shift = (u32::from(count) * 16).saturating_sub(search_range) as u16;
    out.extend_from_slice(&range_shift.to_be_bytes());

    let mut offset = 12 + usize::from(count) * 16;
    let mut body: Vec<u8> = Vec::with_capacity(cff.len() + 128);
    for (tag, data) in &tables {
        let mut table = data.to_vec();
        while !table.len().is_multiple_of(4) {
            table.push(0);
        }
        out.extend_from_slice(*tag);
        out.extend_from_slice(&0_u32.to_be_bytes());
        out.extend_from_slice(&u32::try_from(offset).ok()?.to_be_bytes());
        out.extend_from_slice(&u32::try_from(data.len()).ok()?.to_be_bytes());
        offset += table.len();
        body.extend_from_slice(&table);
    }
    out.extend_from_slice(&body);
    Some(out)
}

/// The `CFF ` table inside an OpenType file.
fn cff_table_of_sfnt(data: &[u8]) -> Option<&[u8]> {
    let count = usize::from(u16::from_be_bytes([*data.get(4)?, *data.get(5)?]));
    for index in 0..count {
        let at = 12 + index * 16;
        if data.get(at..at + 4)? == b"CFF " {
            let offset = u32::from_be_bytes([
                *data.get(at + 8)?,
                *data.get(at + 9)?,
                *data.get(at + 10)?,
                *data.get(at + 11)?,
            ]);
            let length = u32::from_be_bytes([
                *data.get(at + 12)?,
                *data.get(at + 13)?,
                *data.get(at + 14)?,
                *data.get(at + 15)?,
            ]);
            let start = usize::try_from(offset).ok()?;
            let end = start.checked_add(usize::try_from(length).ok()?)?;
            return data.get(start..end);
        }
    }
    None
}

/// A CFF table's charset offset and glyph count.
fn cff_layout(cff: &[u8]) -> Option<(usize, u16)> {
    let header_size = usize::from(*cff.get(2)?);
    let (_, after_name) = cff_index(cff, header_size)?;
    let (top_count, after_top) = cff_index(cff, after_name)?;
    if top_count == 0 {
        return None;
    }
    let (_, after_strings) = cff_index(cff, after_top)?;
    let (_, after_global_subrs) = cff_index(cff, after_strings)?;
    let _ = after_global_subrs;
    let top_dict = cff_index_item(cff, after_name, 0)?;
    let charstrings_at = top_dict_operator(top_dict, 17)?;
    let (glyphs, _) = cff_index(cff, charstrings_at)?;
    let charset_at = top_dict_operator(top_dict, 15).unwrap_or(0);
    Some((charset_at, u16::try_from(glyphs).ok()?))
}

/// Whether the Top DICT declares an ROS (registry, ordering, supplement), which
/// is what makes a CFF font CID-keyed (`9.7.4` of the CFF spec).
fn top_dict_declares_ros(cff: &[u8]) -> bool {
    let Some(header_size) = cff.get(2).map(|size| usize::from(*size)) else {
        return false;
    };
    let Some((_, after_name)) = cff_index(cff, header_size) else {
        return false;
    };
    let Some(dict) = cff_index_item(cff, after_name, 0) else {
        return false;
    };
    // Operator 12 30 (ROS): operands, then the two bytes, in that order.
    dict.array_windows::<2>().any(|window| window == &[12, 30])
}

/// The CID → glyph id pairs a CID-keyed CFF charset declares.
///
/// Formats 0, 1 and 2 are read; the three predefined charsets (offsets 0, 1 and
/// 2) are the standard Latin character sets, which are not CID-keyed, so they
/// yield no pairs and the CID is used as the glyph id.
fn cff_charset(cff: &[u8], at: usize, glyphs: u16) -> Vec<(u16, u16)> {
    let mut pairs = Vec::new();
    if at < 3 {
        return pairs;
    }
    let Some(&format) = cff.get(at) else {
        return pairs;
    };
    let mut index = at + 1;
    let mut gid = 1u16;
    match format {
        0 => {
            while gid < glyphs {
                let cid = cff
                    .get(index..index + 2)
                    .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
                let Some(cid) = cid else { break };
                pairs.push((cid, gid));
                gid += 1;
                index += 2;
            }
        }
        1 | 2 => {
            while gid < glyphs {
                let width = if format == 1 { 1 } else { 2 };
                let first = cff
                    .get(index..index + 2)
                    .map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]));
                let left = cff.get(index + 2..index + 2 + width).map(|bytes| {
                    if width == 1 {
                        u16::from(bytes[0])
                    } else {
                        u16::from_be_bytes([bytes[0], bytes[1]])
                    }
                });
                let (Some(first), Some(left)) = (first, left) else {
                    break;
                };
                for offset in 0..=left {
                    if gid >= glyphs {
                        break;
                    }
                    pairs.push((first.wrapping_add(offset), gid));
                    gid += 1;
                }
                index += 2 + width;
            }
        }
        _ => {}
    }
    pairs
}

/// A CFF INDEX: its entry count and the offset just past it.
fn cff_index(data: &[u8], at: usize) -> Option<(usize, usize)> {
    let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
    if count == 0 {
        return Some((0, at + 2));
    }
    let off_size = usize::from(*data.get(at + 2)?);
    if !(1..=4).contains(&off_size) {
        return None;
    }
    let offsets_at = at + 3;
    let data_at = offsets_at + (count + 1) * off_size;
    let mut last = 0;
    for index in 0..off_size {
        last = (last << 8) | usize::from(*data.get(offsets_at + count * off_size + index)?);
    }
    Some((count, data_at + last.saturating_sub(1)))
}

/// One entry of a CFF INDEX, by position.
fn cff_index_item(data: &[u8], at: usize, item: usize) -> Option<&[u8]> {
    let count = usize::from(u16::from_be_bytes([*data.get(at)?, *data.get(at + 1)?]));
    if item >= count {
        return None;
    }
    let off_size = usize::from(*data.get(at + 2)?);
    let offsets_at = at + 3;
    let data_at = offsets_at + (count + 1) * off_size;
    let read = |position: usize| -> Option<usize> {
        let base = offsets_at + position * off_size;
        let mut value = 0;
        for index in 0..off_size {
            value = (value << 8) | usize::from(*data.get(base + index)?);
        }
        Some(value)
    };
    let start = read(item)?;
    let end = read(item + 1)?;
    data.get(data_at + start - 1..data_at + end - 1)
}

/// The last operand of `operator` inside a CFF Top DICT.
fn top_dict_operator(dict: &[u8], operator: u8) -> Option<usize> {
    let mut operands: Vec<f64> = Vec::new();
    let mut index = 0;
    while index < dict.len() {
        let byte = *dict.get(index)?;
        index += 1;
        match byte {
            28 => {
                let value = i16::from_be_bytes([*dict.get(index)?, *dict.get(index + 1)?]);
                operands.push(f64::from(value));
                index += 2;
            }
            29 => {
                let mut bytes = [0_u8; 4];
                for (offset, slot) in bytes.iter_mut().enumerate() {
                    *slot = *dict.get(index + offset)?;
                }
                operands.push(f64::from(i32::from_be_bytes(bytes)));
                index += 4;
            }
            32..=246 => operands.push(f64::from(byte) - 139.0),
            247..=250 => {
                let next = f64::from(*dict.get(index)?);
                operands.push((f64::from(byte) - 247.0) * 256.0 + next + 108.0);
                index += 1;
            }
            251..=254 => {
                let next = f64::from(*dict.get(index)?);
                operands.push(-(f64::from(byte) - 251.0) * 256.0 - next - 108.0);
                index += 1;
            }
            30 => {
                // A real number; no Top DICT operand this module reads needs
                // one, so it is consumed and ignored.
                while index < dict.len() {
                    let nibble = dict[index];
                    index += 1;
                    if nibble & 0x0F == 0x0F || nibble >> 4 == 0x0F {
                        break;
                    }
                }
                operands.push(f64::NAN);
            }
            0..=21 => {
                if byte == 12 {
                    index += 1;
                }
                if byte == operator {
                    if let Some(value) = operands.last()
                        && value.is_finite()
                        && *value >= 0.0
                    {
                        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                        return Some(*value as usize);
                    }
                    return None;
                }
                operands.clear();
            }
            _ => operands.clear(),
        }
    }
    None
}

/// An outline for a glyph id, from a parsed TrueType program.
fn glyph_from_face(data: &[u8], glyph_id: ttf_parser::GlyphId) -> Option<Glyph> {
    let face = ttf_parser::Face::parse(data, 0).ok()?;
    let units = f64::from(face.units_per_em());
    let mut builder = OutlineBuilder::new(units);
    face.outline_glyph(glyph_id, &mut builder)?;
    let advance = f64::from(face.glyph_hor_advance(glyph_id).unwrap_or(0)) / units;
    Some(Glyph {
        contours: builder.contours,
        advance,
    })
}

const BUILTIN_ADVANCE: f64 = 6.0 / 9.0;
const BUILTIN_CELL: f64 = 1.0 / 9.0;
const BUILTIN_WIDTH: u8 = 5;
const BUILTIN_HEIGHT: u8 = 7;

/// A 5×7 bitmap alphabet. Lowercase letters use the uppercase shapes; anything
/// without a pattern is drawn as a notdef box.
fn builtin_glyph(character: char) -> Option<Glyph> {
    let code = u8::try_from(u32::from(character)).ok()?;
    if character == ' ' {
        return Some(Glyph {
            contours: Vec::new(),
            advance: BUILTIN_ADVANCE,
        });
    }
    if let Some(rows) = glyph_rows(code) {
        return Some(Glyph {
            contours: rows_to_contours(&rows),
            advance: BUILTIN_ADVANCE,
        });
    }
    if character == '\u{2022}' {
        return Some(Glyph {
            contours: rows_to_contours(&[0, 0, 0b00100, 0b01110, 0b00100, 0, 0]),
            advance: BUILTIN_ADVANCE,
        });
    }
    // Latin-1 text is the common case for base-14 fonts, so an accented letter
    // is drawn as its unaccented base plus the mark rather than as .notdef.
    if let Some((base, accent)) = decompose(character) {
        let rows = glyph_rows(u8::try_from(u32::from(base)).unwrap_or(b'?'))
            .or_else(|| upper(base).and_then(|upper| glyph_rows(upper as u8)))
            .unwrap_or_else(notdef_rows);
        let mut contours = rows_to_contours(&rows);
        contours.extend(
            accent
                .cells()
                .iter()
                .map(|&(column, layer)| mark_cell(column, layer)),
        );
        return Some(Glyph {
            contours,
            advance: BUILTIN_ADVANCE,
        });
    }
    if character == '\u{00F8}' || character == '\u{00D8}' {
        // `ø` is `o` with a slash through it, which no mark above the box can
        // show, so the slash goes across the glyph body instead.
        let mut contours = rows_to_contours(&glyph_rows(b'O').unwrap_or_else(notdef_rows));
        contours.extend(
            [(0, 5), (1, 4), (2, 3), (3, 2), (4, 1)]
                .iter()
                .map(|&(column, layer)| mark_cell(column, layer)),
        );
        return Some(Glyph {
            contours,
            advance: BUILTIN_ADVANCE,
        });
    }
    let rows = upper(character)
        .and_then(|upper| glyph_rows(upper as u8))
        .unwrap_or_else(notdef_rows);
    Some(Glyph {
        contours: rows_to_contours(&rows),
        advance: BUILTIN_ADVANCE,
    })
}

/// A mark that can sit on a 5×7 base letter: above the glyph box (layers 0 and
/// up) or below the baseline (negative layers, used by the cedilla).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Accent {
    Acute,
    Grave,
    Circumflex,
    Diaeresis,
    Tilde,
    Ring,
    Cedilla,
}

impl Accent {
    /// Cell coordinates: `column` across the five-column box, `layer` up from
    /// the top of the glyph (layer 0 starts at 7/9 em) or, when negative, down
    /// from the baseline.
    fn cells(self) -> &'static [(u8, i8)] {
        match self {
            Self::Acute => &[(2, 0), (3, 0), (3, 1)],
            Self::Grave => &[(2, 1), (3, 1), (3, 0)],
            Self::Circumflex => &[(1, 0), (2, 1), (3, 0)],
            Self::Diaeresis => &[(1, 1), (3, 1)],
            Self::Tilde => &[(1, 1), (2, 0), (3, 1)],
            Self::Ring => &[(1, 0), (2, 1), (3, 0), (2, 0)],
            Self::Cedilla => &[(2, -1), (3, -1), (3, -2)],
        }
    }
}

/// One cell of a mark, as a rectangle in em units.
fn mark_cell(column: u8, layer: i8) -> Vec<Point> {
    let x0 = f64::from(column) * BUILTIN_CELL;
    let x1 = x0 + BUILTIN_CELL;
    let (bottom, top) = if layer < 0 {
        (
            f64::from(layer) * BUILTIN_CELL,
            f64::from(layer + 1) * BUILTIN_CELL,
        )
    } else {
        (
            f64::from(BUILTIN_HEIGHT + layer as u8) * BUILTIN_CELL,
            f64::from(BUILTIN_HEIGHT + layer as u8 + 1) * BUILTIN_CELL,
        )
    };
    vec![
        Point::new(x0, bottom),
        Point::new(x1, bottom),
        Point::new(x1, top),
        Point::new(x0, top),
    ]
}

/// The base letter and mark for a precomposed Latin-1 / Latin Extended-A
/// character the 5×7 alphabet does not carry itself.
fn decompose(character: char) -> Option<(char, Accent)> {
    let (base, accent) = match character {
        'á' | 'Á' => ('a', Accent::Acute),
        'é' | 'É' => ('e', Accent::Acute),
        'í' | 'Í' => ('i', Accent::Acute),
        'ó' | 'Ó' => ('o', Accent::Acute),
        'ú' | 'Ú' => ('u', Accent::Acute),
        'ý' | 'Ý' => ('y', Accent::Acute),
        'à' | 'À' => ('a', Accent::Grave),
        'è' | 'È' => ('e', Accent::Grave),
        'ì' | 'Ì' => ('i', Accent::Grave),
        'ò' | 'Ò' => ('o', Accent::Grave),
        'ù' | 'Ù' => ('u', Accent::Grave),
        'â' | 'Â' => ('a', Accent::Circumflex),
        'ê' | 'Ê' => ('e', Accent::Circumflex),
        'î' | 'Î' => ('i', Accent::Circumflex),
        'ô' | 'Ô' => ('o', Accent::Circumflex),
        'û' | 'Û' => ('u', Accent::Circumflex),
        'ä' | 'Ä' => ('a', Accent::Diaeresis),
        'ë' | 'Ë' => ('e', Accent::Diaeresis),
        'ï' | 'Ï' => ('i', Accent::Diaeresis),
        'ö' | 'Ö' => ('o', Accent::Diaeresis),
        'ü' | 'Ü' => ('u', Accent::Diaeresis),
        'ÿ' | 'Ÿ' => ('y', Accent::Diaeresis),
        'ã' | 'Ã' => ('a', Accent::Tilde),
        'õ' | 'Õ' => ('o', Accent::Tilde),
        'ñ' | 'Ñ' => ('n', Accent::Tilde),
        'å' | 'Å' => ('a', Accent::Ring),
        'ç' | 'Ç' => ('c', Accent::Cedilla),
        _ => return None,
    };
    Some((base, accent))
}

fn upper(character: char) -> Option<char> {
    character
        .to_uppercase()
        .next()
        .filter(|upper| *upper != character)
}

fn notdef_rows() -> [u8; BUILTIN_HEIGHT as usize] {
    [
        0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111,
    ]
}

fn rows_to_contours(rows: &[u8; BUILTIN_HEIGHT as usize]) -> Vec<Vec<Point>> {
    let mut contours = Vec::new();
    for (row, bits) in rows.iter().enumerate() {
        for column in 0..BUILTIN_WIDTH {
            let mask = 1_u8 << (BUILTIN_WIDTH - 1 - column);
            if bits & mask == 0 {
                continue;
            }
            let x0 = f64::from(column) * BUILTIN_CELL;
            let x1 = x0 + BUILTIN_CELL;
            let top = f64::from(BUILTIN_HEIGHT - 1 - row as u8) * BUILTIN_CELL;
            let bottom = top + BUILTIN_CELL;
            contours.push(vec![
                Point::new(x0, bottom),
                Point::new(x1, bottom),
                Point::new(x1, top),
                Point::new(x0, top),
            ]);
        }
    }
    contours
}

fn glyph_rows(code: u8) -> Option<[u8; 7]> {
    let rows = match code {
        b'A' => [
            0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
        ],
        b'B' => [
            0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110,
        ],
        b'C' => [
            0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110,
        ],
        b'D' => [
            0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110,
        ],
        b'E' => [
            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111,
        ],
        b'F' => [
            0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000,
        ],
        b'G' => [
            0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01110,
        ],
        b'H' => [
            0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001,
        ],
        b'I' => [
            0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
        ],
        b'J' => [
            0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100,
        ],
        b'K' => [
            0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001,
        ],
        b'L' => [
            0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111,
        ],
        b'M' => [
            0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001,
        ],
        b'N' => [
            0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001,
        ],
        b'O' => [
            0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
        ],
        b'P' => [
            0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000,
        ],
        b'Q' => [
            0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101,
        ],
        b'R' => [
            0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001,
        ],
        b'S' => [
            0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110,
        ],
        b'T' => [
            0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100,
        ],
        b'U' => [
            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110,
        ],
        b'V' => [
            0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100,
        ],
        b'W' => [
            0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001,
        ],
        b'X' => [
            0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001,
        ],
        b'Y' => [
            0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100,
        ],
        b'Z' => [
            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111,
        ],
        b'0' => [
            0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
        ],
        b'1' => [
            0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
        ],
        b'2' => [
            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
        ],
        b'3' => [
            0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110,
        ],
        b'4' => [
            0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
        ],
        b'5' => [
            0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
        ],
        b'6' => [
            0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
        ],
        b'7' => [
            0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
        ],
        b'8' => [
            0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
        ],
        b'9' => [
            0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
        ],
        b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
        b',' => [0, 0, 0, 0, 0b01100, 0b01100, 0b01000],
        b'!' => [
            0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00000, 0b00100,
        ],
        b'?' => [
            0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b00000, 0b00100,
        ],
        b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
        b':' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0],
        b';' => [0, 0b01100, 0b01100, 0, 0b01100, 0b01100, 0b01000],
        b'\'' => [0b00100, 0b00100, 0b01000, 0, 0, 0, 0],
        b'"' => [0b01010, 0b01010, 0, 0, 0, 0, 0],
        b'(' => [
            0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010,
        ],
        b')' => [
            0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000,
        ],
        b'/' => [
            0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000,
        ],
        b'+' => [0, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0],
        b'=' => [0, 0, 0b11111, 0, 0b11111, 0, 0],
        b'*' => [0, 0b10101, 0b01110, 0b11111, 0b01110, 0b10101, 0],
        b'#' => [
            0b01010, 0b01010, 0b11111, 0b01010, 0b11111, 0b01010, 0b01010,
        ],
        b'%' => [
            0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011,
        ],
        b'&' => [
            0b01100, 0b10010, 0b10100, 0b01000, 0b10101, 0b10010, 0b01101,
        ],
        _ => return None,
    };
    Some(rows)
}

/// Collects `ttf-parser` outlines into em-space contours.
struct OutlineBuilder {
    units: f64,
    contours: Vec<Vec<Point>>,
    current: Vec<Point>,
}

impl OutlineBuilder {
    fn new(units: f64) -> Self {
        Self {
            units,
            contours: Vec::new(),
            current: Vec::new(),
        }
    }

    fn point(&self, x: f32, y: f32) -> Point {
        Point::new(f64::from(x) / self.units, f64::from(y) / self.units)
    }

    fn finish_contour(&mut self) {
        if self.current.len() > 1 {
            self.contours.push(std::mem::take(&mut self.current));
        }
    }
}

impl ttf_parser::OutlineBuilder for OutlineBuilder {
    fn move_to(&mut self, x: f32, y: f32) {
        self.finish_contour();
        self.current.push(self.point(x, y));
    }

    fn line_to(&mut self, x: f32, y: f32) {
        self.current.push(self.point(x, y));
    }

    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
        let Some(&start) = self.current.last() else {
            return;
        };
        let control = self.point(x1, y1);
        let end = self.point(x, y);
        for step in 1..=8 {
            let t = f64::from(step) / 8.0;
            let u = 1.0 - t;
            self.current.push(Point::new(
                u * u * start.x + 2.0 * u * t * control.x + t * t * end.x,
                u * u * start.y + 2.0 * u * t * control.y + t * t * end.y,
            ));
        }
    }

    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
        let Some(&start) = self.current.last() else {
            return;
        };
        let c1 = self.point(x1, y1);
        let c2 = self.point(x2, y2);
        let end = self.point(x, y);
        for step in 1..=12 {
            let t = f64::from(step) / 12.0;
            let u = 1.0 - t;
            self.current.push(Point::new(
                u * u * u * start.x
                    + 3.0 * u * u * t * c1.x
                    + 3.0 * u * t * t * c2.x
                    + t * t * t * end.x,
                u * u * u * start.y
                    + 3.0 * u * u * t * c1.y
                    + 3.0 * u * t * t * c2.y
                    + t * t * t * end.y,
            ));
        }
    }

    fn close(&mut self) {
        self.finish_contour();
    }
}

#[cfg(test)]
mod tests {
    use super::Font;
    use pdf2::Encoding;

    #[test]
    fn the_builtin_font_draws_letters_as_ink() {
        let font = Font::builtin(Encoding::standard());
        let glyph = font.glyph(b'H').expect("H");
        assert!(!glyph.contours.is_empty());
        assert!((glyph.advance - 0.6667).abs() < 1e-3);
        // Every contour is a rectangle inside the glyph box.
        for contour in &glyph.contours {
            assert_eq!(contour.len(), 4);
            for point in contour {
                assert!(point.x >= 0.0 && point.x <= 6.0 / 9.0 + 1e-9);
                assert!(point.y >= 0.0 && point.y <= 7.0 / 9.0 + 1e-9);
            }
        }
    }

    #[test]
    fn the_builtin_font_is_blank_for_space() {
        let font = Font::builtin(Encoding::standard());
        let glyph = font.glyph(b' ').expect("space");
        assert!(glyph.contours.is_empty());
        assert!(glyph.advance > 0.0);
    }

    #[test]
    fn glyph_ids_are_selected_directly_for_composite_fonts() {
        let font = Font::builtin(Encoding::standard());
        assert!(
            font.glyph_by_id(1).is_none(),
            "the bitmap alphabet has no glyph ids"
        );
    }

    #[test]
    fn a_broken_font_program_is_rejected() {
        assert!(Font::true_type(Encoding::standard(), vec![0, 1, 2, 3]).is_none());
        assert!(Font::true_type(Encoding::standard(), Vec::new()).is_none());
    }

    #[test]
    fn accented_latin_composes_instead_of_drawing_notdef() {
        let font = Font::builtin(Encoding::win_ansi());
        // code, the ASCII base the accent is composed onto, and the number of
        // mark cells the accent contributes.
        for (code, base, marks) in [
            (0xE9_u8, b'E', 3), // é, acute
            (0xF1, b'N', 3),    // ñ, tilde
            (0xFC, b'U', 2),    // ü, diaeresis
            (0xE7, b'C', 3),    // ç, cedilla
            (0xE5, b'A', 4),    // å, ring
            (0xE2, b'A', 3),    // â, circumflex
        ] {
            let glyph = font.glyph(code).expect("a composed glyph");
            let plain = font.glyph(base).expect("the base letter");
            assert_eq!(
                glyph.contours.len(),
                plain.contours.len() + marks,
                "{} on {}",
                code as char,
                base as char
            );
            assert_ne!(glyph.contours, plain.contours);
        }
        // Anything the table does not name still falls back to .notdef, and
        // that is a hollow box, not a panic.
        let other = font.glyph(0xA4).expect("undefined code");
        assert_eq!(other.contours.len(), 20, "the notdef box");
    }

    #[test]
    fn marks_sit_outside_the_glyph_box_and_cedillas_below_the_baseline() {
        let font = Font::builtin(Encoding::win_ansi());
        let acute = font.glyph(0xE9).expect("é");
        let top = acute
            .contours
            .iter()
            .flatten()
            .fold(f64::MIN, |max, point| max.max(point.y));
        assert!((7.0 / 9.0..=1.0).contains(&top), "accent tops out at {top}");
        let cedilla = font.glyph(0xE7).expect("ç");
        let bottom = cedilla
            .contours
            .iter()
            .flatten()
            .fold(f64::MAX, |min, point| min.min(point.y));
        assert!(bottom < 0.0, "the cedilla hangs to {bottom}");
    }

    #[test]
    fn unknown_characters_become_the_notdef_box() {
        let font = Font::builtin(Encoding::standard());
        // 0xA4 is undefined in StandardEncoding, so there is no glyph at all.
        assert!(font.glyph(0xA4).is_none());
        // A mapped but unpatterned character gets the notdef box, not a panic.
        let glyph = font.glyph(b'@').expect("@");
        assert_eq!(
            glyph.contours.len(),
            20,
            "the notdef box is a hollow 5×7 frame"
        );
    }
}

#[cfg(test)]
mod cff_tests {
    use super::{Font, cff_layout, top_dict_operator, wrap_cff};

    /// A three-glyph bare CFF built by hand: header, one-entry Name INDEX, a Top
    /// DICT pointing at its CharStrings, empty String and Global Subr INDEXes,
    /// and three empty charstrings (`endchar`).
    fn synthetic_cff() -> Vec<u8> {
        let mut cff = vec![1, 0, 4, 4];
        // Name INDEX: one entry, "A".
        cff.extend_from_slice(&[0, 1, 1, 1, 2, b'A']);
        // Top DICT INDEX: one entry of 6 bytes, CharStrings at offset 25.
        cff.extend_from_slice(&[0, 1, 1, 1, 7]);
        cff.extend_from_slice(&[29, 0, 0, 0, 25, 17]);
        // String INDEX and Global Subr INDEX: both empty.
        cff.extend_from_slice(&[0, 0]);
        cff.extend_from_slice(&[0, 0]);
        assert_eq!(cff.len(), 25, "the CharStrings offset above");
        // CharStrings INDEX: three entries, all empty.
        cff.extend_from_slice(&[0, 3, 1, 1, 1, 1, 1]);
        cff
    }

    #[test]
    fn a_bare_cff_becomes_a_face_ttf_parser_reads() {
        let cff = synthetic_cff();
        let (charset_at, glyphs) = cff_layout(&cff).expect("layout");
        assert_eq!((charset_at, glyphs), (0, 3), "predefined charset, 3 glyphs");
        let wrapped = wrap_cff(&cff, glyphs).expect("wrap");
        let face = ttf_parser::Face::parse(&wrapped, 0).expect("parse the wrapper");
        assert_eq!(face.number_of_glyphs(), 3);
        assert_eq!(face.units_per_em(), 1000);
        assert!(Font::cff(pdf2::Encoding::standard(), cff).is_some());
    }

    #[test]
    fn a_program_without_charstrings_is_refused() {
        // The same file with its Top DICT truncated: no CharStrings operator.
        let cff = synthetic_cff();
        assert!(cff_layout(&cff[..8]).is_none());
        assert!(Font::cff(pdf2::Encoding::standard(), vec![0, 1]).is_none());
    }

    #[test]
    fn the_top_dict_operator_reader_handles_each_number_encoding() {
        // 29 = 32-bit integer, 28 = 16-bit, 32..=246 = byte - 139.
        assert_eq!(top_dict_operator(&[29, 0, 0, 1, 0, 17], 17), Some(256));
        assert_eq!(top_dict_operator(&[28, 1, 0, 17], 17), Some(256));
        assert_eq!(top_dict_operator(&[139 + 42, 17], 17), Some(42));
        // 251..=254 encode negative numbers, which no offset may be.
        assert_eq!(top_dict_operator(&[251, 0, 17], 17), None);
        assert_eq!(
            top_dict_operator(&[29, 0, 0, 0, 9], 17),
            None,
            "no operator"
        );
    }
}

#[cfg(test)]
mod cache_tests {
    use super::Font;
    use pdf2::Encoding;

    fn subset_font() -> Vec<u8> {
        std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/fonts/CrimsonText-Regular-subset.ttf"
        ))
        .expect("the committed subset font")
    }

    #[test]
    fn a_glyph_looked_up_twice_is_the_same_outline() {
        let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
        let first = font.glyph(b'A').expect("A");
        let second = font.glyph(b'A').expect("A");
        assert_eq!(first, second, "the cache returns what the parser did");
        assert!(!first.contours.is_empty(), "A is a drawn glyph");
        assert!(first.advance > 0.0);
        // A different code is a different glyph, not a cache collision.
        let b = font.glyph(b'B').expect("B");
        assert_ne!(first, b);
    }

    #[test]
    fn the_cache_is_shared_by_clones_and_survives_them() {
        let font = Font::true_type(Encoding::standard(), subset_font()).expect("font");
        let clone = font.clone();
        let from_original = font.glyph(b'C').expect("C");
        let from_clone = clone.glyph(b'C').expect("C");
        assert_eq!(from_original, from_clone);
    }

    #[test]
    fn a_program_with_a_cmap_answers_the_question_honestly() {
        let with_cmap = Font::true_type(Encoding::standard(), subset_font()).expect("font");
        assert!(with_cmap.has_character_map());
        assert!(with_cmap.glyph(b'Z').is_some(), "the subset carries Z");
        assert!(
            with_cmap.glyph(0x00).is_none(),
            "an unmapped code has no glyph"
        );
    }

    /// The committed OFL subset, so a `cmap` can be rewritten without a new binary.
    fn fixture_font() -> Vec<u8> {
        std::fs::read(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/fonts/CrimsonText-Regular-subset.ttf"
        ))
        .expect("the committed subset font")
    }

    /// Rewrite a program's `cmap` so it holds exactly one format-0 subtable of the
    /// given platform and encoding, mapping `A` to the glyph the original Unicode
    /// map chose. The table only ever shrinks, so the directory stays valid.
    fn with_one_subtable(program: &[u8], platform: u16, encoding: u16) -> Vec<u8> {
        let mut data = program.to_vec();
        let tables = u16::from_be_bytes([data[4], data[5]]) as usize;
        let mut cmap = None;
        for index in 0..tables {
            let record = 12 + index * 16;
            if &data[record..record + 4] == b"cmap" {
                let offset = u32::from_be_bytes([
                    data[record + 8],
                    data[record + 9],
                    data[record + 10],
                    data[record + 11],
                ]) as usize;
                let length = u32::from_be_bytes([
                    data[record + 12],
                    data[record + 13],
                    data[record + 14],
                    data[record + 15],
                ]) as usize;
                // The glyph the font's own Unicode map gives `A`.
                let face = ttf_parser::Face::parse(program, 0).expect("a parsable subset");
                let glyph = face.glyph_index('A').expect("the subset maps A").0;
                cmap = Some((offset, length, glyph));
            }
        }
        let (offset, length, glyph) = cmap.expect("a cmap table");
        assert!(
            length >= 274,
            "the table has room for a 262-byte format 0 subtable"
        );
        // version, one subtable, its record, then a format 0 subtable of 256 codes.
        let mut table = vec![0_u8; 274];
        table[2..4].copy_from_slice(&1_u16.to_be_bytes());
        table[4..6].copy_from_slice(&platform.to_be_bytes());
        table[6..8].copy_from_slice(&encoding.to_be_bytes());
        table[8..12].copy_from_slice(&12_u32.to_be_bytes());
        table[14..16].copy_from_slice(&262_u16.to_be_bytes());
        table[18 + usize::from(b'A')] = u8::try_from(glyph).expect("a glyph id under 256");
        data[offset..offset + 274].copy_from_slice(&table);
        data
    }

    #[test]
    fn a_macintosh_only_cmap_is_consulted_by_the_code() {
        // The CV that started this: `/TT1`'s program has one `(1,0)` subtable, and a
        // Unicode-only lookup found nothing in it, so every glyph drew air with no
        // report. The code is the Mac Roman byte, so the subtable answers directly.
        let font = Font::true_type(
            Encoding::from_name(b"MacRomanEncoding"),
            with_one_subtable(&fixture_font(), 1, 0),
        )
        .expect("the patched subset loads");
        assert!(font.has_character_map(), "a (1,0) subtable is usable");
        let glyph = font
            .glyph(b'A')
            .expect("A reaches its glyph through the Mac map");
        assert!(!glyph.contours.is_empty(), "and the glyph has an outline");
    }

    #[test]
    fn a_cmap_no_reader_can_consult_is_reported_as_such() {
        // `(3,2)` is neither Unicode nor Macintosh Roman: nothing can be decoded, and
        // the caller reports `font:TrueType-without-cmap` instead of a blank page.
        let font = Font::true_type(
            Encoding::standard(),
            with_one_subtable(&fixture_font(), 3, 2),
        )
        .expect("the patched subset loads");
        assert!(!font.has_character_map());
        assert!(font.glyph(b'A').is_none());
    }
}