Skip to main content

write_fonts/tables/glyf/
composite.rs

1//! Composite glyphs (containing other glyphs as components)
2
3use crate::{
4    from_obj::{FromObjRef, FromTableRef, ToOwnedTable},
5    FontWrite,
6};
7
8use read_fonts::{
9    tables::glyf::CompositeGlyphFlags,
10    types::{GlyphId, Uint24},
11    FontRead, ReadArgs,
12};
13
14use super::Bbox;
15
16pub use read_fonts::tables::glyf::{Anchor, Transform};
17
18/// A glyph consisting of multiple component sub-glyphs
19#[derive(Clone, Debug, PartialEq, Eq)]
20pub struct CompositeGlyph {
21    pub bbox: Bbox,
22    components: Vec<Component>,
23    instructions: Vec<u8>,
24}
25
26/// A single component glyph (part of a [`CompositeGlyph`]).
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct Component {
29    pub glyph: GlyphId,
30    pub anchor: Anchor,
31    pub flags: ComponentFlags,
32    pub transform: Transform,
33}
34
35/// Options that can be manually set for a given component.
36///
37/// This provides an easier interface for setting those flags that are not
38/// calculated based on other properties of the glyph. For more information
39/// on these flags, see [Component Glyph Flags](flags-spec) in the spec.
40///
41/// These eventually are combined with calculated flags into the
42/// [`CompositeGlyphFlags`] bitset.
43///
44/// [flags-spec]: https://learn.microsoft.com/en-us/typography/opentype/spec/glyf#compositeGlyphFlags
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
46pub struct ComponentFlags {
47    /// Round xy values to the nearest grid line
48    pub round_xy_to_grid: bool,
49    /// Use the advance/lsb/rsb values of this component for the whole
50    /// composite glyph
51    pub use_my_metrics: bool,
52    /// The composite should have this component's offset scaled
53    pub scaled_component_offset: bool,
54    /// The composite should *not* have this component's offset scaled
55    pub unscaled_component_offset: bool,
56    /// If set, the components of the composite glyph overlap.
57    pub overlap_compound: bool,
58}
59
60impl FromObjRef<read_fonts::tables::glyf::CompositeGlyph<'_>> for CompositeGlyph {
61    fn from_obj_ref(
62        from: &read_fonts::tables::glyf::CompositeGlyph,
63        _data: read_fonts::FontData,
64    ) -> Self {
65        let bbox = Bbox {
66            x_min: from.x_min(),
67            y_min: from.y_min(),
68            x_max: from.x_max(),
69            y_max: from.y_max(),
70        };
71        let components = from
72            .components()
73            .map(|c| Component {
74                glyph: c.glyph,
75                anchor: c.anchor,
76                flags: c.flags.into(),
77                transform: c.transform,
78            })
79            .collect();
80        Self {
81            bbox,
82            components,
83            instructions: from
84                .instructions()
85                .map(|v| v.to_owned())
86                .unwrap_or_default(),
87        }
88    }
89}
90
91impl FromTableRef<read_fonts::tables::glyf::CompositeGlyph<'_>> for CompositeGlyph {}
92
93impl ReadArgs for CompositeGlyph {
94    type Args = ();
95}
96
97impl<'a> FontRead<'a> for CompositeGlyph {
98    fn read_with_args(
99        data: read_fonts::FontData<'a>,
100        _: (),
101    ) -> Result<Self, read_fonts::ReadError> {
102        read_fonts::tables::glyf::CompositeGlyph::read(data).map(|g| g.to_owned_table())
103    }
104}
105
106impl Component {
107    /// Create a new component.
108    pub fn new(
109        glyph: GlyphId,
110        anchor: Anchor,
111        transform: Transform,
112        flags: impl Into<ComponentFlags>,
113    ) -> Self {
114        Component {
115            glyph,
116            anchor,
117            flags: flags.into(),
118            transform,
119        }
120    }
121    /// Compute the flags for this glyph, excepting `MORE_COMPONENTS` and
122    /// `WE_HAVE_INSTRUCTIONS`, which must be set manually
123    fn compute_flag(&self) -> CompositeGlyphFlags {
124        let glyph_flag = if self.glyph.to_u32() > u16::MAX as u32 {
125            CompositeGlyphFlags::GID_IS_24_BIT
126        } else {
127            CompositeGlyphFlags::empty()
128        };
129        self.anchor.compute_flags()
130            | self.transform.compute_flags()
131            | self.flags.into()
132            | glyph_flag
133    }
134
135    /// like `FontWrite` but lets us pass in the flags that must be determined
136    /// externally (WE_HAVE_INSTRUCTIONS and MORE_COMPONENTS)
137    fn write_into(&self, writer: &mut crate::TableWriter, extra_flags: CompositeGlyphFlags) {
138        let flags = self.compute_flag() | extra_flags;
139        flags.bits().write_into(writer);
140        if flags.contains(CompositeGlyphFlags::GID_IS_24_BIT) {
141            Uint24::new(self.glyph.to_u32()).write_into(writer);
142        } else {
143            (self.glyph.to_u32() as u16).write_into(writer);
144        }
145        self.anchor.write_into(writer);
146        self.transform.write_into(writer);
147    }
148}
149
150/// An error that occurs if a `CompositeGlyph` is constructed with no components.
151#[derive(Clone, Copy, Debug)]
152#[non_exhaustive]
153pub struct NoComponents;
154
155impl std::fmt::Display for NoComponents {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        write!(f, "A composite glyph must contain at least one component")
158    }
159}
160
161impl std::error::Error for NoComponents {}
162
163impl CompositeGlyph {
164    /// Create a new composite glyph, with the provided component.
165    ///
166    /// The 'bbox' argument is the bounding box of the glyph after the transform
167    /// has been applied.
168    ///
169    /// Additional components can be added with [`add_component`][Self::add_component]
170    pub fn new(component: Component, bbox: impl Into<Bbox>) -> Self {
171        Self {
172            bbox: bbox.into(),
173            components: vec![component],
174            instructions: Default::default(),
175        }
176    }
177
178    /// Add a new component to this glyph
179    ///
180    /// The 'bbox' argument is the bounding box of the glyph after the transform
181    /// has been applied.
182    pub fn add_component(&mut self, component: Component, bbox: impl Into<Bbox>) {
183        self.components.push(component);
184        self.bbox = self.bbox.union(bbox.into());
185    }
186
187    /// Construct a `CompositeGlyph` from an iterator of `Component` and `Bbox`es.
188    ///
189    /// This returns an error if the iterator is empty; a CompositeGlyph must always
190    /// contain at least one component.
191    pub fn try_from_iter(
192        source: impl IntoIterator<Item = (Component, Bbox)>,
193    ) -> Result<Self, NoComponents> {
194        let mut source = source.into_iter();
195        let (component, bbox) = source.next().ok_or(NoComponents)?;
196        let mut glyph = Self::new(component, bbox);
197        for (component, bbox) in source {
198            glyph.add_component(component, bbox);
199        }
200        Ok(glyph)
201    }
202
203    pub fn components(&self) -> &[Component] {
204        &self.components
205    }
206
207    pub fn components_mut(&mut self) -> &mut [Component] {
208        &mut self.components
209    }
210
211    pub fn set_instructions(&mut self, instructions: &[u8]) {
212        self.instructions = instructions.to_vec();
213    }
214
215    pub fn instructions(&self) -> &[u8] {
216        &self.instructions
217    }
218}
219
220impl FontWrite for CompositeGlyph {
221    fn write_into(&self, writer: &mut crate::TableWriter) {
222        const N_CONTOURS: i16 = -1;
223        N_CONTOURS.write_into(writer);
224        self.bbox.write_into(writer);
225        let (last, rest) = self
226            .components
227            .split_last()
228            .expect("empty composites checked in validation");
229        for comp in rest {
230            comp.write_into(writer, CompositeGlyphFlags::MORE_COMPONENTS);
231        }
232        let last_flags = if self.instructions.is_empty() {
233            CompositeGlyphFlags::empty()
234        } else {
235            CompositeGlyphFlags::WE_HAVE_INSTRUCTIONS
236        };
237        last.write_into(writer, last_flags);
238
239        if !self.instructions.is_empty() {
240            (self.instructions.len() as u16).write_into(writer);
241            self.instructions.write_into(writer);
242        }
243        writer.pad_to_2byte_aligned();
244    }
245}
246
247impl crate::validate::Validate for CompositeGlyph {
248    fn validate_impl(&self, ctx: &mut crate::codegen_prelude::ValidationCtx) {
249        if self.components.is_empty() {
250            ctx.report("composite glyph must have components");
251        }
252        if self.instructions.len() > u16::MAX as usize {
253            ctx.report("instructions len overflows");
254        }
255        if self
256            .components
257            .iter()
258            .any(|component| component.glyph.to_u32() > 0xffffff)
259        {
260            ctx.report("component glyph identifier overflows 24 bits");
261        }
262    }
263}
264
265impl FontWrite for Anchor {
266    fn write_into(&self, writer: &mut crate::TableWriter) {
267        let two_bytes = self
268            .compute_flags()
269            .contains(CompositeGlyphFlags::ARG_1_AND_2_ARE_WORDS);
270        match self {
271            Anchor::Offset { x, y } if !two_bytes => [*x as i8, *y as i8].write_into(writer),
272            Anchor::Offset { x, y } => [*x, *y].write_into(writer),
273            Anchor::Point { base, component } if !two_bytes => {
274                [*base as u8, *component as u8].write_into(writer)
275            }
276            Anchor::Point { base, component } => [*base, *component].write_into(writer),
277        }
278    }
279}
280
281impl FontWrite for Transform {
282    fn write_into(&self, writer: &mut crate::TableWriter) {
283        let flags = self.compute_flags();
284        if flags.contains(CompositeGlyphFlags::WE_HAVE_A_TWO_BY_TWO) {
285            [self.xx, self.yx, self.xy, self.yy].write_into(writer);
286        } else if flags.contains(CompositeGlyphFlags::WE_HAVE_AN_X_AND_Y_SCALE) {
287            [self.xx, self.yy].write_into(writer);
288        } else if flags.contains(CompositeGlyphFlags::WE_HAVE_A_SCALE) {
289            self.xx.write_into(writer)
290        }
291    }
292}
293
294impl From<CompositeGlyphFlags> for ComponentFlags {
295    fn from(src: CompositeGlyphFlags) -> ComponentFlags {
296        ComponentFlags {
297            round_xy_to_grid: src.contains(CompositeGlyphFlags::ROUND_XY_TO_GRID),
298            use_my_metrics: src.contains(CompositeGlyphFlags::USE_MY_METRICS),
299            scaled_component_offset: src.contains(CompositeGlyphFlags::SCALED_COMPONENT_OFFSET),
300            unscaled_component_offset: src.contains(CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET),
301            overlap_compound: src.contains(CompositeGlyphFlags::OVERLAP_COMPOUND),
302        }
303    }
304}
305
306impl From<ComponentFlags> for CompositeGlyphFlags {
307    fn from(value: ComponentFlags) -> Self {
308        (if value.round_xy_to_grid {
309            CompositeGlyphFlags::ROUND_XY_TO_GRID
310        } else {
311            Default::default()
312        }) | if value.use_my_metrics {
313            CompositeGlyphFlags::USE_MY_METRICS
314        } else {
315            Default::default()
316        } | if value.scaled_component_offset {
317            CompositeGlyphFlags::SCALED_COMPONENT_OFFSET
318        } else {
319            Default::default()
320        } | if value.unscaled_component_offset {
321            CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET
322        } else {
323            Default::default()
324        } | if value.overlap_compound {
325            CompositeGlyphFlags::OVERLAP_COMPOUND
326        } else {
327            Default::default()
328        }
329    }
330}
331
332#[cfg(test)]
333mod tests {
334
335    use read_fonts::{
336        tables::glyf as read_glyf, types::GlyphId, FontData, FontRead, FontRef, TableProvider,
337    };
338
339    use super::*;
340
341    #[test]
342    fn try_from_iter_unions_bboxes() {
343        let component = |gid: u32| {
344            Component::new(
345                GlyphId::new(gid),
346                Anchor::Offset { x: 0, y: 0 },
347                Transform::default(),
348                ComponentFlags::default(),
349            )
350        };
351        let bbox = |x_min, y_min, x_max, y_max| Bbox {
352            x_min,
353            y_min,
354            x_max,
355            y_max,
356        };
357
358        let glyph = CompositeGlyph::try_from_iter([
359            (component(1), bbox(0, 0, 10, 10)),
360            (component(2), bbox(20, -5, 30, 5)),
361            (component(3), bbox(-10, 15, -5, 20)),
362        ])
363        .unwrap();
364
365        assert_eq!(glyph.bbox, bbox(-10, -5, 30, 20));
366        assert_eq!(glyph.components().len(), 3);
367        assert!(CompositeGlyph::try_from_iter([]).is_err());
368    }
369
370    #[test]
371    fn roundtrip_extended_composite_components() {
372        let half = read_fonts::types::F2Dot14::from_f32(0.5);
373        let bbox = Bbox {
374            x_min: 0,
375            y_min: 0,
376            x_max: 80,
377            y_max: 80,
378        };
379        for gid in [65535, 65536, 0xffffff] {
380            for anchor in [
381                Anchor::Offset { x: 1, y: -2 },
382                Anchor::Point {
383                    base: 256,
384                    component: 512,
385                },
386            ] {
387                for transform in [
388                    Transform::default(),
389                    Transform {
390                        xx: half,
391                        yy: half,
392                        ..Default::default()
393                    },
394                    Transform {
395                        xx: half,
396                        ..Default::default()
397                    },
398                    Transform {
399                        xy: half,
400                        ..Default::default()
401                    },
402                ] {
403                    let mut glyph = CompositeGlyph::new(
404                        Component::new(
405                            GlyphId::new(gid),
406                            anchor,
407                            transform,
408                            ComponentFlags::default(),
409                        ),
410                        bbox,
411                    );
412                    glyph.add_component(
413                        Component::new(
414                            GlyphId::new(7),
415                            Anchor::Offset { x: 3, y: 4 },
416                            Transform::default(),
417                            ComponentFlags::default(),
418                        ),
419                        bbox,
420                    );
421                    glyph.set_instructions(&[0xb0, 0, 0x21]);
422                    let bytes = crate::dump_table(&glyph).unwrap();
423                    let read = read_glyf::CompositeGlyph::read(bytes.as_slice().into()).unwrap();
424                    let components: Vec<_> = read.components().collect();
425                    let ids: Vec<_> = read.component_glyphs_and_flags().map(|c| c.0).collect();
426                    assert_eq!(ids, [GlyphId::new(gid), GlyphId::new(7)]);
427                    assert_eq!(components[0].glyph, ids[0]);
428                    assert_eq!(components[0].anchor, anchor);
429                    assert_eq!(components[0].transform, transform);
430                    assert_eq!(
431                        components[0]
432                            .flags
433                            .contains(CompositeGlyphFlags::GID_IS_24_BIT),
434                        gid > 65535
435                    );
436                    assert!(!components[1]
437                        .flags
438                        .contains(CompositeGlyphFlags::GID_IS_24_BIT));
439                    assert_eq!(
440                        read.count_and_instructions(),
441                        (2, Some(&[0xb0, 0, 0x21][..]))
442                    );
443                    let owned: CompositeGlyph = read.to_owned_table();
444                    assert_eq!(owned, glyph);
445                    assert_eq!(crate::dump_table(&owned).unwrap(), bytes);
446                }
447            }
448        }
449        let glyph = CompositeGlyph::new(
450            Component::new(
451                GlyphId::new(0x1000000),
452                Anchor::Offset { x: 0, y: 0 },
453                Transform::default(),
454                ComponentFlags::default(),
455            ),
456            bbox,
457        );
458        assert!(crate::dump_table(&glyph).is_err());
459    }
460
461    #[test]
462    fn roundtrip_composite() {
463        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
464        let loca = font.loca(None).unwrap();
465        let glyf = font.glyf().unwrap();
466        let read_glyf::Glyph::Composite(orig) = loca
467            .get(GlyphId::new(2), &glyf)
468            .and_then(|g| g.into_glyph())
469            .unwrap()
470        else {
471            panic!("not a composite glyph")
472        };
473
474        let bbox = Bbox {
475            x_min: orig.x_min(),
476            y_min: orig.y_min(),
477            x_max: orig.x_max(),
478            y_max: orig.y_max(),
479        };
480        let mut iter = orig
481            .components()
482            .map(|comp| Component::new(comp.glyph, comp.anchor, comp.transform, comp.flags));
483        let mut composite = CompositeGlyph::new(iter.next().unwrap(), bbox);
484        composite.add_component(iter.next().unwrap(), bbox);
485        composite.instructions = orig.instructions().unwrap_or_default().to_vec();
486        assert!(iter.next().is_none());
487        let bytes = crate::dump_table(&composite).unwrap();
488        let ours = read_fonts::tables::glyf::CompositeGlyph::read(FontData::new(&bytes)).unwrap();
489
490        let our_comps = ours.components().collect::<Vec<_>>();
491        let orig_comps = orig.components().collect::<Vec<_>>();
492        assert_eq!(our_comps.len(), orig_comps.len());
493        assert_eq!(our_comps.len(), 2);
494        assert_eq!(&our_comps[0], &orig_comps[0]);
495        assert_eq!(&our_comps[1], &orig_comps[1]);
496        assert_eq!(ours.instructions(), orig.instructions());
497        assert_eq!(orig.offset_data().len(), bytes.len());
498
499        assert_eq!(orig.offset_data().as_ref(), bytes);
500    }
501}