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
//! TrueType の字形を読む
//!
//! OpenType のうち sfnt が 0x00010000 のものは、字形を glyf テーブルに 2 次ベジエで持っている。
//! Cambria Math や Times New Roman がこちらである。
use crate::error::Error;
use crate::opentype::{read_i16, read_u8, read_u16, read_u32};
use crate::outline::{Outline, Segment};
/// 字形の位置を引くのに要るもの
#[derive(Debug, Clone, Copy)]
pub struct Glyf {
glyf_at: usize,
loca_at: usize,
long_loca: bool,
count: usize,
}
/// 入れ子の合成字形をたどる深さの上限
const NEST_LIMIT: usize = 5;
const ARG_WORD: u16 = 0x0001;
const ARG_XY: u16 = 0x0002;
const HAS_SCALE: u16 = 0x0008;
const MORE: u16 = 0x0020;
const HAS_XY_SCALE: u16 = 0x0040;
const HAS_MATRIX: u16 = 0x0080;
const ON_CURVE: u8 = 0x01;
const X_SHORT: u8 = 0x02;
const Y_SHORT: u8 = 0x04;
const REPEAT: u8 = 0x08;
const X_SAME: u8 = 0x10;
const Y_SAME: u8 = 0x20;
pub fn new(glyf_at: usize, loca_at: usize, long_loca: bool, count: usize) -> Glyf {
Glyf {glyf_at, loca_at, long_loca, count}
}
/// 字形のバイト範囲。中身のない字形(空白など)は None
fn range(data: &[u8], glyf: &Glyf, glyph: u16) -> Result<Option<(usize, usize)>, Error> {
let index = glyph as usize;
if index >= glyf.count {
return Ok(None);
}
let (start, end) = if glyf.long_loca {
(
read_u32(data, glyf.loca_at + index * 4)? as usize,
read_u32(data, glyf.loca_at + index * 4 + 4)? as usize,
)
} else {
(
read_u16(data, glyf.loca_at + index * 2)? as usize * 2,
read_u16(data, glyf.loca_at + index * 2 + 2)? as usize * 2,
)
};
if end <= start {
return Ok(None);
}
Ok(Some((glyf.glyf_at + start, glyf.glyf_at + end)))
}
/// 1 つの字形の輪郭。座標はフォントの単位で、y は上向き
pub fn outline(data: &[u8], glyf: &Glyf, glyph: u16) -> Result<Outline, Error> {
let mut found = Outline::default();
read_into(data, glyf, glyph, 0.0, 0.0, &mut found, 0)?;
Ok(found)
}
fn read_into(
data: &[u8],
glyf: &Glyf,
glyph: u16,
shift_x: f64,
shift_y: f64,
found: &mut Outline,
depth: usize,
) -> Result<(), Error> {
if depth > NEST_LIMIT {
return Err(Error::new("合成した字形の入れ子が深すぎます", 0));
}
let (start, end) = match range(data, glyf, glyph)? {
Some(found) => found,
None => return Ok(()),
};
let contours = read_i16(data, start)?;
if contours >= 0 {
return simple(data, start, contours as usize, shift_x, shift_y, found);
}
composite(data, glyf, start, end, shift_x, shift_y, found, depth)
}
/// 輪郭をそのまま持つ字形
fn simple(
data: &[u8],
start: usize,
contours: usize,
shift_x: f64,
shift_y: f64,
found: &mut Outline,
) -> Result<(), Error> {
if contours == 0 {
return Ok(());
}
let ends_at = start + 10;
let point_count = read_u16(data, ends_at + (contours - 1) * 2)? as usize + 1;
let instruction_at = ends_at + contours * 2;
let mut at = instruction_at + 2 + read_u16(data, instruction_at)? as usize;
let mut flags = Vec::with_capacity(point_count);
while flags.len() < point_count {
let flag = read_u8(data, at)?;
at += 1;
flags.push(flag);
if flag & REPEAT != 0 {
let times = read_u8(data, at)?;
at += 1;
for _ in 0..times {
if flags.len() >= point_count {
break;
}
flags.push(flag);
}
}
}
let mut x = Vec::with_capacity(point_count);
let mut value = 0i32;
for flag in &flags {
if flag & X_SHORT != 0 {
let step = read_u8(data, at)? as i32;
at += 1;
value += if flag & X_SAME != 0 {step} else {-step};
} else if flag & X_SAME == 0 {
value += read_i16(data, at)? as i32;
at += 2;
}
x.push(value as f64 + shift_x);
}
let mut y = Vec::with_capacity(point_count);
value = 0;
for flag in &flags {
if flag & Y_SHORT != 0 {
let step = read_u8(data, at)? as i32;
at += 1;
value += if flag & Y_SAME != 0 {step} else {-step};
} else if flag & Y_SAME == 0 {
value += read_i16(data, at)? as i32;
at += 2;
}
y.push(value as f64 + shift_y);
}
let mut first = 0usize;
for index in 0..contours {
let last = read_u16(data, ends_at + index * 2)? as usize;
if last >= point_count || last < first {
return Err(Error::new("輪郭の終わりの点が範囲の外です", ends_at));
}
write_contour(&flags[first..=last], &x[first..=last], &y[first..=last], found);
first = last + 1;
}
Ok(())
}
/// 1 本の輪郭を線に直す。曲線の外側の点が続いたら、そのあいだに点があるものとして扱う
fn write_contour(flags: &[u8], x: &[f64], y: &[f64], found: &mut Outline) {
let count = flags.len();
if count == 0 {
return;
}
let on = |index: usize| flags[index % count] & ON_CURVE != 0;
let point = |index: usize| (x[index % count], y[index % count]);
let middle = |first: (f64, f64), second: (f64, f64)| {
((first.0 + second.0) / 2.0, (first.1 + second.1) / 2.0)
};
// 始まりの点を決める。曲線の上の点がなければ、外側の点どうしの中間から始める
let start_index = (0..count).find(|index| on(*index));
let start = match start_index {
Some(index) => point(index),
None => middle(point(0), point(1)),
};
let begin = start_index.map_or(0, |index| index + 1);
found.segment.push(Segment::Move {x: start.0, y: start.1});
let mut control: Option<(f64, f64)> = None;
for step in 0..count {
let index = begin + step;
let here = point(index);
if on(index) {
match control.take() {
Some(hold) => found.segment.push(Segment::Quadratic {
x1: hold.0,
y1: hold.1,
x: here.0,
y: here.1,
}),
None => found.segment.push(Segment::Line {x: here.0, y: here.1}),
}
continue;
}
if let Some(hold) = control {
let between = middle(hold, here);
found.segment.push(Segment::Quadratic {
x1: hold.0,
y1: hold.1,
x: between.0,
y: between.1,
});
}
control = Some(here);
}
if let Some(hold) = control {
found.segment.push(Segment::Quadratic {
x1: hold.0,
y1: hold.1,
x: start.0,
y: start.1,
});
}
found.segment.push(Segment::Close);
}
/// ほかの字形を組み合わせた字形
#[allow(clippy::too_many_arguments)]
fn composite(
data: &[u8],
glyf: &Glyf,
start: usize,
end: usize,
shift_x: f64,
shift_y: f64,
found: &mut Outline,
depth: usize,
) -> Result<(), Error> {
let mut at = start + 10;
loop {
if at + 4 > end {
return Ok(());
}
let flags = read_u16(data, at)?;
let glyph = read_u16(data, at + 2)?;
at += 4;
let (dx, dy) = if flags & ARG_WORD != 0 {
let first = read_i16(data, at)? as f64;
let second = read_i16(data, at + 2)? as f64;
at += 4;
(first, second)
} else {
let first = read_u8(data, at)? as i8 as f64;
let second = read_u8(data, at + 1)? as i8 as f64;
at += 2;
(first, second)
};
// 拡大や回転の付いた合成は、数式のフォントでは使われない。位置だけを読む
if flags & HAS_SCALE != 0 {
at += 2;
} else if flags & HAS_XY_SCALE != 0 {
at += 4;
} else if flags & HAS_MATRIX != 0 {
at += 8;
}
let (move_x, move_y) = if flags & ARG_XY != 0 {(dx, dy)} else {(0.0, 0.0)};
read_into(data, glyf, glyph, shift_x + move_x, shift_y + move_y, found, depth + 1)?;
if flags & MORE == 0 {
return Ok(());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::opentype::{character_map, glyph_count, head, require};
use crate::outline::bounds;
fn font() -> Option<(Vec<u8>, Glyf, f64)> {
let path = "/System/Library/Fonts/Supplemental/Times New Roman.ttf";
let data = std::fs::read(path).ok()?;
let (head_at, _) = require(&data, "head").unwrap();
let shape = head(&data, head_at).unwrap();
let (maxp_at, _) = require(&data, "maxp").unwrap();
let count = glyph_count(&data, maxp_at).unwrap();
let (glyf_at, _) = require(&data, "glyf").unwrap();
let (loca_at, _) = require(&data, "loca").unwrap();
Some((data, new(glyf_at, loca_at, shape.long_loca, count), shape.units_per_em))
}
#[test]
fn reads_a_letter_from_a_truetype_font() {
let Some((data, glyf, units)) = font() else {
return;
};
let (cmap_at, _) = require(&data, "cmap").unwrap();
let map = character_map(&data, cmap_at).unwrap();
let (_, bottom, _, top) = bounds(&outline(&data, &glyf, map[&'x']).unwrap());
assert!(bottom.abs() < 0.03 * units);
assert!(top > 0.3 * units && top < 0.6 * units, "x の高さ: {top}");
}
#[test]
fn a_descender_reaches_below_the_baseline() {
let Some((data, glyf, units)) = font() else {
return;
};
let (cmap_at, _) = require(&data, "cmap").unwrap();
let map = character_map(&data, cmap_at).unwrap();
let (_, bottom, _, _) = bounds(&outline(&data, &glyf, map[&'y']).unwrap());
assert!(bottom < -0.1 * units, "y の深さ: {bottom}");
}
#[test]
fn every_glyph_can_be_read() {
let Some((data, glyf, _)) = font() else {
return;
};
for glyph in 0..glyf.count {
let result = outline(&data, &glyf, glyph as u16);
assert!(result.is_ok(), "字形 {glyph} を読めません: {:?}", result.err());
}
}
}