Skip to main content

xberg_ttf_parser/
lib.rs

1/*!
2A high-level, safe, zero-allocation font parser for:
3* [TrueType](https://docs.microsoft.com/en-us/typography/truetype/),
4* [OpenType](https://docs.microsoft.com/en-us/typography/opentype/spec/), and
5* [AAT](https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6AATIntro.html)
6  fonts.
7
8Font parsing starts with a [`Face`].
9
10## Features
11
12- A high-level API for most common properties, hiding all parsing and data resolving logic.
13- A low-level, but safe API to access TrueType tables data.
14- Highly configurable. You can disable most of the features, reducing binary size.
15  You can also parse TrueType tables separately, without loading the whole font/face.
16- Zero heap allocations.
17- Zero unsafe.
18- Zero dependencies.
19- `no_std`/WASM compatible.
20- Fast.
21- Stateless. All parsing methods are immutable.
22- Simple and maintainable code (no magic numbers).
23
24## Safety
25
26- The library must not panic. Any panic considered as a critical bug and should be reported.
27- The library forbids unsafe code.
28- No heap allocations, so crash due to OOM is not possible.
29- All recursive methods have a depth limit.
30- Technically, should use less than 64KiB of stack in worst case scenario.
31- Most of arithmetic operations are checked.
32- Most of numeric casts are checked.
33*/
34
35#![no_std]
36#![forbid(unsafe_code)]
37#![warn(missing_docs)]
38#![warn(missing_copy_implementations)]
39#![warn(missing_debug_implementations)]
40#![allow(clippy::get_first)] // we use it for readability
41#![allow(clippy::identity_op)] // we use it for readability
42#![allow(clippy::too_many_arguments)]
43#![allow(clippy::collapsible_else_if)]
44#![allow(clippy::field_reassign_with_default)]
45#![allow(clippy::upper_case_acronyms)]
46#![allow(clippy::bool_assert_comparison)]
47// Xberg vendoring: the workspace lints are stricter than upstream's CI, and
48// upstream holds a 1.63 MSRV. Silencing these keeps the vendored source
49// byte-identical to upstream so future cherry-picks apply without conflict;
50// `div_ceil` and `is_multiple_of` in particular postdate that MSRV, so
51// "fixing" them here would break upstream's own build. ~keep
52// `missing_docs` is upstream's own `warn` (above), which the workspace `-D warnings`
53// promotes to an error; upstream leaves its table modules undocumented. ~keep
54#![allow(missing_docs)]
55// Lean feature combos (e.g. `--no-default-features --features no-std-float`) leave parts of
56// the vendored tables unreachable — `colr` drops a format binding, `glyf::outline_points` and
57// `post::glyph_indexes` are only reached with `variable-fonts`/`glyph-names`. Allowing here
58// keeps those three files byte-identical to upstream instead of scattering per-site
59// `#[allow]`s that every cherry-pick would then conflict on. ~keep
60#![allow(dead_code)]
61#![allow(unused_variables)]
62// `mismatched_lifetime_syntaxes` postdates the crate's 1.88 MSRV floor, so
63// toolchains at the floor warn on the allow itself. Suppress that first. ~keep
64#![allow(unknown_lints)]
65#![allow(mismatched_lifetime_syntaxes)]
66#![allow(clippy::manual_div_ceil)]
67#![allow(clippy::manual_is_multiple_of)]
68#![allow(clippy::same_item_push)]
69#![allow(clippy::unnecessary_map_or)]
70#![allow(clippy::derivable_impls)]
71#![allow(clippy::large_enum_variant)]
72
73#[cfg(feature = "std")]
74#[macro_use]
75extern crate std;
76
77#[cfg(not(any(feature = "std", feature = "no-std-float")))]
78compile_error!("You have to activate either the `std` or the `no-std-float` feature.");
79
80#[cfg(not(feature = "std"))]
81use core_maths::CoreFloat;
82
83#[cfg(feature = "apple-layout")]
84mod aat;
85#[cfg(feature = "variable-fonts")]
86mod delta_set;
87#[cfg(feature = "opentype-layout")]
88mod ggg;
89mod language;
90mod parser;
91mod tables;
92#[cfg(feature = "variable-fonts")]
93mod var_store;
94
95use head::IndexToLocationFormat;
96pub use parser::{Fixed, FromData, LazyArray16, LazyArray32, LazyArrayIter16, LazyArrayIter32};
97use parser::{NumFrom, Offset, Offset32, Stream, TryNumFrom};
98
99#[cfg(feature = "variable-fonts")]
100pub use fvar::VariationAxis;
101
102pub use language::Language;
103pub use name::{PlatformId, name_id};
104pub use os2::{Permissions, ScriptMetrics, Style, UnicodeRanges, Weight, Width};
105pub use tables::CFFError;
106#[cfg(feature = "apple-layout")]
107pub use tables::{ankr, feat, kerx, morx, trak};
108#[cfg(feature = "variable-fonts")]
109pub use tables::{avar, cff2, fvar, gvar, hvar, mvar, vvar};
110pub use tables::{cbdt, cblc, cff1 as cff, vhea};
111pub use tables::{cmap, colr, cpal, glyf, head, hhea, hmtx, kern, loca, maxp, name, os2, post, sbix, stat, svg, vorg};
112#[cfg(feature = "opentype-layout")]
113pub use tables::{gdef, gpos, gsub, math};
114
115#[cfg(feature = "opentype-layout")]
116pub mod opentype_layout {
117    //! This module contains
118    //! [OpenType Layout](https://docs.microsoft.com/en-us/typography/opentype/spec/chapter2#overview)
119    //! supplementary tables implementation.
120    pub use crate::ggg::*;
121}
122
123#[cfg(feature = "apple-layout")]
124pub mod apple_layout {
125    //! This module contains
126    //! [Apple Advanced Typography Layout](
127    //! https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6AATIntro.html)
128    //! supplementary tables implementation.
129    pub use crate::aat::*;
130}
131
132/// A type-safe wrapper for glyph ID.
133#[repr(transparent)]
134#[derive(Clone, Copy, Ord, PartialOrd, Eq, PartialEq, Default, Debug, Hash)]
135pub struct GlyphId(pub u16);
136
137impl FromData for GlyphId {
138    const SIZE: usize = 2;
139
140    #[inline]
141    fn parse(data: &[u8]) -> Option<Self> {
142        u16::parse(data).map(GlyphId)
143    }
144}
145
146/// A TrueType font magic.
147///
148/// https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
149#[derive(Clone, Copy, PartialEq, Debug)]
150enum Magic {
151    TrueType,
152    OpenType,
153    FontCollection,
154}
155
156impl FromData for Magic {
157    const SIZE: usize = 4;
158
159    #[inline]
160    fn parse(data: &[u8]) -> Option<Self> {
161        match u32::parse(data)? {
162            0x00010000 | 0x74727565 => Some(Magic::TrueType),
163            0x4F54544F => Some(Magic::OpenType),
164            0x74746366 => Some(Magic::FontCollection),
165            _ => None,
166        }
167    }
168}
169
170/// A variation coordinate in a normalized coordinate system.
171///
172/// Basically any number in a -1.0..1.0 range.
173/// Where 0 is a default value.
174///
175/// The number is stored as f2.16
176#[repr(transparent)]
177#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
178pub struct NormalizedCoordinate(i16);
179
180impl From<i16> for NormalizedCoordinate {
181    /// Creates a new coordinate.
182    ///
183    /// The provided number will be clamped to the -16384..16384 range.
184    #[inline]
185    fn from(n: i16) -> Self {
186        NormalizedCoordinate(parser::i16_bound(-16384, n, 16384))
187    }
188}
189
190impl From<f32> for NormalizedCoordinate {
191    /// Creates a new coordinate.
192    ///
193    /// The provided number will be clamped to the -1.0..1.0 range.
194    #[inline]
195    fn from(n: f32) -> Self {
196        NormalizedCoordinate((parser::f32_bound(-1.0, n, 1.0) * 16384.0) as i16)
197    }
198}
199
200impl NormalizedCoordinate {
201    /// Returns the coordinate value as f2.14.
202    #[inline]
203    pub fn get(self) -> i16 {
204        self.0
205    }
206}
207
208/// A font variation value.
209///
210/// # Example
211///
212/// ```
213/// use ttf_parser::{Variation, Tag};
214///
215/// Variation { axis: Tag::from_bytes(b"wght"), value: 500.0 };
216/// ```
217#[derive(Clone, Copy, PartialEq, Debug)]
218pub struct Variation {
219    /// An axis tag name.
220    pub axis: Tag,
221    /// An axis value.
222    pub value: f32,
223}
224
225/// A 4-byte tag.
226#[repr(transparent)]
227#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
228pub struct Tag(pub u32);
229
230impl Tag {
231    /// Creates a `Tag` from bytes.
232    ///
233    /// # Example
234    ///
235    /// ```rust
236    /// println!("{}", ttf_parser::Tag::from_bytes(b"name"));
237    /// ```
238    #[inline]
239    pub const fn from_bytes(bytes: &[u8; 4]) -> Self {
240        Tag(((bytes[0] as u32) << 24) | ((bytes[1] as u32) << 16) | ((bytes[2] as u32) << 8) | (bytes[3] as u32))
241    }
242
243    /// Creates a `Tag` from bytes.
244    ///
245    /// In case of empty data will return `Tag` set to 0.
246    ///
247    /// When `bytes` are shorter than 4, will set missing bytes to ` `.
248    ///
249    /// Data after first 4 bytes is ignored.
250    #[inline]
251    pub fn from_bytes_lossy(bytes: &[u8]) -> Self {
252        if bytes.is_empty() {
253            return Tag::from_bytes(&[0, 0, 0, 0]);
254        }
255
256        let mut iter = bytes.iter().cloned().chain(core::iter::repeat(b' '));
257        Tag::from_bytes(&[
258            iter.next().unwrap(),
259            iter.next().unwrap(),
260            iter.next().unwrap(),
261            iter.next().unwrap(),
262        ])
263    }
264
265    /// Returns tag as 4-element byte array.
266    #[inline]
267    pub const fn to_bytes(self) -> [u8; 4] {
268        [
269            (self.0 >> 24 & 0xff) as u8,
270            (self.0 >> 16 & 0xff) as u8,
271            (self.0 >> 8 & 0xff) as u8,
272            (self.0 >> 0 & 0xff) as u8,
273        ]
274    }
275
276    /// Returns tag as 4-element byte array.
277    #[inline]
278    pub const fn to_chars(self) -> [char; 4] {
279        [
280            (self.0 >> 24 & 0xff) as u8 as char,
281            (self.0 >> 16 & 0xff) as u8 as char,
282            (self.0 >> 8 & 0xff) as u8 as char,
283            (self.0 >> 0 & 0xff) as u8 as char,
284        ]
285    }
286
287    /// Checks if tag is null / `[0, 0, 0, 0]`.
288    #[inline]
289    pub const fn is_null(&self) -> bool {
290        self.0 == 0
291    }
292
293    /// Returns tag value as `u32` number.
294    #[inline]
295    pub const fn as_u32(&self) -> u32 {
296        self.0
297    }
298}
299
300impl core::fmt::Debug for Tag {
301    #[inline]
302    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
303        write!(f, "Tag({})", self)
304    }
305}
306
307impl core::fmt::Display for Tag {
308    #[inline]
309    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
310        let b = self.to_chars();
311        write!(
312            f,
313            "{}{}{}{}",
314            b.get(0).unwrap_or(&' '),
315            b.get(1).unwrap_or(&' '),
316            b.get(2).unwrap_or(&' '),
317            b.get(3).unwrap_or(&' ')
318        )
319    }
320}
321
322impl FromData for Tag {
323    const SIZE: usize = 4;
324
325    #[inline]
326    fn parse(data: &[u8]) -> Option<Self> {
327        u32::parse(data).map(Tag)
328    }
329}
330
331/// A line metrics.
332///
333/// Used for underline and strikeout.
334#[repr(C)]
335#[derive(Clone, Copy, PartialEq, Eq, Debug)]
336pub struct LineMetrics {
337    /// Line position.
338    pub position: i16,
339
340    /// Line thickness.
341    pub thickness: i16,
342}
343
344/// A rectangle.
345///
346/// Doesn't guarantee that `x_min` <= `x_max` and/or `y_min` <= `y_max`.
347#[repr(C)]
348#[allow(missing_docs)]
349#[derive(Clone, Copy, PartialEq, Eq, Debug)]
350pub struct Rect {
351    pub x_min: i16,
352    pub y_min: i16,
353    pub x_max: i16,
354    pub y_max: i16,
355}
356
357impl Rect {
358    #[inline]
359    fn zero() -> Self {
360        Self {
361            x_min: 0,
362            y_min: 0,
363            x_max: 0,
364            y_max: 0,
365        }
366    }
367
368    /// Returns rect's width.
369    #[inline]
370    pub fn width(&self) -> i16 {
371        self.x_max - self.x_min
372    }
373
374    /// Returns rect's height.
375    #[inline]
376    pub fn height(&self) -> i16 {
377        self.y_max - self.y_min
378    }
379}
380
381/// A rectangle described by the left-lower and upper-right points.
382#[derive(Clone, Copy, Debug, PartialEq)]
383pub struct RectF {
384    /// The horizontal minimum of the rect.
385    pub x_min: f32,
386    /// The vertical minimum of the rect.
387    pub y_min: f32,
388    /// The horizontal maximum of the rect.
389    pub x_max: f32,
390    /// The vertical maximum of the rect.
391    pub y_max: f32,
392}
393
394impl RectF {
395    #[inline]
396    fn new() -> Self {
397        RectF {
398            x_min: f32::MAX,
399            y_min: f32::MAX,
400            x_max: f32::MIN,
401            y_max: f32::MIN,
402        }
403    }
404
405    #[inline]
406    fn is_default(&self) -> bool {
407        self.x_min == f32::MAX && self.y_min == f32::MAX && self.x_max == f32::MIN && self.y_max == f32::MIN
408    }
409
410    #[inline]
411    fn extend_by(&mut self, x: f32, y: f32) {
412        self.x_min = self.x_min.min(x);
413        self.y_min = self.y_min.min(y);
414        self.x_max = self.x_max.max(x);
415        self.y_max = self.y_max.max(y);
416    }
417
418    #[inline]
419    fn to_rect(self) -> Option<Rect> {
420        Some(Rect {
421            x_min: i16::try_num_from(self.x_min)?,
422            y_min: i16::try_num_from(self.y_min)?,
423            x_max: i16::try_num_from(self.x_max)?,
424            y_max: i16::try_num_from(self.y_max)?,
425        })
426    }
427}
428
429/// An affine transform.
430#[derive(Clone, Copy, PartialEq)]
431pub struct Transform {
432    /// The 'a' component of the transform.
433    pub a: f32,
434    /// The 'b' component of the transform.
435    pub b: f32,
436    /// The 'c' component of the transform.
437    pub c: f32,
438    /// The 'd' component of the transform.
439    pub d: f32,
440    /// The 'e' component of the transform.
441    pub e: f32,
442    /// The 'f' component of the transform.
443    pub f: f32,
444}
445
446impl Transform {
447    /// Creates a new transform with the specified components.
448    #[inline]
449    pub fn new(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
450        Transform { a, b, c, d, e, f }
451    }
452
453    /// Creates a new translation transform.
454    #[inline]
455    pub fn new_translate(tx: f32, ty: f32) -> Self {
456        Transform::new(1.0, 0.0, 0.0, 1.0, tx, ty)
457    }
458
459    /// Creates a new rotation transform.
460    #[inline]
461    pub fn new_rotate(angle: f32) -> Self {
462        let cc = (angle * core::f32::consts::PI).cos();
463        let ss = (angle * core::f32::consts::PI).sin();
464
465        Transform::new(cc, ss, -ss, cc, 0.0, 0.0)
466    }
467
468    /// Creates a new skew transform.
469    #[inline]
470    pub fn new_skew(skew_x: f32, skew_y: f32) -> Self {
471        let x = (skew_x * core::f32::consts::PI).tan();
472        let y = (skew_y * core::f32::consts::PI).tan();
473
474        Transform::new(1.0, y, -x, 1.0, 0.0, 0.0)
475    }
476
477    /// Creates a new scale transform.
478    #[inline]
479    pub fn new_scale(sx: f32, sy: f32) -> Self {
480        Transform::new(sx, 0.0, 0.0, sy, 0.0, 0.0)
481    }
482
483    /// Combines two transforms with each other.
484    #[inline]
485    pub fn combine(ts1: Self, ts2: Self) -> Self {
486        Transform {
487            a: ts1.a * ts2.a + ts1.c * ts2.b,
488            b: ts1.b * ts2.a + ts1.d * ts2.b,
489            c: ts1.a * ts2.c + ts1.c * ts2.d,
490            d: ts1.b * ts2.c + ts1.d * ts2.d,
491            e: ts1.a * ts2.e + ts1.c * ts2.f + ts1.e,
492            f: ts1.b * ts2.e + ts1.d * ts2.f + ts1.f,
493        }
494    }
495
496    #[inline]
497    fn apply_to(&self, x: &mut f32, y: &mut f32) {
498        let tx = *x;
499        let ty = *y;
500        *x = self.a * tx + self.c * ty + self.e;
501        *y = self.b * tx + self.d * ty + self.f;
502    }
503
504    /// Checks whether a transform is the identity transform.
505    #[inline]
506    pub fn is_default(&self) -> bool {
507        // A direct float comparison is fine in our case.
508        self.a == 1.0 && self.b == 0.0 && self.c == 0.0 && self.d == 1.0 && self.e == 0.0 && self.f == 0.0
509    }
510}
511
512impl Default for Transform {
513    #[inline]
514    fn default() -> Self {
515        Transform {
516            a: 1.0,
517            b: 0.0,
518            c: 0.0,
519            d: 1.0,
520            e: 0.0,
521            f: 0.0,
522        }
523    }
524}
525
526impl core::fmt::Debug for Transform {
527    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
528        write!(
529            f,
530            "Transform({} {} {} {} {} {})",
531            self.a, self.b, self.c, self.d, self.e, self.f
532        )
533    }
534}
535
536/// A float point.
537#[derive(Clone, Copy, Debug)]
538pub struct PointF {
539    /// The X-axis coordinate.
540    pub x: f32,
541    /// The Y-axis coordinate.
542    pub y: f32,
543}
544
545/// Phantom points.
546///
547/// Available only for variable fonts with the `gvar` table.
548#[derive(Clone, Copy, Debug)]
549pub struct PhantomPoints {
550    /// Left side bearing point.
551    pub left: PointF,
552    /// Right side bearing point.
553    pub right: PointF,
554    /// Top side bearing point.
555    pub top: PointF,
556    /// Bottom side bearing point.
557    pub bottom: PointF,
558}
559
560/// A RGBA color in the sRGB color space.
561#[allow(missing_docs)]
562#[derive(Clone, Copy, PartialEq, Eq, Debug)]
563pub struct RgbaColor {
564    pub red: u8,
565    pub green: u8,
566    pub blue: u8,
567    pub alpha: u8,
568}
569
570impl RgbaColor {
571    /// Creates a new `RgbaColor`.
572    #[inline]
573    pub fn new(red: u8, green: u8, blue: u8, alpha: u8) -> Self {
574        Self {
575            blue,
576            green,
577            red,
578            alpha,
579        }
580    }
581
582    pub(crate) fn apply_alpha(&mut self, alpha: f32) {
583        self.alpha = (((f32::from(self.alpha) / 255.0) * alpha) * 255.0) as u8;
584    }
585}
586
587/// A trait for glyph outline construction.
588pub trait OutlineBuilder {
589    /// Appends a MoveTo segment.
590    ///
591    /// Start of a contour.
592    fn move_to(&mut self, x: f32, y: f32);
593
594    /// Appends a LineTo segment.
595    fn line_to(&mut self, x: f32, y: f32);
596
597    /// Appends a QuadTo segment.
598    fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32);
599
600    /// Appends a CurveTo segment.
601    fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32);
602
603    /// Appends a ClosePath segment.
604    ///
605    /// End of a contour.
606    fn close(&mut self);
607}
608
609struct DummyOutline;
610impl OutlineBuilder for DummyOutline {
611    fn move_to(&mut self, _: f32, _: f32) {}
612    fn line_to(&mut self, _: f32, _: f32) {}
613    fn quad_to(&mut self, _: f32, _: f32, _: f32, _: f32) {}
614    fn curve_to(&mut self, _: f32, _: f32, _: f32, _: f32, _: f32, _: f32) {}
615    fn close(&mut self) {}
616}
617
618/// A glyph raster image format.
619#[allow(missing_docs)]
620#[derive(Clone, Copy, PartialEq, Eq, Debug)]
621pub enum RasterImageFormat {
622    PNG,
623
624    /// A monochrome bitmap.
625    ///
626    /// The most significant bit of the first byte corresponds to the top-left pixel, proceeding
627    /// through succeeding bits moving left to right. The data for each row is padded to a byte
628    /// boundary, so the next row begins with the most significant bit of a new byte. 1 corresponds
629    /// to black, and 0 to white.
630    BitmapMono,
631
632    /// A packed monochrome bitmap.
633    ///
634    /// The most significant bit of the first byte corresponds to the top-left pixel, proceeding
635    /// through succeeding bits moving left to right. Data is tightly packed with no padding. 1
636    /// corresponds to black, and 0 to white.
637    BitmapMonoPacked,
638
639    /// A grayscale bitmap with 2 bits per pixel.
640    ///
641    /// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
642    /// through succeeding bits moving left to right. The data for each row is padded to a byte
643    /// boundary, so the next row begins with the most significant bit of a new byte.
644    BitmapGray2,
645
646    /// A packed grayscale bitmap with 2 bits per pixel.
647    ///
648    /// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
649    /// through succeeding bits moving left to right. Data is tightly packed with no padding.
650    BitmapGray2Packed,
651
652    /// A grayscale bitmap with 4 bits per pixel.
653    ///
654    /// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
655    /// through succeeding bits moving left to right. The data for each row is padded to a byte
656    /// boundary, so the next row begins with the most significant bit of a new byte.
657    BitmapGray4,
658
659    /// A packed grayscale bitmap with 4 bits per pixel.
660    ///
661    /// The most significant bits of the first byte corresponds to the top-left pixel, proceeding
662    /// through succeeding bits moving left to right. Data is tightly packed with no padding.
663    BitmapGray4Packed,
664
665    /// A grayscale bitmap with 8 bits per pixel.
666    ///
667    /// The first byte corresponds to the top-left pixel, proceeding through succeeding bytes
668    /// moving left to right.
669    BitmapGray8,
670
671    /// A color bitmap with 32 bits per pixel.
672    ///
673    /// The first group of four bytes corresponds to the top-left pixel, proceeding through
674    /// succeeding pixels moving left to right. Each byte corresponds to a color channel and the
675    /// channels within a pixel are in blue, green, red, alpha order. Color values are
676    /// pre-multiplied by the alpha. For example, the color "full-green with half translucency"
677    /// is encoded as `\x00\x80\x00\x80`, and not `\x00\xFF\x00\x80`.
678    BitmapPremulBgra32,
679}
680
681/// A glyph's raster image.
682///
683/// Note, that glyph metrics are in pixels and not in font units.
684#[derive(Clone, Copy, PartialEq, Eq, Debug)]
685pub struct RasterGlyphImage<'a> {
686    /// Horizontal offset.
687    pub x: i16,
688
689    /// Vertical offset.
690    pub y: i16,
691
692    /// Image width.
693    ///
694    /// It doesn't guarantee that this value is the same as set in the `data`.
695    pub width: u16,
696
697    /// Image height.
698    ///
699    /// It doesn't guarantee that this value is the same as set in the `data`.
700    pub height: u16,
701
702    /// A pixels per em of the selected strike.
703    pub pixels_per_em: u16,
704
705    /// An image format.
706    pub format: RasterImageFormat,
707
708    /// A raw image data. It's up to the caller to decode it.
709    pub data: &'a [u8],
710}
711
712/// A raw table record.
713#[derive(Clone, Copy, Debug)]
714#[allow(missing_docs)]
715pub struct TableRecord {
716    pub tag: Tag,
717    #[allow(dead_code)]
718    pub check_sum: u32,
719    pub offset: u32,
720    pub length: u32,
721}
722
723impl FromData for TableRecord {
724    const SIZE: usize = 16;
725
726    #[inline]
727    fn parse(data: &[u8]) -> Option<Self> {
728        let mut s = Stream::new(data);
729        Some(TableRecord {
730            tag: s.read::<Tag>()?,
731            check_sum: s.read::<u32>()?,
732            offset: s.read::<u32>()?,
733            length: s.read::<u32>()?,
734        })
735    }
736}
737
738#[cfg(feature = "variable-fonts")]
739const MAX_VAR_COORDS: usize = 64;
740
741#[cfg(feature = "variable-fonts")]
742#[derive(Clone)]
743struct VarCoords {
744    data: [NormalizedCoordinate; MAX_VAR_COORDS],
745    len: u8,
746}
747
748#[cfg(feature = "variable-fonts")]
749impl Default for VarCoords {
750    fn default() -> Self {
751        Self {
752            data: [NormalizedCoordinate::default(); MAX_VAR_COORDS],
753            len: u8::default(),
754        }
755    }
756}
757
758#[cfg(feature = "variable-fonts")]
759impl VarCoords {
760    #[inline]
761    fn as_slice(&self) -> &[NormalizedCoordinate] {
762        &self.data[0..usize::from(self.len)]
763    }
764
765    #[inline]
766    fn as_mut_slice(&mut self) -> &mut [NormalizedCoordinate] {
767        let end = usize::from(self.len);
768        &mut self.data[0..end]
769    }
770}
771
772/// A list of font face parsing errors.
773#[derive(Clone, Copy, PartialEq, Eq, Debug)]
774pub enum FaceParsingError {
775    /// An attempt to read out of bounds detected.
776    ///
777    /// Should occur only on malformed fonts.
778    MalformedFont,
779
780    /// Face data must start with `0x00010000`, `0x74727565`, `0x4F54544F` or `0x74746366`.
781    UnknownMagic,
782
783    /// The face index is larger than the number of faces in the font.
784    FaceIndexOutOfBounds,
785
786    /// The `head` table is missing or malformed.
787    NoHeadTable,
788
789    /// The `hhea` table is missing or malformed.
790    NoHheaTable,
791
792    /// The `maxp` table is missing or malformed.
793    NoMaxpTable,
794}
795
796impl core::fmt::Display for FaceParsingError {
797    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
798        match self {
799            FaceParsingError::MalformedFont => write!(f, "malformed font"),
800            FaceParsingError::UnknownMagic => write!(f, "unknown magic"),
801            FaceParsingError::FaceIndexOutOfBounds => write!(f, "face index is out of bounds"),
802            FaceParsingError::NoHeadTable => write!(f, "the head table is missing or malformed"),
803            FaceParsingError::NoHheaTable => write!(f, "the hhea table is missing or malformed"),
804            FaceParsingError::NoMaxpTable => write!(f, "the maxp table is missing or malformed"),
805        }
806    }
807}
808
809#[cfg(feature = "std")]
810impl std::error::Error for FaceParsingError {}
811
812/// A raw font face.
813///
814/// You are probably looking for [`Face`]. This is a low-level type.
815///
816/// Unlike [`Face`], [`RawFace`] parses only face table records.
817/// Meaning all you can get from this type is a raw (`&[u8]`) data of a requested table.
818/// Then you can either parse just a singe table from a font/face or populate [`RawFaceTables`]
819/// manually before passing it to [`Face::from_raw_tables`].
820#[derive(Clone, Copy)]
821pub struct RawFace<'a> {
822    /// The input font file data.
823    pub data: &'a [u8],
824    /// An array of table records.
825    pub table_records: LazyArray16<'a, TableRecord>,
826}
827
828impl<'a> RawFace<'a> {
829    /// Creates a new [`RawFace`] from a raw data.
830    ///
831    /// `index` indicates the specific font face in a font collection.
832    /// Use [`fonts_in_collection`] to get the total number of font faces.
833    /// Set to 0 if unsure.
834    ///
835    /// While we do reuse [`FaceParsingError`], `No*Table` errors will not be throws.
836    #[deprecated(since = "0.16.0", note = "use `parse` instead")]
837    pub fn from_slice(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
838        Self::parse(data, index)
839    }
840
841    /// Creates a new [`RawFace`] from a raw data.
842    ///
843    /// `index` indicates the specific font face in a font collection.
844    /// Use [`fonts_in_collection`] to get the total number of font faces.
845    /// Set to 0 if unsure.
846    ///
847    /// While we do reuse [`FaceParsingError`], `No*Table` errors will not be throws.
848    pub fn parse(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
849        // https://docs.microsoft.com/en-us/typography/opentype/spec/otff#organization-of-an-opentype-font
850
851        let mut s = Stream::new(data);
852
853        // Read **font** magic.
854        let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
855        if magic == Magic::FontCollection {
856            s.skip::<u32>(); // version
857            let number_of_faces = s.read::<u32>().ok_or(FaceParsingError::MalformedFont)?;
858            let offsets = s
859                .read_array32::<Offset32>(number_of_faces)
860                .ok_or(FaceParsingError::MalformedFont)?;
861
862            let face_offset = offsets.get(index).ok_or(FaceParsingError::FaceIndexOutOfBounds)?;
863            // Face offset is from the start of the font data,
864            // so we have to adjust it to the current parser offset.
865            let face_offset = face_offset
866                .to_usize()
867                .checked_sub(s.offset())
868                .ok_or(FaceParsingError::MalformedFont)?;
869            s.advance_checked(face_offset).ok_or(FaceParsingError::MalformedFont)?;
870
871            // Read **face** magic.
872            // Each face in a font collection also starts with a magic.
873            let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
874            // And face in a font collection can't be another collection.
875            if magic == Magic::FontCollection {
876                return Err(FaceParsingError::UnknownMagic);
877            }
878        } else {
879            // When reading from a regular font (not a collection) disallow index to be non-zero
880            // Basically treat the font as a one-element collection
881            if index != 0 {
882                return Err(FaceParsingError::FaceIndexOutOfBounds);
883            }
884        }
885
886        let num_tables = s.read::<u16>().ok_or(FaceParsingError::MalformedFont)?;
887        s.advance(6); // searchRange (u16) + entrySelector (u16) + rangeShift (u16)
888        let table_records = s
889            .read_array16::<TableRecord>(num_tables)
890            .ok_or(FaceParsingError::MalformedFont)?;
891
892        Ok(RawFace { data, table_records })
893    }
894
895    /// Returns the raw data of a selected table.
896    pub fn table(&self, tag: Tag) -> Option<&'a [u8]> {
897        let (_, table) = self.table_records.binary_search_by(|record| record.tag.cmp(&tag))?;
898        let offset = usize::num_from(table.offset);
899        let length = usize::num_from(table.length);
900        let end = offset.checked_add(length)?;
901        self.data.get(offset..end)
902    }
903}
904
905impl core::fmt::Debug for RawFace<'_> {
906    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
907        write!(f, "RawFace {{ ... }}")
908    }
909}
910
911/// A list of all supported tables as raw data.
912///
913/// This type should be used in tandem with
914/// [`Face::from_raw_tables()`](struct.Face.html#method.from_raw_tables).
915///
916/// This allows loading font faces not only from TrueType font files,
917/// but from any source. Mainly used for parsing WOFF.
918#[allow(missing_docs)]
919#[allow(missing_debug_implementations)]
920#[derive(Clone, Default)]
921pub struct RawFaceTables<'a> {
922    // Mandatory tables.
923    pub head: &'a [u8],
924    pub hhea: &'a [u8],
925    pub maxp: &'a [u8],
926
927    pub bdat: Option<&'a [u8]>,
928    pub bloc: Option<&'a [u8]>,
929    pub cbdt: Option<&'a [u8]>,
930    pub cblc: Option<&'a [u8]>,
931    pub cff: Option<&'a [u8]>,
932    pub cmap: Option<&'a [u8]>,
933    pub colr: Option<&'a [u8]>,
934    pub cpal: Option<&'a [u8]>,
935    pub ebdt: Option<&'a [u8]>,
936    pub eblc: Option<&'a [u8]>,
937    pub glyf: Option<&'a [u8]>,
938    pub hmtx: Option<&'a [u8]>,
939    pub kern: Option<&'a [u8]>,
940    pub loca: Option<&'a [u8]>,
941    pub name: Option<&'a [u8]>,
942    pub os2: Option<&'a [u8]>,
943    pub post: Option<&'a [u8]>,
944    pub sbix: Option<&'a [u8]>,
945    pub stat: Option<&'a [u8]>,
946    pub svg: Option<&'a [u8]>,
947    pub vhea: Option<&'a [u8]>,
948    pub vmtx: Option<&'a [u8]>,
949    pub vorg: Option<&'a [u8]>,
950
951    #[cfg(feature = "opentype-layout")]
952    pub gdef: Option<&'a [u8]>,
953    #[cfg(feature = "opentype-layout")]
954    pub gpos: Option<&'a [u8]>,
955    #[cfg(feature = "opentype-layout")]
956    pub gsub: Option<&'a [u8]>,
957    #[cfg(feature = "opentype-layout")]
958    pub math: Option<&'a [u8]>,
959
960    #[cfg(feature = "apple-layout")]
961    pub ankr: Option<&'a [u8]>,
962    #[cfg(feature = "apple-layout")]
963    pub feat: Option<&'a [u8]>,
964    #[cfg(feature = "apple-layout")]
965    pub kerx: Option<&'a [u8]>,
966    #[cfg(feature = "apple-layout")]
967    pub morx: Option<&'a [u8]>,
968    #[cfg(feature = "apple-layout")]
969    pub trak: Option<&'a [u8]>,
970
971    #[cfg(feature = "variable-fonts")]
972    pub avar: Option<&'a [u8]>,
973    #[cfg(feature = "variable-fonts")]
974    pub cff2: Option<&'a [u8]>,
975    #[cfg(feature = "variable-fonts")]
976    pub fvar: Option<&'a [u8]>,
977    #[cfg(feature = "variable-fonts")]
978    pub gvar: Option<&'a [u8]>,
979    #[cfg(feature = "variable-fonts")]
980    pub hvar: Option<&'a [u8]>,
981    #[cfg(feature = "variable-fonts")]
982    pub mvar: Option<&'a [u8]>,
983    #[cfg(feature = "variable-fonts")]
984    pub vvar: Option<&'a [u8]>,
985}
986
987/// Parsed face tables.
988///
989/// Unlike [`Face`], provides a low-level parsing abstraction over TrueType tables.
990/// Useful when you need a direct access to tables data.
991///
992/// Also, used when high-level API is problematic to implement.
993/// A good example would be OpenType layout tables (GPOS/GSUB).
994#[allow(missing_docs)]
995#[allow(missing_debug_implementations)]
996#[derive(Clone)]
997pub struct FaceTables<'a> {
998    // Mandatory tables.
999    pub head: head::Table,
1000    pub hhea: hhea::Table,
1001    pub maxp: maxp::Table,
1002
1003    pub bdat: Option<cbdt::Table<'a>>,
1004    pub cbdt: Option<cbdt::Table<'a>>,
1005    pub cff: Option<cff::Table<'a>>,
1006    pub cmap: Option<cmap::Table<'a>>,
1007    pub colr: Option<colr::Table<'a>>,
1008    pub ebdt: Option<cbdt::Table<'a>>,
1009    pub glyf: Option<glyf::Table<'a>>,
1010    pub hmtx: Option<hmtx::Table<'a>>,
1011    pub kern: Option<kern::Table<'a>>,
1012    pub name: Option<name::Table<'a>>,
1013    pub os2: Option<os2::Table<'a>>,
1014    pub post: Option<post::Table<'a>>,
1015    pub sbix: Option<sbix::Table<'a>>,
1016    pub stat: Option<stat::Table<'a>>,
1017    pub svg: Option<svg::Table<'a>>,
1018    pub vhea: Option<vhea::Table>,
1019    pub vmtx: Option<hmtx::Table<'a>>,
1020    pub vorg: Option<vorg::Table<'a>>,
1021
1022    #[cfg(feature = "opentype-layout")]
1023    pub gdef: Option<gdef::Table<'a>>,
1024    #[cfg(feature = "opentype-layout")]
1025    pub gpos: Option<opentype_layout::LayoutTable<'a>>,
1026    #[cfg(feature = "opentype-layout")]
1027    pub gsub: Option<opentype_layout::LayoutTable<'a>>,
1028    #[cfg(feature = "opentype-layout")]
1029    pub math: Option<math::Table<'a>>,
1030
1031    #[cfg(feature = "apple-layout")]
1032    pub ankr: Option<ankr::Table<'a>>,
1033    #[cfg(feature = "apple-layout")]
1034    pub feat: Option<feat::Table<'a>>,
1035    #[cfg(feature = "apple-layout")]
1036    pub kerx: Option<kerx::Table<'a>>,
1037    #[cfg(feature = "apple-layout")]
1038    pub morx: Option<morx::Table<'a>>,
1039    #[cfg(feature = "apple-layout")]
1040    pub trak: Option<trak::Table<'a>>,
1041
1042    #[cfg(feature = "variable-fonts")]
1043    pub avar: Option<avar::Table<'a>>,
1044    #[cfg(feature = "variable-fonts")]
1045    pub cff2: Option<cff2::Table<'a>>,
1046    #[cfg(feature = "variable-fonts")]
1047    pub fvar: Option<fvar::Table<'a>>,
1048    #[cfg(feature = "variable-fonts")]
1049    pub gvar: Option<gvar::Table<'a>>,
1050    #[cfg(feature = "variable-fonts")]
1051    pub hvar: Option<hvar::Table<'a>>,
1052    #[cfg(feature = "variable-fonts")]
1053    pub mvar: Option<mvar::Table<'a>>,
1054    #[cfg(feature = "variable-fonts")]
1055    pub vvar: Option<vvar::Table<'a>>,
1056}
1057
1058/// A font face.
1059///
1060/// Provides a high-level API for working with TrueType fonts.
1061/// If you're not familiar with how TrueType works internally, you should use this type.
1062/// If you do know and want a bit more low-level access - checkout [`FaceTables`].
1063///
1064/// Note that `Face` doesn't own the font data and doesn't allocate anything in heap.
1065/// Therefore you cannot "store" it. The idea is that you should parse the `Face`
1066/// when needed, get required data and forget about it.
1067/// That's why the initial parsing is highly optimized and should not become a bottleneck.
1068///
1069/// If you still want to store `Face` - checkout
1070/// [owned_ttf_parser](https://crates.io/crates/owned_ttf_parser). Requires `unsafe`.
1071///
1072/// While `Face` is technically copyable, we disallow it because it's almost 2KB big.
1073#[derive(Clone)]
1074pub struct Face<'a> {
1075    raw_face: RawFace<'a>,
1076    tables: FaceTables<'a>, // Parsed tables.
1077    #[cfg(feature = "variable-fonts")]
1078    coordinates: VarCoords,
1079}
1080
1081impl<'a> Face<'a> {
1082    /// Creates a new [`Face`] from a raw data.
1083    ///
1084    /// `index` indicates the specific font face in a font collection.
1085    /// Use [`fonts_in_collection`] to get the total number of font faces.
1086    /// Set to 0 if unsure.
1087    ///
1088    /// This method will do some parsing and sanitization,
1089    /// but in general can be considered free. No significant performance overhead.
1090    ///
1091    /// Required tables: `head`, `hhea` and `maxp`.
1092    ///
1093    /// If an optional table has invalid data it will be skipped.
1094    #[deprecated(since = "0.16.0", note = "use `parse` instead")]
1095    pub fn from_slice(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
1096        Self::parse(data, index)
1097    }
1098
1099    /// Creates a new [`Face`] from a raw data.
1100    ///
1101    /// `index` indicates the specific font face in a font collection.
1102    /// Use [`fonts_in_collection`] to get the total number of font faces.
1103    /// Set to 0 if unsure.
1104    ///
1105    /// This method will do some parsing and sanitization,
1106    /// but in general can be considered free. No significant performance overhead.
1107    ///
1108    /// Required tables: `head`, `hhea` and `maxp`.
1109    ///
1110    /// If an optional table has invalid data it will be skipped.
1111    pub fn parse(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
1112        let raw_face = RawFace::parse(data, index)?;
1113        let raw_tables = Self::collect_tables(raw_face);
1114
1115        #[allow(unused_mut)]
1116        let mut face = Face {
1117            raw_face,
1118            #[cfg(feature = "variable-fonts")]
1119            coordinates: VarCoords::default(),
1120            tables: Self::parse_tables(raw_tables)?,
1121        };
1122
1123        #[cfg(feature = "variable-fonts")]
1124        {
1125            if let Some(ref fvar) = face.tables.fvar {
1126                face.coordinates.len = fvar.axes.len().min(MAX_VAR_COORDS as u16) as u8;
1127            }
1128        }
1129
1130        Ok(face)
1131    }
1132
1133    fn collect_tables(raw_face: RawFace<'a>) -> RawFaceTables<'a> {
1134        let mut tables = RawFaceTables::default();
1135
1136        for record in raw_face.table_records {
1137            let start = usize::num_from(record.offset);
1138            let end = match start.checked_add(usize::num_from(record.length)) {
1139                Some(v) => v,
1140                None => continue,
1141            };
1142
1143            let table_data = raw_face.data.get(start..end);
1144            match &record.tag.to_bytes() {
1145                b"bdat" => tables.bdat = table_data,
1146                b"bloc" => tables.bloc = table_data,
1147                b"CBDT" => tables.cbdt = table_data,
1148                b"CBLC" => tables.cblc = table_data,
1149                b"CFF " => tables.cff = table_data,
1150                #[cfg(feature = "variable-fonts")]
1151                b"CFF2" => tables.cff2 = table_data,
1152                b"COLR" => tables.colr = table_data,
1153                b"CPAL" => tables.cpal = table_data,
1154                b"EBDT" => tables.ebdt = table_data,
1155                b"EBLC" => tables.eblc = table_data,
1156                #[cfg(feature = "opentype-layout")]
1157                b"GDEF" => tables.gdef = table_data,
1158                #[cfg(feature = "opentype-layout")]
1159                b"GPOS" => tables.gpos = table_data,
1160                #[cfg(feature = "opentype-layout")]
1161                b"GSUB" => tables.gsub = table_data,
1162                #[cfg(feature = "opentype-layout")]
1163                b"MATH" => tables.math = table_data,
1164                #[cfg(feature = "variable-fonts")]
1165                b"HVAR" => tables.hvar = table_data,
1166                #[cfg(feature = "variable-fonts")]
1167                b"MVAR" => tables.mvar = table_data,
1168                b"OS/2" => tables.os2 = table_data,
1169                b"SVG " => tables.svg = table_data,
1170                b"VORG" => tables.vorg = table_data,
1171                #[cfg(feature = "variable-fonts")]
1172                b"VVAR" => tables.vvar = table_data,
1173                #[cfg(feature = "apple-layout")]
1174                b"ankr" => tables.ankr = table_data,
1175                #[cfg(feature = "variable-fonts")]
1176                b"avar" => tables.avar = table_data,
1177                b"cmap" => tables.cmap = table_data,
1178                #[cfg(feature = "apple-layout")]
1179                b"feat" => tables.feat = table_data,
1180                #[cfg(feature = "variable-fonts")]
1181                b"fvar" => tables.fvar = table_data,
1182                b"glyf" => tables.glyf = table_data,
1183                #[cfg(feature = "variable-fonts")]
1184                b"gvar" => tables.gvar = table_data,
1185                b"head" => tables.head = table_data.unwrap_or_default(),
1186                b"hhea" => tables.hhea = table_data.unwrap_or_default(),
1187                b"hmtx" => tables.hmtx = table_data,
1188                b"kern" => tables.kern = table_data,
1189                #[cfg(feature = "apple-layout")]
1190                b"kerx" => tables.kerx = table_data,
1191                b"loca" => tables.loca = table_data,
1192                b"maxp" => tables.maxp = table_data.unwrap_or_default(),
1193                #[cfg(feature = "apple-layout")]
1194                b"morx" => tables.morx = table_data,
1195                b"name" => tables.name = table_data,
1196                b"post" => tables.post = table_data,
1197                b"sbix" => tables.sbix = table_data,
1198                b"STAT" => tables.stat = table_data,
1199                #[cfg(feature = "apple-layout")]
1200                b"trak" => tables.trak = table_data,
1201                b"vhea" => tables.vhea = table_data,
1202                b"vmtx" => tables.vmtx = table_data,
1203                _ => {}
1204            }
1205        }
1206
1207        tables
1208    }
1209
1210    /// Creates a new [`Face`] from provided [`RawFaceTables`].
1211    pub fn from_raw_tables(raw_tables: RawFaceTables<'a>) -> Result<Self, FaceParsingError> {
1212        #[allow(unused_mut)]
1213        let mut face = Face {
1214            raw_face: RawFace {
1215                data: &[],
1216                table_records: LazyArray16::default(),
1217            },
1218            #[cfg(feature = "variable-fonts")]
1219            coordinates: VarCoords::default(),
1220            tables: Self::parse_tables(raw_tables)?,
1221        };
1222
1223        #[cfg(feature = "variable-fonts")]
1224        {
1225            if let Some(ref fvar) = face.tables.fvar {
1226                face.coordinates.len = fvar.axes.len().min(MAX_VAR_COORDS as u16) as u8;
1227            }
1228        }
1229
1230        Ok(face)
1231    }
1232
1233    fn parse_tables(raw_tables: RawFaceTables<'a>) -> Result<FaceTables<'a>, FaceParsingError> {
1234        let head = head::Table::parse(raw_tables.head).ok_or(FaceParsingError::NoHeadTable)?;
1235        let hhea = hhea::Table::parse(raw_tables.hhea).ok_or(FaceParsingError::NoHheaTable)?;
1236        let maxp = maxp::Table::parse(raw_tables.maxp).ok_or(FaceParsingError::NoMaxpTable)?;
1237
1238        let hmtx = raw_tables
1239            .hmtx
1240            .and_then(|data| hmtx::Table::parse(hhea.number_of_metrics, maxp.number_of_glyphs, data));
1241
1242        let vhea = raw_tables.vhea.and_then(vhea::Table::parse);
1243        let vmtx = if let Some(vhea) = vhea {
1244            raw_tables
1245                .vmtx
1246                .and_then(|data| hmtx::Table::parse(vhea.number_of_metrics, maxp.number_of_glyphs, data))
1247        } else {
1248            None
1249        };
1250
1251        let loca = raw_tables
1252            .loca
1253            .and_then(|data| loca::Table::parse(maxp.number_of_glyphs, head.index_to_location_format, data));
1254        let glyf = if let Some(loca) = loca {
1255            raw_tables.glyf.and_then(|data| glyf::Table::parse(loca, data))
1256        } else {
1257            None
1258        };
1259
1260        let bdat = if let Some(bloc) = raw_tables.bloc.and_then(cblc::Table::parse) {
1261            raw_tables.bdat.and_then(|data| cbdt::Table::parse(bloc, data))
1262        } else {
1263            None
1264        };
1265
1266        let cbdt = if let Some(cblc) = raw_tables.cblc.and_then(cblc::Table::parse) {
1267            raw_tables.cbdt.and_then(|data| cbdt::Table::parse(cblc, data))
1268        } else {
1269            None
1270        };
1271
1272        let ebdt = if let Some(eblc) = raw_tables.eblc.and_then(cblc::Table::parse) {
1273            raw_tables.ebdt.and_then(|data| cbdt::Table::parse(eblc, data))
1274        } else {
1275            None
1276        };
1277
1278        let cpal = raw_tables.cpal.and_then(cpal::Table::parse);
1279        let colr = if let Some(cpal) = cpal {
1280            raw_tables.colr.and_then(|data| colr::Table::parse(cpal, data))
1281        } else {
1282            None
1283        };
1284
1285        Ok(FaceTables {
1286            head,
1287            hhea,
1288            maxp,
1289
1290            bdat,
1291            cbdt,
1292            cff: raw_tables.cff.and_then(cff::Table::parse),
1293            cmap: raw_tables.cmap.and_then(cmap::Table::parse),
1294            colr,
1295            ebdt,
1296            glyf,
1297            hmtx,
1298            kern: raw_tables.kern.and_then(kern::Table::parse),
1299            name: raw_tables.name.and_then(name::Table::parse),
1300            os2: raw_tables.os2.and_then(os2::Table::parse),
1301            post: raw_tables.post.and_then(post::Table::parse),
1302            sbix: raw_tables
1303                .sbix
1304                .and_then(|data| sbix::Table::parse(maxp.number_of_glyphs, data)),
1305            stat: raw_tables.stat.and_then(stat::Table::parse),
1306            svg: raw_tables.svg.and_then(svg::Table::parse),
1307            vhea: raw_tables.vhea.and_then(vhea::Table::parse),
1308            vmtx,
1309            vorg: raw_tables.vorg.and_then(vorg::Table::parse),
1310
1311            #[cfg(feature = "opentype-layout")]
1312            gdef: raw_tables.gdef.and_then(gdef::Table::parse),
1313            #[cfg(feature = "opentype-layout")]
1314            gpos: raw_tables.gpos.and_then(opentype_layout::LayoutTable::parse),
1315            #[cfg(feature = "opentype-layout")]
1316            gsub: raw_tables.gsub.and_then(opentype_layout::LayoutTable::parse),
1317            #[cfg(feature = "opentype-layout")]
1318            math: raw_tables.math.and_then(math::Table::parse),
1319
1320            #[cfg(feature = "apple-layout")]
1321            ankr: raw_tables
1322                .ankr
1323                .and_then(|data| ankr::Table::parse(maxp.number_of_glyphs, data)),
1324            #[cfg(feature = "apple-layout")]
1325            feat: raw_tables.feat.and_then(feat::Table::parse),
1326            #[cfg(feature = "apple-layout")]
1327            kerx: raw_tables
1328                .kerx
1329                .and_then(|data| kerx::Table::parse(maxp.number_of_glyphs, data)),
1330            #[cfg(feature = "apple-layout")]
1331            morx: raw_tables
1332                .morx
1333                .and_then(|data| morx::Table::parse(maxp.number_of_glyphs, data)),
1334            #[cfg(feature = "apple-layout")]
1335            trak: raw_tables.trak.and_then(trak::Table::parse),
1336
1337            #[cfg(feature = "variable-fonts")]
1338            avar: raw_tables.avar.and_then(avar::Table::parse),
1339            #[cfg(feature = "variable-fonts")]
1340            cff2: raw_tables.cff2.and_then(cff2::Table::parse),
1341            #[cfg(feature = "variable-fonts")]
1342            fvar: raw_tables.fvar.and_then(fvar::Table::parse),
1343            #[cfg(feature = "variable-fonts")]
1344            gvar: raw_tables.gvar.and_then(gvar::Table::parse),
1345            #[cfg(feature = "variable-fonts")]
1346            hvar: raw_tables.hvar.and_then(hvar::Table::parse),
1347            #[cfg(feature = "variable-fonts")]
1348            mvar: raw_tables.mvar.and_then(mvar::Table::parse),
1349            #[cfg(feature = "variable-fonts")]
1350            vvar: raw_tables.vvar.and_then(vvar::Table::parse),
1351        })
1352    }
1353
1354    /// Returns low-level face tables.
1355    #[inline]
1356    pub fn tables(&self) -> &FaceTables<'a> {
1357        &self.tables
1358    }
1359
1360    /// Returns the `RawFace` used to create this `Face`.
1361    ///
1362    /// Useful if you want to parse the data manually.
1363    ///
1364    /// Available only for faces created using [`Face::parse()`](struct.Face.html#method.parse).
1365    #[inline]
1366    pub fn raw_face(&self) -> &RawFace<'a> {
1367        &self.raw_face
1368    }
1369
1370    /// Returns the raw data of a selected table.
1371    ///
1372    /// Useful if you want to parse the data manually.
1373    ///
1374    /// Available only for faces created using [`Face::parse()`](struct.Face.html#method.parse).
1375    #[deprecated(since = "0.16.0", note = "use `self.raw_face().table()` instead")]
1376    #[inline]
1377    pub fn table_data(&self, tag: Tag) -> Option<&'a [u8]> {
1378        self.raw_face.table(tag)
1379    }
1380
1381    /// Returns a list of names.
1382    ///
1383    /// Contains face name and other strings.
1384    #[inline]
1385    pub fn names(&self) -> name::Names<'a> {
1386        self.tables.name.unwrap_or_default().names
1387    }
1388
1389    /// Checks that face is marked as *Regular*.
1390    ///
1391    /// Returns `false` when OS/2 table is not present.
1392    #[inline]
1393    pub fn is_regular(&self) -> bool {
1394        self.style() == Style::Normal
1395    }
1396
1397    /// Checks that face is marked as *Italic*.
1398    #[inline]
1399    pub fn is_italic(&self) -> bool {
1400        // A face can have a Normal style and a non-zero italic angle, which also makes it italic.
1401        self.style() == Style::Italic || self.italic_angle() != 0.0
1402    }
1403
1404    /// Checks that face is marked as *Bold*.
1405    ///
1406    /// Returns `false` when OS/2 table is not present.
1407    #[inline]
1408    pub fn is_bold(&self) -> bool {
1409        self.tables.os2.map(|os2| os2.is_bold()).unwrap_or(false)
1410    }
1411
1412    /// Checks that face is marked as *Oblique*.
1413    ///
1414    /// Returns `false` when OS/2 table is not present or when its version is < 4.
1415    #[inline]
1416    pub fn is_oblique(&self) -> bool {
1417        self.style() == Style::Oblique
1418    }
1419
1420    /// Returns face style.
1421    ///
1422    /// Returns `Style::Normal` when OS/2 table is not present.
1423    #[inline]
1424    pub fn style(&self) -> Style {
1425        self.tables.os2.map(|os2| os2.style()).unwrap_or_default()
1426    }
1427
1428    /// Checks that face is marked as *Monospaced*.
1429    ///
1430    /// Returns `false` when `post` table is not present.
1431    #[inline]
1432    pub fn is_monospaced(&self) -> bool {
1433        self.tables.post.map(|post| post.is_monospaced).unwrap_or(false)
1434    }
1435
1436    /// Checks that face is variable.
1437    ///
1438    /// Simply checks the presence of a `fvar` table.
1439    #[inline]
1440    pub fn is_variable(&self) -> bool {
1441        #[cfg(feature = "variable-fonts")]
1442        {
1443            // `fvar::Table::parse` already checked that `axisCount` is non-zero.
1444            self.tables.fvar.is_some()
1445        }
1446
1447        #[cfg(not(feature = "variable-fonts"))]
1448        {
1449            false
1450        }
1451    }
1452
1453    /// Returns face's weight.
1454    ///
1455    /// Returns `Weight::Normal` when OS/2 table is not present.
1456    #[inline]
1457    pub fn weight(&self) -> Weight {
1458        self.tables.os2.map(|os2| os2.weight()).unwrap_or_default()
1459    }
1460
1461    /// Returns face's width.
1462    ///
1463    /// Returns `Width::Normal` when OS/2 table is not present or when value is invalid.
1464    #[inline]
1465    pub fn width(&self) -> Width {
1466        self.tables.os2.map(|os2| os2.width()).unwrap_or_default()
1467    }
1468
1469    /// Returns face's italic angle.
1470    ///
1471    /// Returns `0.0` when `post` table is not present.
1472    #[inline]
1473    pub fn italic_angle(&self) -> f32 {
1474        self.tables.post.map(|table| table.italic_angle).unwrap_or(0.0)
1475    }
1476
1477    // Read https://github.com/freetype/freetype/blob/49270c17011491227ec7bd3fb73ede4f674aa065/src/sfnt/sfobjs.c#L1279
1478    // to learn more about the logic behind the following functions.
1479
1480    /// Returns a horizontal face ascender.
1481    ///
1482    /// This method is affected by variation axes.
1483    #[inline]
1484    pub fn ascender(&self) -> i16 {
1485        if let Some(os_2) = self.tables.os2
1486            && os_2.use_typographic_metrics()
1487        {
1488            let value = os_2.typographic_ascender();
1489            return self.apply_metrics_variation(Tag::from_bytes(b"hasc"), value);
1490        }
1491
1492        let mut value = self.tables.hhea.ascender;
1493        if value == 0
1494            && let Some(os_2) = self.tables.os2
1495        {
1496            value = os_2.typographic_ascender();
1497            if value == 0 {
1498                value = os_2.windows_ascender();
1499                value = self.apply_metrics_variation(Tag::from_bytes(b"hcla"), value);
1500            } else {
1501                value = self.apply_metrics_variation(Tag::from_bytes(b"hasc"), value);
1502            }
1503        }
1504
1505        value
1506    }
1507
1508    /// Returns a horizontal face descender.
1509    ///
1510    /// This method is affected by variation axes.
1511    #[inline]
1512    pub fn descender(&self) -> i16 {
1513        if let Some(os_2) = self.tables.os2
1514            && os_2.use_typographic_metrics()
1515        {
1516            let value = os_2.typographic_descender();
1517            return self.apply_metrics_variation(Tag::from_bytes(b"hdsc"), value);
1518        }
1519
1520        let mut value = self.tables.hhea.descender;
1521        if value == 0
1522            && let Some(os_2) = self.tables.os2
1523        {
1524            value = os_2.typographic_descender();
1525            if value == 0 {
1526                value = os_2.windows_descender();
1527                value = self.apply_metrics_variation(Tag::from_bytes(b"hcld"), value);
1528            } else {
1529                value = self.apply_metrics_variation(Tag::from_bytes(b"hdsc"), value);
1530            }
1531        }
1532
1533        value
1534    }
1535
1536    /// Returns face's height.
1537    ///
1538    /// This method is affected by variation axes.
1539    #[inline]
1540    pub fn height(&self) -> i16 {
1541        self.ascender() - self.descender()
1542    }
1543
1544    /// Returns a horizontal face line gap.
1545    ///
1546    /// This method is affected by variation axes.
1547    #[inline]
1548    pub fn line_gap(&self) -> i16 {
1549        if let Some(os_2) = self.tables.os2
1550            && os_2.use_typographic_metrics()
1551        {
1552            let value = os_2.typographic_line_gap();
1553            return self.apply_metrics_variation(Tag::from_bytes(b"hlgp"), value);
1554        }
1555
1556        let mut value = self.tables.hhea.line_gap;
1557        // For line gap, we have to check that ascender or descender are 0, not line gap itself.
1558        if (self.tables.hhea.ascender == 0 || self.tables.hhea.descender == 0)
1559            && let Some(os_2) = self.tables.os2
1560        {
1561            if os_2.typographic_ascender() != 0 || os_2.typographic_descender() != 0 {
1562                value = os_2.typographic_line_gap();
1563                value = self.apply_metrics_variation(Tag::from_bytes(b"hlgp"), value);
1564            } else {
1565                value = 0;
1566            }
1567        }
1568
1569        value
1570    }
1571
1572    /// Returns a horizontal typographic face ascender.
1573    ///
1574    /// Prefer `Face::ascender` unless you explicitly want this. This is a more
1575    /// low-level alternative.
1576    ///
1577    /// This method is affected by variation axes.
1578    ///
1579    /// Returns `None` when OS/2 table is not present.
1580    #[inline]
1581    pub fn typographic_ascender(&self) -> Option<i16> {
1582        self.tables.os2.map(|table| {
1583            let v = table.typographic_ascender();
1584            self.apply_metrics_variation(Tag::from_bytes(b"hasc"), v)
1585        })
1586    }
1587
1588    /// Returns a horizontal typographic face descender.
1589    ///
1590    /// Prefer `Face::descender` unless you explicitly want this. This is a more
1591    /// low-level alternative.
1592    ///
1593    /// This method is affected by variation axes.
1594    ///
1595    /// Returns `None` when OS/2 table is not present.
1596    #[inline]
1597    pub fn typographic_descender(&self) -> Option<i16> {
1598        self.tables.os2.map(|table| {
1599            let v = table.typographic_descender();
1600            self.apply_metrics_variation(Tag::from_bytes(b"hdsc"), v)
1601        })
1602    }
1603
1604    /// Returns a horizontal typographic face line gap.
1605    ///
1606    /// Prefer `Face::line_gap` unless you explicitly want this. This is a more
1607    /// low-level alternative.
1608    ///
1609    /// This method is affected by variation axes.
1610    ///
1611    /// Returns `None` when OS/2 table is not present.
1612    #[inline]
1613    pub fn typographic_line_gap(&self) -> Option<i16> {
1614        self.tables.os2.map(|table| {
1615            let v = table.typographic_line_gap();
1616            self.apply_metrics_variation(Tag::from_bytes(b"hlgp"), v)
1617        })
1618    }
1619
1620    /// Returns a vertical face ascender.
1621    ///
1622    /// This method is affected by variation axes.
1623    #[inline]
1624    pub fn vertical_ascender(&self) -> Option<i16> {
1625        self.tables
1626            .vhea
1627            .map(|vhea| vhea.ascender)
1628            .map(|v| self.apply_metrics_variation(Tag::from_bytes(b"vasc"), v))
1629    }
1630
1631    /// Returns a vertical face descender.
1632    ///
1633    /// This method is affected by variation axes.
1634    #[inline]
1635    pub fn vertical_descender(&self) -> Option<i16> {
1636        self.tables
1637            .vhea
1638            .map(|vhea| vhea.descender)
1639            .map(|v| self.apply_metrics_variation(Tag::from_bytes(b"vdsc"), v))
1640    }
1641
1642    /// Returns a vertical face height.
1643    ///
1644    /// This method is affected by variation axes.
1645    #[inline]
1646    pub fn vertical_height(&self) -> Option<i16> {
1647        Some(self.vertical_ascender()? - self.vertical_descender()?)
1648    }
1649
1650    /// Returns a vertical face line gap.
1651    ///
1652    /// This method is affected by variation axes.
1653    #[inline]
1654    pub fn vertical_line_gap(&self) -> Option<i16> {
1655        self.tables
1656            .vhea
1657            .map(|vhea| vhea.line_gap)
1658            .map(|v| self.apply_metrics_variation(Tag::from_bytes(b"vlgp"), v))
1659    }
1660
1661    /// Returns face's units per EM.
1662    ///
1663    /// Guarantee to be in a 16..=16384 range.
1664    #[inline]
1665    pub fn units_per_em(&self) -> u16 {
1666        self.tables.head.units_per_em
1667    }
1668
1669    /// Returns face's x height.
1670    ///
1671    /// This method is affected by variation axes.
1672    ///
1673    /// Returns `None` when OS/2 table is not present or when its version is < 2.
1674    #[inline]
1675    pub fn x_height(&self) -> Option<i16> {
1676        self.tables
1677            .os2
1678            .and_then(|os_2| os_2.x_height())
1679            .map(|v| self.apply_metrics_variation(Tag::from_bytes(b"xhgt"), v))
1680    }
1681
1682    /// Returns face's capital height.
1683    ///
1684    /// This method is affected by variation axes.
1685    ///
1686    /// Returns `None` when OS/2 table is not present or when its version is < 2.
1687    #[inline]
1688    pub fn capital_height(&self) -> Option<i16> {
1689        self.tables
1690            .os2
1691            .and_then(|os_2| os_2.capital_height())
1692            .map(|v| self.apply_metrics_variation(Tag::from_bytes(b"cpht"), v))
1693    }
1694
1695    /// Returns face's underline metrics.
1696    ///
1697    /// This method is affected by variation axes.
1698    ///
1699    /// Returns `None` when `post` table is not present.
1700    #[inline]
1701    pub fn underline_metrics(&self) -> Option<LineMetrics> {
1702        let mut metrics = self.tables.post?.underline_metrics;
1703
1704        if self.is_variable() {
1705            self.apply_metrics_variation_to(Tag::from_bytes(b"undo"), &mut metrics.position);
1706            self.apply_metrics_variation_to(Tag::from_bytes(b"unds"), &mut metrics.thickness);
1707        }
1708
1709        Some(metrics)
1710    }
1711
1712    /// Returns face's strikeout metrics.
1713    ///
1714    /// This method is affected by variation axes.
1715    ///
1716    /// Returns `None` when OS/2 table is not present.
1717    #[inline]
1718    pub fn strikeout_metrics(&self) -> Option<LineMetrics> {
1719        let mut metrics = self.tables.os2?.strikeout_metrics();
1720
1721        if self.is_variable() {
1722            self.apply_metrics_variation_to(Tag::from_bytes(b"stro"), &mut metrics.position);
1723            self.apply_metrics_variation_to(Tag::from_bytes(b"strs"), &mut metrics.thickness);
1724        }
1725
1726        Some(metrics)
1727    }
1728
1729    /// Returns face's subscript metrics.
1730    ///
1731    /// This method is affected by variation axes.
1732    ///
1733    /// Returns `None` when OS/2 table is not present.
1734    #[inline]
1735    pub fn subscript_metrics(&self) -> Option<ScriptMetrics> {
1736        let mut metrics = self.tables.os2?.subscript_metrics();
1737
1738        if self.is_variable() {
1739            self.apply_metrics_variation_to(Tag::from_bytes(b"sbxs"), &mut metrics.x_size);
1740            self.apply_metrics_variation_to(Tag::from_bytes(b"sbys"), &mut metrics.y_size);
1741            self.apply_metrics_variation_to(Tag::from_bytes(b"sbxo"), &mut metrics.x_offset);
1742            self.apply_metrics_variation_to(Tag::from_bytes(b"sbyo"), &mut metrics.y_offset);
1743        }
1744
1745        Some(metrics)
1746    }
1747
1748    /// Returns face's superscript metrics.
1749    ///
1750    /// This method is affected by variation axes.
1751    ///
1752    /// Returns `None` when OS/2 table is not present.
1753    #[inline]
1754    pub fn superscript_metrics(&self) -> Option<ScriptMetrics> {
1755        let mut metrics = self.tables.os2?.superscript_metrics();
1756
1757        if self.is_variable() {
1758            self.apply_metrics_variation_to(Tag::from_bytes(b"spxs"), &mut metrics.x_size);
1759            self.apply_metrics_variation_to(Tag::from_bytes(b"spys"), &mut metrics.y_size);
1760            self.apply_metrics_variation_to(Tag::from_bytes(b"spxo"), &mut metrics.x_offset);
1761            self.apply_metrics_variation_to(Tag::from_bytes(b"spyo"), &mut metrics.y_offset);
1762        }
1763
1764        Some(metrics)
1765    }
1766
1767    /// Returns face permissions.
1768    ///
1769    /// Returns `None` in case of a malformed value.
1770    #[inline]
1771    pub fn permissions(&self) -> Option<Permissions> {
1772        self.tables.os2?.permissions()
1773    }
1774
1775    /// Checks if the face allows embedding a subset, further restricted by [`Self::permissions`].
1776    #[inline]
1777    pub fn is_subsetting_allowed(&self) -> bool {
1778        self.tables.os2.map(|t| t.is_subsetting_allowed()).unwrap_or(false)
1779    }
1780
1781    /// Checks if the face allows outline data to be embedded.
1782    ///
1783    /// If false, only bitmaps may be embedded in accordance with [`Self::permissions`].
1784    ///
1785    /// If the font contains no bitmaps and this flag is not set, it implies no embedding is allowed.
1786    #[inline]
1787    pub fn is_outline_embedding_allowed(&self) -> bool {
1788        self.tables
1789            .os2
1790            .map(|t| t.is_outline_embedding_allowed())
1791            .unwrap_or(false)
1792    }
1793
1794    /// Returns [Unicode Ranges](https://docs.microsoft.com/en-us/typography/opentype/spec/os2#ur).
1795    #[inline]
1796    pub fn unicode_ranges(&self) -> UnicodeRanges {
1797        self.tables.os2.map(|t| t.unicode_ranges()).unwrap_or_default()
1798    }
1799
1800    /// Returns a total number of glyphs in the face.
1801    ///
1802    /// Never zero.
1803    ///
1804    /// The value was already parsed, so this function doesn't involve any parsing.
1805    #[inline]
1806    pub fn number_of_glyphs(&self) -> u16 {
1807        self.tables.maxp.number_of_glyphs.get()
1808    }
1809
1810    /// Resolves a Glyph ID for a code point.
1811    ///
1812    /// Returns `None` instead of `0` when glyph is not found.
1813    ///
1814    /// All subtable formats except Mixed Coverage (8) are supported.
1815    ///
1816    /// If you need a more low-level control, prefer `Face::tables().cmap`.
1817    #[inline]
1818    pub fn glyph_index(&self, code_point: char) -> Option<GlyphId> {
1819        for subtable in self.tables.cmap?.subtables {
1820            if !subtable.is_unicode() {
1821                continue;
1822            }
1823
1824            if let Some(id) = subtable.glyph_index(u32::from(code_point)) {
1825                return Some(id);
1826            }
1827        }
1828
1829        None
1830    }
1831
1832    /// Resolves a Glyph ID for a glyph name.
1833    ///
1834    /// Uses the `post` and `CFF` tables as sources.
1835    ///
1836    /// Returns `None` when no name is associated with a `glyph`.
1837    #[cfg(feature = "glyph-names")]
1838    #[inline]
1839    pub fn glyph_index_by_name(&self, name: &str) -> Option<GlyphId> {
1840        if let Some(name) = self.tables.post.and_then(|post| post.glyph_index_by_name(name)) {
1841            return Some(name);
1842        }
1843
1844        if let Some(name) = self.tables.cff.as_ref().and_then(|cff| cff.glyph_index_by_name(name)) {
1845            return Some(name);
1846        }
1847
1848        None
1849    }
1850
1851    /// Resolves a variation of a Glyph ID from two code points.
1852    ///
1853    /// Implemented according to
1854    /// [Unicode Variation Sequences](
1855    /// https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-14-unicode-variation-sequences).
1856    ///
1857    /// Returns `None` instead of `0` when glyph is not found.
1858    #[inline]
1859    pub fn glyph_variation_index(&self, code_point: char, variation: char) -> Option<GlyphId> {
1860        for subtable in self.tables.cmap?.subtables {
1861            if let cmap::Format::UnicodeVariationSequences(ref table) = subtable.format {
1862                return match table.glyph_index(u32::from(code_point), u32::from(variation))? {
1863                    cmap::GlyphVariationResult::Found(v) => Some(v),
1864                    cmap::GlyphVariationResult::UseDefault => self.glyph_index(code_point),
1865                };
1866            }
1867        }
1868
1869        None
1870    }
1871
1872    /// Returns glyph's horizontal advance.
1873    ///
1874    /// This method is affected by variation axes.
1875    #[inline]
1876    pub fn glyph_hor_advance(&self, glyph_id: GlyphId) -> Option<u16> {
1877        #[cfg(feature = "variable-fonts")]
1878        {
1879            let mut advance = self.tables.hmtx?.advance(glyph_id)? as f32;
1880
1881            if self.is_variable() {
1882                // Ignore variation offset when `hvar` is not set.
1883                if let Some(hvar) = self.tables.hvar {
1884                    if let Some(offset) = hvar.advance_offset(glyph_id, self.coords()) {
1885                        // We can't use `round()` in `no_std`, so this is the next best thing.
1886                        advance += offset + 0.5;
1887                    }
1888                } else if let Some(points) = self.glyph_phantom_points(glyph_id) {
1889                    // We can't use `round()` in `no_std`, so this is the next best thing.
1890                    advance += points.right.x + 0.5
1891                }
1892            }
1893
1894            u16::try_num_from(advance)
1895        }
1896
1897        #[cfg(not(feature = "variable-fonts"))]
1898        {
1899            self.tables.hmtx?.advance(glyph_id)
1900        }
1901    }
1902
1903    /// Returns glyph's vertical advance.
1904    ///
1905    /// This method is affected by variation axes.
1906    #[inline]
1907    pub fn glyph_ver_advance(&self, glyph_id: GlyphId) -> Option<u16> {
1908        #[cfg(feature = "variable-fonts")]
1909        {
1910            let mut advance = self.tables.vmtx?.advance(glyph_id)? as f32;
1911
1912            if self.is_variable() {
1913                // Ignore variation offset when `vvar` is not set.
1914                if let Some(vvar) = self.tables.vvar {
1915                    if let Some(offset) = vvar.advance_offset(glyph_id, self.coords()) {
1916                        // We can't use `round()` in `no_std`, so this is the next best thing.
1917                        advance += offset + 0.5;
1918                    }
1919                } else if let Some(points) = self.glyph_phantom_points(glyph_id) {
1920                    // We can't use `round()` in `no_std`, so this is the next best thing.
1921                    advance += points.bottom.y + 0.5
1922                }
1923            }
1924
1925            u16::try_num_from(advance)
1926        }
1927
1928        #[cfg(not(feature = "variable-fonts"))]
1929        {
1930            self.tables.vmtx?.advance(glyph_id)
1931        }
1932    }
1933
1934    /// Returns glyph's horizontal side bearing.
1935    ///
1936    /// This method is affected by variation axes.
1937    #[inline]
1938    pub fn glyph_hor_side_bearing(&self, glyph_id: GlyphId) -> Option<i16> {
1939        #[cfg(feature = "variable-fonts")]
1940        {
1941            let mut bearing = self.tables.hmtx?.side_bearing(glyph_id)? as f32;
1942
1943            if self.is_variable() {
1944                // Ignore variation offset when `hvar` is not set.
1945                if let Some(hvar) = self.tables.hvar
1946                    && let Some(offset) = hvar.left_side_bearing_offset(glyph_id, self.coords())
1947                {
1948                    // We can't use `round()` in `no_std`, so this is the next best thing.
1949                    bearing += offset + 0.5;
1950                }
1951            }
1952
1953            i16::try_num_from(bearing)
1954        }
1955
1956        #[cfg(not(feature = "variable-fonts"))]
1957        {
1958            self.tables.hmtx?.side_bearing(glyph_id)
1959        }
1960    }
1961
1962    /// Returns glyph's vertical side bearing.
1963    ///
1964    /// This method is affected by variation axes.
1965    #[inline]
1966    pub fn glyph_ver_side_bearing(&self, glyph_id: GlyphId) -> Option<i16> {
1967        #[cfg(feature = "variable-fonts")]
1968        {
1969            let mut bearing = self.tables.vmtx?.side_bearing(glyph_id)? as f32;
1970
1971            if self.is_variable() {
1972                // Ignore variation offset when `vvar` is not set.
1973                if let Some(vvar) = self.tables.vvar
1974                    && let Some(offset) = vvar.top_side_bearing_offset(glyph_id, self.coords())
1975                {
1976                    // We can't use `round()` in `no_std`, so this is the next best thing.
1977                    bearing += offset + 0.5;
1978                }
1979            }
1980
1981            i16::try_num_from(bearing)
1982        }
1983
1984        #[cfg(not(feature = "variable-fonts"))]
1985        {
1986            self.tables.vmtx?.side_bearing(glyph_id)
1987        }
1988    }
1989
1990    /// Returns glyph's vertical origin according to
1991    /// [Vertical Origin Table](https://docs.microsoft.com/en-us/typography/opentype/spec/vorg).
1992    ///
1993    /// This method is affected by variation axes.
1994    pub fn glyph_y_origin(&self, glyph_id: GlyphId) -> Option<i16> {
1995        #[cfg(feature = "variable-fonts")]
1996        {
1997            let mut origin = self.tables.vorg.map(|vorg| vorg.glyph_y_origin(glyph_id))? as f32;
1998
1999            if self.is_variable() {
2000                // Ignore variation offset when `vvar` is not set.
2001                if let Some(vvar) = self.tables.vvar
2002                    && let Some(offset) = vvar.vertical_origin_offset(glyph_id, self.coords())
2003                {
2004                    // We can't use `round()` in `no_std`, so this is the next best thing.
2005                    origin += offset + 0.5;
2006                }
2007            }
2008
2009            i16::try_num_from(origin)
2010        }
2011
2012        #[cfg(not(feature = "variable-fonts"))]
2013        {
2014            self.tables.vorg.map(|vorg| vorg.glyph_y_origin(glyph_id))
2015        }
2016    }
2017
2018    /// Returns glyph's name.
2019    ///
2020    /// Uses the `post` and `CFF` tables as sources.
2021    ///
2022    /// Returns `None` when no name is associated with a `glyph`.
2023    #[cfg(feature = "glyph-names")]
2024    #[inline]
2025    pub fn glyph_name(&self, glyph_id: GlyphId) -> Option<&str> {
2026        if let Some(name) = self.tables.post.and_then(|post| post.glyph_name(glyph_id)) {
2027            return Some(name);
2028        }
2029
2030        if let Some(name) = self.tables.cff.as_ref().and_then(|cff1| cff1.glyph_name(glyph_id)) {
2031            return Some(name);
2032        }
2033
2034        None
2035    }
2036
2037    /// Outlines a glyph and returns its tight bounding box.
2038    ///
2039    /// **Warning**: since `ttf-parser` is a pull parser,
2040    /// `OutlineBuilder` will emit segments even when outline is partially malformed.
2041    /// You must check `outline_glyph()` result before using
2042    /// `OutlineBuilder`'s output.
2043    ///
2044    /// `gvar`, `glyf`, `CFF` and `CFF2` tables are supported.
2045    /// And they will be accesses in this specific order.
2046    ///
2047    /// This method is affected by variation axes.
2048    ///
2049    /// Returns `None` when glyph has no outline or on error.
2050    ///
2051    /// # Example
2052    ///
2053    /// ```
2054    /// use std::fmt::Write;
2055    /// use ttf_parser;
2056    ///
2057    /// struct Builder(String);
2058    ///
2059    /// impl ttf_parser::OutlineBuilder for Builder {
2060    ///     fn move_to(&mut self, x: f32, y: f32) {
2061    ///         write!(&mut self.0, "M {} {} ", x, y).unwrap();
2062    ///     }
2063    ///
2064    ///     fn line_to(&mut self, x: f32, y: f32) {
2065    ///         write!(&mut self.0, "L {} {} ", x, y).unwrap();
2066    ///     }
2067    ///
2068    ///     fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32) {
2069    ///         write!(&mut self.0, "Q {} {} {} {} ", x1, y1, x, y).unwrap();
2070    ///     }
2071    ///
2072    ///     fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32) {
2073    ///         write!(&mut self.0, "C {} {} {} {} {} {} ", x1, y1, x2, y2, x, y).unwrap();
2074    ///     }
2075    ///
2076    ///     fn close(&mut self) {
2077    ///         write!(&mut self.0, "Z ").unwrap();
2078    ///     }
2079    /// }
2080    ///
2081    /// let data = std::fs::read("tests/fonts/demo.ttf").unwrap();
2082    /// let face = ttf_parser::Face::parse(&data, 0).unwrap();
2083    /// let mut builder = Builder(String::new());
2084    /// let bbox = face.outline_glyph(ttf_parser::GlyphId(1), &mut builder).unwrap();
2085    /// assert_eq!(builder.0, "M 173 267 L 369 267 L 270 587 L 173 267 Z M 6 0 L 224 656 \
2086    ///                        L 320 656 L 541 0 L 452 0 L 390 200 L 151 200 L 85 0 L 6 0 Z ");
2087    /// assert_eq!(bbox, ttf_parser::Rect { x_min: 6, y_min: 0, x_max: 541, y_max: 656 });
2088    /// ```
2089    #[inline]
2090    pub fn outline_glyph(&self, glyph_id: GlyphId, builder: &mut dyn OutlineBuilder) -> Option<Rect> {
2091        #[cfg(feature = "variable-fonts")]
2092        {
2093            if let Some(ref gvar) = self.tables.gvar {
2094                return gvar.outline(self.tables.glyf?, self.coords(), glyph_id, builder);
2095            }
2096        }
2097
2098        if let Some(table) = self.tables.glyf {
2099            return table.outline(glyph_id, builder);
2100        }
2101
2102        if let Some(ref cff) = self.tables.cff {
2103            return cff.outline(glyph_id, builder).ok();
2104        }
2105
2106        #[cfg(feature = "variable-fonts")]
2107        {
2108            if let Some(ref cff2) = self.tables.cff2 {
2109                return cff2.outline(self.coords(), glyph_id, builder).ok();
2110            }
2111        }
2112
2113        None
2114    }
2115
2116    /// Returns a tight glyph bounding box.
2117    ///
2118    /// This is just a shorthand for `outline_glyph()` since only the `glyf` table stores
2119    /// a bounding box. We ignore `glyf` table bboxes because they can be malformed.
2120    /// In case of CFF and variable fonts we have to actually outline
2121    /// a glyph to find it's bounding box.
2122    ///
2123    /// When a glyph is defined by a raster or a vector image,
2124    /// that can be obtained via `glyph_image()`,
2125    /// the bounding box must be calculated manually and this method will return `None`.
2126    ///
2127    /// Note: the returned bbox is not validated in any way. A font file can have a glyph bbox
2128    /// set to zero/negative width and/or height and this is perfectly ok.
2129    /// For calculated bboxes, zero width and/or height is also perfectly fine.
2130    ///
2131    /// This method is affected by variation axes.
2132    #[inline]
2133    pub fn glyph_bounding_box(&self, glyph_id: GlyphId) -> Option<Rect> {
2134        self.outline_glyph(glyph_id, &mut DummyOutline)
2135    }
2136
2137    /// Returns a bounding box that large enough to enclose any glyph from the face.
2138    #[inline]
2139    pub fn global_bounding_box(&self) -> Rect {
2140        self.tables.head.global_bbox
2141    }
2142
2143    /// Returns a reference to a glyph's raster image.
2144    ///
2145    /// A font can define a glyph using a raster or a vector image instead of a simple outline.
2146    /// Which is primarily used for emojis. This method should be used to access raster images.
2147    ///
2148    /// `pixels_per_em` allows selecting a preferred image size. The chosen size will
2149    /// be closer to an upper one. So when font has 64px and 96px images and `pixels_per_em`
2150    /// is set to 72, 96px image will be returned.
2151    /// To get the largest image simply use `std::u16::MAX`.
2152    ///
2153    /// Note that this method will return an encoded image. It should be decoded
2154    /// by the caller. We don't validate or preprocess it in any way.
2155    ///
2156    /// Also, a font can contain both: images and outlines. So when this method returns `None`
2157    /// you should also try `outline_glyph()` afterwards.
2158    ///
2159    /// There are multiple ways an image can be stored in a TrueType font
2160    /// and this method supports most of them.
2161    /// This includes `sbix`, `bloc` + `bdat`, `EBLC` + `EBDT`, `CBLC` + `CBDT`.
2162    /// And font's tables will be accesses in this specific order.
2163    #[inline]
2164    pub fn glyph_raster_image(&self, glyph_id: GlyphId, pixels_per_em: u16) -> Option<RasterGlyphImage> {
2165        if let Some(table) = self.tables.sbix
2166            && let Some(strike) = table.best_strike(pixels_per_em)
2167        {
2168            return strike.get(glyph_id);
2169        }
2170        if let Some(bdat) = self.tables.bdat {
2171            return bdat.get(glyph_id, pixels_per_em);
2172        }
2173
2174        if let Some(ebdt) = self.tables.ebdt {
2175            return ebdt.get(glyph_id, pixels_per_em);
2176        }
2177
2178        if let Some(cbdt) = self.tables.cbdt {
2179            return cbdt.get(glyph_id, pixels_per_em);
2180        }
2181
2182        None
2183    }
2184
2185    /// Returns a reference to a glyph's SVG image.
2186    ///
2187    /// A font can define a glyph using a raster or a vector image instead of a simple outline.
2188    /// Which is primarily used for emojis. This method should be used to access SVG images.
2189    ///
2190    /// Note that this method will return just an SVG data. It should be rendered
2191    /// or even decompressed (in case of SVGZ) by the caller.
2192    /// We don't validate or preprocess it in any way.
2193    ///
2194    /// Also, a font can contain both: images and outlines. So when this method returns `None`
2195    /// you should also try `outline_glyph()` afterwards.
2196    #[inline]
2197    pub fn glyph_svg_image(&self, glyph_id: GlyphId) -> Option<svg::SvgDocument<'a>> {
2198        self.tables.svg.and_then(|svg| svg.documents.find(glyph_id))
2199    }
2200
2201    /// Returns `true` if the glyph can be colored/painted using the `COLR`+`CPAL` tables.
2202    ///
2203    /// See [`paint_color_glyph`](Face::paint_color_glyph) for details.
2204    pub fn is_color_glyph(&self, glyph_id: GlyphId) -> bool {
2205        self.tables().colr.map(|colr| colr.contains(glyph_id)).unwrap_or(false)
2206    }
2207
2208    /// Returns the number of palettes stored in the `COLR`+`CPAL` tables.
2209    ///
2210    /// See [`paint_color_glyph`](Face::paint_color_glyph) for details.
2211    pub fn color_palettes(&self) -> Option<core::num::NonZeroU16> {
2212        Some(self.tables().colr?.palettes.palettes())
2213    }
2214
2215    /// Paints a color glyph from the `COLR` table.
2216    ///
2217    /// A font can have multiple palettes, which you can check via
2218    /// [`color_palettes`](Face::color_palettes).
2219    /// If unsure, just pass 0 to the `palette` argument, which is the default.
2220    ///
2221    /// A font can define a glyph using layers of colored shapes instead of a
2222    /// simple outline. Which is primarily used for emojis. This method should
2223    /// be used to access glyphs defined in the `COLR` table.
2224    ///
2225    /// Also, a font can contain both: a layered definition and outlines. So
2226    /// when this method returns `None` you should also try
2227    /// [`outline_glyph`](Face::outline_glyph) afterwards.
2228    ///
2229    /// Returns `None` if the glyph has no `COLR` definition or if the glyph
2230    /// definition is malformed.
2231    ///
2232    /// See `examples/font2svg.rs` for usage examples.
2233    #[inline]
2234    pub fn paint_color_glyph(
2235        &self,
2236        glyph_id: GlyphId,
2237        palette: u16,
2238        foreground_color: RgbaColor,
2239        painter: &mut dyn colr::Painter<'a>,
2240    ) -> Option<()> {
2241        self.tables.colr?.paint(
2242            glyph_id,
2243            palette,
2244            painter,
2245            #[cfg(feature = "variable-fonts")]
2246            self.coords(),
2247            foreground_color,
2248        )
2249    }
2250
2251    /// Returns an iterator over variation axes.
2252    #[cfg(feature = "variable-fonts")]
2253    #[inline]
2254    pub fn variation_axes(&self) -> LazyArray16<'a, VariationAxis> {
2255        self.tables.fvar.map(|fvar| fvar.axes).unwrap_or_default()
2256    }
2257
2258    /// Sets a variation axis coordinate.
2259    ///
2260    /// This is one of the two only mutable methods in the library.
2261    /// We can simplify the API a lot by storing the variable coordinates
2262    /// in the face object itself.
2263    ///
2264    /// Since coordinates are stored on the stack, we allow only 64 of them.
2265    ///
2266    /// Returns `None` when face is not variable or doesn't have such axis.
2267    #[cfg(feature = "variable-fonts")]
2268    pub fn set_variation(&mut self, axis: Tag, value: f32) -> Option<()> {
2269        if !self.is_variable() {
2270            return None;
2271        }
2272
2273        if usize::from(self.variation_axes().len()) >= MAX_VAR_COORDS {
2274            return None;
2275        }
2276
2277        let mut success = false;
2278        for (i, var_axis) in self.variation_axes().into_iter().enumerate() {
2279            if var_axis.tag == axis {
2280                success = true;
2281                self.coordinates.data[i] = var_axis.normalized_value(value);
2282
2283                if let Some(avar) = self.tables.avar {
2284                    let _ = avar.map_coordinate(self.coordinates.as_mut_slice(), i);
2285                }
2286            }
2287        }
2288
2289        success.then_some(())
2290    }
2291
2292    /// Returns the current normalized variation coordinates.
2293    #[cfg(feature = "variable-fonts")]
2294    #[inline]
2295    pub fn variation_coordinates(&self) -> &[NormalizedCoordinate] {
2296        self.coordinates.as_slice()
2297    }
2298
2299    /// Checks that face has non-default variation coordinates.
2300    #[cfg(feature = "variable-fonts")]
2301    #[inline]
2302    pub fn has_non_default_variation_coordinates(&self) -> bool {
2303        self.coordinates.as_slice().iter().any(|c| c.0 != 0)
2304    }
2305
2306    /// Parses glyph's phantom points.
2307    ///
2308    /// Available only for variable fonts with the `gvar` table.
2309    #[cfg(feature = "variable-fonts")]
2310    pub fn glyph_phantom_points(&self, glyph_id: GlyphId) -> Option<PhantomPoints> {
2311        let glyf = self.tables.glyf?;
2312        let gvar = self.tables.gvar?;
2313        gvar.phantom_points(glyf, self.coords(), glyph_id)
2314    }
2315
2316    #[cfg(feature = "variable-fonts")]
2317    #[inline]
2318    fn metrics_var_offset(&self, tag: Tag) -> f32 {
2319        self.tables
2320            .mvar
2321            .and_then(|table| table.metric_offset(tag, self.coords()))
2322            .unwrap_or(0.0)
2323    }
2324
2325    #[inline]
2326    fn apply_metrics_variation(&self, tag: Tag, mut value: i16) -> i16 {
2327        self.apply_metrics_variation_to(tag, &mut value);
2328        value
2329    }
2330
2331    #[cfg(feature = "variable-fonts")]
2332    #[inline]
2333    fn apply_metrics_variation_to(&self, tag: Tag, value: &mut i16) {
2334        if self.is_variable() {
2335            let v = f32::from(*value) + self.metrics_var_offset(tag);
2336            // TODO: Should probably round it, but f32::round is not available in core.
2337            if let Some(v) = i16::try_num_from(v) {
2338                *value = v;
2339            }
2340        }
2341    }
2342
2343    #[cfg(not(feature = "variable-fonts"))]
2344    #[inline]
2345    fn apply_metrics_variation_to(&self, _: Tag, _: &mut i16) {}
2346
2347    #[cfg(feature = "variable-fonts")]
2348    #[inline]
2349    fn coords(&self) -> &[NormalizedCoordinate] {
2350        self.coordinates.as_slice()
2351    }
2352}
2353
2354impl core::fmt::Debug for Face<'_> {
2355    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2356        write!(f, "Face()")
2357    }
2358}
2359
2360/// Returns the number of fonts stored in a TrueType font collection.
2361///
2362/// Returns `None` if a provided data is not a TrueType font collection.
2363#[inline]
2364pub fn fonts_in_collection(data: &[u8]) -> Option<u32> {
2365    let mut s = Stream::new(data);
2366    if s.read::<Magic>()? != Magic::FontCollection {
2367        return None;
2368    }
2369
2370    s.skip::<u32>(); // version
2371    s.read::<u32>()
2372}