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
//! Puts a font into the form that is embedded in the PDF
//!
//! The file of a CFF typeface is embedded as it is. For a glyf typeface, only the glyphs that are
//! used are kept and packed together.
//! Glyph IDs do not change, so the PDF can keep using Identity to refer to the glyphs.
//!
//! A typeface for Japanese text can be larger than 20MB, and embedding it as it is would make the
//! PDF large by that alone.
use crate::font::{Face, Outline};
use std::collections::BTreeSet;
use suki::opentype::{find, read_u16, read_u32};
/// Makes the data to embed
pub fn program(face: &Face, used: &BTreeSet<u16>) -> Vec<u8> {
match face.outline {
Outline::Cff => face.data.clone(),
Outline::TrueType => subset(face, used).unwrap_or_else(|| face.data.clone()),
}
}
/// Builds a font that has only the glyphs to keep. None if it cannot be built
fn subset(face: &Face, used: &BTreeSet<u16>) -> Option<Vec<u8>> {
let data = &face.data;
let (head_at, _) = find(data, "head").ok()??;
let (loca_at, _) = find(data, "loca").ok()??;
let (glyf_at, glyf_length) = find(data, "glyf").ok()??;
let long = read_u16(data, head_at + 50).ok()? != 0;
let count = face.count;
let mut offset = Vec::with_capacity(count + 1);
for index in 0..=count {
let value = if long {
read_u32(data, loca_at + index * 4).ok()? as usize
} else {
read_u16(data, loca_at + index * 2).ok()? as usize * 2
};
if value > glyf_length {
return None;
}
offset.push(value);
}
let want = wanted(data, glyf_at, &offset, used, count);
let mut glyf = Vec::new();
let mut loca = Vec::with_capacity((count + 1) * 4);
for index in 0..count {
loca.extend_from_slice(&(glyf.len() as u32).to_be_bytes());
if want.contains(&(index as u16)) && offset[index + 1] > offset[index] {
glyf.extend_from_slice(&data[glyf_at + offset[index]..glyf_at + offset[index + 1]]);
while glyf.len() % 4 != 0 {
glyf.push(0);
}
}
}
loca.extend_from_slice(&(glyf.len() as u32).to_be_bytes());
let mut head = data.get(head_at..head_at + 54)?.to_vec();
head[8..12].copy_from_slice(&0u32.to_be_bytes());
head[50..52].copy_from_slice(&1i16.to_be_bytes());
let mut table: Vec<(&str, Vec<u8>)> = vec![
("head", head),
("loca", loca),
("glyf", glyf),
];
for tag in ["hhea", "maxp", "hmtx", "cvt ", "fpgm", "prep", "gasp"] {
if let Ok(Some((at, length))) = find(data, tag) {
if let Some(slice) = data.get(at..at + length) {
table.push((tag, slice.to_vec()));
}
}
}
Some(assemble(table))
}
/// Collects the glyphs to keep. A composite glyph also needs its components
fn wanted(
data: &[u8],
glyf_at: usize,
offset: &[usize],
used: &BTreeSet<u16>,
count: usize,
) -> BTreeSet<u16> {
let mut found = BTreeSet::new();
let mut left: Vec<u16> = used.iter().copied().collect();
left.push(0);
while let Some(glyph) = left.pop() {
if glyph as usize >= count || !found.insert(glyph) {
continue;
}
for part in components(data, glyf_at, offset, glyph) {
left.push(part);
}
}
found
}
/// The glyph IDs that a composite glyph uses
fn components(data: &[u8], glyf_at: usize, offset: &[usize], glyph: u16) -> Vec<u16> {
let index = glyph as usize;
if index + 1 >= offset.len() || offset[index + 1] <= offset[index] {
return Vec::new();
}
let start = glyf_at + offset[index];
let contours = match read_u16(data, start) {
Ok(value) => value as i16,
Err(_) => return Vec::new(),
};
if contours >= 0 {
return Vec::new();
}
let mut found = Vec::new();
let mut at = start + 10;
loop {
let flags = match read_u16(data, at) {
Ok(value) => value,
Err(_) => break,
};
let part = match read_u16(data, at + 2) {
Ok(value) => value,
Err(_) => break,
};
found.push(part);
at += 4;
at += if flags & 1 != 0 {4} else {2};
if flags & 8 != 0 {
at += 2;
} else if flags & 64 != 0 {
at += 4;
} else if flags & 128 != 0 {
at += 8;
}
if flags & 32 == 0 {
break;
}
}
found
}
/// Arranges the tables to make one font
fn assemble(mut table: Vec<(&str, Vec<u8>)>) -> Vec<u8> {
table.sort_by(|left, right| left.0.cmp(right.0));
let count = table.len();
let mut power = 1;
while power * 2 <= count {
power *= 2;
}
let search_range = (power * 16) as u16;
let entry_selector = (power as f64).log2() as u16;
let range_shift = (count * 16) as u16 - search_range;
let mut out = Vec::new();
out.extend_from_slice(&0x0001_0000u32.to_be_bytes());
out.extend_from_slice(&(count as u16).to_be_bytes());
out.extend_from_slice(&search_range.to_be_bytes());
out.extend_from_slice(&entry_selector.to_be_bytes());
out.extend_from_slice(&range_shift.to_be_bytes());
let mut at = 12 + count * 16;
let mut place = Vec::with_capacity(count);
for (_, body) in &table {
place.push(at);
at += body.len();
while at % 4 != 0 {
at += 1;
}
}
for (index, (tag, body)) in table.iter().enumerate() {
out.extend_from_slice(tag.as_bytes());
out.extend_from_slice(&checksum(body).to_be_bytes());
out.extend_from_slice(&(place[index] as u32).to_be_bytes());
out.extend_from_slice(&(body.len() as u32).to_be_bytes());
}
for (_, body) in &table {
out.extend_from_slice(body);
while out.len() % 4 != 0 {
out.push(0);
}
}
let head_at = table
.iter()
.position(|(tag, _)| *tag == "head")
.map(|index| place[index]);
if let Some(head_at) = head_at {
let total = checksum(&out);
let adjustment = 0xb1b0_afbau32.wrapping_sub(total);
out[head_at + 8..head_at + 12].copy_from_slice(&adjustment.to_be_bytes());
}
out
}
/// The checksum of a table. Adds 4 bytes at a time
fn checksum(body: &[u8]) -> u32 {
let mut total = 0u32;
let mut at = 0;
while at < body.len() {
let mut word = [0u8; 4];
for (index, slot) in word.iter_mut().enumerate() {
if let Some(byte) = body.get(at + index) {
*slot = *byte;
}
}
total = total.wrapping_add(u32::from_be_bytes(word));
at += 4;
}
total
}
#[cfg(test)]
mod tests {
use super::*;
use crate::font;
#[test]
fn a_cff_font_is_embedded_as_it_is() {
let data = std::fs::read("../suki/font/latinmodern-math.otf").unwrap();
let face = font::build(data.clone()).unwrap();
let used = BTreeSet::from([3u16, 4, 5]);
assert_eq!(program(&face, &used).len(), data.len());
}
#[test]
fn a_truetype_font_gets_smaller() {
let path = "/System/Library/Fonts/Supplemental/Times New Roman.ttf";
if !std::path::Path::new(path).exists() {
return;
}
let data = std::fs::read(path).unwrap();
let face = font::build(data.clone()).unwrap();
let mut used = BTreeSet::new();
for character in "abcあ".chars() {
if let Some(glyph) = font::glyph(&face, character) {
used.insert(glyph);
}
}
let made = program(&face, &used);
assert!(made.len() < data.len() / 2, "{} / {}", made.len(), data.len());
assert_eq!(&made[0..4], &[0, 1, 0, 0]);
}
}