guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
use std::hash::{Hash, Hasher};

use glyphon::cosmic_text::{Align, Ellipsize, EllipsizeHeightLimit, Wrap};
use glyphon::{
    Attrs, Buffer, Cache, Color as GlyphonColor, ColorMode, FontSystem, Metrics, Resolution,
    Shaping, SwashCache, TextArea, TextAtlas, TextBounds, TextRenderer, Viewport,
};
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use wgpu::{Device, MultisampleState, Queue};

use crate::app_state::with_app_state;
use crate::render_stats::{self, Pipeline};
use crate::widgets::font::{FontFamily, FontWeight, LineHeight};
use crate::widgets::{Rect, TextAlign, TextOverflow};

use super::clip::ClipChains;

use super::text_measurer::LineFit;
use super::types::TextEntry;

/// Compute a cache key for a text buffer based on content and styling.
/// Two entries with the same key produce identical glyphon Buffers.
fn text_buffer_key(entry: &TextEntry, scale_factor: f32) -> u64 {
    let mut hasher = rustc_hash::FxHasher::default();
    entry.text.hash(&mut hasher);
    (entry.font_size * scale_factor).to_bits().hash(&mut hasher);
    entry.font_weight.hash(&mut hasher);
    entry.line_height.key().hash(&mut hasher);
    entry.letter_spacing.to_bits().hash(&mut hasher);
    entry.font_family.hash(&mut hasher);
    entry.align.hash(&mut hasher);
    // Whether it wraps is the fit's, hashed below.
    let (width, _) = line_width(
        entry.fit,
        Some(entry.rect.width * scale_factor),
        scale_factor,
    );
    width.map(f32::to_bits).hash(&mut hasher);
    buffer_height(entry.rect, scale_factor)
        .to_bits()
        .hash(&mut hasher);
    entry.fit.map(|fit| fit.key()).hash(&mut hasher);
    hasher.finish()
}

/// The width a text's lines are laid out in, in physical pixels, and whether
/// they wrap there.
///
/// The width layout laid the text out in, which its fit carries: a text shaped
/// in any other width breaks its lines somewhere else, so this is the one width
/// the measurer and the three draw paths all shape in. Its box is no substitute
/// — a box can come back a hair narrower than the line it measured, and a line
/// shaped in it wraps one letter early. Where the box is narrower than this
/// width, [`paint_offset`] puts the lines back in it.
///
/// A text laid out with no width runs on one line per paragraph, and is shaped
/// so, without wrapping: across `box_width` when there is one, which is only
/// where its lines are aligned, since nothing can break.
///
/// A text drawn with no fit at all — `PaintContext::draw_text` from a widget
/// that measured it some other way — wraps at its box, which is all it says
/// about where it was laid out.
pub(super) fn line_width(
    fit: Option<LineFit>,
    box_width: Option<f32>,
    scale: f32,
) -> (Option<f32>, bool) {
    match fit {
        None => (box_width, true),
        Some(LineFit {
            width: Some(width),
            wrap,
            ..
        }) => (Some(width * scale), wrap),
        Some(_) => (box_width, false),
    }
}

/// The height glyphon is given to shape an uncut text of this layout box in, in
/// physical pixels — the box's, and never under 50 logical pixels.
///
/// The transformed path's is
/// [`text_quad::buffer_height`](super::text_quad::buffer_height), and a frost
/// is shaped in whichever of the two draws its letters.
pub(super) fn buffer_height(rect: Rect, scale: f32) -> f32 {
    rect.height.max(50.0) * scale
}

/// How far right a shaped text is drawn of its box's left edge, in the same
/// pixels as the buffer and the box.
///
/// A text is shaped in the width it was laid out in, which its box can come
/// back narrower than — a box hugs its widest line — and cosmic-text places
/// each line across the width it was shaped in. So a line that starts at the
/// right, a right-to-left one, or one aligned to the centre or the end, would
/// sit against the wrong edge. This moves the whole buffer by the alignment's
/// fraction of the difference, as Flutter's `TextPainter` does with its paint
/// offset: nothing for a line that starts at the left, all of it for one that
/// starts at the right, half for a centred one. The direction is the first
/// line's, as Flutter takes the paragraph's.
///
/// One function for glyphon, the transformed quad and the frost's mask, because
/// a frost has to sit exactly under the letters it is cut for.
pub(super) fn paint_offset(buffer: &Buffer, box_width: f32, align: TextAlign) -> f32 {
    let Some(shaped_in) = buffer.size().0 else {
        return 0.0;
    };
    let rtl = buffer.layout_runs().next().is_some_and(|run| run.rtl);
    let fraction = match (align, rtl) {
        (TextAlign::Center, _) => 0.5,
        (TextAlign::Start | TextAlign::Justified, false) | (TextAlign::End, true) => 0.0,
        (TextAlign::Start | TextAlign::Justified, true) | (TextAlign::End, false) => 1.0,
    };
    fraction * (box_width - shaped_in)
}

/// Shape an untransformed text into a fresh buffer, as glyphon will draw it.
fn shape_entry(font_system: &mut FontSystem, entry: &TextEntry, scale_factor: f32) -> Buffer {
    shape(
        font_system,
        &entry.text,
        entry.font_size * scale_factor,
        entry.font_family,
        entry.font_weight,
        entry.line_height,
        entry.letter_spacing,
        entry.align,
        (
            Some(entry.rect.width * scale_factor),
            Some(buffer_height(entry.rect, scale_factor)),
        ),
        entry.fit,
        scale_factor,
    )
}

/// Shape `text` at `font_size` physical pixels, in the width `fit` says it was
/// laid out in and, when it is cut, to the lines `fit` allows — at `scale`
/// physical pixels per logical one. `frame` is the box's width and the height
/// an uncut text is given, in physical pixels; the width is used only for a
/// text laid out with none (see [`line_width`]).
///
/// One function for every path that shapes — the measurer, glyphon's, the
/// transformed quad's and the frost's mask — because a frost has to break and
/// align its lines exactly where the letters over it do, a text has to be
/// drawn on the lines it was measured on, and four copies of this are four
/// places for an option to reach three of.
///
/// Every text is shaped at the width it was laid out in, aligned or not and
/// cut or not, so its lines break where the measurer broke them and the line
/// an ellipsis lands on is the line the measurer counted. Where those lines
/// sit inside a box narrower than that width is [`paint_offset`]'s to say.
///
/// The line height is resolved here and nowhere else, so the measurer and the
/// three draw paths cannot disagree about how tall a line is: `Normal` is the
/// primary face's own (see [`resolve_font`]), `Relative` a multiple of the
/// size, and `Absolute` logical pixels taken to physical ones by `scale`. A
/// number that is not a height — zero, negative, not finite — is `Normal`'s
/// answer, because `Metrics` handed one does not come back (#349).
///
/// A cut text is given the height of the lines it keeps, which is where every
/// reader of its lines stops and where shaping stops too. Half a line short of
/// the next one, so a line whose glyphs are taller than the line box neither
/// loses the last line kept nor lets the first one cut back in. That height is
/// the whole of an unmarked cut; a marked one is finished by [`cut_to_lines`].
///
/// The letter spacing is resolved here too, for the same reason: logical
/// pixels, taken to physical ones by `scale` like an absolute line height, and
/// handed to cosmic-text as the fraction of the size it asks for. What it is
/// added to is cosmic-text's decision — the advance of every glyph it puts
/// out — and the measurer, glyphon, the quad and the mask all take it from
/// this one call. A number that is not one is no spacing.
#[allow(clippy::too_many_arguments)]
pub(super) fn shape(
    font_system: &mut FontSystem,
    text: &str,
    font_size: f32,
    font_family: FontFamily,
    font_weight: FontWeight,
    line_height: LineHeight,
    letter_spacing: f32,
    align: TextAlign,
    frame: (Option<f32>, Option<f32>),
    fit: Option<LineFit>,
    scale: f32,
) -> Buffer {
    let px = crate::renderer::text_measurer::shapeable_size(font_size);
    let weight = if font_weight == FontWeight::default() {
        FontWeight::NORMAL
    } else {
        font_weight
    };
    let declared = match line_height {
        LineHeight::Normal => None,
        LineHeight::Relative(factor) => Some(factor * px),
        LineHeight::Absolute(height) => Some(height * scale),
    };
    let font = resolve_font(font_system, font_family, weight);
    let line_height = declared
        .filter(|h| h.is_finite() && *h > 0.0)
        .unwrap_or(font.line_ratio * px);
    let mut buffer = Buffer::new(font_system, Metrics::new(px, line_height));
    let lines = fit.and_then(|fit| fit.max_lines).map(|n| n.max(1) as usize);
    let (width, wraps) = line_width(fit, frame.0, scale);
    let height = match lines {
        Some(n) => Some((n as f32 - 0.5) * line_height),
        None => frame.1,
    };
    buffer.set_size(width, height);
    if !wraps {
        buffer.set_wrap(Wrap::None);
    }
    let mut attrs = Attrs::new()
        .family(font.family.to_cosmic())
        .weight(weight.to_cosmic());
    let spacing = letter_spacing * scale;
    if spacing.is_finite() && spacing != 0.0 {
        attrs = attrs.letter_spacing(spacing / px);
    }
    buffer.set_text(text, &attrs, Shaping::Advanced, cosmic_align(align));
    buffer.shape_until_scroll(font_system, true);
    if let (Some(lines), Some(mark)) = (lines, fit.and_then(|fit| ellipsize(fit.overflow))) {
        cut_to_lines(font_system, &mut buffer, lines, mark);
    }
    buffer
}

/// What a declared family and weight are drawn in: the installed family that
/// draws it, and the line height over its size of that family's face nearest
/// the weight.
#[derive(Clone, Copy)]
pub(crate) struct ResolvedFont {
    family: FontFamily,
    line_ratio: f32,
}

/// Resolve a declared family and weight to the face that draws them.
///
/// **The family** is a named one as declared, when the font database has it.
/// Otherwise it is the one that draws a space in the declared family at 400,
/// found by shaping one, because that is how cosmic-text finds it: a generic
/// family names one font (sans-serif is Open Sans), and where that font is not
/// installed the text is drawn in a fallback no query of the font database
/// returns. An installed name is not probed, because a family need not have a
/// space: an icon font such as Symbols Nerd Font draws it in a fallback, and
/// the icons would be measured in that (#604).
///
/// Naming that family is what keeps a weight inside it. Handed a generic family
/// whose font is missing, cosmic-text draws a weight the fallback does not
/// have in the first face anywhere that has it exactly — a semibold clock in
/// an emoji font's digits (#575). Handed the family by name, it takes the
/// nearest weight the family has, as CSS Fonts 4 §5.2 matches it. The weight
/// itself is passed on as declared: a variable face is listed once, at its
/// default, and cosmic-text sets its `wght` axis from the weight it is given.
///
/// **The line ratio** is the ascent, descent and line gap over its em, as
/// Chromium and Parley count them, of the family's face nearest the weight by
/// `fontdb`'s CSS query — the face that draws the text, so a fallback glyph
/// later in the line does not make the line taller.
///
/// Kept per family and weight in the application's state: the faces every font
/// system holds are the same ones, fixed once the first of them is built, and a
/// probe is a shaping.
fn resolve_font(
    font_system: &mut FontSystem,
    family: FontFamily,
    weight: FontWeight,
) -> ResolvedFont {
    let known = with_app_state(|app| app.resolved_fonts.borrow().get(&(family, weight)).copied());
    if let Some(resolved) = known {
        return resolved;
    }
    let nearest_face = |font_system: &FontSystem, of: FontFamily| {
        let db = font_system.db();
        let id = db.query(&glyphon::fontdb::Query {
            families: &[of.to_cosmic()],
            weight: weight.to_cosmic(),
            ..Default::default()
        })?;
        Some((id, FontWeight(db.face(id)?.weight.0)))
    };
    let drawing_family = match family {
        FontFamily::Name(_) if nearest_face(font_system, family).is_some() => Some(family),
        _ => drawing_family_of_a_space(font_system, family),
    };
    let nearest = drawing_family.and_then(|drawing| nearest_face(font_system, drawing));
    let line_ratio = nearest
        .and_then(|(id, weight)| font_system.get_font(id, weight.to_cosmic()))
        .and_then(|font| {
            let m = font.metrics();
            line_ratio(m.ascent, m.descent, m.leading, m.units_per_em)
        })
        .unwrap_or(RATIO_WITHOUT_A_FACE);
    let resolved = ResolvedFont {
        family: drawing_family.unwrap_or(family),
        line_ratio,
    };
    with_app_state(|app| {
        app.resolved_fonts
            .borrow_mut()
            .insert((family, weight), resolved)
    });
    resolved
}

/// The family cosmic-text draws a space in `family` at 400 with — the family
/// itself, or the fallback a missing font is drawn in.
fn drawing_family_of_a_space(
    font_system: &mut FontSystem,
    family: FontFamily,
) -> Option<FontFamily> {
    let mut probe = Buffer::new(font_system, Metrics::new(16.0, 16.0));
    probe.set_text(
        " ",
        &Attrs::new()
            .family(family.to_cosmic())
            .weight(FontWeight::NORMAL.to_cosmic()),
        Shaping::Advanced,
        None,
    );
    probe.shape_until_scroll(font_system, false);
    probe
        .layout_runs()
        .find_map(|run| run.glyphs.first().map(|glyph| glyph.font_id))
        .and_then(|id| font_system.db().face(id))
        .and_then(|face| face.families.first())
        .map(|(name, _)| FontFamily::name(name))
}

/// A face's line height over its size, from its metrics in font units: ascent,
/// descent (negative, below the baseline), line gap and units per em. `None`
/// for metrics that do not make a height — a face that says nothing, or an em
/// of zero.
fn line_ratio(ascent: f32, descent: f32, line_gap: f32, units_per_em: u16) -> Option<f32> {
    let ratio = (ascent - descent + line_gap) / f32::from(units_per_em);
    (ratio.is_finite() && ratio > 0.0).then_some(ratio)
}

/// The line height over the size when no face draws even a space — a font
/// system with no faces at all, where nothing draws. CSS 2.1 suggests 1.0 to 1.2 for `normal`.
const RATIO_WITHOUT_A_FACE: f32 = 1.2;

/// cosmic-text's word for an alignment. `Start` is no word at all, so the
/// text's own direction decides where its lines begin.
fn cosmic_align(align: TextAlign) -> Option<Align> {
    match align {
        TextAlign::Start => None,
        TextAlign::Center => Some(Align::Center),
        TextAlign::End => Some(Align::End),
        TextAlign::Justified => Some(Align::Justified),
    }
}

/// What cosmic-text is asked to mark a one-line cut with. `None` for a cut
/// nothing marks.
fn ellipsize(overflow: TextOverflow) -> Option<Ellipsize> {
    let limit = EllipsizeHeightLimit::Lines(1);
    match overflow {
        TextOverflow::Clip => None,
        TextOverflow::Ellipsis => Some(Ellipsize::End(limit)),
        TextOverflow::EllipsisStart => Some(Ellipsize::Start(limit)),
        TextOverflow::EllipsisMiddle => Some(Ellipsize::Middle(limit)),
    }
}

/// Cut a shaped buffer to `max_lines` lines across all its paragraphs, and
/// mark the cut.
///
/// By hand around cosmic-text's own ellipsis rather than through it, for two
/// reasons. Its limit is per paragraph — a `\n` starts the count again, and a
/// cut that lands on a line break has no mark, because the paragraph before it
/// fit. And a mark it puts on any line but the first starts that line at the
/// blank the wrap broke on, so the last line sits a space to the right of the
/// ones above it — in 0.19 as in 0.18.
///
/// So the last line kept is made a paragraph of its own, split off where it
/// begins, and cosmic-text is asked to mark only that one line, which is the
/// case it gets right. When the cut fell after it rather than inside it, the
/// line is given a `…` of its own to end in. An unwrapped line wider than the
/// box is marked the same way wherever it is: it is one line already.
///
/// `mark` is what the cut line is marked with, as [`ellipsize`] gave it.
fn cut_to_lines(
    font_system: &mut FontSystem,
    buffer: &mut Buffer,
    max_lines: usize,
    mark: Ellipsize,
) {
    let width = buffer.size().0.unwrap_or(f32::INFINITY);
    let mut remaining = max_lines;
    let mut i = 0;
    while i < buffer.lines.len() {
        let layout = buffer.line_layout(font_system, i).unwrap_or_default();
        let count = layout.len();
        let kept = count.min(remaining);
        let last = kept.checked_sub(1).and_then(|at| layout.get(at));
        let too_wide = last.is_some_and(|line| line.w > width);
        let begins_at = last.map_or(0, |line| {
            line.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
        });
        let ends_here = count >= remaining;
        let more_inside = count > remaining;
        let more_after = ends_here && i + 1 < buffer.lines.len();

        if !(more_inside || more_after || too_wide) {
            if ends_here {
                return;
            }
            remaining -= count;
            i += 1;
            continue;
        }

        if ends_here {
            buffer.lines.truncate(i + 1);
        }
        if kept > 1 {
            let rest = buffer.lines[i].split_off(begins_at);
            buffer.lines.insert(i + 1, rest);
            // The lines above the cut, laid out again as they were: a line
            // that has none is where every reader of the buffer stops.
            buffer.line_layout(font_system, i);
            i += 1;
        }
        let mark = if more_inside || too_wide {
            mark
        } else {
            let line = &mut buffer.lines[i];
            let marked = format!("{}\u{2026}", line.text());
            let (ending, attrs) = (line.ending(), line.attrs_list().clone());
            line.set_text(marked, ending, attrs);
            Ellipsize::End(EllipsizeHeightLimit::Lines(1))
        };
        let (fits_in, wrap, font_size) =
            (buffer.size().0, buffer.wrap(), buffer.metrics().font_size);
        let (mono, tab, hinting) = (
            buffer.monospace_width(),
            buffer.tab_width(),
            buffer.hinting(),
        );
        let line = &mut buffer.lines[i];
        line.reset_layout();
        line.layout(
            font_system,
            font_size,
            fits_in,
            wrap,
            mark,
            mono,
            tab,
            hinting,
        );
        if ends_here {
            return;
        }
        remaining -= kept;
        i += 1;
    }
}

pub struct TextRenderState {
    font_system: FontSystem,
    swash_cache: SwashCache,
    #[allow(dead_code)] // Used for viewport and atlas construction
    cache: Cache,
    atlas: TextAtlas,
    /// One renderer per draw group that contains text.
    ///
    /// glyphon draws everything a `TextRenderer` prepared in a single call,
    /// so text that must appear between two other groups needs a renderer of
    /// its own. Grown on demand and reused across frames; a UI with one group
    /// keeps exactly one, as before.
    text_renderers: Vec<TextRenderer>,
    buffers: Vec<Buffer>,
    viewport: Viewport,
    /// Cache of shaped text buffers from the previous frame, keyed by
    /// content+style hash. Avoids expensive Unicode analysis and glyph
    /// shaping for unchanged text. Multi-valued: the same label can appear
    /// several times in a frame (e.g. repeated list items) — with a
    /// single-entry cache the first occurrence consumed the only buffer and
    /// every duplicate re-shaped from scratch, every frame, forever.
    ///
    /// One buffer inline, because almost every key holds one: a `Vec` here
    /// was an allocation per text per frame, made in `begin_frame` and
    /// dropped by `end_frame`'s `clear`. Only a label drawn twice spills.
    buffer_cache: FxHashMap<u64, SmallVec<[Buffer; 1]>>,
    /// Keys for current frame's buffers (parallel to `self.buffers`), used to
    /// repopulate `buffer_cache` at the start of the next frame.
    frame_keys: Vec<u64>,
    /// Positions in the group's texts that the textured-quad path takes, and
    /// what [`prepare_layer`](Self::prepare_layer) hands back.
    ///
    /// A field for the same reason `buffers` is one: the group it describes
    /// lasts a frame, the container it needs does not have to.
    transformed_indices: Vec<usize>,
    /// Positions in the group's texts that glyphon draws, parallel to the
    /// buffers this group pushed.
    ///
    /// Written in the one place a buffer is pushed, so the two lists cannot
    /// come apart: a text area reads the entry and the buffer that was shaped
    /// for it, and an early-out added later drops both or neither. The two
    /// hash sets this replaces said the same thing by saying who was *left
    /// out*, which every skipping branch then had to remember.
    kept: Vec<usize>,
}

/// Whether a text lies entirely off one side of its clip, and so is not drawn
/// at all.
///
/// A whole side, not a corner: two boxes that overlap on neither axis are
/// still both here, and this only says yes when one interval is wholly past
/// the other. The tolerance is for the boundary, where a text ending exactly
/// where its clip does should be kept rather than lost to the last bit of a
/// float.
fn falls_outside(text: Rect, clip: Rect) -> bool {
    const EPSILON: f32 = 0.1;
    text.x + text.width < clip.x - EPSILON
        || text.x > clip.x + clip.width + EPSILON
        || text.y + text.height < clip.y - EPSILON
        || text.y > clip.y + clip.height + EPSILON
}

/// A text's layout box, in world pixels.
///
/// What the culling check has always compared against a clip, lifted out so
/// the routing question below can ask it too. Not outset: widening it here
/// would widen what gets culled, and the two questions want different
/// margins — see the call that adds one.
fn laid_out_in(entry: &TextEntry) -> Rect {
    let (p1x, p1y) = entry.transform.transform_point(entry.rect.x, entry.rect.y);
    let (p2x, p2y) = entry.transform.transform_point(
        entry.rect.x + entry.rect.width,
        entry.rect.y + entry.rect.height,
    );
    Rect::new(
        p1x.min(p2x),
        p1y.min(p2y),
        (p2x - p1x).abs(),
        (p2y - p1y).abs(),
    )
}

impl TextRenderState {
    pub fn new(device: &Device, queue: &Queue, format: wgpu::TextureFormat) -> Self {
        let mut font_system = FontSystem::new();
        for data in crate::get_registered_fonts() {
            font_system
                .db_mut()
                .load_font_source(glyphon::fontdb::Source::Binary(data));
        }
        let swash_cache = SwashCache::new();
        let cache = Cache::new(device);
        let mut atlas = TextAtlas::with_color_mode(device, queue, &cache, format, ColorMode::Web);
        let text_renderer =
            TextRenderer::new(&mut atlas, device, MultisampleState::default(), None);
        let viewport = Viewport::new(device, &cache);

        Self {
            font_system,
            swash_cache,
            cache,
            atlas,
            text_renderers: vec![text_renderer],
            buffers: Vec::new(),
            viewport,
            buffer_cache: FxHashMap::default(),
            frame_keys: Vec::new(),
            transformed_indices: Vec::new(),
            kept: Vec::new(),
        }
    }

    /// Start a frame: recycle last frame's shaped buffers into the cache.
    ///
    /// Split out of [`prepare_layer`](Self::prepare_layer) because a frame may
    /// prepare several groups and the recycling has to happen once for all.
    pub fn begin_frame(&mut self, queue: &Queue, screen: (u32, u32)) {
        // The last frame's glyphs stop being in use, so this frame's prepares
        // may evict them. Here and not at the end of a prepare: every group of
        // a frame prepares before any of them renders, and a glyph one group
        // placed must not be evicted by the next.
        self.atlas.trim();
        for (key, buffer) in self.frame_keys.drain(..).zip(self.buffers.drain(..)) {
            self.buffer_cache.entry(key).or_default().push(buffer);
        }
        // Once per frame, not once per group: every group renders into the
        // same viewport.
        self.viewport.update(
            queue,
            Resolution {
                width: screen.0,
                height: screen.1,
            },
        );
    }

    /// Drop shaped buffers no group asked for. Call once every group has been
    /// prepared — whatever is still cached went unused this frame.
    pub fn end_frame(&mut self) {
        self.buffer_cache.clear();
    }

    /// Prepare one draw group's non-transformed text.
    ///
    /// `slot` selects the renderer, and with it when this text lands relative
    /// to the other groups; see [`render_slot`](Self::render_slot).
    /// Returns the indices, within `texts`, that need the textured-quad path —
    /// borrowed from the scratch they were sorted into, so the group's own
    /// prepare is the one that reads them.
    #[allow(clippy::too_many_arguments)]
    pub fn prepare_layer(
        &mut self,
        slot: usize,
        device: &Device,
        queue: &Queue,
        texts: &[TextEntry],
        chains: &ClipChains,
        screen: (u32, u32),
        scale_factor: f32,
    ) -> &[usize] {
        let (screen_width, screen_height) = screen;
        while self.text_renderers.len() <= slot {
            self.text_renderers.push(TextRenderer::new(
                &mut self.atlas,
                device,
                MultisampleState::default(),
                None,
            ));
        }
        // Buffers accumulate across the frame's groups; this is where this
        // group's own shaped buffers begin.
        let buffers_start = self.buffers.len();

        self.transformed_indices.clear();
        self.kept.clear();

        for (idx, entry) in texts.iter().enumerate() {
            // Text scaled to nothing is skipped before any work is done for
            // it. The scale comes from the row norms, not from the diagonal:
            // `a` and `d` are both `cos θ` for a rotation, so reading them as
            // the scale calls a quarter turn a collapse and throws the text
            // away at exactly 90° and 270° — and only there, which is why it
            // survived so long. `extract_scale_components` is what the rest of
            // the renderer already asks.
            if !entry.transform.is_identity() && !entry.transform.is_translation_only() {
                let (sx, sy) = entry.transform.extract_scale_components();
                if sx.abs() < 1e-3 || sy.abs() < 1e-3 {
                    continue;
                }
            }

            // Skip text that is completely outside its clip region (culling optimization)
            // Check this FIRST so culled texts don't get rendered via texture path either
            let laid_out = laid_out_in(entry);
            if entry
                .clip
                .is_some_and(|clip| falls_outside(laid_out, clip.open))
            {
                // Text is completely outside clip - skip it entirely
                continue;
            }

            // Route all non-translation transforms (rotation, scale) to TextQuadRenderer.
            // This keeps the glyphon atlas stable — only identity/translation text goes through it.
            //
            // And anything glyphon cannot cut. `TextBounds` is four integers,
            // so the only clip it can honour is an upright rectangle: a turned
            // one, or a corner this text actually reaches into, has to be
            // tested in the clip's own space, and the quad is what does that
            // (#405). Asked of where the two answers *differ* rather than
            // whether they can, because a quad costs a rasterization and an
            // upload per text — a label in the middle of a rounded card is cut
            // the same by the box and stays with glyphon.
            let moved = !entry.transform.is_identity() && !entry.transform.is_translation_only();
            // Glyphs overshoot the box they were laid out in — descenders,
            // italics, accents — and ink that overshoots into a corner is ink
            // the box would not have cut. Half the font size is the slack
            // `command_to_text_backdrop` allows for the same reason, and it
            // errs the safe way here: too generous sends a text down the quad
            // path the box would have cut correctly, costing a rasterization;
            // too tight leaves ink outside its clip, which is the defect.
            let ink = laid_out.outset(entry.font_size * 0.5);
            // Every shape the text is cut by is asked, not only the first: the
            // box glyphon is given is all of theirs intersected, and that cuts
            // like the shapes exactly when each one's box cuts like its shape.
            let box_will_not_do = entry.clip.as_ref().is_some_and(|clip| {
                chains
                    .shapes(clip)
                    .any(|shape| !shape.box_cuts_like_the_shape(ink))
            });
            if moved || box_will_not_do {
                self.transformed_indices.push(idx);
                continue; // Skip transformed text in direct rendering
            }

            // Check buffer cache before expensive text shaping
            let key = text_buffer_key(entry, scale_factor);
            let cached = self
                .buffer_cache
                .get_mut(&key)
                .and_then(|buffers| buffers.pop());
            let buffer =
                cached.unwrap_or_else(|| shape_entry(&mut self.font_system, entry, scale_factor));
            self.kept.push(idx);
            self.frame_keys.push(key);
            self.buffers.push(buffer);
        }

        // Destructured so the text areas can borrow the buffers immutably
        // while `prepare` takes the font system and atlas mutably.
        let Self {
            font_system,
            swash_cache,
            atlas,
            viewport,
            buffers,
            text_renderers,
            kept,
            ..
        } = self;

        // Lazy rather than collected: glyphon takes an iterator, so the areas
        // are built as it reads them and the borrow of `buffers` each one
        // carries never has to outlive the call.
        let text_areas = kept
            .iter()
            .map(|&idx| &texts[idx])
            .zip(buffers[buffers_start..].iter())
            .map(|(entry, buffer)| {
                // Position text in world space using the full transform.
                // This is consistent with the clip rect (also in world space via
                // transform_clip_to_world), so TextBounds clipping works correctly.
                let (screen_x, screen_y) =
                    entry.transform.transform_point(entry.rect.x, entry.rect.y);

                // Scale positions for HiDPI rendering
                let scaled_left = screen_x * scale_factor
                    + paint_offset(buffer, entry.rect.width * scale_factor, entry.align);
                let scaled_top = screen_y * scale_factor;

                // Use clip rect if provided, otherwise use full screen
                // Clip bounds stay in screen space - don't apply transform translation
                // (text position is transformed, but clip region should remain fixed)
                // The box every clip leaves open, because `TextBounds` is four
                // integers and glyphon has nowhere to put a shape. That is
                // exact here rather than approximate: a text that box would
                // cut differently from the shapes never reaches this point —
                // `box_cuts_like_the_shape` sent it down the quad path
                // instead, which tests in the clip's own space (#405).
                let bounds = if let Some(clip_rect) = &entry.clip.map(|c| c.open) {
                    TextBounds {
                        left: (clip_rect.x * scale_factor) as i32,
                        top: (clip_rect.y * scale_factor) as i32,
                        right: ((clip_rect.x + clip_rect.width) * scale_factor) as i32,
                        bottom: ((clip_rect.y + clip_rect.height) * scale_factor) as i32,
                    }
                } else {
                    TextBounds {
                        left: 0,
                        top: 0,
                        right: screen_width as i32,
                        bottom: screen_height as i32,
                    }
                };

                TextArea {
                    buffer,
                    left: scaled_left,
                    top: scaled_top,
                    scale: 1.0, // Buffer is already scaled, no additional scaling needed
                    bounds,
                    // The fade goes into the colour here: glyphon's atlas
                    // holds coverage and the colour rides each glyph's
                    // vertices, so a new alpha rasterises nothing.
                    default_color: {
                        let color = entry.color.scale_alpha(entry.opacity);
                        GlyphonColor::rgba(
                            (color.r * 255.0) as u8,
                            (color.g * 255.0) as u8,
                            (color.b * 255.0) as u8,
                            (color.a * 255.0) as u8,
                        )
                    },
                    custom_glyphs: &[],
                }
            });

        let result = text_renderers[slot].prepare(
            device,
            queue,
            font_system,
            atlas,
            viewport,
            text_areas,
            swash_cache,
        );

        if let Err(e) = result {
            log::error!("Text prepare failed: {:?}", e);
        }

        &self.transformed_indices
    }

    /// Draw the text prepared into `slot`.
    pub fn render_slot<'a>(&'a self, slot: usize, pass: &mut wgpu::RenderPass<'a>) {
        if let Some(renderer) = self.text_renderers.get(slot) {
            renderer
                .render(&self.atlas, &self.viewport, pass)
                .expect("Failed to render text");
            render_stats::record_draw_calls(Pipeline::Text, 1);
        }
    }
}

/// A text entry with nothing but its box and its placement said.
///
/// Shared by every test module that needs one — `text_quad`'s sets its own
/// `text` on top — rather than written out per module:
/// `TextEntry` is all public fields and no constructor, so a builder per
/// module is a field list per module to keep in step.
#[cfg(test)]
pub(super) fn test_entry(rect: Rect, transform: crate::transform::Transform) -> TextEntry {
    TextEntry {
        text: "x".into(),
        rect,
        color: crate::widgets::Color::WHITE,
        font_size: 16.0,
        font_family: crate::widgets::FontFamily::default(),
        font_weight: FontWeight::default(),
        line_height: LineHeight::Normal,
        letter_spacing: 0.0,
        align: Default::default(),
        fit: None,
        opacity: 1.0,
        clip: None,
        transform,
    }
}

/// A font system holding the vendored test font and nothing else, so the
/// widths a test reads are the font's and not the machine's.
#[cfg(test)]
pub(super) fn vendored_font_system() -> FontSystem {
    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(FONT.to_vec());
    FontSystem::new_with_locale_and_db("en-US".into(), db)
}

/// The per-group scratch is grown once and then kept.
///
/// Capacity and not an allocation count: counting allocations needs an
/// allocator this crate does not install (#461). What a capacity can say is
/// that the container outlived the frame boundary, which is the whole of this
/// change — and a local cannot be asked the question at all.
///
/// The second frame asks for *less* than the first, which is what makes the
/// answer mean something: only a container that was cleared rather than
/// dropped still has the first frame's room in it.
///
/// Five upright texts in that first frame, and not one or two, because a
/// `Vec<usize>` allocates room for four on its first push however few things
/// go into it. With fewer, `kept` reads 4 on a frame that keeps five and 4
/// again on a rebuilt frame that keeps one, and that half of the assertion
/// cannot fail. Five crosses the step to 8. `transformed_indices` needs no
/// such help — it goes from one entry to none, so a rebuilt one reads 0.
#[cfg(test)]
mod scratch_survives_the_frame {
    use super::{TextRenderState, test_entry};
    use crate::renderer::GpuContext;
    use crate::renderer::types::TextEntry;
    use crate::transform::Transform;
    use crate::widgets::Rect;

    #[test]
    fn a_smaller_second_frame_still_has_the_first_frame_s_room() {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let mut state =
            TextRenderState::new(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8UnormSrgb);

        /// What a `Vec<usize>` allocates for its first push.
        const MIN_CAP: usize = 4;
        /// Enough upright texts to take `kept` past that floor.
        const UPRIGHT: usize = 5;

        // Texts glyphon draws, and then one the quad path takes, so both
        // lists are filled: `kept` holds the first five, `transformed_indices`
        // the last.
        let box_ = Rect::new(0.0, 0.0, 80.0, 20.0);
        let mut texts: Vec<TextEntry> = (0..UPRIGHT)
            .map(|_| test_entry(box_, Transform::default()))
            .collect();
        texts.push(test_entry(box_, Transform::scale(2.0)));

        let frame = |state: &mut TextRenderState, texts: &[TextEntry]| {
            state.begin_frame(&gpu.queue, (200, 100));
            let transformed = state.prepare_layer(
                0,
                &gpu.device,
                &gpu.queue,
                texts,
                &Default::default(),
                (200, 100),
                1.0,
            );
            let quads = transformed.to_vec();
            state.end_frame();
            quads
        };

        assert_eq!(
            frame(&mut state, &texts),
            [UPRIGHT],
            "the scaled text goes to the quad path, and only it"
        );
        let first = (state.transformed_indices.capacity(), state.kept.capacity());
        assert!(
            first.0 > 0 && first.1 > MIN_CAP,
            "five upright and one scaled should fill one list and grow the \
             other past a fresh `Vec`'s floor: {first:?}"
        );

        // One upright text now, and nothing at all for the quad path.
        assert_eq!(frame(&mut state, &texts[..1]), []);
        assert_eq!(
            (state.transformed_indices.capacity(), state.kept.capacity()),
            first,
            "the second frame reused the first frame's scratch"
        );
    }
}

/// What the scale-collapse cull decides, at the boundary and either side.
///
/// The one branch in `prepare_layer` that throws a text away before anything
/// is done for it, and it has been wrong once already: it read the diagonal
/// rather than the row norms, so a quarter turn — where `a` and `d` are both
/// `cos θ` — was called a collapse and the label vanished at exactly 90° and
/// 270°. `tests/text_at_angles.rs` counts the pixels that came back, which is
/// what caught *that*, but pixels cannot see this branch invert: a text the
/// cull lets through at zero scale draws a quad of zero width, so nothing
/// appears either way and the only difference is the work done to produce
/// nothing.
///
/// So this asks the decision rather than the picture. `||` read as `&&` keeps
/// a text flattened on one axis, and the threshold read as `<=` or `==`
/// changes the answer for a text sitting exactly on it — `1e-3` survives
/// `scale_xy` and the row norm unchanged, so the boundary is a real value and
/// not a hair either side of one.
#[cfg(test)]
mod a_text_is_culled_only_when_an_axis_has_collapsed {
    use super::{TextRenderState, test_entry};
    use crate::renderer::GpuContext;
    use crate::transform::Transform;
    use crate::widgets::Rect;

    /// The scale at which a text stops being drawn, as `prepare_layer` spells
    /// it.
    const COLLAPSED: f32 = 1e-3;

    #[test]
    fn one_flattened_axis_is_enough_and_the_threshold_itself_is_not() {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let mut state =
            TextRenderState::new(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8UnormSrgb);
        let box_ = Rect::new(0.0, 0.0, 80.0, 20.0);

        // `true` where the text should be thrown away. Anything kept is a
        // transformed text, so it leaves by the quad path rather than through
        // glyphon.
        let cases = [
            (Transform::scale_xy(0.0, 1.0), true, "flat in x, whole in y"),
            (Transform::scale_xy(1.0, 0.0), true, "whole in x, flat in y"),
            (Transform::scale_xy(0.0, 0.0), true, "flat in both"),
            (
                Transform::scale_xy(COLLAPSED, 1.0),
                false,
                "x exactly at the threshold, which is not below it",
            ),
            (
                Transform::scale_xy(1.0, COLLAPSED),
                false,
                "y exactly at the threshold",
            ),
            (
                Transform::rotate(std::f32::consts::FRAC_PI_2),
                false,
                "a quarter turn, where the diagonal is zero and the scale is not",
            ),
        ];

        for (transform, culled, what) in cases {
            let texts = [test_entry(box_, transform)];
            state.begin_frame(&gpu.queue, (200, 100));
            let transformed = state.prepare_layer(
                0,
                &gpu.device,
                &gpu.queue,
                &texts,
                &Default::default(),
                (200, 100),
                1.0,
            );
            let quads = transformed.to_vec();
            let kept = state.kept.len();
            state.end_frame();

            assert_eq!(
                quads.is_empty(),
                culled,
                "{what}: {quads:?} went to the quad path"
            );
            assert_eq!(kept, 0, "{what}: a transformed text never reaches glyphon");
        }
    }
}

#[cfg(test)]
mod laid_out_tests {
    use super::{laid_out_in, test_entry as entry};
    use crate::transform::Transform;
    use crate::widgets::Rect;

    /// The box a text was laid out in, carried through its placement.
    ///
    /// Two callers read it — what gets culled against its clip, and what gets
    /// routed away from glyphon — so every term here decides whether a text is
    /// drawn at all or drawn through the wrong pipeline. It is four
    /// arithmetic operations and each of them can be written backwards without
    /// the picture obviously changing.
    /// A text is dropped only when it is wholly past one side of its clip.
    ///
    /// The cheapest thing the text path does and the easiest to get backwards:
    /// too eager and a visible text is never drawn, with nothing to say why.
    #[test]
    fn a_text_is_dropped_only_when_it_is_wholly_outside_its_clip() {
        use super::falls_outside;
        let clip = Rect::new(100.0, 100.0, 200.0, 100.0);

        assert!(
            !falls_outside(Rect::new(150.0, 120.0, 40.0, 20.0), clip),
            "inside"
        );
        assert!(
            !falls_outside(Rect::new(0.0, 0.0, 400.0, 400.0), clip),
            "over all of it"
        );

        // A whole side past, on each of the four.
        assert!(
            falls_outside(Rect::new(10.0, 120.0, 80.0, 20.0), clip),
            "left of it"
        );
        assert!(
            falls_outside(Rect::new(310.0, 120.0, 80.0, 20.0), clip),
            "right of it"
        );
        assert!(
            falls_outside(Rect::new(150.0, 10.0, 40.0, 80.0), clip),
            "above it"
        );
        assert!(
            falls_outside(Rect::new(150.0, 210.0, 40.0, 80.0), clip),
            "below it"
        );

        // Just reaching in on each side is not outside — the far edge is what
        // decides, and reading the near one instead keeps a text that has
        // gone and drops one that is still here.
        assert!(
            !falls_outside(Rect::new(20.0, 120.0, 81.0, 20.0), clip),
            "reaching in from the left"
        );
        assert!(
            !falls_outside(Rect::new(299.0, 120.0, 80.0, 20.0), clip),
            "reaching in from the right"
        );
        assert!(
            !falls_outside(Rect::new(150.0, 20.0, 40.0, 81.0), clip),
            "reaching in from above"
        );
        assert!(
            !falls_outside(Rect::new(150.0, 199.0, 40.0, 80.0), clip),
            "reaching in from below"
        );

        // Overlapping on neither axis is still two boxes in the same frame,
        // and a corner-to-corner pair is outside by both.
        assert!(
            falls_outside(Rect::new(0.0, 0.0, 50.0, 50.0), clip),
            "off the top-left corner"
        );

        // The tolerance, which is the whole reason there is one. A text
        // ending exactly where its clip begins is kept, and so is one a
        // hundredth of a pixel short of it — which is where a float lands
        // after a transform. Half a pixel past is gone. The margin runs
        // outward on every side; inward on any of them drops a text that is
        // still touching its clip.
        for (label, text) in [
            (
                "ending exactly at the left edge",
                Rect::new(20.0, 120.0, 80.0, 20.0),
            ),
            (
                "a hundredth short of the left edge",
                Rect::new(20.0, 120.0, 79.99, 20.0),
            ),
            (
                "starting exactly at the right edge",
                Rect::new(300.0, 120.0, 80.0, 20.0),
            ),
            (
                "a hundredth past the right edge",
                Rect::new(300.01, 120.0, 80.0, 20.0),
            ),
            (
                "ending exactly at the top edge",
                Rect::new(150.0, 20.0, 40.0, 80.0),
            ),
            (
                "starting exactly at the bottom edge",
                Rect::new(150.0, 200.0, 40.0, 80.0),
            ),
        ] {
            assert!(
                !falls_outside(text, clip),
                "{label}: a text touching its clip is still drawn"
            );
        }
        for (label, text) in [
            (
                "half a pixel short of the left edge",
                Rect::new(20.0, 120.0, 79.5, 20.0),
            ),
            (
                "half a pixel past the right edge",
                Rect::new(300.5, 120.0, 80.0, 20.0),
            ),
            (
                "half a pixel short of the top edge",
                Rect::new(150.0, 20.0, 40.0, 79.5),
            ),
            (
                "half a pixel past the bottom edge",
                Rect::new(150.0, 200.5, 40.0, 80.0),
            ),
        ] {
            assert!(
                falls_outside(text, clip),
                "{label}: past the tolerance is past the clip"
            );
        }
    }

    #[test]
    fn a_text_is_laid_out_where_its_placement_puts_it() {
        let r = Rect::new(10.0, 20.0, 100.0, 40.0);

        let plain = laid_out_in(&entry(r, Transform::IDENTITY));
        assert_eq!((plain.x, plain.y), (10.0, 20.0));
        assert_eq!((plain.width, plain.height), (100.0, 40.0));

        let moved = laid_out_in(&entry(r, Transform::translate(5.0, -7.0)));
        assert_eq!((moved.x, moved.y), (15.0, 13.0));
        assert_eq!((moved.width, moved.height), (100.0, 40.0));

        let scaled = laid_out_in(&entry(r, Transform::scale_xy(2.0, 3.0)));
        assert_eq!((scaled.x, scaled.y), (20.0, 60.0));
        assert_eq!((scaled.width, scaled.height), (200.0, 120.0));

        // A mirror puts the far corner first, and the box is still a box with
        // a positive extent — which is why the corners are taken as a min and
        // an absolute difference rather than as first and second.
        let mirrored = laid_out_in(&entry(r, Transform::scale_xy(-1.0, 1.0)));
        assert_eq!((mirrored.x, mirrored.y), (-110.0, 20.0));
        assert_eq!((mirrored.width, mirrored.height), (100.0, 40.0));
    }
}

#[cfg(test)]
mod line_width_tests {
    use super::{buffer_height, line_width};
    use crate::renderer::LineFit;
    use crate::widgets::{Rect, TextOverflow};

    fn laid_out_in(width: Option<f32>, wrap: bool) -> Option<LineFit> {
        Some(LineFit {
            width,
            max_lines: None,
            overflow: TextOverflow::Clip,
            wrap,
        })
    }

    /// A text is shaped in the width it was laid out in, scaled, and in
    /// nothing else: not its box, which a measured line can be a hair wider
    /// than, and not a floor.
    #[test]
    fn the_width_laid_out_in_is_the_width_shaped_in() {
        let box_width = Some(48.0);
        assert_eq!(
            line_width(laid_out_in(Some(50.0), true), box_width, 1.0),
            (Some(50.0), true)
        );
        assert_eq!(
            line_width(laid_out_in(Some(50.0), true), box_width, 1.5),
            (Some(75.0), true),
            "scaled, and nothing floors it"
        );
        // An unwrapped text that a mark needs a width for keeps the width, to
        // mark at, and does not wrap there.
        assert_eq!(
            line_width(laid_out_in(Some(90.0), false), box_width, 1.0),
            (Some(90.0), false)
        );
    }

    /// A text laid out with no width ran on one line per paragraph, and is
    /// shaped so: in its box, which can then only align it, never break it.
    #[test]
    fn a_text_laid_out_with_no_width_is_shaped_in_its_box_unwrapped() {
        for fit in [laid_out_in(None, true), laid_out_in(None, false)] {
            assert_eq!(line_width(fit, Some(72.0), 2.0), (Some(72.0), false));
            assert_eq!(line_width(fit, None, 2.0), (None, false));
        }
    }

    /// A text drawn without a fit says nothing of where it was laid out but
    /// its box, so it wraps there.
    #[test]
    fn no_fit_wraps_at_the_box() {
        assert_eq!(line_width(None, Some(72.0), 2.0), (Some(72.0), true));
    }

    /// The height floor is in logical pixels and the scale is applied after it,
    /// so a short box on a HiDPI screen gets the floor at that screen's density
    /// rather than a floor that shrinks as the screen gets finer.
    #[test]
    fn the_height_floor_is_logical_and_the_scale_comes_after_it() {
        assert_eq!(buffer_height(Rect::new(0.0, 0.0, 50.0, 10.0), 1.0), 50.0);
        assert_eq!(buffer_height(Rect::new(0.0, 0.0, 50.0, 10.0), 2.0), 100.0);
        assert_eq!(buffer_height(Rect::new(0.0, 0.0, 50.0, 80.0), 0.5), 40.0);
    }

    /// The two paths give an uncut text different heights, which is why a
    /// coverage mask has to pick one rather than assume. If this ever passes,
    /// `text_mask` no longer has a choice to get wrong — and the comment saying
    /// it does is stale. Their widths are one function's.
    #[test]
    fn the_transformed_shaper_asks_for_another_height() {
        let rect = Rect::new(0.0, 0.0, 72.0, 30.0);
        assert_ne!(
            buffer_height(rect, 4.0),
            super::super::text_quad::buffer_height(rect, 4.0),
            "a 30-point box: 200 texels through this one and 132 through the other"
        );
    }
}

/// A line is placed in the text's own box, whatever width it was laid out in.
///
/// Shaped with the vendored font alone, so the widths are the font's and not
/// the machine's. The text was laid out in 300 pixels and its box is 120, as a
/// box that does not fill its column comes back — and the line is far shorter
/// than either, so a line placed across the width it was shaped in instead of
/// its box starts 90 pixels late when centred, and a right-to-left one starts
/// past the box's right edge (#617, #621).
#[cfg(test)]
mod a_line_is_placed_in_its_own_box {
    use super::{paint_offset, shape_entry, test_entry, text_buffer_key, vendored_font_system};
    use crate::renderer::LineFit;
    use crate::transform::Transform;
    use crate::widgets::{FontFamily, Rect, TextAlign, TextOverflow};

    const BOX: f32 = 120.0;
    const OFFERED: f32 = 300.0;
    const ARABIC: &str = "\u{633}\u{644}\u{627}\u{645}";

    fn entry(text: &str, align: TextAlign) -> super::TextEntry {
        let mut entry = test_entry(Rect::new(0.0, 0.0, BOX, 20.0), Transform::default());
        entry.text = text.into();
        entry.font_family = FontFamily::name("DejaVu Sans Mono");
        entry.align = align;
        entry.fit = Some(LineFit {
            width: Some(OFFERED),
            max_lines: None,
            overflow: TextOverflow::Clip,
            wrap: true,
        });
        entry
    }

    /// Where the first line's glyphs begin in the box, once placed, and how
    /// wide the line is, in physical pixels.
    fn first_line(entry: &super::TextEntry, scale: f32) -> (f32, f32) {
        let buffer = shape_entry(&mut vendored_font_system(), entry, scale);
        let offset = paint_offset(&buffer, entry.rect.width * scale, entry.align);
        let run = buffer.layout_runs().next().expect("a line");
        let start = run.glyphs.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
        (start + offset, run.line_w)
    }

    #[test]
    fn a_centred_line_is_centred_in_its_box_and_not_in_the_width_it_was_laid_out_in() {
        for scale in [1.0, 1.5, 2.0] {
            let (start, width) = first_line(&entry("hi", TextAlign::Center), scale);
            let expected = (BOX * scale - width) / 2.0;
            assert!(
                (start - expected).abs() < 0.5,
                "at scale {scale} a {width}-pixel line in a {}-pixel box starts at \
                 {start}, not at {expected}",
                BOX * scale
            );
        }
    }

    #[test]
    fn an_end_aligned_line_ends_where_its_box_does() {
        let (start, width) = first_line(&entry("hi", TextAlign::End), 1.0);
        assert!(
            (start + width - BOX).abs() < 0.5,
            "the line ends at {} in a box that ends at {BOX}",
            start + width
        );
    }

    #[test]
    fn a_start_aligned_line_starts_at_the_box() {
        let (start, _) = first_line(&entry("hi", TextAlign::Start), 1.0);
        assert!(start.abs() < 0.5, "the line starts at {start}");
    }

    /// A right-to-left line starts at the start of its box, which is its
    /// right edge — and ends at the left one when it is aligned to the end.
    #[test]
    fn a_right_to_left_line_starts_at_its_box_s_right_edge() {
        for scale in [1.0, 1.5] {
            let (start, width) = first_line(&entry(ARABIC, TextAlign::Start), scale);
            assert!(
                (start + width - BOX * scale).abs() < 0.5,
                "at scale {scale} the line ends at {} in a box that ends at {}",
                start + width,
                BOX * scale
            );
            let (start, _) = first_line(&entry(ARABIC, TextAlign::End), scale);
            assert!(start.abs() < 0.5, "at scale {scale} its end is at {start}");
        }
    }

    /// Two texts that differ only in alignment are two different buffers, so
    /// the cache must not hand one the other's.
    #[test]
    fn alignment_is_part_of_the_cache_key() {
        let keys: Vec<u64> = [
            TextAlign::Start,
            TextAlign::Center,
            TextAlign::End,
            TextAlign::Justified,
        ]
        .map(|align| text_buffer_key(&entry("hi", align), 1.0))
        .into();
        for (i, a) in keys.iter().enumerate() {
            for b in &keys[i + 1..] {
                assert_ne!(a, b, "two alignments share a cached buffer");
            }
        }
    }
}

/// A text drawn without a fit — `PaintContext::draw_text` from a widget
/// outside the crate — wraps at the box it was drawn in, as it always has.
#[cfg(test)]
#[test]
fn a_text_drawn_without_a_fit_wraps_at_its_box() {
    let mut entry = test_entry(
        Rect::new(0.0, 0.0, 80.0, 200.0),
        crate::transform::Transform::default(),
    );
    entry.text = "one two three four five six seven".into();
    entry.font_family = FontFamily::name("DejaVu Sans Mono");
    for scale in [1.0, 1.5] {
        let buffer = shape_entry(&mut vendored_font_system(), &entry, scale);
        assert!(
            buffer.layout_runs().count() > 1,
            "at {scale}x a long text in an 80-pixel box ran on one line"
        );
    }
}

/// A wrapped text is drawn on the lines it was measured on, in a box as narrow
/// as its widest line (#622).
///
/// The measurer lays the text out in the width it was offered and the box
/// comes back as its widest line; glyphon shapes it from the entry that box
/// and that fit make. The two have to keep the same glyphs on the same lines.
/// With the vendored font, so the widths are the font's.
#[cfg(test)]
mod a_wrapped_text_keeps_its_measured_lines {
    use super::{shape_entry, test_entry, vendored_font_system};
    use crate::renderer::LineFit;
    use crate::transform::Transform;
    use crate::widgets::{FontFamily, FontWeight, LineHeight, Rect, TextAlign, TextOverflow};

    const OFFERED: f32 = 120.0;

    fn lines(buffer: &glyphon::Buffer) -> Vec<Vec<u16>> {
        buffer
            .layout_runs()
            .map(|run| run.glyphs.iter().map(|g| g.glyph_id).collect())
            .collect()
    }

    #[test]
    fn the_lines_drawn_are_the_lines_measured() {
        let family = FontFamily::name("DejaVu Sans Mono");
        let fit = LineFit {
            width: Some(OFFERED),
            max_lines: None,
            overflow: TextOverflow::Clip,
            wrap: true,
        };
        for text in [
            "one two three four five six seven",
            "\u{633}\u{644}\u{627}\u{645} \u{633}\u{644}\u{627}\u{645} \
             \u{633}\u{644}\u{627}\u{645} \u{633}\u{644}\u{627}\u{645}",
        ] {
            let measured = super::shape(
                &mut vendored_font_system(),
                text,
                16.0,
                family,
                FontWeight::NORMAL,
                LineHeight::Normal,
                0.0,
                TextAlign::Start,
                (None, None),
                Some(fit),
                1.0,
            );
            let widest = measured.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
            let height: f32 = measured.layout_runs().map(|r| r.line_height).sum();
            assert!(
                measured.layout_runs().count() > 1,
                "the text has to wrap at {OFFERED}, or this proves nothing"
            );

            let mut entry = test_entry(Rect::new(0.0, 0.0, widest, height), Transform::default());
            entry.text = text.into();
            entry.font_family = family;
            entry.fit = Some(fit);
            for scale in [1.0, 1.5] {
                let drawn = shape_entry(&mut vendored_font_system(), &entry, scale);
                assert_eq!(
                    lines(&drawn),
                    lines(&measured),
                    "{text:?} at {scale}x is drawn on other lines than it was measured on"
                );
            }
        }
    }
}

/// Two texts that differ only in line height are two buffers, so the glyphon
/// path's cache must not hand one the other's lines.
#[cfg(test)]
#[test]
fn line_height_is_part_of_the_buffer_key() {
    use crate::transform::Transform;
    let entry = |line_height| TextEntry {
        line_height,
        ..test_entry(Rect::new(0.0, 0.0, 120.0, 40.0), Transform::default())
    };
    assert_ne!(
        text_buffer_key(&entry(LineHeight::Normal), 1.0),
        text_buffer_key(&entry(LineHeight::Absolute(30.0)), 1.0),
    );
    assert_ne!(
        text_buffer_key(&entry(LineHeight::Relative(2.0)), 1.0),
        text_buffer_key(&entry(LineHeight::Absolute(2.0)), 1.0),
        "a factor and a height of the same number are not the same line",
    );
}

/// Two texts that differ only in letter spacing are two buffers: a key without
/// it hands the second the first one's glyph positions, under a box measured
/// for the second.
#[cfg(test)]
#[test]
fn letter_spacing_is_part_of_the_buffer_key() {
    use crate::transform::Transform;
    let entry = |letter_spacing| TextEntry {
        letter_spacing,
        ..test_entry(Rect::new(0.0, 0.0, 120.0, 40.0), Transform::default())
    };
    assert_ne!(
        text_buffer_key(&entry(0.0), 1.0),
        text_buffer_key(&entry(2.0), 1.0),
    );
}

/// An aligned text that is cut is cut where it was measured, and its lines are
/// aligned across its own box.
///
/// Every path shapes a cut text at the width it was laid out in, and an
/// aligned one is then placed across its box, which is its widest kept line.
/// The lines drawn must keep the same glyphs as the lines measured, the mark
/// included, or a label is measured on one set of lines and drawn on another;
/// and once placed they must be centred in the box, not in the wider width.
/// With the vendored font, so the widths are the font's.
#[cfg(test)]
mod an_aligned_cut_is_the_measured_cut {
    use super::{paint_offset, shape, vendored_font_system};
    use crate::renderer::LineFit;
    use crate::widgets::{FontFamily, FontWeight, LineHeight, TextAlign, TextOverflow};

    const WORDS: &str = "one two three four five six seven eight nine ten eleven twelve";
    const OFFERED: f32 = 150.0;
    const SIZE: f32 = 16.0;

    fn fit(overflow: TextOverflow) -> LineFit {
        LineFit {
            width: Some(OFFERED),
            max_lines: Some(2),
            overflow,
            wrap: true,
        }
    }

    /// Each line as its glyph ids, where it starts in a box `width` wide once
    /// placed, and how wide it is.
    fn lines(
        align: TextAlign,
        width: Option<f32>,
        fit: LineFit,
        scale: f32,
    ) -> Vec<(Vec<u16>, f32, f32)> {
        let family = FontFamily::name("DejaVu Sans Mono");
        let buffer = shape(
            &mut vendored_font_system(),
            WORDS,
            SIZE * scale,
            family,
            FontWeight::NORMAL,
            LineHeight::Normal,
            0.0,
            align,
            (width, Some(1000.0)),
            Some(fit),
            scale,
        );
        let offset = width.map_or(0.0, |width| paint_offset(&buffer, width, align));
        buffer
            .layout_runs()
            .map(|run| {
                let start = run.glyphs.iter().map(|g| g.x).fold(f32::INFINITY, f32::min);
                (
                    run.glyphs.iter().map(|g| g.glyph_id).collect(),
                    start + offset,
                    run.line_w,
                )
            })
            .collect()
    }

    fn ellipsis_glyph() -> u16 {
        let buffer = shape(
            &mut vendored_font_system(),
            "\u{2026}",
            SIZE,
            FontFamily::name("DejaVu Sans Mono"),
            FontWeight::NORMAL,
            LineHeight::Normal,
            0.0,
            TextAlign::Start,
            (None, None),
            None,
            1.0,
        );
        buffer.layout_runs().next().unwrap().glyphs[0].glyph_id
    }

    #[test]
    fn a_centred_ellipsis_keeps_the_measured_lines_and_centres_them_in_the_box() {
        for overflow in [TextOverflow::Ellipsis, TextOverflow::Clip] {
            // As the measurer shapes it: at the width layout offered.
            let measured = lines(TextAlign::Start, None, fit(overflow), 1.0);
            assert_eq!(measured.len(), 2, "{measured:?}");
            let widest = measured.iter().map(|l| l.2).fold(0.0, f32::max);

            for scale in [1.0, 2.0] {
                let drawn = lines(
                    TextAlign::Center,
                    Some(widest * scale),
                    fit(overflow),
                    scale,
                );
                let glyphs = |ls: &[(Vec<u16>, f32, f32)]| {
                    ls.iter().map(|l| l.0.clone()).collect::<Vec<_>>()
                };
                assert_eq!(
                    glyphs(&drawn),
                    glyphs(&measured),
                    "{overflow:?} at {scale}x cut somewhere else than it was measured"
                );
                for (_, start, width) in &drawn {
                    let expected = (widest * scale - width) / 2.0;
                    assert!(
                        (start - expected).abs() < 0.5,
                        "{overflow:?} at {scale}x: a {width}-pixel line starts at \
                         {start}, not centred at {expected}"
                    );
                }
            }
            if overflow == TextOverflow::Ellipsis {
                assert_eq!(measured[1].0.last(), Some(&ellipsis_glyph()));
            }
        }
    }
}

/// A generic family whose configured name is not installed still has a face
/// that draws it — cosmic-text falls back to one — and `Normal` is that face's
/// line height, not a guess. cosmic-text names Open Sans for sans-serif, which
/// most machines do not have; here the only face is DejaVu Sans Mono.
#[cfg(test)]
#[test]
fn normal_is_the_line_height_of_the_face_that_draws_the_text() {
    let mut font_system = vendored_font_system();
    let ratio =
        resolve_font(&mut font_system, FontFamily::SansSerif, FontWeight::NORMAL).line_ratio;
    assert!(
        (ratio - 1.1640625).abs() < 1e-4,
        "{ratio} is not DejaVu Sans Mono's own 1.164"
    );
}

/// A face's own line is its ascent, its descent and its line gap, all three:
/// the vendored font declares no gap, so only a face that does can tell a gap
/// added from a gap taken away.
#[cfg(test)]
#[test]
fn a_face_s_line_counts_its_ascent_descent_and_gap() {
    assert_eq!(line_ratio(800.0, -200.0, 200.0, 1000), Some(1.2));
    assert_eq!(line_ratio(800.0, -200.0, 0.0, 2000), Some(0.5));
}

/// Metrics that make no height are not a ratio, so the caller falls back
/// rather than hand `Metrics` a line that does not come back (#349).
#[cfg(test)]
#[test]
fn metrics_that_make_no_height_are_no_ratio() {
    assert_eq!(line_ratio(800.0, -200.0, 0.0, 0), None, "an em of zero");
    assert_eq!(
        line_ratio(0.0, 0.0, 0.0, 1000),
        None,
        "a face that says nothing"
    );
    assert_eq!(line_ratio(f32::NAN, -200.0, 0.0, 1000), None);
}

/// An absolute line height is logical pixels, so a text shaped at twice the
/// scale has lines twice as tall — the step every draw path at HiDPI takes.
#[cfg(test)]
#[test]
fn an_absolute_line_height_is_scaled_with_the_text() {
    const FONT: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(FONT.to_vec());
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let line = |font_system: &mut FontSystem, scale: f32| {
        shape(
            font_system,
            "a",
            14.0 * scale,
            FontFamily::name("DejaVu Sans Mono"),
            FontWeight::NORMAL,
            LineHeight::Absolute(20.0),
            0.0,
            TextAlign::Start,
            (None, None),
            None,
            scale,
        )
        .metrics()
        .line_height
    };
    assert_eq!(line(&mut font_system, 1.0), 20.0);
    assert_eq!(line(&mut font_system, 2.0), 40.0);
}

/// A weight the family does not have is the nearest one it does, as CSS Fonts 4
/// §5.2 matches it — not the first face anywhere with that exact weight.
///
/// Asked as `sans-serif`, the way an application asks: cosmic-text names Open
/// Sans for it, which is not here, so the family that draws it is the one the
/// 400 probe finds — DejaVu Sans Mono, which has 400 and 700. "Weight Decoy"
/// has a 600 and nothing else. Both extra faces are DejaVu Sans Mono Bold cut
/// down to the digits, the decoy renamed, as its license asks of a derivative
/// (`tests/assets/`).
#[cfg(test)]
#[test]
fn a_missing_weight_is_the_nearest_one_of_the_same_family() {
    const REGULAR: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    const BOLD: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono-Bold-digits.ttf");
    const DECOY: &[u8] = include_bytes!("../../tests/assets/WeightDecoy-SemiBold-digits.ttf");
    let mut db = glyphon::fontdb::Database::new();
    for font in [REGULAR, BOLD, DECOY] {
        db.load_font_data(font.to_vec());
    }
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);

    let mut drawn_in = |weight: FontWeight| {
        let buffer = shape(
            &mut font_system,
            "2356",
            14.0,
            FontFamily::SansSerif,
            weight,
            LineHeight::Normal,
            0.0,
            TextAlign::Start,
            (None, None),
            None,
            1.0,
        );
        buffer
            .layout_runs()
            .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.font_id))
            .map(|id| {
                let face = font_system.db().face(id).expect("a face that drew a glyph");
                (face.families[0].0.clone(), face.weight.0)
            })
            .collect::<Vec<_>>()
    };

    let semibold = drawn_in(FontWeight(600));
    assert_eq!(semibold.len(), 4, "four digits drawn");
    assert!(
        semibold
            .iter()
            .all(|face| *face == ("DejaVu Sans Mono".into(), 700)),
        "600 was drawn in {semibold:?}, not the family's nearest, 700"
    );
    let light = drawn_in(FontWeight(300));
    assert!(
        light
            .iter()
            .all(|face| *face == ("DejaVu Sans Mono".into(), 400)),
        "300 was drawn in {light:?}, not the family's nearest, 400"
    );
}

/// A variable face keeps the weight asked of it: fontdb lists the face once,
/// at its default, and cosmic-text sets the `wght` axis from the weight it is
/// handed — so resolving the weight to the face's own would draw every weight
/// of a variable family at 400. `GuidoVariable.ttf` is built from nothing by
/// `tests/assets/make_variable_fixture.py`: one `wght` axis, 100 to 900.
#[cfg(test)]
#[test]
fn a_variable_face_is_shaped_at_the_weight_asked_of_it() {
    const VARIABLE: &[u8] = include_bytes!("../../tests/assets/GuidoVariable.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(VARIABLE.to_vec());
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let buffer = shape(
        &mut font_system,
        "2356",
        14.0,
        FontFamily::name("Guido Variable"),
        FontWeight::BOLD,
        LineHeight::Normal,
        0.0,
        TextAlign::Start,
        (None, None),
        None,
        1.0,
    );
    let weights: Vec<u16> = buffer
        .layout_runs()
        .flat_map(|run| run.glyphs.iter().map(|glyph| glyph.font_weight.0))
        .collect();
    assert_eq!(weights, [700; 4], "the axis was set to {weights:?}");
}

/// The line height of a weight is read from the face that draws that weight,
/// not from the family's regular one. The Bold fixture declares a line gap
/// the Regular does not (410 units of 2048), so the two lines differ.
#[cfg(test)]
#[test]
fn a_weight_s_line_height_is_its_own_face_s() {
    const REGULAR: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    const BOLD: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono-Bold-digits.ttf");
    let mut db = glyphon::fontdb::Database::new();
    for font in [REGULAR, BOLD] {
        db.load_font_data(font.to_vec());
    }
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let ratio = |font_system: &mut FontSystem, weight| {
        resolve_font(font_system, FontFamily::SansSerif, weight).line_ratio
    };
    assert!((ratio(&mut font_system, FontWeight::NORMAL) - 1.1640625).abs() < 1e-4);
    let bold = ratio(&mut font_system, FontWeight::BOLD);
    assert!(
        (bold - 1.3642578).abs() < 1e-4,
        "{bold} is the regular face's line, not the bold one's 1.364"
    );
}

/// A named family that is installed is measured in itself, even when it has
/// no space for the probe to draw — an icon font such as Symbols Nerd Font
/// (#604). Probed, the space falls back to DejaVu Sans Mono, and the digits
/// would be measured in DejaVu's narrow ones while drawn in the wide ones.
#[cfg(test)]
#[test]
fn a_named_family_without_a_space_is_measured_in_itself() {
    const FALLBACK: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    const NO_SPACE: &[u8] = include_bytes!("../../tests/assets/GuidoNoSpace.ttf");
    let mut db = glyphon::fontdb::Database::new();
    for font in [FALLBACK, NO_SPACE] {
        db.load_font_data(font.to_vec());
    }
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let buffer = shape(
        &mut font_system,
        "2356",
        14.0,
        FontFamily::name("Guido No Space"),
        FontWeight::NORMAL,
        LineHeight::Normal,
        0.0,
        TextAlign::Start,
        (None, None),
        None,
        1.0,
    );
    let width: f32 = buffer.layout_runs().map(|run| run.line_w).sum();
    assert!(
        (width - 4.0 * 1.5 * 14.0).abs() < 0.01,
        "four digits 1.5 em wide at 14 px were laid out {width} px wide"
    );
    let line = buffer.metrics().line_height;
    assert_eq!(
        line, 14.0,
        "a line of the family's own 1.0, not DejaVu's 1.164"
    );
}

/// A name that is not installed is still probed: the text is drawn in the
/// fallback a space finds, so its line is that face's and not the ratio kept
/// for a font system with no face at all.
#[cfg(test)]
#[test]
fn a_named_family_that_is_not_installed_is_measured_in_its_fallback() {
    const FALLBACK: &[u8] = include_bytes!("../../tests/assets/DejaVuSansMono.ttf");
    let mut db = glyphon::fontdb::Database::new();
    db.load_font_data(FALLBACK.to_vec());
    let mut font_system = FontSystem::new_with_locale_and_db("en-US".into(), db);
    let ratio = resolve_font(
        &mut font_system,
        FontFamily::name("Not Installed Anywhere"),
        FontWeight::NORMAL,
    )
    .line_ratio;
    assert!(
        (ratio - 1.1640625).abs() < 1e-4,
        "{ratio} is not DejaVu Sans Mono's 1.164"
    );
}

/// The glyph atlas holds what a frame draws, not what every frame drew.
///
/// glyphon marks every glyph a `prepare` touches as in use and evicts only
/// glyphs that are not, and the only thing that clears the mark is
/// `TextAtlas::trim`. Never trimmed, every glyph ever drawn stays in use: the
/// atlas doubles until it reaches the device's limit, and then `prepare` fails
/// and text stops being drawn at all. A text whose content keeps changing
/// walks it there, and so does a font-size animation — glyphs are keyed by
/// size.
///
/// glyphon will not say how big its atlas is; the device it allocates from
/// will, which is what `GpuContext::texture_bytes` asks. Every frame here draws
/// glyphs of one size, so a frame's glyphs fit where the last frame's were and
/// a trimmed atlas has no reason to grow at all.
#[cfg(test)]
pub(super) mod the_glyph_atlas_holds_a_frame_not_a_history {
    use super::{TextRenderState, test_entry, vendored_font_system};
    use crate::renderer::GpuContext;
    use crate::renderer::types::TextEntry;
    use crate::transform::Transform;
    use crate::widgets::{FontFamily, Rect};

    /// Pages of 32 characters the vendored font has, no two sharing one —
    /// Latin Extended-A, Greek and Cyrillic: a text that changes every frame,
    /// and every change a set of glyphs the atlas has not seen.
    pub(in crate::renderer) fn pages() -> Vec<String> {
        let characters: Vec<char> = (0x100..0x180)
            .chain(0x391..0x3CA)
            .chain(0x400..0x460)
            .filter_map(char::from_u32)
            .collect();
        characters
            .chunks(32)
            .map(|page| page.iter().collect())
            .collect()
    }

    /// `text` in the vendored font, large enough that a few pages of it fill
    /// an atlas that does not forget.
    pub(in crate::renderer) fn page(text: &str, transform: Transform) -> TextEntry {
        let mut entry = test_entry(Rect::new(0.0, 0.0, 1200.0, 60.0), transform);
        entry.text = text.into();
        entry.font_family = FontFamily::name("DejaVu Sans Mono");
        entry.font_size = 32.0;
        entry
    }

    /// Asserts that drawing every page, one per pass, leaves no more texture
    /// memory than drawing one: what `atlas_after` measures is a fresh
    /// renderer's growth.
    pub(in crate::renderer) fn holds_one_page(
        atlas_after: impl Fn(&GpuContext, &[String]) -> isize,
    ) {
        let Some(gpu) = crate::or_skip(GpuContext::try_new()) else {
            return;
        };
        let pages = pages();
        let one = atlas_after(&gpu, &pages[..1]);
        // An atlas is made for the first page, so a count of nothing is a
        // device that is not counting — wgpu's `counters` feature off — and
        // every comparison below would hold for the wrong reason.
        assert!(one > 0, "the device counted no texture memory at all");
        let every = atlas_after(&gpu, &pages);
        assert!(
            every <= one,
            "one page's glyphs need {one} bytes of atlas; {} new pages left {every}",
            pages.len()
        );
    }

    /// The texture memory a fresh renderer holds after drawing `frames`, one
    /// frame each.
    fn atlas_after(gpu: &GpuContext, frames: &[String]) -> isize {
        let before = gpu.texture_bytes();
        let format = wgpu::TextureFormat::Rgba8UnormSrgb;
        let mut state = TextRenderState::new(&gpu.device, &gpu.queue, format);
        state.font_system = vendored_font_system();
        let screen = (1200, 60);
        for text in frames {
            state.begin_frame(&gpu.queue, screen);
            let texts = [page(text, Transform::IDENTITY)];
            state.prepare_layer(
                0,
                &gpu.device,
                &gpu.queue,
                &texts,
                &Default::default(),
                screen,
                1.0,
            );
            state.end_frame();
            gpu.queue.submit([]);
        }
        gpu.texture_bytes() - before
    }

    #[test]
    fn a_text_that_changes_every_frame_needs_no_more_atlas_than_one_frame() {
        holds_one_page(atlas_after);
    }
}