Skip to main content

write_fonts/tables/
glyf.rs

1//! The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
2
3use crate::{
4    from_obj::{FromObjRef, FromTableRef},
5    validate::{Validate, ValidationCtx},
6    FontWrite, OtRound, TableWriter,
7};
8
9use font_types::Tag;
10use kurbo::Rect;
11use read_fonts::{FontRead, ReadArgs, TopLevelTable};
12
13mod composite;
14mod glyf_loca_builder;
15mod simple;
16
17pub use composite::{Anchor, Component, ComponentFlags, CompositeGlyph, Transform};
18pub use glyf_loca_builder::{GlyfLocaBuilder, SomeGlyph};
19pub use simple::{Contour, MalformedPath, SimpleGlyph};
20
21/// The [glyf (Glyph Data)](https://docs.microsoft.com/en-us/typography/opentype/spec/glyf) table
22///
23/// This table is the concatenated bytes of all the glyphs in the font, with
24/// the positions of each individual glyph stored in the ['loca' table][super::loca].
25/// As such, these two tables must be constructed together. The [`GlyfLocaBuilder`]
26/// type is provided to simplify this.
27#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29pub struct Glyf(Vec<u8>);
30
31impl TopLevelTable for Glyf {
32    /// 'glyf'
33    const TAG: Tag = Tag::new(b"glyf");
34}
35
36/// A simple or composite glyph
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub enum Glyph {
39    /// An empty glyph gets an entry in `loca`, but no data is written to `glyf`
40    Empty,
41    Simple(SimpleGlyph),
42    Composite(CompositeGlyph),
43}
44
45/// A Bounding box.
46///
47/// This should be the minimum rectangle which fully encloses the glyph outline;
48/// importantly this can only be determined by computing the individual Bezier
49/// segments, and cannot be determined from points alone.
50#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
51pub struct Bbox {
52    pub x_min: i16,
53    pub y_min: i16,
54    pub x_max: i16,
55    pub y_max: i16,
56}
57
58impl Glyph {
59    /// The bounding box for the glyph
60    pub fn bbox(&self) -> Option<Bbox> {
61        match self {
62            Glyph::Empty => None,
63            Glyph::Simple(glyph) => Some(glyph.bbox),
64            Glyph::Composite(glyph) => Some(glyph.bbox),
65        }
66    }
67}
68
69impl Bbox {
70    /// Return the smallest bounding box covering `self` and `other`
71    #[must_use]
72    pub fn union(self, other: Bbox) -> Bbox {
73        Bbox {
74            x_min: self.x_min.min(other.x_min),
75            y_min: self.y_min.min(other.y_min),
76            x_max: self.x_max.max(other.x_max),
77            y_max: self.y_max.max(other.y_max),
78        }
79    }
80}
81
82impl From<Rect> for Bbox {
83    fn from(value: Rect) -> Self {
84        Bbox {
85            x_min: value.min_x().ot_round(),
86            y_min: value.min_y().ot_round(),
87            x_max: value.max_x().ot_round(),
88            y_max: value.max_y().ot_round(),
89        }
90    }
91}
92
93impl FontWrite for Bbox {
94    fn write_into(&self, writer: &mut crate::TableWriter) {
95        let Bbox {
96            x_min,
97            y_min,
98            x_max,
99            y_max,
100        } = *self;
101        [x_min, y_min, x_max, y_max].write_into(writer)
102    }
103}
104
105impl<'a> FromObjRef<read_fonts::tables::glyf::Glyph<'a>> for Glyph {
106    fn from_obj_ref(
107        from: &read_fonts::tables::glyf::Glyph<'a>,
108        data: read_fonts::FontData,
109    ) -> Self {
110        match from {
111            read_fonts::tables::glyf::Glyph::Simple(glyph) => {
112                Self::Simple(SimpleGlyph::from_obj_ref(glyph, data))
113            }
114            read_fonts::tables::glyf::Glyph::Composite(glyph) => {
115                Self::Composite(CompositeGlyph::from_obj_ref(glyph, data))
116            }
117        }
118    }
119}
120
121impl FromTableRef<read_fonts::tables::glyf::Glyph<'_>> for Glyph {}
122
123impl ReadArgs for Glyph {
124    type Args = ();
125}
126
127impl<'a> FontRead<'a> for Glyph {
128    fn read_with_args(
129        data: read_fonts::FontData<'a>,
130        _: (),
131    ) -> Result<Self, read_fonts::ReadError> {
132        read_fonts::tables::glyf::Glyph::read(data).map(|g| Glyph::from_table_ref(&g))
133    }
134}
135
136impl From<SimpleGlyph> for Glyph {
137    fn from(value: SimpleGlyph) -> Self {
138        if value.contours.is_empty() {
139            Glyph::Empty
140        } else {
141            Glyph::Simple(value)
142        }
143    }
144}
145
146impl From<CompositeGlyph> for Glyph {
147    fn from(value: CompositeGlyph) -> Self {
148        Glyph::Composite(value)
149    }
150}
151
152impl Validate for Glyph {
153    fn validate_impl(&self, ctx: &mut ValidationCtx) {
154        match self {
155            Glyph::Empty => (),
156            Glyph::Simple(glyph) => glyph.validate_impl(ctx),
157            Glyph::Composite(glyph) => glyph.validate_impl(ctx),
158        }
159    }
160}
161
162impl FontWrite for Glyph {
163    fn write_into(&self, writer: &mut crate::TableWriter) {
164        match self {
165            Glyph::Empty => (),
166            Glyph::Simple(glyph) => glyph.write_into(writer),
167            Glyph::Composite(glyph) => glyph.write_into(writer),
168        }
169    }
170}
171
172impl Validate for Glyf {
173    fn validate_impl(&self, _ctx: &mut ValidationCtx) {}
174}
175
176impl FontWrite for Glyf {
177    fn write_into(&self, writer: &mut TableWriter) {
178        writer.write_slice(&self.0)
179    }
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185
186    #[test]
187    fn union_box() {
188        assert_eq!(
189            Bbox {
190                x_min: -1,
191                y_min: -2,
192                x_max: 5,
193                y_max: 6
194            },
195            Bbox {
196                x_min: 0,
197                y_min: 0,
198                x_max: 5,
199                y_max: 6
200            }
201            .union(Bbox {
202                x_min: -1,
203                y_min: -2,
204                x_max: 3,
205                y_max: 4
206            })
207        )
208    }
209}