read-fonts 0.46.0

Reading OpenType font files.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
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
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
//! Metrics in a caller's own units.

use super::{
    Decoration, GlyphExtents, GlyphMetrics, LineBox, LineExtents, Metrics, ScriptMetrics,
    StyleMetrics,
};
use crate::model::glyph::GlyphSourceOrder;
use types::{BoundingBox, F26Dot6, F48Dot16, Fixed, GlyphId};

/// Converts a measurement in font units into a caller's own units.
///
/// Written by whatever owns scaling in a text stack: a shaper, or the bridge
/// between one and this crate. Callers that want font units read them from
/// [`GlyphMetrics`], [`Metrics`] and [`StyleMetrics`] and never implement this.
///
/// An implementation chooses the number format, the rounding, and the order
/// of operations for each axis. This crate defines how measurements combine
/// into a metric.
///
/// The arithmetic is part of the trait for the same reason: an
/// implementation decides what an overflowing sum does and which way a
/// halved odd number rounds.
pub trait Scale {
    /// What a scaled measurement is expressed as.
    type Value: Copy;

    /// Returns `a` plus `b`.
    ///
    /// This and the two below take no scale. They describe
    /// [`Value`](Self::Value) itself, so every scale of that type answers
    /// them alike.
    fn add(a: Self::Value, b: Self::Value) -> Self::Value;

    /// Returns `a` less `b`.
    fn sub(a: Self::Value, b: Self::Value) -> Self::Value;

    /// Returns half of `value`.
    fn half(value: Self::Value) -> Self::Value;

    /// Scales a measurement along the x axis.
    fn scale_x(&self, value: F48Dot16) -> Self::Value;

    /// Scales a measurement along the y axis.
    ///
    /// Separate from [`scale_x`](Self::scale_x) because the two axes need
    /// not agree, and because a caller whose y runs down the page says so
    /// here.
    fn scale_y(&self, value: F48Dot16) -> Self::Value;

    /// Scales where a glyph's ink sits.
    ///
    /// One call rather than four, so that a scale running the other way up
    /// settles in one place what that means for a bearing and a size. The
    /// scale also decides whether to round the box's corners before scaling.
    fn scale_glyph_extents(&self, extents: GlyphExtents<F48Dot16>) -> GlyphExtents<Self::Value>;

    /// Scales a region given by its corners.
    ///
    /// One call for the same reason as [`scale_glyph_extents`](Self::scale_glyph_extents):
    /// a scale running the other way up decides here which corner ends up
    /// least.
    fn scale_rect(&self, bounds: BoundingBox<F48Dot16>) -> BoundingBox<Self::Value>;

    /// Returns the size in pixels per em, if the scale has one.
    ///
    /// Embedded bitmaps are measured from the strike selected for this size.
    /// `None`, the default, selects the largest strike.
    fn ppem(&self) -> Option<f32> {
        None
    }
}

/// Scales design-unit metrics to 26.6 pixels with 16.16 fixed-point
/// arithmetic.
///
/// Sums saturate and halves round toward negative infinity. A measurement
/// with a fraction is rounded to a whole unit before it is scaled;
/// [`ScaleF32`] keeps the fraction.
#[derive(Copy, Clone, Debug)]
pub struct Scale26Dot6 {
    x: Fixed,
    y: Fixed,
    ppem: f32,
}

impl Scale26Dot6 {
    /// Creates a scale with a separate size for each axis.
    pub fn new(x_ppem: f32, y_ppem: f32, units_per_em: u16) -> Self {
        Self {
            x: Self::factor(x_ppem, units_per_em),
            y: Self::factor(y_ppem, units_per_em),
            ppem: x_ppem.max(y_ppem),
        }
    }

    /// Creates a scale that maps `units_per_em` font units to `ppem` pixels.
    pub fn from_ppem(ppem: f32, units_per_em: u16) -> Self {
        Self::new(ppem, ppem, units_per_em)
    }

    /// Returns the factor that converts whole font units to 26.6 pixels.
    ///
    /// The factor includes the conversion to 1/64 pixel, so a 16.16 multiply
    /// of a whole design unit produces 26.6 bits.
    fn factor(ppem: f32, units_per_em: u16) -> Fixed {
        Fixed::from_bits((ppem * 64.0) as i32) / Fixed::from_bits(units_per_em.max(1) as i32)
    }

    fn scale(value: F48Dot16, factor: Fixed) -> F26Dot6 {
        F26Dot6::from_bits((Fixed::from_bits(value.to_i32()) * factor).to_bits())
    }
}

impl Scale for Scale26Dot6 {
    type Value = F26Dot6;

    fn add(a: F26Dot6, b: F26Dot6) -> F26Dot6 {
        a.saturating_add(b)
    }

    fn sub(a: F26Dot6, b: F26Dot6) -> F26Dot6 {
        a.saturating_sub(b)
    }

    fn half(value: F26Dot6) -> F26Dot6 {
        F26Dot6::from_bits(value.to_bits() >> 1)
    }

    fn scale_x(&self, value: F48Dot16) -> F26Dot6 {
        Self::scale(value, self.x)
    }

    fn scale_y(&self, value: F48Dot16) -> F26Dot6 {
        Self::scale(value, self.y)
    }

    fn scale_glyph_extents(&self, e: GlyphExtents<F48Dot16>) -> GlyphExtents<F26Dot6> {
        if e.width <= F48Dot16::ZERO || e.height <= F48Dot16::ZERO {
            return GlyphExtents::default();
        }
        // Match FreeType's FT_RoundFix: ties round away from zero.
        let round = |value: F48Dot16| {
            let bits = value.to_bits();
            F48Dot16::from_bits(bits.wrapping_add(0x8000 - i64::from(bits < 0)) & !0xffff)
        };
        let left = round(e.x_bearing);
        let top = round(e.y_bearing);
        let right = round(e.x_bearing + e.width);
        let bottom = round(e.y_bearing - e.height);
        GlyphExtents {
            x_bearing: self.scale_x(left),
            y_bearing: self.scale_y(top),
            width: self.scale_x(right - left),
            height: self.scale_y(top - bottom),
        }
    }

    fn scale_rect(&self, b: BoundingBox<F48Dot16>) -> BoundingBox<F26Dot6> {
        BoundingBox {
            x_min: self.scale_x(b.x_min),
            y_min: self.scale_y(b.y_min),
            x_max: self.scale_x(b.x_max),
            y_max: self.scale_y(b.y_max),
        }
    }

    fn ppem(&self) -> Option<f32> {
        Some(self.ppem)
    }
}

/// Scales font units to `f32` pixels.
///
/// Nothing here rounds, so a measurement carrying a fraction keeps it, which
/// [`Scale26Dot6`] does not.
#[derive(Copy, Clone, Debug)]
pub struct ScaleF32 {
    x: f32,
    y: f32,
    ppem: f32,
}

impl ScaleF32 {
    /// Creates a scale with a separate size for each axis.
    pub fn new(x_ppem: f32, y_ppem: f32, units_per_em: u16) -> Self {
        let per_unit = |ppem: f32| ppem / units_per_em.max(1) as f32;
        Self {
            x: per_unit(x_ppem),
            y: per_unit(y_ppem),
            ppem: x_ppem.max(y_ppem),
        }
    }

    /// Creates a scale that maps `units_per_em` font units to `ppem` pixels.
    pub fn from_ppem(ppem: f32, units_per_em: u16) -> Self {
        Self::new(ppem, ppem, units_per_em)
    }
}

impl Scale for ScaleF32 {
    type Value = f32;

    fn add(a: f32, b: f32) -> f32 {
        a + b
    }

    fn sub(a: f32, b: f32) -> f32 {
        a - b
    }

    fn half(value: f32) -> f32 {
        value * 0.5
    }

    fn scale_x(&self, value: F48Dot16) -> f32 {
        value.to_f32() * self.x
    }

    fn scale_y(&self, value: F48Dot16) -> f32 {
        value.to_f32() * self.y
    }

    fn scale_glyph_extents(&self, e: GlyphExtents<F48Dot16>) -> GlyphExtents<f32> {
        GlyphExtents {
            x_bearing: self.scale_x(e.x_bearing),
            y_bearing: self.scale_y(e.y_bearing),
            width: self.scale_x(e.width),
            height: self.scale_y(e.height),
        }
    }

    fn scale_rect(&self, b: BoundingBox<F48Dot16>) -> BoundingBox<f32> {
        BoundingBox {
            x_min: self.scale_x(b.x_min),
            y_min: self.scale_y(b.y_min),
            x_max: self.scale_x(b.x_max),
            y_max: self.scale_y(b.y_max),
        }
    }

    fn ppem(&self) -> Option<f32> {
        Some(self.ppem)
    }
}

/// Measurements of a font as a whole, in a caller's own units.
///
/// A view rather than a set of scaled fields, so reading one measurement
/// does not compute the rest. What carries no unit, such as the glyph count,
/// is reported unchanged.
#[derive(Clone, Copy)]
pub struct ScaledMetrics<'a, S: Scale> {
    metrics: &'a Metrics,
    scale: S,
}

impl<'a, S: Scale> ScaledMetrics<'a, S> {
    pub(crate) fn new(metrics: &'a Metrics, scale: S) -> Self {
        Self { metrics, scale }
    }

    /// Returns the number of glyphs in the font.
    #[inline]
    pub fn num_glyphs(&self) -> u32 {
        self.metrics.num_glyphs
    }

    /// Returns the size of the font's design em.
    #[inline]
    pub fn units_per_em(&self) -> u16 {
        self.metrics.units_per_em
    }

    /// Returns the box enclosing every glyph in the font.
    #[inline]
    pub fn bounds(&self) -> BoundingBox<S::Value> {
        self.scale.scale_rect(self.metrics.bounds)
    }

    /// Returns the ascender, descender and gap for horizontal text.
    ///
    /// Resolved as [`Metrics::h_line`] resolves it, with each end
    /// scaled on its own so that a caller subtracting them gets the height
    /// the glyph metrics report for a font that stacks by this line.
    #[inline]
    pub fn h_line(&self) -> Option<LineBox<S::Value>> {
        self.metrics.h_line().map(|line| self.scale_line_y(line))
    }

    /// Returns the line `hhea` provides.
    #[inline]
    pub fn hhea_line(&self) -> Option<LineBox<S::Value>> {
        self.metrics.hhea_line.map(|line| self.scale_line_y(line))
    }

    /// Returns the typographic line `OS/2` provides.
    #[inline]
    pub fn typo_line(&self) -> Option<LineBox<S::Value>> {
        self.metrics.typo_line.map(|line| self.scale_line_y(line))
    }

    /// Returns whether the font asks for its typographic line to be read.
    #[inline]
    pub fn use_typo_metrics(&self) -> bool {
        self.metrics.use_typo_metrics
    }

    /// Returns the line `vhea` provides, where the font has one.
    ///
    /// A vertical line runs across the page, so its measurements scale along
    /// x where a horizontal line's scale along y.
    #[inline]
    pub fn vhea_line(&self) -> Option<LineBox<S::Value>> {
        self.metrics.vhea_line.map(|line| LineBox {
            ascender: self.scale.scale_x(line.ascender),
            descender: self.scale.scale_x(line.descender),
            line_gap: self.scale.scale_x(line.line_gap),
        })
    }

    /// Returns the height of a lowercase letter, where the font provides one.
    #[inline]
    pub fn x_height(&self) -> Option<S::Value> {
        self.scaled_y(self.metrics.x_height)
    }

    /// Returns the height of a capital letter, where the font provides one.
    #[inline]
    pub fn cap_height(&self) -> Option<S::Value> {
        self.scaled_y(self.metrics.cap_height)
    }

    /// Returns the widest advance in the font, where it provides one.
    #[inline]
    pub fn max_h_advance(&self) -> Option<S::Value> {
        self.metrics
            .max_h_advance
            .map(|value| self.scale.scale_x(value))
    }

    /// Returns the tallest advance in the font, where it provides one.
    #[inline]
    pub fn max_v_advance(&self) -> Option<S::Value> {
        self.scaled_y(self.metrics.max_v_advance)
    }

    /// Returns the average advance in the font, where it provides one.
    #[inline]
    pub fn average_char_width(&self) -> Option<S::Value> {
        self.metrics
            .average_char_width
            .map(|value| self.scale.scale_x(value))
    }

    /// Returns the line outside which the font asks not to be clipped.
    #[inline]
    pub fn win_line(&self) -> Option<LineExtents<S::Value>> {
        self.metrics.win_line.map(|line| self.scale_line(line))
    }

    #[inline]
    fn scale_line_y(&self, line: LineBox<F48Dot16>) -> LineBox<S::Value> {
        LineBox {
            ascender: self.scale.scale_y(line.ascender),
            descender: self.scale.scale_y(line.descender),
            line_gap: self.scale.scale_y(line.line_gap),
        }
    }

    #[inline]
    fn scale_line(&self, line: LineExtents<F48Dot16>) -> LineExtents<S::Value> {
        LineExtents {
            ascender: self.scale.scale_y(line.ascender),
            descender: self.scale.scale_y(line.descender),
        }
    }

    #[inline]
    fn scaled_y(&self, value: Option<F48Dot16>) -> Option<S::Value> {
        value.map(|value| self.scale.scale_y(value))
    }
}

impl Metrics {
    /// Returns these metrics in the units `scale` describes.
    #[inline]
    pub fn scaled<S: Scale>(&self, scale: S) -> ScaledMetrics<'_, S> {
        ScaledMetrics::new(self, scale)
    }

    /// Returns these metrics in pixels at `ppem`, as `f32`.
    #[inline]
    pub fn scaled_f32(&self, ppem: f32) -> ScaledMetrics<'_, ScaleF32> {
        self.scaled(ScaleF32::from_ppem(ppem, self.units_per_em))
    }

    /// Returns these metrics in pixels at `ppem`, in 26.6 fixed point.
    #[inline]
    pub fn scaled_26dot6(&self, ppem: f32) -> ScaledMetrics<'_, Scale26Dot6> {
        self.scaled(Scale26Dot6::from_ppem(ppem, self.units_per_em))
    }
}

/// Style measurements in a caller's own units.
///
/// Scaling is done when a measurement is requested. The italic angle and
/// fixed-pitch flag have no length to scale and are returned unchanged.
#[derive(Clone, Copy)]
pub struct ScaledStyleMetrics<'a, S: Scale> {
    metrics: &'a StyleMetrics,
    scale: S,
}

impl<'a, S: Scale> ScaledStyleMetrics<'a, S> {
    pub(crate) fn new(metrics: &'a StyleMetrics, scale: S) -> Self {
        Self { metrics, scale }
    }

    /// Returns the suggested subscript em box and placement.
    pub fn subscript(&self) -> Option<ScriptMetrics<S::Value>> {
        self.metrics
            .subscript
            .map(|script| self.scale_script(script))
    }

    /// Returns the suggested superscript em box and placement.
    pub fn superscript(&self) -> Option<ScriptMetrics<S::Value>> {
        self.metrics
            .superscript
            .map(|script| self.scale_script(script))
    }

    /// Returns the suggested underline position and thickness.
    pub fn underline(&self) -> Option<Decoration<S::Value>> {
        self.metrics
            .underline
            .map(|decoration| self.scale_decoration(decoration))
    }

    /// Returns the suggested strikethrough position and thickness.
    pub fn strike_through(&self) -> Option<Decoration<S::Value>> {
        self.metrics
            .strike_through
            .map(|decoration| self.scale_decoration(decoration))
    }

    /// Returns the italic angle in degrees, unaffected by scaling.
    pub fn italic_angle(&self) -> Option<Fixed> {
        self.metrics.italic_angle
    }

    /// Returns whether the font reports a fixed pitch.
    pub fn is_fixed_pitch(&self) -> Option<bool> {
        self.metrics.is_fixed_pitch
    }

    fn scale_script(&self, script: ScriptMetrics) -> ScriptMetrics<S::Value> {
        ScriptMetrics {
            x_size: self.scale.scale_x(script.x_size),
            y_size: self.scale.scale_y(script.y_size),
            x_offset: self.scale.scale_x(script.x_offset),
            y_offset: self.scale.scale_y(script.y_offset),
        }
    }

    fn scale_decoration(&self, decoration: Decoration) -> Decoration<S::Value> {
        Decoration {
            position: self.scale.scale_y(decoration.position),
            thickness: self.scale.scale_y(decoration.thickness),
        }
    }
}

impl StyleMetrics {
    /// Returns these style measurements in the units `scale` describes.
    pub fn scaled<S: Scale>(&self, scale: S) -> ScaledStyleMetrics<'_, S> {
        ScaledStyleMetrics::new(self, scale)
    }

    /// Returns these style measurements in pixels at `ppem`, as `f32`.
    #[inline]
    pub fn scaled_f32(&self, ppem: f32) -> ScaledStyleMetrics<'_, ScaleF32> {
        self.scaled(ScaleF32::from_ppem(ppem, self.units_per_em))
    }

    /// Returns these style measurements in pixels at `ppem`, in 26.6 fixed
    /// point.
    #[inline]
    pub fn scaled_26dot6(&self, ppem: f32) -> ScaledStyleMetrics<'_, Scale26Dot6> {
        self.scaled(Scale26Dot6::from_ppem(ppem, self.units_per_em))
    }
}

/// Measurements of individual glyphs, in a caller's own units.
///
/// Holds borrows and a scale, so it is as cheap to make as the metrics it
/// scales and can be taken per query. It remembers nothing between calls: a
/// caller wanting measurements kept holds them itself.
#[derive(Clone, Copy)]
pub struct ScaledGlyphMetrics<'a, 'extents, S: Scale> {
    metrics: GlyphMetrics<'a>,
    scale: S,
    line: Option<LineExtents<S::Value>>,
    extents: Option<&'extents dyn Fn(GlyphId) -> Option<GlyphExtents<S::Value>>>,
}

impl<'a, 'extents, S: Scale> ScaledGlyphMetrics<'a, 'extents, S> {
    pub(crate) fn new(metrics: GlyphMetrics<'a>, scale: S) -> Self {
        Self {
            metrics: metrics.with_bitmap_ppem(scale.ppem()),
            scale,
            line: None,
            extents: None,
        }
    }

    /// Measures against a line the caller supplies rather than the font's own.
    ///
    /// A caller that reads its line from elsewhere supplies it here, so the
    /// metrics built on it agree with the rest of its layout. The line is in
    /// the same units as everything else this type reports, so nothing is
    /// converted back into font units.
    ///
    /// `None` leaves the font's own line in place, so a caller can pass
    /// whatever it happens to have without first checking.
    pub fn with_line_extents(self, line: Option<LineExtents<S::Value>>) -> Self {
        Self { line, ..self }
    }

    /// Measures ink using the sources in `order`.
    ///
    /// See [`GlyphMetrics::with_extents_source_order`].
    pub fn with_extents_source_order(self, order: GlyphSourceOrder) -> Self {
        Self {
            metrics: self.metrics.with_extents_source_order(order),
            ..self
        }
    }

    /// Measures ink by a function the caller supplies rather than the font.
    ///
    /// A caller that measures glyphs elsewhere supplies that here, so the
    /// metrics built on ink agree with the rest of what it reports. The
    /// function answers in the same units as everything else this type
    /// reports, so nothing is converted back into font units. `None` from
    /// the function means extents are unavailable; return
    /// `Some(GlyphExtents::default())` for a present glyph with no ink.
    ///
    /// `None` leaves the font's own measurement in place, so a caller can
    /// pass whatever it happens to have without first checking.
    ///
    /// The function is borrowed only for the lifetime of the returned view.
    pub fn with_glyph_extents<'new>(
        self,
        extents: Option<&'new dyn Fn(GlyphId) -> Option<GlyphExtents<S::Value>>>,
    ) -> ScaledGlyphMetrics<'a, 'new, S> {
        ScaledGlyphMetrics {
            metrics: self.metrics,
            scale: self.scale,
            line: self.line,
            extents,
        }
    }

    /// Returns the advance width of `glyph`.
    #[inline]
    pub fn h_advance(&self, glyph: GlyphId) -> S::Value {
        self.scale.scale_x(self.metrics.h_advance_exact(glyph))
    }

    /// Writes the advance width of each glyph to its slot, in order.
    #[inline]
    pub fn h_advance_batched<'o, V: 'o>(
        &self,
        convert: impl Fn(S::Value) -> V,
        glyphs: impl Iterator<Item = (GlyphId, &'o mut V)>,
    ) {
        self.metrics
            .h_advance_batched(|value| convert(self.scale.scale_x(value)), glyphs);
    }

    /// Returns the advance height of `glyph`.
    ///
    /// A font with no vertical metrics stacks its glyphs by the line, the
    /// only measurement here a caller can supply. One that has them is
    /// measured by what it says, and a supplied line changes nothing.
    #[inline]
    pub fn v_advance(&self, glyph: GlyphId) -> S::Value {
        // Only a font with no vertical metrics stacks by the line; one
        // that has them is read below, supplied line or not.
        match self.line_height_fallback() {
            Some(height) => height,
            None => self.scale.scale_y(self.metrics.v_advance_exact(glyph)),
        }
    }

    /// Writes the advance height of each glyph to its slot, in order.
    #[inline]
    pub fn v_advance_batched<'o, V: 'o>(
        &self,
        convert: impl Fn(S::Value) -> V,
        glyphs: impl Iterator<Item = (GlyphId, &'o mut V)>,
    ) {
        // Settled before the run, as the table to read is. Only a font
        // with no vertical metrics reaches this, and then all its glyphs
        // advance the same; one that has them is read below, supplied line
        // or not.
        if let Some(height) = self.line_height_fallback() {
            for (_, out) in glyphs {
                *out = convert(height);
            }
            return;
        }
        self.metrics
            .v_advance_batched(|value| convert(self.scale.scale_y(value)), glyphs);
    }

    /// Returns the y coordinate of `glyph`'s vertical origin.
    ///
    /// This places the glyph relative to the pen in vertical text. The x
    /// coordinate is half the advance width, so only y is returned.
    ///
    /// The origin comes from the first available of: `VORG`, the `glyf` top
    /// phantom point when the font has vertical metrics, the ink centered in
    /// the line, and the ascender. The last two use the supplied ink
    /// measurement.
    pub fn v_origin_y(&self, glyph: GlyphId) -> S::Value {
        let mut origin = self.scale.scale_y(F48Dot16::ZERO);
        self.v_origin_y_batched(|value| value, core::iter::once((glyph, &mut origin)));
        origin
    }

    /// Writes the vertical origin of each glyph to its slot, in order.
    ///
    /// The line is measured only if a glyph reaches the extents fallback, and
    /// then reused for the rest of the run.
    pub fn v_origin_y_batched<'o, V: 'o>(
        &self,
        convert: impl Fn(S::Value) -> V,
        glyphs: impl Iterator<Item = (GlyphId, &'o mut V)>,
    ) {
        let mut line = None;
        self.metrics.v_origin_y_batched_with(
            |glyph, origin| {
                let value = match origin {
                    Some(origin) => self.scale.scale_y(origin),
                    None => self
                        .origin_against_ink(glyph, *line.get_or_insert_with(|| self.origin_line())),
                };
                convert(value)
            },
            |glyphs| {
                let line = self.origin_line();
                self.extents_batched(
                    |extents| convert(self.origin_from_extents(extents, line)),
                    glyphs,
                );
            },
            glyphs,
        );
    }

    /// Returns where `glyph`'s ink sits.
    ///
    /// An empty glyph has zero extents. `None` means the glyph is unavailable
    /// or its extents could not be read. A supplied extents function may use
    /// `None` for any glyph it does not measure.
    #[inline]
    pub fn extents(&self, glyph: GlyphId) -> Option<GlyphExtents<S::Value>> {
        match self.extents {
            Some(extents) => extents(glyph),
            None => {
                let mut extents = None;
                self.metrics.extents_batched(
                    |value| value.map(|extents| self.scale.scale_glyph_extents(extents)),
                    core::iter::once((glyph, &mut extents)),
                );
                extents
            }
        }
    }

    /// Writes where each glyph's ink sits to its slot, in order.
    #[inline]
    pub fn extents_batched<'o, V: 'o>(
        &self,
        convert: impl Fn(Option<GlyphExtents<S::Value>>) -> V,
        glyphs: impl Iterator<Item = (GlyphId, &'o mut V)>,
    ) {
        // Settled before the run, as the source to read is: a supplied
        // function answers for every glyph, and the font is never read.
        if let Some(extents) = self.extents {
            for (glyph, out) in glyphs {
                *out = convert(extents(glyph));
            }
            return;
        }
        self.metrics.extents_batched(
            |extents| convert(extents.map(|extents| self.scale.scale_glyph_extents(extents))),
            glyphs,
        );
    }

    /// The height a glyph takes from the line, where it takes one.
    ///
    /// `None` for two reasons that mean the same thing here: the font has
    /// vertical metrics of its own, so the line is not what its glyphs stack
    /// by; or it has no line either, which the unscaled metrics answer with
    /// an em. A supplied line applies only in the first case, so supplying
    /// one never overrides what a font says about itself.
    ///
    /// Each end is scaled before the two are subtracted, so a scale that
    /// rounds rounds them as a caller supplying its own line would, and the
    /// answer does not turn on whether one was supplied.
    #[inline]
    fn line_height_fallback(&self) -> Option<S::Value> {
        if self.metrics.states_vertical_advances() {
            return None;
        }
        let line = self.origin_line();
        Some(S::sub(line.ascender, line.descender))
    }

    /// The line a glyph stacks by, in the units this type reports.
    ///
    /// The supplied line if there is one, and the font's otherwise. A font
    /// with no line metrics gets one proportioned to its em.
    fn origin_line(&self) -> LineExtents<S::Value> {
        // A supplied line is reported as it was given: a caller stating its
        // own has already decided which way its ends run.
        if let Some(line) = self.line {
            return line;
        }
        let line = self.metrics.origin_line();
        // Each end is scaled, rather than the height between them, so a scale
        // that rounds reports ends a caller can lay out against.
        LineExtents {
            ascender: self.scale.scale_y(line.ascender),
            descender: self.scale.scale_y(line.descender),
        }
    }

    /// The last two rungs of [`v_origin_y`](Self::v_origin_y), which measure
    /// against the ink.
    fn origin_against_ink(&self, glyph: GlyphId, line: LineExtents<S::Value>) -> S::Value {
        self.origin_from_extents(self.extents(glyph), line)
    }

    fn origin_from_extents(
        &self,
        extents: Option<GlyphExtents<S::Value>>,
        line: LineExtents<S::Value>,
    ) -> S::Value {
        let Some(extents) = extents else {
            return line.ascender;
        };
        let line_height = S::sub(line.ascender, line.descender);
        S::add(
            extents.y_bearing,
            S::half(S::sub(line_height, extents.height)),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Blob;
    use crate::model::Font;
    use alloc::sync::Arc;
    use types::{GlyphId, Tag};

    /// Scales font units to pixels at a size, halving toward zero.
    #[derive(Clone, Copy)]
    struct Ppem {
        ppem: f32,
        upem: u16,
    }

    impl Scale for Ppem {
        type Value = f32;

        fn scale_x(&self, value: F48Dot16) -> f32 {
            value.to_f32() * self.ppem / self.upem as f32
        }

        fn scale_y(&self, value: F48Dot16) -> f32 {
            self.scale_x(value)
        }

        fn scale_glyph_extents(&self, extents: GlyphExtents<F48Dot16>) -> GlyphExtents<f32> {
            GlyphExtents {
                x_bearing: self.scale_x(extents.x_bearing),
                y_bearing: self.scale_y(extents.y_bearing),
                width: self.scale_x(extents.width),
                height: self.scale_y(extents.height),
            }
        }

        fn scale_rect(&self, b: BoundingBox<F48Dot16>) -> BoundingBox<f32> {
            BoundingBox {
                x_min: self.scale_x(b.x_min),
                y_min: self.scale_y(b.y_min),
                x_max: self.scale_x(b.x_max),
                y_max: self.scale_y(b.y_max),
            }
        }

        fn add(a: f32, b: f32) -> f32 {
            a + b
        }

        fn sub(a: f32, b: f32) -> f32 {
            a - b
        }

        fn half(value: f32) -> f32 {
            value / 2.0
        }
    }

    const STATIC: &[u8] = font_test_data::TINOS_SUBSET;
    const VERT: &[u8] = font_test_data::MPLUS1CODE_VERTICAL_SUBSET;
    /// States its vertical origins outright.
    const VORG: &[u8] = font_test_data::VORG;

    fn scaled(data: &[u8], ppem: f32) -> (Font, Ppem) {
        let font = Font::new(data.to_vec(), 0).unwrap();
        let upem = font.metrics().units_per_em;
        (font, Ppem { ppem, upem })
    }

    fn line(ascender: f32, descender: f32) -> LineExtents<f32> {
        LineExtents {
            ascender,
            descender,
        }
    }

    /// Rounds every scaled value to a whole number, as a hinted scale does.
    #[derive(Clone, Copy)]
    struct Rounding(f32, u16);

    impl Scale for Rounding {
        type Value = f32;
        fn scale_x(&self, value: F48Dot16) -> f32 {
            (value.to_f32() * self.0 / self.1 as f32).round()
        }
        fn scale_y(&self, value: F48Dot16) -> f32 {
            self.scale_x(value)
        }
        fn scale_glyph_extents(&self, e: GlyphExtents<F48Dot16>) -> GlyphExtents<f32> {
            GlyphExtents {
                x_bearing: self.scale_x(e.x_bearing),
                y_bearing: self.scale_y(e.y_bearing),
                width: self.scale_x(e.width),
                height: self.scale_y(e.height),
            }
        }

        fn scale_rect(&self, b: BoundingBox<F48Dot16>) -> BoundingBox<f32> {
            BoundingBox {
                x_min: self.scale_x(b.x_min),
                y_min: self.scale_y(b.y_min),
                x_max: self.scale_x(b.x_max),
                y_max: self.scale_y(b.y_max),
            }
        }
        fn add(a: f32, b: f32) -> f32 {
            a + b
        }
        fn sub(a: f32, b: f32) -> f32 {
            a - b
        }
        fn half(value: f32) -> f32 {
            value / 2.0
        }
    }

    #[test]
    fn a_rounding_scale_rounds_the_ends_of_the_line_not_the_height() {
        // A font with no `vmtx` stacks by the line, and the height comes
        // from two ends. Scaling each before subtracting is what a caller
        // stating its own line does, so doing it the other way round would
        // answer differently depending on whether one was supplied. It shows
        // up only where the scale rounds, and then by a whole unit.
        let font = Font::new(STATIC.to_vec(), 0).unwrap();
        let upem = font.metrics().units_per_em;
        let from_font = font.metrics().h_line().unwrap().extents();
        let mut rounded_apart = 0;
        for ppem in [11.0f32, 12.0, 13.0, 14.0, 16.0, 19.0, 24.0] {
            let scale = Rounding(ppem, upem);
            let metrics = font.glyph_metrics().scaled(scale);
            let ends = LineExtents {
                ascender: scale.scale_y(from_font.ascender),
                descender: scale.scale_y(from_font.descender),
            };
            let from_ends = Rounding::sub(ends.ascender, ends.descender);
            assert_eq!(
                metrics.v_advance(GlyphId::new(1)),
                from_ends,
                "at {ppem}ppem"
            );
            // And stating the same line back gives the same answer.
            assert_eq!(
                metrics
                    .with_line_extents(Some(ends))
                    .v_advance(GlyphId::new(1)),
                from_ends,
                "at {ppem}ppem, supplied"
            );
            // The other way round: subtract in design units, scale once.
            if scale.scale_y(from_font.ascender - from_font.descender) != from_ends {
                rounded_apart += 1;
            }
        }
        assert!(
            rounded_apart > 0,
            "no size here rounds the two ways apart, so this proves nothing"
        );
    }

    #[test]
    fn the_scaled_line_is_the_one_the_glyph_metrics_stack_by() {
        // The reason both views exist. A caller reading the line from the
        // global metrics and subtracting its ends must land on the height
        // the glyph metrics give a font that stacks by that line, or the two
        // disagree about the same font at the same size.
        let font = Font::new(STATIC.to_vec(), 0).unwrap();
        let upem = font.metrics().units_per_em;
        for ppem in [11.0f32, 12.0, 13.0, 16.0, 19.0, 24.0] {
            let scale = Rounding(ppem, upem);
            let line = font.metrics().scaled(scale).h_line().unwrap();
            let height = Rounding::sub(line.ascender, line.descender);
            let glyphs = font.glyph_metrics().scaled(scale);
            for gid in (0..font.num_glyphs()).map(GlyphId::new) {
                assert_eq!(glyphs.v_advance(gid), height, "glyph {gid} at {ppem}ppem");
            }
        }
    }

    #[test]
    fn every_measurement_is_the_unscaled_one_through_the_scale() {
        // One case per field of `Metrics`, so that a field added there
        // without one here is a gap someone has to notice.
        let font = Font::new(STATIC.to_vec(), 0).unwrap();
        let global = font.metrics();
        let scale = Ppem {
            ppem: 16.0,
            upem: global.units_per_em,
        };
        let scaled = global.scaled(scale);
        let y = |line: LineBox<F48Dot16>| LineBox {
            ascender: scale.scale_y(line.ascender),
            descender: scale.scale_y(line.descender),
            line_gap: scale.scale_y(line.line_gap),
        };
        let x = |line: LineBox<F48Dot16>| LineBox {
            ascender: scale.scale_x(line.ascender),
            descender: scale.scale_x(line.descender),
            line_gap: scale.scale_x(line.line_gap),
        };
        assert_eq!(scaled.bounds(), scale.scale_rect(global.bounds));
        assert_eq!(scaled.hhea_line(), global.hhea_line.map(y));
        assert_eq!(scaled.typo_line(), global.typo_line.map(y));
        assert_eq!(scaled.vhea_line(), global.vhea_line.map(x));
        assert_eq!(scaled.h_line(), global.h_line().map(y));
        assert_eq!(
            scaled.win_line(),
            global.win_line.map(|l| LineExtents {
                ascender: scale.scale_y(l.ascender),
                descender: scale.scale_y(l.descender),
            })
        );
        assert_eq!(scaled.x_height(), global.x_height.map(|v| scale.scale_y(v)));
        assert_eq!(
            scaled.cap_height(),
            global.cap_height.map(|v| scale.scale_y(v))
        );
        assert_eq!(
            scaled.max_h_advance(),
            global.max_h_advance.map(|v| scale.scale_x(v))
        );
        assert_eq!(
            scaled.max_v_advance(),
            global.max_v_advance.map(|v| scale.scale_y(v))
        );
        assert_eq!(
            scaled.average_char_width(),
            global.average_char_width.map(|v| scale.scale_x(v))
        );
        // What carries no unit is reported unchanged.
        assert_eq!(scaled.units_per_em(), global.units_per_em);
        assert_eq!(scaled.num_glyphs(), global.num_glyphs);
        assert_eq!(scaled.use_typo_metrics(), global.use_typo_metrics);
        // And this font provides enough for the comparison to mean something.
        assert!(scaled.hhea_line().is_some() && scaled.typo_line().is_some());
    }

    #[test]
    fn the_clipping_line_reports_its_descent_as_a_position() {
        // `OS/2` gives the descent as a positive number below the baseline.
        // Reporting it as a position keeps the pair readable as a line.
        let font = Font::new(STATIC.to_vec(), 0).unwrap();
        let global = font.metrics();
        let win = global
            .win_line
            .expect("this font provides clipping metrics");
        assert!(win.ascender > F48Dot16::ZERO);
        assert!(win.descender < F48Dot16::ZERO);
        let scale = Ppem {
            ppem: 16.0,
            upem: global.units_per_em,
        };
        let scaled = global.scaled(scale).win_line().unwrap();
        assert_eq!(scaled.ascender, scale.scale_y(win.ascender));
        assert_eq!(scaled.descender, scale.scale_y(win.descender));
    }

    #[test]
    fn the_two_scales_agree_within_what_each_can_hold() {
        // The same font at the same size, in two number types. They differ by
        // what each can represent, so the coarser rounds the finer rather
        // than disagreeing with it.
        let font = Font::new(STATIC.to_vec(), 0).unwrap();
        let upem = font.metrics().units_per_em;
        let coarse = font
            .glyph_metrics()
            .scaled(Scale26Dot6::from_ppem(16.0, upem));
        let fine = font.glyph_metrics().scaled(ScaleF32::from_ppem(16.0, upem));
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            // 26.6 resolves 1/64 pixel, so it lands within one of those.
            let apart = (coarse.h_advance(gid).to_f32() - fine.h_advance(gid)).abs();
            assert!(apart < 1.0 / 32.0, "glyph {gid} is {apart} apart");
        }
    }

    #[test]
    fn a_scale_with_a_size_per_axis_uses_each_in_its_own_direction() {
        // The axes are apart because HarfBuzz keeps them apart, so a scale
        // built from two factors has to use the right one in each direction.
        let font = Font::new(VERT.to_vec(), 0).unwrap();
        let upem = font.metrics().units_per_em;
        let em = upem as f32;
        let wide = ScaleF32::new(em * 2.0, em, upem);
        let tall = ScaleF32::new(em, em * 2.0, upem);
        let plain = ScaleF32::new(em, em, upem);
        let gid = GlyphId::new(1);
        let (w, t, p) = (
            font.glyph_metrics().scaled(wide),
            font.glyph_metrics().scaled(tall),
            font.glyph_metrics().scaled(plain),
        );
        assert_eq!(w.h_advance(gid), p.h_advance(gid) * 2.0);
        assert_eq!(w.v_advance(gid), p.v_advance(gid));
        assert_eq!(t.v_advance(gid), p.v_advance(gid) * 2.0);
        assert_eq!(t.h_advance(gid), p.h_advance(gid));
    }

    #[test]
    fn freetype_scales_whole_design_units() {
        // What separates the two: FreeType multiplies a whole design unit,
        // so a measurement carrying a fraction loses it before the multiply.
        // A varied advance carries one, which is why the other exists.
        let upem = 1000;
        let fraction = F48Dot16::from_f64(10.5);
        assert_eq!(
            Scale26Dot6::from_ppem(upem as f32, upem).scale_x(fraction),
            F26Dot6::from_f64(11.0)
        );
        assert_eq!(
            ScaleF32::from_ppem(upem as f32, upem).scale_x(fraction),
            10.5
        );
    }

    #[test]
    fn a_rounding_scale_rounds_extents_corners_before_size() {
        let extents = GlyphExtents {
            x_bearing: F48Dot16::from_f64(10.6),
            y_bearing: F48Dot16::from_f64(-0.5),
            width: F48Dot16::from_f64(9.8),
            height: F48Dot16::from_f64(20.0),
        };
        let scale = Scale26Dot6::from_ppem(1000.0, 1000);
        assert_eq!(
            scale.scale_glyph_extents(extents),
            GlyphExtents {
                x_bearing: F26Dot6::from_f64(11.0),
                y_bearing: F26Dot6::from_f64(-1.0),
                width: F26Dot6::from_f64(9.0),
                height: F26Dot6::from_f64(20.0),
            }
        );

        let below_half = F48Dot16::from_bits((100_000 << 16) + 0x7fff);
        let extents = GlyphExtents {
            x_bearing: below_half,
            y_bearing: F48Dot16::from_i32(10),
            width: F48Dot16::from_i32(2),
            height: F48Dot16::from_i32(2),
        };
        assert_eq!(
            scale.scale_glyph_extents(extents).x_bearing,
            F26Dot6::from_i32(100_000)
        );
    }

    #[test]
    fn halving_rounds_toward_negative_infinity_in_26_6() {
        // Documented, because HarfBuzz halves two ways within one function
        // and a caller writing its own needs to know which it is getting.
        assert_eq!(
            Scale26Dot6::half(F26Dot6::from_bits(-3)),
            F26Dot6::from_bits(-2)
        );
        assert_eq!(ScaleF32::half(-3.0), -1.5);
    }

    #[test]
    fn a_scaled_advance_is_the_design_unit_one_through_the_scale() {
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics();
        let scaled = metrics.scaled(scale);
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            assert_eq!(
                scaled.h_advance(gid),
                scale.scale_x(metrics.h_advance_exact(gid)),
                "glyph {gid}"
            );
        }
    }

    #[test]
    fn a_stated_line_measures_a_font_that_states_none() {
        // This font has no `vmtx`, so its glyphs stack by the line.
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let supplied = metrics.with_line_extents(Some(line(12.0, -4.0)));
        let gid = GlyphId::new(1);
        assert_eq!(supplied.v_advance(gid), 16.0);
        assert!(metrics.v_advance(gid) != 16.0);
    }

    #[test]
    fn a_font_that_states_its_own_ignores_the_line() {
        // This one has `vmtx`, so the line is not what its glyphs stack by,
        // and stating one changes nothing.
        let (font, scale) = scaled(VERT, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let supplied = metrics.with_line_extents(Some(line(99.0, -99.0)));
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            assert_eq!(
                metrics.v_advance(gid),
                supplied.v_advance(gid),
                "glyph {gid}"
            );
        }
    }

    #[test]
    fn stating_nothing_is_stating_nothing() {
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let gid = GlyphId::new(1);
        assert_eq!(
            metrics.with_line_extents(None).v_advance(gid),
            metrics.v_advance(gid)
        );
    }

    #[test]
    fn a_batch_agrees_with_one_at_a_time() {
        for (data, supplied) in [
            (STATIC, None),
            (STATIC, Some(line(12.0, -4.0))),
            (VERT, None),
            (VERT, Some(line(12.0, -4.0))),
        ] {
            let (font, scale) = scaled(data, 16.0);
            let metrics = font
                .glyph_metrics()
                .scaled(scale)
                .with_line_extents(supplied);
            let gids: Vec<_> = (0..font.num_glyphs()).map(GlyphId::new).collect();
            let mut h = vec![0.0f32; gids.len()];
            let mut v = vec![0.0f32; gids.len()];
            metrics.h_advance_batched(|value| value, gids.iter().copied().zip(h.iter_mut()));
            metrics.v_advance_batched(|value| value, gids.iter().copied().zip(v.iter_mut()));
            for (i, gid) in gids.iter().enumerate() {
                assert_eq!(metrics.h_advance(*gid), h[i], "h, glyph {gid}");
                assert_eq!(metrics.v_advance(*gid), v[i], "v, glyph {gid}");
            }
        }
    }

    #[test]
    fn a_scaled_box_is_the_font_box_through_the_scale() {
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics();
        let scaled = metrics.scaled(scale);
        let mut measured = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            let expected = metrics
                .extents_exact(gid)
                .map(|extents| scale.scale_glyph_extents(extents));
            assert_eq!(scaled.extents(gid), expected, "glyph {gid}");
            measured += expected.is_some() as u32;
        }
        assert!(measured > 0);
    }

    #[test]
    fn a_supplied_measurement_replaces_the_font_one() {
        // A caller measuring ink elsewhere answers for every glyph, including
        // one it cannot measure where the font states a box.
        let (font, scale) = scaled(STATIC, 16.0);
        let ink = GlyphExtents {
            x_bearing: 1.0,
            y_bearing: 2.0,
            width: 3.0,
            height: 4.0,
        };
        let supplied = |glyph: GlyphId| (glyph.to_u32() % 2 == 0).then_some(ink);
        let metrics = font.glyph_metrics().scaled(scale);
        let overridden = metrics.with_glyph_extents(Some(&supplied));
        let mut replaced = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            assert_eq!(overridden.extents(gid), supplied(gid), "glyph {gid}");
            replaced += (metrics.extents(gid) != supplied(gid)) as u32;
        }
        assert!(replaced > 0, "the font already agreed everywhere");
    }

    #[test]
    fn a_supplied_measurement_answers_a_whole_run() {
        let (font, scale) = scaled(STATIC, 16.0);
        let ink = GlyphExtents {
            x_bearing: 5.0,
            y_bearing: 6.0,
            width: 7.0,
            height: 8.0,
        };
        let supplied = |glyph: GlyphId| (glyph.to_u32() % 3 != 0).then_some(ink);
        let metrics = font
            .glyph_metrics()
            .scaled(scale)
            .with_glyph_extents(Some(&supplied));
        let glyphs: Vec<_> = (0..font.num_glyphs()).map(GlyphId::new).collect();
        let mut batched = vec![None; glyphs.len()];
        metrics.extents_batched(
            |extents| extents,
            glyphs.iter().copied().zip(batched.iter_mut()),
        );
        for (gid, batched) in glyphs.iter().copied().zip(batched) {
            assert_eq!(batched, supplied(gid), "glyph {gid}");
        }
    }

    #[test]
    fn no_supplied_measurement_leaves_the_font_in_place() {
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            assert_eq!(
                metrics.with_glyph_extents(None).extents(gid),
                metrics.extents(gid),
                "glyph {gid}"
            );
        }
    }

    #[test]
    fn a_supplied_measurement_can_borrow_for_one_query() {
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let glyph = GlyphId::new(1);
        let original = metrics.extents(glyph);
        let supplied = {
            let ink = GlyphExtents {
                x_bearing: 1.0,
                y_bearing: 2.0,
                width: 3.0,
                height: 4.0,
            };
            let callback = |_: GlyphId| Some(ink);
            metrics.with_glyph_extents(Some(&callback)).extents(glyph)
        };
        assert_ne!(supplied, original);
        assert_eq!(metrics.extents(glyph), original);
    }

    #[test]
    fn vorg_answers_ahead_of_everything_else() {
        // A font stating this states it outright, whatever its ink or its
        // vertical metrics would otherwise say.
        let (font, scale) = scaled(VORG, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let direct = crate::FontRef::new(VORG).unwrap();
        let vorg = crate::TableProvider::vorg(&direct).unwrap();
        for gid in (0..4).map(GlyphId::new) {
            assert_eq!(
                metrics.v_origin_y(gid),
                scale.scale_y(F48Dot16::from_i32(vorg.vertical_origin_y(gid) as i32)),
                "glyph {gid}"
            );
        }
        // And it answers even where the ink is measured differently.
        let ink = GlyphExtents {
            x_bearing: 0.0,
            y_bearing: 999.0,
            width: 1.0,
            height: 1.0,
        };
        let supplied = |_: GlyphId| Some(ink);
        let overridden = metrics.with_glyph_extents(Some(&supplied));
        for gid in (0..4).map(GlyphId::new) {
            assert_eq!(overridden.v_origin_y(gid), metrics.v_origin_y(gid));
        }
    }

    #[test]
    fn vmtx_uses_the_glyf_top_phantom_point() {
        // With no `VORG`, the top phantom point includes the top side bearing.
        let (font, scale) = scaled(VERT, 16.0);
        let glyph_metrics = font.glyph_metrics();
        let metrics = glyph_metrics.scaled(scale);
        assert!(glyph_metrics.stated_v_origin(GlyphId::new(1)).is_none());
        let mut checked = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            let (Some(extents), Some(bearing)) = (
                glyph_metrics.extents_exact(gid),
                glyph_metrics.stated_v_bearing(gid),
            ) else {
                continue;
            };
            assert_eq!(
                metrics.v_origin_y(gid),
                scale.scale_y(glyph_metrics.glyf_v_origin(gid).unwrap()),
                "glyph {gid}"
            );
            assert_eq!(
                glyph_metrics.glyf_v_origin(gid).unwrap(),
                extents.y_bearing + bearing,
                "glyph {gid}"
            );
            checked += 1;
        }
        assert!(checked > 0, "no glyph stated both");

        let supplied = |_: GlyphId| {
            Some(GlyphExtents {
                x_bearing: 0.0,
                y_bearing: 999.0,
                width: 1.0,
                height: 1.0,
            })
        };
        let overridden = metrics.with_glyph_extents(Some(&supplied));
        assert_eq!(
            overridden.v_origin_y(GlyphId::new(1)),
            metrics.v_origin_y(GlyphId::new(1))
        );
    }

    #[test]
    fn without_vmtx_the_ink_is_centered_in_the_line() {
        // The leftover of the line, half above the ink and half below it.
        let (font, scale) = scaled(STATIC, 16.0);
        let glyph_metrics = font.glyph_metrics();
        let metrics = glyph_metrics.scaled(scale);
        assert!(glyph_metrics.stated_v_bearing(GlyphId::new(1)).is_none());
        let line = glyph_metrics.line_extents().unwrap();
        let height = scale.scale_y(line.ascender) - scale.scale_y(line.descender);
        let mut checked = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            let Some(extents) = glyph_metrics.extents_exact(gid) else {
                continue;
            };
            let extents = scale.scale_glyph_extents(extents);
            assert_eq!(
                metrics.v_origin_y(gid),
                extents.y_bearing + (height - extents.height) / 2.0,
                "glyph {gid}"
            );
            checked += 1;
        }
        assert!(checked > 0);
    }

    #[test]
    fn an_empty_glyph_is_centered_but_unavailable_extents_use_the_ascender() {
        let (font, scale) = scaled(STATIC, 16.0);
        let glyph_metrics = font.glyph_metrics();
        let metrics = glyph_metrics.scaled(scale);
        let line = metrics.origin_line();
        let absent = |_: GlyphId| None;
        let overridden = metrics.with_glyph_extents(Some(&absent));
        let mut checked = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            if glyph_metrics.extents(gid) != Some(GlyphExtents::default()) {
                continue;
            }
            assert_eq!(
                metrics.v_origin_y(gid),
                (line.ascender - line.descender) / 2.0,
                "glyph {gid}"
            );
            assert_eq!(overridden.v_origin_y(gid), line.ascender);
            checked += 1;
        }
        assert!(checked > 0, "no glyph was empty");
    }

    #[test]
    fn a_supplied_measurement_moves_the_origin_with_it() {
        // The two middle rungs read the ink, so a caller substituting its own
        // gets an origin consistent with it rather than with the font.
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let ink = GlyphExtents {
            x_bearing: 0.0,
            y_bearing: 100.0,
            width: 10.0,
            height: 20.0,
        };
        let supplied = |_: GlyphId| Some(ink);
        let overridden = metrics.with_glyph_extents(Some(&supplied));
        let line = metrics.origin_line();
        let height = line.ascender - line.descender;
        let expected = ink.y_bearing + (height - ink.height) / 2.0;
        let mut moved = 0;
        for gid in (0..font.num_glyphs()).map(GlyphId::new) {
            assert_eq!(overridden.v_origin_y(gid), expected, "glyph {gid}");
            moved += (metrics.v_origin_y(gid) != expected) as u32;
        }
        assert!(moved > 0, "the font already agreed everywhere");

        let gids: Vec<_> = (0..font.num_glyphs()).map(GlyphId::new).collect();
        let mut origins = vec![0.0; gids.len()];
        overridden.v_origin_y_batched(
            |origin| origin,
            gids.iter().copied().zip(origins.iter_mut()),
        );
        assert!(origins.iter().all(|origin| *origin == expected));
    }

    #[test]
    fn a_supplied_line_moves_the_origin_with_it() {
        // The centered rung measures against the line, so a caller laying out
        // against its own line gets an origin in that line.
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font.glyph_metrics().scaled(scale);
        let taller = metrics.with_line_extents(Some(line(100.0, -20.0)));
        let gid = (0..font.num_glyphs())
            .map(GlyphId::new)
            .find(|gid| font.glyph_metrics().extents(*gid).is_some())
            .unwrap();
        assert_ne!(taller.v_origin_y(gid), metrics.v_origin_y(gid));
    }

    #[test]
    fn a_run_of_origins_agrees_with_one_at_a_time() {
        for data in [VORG, VERT, STATIC] {
            let (font, scale) = scaled(data, 16.0);
            let metrics = font.glyph_metrics().scaled(scale);
            let glyphs: Vec<_> = (0..font.num_glyphs()).map(GlyphId::new).collect();
            let mut batched = vec![0.0; glyphs.len()];
            metrics.v_origin_y_batched(
                |origin| origin,
                glyphs.iter().copied().zip(batched.iter_mut()),
            );
            for (gid, batched) in glyphs.iter().copied().zip(batched) {
                assert_eq!(metrics.v_origin_y(gid), batched, "glyph {gid}");
            }
        }
    }

    #[test]
    fn a_font_stating_no_line_is_given_one_proportioned_to_its_em() {
        // Four fifths of the em above the baseline and the rest below, which
        // is what a glyph with no ink to measure then sits on.
        let font = font_without(&[b"hhea", b"OS/2"]);
        let glyph_metrics = font.glyph_metrics();
        assert!(glyph_metrics.line_extents().is_none());
        let em = font.units_per_em();
        assert!(
            em > 0,
            "the em itself has to survive for this to mean anything"
        );

        let scale = Ppem {
            ppem: 16.0,
            upem: em,
        };
        let metrics = glyph_metrics.scaled(scale);
        let ascender = F48Dot16::from_f64(em as f64 * 0.8);
        let empty = empty_glyph(&font);
        assert_eq!(
            metrics.v_origin_y(empty),
            scale.scale_y(F48Dot16::from_i32(em as i32)) / 2.0
        );
        let absent = |_: GlyphId| None;
        assert_eq!(
            metrics.with_glyph_extents(Some(&absent)).v_origin_y(empty),
            scale.scale_y(ascender)
        );
        // And the line it implies is a whole em tall, so a glyph with no
        // vertical metrics still advances by one.
        assert_eq!(
            metrics.v_advance(empty),
            scale.scale_y(ascender) - scale.scale_y(ascender - F48Dot16::from_i32(em as i32))
        );
    }

    /// A font serving every table but the ones named.
    fn font_without(hide: &'static [&[u8; 4]]) -> Font {
        let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag: Tag| {
            if hide.iter().any(|hidden| Tag::new(hidden) == tag) {
                return None;
            }
            let font = crate::FontRef::new(STATIC).ok()?;
            Some(Blob::from(font.table_data(tag)?.as_bytes().to_vec()))
        });
        Font::new(source, 0).unwrap()
    }

    #[test]
    fn the_ends_of_the_line_are_signed_whatever_the_font_says() {
        // Fonts state these both ways round: some as positions, where the
        // descender runs down and is negative, and some as magnitudes, where
        // it is not. All three describe one line and have to measure as one.
        let stated = font_with_hhea_ends(1600, -400);
        let scale = Ppem {
            ppem: 16.0,
            upem: stated.units_per_em(),
        };
        let empty = empty_glyph(&stated);
        let ink = drawn_glyph(&stated);
        let expected = stated.glyph_metrics().scaled(scale);
        for (ascender, descender) in [(1600, 400), (-1600, 400), (-1600, -400)] {
            let font = font_with_hhea_ends(ascender, descender);
            let actual = font.glyph_metrics().scaled(scale);
            // The line itself, through the two rungs that read it.
            assert_eq!(
                actual.v_origin_y(empty),
                expected.v_origin_y(empty),
                "ascender {ascender}, descender {descender}"
            );
            assert_eq!(
                actual.v_origin_y(ink),
                expected.v_origin_y(ink),
                "ascender {ascender}, descender {descender}"
            );
            // And the height a glyph advances by, which is that line too.
            assert_eq!(
                actual.v_advance(ink),
                expected.v_advance(ink),
                "ascender {ascender}, descender {descender}"
            );
        }
        // And the line really is the one the font states, not a fallback that
        // would agree by accident.
        assert_eq!(
            expected.v_origin_y(empty),
            scale.scale_y(F48Dot16::from_i32(1000))
        );
    }

    // A bitmap is measured from the strike for the scale's size, and a scale
    // with no size measures from the largest strike.
    #[test]
    fn the_scale_chooses_the_bitmap_strike() {
        let font = Font::new(font_test_data::CBDT, 0).unwrap();
        let glyph = GlyphId::new(2);
        let upem = font.units_per_em();
        let metrics = font.glyph_metrics();
        for scale in [
            ScaleF32::from_ppem(12.0, upem),
            ScaleF32::new(12.0, 10.0, upem),
        ] {
            assert_eq!(scale.ppem(), Some(12.0));
            let expected = metrics
                .with_bitmap_ppem(Some(12.0))
                .extents_exact(glyph)
                .map(|extents| scale.scale_glyph_extents(extents));
            assert_eq!(metrics.scaled(scale).extents(glyph), expected);
        }
        assert_eq!(Scale26Dot6::new(10.0, 14.0, upem).ppem(), Some(14.0));
        // The 12 ppem strike and the largest measure the glyph differently.
        assert_ne!(
            metrics.with_bitmap_ppem(Some(12.0)).extents_exact(glyph),
            metrics.with_bitmap_ppem(None).extents_exact(glyph)
        );
        // A scale of its own with no size gets the largest strike.
        struct NoSize(ScaleF32);
        impl Scale for NoSize {
            type Value = f32;
            fn add(a: f32, b: f32) -> f32 {
                ScaleF32::add(a, b)
            }
            fn sub(a: f32, b: f32) -> f32 {
                ScaleF32::sub(a, b)
            }
            fn half(value: f32) -> f32 {
                ScaleF32::half(value)
            }
            fn scale_x(&self, value: F48Dot16) -> f32 {
                self.0.scale_x(value)
            }
            fn scale_y(&self, value: F48Dot16) -> f32 {
                self.0.scale_y(value)
            }
            fn scale_glyph_extents(&self, extents: GlyphExtents<F48Dot16>) -> GlyphExtents<f32> {
                self.0.scale_glyph_extents(extents)
            }
            fn scale_rect(&self, bounds: BoundingBox<F48Dot16>) -> BoundingBox<f32> {
                self.0.scale_rect(bounds)
            }
        }
        let no_size = NoSize(ScaleF32::from_ppem(12.0, upem));
        let largest = metrics
            .with_bitmap_ppem(None)
            .extents_exact(glyph)
            .map(|extents| no_size.scale_glyph_extents(extents));
        assert_eq!(metrics.scaled(no_size).extents(glyph), largest);
    }

    #[test]
    fn a_supplied_line_is_taken_as_it_was_given() {
        // The signing is what HarfBuzz applies to what it reads from a font.
        // A caller stating its own line has already decided, so an ascender
        // below the baseline stays there.
        let (font, scale) = scaled(STATIC, 16.0);
        let metrics = font
            .glyph_metrics()
            .scaled(scale)
            .with_line_extents(Some(line(-100.0, 20.0)));
        let absent = |_: GlyphId| None;
        assert_eq!(
            metrics
                .with_glyph_extents(Some(&absent))
                .v_origin_y(empty_glyph(&font)),
            -100.0
        );
    }

    /// `STATIC` with the ends of its `hhea` line replaced, and no `OS/2` to
    /// be read ahead of it.
    fn font_with_hhea_ends(ascender: i16, descender: i16) -> Font {
        let source: Arc<dyn Fn(Tag) -> Option<Blob> + Send + Sync> = Arc::new(move |tag: Tag| {
            if tag == Tag::new(b"OS/2") {
                return None;
            }
            let font = crate::FontRef::new(STATIC).ok()?;
            let mut data = font.table_data(tag)?.as_bytes().to_vec();
            if tag == Tag::new(b"hhea") {
                // Both ends sit right after the version.
                data.get_mut(4..6)?.copy_from_slice(&ascender.to_be_bytes());
                data.get_mut(6..8)?
                    .copy_from_slice(&descender.to_be_bytes());
            }
            Some(Blob::from(data))
        });
        Font::new(source, 0).unwrap()
    }

    /// A present glyph of `font` with no outline and a zero box.
    fn empty_glyph(font: &Font) -> GlyphId {
        let metrics = font.glyph_metrics();
        (0..font.num_glyphs())
            .map(GlyphId::new)
            .find(|gid| metrics.extents(*gid) == Some(GlyphExtents::default()))
            .expect("no glyph has a zero box")
    }

    /// A glyph of `font` with ink to measure against.
    fn drawn_glyph(font: &Font) -> GlyphId {
        let metrics = font.glyph_metrics();
        (0..font.num_glyphs())
            .map(GlyphId::new)
            .find(|gid| metrics.extents(*gid).is_some())
            .expect("no glyph drew anything")
    }
}