-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathlib.rs
2416 lines (2148 loc) · 78 KB
/
lib.rs
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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
A high-level, safe, zero-allocation font parser for:
* [TrueType](https://docs.microsoft.com/en-us/typography/truetype/),
* [OpenType](https://docs.microsoft.com/en-us/typography/opentype/spec/), and
* [AAT](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6AATIntro.html)
fonts.
Font parsing starts with a [`Face`].
## Features
- A high-level API for most common properties, hiding all parsing and data resolving logic.
- A low-level, but safe API to access TrueType tables data.
- Highly configurable. You can disable most of the features, reducing binary size.
You can also parse TrueType tables separately, without loading the whole font/face.
- Zero heap allocations.
- Zero unsafe.
- Zero dependencies.
- `no_std`/WASM compatible.
- Fast.
- Stateless. All parsing methods are immutable.
- Simple and maintainable code (no magic numbers).
## Safety
- The library must not panic. Any panic considered as a critical bug and should be reported.
- The library forbids unsafe code.
- No heap allocations, so crash due to OOM is not possible.
- All recursive methods have a depth limit.
- Technically, should use less than 64KiB of stack in worst case scenario.
- Most of arithmetic operations are checked.
- Most of numeric casts are checked.
*/
#![no_std]
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![warn(missing_copy_implementations)]
#![warn(missing_debug_implementations)]
#![allow(clippy::get_first)] // we use it for readability
#![allow(clippy::identity_op)] // we use it for readability
#![allow(clippy::too_many_arguments)]
#![allow(clippy::collapsible_else_if)]
#![allow(clippy::field_reassign_with_default)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::bool_assert_comparison)]
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[cfg(not(any(feature = "std", feature = "no-std-float")))]
compile_error!("You have to activate either the `std` or the `no-std-float` feature.");
#[cfg(not(feature = "std"))]
use core_maths::CoreFloat;
#[cfg(feature = "apple-layout")]
mod aat;
#[cfg(feature = "variable-fonts")]
mod delta_set;
#[cfg(feature = "opentype-layout")]
mod ggg;
mod language;
mod parser;
mod tables;
#[cfg(feature = "variable-fonts")]
mod var_store;
use head::IndexToLocationFormat;
pub use parser::{Fixed, FromData, LazyArray16, LazyArray32, LazyArrayIter16, LazyArrayIter32};
use parser::{NumFrom, Offset, Offset32, Stream, TryNumFrom};
#[cfg(feature = "variable-fonts")]
pub use fvar::VariationAxis;
pub use language::Language;
pub use name::{name_id, PlatformId};
pub use os2::{Permissions, ScriptMetrics, Style, UnicodeRanges, Weight, Width};
pub use tables::CFFError;
#[cfg(feature = "apple-layout")]
pub use tables::{ankr, feat, kerx, morx, trak};
#[cfg(feature = "variable-fonts")]
pub use tables::{avar, cff2, fvar, gvar, hvar, mvar, vvar};
pub use tables::{cbdt, cblc, cff1 as cff, vhea};
pub use tables::{
cmap, colr, cpal, glyf, head, hhea, hmtx, kern, loca, maxp, name, os2, post, sbix, stat, svg,
vorg,
};
#[cfg(feature = "opentype-layout")]
pub use tables::{gdef, gpos, gsub, math};
#[cfg(feature = "opentype-layout")]
pub mod opentype_layout {
//! This module contains
//! [OpenType Layout](https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#overview)
//! supplementary tables implementation.
pub use crate::ggg::*;
}
#[cfg(feature = "apple-layout")]
pub mod apple_layout {
//! This module contains
//! [Apple Advanced Typography Layout](
//! https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6AATIntro.html)
//! supplementary tables implementation.
pub use crate::aat::*;
}
/// A type-safe wrapper for glyph ID.
#[repr(transparent)]
#[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Default, Debug, Hash)]
pub struct GlyphId(pub u16);
impl FromData for GlyphId {
const SIZE: usize = 2;
#[inline]
fn parse(data: &[u8]) -> Option<Self> {
u16::parse(data).map(GlyphId)
}
}
/// A TrueType font magic.
///
/// https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
#[derive(Clone, Copy, PartialEq, Debug)]
enum Magic {
TrueType,
OpenType,
FontCollection,
}
impl FromData for Magic {
const SIZE: usize = 4;
#[inline]
fn parse(data: &[u8]) -> Option<Self> {
match u32::parse(data)? {
0x00010000 | 0x74727565 => Some(Magic::TrueType),
0x4F54544F => Some(Magic::OpenType),
0x74746366 => Some(Magic::FontCollection),
_ => None,
}
}
}
/// A variation coordinate in a normalized coordinate system.
///
/// Basically any number in a -1.0..1.0 range.
/// Where 0 is a default value.
///
/// The number is stored as f2.16
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
pub struct NormalizedCoordinate(i16);
impl From<i16> for NormalizedCoordinate {
/// Creates a new coordinate.
///
/// The provided number will be clamped to the -16384..16384 range.
#[inline]
fn from(n: i16) -> Self {
NormalizedCoordinate(parser::i16_bound(-16384, n, 16384))
}
}
impl From<f32> for NormalizedCoordinate {
/// Creates a new coordinate.
///
/// The provided number will be clamped to the -1.0..1.0 range.
#[inline]
fn from(n: f32) -> Self {
NormalizedCoordinate((parser::f32_bound(-1.0, n, 1.0) * 16384.0) as i16)
}
}
impl NormalizedCoordinate {
/// Returns the coordinate value as f2.14.
#[inline]
pub fn get(self) -> i16 {
self.0
}
}
/// A font variation value.
///
/// # Example
///
/// ```
/// use ttf_parser::{Variation, Tag};
///
/// Variation { axis: Tag::from_bytes(b"wght"), value: 500.0 };
/// ```
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Variation {
/// An axis tag name.
pub axis: Tag,
/// An axis value.
pub value: f32,
}
/// A 4-byte tag.
#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag(pub u32);
impl Tag {
/// Creates a `Tag` from bytes.
///
/// # Example
///
/// ```rust
/// println!("{}", ttf_parser::Tag::from_bytes(b"name"));
/// ```
#[inline]
pub const fn from_bytes(bytes: &[u8; 4]) -> Self {
Tag(((bytes[0] as u32) << 24)
| ((bytes[1] as u32) << 16)
| ((bytes[2] as u32) << 8)
| (bytes[3] as u32))
}
/// Creates a `Tag` from bytes.
///
/// In case of empty data will return `Tag` set to 0.
///
/// When `bytes` are shorter than 4, will set missing bytes to ` `.
///
/// Data after first 4 bytes is ignored.
#[inline]
pub fn from_bytes_lossy(bytes: &[u8]) -> Self {
if bytes.is_empty() {
return Tag::from_bytes(&[0, 0, 0, 0]);
}
let mut iter = bytes.iter().cloned().chain(core::iter::repeat(b' '));
Tag::from_bytes(&[
iter.next().unwrap(),
iter.next().unwrap(),
iter.next().unwrap(),
iter.next().unwrap(),
])
}
/// Returns tag as 4-element byte array.
#[inline]
pub const fn to_bytes(self) -> [u8; 4] {
[
(self.0 >> 24 & 0xff) as u8,
(self.0 >> 16 & 0xff) as u8,
(self.0 >> 8 & 0xff) as u8,
(self.0 >> 0 & 0xff) as u8,
]
}
/// Returns tag as 4-element byte array.
#[inline]
pub const fn to_chars(self) -> [char; 4] {
[
(self.0 >> 24 & 0xff) as u8 as char,
(self.0 >> 16 & 0xff) as u8 as char,
(self.0 >> 8 & 0xff) as u8 as char,
(self.0 >> 0 & 0xff) as u8 as char,
]
}
/// Checks if tag is null / `[0, 0, 0, 0]`.
#[inline]
pub const fn is_null(&self) -> bool {
self.0 == 0
}
/// Returns tag value as `u32` number.
#[inline]
pub const fn as_u32(&self) -> u32 {
self.0
}
}
impl core::fmt::Debug for Tag {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Tag({})", self)
}
}
impl core::fmt::Display for Tag {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let b = self.to_chars();
write!(
f,
"{}{}{}{}",
b.get(0).unwrap_or(&' '),
b.get(1).unwrap_or(&' '),
b.get(2).unwrap_or(&' '),
b.get(3).unwrap_or(&' ')
)
}
}
impl FromData for Tag {
const SIZE: usize = 4;
#[inline]
fn parse(data: &[u8]) -> Option<Self> {
u32::parse(data).map(Tag)
}
}
/// A line metrics.
///
/// Used for underline and strikeout.
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct LineMetrics {
/// Line position.
pub position: i16,
/// Line thickness.
pub thickness: i16,
}
/// A rectangle.
///
/// Doesn't guarantee that `x_min` <= `x_max` and/or `y_min` <= `y_max`.
#[repr(C)]
#[allow(missing_docs)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct Rect {
pub x_min: i16,
pub y_min: i16,
pub x_max: i16,
pub y_max: i16,
}
impl Rect {
#[inline]
fn zero() -> Self {
Self {
x_min: 0,
y_min: 0,
x_max: 0,
y_max: 0,
}
}
/// Returns rect's width.
#[inline]
pub fn width(&self) -> i16 {
self.x_max - self.x_min
}
/// Returns rect's height.
#[inline]
pub fn height(&self) -> i16 {
self.y_max - self.y_min
}
}
/// A rectangle described by the left-lower and upper-right points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RectF {
/// The horizontal minimum of the rect.
pub x_min: f32,
/// The vertical minimum of the rect.
pub y_min: f32,
/// The horizontal maximum of the rect.
pub x_max: f32,
/// The vertical maximum of the rect.
pub y_max: f32,
}
impl RectF {
#[inline]
fn new() -> Self {
RectF {
x_min: f32::MAX,
y_min: f32::MAX,
x_max: f32::MIN,
y_max: f32::MIN,
}
}
#[inline]
fn is_default(&self) -> bool {
self.x_min == f32::MAX
&& self.y_min == f32::MAX
&& self.x_max == f32::MIN
&& self.y_max == f32::MIN
}
#[inline]
fn extend_by(&mut self, x: f32, y: f32) {
self.x_min = self.x_min.min(x);
self.y_min = self.y_min.min(y);
self.x_max = self.x_max.max(x);
self.y_max = self.y_max.max(y);
}
#[inline]
fn to_rect(self) -> Option<Rect> {
Some(Rect {
x_min: i16::try_num_from(self.x_min)?,
y_min: i16::try_num_from(self.y_min)?,
x_max: i16::try_num_from(self.x_max)?,
y_max: i16::try_num_from(self.y_max)?,
})
}
}
/// An affine transform.
#[derive(Clone, Copy, PartialEq)]
pub struct Transform {
/// The 'a' component of the transform.
pub a: f32,
/// The 'b' component of the transform.
pub b: f32,
/// The 'c' component of the transform.
pub c: f32,
/// The 'd' component of the transform.
pub d: f32,
/// The 'e' component of the transform.
pub e: f32,
/// The 'f' component of the transform.
pub f: f32,
}
impl Transform {
/// Creates a new transform with the specified components.
#[inline]
pub fn new(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
Transform { a, b, c, d, e, f }
}
/// Creates a new translation transform.
#[inline]
pub fn new_translate(tx: f32, ty: f32) -> Self {
Transform::new(1.0, 0.0, 0.0, 1.0, tx, ty)
}
/// Creates a new rotation transform.
#[inline]
pub fn new_rotate(angle: f32) -> Self {
let cc = (angle * core::f32::consts::PI).cos();
let ss = (angle * core::f32::consts::PI).sin();
Transform::new(cc, ss, -ss, cc, 0.0, 0.0)
}
/// Creates a new skew transform.
#[inline]
pub fn new_skew(skew_x: f32, skew_y: f32) -> Self {
let x = (skew_x * core::f32::consts::PI).tan();
let y = (skew_y * core::f32::consts::PI).tan();
Transform::new(1.0, y, -x, 1.0, 0.0, 0.0)
}
/// Creates a new scale transform.
#[inline]
pub fn new_scale(sx: f32, sy: f32) -> Self {
Transform::new(sx, 0.0, 0.0, sy, 0.0, 0.0)
}
/// Combines two transforms with each other.
#[inline]
pub fn combine(ts1: Self, ts2: Self) -> Self {
Transform {
a: ts1.a * ts2.a + ts1.c * ts2.b,
b: ts1.b * ts2.a + ts1.d * ts2.b,
c: ts1.a * ts2.c + ts1.c * ts2.d,
d: ts1.b * ts2.c + ts1.d * ts2.d,
e: ts1.a * ts2.e + ts1.c * ts2.f + ts1.e,
f: ts1.b * ts2.e + ts1.d * ts2.f + ts1.f,
}
}
#[inline]
fn apply_to(&self, x: &mut f32, y: &mut f32) {
let tx = *x;
let ty = *y;
*x = self.a * tx + self.c * ty + self.e;
*y = self.b * tx + self.d * ty + self.f;
}
/// Checks whether a transform is the identity transform.
#[inline]
pub fn is_default(&self) -> bool {
// A direct float comparison is fine in our case.
self.a == 1.0
&& self.b == 0.0
&& self.c == 0.0
&& self.d == 1.0
&& self.e == 0.0
&& self.f == 0.0
}
}
impl Default for Transform {
#[inline]
fn default() -> Self {
Transform {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
e: 0.0,
f: 0.0,
}
}
}
impl core::fmt::Debug for Transform {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
write!(
f,
"Transform({} {} {} {} {} {})",
self.a, self.b, self.c, self.d, self.e, self.f
)
}
}
/// A float point.
#[derive(Clone, Copy, Debug)]
pub struct PointF {
/// The X-axis coordinate.
pub x: f32,
/// The Y-axis coordinate.
pub y: f32,
}
/// Phantom points.
///
/// Available only for variable fonts with the `gvar` table.
#[derive(Clone, Copy, Debug)]
pub struct PhantomPoints {
/// Left side bearing point.
pub left: PointF,
/// Right side bearing point.
pub right: PointF,
/// Top side bearing point.
pub top: PointF,
/// Bottom side bearing point.
pub bottom: PointF,
}
/// A RGBA color in the sRGB color space.
#[allow(missing_docs)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct RgbaColor {
pub red: u8,
pub green: u8,
pub blue: u8,
pub alpha: u8,
}
impl RgbaColor {
/// Creates a new `RgbaColor`.
#[inline]
pub fn new(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
Self {
blue,
green,
red,
alpha,
}
}
pub(crate) fn apply_alpha(&mut self, alpha: f32) {
self.alpha = (((f32::from(self.alpha) / 255.0) * alpha) * 255.0) as u8;
}
}
/// A trait for glyph outline construction.
pub trait OutlineBuilder {
/// Appends a MoveTo segment.
///
/// Start of a contour.
fn move_to(&mut self, x: f32, y: f32);
/// Appends a LineTo segment.
fn line_to(&mut self, x: f32, y: f32);
/// Appends a QuadTo segment.
fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32);
/// Appends a CurveTo segment.
fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32);
/// Appends a ClosePath segment.
///
/// End of a contour.
fn close(&mut self);
}
struct DummyOutline;
impl OutlineBuilder for DummyOutline {
fn move_to(&mut self, _: f32, _: f32) {}
fn line_to(&mut self, _: f32, _: f32) {}
fn quad_to(&mut self, _: f32, _: f32, _: f32, _: f32) {}
fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, _: f32, _: f32) {}
fn close(&mut self) {}
}
/// A glyph raster image format.
#[allow(missing_docs)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum RasterImageFormat {
PNG,
/// A monochrome bitmap.
///
/// The most significant bit of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. The data for each row is padded to a byte
/// boundary, so the next row begins with the most significant bit of a new byte. 1 corresponds
/// to black, and 0 to white.
BitmapMono,
/// A packed monochrome bitmap.
///
/// The most significant bit of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. Data is tightly packed with no padding. 1
/// corresponds to black, and 0 to white.
BitmapMonoPacked,
/// A grayscale bitmap with 2 bits per pixel.
///
/// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. The data for each row is padded to a byte
/// boundary, so the next row begins with the most significant bit of a new byte.
BitmapGray2,
/// A packed grayscale bitmap with 2 bits per pixel.
///
/// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. Data is tightly packed with no padding.
BitmapGray2Packed,
/// A grayscale bitmap with 4 bits per pixel.
///
/// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. The data for each row is padded to a byte
/// boundary, so the next row begins with the most significant bit of a new byte.
BitmapGray4,
/// A packed grayscale bitmap with 4 bits per pixel.
///
/// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
/// through succeeding bits moving left to right. Data is tightly packed with no padding.
BitmapGray4Packed,
/// A grayscale bitmap with 8 bits per pixel.
///
/// The first byte corresponds to the top-left pixel, proceeding through succeeding bytes
/// moving left to right.
BitmapGray8,
/// A color bitmap with 32 bits per pixel.
///
/// The first group of four bytes corresponds to the top-left pixel, proceeding through
/// succeeding pixels moving left to right. Each byte corresponds to a color channel and the
/// channels within a pixel are in blue, green, red, alpha order. Color values are
/// pre-multiplied by the alpha. For example, the color "full-green with half translucency"
/// is encoded as `\x00\x80\x00\x80`, and not `\x00\xFF\x00\x80`.
BitmapPremulBgra32,
}
/// A glyph's raster image.
///
/// Note, that glyph metrics are in pixels and not in font units.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct RasterGlyphImage<'a> {
/// Horizontal offset.
pub x: i16,
/// Vertical offset.
pub y: i16,
/// Image width.
///
/// It doesn't guarantee that this value is the same as set in the `data`.
pub width: u16,
/// Image height.
///
/// It doesn't guarantee that this value is the same as set in the `data`.
pub height: u16,
/// A pixels per em of the selected strike.
pub pixels_per_em: u16,
/// An image format.
pub format: RasterImageFormat,
/// A raw image data. It's up to the caller to decode it.
pub data: &'a [u8],
}
/// A raw table record.
#[derive(Clone, Copy, Debug)]
#[allow(missing_docs)]
pub struct TableRecord {
pub tag: Tag,
#[allow(dead_code)]
pub check_sum: u32,
pub offset: u32,
pub length: u32,
}
impl FromData for TableRecord {
const SIZE: usize = 16;
#[inline]
fn parse(data: &[u8]) -> Option<Self> {
let mut s = Stream::new(data);
Some(TableRecord {
tag: s.read::<Tag>()?,
check_sum: s.read::<u32>()?,
offset: s.read::<u32>()?,
length: s.read::<u32>()?,
})
}
}
#[cfg(feature = "variable-fonts")]
const MAX_VAR_COORDS: usize = 64;
#[cfg(feature = "variable-fonts")]
#[derive(Clone)]
struct VarCoords {
data: [NormalizedCoordinate; MAX_VAR_COORDS],
len: u8,
}
#[cfg(feature = "variable-fonts")]
impl Default for VarCoords {
fn default() -> Self {
Self {
data: [NormalizedCoordinate::default(); MAX_VAR_COORDS],
len: u8::default(),
}
}
}
#[cfg(feature = "variable-fonts")]
impl VarCoords {
#[inline]
fn as_slice(&self) -> &[NormalizedCoordinate] {
&self.data[0..usize::from(self.len)]
}
#[inline]
fn as_mut_slice(&mut self) -> &mut [NormalizedCoordinate] {
let end = usize::from(self.len);
&mut self.data[0..end]
}
}
/// A list of font face parsing errors.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum FaceParsingError {
/// An attempt to read out of bounds detected.
///
/// Should occur only on malformed fonts.
MalformedFont,
/// Face data must start with `0x00010000`, `0x74727565`, `0x4F54544F` or `0x74746366`.
UnknownMagic,
/// The face index is larger than the number of faces in the font.
FaceIndexOutOfBounds,
/// The `head` table is missing or malformed.
NoHeadTable,
/// The `hhea` table is missing or malformed.
NoHheaTable,
/// The `maxp` table is missing or malformed.
NoMaxpTable,
}
impl core::fmt::Display for FaceParsingError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FaceParsingError::MalformedFont => write!(f, "malformed font"),
FaceParsingError::UnknownMagic => write!(f, "unknown magic"),
FaceParsingError::FaceIndexOutOfBounds => write!(f, "face index is out of bounds"),
FaceParsingError::NoHeadTable => write!(f, "the head table is missing or malformed"),
FaceParsingError::NoHheaTable => write!(f, "the hhea table is missing or malformed"),
FaceParsingError::NoMaxpTable => write!(f, "the maxp table is missing or malformed"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for FaceParsingError {}
/// A raw font face.
///
/// You are probably looking for [`Face`]. This is a low-level type.
///
/// Unlike [`Face`], [`RawFace`] parses only face table records.
/// Meaning all you can get from this type is a raw (`&[u8]`) data of a requested table.
/// Then you can either parse just a singe table from a font/face or populate [`RawFaceTables`]
/// manually before passing it to [`Face::from_raw_tables`].
#[derive(Clone, Copy)]
pub struct RawFace<'a> {
/// The input font file data.
pub data: &'a [u8],
/// An array of table records.
pub table_records: LazyArray16<'a, TableRecord>,
}
impl<'a> RawFace<'a> {
/// Creates a new [`RawFace`] from a raw data.
///
/// `index` indicates the specific font face in a font collection.
/// Use [`fonts_in_collection`] to get the total number of font faces.
/// Set to 0 if unsure.
///
/// While we do reuse [`FaceParsingError`], `No*Table` errors will not be throws.
#[deprecated(since = "0.16.0", note = "use `parse` instead")]
pub fn from_slice(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
Self::parse(data, index)
}
/// Creates a new [`RawFace`] from a raw data.
///
/// `index` indicates the specific font face in a font collection.
/// Use [`fonts_in_collection`] to get the total number of font faces.
/// Set to 0 if unsure.
///
/// While we do reuse [`FaceParsingError`], `No*Table` errors will not be throws.
pub fn parse(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
// https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
let mut s = Stream::new(data);
// Read **font** magic.
let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
if magic == Magic::FontCollection {
s.skip::<u32>(); // version
let number_of_faces = s.read::<u32>().ok_or(FaceParsingError::MalformedFont)?;
let offsets = s
.read_array32::<Offset32>(number_of_faces)
.ok_or(FaceParsingError::MalformedFont)?;
let face_offset = offsets
.get(index)
.ok_or(FaceParsingError::FaceIndexOutOfBounds)?;
// Face offset is from the start of the font data,
// so we have to adjust it to the current parser offset.
let face_offset = face_offset
.to_usize()
.checked_sub(s.offset())
.ok_or(FaceParsingError::MalformedFont)?;
s.advance_checked(face_offset)
.ok_or(FaceParsingError::MalformedFont)?;
// Read **face** magic.
// Each face in a font collection also starts with a magic.
let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
// And face in a font collection can't be another collection.
if magic == Magic::FontCollection {
return Err(FaceParsingError::UnknownMagic);
}
} else {
// When reading from a regular font (not a collection) disallow index to be non-zero
// Basically treat the font as a one-element collection
if index != 0 {
return Err(FaceParsingError::FaceIndexOutOfBounds);
}
}
let num_tables = s.read::<u16>().ok_or(FaceParsingError::MalformedFont)?;
s.advance(6); // searchRange (u16) + entrySelector (u16) + rangeShift (u16)
let table_records = s
.read_array16::<TableRecord>(num_tables)
.ok_or(FaceParsingError::MalformedFont)?;
Ok(RawFace {
data,
table_records,
})
}
/// Returns the raw data of a selected table.
pub fn table(&self, tag: Tag) -> Option<&'a [u8]> {
let (_, table) = self
.table_records
.binary_search_by(|record| record.tag.cmp(&tag))?;
let offset = usize::num_from(table.offset);
let length = usize::num_from(table.length);
let end = offset.checked_add(length)?;
self.data.get(offset..end)
}
}
impl core::fmt::Debug for RawFace<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "RawFace {{ ... }}")
}
}
/// A list of all supported tables as raw data.
///
/// This type should be used in tandem with
/// [`Face::from_raw_tables()`](struct.Face.html#method.from_raw_tables).
///
/// This allows loading font faces not only from TrueType font files,
/// but from any source. Mainly used for parsing WOFF.
#[allow(missing_docs)]
#[allow(missing_debug_implementations)]
#[derive(Clone, Default)]
pub struct RawFaceTables<'a> {
// Mandatory tables.
pub head: &'a [u8],
pub hhea: &'a [u8],
pub maxp: &'a [u8],
pub bdat: Option<&'a [u8]>,
pub bloc: Option<&'a [u8]>,
pub cbdt: Option<&'a [u8]>,
pub cblc: Option<&'a [u8]>,
pub cff: Option<&'a [u8]>,
pub cmap: Option<&'a [u8]>,
pub colr: Option<&'a [u8]>,
pub cpal: Option<&'a [u8]>,
pub ebdt: Option<&'a [u8]>,
pub eblc: Option<&'a [u8]>,
pub glyf: Option<&'a [u8]>,
pub hmtx: Option<&'a [u8]>,
pub kern: Option<&'a [u8]>,
pub loca: Option<&'a [u8]>,
pub name: Option<&'a [u8]>,
pub os2: Option<&'a [u8]>,
pub post: Option<&'a [u8]>,
pub sbix: Option<&'a [u8]>,
pub stat: Option<&'a [u8]>,
pub svg: Option<&'a [u8]>,
pub vhea: Option<&'a [u8]>,
pub vmtx: Option<&'a [u8]>,
pub vorg: Option<&'a [u8]>,
#[cfg(feature = "opentype-layout")]
pub gdef: Option<&'a [u8]>,
#[cfg(feature = "opentype-layout")]
pub gpos: Option<&'a [u8]>,
#[cfg(feature = "opentype-layout")]
pub gsub: Option<&'a [u8]>,
#[cfg(feature = "opentype-layout")]
pub math: Option<&'a [u8]>,
#[cfg(feature = "apple-layout")]
pub ankr: Option<&'a [u8]>,
#[cfg(feature = "apple-layout")]
pub feat: Option<&'a [u8]>,
#[cfg(feature = "apple-layout")]
pub kerx: Option<&'a [u8]>,
#[cfg(feature = "apple-layout")]
pub morx: Option<&'a [u8]>,
#[cfg(feature = "apple-layout")]
pub trak: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub avar: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub cff2: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub fvar: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub gvar: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub hvar: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub mvar: Option<&'a [u8]>,
#[cfg(feature = "variable-fonts")]
pub vvar: Option<&'a [u8]>,
}
/// Parsed face tables.
///
/// Unlike [`Face`], provides a low-level parsing abstraction over TrueType tables.
/// Useful when you need a direct access to tables data.
///
/// Also, used when high-level API is problematic to implement.
/// A good example would be OpenType layout tables (GPOS/GSUB).
#[allow(missing_docs)]
#[allow(missing_debug_implementations)]
#[derive(Clone)]
pub struct FaceTables<'a> {
// Mandatory tables.
pub head: head::Table,
pub hhea: hhea::Table,
pub maxp: maxp::Table,
pub bdat: Option<cbdt::Table<'a>>,