read-fonts 0.46.0

Reading OpenType 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
483
484
485
486
487
488
489
490
491
492
493
494
495
//! the [GPOS] table
//!
//! [GPOS]: https://docs.microsoft.com/en-us/typography/opentype/spec/gpos

#[path = "./value_record.rs"]
mod value_record;

#[cfg(feature = "std")]
mod closure;

use crate::array::ComputedArray;

use super::layout::header::HeaderOffset;
/// reexport stuff from layout that we use
pub use super::layout::{
    ClassDef, CoverageTable, Device, DeviceOrVariationIndex, FeatureList, FeatureVariations,
    Lookup, ScriptList,
};
use super::layout::{ExtensionLookup, LookupFlag, SelectedLookupList, Subtables};
pub use value_record::ValueRecord;

#[cfg(test)]
#[path = "../tests/test_gpos.rs"]
mod spec_tests;

use crate::types::Compatible;

include!("../../generated/generated_gpos.rs");

impl<'a> Gpos<'a> {
    /// The offset to the script list, original or extended.
    pub(crate) fn selected_script_list_offset(&self) -> Result<HeaderOffset, ReadError> {
        self.select_offset(self.script_list_offset(), self.script_list2_offset())
    }

    /// The offset to the feature list, original or extended.
    pub(crate) fn selected_feature_list_offset(&self) -> Result<HeaderOffset, ReadError> {
        self.select_offset(self.feature_list_offset(), self.feature_list2_offset())
    }

    /// The offset to the lookup list, original or extended.
    pub(crate) fn selected_lookup_list_offset(&self) -> Result<HeaderOffset, ReadError> {
        self.select_offset(self.lookup_list_offset(), self.lookup_list2_offset())
    }

    fn select_offset(
        &self,
        original: Nullable<Offset16>,
        extended: Option<Nullable<Offset32>>,
    ) -> Result<HeaderOffset, ReadError> {
        HeaderOffset::select(original, extended, self.version().compatible((1, 2)))
    }

    /// Resolves the table, preferring the 32-bit offset when it is nonzero.
    pub fn script_list(&self) -> Result<ScriptList<'a>, ReadError> {
        self.selected_script_list_offset()?
            .offset()
            .resolve(self.offset_data())
    }

    /// Resolves the original 16-bit offset without applying precedence.
    pub fn original_script_list(&self) -> Option<Result<ScriptList<'a>, ReadError>> {
        self.script_list_offset().resolve(self.offset_data())
    }

    /// Resolves the table, preferring the 32-bit offset when it is nonzero.
    pub fn feature_list(&self) -> Result<FeatureList<'a>, ReadError> {
        self.selected_feature_list_offset()?
            .offset()
            .resolve(self.offset_data())
    }

    /// Resolves the original 16-bit offset without applying precedence.
    pub fn original_feature_list(&self) -> Option<Result<FeatureList<'a>, ReadError>> {
        self.feature_list_offset().resolve(self.offset_data())
    }

    /// Resolves the lookup list, preferring LookupList2 when its offset is nonzero.
    pub fn lookup_list(&self) -> Result<PositionLookupList<'a>, ReadError> {
        let data = self.offset_data();
        match self.selected_lookup_list_offset()? {
            HeaderOffset::Original(offset) => {
                offset.resolve(data).map(SelectedLookupList::Original)
            }
            HeaderOffset::Extended(offset) => {
                offset.resolve(data).map(SelectedLookupList::Extended)
            }
        }
    }

    /// Resolves the original 16-bit lookup-list offset.
    pub fn original_lookup_list(
        &self,
    ) -> Option<Result<OriginalPositionLookupList<'a>, ReadError>> {
        self.lookup_list_offset().resolve(self.offset_data())
    }
}

/// The GPOS lookup list selected by the header.
pub type PositionLookupList<'a> = super::layout::SelectedLookupList<'a, PositionLookup<'a>>;

/// A lookup list with the original 16-bit offsets.
pub type OriginalPositionLookupList<'a> = super::layout::LookupList<'a, PositionLookup<'a>>;

/// A lookup list with 32-bit offsets.
pub type PositionLookupList2<'a> = super::layout::LookupList2<'a, PositionLookup<'a>>;

/// A GPOS [SequenceContext](super::layout::SequenceContext)
pub type PositionSequenceContext<'a> = super::layout::SequenceContext<'a>;

/// A GPOS [ChainedSequenceContext](super::layout::ChainedSequenceContext)
pub type PositionChainContext<'a> = super::layout::ChainedSequenceContext<'a>;

impl<'a> AnchorTable<'a> {
    /// Attempt to resolve the `Device` or `VariationIndex` table for the
    /// x_coordinate, if present
    pub fn x_device(&self) -> Option<Result<DeviceOrVariationIndex<'a>, ReadError>> {
        match self {
            AnchorTable::Format3(inner) => inner.x_device(),
            _ => None,
        }
    }

    /// Attempt to resolve the `Device` or `VariationIndex` table for the
    /// y_coordinate, if present
    pub fn y_device(&self) -> Option<Result<DeviceOrVariationIndex<'a>, ReadError>> {
        match self {
            AnchorTable::Format3(inner) => inner.y_device(),
            _ => None,
        }
    }
}

impl<'a, T: FontRead<'a, Args = ()>> ExtensionLookup<'a, T> for ExtensionPosFormat1<'a, T> {
    fn extension(&self) -> Result<T, ReadError> {
        self.extension()
    }
}

type PosSubtables<'a, T> = Subtables<'a, T, ExtensionPosFormat1<'a, T>>;

/// The subtables from a GPOS lookup.
///
/// This type is a convenience that removes the need to dig into the
/// [`PositionLookup`] enum in order to access subtables, and it also abstracts
/// away the distinction between extension and non-extension lookups.
pub enum PositionSubtables<'a> {
    Single(PosSubtables<'a, SinglePos<'a>>),
    Pair(PosSubtables<'a, PairPos<'a>>),
    Cursive(PosSubtables<'a, CursivePos<'a>>),
    MarkToBase(PosSubtables<'a, MarkBasePos<'a>>),
    MarkToLig(PosSubtables<'a, MarkLigPos<'a>>),
    MarkToMark(PosSubtables<'a, MarkMarkPos<'a>>),
    Contextual(PosSubtables<'a, PositionSequenceContext<'a>>),
    ChainContextual(PosSubtables<'a, PositionChainContext<'a>>),
    /// An extension lookup did not have any subtables
    EmptyExtension,
}

impl<'a> PositionLookup<'a> {
    pub fn lookup_flag(&self) -> LookupFlag {
        self.of_unit_type().lookup_flag()
    }

    /// Different enumerations for GSUB and GPOS
    pub fn lookup_type(&self) -> u16 {
        self.of_unit_type().lookup_type()
    }

    pub fn mark_filtering_set(&self) -> Option<u16> {
        self.of_unit_type().mark_filtering_set()
    }

    /// Return the subtables for this lookup.
    ///
    /// This method handles both extension and non-extension lookups, and saves
    /// the caller needing to dig into the `PositionLookup` enum itself.
    pub fn subtables(&self) -> Result<PositionSubtables<'a>, ReadError> {
        let raw_lookup = self.of_unit_type();
        let offsets = raw_lookup.subtable_offsets();
        let data = raw_lookup.offset_data();
        match raw_lookup.lookup_type() {
            1 => Ok(PositionSubtables::Single(Subtables::new(offsets, data))),
            2 => Ok(PositionSubtables::Pair(Subtables::new(offsets, data))),
            3 => Ok(PositionSubtables::Cursive(Subtables::new(offsets, data))),
            4 => Ok(PositionSubtables::MarkToBase(Subtables::new(offsets, data))),
            5 => Ok(PositionSubtables::MarkToLig(Subtables::new(offsets, data))),
            6 => Ok(PositionSubtables::MarkToMark(Subtables::new(offsets, data))),
            7 => Ok(PositionSubtables::Contextual(Subtables::new(offsets, data))),
            8 => Ok(PositionSubtables::ChainContextual(Subtables::new(
                offsets, data,
            ))),
            9 => {
                // look through subtable offsets to try and find a lookup type.
                // this is robust in the case where the first subtable offset is
                // malformed, but a later one is okay.
                let Some(lookup_type) = offsets.iter().find_map(|off| {
                    off.get()
                        .resolve::<ExtensionPosFormat1<()>>(data)
                        .ok()
                        .map(|ext| ext.extension_lookup_type())
                }) else {
                    return Ok(PositionSubtables::EmptyExtension);
                };

                match lookup_type {
                    1 => Ok(PositionSubtables::Single(Subtables::new_ext(offsets, data))),
                    2 => Ok(PositionSubtables::Pair(Subtables::new_ext(offsets, data))),
                    3 => Ok(PositionSubtables::Cursive(Subtables::new_ext(
                        offsets, data,
                    ))),
                    4 => Ok(PositionSubtables::MarkToBase(Subtables::new_ext(
                        offsets, data,
                    ))),
                    5 => Ok(PositionSubtables::MarkToLig(Subtables::new_ext(
                        offsets, data,
                    ))),
                    6 => Ok(PositionSubtables::MarkToMark(Subtables::new_ext(
                        offsets, data,
                    ))),
                    7 => Ok(PositionSubtables::Contextual(Subtables::new_ext(
                        offsets, data,
                    ))),
                    8 => Ok(PositionSubtables::ChainContextual(Subtables::new_ext(
                        offsets, data,
                    ))),
                    other => Err(ReadError::InvalidFormat(other as _)),
                }
            }
            other => Err(ReadError::InvalidFormat(other as _)),
        }
    }
}

/// Extends the generated pair value records with a binary search.
impl<'a> PairSet<'a> {
    /// Returns the pair value record for `second_glyph`, using a binary search.
    ///
    /// Pair value records are ordered by second glyph, and are located rather
    /// than read, so this reads only the glyph id of each probed record.
    pub fn find_pair_value_record(&self, second_glyph: GlyphId16) -> Option<PairValueRecord<'a>> {
        let records = self.pair_value_records();
        let (mut lo, mut hi) = (0usize, records.len());
        while lo < hi {
            // deliberately not usize::midpoint, which widens to u128; these
            // values are bounded by a u16 count
            #[allow(clippy::manual_midpoint)]
            let mid = (lo + hi) / 2;
            let record = records.get(mid).ok()?;
            match record.second_glyph().cmp(&second_glyph) {
                core::cmp::Ordering::Less => lo = mid + 1,
                core::cmp::Ordering::Greater => hi = mid,
                core::cmp::Ordering::Equal => return Some(record),
            }
        }
        None
    }
}

/// The two-dimensional array of value records in a [`PairPosFormat2`], located
/// but not read.
///
/// The class counts, value formats and record stride are read once when this is
/// built, so addressing a record afterwards is pure arithmetic. Callers walking
/// many class pairs should build this once and reuse it rather than going
/// through [`PairPosFormat2::value_record_refs`], which rebuilds it every call.
#[derive(Copy, Clone)]
pub struct ClassValueRecords<'a> {
    data: FontData<'a>,
    start: u32,
    record_size: u32,
    format1_len: u32,
    class1_count: u16,
    class2_count: u16,
    format1: ValueFormat,
    format2: ValueFormat,
}

impl<'a> ClassValueRecords<'a> {
    /// Number of classes in classDef1, including class 0.
    #[inline]
    pub fn class1_count(&self) -> u16 {
        self.class1_count
    }

    /// Number of classes in classDef2, including class 0.
    #[inline]
    pub fn class2_count(&self) -> u16 {
        self.class2_count
    }

    /// Returns the pair of value records for the given classes.
    ///
    /// Returns `None` if either class is out of range.
    #[inline]
    pub fn get(&self, class1: u16, class2: u16) -> Option<[ValueRecord<'a>; 2]> {
        if class1 >= self.class1_count || class2 >= self.class2_count {
            return None;
        }
        // Compute an offset into the 2D array of positioning records. Every
        // term is bounded by a u16 count times a u16-derived stride, so this
        // cannot overflow usize on any supported target.
        let record_offset = self.start as usize
            + class1 as usize * self.record_size as usize * self.class2_count as usize
            + class2 as usize * self.record_size as usize;
        Some([
            ValueRecord::new(self.data, record_offset, self.format1),
            ValueRecord::new(
                self.data,
                record_offset + self.format1_len as usize,
                self.format2,
            ),
        ])
    }
}

impl<'a> PairPosFormat2<'a> {
    /// Returns the two-dimensional array of class value records, located but
    /// not read.
    pub fn class_value_records(&self) -> ClassValueRecords<'a> {
        let format1 = self.value_format1();
        let format2 = self.value_format2();
        let format1_len = format1.record_byte_len();
        ClassValueRecords {
            data: self.offset_data(),
            start: self.class1_records_byte_range().start as u32,
            record_size: (format1_len + format2.record_byte_len()) as u32,
            format1_len: format1_len as u32,
            class1_count: self.class1_count(),
            class2_count: self.class2_count(),
            format1,
            format2,
        }
    }

    /// Returns the pair of value records for the given classes, located but
    /// not read.
    ///
    /// Returns `None` if either class is out of range. When reading more than
    /// one class pair, prefer [`class_value_records`][Self::class_value_records],
    /// which reads the table's counts and formats only once.
    #[inline]
    pub fn value_record_refs(&self, class1: u16, class2: u16) -> Option<[ValueRecord<'a>; 2]> {
        self.class_value_records().get(class1, class2)
    }
}

impl<'a> PairPosFormat4<'a> {
    /// Returns the two-dimensional array of class value records, located but
    /// not read.
    pub fn class_value_records(&self) -> ClassValueRecords<'a> {
        let format1 = self.value_format1();
        let format2 = self.value_format2();
        let format1_len = format1.record_byte_len();
        ClassValueRecords {
            data: self.offset_data(),
            start: self.class1_records_byte_range().start as u32,
            record_size: (format1_len + format2.record_byte_len()) as u32,
            format1_len: format1_len as u32,
            class1_count: self.class1_count(),
            class2_count: self.class2_count(),
            format1,
            format2,
        }
    }

    /// Returns the pair of value records for the given classes, located but
    /// not read.
    ///
    /// Returns `None` if either class is out of range. When reading more than
    /// one class pair, prefer [`class_value_records`][Self::class_value_records],
    /// which reads the table's counts and formats only once.
    #[inline]
    pub fn value_record_refs(&self, class1: u16, class2: u16) -> Option<[ValueRecord<'a>; 2]> {
        self.class_value_records().get(class1, class2)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A value record is located, not read, so two ways of arriving at the
    /// same record must land on the same bytes.
    fn assert_same_record(a: ValueRecord, b: ValueRecord) {
        assert_eq!(a.format(), b.format());
        assert_eq!(a.bytes(), b.bytes());
        assert_eq!(a, b);
    }

    /// `class_value_records` reads the counts and formats once and addresses
    /// the 2D array arithmetically; walking `class1_records` reads them per
    /// row. Both must reach the same records.
    #[test]
    fn pair_pos2_hoisted_matches_nested() {
        let data = FontData::new(font_test_data::gpos::PAIRPOSFORMAT2);
        let table = PairPosFormat2::read(data).unwrap();
        let class1_count = table.class1_count();
        let class2_count = table.class2_count();
        assert!(class1_count > 0 && class2_count > 0);

        let hoisted = table.class_value_records();
        let rows = table.class1_records();
        for class1 in 0..class1_count {
            let row = rows.get(class1 as usize).unwrap();
            let cells = row.class2_records();
            for class2 in 0..class2_count {
                let cell = cells.get(class2 as usize).unwrap();
                let [a, b] = hoisted.get(class1, class2).unwrap();
                assert_same_record(a, cell.value_record1);
                assert_same_record(b, cell.value_record2);
            }
        }
        assert!(hoisted.get(class1_count, 0).is_none());
        assert!(hoisted.get(0, class2_count).is_none());
    }

    /// The binary search must find exactly what a linear scan finds.
    #[test]
    fn pair_set_find_matches_scan() {
        let data = FontData::new(font_test_data::gpos::PAIRPOSFORMAT1);
        let table = PairPosFormat1::read(data).unwrap();
        let mut seen = 0;
        for set_offset in table.pair_set_offsets() {
            let pair_set = set_offset
                .get()
                .resolve_with_args::<PairSet>(data, (table.value_format1(), table.value_format2()))
                .unwrap();
            let records = pair_set.pair_value_records();
            assert!(!records.is_empty());
            for i in 0..records.len() {
                let want = records.get(i).unwrap();
                let found = pair_set
                    .find_pair_value_record(want.second_glyph())
                    .unwrap();
                assert_eq!(found.second_glyph(), want.second_glyph());
                assert_same_record(found.value_record1, want.value_record1);
                assert_same_record(found.value_record2, want.value_record2);
                seen += 1;
            }
            assert!(pair_set
                .find_pair_value_record(GlyphId16::new(0xFFFF))
                .is_none());
        }
        assert!(seen > 0);
    }

    /// Device offsets in a value record resolve against the table containing
    /// the record, so a located record must carry that table's data.
    #[test]
    fn value_record_resolves_devices_against_its_table() {
        let data = FontData::new(font_test_data::gpos::VALUEFORMATTABLE);
        let table = SinglePosFormat1::read(data).unwrap();
        let record = table.value_record();
        assert!(record
            .format()
            .intersects(ValueFormat::ANY_DEVICE_OR_VARIDX));
        // the offsets are measured from the start of the table, not the record,
        // which begins six bytes in
        assert!(record.offset() > 0);
        assert!(record.x_placement_device().unwrap().is_ok());
        assert!(record.y_advance_device().unwrap().is_ok());
    }

    #[test]
    fn single_pos2_records_are_evenly_spaced() {
        let data = FontData::new(font_test_data::gpos::SINGLEPOSFORMAT2);
        let table = SinglePosFormat2::read(data).unwrap();
        let records = table.value_records();
        let stride = table.value_format().record_byte_len();
        assert!(records.len() > 1);
        let first = records.get(0).unwrap();
        for i in 0..records.len() {
            let rec = records.get(i).unwrap();
            assert_eq!(rec.offset(), first.offset() + i * stride);
            assert_eq!(rec.format(), table.value_format());
        }
        assert!(records.get(records.len()).is_err());
    }

    #[test]
    fn default_for_generics() {
        let ExtensionSubtable::Single(inner) = ExtensionSubtable::default() else {
            panic!("this is quite bad");
        };

        // this is invalid, but we the default impl for the extension offset
        // will be the first variant of the enum anyway
        assert_eq!(inner.extension_lookup_type(), 0);

        let SinglePos::Format1(_hmm) = inner.extension().unwrap_or_default() else {
            panic!("unexpected");
        };
    }
}