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
extern crate byteorder;
extern crate footile;
extern crate unicode_normalization;
mod tt;
pub use footile::PathOp;
use unicode_normalization::UnicodeNormalization;
use std::fmt;
use std::sync::Arc;
#[derive(Copy, Clone)]
struct Vec2(pub f32, pub f32);
#[derive(Clone, Debug)]
pub struct FontCollection<'a>(SharedBytes<'a>);
#[derive(Clone)]
pub struct Font<'a> {
info: tt::FontInfo<SharedBytes<'a>>,
}
#[derive(Clone, Debug)]
pub enum SharedBytes<'a> {
ByRef(&'a [u8]),
ByArc(Arc<[u8]>),
}
impl<'a> ::std::ops::Deref for SharedBytes<'a> {
type Target = [u8];
fn deref(&self) -> &[u8] {
match *self {
SharedBytes::ByRef(bytes) => bytes,
SharedBytes::ByArc(ref bytes) => &**bytes,
}
}
}
impl<'a> From<&'a [u8]> for SharedBytes<'a> {
fn from(bytes: &'a [u8]) -> SharedBytes<'a> {
SharedBytes::ByRef(bytes)
}
}
impl From<Arc<[u8]>> for SharedBytes<'static> {
fn from(bytes: Arc<[u8]>) -> SharedBytes<'static> {
SharedBytes::ByArc(bytes)
}
}
impl From<Box<[u8]>> for SharedBytes<'static> {
fn from(bytes: Box<[u8]>) -> SharedBytes<'static> {
SharedBytes::ByArc(bytes.into())
}
}
impl From<Vec<u8>> for SharedBytes<'static> {
fn from(bytes: Vec<u8>) -> SharedBytes<'static> {
SharedBytes::ByArc(bytes.into())
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct Codepoint(pub u32);
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
struct GlyphId(pub u32);
#[derive(Clone)]
struct Glyph<'a> {
inner: GlyphInner<'a>,
v: Vec2,
}
#[derive(Clone)]
struct GlyphInner<'a>(Font<'a>, u32);
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
struct HMetrics {
pub advance_width: f32,
pub left_side_bearing: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
struct VMetrics {
pub ascent: f32,
pub descent: f32,
pub line_gap: f32,
}
impl From<tt::VMetrics> for VMetrics {
fn from(vm: tt::VMetrics) -> Self {
Self {
ascent: vm.ascent as f32,
descent: vm.descent as f32,
line_gap: vm.line_gap as f32,
}
}
}
trait IntoGlyphId {
fn into_glyph_id(self, &Font) -> GlyphId;
}
impl IntoGlyphId for char {
fn into_glyph_id(self, font: &Font) -> GlyphId {
GlyphId(font.info.find_glyph_index(self as u32))
}
}
impl IntoGlyphId for Codepoint {
fn into_glyph_id(self, font: &Font) -> GlyphId {
GlyphId(font.info.find_glyph_index(self.0))
}
}
impl IntoGlyphId for GlyphId {
fn into_glyph_id(self, _font: &Font) -> GlyphId {
self
}
}
impl<'a> FontCollection<'a> {
pub fn new<B: Into<SharedBytes<'a>>>(bytes: B) -> Result<FontCollection<'a>, Error> {
let bytes = bytes.into();
if !tt::is_font(&bytes) && &bytes[0..4] != b"ttcf" {
return Err(Error::UnrecognizedFormat);
}
Ok(FontCollection(bytes))
}
pub fn into_font(self) -> Result<Font<'a>, Error> {
let offset = if tt::is_font(&self.0) {
0
} else if tt::get_font_offset_for_index(&self.0, 1).is_some() {
return Err(Error::CollectionContainsMultipleFonts);
} else {
match tt::get_font_offset_for_index(&self.0, 0) {
None => return Err(Error::IllFormed),
Some(offset) => offset,
}
};
let info = tt::FontInfo::new(self.0, offset as usize).ok_or(Error::IllFormed)?;
Ok(Font { info })
}
pub fn font_at(&self, i: usize) -> Result<Font<'a>, Error> {
let offset = tt::get_font_offset_for_index(&self.0, i as i32)
.ok_or(Error::CollectionIndexOutOfBounds)?;
let info = tt::FontInfo::new(self.0.clone(), offset as usize).ok_or(Error::IllFormed)?;
Ok(Font { info })
}
pub fn into_fonts(self) -> Vec<Font<'a>> {
let mut fonts = vec![];
let mut index = 0;
loop {
let result = self.font_at(index);
if let Err(Error::CollectionIndexOutOfBounds) = result {
break;
}
index += 1;
fonts.push(result.unwrap());
}
fonts
}
}
pub struct PathIterator<'a> {
glyph_iter: GlyphIterator<'a>,
glyph: Option<Glyph<'a>>,
x: f32, y: f32, cx: f32, cy: f32, oc: usize,
vt: bool, rl: bool, ch: char, advance: f32, f: f32, }
static mut OP: PathOp = PathOp::Close();
impl<'a> PathIterator<'a> {
fn new(glyph_iter: GlyphIterator<'a>, xy: (f32, f32)) -> Self {
PathIterator {
glyph_iter,
glyph: None,
x: xy.0,
y: xy.1,
cx: xy.0,
cy: xy.1,
oc: 0,
vt: false,
rl: false,
ch: '\0',
advance: 0.0,
f: 0.0,
}
}
pub fn vertical(mut self) -> Self {
self.vt = true;
self
}
pub fn right_to_left(mut self) -> Self {
self.rl = true;
self
}
}
impl<'a> Iterator for PathIterator<'a> {
type Item = &'static PathOp;
fn next(&mut self) -> Option<Self::Item> {
if self.ch == '\0' {
self.ch = '\x01';
return Some(&PathOp::PenWidth(0.0));
}
if self.glyph.is_none() {
self.ch = *self.glyph_iter.string.get(self.glyph_iter.cursor)?;
let (glyph, advance) = self.glyph_iter.next()?;
if self.ch == '\n' {
self.advance = 0.0;
if self.vt {
self.cy = self.y;
self.cx += if self.rl { -1.0 } else { 1.0 } * glyph.font().v_metrics(glyph.v);
self.f = 0.0;
} else {
self.cx = self.x;
self.cy += glyph.font().v_metrics(glyph.v);
}
return Self::next(self);
} else if self.ch == ' ' && self.vt {
self.advance = 0.0;
self.f = 0.0;
self.cy += glyph.font().v_metrics(glyph.v) * 2.0;
return Self::next(self);
} else if self.ch == '\t' {
if self.vt {
self.advance = 0.0;
self.f = 0.0;
self.cy += glyph.font().v_metrics(glyph.v);
} else {
self.cx += glyph.font().v_metrics(glyph.v) * if self.rl { -4.0 } else { 4.0 };
}
return Self::next(self);
}
self.oc = 0;
if self.vt {
self.f += self.advance;
if self.ch == '.' {
self.f = glyph.font().v_metrics(glyph.v) - advance;
} else if self.f + advance >= glyph.font().v_metrics(glyph.v)
&& advance <= glyph.font().v_metrics(glyph.v)
{
self.f = 0.0;
self.cy += glyph.font().v_metrics(glyph.v);
}
} else {
self.cx += if self.rl { -self.advance } else { self.advance };
}
self.advance = advance;
self.glyph = Some(glyph);
}
let shape = {
let glyph = self.glyph.as_ref().unwrap();
let (font, id) = (glyph.font(), glyph.id());
font.info.get_glyph_shape(id.0).unwrap_or_else(Vec::new)
};
let v = if let Some(v) = shape.get(self.oc) {
v
} else {
self.glyph = None;
return Self::next(self);
};
let glyph = self.glyph.as_ref().unwrap();
let ay = glyph.font().v_metrics(glyph.v);
let x = v.x as f32 * glyph.v.0 + self.cx + if self.rl {
-self.advance - self.f
} else {
self.f
};
let y = -v.y as f32 * glyph.v.1 + self.cy + ay;
use tt::VertexType;
match v.vertex_type() {
VertexType::LineTo => unsafe { OP = PathOp::Line(x, y) },
VertexType::CurveTo => {
let cx = v.cx as f32 * glyph.v.0 + self.cx + if self.rl {
-self.advance - self.f
} else {
self.f
};
let cy = -v.cy as f32 * glyph.v.1 + self.cy + ay;
unsafe { OP = PathOp::Quad(cx, cy, x, y) };
}
VertexType::MoveTo => unsafe { OP = PathOp::Move(x, y) },
}
self.oc += 1;
unsafe { Some(&OP) }
}
}
struct GlyphIterator<'a> {
font: &'a Font<'a>,
api_scale: (f32, f32),
scale: Vec2,
string: Vec<char>,
cursor: usize,
last: Option<Glyph<'a>>,
}
impl<'a> Iterator for GlyphIterator<'a> {
type Item = (Glyph<'a>, f32);
fn next(&mut self) -> Option<(Glyph<'a>, f32)> {
let c = self.string.get(self.cursor);
if let Some(c) = c {
let glyph: Glyph<'a> = self.font.glyph(*c, self.scale);
let mut advance = self
.font
.info
.get_glyph_h_metrics(glyph.id().0)
.advance_width as f32
* self.scale.0;
if self.cursor != 0 {
advance += self.font.kerning(
self.api_scale,
self.scale,
self.last.as_ref().unwrap(),
&glyph,
);
}
self.last = Some(glyph.clone());
self.cursor += 1;
Some((glyph, advance))
} else {
None
}
}
}
impl<'a> Font<'a> {
pub fn new<B: Into<SharedBytes<'a>>>(bytes: B) -> Result<Font<'a>, Error> {
FontCollection::new(bytes).and_then(|c| c.into_font())
}
fn v_metrics(&self, scale: Vec2) -> f32 {
let vm = self.info.get_v_metrics();
let scale = scale.1;
(vm.ascent as f32) * scale
}
fn glyph_count(&self) -> usize {
self.info.get_num_glyphs() as usize
}
fn glyph<C: IntoGlyphId>(&self, id: C, v: Vec2) -> Glyph<'a> {
let gid = id.into_glyph_id(self);
assert!((gid.0 as usize) < self.glyph_count());
Glyph::new(GlyphInner(self.clone(), gid.0), v)
}
fn pair_kerning<A, B>(&self, scale: (f32, f32), v: Vec2, first: A, second: B) -> f32
where
A: IntoGlyphId,
B: IntoGlyphId,
{
let (first, second) = (self.glyph(first, v), self.glyph(second, v));
let factor = self.info.scale_for_pixel_height(scale.1) * (scale.0 / scale.1);
let kern = self
.info
.get_glyph_kern_advance(first.id().0, second.id().0);
factor * kern as f32
}
fn glyphs<T: ToString>(&'a self, text: T, scale: (f32, f32)) -> GlyphIterator<'a> {
let (scale_x, scale_y) = {
let scale_y = self.info.scale_for_pixel_height(scale.1);
let scale_x = scale_y * scale.0 / scale.1;
(scale_x, scale_y)
};
GlyphIterator {
font: &self,
api_scale: scale,
scale: Vec2(scale_x, scale_y),
string: text.to_string().nfc().collect::<Vec<char>>(),
cursor: 0,
last: None,
}
}
pub fn render<T: ToString>(&self, text: T, xy: (f32, f32), wh: (f32, f32)) -> PathIterator {
PathIterator::new(self.glyphs(text, wh), xy)
}
fn kerning(&self, scale: (f32, f32), v: Vec2, first: &Glyph<'a>, second: &Glyph<'a>) -> f32 {
self.pair_kerning(scale, v, first.id(), second.id())
}
}
impl<'a> Glyph<'a> {
fn new(inner: GlyphInner<'a>, v: Vec2) -> Glyph<'a> {
Glyph { inner, v }
}
fn font(&self) -> &Font<'a> {
&self.inner.0
}
fn id(&self) -> GlyphId {
GlyphId(self.inner.1)
}
}
#[derive(Debug)]
pub enum Error {
UnrecognizedFormat,
IllFormed,
CollectionIndexOutOfBounds,
CollectionContainsMultipleFonts,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> {
f.write_str(std::error::Error::description(self))
}
}
impl std::error::Error for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
UnrecognizedFormat => "Font data in unrecognized format",
IllFormed => "Font data is ill-formed",
CollectionIndexOutOfBounds => "Font collection has no font at the given index",
CollectionContainsMultipleFonts => {
"Attempted to convert collection into a font, \
but collection contais more than one font"
}
}
}
}
impl std::convert::From<Error> for std::io::Error {
fn from(error: Error) -> Self {
std::io::Error::new(std::io::ErrorKind::Other, error)
}
}