1include!("../../generated/generated_gvar.rs");
5
6mod deltas;
7
8pub use deltas::DeltaBuffers;
9
10use super::{
11 glyf::{CompositeGlyphFlags, Glyf, Glyph, PointCoord},
12 loca::{Loca, LocaGlyph},
13 variations::{
14 scalar_for, PackedPointNumbers, Tuple, TupleDelta, TupleVariationCount, TupleVariationData,
15 TupleVariationHeader, NOT_COMPUTED,
16 },
17};
18
19pub type GlyphVariationData<'a> = TupleVariationData<'a, GlyphDelta>;
21
22#[derive(Clone)]
24pub enum SelectedGvar<'a> {
25 Original(Gvar<'a>),
27 Extended(GvarExtended<'a>),
29}
30
31impl<'a> From<Gvar<'a>> for SelectedGvar<'a> {
32 fn from(table: Gvar<'a>) -> Self {
33 Self::Original(table)
34 }
35}
36
37impl<'a> From<GvarExtended<'a>> for SelectedGvar<'a> {
38 fn from(table: GvarExtended<'a>) -> Self {
39 Self::Extended(table)
40 }
41}
42
43impl<'a> SelectedGvar<'a> {
44 pub fn glyph_count(&self) -> u32 {
46 match self {
47 Self::Original(table) => table.glyph_count().into(),
48 Self::Extended(table) => table.glyph_count().into(),
49 }
50 }
51
52 fn is_extended(&self) -> bool {
53 matches!(self, Self::Extended(_))
54 }
55
56 selected_table_getters!(
57 version -> MajorMinor,
58 axis_count -> u16,
59 shared_tuple_count -> u16,
60 shared_tuples_offset -> Offset32,
61 flags -> GvarFlags,
62 glyph_variation_data_array_offset -> u32,
63 glyph_variation_data_offsets -> ComputedArray<'a, U16Or32>,
64 offset_data -> FontData<'a>,
65 );
66}
67
68#[derive(Clone, Copy, Debug)]
69pub struct U16Or32(u32);
70
71crate::impl_font_read_at!(U16Or32);
72
73impl ReadArgs for U16Or32 {
74 type Args = GvarFlags;
75}
76
77impl ComputeSize for U16Or32 {
78 fn compute_size(args: GvarFlags) -> Result<usize, ReadError> {
79 Ok(if args.contains(GvarFlags::LONG_OFFSETS) {
80 4
81 } else {
82 2
83 })
84 }
85}
86
87impl FontRead<'_> for U16Or32 {
88 fn read_with_args(data: FontData<'_>, args: Self::Args) -> Result<Self, ReadError> {
89 if args.contains(GvarFlags::LONG_OFFSETS) {
90 data.read_at::<u32>(0).map(Self)
91 } else {
92 data.read_at::<u16>(0).map(|v| Self(v as u32 * 2))
93 }
94 }
95}
96
97impl U16Or32 {
98 #[inline]
99 pub fn get(self) -> u32 {
100 self.0
101 }
102}
103
104impl<'a> GlyphVariationDataHeader<'a> {
105 fn raw_tuple_header_data(&self) -> FontData<'a> {
106 let range = self.tuple_variation_headers_byte_range();
107 self.offset_data().split_off(range.start).unwrap()
108 }
109}
110
111impl<'a> GlyphVariationDataHeaderExtended<'a> {
112 fn raw_tuple_header_data(&self) -> FontData<'a> {
113 let range = self.tuple_variation_headers_byte_range();
114 self.offset_data().split_off(range.start).unwrap()
115 }
116}
117
118macro_rules! impl_gvar_header {
119 ($table:ident, $extended:expr) => {
120 impl<'a> $table<'a> {
121 pub fn shared_tuples_offset(&self) -> Offset32 {
123 self.offset_data()
124 .read_at(self.shared_tuples_offset_byte_range().start)
125 .ok()
126 .unwrap()
127 }
128
129 fn is_extended(&self) -> bool {
130 $extended
131 }
132 }
133 };
134}
135
136impl_gvar_header!(Gvar, false);
137impl_gvar_header!(GvarExtended, true);
138
139macro_rules! impl_gvar_methods {
140 ($table:ident) => {
141 impl<'a> $table<'a> {
142 pub fn shared_tuples(&self) -> Result<SharedTuples<'a>, ReadError> {
145 let count = self.shared_tuple_count();
146 let axis_count = self.axis_count();
147 let offset = self.shared_tuples_offset();
148 if count == 0 && offset.is_null() {
149 return SharedTuples::read(self.offset_data(), 0, axis_count);
150 }
151 offset.resolve_with_args(self.offset_data(), (count, axis_count))
152 }
153
154 pub fn data_for_gid(&self, gid: GlyphId) -> Result<Option<FontData<'a>>, ReadError> {
158 let range = self.data_range_for_gid(gid)?;
159 if range.is_empty() {
160 return Ok(None);
161 }
162 match self.offset_data().slice(range) {
163 Some(data) => Ok(Some(data)),
164 None => Err(ReadError::OutOfBounds),
165 }
166 }
167
168 pub fn glyph_variation_data_for_range(
169 &self,
170 offset_range: Range<usize>,
171 ) -> Result<FontData<'a>, ReadError> {
172 let base = self.glyph_variation_data_array_offset() as usize;
173 let start = base
174 .checked_add(offset_range.start)
175 .ok_or(ReadError::OutOfBounds)?;
176 let end = base
177 .checked_add(offset_range.end)
178 .ok_or(ReadError::OutOfBounds)?;
179 self.offset_data()
180 .slice(start..end)
181 .ok_or(ReadError::OutOfBounds)
182 }
183
184 pub fn as_bytes(&self) -> &[u8] {
185 self.offset_data().as_bytes()
186 }
187
188 fn data_range_for_gid(&self, gid: GlyphId) -> Result<Range<usize>, ReadError> {
189 let start_idx = gid.to_u32() as usize;
190 let end_idx = start_idx.checked_add(1).ok_or(ReadError::OutOfBounds)?;
191 let data_start = self.glyph_variation_data_array_offset();
192 let start = data_start
193 .checked_add(self.glyph_variation_data_offsets().get(start_idx)?.get());
194 let end =
195 data_start.checked_add(self.glyph_variation_data_offsets().get(end_idx)?.get());
196 let (Some(start), Some(end)) = (start, end) else {
197 return Err(ReadError::OutOfBounds);
198 };
199 Ok(start as usize..end as usize)
200 }
201
202 pub fn glyph_variation_data(
207 &self,
208 gid: GlyphId,
209 ) -> Result<Option<GlyphVariationData<'a>>, ReadError> {
210 let shared_tuples = self.shared_tuples()?;
211 let axis_count = self.axis_count();
212 let data = self.data_for_gid(gid)?;
213 data.map(|data| {
214 if self.is_extended() {
215 GlyphVariationData::new_extended(data, axis_count, shared_tuples)
216 } else {
217 GlyphVariationData::new(data, axis_count, shared_tuples)
218 }
219 })
220 .transpose()
221 }
222
223 pub fn compute_scalars(&self, coords: &[F2Dot14], out: &mut [Fixed]) -> usize {
240 let Ok(shared) = self.shared_tuples() else {
241 out.fill(NOT_COMPUTED);
242 return 0;
243 };
244 let shared = shared.tuples();
245 let axis_count = self.axis_count() as usize;
246 let count = out.len().min(self.shared_tuple_count() as usize);
247 for (i, out) in out[..count].iter_mut().enumerate() {
248 let Ok(tuple) = shared.get(i) else {
251 return i;
252 };
253 *out = (tuple.len() == axis_count)
254 .then(|| scalar_for(&tuple, None, coords))
255 .flatten()
256 .unwrap_or(Fixed::ZERO);
257 }
258 out[count..].fill(NOT_COMPUTED);
260 count
261 }
262
263 pub fn phantom_point_deltas(
264 &self,
265 glyf: &Glyf,
266 loca: &Loca,
267 coords: &[F2Dot14],
268 glyph_id: GlyphId,
269 ) -> Option<[Point<Fixed>; 4]> {
270 self.phantom_point_deltas_with_scalars(glyf, loca, coords, &[], glyph_id)
271 }
272
273 pub fn phantom_point_deltas_with_scalars(
280 &self,
281 glyf: &Glyf,
282 loca: &Loca,
283 coords: &[F2Dot14],
284 scalars: &[Fixed],
285 glyph_id: GlyphId,
286 ) -> Option<[Point<Fixed>; 4]> {
287 let (glyph_id, point_count) =
298 find_glyph_and_point_count(glyf, loca, glyph_id, 0).ok()?;
299 let mut phantom_deltas = [Point::default(); 4];
300 let phantom_range = point_count..point_count + 4;
301 let Ok(Some(var_data)) = self.glyph_variation_data(glyph_id) else {
302 return None;
303 };
304 for (tuple, scalar) in var_data.active_tuples_at_with_scalars(coords, scalars) {
307 for tuple_delta in tuple.deltas() {
308 let ix = tuple_delta.position as usize;
309 if phantom_range.contains(&ix) {
310 phantom_deltas[ix - phantom_range.start] +=
311 tuple_delta.apply_scalar(scalar);
312 }
313 }
314 }
315 Some(phantom_deltas)
316 }
317 }
318 };
319}
320
321impl_gvar_methods!(Gvar);
322impl_gvar_methods!(GvarExtended);
323impl_gvar_methods!(SelectedGvar);
324
325impl<'a> GlyphVariationData<'a> {
326 pub(crate) fn new(
327 data: FontData<'a>,
328 axis_count: u16,
329 shared_tuples: SharedTuples<'a>,
330 ) -> Result<Self, ReadError> {
331 Self::new_with_format(data, axis_count, shared_tuples, false)
332 }
333
334 fn new_extended(
335 data: FontData<'a>,
336 axis_count: u16,
337 shared_tuples: SharedTuples<'a>,
338 ) -> Result<Self, ReadError> {
339 Self::new_with_format(data, axis_count, shared_tuples, true)
340 }
341
342 fn new_with_format(
343 data: FontData<'a>,
344 axis_count: u16,
345 shared_tuples: SharedTuples<'a>,
346 extended: bool,
347 ) -> Result<Self, ReadError> {
348 let (count, header_data, data) = if extended {
349 let header = GlyphVariationDataHeaderExtended::read(data)?;
350 (
351 header.tuple_variation_count(),
352 header.raw_tuple_header_data(),
353 header.serialized_data()?,
354 )
355 } else {
356 let header = GlyphVariationDataHeader::read(data)?;
357 (
358 header.tuple_variation_count(),
359 header.raw_tuple_header_data(),
360 header.serialized_data()?,
361 )
362 };
363
364 let (shared_point_numbers, serialized_data) = if count.shared_point_numbers() {
366 let (packed, data) = PackedPointNumbers::split_off_front(data);
367 (Some(packed), data)
368 } else {
369 (None, data)
370 };
371
372 Ok(GlyphVariationData {
373 tuple_count: count,
374 axis_count,
375 shared_tuples: Some(shared_tuples.tuples()),
376 shared_point_numbers,
377 header_data,
378 serialized_data,
379 _marker: std::marker::PhantomData,
380 })
381 }
382}
383
384#[derive(Clone, Copy, Debug, PartialEq, Eq)]
386pub struct GlyphDelta {
387 pub position: u16,
389 pub x_delta: i32,
391 pub y_delta: i32,
393}
394
395impl GlyphDelta {
396 pub fn apply_scalar<D: PointCoord>(self, scalar: Fixed) -> Point<D> {
398 let scalar = D::from_fixed(scalar);
399 Point::new(self.x_delta, self.y_delta).map(D::from_i32) * scalar
400 }
401}
402
403impl TupleDelta for GlyphDelta {
404 fn is_point() -> bool {
405 true
406 }
407
408 fn new(position: u16, x: i32, y: i32) -> Self {
409 Self {
410 position,
411 x_delta: x,
412 y_delta: y,
413 }
414 }
415}
416
417fn find_glyph_and_point_count(
427 glyf: &Glyf,
428 loca: &Loca,
429 glyph_id: GlyphId,
430 recurse_depth: usize,
431) -> Result<(GlyphId, usize), ReadError> {
432 if recurse_depth > crate::limits::MAX_RECURSION_DEPTH {
433 return Err(ReadError::MalformedData(
434 "nesting too deep in composite glyph",
435 ));
436 }
437 let glyph = match loca.get(glyph_id, glyf) {
438 Some(LocaGlyph::Empty) => return Ok((glyph_id, 0)),
441 Some(LocaGlyph::Glyph(glyph)) => glyph,
442 None => return Err(ReadError::OutOfBounds),
443 };
444 match glyph {
445 Glyph::Simple(simple) => {
446 Ok((glyph_id, simple.num_points()))
448 }
449 Glyph::Composite(composite) => {
450 let (count, inherit_metrics) = composite.component_glyphs_and_flags().fold(
456 (0, None),
457 |(count, inherit_metrics), (component_id, flags)| {
458 let has_flag = flags.contains(CompositeGlyphFlags::USE_MY_METRICS);
459 let preferred = has_flag.then_some(component_id).or(inherit_metrics);
460
461 (count + 1, preferred)
462 },
463 );
464
465 if let Some(component) = inherit_metrics {
466 find_glyph_and_point_count(glyf, loca, component, recurse_depth + 1)
467 } else {
468 Ok((glyph_id, count))
469 }
470 }
471 }
472}
473
474#[cfg(test)]
475mod tests {
476 use std::collections::HashMap;
477
478 use font_test_data::bebuffer::BeBuffer;
479
480 use super::*;
481 use crate::{FontRef, TableProvider};
482
483 #[test]
484 fn extended_gvar_glyph_counts_and_data_offsets() {
485 for long_offsets in [false, true] {
486 for wide_data_offset in [false, true] {
487 let bytes =
488 font_test_data::extended::gvar(65537, true, long_offsets, wide_data_offset);
489 let raw = GvarExtended::read(bytes.as_slice().into()).unwrap();
490 let selected = SelectedGvar::Extended(raw.clone());
491 assert_eq!(raw.glyph_count().to_u32(), 65537);
492 assert_eq!(selected.glyph_count(), 65537);
493 assert_eq!(raw.flags().contains(GvarFlags::LONG_OFFSETS), long_offsets);
494 assert_eq!(raw.glyph_variation_data_offsets().len(), 65538);
495 assert!(raw.glyph_variation_data(GlyphId::new(0)).unwrap().is_none());
496 for table in [SelectedGvar::Extended(raw), selected] {
497 let mut scalars = [Fixed::ZERO];
498 assert_eq!(
499 table.compute_scalars(&[F2Dot14::from_f32(0.5)], &mut scalars),
500 1
501 );
502 assert_eq!(scalars[0], Fixed::from_f64(0.5));
503 let data = table
504 .glyph_variation_data(GlyphId::new(65536))
505 .unwrap()
506 .unwrap();
507 let tuples: Vec<_> = data.tuples().collect();
508 assert_eq!(tuples.len(), 1);
509 assert!(tuples[0].has_deltas_for_all_points());
510 let mut dense = [Point::<Fixed>::default(); 8];
511 tuples[0]
512 .accumulate_dense_deltas(&mut dense, Fixed::ONE)
513 .unwrap();
514 assert_eq!(dense[0].x, Fixed::from_i32(40));
515 let deltas: Vec<_> =
516 tuples[0].deltas().map(|d| (d.x_delta, d.y_delta)).collect();
517 assert_eq!(
518 deltas,
519 [
520 (40, 0),
521 (40, 0),
522 (40, 0),
523 (40, 0),
524 (0, 0),
525 (100, 0),
526 (0, 40),
527 (0, -20)
528 ]
529 );
530 for gid in [65537, u32::MAX] {
531 assert!(table.glyph_variation_data(GlyphId::new(gid)).is_err());
532 }
533 }
534 }
535 }
536 }
537
538 #[test]
539 fn extended_gvar_selection_and_malformed_headers() {
540 use font_test_data::extended::{font, gvar};
541 let extended = gvar(65537, true, true, false);
542 let legacy = gvar(3, false, false, false);
543 for with_legacy in [false, true] {
544 let mut tables = vec![(*b"GVAR", extended.as_slice())];
545 if with_legacy {
546 tables.push((*b"gvar", legacy.as_slice()));
547 }
548 let bytes = font(&tables);
549 let font = FontRef::new(&bytes).unwrap();
550 assert_eq!(font.selected_gvar().unwrap().glyph_count(), 65537);
551 }
552 let bytes = font(&[(*b"gvar", &legacy)]);
553 assert_eq!(
554 FontRef::new(&bytes)
555 .unwrap()
556 .selected_gvar()
557 .unwrap()
558 .glyph_count(),
559 3
560 );
561 let bytes = font(&[(*b"GVAR", &extended[..20]), (*b"gvar", &legacy)]);
562 assert!(FontRef::new(&bytes).unwrap().selected_gvar().is_err());
563 let bytes = font(&[(*b"GVAR", &extended[..21]), (*b"gvar", &legacy)]);
564 let source = FontRef::new(&bytes).unwrap();
565 let selected = source.selected_gvar().unwrap();
566 assert_eq!(selected.glyph_count(), 65537);
567 assert!(selected.glyph_variation_data(GlyphId::new(65536)).is_err());
568 let mut overflowing_offsets = extended.clone();
569 overflowing_offsets[17..21].copy_from_slice(&u32::MAX.to_be_bytes());
570 let table = GvarExtended::read(overflowing_offsets.as_slice().into()).unwrap();
571 assert!(table.glyph_variation_data(GlyphId::new(65536)).is_err());
572 }
573 #[test]
574 fn extended_gvar_rejects_truncated_glyph_headers_and_data_offsets() {
575 let tuples = SharedTuples::read(FontData::new(&[]), 0, 0).unwrap();
576 for bytes in [&[0, 1, 0, 0][..], &[0, 1, 0xff, 0xff, 0xff][..]] {
577 assert!(GlyphVariationData::new_extended(bytes.into(), 0, tuples.clone()).is_err());
578 }
579 }
580
581 #[test]
588 fn a_cached_scalar_changes_nothing() {
589 use crate::tables::variations::NOT_COMPUTED;
590
591 let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
592 let gvar = font.gvar().unwrap();
593 let glyf = font.glyf().unwrap();
594 let loca = font.loca(None).unwrap();
595 let coords = [F2Dot14::from_f32(-0.75)];
596
597 let mut buf = [Fixed::ZERO; 32];
598 let written = gvar.compute_scalars(&coords, &mut buf);
599 assert!(buf[written..].iter().all(|s| *s == NOT_COMPUTED));
602
603 let mut gapped = buf;
605 if written > 0 {
606 gapped[0] = NOT_COMPUTED;
607 }
608
609 for gid in (0..font.maxp().unwrap().num_glyphs()).map(GlyphId::from) {
610 let plain = gvar.phantom_point_deltas(&glyf, &loca, &coords, gid);
611 for (name, scalars) in [
612 ("full", &buf[..written]),
613 ("padded", &buf[..]),
614 ("gapped", &gapped[..]),
615 ("partial", &buf[..written / 2]),
616 ("empty", &[][..]),
617 ] {
618 assert_eq!(
619 gvar.phantom_point_deltas_with_scalars(&glyf, &loca, &coords, scalars, gid),
620 plain,
621 "{name} cache disagreed at {gid}"
622 );
623 }
624 }
625 }
626
627 static SKIA_GVAR_SHARED_TUPLES_DATA: FontData = FontData::new(&[
631 0x40, 0x00, 0x00, 0x00, 0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0xC0,
632 0x00, 0xC0, 0x00, 0xC0, 0x00, 0x40, 0x00, 0xC0, 0x00, 0x40, 0x00, 0x40, 0x00, 0xC0, 0x00,
633 0x40, 0x00,
634 ]);
635
636 static SKIA_GVAR_I_DATA: FontData = FontData::new(&[
637 0x00, 0x08, 0x00, 0x24, 0x00, 0x33, 0x20, 0x00, 0x00, 0x15, 0x20, 0x01, 0x00, 0x1B, 0x20,
638 0x02, 0x00, 0x24, 0x20, 0x03, 0x00, 0x15, 0x20, 0x04, 0x00, 0x26, 0x20, 0x07, 0x00, 0x0D,
639 0x20, 0x06, 0x00, 0x1A, 0x20, 0x05, 0x00, 0x40, 0x01, 0x01, 0x01, 0x81, 0x80, 0x43, 0xFF,
640 0x7E, 0xFF, 0x7E, 0xFF, 0x7E, 0xFF, 0x7E, 0x00, 0x81, 0x45, 0x01, 0x01, 0x01, 0x03, 0x01,
641 0x04, 0x01, 0x04, 0x01, 0x04, 0x01, 0x02, 0x80, 0x40, 0x00, 0x82, 0x81, 0x81, 0x04, 0x3A,
642 0x5A, 0x3E, 0x43, 0x20, 0x81, 0x04, 0x0E, 0x40, 0x15, 0x45, 0x7C, 0x83, 0x00, 0x0D, 0x9E,
643 0xF3, 0xF2, 0xF0, 0xF0, 0xF0, 0xF0, 0xF3, 0x9E, 0xA0, 0xA1, 0xA1, 0xA1, 0x9F, 0x80, 0x00,
644 0x91, 0x81, 0x91, 0x00, 0x0D, 0x0A, 0x0A, 0x09, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A, 0x0A,
645 0x0A, 0x0A, 0x0A, 0x0B, 0x80, 0x00, 0x15, 0x81, 0x81, 0x00, 0xC4, 0x89, 0x00, 0xC4, 0x83,
646 0x00, 0x0D, 0x80, 0x99, 0x98, 0x96, 0x96, 0x96, 0x96, 0x99, 0x80, 0x82, 0x83, 0x83, 0x83,
647 0x81, 0x80, 0x40, 0xFF, 0x18, 0x81, 0x81, 0x04, 0xE6, 0xF9, 0x10, 0x21, 0x02, 0x81, 0x04,
648 0xE8, 0xE5, 0xEB, 0x4D, 0xDA, 0x83, 0x00, 0x0D, 0xCE, 0xD3, 0xD4, 0xD3, 0xD3, 0xD3, 0xD5,
649 0xD2, 0xCE, 0xCC, 0xCD, 0xCD, 0xCD, 0xCD, 0x80, 0x00, 0xA1, 0x81, 0x91, 0x00, 0x0D, 0x07,
650 0x03, 0x04, 0x02, 0x02, 0x02, 0x03, 0x03, 0x07, 0x07, 0x08, 0x08, 0x08, 0x07, 0x80, 0x00,
651 0x09, 0x81, 0x81, 0x00, 0x28, 0x40, 0x00, 0xA4, 0x02, 0x24, 0x24, 0x66, 0x81, 0x04, 0x08,
652 0xFA, 0xFA, 0xFA, 0x28, 0x83, 0x00, 0x82, 0x02, 0xFF, 0xFF, 0xFF, 0x83, 0x02, 0x01, 0x01,
653 0x01, 0x84, 0x91, 0x00, 0x80, 0x06, 0x07, 0x08, 0x08, 0x08, 0x08, 0x0A, 0x07, 0x80, 0x03,
654 0xFE, 0xFF, 0xFF, 0xFF, 0x81, 0x00, 0x08, 0x81, 0x82, 0x02, 0xEE, 0xEE, 0xEE, 0x8B, 0x6D,
655 0x00,
656 ]);
657
658 #[test]
659 fn test_shared_tuples() {
660 #[allow(overflowing_literals)]
661 const MINUS_ONE: F2Dot14 = F2Dot14::from_bits(0xC000);
662 assert_eq!(MINUS_ONE, F2Dot14::from_f32(-1.0));
663
664 static EXPECTED: &[(F2Dot14, F2Dot14)] = &[
665 (F2Dot14::ONE, F2Dot14::ZERO),
666 (MINUS_ONE, F2Dot14::ZERO),
667 (F2Dot14::ZERO, F2Dot14::ONE),
668 (F2Dot14::ZERO, MINUS_ONE),
669 (MINUS_ONE, MINUS_ONE),
670 (F2Dot14::ONE, MINUS_ONE),
671 (F2Dot14::ONE, F2Dot14::ONE),
672 (MINUS_ONE, F2Dot14::ONE),
673 ];
674
675 const N_AXES: u16 = 2;
676
677 let tuples =
678 SharedTuples::read(SKIA_GVAR_SHARED_TUPLES_DATA, EXPECTED.len() as u16, N_AXES)
679 .unwrap();
680 let tuple_vec: Vec<_> = tuples
681 .tuples()
682 .iter()
683 .map(|tup| {
684 let values = tup.unwrap().values();
685 assert_eq!(values.len(), N_AXES as usize);
686 (values[0].get(), values[1].get())
687 })
688 .collect();
689
690 assert_eq!(tuple_vec, EXPECTED);
691 }
692
693 #[test]
694 fn embedded_peak_with_null_shared_tuples_offset() {
695 let glyph_data = [
698 0x00, 0x01, 0x00, 0x0A, 0x00, 0x04, 0xA0, 0x00, 0x40, 0x00, 0x00, 0x00, 0x0A, 0x80, ];
707 let mut buf = BeBuffer::new();
708 buf = buf.push(1u16).push(0u16); buf = buf.push(1u16); buf = buf.push(0u16).push(0u32); buf = buf.push(1u16).push(1u16); buf = buf.push(28u32); buf = buf.push(0u32).push(glyph_data.len() as u32);
714 let mut bytes = buf.to_vec();
715 bytes.extend_from_slice(&glyph_data);
716
717 let gvar = Gvar::read(FontData::new(&bytes)).unwrap();
718 assert_eq!(gvar.shared_tuples().unwrap().tuples().iter().count(), 0);
719 let data = gvar.glyph_variation_data(GlyphId::new(0)).unwrap().unwrap();
720 let (tuple, scalar) = data.active_tuples_at(&[F2Dot14::ONE]).next().unwrap();
721 assert_eq!(scalar, Fixed::ONE);
722 assert_eq!(
723 tuple.deltas().collect::<Vec<_>>(),
724 [GlyphDelta {
725 position: 0,
726 x_delta: 10,
727 y_delta: 0,
728 }]
729 );
730
731 bytes[6..8].copy_from_slice(&1u16.to_be_bytes());
733 let gvar = Gvar::read(FontData::new(&bytes)).unwrap();
734 assert!(matches!(gvar.shared_tuples(), Err(ReadError::NullOffset)));
735 }
736
737 #[test]
739 fn smoke_test() {
740 let header = GlyphVariationDataHeader::read(SKIA_GVAR_I_DATA).unwrap();
741 assert_eq!(header.serialized_data_offset(), 36);
742 assert_eq!(header.tuple_variation_count().count(), 8);
743 let shared_tuples = SharedTuples::read(SKIA_GVAR_SHARED_TUPLES_DATA, 8, 2).unwrap();
744
745 let vardata = GlyphVariationData::new(SKIA_GVAR_I_DATA, 2, shared_tuples).unwrap();
746 assert_eq!(vardata.tuple_count(), 8);
747 let deltas = vardata
748 .tuples()
749 .next()
750 .unwrap()
751 .deltas()
752 .collect::<Vec<_>>();
753 assert_eq!(deltas.len(), 18);
754 static EXPECTED: &[(i32, i32)] = &[
755 (257, 0),
756 (-127, 0),
757 (-128, 58),
758 (-130, 90),
759 (-130, 62),
760 (-130, 67),
761 (-130, 32),
762 (-127, 0),
763 (257, 0),
764 (259, 14),
765 (260, 64),
766 (260, 21),
767 (260, 69),
768 (258, 124),
769 (0, 0),
770 (130, 0),
771 (0, 0),
772 (0, 0),
773 ];
774 let expected = EXPECTED
775 .iter()
776 .copied()
777 .enumerate()
778 .map(|(pos, (x_delta, y_delta))| GlyphDelta {
779 position: pos as _,
780 x_delta,
781 y_delta,
782 })
783 .collect::<Vec<_>>();
784
785 for (a, b) in deltas.iter().zip(expected.iter()) {
786 assert_eq!(a, b);
787 }
788 }
789
790 #[test]
791 fn vazirmatn_var_a() {
792 let gvar = FontRef::new(font_test_data::VAZIRMATN_VAR)
793 .unwrap()
794 .gvar()
795 .unwrap();
796 let a_glyph_var = gvar.glyph_variation_data(GlyphId::new(1)).unwrap().unwrap();
797 assert_eq!(a_glyph_var.axis_count, 1);
798 let mut tuples = a_glyph_var.tuples();
799 let tup1 = tuples.next().unwrap();
800 assert_eq!(tup1.peak().values(), &[F2Dot14::from_f32(-1.0)]);
801 assert_eq!(tup1.deltas().count(), 18);
802 let x_vals = &[
803 -90, -134, 4, -6, -81, 18, -25, -33, -109, -121, -111, -111, -22, -22, 0, -113, 0, 0,
804 ];
805 let y_vals = &[
806 83, 0, 0, 0, 0, 0, 83, 0, 0, 0, -50, 54, 54, -50, 0, 0, -21, 0,
807 ];
808 assert_eq!(tup1.deltas().map(|d| d.x_delta).collect::<Vec<_>>(), x_vals);
809 assert_eq!(tup1.deltas().map(|d| d.y_delta).collect::<Vec<_>>(), y_vals);
810 let tup2 = tuples.next().unwrap();
811 assert_eq!(tup2.peak().values(), &[F2Dot14::from_f32(1.0)]);
812 let x_vals = &[
813 20, 147, -33, -53, 59, -90, 37, -6, 109, 90, -79, -79, -8, -8, 0, 59, 0, 0,
814 ];
815 let y_vals = &[
816 -177, 0, 0, 0, 0, 0, -177, 0, 0, 0, 4, -109, -109, 4, 0, 0, 9, 0,
817 ];
818
819 assert_eq!(tup2.deltas().map(|d| d.x_delta).collect::<Vec<_>>(), x_vals);
820 assert_eq!(tup2.deltas().map(|d| d.y_delta).collect::<Vec<_>>(), y_vals);
821 assert!(tuples.next().is_none());
822 }
823
824 #[test]
825 fn vazirmatn_var_agrave() {
826 let gvar = FontRef::new(font_test_data::VAZIRMATN_VAR)
827 .unwrap()
828 .gvar()
829 .unwrap();
830 let agrave_glyph_var = gvar.glyph_variation_data(GlyphId::new(2)).unwrap().unwrap();
831 let mut tuples = agrave_glyph_var.tuples();
832 let tup1 = tuples.next().unwrap();
833 assert_eq!(
834 tup1.deltas()
835 .map(|d| (d.position, d.x_delta, d.y_delta))
836 .collect::<Vec<_>>(),
837 &[(1, -51, 8), (3, -113, 0)]
838 );
839 let tup2 = tuples.next().unwrap();
840 assert_eq!(
841 tup2.deltas()
842 .map(|d| (d.position, d.x_delta, d.y_delta))
843 .collect::<Vec<_>>(),
844 &[(1, -54, -1), (3, 59, 0)]
845 );
846 }
847
848 #[test]
849 fn vazirmatn_var_grave() {
850 let gvar = FontRef::new(font_test_data::VAZIRMATN_VAR)
851 .unwrap()
852 .gvar()
853 .unwrap();
854 let grave_glyph_var = gvar.glyph_variation_data(GlyphId::new(3)).unwrap().unwrap();
855 let mut tuples = grave_glyph_var.tuples();
856 let tup1 = tuples.next().unwrap();
857 let tup2 = tuples.next().unwrap();
858 assert!(tuples.next().is_none());
859 assert_eq!(tup1.deltas().count(), 8);
860 assert_eq!(
861 tup2.deltas().map(|d| d.y_delta).collect::<Vec<_>>(),
862 &[0, -20, -20, 0, 0, 0, 0, 0]
863 );
864 }
865
866 #[test]
867 fn phantom_point_deltas() {
868 let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
869 #[rustfmt::skip]
870 let a_cases = [
871 (&[0.0], [(0.0, 0.0); 4]),
873 (&[1.0], [(0.0, 0.0), (59.0, 0.0), (0.0, 9.0), (0.0, 0.0)]),
874 (&[-1.0], [(0.0, 0.0), (-113.0, 0.0), (0.0, -21.0), (0.0, 0.0)]),
875 (&[0.5], [(0.0, 0.0), (29.5, 0.0), (0.0, 4.5), (0.0, 0.0)]),
876 (&[-0.5], [(0.0, 0.0), (-56.5, 0.0), (0.0, -10.5), (0.0, 0.0)]),
877 ];
878 for (coords, deltas) in a_cases {
879 assert_eq!(
881 compute_phantom_deltas(&font, coords, GlyphId::new(1)),
882 deltas
883 );
884 assert_eq!(
887 compute_phantom_deltas(&font, coords, GlyphId::new(2)),
888 deltas
889 );
890 }
891 #[rustfmt::skip]
892 let grave_cases = [
893 (&[0.0], [(0.0, 0.0); 4]),
895 (&[1.0], [(0.0, 0.0), (63.0, 0.0), (0.0, 0.0), (0.0, 0.0)]),
896 (&[-1.0], [(0.0, 0.0), (-96.0, 0.0), (0.0, 0.0), (0.0, 0.0)]),
897 (&[0.5], [(0.0, 0.0), (31.5, 0.0), (0.0, 0.0), (0.0, 0.0)]),
898 (&[-0.5], [(0.0, 0.0), (-48.0, 0.0), (0.0, 0.0), (0.0, 0.0)]),
899 ];
900 for (coords, deltas) in grave_cases {
902 assert_eq!(
903 compute_phantom_deltas(&font, coords, GlyphId::new(3)),
904 deltas
905 );
906 }
907 }
908
909 fn compute_phantom_deltas(
910 font: &FontRef,
911 coords: &[f32],
912 glyph_id: GlyphId,
913 ) -> [(f32, f32); 4] {
914 let loca = font.loca(None).unwrap();
915 let glyf = font.glyf().unwrap();
916 let gvar = font.gvar().unwrap();
917 let coords = coords
918 .iter()
919 .map(|coord| F2Dot14::from_f32(*coord))
920 .collect::<Vec<_>>();
921 gvar.phantom_point_deltas(&glyf, &loca, &coords, glyph_id)
922 .unwrap()
923 .map(|delta| delta.map(Fixed::to_f32))
924 .map(|p| (p.x, p.y))
925 }
926
927 #[test]
930 fn avoid_data_range_overflow() {
931 let mut buf = BeBuffer::new();
934 buf = buf.push(1u16).push(0u16);
936 buf = buf.push(0u16);
938 buf = buf.push(0u16).push(0u32);
940 buf = buf.push(1u16);
942 buf = buf.push(1u16);
944 buf = buf.push(u32::MAX - 10);
946 buf = buf.push(0u32).push(11u32);
948 let gvar = Gvar::read(buf.data().into()).unwrap();
949 let _ = gvar.data_range_for_gid(GlyphId::new(0));
951 }
952
953 #[test]
956 fn follow_use_my_metrics() {
957 let font = FontRef::new(font_test_data::gvar::USE_MY_METRICS).unwrap();
959 let glyf = font.glyf().unwrap();
960 let loca = font.loca(None).unwrap();
961 let post = font.post().unwrap();
962
963 let gids = (0..post.num_glyphs().unwrap())
965 .map(GlyphId16::new)
966 .map(|gid| (post.glyph_name(gid).unwrap(), gid))
967 .collect::<HashMap<_, _>>();
968
969 let (source, _) =
971 find_glyph_and_point_count(&glyf, &loca, gids["neither"].into(), 5).unwrap();
972 assert_eq!(
973 source, gids["neither"],
974 "a composite without any USE_MY_METRICS components should use its own metrics"
975 );
976
977 let (source, _) =
978 find_glyph_and_point_count(&glyf, &loca, gids["firstonly"].into(), 5).unwrap();
979 assert_eq!(
980 source, gids["first"],
981 "a composite with a single USE_MY_METRICS component should use that component's metrics"
982 );
983
984 let (source, _) = find_glyph_and_point_count(&glyf, &loca, gids["both"].into(), 5).unwrap();
985 assert_eq!(
986 source, gids["second"],
987 "a composite with multiple USE_MY_METRICS components should use the last flagged component's metrics"
988 );
989 }
990}