frus-text 0.5.0

frus — text shaping and measurement (cosmic-text)
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
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
//! `frus-text` — text measurement, and in time shaping, on top of
//! [`cosmic_text`](https://docs.rs/cosmic-text).
//!
//! At this milestone the API is limited to [`measure`]: the natural size of a line
//! of text, which the layout engine needs in order to size a `Text` widget.
//!
//! The `FontSystem`, which loads the fonts, is expensive: it is initialised
//! **lazily** and shared behind a `Mutex`. That is a pragmatic v1 choice;
//! unifying it with the renderer's own `FontSystem` will come later.

#![deny(missing_docs)]

// The README's example is compiled and run by `cargo test --doc`, so it cannot rot.
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, OnceLock, RwLock};

use cosmic_text::{Attrs, Buffer, FontSystem, Metrics, Shaping, Style, Weight};
use frus_core::{fits, FontWeight, Point, Rect, ResolvedTextStyle, Size, TextRun, TextStyle};

/// The default line-height to font-size ratio.
///
/// It lives in `frus-core` now, because the renderer needs the same number and a copy of
/// it here is a copy that can drift: a measure and a paint disagreeing about how tall a
/// line is puts the second line of every paragraph where the layout reserved nothing.
use frus_core::DEFAULT_LINE_HEIGHT as LINE_HEIGHT_FACTOR;

// --- The bundled fonts ---
//
// Bundling guarantees deterministic text on **every** platform — Android above all,
// where the system "sans-serif" alias, defined in `fonts.xml` and not read by fontdb,
// resolves to no font at all.
//
// It is also the single largest thing frus puts in an application: about 3.4 MB of
// faces, ~1.8 MB once the APK compresses them, which is roughly **40%** of a minimal
// frus app (milestone 292). So each group is a cargo feature, on by default, and an
// application that ships its own faces can turn off the ones it does not need:
//
// ```toml
// frus = { version = "0.3", default-features = false, features = ["bundled-sans"] }
// ```
//
// Turning one off never turns an API into a panic — see [`available_style`] and
// [`family_for`], which resolve to what is actually loaded.

/// The bundled sans-serif, regular and bold. cosmic-text demands an **exact** weight
/// match on the primary family, so both are needed for `.bold()` to shape rather than
/// fall through to platform lists that do not exist on Android.
#[cfg(feature = "bundled-sans")]
const DEJAVU_SANS: &[u8] = include_bytes!("../assets/DejaVuSans.ttf");
#[cfg(feature = "bundled-sans")]
const DEJAVU_SANS_BOLD: &[u8] = include_bytes!("../assets/DejaVuSans-Bold.ttf");
/// The **oblique** faces, for the same reason one step further: cosmic-text demands an
/// exact *style* match too, so without them a plain `.italic()` used to **panic** ("no
/// default font found") — caught on the Android device. They are 1.28 MB of the 3.4,
/// so they are separable; when they are absent italic text is rendered **upright**
/// rather than not at all.
#[cfg(feature = "bundled-italic")]
const DEJAVU_SANS_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-Oblique.ttf");
#[cfg(feature = "bundled-italic")]
const DEJAVU_SANS_BOLD_OBLIQUE: &[u8] = include_bytes!("../assets/DejaVuSans-BoldOblique.ttf");
/// The monospace face — only ever reached by widgets that ask for it (`Kbd`, code).
#[cfg(feature = "bundled-mono")]
const DEJAVU_MONO: &[u8] = include_bytes!("../assets/DejaVuSansMono.ttf");
/// **Arabic** (Noto Naskh): DejaVu does not cover the Arabic script — it has no
/// contextual joining forms — so this face provides the fallback for Arabic runs.
#[cfg(feature = "bundled-arabic")]
const NOTO_ARABIC: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Regular.ttf");
#[cfg(feature = "bundled-arabic")]
const NOTO_ARABIC_BOLD: &[u8] = include_bytes!("../assets/NotoNaskhArabic-Bold.ttf");

/// The bundled fonts' internal family names; they must match the TTFs.
#[cfg(feature = "bundled-sans")]
const SANS_FAMILY: &str = "DejaVu Sans";
#[cfg(feature = "bundled-mono")]
const MONO_FAMILY: &str = "DejaVu Sans Mono";
/// The bundled Arabic face's family (Noto Naskh).
#[cfg(feature = "bundled-arabic")]
const ARABIC_FAMILY: &str = "Noto Naskh Arabic";

// --- The families text actually resolves to ---
//
// `None` means "nothing is loaded for this role": text falls back to the generic
// family and lets the platform answer, which is the best that can be done and is what
// the desktop wants anyway. An application that ships its own faces names them here
// through [`set_default_family`] / [`set_monospace_family`].
//
// A slot holds the name **as it was asked for**. What it is drawn in is decided against
// the faces actually loaded — see [`loaded_family`] — because the name a developer writes
// and the name inside a font file are often not the same: Inter's static files call their
// family "Inter 24pt". A family nobody loaded is not a smaller failure on Android, where
// there is no fallback list behind it: it draws **nothing at all** (milestone 626).

#[cfg(feature = "bundled-sans")]
static SANS: RwLock<Option<&'static str>> = RwLock::new(Some(SANS_FAMILY));
#[cfg(not(feature = "bundled-sans"))]
static SANS: RwLock<Option<&'static str>> = RwLock::new(None);
#[cfg(feature = "bundled-mono")]
static MONO: RwLock<Option<&'static str>> = RwLock::new(Some(MONO_FAMILY));
#[cfg(not(feature = "bundled-mono"))]
static MONO: RwLock<Option<&'static str>> = RwLock::new(None);
#[cfg(feature = "bundled-arabic")]
static ARABIC: RwLock<Option<&'static str>> = RwLock::new(Some(ARABIC_FAMILY));
#[cfg(not(feature = "bundled-arabic"))]
static ARABIC: RwLock<Option<&'static str>> = RwLock::new(None);
/// Whether an italic face exists for the default family. Set when the font system is
/// built, by looking at what was actually loaded rather than at what was asked for.
static ITALIC: AtomicBool = AtomicBool::new(cfg!(feature = "bundled-italic"));

/// Faces the application supplies itself. Every `FontSystem` frus builds loads them,
/// so they must be registered **before the application runs** — the renderer builds
/// its own system at start-up, exactly like declaring fonts in a manifest.
static EXTRA_FONTS: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());

/// The families inside [`EXTRA_FONTS`], in the order they were registered: the first
/// place to look when a name the application gave matches nothing.
static APP_FAMILIES: Mutex<Vec<String>> = Mutex::new(Vec::new());

/// Registers a font face from its bytes (TTF/OTF), for the whole process.
///
/// Call it **before** starting the application: the renderer builds its font database
/// at start-up and a face added afterwards will measure but not paint.
///
/// ```ignore
/// frus_text::add_font(include_bytes!("../fonts/Inter-Regular.ttf").to_vec());
/// frus_text::set_default_family("Inter");
/// ```
///
/// Bytes that hold no face this build can read are not registered, and the console says
/// so: a file that is not a font, or not the one you meant, is otherwise found on a device.
pub fn add_font(data: Vec<u8>) {
    let families = families_in(&data);
    if families.is_empty() {
        log::warn!(
            "frus: add_font was given {} bytes that hold no font face; nothing was registered",
            data.len()
        );
        return;
    }
    {
        let mut known = APP_FAMILIES.lock().expect("font registry");
        for family in families {
            if !known.contains(&family) {
                known.push(family);
            }
        }
    }
    EXTRA_FONTS
        .lock()
        .expect("font registry")
        .push(data.clone());
    // Anything already measuring gets it too, so tests and tools do not have to care
    // about ordering.
    if let Some(system) = FONT_SYSTEM.get() {
        if let Ok(mut system) = system.lock() {
            let db = system.db_mut();
            db.load_font_data(data);
            take_stock(db);
        }
    }
    forget_measurements();
}

/// Names the family text uses by default — the one an application ships instead of,
/// or alongside, the bundled sans. The face itself must be registered with
/// [`add_font`], or be present on the system.
///
/// The name is the one **inside** the font file, which is not always the file's: Inter's
/// static files are called "Inter 24pt". A name that matches no loaded family is not left
/// to draw nothing. frus takes the loaded family it plainly means — the same name in
/// another case or spacing, or one that extends it by a word ("Inter" → "Inter 24pt") —
/// and failing that the first family the application registered, then the platform's own
/// sans. The console names what was chosen and what to write instead.
pub fn set_default_family(name: &'static str) {
    *SANS.write().expect("family registry") = Some(name);
    forget_measurements();
}

/// Names the family monospaced text uses. See [`set_default_family`], whose rules for a
/// name that is not loaded apply here too; with nothing to fall back on, monospaced text
/// is drawn in the default family rather than not at all.
pub fn set_monospace_family(name: &'static str) {
    *MONO.write().expect("family registry") = Some(name);
    forget_measurements();
}

/// The family names a font file declares, in the form fontdb reports them (the
/// typographic family when the file has one).
fn families_in(data: &[u8]) -> Vec<String> {
    let mut db = cosmic_text::fontdb::Database::new();
    db.load_font_data(data.to_vec());
    let mut names: Vec<String> = Vec::new();
    for face in db.faces() {
        for (name, _) in &face.families {
            if !names.contains(name) {
                names.push(name.clone());
            }
        }
    }
    names
}

/// A family name with case, spaces, hyphens and underscores taken out: "Open Sans",
/// "open-sans" and "OpenSans" are one name to a person, and three to an exact match.
fn squashed(name: &str) -> String {
    name.chars()
        .filter(|c| !matches!(c, ' ' | '-' | '_'))
        .flat_map(char::to_lowercase)
        .collect()
}

/// The loaded family `requested` means, or `None` when none plainly does.
///
/// Three tries, from the strictest: the name exactly; the name up to case, spaces and
/// hyphens; a family that **extends** it by a word — "Inter" finds "Inter 24pt", which is
/// what Inter's static files call themselves. Among several extensions the ones in
/// `preferred` (the application's own faces) come first, then the shortest, so "DejaVu"
/// finds "DejaVu Sans" before "DejaVu Sans Mono".
///
/// It never guesses past that. A name that merely shares a first letter, or that the
/// loaded family only begins ("Inter Tight" asked, "Inter" loaded), is not a match: a
/// wrong face drawn silently is the failure this exists to end, not a new one.
fn match_family<'a>(
    requested: &str,
    loaded: &'a [String],
    preferred: &[String],
) -> Option<&'a str> {
    if let Some(exact) = loaded.iter().find(|family| *family == requested) {
        return Some(exact);
    }
    let wanted = squashed(requested);
    if let Some(same) = loaded.iter().find(|family| squashed(family) == wanted) {
        return Some(same);
    }
    let prefix = format!("{} ", requested.trim().to_lowercase());
    loaded
        .iter()
        .filter(|family| family.to_lowercase().starts_with(&prefix))
        .min_by_key(|family| (!preferred.contains(family), family.len()))
        .map(String::as_str)
}

/// The weights a face covers: one, or the range of its `wght` axis for a variable font,
/// which draws every weight in between.
fn weight_range(
    db: &cosmic_text::fontdb::Database,
    face: &cosmic_text::fontdb::FaceInfo,
) -> (u16, u16) {
    use cosmic_text::skrifa::MetadataProvider;
    let axis = db.with_face_data(face.id, |data, index| {
        let font = cosmic_text::skrifa::FontRef::from_index(data, index).ok()?;
        let axis = font
            .axes()
            .get_by_tag(cosmic_text::skrifa::Tag::new(b"wght"))?;
        Some((axis.min_value() as u16, axis.max_value() as u16))
    });
    match axis {
        Some(Some((low, high))) if low <= high => (low, high),
        _ => (face.weight.0, face.weight.0),
    }
}

/// What the font database holds, as far as naming a family goes. Every `FontSystem` frus
/// builds loads the same faces, so one inventory answers for all of them.
struct Loaded {
    /// Every family, as the files spell it.
    families: Vec<String>,
    /// The families that can draw text — every one but the emoji faces.
    text: Vec<String>,
    /// The application's own families, in registration order.
    app: Vec<String>,
    /// The families with an oblique or italic face.
    slanted: Vec<String>,
    /// Whether the generic sans-serif and monospace resolved to a face before frus
    /// pointed them anywhere: on a desktop they do, on Android nothing answers.
    generic_sans: bool,
    generic_mono: bool,
    /// What [`loaded_family`] answered, per name asked. An inventory is replaced whenever
    /// a face arrives, and its answers go with it.
    answers: Mutex<std::collections::HashMap<&'static str, Option<&'static str>>>,
}

impl Loaded {
    fn of(db: &cosmic_text::fontdb::Database) -> Self {
        use cosmic_text::fontdb::{Family, Query, Style};
        let mut families: Vec<String> = Vec::new();
        let mut text: Vec<String> = Vec::new();
        let mut slanted: Vec<String> = Vec::new();
        for face in db.faces() {
            let emoji = face.post_script_name.contains("Emoji");
            for (name, _) in &face.families {
                if !families.contains(name) {
                    families.push(name.clone());
                }
                if !emoji && !text.contains(name) {
                    text.push(name.clone());
                }
                if face.style != Style::Normal && !slanted.contains(name) {
                    slanted.push(name.clone());
                }
            }
        }
        let resolves = |family| {
            db.query(&Query {
                families: &[family],
                ..Query::default()
            })
            .is_some()
        };
        Loaded {
            families,
            text,
            app: APP_FAMILIES.lock().expect("font registry").clone(),
            slanted,
            generic_sans: resolves(Family::SansSerif),
            generic_mono: resolves(Family::Monospace),
            answers: Mutex::new(std::collections::HashMap::new()),
        }
    }

    /// What text is drawn in when the family asked for is not loaded: the application's
    /// first face, then the platform's sans (Roboto, on Android), then any face that draws
    /// text — never nothing while there is something.
    fn fallback(&self) -> Option<&str> {
        self.app
            .iter()
            .find(|family| self.text.contains(family))
            .or_else(|| self.text.iter().find(|family| *family == PLATFORM_SANS))
            .or_else(|| self.text.first())
            .map(String::as_str)
    }

    /// Whether default text has nothing good to be drawn in: the family asked for is not
    /// there, nor any face of the application's, nor a generic sans the platform answers
    /// for. Only Android gets here with a build that dropped `bundled-sans`, and it is
    /// the cue to take the platform's own sans from disk.
    #[cfg(any(target_os = "android", test))]
    fn wants_platform_sans(&self, requested: Option<&str>) -> bool {
        let named = requested.is_some_and(|name| {
            match_family(name, &self.families, &self.app)
                .is_some_and(|family| self.text.iter().any(|text| text == family))
        });
        let own = self.app.iter().any(|family| self.text.contains(family));
        !(named || own || (requested.is_none() && self.generic_sans))
    }
}

/// The weights the default family covers, as ranges — one weight for a static face, the
/// span of its `wght` axis for a variable one. Empty when the default family is the
/// platform's generic, which is not frus's to inventory.
static WEIGHTS: RwLock<Vec<(u16, u16)>> = RwLock::new(Vec::new());

/// The weight ranges `family`'s faces cover in `db`, upright faces first: an italic-only
/// family still has weights to offer.
fn weights_of(db: &cosmic_text::fontdb::Database, family: &str) -> Vec<(u16, u16)> {
    let faces: Vec<_> = db
        .faces()
        .filter(|face| face.families.iter().any(|(name, _)| name == family))
        .collect();
    let upright: Vec<_> = faces
        .iter()
        .filter(|face| face.style == cosmic_text::fontdb::Style::Normal)
        .collect();
    let chosen = if upright.is_empty() {
        faces.iter().collect()
    } else {
        upright
    };
    let mut ranges: Vec<(u16, u16)> = chosen.iter().map(|face| weight_range(db, face)).collect();
    ranges.sort_unstable();
    ranges.dedup();
    ranges
}

/// The weight to ask for when `wanted` is asked of a family covering `have`, by the rule
/// type on the web follows: an exact weight, or one inside a variable face's range, as it
/// is; for 400 to 500, the next heavier up to 500, then lighter, then heavier; below 400,
/// lighter first; above 500, heavier first. `have` empty answers `wanted`.
fn nearest_weight(wanted: u16, have: &[(u16, u16)]) -> u16 {
    if have
        .iter()
        .any(|&(low, high)| (low..=high).contains(&wanted))
    {
        return wanted;
    }
    // Outside every range, the candidates are the ranges' ends.
    let mut ends: Vec<u16> = have.iter().flat_map(|&(low, high)| [low, high]).collect();
    ends.sort_unstable();
    ends.dedup();
    let lighter = ends.iter().rev().find(|&&w| w < wanted).copied();
    let heavier = ends.iter().find(|&&w| w > wanted).copied();
    let pick = if (400..=500).contains(&wanted) {
        ends.iter()
            .find(|&&w| w > wanted && w <= 500)
            .copied()
            .or(lighter)
            .or(heavier)
    } else if wanted < 400 {
        lighter.or(heavier)
    } else {
        heavier.or(lighter)
    };
    pick.unwrap_or(wanted)
}

/// The family Android draws its own text in, and the one frus takes from the platform
/// when nothing else can draw.
const PLATFORM_SANS: &str = "Roboto";

/// The inventory of the last font database frus built. `None` until one is built — and
/// then nothing can be judged, and names are taken as written.
static LOADED: RwLock<Option<Loaded>> = RwLock::new(None);

/// Family names the inventory gave out. The slots hold `&'static str`, and a name read
/// from a font file is not one; each is leaked once, and only once.
static INTERNED: Mutex<Vec<&'static str>> = Mutex::new(Vec::new());

fn interned(name: &str) -> &'static str {
    let mut interned = INTERNED.lock().expect("family registry");
    if let Some(found) = interned.iter().find(|known| **known == name) {
        return found;
    }
    let leaked: &'static str = Box::leak(name.to_string().into_boxed_str());
    interned.push(leaked);
    leaked
}

/// What the console has already been told. A warning a frame would print sixty times a
/// second is noise; once is the message.
static WARNED: Mutex<Vec<String>> = Mutex::new(Vec::new());

fn warn_once(message: String) {
    let mut warned = WARNED.lock().expect("family registry");
    if !warned.contains(&message) {
        log::warn!("{message}");
        warned.push(message);
    }
}

/// Takes the inventory of `db` and points its generic families at faces that are there.
/// Run whenever the faces change: a family's weights, its italic and the names it answers
/// to are all read from it.
fn take_stock(db: &mut cosmic_text::fontdb::Database) {
    *LOADED.write().expect("family registry") = Some(Loaded::of(db));
    // Makes every generic family resolve to a font that is actually present — but
    // only when one is: pointing `sans-serif` at a family nobody loaded is worse than
    // leaving fontdb's own answer alone.
    let sans = default_family();
    if let Some(sans) = sans {
        db.set_sans_serif_family(sans);
        db.set_serif_family(sans);
        db.set_cursive_family(sans);
        db.set_fantasy_family(sans);
    }
    if let cosmic_text::Family::Name(mono) = monospace_family() {
        db.set_monospace_family(mono);
    }
    *WEIGHTS.write().expect("family registry") = match sans {
        Some(name) => weights_of(db, name),
        None => Vec::new(),
    };
    // What is *actually* there decides whether italic is asked for, since an
    // application may have supplied an oblique face of its own — or none.
    let italic = match LOADED.read().expect("family registry").as_ref() {
        Some(loaded) => match sans {
            Some(name) => loaded.slanted.iter().any(|family| family == name),
            None => !loaded.slanted.is_empty(),
        },
        None => false,
    };
    ITALIC.store(italic, Ordering::Relaxed);
}

/// The loaded family `name` means — itself when a face carries it, otherwise what
/// [`match_family`] finds, with a warning naming it — or `None` when nothing loaded
/// answers to it. Before any font database exists there is nothing to judge against, and
/// the name is taken as written.
fn loaded_family(name: &'static str) -> Option<&'static str> {
    let guard = LOADED.read().expect("family registry");
    let Some(loaded) = guard.as_ref() else {
        return Some(name);
    };
    let mut answers = loaded.answers.lock().expect("family registry");
    if let Some(answer) = answers.get(name) {
        return *answer;
    }
    let answer = match_family(name, &loaded.families, &loaded.app).map(interned);
    if let Some(actual) = answer {
        if actual != name {
            warn_once(format!(
                "frus: no font family is called \"{name}\"; drawing \"{actual}\", the name \
                 inside the font files. Write \"{actual}\" to say so."
            ));
        }
    }
    answers.insert(name, answer);
    answer
}

/// The family to draw in when `name`, asked for in the role `role`, is not loaded — with
/// a warning that says so and lists what the application did register.
fn fallback_for(role: &str, name: &str) -> Option<&'static str> {
    let guard = LOADED.read().expect("family registry");
    let loaded = guard.as_ref()?;
    let fallback = loaded.fallback().map(interned);
    let registered = if loaded.app.is_empty() {
        "add_font registered none".to_string()
    } else {
        format!("add_font registered {:?}", loaded.app)
    };
    let drawn = match fallback {
        Some(family) => format!("drawing \"{family}\" instead"),
        None => "and no other face can draw text".to_string(),
    };
    warn_once(format!(
        "frus: the {role} font family \"{name}\" is not loaded; {drawn}. The name must be \
         the one inside the font file ({registered})."
    ));
    fallback
}

/// The family default text is drawn in: the one the application named, as it is loaded;
/// failing that a face that can draw, never a name that resolves to nothing. `None` leaves
/// the generic sans-serif to the platform, which answers on a desktop.
fn default_family() -> Option<&'static str> {
    let requested = *SANS.read().expect("family registry");
    match requested {
        Some(name) => loaded_family(name).or_else(|| fallback_for("default", name)),
        None => {
            let generic = LOADED
                .read()
                .expect("family registry")
                .as_ref()
                .is_none_or(|loaded| loaded.generic_sans);
            if generic {
                None
            } else {
                LOADED
                    .read()
                    .expect("family registry")
                    .as_ref()
                    .and_then(Loaded::fallback)
                    .map(interned)
            }
        }
    }
}

/// The default sans-serif as a cosmic-text family.
fn sans_family() -> cosmic_text::Family<'static> {
    match default_family() {
        Some(name) => cosmic_text::Family::Name(name),
        None => cosmic_text::Family::SansSerif,
    }
}

/// `true` when `text` holds at least one character of the **Arabic** script
/// (the Arabic, Supplement, Extended-A and Presentation Forms A/B blocks).
fn contains_arabic(text: &str) -> bool {
    text.chars().any(|c| {
        matches!(c as u32,
            0x0600..=0x06FF | 0x0750..=0x077F | 0x08A0..=0x08FF | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF)
    })
}

/// The **font family** to use for `text`: the bundled Arabic face when the text
/// contains Arabic, otherwise the default sans-serif.
///
/// This is essential because cosmic-text does **not** fall back across families on
/// Android, where the platform fallback lists are empty: without an explicit
/// assignment an Arabic run would render nothing. So the family is chosen by script
/// at the source, and measurement **and** rendering share the rule.
pub fn family_for(text: &str) -> cosmic_text::Family<'static> {
    if contains_arabic(text) {
        // No Arabic face loaded: the sans is a better guess than a family name that
        // resolves to nothing, and on the desktop the system usually has one.
        let arabic = *ARABIC.read().expect("family registry");
        match arabic.and_then(loaded_family) {
            Some(name) => cosmic_text::Family::Name(name),
            None => sans_family(),
        }
    } else {
        sans_family()
    }
}

/// The family to draw `text` in when a style **named one**.
///
/// # Why a named family does not simply win
///
/// A run containing Arabic keeps the registered Arabic face, whatever was named. It is not
/// a hedge: cosmic-text does not fall back across families on Android, where the platform
/// fallback lists are empty, so a family without Arabic coverage renders **nothing at
/// all** — not a substituted glyph, not a box, nothing. Text in an unexpected face is a
/// smaller failure than a blank screen, and a caller who wants an Arabic family names it
/// and gets it.
///
/// The same reasoning covers a named family that is not loaded: it is matched to the
/// loaded family it plainly means, or drawn in the default family, and the console says
/// which — never a name that resolves to nothing.
///
/// Coverage is what would settle this properly — asking the face whether it has the
/// characters — and fontdb does not offer it cheaply. That is a limit, and it is written
/// down here rather than left for someone to discover on a device.
pub fn family_for_style(
    text: &str,
    family: Option<frus_core::FontFamily>,
) -> cosmic_text::Family<'static> {
    use frus_core::FontFamily;
    match family {
        // Nothing named: the existing rule, which already chooses by script.
        None => family_for(text),
        // Named, but the run needs the Arabic face to be drawn at all.
        Some(_) if contains_arabic(text) => family_for(text),
        Some(FontFamily::SansSerif) => sans_family(),
        Some(FontFamily::Serif) => cosmic_text::Family::Serif,
        Some(FontFamily::Monospace) => monospace_family(),
        Some(FontFamily::Named(name)) => match loaded_family(name) {
            Some(found) => cosmic_text::Family::Name(found),
            None => {
                fallback_for("named", name);
                sans_family()
            }
        },
    }
}

/// The monospaced family, for the widgets that ask for one. When neither the family
/// named nor the platform's generic monospace is there — Android without
/// `bundled-mono` — it is the default family: text in the wrong face, not none.
pub fn monospace_family() -> cosmic_text::Family<'static> {
    let requested = *MONO.read().expect("family registry");
    match requested {
        Some(name) => match loaded_family(name) {
            Some(found) => cosmic_text::Family::Name(found),
            None => {
                fallback_for("monospace", name);
                sans_family()
            }
        },
        None => {
            let generic = LOADED
                .read()
                .expect("family registry")
                .as_ref()
                .is_none_or(|loaded| loaded.generic_mono);
            if generic {
                cosmic_text::Family::Monospace
            } else {
                sans_family()
            }
        }
    }
}

/// The style **actually available** for the default family. Italic when an oblique
/// face is loaded, upright when none is — because cosmic-text demands an exact style
/// match, and asking for one that does not exist sends it to platform fallback lists
/// that are empty on Android. Turning off `bundled-italic` should cost you slanted
/// text, not text.
pub fn available_style(italic: bool) -> Style {
    if italic && ITALIC.load(Ordering::Relaxed) {
        Style::Italic
    } else {
        Style::Normal
    }
}

/// Where Android keeps its fonts.
#[cfg(target_os = "android")]
const ANDROID_FONT_DIR: &str = "/system/fonts";

/// Loads the font files of `dir` whose lower-cased name `keep` accepts. Returns how many
/// files were taken; a directory that is not there is a platform without one, and none.
#[cfg(any(target_os = "android", test))]
fn load_platform_faces(
    db: &mut cosmic_text::fontdb::Database,
    dir: &std::path::Path,
    keep: impl Fn(&str) -> bool,
) -> usize {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    let mut taken = 0;
    for path in entries.flatten().map(|entry| entry.path()) {
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .map(str::to_ascii_lowercase)
            .unwrap_or_default();
        let font = [".ttf", ".otf", ".ttc"]
            .iter()
            .any(|extension| name.ends_with(extension));
        if font && keep(&name) && db.load_font_file(&path).is_ok() {
            taken += 1;
        }
    }
    taken
}

/// Loads the **emoji** faces from a font directory — every font file whose name says
/// `emoji` — and nothing else from it. Returns how many files were taken.
///
/// Only the emoji faces, because that is the gap: the bundled faces answer for text, and
/// a platform's whole font directory is hundreds of files. They are taken from the
/// platform rather than bundled because colour emoji are the platform's own look and the
/// largest font on it. They then need no fallback list to be found: cosmic-text's last
/// pass tries every face whose name says `Emoji`, whatever the style asked for.
#[cfg(any(target_os = "android", test))]
fn load_emoji_faces(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
    load_platform_faces(db, dir, |name| name.contains("emoji"))
}

/// Loads the platform's own **sans** — Roboto's files, not its condensed cut — for when
/// nothing frus or the application loaded can draw text. Returns how many files were
/// taken.
///
/// It is the last resort, not the default: a build that dropped `bundled-sans` and
/// registered no face of its own used to draw no text at all on Android, and the platform
/// has a perfectly good face on disk.
#[cfg(any(target_os = "android", test))]
fn load_platform_sans(db: &mut cosmic_text::fontdb::Database, dir: &std::path::Path) -> usize {
    load_platform_faces(db, dir, |name| name.starts_with("roboto-"))
}

/// Builds a ready-to-use `FontSystem`: the system fonts, which provide the emoji
/// and script fallbacks, **plus** the bundled font, set as the default family. Use
/// it everywhere a `FontSystem` is created — measurement here, rendering in
/// `frus-gpu` — for consistent text rendering that does not depend on system fonts,
/// which may have no resolvable default at all, as on Android.
///
/// On Android "the system fonts" used to be **none**: fontdb reads no directory there,
/// and cosmic-text has no fallback list for the platform, so an emoji in a run was drawn
/// as an empty box (milestone 506). The platform's emoji faces are loaded explicitly —
/// and its sans too, when nothing else loaded can draw text (milestone 626).
pub fn new_font_system() -> FontSystem {
    let started = web_time::Instant::now();
    let font_system = build_font_system();
    if let Ok(mut loading) = FONT_LOADING.lock() {
        loading.0 += started.elapsed();
        loading.1 += 1;
    }
    font_system
}

/// How long building the font systems took, all together, and how many were built — one for
/// measuring text, one for drawing it: a part of an application's time to its first frame
/// (milestone 683, #211). The system's fonts are read for each.
pub fn font_loading() -> (std::time::Duration, u32) {
    FONT_LOADING
        .lock()
        .map(|loading| *loading)
        .unwrap_or_default()
}

static FONT_LOADING: Mutex<(std::time::Duration, u32)> = Mutex::new((std::time::Duration::ZERO, 0));

fn build_font_system() -> FontSystem {
    let mut font_system = FontSystem::new();
    let db = font_system.db_mut();
    #[cfg(target_os = "android")]
    load_emoji_faces(db, std::path::Path::new(ANDROID_FONT_DIR));
    #[cfg(feature = "bundled-sans")]
    {
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
    }
    #[cfg(feature = "bundled-italic")]
    {
        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
        db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
    }
    #[cfg(feature = "bundled-mono")]
    db.load_font_data(DEJAVU_MONO.to_vec());
    #[cfg(feature = "bundled-arabic")]
    {
        db.load_font_data(NOTO_ARABIC.to_vec());
        db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
    }
    // Whatever the application supplied itself, over the bundled faces.
    for face in EXTRA_FONTS.lock().expect("font registry").iter() {
        db.load_font_data(face.clone());
    }
    // Nothing loaded draws default text: the platform's own sans, rather than a blank
    // screen.
    #[cfg(target_os = "android")]
    {
        let requested = *SANS.read().expect("family registry");
        if Loaded::of(db).wants_platform_sans(requested)
            && load_platform_sans(db, std::path::Path::new(ANDROID_FONT_DIR)) > 0
        {
            log::info!(
                "frus: no bundled or registered face draws text; using the platform's Roboto"
            );
        }
    }
    take_stock(db);
    font_system
}

static FONT_SYSTEM: OnceLock<Mutex<FontSystem>> = OnceLock::new();

fn font_system() -> &'static Mutex<FontSystem> {
    FONT_SYSTEM.get_or_init(|| Mutex::new(new_font_system()))
}

/// Everything about a measurement that can change its answer. The weight and the
/// style are the **resolved** ones — what the database can actually serve — so a
/// Medium asked for on a family that only has Regular hits the same entry as the
/// Regular, which is the same shaping either way. Floats are keyed by their bits:
/// two sizes that are bit-identical measure identically, and no other pair needs to
/// share an entry.
#[derive(PartialEq, Eq, Hash)]
struct MeasureKey {
    text: String,
    size: u32,
    weight: u16,
    italic: bool,
    max_width: Option<u32>,
    /// The line height these words were measured at, in bits. A style may name one, so it
    /// is part of the question and not a constant.
    line_h: u32,
    /// The family they were measured in. Different faces have different widths, which is
    /// the reason for naming one at all.
    family: Option<frus_core::FontFamily>,
    /// The letter spacing, in bits: two spacings give two widths.
    letter_spacing: u32,
}

/// How many entries a generation holds before it is retired. Two generations live at
/// once, so this bounds the cache at roughly `2 × CAP` measurements — a few hundred
/// kilobytes, against the ~290 µs a twelve-row screen was spending per frame
/// re-measuring strings that had not changed (milestone 299).
const CACHE_CAP: usize = 2048;

/// A two-generation cache. A string still being drawn is found in `current` or
/// promoted out of `previous`, so it survives a rotation; a string that has gone —
/// last second's clock, yesterday's search box — falls out with the generation it
/// was in. That is the whole eviction policy, and it needs no timestamps.
#[derive(Default)]
struct MeasureCache {
    current: std::collections::HashMap<MeasureKey, Size>,
    previous: std::collections::HashMap<MeasureKey, Size>,
}

static MEASURE_CACHE: Mutex<Option<MeasureCache>> = Mutex::new(None);

/// Forgets every measurement. Called whenever what a face measures to can have
/// changed — a font registered, a family renamed — because an answer from before
/// that is simply wrong, not merely stale.
fn forget_measurements() {
    if let Ok(mut cache) = MEASURE_CACHE.lock() {
        *cache = None;
    }
}

/// The weight **actually available** in the default family closest to the one
/// requested. This is essential: cosmic-text demands an **exact** weight match on the
/// primary family, and a missing weight (Medium 500 on DejaVu) sends it off to the
/// platform fallback lists — which do not exist on Android ("no default font found", a
/// panic caught on the device). Routing every `Attrs` through here is what makes
/// rendering deterministic.
///
/// "Available" is read from the faces loaded, not assumed: the bundled sans has 400 and
/// 700, so Medium draws as Regular and SemiBold as Bold; an application that registers
/// Medium and SemiBold faces of its own gets them, and a variable face draws every weight
/// its axis spans (milestone 626). With the generic family in charge — nothing named, on
/// a desktop — the answer is the bundled sans's, 400 or 700.
pub fn available_weight(weight: FontWeight) -> u16 {
    let wanted = weight.to_u16();
    let have = WEIGHTS.read().expect("family registry");
    if have.is_empty() {
        return if wanted < 550 { 400 } else { 700 };
    }
    nearest_weight(wanted, &have)
}

/// What a baseline depends on: the size and the **resolved** weight and style. The
/// text does not enter into it — a baseline is a property of the font at a size, not of
/// what is written in it.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
struct BaselineKey {
    size: u32,
    weight: u16,
    italic: bool,
}

static BASELINES: std::sync::LazyLock<
    std::sync::Mutex<std::collections::HashMap<BaselineKey, f32>>,
> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new()));

/// `attrs` with **letter spacing**: `letter_spacing` logical pixels after every character,
/// which the shaper takes as a fraction of the size (milestone 623). Every place that shapes
/// text goes through this, so a measure and a paint space the same words alike.
pub fn spaced(attrs: Attrs<'static>, letter_spacing: f32, size_px: f32) -> Attrs<'static> {
    if letter_spacing == 0.0 || size_px <= 0.0 {
        attrs
    } else {
        attrs.letter_spacing(letter_spacing / size_px)
    }
}

/// The line height for a given font size, in pixels, **for a style that says nothing
/// about it**.
///
/// A style that *does* say something answers for itself:
/// [`ResolvedTextStyle::line_height`]. Prefer that wherever a style is in reach — this
/// form cannot honour a `height` it was never shown, and a caller holding a style and
/// calling this anyway is the same measure-and-paint disagreement in miniature.
pub fn line_height(size_px: f32) -> f32 {
    size_px * LINE_HEIGHT_FACTOR
}

/// The **alphabetic baseline** of a line of text at `size_px`: the distance from the
/// top of the line box down to the line the letters sit on.
///
/// It is the number two pieces of text need in order to agree on where "the same line"
/// is. Sizes and line heights differ, so aligning two runs by their tops or their
/// bottoms puts them at different heights; aligning them by this puts them where a
/// reader expects.
///
/// It is **shaped**, not derived from the size. The ascent belongs to the font the
/// fallback chain actually chose, and guessing it from the point size is wrong by a few
/// per cent per family — enough to see when two labels sit side by side, which is the
/// only situation this number is ever used in.
pub fn baseline(size_px: f32, weight: FontWeight, italic: bool) -> f32 {
    // The system is built before the key is resolved, for the reason `measure_wrapped`
    // gives: resolving reads state that building it sets.
    let _ = font_system();
    let key = BaselineKey {
        size: size_px.to_bits(),
        weight: available_weight(weight),
        italic: available_style(italic) == Style::Italic,
    };
    if let Some(cached) = BASELINES.lock().expect("baseline cache").get(&key) {
        return *cached;
    }

    let line_h = line_height(size_px);
    let mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(size_px, line_h);
    let mut buffer = Buffer::new(&mut font_system, metrics);
    // Two letters with an ascender and a descender, so the line is shaped at its full
    // height rather than at the height of whatever happens to be in it.
    let probe = "Hg";
    let attrs = Attrs::new()
        .family(family_for(probe))
        .weight(Weight(available_weight(weight)))
        .style(available_style(italic));
    buffer.set_text(probe, &attrs, Shaping::Advanced, None);
    buffer.shape_until_scroll(&mut font_system, false);
    // `line_y` is where the renderer puts the baseline, so taking it from the same
    // place is what keeps layout and paint talking about the same line.
    let baseline = buffer
        .layout_runs()
        .next()
        .map(|run| run.line_y)
        .unwrap_or(size_px);
    drop(font_system);
    BASELINES
        .lock()
        .expect("baseline cache")
        .insert(key, baseline);
    baseline
}

/// The first baseline of a sequence of styled runs: the **largest** of their
/// baselines, since they share a line and the tallest ascender sets where it sits.
pub fn baseline_of_runs(runs: &[TextRun]) -> Option<f32> {
    runs.iter()
        .map(|run| baseline(run.size, run.weight, run.italic))
        .fold(None, |acc: Option<f32>, b| {
            Some(acc.map_or(b, |a| a.max(b)))
        })
}

/// Measures a text's natural size (multiple lines allowed), in pixels, at regular
/// weight. See [`measure_styled`] for weight and italics.
pub fn measure(text: &str, size_px: f32) -> Size {
    measure_styled(text, size_px, FontWeight::Regular, false)
}

/// Measures `text` under a [`TextStyle`], **resolving whatever it left open** to the
/// framework's own defaults.
///
/// Every widget that measures a label wants this and used to spell it out as three
/// arguments. Three arguments is three chances to pass a size from one style and a weight
/// from another, which draws text the layout never measured.
pub fn measure_style(text: &str, style: TextStyle) -> Size {
    measure_resolved(text, &style.resolved())
}

/// Measures `text` under a style that has **already** been resolved — the same thing one
/// step further down, for the code that has done the resolving once and is measuring
/// several times against it.
pub fn measure_resolved(text: &str, style: &ResolvedTextStyle) -> Size {
    measure_wrapped_resolved(text, style, None)
}

/// The height a box needs to hold **one line** of `style` with `padding` of room around
/// it: `min`, unless the reader asked for type that does not fit in `min`.
///
/// It is the reference's rule for its own components — a default height is a *floor*, and
/// content taller than it wins — written once rather than as a `max` remembered at each of
/// the places that need it. A component whose height is a bare constant clips its own text
/// the moment somebody turns the system font size up, and says nothing about it.
pub fn line_box(min: f32, style: &ResolvedTextStyle, padding: f32) -> f32 {
    // Rounded **up**. The layout works in whole pixels, and a box that came out at 43 for
    // a line needing 43.2 clips it — by a fifth of a pixel, which is still a clip.
    min.max(fits(style.line_height() + padding))
}

/// Measures `text` under an already-resolved style, **wrapping** at `max_width`. The
/// resolved counterpart of [`measure_wrapped`], for a paragraph whose style has been
/// settled once and must be measured and painted at the same size.
pub fn measure_wrapped_resolved(
    text: &str,
    style: &ResolvedTextStyle,
    max_width: Option<f32>,
) -> Size {
    // Through `measure_at`, not `measure_wrapped`: the style may name a line height, and
    // going by the size alone would measure at one height what the renderer draws at
    // another.
    measure_at(text, style, max_width)
}

/// Measures a **styled** text's natural size; weight and italics count, since bold
/// is wider than regular and the layout has to know.
pub fn measure_styled(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Size {
    measure_wrapped(text, size_px, weight, italic, None)
}

/// Measures a styled text **under a width constraint**: beyond `max_width` the text
/// wraps and the height grows. `None` means unconstrained, giving the natural size.
/// This is the measurement wired into taffy's measure closure for paragraphs.
pub fn measure_wrapped(
    text: &str,
    size_px: f32,
    weight: FontWeight,
    italic: bool,
    max_width: Option<f32>,
) -> Size {
    let style = ResolvedTextStyle {
        weight,
        italic,
        ..ResolvedTextStyle::exact(size_px)
    };
    measure_at(text, &style, max_width)
}

/// The measurement itself, under a **whole resolved style**.
///
/// Every public form funnels here, and it takes the style rather than its parts because
/// a style may name a line height, a family and a letter spacing (milestone 623): two
/// callers each passing some of them is how a measure and a paint come to disagree about
/// where the second line starts, or how wide the first one is.
fn measure_at(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Size {
    let (size_px, weight, italic) = (style.size, style.weight, style.italic);
    let (line_h, family, letter_spacing) =
        (style.line_height(), style.family, style.letter_spacing);
    if text.is_empty() {
        // Whole, like every other measurement here: a line height is a fraction of a
        // size — 19.2 for a 16 px label — and an empty label reserving 19.2 is handed a
        // box of 19, which clips the caret and any text put there later.
        return Size::new(0.0, fits(line_h));
    }

    // The key records the **resolved** weight and style, and resolving reads state
    // that building the font system sets (`ITALIC`, from the faces actually loaded).
    // So the system is built first: otherwise the very first measurement would be
    // filed under what was true before it existed.
    let _ = font_system();

    // Shaping the same string again every frame was three quarters of what building a
    // frame cost (milestone 299). A hit here also skips the `FontSystem` lock, which
    // the renderer wants at the same time.
    let key = MeasureKey {
        text: text.to_string(),
        size: size_px.to_bits(),
        weight: available_weight(weight),
        italic: available_style(italic) == Style::Italic,
        max_width: max_width.map(f32::to_bits),
        // Two line heights give two different answers for the same words, so they cannot
        // share a cache entry. Nor can two families: that is the point of naming one.
        line_h: line_h.to_bits(),
        family,
        letter_spacing: letter_spacing.to_bits(),
    };
    if let Some(size) = cached_measurement(&key) {
        return size;
    }

    let mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(size_px, line_h);
    let mut buffer = Buffer::new(&mut font_system, metrics);
    // A constrained width (wrapping) or a free one; the height is always free.
    buffer.set_size(max_width, None);
    let attrs = spaced(
        Attrs::new()
            // The face the **renderer** will use, not the default: measuring in one family
            // and drawing in another reserves a width for letters of a different shape.
            .family(family_for_style(text, family))
            .weight(Weight(available_weight(weight)))
            .style(available_style(italic)),
        letter_spacing,
        size_px,
    );
    buffer.set_text(text, &attrs, Shaping::Advanced, None);
    buffer.shape_until_scroll(&mut font_system, false);

    let mut width = 0.0_f32;
    let mut lines = 0.0_f32;
    for run in buffer.layout_runs() {
        width = width.max(run.line_w);
        lines += 1.0;
    }

    // **Rounded up**, and this matters more than it looks. The layout engine rounds
    // the boxes it hands out to whole pixels, so a natural width of 146.4 becomes a
    // box of 146 — narrower than the text that asked for it. The text is then shaped
    // again at 146 when painting, wraps onto a second line, and overlaps whatever the
    // layout put below it on the strength of a one-line height. A ceiling here is what
    // keeps the measurement and the painting talking about the same box.
    //
    // Under a constraint the ceiling is clamped back to it: the text did fit that
    // width, and a box a fraction wider than allowed is a different bug.
    let width = match max_width {
        Some(max) => fits(width).min(max),
        None => fits(width),
    };
    // **And the height too**, which milestone 289 did not do: it fixed the width the
    // wrapping bug presented on and left the other axis fractional. A line height is
    // typically not whole — 14.4 for a 12 px line — so a two-line paragraph measured
    // itself at 28.8 and, at a top edge that rounded up, was handed 28. The same bug, the
    // same function, the axis nobody looked at (issue #54).
    let measured = Size::new(width, fits(lines.max(1.0) * line_h));
    remember_measurement(key, measured);
    measured
}

/// The cached answer for `key`, promoting it out of the retiring generation if that
/// is where it was found.
fn cached_measurement(key: &MeasureKey) -> Option<Size> {
    let mut guard = MEASURE_CACHE.lock().ok()?;
    let cache = guard.as_mut()?;
    if let Some(size) = cache.current.get(key) {
        return Some(*size);
    }
    let size = *cache.previous.get(key)?;
    // Still in use, so it moves forward rather than falling out with its generation.
    cache.current.insert(
        MeasureKey {
            text: key.text.clone(),
            ..*key
        },
        size,
    );
    Some(size)
}

fn remember_measurement(key: MeasureKey, size: Size) {
    let Ok(mut guard) = MEASURE_CACHE.lock() else {
        return;
    };
    let cache = guard.get_or_insert_with(MeasureCache::default);
    if cache.current.len() >= CACHE_CAP {
        cache.previous = std::mem::take(&mut cache.current);
    }
    cache.current.insert(key, size);
}

/// The **visual lines** a piece of text breaks into inside a box `max_width` wide, as
/// byte ranges into `text`.
///
/// The reference's `maxLines` and `overflow` both need this and neither can be answered by
/// a measurement: a height tells you how many lines there are, not *where they broke*, and
/// a cut has to fall on a break the shaper chose or the words move.
///
/// Ranges rather than strings, because the caller wants a **prefix** of the original: a
/// text handed to the renderer as separate lines is a paragraph per line, and rules that
/// span a paragraph — a justified block leaving its last line ragged — stop working.
///
/// Not cached. Only text that asked for a line limit gets here, and the shaping it does is
/// the same shaping the renderer does again; everything else goes through the cached
/// measurement.
pub fn line_spans(
    text: &str,
    size_px: f32,
    weight: FontWeight,
    italic: bool,
    max_width: Option<f32>,
    soft_wrap: bool,
) -> Vec<std::ops::Range<usize>> {
    let style = ResolvedTextStyle {
        weight,
        italic,
        ..ResolvedTextStyle::exact(size_px)
    };
    line_spans_resolved(text, &style, max_width, soft_wrap)
}

/// [`line_spans`] under a whole resolved style: its line height, its family and its letter
/// spacing break the lines as the renderer will (milestone 623).
pub fn line_spans_resolved(
    text: &str,
    style: &ResolvedTextStyle,
    max_width: Option<f32>,
    soft_wrap: bool,
) -> Vec<std::ops::Range<usize>> {
    let size_px = style.size;
    let mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(size_px, style.line_height());
    let mut buffer = Buffer::new(&mut font_system, metrics);
    if !soft_wrap {
        buffer.set_wrap(cosmic_text::Wrap::None);
    }
    buffer.set_size(max_width, None);
    let attrs = spaced(
        Attrs::new()
            .family(family_for_style(text, style.family))
            .weight(Weight(available_weight(style.weight)))
            .style(available_style(style.italic)),
        style.letter_spacing,
        size_px,
    );
    buffer.set_text(text, &attrs, Shaping::Advanced, None);
    buffer.shape_until_scroll(&mut font_system, false);

    // A buffer line per explicit newline; a layout run's glyph offsets are into its own
    // buffer line, so the starts of those lines are what turns them into offsets into the
    // whole.
    let mut line_start = Vec::new();
    let mut at = 0usize;
    for line in &buffer.lines {
        line_start.push(at);
        at += line.text().len() + 1;
    }

    let mut spans = Vec::new();
    for run in buffer.layout_runs() {
        let base = line_start.get(run.line_i).copied().unwrap_or(0);
        // The glyphs are in **visual** order, so a right-to-left line has its last byte
        // first: the span is the extent of the run, not its ends in order.
        let start = run.glyphs.iter().map(|g| g.start).min();
        let end = run.glyphs.iter().map(|g| g.end).max();
        match (start, end) {
            (Some(start), Some(end)) => spans.push(base + start..base + end),
            // A blank line between two paragraphs has no glyphs and is still a line.
            _ => spans.push(base..base),
        }
    }
    // An empty paragraph still occupies a line, and a caller counting them would
    // otherwise see none.
    if spans.is_empty() {
        spans.push(0..0);
    }
    spans
}

/// Measures a **rich text**'s natural size — resolved runs with mixed styles and
/// sizes: the longest line's width, and the shaped lines' real height.
pub fn measure_runs(runs: &[TextRun]) -> Size {
    measure_runs_wrapped(runs, None)
}

/// Measures a rich text **under a width constraint**: beyond `max_width` the runs
/// wrap. `None` means unconstrained.
pub fn measure_runs_wrapped(runs: &[TextRun], max_width: Option<f32>) -> Size {
    if runs.iter().all(|r| r.text.is_empty()) {
        return Size::new(0.0, 0.0);
    }
    let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);

    let mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(base, line_height(base));
    let mut buffer = Buffer::new(&mut font_system, metrics);
    buffer.set_size(max_width, None);
    let spans = runs.iter().map(|run| {
        (
            run.text.as_str(),
            spaced(
                Attrs::new()
                    .family(family_for(&run.text))
                    .weight(Weight(available_weight(run.weight)))
                    .style(available_style(run.italic))
                    .metrics(Metrics::new(run.size, line_height(run.size))),
                run.letter_spacing,
                run.size,
            ),
        )
    });
    buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
    buffer.shape_until_scroll(&mut font_system, false);

    let mut width = 0.0_f32;
    let mut height = 0.0_f32;
    for run in buffer.layout_runs() {
        width = width.max(run.line_w);
        height = height.max(run.line_top + run.line_height);
    }
    // Rounded up for the same reason as [`measure_wrapped`]: a box rounded down below
    // the width the text asked for makes the text wrap when it is painted, on a height
    // that says it did not.
    let width = match max_width {
        Some(max) => fits(width).min(max),
        None => fits(width),
    };
    // The height as well, for the reason above: a run's line height is a fraction of its
    // size and lands whole only by accident.
    Size::new(width, fits(height))
}

/// The byte offset at which a rich text runs past `max_lines` visual lines, and how many
/// lines it actually took — `None` when it fits.
///
/// The offset is into the **concatenation** of the runs' texts, which is what the shaper
/// was given and the only coordinate the runs and the lines share. Splitting the runs
/// there is the caller's job, and cheap once the number is known.
///
/// Rich text is cut here rather than in the widget because the cut has to land on a break
/// the shaper chose, and only the shaper knows where those are — the same reason
/// [`line_spans`] exists, one primitive along.
pub fn runs_cut_at(
    runs: &[TextRun],
    max_width: Option<f32>,
    soft_wrap: bool,
    max_lines: usize,
) -> Option<usize> {
    if runs.iter().all(|r| r.text.is_empty()) {
        return None;
    }
    let base = runs.iter().map(|r| r.size).fold(0.0_f32, f32::max);
    let mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(base, line_height(base));
    let mut buffer = Buffer::new(&mut font_system, metrics);
    if !soft_wrap {
        buffer.set_wrap(cosmic_text::Wrap::None);
    }
    buffer.set_size(max_width, None);
    let spans = runs.iter().map(|run| {
        (
            run.text.as_str(),
            spaced(
                Attrs::new()
                    .family(family_for(&run.text))
                    .weight(Weight(available_weight(run.weight)))
                    .style(available_style(run.italic))
                    .metrics(Metrics::new(run.size, line_height(run.size))),
                run.letter_spacing,
                run.size,
            ),
        )
    });
    buffer.set_rich_text(spans, &Attrs::new(), Shaping::Advanced, None);
    buffer.shape_until_scroll(&mut font_system, false);

    // A buffer line per explicit newline; the offsets a layout run carries are into its
    // own buffer line, so the starts of those lines are what turns them back into offsets
    // into the whole.
    let mut line_start = Vec::new();
    let mut at = 0usize;
    for line in &buffer.lines {
        line_start.push(at);
        at += line.text().len() + 1;
    }
    for (index, run) in buffer.layout_runs().enumerate() {
        if index < max_lines {
            continue;
        }
        let start = run.glyphs.iter().map(|g| g.start).min().unwrap_or(0);
        return Some(line_start.get(run.line_i).copied().unwrap_or(0) + start);
    }
    None
}

/// One shaped line of a [`TextLayout`]: the `x` offsets of every **character
/// boundary**, taken from the real glyphs, kerning and ligatures included.
struct LayoutLine {
    /// The line's first boundary, as a character index global to the text.
    start_char: usize,
    /// The `x` of every character boundary on the line (`chars + 1` entries).
    offsets: Vec<f32>,
    /// The line's top edge.
    top: f32,
    /// The line's height.
    height: f32,
}

/// A text's **shaped** layout — a single cosmic-text pass — exposing the geometry an
/// editing widget needs: caret position by character index, reverse hit-testing, and
/// selection rectangles. Coordinates are **local** to the text, with the origin at
/// its top-left corner. Indices are in **characters** — frus's editing convention —
/// with boundaries `0..=len`.
///
/// Unlike a prefix measurement re-shaped substring by substring, the offsets come
/// from the **whole** shaped line: consistent with one another (kerning), and
/// computed in one pass instead of `n`.
pub struct TextLayout {
    lines: Vec<LayoutLine>,
    size: Size,
    /// The total character count — the last valid boundary.
    chars: usize,
}

impl TextLayout {
    /// Shapes `text` (multiple lines allowed, width unconstrained) in the given style
    /// and extracts its geometry.
    pub fn new(text: &str, size_px: f32, weight: FontWeight, italic: bool) -> Self {
        Self::wrapped(text, size_px, weight, italic, None)
    }

    /// Like [`TextLayout::new`], but **wraps** the text at `max_width` — a soft wrap,
    /// as in a multi-line field. `None` is unconstrained, where only `\n` breaks.
    ///
    /// Every **visual line** (one cosmic-text `LayoutRun`) is delimited by **its
    /// glyphs' bytes**, not by `run.text` — which is the whole *hard* line, repeated
    /// for each wrap. A soft wrap therefore fabricates no phantom character, and each
    /// line's `start_char` comes from its hard line's byte offset — exact indexing
    /// straight through the wraps.
    pub fn wrapped(
        text: &str,
        size_px: f32,
        weight: FontWeight,
        italic: bool,
        max_width: Option<f32>,
    ) -> Self {
        Self::shaped(
            text,
            size_px,
            weight,
            italic,
            max_width,
            line_height(size_px),
            None,
            0.0,
        )
    }

    /// Like [`TextLayout::wrapped`], under a style that has **already been resolved**: its
    /// line height and its face, which `wrapped` knows nothing of.
    ///
    /// For text that is drawn from a [`ResolvedTextStyle`] and must be *hit* where it is
    /// drawn — a selectable paragraph. A layout at the default leading over a paragraph
    /// painted at another puts every line after the first somewhere else, and a tap lands
    /// on the wrong word.
    pub fn resolved(text: &str, style: &ResolvedTextStyle, max_width: Option<f32>) -> Self {
        Self::shaped(
            text,
            style.size,
            style.weight,
            style.italic,
            max_width,
            style.line_height(),
            style.family,
            style.letter_spacing,
        )
    }

    // A text's whole shaping, argument by argument; grouping them would only move them.
    #[allow(clippy::too_many_arguments)]
    fn shaped(
        text: &str,
        size_px: f32,
        weight: FontWeight,
        italic: bool,
        max_width: Option<f32>,
        fallback_h: f32,
        family: Option<frus_core::FontFamily>,
        letter_spacing: f32,
    ) -> Self {
        let mut lines: Vec<LayoutLine> = Vec::new();
        let mut width = 0.0_f32;
        let mut height = 0.0_f32;

        if !text.is_empty() {
            // The byte offset of every **hard** line's start (those split by `\n`).
            let hard: Vec<&str> = text.split('\n').collect();
            let mut line_byte_start = Vec::with_capacity(hard.len());
            {
                let mut b = 0usize;
                for l in &hard {
                    line_byte_start.push(b);
                    b += l.len() + 1; // +1 for the `\n`
                }
            }

            let mut font_system = font_system().lock().expect("FontSystem lock");
            let metrics = Metrics::new(size_px, fallback_h);
            let mut buffer = Buffer::new(&mut font_system, metrics);
            buffer.set_size(max_width, None);
            let attrs = spaced(
                Attrs::new()
                    .family(family_for_style(text, family))
                    .weight(Weight(available_weight(weight)))
                    .style(available_style(italic)),
                letter_spacing,
                size_px,
            );
            buffer.set_text(text, &attrs, Shaping::Advanced, None);
            buffer.shape_until_scroll(&mut font_system, false);

            // Collect the runs so we can look at the next one, which ends this segment.
            let runs: Vec<_> = buffer.layout_runs().collect();
            for (idx, run) in runs.iter().enumerate() {
                let line_text = hard[run.line_i];
                let first_of_line = idx == 0 || runs[idx - 1].line_i != run.line_i;
                // The segment [lo, hi) of the hard line, in bytes, that this visual line
                // carries: from its first glyph (0 if it is the first visual line) to the
                // first glyph of the next visual line of the same hard line, or the end
                // otherwise — which takes in the break space, absent from the glyphs.
                let lo = if first_of_line {
                    0
                } else {
                    run.glyphs.iter().map(|g| g.start).min().unwrap_or(0)
                };
                let hi = runs
                    .get(idx + 1)
                    .filter(|r| r.line_i == run.line_i)
                    .and_then(|r| r.glyphs.iter().map(|g| g.start).min())
                    .unwrap_or(line_text.len());

                // The segment's character boundaries, in bytes relative to the hard line.
                let span = &line_text[lo..hi];
                let char_bytes: Vec<usize> = span.char_indices().map(|(b, _)| lo + b).collect();
                let n = char_bytes.len();
                let mut offsets = vec![f32::NAN; n + 1];
                offsets[0] = 0.0;

                // Each glyph covers a byte cluster [start, end) over [x, x+w), where x is
                // **local to the visual line**; interior boundaries are interpolated.
                for glyph in run.glyphs.iter() {
                    let covered: Vec<usize> = (0..n)
                        .filter(|&i| char_bytes[i] >= glyph.start && char_bytes[i] < glyph.end)
                        .collect();
                    let k = covered.len().max(1) as f32;
                    for (j, &i) in covered.iter().enumerate() {
                        offsets[i] = glyph.x + glyph.w * (j as f32 / k);
                    }
                    if let Some(next) = (0..=n).find(|&i| {
                        let b = if i == n {
                            lo + span.len()
                        } else {
                            char_bytes[i]
                        };
                        b == glyph.end
                    }) {
                        offsets[next] = glyph.x + glyph.w;
                    }
                }
                // Boundaries left without a glyph (the break space) keep continuity.
                for i in 1..=n {
                    if offsets[i].is_nan() {
                        offsets[i] = offsets[i - 1];
                    }
                }

                let start_char = text[..line_byte_start[run.line_i] + lo].chars().count();
                width = width.max(run.line_w);
                height = height.max(run.line_top + run.line_height);
                lines.push(LayoutLine {
                    start_char,
                    offsets,
                    top: run.line_top,
                    height: run.line_height,
                });
            }
        }

        // Empty text, or no shaped line: a synthetic empty line keeps caret and hit
        // defined, with the caret at x = 0.
        if lines.is_empty() {
            lines.push(LayoutLine {
                start_char: 0,
                offsets: vec![0.0],
                top: 0.0,
                height: fallback_h,
            });
            height = fallback_h;
        }

        let chars = text.chars().count();
        Self {
            lines,
            size: Size::new(width, height),
            chars,
        }
    }

    /// The shaped text's natural size.
    pub fn size(&self) -> Size {
        self.size
    }

    /// The line containing the character boundary `index`.
    fn line_of(&self, index: usize) -> &LayoutLine {
        self.lines
            .iter()
            .rev()
            .find(|line| index >= line.start_char)
            .unwrap_or(&self.lines[0])
    }

    /// The caret's rectangle at boundary `index`, of zero width — it is up to the
    /// widget to choose the stroke thickness. `index` is clamped to the text.
    pub fn caret_rect(&self, index: usize) -> Rect {
        let index = index.min(self.chars);
        let line = self.line_of(index);
        let local = (index - line.start_char).min(line.offsets.len() - 1);
        Rect::new(line.offsets[local], line.top, 0.0, line.height)
    }

    /// The character boundary **closest** to `point`, in text-local coordinates. The
    /// `y` picks the line (clamped), the `x` picks the boundary.
    pub fn hit_test(&self, point: Point) -> usize {
        let line = self
            .lines
            .iter()
            .find(|line| point.y < line.top + line.height)
            .unwrap_or(self.lines.last().expect("at least one line"));

        let mut best = 0;
        let mut best_dist = f32::MAX;
        for (i, x) in line.offsets.iter().enumerate() {
            let dist = (x - point.x).abs();
            if dist < best_dist {
                best_dist = dist;
                best = i;
            }
        }
        (line.start_char + best).min(self.chars)
    }

    /// The rectangles covering the character range `[start, end)`, one per line
    /// crossed; empty ones are omitted.
    pub fn selection_rects(&self, start: usize, end: usize) -> Vec<Rect> {
        let (start, end) = (start.min(self.chars), end.min(self.chars));
        if start >= end {
            return Vec::new();
        }
        let mut rects = Vec::new();
        for line in &self.lines {
            let line_len = line.offsets.len() - 1;
            let lo = start.max(line.start_char);
            let hi = end.min(line.start_char + line_len);
            if lo >= hi {
                continue;
            }
            let x0 = line.offsets[lo - line.start_char];
            let x1 = line.offsets[hi - line.start_char];
            if x1 > x0 {
                rects.push(Rect::new(x0, line.top, x1 - x0, line.height));
            }
        }
        rects
    }
}

#[cfg(test)]
mod tests {

    /// **Letter spacing widens a word by its spacing, once per character** (milestone 623):
    /// a word of eight letters spaced 2 px is about 16 px wider, and not the same width as
    /// the unspaced word cached a moment before — the spacing is part of the question.
    /// Negative spacing draws the letters closer.
    #[test]
    fn letter_spacing_widens_a_word_by_its_spacing() {
        let word = "Spacious";
        let plain = ResolvedTextStyle::exact(16.0);
        let spaced = ResolvedTextStyle {
            letter_spacing: 2.0,
            ..plain
        };
        let tight = ResolvedTextStyle {
            letter_spacing: -0.5,
            ..plain
        };
        let w0 = measure_resolved(word, &plain).width;
        let w2 = measure_resolved(word, &spaced).width;
        let wt = measure_resolved(word, &tight).width;
        let added = w2 - w0;
        assert!(
            (added - 16.0).abs() <= 2.5,
            "eight letters, two pixels each: {added} added"
        );
        assert!(wt < w0, "negative spacing tightens: {wt} vs {w0}");
        // And the layout that places the caret agrees with the measurement.
        let layout = TextLayout::resolved(word, &spaced, None);
        let laid = layout.size().width;
        assert!((laid - w2).abs() <= 1.0, "{laid} vs {w2}");
        // The caret after the last letter is past the spaced word, not the plain one.
        let end = layout.caret_rect(word.chars().count()).x;
        assert!(end > w0 + 8.0, "the caret ends past the spacing: {end}");
    }

    /// **Spacing moves the line breaks**: words that fit a box unspaced need a second line
    /// spaced, and the lines are cut where the renderer will cut them.
    #[test]
    fn letter_spacing_moves_the_line_breaks() {
        let text = "one two three";
        let plain = ResolvedTextStyle::exact(14.0);
        let width = measure_resolved(text, &plain).width + 2.0;
        assert_eq!(
            line_spans_resolved(text, &plain, Some(width), true).len(),
            1
        );
        let spaced = ResolvedTextStyle {
            letter_spacing: 3.0,
            ..plain
        };
        assert!(line_spans_resolved(text, &spaced, Some(width), true).len() >= 2);
    }

    /// **A layout under a resolved style has that style's leading**: the second line of a
    /// paragraph set at twice the line height is twice as far down, and the same paragraph
    /// laid out by [`TextLayout::wrapped`] — which knows the default alone — puts it where the
    /// default does. A selection hit-tested against the wrong one lands on the wrong line.
    #[test]
    fn a_resolved_layout_takes_the_styles_leading() {
        let text = "one two three four five six seven eight";
        let open = ResolvedTextStyle {
            height: Some(2.0),
            ..ResolvedTextStyle::exact(16.0)
        };
        let styled = TextLayout::resolved(text, &open, Some(90.0));
        let plain = TextLayout::wrapped(text, 16.0, FontWeight::Regular, false, Some(90.0));
        let spans = line_spans(text, 16.0, FontWeight::Regular, false, Some(90.0), true);
        assert!(spans.len() >= 3, "the fixture wraps: {spans:?}");
        let second = spans[1].start;
        assert_eq!(styled.caret_rect(second).y, 32.0, "two lines of 32 px");
        assert_eq!(plain.caret_rect(second).y, line_height(16.0));
        assert!(styled.size().height > plain.size().height * 1.5);
        // The same style with nothing named is the layout `wrapped` gives.
        let closed = TextLayout::resolved(text, &ResolvedTextStyle::exact(16.0), Some(90.0));
        assert_eq!(closed.caret_rect(second), plain.caret_rect(second));
        assert_eq!(closed.size(), plain.size());
    }

    /// The spans come back **as the shaper broke them**: each one fits the box, and the
    /// words they cover are the words that were written, in order. That is what makes it
    /// safe to keep a prefix of the text and drop the rest.
    #[test]
    fn line_spans_break_where_the_shaper_breaks() {
        let text = "one two three four five six seven eight";
        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
        assert!(spans.len() > 1, "it wrapped: {spans:?}");
        let words: Vec<&str> = spans
            .iter()
            .flat_map(|s| text[s.clone()].split_whitespace())
            .collect();
        assert_eq!(words, text.split_whitespace().collect::<Vec<_>>());
        for span in &spans {
            let w = measure_styled(&text[span.clone()], 14.0, FontWeight::Regular, false).width;
            assert!(
                w <= 80.5,
                "each line fits: {:?} at {w}",
                &text[span.clone()]
            );
        }
    }

    /// The spans are **in order and do not overlap**, which is what lets a caller cut at
    /// the start of the first line it is dropping.
    #[test]
    fn the_spans_run_forwards() {
        let text = "one two three four five six seven eight";
        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(80.0), true);
        for pair in spans.windows(2) {
            assert!(pair[0].end <= pair[1].start, "{pair:?}");
        }
    }

    /// Without wrapping there is one line however narrow the box: nothing may push a
    /// word onto the next one, so the line runs past the edge instead.
    #[test]
    fn without_wrapping_there_is_one_line() {
        let text = "one two three four five six seven eight";
        let spans = line_spans(text, 14.0, FontWeight::Regular, false, Some(40.0), false);
        assert_eq!(spans.len(), 1);
        assert_eq!(&text[spans[0].clone()], text);
    }
    use super::*;

    #[test]
    fn empty_text_has_zero_width() {
        let size = measure("", 16.0);
        assert_eq!(size.width, 0.0);
        assert!(size.height > 0.0);
    }

    #[test]
    fn non_empty_text_has_positive_size() {
        let size = measure("Bonjour", 24.0);
        assert!(size.width > 0.0, "width = {}", size.width);
        assert!(size.height > 0.0, "height = {}", size.height);
    }

    #[test]
    fn rich_runs_measure_mixed_styles() {
        use frus_core::Color;
        let run = |text: &str, size: f32, weight: FontWeight| TextRun {
            text: text.to_string(),
            size,
            weight,
            italic: false,
            color: Color::WHITE,
            decoration: frus_core::TextDecoration::NONE,
            decoration_color: None,
            letter_spacing: 0.0,
        };
        // "normal BOLD" is wider than "normal" alone; the height comes from the
        // largest run.
        let plain = measure_runs(&[run("normal", 16.0, FontWeight::Regular)]);
        let mixed = measure_runs(&[
            run("normal", 16.0, FontWeight::Regular),
            run(" BOLD", 24.0, FontWeight::Bold),
        ]);
        assert!(mixed.width > plain.width);
        assert!(
            mixed.height >= line_height(24.0) - 1.0,
            "height driven by the 24px run: {}",
            mixed.height
        );
        // Empty gives a zero size.
        assert_eq!(measure_runs(&[]), Size::new(0.0, 0.0));
    }

    #[test]
    fn wrapped_text_grows_taller_within_the_width() {
        let text = "a text that is long enough to wrap onto several lines";
        let free = measure_wrapped(text, 16.0, FontWeight::Regular, false, None);
        let narrow = measure_wrapped(text, 16.0, FontWeight::Regular, false, Some(120.0));
        assert!(
            narrow.width <= 120.0,
            "wrapped within the width: {}",
            narrow.width
        );
        assert!(narrow.height > free.height, "wrapping grows the height");
    }

    #[test]
    fn layout_offsets_are_monotonic_and_match_size() {
        let layout = TextLayout::new("Bonjour le monde", 18.0, FontWeight::Regular, false);
        let mut prev = -1.0;
        for i in 0..=16 {
            let x = layout.caret_rect(i).x;
            assert!(x >= prev, "offset decreasing at boundary {i}");
            prev = x;
        }
        // The last boundary reaches the natural width.
        assert!((layout.caret_rect(16).x - layout.size().width).abs() < 0.5);
        // A boundary past the end of the text is clamped.
        assert_eq!(layout.caret_rect(99).x, layout.caret_rect(16).x);
    }

    #[test]
    fn hit_test_roundtrips_caret_positions() {
        let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
        for i in 0..=7 {
            let caret = layout.caret_rect(i);
            let hit = layout.hit_test(Point::new(caret.x, caret.y + 1.0));
            assert_eq!(hit, i, "caret->hit round trip at boundary {i}");
        }
        // Far to the left or right: the bounds.
        assert_eq!(layout.hit_test(Point::new(-100.0, 0.0)), 0);
        assert_eq!(layout.hit_test(Point::new(10_000.0, 0.0)), 7);
    }

    #[test]
    fn selection_rects_cover_the_range() {
        let layout = TextLayout::new("Bonjour", 18.0, FontWeight::Regular, false);
        let rects = layout.selection_rects(2, 5);
        assert_eq!(rects.len(), 1);
        let r = rects[0];
        assert!((r.x - layout.caret_rect(2).x).abs() < 0.01);
        assert!((r.x + r.width - layout.caret_rect(5).x).abs() < 0.01);
        assert!(r.height > 0.0);
        // An empty or inverted range gives no rectangle.
        assert!(layout.selection_rects(3, 3).is_empty());
        assert!(layout.selection_rects(5, 2).is_empty());
    }

    #[test]
    fn multiline_layout_maps_lines_and_indices() {
        // "ab\ncd": boundaries 0..=2 on line 1, 3..=5 on line 2.
        let layout = TextLayout::new("ab\ncd", 18.0, FontWeight::Regular, false);
        let first = layout.caret_rect(0);
        let second = layout.caret_rect(3);
        assert!(second.y > first.y, "the 2nd line sits lower");
        assert_eq!(second.x, 0.0, "second line starts at x = 0");
        // A hit on the second line gives second-line indices.
        let hit = layout.hit_test(Point::new(0.0, second.y + 1.0));
        assert_eq!(hit, 3);
    }

    #[test]
    fn soft_wrap_indexes_chars_correctly_across_lines() {
        // A soft wrap with no `\n`: each word on its own visual line. Indexing must
        // stay exact — an index's caret lands on the right line, and the line starts
        // are contiguous, with no phantom character at the break.
        let text = "aaaa bbbb cccc dddd"; // 19 characters, one word per line at 60px
        let layout = TextLayout::wrapped(text, 18.0, FontWeight::Regular, false, Some(60.0));
        assert!(
            layout.size().height > line_height(18.0) * 2.0,
            "several visual lines"
        );

        // Each word's start: "aaaa"@0, "bbbb"@5, "cccc"@10, "dddd"@15 — each at x
        // about 0, the start of its line, on lines of increasing y.
        let mut prev_y = -1.0;
        for &start in &[0usize, 5, 10, 15] {
            let c = layout.caret_rect(start);
            assert!(c.x < 1.0, "word start {start} at x about 0 (x={})", c.x);
            assert!(c.y > prev_y, "lines of increasing y at {start}");
            prev_y = c.y;
        }
        // A point in the **middle** of a wrapped line round-trips (index 11 is the
        // second 'c' of "cccc", clearly not a break boundary).
        let c = layout.caret_rect(11);
        assert_eq!(layout.hit_test(Point::new(c.x, c.y + 1.0)), 11);
        // The last boundary is 19: the three wraps inject no stray +1.
        assert_eq!(layout.caret_rect(19).x, layout.caret_rect(99).x);
        assert_eq!(layout.caret_rect(19).y, layout.caret_rect(99).y);
    }

    #[test]
    fn empty_layout_keeps_caret_at_origin() {
        let layout = TextLayout::new("", 18.0, FontWeight::Regular, false);
        let caret = layout.caret_rect(0);
        assert_eq!(caret.x, 0.0);
        assert!(caret.height > 0.0, "wrapped line height");
        assert_eq!(layout.hit_test(Point::new(50.0, 0.0)), 0);
    }

    /// Reproduces the Android worst case, caught on the device: **no** usable system
    /// font at all, only the bundled faces. Shaping must never panic ("no default
    /// font found") for **any** weight × italic combination the API can reach.
    /// cosmic-text demands an *exact* style and weight match on the primary family:
    /// without a bundled oblique face, `.italic()` panicked on the device.
    #[test]
    #[cfg(all(
        feature = "bundled-sans",
        feature = "bundled-italic",
        feature = "bundled-mono"
    ))]
    fn embedded_only_font_system_shapes_every_style() {
        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
        db.load_font_data(DEJAVU_SANS_BOLD_OBLIQUE.to_vec());
        db.load_font_data(DEJAVU_MONO.to_vec());
        db.set_sans_serif_family(SANS_FAMILY);
        db.set_serif_family(SANS_FAMILY);
        db.set_cursive_family(SANS_FAMILY);
        db.set_fantasy_family(SANS_FAMILY);
        db.set_monospace_family(MONO_FAMILY);
        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);

        for weight in [
            FontWeight::Regular,
            FontWeight::Medium,
            FontWeight::SemiBold,
            FontWeight::Bold,
        ] {
            for italic in [false, true] {
                let attrs = Attrs::new()
                    .weight(Weight(available_weight(weight)))
                    .style(if italic { Style::Italic } else { Style::Normal });
                let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
                buffer.set_size(None, None);
                buffer.set_text("Nothing to show", &attrs, Shaping::Advanced, None);
                buffer.shape_until_scroll(&mut fs, false); // panics here if broken
                let w: f32 = buffer.layout_runs().map(|r| r.line_w).fold(0.0, f32::max);
                assert!(w > 0.0, "weight {weight:?} italic {italic}: nothing shaped");
            }
        }
    }

    /// A scratch font directory, removed when dropped.
    struct FontDir(std::path::PathBuf);

    impl FontDir {
        fn new(tag: &str) -> Self {
            let dir = std::env::temp_dir().join(format!("frus-fonts-{tag}-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).expect("a scratch font directory");
            Self(dir)
        }

        fn put(&self, name: &str, bytes: &[u8]) {
            std::fs::write(self.0.join(name), bytes).expect("a scratch font file");
        }
    }

    impl Drop for FontDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// **Only the emoji faces are taken from the platform's font directory** (milestone
    /// 506): a font file named for emoji, and nothing else — not the platform's text
    /// faces, which the bundled ones answer for, and not a file that is not a font.
    ///
    /// Every file here holds a perfectly good face, so a filter that let one through would
    /// show as a second face in the database.
    #[test]
    #[cfg(feature = "bundled-sans")]
    fn only_the_emoji_faces_are_taken_from_a_font_directory() {
        let dir = FontDir::new("filter");
        dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
        dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
        dir.put("emoji-notes.txt", DEJAVU_SANS);
        let mut db = cosmic_text::fontdb::Database::new();
        assert_eq!(load_emoji_faces(&mut db, &dir.0), 1, "one file taken");
        assert_eq!(db.faces().count(), 1, "and one face in the database");
        // A directory that is not there is a platform without one, not an error.
        assert_eq!(load_emoji_faces(&mut db, &dir.0.join("absent")), 0);
    }

    /// **The platform's sans is Roboto's own files** (milestone 626): not its condensed
    /// cut, not the emoji face, not a file that is not a font.
    #[test]
    #[cfg(feature = "bundled-sans")]
    fn the_platform_sans_is_robotos_files_and_nothing_else() {
        let dir = FontDir::new("platform-sans");
        dir.put("Roboto-Regular.ttf", DEJAVU_SANS);
        dir.put("Roboto-Bold.ttf", DEJAVU_SANS_BOLD);
        dir.put("RobotoCondensed-Regular.ttf", DEJAVU_SANS);
        dir.put("NotoColorEmoji.ttf", DEJAVU_SANS);
        dir.put("roboto-notes.txt", DEJAVU_SANS);
        let mut db = cosmic_text::fontdb::Database::new();
        assert_eq!(load_platform_sans(&mut db, &dir.0), 2, "two files taken");
        assert_eq!(db.faces().count(), 2);
        assert_eq!(load_platform_sans(&mut db, &dir.0.join("absent")), 0);
    }

    /// **A family is asked for by the name a person writes, and found by the one in the
    /// file** (milestone 626). The case that started it: an application registered Inter's
    /// static files, named "Inter", and drew nothing on Android — the files say
    /// "Inter 24pt".
    #[test]
    fn a_family_name_finds_the_one_inside_the_file() {
        let loaded: Vec<String> = ["DejaVu Sans", "DejaVu Sans Mono", "Inter 24pt", "Open Sans"]
            .map(String::from)
            .to_vec();
        let none: Vec<String> = Vec::new();
        // Exactly, first.
        assert_eq!(
            match_family("DejaVu Sans", &loaded, &none),
            Some("DejaVu Sans")
        );
        // Up to case, spaces and hyphens.
        assert_eq!(match_family("open-sans", &loaded, &none), Some("Open Sans"));
        assert_eq!(match_family("OPENSANS", &loaded, &none), Some("Open Sans"));
        // Extended by a word: the file's own name.
        assert_eq!(match_family("Inter", &loaded, &none), Some("Inter 24pt"));
        assert_eq!(match_family("inter", &loaded, &none), Some("Inter 24pt"));
        // Several extensions: the shortest, unless the application's own come first.
        assert_eq!(match_family("DejaVu", &loaded, &none), Some("DejaVu Sans"));
        let mono = vec!["DejaVu Sans Mono".to_string()];
        assert_eq!(
            match_family("DejaVu", &loaded, &mono),
            Some("DejaVu Sans Mono")
        );
        // And no further: a name the loaded family only begins, a part of a word, nothing.
        assert_eq!(match_family("Inter Tight", &loaded, &none), None);
        assert_eq!(match_family("Int", &loaded, &none), None);
        assert_eq!(match_family("Roboto", &loaded, &none), None);
    }

    /// **The weight drawn is the nearest one loaded, by the web's rule** (milestone 626).
    #[test]
    fn a_weight_snaps_to_the_nearest_loaded_by_the_webs_rule() {
        let bundled = [(400, 400), (700, 700)];
        // The bundled sans: the old 400-or-700 answers, unchanged.
        assert_eq!(nearest_weight(400, &bundled), 400);
        assert_eq!(nearest_weight(500, &bundled), 400);
        assert_eq!(nearest_weight(600, &bundled), 700);
        assert_eq!(nearest_weight(300, &bundled), 400);
        assert_eq!(nearest_weight(900, &bundled), 700);
        // An application's four static faces are all used.
        let four = [(400, 400), (500, 500), (600, 600), (700, 700)];
        for weight in [400, 500, 600, 700] {
            assert_eq!(nearest_weight(weight, &four), weight);
        }
        // 400 to 500 look heavier up to 500 first, then lighter.
        assert_eq!(nearest_weight(400, &[(300, 300), (500, 500)]), 500);
        assert_eq!(nearest_weight(450, &[(300, 300), (600, 600)]), 300);
        // Below 400 lighter first; above 500 heavier first.
        assert_eq!(nearest_weight(350, &[(300, 300), (400, 400)]), 300);
        assert_eq!(nearest_weight(550, &[(500, 500), (600, 600)]), 600);
        // A variable face draws every weight its axis spans, and its ends outside it.
        assert_eq!(nearest_weight(650, &[(100, 900)]), 650);
        assert_eq!(nearest_weight(950, &[(100, 900)]), 900);
        // Nothing known: the weight as asked.
        assert_eq!(nearest_weight(500, &[]), 500);
    }

    /// **The inventory reads what a database holds** — and says when default text would
    /// have nothing to be drawn in, the cue Android takes to load its own sans.
    #[test]
    #[cfg(all(feature = "bundled-sans", feature = "bundled-italic"))]
    fn the_inventory_reads_the_faces_loaded() {
        assert_eq!(families_in(DEJAVU_SANS), vec!["DejaVu Sans".to_string()]);
        assert!(families_in(b"not a font").is_empty());

        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_data(DEJAVU_SANS_BOLD.to_vec());
        db.load_font_data(DEJAVU_SANS_OBLIQUE.to_vec());
        let mut loaded = Loaded::of(&db);
        loaded.app.clear();
        assert_eq!(loaded.text, vec!["DejaVu Sans".to_string()]);
        assert_eq!(loaded.slanted, vec!["DejaVu Sans".to_string()]);
        assert_eq!(weights_of(&db, "DejaVu Sans"), vec![(400, 400), (700, 700)]);
        assert!(weights_of(&db, "Inter").is_empty());

        // fontdb's generic sans is a name nobody loaded here, as on Android.
        assert!(!loaded.generic_sans);
        assert!(
            !loaded.wants_platform_sans(Some("DejaVu")),
            "a name it plainly means"
        );
        assert!(
            loaded.wants_platform_sans(Some("Inter")),
            "a name nothing answers to"
        );
        assert!(
            loaded.wants_platform_sans(None),
            "no name, and no generic either"
        );
        // Nothing the name means — but a face of the application's own is a better
        // answer than the platform's, and it is the one drawn.
        loaded.app = vec!["DejaVu Sans".to_string()];
        assert!(!loaded.wants_platform_sans(Some("Inter")));
        assert_eq!(loaded.fallback(), Some("DejaVu Sans"));
    }

    /// **A misspelt family is drawn in the face it means**, in the database Android is left
    /// with: no system font, so no fallback list behind a name that resolves to nothing.
    /// Shaping in the name `match_family` found gives real glyphs from that face.
    #[test]
    #[cfg(feature = "bundled-sans")]
    fn a_family_found_by_its_plain_name_draws_real_glyphs() {
        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        let face = db.faces().next().map(|face| face.id).expect("the face");
        let loaded = Loaded::of(&db);
        let family = match_family("dejavu", &loaded.families, &[]).expect("found");
        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
        let mut buffer = Buffer::new(&mut fs, Metrics::new(20.0, 24.0));
        buffer.set_size(None, None);
        let attrs = Attrs::new().family(cosmic_text::Family::Name(family));
        buffer.set_text("Hello", &attrs, Shaping::Advanced, None);
        buffer.shape_until_scroll(&mut fs, false);
        let glyphs: Vec<_> = buffer
            .layout_runs()
            .flat_map(|run| run.glyphs.iter())
            .map(|glyph| (glyph.font_id, glyph.glyph_id))
            .collect();
        assert_eq!(glyphs.len(), 5);
        assert!(glyphs
            .iter()
            .all(|&(font, glyph)| font == face && glyph != 0));
    }

    /// **An emoji is drawn from the emoji face** when the run's own font lacks it, in the
    /// arrangement Android is left with: the bundled faces, no system font, and the emoji
    /// face loaded on its own. The glyph comes from that face and is a real one — on the
    /// device it was an empty box.
    ///
    /// It needs a colour emoji font to load, and Windows ships one; elsewhere there is
    /// nothing to load, and the test says so and passes.
    #[test]
    #[cfg(feature = "bundled-sans")]
    fn an_emoji_is_drawn_from_the_emoji_face_the_runs_font_lacks() {
        let emoji = std::path::Path::new("C:\\Windows\\Fonts\\seguiemj.ttf");
        if !emoji.exists() {
            eprintln!("no colour emoji font at {}; skipped", emoji.display());
            return;
        }
        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_file(emoji).expect("the emoji font");
        db.set_sans_serif_family(SANS_FAMILY);
        let emoji_face = db
            .faces()
            .find(|face| face.post_script_name.contains("Emoji"))
            .map(|face| face.id)
            .expect("an emoji face");
        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);

        let text = "Hi \u{1F44B}";
        let at = text.find('\u{1F44B}').expect("the wave");
        let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
        buffer.set_size(None, None);
        buffer.set_text(
            text,
            &Attrs::new().family(family_for(text)),
            Shaping::Advanced,
            None,
        );
        buffer.shape_until_scroll(&mut fs, false);
        let (font, glyph) = buffer
            .layout_runs()
            .flat_map(|run| run.glyphs.iter())
            .find(|glyph| glyph.start == at)
            .map(|glyph| (glyph.font_id, glyph.glyph_id))
            .expect("a glyph for the emoji");
        assert_eq!(font, emoji_face, "the emoji comes from the emoji face");
        assert_ne!(glyph, 0, "and is a real glyph, not the empty box");
    }

    /// Reproduces the Android Arabic case **exactly**: the bundled db alone, with no
    /// system font and therefore no platform fallback list, with the Noto Naskh face
    /// loaded. `family_for` must route the Arabic run to the Naskh family, and shaping
    /// must produce **real** glyphs (non-zero ids), not `.notdef`. If `Family::Name`
    /// fails to resolve here, the glyphs come out empty — the blank seen on the
    /// device.
    #[test]
    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
    fn arabic_shapes_with_embedded_only_font_system() {
        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_data(NOTO_ARABIC.to_vec());
        db.load_font_data(NOTO_ARABIC_BOLD.to_vec());
        db.set_sans_serif_family(SANS_FAMILY);
        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);

        let text = "مهامي";
        let attrs = Attrs::new().family(family_for(text));
        let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
        buffer.set_size(None, None);
        buffer.set_text(text, &attrs, Shaping::Advanced, None);
        buffer.shape_until_scroll(&mut fs, false);

        let mut glyphs = 0usize;
        let mut real = 0usize; // glyphs whose glyph_id != 0, so not .notdef
        for run in buffer.layout_runs() {
            for g in run.glyphs.iter() {
                glyphs += 1;
                if g.glyph_id != 0 {
                    real += 1;
                }
            }
        }
        assert!(glyphs > 0, "no glyph shaped for Arabic");
        assert!(
            real > 0,
            "only .notdef ({glyphs} glyphs, 0 real): Family::Name(\"{ARABIC_FAMILY}\") did not resolve the Naskh face"
        );
    }

    /// A positioning diagnosis: an RTL run in a **wide** buffer (width = the surface)
    /// gets **right-aligned** by cosmic-text, so the glyphs land near the right edge
    /// (x about the width) and therefore off-screen once shifted by `position.x`.
    /// With no width constraint (`None`) they start at x about 0. This is the cause
    /// of the blank Arabic text on the device.
    #[test]
    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
    fn rtl_right_aligns_to_buffer_width() {
        let mut db = cosmic_text::fontdb::Database::new();
        db.load_font_data(DEJAVU_SANS.to_vec());
        db.load_font_data(NOTO_ARABIC.to_vec());
        db.set_sans_serif_family(SANS_FAMILY);
        let mut fs = FontSystem::new_with_locale_and_db("en-TG".to_string(), db);
        let text = "العربية";
        let attrs = Attrs::new().family(family_for(text));

        let mut first_glyph_x = |width: Option<f32>| {
            let mut buffer = Buffer::new(&mut fs, Metrics::new(40.0, 48.0));
            buffer.set_size(width, Some(200.0));
            buffer.set_text(text, &attrs, Shaping::Advanced, None);
            buffer.shape_until_scroll(&mut fs, false);
            buffer
                .layout_runs()
                .flat_map(|r| r.glyphs.iter().map(|g| g.x))
                .fold(f32::MAX, f32::min)
        };

        let wide = first_glyph_x(Some(1080.0));
        let free = first_glyph_x(None);
        assert!(wide > 500.0, "a wide RTL run should push right (x={wide})");
        assert!(
            free < 50.0,
            "an unconstrained RTL run should start left (x={free})"
        );
    }

    #[test]
    #[cfg(all(feature = "bundled-sans", feature = "bundled-arabic"))]
    fn arabic_falls_back_to_the_embedded_naskh_face() {
        // DejaVu does not cover Arabic: the bundled fallback (Noto Naskh) has to take
        // over and **shape** the glyphs, giving a non-zero, sensible width. A missing
        // fallback would give 0, or .notdef glyphs.
        let hello = "مرحبا بالعالم"; // "hello world"
        let m = measure(hello, 24.0);
        assert!(m.width > 60.0, "Arabic must shape (width {})", m.width);
        assert!(m.height > 0.0);

        // The fallback does not trample Latin: "Hello" keeps a coherent width.
        let latin = measure("Hello", 24.0);
        assert!(latin.width > 0.0);

        // Mixed bidi (Arabic plus Latin digits) is measured as one piece, without
        // panicking; cosmic-text reorders internally.
        let mixed = measure("قيمة 42 نقطة", 24.0);
        assert!(mixed.width > 0.0, "mixed bidi text was not shaped");
    }

    #[test]
    fn weights_snap_to_embedded_faces() {
        // A weight with no exact face (Medium 500) MUST fall back to a bundled face —
        // otherwise cosmic-text switches to platform fallback lists, which do not
        // exist on Android (a panic on the device).
        assert_eq!(available_weight(FontWeight::Regular), 400);
        assert_eq!(available_weight(FontWeight::Medium), 400);
        assert_eq!(available_weight(FontWeight::SemiBold), 700);
        assert_eq!(available_weight(FontWeight::Bold), 700);
        // And shaping is deterministic: Medium measures like Regular (the same face),
        // and SemiBold like Bold.
        let text = "Titre de section";
        let regular = measure_styled(text, 20.0, FontWeight::Regular, false);
        let medium = measure_styled(text, 20.0, FontWeight::Medium, false);
        assert_eq!(medium.width, regular.width);
        let semibold = measure_styled(text, 20.0, FontWeight::SemiBold, false);
        let bold = measure_styled(text, 20.0, FontWeight::Bold, false);
        assert_eq!(semibold.width, bold.width);
        assert!(bold.width > regular.width);
    }

    /// The natural width is a **whole** number, and never less than what the text
    /// needs. The layout engine rounds the boxes it hands out to whole pixels, so a
    /// measurement of 146.4 becomes a box of 146 — and the text, shaped again at 146
    /// when it is painted, wraps onto a line the layout never reserved.
    #[test]
    fn the_natural_width_is_never_rounded_down_below_the_text() {
        for text in ["Write code", "Bonjour le monde", "A", "iiiii"] {
            for size in [12.0_f32, 15.0, 20.0, 24.0] {
                let natural = measure_styled(text, size, FontWeight::Bold, false);
                assert_eq!(
                    natural.width,
                    natural.width.ceil(),
                    "a whole number for {text:?} at {size}: {}",
                    natural.width
                );
                // Given exactly that width, the text still fits on one line.
                let at_its_width =
                    measure_wrapped(text, size, FontWeight::Bold, false, Some(natural.width));
                assert_eq!(
                    at_its_width.height, natural.height,
                    "{text:?} at {size} wrapped inside its own width"
                );
            }
        }
    }

    /// **And the height, which milestone 289 left fractional.** It fixed the axis the
    /// wrapping bug presented on and no more: a line height is a fraction of a size —
    /// 14.4 for a 12 px line — so a two-line paragraph measured itself at 28.8 and, at a
    /// top edge that rounded the other way, was handed 28.
    ///
    /// The same bug, in the same function, on the axis nobody looked at. It was found by
    /// the rule this milestone put in rather than by a screen, which is the argument for
    /// having the rule (issue #54).
    #[test]
    fn the_natural_height_is_a_whole_number_too() {
        for text in ["Write code", "one two three four five six seven eight", "A"] {
            for size in [12.0_f32, 15.0, 20.0, 24.0] {
                for width in [None, Some(60.0), Some(120.0)] {
                    let measured = measure_wrapped(text, size, FontWeight::Bold, false, width);
                    assert_eq!(
                        measured.height,
                        measured.height.ceil(),
                        "a whole number for {text:?} at {size} in {width:?}: {}",
                        measured.height
                    );
                }
            }
        }
        // An empty label reserves a whole line as well: it is where a caret goes, and
        // where text put there later has to fit.
        let empty = measure_styled("", 16.0, FontWeight::Regular, false);
        assert_eq!(empty.height, empty.height.ceil(), "{}", empty.height);
        assert!(empty.height >= line_height(16.0));
    }

    /// Under a constraint the ceiling is clamped back to it: a box wider than allowed
    /// is a different bug from the one above.
    #[test]
    fn a_constrained_measurement_never_exceeds_its_constraint() {
        let measured = measure_wrapped(
            "A rather long sentence that has to wrap somewhere",
            18.0,
            FontWeight::Regular,
            false,
            Some(120.0),
        );
        assert!(measured.width <= 120.0, "{}", measured.width);
    }

    /// Italic text measures whatever faces are bundled. This is the guard on the
    /// promise that dropping `bundled-italic` costs slanted text and not text: asking
    /// cosmic-text for a style it has no face for used to reach the platform fallback
    /// lists, which are empty on Android, and panic there.
    #[test]
    fn italic_measures_whether_or_not_an_oblique_face_is_bundled() {
        let measured = measure_styled("Slanted", 16.0, FontWeight::Regular, true);
        assert!(measured.width > 0.0, "nothing shaped");
    }

    /// A style is only ever *asked for* when the database can answer it — the whole
    /// point of [`available_style`], and true in either configuration.
    #[test]
    fn italic_is_only_asked_for_when_a_face_can_answer() {
        // Measuring is what builds the font system, which is what reads the database.
        let _ = measure("x", 12.0);
        assert_eq!(
            available_style(false),
            Style::Normal,
            "upright asked for italic"
        );
        assert_eq!(
            available_style(true) == Style::Italic,
            ITALIC.load(Ordering::Relaxed),
            "italic asked for without a face to answer it"
        );
    }

    #[test]
    fn bold_measures_wider_than_regular() {
        // The bundled bold face must actually be chosen: bold is wider than regular
        // at the same size.
        let regular = measure_styled("Bonjour le monde", 24.0, FontWeight::Regular, false);
        let bold = measure_styled("Bonjour le monde", 24.0, FontWeight::Bold, false);
        assert!(
            bold.width > regular.width,
            "gras {} <= normal {}",
            bold.width,
            regular.width
        );
    }

    /// The cache must be invisible: measuring twice gives the same answer as measuring
    /// once, whichever entry point asked, and under a constraint as well as free.
    #[test]
    fn a_cached_measurement_is_the_measurement() {
        for (text, size) in [("Open", 15.0_f32), ("Task number 42 — due Friday", 13.0)] {
            let first = measure(text, size);
            let second = measure(text, size);
            assert_eq!(
                first, second,
                "{text:?} measured differently the second time"
            );

            let styled = measure_styled(text, size, FontWeight::Bold, false);
            assert_eq!(
                styled,
                measure_styled(text, size, FontWeight::Bold, false),
                "{text:?} bold measured differently the second time"
            );

            let wrapped = measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0));
            assert_eq!(
                wrapped,
                measure_wrapped(text, size, FontWeight::Regular, false, Some(60.0)),
                "{text:?} wrapped measured differently the second time"
            );
            // The constraint is part of the key: a different width is a different
            // answer, not a hit on the free one.
            assert!(
                wrapped.height >= first.height,
                "wrapping to 60 px should not make {text:?} shorter"
            );
        }
    }

    /// A retired generation must not lose an entry that is still being asked for:
    /// enough distinct strings to rotate the cache several times over, with one string
    /// re-measured throughout, which has to keep the same answer.
    #[test]
    fn a_string_still_in_use_survives_the_rotation() {
        let kept = measure("still here", 14.0);
        for i in 0..(CACHE_CAP * 2 + 64) {
            measure(&format!("filler {i}"), 14.0);
            if i % 512 == 0 {
                assert_eq!(kept, measure("still here", 14.0), "lost at {i}");
            }
        }
        assert_eq!(kept, measure("still here", 14.0));
    }

    /// Registering a face changes what text can measure to, so every remembered
    /// answer has to go. The measurement itself must still work afterwards.
    #[test]
    fn registering_a_font_forgets_what_was_measured() {
        let before = measure("forget me", 15.0);
        forget_measurements();
        let after = measure("forget me", 15.0);
        assert_eq!(before, after, "the same faces must measure the same");
    }
    /// A baseline sits inside its line box, below the top and above the bottom — and
    /// well above the middle, because most of a face is above the baseline.
    #[test]
    fn a_baseline_sits_where_a_line_of_text_does() {
        let size = 20.0;
        let b = baseline(size, FontWeight::Regular, false);
        let line = line_height(size);
        assert!(b > 0.0 && b < line, "inside the line box: {b} of {line}");
        assert!(b > line * 0.5, "and below its middle: {b} of {line}");
    }

    /// It scales with the size, which is the whole reason two sizes cannot be aligned
    /// by their tops.
    #[test]
    fn a_bigger_face_has_a_lower_baseline() {
        let small = baseline(12.0, FontWeight::Regular, false);
        let large = baseline(24.0, FontWeight::Regular, false);
        assert!(large > small * 1.5, "{small} then {large}");
    }

    /// Runs sharing a line share the **largest** baseline: the tallest ascender is
    /// what decides where the line sits.
    #[test]
    fn mixed_runs_take_the_tallest_baseline() {
        let run = |text: &str, size: f32| TextRun {
            text: text.into(),
            size,
            weight: FontWeight::Regular,
            italic: false,
            color: frus_core::Color::WHITE,
            decoration: frus_core::TextDecoration::default(),
            decoration_color: None,
            letter_spacing: 0.0,
        };
        let runs = vec![run("small", 12.0), run("large", 24.0)];
        let mixed = baseline_of_runs(&runs).expect("two runs");
        assert!((mixed - baseline(24.0, FontWeight::Regular, false)).abs() < 0.01);
    }

    /// **A taller line makes a taller measurement**, and by exactly the ratio asked for.
    ///
    /// This is the assertion that matters: the renderer lays a paragraph out with
    /// `Metrics::new(size, size * height)`, and if the measurement did not use the same
    /// number the layout would reserve room for lines that land somewhere else.
    #[test]
    fn a_named_line_height_reaches_the_measurement() {
        let words = "one two three four five six seven eight nine ten";
        let plain = ResolvedTextStyle::exact(16.0);
        let open = ResolvedTextStyle {
            height: Some(2.4),
            ..plain
        };
        // Wrapped to a narrow column, so there are several lines to stack.
        let a = measure_wrapped_resolved(words, &plain, Some(80.0));
        let b = measure_wrapped_resolved(words, &open, Some(80.0));
        assert!(a.height > 0.0 && b.height > 0.0);
        assert_eq!(
            a.width, b.width,
            "the line height changes the stacking, never the letters"
        );
        let ratio = b.height / a.height;
        assert!(
            (ratio - 2.0).abs() < 0.01,
            "doubling the line height doubles the block: {ratio}"
        );
    }

    /// The measurement cache is keyed on the line height too. Without that, the same words
    /// at two heights would share one answer and the second would be silently wrong.
    #[test]
    fn two_line_heights_do_not_share_a_cached_answer() {
        let words = "cached words that wrap across a couple of lines here";
        let packed = ResolvedTextStyle {
            height: Some(1.0),
            ..ResolvedTextStyle::exact(14.0)
        };
        let open = ResolvedTextStyle {
            height: Some(2.0),
            ..ResolvedTextStyle::exact(14.0)
        };
        let first = measure_wrapped_resolved(words, &packed, Some(90.0));
        let second = measure_wrapped_resolved(words, &open, Some(90.0));
        // Asked again, in the other order, to catch a cache that answered from the wrong
        // entry rather than one that simply never filled.
        assert_eq!(measure_wrapped_resolved(words, &open, Some(90.0)), second);
        assert_eq!(measure_wrapped_resolved(words, &packed, Some(90.0)), first);
        assert!(second.height > first.height);
    }

    /// A one-line box floor follows the style's line height, not the size alone.
    #[test]
    fn a_line_box_follows_the_height_it_was_given() {
        let open = ResolvedTextStyle {
            height: Some(3.0),
            ..ResolvedTextStyle::exact(16.0)
        };
        assert_eq!(line_box(32.0, &ResolvedTextStyle::exact(16.0), 0.0), 32.0);
        assert_eq!(
            line_box(32.0, &open, 0.0),
            48.0,
            "the content wins over the floor"
        );
    }

    /// A named family reaches the shaping, and a **different face measures differently** —
    /// which is the whole reason a style may name one.
    #[test]
    fn a_named_family_reaches_the_measurement() {
        let words = "The quick brown fox";
        let plain = ResolvedTextStyle::exact(16.0);
        let mono = ResolvedTextStyle {
            family: Some(frus_core::FontFamily::Monospace),
            ..plain
        };
        let a = measure_wrapped_resolved(words, &plain, None);
        let b = measure_wrapped_resolved(words, &mono, None);
        assert!(a.width > 0.0 && b.width > 0.0);
        assert_ne!(
            a.width, b.width,
            "a monospaced face sets these words to a different width"
        );
    }

    /// **Arabic keeps its face even when a family is named.**
    ///
    /// Not a hedge: cosmic-text does not fall back across families on Android, where the
    /// platform fallback lists are empty, so a family without Arabic coverage draws
    /// nothing at all. Text in an unexpected face is a smaller failure than a blank
    /// screen. The measurement has to make the same choice the renderer will, so the rule
    /// lives in one function that both call.
    #[test]
    fn arabic_keeps_its_face_whatever_was_named() {
        let arabic = "\u{0645}\u{0631}\u{062d}\u{0628}\u{0627}";
        let named = family_for_style(arabic, Some(frus_core::FontFamily::Monospace));
        assert_eq!(
            format!("{named:?}"),
            format!("{:?}", family_for(arabic)),
            "the script wins over the name"
        );
        // And a Latin run in the same style is free to take the name.
        let latin = family_for_style("hello", Some(frus_core::FontFamily::Monospace));
        assert_eq!(format!("{latin:?}"), format!("{:?}", monospace_family()));
    }

    /// Two families do not share a cached measurement, for the same reason two line
    /// heights do not: the answer is different and the words are the same.
    #[test]
    fn two_families_do_not_share_a_cached_answer() {
        let words = "shared words in two faces";
        let plain = ResolvedTextStyle::exact(15.0);
        let mono = ResolvedTextStyle {
            family: Some(frus_core::FontFamily::Monospace),
            ..plain
        };
        let first = measure_wrapped_resolved(words, &plain, None);
        let second = measure_wrapped_resolved(words, &mono, None);
        // Asked again in the other order, to catch a cache answering from the wrong entry
        // rather than one that simply never filled.
        assert_eq!(measure_wrapped_resolved(words, &mono, None), second);
        assert_eq!(measure_wrapped_resolved(words, &plain, None), first);
        assert_ne!(first.width, second.width);
    }
}