1#![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)] #![allow(clippy::identity_op)] #![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#![allow(missing_docs)]
55#![allow(dead_code)]
61#![allow(unused_variables)]
62#![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 pub use crate::ggg::*;
121}
122
123#[cfg(feature = "apple-layout")]
124pub mod apple_layout {
125 pub use crate::aat::*;
130}
131
132#[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#[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#[repr(transparent)]
177#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
178pub struct NormalizedCoordinate(i16);
179
180impl From<i16> for NormalizedCoordinate {
181 #[inline]
185 fn from(n: i16) -> Self {
186 NormalizedCoordinate(parser::i16_bound(-16384, n, 16384))
187 }
188}
189
190impl From<f32> for NormalizedCoordinate {
191 #[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 #[inline]
203 pub fn get(self) -> i16 {
204 self.0
205 }
206}
207
208#[derive(Clone, Copy, PartialEq, Debug)]
218pub struct Variation {
219 pub axis: Tag,
221 pub value: f32,
223}
224
225#[repr(transparent)]
227#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
228pub struct Tag(pub u32);
229
230impl Tag {
231 #[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 #[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 #[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 #[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 #[inline]
289 pub const fn is_null(&self) -> bool {
290 self.0 == 0
291 }
292
293 #[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#[repr(C)]
335#[derive(Clone, Copy, PartialEq, Eq, Debug)]
336pub struct LineMetrics {
337 pub position: i16,
339
340 pub thickness: i16,
342}
343
344#[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 #[inline]
370 pub fn width(&self) -> i16 {
371 self.x_max - self.x_min
372 }
373
374 #[inline]
376 pub fn height(&self) -> i16 {
377 self.y_max - self.y_min
378 }
379}
380
381#[derive(Clone, Copy, Debug, PartialEq)]
383pub struct RectF {
384 pub x_min: f32,
386 pub y_min: f32,
388 pub x_max: f32,
390 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#[derive(Clone, Copy, PartialEq)]
431pub struct Transform {
432 pub a: f32,
434 pub b: f32,
436 pub c: f32,
438 pub d: f32,
440 pub e: f32,
442 pub f: f32,
444}
445
446impl Transform {
447 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
506 pub fn is_default(&self) -> bool {
507 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#[derive(Clone, Copy, Debug)]
538pub struct PointF {
539 pub x: f32,
541 pub y: f32,
543}
544
545#[derive(Clone, Copy, Debug)]
549pub struct PhantomPoints {
550 pub left: PointF,
552 pub right: PointF,
554 pub top: PointF,
556 pub bottom: PointF,
558}
559
560#[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 #[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
587pub trait OutlineBuilder {
589 fn move_to(&mut self, x: f32, y: f32);
593
594 fn line_to(&mut self, x: f32, y: f32);
596
597 fn quad_to(&mut self, x1: f32, y1: f32, x: f32, y: f32);
599
600 fn curve_to(&mut self, x1: f32, y1: f32, x2: f32, y2: f32, x: f32, y: f32);
602
603 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#[allow(missing_docs)]
620#[derive(Clone, Copy, PartialEq, Eq, Debug)]
621pub enum RasterImageFormat {
622 PNG,
623
624 BitmapMono,
631
632 BitmapMonoPacked,
638
639 BitmapGray2,
645
646 BitmapGray2Packed,
651
652 BitmapGray4,
658
659 BitmapGray4Packed,
664
665 BitmapGray8,
670
671 BitmapPremulBgra32,
679}
680
681#[derive(Clone, Copy, PartialEq, Eq, Debug)]
685pub struct RasterGlyphImage<'a> {
686 pub x: i16,
688
689 pub y: i16,
691
692 pub width: u16,
696
697 pub height: u16,
701
702 pub pixels_per_em: u16,
704
705 pub format: RasterImageFormat,
707
708 pub data: &'a [u8],
710}
711
712#[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#[derive(Clone, Copy, PartialEq, Eq, Debug)]
774pub enum FaceParsingError {
775 MalformedFont,
779
780 UnknownMagic,
782
783 FaceIndexOutOfBounds,
785
786 NoHeadTable,
788
789 NoHheaTable,
791
792 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#[derive(Clone, Copy)]
821pub struct RawFace<'a> {
822 pub data: &'a [u8],
824 pub table_records: LazyArray16<'a, TableRecord>,
826}
827
828impl<'a> RawFace<'a> {
829 #[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 pub fn parse(data: &'a [u8], index: u32) -> Result<Self, FaceParsingError> {
849 let mut s = Stream::new(data);
852
853 let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
855 if magic == Magic::FontCollection {
856 s.skip::<u32>(); 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 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 let magic = s.read::<Magic>().ok_or(FaceParsingError::UnknownMagic)?;
874 if magic == Magic::FontCollection {
876 return Err(FaceParsingError::UnknownMagic);
877 }
878 } else {
879 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); 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 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#[allow(missing_docs)]
919#[allow(missing_debug_implementations)]
920#[derive(Clone, Default)]
921pub struct RawFaceTables<'a> {
922 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#[allow(missing_docs)]
995#[allow(missing_debug_implementations)]
996#[derive(Clone)]
997pub struct FaceTables<'a> {
998 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#[derive(Clone)]
1074pub struct Face<'a> {
1075 raw_face: RawFace<'a>,
1076 tables: FaceTables<'a>, #[cfg(feature = "variable-fonts")]
1078 coordinates: VarCoords,
1079}
1080
1081impl<'a> Face<'a> {
1082 #[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 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 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 #[inline]
1356 pub fn tables(&self) -> &FaceTables<'a> {
1357 &self.tables
1358 }
1359
1360 #[inline]
1366 pub fn raw_face(&self) -> &RawFace<'a> {
1367 &self.raw_face
1368 }
1369
1370 #[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 #[inline]
1385 pub fn names(&self) -> name::Names<'a> {
1386 self.tables.name.unwrap_or_default().names
1387 }
1388
1389 #[inline]
1393 pub fn is_regular(&self) -> bool {
1394 self.style() == Style::Normal
1395 }
1396
1397 #[inline]
1399 pub fn is_italic(&self) -> bool {
1400 self.style() == Style::Italic || self.italic_angle() != 0.0
1402 }
1403
1404 #[inline]
1408 pub fn is_bold(&self) -> bool {
1409 self.tables.os2.map(|os2| os2.is_bold()).unwrap_or(false)
1410 }
1411
1412 #[inline]
1416 pub fn is_oblique(&self) -> bool {
1417 self.style() == Style::Oblique
1418 }
1419
1420 #[inline]
1424 pub fn style(&self) -> Style {
1425 self.tables.os2.map(|os2| os2.style()).unwrap_or_default()
1426 }
1427
1428 #[inline]
1432 pub fn is_monospaced(&self) -> bool {
1433 self.tables.post.map(|post| post.is_monospaced).unwrap_or(false)
1434 }
1435
1436 #[inline]
1440 pub fn is_variable(&self) -> bool {
1441 #[cfg(feature = "variable-fonts")]
1442 {
1443 self.tables.fvar.is_some()
1445 }
1446
1447 #[cfg(not(feature = "variable-fonts"))]
1448 {
1449 false
1450 }
1451 }
1452
1453 #[inline]
1457 pub fn weight(&self) -> Weight {
1458 self.tables.os2.map(|os2| os2.weight()).unwrap_or_default()
1459 }
1460
1461 #[inline]
1465 pub fn width(&self) -> Width {
1466 self.tables.os2.map(|os2| os2.width()).unwrap_or_default()
1467 }
1468
1469 #[inline]
1473 pub fn italic_angle(&self) -> f32 {
1474 self.tables.post.map(|table| table.italic_angle).unwrap_or(0.0)
1475 }
1476
1477 #[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 #[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 #[inline]
1540 pub fn height(&self) -> i16 {
1541 self.ascender() - self.descender()
1542 }
1543
1544 #[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 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 #[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 #[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 #[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 #[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 #[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 #[inline]
1646 pub fn vertical_height(&self) -> Option<i16> {
1647 Some(self.vertical_ascender()? - self.vertical_descender()?)
1648 }
1649
1650 #[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 #[inline]
1665 pub fn units_per_em(&self) -> u16 {
1666 self.tables.head.units_per_em
1667 }
1668
1669 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
1771 pub fn permissions(&self) -> Option<Permissions> {
1772 self.tables.os2?.permissions()
1773 }
1774
1775 #[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 #[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 #[inline]
1796 pub fn unicode_ranges(&self) -> UnicodeRanges {
1797 self.tables.os2.map(|t| t.unicode_ranges()).unwrap_or_default()
1798 }
1799
1800 #[inline]
1806 pub fn number_of_glyphs(&self) -> u16 {
1807 self.tables.maxp.number_of_glyphs.get()
1808 }
1809
1810 #[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 #[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 #[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 #[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 if let Some(hvar) = self.tables.hvar {
1884 if let Some(offset) = hvar.advance_offset(glyph_id, self.coords()) {
1885 advance += offset + 0.5;
1887 }
1888 } else if let Some(points) = self.glyph_phantom_points(glyph_id) {
1889 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 #[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 if let Some(vvar) = self.tables.vvar {
1915 if let Some(offset) = vvar.advance_offset(glyph_id, self.coords()) {
1916 advance += offset + 0.5;
1918 }
1919 } else if let Some(points) = self.glyph_phantom_points(glyph_id) {
1920 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 #[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 if let Some(hvar) = self.tables.hvar
1946 && let Some(offset) = hvar.left_side_bearing_offset(glyph_id, self.coords())
1947 {
1948 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 #[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 if let Some(vvar) = self.tables.vvar
1974 && let Some(offset) = vvar.top_side_bearing_offset(glyph_id, self.coords())
1975 {
1976 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 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 if let Some(vvar) = self.tables.vvar
2002 && let Some(offset) = vvar.vertical_origin_offset(glyph_id, self.coords())
2003 {
2004 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 #[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 #[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 #[inline]
2133 pub fn glyph_bounding_box(&self, glyph_id: GlyphId) -> Option<Rect> {
2134 self.outline_glyph(glyph_id, &mut DummyOutline)
2135 }
2136
2137 #[inline]
2139 pub fn global_bounding_box(&self) -> Rect {
2140 self.tables.head.global_bbox
2141 }
2142
2143 #[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 #[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 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 pub fn color_palettes(&self) -> Option<core::num::NonZeroU16> {
2212 Some(self.tables().colr?.palettes.palettes())
2213 }
2214
2215 #[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 #[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 #[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 #[cfg(feature = "variable-fonts")]
2294 #[inline]
2295 pub fn variation_coordinates(&self) -> &[NormalizedCoordinate] {
2296 self.coordinates.as_slice()
2297 }
2298
2299 #[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 #[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 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#[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>(); s.read::<u32>()
2372}