ttf_parser/tables/
gvar.rs

1//! A [Glyph Variations Table](
2//! https://docs.microsoft.com/en-us/typography/opentype/spec/gvar) implementation.
3
4// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuple-variation-store
5
6use core::cmp;
7use core::convert::TryFrom;
8use core::num::NonZeroU16;
9
10use crate::{GlyphId, OutlineBuilder, Rect, BBox, NormalizedCoordinate};
11use crate::parser::{Stream, Offset, Offset16, Offset32, LazyArray16, F2DOT14};
12use crate::glyf::{self, Transform};
13
14/// 'The TrueType rasterizer dynamically generates 'phantom' points for each glyph
15/// that represent horizontal and vertical advance widths and side bearings,
16/// and the variation data within the `gvar` table includes data for these phantom points.'
17///
18/// We don't actually use them, but they are required during deltas parsing.
19const PHANTOM_POINTS_LEN: usize = 4;
20
21#[derive(Clone, Copy)]
22enum GlyphVariationDataOffsets<'a> {
23    Short(LazyArray16<'a, Offset16>),
24    Long(LazyArray16<'a, Offset32>),
25}
26
27
28#[derive(Clone, Copy, Default, Debug)]
29struct PointAndDelta {
30    x: i16,
31    y: i16,
32    x_delta: f32,
33    y_delta: f32,
34}
35
36
37// This structure will be used by the `VariationTuples` stack buffer,
38// so it has to be as small as possible.
39#[derive(Clone, Copy, Default)]
40struct VariationTuple<'a> {
41    set_points: Option<SetPointsIter<'a>>,
42    deltas: PackedDeltasIter<'a>,
43    /// The last parsed point with delta in the contour.
44    /// Used during delta resolving.
45    prev_point: Option<PointAndDelta>,
46}
47
48
49/// The maximum number of variation tuples stored on the stack.
50///
51/// The TrueType spec allows up to 4095 tuples, which is way larger
52/// than we do. But in reality, an average font will have less than 10 tuples.
53/// We can avoid heap allocations if the number of tuples is less than this number.
54const MAX_STACK_TUPLES_LEN: u16 = 32;
55
56/// A list of variation tuples, possibly stored on the heap.
57///
58/// This is the only part of the `gvar` algorithm that actually allocates a data.
59/// This is probably unavoidable due to `gvar` structure,
60/// since we have to iterate all tuples in parallel.
61enum VariationTuples<'a> {
62    Stack {
63        headers: [VariationTuple<'a>; MAX_STACK_TUPLES_LEN as usize],
64        len: u16
65    },
66    #[cfg(feature = "gvar-alloc")]
67    Heap {
68        vec: std::vec::Vec<VariationTuple<'a>>
69    }
70}
71
72impl<'a> Default for VariationTuples<'a> {
73    fn default() -> Self {
74        Self::Stack { headers: [VariationTuple::default(); MAX_STACK_TUPLES_LEN as usize], len: 0 }
75    }
76}
77
78impl<'a> VariationTuples<'a> {
79    /// Attempt to reserve up to `capacity` total slots for variation tuples.
80    #[cfg(feature = "gvar-alloc")]
81    fn reserve(&mut self, capacity: u16) -> bool {
82        // If the requested capacity exceeds the configured maximum stack tuple size ...
83        if capacity > MAX_STACK_TUPLES_LEN {
84            // ... and we're currently on the stack, move to the heap.
85            if let Self::Stack { headers, len } = self {
86                let mut vec = std::vec::Vec::with_capacity(capacity as usize);
87                for header in headers.iter_mut().take(*len as usize) {
88                    let header = core::mem::take(header);
89                    vec.push(header);
90                }
91
92                *self = Self::Heap { vec };
93                return true;
94            }
95        }
96
97        // Otherwise ...
98        match self {
99            // ... extend the vec capacity to hold our new elements ...
100            Self::Heap { vec } if vec.len() < capacity as usize => {
101                vec.reserve(capacity as usize - vec.len());
102                true
103            }
104            // ... or do nothing if the vec is already large enough or we're on the stack.
105            _ => true
106        }
107    }
108
109    /// Attempt to reserve up to `capacity` total slots for variation tuples.
110    #[cfg(not(feature = "gvar-alloc"))]
111    fn reserve(&mut self, capacity: u16) -> bool {
112        capacity <= MAX_STACK_TUPLES_LEN
113    }
114
115    /// Get the number of tuples stored in the structure.
116    #[cfg_attr(not(feature = "gvar-alloc"), allow(dead_code))]
117    fn len(&self) -> u16 {
118        match self {
119            Self::Stack { len, .. } => *len,
120            #[cfg(feature = "gvar-alloc")]
121            Self::Heap { vec } => vec.len() as u16
122        }
123    }
124
125    /// Append a new tuple header to the list.
126    /// This may panic if the list can't hold a new header.
127    #[cfg(feature = "gvar-alloc")]
128    fn push(&mut self, header: VariationTuple<'a>) {
129        // Reserve space for the new element.
130        // This may fail and result in a later panic, but that matches pre-heap behavior.
131        self.reserve(self.len() + 1);
132
133        match self {
134            Self::Stack { headers, len } => {
135                headers[usize::from(*len)] = header;
136                *len += 1;
137            },
138            Self::Heap { vec } => vec.push(header)
139        }
140    }
141    
142    /// Append a new tuple header to the list.
143    /// This may panic if the list can't hold a new header.
144    #[cfg(not(feature = "gvar-alloc"))]
145    #[inline]
146    fn push(&mut self, header: VariationTuple<'a>) {
147        match self {
148            Self::Stack { headers, len } => {
149                headers[usize::from(*len)] = header;
150                *len += 1;
151            }
152        }
153    }
154
155    /// Remove all tuples from the structure.
156    fn clear(&mut self) {
157        match self {
158            Self::Stack { len, .. } => *len = 0,
159            #[cfg(feature = "gvar-alloc")]
160            Self::Heap { vec } => vec.clear()
161        }
162    }
163
164    #[inline]
165    fn as_mut_slice(&mut self) -> &mut [VariationTuple<'a>] {
166        match self {
167            Self::Stack { headers, len } => &mut headers[0..usize::from(*len)],
168            #[cfg(feature = "gvar-alloc")]
169            Self::Heap { vec } => vec.as_mut_slice()
170        }
171    }
172
173    fn apply(
174        &mut self,
175        all_points: glyf::GlyphPointsIter,
176        points: glyf::GlyphPointsIter,
177        point: glyf::GlyphPoint,
178    ) -> Option<(f32, f32)> {
179        let mut x = f32::from(point.x);
180        let mut y = f32::from(point.y);
181
182        for tuple in self.as_mut_slice() {
183            if let Some(ref mut set_points) = tuple.set_points {
184                if set_points.next()? {
185                    if let Some((x_delta, y_delta)) = tuple.deltas.next() {
186                        // Remember the last set point and delta.
187                        tuple.prev_point = Some(PointAndDelta {
188                            x: point.x, y: point.y, x_delta, y_delta
189                        });
190
191                        x += x_delta;
192                        y += y_delta;
193                    } else {
194                        // If there are no more deltas, we have to resolve them manually.
195                        let set_points = set_points.clone();
196                        let (x_delta, y_delta) = infer_deltas(
197                            tuple, set_points, points.clone(), all_points.clone(), point
198                        );
199
200                        x += x_delta;
201                        y += y_delta;
202                    }
203                } else {
204                    // Point is not referenced, so we have to resolve it.
205                    let set_points = set_points.clone();
206                    let (x_delta, y_delta) = infer_deltas(
207                        tuple, set_points, points.clone(), all_points.clone(), point
208                    );
209
210                    x += x_delta;
211                    y += y_delta;
212                }
213
214                if point.last_point {
215                    tuple.prev_point = None;
216                }
217            } else {
218                if let Some((x_delta, y_delta)) = tuple.deltas.next() {
219                    x += x_delta;
220                    y += y_delta;
221                }
222            }
223        }
224
225        Some((x, y))
226    }
227
228    // This is just like `apply()`, but without `infer_deltas`,
229    // since we use it only for component points and not a contour.
230    // And since there are no contour and no points, `infer_deltas()` will do nothing.
231    fn apply_null(&mut self) -> Option<(f32, f32)> {
232        let mut x = 0.0;
233        let mut y = 0.0;
234
235        for tuple in self.as_mut_slice() {
236            if let Some(ref mut set_points) = tuple.set_points {
237                if set_points.next()? {
238                    if let Some((x_delta, y_delta)) = tuple.deltas.next() {
239                        x += x_delta;
240                        y += y_delta;
241                    }
242                }
243            } else {
244                if let Some((x_delta, y_delta)) = tuple.deltas.next() {
245                    x += x_delta;
246                    y += y_delta;
247                }
248            }
249        }
250
251        Some((x, y))
252    }
253}
254
255
256#[derive(Clone, Copy, Default, Debug)]
257struct TupleVariationHeaderData {
258    scalar: f32,
259    has_private_point_numbers: bool,
260    serialized_data_len: u16,
261}
262
263
264// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuplevariationheader
265fn parse_variation_tuples<'a>(
266    count: u16,
267    coordinates: &[NormalizedCoordinate],
268    shared_tuple_records: &LazyArray16<F2DOT14>,
269    shared_point_numbers: Option<PackedPointsIter<'a>>,
270    points_len: u16,
271    mut main_s: Stream<'a>,
272    mut serialized_s: Stream<'a>,
273    tuples: &mut VariationTuples<'a>,
274) -> Option<()> {
275    debug_assert!(core::mem::size_of::<VariationTuple>() <= 80);
276
277    // `TupleVariationHeader` has a variable size, so we cannot use a `LazyArray`.
278    for _ in 0..count {
279        let header = parse_tuple_variation_header(coordinates, shared_tuple_records, &mut main_s)?;
280        if !(header.scalar > 0.0) {
281            // Serialized data for headers with non-positive scalar should be skipped.
282            serialized_s.advance(usize::from(header.serialized_data_len));
283            continue;
284        }
285
286        let serialized_data_start = serialized_s.offset();
287
288        // Resolve point numbers source.
289        let point_numbers = if header.has_private_point_numbers {
290            PackedPointsIter::new(&mut serialized_s)?
291        } else {
292            shared_point_numbers.clone()
293        };
294
295        // TODO: this
296        // Since the packed representation can include zero values,
297        // it is possible for a given point number to be repeated in the derived point number list.
298        // In that case, there will be multiple delta values in the deltas data
299        // associated with that point number. All of these deltas must be applied
300        // cumulatively to the given point.
301
302        let deltas_count = if let Some(point_numbers) = point_numbers.clone() {
303            u16::try_from(point_numbers.clone().count()).ok()?
304        } else {
305            points_len
306        };
307
308        let deltas = {
309            // Use `checked_sub` in case we went over the `serialized_data_len`.
310            let left = usize::from(header.serialized_data_len)
311                .checked_sub(serialized_s.offset() - serialized_data_start)?;
312            let deltas_data = serialized_s.read_bytes(left)?;
313            PackedDeltasIter::new(header.scalar, deltas_count, deltas_data)
314        };
315
316        let tuple = VariationTuple {
317            set_points: point_numbers.map(SetPointsIter::new),
318            deltas,
319            prev_point: None,
320        };
321
322        tuples.push(tuple);
323    }
324
325    Some(())
326}
327
328// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuplevariationheader
329fn parse_tuple_variation_header(
330    coordinates: &[NormalizedCoordinate],
331    shared_tuple_records: &LazyArray16<F2DOT14>,
332    s: &mut Stream,
333) -> Option<TupleVariationHeaderData> {
334    const EMBEDDED_PEAK_TUPLE_FLAG: u16 = 0x8000;
335    const INTERMEDIATE_REGION_FLAG: u16 = 0x4000;
336    const PRIVATE_POINT_NUMBERS_FLAG: u16 = 0x2000;
337    const TUPLE_INDEX_MASK: u16 = 0x0FFF;
338
339    let serialized_data_size = s.read::<u16>()?;
340    let tuple_index = s.read::<u16>()?;
341
342    let has_embedded_peak_tuple = tuple_index & EMBEDDED_PEAK_TUPLE_FLAG != 0;
343    let has_intermediate_region = tuple_index & INTERMEDIATE_REGION_FLAG != 0;
344    let has_private_point_numbers = tuple_index & PRIVATE_POINT_NUMBERS_FLAG != 0;
345    let tuple_index = tuple_index & TUPLE_INDEX_MASK;
346
347    let axis_count = coordinates.len() as u16;
348
349    let peak_tuple = if has_embedded_peak_tuple {
350        s.read_array16::<F2DOT14>(axis_count)?
351    } else {
352        // Use shared tuples.
353        let start = tuple_index.checked_mul(axis_count)?;
354        let end = start.checked_add(axis_count)?;
355        shared_tuple_records.slice(start..end)?
356    };
357
358    let (start_tuple, end_tuple) = if has_intermediate_region {
359        (s.read_array16::<F2DOT14>(axis_count)?, s.read_array16::<F2DOT14>(axis_count)?)
360    } else {
361        (LazyArray16::<F2DOT14>::default(), LazyArray16::<F2DOT14>::default())
362    };
363
364    let mut header = TupleVariationHeaderData {
365        scalar: 0.0,
366        has_private_point_numbers,
367        serialized_data_len: serialized_data_size,
368    };
369
370    // Calculate the scalar value according to the pseudo-code described at:
371    // https://docs.microsoft.com/en-us/typography/opentype/spec/otvaroverview#algorithm-for-interpolation-of-instance-values
372    let mut scalar = 1.0;
373    for i in 0..axis_count {
374        let v = coordinates[usize::from(i)].get();
375        let peak = peak_tuple.get(i)?.0;
376        if peak == 0 || v == peak {
377            continue;
378        }
379
380        if has_intermediate_region {
381            let start = start_tuple.get(i)?.0;
382            let end = end_tuple.get(i)?.0;
383            if start > peak || peak > end || (start < 0 && end > 0 && peak != 0) {
384                continue;
385            }
386
387            if v < start || v > end {
388                return Some(header);
389            }
390
391            if v < peak {
392                if peak != start {
393                    scalar *= f32::from(v - start) / f32::from(peak - start);
394                }
395            } else {
396                if peak != end {
397                    scalar *= f32::from(end - v) / f32::from(end - peak);
398                }
399            }
400        } else if v == 0 || v < cmp::min(0, peak) || v > cmp::max(0, peak) {
401            // 'If the instance coordinate is out of range for some axis, then the
402            // region and its associated deltas are not applicable.'
403            return Some(header);
404        } else {
405            scalar *= f32::from(v) / f32::from(peak);
406        }
407    }
408
409    header.scalar = scalar;
410    Some(header)
411}
412
413
414// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#packed-point-numbers
415mod packed_points {
416    use crate::parser::{Stream, FromData};
417
418    struct Control(u8);
419
420    impl Control {
421        const POINTS_ARE_WORDS_FLAG: u8 = 0x80;
422        const POINT_RUN_COUNT_MASK: u8 = 0x7F;
423
424        #[inline]
425        fn is_points_are_words(&self) -> bool { self.0 & Self::POINTS_ARE_WORDS_FLAG != 0 }
426
427        // 'Mask for the low 7 bits to provide the number of point values in the run, minus one.'
428        // So we have to add 1.
429        // It will never overflow because of a mask.
430        #[inline]
431        fn run_count(&self) -> u8 { (self.0 & Self::POINT_RUN_COUNT_MASK) + 1 }
432    }
433
434    impl FromData for Control {
435        const SIZE: usize = 1;
436
437        #[inline]
438        fn parse(data: &[u8]) -> Option<Self> { data.get(0).copied().map(Control) }
439    }
440
441
442    #[derive(Clone, Copy, PartialEq)]
443    enum State {
444        Control,
445        ShortPoint,
446        LongPoint,
447    }
448
449    // This structure will be used by the `VariationTuples` stack buffer,
450    // so it has to be as small as possible.
451    // Therefore we cannot use `Stream` and other abstractions.
452    #[derive(Clone, Copy)]
453    pub struct PackedPointsIter<'a> {
454        data: &'a [u8],
455        // u16 is enough, since the maximum number of points is 32767.
456        offset: u16,
457        state: State,
458        points_left: u8,
459    }
460
461    impl<'a> PackedPointsIter<'a> {
462        // The first Option::None indicates a parsing error.
463        // The second Option::None indicates "no points".
464        pub fn new<'b>(s: &'b mut Stream<'a>) -> Option<Option<Self>> {
465            // The total amount of points can be set as one or two bytes
466            // depending on the first bit.
467            let b1 = s.read::<u8>()?;
468            let mut count = u16::from(b1);
469            if b1 & Control::POINTS_ARE_WORDS_FLAG != 0 {
470                let b2 = s.read::<u8>()?;
471                count = (u16::from(b1 & Control::POINT_RUN_COUNT_MASK) << 8) | u16::from(b2);
472            }
473
474            if count == 0 {
475                // No points is not an error.
476                return Some(None);
477            }
478
479            let start = s.offset();
480            let tail = s.tail()?;
481
482            // The actual packed points data size is not stored,
483            // so we have to parse the points first to advance the provided stream.
484            // Since deltas will be right after points.
485            let mut i = 0;
486            while i < count {
487                let control = s.read::<Control>()?;
488                let run_count = u16::from(control.run_count());
489                let is_points_are_words = control.is_points_are_words();
490                // Do not actually parse the number, simply advance.
491                s.advance_checked(if is_points_are_words { 2 } else { 1 } * usize::from(run_count))?;
492                i += run_count;
493            }
494
495            if i == 0 {
496                // No points is not an error.
497                return Some(None);
498            }
499
500            if i > count {
501                // Malformed font.
502                return None;
503            }
504
505            // Check that points data size is smaller than the storage type
506            // used by the iterator.
507            let data_len = s.offset() - start;
508            if data_len > usize::from(core::u16::MAX) {
509                return None;
510            }
511
512            Some(Some(PackedPointsIter {
513                data: &tail[0..data_len],
514                offset: 0,
515                state: State::Control,
516                points_left: 0,
517            }))
518        }
519    }
520
521    impl<'a> Iterator for PackedPointsIter<'a> {
522        type Item = u16;
523
524        fn next(&mut self) -> Option<Self::Item> {
525            if usize::from(self.offset) >= self.data.len() {
526                return None;
527            }
528
529            if self.state == State::Control {
530                let control = Control(self.data[usize::from(self.offset)]);
531                self.offset += 1;
532
533                self.points_left = control.run_count();
534                self.state = if control.is_points_are_words() {
535                    State::LongPoint
536                } else {
537                    State::ShortPoint
538                };
539
540                self.next()
541            } else {
542                let mut s = Stream::new_at(self.data, usize::from(self.offset))?;
543                let point = if self.state == State::LongPoint {
544                    self.offset += 2;
545                    s.read::<u16>()?
546                } else {
547                    self.offset += 1;
548                    u16::from(s.read::<u8>()?)
549                };
550
551                self.points_left -= 1;
552                if self.points_left == 0 {
553                    self.state = State::Control;
554                }
555
556                Some(point)
557            }
558        }
559    }
560
561
562    // The `PackedPointsIter` will return referenced point numbers as deltas.
563    // i.e. 1 2 4 is actually 1 3 7
564    // But this is not very useful in our current algorithm,
565    // so we will convert it once again into:
566    // false true false true false false false true
567    // This way we can iterate glyph points and point numbers in parallel.
568    #[derive(Clone, Copy)]
569    pub struct SetPointsIter<'a> {
570        iter: PackedPointsIter<'a>,
571        unref_count: u16,
572    }
573
574    impl<'a> SetPointsIter<'a> {
575        #[inline]
576        pub fn new(mut iter: PackedPointsIter<'a>) -> Self {
577            let unref_count = iter.next().unwrap_or(0);
578            SetPointsIter { iter, unref_count }
579        }
580
581        #[inline]
582        pub fn restart(self) -> Self {
583            let mut iter = self.iter.clone();
584            iter.offset = 0;
585            iter.state = State::Control;
586            iter.points_left = 0;
587
588            let unref_count = iter.next().unwrap_or(0);
589            SetPointsIter { iter, unref_count }
590        }
591    }
592
593    impl<'a> Iterator for SetPointsIter<'a> {
594        type Item = bool;
595
596        #[inline]
597        fn next(&mut self) -> Option<Self::Item> {
598            if self.unref_count != 0 {
599                self.unref_count -= 1;
600                return Some(false);
601            }
602
603            if let Some(unref_count) = self.iter.next() {
604                self.unref_count = unref_count;
605                if self.unref_count != 0 {
606                    self.unref_count -= 1;
607                }
608            }
609
610            // Iterator will be returning `Some(true)` after "finished".
611            // This is because this iterator will be zipped with the `glyf::GlyphPointsIter`
612            // and the number of glyph points can be larger than the amount of set points.
613            // Anyway, this is a non-issue in a well-formed font.
614            Some(true)
615        }
616    }
617
618
619    #[cfg(test)]
620    mod tests {
621        use super::*;
622
623        struct NewControl {
624            deltas_are_words: bool,
625            run_count: u8,
626        }
627
628        fn gen_control(control: NewControl) -> u8 {
629            assert!(control.run_count > 0, "run count cannot be zero");
630
631            let mut n = 0;
632            if control.deltas_are_words { n |= 0x80; }
633            n |= (control.run_count - 1) & 0x7F;
634            n
635        }
636
637        #[test]
638        fn empty() {
639            let mut s = Stream::new(&[]);
640            assert!(PackedPointsIter::new(&mut s).is_none());
641        }
642
643        #[test]
644        fn single_zero_control() {
645            let mut s = Stream::new(&[0]);
646            assert!(PackedPointsIter::new(&mut s).unwrap().is_none());
647        }
648
649        #[test]
650        fn single_point() {
651            let data = vec![
652                1, // total count
653                gen_control(NewControl { deltas_are_words: false, run_count: 1 }),
654                1
655            ];
656
657            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
658            let mut iter = SetPointsIter::new(points_iter);
659            assert_eq!(iter.next().unwrap(), false);
660            assert_eq!(iter.next().unwrap(), true);
661            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
662        }
663
664        #[test]
665        fn set_0_and_2() {
666            let data = vec![
667                2, // total count
668                gen_control(NewControl { deltas_are_words: false, run_count: 2 }),
669                0, 2
670            ];
671
672            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
673            let mut iter = SetPointsIter::new(points_iter);
674            assert_eq!(iter.next().unwrap(), true);
675            assert_eq!(iter.next().unwrap(), false);
676            assert_eq!(iter.next().unwrap(), true);
677            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
678        }
679
680        #[test]
681        fn set_1_and_2() {
682            let data = vec![
683                2, // total count
684                gen_control(NewControl { deltas_are_words: false, run_count: 2 }),
685                1, 1
686            ];
687
688            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
689            let mut iter = SetPointsIter::new(points_iter);
690            assert_eq!(iter.next().unwrap(), false);
691            assert_eq!(iter.next().unwrap(), true);
692            assert_eq!(iter.next().unwrap(), true);
693            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
694        }
695
696        #[test]
697        fn set_1_and_3() {
698            let data = vec![
699                2, // total count
700                gen_control(NewControl { deltas_are_words: false, run_count: 2 }),
701                1, 2
702            ];
703
704            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
705            let mut iter = SetPointsIter::new(points_iter);
706            assert_eq!(iter.next().unwrap(), false);
707            assert_eq!(iter.next().unwrap(), true);
708            assert_eq!(iter.next().unwrap(), false);
709            assert_eq!(iter.next().unwrap(), true);
710            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
711        }
712
713        #[test]
714        fn set_2_5_7() {
715            let data = vec![
716                3, // total count
717                gen_control(NewControl { deltas_are_words: false, run_count: 3 }),
718                2, 3, 2
719            ];
720
721            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
722            let mut iter = SetPointsIter::new(points_iter);
723            assert_eq!(iter.next().unwrap(), false);
724            assert_eq!(iter.next().unwrap(), false);
725            assert_eq!(iter.next().unwrap(), true);
726            assert_eq!(iter.next().unwrap(), false);
727            assert_eq!(iter.next().unwrap(), false);
728            assert_eq!(iter.next().unwrap(), true);
729            assert_eq!(iter.next().unwrap(), false);
730            assert_eq!(iter.next().unwrap(), true);
731            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
732        }
733
734        #[test]
735        fn more_than_127_points() {
736            let mut data = vec![];
737            // total count
738            data.push(Control::POINTS_ARE_WORDS_FLAG);
739            data.push(150);
740
741            data.push(gen_control(NewControl { deltas_are_words: false, run_count: 100 }));
742            for _ in 0..100 {
743                data.push(2);
744            }
745            data.push(gen_control(NewControl { deltas_are_words: false, run_count: 50 }));
746            for _ in 0..50 {
747                data.push(2);
748            }
749
750            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
751            let mut iter = SetPointsIter::new(points_iter);
752            assert_eq!(iter.next().unwrap(), false);
753            for _ in 0..150 {
754                assert_eq!(iter.next().unwrap(), false);
755                assert_eq!(iter.next().unwrap(), true);
756            }
757            assert_eq!(iter.next().unwrap(), true);
758            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
759        }
760
761        #[test]
762        fn long_points() {
763            let data = vec![
764                2, // total count
765                gen_control(NewControl { deltas_are_words: true, run_count: 2 }),
766                0, 2, 0, 3
767            ];
768
769            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
770            let mut iter = SetPointsIter::new(points_iter);
771            assert_eq!(iter.next().unwrap(), false);
772            assert_eq!(iter.next().unwrap(), false);
773            assert_eq!(iter.next().unwrap(), true);
774            assert_eq!(iter.next().unwrap(), false);
775            assert_eq!(iter.next().unwrap(), false);
776            assert_eq!(iter.next().unwrap(), true);
777            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
778        }
779
780        #[test]
781        fn multiple_runs() {
782            let data = vec![
783                5, // total count
784                gen_control(NewControl { deltas_are_words: true, run_count: 2 }),
785                0, 2, 0, 3,
786                gen_control(NewControl { deltas_are_words: false, run_count: 3 }),
787                2, 3, 2
788            ];
789
790            let points_iter = PackedPointsIter::new(&mut Stream::new(&data)).unwrap().unwrap();
791            let mut iter = SetPointsIter::new(points_iter);
792            assert_eq!(iter.next().unwrap(), false);
793            assert_eq!(iter.next().unwrap(), false);
794            assert_eq!(iter.next().unwrap(), true);
795            assert_eq!(iter.next().unwrap(), false);
796            assert_eq!(iter.next().unwrap(), false);
797            assert_eq!(iter.next().unwrap(), true);
798            assert_eq!(iter.next().unwrap(), false);
799            assert_eq!(iter.next().unwrap(), true);
800            assert_eq!(iter.next().unwrap(), false);
801            assert_eq!(iter.next().unwrap(), false);
802            assert_eq!(iter.next().unwrap(), true);
803            assert_eq!(iter.next().unwrap(), false);
804            assert_eq!(iter.next().unwrap(), true);
805            assert_eq!(iter.next().unwrap(), true); // Endlessly true.
806        }
807
808        #[test]
809        fn runs_overflow() {
810            // TrueType allows up to 32767 points.
811            let data = vec![0xFF; 0xFFFF * 2];
812            assert!(PackedPointsIter::new(&mut Stream::new(&data)).is_none());
813        }
814    }
815}
816
817use packed_points::*;
818
819
820// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#packed-deltas
821mod packed_deltas {
822    use crate::parser::Stream;
823
824    struct Control(u8);
825
826    impl Control {
827        const DELTAS_ARE_ZERO_FLAG: u8 = 0x80;
828        const DELTAS_ARE_WORDS_FLAG: u8 = 0x40;
829        const DELTA_RUN_COUNT_MASK: u8 = 0x3F;
830
831        #[inline]
832        fn is_deltas_are_zero(&self) -> bool { self.0 & Self::DELTAS_ARE_ZERO_FLAG != 0 }
833
834        #[inline]
835        fn is_deltas_are_words(&self) -> bool { self.0 & Self::DELTAS_ARE_WORDS_FLAG != 0 }
836
837        // 'Mask for the low 6 bits to provide the number of delta values in the run, minus one.'
838        // So we have to add 1.
839        // It will never overflow because of a mask.
840        #[inline]
841        fn run_count(&self) -> u8 { (self.0 & Self::DELTA_RUN_COUNT_MASK) + 1 }
842    }
843
844
845    #[derive(Clone, Copy, PartialEq, Debug)]
846    enum State {
847        Control,
848        ZeroDelta,
849        ShortDelta,
850        LongDelta,
851    }
852
853    impl Default for State {
854        #[inline]
855        fn default() -> Self {
856            State::Control
857        }
858    }
859
860
861    #[derive(Clone, Copy, Default)]
862    struct RunState {
863        data_offset: u16,
864        state: State,
865        run_deltas_left: u8,
866    }
867
868    impl RunState {
869        fn next(&mut self, data: &[u8], scalar: f32) -> Option<f32> {
870            if self.state == State::Control {
871                if usize::from(self.data_offset) == data.len() {
872                    return None;
873                }
874
875                let control = Control(Stream::read_at::<u8>(data, usize::from(self.data_offset))?);
876                self.data_offset += 1;
877
878                self.run_deltas_left = control.run_count();
879                self.state = if control.is_deltas_are_zero() {
880                    State::ZeroDelta
881                } else if control.is_deltas_are_words() {
882                    State::LongDelta
883                } else {
884                    State::ShortDelta
885                };
886
887                self.next(data, scalar)
888            } else {
889                let mut s = Stream::new_at(data, usize::from(self.data_offset))?;
890                let delta = if self.state == State::LongDelta {
891                    self.data_offset += 2;
892                    f32::from(s.read::<i16>()?) * scalar
893                } else if self.state == State::ZeroDelta {
894                    0.0
895                } else {
896                    self.data_offset += 1;
897                    f32::from(s.read::<i8>()?) * scalar
898                };
899
900                self.run_deltas_left -= 1;
901                if self.run_deltas_left == 0 {
902                    self.state = State::Control;
903                }
904
905                Some(delta)
906            }
907        }
908    }
909
910
911    // This structure will be used by the `VariationTuples` stack buffer,
912    // so it has to be as small as possible.
913    // Therefore we cannot use `Stream` and other abstractions.
914    #[derive(Clone, Copy, Default)]
915    pub struct PackedDeltasIter<'a> {
916        data: &'a [u8],
917        x_run: RunState,
918        y_run: RunState,
919
920        /// A total number of deltas per axis.
921        ///
922        /// Required only by restart()
923        total_count: u16,
924
925        scalar: f32,
926    }
927
928    impl<'a> PackedDeltasIter<'a> {
929        /// `count` indicates a number of delta pairs.
930        pub fn new(scalar: f32, count: u16, data: &'a [u8]) -> Self {
931            debug_assert!(core::mem::size_of::<PackedDeltasIter>() <= 32);
932
933            let mut iter = PackedDeltasIter {
934                data,
935                total_count: count,
936                scalar,
937                ..PackedDeltasIter::default()
938            };
939
940            // 'The packed deltas are arranged with all of the deltas for X coordinates first,
941            // followed by the deltas for Y coordinates.'
942            // So we have to skip X deltas in the Y deltas iterator.
943            //
944            // Note that Y deltas doesn't necessarily start with a Control byte
945            // and can actually start in the middle of the X run.
946            // So we can't simply split the input data in half
947            // and process those chunks separately.
948            for _ in 0..count {
949                iter.y_run.next(data, scalar);
950            }
951
952            iter
953        }
954
955        #[inline]
956        pub fn restart(self) -> Self {
957            PackedDeltasIter::new(self.scalar, self.total_count, self.data)
958        }
959
960        #[inline]
961        pub fn next(&mut self) -> Option<(f32, f32)> {
962            let x = self.x_run.next(self.data, self.scalar)?;
963            let y = self.y_run.next(self.data, self.scalar)?;
964            Some((x, y))
965        }
966    }
967
968    #[cfg(test)]
969    mod tests {
970        use super::*;
971
972        struct NewControl {
973            deltas_are_zero: bool,
974            deltas_are_words: bool,
975            run_count: u8,
976        }
977
978        fn gen_control(control: NewControl) -> u8 {
979            assert!(control.run_count > 0, "run count cannot be zero");
980
981            let mut n = 0;
982            if control.deltas_are_zero  { n |= 0x80; }
983            if control.deltas_are_words { n |= 0x40; }
984            n |= (control.run_count - 1) & 0x3F;
985            n
986        }
987
988        #[test]
989        fn empty() {
990            let mut iter = PackedDeltasIter::new(1.0, 1, &[]);
991            assert!(iter.next().is_none());
992        }
993
994        #[test]
995        fn single_delta() {
996            let data = vec![
997                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
998                2, 3
999            ];
1000
1001            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1002            assert_eq!(iter.next().unwrap(), (2.0, 3.0));
1003            assert!(iter.next().is_none());
1004        }
1005
1006        #[test]
1007        fn two_deltas() {
1008            let data = vec![
1009                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 4 }),
1010                2, 3, 4, 5,
1011            ];
1012
1013            let mut iter = PackedDeltasIter::new(1.0, 2, &data);
1014            // Remember that X deltas are defined first.
1015            assert_eq!(iter.next().unwrap(), (2.0, 4.0));
1016            assert_eq!(iter.next().unwrap(), (3.0, 5.0));
1017            assert!(iter.next().is_none());
1018        }
1019
1020        #[test]
1021        fn single_long_delta() {
1022            let data = vec![
1023                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1024                0, 2, 0, 3
1025            ];
1026
1027            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1028            assert_eq!(iter.next().unwrap(), (2.0, 3.0));
1029            assert!(iter.next().is_none());
1030        }
1031
1032        #[test]
1033        fn zeros() {
1034            let data = vec![
1035                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 4 }),
1036            ];
1037
1038            let mut iter = PackedDeltasIter::new(1.0, 2, &data);
1039            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1040            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1041            assert!(iter.next().is_none());
1042        }
1043
1044        #[test]
1045        fn zero_words() {
1046            // When `deltas_are_zero` is set, `deltas_are_words` should be ignored.
1047
1048            let data = vec![
1049                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: true, run_count: 4 }),
1050            ];
1051
1052            let mut iter = PackedDeltasIter::new(1.0, 2, &data);
1053            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1054            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1055            assert!(iter.next().is_none());
1056        }
1057
1058        #[test]
1059        fn zero_runs() {
1060            let data = vec![
1061                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 2 }),
1062                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 4 }),
1063                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 6 }),
1064            ];
1065
1066            let mut iter = PackedDeltasIter::new(1.0, 6, &data);
1067            // First run.
1068            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1069            // Second run.
1070            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1071            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1072            // Third run.
1073            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1074            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1075            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1076            assert!(iter.next().is_none());
1077        }
1078
1079        #[test]
1080        fn delta_after_zeros() {
1081            let data = vec![
1082                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 2 }),
1083                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1084                2, 3
1085            ];
1086
1087            let mut iter = PackedDeltasIter::new(1.0, 2, &data);
1088            assert_eq!(iter.next().unwrap(), (0.0, 2.0));
1089            assert_eq!(iter.next().unwrap(), (0.0, 3.0));
1090            assert!(iter.next().is_none());
1091        }
1092
1093        #[test]
1094        fn unexpected_end_of_data_1() {
1095            let data = vec![
1096                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1097            ];
1098
1099            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1100            assert!(iter.next().is_none());
1101        }
1102
1103        #[test]
1104        fn unexpected_end_of_data_2() {
1105            // Only X is set.
1106
1107            let data = vec![
1108                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1109                1
1110            ];
1111
1112            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1113            assert!(iter.next().is_none());
1114        }
1115
1116        #[test]
1117        fn unexpected_end_of_data_3() {
1118            let data = vec![
1119                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1120            ];
1121
1122            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1123            assert!(iter.next().is_none());
1124        }
1125
1126        #[test]
1127        fn unexpected_end_of_data_4() {
1128            // X data is too short.
1129
1130            let data = vec![
1131                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1132                1
1133            ];
1134
1135            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1136            assert!(iter.next().is_none());
1137        }
1138
1139        #[test]
1140        fn unexpected_end_of_data_6() {
1141            // Only X is set.
1142
1143            let data = vec![
1144                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1145                0, 1
1146            ];
1147
1148            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1149            assert!(iter.next().is_none());
1150        }
1151
1152        #[test]
1153        fn unexpected_end_of_data_7() {
1154            // Y data is too short.
1155
1156            let data = vec![
1157                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1158                0, 1, 0
1159            ];
1160
1161            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1162            assert!(iter.next().is_none());
1163        }
1164
1165        #[test]
1166        fn single_run() {
1167            let data = vec![
1168                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 1 }),
1169                2, 3
1170            ];
1171
1172            let mut iter = PackedDeltasIter::new(1.0, 1, &data);
1173            assert!(iter.next().is_none());
1174        }
1175
1176        #[test]
1177        fn too_many_pairs() {
1178            let data = vec![
1179                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1180                2, 3
1181            ];
1182
1183            // We have only one pair, not 10.
1184            let mut iter = PackedDeltasIter::new(1.0, 10, &data);
1185            assert!(iter.next().is_none());
1186        }
1187
1188        #[test]
1189        fn invalid_number_of_pairs() {
1190            let data = vec![
1191                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1192                2, 3, 4, 5, 6, 7,
1193            ];
1194
1195            // We have 3 pairs, not 4.
1196            // We don't actually check this, since it will be very expensive.
1197            // And it should not happen in a well-formed font anyway.
1198            // So as long as it doesn't panic - we are fine.
1199            let mut iter = PackedDeltasIter::new(1.0, 4, &data);
1200            assert_eq!(iter.next().unwrap(), (2.0, 7.0));
1201            assert!(iter.next().is_none());
1202        }
1203
1204        #[test]
1205        fn mixed_runs() {
1206            let data = vec![
1207                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 3 }),
1208                2, 3, 4,
1209                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: true, run_count: 2 }),
1210                0, 5, 0, 6,
1211                gen_control(NewControl { deltas_are_zero: true, deltas_are_words: false, run_count: 1 }),
1212            ];
1213
1214            let mut iter = PackedDeltasIter::new(1.0, 3, &data);
1215            assert_eq!(iter.next().unwrap(), (2.0, 5.0));
1216            assert_eq!(iter.next().unwrap(), (3.0, 6.0));
1217            assert_eq!(iter.next().unwrap(), (4.0, 0.0));
1218            assert!(iter.next().is_none());
1219        }
1220
1221        #[test]
1222        fn non_default_scalar() {
1223            let data = vec![
1224                gen_control(NewControl { deltas_are_zero: false, deltas_are_words: false, run_count: 2 }),
1225                2, 3
1226            ];
1227
1228            let mut iter = PackedDeltasIter::new(0.5, 1, &data);
1229            assert_eq!(iter.next().unwrap(), (1.0, 1.5));
1230            assert!(iter.next().is_none());
1231        }
1232
1233        #[test]
1234        fn runs_overflow() {
1235            let data = vec![0xFF; 0xFFFF];
1236            let mut iter = PackedDeltasIter::new(1.0, 0xFFFF, &data);
1237            // As long as it doesn't panic - we are fine.
1238            assert_eq!(iter.next().unwrap(), (0.0, 0.0));
1239        }
1240    }
1241}
1242
1243use packed_deltas::PackedDeltasIter;
1244
1245
1246/// Infer unreferenced deltas.
1247///
1248/// A font can define deltas only for specific points, to reduce the file size.
1249/// In this case, we have to infer undefined/unreferenced deltas manually,
1250/// depending on the context.
1251///
1252/// This is already a pretty complex task, since deltas should be resolved
1253/// only inside the current contour (do not confuse with component).
1254/// And during resolving we can actually wrap around the contour.
1255/// So if there is no deltas after the current one, we have to use
1256/// the first delta of the current contour instead.
1257/// Same goes for the previous delta. If there are no deltas
1258/// before the current one, we have to use the last one in the current contour.
1259///
1260/// And in case of `ttf-parser` everything is becoming even more complex,
1261/// since we don't actually have a list of points and deltas, only iterators.
1262/// Because of `ttf-parser`'s allocation free policy.
1263/// Which makes the code even more complicated.
1264///
1265/// https://docs.microsoft.com/en-us/typography/opentype/spec/gvar#inferred-deltas-for-un-referenced-point-numbers
1266fn infer_deltas(
1267    tuple: &VariationTuple,
1268    points_set: SetPointsIter,
1269    // A points iterator that starts after the current point.
1270    points: glyf::GlyphPointsIter,
1271    // A points iterator that starts from the first point in the glyph.
1272    all_points: glyf::GlyphPointsIter,
1273    curr_point: glyf::GlyphPoint,
1274) -> (f32, f32) {
1275    let mut current_contour = points.current_contour();
1276    if curr_point.last_point && current_contour != 0 {
1277        // When we parsed the last point of a contour,
1278        // an iterator had switched to the next contour.
1279        // So we have to move to the previous one.
1280        current_contour -= 1;
1281    }
1282
1283    let prev_point = if let Some(prev_point) = tuple.prev_point {
1284        // If a contour already had a delta - just use it.
1285        prev_point
1286    } else {
1287        // If not, find the last point with delta in the current contour.
1288        let mut last_point = None;
1289        let mut deltas = tuple.deltas.clone();
1290        for (point, is_set) in points.clone().zip(points_set.clone()) {
1291            if is_set {
1292                if let Some((x_delta, y_delta)) = deltas.next() {
1293                    last_point = Some(PointAndDelta {
1294                        x: point.x,
1295                        y: point.y,
1296                        x_delta,
1297                        y_delta,
1298                    });
1299                }
1300            }
1301
1302            if point.last_point {
1303                break;
1304            }
1305        }
1306
1307        // If there is no last point, there are no deltas.
1308        match last_point {
1309            Some(p) => p,
1310            None => return (0.0, 0.0),
1311        }
1312    };
1313
1314    let mut next_point = None;
1315    if !curr_point.last_point {
1316        // If the current point is not the last one in the contour,
1317        // find the first set delta in the current contour.
1318        let mut deltas = tuple.deltas.clone();
1319        for (point, is_set) in points.clone().zip(points_set.clone()) {
1320            if is_set {
1321                if let Some((x_delta, y_delta)) = deltas.next() {
1322                    next_point = Some(PointAndDelta {
1323                        x: point.x,
1324                        y: point.y,
1325                        x_delta,
1326                        y_delta,
1327                    });
1328                }
1329
1330                break;
1331            }
1332
1333            if point.last_point {
1334                break;
1335            }
1336        }
1337    }
1338
1339    if next_point.is_none() {
1340        // If there were no deltas after the current point,
1341        // restart from the start of the contour.
1342        //
1343        // This is probably the most expensive branch,
1344        // but nothing we can do about it since `glyf`/`gvar` data structure
1345        // doesn't allow implementing a reverse iterator.
1346        // So we have to parse everything once again.
1347
1348        let mut all_points = all_points.clone();
1349        let mut deltas = tuple.deltas.clone().restart();
1350        let mut points_set = points_set.clone().restart();
1351
1352        let mut contour = 0;
1353        while let (Some(point), Some(is_set)) = (all_points.next(), points_set.next()) {
1354            // First, we have to skip already processed contours.
1355            if contour != current_contour {
1356                if is_set {
1357                    let _ = deltas.next();
1358                }
1359
1360                contour = all_points.current_contour();
1361                continue;
1362            }
1363
1364            if is_set {
1365                let (x_delta, y_delta) = deltas.next().unwrap_or((0.0, 0.0));
1366                next_point = Some(PointAndDelta {
1367                    x: point.x,
1368                    y: point.y,
1369                    x_delta,
1370                    y_delta,
1371                });
1372
1373                break;
1374            }
1375
1376            if point.last_point {
1377                break;
1378            }
1379        }
1380    }
1381
1382    // If there is no next point, there are no deltas.
1383    let next_point = match next_point {
1384        Some(p) => p,
1385        None => return (0.0, 0.0),
1386    };
1387
1388    let dx = infer_delta(prev_point.x, curr_point.x, next_point.x,
1389                         prev_point.x_delta, next_point.x_delta);
1390
1391    let dy = infer_delta(prev_point.y, curr_point.y, next_point.y,
1392                         prev_point.y_delta, next_point.y_delta);
1393
1394    (dx, dy)
1395}
1396
1397fn infer_delta(
1398    prev_point: i16,
1399    target_point: i16,
1400    next_point: i16,
1401    prev_delta: f32,
1402    next_delta: f32,
1403) -> f32 {
1404    if prev_point == next_point {
1405        if prev_delta == next_delta { prev_delta } else { 0.0 }
1406    } else if target_point <= prev_point.min(next_point) {
1407        if prev_point < next_point { prev_delta } else { next_delta }
1408    } else if target_point >= prev_point.max(next_point) {
1409        if prev_point > next_point { prev_delta } else { next_delta }
1410    } else {
1411        // 'Target point coordinate is between adjacent point coordinates.'
1412        //
1413        // 'Target point delta is derived from the adjacent point deltas
1414        // using linear interpolation.'
1415        let d =   f32::from(try_opt_or!(target_point.checked_sub(prev_point), 0.0))
1416                / f32::from(try_opt_or!(next_point.checked_sub(prev_point), 0.0));
1417        (1.0 - d) * prev_delta + d * next_delta
1418    }
1419}
1420
1421
1422/// A [Glyph Variations Table](
1423/// https://docs.microsoft.com/en-us/typography/opentype/spec/gvar).
1424#[derive(Clone, Copy)]
1425pub struct Table<'a> {
1426    axis_count: NonZeroU16,
1427    shared_tuple_records: LazyArray16<'a, F2DOT14>,
1428    offsets: GlyphVariationDataOffsets<'a>,
1429    glyphs_variation_data: &'a [u8],
1430}
1431
1432impl<'a> Table<'a> {
1433    /// Parses a table from raw data.
1434    pub fn parse(data: &'a [u8]) -> Option<Self> {
1435        let mut s = Stream::new(data);
1436        let version = s.read::<u32>()?;
1437        if version != 0x00010000 {
1438            return None;
1439        }
1440
1441        let axis_count = s.read::<u16>()?;
1442        let shared_tuple_count = s.read::<u16>()?;
1443        let shared_tuples_offset = s.read::<Offset32>()?;
1444        let glyph_count = s.read::<u16>()?;
1445        let flags = s.read::<u16>()?;
1446        let glyph_variation_data_array_offset = s.read::<Offset32>()?;
1447
1448        // The axis count cannot be zero.
1449        let axis_count = NonZeroU16::new(axis_count)?;
1450
1451        let shared_tuple_records = {
1452            let mut sub_s = Stream::new_at(data, shared_tuples_offset.to_usize())?;
1453            sub_s.read_array16::<F2DOT14>(shared_tuple_count.checked_mul(axis_count.get())?)?
1454        };
1455
1456        let glyphs_variation_data = data.get(glyph_variation_data_array_offset.to_usize()..)?;
1457        let offsets = {
1458            let offsets_count = glyph_count.checked_add(1)?;
1459            let is_long_format = flags & 1 == 1; // The first bit indicates a long format.
1460            if is_long_format {
1461                GlyphVariationDataOffsets::Long(s.read_array16::<Offset32>(offsets_count)?)
1462            } else {
1463                GlyphVariationDataOffsets::Short(s.read_array16::<Offset16>(offsets_count)?)
1464            }
1465        };
1466
1467        Some(Table {
1468            axis_count,
1469            shared_tuple_records,
1470            offsets,
1471            glyphs_variation_data,
1472        })
1473    }
1474
1475    #[inline]
1476    fn parse_variation_data(
1477        &self,
1478        glyph_id: GlyphId,
1479        coordinates: &[NormalizedCoordinate],
1480        points_len: u16,
1481        tuples: &mut VariationTuples<'a>,
1482    ) -> Option<()> {
1483        tuples.clear();
1484
1485        if coordinates.len() != usize::from(self.axis_count.get()) {
1486            return None;
1487        }
1488
1489        let next_glyph_id = glyph_id.0.checked_add(1)?;
1490
1491        let (start, end) = match self.offsets {
1492            GlyphVariationDataOffsets::Short(ref array) => {
1493                // 'If the short format (Offset16) is used for offsets,
1494                // the value stored is the offset divided by 2.'
1495                (array.get(glyph_id.0)?.to_usize() * 2, array.get(next_glyph_id)?.to_usize() * 2)
1496            }
1497            GlyphVariationDataOffsets::Long(ref array) => {
1498                (array.get(glyph_id.0)?.to_usize(), array.get(next_glyph_id)?.to_usize())
1499            }
1500        };
1501
1502        // Ignore empty data.
1503        if start == end {
1504            return Some(());
1505        }
1506
1507        let data = self.glyphs_variation_data.get(start..end)?;
1508        parse_variation_data(coordinates, &self.shared_tuple_records, points_len, data, tuples)
1509    }
1510
1511    /// Outlines a glyph.
1512    pub fn outline(
1513        &self,
1514        glyf_table: glyf::Table,
1515        coordinates: &[NormalizedCoordinate],
1516        glyph_id: GlyphId,
1517        builder: &mut dyn OutlineBuilder,
1518    ) -> Option<Rect> {
1519        let mut b = glyf::Builder::new(Transform::default(), BBox::new(), builder);
1520        let glyph_data = glyf_table.get(glyph_id)?;
1521        outline_var_impl(glyf_table, self, glyph_id, glyph_data, coordinates, 0, &mut b);
1522        b.bbox.to_rect()
1523    }
1524}
1525
1526impl core::fmt::Debug for Table<'_> {
1527    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
1528        write!(f, "Table {{ ... }}")
1529    }
1530}
1531
1532fn outline_var_impl<'a>(
1533    glyf_table: glyf::Table,
1534    gvar_table: &Table,
1535    glyph_id: GlyphId,
1536    data: &[u8],
1537    coordinates: &[NormalizedCoordinate],
1538    depth: u8,
1539    builder: &mut glyf::Builder,
1540) -> Option<()> {
1541    if depth >= glyf::MAX_COMPONENTS {
1542        return None;
1543    }
1544
1545    let mut s = Stream::new(data);
1546    let number_of_contours = s.read::<i16>()?;
1547
1548    // Skip bbox.
1549    //
1550    // In case of a variable font, a bounding box defined in the `glyf` data
1551    // refers to the default variation values. Which is not what we want.
1552    // Instead, we have to manually calculate outline's bbox.
1553    s.advance(8);
1554
1555    // TODO: This is the most expensive part. Find a way to allocate it only once.
1556    // `VariationTuples` is a very large struct, so allocate it once.
1557    let mut tuples = VariationTuples::default();
1558
1559    if number_of_contours > 0 {
1560        // Simple glyph.
1561
1562        let number_of_contours = NonZeroU16::new(number_of_contours as u16)?;
1563        let mut glyph_points = glyf::parse_simple_outline(s.tail()?, number_of_contours)?;
1564        let all_glyph_points = glyph_points.clone();
1565        let points_len = glyph_points.points_left;
1566        gvar_table.parse_variation_data(glyph_id, coordinates, points_len, &mut tuples)?;
1567
1568        while let Some(point) = glyph_points.next() {
1569            let (x, y) = tuples.apply(all_glyph_points.clone(), glyph_points.clone(), point)?;
1570            builder.push_point(x, y, point.on_curve_point, point.last_point);
1571        }
1572
1573        Some(())
1574    } else if number_of_contours < 0 {
1575        // Composite glyph.
1576
1577        // In case of a composite glyph, `gvar` data contains position adjustments
1578        // for each component.
1579        // Basically, an additional translation used during transformation.
1580        // So we have to push zero points manually, instead of parsing the `glyf` data.
1581        //
1582        // Details:
1583        // https://docs.microsoft.com/en-us/typography/opentype/spec/gvar#point-numbers-and-processing-for-composite-glyphs
1584
1585        let mut components = glyf::CompositeGlyphIter::new(s.tail()?);
1586        let components_count = components.clone().count() as u16;
1587        gvar_table.parse_variation_data(glyph_id, coordinates, components_count, &mut tuples)?;
1588
1589        while let Some(component) = components.next() {
1590            let (tx, ty) = tuples.apply_null()?;
1591
1592            let mut transform = builder.transform;
1593
1594            // Variation component offset should be applied only when
1595            // the ARGS_ARE_XY_VALUES flag is set.
1596            if component.flags.args_are_xy_values() {
1597                transform = Transform::combine(transform, Transform::new_translate(tx, ty));
1598            }
1599
1600            transform = Transform::combine(transform, component.transform);
1601
1602            let mut b = glyf::Builder::new(transform, builder.bbox, builder.builder);
1603            let glyph_data = glyf_table.get(component.glyph_id)?;
1604            outline_var_impl(
1605                glyf_table, gvar_table, component.glyph_id,
1606                glyph_data, coordinates, depth + 1, &mut b,
1607            )?;
1608
1609            // Take updated bbox.
1610            builder.bbox = b.bbox;
1611        }
1612
1613        Some(())
1614    } else {
1615        // An empty glyph.
1616        None
1617    }
1618}
1619
1620// https://docs.microsoft.com/en-us/typography/opentype/spec/otvarcommonformats#tuple-variation-store-header
1621fn parse_variation_data<'a>(
1622    coordinates: &[NormalizedCoordinate],
1623    shared_tuple_records: &LazyArray16<F2DOT14>,
1624    points_len: u16,
1625    data: &'a [u8],
1626    tuples: &mut VariationTuples<'a>,
1627) -> Option<()> {
1628    const SHARED_POINT_NUMBERS_FLAG: u16 = 0x8000;
1629    const COUNT_MASK: u16 = 0x0FFF;
1630
1631    let mut main_stream = Stream::new(data);
1632    let tuple_variation_count = main_stream.read::<u16>()?;
1633    let data_offset = main_stream.read::<Offset16>()?;
1634
1635    // 'The high 4 bits are flags, and the low 12 bits
1636    // are the number of tuple variation tables for this glyph.'
1637    let has_shared_point_numbers = tuple_variation_count & SHARED_POINT_NUMBERS_FLAG != 0;
1638    let tuple_variation_count = tuple_variation_count & COUNT_MASK;
1639
1640    // 'The number of tuple variation tables can be any number between 1 and 4095.'
1641    // No need to check for 4095, because this is 0x0FFF that we masked before.
1642    if tuple_variation_count == 0 {
1643        return None;
1644    }
1645
1646    // Attempt to reserve space for the tuples we're about to parse.
1647    // If it fails, bail out.
1648    if !tuples.reserve(tuple_variation_count) {
1649        return None;
1650    }
1651
1652    // A glyph variation data consists of three parts: header + variation tuples + serialized data.
1653    // Each tuple has it's own chunk in the serialized data.
1654    // Because of that, we are using two parsing streams: one for tuples and one for serialized data.
1655    // So we can parse them in parallel and avoid needless allocations.
1656    let mut serialized_stream = Stream::new_at(data, data_offset.to_usize())?;
1657
1658    // All tuples in the variation data can reference the same point numbers,
1659    // which are defined at the start of the serialized data.
1660    let mut shared_point_numbers = None;
1661    if has_shared_point_numbers {
1662        shared_point_numbers = PackedPointsIter::new(&mut serialized_stream)?;
1663    }
1664
1665    parse_variation_tuples(
1666        tuple_variation_count,
1667        coordinates,
1668        shared_tuple_records,
1669        shared_point_numbers,
1670        points_len.checked_add(PHANTOM_POINTS_LEN as u16)?,
1671        main_stream,
1672        serialized_stream,
1673        tuples,
1674    )
1675}