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
//! Reading an OpenType or TrueType font, ported from `sfnt.c`, `tt_table.c`,
//! `tt_cmap.c` and `tt_post.c` in tectonic's `xdvipdfmx`.
//!
//! This is the modern half of the font problem. A `.tfm` says how wide a
//! character is and a `.pk` says what its pixels are, but a document set in an
//! OpenType font names the file itself, and everything a driver needs is
//! inside it: how many units to the em, how wide each glyph is, which glyph a
//! character maps to, and what the glyphs are called.
//!
//! The container is Apple's `sfnt`: a directory of tables, each with a
//! four-character tag, an offset and a length. The tables that matter here are
//! the ones `xdvipdfmx` reads before it can put a glyph on a page --
//! `head`, `hhea`, `maxp`, `hmtx`, `name`, `cmap` and `post`. The outlines
//! themselves (`glyf` or `CFF`) are not read: a driver embeds those, it does
//! not interpret them, and texrs has nothing to embed them into yet.
use std::collections::BTreeMap;
use std::path::Path;
/// One entry of the table directory.
#[derive(Debug, Clone, PartialEq)]
pub struct Table {
pub tag: String,
pub checksum: u32,
pub offset: usize,
pub length: usize,
}
/// One string a font carries: which platform and language it is for, which of
/// the standard names it is, and the text.
#[derive(Debug, Clone, PartialEq)]
pub struct NameRecord {
pub platform: u16,
pub encoding: u16,
pub language: u16,
/// 1 family, 2 subfamily, 4 full name, 5 version, 6 PostScript name.
pub id: u16,
pub text: String,
}
/// `head`: what the whole font is measured in.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Head {
/// The em, in font units. Everything else in the font is in these.
pub units_per_em: u16,
pub x_min: i16,
pub y_min: i16,
pub x_max: i16,
pub y_max: i16,
/// Whether `loca` holds shorts or longs, which is how `glyf` is found.
pub long_loca: bool,
}
/// `hhea`: how the line is laid out, and how much of `hmtx` is widths.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Hhea {
pub ascender: i16,
pub descender: i16,
pub line_gap: i16,
pub number_of_h_metrics: u16,
}
/// A font.
///
/// The bytes are kept: a table is a range of them, and a driver reads several
/// tables of a font it has opened once.
pub struct Sfnt {
bytes: Vec<u8>,
/// The signature: `0x00010000` for TrueType outlines, `OTTO` for CFF ones.
pub signature: u32,
pub tables: Vec<Table>,
}
/// A big-endian read that says where it ran out rather than panicking.
fn number(bytes: &[u8], at: usize, width: usize) -> Result<u64, String> {
bytes
.get(at..at + width)
.map(|region| {
region
.iter()
.fold(0u64, |value, &b| (value << 8) | b as u64)
})
.ok_or_else(|| format!("byte {at} is past the end of the font"))
}
fn u16_at(bytes: &[u8], at: usize) -> Result<u16, String> {
Ok(number(bytes, at, 2)? as u16)
}
fn i16_at(bytes: &[u8], at: usize) -> Result<i16, String> {
Ok(number(bytes, at, 2)? as u16 as i16)
}
fn u32_at(bytes: &[u8], at: usize) -> Result<u32, String> {
Ok(number(bytes, at, 4)? as u32)
}
/// A table's checksum: its bytes read as big-endian longs and added up, the
/// tail padded with zeros. What the directory carries beside every table.
fn checksum(body: &[u8]) -> u32 {
body.chunks(4).fold(0u32, |sum, word| {
let mut four = [0u8; 4];
four[..word.len()].copy_from_slice(word);
sum.wrapping_add(u32::from_be_bytes(four))
})
}
fn tag_at(bytes: &[u8], at: usize) -> Result<String, String> {
Ok(bytes
.get(at..at + 4)
.ok_or("a tag past the end of the font")?
.iter()
.map(|&b| b as char)
.collect())
}
impl std::fmt::Debug for Sfnt {
/// Without the bytes: a font is megabytes, and what a person wants to see
/// is which tables it holds.
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Sfnt")
.field("signature", &format_args!("0x{:08x}", self.signature))
.field("bytes", &self.bytes.len())
.field(
"tables",
&self
.tables
.iter()
.map(|t| t.tag.as_str())
.collect::<Vec<_>>(),
)
.finish()
}
}
impl Sfnt {
pub fn open(path: impl AsRef<Path>) -> Result<Sfnt, String> {
let path = path.as_ref();
let bytes =
std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
Sfnt::parse(bytes).map_err(|e| format!("{}: {e}", path.display()))
}
/// Read the table directory.
///
/// A font collection (`ttcf`) holds several fonts in one file with their
/// tables shared; this reads the first, as a driver does when a document
/// names the file rather than a face inside it.
pub fn parse(bytes: Vec<u8>) -> Result<Sfnt, String> {
let mut signature = u32_at(&bytes, 0)?;
let mut directory = 0usize;
if &tag_at(&bytes, 0)? == "ttcf" {
// A collection: the offsets of its fonts follow the count.
let count = u32_at(&bytes, 8)?;
if count == 0 {
return Err("a font collection holding no fonts".into());
}
directory = u32_at(&bytes, 12)? as usize;
signature = u32_at(&bytes, directory)?;
}
match signature {
// TrueType outlines, CFF outlines, and Apple's older signature.
0x0001_0000 | 0x4f54_544f | 0x7472_7565 => {}
other => {
return Err(format!(
"0x{other:08x} is not a font signature (00010000, OTTO or true)"
))
}
}
let count = u16_at(&bytes, directory + 4)? as usize;
// A directory entry is sixteen bytes, and a font with thousands of
// tables is a damaged file rather than an ambitious one.
if count > 512 {
return Err(format!("{count} tables is not a font"));
}
let mut tables = Vec::with_capacity(count);
for i in 0..count {
let at = directory + 12 + i * 16;
tables.push(Table {
tag: tag_at(&bytes, at)?,
checksum: u32_at(&bytes, at + 4)?,
offset: u32_at(&bytes, at + 8)? as usize,
length: u32_at(&bytes, at + 12)? as usize,
});
}
Ok(Sfnt {
bytes,
signature,
tables,
})
}
/// A table's bytes, or `None` when the font has no such table.
pub fn table(&self, tag: &str) -> Option<&[u8]> {
// A tag is four characters, so `CFF` is stored as `CFF `; either
// spelling finds it.
let entry = self.tables.iter().find(|t| t.tag.trim() == tag.trim())?;
// A length that runs past the end is a damaged font, and the bytes
// that are there are still worth reading.
let end = (entry.offset + entry.length).min(self.bytes.len());
self.bytes.get(entry.offset..end)
}
/// Whether the outlines are CFF (`OTTO`) rather than TrueType.
pub fn is_cff(&self) -> bool {
self.signature == 0x4f54_544f
}
pub fn head(&self) -> Result<Head, String> {
let head = self.table("head").ok_or("the font has no head table")?;
Ok(Head {
units_per_em: u16_at(head, 18)?,
x_min: i16_at(head, 36)?,
y_min: i16_at(head, 38)?,
x_max: i16_at(head, 40)?,
y_max: i16_at(head, 42)?,
long_loca: u16_at(head, 50)? == 1,
})
}
pub fn hhea(&self) -> Result<Hhea, String> {
let hhea = self.table("hhea").ok_or("the font has no hhea table")?;
Ok(Hhea {
ascender: i16_at(hhea, 4)?,
descender: i16_at(hhea, 6)?,
line_gap: i16_at(hhea, 8)?,
number_of_h_metrics: u16_at(hhea, 34)?,
})
}
/// The height of a lowercase `x`, in font units.
///
/// This is what fontspec's `Scale=MatchLowercase` matches: a display face
/// set beside a text face at the same nominal size looks wrong when their
/// x-heights differ, so the ratio of the two is the scale. Orbitron's is
/// large against Arimo's, which is why an unscaled `\Huge` heading is
/// visibly bigger than the document asked for.
///
/// `OS/2` states it directly from version 2 on (`sxHeight`, offset 86).
/// Version 0 and 1 predate the field, and `None` there is honest: the
/// caller scales by 1 rather than by a guess.
pub fn x_height(&self) -> Option<i16> {
let os2 = self.table("OS/2")?;
if u16_at(os2, 0).ok()? < 2 {
return None;
}
i16_at(os2, 86).ok().filter(|h| *h > 0)
}
/// How many glyphs the font holds.
pub fn num_glyphs(&self) -> Result<u16, String> {
let maxp = self.table("maxp").ok_or("the font has no maxp table")?;
u16_at(maxp, 4)
}
/// Every glyph's advance width, in font units.
///
/// `hmtx` stops repeating itself once the widths do: after
/// `number_of_h_metrics` entries the last width holds for every glyph that
/// follows, which is how a monospaced font stores one width for thousands
/// of glyphs.
pub fn advance_widths(&self) -> Result<Vec<u16>, String> {
let hmtx = self.table("hmtx").ok_or("the font has no hmtx table")?;
let metrics = self.hhea()?.number_of_h_metrics as usize;
let glyphs = self.num_glyphs()? as usize;
if metrics == 0 {
return Err("hhea says the font has no widths".into());
}
let mut out = Vec::with_capacity(glyphs);
let mut last = 0u16;
for glyph in 0..glyphs {
if glyph < metrics {
last = u16_at(hmtx, glyph * 4)?;
}
out.push(last);
}
Ok(out)
}
/// The font, carrying only the outlines of the glyphs named -- and every
/// glyph id it had, so a glyph is still found where it was.
///
/// A document that borrows box drawing from a broad face borrows nine
/// glyphs from fifty thousand, and embedding the file whole puts 23 MB into
/// a book to draw them: measured on Arial Unicode, which is what the corpus
/// books' own fallback chain names first. This is why every driver
/// subsets. The ids are NOT renumbered, because a `/CIDToGIDMap /Identity`
/// font addresses a glyph by the id the face gave it, and renumbering would
/// mean rewriting `cmap` to agree; instead `loca` keeps its full length and
/// every glyph not asked for becomes a zero-length entry, which is how a
/// TrueType font spells "this glyph is blank".
///
/// Composite glyphs name their parts by glyph id, so a part is kept
/// whenever the glyph built out of it is (`glyf`, the component flags loop).
/// Dropping one would leave an accent without its letter.
pub fn subset(&self, keep: &std::collections::BTreeSet<u16>) -> Result<Vec<u8>, String> {
self.cut(keep, &[])
}
/// The same, for a font a PDF addresses by CODE rather than by glyph id.
///
/// A simple `/TrueType` font written with `/Encoding /WinAnsiEncoding` is
/// resolved by the reader through the face's OWN `cmap` (S9.6.6.4): the code
/// names a character and the character names the glyph. A subset that
/// dropped `cmap` would leave the reader nothing to go from a code to an
/// outline with, and the page would come out blank -- so the table travels
/// whole. It costs a few kilobytes against the hundreds the outlines cost,
/// the glyph ids did not change so every entry still points where it did,
/// and an entry naming a glyph that is now empty is one nothing asks for.
pub fn subset_encoded(
&self,
keep: &std::collections::BTreeSet<u16>,
) -> Result<Vec<u8>, String> {
self.cut(keep, &["cmap"])
}
/// The subset itself; `also` names tables to carry beyond the ones a
/// glyph-addressed font needs.
fn cut(
&self,
keep: &std::collections::BTreeSet<u16>,
also: &[&str],
) -> Result<Vec<u8>, String> {
let glyphs = self.num_glyphs()? as usize;
let long = self.head()?.long_loca;
let loca = self.table("loca").ok_or("the font has no loca table")?;
let glyf = self.table("glyf").ok_or("the font has no glyf table")?;
let at = |glyph: usize| -> Result<usize, String> {
match long {
true => Ok(u32_at(loca, glyph * 4)? as usize),
false => Ok(u16_at(loca, glyph * 2)? as usize * 2),
}
};
let record = |glyph: usize| -> Option<&[u8]> {
let (from, to) = (at(glyph).ok()?, at(glyph + 1).ok()?);
match to > from {
true => glyf.get(from..to.min(glyf.len())),
false => None,
}
};
// The parts a composite is built out of, and the parts of those.
let mut wanted: std::collections::BTreeSet<u16> = keep.clone();
let mut pending: Vec<u16> = wanted.iter().copied().collect();
while let Some(glyph) = pending.pop() {
let Some(body) = record(glyph as usize) else {
continue;
};
// A negative contour count is what marks a composite (`glyf`).
if i16_at(body, 0).unwrap_or(0) >= 0 {
continue;
}
let mut cursor = 10usize;
while let (Ok(flags), Ok(part)) = (u16_at(body, cursor), u16_at(body, cursor + 2)) {
if wanted.insert(part) {
pending.push(part);
}
// ARG_1_AND_2_ARE_WORDS doubles the two arguments; the three
// transform flags each carry their own number of F2Dot14s.
cursor += 4 + if flags & 0x0001 != 0 { 4 } else { 2 };
cursor += match flags {
f if f & 0x0008 != 0 => 2,
f if f & 0x0040 != 0 => 4,
f if f & 0x0080 != 0 => 8,
_ => 0,
};
// MORE_COMPONENTS.
if flags & 0x0020 == 0 {
break;
}
}
}
// `glyf`, and the offsets into it. Every record is padded to four
// bytes, so an offset is always even and either `loca` form can state
// it; the short form halves a table that is one entry per glyph of a
// face that may hold fifty thousand, and reaches to 128 KB of outlines,
// which is far more than a document borrows.
let mut new_glyf: Vec<u8> = Vec::new();
let mut offsets: Vec<usize> = Vec::with_capacity(glyphs + 1);
for glyph in 0..glyphs {
offsets.push(new_glyf.len());
if wanted.contains(&(glyph as u16)) {
if let Some(body) = record(glyph) {
new_glyf.extend_from_slice(body);
while !new_glyf.len().is_multiple_of(4) {
new_glyf.push(0);
}
}
}
}
offsets.push(new_glyf.len());
let short = new_glyf.len() <= 0x1_FFFE;
let new_loca: Vec<u8> = match short {
true => offsets
.iter()
.flat_map(|at| ((at / 2) as u16).to_be_bytes())
.collect(),
false => offsets
.iter()
.flat_map(|at| (*at as u32).to_be_bytes())
.collect(),
};
// `head` says which form `loca` is in, and its checksum covers a file
// that no longer exists; both are corrected here.
let mut head = self
.table("head")
.ok_or("the font has no head table")?
.to_vec();
if head.len() < 54 {
return Err("the head table is too short to be one".into());
}
head[8..12].copy_from_slice(&0u32.to_be_bytes());
head[50..52].copy_from_slice(&u16::from(!short).to_be_bytes());
// `hmtx` is four bytes a glyph up to `hhea`'s count and one width for
// every glyph after it, so cutting the count at the last glyph borrowed
// drops the rest: 200 KB of widths for glyphs the file never draws. The
// ones past the cut then read as the last width, which is what that
// rule means and is a width nothing asks for.
let mut hhea = self
.table("hhea")
.ok_or("the font has no hhea table")?
.to_vec();
let mut hmtx = self.table("hmtx").map(<[u8]>::to_vec).unwrap_or_default();
let metrics = self.hhea()?.number_of_h_metrics as usize;
let last = wanted
.iter()
.next_back()
.map(|g| *g as usize + 1)
.unwrap_or(1);
if hhea.len() >= 36 && last < metrics && hmtx.len() >= last * 4 {
hmtx.truncate(last * 4);
hhea[34..36].copy_from_slice(&(last as u16).to_be_bytes());
}
// What a glyph-addressed font needs and nothing else: no `cmap` unless
// the caller asked for one, since a code there is a glyph id; no
// `name`, `post` or layout tables, since nothing looks a glyph up by
// name. `cvt `, `fpgm` and `prep` are the hinting programs, kept
// because a glyph's instructions call them.
let mut tables: Vec<(String, Vec<u8>)> = vec![
("head".to_string(), head),
("hhea".to_string(), hhea),
("hmtx".to_string(), hmtx),
("glyf".to_string(), new_glyf),
("loca".to_string(), new_loca),
];
for tag in ["maxp", "cvt ", "fpgm", "prep"].iter().chain(also) {
if let Some(body) = self.table(tag) {
tables.push((tag.to_string(), body.to_vec()));
}
}
tables.sort_by(|a, b| a.0.cmp(&b.0));
// The directory: a header, then one entry a table, then the tables
// themselves, each starting on a four-byte boundary.
let count = tables.len();
let mut out: Vec<u8> = Vec::new();
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
out.extend_from_slice(&(count as u16).to_be_bytes());
let entry_selector = (usize::BITS - 1 - count.leading_zeros().min(usize::BITS - 1)) as u16;
let search_range = 16u16 << entry_selector;
out.extend_from_slice(&search_range.to_be_bytes());
out.extend_from_slice(&entry_selector.to_be_bytes());
out.extend_from_slice(&(count as u16 * 16 - search_range).to_be_bytes());
let mut offset = 12 + count * 16;
for (tag, body) in &tables {
out.extend_from_slice(tag.as_bytes());
out.extend_from_slice(&checksum(body).to_be_bytes());
out.extend_from_slice(&(offset as u32).to_be_bytes());
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
offset += body.len().next_multiple_of(4);
}
for (_, body) in &tables {
out.extend_from_slice(body);
while !out.len().is_multiple_of(4) {
out.push(0);
}
}
Ok(out)
}
/// The font's CFF outlines, when it has them.
pub fn cff(&self) -> Option<crate::cff::Cff> {
crate::cff::Cff::parse(self.table("CFF")?).ok()
}
/// The `name` table, as it is stored.
pub fn names(&self) -> Result<Vec<NameRecord>, String> {
let name = self.table("name").ok_or("the font has no name table")?;
let count = u16_at(name, 2)? as usize;
let strings = u16_at(name, 4)? as usize;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let at = 6 + i * 12;
let platform = u16_at(name, at)?;
let encoding = u16_at(name, at + 2)?;
let language = u16_at(name, at + 4)?;
let id = u16_at(name, at + 6)?;
let length = u16_at(name, at + 8)? as usize;
let offset = u16_at(name, at + 10)? as usize;
let Some(raw) = name.get(strings + offset..strings + offset + length) else {
continue;
};
// Windows and Unicode strings are UTF-16 big-endian; Macintosh
// ones are a single byte each, and are ASCII in practice.
let text = match platform == 1 {
true => raw.iter().map(|&b| b as char).collect(),
false => {
// Two bytes to a unit, big-endian, as everything in an
// sfnt is.
let units: Vec<u16> = raw
.as_chunks::<2>()
.0
.iter()
.map(|pair| u16::from_be_bytes(*pair))
.collect();
String::from_utf16_lossy(&units)
}
};
out.push(NameRecord {
platform,
encoding,
language,
id,
text,
});
}
Ok(out)
}
/// One name, preferring the Windows entry a driver reads first.
///
/// The ids are the ones every font carries: 1 family, 2 subfamily, 4 full
/// name, 5 version, 6 PostScript name.
pub fn name(&self, id: u16) -> Option<String> {
let names = self.names().ok()?;
names
.iter()
.find(|record| record.platform == 3 && record.id == id)
.or_else(|| names.iter().find(|record| record.id == id))
.map(|record| record.text.clone())
}
/// What character maps to what glyph.
///
/// A font carries several `cmap` subtables for different platforms; this
/// reads the one a driver would, preferring the Unicode ones that can say
/// more than 65535 characters.
pub fn cmap(&self) -> Result<BTreeMap<u32, u16>, String> {
let cmap = self.table("cmap").ok_or("the font has no cmap table")?;
let count = u16_at(cmap, 2)? as usize;
let mut best: Option<(u8, usize)> = None;
for i in 0..count {
let at = 4 + i * 8;
let platform = u16_at(cmap, at)?;
let encoding = u16_at(cmap, at + 2)?;
let offset = u32_at(cmap, at + 4)? as usize;
// Windows full Unicode, then Windows basic Unicode, then Unicode,
// then Macintosh -- the order xdvipdfmx tries them in.
let rank = match (platform, encoding) {
(3, 10) => 4,
(3, 1) => 3,
(0, _) => 2,
(1, 0) => 1,
_ => 0,
};
if rank > 0 && best.is_none_or(|(best_rank, _)| rank > best_rank) {
best = Some((rank, offset));
}
}
let (_, offset) = best.ok_or("the font's cmap holds no subtable this can read")?;
let sub = cmap
.get(offset..)
.ok_or("a cmap subtable past the end of the table")?;
let mut out = BTreeMap::new();
match u16_at(sub, 0)? {
// A byte to a glyph, which is what an old Macintosh font used.
0 => {
for code in 0..256usize {
let glyph = *sub.get(6 + code).ok_or("a short format 0 subtable")? as u16;
if glyph != 0 {
out.insert(code as u32, glyph);
}
}
}
// Segments, with a delta or an array per segment. This is the one
// nearly every font uses, and the one with the pointer arithmetic
// worth getting right.
4 => {
let segments = u16_at(sub, 6)? as usize / 2;
let ends = 14;
let starts = ends + segments * 2 + 2;
let deltas = starts + segments * 2;
let ranges = deltas + segments * 2;
for segment in 0..segments {
let end = u16_at(sub, ends + segment * 2)?;
let start = u16_at(sub, starts + segment * 2)?;
let delta = u16_at(sub, deltas + segment * 2)?;
let range = u16_at(sub, ranges + segment * 2)? as usize;
if start > end {
continue;
}
for code in start..=end {
if code == 0xffff {
continue;
}
let glyph = match range == 0 {
true => code.wrapping_add(delta),
false => {
// The offset is from the range entry itself,
// which is what makes this table compact and
// its readers wrong.
let at = ranges + segment * 2 + range + (code - start) as usize * 2;
match u16_at(sub, at)? {
0 => 0,
glyph => glyph.wrapping_add(delta),
}
}
};
if glyph != 0 {
out.insert(code as u32, glyph);
}
}
}
}
// A run of codes from a first one.
6 => {
let first = u16_at(sub, 6)? as u32;
let count = u16_at(sub, 8)? as u32;
for i in 0..count {
let glyph = u16_at(sub, 10 + i as usize * 2)?;
if glyph != 0 {
out.insert(first + i, glyph);
}
}
}
// Groups, for the characters above 65535.
12 => {
let groups = u32_at(sub, 12)? as usize;
for group in 0..groups {
let at = 16 + group * 12;
let start = u32_at(sub, at)?;
let end = u32_at(sub, at + 4)?;
let glyph = u32_at(sub, at + 8)?;
if start > end || end - start > 0x10_ffff {
continue;
}
for code in start..=end {
let glyph = glyph + (code - start);
if glyph != 0 && glyph <= u16::MAX as u32 {
out.insert(code, glyph as u16);
}
}
}
}
other => return Err(format!("cmap format {other} is not one this reads")),
}
Ok(out)
}
/// What the glyphs are called.
///
/// A TrueType font carries its names in `post`; a CFF font carries them in
/// the CFF charset, which [`crate::cff`] reads. Either way this answers,
/// because a driver asking what a glyph is called does not care which kind
/// of font it has.
pub fn glyph_names(&self) -> Result<Vec<String>, String> {
// The CFF is asked first, because a CFF font's `post` is version 3.0
// and carries no names at all.
if let Some(table) = self.table("CFF") {
return Ok(crate::cff::Cff::parse(table)?.glyph_names);
}
let post = self.table("post").ok_or("the font has no post table")?;
let version = u32_at(post, 0)?;
if version != 0x0002_0000 {
return Err(format!(
"post version {}.{} carries no names",
version >> 16,
version & 0xffff
));
}
let count = u16_at(post, 32)? as usize;
let mut indices = Vec::with_capacity(count);
for glyph in 0..count {
indices.push(u16_at(post, 34 + glyph * 2)? as usize);
}
// The names that are not standard follow, as Pascal strings.
let mut extra: Vec<String> = Vec::new();
let mut at = 34 + count * 2;
while at < post.len() {
let length = post[at] as usize;
at += 1;
let Some(raw) = post.get(at..at + length) else {
break;
};
extra.push(raw.iter().map(|&b| b as char).collect());
at += length;
}
Ok(indices
.iter()
.map(|&index| match index < MAC_GLYPH_NAMES.len() {
true => MAC_GLYPH_NAMES[index].to_string(),
false => extra
.get(index - MAC_GLYPH_NAMES.len())
.cloned()
.unwrap_or_else(|| format!("glyph{index}")),
})
.collect())
}
/// A summary a person reads.
pub fn summary(&self) -> String {
let mut out = String::new();
for (label, id) in [
("family", 1u16),
("subfamily", 2),
("full name", 4),
("version", 5),
("postscript", 6),
] {
if let Some(text) = self.name(id) {
out.push_str(&format!("{label:<13} {}\n", text.trim()));
}
}
out.push_str(&format!(
"outlines {}\n",
match self.is_cff() {
true => "CFF",
false => "TrueType",
}
));
if let Ok(head) = self.head() {
out.push_str(&format!("units per em {}\n", head.units_per_em));
out.push_str(&format!(
"bounding box {} {} {} {}\n",
head.x_min, head.y_min, head.x_max, head.y_max
));
}
if let Ok(hhea) = self.hhea() {
out.push_str(&format!(
"ascender {} descender {} line gap {}\n",
hhea.ascender, hhea.descender, hhea.line_gap
));
}
if let Ok(glyphs) = self.num_glyphs() {
out.push_str(&format!("glyphs {glyphs}\n"));
}
if let Ok(cmap) = self.cmap() {
out.push_str(&format!("characters {}\n", cmap.len()));
}
out.push_str(&format!("tables {}\n", self.tables.len()));
for table in &self.tables {
out.push_str(&format!(" {:<5} {:>8} bytes\n", table.tag, table.length));
}
out
}
/// What one character becomes: the glyph it maps to, its number, its name
/// where the font says one, and how wide it is.
pub fn describe(&self, code: u32) -> String {
let Ok(cmap) = self.cmap() else {
return "the font has no cmap this reads\n".to_string();
};
let shown = match char::from_u32(code) {
Some(c) if c.is_ascii_graphic() => format!("'{c}'"),
_ => format!("U+{code:04X}"),
};
let Some(&glyph) = cmap.get(&code) else {
return format!("{shown}: the font has no glyph for it\n");
};
let name = self
.glyph_names()
.ok()
.and_then(|names| names.get(glyph as usize).cloned());
let width = self
.advance_widths()
.ok()
.and_then(|widths| widths.get(glyph as usize).copied());
let units = self.head().map(|h| h.units_per_em).unwrap_or(1000);
let mut out = format!("{shown} glyph {glyph}");
if let Some(name) = name {
out.push_str(&format!(" ({name})"));
}
if let Some(width) = width {
out.push_str(&format!(
" width {width} of {units} ({:.4} em)",
width as f64 / units as f64
));
}
out.push('\n');
out
}
}
/// The 258 names a `post` table numbers rather than spells, from `tt_post.c`.
/// A font that uses only these carries no strings at all.
pub const MAC_GLYPH_NAMES: [&str; 258] = [
".notdef",
".null",
"nonmarkingreturn",
"space",
"exclam",
"quotedbl",
"numbersign",
"dollar",
"percent",
"ampersand",
"quotesingle",
"parenleft",
"parenright",
"asterisk",
"plus",
"comma",
"hyphen",
"period",
"slash",
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"colon",
"semicolon",
"less",
"equal",
"greater",
"question",
"at",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
"bracketleft",
"backslash",
"bracketright",
"asciicircum",
"underscore",
"grave",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"braceleft",
"bar",
"braceright",
"asciitilde",
"Adieresis",
"Aring",
"Ccedilla",
"Eacute",
"Ntilde",
"Odieresis",
"Udieresis",
"aacute",
"agrave",
"acircumflex",
"adieresis",
"atilde",
"aring",
"ccedilla",
"eacute",
"egrave",
"ecircumflex",
"edieresis",
"iacute",
"igrave",
"icircumflex",
"idieresis",
"ntilde",
"oacute",
"ograve",
"ocircumflex",
"odieresis",
"otilde",
"uacute",
"ugrave",
"ucircumflex",
"udieresis",
"dagger",
"degree",
"cent",
"sterling",
"section",
"bullet",
"paragraph",
"germandbls",
"registered",
"copyright",
"trademark",
"acute",
"dieresis",
"notequal",
"AE",
"Oslash",
"infinity",
"plusminus",
"lessequal",
"greaterequal",
"yen",
"mu",
"partialdiff",
"summation",
"product",
"pi",
"integral",
"ordfeminine",
"ordmasculine",
"Omega",
"ae",
"oslash",
"questiondown",
"exclamdown",
"logicalnot",
"radical",
"florin",
"approxequal",
"Delta",
"guillemotleft",
"guillemotright",
"ellipsis",
"nonbreakingspace",
"Agrave",
"Atilde",
"Otilde",
"OE",
"oe",
"endash",
"emdash",
"quotedblleft",
"quotedblright",
"quoteleft",
"quoteright",
"divide",
"lozenge",
"ydieresis",
"Ydieresis",
"fraction",
"currency",
"guilsinglleft",
"guilsinglright",
"fi",
"fl",
"daggerdbl",
"periodcentered",
"quotesinglbase",
"quotedblbase",
"perthousand",
"Acircumflex",
"Ecircumflex",
"Aacute",
"Edieresis",
"Egrave",
"Iacute",
"Icircumflex",
"Idieresis",
"Igrave",
"Oacute",
"Ocircumflex",
"apple",
"Ograve",
"Uacute",
"Ucircumflex",
"Ugrave",
"dotlessi",
"circumflex",
"tilde",
"macron",
"breve",
"dotaccent",
"ring",
"cedilla",
"hungarumlaut",
"ogonek",
"caron",
"Lslash",
"lslash",
"Scaron",
"scaron",
"Zcaron",
"zcaron",
"brokenbar",
"Eth",
"eth",
"Yacute",
"yacute",
"Thorn",
"thorn",
"minus",
"multiply",
"onesuperior",
"twosuperior",
"threesuperior",
"onehalf",
"onequarter",
"threequarters",
"franc",
"Gbreve",
"gbreve",
"Idotaccent",
"Scedilla",
"scedilla",
"Cacute",
"cacute",
"Ccaron",
"ccaron",
"dcroat",
];
#[cfg(test)]
mod tests {
use super::*;
fn installed(name: &str) -> Option<Vec<u8>> {
let found = std::process::Command::new("kpsewhich")
.arg(name)
.output()
.ok()?;
let path = String::from_utf8_lossy(&found.stdout).trim().to_string();
std::fs::read(path).ok()
}
/// Latin Modern, which is Computer Modern as an OpenType font -- the one a
/// document that says `\usepackage{lmodern}` and runs on a modern engine
/// is set in.
#[test]
fn an_opentype_font_says_what_it_holds() {
let Some(bytes) = installed("lmroman10-regular.otf") else {
return;
};
let font = Sfnt::parse(bytes).expect("lmroman reads");
assert!(font.is_cff(), "Latin Modern carries CFF outlines");
assert_eq!(font.name(1).as_deref(), Some("LM Roman 10"));
assert_eq!(font.name(6).as_deref(), Some("LMRoman10-Regular"));
let head = font.head().expect("a head table");
assert_eq!(head.units_per_em, 1000, "a CFF font counts in thousandths");
assert!(head.x_max > head.x_min && head.y_max > head.y_min);
// The characters a Latin font must have map to glyphs, and the widths
// are the ones the metrics say.
let cmap = font.cmap().expect("a cmap");
let widths = font.advance_widths().expect("widths");
for c in ['A', 'z', '0', ' ', '\u{e9}'] {
let glyph = *cmap
.get(&(c as u32))
.unwrap_or_else(|| panic!("no glyph for {c:?}"));
assert!(
(glyph as usize) < widths.len(),
"{c:?} maps past the end of hmtx"
);
}
// An A in Computer Modern is 750 thousandths of an em, as its .tfm
// says.
let a = widths[cmap[&(b'A' as u32)] as usize];
assert_eq!(a, 750, "an A is 0.75em");
// A space is narrower than an m.
assert!(widths[cmap[&(b' ' as u32)] as usize] < widths[cmap[&(b'm' as u32)] as usize]);
}
/// A TrueType font, which carries its glyph names where an OpenType one
/// does not.
#[test]
fn a_truetype_font_carries_its_glyph_names() {
let path = "/usr/local/texlive/2026/texmf-dist/fonts/truetype/intel/clearsans/ClearSans-Regular.ttf";
let Ok(bytes) = std::fs::read(path) else {
return;
};
let font = Sfnt::parse(bytes).expect("reads");
assert!(!font.is_cff());
let names = font.glyph_names().expect("post 2.0 names");
assert_eq!(names.len(), font.num_glyphs().expect("maxp") as usize);
assert_eq!(names[0], ".notdef", "glyph zero is always the empty one");
// The name of the glyph an A maps to is the name an A has.
let cmap = font.cmap().expect("a cmap");
let a = cmap[&(b'A' as u32)] as usize;
assert_eq!(names[a], "A");
}
/// What is not a font is refused rather than read as one.
#[test]
fn what_is_not_a_font_is_refused() {
assert!(Sfnt::parse(Vec::new()).is_err());
assert!(Sfnt::parse(b"not a font at all".to_vec()).is_err());
// A .pk begins with 247, which is not a signature.
let e = Sfnt::parse(vec![247, 89, 0, 0, 0, 0]).unwrap_err();
assert!(e.contains("not a font signature"), "{e}");
// The right signature and a directory that promises more tables than
// the file holds.
let mut lying = vec![0, 1, 0, 0, 0x01, 0xff];
lying.extend([0; 10]);
assert!(Sfnt::parse(lying).is_err());
}
}