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
//! CFF の字形を読む
//!
//! OpenType のうち OTTO のものは、字形を CFF の charstring として持っている。
//! ここでは INDEX と DICT をたどって charstring を取り出し、Type 2 の命令を解いて輪郭に直す。
//!
//! 字送りは hmtx から取るので、charstring の先頭に付くことのある幅は読み飛ばすだけでよい。
use crate::error::Error;
use crate::opentype::{read_u16, read_u32, read_u8};
use crate::outline::{Outline, Segment};
/// 字形を引くのに要る位置
#[derive(Debug, Clone)]
pub struct Cff {
/// 字形ごとの charstring のバイト範囲
charstring: Vec<(usize, usize)>,
/// 大域のサブルーチン
global: Vec<(usize, usize)>,
/// 局所のサブルーチン。CID のフォントでは字形によって使う組が変わる
local: Vec<Vec<(usize, usize)>>,
/// 字形番号から local の添字へ。CID でなければ None
select: Option<Vec<u8>>,
/// charstring の座標をフォントの単位に直す倍率
unit: f64,
}
/// 入れ子のサブルーチンをたどる深さの上限
const CALL_LIMIT: usize = 10;
/// charstring の積みの上限
const STACK_LIMIT: usize = 48;
pub fn glyph_count(cff: &Cff) -> usize {
cff.charstring.len()
}
/// CFF のテーブルを読む
pub fn parse(data: &[u8], at: usize, units_per_em: f64) -> Result<Cff, Error> {
let header_size = read_u8(data, at + 2)? as usize;
let after_name = skip_index(data, at + header_size)?;
let (top_dict, after_top) = first_index_entry(data, after_name)?;
let after_string = skip_index(data, after_top)?;
let global = index_entries(data, after_string)?;
let top = parse_dict(data, top_dict.0, top_dict.1)?;
if let Some(kind) = top.get(&Key::Two(6)) {
if kind.first().copied().unwrap_or(2.0) != 2.0 {
return Err(Error::new("CharstringType が 2 ではありません", at));
}
}
// DICT に入っている位置は、どれも CFF テーブルの先頭から数えたものである
let charstring_at = at + operand(&top, Key::One(17), at, "CharStrings")? as usize;
let charstring = index_entries(data, charstring_at)?;
let unit = font_matrix_unit(&top, units_per_em);
let (local, select) = read_private(data, at, &top, charstring.len())?;
Ok(Cff {charstring, global, local, select, unit})
}
/// FontMatrix から、charstring の座標をフォントの単位に直す倍率を出す
fn font_matrix_unit(top: &Dict, units_per_em: f64) -> f64 {
let scale = top
.get(&Key::Two(7))
.and_then(|value| value.first().copied())
.unwrap_or(0.001);
if scale <= 0.0 {
return 1.0;
}
scale * units_per_em
}
/// INDEX の各項のバイト範囲
type Ranges = Vec<(usize, usize)>;
/// 局所サブルーチンの組と、字形番号からその組を引く表
type Private = (Vec<Ranges>, Option<Vec<u8>>);
/// 局所サブルーチンを読む。CID のフォントは FDArray と FDSelect をたどる
fn read_private(data: &[u8], at: usize, top: &Dict, count: usize) -> Result<Private, Error> {
if let Some(array_at) = top.get(&Key::Two(36)).and_then(|value| value.first().copied()) {
let fonts = index_entries(data, at + array_at as usize)?;
let mut local = Vec::with_capacity(fonts.len());
for (start, end) in fonts {
let dict = parse_dict(data, start, end)?;
local.push(local_subr(data, at, &dict)?);
}
let select_at = top.get(&Key::Two(37)).and_then(|value| value.first().copied());
let select = match select_at {
Some(offset) => Some(read_select(data, at + offset as usize, count)?),
None => None,
};
return Ok((local, select));
}
Ok((vec![local_subr(data, at, top)?], None))
}
fn local_subr(data: &[u8], at: usize, dict: &Dict) -> Result<Ranges, Error> {
let private = match dict.get(&Key::One(18)) {
Some(value) if value.len() >= 2 => value,
_ => return Ok(Vec::new()),
};
let size = private[0] as usize;
let start = at + private[1] as usize;
let inner = parse_dict(data, start, start + size)?;
match inner.get(&Key::One(19)).and_then(|value| value.first().copied()) {
Some(offset) => index_entries(data, start + offset as usize),
None => Ok(Vec::new()),
}
}
/// FDSelect。字形番号から FDArray の添字を引く
fn read_select(data: &[u8], at: usize, count: usize) -> Result<Vec<u8>, Error> {
let mut found = vec![0u8; count];
match read_u8(data, at)? {
0 => {
for (index, slot) in found.iter_mut().enumerate() {
*slot = read_u8(data, at + 1 + index)?;
}
}
3 => {
let ranges = read_u16(data, at + 1)? as usize;
let sentinel = read_u16(data, at + 3 + ranges * 3)? as usize;
for index in 0..ranges {
let entry = at + 3 + index * 3;
let first = read_u16(data, entry)? as usize;
let font = read_u8(data, entry + 2)?;
let next = if index + 1 == ranges {
sentinel
} else {
read_u16(data, entry + 3)? as usize
};
for slot in found.iter_mut().take(next.min(count)).skip(first) {
*slot = font;
}
}
}
other => return Err(Error::new(format!("FDSelect の形式 {other} は読めません"), at)),
}
Ok(found)
}
// ── INDEX ──
/// INDEX の各項を読む
fn index_entries(data: &[u8], at: usize) -> Result<Ranges, Error> {
let count = read_u16(data, at)? as usize;
if count == 0 {
return Ok(Vec::new());
}
let offset_size = read_u8(data, at + 2)? as usize;
if offset_size == 0 || offset_size > 4 {
return Err(Error::new(format!("INDEX の offSize {offset_size} は読めません"), at + 2));
}
let table = at + 3;
let base = table + (count + 1) * offset_size - 1;
let mut found = Vec::with_capacity(count);
for index in 0..count {
let start = base + read_offset(data, table + index * offset_size, offset_size)?;
let end = base + read_offset(data, table + (index + 1) * offset_size, offset_size)?;
if end < start || end > data.len() {
return Err(Error::new("INDEX の範囲が壊れています", at));
}
found.push((start, end));
}
Ok(found)
}
fn read_offset(data: &[u8], at: usize, size: usize) -> Result<usize, Error> {
let mut value = 0usize;
for step in 0..size {
value = (value << 8) | read_u8(data, at + step)? as usize;
}
Ok(value)
}
/// INDEX の終わりの位置
fn skip_index(data: &[u8], at: usize) -> Result<usize, Error> {
let count = read_u16(data, at)? as usize;
if count == 0 {
return Ok(at + 2);
}
let offset_size = read_u8(data, at + 2)? as usize;
if offset_size == 0 || offset_size > 4 {
return Err(Error::new(format!("INDEX の offSize {offset_size} は読めません"), at + 2));
}
let table = at + 3;
let last = read_offset(data, table + count * offset_size, offset_size)?;
Ok(table + (count + 1) * offset_size - 1 + last)
}
/// INDEX の先頭の項と、INDEX の終わりの位置
fn first_index_entry(data: &[u8], at: usize) -> Result<((usize, usize), usize), Error> {
let entries = index_entries(data, at)?;
let first = match entries.first() {
Some(found) => *found,
None => return Err(Error::new("Top DICT の INDEX が空です", at)),
};
Ok((first, skip_index(data, at)?))
}
// ── DICT ──
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum Key {
One(u8),
Two(u8),
}
type Dict = std::collections::HashMap<Key, Vec<f64>>;
fn operand(dict: &Dict, key: Key, at: usize, name: &str) -> Result<f64, Error> {
match dict.get(&key).and_then(|value| value.first().copied()) {
Some(found) => Ok(found),
None => Err(Error::new(format!("CFF の {name} がありません"), at)),
}
}
fn parse_dict(data: &[u8], start: usize, end: usize) -> Result<Dict, Error> {
let mut dict = Dict::new();
let mut operands: Vec<f64> = Vec::new();
let mut at = start;
while at < end {
let first = read_u8(data, at)?;
if first <= 21 {
let key = if first == 12 {
at += 1;
Key::Two(read_u8(data, at)?)
} else {
Key::One(first)
};
at += 1;
dict.insert(key, std::mem::take(&mut operands));
continue;
}
let (value, next) = read_operand(data, at)?;
operands.push(value);
at = next;
}
Ok(dict)
}
fn read_operand(data: &[u8], at: usize) -> Result<(f64, usize), Error> {
let first = read_u8(data, at)?;
if (32..=246).contains(&first) {
return Ok((first as f64 - 139.0, at + 1));
}
if (247..=250).contains(&first) {
let second = read_u8(data, at + 1)? as f64;
return Ok(((first as f64 - 247.0) * 256.0 + second + 108.0, at + 2));
}
if (251..=254).contains(&first) {
let second = read_u8(data, at + 1)? as f64;
return Ok((-(first as f64 - 251.0) * 256.0 - second - 108.0, at + 2));
}
if first == 28 {
return Ok((read_u16(data, at + 1)? as i16 as f64, at + 3));
}
if first == 29 {
return Ok((read_u32(data, at + 1)? as i32 as f64, at + 5));
}
if first == 30 {
return read_real(data, at + 1);
}
Err(Error::new(format!("DICT の値 {first} を読めません"), at))
}
/// charstring に置かれた数。DICT とほとんど同じだが、255 が 16.16 の固定小数になる
fn read_number(data: &[u8], at: usize) -> Result<(f64, usize), Error> {
if read_u8(data, at)? == 255 {
let raw = read_u32(data, at + 1)? as i32;
return Ok((raw as f64 / 65536.0, at + 5));
}
read_operand(data, at)
}
/// 実数。4 ビットずつの数字で書いてある
fn read_real(data: &[u8], at: usize) -> Result<(f64, usize), Error> {
let mut text = String::new();
let mut cursor = at;
loop {
let byte = read_u8(data, cursor)?;
cursor += 1;
for nibble in [byte >> 4, byte & 0x0f] {
match nibble {
0..=9 => text.push((b'0' + nibble) as char),
0x0a => text.push('.'),
0x0b => text.push('E'),
0x0c => text.push_str("E-"),
0x0e => text.push('-'),
0x0f => {
let value = text.parse::<f64>().unwrap_or(0.0);
return Ok((value, cursor));
}
_ => {}
}
}
}
}
// ── charstring ──
struct Machine<'a> {
data: &'a [u8],
global: &'a [(usize, usize)],
local: &'a [(usize, usize)],
stack: Vec<f64>,
x: f64,
y: f64,
stem: usize,
width_seen: bool,
open: bool,
outline: Outline,
}
/// サブルーチンの番号にかかる下駄
fn bias(count: usize) -> i32 {
if count < 1240 {
107
} else if count < 33900 {
1131
} else {
32768
}
}
/// 1 つの字形の輪郭。座標はフォントの単位で、y は上向き
pub fn outline(data: &[u8], cff: &Cff, glyph: u16) -> Result<Outline, Error> {
let index = glyph as usize;
let range = match cff.charstring.get(index) {
Some(found) => *found,
None => return Ok(Outline::default()),
};
let font = match &cff.select {
Some(select) => select.get(index).copied().unwrap_or(0) as usize,
None => 0,
};
let empty: Vec<(usize, usize)> = Vec::new();
let local = cff.local.get(font).unwrap_or(&empty);
let mut machine = Machine {
data,
global: &cff.global,
local,
stack: Vec::with_capacity(STACK_LIMIT),
x: 0.0,
y: 0.0,
stem: 0,
width_seen: false,
open: false,
outline: Outline::default(),
};
run(&mut machine, range.0, range.1, 0)?;
if machine.open {
machine.outline.segment.push(Segment::Close);
}
if cff.unit != 1.0 {
scale_outline(&mut machine.outline, cff.unit);
}
Ok(machine.outline)
}
fn scale_outline(outline: &mut Outline, unit: f64) {
for segment in &mut outline.segment {
match segment {
Segment::Move {x, y} | Segment::Line {x, y} => {
*x *= unit;
*y *= unit;
}
Segment::Quadratic {x1, y1, x, y} => {
*x1 *= unit;
*y1 *= unit;
*x *= unit;
*y *= unit;
}
Segment::Cubic {x1, y1, x2, y2, x, y} => {
*x1 *= unit;
*y1 *= unit;
*x2 *= unit;
*y2 *= unit;
*x *= unit;
*y *= unit;
}
Segment::Close => {}
}
}
}
fn move_to(machine: &mut Machine, dx: f64, dy: f64) {
if machine.open {
machine.outline.segment.push(Segment::Close);
}
machine.x += dx;
machine.y += dy;
machine.outline.segment.push(Segment::Move {x: machine.x, y: machine.y});
machine.open = true;
}
fn line_to(machine: &mut Machine, dx: f64, dy: f64) {
machine.x += dx;
machine.y += dy;
machine.outline.segment.push(Segment::Line {x: machine.x, y: machine.y});
}
fn curve_to(machine: &mut Machine, delta: [f64; 6]) {
let x1 = machine.x + delta[0];
let y1 = machine.y + delta[1];
let x2 = x1 + delta[2];
let y2 = y1 + delta[3];
machine.x = x2 + delta[4];
machine.y = y2 + delta[5];
machine.outline.segment.push(Segment::Cubic {
x1,
y1,
x2,
y2,
x: machine.x,
y: machine.y,
});
}
/// 幅が先頭に付いているなら落とす。積みを空にする命令の 1 回目だけに起きる
fn drop_width(machine: &mut Machine, expected: usize, even: bool) {
if machine.width_seen {
return;
}
machine.width_seen = true;
let extra = if even {
machine.stack.len() % 2 == 1
} else {
machine.stack.len() > expected
};
if extra && !machine.stack.is_empty() {
machine.stack.remove(0);
}
}
fn run(machine: &mut Machine, start: usize, end: usize, depth: usize) -> Result<bool, Error> {
if depth > CALL_LIMIT {
return Err(Error::new("charstring の入れ子が深すぎます", start));
}
let mut at = start;
while at < end {
let code = read_u8(machine.data, at)?;
at += 1;
if code >= 32 || code == 28 {
let (value, next) = read_number(machine.data, at - 1)?;
if machine.stack.len() >= STACK_LIMIT {
return Err(Error::new("charstring の積みがあふれました", at));
}
machine.stack.push(value);
at = next;
continue;
}
match code {
1 | 3 | 18 | 23 => {
drop_width(machine, 0, true);
machine.stem += machine.stack.len() / 2;
machine.stack.clear();
}
19 | 20 => {
drop_width(machine, 0, true);
machine.stem += machine.stack.len() / 2;
machine.stack.clear();
at += machine.stem.div_ceil(8);
}
21 => {
drop_width(machine, 2, false);
let dx = machine.stack.first().copied().unwrap_or(0.0);
let dy = machine.stack.get(1).copied().unwrap_or(0.0);
move_to(machine, dx, dy);
machine.stack.clear();
}
22 => {
drop_width(machine, 1, false);
let dx = machine.stack.first().copied().unwrap_or(0.0);
move_to(machine, dx, 0.0);
machine.stack.clear();
}
4 => {
drop_width(machine, 1, false);
let dy = machine.stack.first().copied().unwrap_or(0.0);
move_to(machine, 0.0, dy);
machine.stack.clear();
}
5 => {
let taken = std::mem::take(&mut machine.stack);
for pair in taken.chunks_exact(2) {
line_to(machine, pair[0], pair[1]);
}
}
6 | 7 => {
let taken = std::mem::take(&mut machine.stack);
let mut horizontal = code == 6;
for value in taken {
if horizontal {
line_to(machine, value, 0.0);
} else {
line_to(machine, 0.0, value);
}
horizontal = !horizontal;
}
}
8 => {
let taken = std::mem::take(&mut machine.stack);
for six in taken.chunks_exact(6) {
curve_to(machine, [six[0], six[1], six[2], six[3], six[4], six[5]]);
}
}
24 => {
let taken = std::mem::take(&mut machine.stack);
let curves = (taken.len().saturating_sub(2)) / 6;
for index in 0..curves {
let six = &taken[index * 6..index * 6 + 6];
curve_to(machine, [six[0], six[1], six[2], six[3], six[4], six[5]]);
}
if taken.len() >= curves * 6 + 2 {
line_to(machine, taken[curves * 6], taken[curves * 6 + 1]);
}
}
25 => {
let taken = std::mem::take(&mut machine.stack);
let lines = (taken.len().saturating_sub(6)) / 2;
for index in 0..lines {
line_to(machine, taken[index * 2], taken[index * 2 + 1]);
}
let rest = lines * 2;
if taken.len() >= rest + 6 {
let six = &taken[rest..rest + 6];
curve_to(machine, [six[0], six[1], six[2], six[3], six[4], six[5]]);
}
}
26 | 27 => {
let taken = std::mem::take(&mut machine.stack);
let mut index = 0;
let mut first = 0.0;
if taken.len() % 4 == 1 {
first = taken[0];
index = 1;
}
while index + 4 <= taken.len() {
let four = &taken[index..index + 4];
if code == 26 {
curve_to(machine, [first, four[0], four[1], four[2], 0.0, four[3]]);
} else {
curve_to(machine, [four[0], first, four[1], four[2], four[3], 0.0]);
}
first = 0.0;
index += 4;
}
}
30 | 31 => {
let taken = std::mem::take(&mut machine.stack);
let mut horizontal = code == 31;
let mut index = 0;
while index + 4 <= taken.len() {
let four = &taken[index..index + 4];
let last = index + 8 > taken.len();
let extra = if last && taken.len() == index + 5 {
taken[index + 4]
} else {
0.0
};
if horizontal {
curve_to(machine, [four[0], 0.0, four[1], four[2], extra, four[3]]);
} else {
curve_to(machine, [0.0, four[0], four[1], four[2], four[3], extra]);
}
horizontal = !horizontal;
index += 4;
}
}
10 | 29 => {
let table = if code == 10 {machine.local} else {machine.global};
let number = match machine.stack.pop() {
Some(value) => value,
None => return Err(Error::new("サブルーチンの番号がありません", at)),
};
let target = number as i32 + bias(table.len());
if target < 0 || target as usize >= table.len() {
return Err(Error::new(format!("サブルーチン {target} がありません"), at));
}
let range = table[target as usize];
if run(machine, range.0, range.1, depth + 1)? {
return Ok(true);
}
}
11 => return Ok(false),
14 => {
if machine.stack.len() == 4 || machine.stack.len() == 5 {
return Err(Error::new("seac の字形は読めません", at));
}
drop_width(machine, 0, false);
machine.stack.clear();
return Ok(true);
}
12 => {
let second = read_u8(machine.data, at)?;
at += 1;
flex(machine, second, at)?;
}
other => return Err(Error::new(format!("charstring の命令 {other} は読めません"), at)),
}
}
Ok(false)
}
/// 平たい曲線を描く 4 つの命令
fn flex(machine: &mut Machine, code: u8, at: usize) -> Result<(), Error> {
let taken = std::mem::take(&mut machine.stack);
match code {
35 if taken.len() >= 12 => {
curve_to(machine, [taken[0], taken[1], taken[2], taken[3], taken[4], taken[5]]);
curve_to(machine, [taken[6], taken[7], taken[8], taken[9], taken[10], taken[11]]);
}
34 if taken.len() >= 7 => {
let start_y = machine.y;
curve_to(machine, [taken[0], 0.0, taken[1], taken[2], taken[3], 0.0]);
let back = start_y - machine.y;
curve_to(machine, [taken[4], 0.0, taken[5], back, taken[6], 0.0]);
}
36 if taken.len() >= 9 => {
let start_y = machine.y;
curve_to(machine, [taken[0], taken[1], taken[2], taken[3], taken[4], 0.0]);
let back = start_y - (machine.y + taken[7]);
curve_to(machine, [taken[5], 0.0, taken[6], taken[7], taken[8], back]);
}
37 if taken.len() >= 11 => {
let start_x = machine.x;
let start_y = machine.y;
let dx: f64 = [taken[0], taken[2], taken[4], taken[6], taken[8]].iter().sum();
let dy: f64 = [taken[1], taken[3], taken[5], taken[7], taken[9]].iter().sum();
curve_to(machine, [taken[0], taken[1], taken[2], taken[3], taken[4], taken[5]]);
let ahead_x = machine.x + taken[6] + taken[8];
let ahead_y = machine.y + taken[7] + taken[9];
let (last_x, last_y) = if dx.abs() > dy.abs() {
(taken[10], start_y - ahead_y)
} else {
(start_x - ahead_x, taken[10])
};
curve_to(machine, [taken[6], taken[7], taken[8], taken[9], last_x, last_y]);
}
other => return Err(Error::new(format!("charstring の命令 12 {other} は読めません"), at)),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::opentype::{Head, character_map, glyph_count as count_glyph, head, require};
use crate::outline::bounds;
fn font() -> (Vec<u8>, Cff, Head) {
let data = std::fs::read("font/latinmodern-math.otf").expect("試験用のフォントを読めません");
let (head_at, _) = require(&data, "head").unwrap();
let shape = head(&data, head_at).unwrap();
let (cff_at, _) = require(&data, "CFF ").unwrap();
let parsed = parse(&data, cff_at, shape.units_per_em).unwrap();
(data, parsed, shape)
}
#[test]
fn the_glyph_count_matches_maxp() {
let (data, cff, _) = font();
let (maxp_at, _) = require(&data, "maxp").unwrap();
assert_eq!(glyph_count(&cff), count_glyph(&data, maxp_at).unwrap());
}
#[test]
fn a_letter_has_a_sensible_box() {
let (data, cff, shape) = font();
let (cmap_at, _) = require(&data, "cmap").unwrap();
let map = character_map(&data, cmap_at).unwrap();
let drawn = outline(&data, &cff, map[&'x']).unwrap();
let (left, bottom, right, top) = bounds(&drawn);
assert!(left >= -50.0 && right < shape.units_per_em);
assert!(bottom.abs() < 30.0, "x に深さが出ています: {bottom}");
assert!(top > 0.3 * shape.units_per_em && top < 0.6 * shape.units_per_em, "x の高さ: {top}");
}
#[test]
fn a_descender_reaches_below_the_baseline() {
let (data, cff, _) = font();
let (cmap_at, _) = require(&data, "cmap").unwrap();
let map = character_map(&data, cmap_at).unwrap();
let (_, bottom, _, _) = bounds(&outline(&data, &cff, map[&'y']).unwrap());
assert!(bottom < -100.0, "y の深さ: {bottom}");
}
#[test]
fn every_glyph_in_the_font_can_be_read() {
let (data, cff, _) = font();
let total = glyph_count(&cff);
for glyph in 0..total {
let result = outline(&data, &cff, glyph as u16);
assert!(result.is_ok(), "字形 {glyph} を読めません: {:?}", result.err());
}
}
#[test]
fn reads_a_font_that_uses_fixed_point_numbers() {
let path = "/System/Library/Fonts/Supplemental/STIXTwoMath.otf";
let Ok(data) = std::fs::read(path) else {
return;
};
let (head_at, _) = require(&data, "head").unwrap();
let shape = head(&data, head_at).unwrap();
let (cff_at, _) = require(&data, "CFF ").unwrap();
let parsed = parse(&data, cff_at, shape.units_per_em).unwrap();
for glyph in 0..glyph_count(&parsed) {
let result = outline(&data, &parsed, glyph as u16);
assert!(result.is_ok(), "字形 {glyph} を読めません: {:?}", result.err());
}
}
#[test]
fn a_missing_glyph_gives_an_empty_outline() {
let (data, cff, _) = font();
assert_eq!(outline(&data, &cff, 60000).unwrap(), Outline::default());
}
}