write-fonts 0.55.0

Writing font files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Composite glyphs (containing other glyphs as components)

use crate::{
    from_obj::{FromObjRef, FromTableRef, ToOwnedTable},
    FontWrite,
};

use read_fonts::{
    tables::glyf::CompositeGlyphFlags,
    types::{GlyphId, Uint24},
    FontRead, ReadArgs,
};

use super::Bbox;

pub use read_fonts::tables::glyf::{Anchor, Transform};

/// A glyph consisting of multiple component sub-glyphs
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CompositeGlyph {
    pub bbox: Bbox,
    components: Vec<Component>,
    instructions: Vec<u8>,
}

/// A single component glyph (part of a [`CompositeGlyph`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Component {
    pub glyph: GlyphId,
    pub anchor: Anchor,
    pub flags: ComponentFlags,
    pub transform: Transform,
}

/// Options that can be manually set for a given component.
///
/// This provides an easier interface for setting those flags that are not
/// calculated based on other properties of the glyph. For more information
/// on these flags, see [Component Glyph Flags](flags-spec) in the spec.
///
/// These eventually are combined with calculated flags into the
/// [`CompositeGlyphFlags`] bitset.
///
/// [flags-spec]: https://learn.microsoft.com/en-us/typography/opentype/spec/glyf#compositeGlyphFlags
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct ComponentFlags {
    /// Round xy values to the nearest grid line
    pub round_xy_to_grid: bool,
    /// Use the advance/lsb/rsb values of this component for the whole
    /// composite glyph
    pub use_my_metrics: bool,
    /// The composite should have this component's offset scaled
    pub scaled_component_offset: bool,
    /// The composite should *not* have this component's offset scaled
    pub unscaled_component_offset: bool,
    /// If set, the components of the composite glyph overlap.
    pub overlap_compound: bool,
}

impl FromObjRef<read_fonts::tables::glyf::CompositeGlyph<'_>> for CompositeGlyph {
    fn from_obj_ref(
        from: &read_fonts::tables::glyf::CompositeGlyph,
        _data: read_fonts::FontData,
    ) -> Self {
        let bbox = Bbox {
            x_min: from.x_min(),
            y_min: from.y_min(),
            x_max: from.x_max(),
            y_max: from.y_max(),
        };
        let components = from
            .components()
            .map(|c| Component {
                glyph: c.glyph,
                anchor: c.anchor,
                flags: c.flags.into(),
                transform: c.transform,
            })
            .collect();
        Self {
            bbox,
            components,
            instructions: from
                .instructions()
                .map(|v| v.to_owned())
                .unwrap_or_default(),
        }
    }
}

impl FromTableRef<read_fonts::tables::glyf::CompositeGlyph<'_>> for CompositeGlyph {}

impl ReadArgs for CompositeGlyph {
    type Args = ();
}

impl<'a> FontRead<'a> for CompositeGlyph {
    fn read_with_args(
        data: read_fonts::FontData<'a>,
        _: (),
    ) -> Result<Self, read_fonts::ReadError> {
        read_fonts::tables::glyf::CompositeGlyph::read(data).map(|g| g.to_owned_table())
    }
}

impl Component {
    /// Create a new component.
    pub fn new(
        glyph: GlyphId,
        anchor: Anchor,
        transform: Transform,
        flags: impl Into<ComponentFlags>,
    ) -> Self {
        Component {
            glyph,
            anchor,
            flags: flags.into(),
            transform,
        }
    }
    /// Compute the flags for this glyph, excepting `MORE_COMPONENTS` and
    /// `WE_HAVE_INSTRUCTIONS`, which must be set manually
    fn compute_flag(&self) -> CompositeGlyphFlags {
        let glyph_flag = if self.glyph.to_u32() > u16::MAX as u32 {
            CompositeGlyphFlags::GID_IS_24_BIT
        } else {
            CompositeGlyphFlags::empty()
        };
        self.anchor.compute_flags()
            | self.transform.compute_flags()
            | self.flags.into()
            | glyph_flag
    }

    /// like `FontWrite` but lets us pass in the flags that must be determined
    /// externally (WE_HAVE_INSTRUCTIONS and MORE_COMPONENTS)
    fn write_into(&self, writer: &mut crate::TableWriter, extra_flags: CompositeGlyphFlags) {
        let flags = self.compute_flag() | extra_flags;
        flags.bits().write_into(writer);
        if flags.contains(CompositeGlyphFlags::GID_IS_24_BIT) {
            Uint24::new(self.glyph.to_u32()).write_into(writer);
        } else {
            (self.glyph.to_u32() as u16).write_into(writer);
        }
        self.anchor.write_into(writer);
        self.transform.write_into(writer);
    }
}

/// An error that occurs if a `CompositeGlyph` is constructed with no components.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct NoComponents;

impl std::fmt::Display for NoComponents {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "A composite glyph must contain at least one component")
    }
}

impl std::error::Error for NoComponents {}

impl CompositeGlyph {
    /// Create a new composite glyph, with the provided component.
    ///
    /// The 'bbox' argument is the bounding box of the glyph after the transform
    /// has been applied.
    ///
    /// Additional components can be added with [`add_component`][Self::add_component]
    pub fn new(component: Component, bbox: impl Into<Bbox>) -> Self {
        Self {
            bbox: bbox.into(),
            components: vec![component],
            instructions: Default::default(),
        }
    }

    /// Add a new component to this glyph
    ///
    /// The 'bbox' argument is the bounding box of the glyph after the transform
    /// has been applied.
    pub fn add_component(&mut self, component: Component, bbox: impl Into<Bbox>) {
        self.components.push(component);
        self.bbox = self.bbox.union(bbox.into());
    }

    /// Construct a `CompositeGlyph` from an iterator of `Component` and `Bbox`es.
    ///
    /// This returns an error if the iterator is empty; a CompositeGlyph must always
    /// contain at least one component.
    pub fn try_from_iter(
        source: impl IntoIterator<Item = (Component, Bbox)>,
    ) -> Result<Self, NoComponents> {
        let mut components = Vec::new();
        let mut union_box: Option<Bbox> = None;

        for (component, bbox) in source {
            components.push(component);
            union_box.get_or_insert(bbox).union(bbox);
        }

        if components.is_empty() {
            Err(NoComponents)
        } else {
            Ok(CompositeGlyph {
                bbox: union_box.unwrap(),
                components,
                instructions: Default::default(),
            })
        }
    }

    pub fn components(&self) -> &[Component] {
        &self.components
    }

    pub fn components_mut(&mut self) -> &mut [Component] {
        &mut self.components
    }

    pub fn set_instructions(&mut self, instructions: &[u8]) {
        self.instructions = instructions.to_vec();
    }

    pub fn instructions(&self) -> &[u8] {
        &self.instructions
    }
}

impl FontWrite for CompositeGlyph {
    fn write_into(&self, writer: &mut crate::TableWriter) {
        const N_CONTOURS: i16 = -1;
        N_CONTOURS.write_into(writer);
        self.bbox.write_into(writer);
        let (last, rest) = self
            .components
            .split_last()
            .expect("empty composites checked in validation");
        for comp in rest {
            comp.write_into(writer, CompositeGlyphFlags::MORE_COMPONENTS);
        }
        let last_flags = if self.instructions.is_empty() {
            CompositeGlyphFlags::empty()
        } else {
            CompositeGlyphFlags::WE_HAVE_INSTRUCTIONS
        };
        last.write_into(writer, last_flags);

        if !self.instructions.is_empty() {
            (self.instructions.len() as u16).write_into(writer);
            self.instructions.write_into(writer);
        }
        writer.pad_to_2byte_aligned();
    }
}

impl crate::validate::Validate for CompositeGlyph {
    fn validate_impl(&self, ctx: &mut crate::codegen_prelude::ValidationCtx) {
        if self.components.is_empty() {
            ctx.report("composite glyph must have components");
        }
        if self.instructions.len() > u16::MAX as usize {
            ctx.report("instructions len overflows");
        }
        if self
            .components
            .iter()
            .any(|component| component.glyph.to_u32() > 0xffffff)
        {
            ctx.report("component glyph identifier overflows 24 bits");
        }
    }
}

impl FontWrite for Anchor {
    fn write_into(&self, writer: &mut crate::TableWriter) {
        let two_bytes = self
            .compute_flags()
            .contains(CompositeGlyphFlags::ARG_1_AND_2_ARE_WORDS);
        match self {
            Anchor::Offset { x, y } if !two_bytes => [*x as i8, *y as i8].write_into(writer),
            Anchor::Offset { x, y } => [*x, *y].write_into(writer),
            Anchor::Point { base, component } if !two_bytes => {
                [*base as u8, *component as u8].write_into(writer)
            }
            Anchor::Point { base, component } => [*base, *component].write_into(writer),
        }
    }
}

impl FontWrite for Transform {
    fn write_into(&self, writer: &mut crate::TableWriter) {
        let flags = self.compute_flags();
        if flags.contains(CompositeGlyphFlags::WE_HAVE_A_TWO_BY_TWO) {
            [self.xx, self.yx, self.xy, self.yy].write_into(writer);
        } else if flags.contains(CompositeGlyphFlags::WE_HAVE_AN_X_AND_Y_SCALE) {
            [self.xx, self.yy].write_into(writer);
        } else if flags.contains(CompositeGlyphFlags::WE_HAVE_A_SCALE) {
            self.xx.write_into(writer)
        }
    }
}

impl From<CompositeGlyphFlags> for ComponentFlags {
    fn from(src: CompositeGlyphFlags) -> ComponentFlags {
        ComponentFlags {
            round_xy_to_grid: src.contains(CompositeGlyphFlags::ROUND_XY_TO_GRID),
            use_my_metrics: src.contains(CompositeGlyphFlags::USE_MY_METRICS),
            scaled_component_offset: src.contains(CompositeGlyphFlags::SCALED_COMPONENT_OFFSET),
            unscaled_component_offset: src.contains(CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET),
            overlap_compound: src.contains(CompositeGlyphFlags::OVERLAP_COMPOUND),
        }
    }
}

impl From<ComponentFlags> for CompositeGlyphFlags {
    fn from(value: ComponentFlags) -> Self {
        (if value.round_xy_to_grid {
            CompositeGlyphFlags::ROUND_XY_TO_GRID
        } else {
            Default::default()
        }) | if value.use_my_metrics {
            CompositeGlyphFlags::USE_MY_METRICS
        } else {
            Default::default()
        } | if value.scaled_component_offset {
            CompositeGlyphFlags::SCALED_COMPONENT_OFFSET
        } else {
            Default::default()
        } | if value.unscaled_component_offset {
            CompositeGlyphFlags::UNSCALED_COMPONENT_OFFSET
        } else {
            Default::default()
        } | if value.overlap_compound {
            CompositeGlyphFlags::OVERLAP_COMPOUND
        } else {
            Default::default()
        }
    }
}

#[cfg(test)]
mod tests {

    use read_fonts::{
        tables::glyf as read_glyf, types::GlyphId, FontData, FontRead, FontRef, TableProvider,
    };

    use super::*;

    #[test]
    fn roundtrip_extended_composite_components() {
        let half = read_fonts::types::F2Dot14::from_f32(0.5);
        let bbox = Bbox {
            x_min: 0,
            y_min: 0,
            x_max: 80,
            y_max: 80,
        };
        for gid in [65535, 65536, 0xffffff] {
            for anchor in [
                Anchor::Offset { x: 1, y: -2 },
                Anchor::Point {
                    base: 256,
                    component: 512,
                },
            ] {
                for transform in [
                    Transform::default(),
                    Transform {
                        xx: half,
                        yy: half,
                        ..Default::default()
                    },
                    Transform {
                        xx: half,
                        ..Default::default()
                    },
                    Transform {
                        xy: half,
                        ..Default::default()
                    },
                ] {
                    let mut glyph = CompositeGlyph::new(
                        Component::new(
                            GlyphId::new(gid),
                            anchor,
                            transform,
                            ComponentFlags::default(),
                        ),
                        bbox,
                    );
                    glyph.add_component(
                        Component::new(
                            GlyphId::new(7),
                            Anchor::Offset { x: 3, y: 4 },
                            Transform::default(),
                            ComponentFlags::default(),
                        ),
                        bbox,
                    );
                    glyph.set_instructions(&[0xb0, 0, 0x21]);
                    let bytes = crate::dump_table(&glyph).unwrap();
                    let read = read_glyf::CompositeGlyph::read(bytes.as_slice().into()).unwrap();
                    let components: Vec<_> = read.components().collect();
                    let ids: Vec<_> = read.component_glyphs_and_flags().map(|c| c.0).collect();
                    assert_eq!(ids, [GlyphId::new(gid), GlyphId::new(7)]);
                    assert_eq!(components[0].glyph, ids[0]);
                    assert_eq!(components[0].anchor, anchor);
                    assert_eq!(components[0].transform, transform);
                    assert_eq!(
                        components[0]
                            .flags
                            .contains(CompositeGlyphFlags::GID_IS_24_BIT),
                        gid > 65535
                    );
                    assert!(!components[1]
                        .flags
                        .contains(CompositeGlyphFlags::GID_IS_24_BIT));
                    assert_eq!(
                        read.count_and_instructions(),
                        (2, Some(&[0xb0, 0, 0x21][..]))
                    );
                    let owned: CompositeGlyph = read.to_owned_table();
                    assert_eq!(owned, glyph);
                    assert_eq!(crate::dump_table(&owned).unwrap(), bytes);
                }
            }
        }
        let glyph = CompositeGlyph::new(
            Component::new(
                GlyphId::new(0x1000000),
                Anchor::Offset { x: 0, y: 0 },
                Transform::default(),
                ComponentFlags::default(),
            ),
            bbox,
        );
        assert!(crate::dump_table(&glyph).is_err());
    }

    #[test]
    fn roundtrip_composite() {
        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
        let loca = font.loca(None).unwrap();
        let glyf = font.glyf().unwrap();
        let read_glyf::Glyph::Composite(orig) = loca
            .get(GlyphId::new(2), &glyf)
            .and_then(|g| g.into_glyph())
            .unwrap()
        else {
            panic!("not a composite glyph")
        };

        let bbox = Bbox {
            x_min: orig.x_min(),
            y_min: orig.y_min(),
            x_max: orig.x_max(),
            y_max: orig.y_max(),
        };
        let mut iter = orig
            .components()
            .map(|comp| Component::new(comp.glyph, comp.anchor, comp.transform, comp.flags));
        let mut composite = CompositeGlyph::new(iter.next().unwrap(), bbox);
        composite.add_component(iter.next().unwrap(), bbox);
        composite.instructions = orig.instructions().unwrap_or_default().to_vec();
        assert!(iter.next().is_none());
        let bytes = crate::dump_table(&composite).unwrap();
        let ours = read_fonts::tables::glyf::CompositeGlyph::read(FontData::new(&bytes)).unwrap();

        let our_comps = ours.components().collect::<Vec<_>>();
        let orig_comps = orig.components().collect::<Vec<_>>();
        assert_eq!(our_comps.len(), orig_comps.len());
        assert_eq!(our_comps.len(), 2);
        assert_eq!(&our_comps[0], &orig_comps[0]);
        assert_eq!(&our_comps[1], &orig_comps[1]);
        assert_eq!(ours.instructions(), orig.instructions());
        assert_eq!(orig.offset_data().len(), bytes.len());

        assert_eq!(orig.offset_data().as_ref(), bytes);
    }
}