frus-text 0.2.1

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
//! `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.1", 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`].

#[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());

/// 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");
/// ```
pub fn add_font(data: Vec<u8>) {
    // 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() {
            system.db_mut().load_font_data(data.clone());
        }
    }
    EXTRA_FONTS.lock().expect("font registry").push(data);
    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.
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`].
pub fn set_monospace_family(name: &'static str) {
    *MONO.write().expect("family registry") = Some(name);
    forget_measurements();
}

/// The family a generic role resolves to, or the generic family when nothing is
/// loaded for it and the platform is the better judge.
fn family_or_generic(
    slot: &RwLock<Option<&'static str>>,
    generic: cosmic_text::Family<'static>,
) -> cosmic_text::Family<'static> {
    match *slot.read().expect("family registry") {
        Some(name) => cosmic_text::Family::Name(name),
        None => generic,
    }
}

/// `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.
        match *ARABIC.read().expect("family registry") {
            Some(name) => cosmic_text::Family::Name(name),
            None => family_or_generic(&SANS, cosmic_text::Family::SansSerif),
        }
    } else {
        family_or_generic(&SANS, cosmic_text::Family::SansSerif)
    }
}

/// 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.
///
/// 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) => family_or_generic(&SANS, cosmic_text::Family::SansSerif),
        Some(FontFamily::Serif) => cosmic_text::Family::Serif,
        Some(FontFamily::Monospace) => monospace_family(),
        Some(FontFamily::Named(name)) => cosmic_text::Family::Name(name),
    }
}

/// The monospaced family, for the widgets that ask for one.
pub fn monospace_family() -> cosmic_text::Family<'static> {
    family_or_generic(&MONO, cosmic_text::Family::Monospace)
}

/// 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 **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 {
    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 && name.contains("emoji") && db.load_font_file(&path).is_ok() {
            taken += 1;
        }
    }
    taken
}

/// 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.
pub fn new_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());
    }
    // 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.
    if let Some(sans) = *SANS.read().expect("family registry") {
        db.set_sans_serif_family(sans);
        db.set_serif_family(sans);
        db.set_cursive_family(sans);
        db.set_fantasy_family(sans);
    }
    if let Some(mono) = *MONO.read().expect("family registry") {
        db.set_monospace_family(mono);
    }
    // What is *actually* there decides whether italic is asked for, since an
    // application may have supplied an oblique face of its own — or none.
    ITALIC.store(has_italic_face(db), Ordering::Relaxed);
    font_system
}

/// Does the database hold an oblique or italic face for the default family?
fn has_italic_face(db: &cosmic_text::fontdb::Database) -> bool {
    let sans = *SANS.read().expect("family registry");
    db.faces().any(|face| {
        face.style != cosmic_text::fontdb::Style::Normal
            && match sans {
                Some(name) => face.families.iter().any(|(family, _)| family == name),
                None => true,
            }
    })
}

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>,
}

/// 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** among the bundled faces (400 or 700) 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.
pub fn available_weight(weight: FontWeight) -> u16 {
    if weight.to_u16() < 550 {
        400
    } else {
        700
    }
}

/// 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()));

/// 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.size,
        style.weight,
        style.italic,
        max_width,
        style.line_height(),
        style.family,
    )
}

/// 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 {
    measure_at(
        text,
        size_px,
        weight,
        italic,
        max_width,
        line_height(size_px),
        None,
    )
}

/// The measurement itself, at an **explicit line height**.
///
/// Every public form funnels here, and the line height is a parameter rather than a
/// constant because a style may name it: two callers computing it separately is how a
/// measure and a paint come to disagree about where the second line starts.
fn measure_at(
    text: &str,
    size_px: f32,
    weight: FontWeight,
    italic: bool,
    max_width: Option<f32>,
    line_h: f32,
    family: Option<frus_core::FontFamily>,
) -> Size {
    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,
    };
    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 = 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));
    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 mut font_system = font_system().lock().expect("FontSystem lock");
    let metrics = Metrics::new(size_px, line_height(size_px));
    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 = Attrs::new()
        .family(family_for(text))
        .weight(Weight(available_weight(weight)))
        .style(available_style(italic));
    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(),
            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))),
        )
    });
    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(),
            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))),
        )
    });
    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 {
        let fallback_h = line_height(size_px);
        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 = Attrs::new()
                .family(family_for(text))
                .weight(Weight(available_weight(weight)))
                .style(available_style(italic));
            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 {

    /// 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,
        };
        // "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);
    }

    /// **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,
        };
        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);
    }
}