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
|
//! Font loading, utility and subsetting.
use std::collections::HashMap;
use std::error;
use std::fmt;
use std::io::{self, Cursor, Seek, SeekFrom};
use byteorder::{BE, ReadBytesExt, WriteBytesExt};
use opentype::{Error as OpentypeError, OpenTypeReader, Outlines, TableRecord, Tag};
use opentype::tables::{Header, Name, CharMap, MaximumProfile, HorizontalMetrics, Post, OS2};
use opentype::tables::{MacStyleFlags, NameEntry};
use crate::doc::Size;
/// An font wrapper which allows to subset a font.
#[derive(Debug, Clone, PartialEq)]
pub struct Font {
/// The base name of the font.
pub name: String,
/// The raw bytes of the font program.
pub program: Vec<u8>,
/// A mapping from character codes to glyph ids.
pub mapping: HashMap<char, u16>,
/// The widths of the glyphs indexed by glyph id.
pub widths: Vec<Size>,
/// The fallback glyph.
pub default_glyph: u16,
/// The relevant metrics of this font.
pub metrics: FontMetrics,
}
/// Font metrics relevant to the typesetting engine.
#[derive(Debug, Clone, PartialEq)]
pub struct FontMetrics {
/// Whether the font is italic.
pub is_italic: bool,
/// Whether font is fixed pitch.
pub is_fixed_pitch: bool,
/// The angle of italics.
pub italic_angle: f32,
/// The glyph bounding box: [x_min, y_min, x_max, y_max],
pub bounding_box: [Size; 4],
/// The typographics ascender relevant for line spacing.
pub ascender: Size,
/// The typographics descender relevant for line spacing.
pub descender: Size,
/// The approximate height of capital letters.
pub cap_height: Size,
/// The weight class of the font.
pub weight_class: u16,
}
impl Font {
/// Create a new font from a font program.
pub fn new(program: Vec<u8>) -> FontResult<Font> {
// Create opentype reader to parse font tables
let mut readable = Cursor::new(&program);
let mut reader = OpenTypeReader::new(&mut readable);
// Read the relevant tables
// (all of these are required by the OpenType specification)
let head = reader.read_table::<Header>()?;
let name = reader.read_table::<Name>()?;
let os2 = reader.read_table::<OS2>()?;
let cmap = reader.read_table::<CharMap>()?;
let hmtx = reader.read_table::<HorizontalMetrics>()?;
let post = reader.read_table::<Post>()?;
// Create conversion function between font units and sizes
let font_unit_ratio = 1.0 / (head.units_per_em as f32);
let font_unit_to_size = |x| Size::from_points(font_unit_ratio * x as f32);
// Find out the name of the font
let font_name = name.get_decoded(NameEntry::PostScriptName)
.unwrap_or_else(|| "unknown".to_owned());
// Convert the widths
let widths = hmtx.metrics.iter().map(|m| font_unit_to_size(m.advance_width)).collect();
// Calculate some metrics
let metrics = FontMetrics {
is_italic: head.mac_style.contains(MacStyleFlags::ITALIC),
is_fixed_pitch: post.is_fixed_pitch,
italic_angle: post.italic_angle.to_f32(),
bounding_box: [
font_unit_to_size(head.x_min),
font_unit_to_size(head.y_min),
font_unit_to_size(head.x_max),
font_unit_to_size(head.y_max),
],
ascender: font_unit_to_size(os2.s_typo_ascender),
descender: font_unit_to_size(os2.s_typo_descender),
cap_height: font_unit_to_size(os2.s_cap_height.unwrap_or(os2.s_typo_ascender)),
weight_class: os2.us_weight_class,
};
Ok(Font {
name: font_name,
program,
mapping: cmap.mapping,
widths,
default_glyph: os2.us_default_char.unwrap_or(0),
metrics,
})
}
/// Map a character to it's glyph index.
#[inline]
pub fn map(&self, c: char) -> u16 {
self.mapping.get(&c).map(|&g| g).unwrap_or(self.default_glyph)
}
/// Encode the given text for this font (into glyph ids).
#[inline]
pub fn encode(&self, text: &str) -> Vec<u8> {
let mut bytes = Vec::with_capacity(2 * text.len());
for glyph in text.chars().map(|c| self.map(c)) {
bytes.push((glyph >> 8) as u8);
bytes.push((glyph & 0xff) as u8);
}
bytes
}
/// Generate a subsetted version of this font including only the chars listed in
/// `chars`.
///
/// All needed tables will be included (returning an error if a table was not present
/// in the source font) and optional tables will be included if there were present
/// in the source font. All other tables will be dropped.
pub fn subsetted<C, I1, S1, I2, S2>(
&self,
chars: C,
needed_tables: I1,
optional_tables: I2
) -> Result<Font, FontError>
where
C: IntoIterator<Item=char>,
I1: IntoIterator<Item=S1>, S1: AsRef<str>,
I2: IntoIterator<Item=S2>, S2: AsRef<str>
{
let mut chars: Vec<char> = chars.into_iter().collect();
chars.sort();
let mut cursor = Cursor::new(&self.program);
let mut reader = OpenTypeReader::new(&mut cursor);
let outlines = reader.outlines()?;
let mut tables = reader.tables()?.to_vec();
tables.sort_by_key(|r| r.tag);
Subsetter {
font: &self,
reader,
outlines,
tables,
cmap: None,
hmtx: None,
loca: None,
glyphs: Vec::with_capacity(chars.len()),
chars,
records: Vec::new(),
body: Vec::new(),
}.subset(needed_tables, optional_tables)
}
}
#[derive(Debug)]
struct Subsetter<'p> {
// Original font
font: &'p Font,
reader: OpenTypeReader<'p, Cursor<&'p Vec<u8>>>,
outlines: Outlines,
tables: Vec<TableRecord>,
cmap: Option<CharMap>,
hmtx: Option<HorizontalMetrics>,
loca: Option<Vec<u32>>,
glyphs: Vec<u16>,
// Subsetted font
chars: Vec<char>,
records: Vec<TableRecord>,
body: Vec<u8>,
}
impl<'p> Subsetter<'p> {
fn subset<I1, S1, I2, S2>(mut self, needed_tables: I1, optional_tables: I2)
-> FontResult<Font>
where
I1: IntoIterator<Item=S1>, S1: AsRef<str>,
I2: IntoIterator<Item=S2>, S2: AsRef<str>
{
// Find out which glyphs to include based on which characters we want
// and which glyphs are used by composition.
self.build_glyphs()?;
// Iterate through the needed tables first
for table in needed_tables.into_iter() {
let table = table.as_ref();
let tag: Tag = table.parse()
.map_err(|_| FontError::UnsupportedTable(table.to_string()))?;
if self.contains(tag) {
self.write_table(tag)?;
} else {
return Err(FontError::MissingTable(tag.to_string()));
}
}
// Now iterate through the optional tables
for table in optional_tables.into_iter() {
let table = table.as_ref();
let tag: Tag = table.parse()
.map_err(|_| FontError::UnsupportedTable(table.to_string()))?;
if self.contains(tag) {
self.write_table(tag)?;
}
}
self.write_header()?;
let widths = self.glyphs.iter()
.map(|&glyph| self.font.widths.get(glyph as usize).map(|&w| w)
.take_invalid("missing glyph metrics"))
.collect::<FontResult<Vec<_>>>()?;
let mapping = self.chars.into_iter().enumerate().map(|(i, c)| (c, i as u16))
.collect::<HashMap<char, u16>>();
Ok(Font {
name: self.font.name.clone(),
program: self.body,
mapping,
widths,
default_glyph: self.font.default_glyph,
metrics: self.font.metrics.clone(),
})
}
fn build_glyphs(&mut self) -> FontResult<()> {
self.read_cmap()?;
let cmap = self.cmap.as_ref().unwrap();
for &c in &self.chars {
self.glyphs.push(cmap.get(c).ok_or_else(|| FontError::MissingCharacter(c))?)
}
self.glyphs.push(self.font.default_glyph);
// Composite glyphs may need additional glyphs we have not yet in our list.
// So now we have a look at the glyf table to check that and add glyphs
// we need additionally.
if self.contains("glyf".parse().unwrap()) {
self.read_loca()?;
let loca = self.loca.as_ref().unwrap();
let table = self.get_table_data("glyf".parse().unwrap())?;
let mut i = 0;
while i < self.glyphs.len() {
let glyph = self.glyphs[i];
let start = *loca.get(glyph as usize).take_bytes()? as usize;
let end = *loca.get(glyph as usize + 1).take_bytes()? as usize;
let glyph = table.get(start..end).take_bytes()?;
if end > start {
let mut cursor = Cursor::new(&glyph);
let num_contours = cursor.read_i16::<BE>()?;
// This is a composite glyph
if num_contours < 0 {
cursor.seek(SeekFrom::Current(8))?;
loop {
let flags = cursor.read_u16::<BE>()?;
let glyph_index = cursor.read_u16::<BE>()?;
if self.glyphs.iter().rev().find(|&&x| x == glyph_index).is_none() {
self.glyphs.push(glyph_index);
}
// This was the last component
if flags & 0x0020 == 0 {
break;
}
let args_len = if flags & 0x0001 == 1 { 4 } else { 2 };
cursor.seek(SeekFrom::Current(args_len))?;
}
}
}
i += 1;
}
}
Ok(())
}
fn write_header(&mut self) -> FontResult<()> {
// Create an output buffer
let header_len = 12 + self.records.len() * 16;
let mut header = Vec::with_capacity(header_len);
let num_tables = self.records.len() as u16;
// The highester power lower than the table count.
let mut max_power = 1u16;
while max_power * 2 <= num_tables {
max_power *= 2;
}
max_power = std::cmp::min(max_power, num_tables);
let search_range = max_power * 16;
let entry_selector = (max_power as f32).log2() as u16;
let range_shift = num_tables * 16 - search_range;
// Write the base header
header.write_u32::<BE>(match self.outlines {
Outlines::TrueType => 0x00010000,
Outlines::CFF => 0x4f54544f,
})?;
header.write_u16::<BE>(num_tables)?;
header.write_u16::<BE>(search_range)?;
header.write_u16::<BE>(entry_selector)?;
header.write_u16::<BE>(range_shift)?;
// Write the table records
for record in &self.records {
header.extend(record.tag.value());
header.write_u32::<BE>(record.check_sum)?;
header.write_u32::<BE>(header_len as u32 + record.offset)?;
header.write_u32::<BE>(record.length)?;
}
header.append(&mut self.body);
self.body = header;
Ok(())
}
fn write_table(&mut self, tag: Tag) -> FontResult<()> {
match tag.value() {
b"head" | b"cvt " | b"prep" | b"fpgm" | b"name" | b"post" | b"OS/2" => {
self.copy_table(tag)
},
b"hhea" => {
let table = self.get_table_data(tag)?;
let glyph_count = self.glyphs.len() as u16;
self.write_table_body(tag, |this| {
this.body.extend(&table[..table.len() - 2]);
Ok(this.body.write_u16::<BE>(glyph_count)?)
})
},
b"maxp" => {
let table = self.get_table_data(tag)?;
let glyph_count = self.glyphs.len() as u16;
self.write_table_body(tag, |this| {
this.body.extend(&table[..4]);
this.body.write_u16::<BE>(glyph_count)?;
Ok(this.body.extend(&table[6..]))
})
},
b"hmtx" => {
self.write_table_body(tag, |this| {
this.read_hmtx()?;
let metrics = this.hmtx.as_ref().unwrap();
for &glyph in &this.glyphs {
let metrics = metrics.get(glyph).take_invalid("missing glyph metrics")?;
this.body.write_i16::<BE>(metrics.advance_width)?;
this.body.write_i16::<BE>(metrics.left_side_bearing)?;
}
Ok(())
})
},
b"loca" => {
self.write_table_body(tag, |this| {
this.read_loca()?;
let loca = this.loca.as_ref().unwrap();
let mut offset = 0;
for &glyph in &this.glyphs {
this.body.write_u32::<BE>(offset)?;
let len = loca.get(glyph as usize + 1).take_bytes()?
- loca.get(glyph as usize).take_bytes()?;
offset += len;
}
this.body.write_u32::<BE>(offset)?;
Ok(())
})
},
b"glyf" => {
self.write_table_body(tag, |this| {
this.read_loca()?;
let loca = this.loca.as_ref().unwrap();
let table = this.get_table_data(tag)?;
for &glyph in &this.glyphs {
let start = *loca.get(glyph as usize).take_bytes()? as usize;
let end = *loca.get(glyph as usize + 1).take_bytes()? as usize;
let mut data = table.get(start..end).take_bytes()?.to_vec();
if end > start {
let mut cursor = Cursor::new(&mut data);
let num_contours = cursor.read_i16::<BE>()?;
// This is a composite glyph
if num_contours < 0 {
cursor.seek(SeekFrom::Current(8))?;
loop {
let flags = cursor.read_u16::<BE>()?;
let glyph_index = cursor.read_u16::<BE>()?;
let new_glyph_index = this.glyphs.iter()
.position(|&g| g == glyph_index)
.take_invalid("referenced non-existent glyph")? as u16;
cursor.seek(SeekFrom::Current(-2))?;
cursor.write_u16::<BE>(new_glyph_index)?;
// This was the last component
if flags & 0x0020 == 0 {
break;
}
let args_len = if flags & 0x0001 == 1 { 4 } else { 2 };
cursor.seek(SeekFrom::Current(args_len))?;
}
}
}
this.body.extend(data);
}
Ok(())
})
},
b"cmap" => {
// Always uses format 12 for simplicity
self.write_table_body(tag, |this| {
// Find out which chars are in consecutive groups
let mut groups = Vec::new();
let len = this.chars.len();
let mut i = 0;
while i < len {
let start = i;
while i + 1 < len && this.chars[i+1] as u32 == this.chars[i] as u32 + 1 {
i += 1;
}
groups.push((this.chars[start], this.chars[i], start));
i += 1;
}
// Table header
this.body.write_u16::<BE>(0)?;
this.body.write_u16::<BE>(1)?;
this.body.write_u16::<BE>(3)?;
this.body.write_u16::<BE>(1)?;
this.body.write_u32::<BE>(12)?;
// Subtable header
this.body.write_u16::<BE>(12)?;
this.body.write_u16::<BE>(0)?;
this.body.write_u32::<BE>((16 + 12 * groups.len()) as u32)?;
this.body.write_u32::<BE>(0)?;
this.body.write_u32::<BE>(groups.len() as u32)?;
// Subtable body
for group in &groups {
this.body.write_u32::<BE>(group.0 as u32)?;
this.body.write_u32::<BE>(group.1 as u32)?;
this.body.write_u32::<BE>(group.2 as u32)?;
}
Ok(())
})
},
_ => Err(FontError::UnsupportedTable(tag.to_string())),
}
}
fn copy_table(&mut self, tag: Tag) -> FontResult<()> {
self.write_table_body(tag, |this| {
let table = this.get_table_data(tag)?;
Ok(this.body.extend(table))
})
}
fn write_table_body<F>(&mut self, tag: Tag, writer: F) -> FontResult<()>
where F: FnOnce(&mut Self) -> FontResult<()> {
let start = self.body.len();
writer(self)?;
let end = self.body.len();
while (self.body.len() - start) % 4 != 0 {
self.body.push(0);
}
Ok(self.records.push(TableRecord {
tag,
check_sum: calculate_check_sum(&self.body[start..]),
offset: start as u32,
length: (end - start) as u32,
}))
}
fn get_table_data(&self, tag: Tag) -> FontResult<&'p [u8]> {
let record = match self.tables.binary_search_by_key(&tag, |r| r.tag) {
Ok(index) => &self.tables[index],
Err(_) => return Err(FontError::MissingTable(tag.to_string())),
};
self.font.program
.get(record.offset as usize .. (record.offset + record.length) as usize)
.take_bytes()
}
fn contains(&self, tag: Tag) -> bool {
self.tables.binary_search_by_key(&tag, |r| r.tag).is_ok()
}
fn read_cmap(&mut self) -> FontResult<()> {
Ok(if self.cmap.is_none() {
self.cmap = Some(self.reader.read_table::<CharMap>()?);
})
}
fn read_hmtx(&mut self) -> FontResult<()> {
Ok(if self.hmtx.is_none() {
self.hmtx = Some(self.reader.read_table::<HorizontalMetrics>()?);
})
}
fn read_loca(&mut self) -> FontResult<()> {
Ok(if self.loca.is_none() {
let mut table = self.get_table_data("loca".parse().unwrap())?;
let format = self.reader.read_table::<Header>()?.index_to_loc_format;
let count = self.reader.read_table::<MaximumProfile>()?.num_glyphs + 1;
let loca = if format == 0 {
(0..count).map(|_| table.read_u16::<BE>()
.map(|x| (x as u32) * 2))
.collect::<io::Result<Vec<u32>>>()
} else {
(0..count).map(|_| table.read_u32::<BE>())
.collect::<io::Result<Vec<u32>>>()
}?;
self.loca = Some(loca);
})
}
}
/// Calculate a checksum over the sliced data as sum of u32's.
/// The data length has to be a multiple of four.
fn calculate_check_sum(data: &[u8]) -> u32 {
let mut sum = 0u32;
data.chunks_exact(4).for_each(|c| {
sum = sum.wrapping_add(
((c[0] as u32) << 24)
+ ((c[1] as u32) << 16)
+ ((c[2] as u32) << 8)
+ (c[3] as u32)
);
});
sum
}
trait TakeInvalid<T>: Sized {
/// Pull the type out of the option, returning a subsetting error
/// about an invalid font wrong.
fn take_invalid<S: Into<String>>(self, message: S) -> FontResult<T>;
/// Pull the type out of the option, returning an error about missing
/// bytes if it is nothing.
fn take_bytes(self) -> FontResult<T> {
self.take_invalid("expected more bytes")
}
}
impl<T> TakeInvalid<T> for Option<T> {
fn take_invalid<S: Into<String>>(self, message: S) -> FontResult<T> {
self.ok_or(FontError::InvalidFont(message.into()))
}
}
type FontResult<T> = Result<T, FontError>;
/// The error type for font operations.
pub enum FontError {
/// The font file is incorrect.
InvalidFont(String),
/// A requested table was not present in the source font.
MissingTable(String),
/// The table is unknown to the subsetting engine (unimplemented or invalid).
UnsupportedTable(String),
/// A requested character was not present in the source font.
MissingCharacter(char),
/// An I/O Error occured while reading the font program.
Io(io::Error),
}
impl error::Error for FontError {
#[inline]
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
FontError::Io(err) => Some(err),
_ => None,
}
}
}
impl fmt::Display for FontError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
FontError::InvalidFont(message) => write!(f, "invalid font: {}", message),
FontError::MissingTable(table) => write!(f, "missing table: {}", table),
FontError::UnsupportedTable(table) => write!(f, "unsupported table: {}", table),
FontError::MissingCharacter(c) => write!(f, "missing character: '{}'", c),
FontError::Io(err) => write!(f, "io error: {}", err),
}
}
}
impl fmt::Debug for FontError {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl From<io::Error> for FontError {
#[inline]
fn from(err: io::Error) -> FontError {
FontError::Io(err)
}
}
impl From<OpentypeError> for FontError {
fn from(err: OpentypeError) -> FontError {
match err {
OpentypeError::InvalidFont(message) => FontError::InvalidFont(message),
OpentypeError::MissingTable(tag) => FontError::MissingTable(tag.to_string()),
OpentypeError::Io(err) => FontError::Io(err),
_ => panic!("unexpected extensible variant"),
}
}
}
|