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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
//! The gvar table
include!("../../generated/generated_gvar.rs");
use std::collections::HashMap;
use indexmap::IndexMap;
use crate::{collections::HasLen, OffsetMarker};
use super::variations::{
PackedDeltas, PackedPointNumbers, Tuple, TupleVariationCount, TupleVariationHeader,
};
pub mod iup;
/// Variation data for a single glyph, before it is compiled
#[derive(Clone, Debug)]
pub struct GlyphVariations {
gid: GlyphId,
variations: Vec<GlyphDeltas>,
}
/// Glyph deltas for one point in the design space.
#[derive(Clone, Debug)]
pub struct GlyphDeltas {
peak_tuple: Tuple,
// start and end tuples of optional intermediate region
intermediate_region: Option<(Tuple, Tuple)>,
// (x, y) deltas or None for do not encode. One entry per point in the glyph.
deltas: Vec<GlyphDelta>,
best_point_packing: PackedPointNumbers,
}
/// A delta for a single value in a glyph.
///
/// This includes a flag indicating whether or not this delta is required (i.e
/// it cannot be interpolated from neighbouring deltas and coordinates).
/// This is only relevant for simple glyphs; interpolatable points may be omitted
/// in the final binary when doing so saves space.
/// See <https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#inferred-deltas-for-un-referenced-point-numbers>
/// for more information.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GlyphDelta {
pub x: i16,
pub y: i16,
/// This delta must be included, i.e. cannot be interpolated
pub required: bool,
}
/// An error representing invalid input when building a gvar table
#[derive(Clone, Debug)]
pub enum GvarInputError {
/// Glyph variations do not have the expected axis count
UnexpectedAxisCount {
gid: GlyphId,
expected: u16,
actual: u16,
},
/// A single glyph contains variations with inconsistent axis counts
InconsistentGlyphAxisCount(GlyphId),
/// A single glyph contains variations with different delta counts
InconsistentDeltaLength(GlyphId),
/// A variation in this glyph contains an intermediate region with a
/// different length than the peak.
InconsistentTupleLengths(GlyphId),
}
impl Gvar {
/// Construct a gvar table from a vector of per-glyph variations and the axis count.
///
/// Variations must be present for each glyph, but may be empty.
/// For non-empty variations, the axis count must be equal to the provided
/// axis count, as specified by the 'fvar' table.
pub fn new(
mut variations: Vec<GlyphVariations>,
axis_count: u16,
) -> Result<Self, GvarInputError> {
fn compute_shared_peak_tuples(glyphs: &[GlyphVariations]) -> Vec<Tuple> {
const MAX_SHARED_TUPLES: usize = 4095;
let mut peak_tuple_counts = IndexMap::new();
for glyph in glyphs {
glyph.count_peak_tuples(&mut peak_tuple_counts);
}
let mut to_share = peak_tuple_counts
.into_iter()
.filter(|(_, n)| *n > 1)
.collect::<Vec<_>>();
// prefer IndexMap::sort_by_key over HashMap::sort_unstable_by_key so the
// order of the shared tuples with equal count doesn't change randomly
// but is kept stable to ensure builds are deterministic.
to_share.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
to_share.truncate(MAX_SHARED_TUPLES);
to_share.into_iter().map(|(t, _)| t.to_owned()).collect()
}
for var in &variations {
var.validate()?;
}
if let Some(bad_var) = variations
.iter()
.find(|var| var.axis_count().is_some() && var.axis_count().unwrap() != axis_count)
{
return Err(GvarInputError::UnexpectedAxisCount {
gid: bad_var.gid,
expected: axis_count,
actual: bad_var.axis_count().unwrap(),
});
}
let shared = compute_shared_peak_tuples(&variations);
let shared_idx_map = shared
.iter()
.enumerate()
.map(|(i, x)| (x, i as u16))
.collect();
variations.sort_unstable_by_key(|g| g.gid);
let glyphs = variations
.into_iter()
.map(|raw_g| raw_g.build(&shared_idx_map))
.collect();
Ok(Gvar {
axis_count,
shared_tuples: SharedTuples::new(shared).into(),
glyph_variation_data_offsets: glyphs,
})
}
fn compute_flags(&self) -> GvarFlags {
let max_offset = self
.glyph_variation_data_offsets
.iter()
.fold(0, |acc, val| acc + val.length + val.length % 2);
if max_offset / 2 <= (u16::MAX as u32) {
GvarFlags::default()
} else {
GvarFlags::LONG_OFFSETS
}
}
fn compute_glyph_count(&self) -> u16 {
self.glyph_variation_data_offsets.len().try_into().unwrap()
}
fn compute_shared_tuples_offset(&self) -> u32 {
const BASE_OFFSET: usize = MajorMinor::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN // axis count
+ u16::RAW_BYTE_LEN // shared tuples count
+ Offset32::RAW_BYTE_LEN
+ u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN // glyph count, flags
+ u32::RAW_BYTE_LEN; // glyph_variation_data_array_offset
let bytes_per_offset = if self.compute_flags() == GvarFlags::LONG_OFFSETS {
u32::RAW_BYTE_LEN
} else {
u16::RAW_BYTE_LEN
};
let offsets_len = (self.glyph_variation_data_offsets.len() + 1) * bytes_per_offset;
(BASE_OFFSET + offsets_len).try_into().unwrap()
}
fn compute_data_array_offset(&self) -> u32 {
let shared_tuples_len: u32 =
(array_len(&self.shared_tuples) * self.axis_count as usize * 2)
.try_into()
.unwrap();
self.compute_shared_tuples_offset() + shared_tuples_len
}
fn compile_variation_data(&self) -> GlyphDataWriter<'_> {
GlyphDataWriter {
long_offsets: self.compute_flags() == GvarFlags::LONG_OFFSETS,
shared_tuples: &self.shared_tuples,
data: &self.glyph_variation_data_offsets,
}
}
}
/// Like [Iterator::max_by_key][1] but returns the first instead of last in case of a tie.
///
/// Intended to match Python's [max()][2] behavior.
///
/// [1]: https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.max_by_key
/// [2]: https://docs.python.org/3/library/functions.html#max
fn max_by_first_key<I, B, F>(iter: I, mut key: F) -> Option<I::Item>
where
I: Iterator,
B: Ord,
F: FnMut(&I::Item) -> B,
{
iter.fold(None, |max_elem: Option<(_, _)>, item| {
let item_key = key(&item);
match &max_elem {
// current item's key not greater than max key so far, keep max unchanged
Some((_, max_key)) if item_key <= *max_key => max_elem,
// either no max yet, or a new max found, update max
_ => Some((item, item_key)),
}
})
.map(|(item, _)| item)
}
impl GlyphVariations {
/// Construct a new set of variation deltas for a glyph.
pub fn new(gid: GlyphId, variations: Vec<GlyphDeltas>) -> Self {
Self { gid, variations }
}
/// called when we build gvar, so we only return errors in one place
fn validate(&self) -> Result<(), GvarInputError> {
let (axis_count, delta_len) = self
.variations
.first()
.map(|var| (var.peak_tuple.len(), var.deltas.len()))
.unwrap_or_default();
for var in &self.variations {
if var.peak_tuple.len() != axis_count {
return Err(GvarInputError::InconsistentGlyphAxisCount(self.gid));
}
if let Some((start, end)) = var.intermediate_region.as_ref() {
if start.len() != axis_count || end.len() != axis_count {
return Err(GvarInputError::InconsistentTupleLengths(self.gid));
}
}
if var.deltas.len() != delta_len {
return Err(GvarInputError::InconsistentDeltaLength(self.gid));
}
}
Ok(())
}
/// Will be `None` if there are no variations for this glyph
pub fn axis_count(&self) -> Option<u16> {
self.variations.first().map(|var| var.peak_tuple.len())
}
fn count_peak_tuples<'a>(&'a self, counter: &mut IndexMap<&'a Tuple, usize>) {
for tuple in &self.variations {
*counter.entry(&tuple.peak_tuple).or_default() += 1;
}
}
/// Determine if we should use 'shared point numbers'
///
/// If multiple tuple variations for a given glyph use the same point numbers,
/// it is possible to store this in the glyph table, avoiding duplicating
/// data.
///
/// This implementation is currently based on the one in fonttools, where it
/// is part of the compileTupleVariationStore method:
/// <https://github.com/fonttools/fonttools/blob/0a3360e52727cdefce2e9b28286b074faf99033c/Lib/fontTools/ttLib/tables/TupleVariation.py#L641>
///
/// # Note
///
/// There is likely room for some optimization here, depending on the
/// structure of the point numbers. If it is common for point numbers to only
/// vary by an item or two, it may be worth picking a set of shared points
/// that is a subset of multiple different tuples; this would mean you could
/// make some tuples include deltas that they might otherwise omit, but let
/// them omit their explicit point numbers.
///
/// For fonts with a large number of variations, this could produce reasonable
/// savings, at the cost of a significantly more complicated algorithm.
///
/// (issue <https://github.com/googlefonts/fontations/issues/634>)
fn compute_shared_points(&self) -> Option<PackedPointNumbers> {
let mut point_number_counts = IndexMap::new();
// count how often each set of numbers occurs
for deltas in &self.variations {
// for each set points, get compiled size + number of occurrences
let (_, count) = point_number_counts
.entry(&deltas.best_point_packing)
.or_insert_with(|| {
let size = deltas.best_point_packing.compute_size();
(size as usize, 0usize)
});
*count += 1;
}
// find the one that saves the most bytes; if multiple are tied, pick the
// first one like python max() does (Rust's max_by_key() would pick the last),
// so that we match the behavior of fonttools
let (pts, _) = max_by_first_key(
point_number_counts
.into_iter()
// no use sharing points if they only occur once
.filter(|(_, (_, count))| *count > 1),
|(_, (size, count))| (*count - 1) * *size,
)?;
Some(pts.to_owned())
}
fn build(self, shared_tuple_map: &HashMap<&Tuple, u16>) -> GlyphVariationData {
let shared_points = self.compute_shared_points();
let (tuple_headers, tuple_data): (Vec<_>, Vec<_>) = self
.variations
.into_iter()
.map(|tup| tup.build(shared_tuple_map, shared_points.as_ref()))
.unzip();
let mut temp = GlyphVariationData {
tuple_variation_headers: tuple_headers,
shared_point_numbers: shared_points,
per_tuple_data: tuple_data,
length: 0,
};
temp.length = temp.compute_size();
temp
}
}
impl GlyphDelta {
/// Create a new delta value.
pub fn new(x: i16, y: i16, required: bool) -> Self {
Self { x, y, required }
}
/// Create a new delta value that must be encoded (cannot be interpolated)
pub fn required(x: i16, y: i16) -> Self {
Self::new(x, y, true)
}
/// Create a new delta value that may be omitted (can be interpolated)
pub fn optional(x: i16, y: i16) -> Self {
Self::new(x, y, false)
}
}
/// The influence of a single axis on a variation region.
///
/// The values here end up serialized in the peak/start/end tuples in the
/// [`TupleVariationHeader`].
///
/// The name 'Tent' is taken from HarfBuzz.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Tent {
peak: F2Dot14,
min: F2Dot14,
max: F2Dot14,
}
impl Tent {
/// Construct a new tent from a peak value and optional intermediate values.
///
/// If the intermediate values are `None`, they will be inferred from the
/// peak value. If all of the intermediate values in all `Tent`s can be
/// inferred for a given variation, they can be omitted from the [`TupleVariationHeader`].
pub fn new(peak: F2Dot14, intermediate: Option<(F2Dot14, F2Dot14)>) -> Self {
let (min, max) = intermediate.unwrap_or_else(|| Tent::implied_intermediates_for_peak(peak));
Self { peak, min, max }
}
fn requires_intermediate(&self) -> bool {
(self.min, self.max) != Self::implied_intermediates_for_peak(self.peak)
}
fn implied_intermediates_for_peak(peak: F2Dot14) -> (F2Dot14, F2Dot14) {
(peak.min(F2Dot14::ZERO), peak.max(F2Dot14::ZERO))
}
}
impl GlyphDeltas {
/// Create a new set of deltas.
///
/// A None delta means do not explicitly encode, typically because IUP suggests
/// it isn't required.
pub fn new(tents: Vec<Tent>, deltas: Vec<GlyphDelta>) -> Self {
let peak_tuple = Tuple::new(tents.iter().map(|coords| coords.peak).collect());
// File size optimisation: if all the intermediates can be derived from
// the relevant peak values, don't serialize them.
// https://github.com/fonttools/fonttools/blob/b467579c/Lib/fontTools/ttLib/tables/TupleVariation.py#L184-L193
let intermediate_region = if tents.iter().any(Tent::requires_intermediate) {
Some(tents.iter().map(|tent| (tent.min, tent.max)).unzip())
} else {
None
};
// at construction time we build both iup optimized & not versions
// of ourselves, to determine what representation is most efficient;
// the caller will look at the generated packed points to decide which
// set should be shared.
let best_point_packing = Self::pick_best_point_number_repr(&deltas);
GlyphDeltas {
peak_tuple,
intermediate_region,
deltas,
best_point_packing,
}
}
// this is a type method just to expose it for testing, we call it before
// we finish instantiating self.
//
// we do a lot of duplicate work here with creating & throwing away
// buffers, and that can be improved at the cost of a bit more complexity
// <https://github.com/googlefonts/fontations/issues/635>
fn pick_best_point_number_repr(deltas: &[GlyphDelta]) -> PackedPointNumbers {
if deltas.iter().all(|d| d.required) {
return PackedPointNumbers::All;
}
let dense = Self::build_non_sparse_data(deltas);
let sparse = Self::build_sparse_data(deltas);
let dense_size = dense.compute_size();
let sparse_size = sparse.compute_size();
log::trace!("dense {dense_size}, sparse {sparse_size}");
if sparse_size < dense_size {
sparse.private_point_numbers.unwrap()
} else {
PackedPointNumbers::All
}
}
fn build_non_sparse_data(deltas: &[GlyphDelta]) -> GlyphTupleVariationData {
let (x_deltas, y_deltas) = deltas
.iter()
.map(|delta| (delta.x as i32, delta.y as i32))
.unzip();
GlyphTupleVariationData {
private_point_numbers: Some(PackedPointNumbers::All),
x_deltas: PackedDeltas::new(x_deltas),
y_deltas: PackedDeltas::new(y_deltas),
}
}
fn build_sparse_data(deltas: &[GlyphDelta]) -> GlyphTupleVariationData {
let (x_deltas, y_deltas) = deltas
.iter()
.filter_map(|delta| delta.required.then_some((delta.x as i32, delta.y as i32)))
.unzip();
let point_numbers = deltas
.iter()
.enumerate()
.filter_map(|(i, delta)| delta.required.then_some(i as u16))
.collect();
GlyphTupleVariationData {
private_point_numbers: Some(PackedPointNumbers::Some(point_numbers)),
x_deltas: PackedDeltas::new(x_deltas),
y_deltas: PackedDeltas::new(y_deltas),
}
}
// shared points is just "whatever points, if any, are shared." We are
// responsible for seeing if these are actually our points, in which case
// we are using shared points.
fn build(
self,
shared_tuple_map: &HashMap<&Tuple, u16>,
shared_points: Option<&PackedPointNumbers>,
) -> (TupleVariationHeader, GlyphTupleVariationData) {
let GlyphDeltas {
peak_tuple,
intermediate_region,
deltas,
best_point_packing: point_numbers,
} = self;
let (idx, peak_tuple) = match shared_tuple_map.get(&peak_tuple) {
Some(idx) => (Some(*idx), None),
None => (None, Some(peak_tuple)),
};
let has_private_points = Some(&point_numbers) != shared_points;
let (x_deltas, y_deltas) = match &point_numbers {
PackedPointNumbers::All => deltas.iter().map(|d| (d.x as i32, d.y as i32)).unzip(),
PackedPointNumbers::Some(pts) => pts
.iter()
.map(|idx| {
let delta = deltas[*idx as usize];
(delta.x as i32, delta.y as i32)
})
.unzip(),
};
let data = GlyphTupleVariationData {
private_point_numbers: has_private_points.then_some(point_numbers),
x_deltas: PackedDeltas::new(x_deltas),
y_deltas: PackedDeltas::new(y_deltas),
};
let data_size = data.compute_size();
let header = TupleVariationHeader::new(
data_size,
idx,
peak_tuple,
intermediate_region,
has_private_points,
);
(header, data)
}
}
/// The serializable representation of a glyph's variation data
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GlyphVariationData {
tuple_variation_headers: Vec<TupleVariationHeader>,
// optional; present if multiple variations have the same point numbers
shared_point_numbers: Option<PackedPointNumbers>,
per_tuple_data: Vec<GlyphTupleVariationData>,
/// calculated length required to store this data
///
/// we compute this once up front because we need to know it in a bunch
/// of different places (u32 because offsets are max u32)
length: u32,
}
/// The serializable representation of a single glyph tuple variation data
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
struct GlyphTupleVariationData {
// this is possibly shared, if multiple are identical for a given glyph
private_point_numbers: Option<PackedPointNumbers>,
x_deltas: PackedDeltas,
y_deltas: PackedDeltas,
}
impl GlyphTupleVariationData {
fn compute_size(&self) -> u16 {
self.private_point_numbers
.as_ref()
.map(PackedPointNumbers::compute_size)
.unwrap_or_default()
.checked_add(self.x_deltas.compute_size())
.unwrap()
.checked_add(self.y_deltas.compute_size())
.unwrap()
}
}
impl FontWrite for GlyphTupleVariationData {
fn write_into(&self, writer: &mut TableWriter) {
self.private_point_numbers.write_into(writer);
self.x_deltas.write_into(writer);
self.y_deltas.write_into(writer);
}
}
struct GlyphDataWriter<'a> {
long_offsets: bool,
shared_tuples: &'a SharedTuples,
data: &'a [GlyphVariationData],
}
impl FontWrite for GlyphDataWriter<'_> {
fn write_into(&self, writer: &mut TableWriter) {
if self.long_offsets {
let mut last = 0u32;
last.write_into(writer);
// write all the offsets
for glyph in self.data {
last += glyph.compute_size();
last.write_into(writer);
}
} else {
// for short offsets we divide the real offset by two; this means
// we will have to add padding if necessary
let mut last = 0u16;
last.write_into(writer);
// write all the offsets
for glyph in self.data {
let size = glyph.compute_size();
// ensure we're always rounding up to the next 2
let short_size = (size / 2) + size % 2;
last += short_size as u16;
last.write_into(writer);
}
}
// then write the shared tuples (should come here according to the spec)
// https://learn.microsoft.com/en-us/typography/opentype/spec/gvar#shared-tuples-array
// > The shared tuples array follows the GlyphVariationData offsets array at the end of the 'gvar' header.
self.shared_tuples.write_into(writer);
// then write the actual data
for glyph in self.data {
if !glyph.is_empty() {
glyph.write_into(writer);
if !self.long_offsets {
writer.pad_to_2byte_aligned();
}
}
}
}
}
impl GlyphVariationData {
fn compute_tuple_variation_count(&self) -> TupleVariationCount {
assert!(self.tuple_variation_headers.len() <= 4095);
let mut bits = self.tuple_variation_headers.len() as u16;
if self.shared_point_numbers.is_some() {
bits |= TupleVariationCount::SHARED_POINT_NUMBERS;
}
TupleVariationCount::from_bits(bits)
}
fn is_empty(&self) -> bool {
self.tuple_variation_headers.is_empty()
}
fn compute_data_offset(&self) -> u16 {
let header_len = self
.tuple_variation_headers
.iter()
.fold(0usize, |acc, header| {
acc.checked_add(header.compute_size() as usize).unwrap()
});
(header_len + TupleVariationCount::RAW_BYTE_LEN + u16::RAW_BYTE_LEN)
.try_into()
.unwrap()
}
fn compute_size(&self) -> u32 {
if self.is_empty() {
return 0;
}
let data_start = self.compute_data_offset() as u32;
let shared_point_len = self
.shared_point_numbers
.as_ref()
.map(|pts| pts.compute_size())
.unwrap_or_default() as u32;
let tuple_data_len = self
.per_tuple_data
.iter()
.fold(0u32, |acc, tup| acc + tup.compute_size() as u32);
data_start + shared_point_len + tuple_data_len
}
}
impl Extend<F2Dot14> for Tuple {
fn extend<T: IntoIterator<Item = F2Dot14>>(&mut self, iter: T) {
self.values.extend(iter);
}
}
impl Validate for GlyphVariationData {
fn validate_impl(&self, ctx: &mut ValidationCtx) {
const MAX_TUPLE_VARIATIONS: usize = 4095;
if !(0..=MAX_TUPLE_VARIATIONS).contains(&self.tuple_variation_headers.len()) {
ctx.in_field("tuple_variation_headers", |ctx| {
ctx.report("expected 0-4095 tuple variation tables")
})
}
}
}
impl FontWrite for GlyphVariationData {
fn write_into(&self, writer: &mut TableWriter) {
self.compute_tuple_variation_count().write_into(writer);
self.compute_data_offset().write_into(writer);
self.tuple_variation_headers.write_into(writer);
self.shared_point_numbers.write_into(writer);
self.per_tuple_data.write_into(writer);
}
}
impl HasLen for SharedTuples {
fn len(&self) -> usize {
self.tuples.len()
}
}
impl FontWrite for TupleVariationCount {
fn write_into(&self, writer: &mut TableWriter) {
self.bits().write_into(writer)
}
}
impl std::fmt::Display for GvarInputError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GvarInputError::UnexpectedAxisCount {
gid,
expected,
actual,
} => {
write!(
f,
"Expected {} axes for glyph {}, got {}",
expected, gid, actual
)
}
GvarInputError::InconsistentGlyphAxisCount(gid) => write!(
f,
"Glyph {gid} contains variations with inconsistent axis counts"
),
GvarInputError::InconsistentDeltaLength(gid) => write!(
f,
"Glyph {gid} contains variations with inconsistent delta counts"
),
GvarInputError::InconsistentTupleLengths(gid) => write!(
f,
"Glyph {gid} contains variations with inconsistent intermediate region sizes"
),
}
}
}
impl std::error::Error for GvarInputError {}
#[cfg(test)]
mod tests {
use super::*;
/// Helper function to concisely state test cases without intermediates.
fn peaks(peaks: Vec<F2Dot14>) -> Vec<Tent> {
peaks
.into_iter()
.map(|peak| Tent::new(peak, None))
.collect()
}
#[test]
fn gvar_smoke_test() {
let _ = env_logger::builder().is_test(true).try_init();
let table = Gvar::new(
vec![
GlyphVariations::new(GlyphId::new(0), vec![]),
GlyphVariations::new(
GlyphId::new(1),
vec![GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(30, 31),
GlyphDelta::required(40, 41),
GlyphDelta::required(-50, -49),
GlyphDelta::required(101, 102),
GlyphDelta::required(10, 11),
],
)],
),
GlyphVariations::new(
GlyphId::new(2),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(11, -20),
GlyphDelta::required(69, -41),
GlyphDelta::required(-69, 49),
GlyphDelta::required(168, 101),
GlyphDelta::required(1, 2),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(0.8), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(3, -200),
GlyphDelta::required(4, -500),
GlyphDelta::required(5, -800),
GlyphDelta::required(6, -1200),
GlyphDelta::required(7, -1500),
],
),
],
),
],
2,
)
.unwrap();
let g2 = &table.glyph_variation_data_offsets[1];
let computed = g2.compute_size();
let actual = crate::dump_table(g2).unwrap().len();
assert_eq!(computed as usize, actual);
let bytes = crate::dump_table(&table).unwrap();
let gvar = read_fonts::tables::gvar::Gvar::read(FontData::new(&bytes)).unwrap();
assert_eq!(gvar.version(), MajorMinor::VERSION_1_0);
assert_eq!(gvar.shared_tuple_count(), 1);
assert_eq!(gvar.glyph_count(), 3);
// Check offsets, the shared_tuples_offset should point to just after the table's header
assert_eq!(gvar.shared_tuples_offset(), Offset32::new(28));
assert_eq!(gvar.glyph_variation_data_array_offset(), 32);
let g1 = gvar.glyph_variation_data(GlyphId::new(1)).unwrap().unwrap();
let g1tup = g1.tuples().collect::<Vec<_>>();
assert_eq!(g1tup.len(), 1);
let (x, y): (Vec<_>, Vec<_>) = g1tup[0].deltas().map(|d| (d.x_delta, d.y_delta)).unzip();
assert_eq!(x, vec![30, 40, -50, 101, 10]);
assert_eq!(y, vec![31, 41, -49, 102, 11]);
let g2 = gvar.glyph_variation_data(GlyphId::new(2)).unwrap().unwrap();
let g2tup = g2.tuples().collect::<Vec<_>>();
assert_eq!(g2tup.len(), 2);
let (x, y): (Vec<_>, Vec<_>) = g2tup[0].deltas().map(|d| (d.x_delta, d.y_delta)).unzip();
assert_eq!(x, vec![11, 69, -69, 168, 1]);
assert_eq!(y, vec![-20, -41, 49, 101, 2]);
let (x, y): (Vec<_>, Vec<_>) = g2tup[1].deltas().map(|d| (d.x_delta, d.y_delta)).unzip();
assert_eq!(x, vec![3, 4, 5, 6, 7]);
assert_eq!(y, vec![-200, -500, -800, -1200, -1500]);
}
#[test]
fn use_iup_when_appropriate() {
// IFF iup provides space savings, we should prefer it.
let _ = env_logger::builder().is_test(true).try_init();
let gid = GlyphId::new(0);
let table = Gvar::new(
vec![GlyphVariations::new(
gid,
vec![GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(30, 31),
GlyphDelta::optional(30, 31),
GlyphDelta::optional(30, 31),
GlyphDelta::required(101, 102),
GlyphDelta::required(10, 11),
GlyphDelta::optional(10, 11),
],
)],
)],
2,
)
.unwrap();
let bytes = crate::dump_table(&table).unwrap();
let gvar = read_fonts::tables::gvar::Gvar::read(FontData::new(&bytes)).unwrap();
assert_eq!(gvar.version(), MajorMinor::VERSION_1_0);
assert_eq!(gvar.shared_tuple_count(), 0);
assert_eq!(gvar.glyph_count(), 1);
let g1 = gvar.glyph_variation_data(gid).unwrap().unwrap();
let g1tup = g1.tuples().collect::<Vec<_>>();
assert_eq!(g1tup.len(), 1);
let tuple_variation = &g1tup[0];
assert!(!tuple_variation.has_deltas_for_all_points());
assert_eq!(
vec![0, 3, 4],
tuple_variation.point_numbers().collect::<Vec<_>>()
);
let points: Vec<_> = tuple_variation
.deltas()
.map(|d| (d.x_delta, d.y_delta))
.collect();
assert_eq!(points, vec![(30, 31), (101, 102), (10, 11)]);
}
#[test]
fn disregard_iup_when_appropriate() {
// if the cost of encoding the list of points is greater than the savings
// from omitting some deltas, we should just encode explicit zeros
let points = vec![
GlyphDelta::required(1, 2),
GlyphDelta::required(3, 4),
GlyphDelta::required(5, 6),
GlyphDelta::optional(5, 6),
GlyphDelta::required(7, 8),
];
let gid = GlyphId::new(0);
let table = Gvar::new(
vec![GlyphVariations::new(
gid,
vec![GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
points,
)],
)],
2,
)
.unwrap();
let bytes = crate::dump_table(&table).unwrap();
let gvar = read_fonts::tables::gvar::Gvar::read(FontData::new(&bytes)).unwrap();
assert_eq!(gvar.version(), MajorMinor::VERSION_1_0);
assert_eq!(gvar.shared_tuple_count(), 0);
assert_eq!(gvar.glyph_count(), 1);
let g1 = gvar.glyph_variation_data(gid).unwrap().unwrap();
let g1tup = g1.tuples().collect::<Vec<_>>();
assert_eq!(g1tup.len(), 1);
let tuple_variation = &g1tup[0];
assert!(tuple_variation.has_deltas_for_all_points());
let points: Vec<_> = tuple_variation
.deltas()
.map(|d| (d.x_delta, d.y_delta))
.collect();
assert_eq!(points, vec![(1, 2), (3, 4), (5, 6), (5, 6), (7, 8)]);
}
#[test]
fn share_points() {
let _ = env_logger::builder().is_test(true).try_init();
let variations = GlyphVariations::new(
GlyphId::new(0),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(1, 2),
GlyphDelta::optional(3, 4),
GlyphDelta::required(5, 6),
GlyphDelta::optional(5, 6),
GlyphDelta::required(7, 8),
GlyphDelta::optional(7, 8),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0), F2Dot14::from_f32(-1.0)]),
vec![
GlyphDelta::required(10, 20),
GlyphDelta::optional(30, 40),
GlyphDelta::required(50, 60),
GlyphDelta::optional(50, 60),
GlyphDelta::required(70, 80),
GlyphDelta::optional(70, 80),
],
),
],
);
assert_eq!(
variations.compute_shared_points(),
Some(PackedPointNumbers::Some(vec![0, 2, 4]))
)
}
#[test]
fn share_all_points() {
let variations = GlyphVariations::new(
GlyphId::new(0),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(1, 2),
GlyphDelta::required(3, 4),
GlyphDelta::required(5, 6),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0), F2Dot14::from_f32(-1.0)]),
vec![
GlyphDelta::required(2, 4),
GlyphDelta::required(6, 8),
GlyphDelta::required(7, 9),
],
),
],
);
let shared_tups = HashMap::new();
let built = variations.build(&shared_tups);
assert_eq!(built.shared_point_numbers, Some(PackedPointNumbers::All))
}
// three tuples with three different packedpoint representations means
// that we should have no shared points
#[test]
fn dont_share_unique_points() {
let variations = GlyphVariations::new(
GlyphId::new(0),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(1, 2),
GlyphDelta::optional(3, 4),
GlyphDelta::required(5, 6),
GlyphDelta::optional(5, 6),
GlyphDelta::required(7, 8),
GlyphDelta::optional(7, 8),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0), F2Dot14::from_f32(-1.0)]),
vec![
GlyphDelta::required(10, 20),
GlyphDelta::required(35, 40),
GlyphDelta::required(50, 60),
GlyphDelta::optional(50, 60),
GlyphDelta::required(70, 80),
GlyphDelta::optional(70, 80),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(0.5), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::required(1, 2),
GlyphDelta::optional(3, 4),
GlyphDelta::required(5, 6),
GlyphDelta::optional(5, 6),
GlyphDelta::optional(7, 8),
GlyphDelta::optional(7, 8),
],
),
],
);
let shared_tups = HashMap::new();
let built = variations.build(&shared_tups);
assert!(built.shared_point_numbers.is_none());
}
// comparing our behaviour against what we know fonttools does.
#[test]
#[allow(non_snake_case)]
fn oswald_Lcaron() {
let _ = env_logger::builder().is_test(true).try_init();
// in this glyph, it is more efficient to encode all points for the first
// tuple, but sparse points for the second (the single y delta in the
// second tuple means you can't encode the y-deltas as 'all zero')
let variations = GlyphVariations::new(
GlyphId::new(0),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0), F2Dot14::from_f32(-1.0)]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(35, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::required(-24, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(26, 15),
GlyphDelta::optional(0, 0),
GlyphDelta::required(46, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
],
);
assert!(variations.compute_shared_points().is_none());
let tups = HashMap::new();
let built = variations.build(&tups);
assert_eq!(
built.per_tuple_data[0].private_point_numbers,
Some(PackedPointNumbers::All)
);
assert_eq!(
built.per_tuple_data[1].private_point_numbers,
Some(PackedPointNumbers::Some(vec![1, 3]))
);
}
#[test]
fn compute_shared_points_is_deterministic() {
// The deltas for glyph "etatonos.sc.ss06" in GoogleSans-VF are such that the
// TupleVariationStore's shared set of point numbers could potentionally be
// computed as either PackedPointNumbers::All or PackedPointNumbers::Some([1, 3])
// without affecting the size (or correctness) of the serialized data.
// However we want to ensure that the result is deterministic, and doesn't
// depend on e.g. HashMap random iteration order.
// https://github.com/googlefonts/fontc/issues/647
let _ = env_logger::builder().is_test(true).try_init();
let variations = GlyphVariations::new(
GlyphId::NOTDEF,
vec![
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(-1.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(0.0),
]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(-17, -4),
GlyphDelta::optional(0, 0),
GlyphDelta::required(-28, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(1.0),
F2Dot14::from_f32(0.0),
]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(0, -10),
GlyphDelta::optional(0, 0),
GlyphDelta::required(34, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(-1.0),
]),
vec![
GlyphDelta::required(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(1.0),
]),
vec![
GlyphDelta::required(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(-1.0),
F2Dot14::from_f32(1.0),
F2Dot14::from_f32(0.0),
]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(-1, 10),
GlyphDelta::optional(0, 0),
GlyphDelta::required(-9, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(-1.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(-1.0),
]),
vec![
GlyphDelta::required(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![
F2Dot14::from_f32(-1.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(1.0),
]),
vec![
GlyphDelta::required(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
],
);
assert_eq!(
variations.compute_shared_points(),
// Also PackedPointNumbers::All would work, but Some([1, 3]) happens
// to be the first one that fits the bill when iterating over the
// tuple variations in the order they are listed for this glyph.
Some(PackedPointNumbers::Some(vec![1, 3]))
);
}
// when using short offsets we store (real offset / 2), so all offsets must
// be even, which means when we have an odd number of bytes we have to pad.
fn make_31_bytes_of_variation_data() -> Vec<GlyphDeltas> {
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0), F2Dot14::from_f32(-1.0)]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(35, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::required(-24, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::optional(0, 0),
],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0), F2Dot14::from_f32(1.0)]),
vec![
GlyphDelta::optional(0, 0),
GlyphDelta::required(26, 15),
GlyphDelta::optional(0, 0),
GlyphDelta::required(46, 0),
GlyphDelta::optional(0, 0),
GlyphDelta::required(1, 0),
],
),
]
}
// sanity checking my input data for two subsequent tests
#[test]
fn who_tests_the_testers() {
let variations = GlyphVariations::new(GlyphId::NOTDEF, make_31_bytes_of_variation_data());
let mut tupl_map = HashMap::new();
// without shared tuples this would be 39 bytes
assert_eq!(variations.clone().build(&tupl_map).length, 39);
// to get our real size we need to mock up the shared tuples:
tupl_map.insert(&variations.variations[0].peak_tuple, 1);
tupl_map.insert(&variations.variations[1].peak_tuple, 2);
let built = variations.clone().build(&tupl_map);
// we need an odd number to test impact of padding
assert_eq!(built.length, 31);
}
fn assert_test_offset_packing(n_glyphs: u16, should_be_short: bool) {
let (offset_len, data_len, expected_flags) = if should_be_short {
// when using short offset we need to pad data to ensure offset is even
(u16::RAW_BYTE_LEN, 32, GvarFlags::empty())
} else {
(u32::RAW_BYTE_LEN, 31, GvarFlags::LONG_OFFSETS)
};
let test_data = make_31_bytes_of_variation_data();
let a_small_number_of_variations = (0..n_glyphs)
.map(|i| GlyphVariations::new(GlyphId::from(i), test_data.clone()))
.collect();
let gvar = Gvar::new(a_small_number_of_variations, 2).unwrap();
assert_eq!(gvar.compute_flags(), expected_flags);
let writer = gvar.compile_variation_data();
let mut sink = TableWriter::default();
writer.write_into(&mut sink);
let bytes = sink.into_data().bytes;
let expected_len = (n_glyphs + 1) as usize * offset_len // offsets
+ 8 // shared tuples TODO remove magic number
+ data_len * n_glyphs as usize; // rounded size of each glyph
assert_eq!(bytes.len(), expected_len);
let dumped = crate::dump_table(&gvar).unwrap();
let loaded = read_fonts::tables::gvar::Gvar::read(FontData::new(&dumped)).unwrap();
assert_eq!(loaded.glyph_count(), n_glyphs);
assert_eq!(loaded.flags(), expected_flags);
assert!(loaded
.glyph_variation_data_offsets()
.iter()
.map(|off| off.unwrap().get())
.enumerate()
.all(|(i, off)| off as usize == i * data_len));
}
#[test]
fn prefer_short_offsets() {
let _ = env_logger::builder().is_test(true).try_init();
assert_test_offset_packing(5, true);
}
#[test]
fn use_long_offsets_when_necessary() {
// 2**16 * 2 / (31 + 1 padding) (bytes per tuple) = 4096 should be the first
// overflow
let _ = env_logger::builder().is_test(true).try_init();
assert_test_offset_packing(4095, true);
assert_test_offset_packing(4096, false);
assert_test_offset_packing(4097, false);
}
#[test]
fn shared_tuples_stable_order() {
// Test that shared tuples are sorted stably and builds reproducible
// https://github.com/googlefonts/fontc/issues/647
let mut variations = Vec::new();
for i in 0..2 {
variations.push(GlyphVariations::new(
GlyphId::new(i),
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0)]),
vec![GlyphDelta::required(10, 20)],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(-1.0)]),
vec![GlyphDelta::required(-10, -20)],
),
],
))
}
for _ in 0..10 {
let table = Gvar::new(variations.clone(), 1).unwrap();
let bytes = crate::dump_table(&table).unwrap();
let gvar = read_fonts::tables::gvar::Gvar::read(FontData::new(&bytes)).unwrap();
assert_eq!(gvar.shared_tuple_count(), 2);
assert_eq!(
gvar.shared_tuples()
.unwrap()
.tuples()
.iter()
.map(|t| t.unwrap().values.to_vec())
.collect::<Vec<_>>(),
vec![vec![F2Dot14::from_f32(1.0)], vec![F2Dot14::from_f32(-1.0)]]
);
}
}
#[test]
fn unexpected_axis_count() {
let variations = GlyphVariations::new(
GlyphId::NOTDEF,
vec![
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0)]),
vec![GlyphDelta::required(1, 2)],
),
GlyphDeltas::new(
peaks(vec![F2Dot14::from_f32(1.0)]),
vec![GlyphDelta::required(1, 2)],
),
],
);
let gvar = Gvar::new(vec![variations], 2);
assert!(matches!(
gvar,
Err(GvarInputError::UnexpectedAxisCount {
gid: GlyphId::NOTDEF,
expected: 2,
actual: 1
})
));
}
#[test]
fn empty_gvar_has_expected_axis_count() {
let variations = GlyphVariations::new(GlyphId::NOTDEF, vec![]);
let gvar = Gvar::new(vec![variations], 2).unwrap();
assert_eq!(gvar.axis_count, 2);
}
#[test]
/// Test the logic for determining whether individual intermediates need to
/// be serialised in the context of their peak coordinates.
fn intermediates_only_when_explicit_needed() {
let any_points = vec![]; // could be anything
// If an intermediate is not provided, one SHOULD NOT be serialised.
let deltas = GlyphDeltas::new(
vec![Tent::new(F2Dot14::from_f32(0.5), None)],
any_points.clone(),
);
assert_eq!(deltas.intermediate_region, None);
// If an intermediate is provided but is equal to the implicit
// intermediate from the peak, it SHOULD NOT be serialised.
let deltas = GlyphDeltas::new(
vec![Tent::new(
F2Dot14::from_f32(0.5),
Some(Tent::implied_intermediates_for_peak(F2Dot14::from_f32(0.5))),
)],
any_points.clone(),
);
assert_eq!(deltas.intermediate_region, None);
// If an intermediate is provided and it is not equal to the implicit
// intermediate from the peak, it SHOULD be serialised.
let deltas = GlyphDeltas::new(
vec![Tent::new(
F2Dot14::from_f32(0.5),
Some((F2Dot14::from_f32(-0.3), F2Dot14::from_f32(0.4))),
)],
any_points.clone(),
);
assert_eq!(
deltas.intermediate_region,
Some((
Tuple::new(vec![F2Dot14::from_f32(-0.3)]),
Tuple::new(vec![F2Dot14::from_f32(0.4)]),
))
);
}
#[test]
/// Test the logic for determining whether multiple intermediates need to be
/// serialised in the context of their peak coordinates and each other.
fn intermediates_only_when_at_least_one_needed() {
let any_points = vec![]; // could be anything
// If every intermediate can be implied, none should be serialised.
let deltas = GlyphDeltas::new(
vec![
Tent::new(F2Dot14::from_f32(0.5), None),
Tent::new(F2Dot14::from_f32(0.5), None),
],
any_points.clone(),
);
assert_eq!(deltas.intermediate_region, None);
// If even one intermediate cannot be implied, all should be serialised.
let deltas = GlyphDeltas::new(
vec![
Tent::new(F2Dot14::from_f32(0.5), None),
Tent::new(F2Dot14::from_f32(0.5), None),
Tent::new(
F2Dot14::from_f32(0.5),
Some((F2Dot14::from_f32(-0.3), F2Dot14::from_f32(0.4))),
),
],
any_points,
);
assert_eq!(
deltas.intermediate_region,
Some((
Tuple::new(vec![
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(0.0),
F2Dot14::from_f32(-0.3)
]),
Tuple::new(vec![
F2Dot14::from_f32(0.5),
F2Dot14::from_f32(0.5),
F2Dot14::from_f32(0.4)
]),
))
);
}
}