deckcraft-text 0.6.1

DeckCraft text layout: runs to shaped glyph lines with bullets, indents, spacing, alignment, anchoring, autofit and caret hit testing
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
//! Text layout for slide text bodies.
//!
//! [`layout`] resolves every run's formatting through the placeholder/style chain and lays each
//! paragraph out in the order bidirectional text needs:
//! 1. embedding levels for the whole logical paragraph (UAX #9, base level from `a:pPr/@rtl`);
//! 2. itemization by level, script, face (per-cluster fallback through the `a:latin`/`a:ea`/`a:cs`
//!    slots and the theme's script fonts) and shaping style, each item shaped with the whole
//!    paragraph as context; paint-only attributes (colour, highlight, underline) never split a
//!    word, so Arabic joining and ligatures survive them;
//! 3. line breaking in logical order (UAX #14 opportunities at cluster boundaries, greedy fill);
//! 4. per line, rules L1/L2 reorder the characters visually (L4 mirroring is done by the shaper).
//!
//! It then places bullets and numbers from the paragraph's start edge (the right edge for RTL
//! paragraphs), applies indents, spacing and alignment (kashida for `justLow`), anchors the block
//! in the shape's text box, and shrinks text on overflow when the body asks for it. The result is
//! positioned glyph runs in shape-local coordinates plus per-line caret geometry for editing:
//! bidirectional carets with affinity, logical and visual movement, and selection as the union of
//! visual boxes.
#![deny(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unimplemented,
    clippy::todo,
    clippy::unreachable
)]
#![forbid(unsafe_code)]

mod bidi;
pub mod datetime;

use std::collections::HashMap;
use std::sync::Arc;

use deckcraft_color::Rgba;
use deckcraft_fonts::script::{self, joins_following, joins_preceding};
use deckcraft_fonts::{FontDb, FontFace, FontSlot, ScriptTag, ShapeParams};
use deckcraft_geom::{Point, Rect};
use deckcraft_model::resolve::{self, Ctx};
use deckcraft_model::text::{
    Align, Anchor, AutoFit, BodyProps, Bullet, Caps, ParaProps, RunKind, RunProps, Spacing, Strike,
    TextBody, TextDir,
};
use deckcraft_model::{Fill, Shape};
use unicode_segmentation::UnicodeSegmentation;

/// A run of glyphs in one face, size and colour.
#[derive(Clone)]
pub struct GlyphRun {
    pub face: Arc<FontFace>,
    /// Font size in points (after autofit scaling).
    pub size: f64,
    pub color: Rgba,
    /// Glyph id and pen position of its origin (baseline), in shape-local points.
    pub glyphs: Vec<(u32, f64, f64)>,
    /// Per glyph: the paragraph character it draws (index, char); empty for bullets.
    pub cells: Vec<(usize, char)>,
    /// Draw a heavier stroke because the family has no bold face.
    pub fake_bold: bool,
    /// Slant because the family has no italic face.
    pub fake_italic: bool,
    pub outline: Option<(Rgba, f64)>,
    /// Paragraph and character range this run covers (for hyperlinks, selection colours).
    pub para: usize,
    pub chars: (usize, usize),
    pub link: bool,
    /// Alpha of the fill (0–1).
    pub alpha: f64,
    pub gradient: Option<deckcraft_model::style::Gradient>,
    /// Shadow and glow behind the glyphs (`a:rPr/a:effectLst`).
    pub effects: Option<RunEffects>,
}

/// A text run's shadow and glow, colours resolved.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RunEffects {
    pub shadow: Option<TextShadow>,
    /// Glow colour (with its alpha) and radius in points.
    pub glow: Option<(Rgba, f64)>,
}

/// An outer shadow: colour (with its alpha), blur radius and offset in points.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TextShadow {
    pub color: Rgba,
    pub blur: f64,
    pub dx: f64,
    pub dy: f64,
}

impl std::fmt::Debug for GlyphRun {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GlyphRun")
            .field("family", &self.face.family)
            .field("size", &self.size)
            .field("glyphs", &self.glyphs.len())
            .finish()
    }
}

/// An underline, strikethrough or highlight box.
#[derive(Clone, Debug)]
pub struct Deco {
    pub rect: Rect,
    pub color: Rgba,
    /// Highlights draw behind text.
    pub behind: bool,
    /// Paragraph the decoration belongs to (by-paragraph animation).
    pub para: usize,
}

#[derive(Clone, Debug, Default)]
pub struct LineInfo {
    pub para: usize,
    /// Character range [start, end) in the paragraph (end excludes the line's break/newline).
    pub start: usize,
    pub end: usize,
    pub top: f64,
    pub baseline: f64,
    pub bottom: f64,
    /// Caret x for each character boundary start..=end (len = end - start + 1), downstream: the
    /// leading edge of the character after the boundary (its right edge if it is right-to-left);
    /// the last entry is the trailing edge of the line's last character.
    pub caret_x: Vec<f64>,
    /// Column index (multi-column bodies).
    pub column: usize,
    /// Right-to-left paragraph.
    pub rtl: bool,
    /// Bidi level of each character start..end after rule L1 (odd = right-to-left).
    pub levels: Vec<u8>,
    /// Visual box (left, right) of each character start..end. Characters inside a grapheme have
    /// empty boxes; a ligature's characters share its width (GDEF ligature carets).
    pub edges: Vec<(f64, f64)>,
    /// Whether a caret may stand before each character start..end (grapheme boundaries).
    pub boundary: Vec<bool>,
    /// Visual extent (left, right) of the line's text.
    pub extent: (f64, f64),
    /// Distance from the paragraph's start edge to the line's text (indent, margin, bullet).
    pub start_offset: f64,
}

#[derive(Clone, Debug, Default)]
pub struct TextLayout {
    pub runs: Vec<GlyphRun>,
    pub decos: Vec<Deco>,
    pub lines: Vec<LineInfo>,
    /// Inner text box (insets applied), shape-local.
    pub inner: Rect,
    /// Height of the laid-out text (before anchoring).
    pub content_height: f64,
    /// Widest line.
    pub content_width: f64,
    /// Autofit font scale used (1 = none).
    pub font_scale: f64,
    pub line_reduction: f64,
    pub overflow: bool,
    /// Text rotation about the shape centre, degrees (vertical text = 90/270).
    pub rotation: f64,
    /// Per paragraph: (first line index, line count).
    pub para_lines: Vec<(usize, usize)>,
    /// Per paragraph: whether a caret may stand at each character offset 0..=len (grapheme
    /// boundaries), for logical caret movement.
    pub boundaries: Vec<Vec<bool>>,
}

/// Values for fields (`slidenum`, `datetime…`, `footer`). `None` keeps the field's saved text.
pub trait Fields {
    fn field(&self, kind: &str) -> Option<String>;
    /// The value of field `kind` in a run of language `lang` (BCP 47, e.g. `en-US`): dates are
    /// written the language's way.
    fn field_in(&self, kind: &str, lang: Option<&str>) -> Option<String> {
        let _ = lang;
        self.field(kind)
    }
}

pub struct NoFields;
impl Fields for NoFields {
    fn field(&self, kind: &str) -> Option<String> {
        if kind == "slidenum" {
            Some("1".into())
        } else {
            None
        }
    }
}

pub struct Opts<'a> {
    /// The text box: the preset's text rectangle in shape-local space.
    pub rect: Rect,
    pub fields: &'a dyn Fields,
    /// Draw this text instead of the body (placeholder prompts), in this colour.
    pub prompt_color: Option<Rgba>,
    /// Ignore autofit shrinking (used to measure natural height).
    pub no_shrink: bool,
}

struct Style {
    face: Arc<FontFace>,
    size: f64,
    color: Rgba,
    alpha: f64,
    fake_bold: bool,
    fake_italic: bool,
    baseline: f64,
    spacing: f64,
    caps: Caps,
    underline: Option<Rgba>,
    strike: Option<Strike>,
    highlight: Option<Rgba>,
    outline: Option<(Rgba, f64)>,
    link: bool,
    gradient: Option<deckcraft_model::style::Gradient>,
    effects: Option<RunEffects>,
    /// "Regular", "Bold"… for the slot and fallback faces.
    style_name: &'static str,
    /// BCP 47 language (`a:rPr/@lang`), for shaping.
    lang: Option<String>,
    /// The `a:ea` and `a:cs` families (theme references resolved), if the document names one.
    ea: Option<String>,
    cs: Option<String>,
    /// The `a:sym` family: private-use characters (U+F000–U+F0FF, as PowerPoint stores symbol-font
    /// characters) are drawn in it.
    sym: Option<String>,
    /// Heading font (`+mj-…`): the theme's major font set applies.
    major: bool,
    /// Pair kerning on: `a:rPr/@kern` is set and the size reaches it.
    kern: bool,
}

/// One character of a paragraph after shaping.
#[derive(Clone)]
struct Cell {
    ch: char,
    style: usize,
    face: usize,
    /// Resolved bidi embedding level (before the line rules).
    level: u8,
    /// Glyphs of the shaping cluster this cell heads, from the cluster's visual left edge (gid,
    /// x, y). Empty for the other cells of a cluster.
    glyphs: Vec<(u32, f64, f64)>,
    /// This character's advance: its share of the cluster (ligature carets); 0 inside a grapheme.
    adv: f64,
    /// Index of the cell heading this character's shaping cluster.
    head: usize,
    /// A grapheme starts here: carets stand and lines break only before such cells.
    boundary: bool,
}

impl Cell {
    /// A line may start before this cell: a grapheme that starts a shaping cluster.
    fn breakable(&self, i: usize) -> bool {
        self.boundary && self.head == i
    }
}

struct ParaShaped {
    cells: Vec<Cell>,
    styles: Vec<Style>,
    faces: Vec<Arc<FontFace>>,
    props: ParaProps,
    /// Size of the paragraph's first run (spacing percentages, empty lines).
    lead_size: f64,
    lead_face: Arc<FontFace>,
    bullet: Option<(String, Style)>,
    #[allow(dead_code)]
    level: u8,
    /// Right-to-left paragraph (`a:pPr/@rtl`).
    rtl: bool,
}

fn style_name(bold: bool, italic: bool) -> &'static str {
    match (bold, italic) {
        (true, true) => "Bold Italic",
        (true, false) => "Bold",
        (false, true) => "Italic",
        (false, false) => "Regular",
    }
}

fn make_style(ctx: &Ctx, r: &RunProps, scale: f64, prompt: Option<Rgba>) -> Style {
    let family = resolve::font_family(ctx, r);
    let bold = r.bold.unwrap_or(false);
    let italic = r.italic.unwrap_or(false);
    let face = FontDb::global().document_face(&family, style_name(bold, italic));
    let fake_bold = bold && face.weight < 550.0;
    let fake_italic = italic && !face.italic;
    let size = (r.size.unwrap_or(18.0) * scale).clamp(0.5, 4000.0);
    let (mut color, alpha, gradient) = match &r.fill {
        Some(Fill::Solid { color }) => (ctx.color(color, None), color.alpha(), None),
        Some(Fill::Gradient(g)) => {
            // Colours resolved here (theme, colour map), so the renderer needs no colour scheme.
            let mut g = g.clone();
            for s in &mut g.stops {
                s.color = deckcraft_model::ColorRef::rgb(ctx.color(&s.color, None));
            }
            (
                g.stops
                    .first()
                    .map(|s| ctx.color(&s.color, None))
                    .unwrap_or(Rgba::BLACK),
                1.0,
                Some(g),
            )
        }
        Some(Fill::None) => (Rgba::TRANSPARENT, 0.0, None),
        _ => (resolve::text_color(ctx, r), 1.0, None),
    };
    if let Some(p) = prompt {
        color = p;
    }
    let major = r.font.as_deref().is_some_and(|f| f.starts_with("+mj"));
    let theme = &ctx.master.theme;
    let slot_family = |explicit: &Option<String>, theme_ref: &str| {
        let name = theme.font(explicit.as_deref().unwrap_or(theme_ref));
        (!name.trim().is_empty()).then_some(name)
    };
    let ea = slot_family(&r.font_ea, if major { "+mj-ea" } else { "+mn-ea" });
    let cs = slot_family(&r.font_cs, if major { "+mj-cs" } else { "+mn-cs" });
    let underline = r.underline.as_deref().filter(|u| *u != "none").map(|_| {
        r.underline_color
            .as_ref()
            .map(|c| ctx.color(c, None))
            .unwrap_or(color)
    });
    let outline = r.outline.as_ref().and_then(|l| match &l.fill {
        Some(Fill::Solid { color: c }) => Some((ctx.color(c, None), l.width.unwrap_or(0.75))),
        _ => None,
    });
    Style {
        face,
        size,
        color,
        alpha,
        fake_bold,
        fake_italic,
        baseline: r.baseline.unwrap_or(0.0),
        spacing: r.spacing.unwrap_or(0.0) * scale,
        caps: r.caps.unwrap_or(Caps::None),
        underline,
        strike: r.strike.filter(|s| *s != Strike::None),
        highlight: r.highlight.as_ref().map(|c| ctx.color(c, None)),
        outline,
        link: r.link.is_some(),
        gradient,
        effects: run_effects(ctx, r, scale),
        style_name: style_name(bold, italic),
        lang: r.lang.clone().filter(|l| !l.is_empty()),
        ea,
        cs,
        sym: r
            .font_sym
            .as_deref()
            .map(|f| ctx.master.theme.font(f))
            .filter(|f| !f.trim().is_empty()),
        major,
        kern: r.kern.is_some_and(|k| k > 0.0 && size + 1e-6 >= k * scale),
    }
}

/// The faces to try for a cluster of `slot`/`script` in style `st`, in order: the slot's
/// typeface, the theme's font for the script (`a:font[@script]`), then the run's Latin face.
fn face_chain(
    ctx: &Ctx,
    st: &Style,
    slot: FontSlot,
    script: Option<ScriptTag>,
) -> Vec<Arc<FontFace>> {
    let db = FontDb::global();
    let mut chain: Vec<Arc<FontFace>> = Vec::with_capacity(3);
    let mut push = |family: &str| {
        // Only families that exist: `FontDb::face` would substitute the default face.
        if db.has_family(family) {
            let f = db.face(family, st.style_name);
            if !chain.iter().any(|c| Arc::ptr_eq(c, &f)) {
                chain.push(f);
            }
        }
    };
    match slot {
        FontSlot::EastAsian => st.ea.as_deref().into_iter().for_each(&mut push),
        FontSlot::ComplexScript => st.cs.as_deref().into_iter().for_each(&mut push),
        FontSlot::Latin => {}
    }
    if let Some(sc) = script.and_then(|t| std::str::from_utf8(&t).ok().map(String::from)) {
        let set = if st.major {
            &ctx.master.theme.fonts.major
        } else {
            &ctx.master.theme.fonts.minor
        };
        if let Some(f) = set.script(&sc) {
            push(f);
        }
    }
    if !chain.iter().any(|c| Arc::ptr_eq(c, &st.face)) {
        chain.push(st.face.clone());
    }
    chain
}

fn spacing_pts(s: Option<Spacing>, size: f64, reduce: f64) -> f64 {
    match s {
        Some(Spacing::Pct(p)) => p * size * 1.2 * (1.0 - reduce),
        Some(Spacing::Pts(v)) => v * (1.0 - reduce),
        None => 0.0,
    }
}

fn roman(mut n: u32, upper: bool) -> String {
    let table = [
        (1000, "m"),
        (900, "cm"),
        (500, "d"),
        (400, "cd"),
        (100, "c"),
        (90, "xc"),
        (50, "l"),
        (40, "xl"),
        (10, "x"),
        (9, "ix"),
        (5, "v"),
        (4, "iv"),
        (1, "i"),
    ];
    let mut s = String::new();
    if n == 0 || n > 3999 {
        return n.to_string();
    }
    for (v, r) in table {
        while n >= v {
            s.push_str(r);
            n -= v;
        }
    }
    if upper { s.to_uppercase() } else { s }
}

fn alpha_num(n: u32, upper: bool) -> String {
    if n == 0 {
        return String::new();
    }
    let mut n = n - 1;
    let c = (b'a' + (n % 26) as u8) as char;
    let reps = n / 26 + 1;
    n = reps;
    let s: String = std::iter::repeat_n(c, n as usize).collect();
    if upper { s.to_uppercase() } else { s }
}

/// Text of an auto-number bullet: `arabicPeriod` 3 → "3.".
pub fn autonum(scheme: &str, n: u32) -> String {
    let (core, upper) = if scheme.starts_with("romanUc") {
        (roman(n, true), true)
    } else if scheme.starts_with("romanLc") {
        (roman(n, false), false)
    } else if scheme.starts_with("alphaUc") {
        (alpha_num(n, true), true)
    } else if scheme.starts_with("alphaLc") {
        (alpha_num(n, false), false)
    } else if scheme.starts_with("circleNum") {
        let c = char::from_u32(0x2460 + n.saturating_sub(1).min(19)).unwrap_or('•');
        return c.to_string();
    } else {
        (n.to_string(), false)
    };
    let _ = upper;
    if scheme.ends_with("ParenBoth") {
        format!("({core})")
    } else if scheme.ends_with("ParenR") {
        format!("{core})")
    } else if scheme.ends_with("Period") {
        format!("{core}.")
    } else if scheme.ends_with("Minus") {
        format!("- {core} -")
    } else {
        core
    }
}

fn shape_para(
    ctx: &Ctx,
    shape: &Shape,
    body: &TextBody,
    pi: usize,
    scale: f64,
    opts: &Opts,
    number: Option<u32>,
) -> ParaShaped {
    let db = FontDb::global();
    let Some(para) = body.paragraphs.get(pi) else {
        let face = db.face("Inter", "Regular");
        return ParaShaped {
            cells: vec![],
            styles: vec![],
            faces: vec![],
            props: ParaProps::default(),
            lead_size: 18.0,
            lead_face: face,
            bullet: None,
            level: 0,
            rtl: false,
        };
    };
    let props = resolve::para(ctx, shape, para);
    let rtl = props.rtl.unwrap_or(false);
    let mut styles: Vec<Style> = vec![];
    let mut faces: Vec<Arc<FontFace>> = vec![];
    // The logical paragraph: its text and each character's style.
    let mut text = String::new();
    let mut char_style: Vec<usize> = vec![];
    for run in &para.runs {
        let rp = resolve::run(ctx, shape, para, &run.props);
        let st = make_style(ctx, &rp, scale, opts.prompt_color);
        let t: String = match &run.kind {
            RunKind::Text => run.text.clone(),
            RunKind::Break => "\u{b}".into(),
            RunKind::Field { field } => opts
                .fields
                .field_in(field, rp.lang.as_deref())
                .unwrap_or_else(|| run.text.clone()),
            RunKind::Math { .. } => run.text.clone(),
        };
        let si = styles.len();
        styles.push(st);
        char_style.extend(std::iter::repeat_n(si, t.chars().count()));
        text.push_str(&t);
    }
    let cells = shape_cells(ctx, &text, &char_style, &styles, &mut faces, rtl);
    let lead = para
        .runs
        .first()
        .map(|r| resolve::run(ctx, shape, para, &r.props))
        .unwrap_or_else(|| resolve::run(ctx, shape, para, &para.end_props));
    let lead_style = make_style(ctx, &lead, scale, opts.prompt_color);
    let lead_size = lead_style.size;
    let lead_face = lead_style.face.clone();
    // Bullet.
    let bullet = if para.is_empty() && opts.prompt_color.is_none() {
        None
    } else {
        match &props.bullet {
            Some(Bullet::Char { char }) => {
                let mut rp = lead.clone();
                if let Some(f) = &props.bullet_font {
                    rp.font = Some(f.clone());
                }
                rp.bold = Some(false);
                rp.italic = Some(false);
                if let Some(c) = &props.bullet_color {
                    rp.fill = Some(Fill::solid(c.clone()));
                }
                rp.size = Some(lead.size.unwrap_or(18.0) * props.bullet_size.unwrap_or(1.0));
                rp.underline = None;
                rp.strike = None;
                rp.highlight = None;
                let mut st = make_style(ctx, &rp, scale, opts.prompt_color);
                st.baseline = 0.0;
                // Symbol fonts (Wingdings) aren't available: map common private-use bullets.
                let ch = map_symbol_bullet(char, props.bullet_font.as_deref());
                bullet_face(db, &mut st, &ch);

                // A symbol font (Wingdings, Symbol…) that is installed draws its own glyph, found
                // at U+F000 + the character code as such fonts map them; otherwise common symbol
                // bullets are mapped to Unicode look-alikes.
                let ch = match symbol_font_char(&st.face, char, props.bullet_font.as_deref()) {
                    Some(c) => c.to_string(),
                    None => map_symbol_bullet(char, props.bullet_font.as_deref()),
                };
                if !st.face.covers(ch.chars().next().unwrap_or('•')) {
                    st.face = db.face("Inter", "Regular");
                }
                Some((ch, st))
            }
            Some(Bullet::AutoNum { scheme, start_at }) => {
                let mut rp = lead.clone();
                if let Some(c) = &props.bullet_color {
                    rp.fill = Some(Fill::solid(c.clone()));
                }
                rp.size = Some(lead.size.unwrap_or(18.0) * props.bullet_size.unwrap_or(1.0));
                rp.underline = None;
                let mut st = make_style(ctx, &rp, scale, opts.prompt_color);
                let label = autonum(
                    scheme,
                    start_at
                        .saturating_sub(1)
                        .saturating_add(number.unwrap_or(1)),
                );
                bullet_face(db, &mut st, &label);
                Some((label, st))
            }
            _ => None,
        }
    };
    ParaShaped {
        cells,
        styles,
        faces,
        props,
        lead_size,
        lead_face,
        bullet,
        level: para.level,
        rtl,
    }
}

/// A face that draws the bullet `label` when the bullet's own can't (circled numbers ①, arrows
/// and other symbols missing from the text font), by the usual fallback.
fn bullet_face(db: &FontDb, st: &mut Style, label: &str) {
    let chars: Vec<char> = label.chars().collect();
    if !chars.is_empty() && !deckcraft_fonts::covers_cluster(&st.face, &chars) {
        st.face = db.cascade(&chars, std::slice::from_ref(&st.face), st.style_name);
    }
}

/// Shape a logical paragraph into cells: bidi levels, per-grapheme faces, items of one level,
/// script, face and shaping style, each shaped with the whole paragraph as context.
/// A run's outer shadow and glow (inner shadows aren't drawn on text), at the layout's `scale`.
fn run_effects(ctx: &Ctx, r: &RunProps, scale: f64) -> Option<RunEffects> {
    let shadow = r.shadow.as_ref().filter(|s| !s.inner).map(|s| {
        let a = s.dir.to_radians();
        TextShadow {
            color: ctx.color(&s.color, None),
            blur: s.blur.max(0.0) * scale,
            dx: a.cos() * s.dist * scale,
            dy: a.sin() * s.dist * scale,
        }
    });
    let glow = r
        .glow
        .as_ref()
        .filter(|g| g.radius > 0.0)
        .map(|g| (ctx.color(&g.color, None), g.radius * scale));
    (shadow.is_some() || glow.is_some()).then_some(RunEffects { shadow, glow })
}

fn shape_cells(
    ctx: &Ctx,
    text: &str,
    char_style: &[usize],
    styles: &[Style],
    faces: &mut Vec<Arc<FontFace>>,
    rtl: bool,
) -> Vec<Cell> {
    let db = FontDb::global();
    let chars: Vec<char> = text.chars().collect();
    let n = chars.len();
    // Byte offset of each character (and of the end).
    let mut byte_of: Vec<usize> = text.char_indices().map(|(b, _)| b).collect();
    byte_of.push(text.len());
    let char_at_byte: HashMap<usize, usize> =
        byte_of.iter().enumerate().map(|(i, b)| (*b, i)).collect();
    let levels = bidi::levels(text, &chars, rtl);
    let scripts = script::resolve(&chars);
    let mut boundary = vec![false; n];
    let mut graphemes: Vec<(usize, usize)> = Vec::new();
    for (b, g) in text.grapheme_indices(true) {
        let Some(&i) = char_at_byte.get(&b) else {
            continue;
        };
        if let Some(x) = boundary.get_mut(i) {
            *x = true;
        }
        graphemes.push((i, i + g.chars().count()));
    }
    let face_index = |faces: &mut Vec<Arc<FontFace>>, f: &Arc<FontFace>| -> usize {
        if let Some(i) = faces.iter().position(|x| Arc::ptr_eq(x, f)) {
            return i;
        }
        faces.push(f.clone());
        faces.len() - 1
    };
    // A face per grapheme cluster (never split between faces).
    let mut char_face = vec![0usize; n];
    let mut chains: HashMap<(usize, FontSlot, Option<ScriptTag>), Vec<Arc<FontFace>>> =
        HashMap::new();
    let mut prev: Option<Arc<FontFace>> = None;
    for &(a, b) in &graphemes {
        let Some(cluster) = chars.get(a..b) else {
            continue;
        };
        let si = char_style.get(a).copied().unwrap_or(0);
        let Some(st) = styles.get(si) else { continue };
        let (sc, slot) = scripts.get(a).copied().unwrap_or((None, FontSlot::Latin));
        // Spaces, digits and punctuation stay in the face of the text before them when it can
        // draw them, so a phrase isn't cut into items at every space.
        // Emoji, and pictographs asked to look like text (U+FE0E), pick their own face.
        let neutral = cluster.iter().all(|c| script::script_of(*c).is_none())
            && !deckcraft_fonts::is_emoji_cluster(cluster)
            && !cluster.contains(&'\u{FE0E}');
        // A symbol-font character (U+F0xx) with an `a:sym` font draws in that font when it's there.
        let sym_face = st
            .sym
            .as_deref()
            .filter(|_| {
                cluster
                    .first()
                    .is_some_and(|c| ('\u{F000}'..='\u{F0FF}').contains(c))
            })
            .filter(|f| db.has_family(f))
            .map(|f| db.face(f, st.style_name))
            .filter(|f| deckcraft_fonts::covers_cluster(f, cluster));
        let face = match (sym_face, prev.as_ref()) {
            (Some(f), _) => f,
            (None, Some(p))
                if neutral
                    && deckcraft_fonts::covers_cluster(p, cluster)
                    && char_style.get(a.wrapping_sub(1)) == Some(&si) =>
            {
                p.clone()
            }
            (None, _) => {
                let chain = chains
                    .entry((si, slot, sc))
                    .or_insert_with(|| face_chain(ctx, st, slot, sc));
                db.cascade(cluster, chain, st.style_name)
            }
        };
        let fi = face_index(faces, &face);
        for f in char_face.get_mut(a..b).into_iter().flatten() {
            *f = fi;
        }
        prev = Some(face);
    }
    let mut cells: Vec<Cell> = (0..n)
        .map(|i| Cell {
            ch: chars.get(i).copied().unwrap_or(' '),
            style: char_style.get(i).copied().unwrap_or(0),
            face: char_face.get(i).copied().unwrap_or(0),
            level: levels.get(i).copied().unwrap_or(0),
            glyphs: vec![],
            adv: 0.0,
            head: i,
            boundary: boundary.get(i).copied().unwrap_or(true),
        })
        .collect();
    // Items: maximal ranges of one level, face, script and shaping style (case mapping, language).
    let upper = |i: usize| {
        styles
            .get(char_style.get(i).copied().unwrap_or(0))
            .is_some_and(|st| st.caps != Caps::None)
    };
    let lang = |i: usize| {
        styles
            .get(char_style.get(i).copied().unwrap_or(0))
            .and_then(|st| st.lang.as_deref())
    };
    let kern = |i: usize| {
        styles
            .get(char_style.get(i).copied().unwrap_or(0))
            .is_some_and(|st| st.kern)
    };
    let key = |i: usize| {
        (
            levels.get(i).copied(),
            char_face.get(i).copied(),
            scripts.get(i).map(|s| s.0),
            upper(i),
            lang(i),
            kern(i),
        )
    };
    let mut a = 0;
    while a < n {
        let mut b = a + 1;
        while b < n && key(b) == key(a) {
            b += 1;
        }
        shape_item(
            &mut cells,
            styles,
            faces,
            text,
            &byte_of,
            &char_at_byte,
            a..b,
            scripts.get(a).and_then(|s| s.0),
            lang(a),
            upper(a),
        );
        a = b;
    }
    cells
}

/// Size of superscript and subscript text relative to the run's size.
const SUB_SUPER: f64 = 0.66;

/// The OpenType features to change from the shaper's defaults for an item, as PowerPoint draws
/// it: kerning only where the run asks for it (`kern`), and no standard or contextual ligatures in
/// Latin, Greek and Cyrillic ("fi", "ffi" and Calibri's "ti" stay apart). Other scripts need
/// their ligatures (Arabic lam-alef), and emoji sequences are joined by them.
fn shaping_features(
    cells: &[Cell],
    styles: &[Style],
    script: Option<ScriptTag>,
) -> Vec<deckcraft_fonts::Feature> {
    let mut f = vec![];
    if !cells
        .first()
        .and_then(|c| styles.get(c.style))
        .is_some_and(|st| st.kern)
    {
        f.extend(deckcraft_fonts::feature("-kern"));
    }
    let alphabetic = matches!(script.as_ref(), Some(b"Latn" | b"Grek" | b"Cyrl"));
    let emoji = cells.iter().any(|c| matches!(c.ch as u32, 0x200D | 0x20E3 | 0xFE0F | 0x2600..=0x27BF | 0x1F000..=0x1FAFF | 0xE0020..=0xE007F));
    if alphabetic && !emoji {
        f.extend(deckcraft_fonts::feature("-liga"));
        f.extend(deckcraft_fonts::feature("-clig"));
    }
    f
}

/// Shape cells `range` (one item) and hang each cluster's glyphs on its first cell, sharing the
/// cluster's advance among its graphemes (by the ligature's GDEF carets when it has them).
#[allow(clippy::too_many_arguments)]
fn shape_item(
    cells: &mut [Cell],
    styles: &[Style],
    faces: &[Arc<FontFace>],
    text: &str,
    byte_of: &[usize],
    char_at_byte: &HashMap<usize, usize>,
    range: std::ops::Range<usize>,
    script: Option<ScriptTag>,
    lang: Option<&str>,
    upper: bool,
) {
    let Some(first) = cells.get(range.start) else {
        return;
    };
    let (fi, level) = (first.face, first.level);
    let Some(face) = faces.get(fi) else { return };
    let rtl = level % 2 == 1;
    let (Some(&b0), Some(&b1)) = (byte_of.get(range.start), byte_of.get(range.end)) else {
        return;
    };
    let features = shaping_features(cells.get(range.clone()).unwrap_or(&[]), styles, script);
    let params = ShapeParams {
        features: &features,
        rtl,
        script,
        language: lang,
    };
    let glyphs = deckcraft_fonts::shape_range(face, text, b0..b1, &params, |ch| {
        if upper {
            ch.to_uppercase().next().unwrap_or(ch)
        } else {
            ch
        }
    });
    let upem = face.upem.max(1.0);
    let scale_of = |cell: &Cell| {
        let st = styles.get(cell.style);
        let size = st.map(|s| s.size).unwrap_or(18.0);
        let small = st.is_some_and(|s| s.caps == Caps::Small) && cell.ch.is_lowercase();
        let size = if small { size * 0.8 } else { size };
        // Superscript and subscript glyphs are drawn at two thirds of the size, so they advance by
        // two thirds too.
        let size = if st.is_some_and(|s| s.baseline != 0.0) {
            size * SUB_SUPER
        } else {
            size
        };
        size / upem
    };
    // Cluster heads in this item, ascending; each cluster spans to the next head.
    let mut heads: Vec<usize> = glyphs
        .iter()
        .filter_map(|g| char_at_byte.get(&g.cluster).copied())
        .filter(|h| range.contains(h))
        .collect();
    heads.sort_unstable();
    heads.dedup();
    let mut width: HashMap<usize, f64> = HashMap::new();
    let mut lig: HashMap<usize, (u32, usize)> = HashMap::new();
    for g in &glyphs {
        let Some(&h) = char_at_byte.get(&g.cluster) else {
            continue;
        };
        let Some(cell) = cells.get_mut(h) else {
            continue;
        };
        if matches!(cell.ch, '\t' | '\u{b}' | '\n') {
            continue;
        }
        let s = scale_of(cell);
        let w = width.entry(h).or_insert(0.0);
        cell.glyphs
            .push((g.gid, *w + g.x_offset as f64 * s, -(g.y_offset as f64) * s));
        *w += g.x_advance as f64 * s;
        let e = lig.entry(h).or_insert((g.gid, 0));
        e.1 += 1;
    }
    for (hi, &h) in heads.iter().enumerate() {
        let end = heads
            .get(hi + 1)
            .copied()
            .unwrap_or(range.end)
            .min(range.end);
        let w = width.get(&h).copied().unwrap_or(0.0);
        for c in cells.get_mut(h..end).into_iter().flatten() {
            c.head = h;
        }
        let stops: Vec<usize> = (h..end)
            .filter(|&i| i == h || cells.get(i).is_some_and(|c| c.boundary))
            .collect();
        let m = stops.len().max(1);
        // Visual widths of the cluster's graphemes, left to right.
        let mut bounds = vec![0.0];
        if m > 1
            && let Some(&(gid, 1)) = lig.get(&h)
        {
            let s = cells.get(h).map(scale_of).unwrap_or(0.0);
            let carets = deckcraft_fonts::ligature_carets(face, gid);
            if carets.len() + 1 >= m {
                bounds.extend(
                    carets
                        .iter()
                        .take(m - 1)
                        .map(|c| (*c as f64 * s).clamp(0.0, w)),
                );
            }
        }
        if bounds.len() != m {
            bounds = (0..m).map(|j| w * j as f64 / m as f64).collect();
        }
        bounds.push(w);
        for (j, &i) in stops.iter().enumerate() {
            let vj = if rtl { m - 1 - j } else { j };
            let share =
                bounds.get(vj + 1).copied().unwrap_or(w) - bounds.get(vj).copied().unwrap_or(0.0);
            if let Some(c) = cells.get_mut(i) {
                c.adv = share.max(0.0);
            }
        }
    }
    // Tracking (character spacing) after every drawn grapheme and space.
    for i in range {
        let Some(c) = cells.get(i) else { continue };
        let drawn = cells.get(c.head).is_some_and(|hd| !hd.glyphs.is_empty());
        if c.boundary
            && (drawn || c.ch == ' ')
            && let Some(sp) = styles.get(c.style).map(|s| s.spacing)
            && let Some(c) = cells.get_mut(i)
        {
            c.adv += sp;
        }
    }
}

/// Is `family` a symbol font (characters at U+F000 + code)?
fn is_symbol_font(family: &str) -> bool {
    let f = family.to_ascii_lowercase();
    f.starts_with("wingdings")
        || f == "symbol"
        || f.starts_with("webdings")
        || f.starts_with("marlett")
}

/// The character to draw bullet `c` with the installed symbol font `face`, when `font` names a
/// symbol font that `face` is (not a substitute) and it has the glyph.
fn symbol_font_char(face: &FontFace, c: &str, font: Option<&str>) -> Option<char> {
    let font = font?;
    if !is_symbol_font(font) || !face.family.eq_ignore_ascii_case(font) {
        return None;
    }
    let first = c.chars().next()?;
    let pua = char::from_u32(0xF000 | ((first as u32) & 0xFF))?;
    if face.covers(pua) {
        Some(pua)
    } else if face.covers(first) {
        Some(first)
    } else {
        None
    }
}

/// The character that draws `c`, a character of text set in the symbol font `font` (Wingdings,
/// Symbol, Webdings…: its code, or U+F000 + its code), with `face`: the installed symbol font's own
/// glyph when `face` is that font, else a Unicode look-alike as bullets use. None when `font` is not
/// a symbol font or `c` is not a symbol code. Metafile text takes this path.
pub fn symbol_char(face: &FontFace, font: &str, c: char) -> Option<char> {
    let code = c as u32;
    if !is_symbol_font(font) || !(code < 0x100 || (0xF000..=0xF0FF).contains(&code)) {
        return None;
    }
    let plain = char::from_u32(code & 0xFF)?;
    let s = plain.to_string();
    Some(symbol_font_char(face, &s, Some(font)).unwrap_or_else(|| {
        map_symbol_bullet(&s, Some(font))
            .chars()
            .next()
            .unwrap_or('•')
    }))
}

fn map_symbol_bullet(c: &str, font: Option<&str>) -> String {
    let f = font.unwrap_or("").to_ascii_lowercase();
    let first = c.chars().next().unwrap_or('•');
    if f.starts_with("webdings") {
        let m = match (first as u32) & 0xff {
            0x6e => '●',
            0x67 => '■',
            0x61 => '✓',
            0x72 => '✕',
            0x33 => '◀',
            0x34 => '▶',
            0x35 => '▲',
            0x36 => '▼',
            _ => '•',
        };
        return m.to_string();
    }
    if f.contains("wingdings") || f.contains("symbol") || ('\u{f000}'..='\u{f0ff}').contains(&first)
    {
        let code = (first as u32) & 0xff;
        // Wingdings 2 and 3 put different shapes at the same codes.
        if f.starts_with("wingdings 2") {
            let m = match code {
                0x97 | 0x98 => '●',
                0x9e..=0xa1 => '■',
                0xa2..=0xa5 => '◆',
                0xea..=0xf3 => '★',
                0xb7..=0xbf => '○',
                0x50 => '✓',
                _ => '•',
            };
            return m.to_string();
        }
        if f.starts_with("wingdings 3") {
            let m = match code {
                0x7d | 0x75 => '►',
                0x7c | 0x74 => '◄',
                0x70 => '▲',
                0x71 => '▼',
                0xc6 | 0xc7 => '➔',
                _ => '▶',
            };
            return m.to_string();
        }
        let m = match code {
            0xa7 => '▪',
            0xd8 => '➢',
            0xfc => '✓',
            0x76 => '❖',
            0x71 => '❑',
            0x6e => '■',
            0x6c => '●',
            0xa8 => '◆',
            0xb7 => '•',
            0x2d => '–',
            _ => '•',
        };
        return m.to_string();
    }
    // PowerPoint draws only the first character of a longer `buChar` ("••" draws one dot).
    c.graphemes(true).next().unwrap_or("•").to_string()
}

fn measure_str(face: &FontFace, size: f64, s: &str) -> (f64, Vec<(u32, f64)>) {
    let g = deckcraft_fonts::shape(face, s, &[], |c| c);
    let k = size / face.upem.max(1.0);
    let mut x = 0.0;
    let mut out = vec![];
    for gl in g {
        out.push((gl.gid, x + gl.x_offset as f64 * k));
        x += gl.x_advance as f64 * k;
    }
    (x, out)
}

/// Single line spacing as a multiple of the font size. PowerPoint spaces single-spaced lines 1.2
/// times the size apart in every font (observed on twenty Latin, CJK, Thai and Indic fonts at 18
/// and 40 pt), whatever the font's own ascent and descent.
///
/// Caveat: this was measured on one Windows install of desktop PowerPoint. It may be a Windows or
/// machine setting; PowerPoint on macOS or the web may space lines by the font's own metrics.
/// Keep it a single tunable value, and re-measure on the other platform before changing it.
const LINE_PITCH: f64 = 1.2;

/// A line's height above and below the baseline at `size`: [`LINE_PITCH`] × size, split where
/// the font's Windows ascent and descent put the baseline.
fn line_metrics(face: &FontFace, size: f64) -> (f64, f64) {
    let h = size * LINE_PITCH;
    (h * face.line_split, h * (1.0 - face.line_split))
}

/// Hangul syllables and jamo: PowerPoint wraps Korean at word boundaries (spaces), not between
/// syllables.
fn is_hangul(c: char) -> bool {
    matches!(c, '\u{1100}'..='\u{11FF}' | '\u{3130}'..='\u{318F}' | '\u{A960}'..='\u{A97F}' | '\u{AC00}'..='\u{D7FF}')
}

/// Closing East Asian punctuation that may hang past the end of a line (`hangingPunct`).
fn is_hanging_punct(c: char) -> bool {
    matches!(
        c,
        '、' | '。'
            | ','
            | '.'
            | ':'
            | ';'
            | '!'
            | '?'
            | ')'
            | '」'
            | '』'
            | '】'
            | '〕'
            | '〉'
            | '》'
            | '〙'
            | '〛'
            | '}'
            | ']'
            | '」'
            | '、'
            | '。'
    )
}

/// Break opportunities: allowed[i] = a line may start at char i. Unicode line breaking, then
/// PowerPoint's differences: without `latinLnBrk` a word doesn't break after `/` or `\`, and
/// Korean breaks only between words.
fn break_opportunities(text: &str, latin_break: bool) -> (Vec<bool>, Vec<bool>) {
    let n = text.chars().count();
    let mut allowed = vec![false; n + 1];
    let mut mandatory = vec![false; n + 1];
    let mut byte_to_char = std::collections::HashMap::new();
    for (ci, (b, _)) in text.char_indices().enumerate() {
        byte_to_char.insert(b, ci);
    }
    byte_to_char.insert(text.len(), n);
    for (b, op) in unicode_linebreak::linebreaks(text) {
        if let Some(&ci) = byte_to_char.get(&b) {
            if let Some(a) = allowed.get_mut(ci) {
                *a = true;
            }
            if op == unicode_linebreak::BreakOpportunity::Mandatory
                && let Some(m) = mandatory.get_mut(ci)
            {
                *m = true;
            }
        }
    }
    let chars: Vec<char> = text.chars().collect();
    for (i, w) in chars.windows(2).enumerate() {
        let (prev, next) = (w[0], w[1]);
        let keep = if is_hangul(prev) && is_hangul(next) {
            false
        } else {
            latin_break || !matches!(prev, '/' | '\\') || next.is_whitespace()
        };
        if !keep
            && !mandatory.get(i + 1).copied().unwrap_or(false)
            && let Some(a) = allowed.get_mut(i + 1)
        {
            *a = false;
        }
    }
    (allowed, mandatory)
}

struct RawLine {
    start: usize,
    end: usize,
    /// End including trailing spaces / the break char consumed.
    next: usize,
}

fn break_lines(
    p: &ParaShaped,
    first_w: f64,
    rest_w: f64,
    wrap: bool,
    tab_stops: &[f64],
    default_tab: f64,
    x0_first: f64,
    x0_rest: f64,
) -> Vec<RawLine> {
    let text: String = p.cells.iter().map(|c| c.ch).collect();
    let (allowed, _) = break_opportunities(&text, p.props.latin_line_break.unwrap_or(false));
    let hang = p.props.hanging_punct.unwrap_or(false);
    let n = p.cells.len();
    let mut lines = vec![];
    let mut start = 0;
    if n == 0 {
        return vec![RawLine {
            start: 0,
            end: 0,
            next: 0,
        }];
    }
    while start < n {
        let avail = if lines.is_empty() { first_w } else { rest_w };
        let x0 = if lines.is_empty() { x0_first } else { x0_rest };
        let mut x = 0.0;
        let mut last_break: Option<usize> = None;
        let mut i = start;
        let mut end = n;
        let mut next = n;
        while i < n {
            let c = p.cells.get(i).map(|c| c.ch).unwrap_or(' ');
            if c == '\u{b}' || c == '\n' {
                end = i;
                next = i + 1;
                break;
            }
            let adv = if c == '\t' {
                tab_advance(x0 + x, tab_stops, default_tab)
            } else {
                p.cells.get(i).map(|c| c.adv).unwrap_or(0.0)
            };
            let breakable = |j: usize| p.cells.get(j).is_none_or(|c| c.breakable(j));
            if i > start && allowed.get(i).copied().unwrap_or(false) && breakable(i) {
                last_break = Some(i);
            }
            // Closing East Asian punctuation hangs past the end instead of wrapping
            // (`hangingPunct`); the line breaks after it.
            if wrap
                && hang
                && x + adv > avail + 0.01
                && x <= avail + 0.01
                && is_hanging_punct(c)
                && i > start
            {
                end = i + 1;
                next = i + 1;
                break;
            }
            if wrap && x + adv > avail + 0.01 && !c.is_whitespace() && i > start {
                // Break at the last opportunity, or force mid-word (between clusters).
                let b = last_break.filter(|b| *b > start).unwrap_or_else(|| {
                    (start + 1..=i)
                        .rev()
                        .find(|&j| breakable(j))
                        .or_else(|| (i + 1..n).find(|&j| breakable(j)))
                        .unwrap_or(n)
                });
                end = b;
                next = b;
                // Trailing spaces belong to the line but don't count.
                while end > start && p.cells.get(end - 1).is_some_and(|c| c.ch == ' ') {
                    end -= 1;
                }
                break;
            }
            x += adv;
            i += 1;
        }
        if i >= n {
            end = n;
            next = n;
        }
        lines.push(RawLine { start, end, next });
        if next <= start {
            // No progress: force one char.
            let last = lines.len() - 1;
            let to = (start + 1..n)
                .find(|&j| p.cells.get(j).is_none_or(|c| c.breakable(j)))
                .unwrap_or(n);
            if let Some(l) = lines.get_mut(last) {
                l.end = to;
                l.next = to;
            }
            start = to;
        } else {
            start = next;
        }
        if next == n && p.cells.last().is_some_and(|c| c.ch == '\u{b}') && start >= n {
            // A trailing line break opens an empty last line.
            lines.push(RawLine {
                start: n,
                end: n,
                next: n,
            });
        }
    }
    lines
}

fn tab_advance(x: f64, stops: &[f64], default_tab: f64) -> f64 {
    for s in stops {
        if *s > x + 0.5 {
            return s - x;
        }
    }
    let d = if default_tab > 1.0 { default_tab } else { 72.0 };
    let next = ((x / d).floor() + 1.0) * d;
    (next - x).max(1.0)
}

/// Lay out a shape's text body.
pub fn layout(ctx: &Ctx, shape: &Shape, body: &TextBody, opts: &Opts) -> TextLayout {
    let bp = resolve::body(ctx, shape);
    let autofit = bp.autofit.unwrap_or(AutoFit::None);
    let mut l = layout_scaled(ctx, shape, body, &bp, opts, 1.0, 0.0);
    if let (AutoFit::Shrink { .. }, false) = (autofit, opts.no_shrink)
        && l.overflow
    {
        // Binary search the largest scale that fits (steps like 90%, 80%… with line reduction).
        let (mut lo, mut hi) = (0.1_f64, 1.0_f64);
        let mut best = None;
        for _ in 0..12 {
            let mid = (lo + hi) / 2.0;
            let red: f64 = ((1.0 - mid) * 0.8_f64).min(0.2);
            let t = layout_scaled(ctx, shape, body, &bp, opts, mid, red);
            if t.overflow {
                hi = mid;
            } else {
                lo = mid;
                best = Some(t);
            }
        }
        l = best.unwrap_or_else(|| layout_scaled(ctx, shape, body, &bp, opts, 0.1, 0.2));
    }
    l
}

fn layout_scaled(
    ctx: &Ctx,
    shape: &Shape,
    body: &TextBody,
    bp: &BodyProps,
    opts: &Opts,
    scale: f64,
    reduce: f64,
) -> TextLayout {
    let r = opts.rect;
    let vert = bp.vert.unwrap_or(TextDir::Horizontal);
    let rotation = match vert {
        TextDir::Vertical | TextDir::EaVertical | TextDir::Stacked => 90.0,
        TextDir::Vertical270 => 270.0,
        TextDir::Horizontal => 0.0,
    } + bp.rot.unwrap_or(0.0);
    // For vertical text, lay out in a box with swapped dimensions centred on the text rect.
    let r = if (rotation - 90.0).abs() < 1e-6 || (rotation - 270.0).abs() < 1e-6 {
        let c = r.center();
        Rect::new(
            c.x - r.height() / 2.0,
            c.y - r.width() / 2.0,
            c.x + r.height() / 2.0,
            c.y + r.width() / 2.0,
        )
    } else {
        r
    };
    let inner = Rect::new(
        r.x0 + bp.inset_l.unwrap_or(7.2),
        r.y0 + bp.inset_t.unwrap_or(3.6),
        (r.x1 - bp.inset_r.unwrap_or(7.2)).max(r.x0 + bp.inset_l.unwrap_or(7.2)),
        (r.y1 - bp.inset_b.unwrap_or(3.6)).max(r.y0 + bp.inset_t.unwrap_or(3.6)),
    );
    // Text that follows a WordArt arch or circle is set on one line per paragraph.
    let follow = bp
        .warp
        .as_deref()
        .is_some_and(deckcraft_geom::warp::is_follow);
    let wrap = bp.wrap.unwrap_or(true)
        && !follow
        && !matches!(bp.autofit, Some(AutoFit::Shape) if shape.text_box && !bp.wrap.unwrap_or(true));
    let ncols = bp.columns.unwrap_or(1).clamp(1, 16) as usize;
    let col_gap = bp.col_spacing.unwrap_or(0.0).max(0.0);
    let col_w = ((inner.width() - col_gap * (ncols as f64 - 1.0)) / ncols as f64).max(1.0);

    let mut out = TextLayout {
        inner,
        font_scale: scale,
        line_reduction: reduce,
        rotation,
        ..Default::default()
    };
    let mut y = 0.0;
    let mut numbering: Vec<u32> = vec![0; 9];
    let mut all_lines: Vec<(LineInfo, LinePlace, f64, Option<(String, f64, f64)>)> = vec![];
    let mut prev_after = 0.0;
    let mut shaped_paras: Vec<ParaShaped> = Vec::with_capacity(body.paragraphs.len());
    for (pi, para) in body.paragraphs.iter().enumerate() {
        let lvl = para.level.min(8) as usize;
        let pp = resolve::para(ctx, shape, para);
        let number = if matches!(pp.bullet, Some(Bullet::AutoNum { .. })) && !para.is_empty() {
            if let Some(n) = numbering.get_mut(lvl) {
                *n += 1;
            }
            for deeper in numbering.iter_mut().skip(lvl + 1) {
                *deeper = 0;
            }
            numbering.get(lvl).copied()
        } else {
            if !para.is_empty() {
                for n in numbering.iter_mut().skip(lvl) {
                    *n = 0;
                }
            }
            None
        };
        shaped_paras.push(shape_para(ctx, shape, body, pi, scale, opts, number));
    }
    for (pi, p) in shaped_paras.iter().enumerate() {
        let props = &p.props;
        let margin = props.margin_left.unwrap_or(0.0).max(0.0);
        let indent = props.indent.unwrap_or(0.0);
        let mr = props.margin_right.unwrap_or(0.0).max(0.0);
        let bullet_w = p
            .bullet
            .as_ref()
            .map(|(s, st)| measure_str(&st.face, st.size, s).0)
            .unwrap_or(0.0);
        let first_x = if p.bullet.is_some() {
            let bx = (margin + indent).max(0.0);
            // A hanging bullet's text starts at the margin. When the hang reaches left of the box
            // (marL + indent < 0), PowerPoint pins the bullet to the box's edge and keeps the
            // hang: the first line's text starts at -indent (later lines stay at the margin).
            let stop = margin.max(-indent);
            if indent < 0.0 && bx + bullet_w <= stop {
                stop
            } else {
                bx + bullet_w + if indent >= 0.0 { 0.0 } else { 3.0 }
            }
        } else {
            (margin + indent).max(0.0)
        };
        let rest_x = margin;
        let tabs: Vec<f64> = props
            .tabs
            .as_ref()
            .map(|t| t.iter().map(|s| s.pos).collect())
            .unwrap_or_default();
        let first_w = (col_w - first_x - mr).max(1.0);
        let rest_w = (col_w - rest_x - mr).max(1.0);
        let raw = break_lines(
            p,
            first_w,
            rest_w,
            wrap,
            &tabs,
            props.default_tab.unwrap_or(72.0),
            first_x,
            rest_x,
        );
        let before = if pi == 0 {
            0.0
        } else {
            spacing_pts(props.space_before, p.lead_size, reduce)
        };
        y += before.max(0.0) + prev_after;
        let first_line_idx = all_lines.len();
        for (li, rl) in raw.iter().enumerate() {
            // Line metrics: max ascent/descent over the line's styles (or the lead style if empty).
            let (mut asc, mut desc, mut size) = (0.0f64, 0.0f64, 0.0f64);
            for c in p.cells.get(rl.start..rl.end.max(rl.start)).unwrap_or(&[]) {
                if let (Some(st), Some(face)) = (p.styles.get(c.style), p.faces.get(c.face)) {
                    let sz = st.size;
                    let (a, d) = line_metrics(face, sz);
                    asc = asc.max(a);
                    desc = desc.max(d);
                    size = size.max(sz);
                }
            }
            if size == 0.0 {
                let (a, d) = line_metrics(&p.lead_face, p.lead_size);
                asc = a;
                desc = d;
                size = p.lead_size;
            }
            let natural = (asc + desc).max(size * 1.0);
            let lh = match props.line_spacing {
                Some(Spacing::Pct(f)) => natural * f.max(0.0) * (1.0 - reduce),
                Some(Spacing::Pts(v)) => v * (1.0 - reduce),
                None => natural * (1.0 - reduce),
            };
            let ratio = if natural > 0.0 { lh / natural } else { 1.0 };
            let top = y;
            let baseline = top + asc * ratio;
            y += lh;
            let x0 = if li == 0 { first_x } else { rest_x };
            let avail = (col_w - x0 - mr).max(0.0);
            let n = rl.end.saturating_sub(rl.start);
            let line_cells = p.cells.get(rl.start..rl.end).unwrap_or(&[]);
            // Logical advances; tabs measure from the start edge.
            let mut adv = Vec::with_capacity(n);
            let mut x = 0.0;
            for c in line_cells {
                let a = if c.ch == '\t' {
                    tab_advance(x0 + x, &tabs, props.default_tab.unwrap_or(72.0))
                } else {
                    c.adv
                };
                adv.push(a);
                x += a;
            }
            let width = x;
            let align = props.align.unwrap_or(Align::Left);
            let last_line = li + 1 == raw.len();
            let slack = (avail - width).max(0.0);
            // Justification: kashida (justLow, Arabic), spaces, or every character.
            let stretch = !last_line && wrap && slack > 0.0;
            let mut kashida = vec![0.0; n];
            let mut filled = false;
            if stretch && align == Align::JustLow {
                let ops = kashida_opportunities(p, rl.start, rl.end);
                if !ops.is_empty() {
                    let each = slack / ops.len() as f64;
                    for k in ops {
                        if let (Some(e), Some(a)) = (kashida.get_mut(k), adv.get_mut(k)) {
                            *e = each;
                            *a += each;
                        }
                    }
                    filled = true;
                }
            }
            if stretch && !filled && matches!(align, Align::Justify | Align::JustLow) {
                let spaces = line_cells.iter().filter(|c| c.ch == ' ').count();
                if spaces > 0 {
                    for (a, c) in adv.iter_mut().zip(line_cells) {
                        if c.ch == ' ' {
                            *a += slack / spaces as f64;
                        }
                    }
                    filled = true;
                }
            }
            if align == Align::Distributed && n > 1 {
                for a in adv.iter_mut().take(n - 1) {
                    *a += slack / (n - 1) as f64;
                }
                filled = true;
            }
            let line_w: f64 = adv.iter().sum();
            // The line box, in column coordinates: the start edge is the left one for LTR and the
            // right one (S = W - rIns) for RTL paragraphs.
            let (box_l, box_r) = if p.rtl {
                (mr, col_w - x0)
            } else {
                (x0, col_w - mr)
            };
            let left = if filled {
                box_l
            } else {
                match align {
                    Align::Left => box_l,
                    Align::Right => box_r - line_w,
                    Align::Center => box_l + (box_r - box_l - line_w) / 2.0,
                    Align::Distributed if n <= 1 => box_l + slack / 2.0,
                    // Justified lines that aren't stretched (the last one) sit at the start edge.
                    Align::Justify | Align::JustLow | Align::Distributed if p.rtl => box_r - line_w,
                    Align::Justify | Align::JustLow | Align::Distributed => box_l,
                }
            };
            // Distance from the box's start edge to the text (bullets move with centred or
            // end-aligned text).
            let content_shift = if p.rtl {
                box_r - (left + line_w)
            } else {
                left - box_l
            };
            // Rules L1 + L2: this line's visual order.
            let chars: Vec<char> = line_cells.iter().map(|c| c.ch).collect();
            let raw_levels: Vec<u8> = line_cells.iter().map(|c| c.level).collect();
            let levels = bidi::line_levels(&chars, &raw_levels, u8::from(p.rtl));
            let order = bidi::visual_order(&levels);
            let mut edges = vec![(left, left); n];
            let mut vx = left;
            for &k in &order {
                let a = adv.get(k).copied().unwrap_or(0.0);
                if let Some(e) = edges.get_mut(k) {
                    *e = (vx, vx + a);
                }
                vx += a;
            }
            let odd = |k: usize| levels.get(k).is_some_and(|l| l % 2 == 1);
            let mut caret_x: Vec<f64> = (0..n)
                .map(|k| {
                    edges
                        .get(k)
                        .map(|e| if odd(k) { e.1 } else { e.0 })
                        .unwrap_or(left)
                })
                .collect();
            caret_x.push(match n.checked_sub(1) {
                Some(k) => edges
                    .get(k)
                    .map(|e| if odd(k) { e.0 } else { e.1 })
                    .unwrap_or(left),
                None if p.rtl => left + line_w,
                None => left,
            });
            let bullet = if li == 0 {
                p.bullet.as_ref().map(|(s, _)| {
                    // Centred and end-aligned text carries its bullet along.
                    let end_aligned = if p.rtl {
                        align == Align::Left
                    } else {
                        align == Align::Right
                    };
                    let shifted = align == Align::Center || end_aligned;
                    let b = if shifted && p.cells.is_empty() {
                        content_shift + x0 - bullet_w
                    } else {
                        (margin + indent).max(0.0) + if shifted { content_shift } else { 0.0 }
                    };
                    // x_bullet = S - (marL + indent) for RTL: the bullet's start edge is its right.
                    let bx = if p.rtl { col_w - b - bullet_w } else { b };
                    (s.clone(), bx, baseline)
                })
            } else {
                None
            };
            out.content_width = out.content_width.max(width + x0 + mr);
            let boundary: Vec<bool> = line_cells.iter().map(|c| c.boundary).collect();
            all_lines.push((
                LineInfo {
                    para: pi,
                    start: rl.start,
                    end: rl.end,
                    top,
                    baseline,
                    bottom: y,
                    caret_x,
                    column: 0,
                    rtl: p.rtl,
                    levels,
                    edges,
                    boundary,
                    extent: (left, left + line_w),
                    start_offset: x0,
                },
                LinePlace { order, kashida },
                lh,
                bullet,
            ));
        }
        out.para_lines.push((first_line_idx, raw.len()));
        prev_after = spacing_pts(props.space_after, p.lead_size, reduce).max(0.0);
    }
    let total = y;
    out.content_height = total;
    // Columns: distribute lines by height.
    let col_h = if ncols > 1 {
        inner.height()
    } else {
        f64::INFINITY
    };
    let mut col = 0usize;
    let mut col_y0 = 0.0;
    for (li, _, _, _) in all_lines.iter_mut() {
        if ncols > 1 && li.bottom - col_y0 > col_h + 0.01 && col + 1 < ncols {
            col += 1;
            col_y0 = li.top;
        }
        li.column = col;
        if col > 0 {
            let dy = col_y0;
            li.top -= dy;
            li.baseline -= dy;
            li.bottom -= dy;
            li.shift_x(col as f64 * (col_w + col_gap));
        }
    }
    let used_h = if ncols > 1 {
        all_lines.iter().map(|(l, ..)| l.bottom).fold(0.0, f64::max)
    } else {
        total
    };
    out.overflow = used_h > inner.height() + 0.5
        || (ncols > 1
            && all_lines
                .last()
                .is_some_and(|(l, ..)| l.bottom > inner.height() + 0.5));
    let anchor = bp.anchor.unwrap_or(Anchor::Top);
    let dy = match anchor {
        Anchor::Top | Anchor::Justified | Anchor::Distributed => 0.0,
        Anchor::Middle => (inner.height() - used_h) / 2.0,
        Anchor::Bottom => inner.height() - used_h,
    };
    // anchorCtr: centre the block horizontally.
    let dx = if bp.anchor_ctr.unwrap_or(false) {
        ((inner.width() - out.content_width) / 2.0).max(0.0)
    } else {
        0.0
    };
    let ox = inner.x0 + dx;
    let oy = inner.y0 + dy;
    // Emit runs, in visual order.
    for (line, place, _, bullet) in all_lines.iter_mut() {
        line.top += oy;
        line.baseline += oy;
        line.bottom += oy;
        line.shift_x(ox);
        let Some(p) = shaped_paras.get(line.para) else {
            continue;
        };
        if let Some((s, bx, by)) = bullet.take()
            && let Some((_, st)) = p.bullet.as_ref()
        {
            let (_, g) = measure_str(&st.face, st.size, &s);
            out.runs.push(GlyphRun {
                face: st.face.clone(),
                size: st.size,
                color: st.color,
                glyphs: g
                    .into_iter()
                    .map(|(gid, x)| {
                        (
                            gid,
                            ox + bx
                                + x
                                + if line.column > 0 {
                                    line.column as f64 * (col_w + col_gap)
                                } else {
                                    0.0
                                },
                            by + oy,
                        )
                    })
                    .collect(),
                cells: vec![],
                fake_bold: false,
                fake_italic: false,
                outline: None,
                para: line.para,
                chars: (0, 0),
                link: false,
                alpha: st.alpha,
                gradient: None,
                effects: None,
            });
        }
        // Group visually consecutive cells by (style, face).
        let mut cur: Option<GlyphRun> = None;
        let mut cur_key = (usize::MAX, usize::MAX);
        for &k in &place.order {
            let ci = line.start + k;
            let Some(cell) = p.cells.get(ci) else {
                continue;
            };
            let Some(st) = p.styles.get(cell.style) else {
                continue;
            };
            let Some(&(cx, cx1)) = line.edges.get(k) else {
                continue;
            };
            let base_y = line.baseline - st.baseline * st.size;
            let size = if st.baseline != 0.0 {
                st.size * SUB_SUPER
            } else {
                st.size
            };
            let size = if st.caps == Caps::Small && cell.ch.is_lowercase() {
                size * 0.8
            } else {
                size
            };
            let key = (cell.style, cell.face);
            if key != cur_key {
                if let Some(r) = cur.take() {
                    out.runs.push(r);
                }
                let Some(face) = p.faces.get(cell.face) else {
                    continue;
                };
                cur = Some(GlyphRun {
                    face: face.clone(),
                    size,
                    color: st.color,
                    glyphs: vec![],
                    cells: vec![],
                    fake_bold: st.fake_bold,
                    fake_italic: st.fake_italic,
                    outline: st.outline,
                    para: line.para,
                    chars: (ci, ci + 1),
                    link: st.link,
                    alpha: st.alpha,
                    gradient: st.gradient.clone(),
                    effects: st.effects,
                });
                cur_key = key;
            }
            if let Some(r) = cur.as_mut() {
                r.chars = (r.chars.0.min(ci), r.chars.1.max(ci + 1));
                if cell.head == ci && !cell.glyphs.is_empty() {
                    // The cluster's glyphs start at its leftmost cell; kashida (right-to-left
                    // only) fills the gap on the cluster's left with tatweel glyphs.
                    let cells_of = (k..line.end.saturating_sub(line.start))
                        .take_while(|&j| p.cells.get(line.start + j).is_some_and(|c| c.head == ci));
                    let (mut cl, mut kash) = (cx, 0.0);
                    for j in cells_of {
                        cl = cl.min(line.edges.get(j).map(|e| e.0).unwrap_or(cx));
                        kash += place.kashida.get(j).copied().unwrap_or(0.0);
                    }
                    if kash > 0.0 {
                        let face = p.faces.get(cell.face);
                        let tg = face.map(|f| f.glyph_for('\u{0640}')).unwrap_or(0);
                        let tw = face
                            .map(|f| f.advance(tg) * size / f.upem.max(1.0))
                            .unwrap_or(0.0);
                        if tg != 0 && tw > 0.0 {
                            let count = ((kash / tw).ceil() as usize).clamp(1, 256);
                            for i in 0..count {
                                r.glyphs.push((
                                    tg,
                                    cl + (i as f64 * tw).min((kash - tw).max(0.0)),
                                    base_y,
                                ));
                                r.cells.push((ci, cell.ch));
                            }
                        }
                    }
                    for (gid, gx, gy) in &cell.glyphs {
                        r.glyphs.push((*gid, cl + kash + gx, base_y + gy));
                        r.cells.push((ci, cell.ch));
                    }
                }
            }
            let adv = cx1 - cx;
            if adv <= 0.0 {
                continue;
            }
            if let Some(hl) = st.highlight {
                out.decos.push(Deco {
                    rect: Rect::new(cx, line.top, cx1, line.bottom),
                    color: hl,
                    behind: true,
                    para: line.para,
                });
            }
            if !cell.ch.is_whitespace() || st.underline.is_some() {
                if let Some(uc) = st.underline {
                    let t = (st.size * 0.06).max(0.5);
                    let uy = line.baseline + st.size * 0.12;
                    out.decos.push(Deco {
                        rect: Rect::new(cx, uy, cx1, uy + t),
                        color: uc,
                        behind: false,
                        para: line.para,
                    });
                }
                if let Some(sk) = st.strike {
                    let t = (st.size * 0.05).max(0.5);
                    let sy = line.baseline - st.size * 0.3;
                    out.decos.push(Deco {
                        rect: Rect::new(cx, sy, cx1, sy + t),
                        color: st.color,
                        behind: false,
                        para: line.para,
                    });
                    if sk == Strike::Double {
                        out.decos.push(Deco {
                            rect: Rect::new(cx, sy - t * 2.0, cx1, sy - t),
                            color: st.color,
                            behind: false,
                            para: line.para,
                        });
                    }
                }
            }
        }
        if let Some(r) = cur.take() {
            out.runs.push(r);
        }
    }
    out.boundaries = shaped_paras
        .iter()
        .map(|p| {
            let mut b: Vec<bool> = p.cells.iter().map(|c| c.boundary).collect();
            b.push(true);
            if let Some(f) = b.first_mut() {
                *f = true;
            }
            b
        })
        .collect();
    out.lines = all_lines.into_iter().map(|(l, ..)| l).collect();
    // Merge adjacent decorations of the same colour on the same line.
    out.decos = merge_decos(std::mem::take(&mut out.decos));
    out
}

fn merge_decos(v: Vec<Deco>) -> Vec<Deco> {
    let mut out: Vec<Deco> = Vec::with_capacity(v.len());
    for d in v {
        if let Some(last) = out.last_mut()
            && last.color == d.color
            && last.behind == d.behind
            && (last.rect.y0 - d.rect.y0).abs() < 0.01
            && (last.rect.y1 - d.rect.y1).abs() < 0.01
            && (last.rect.x1 - d.rect.x0).abs() < 0.5
        {
            last.rect.x1 = d.rect.x1;
            continue;
        }
        out.push(d);
    }
    out
}

/// How a line's cells are placed: visual order (indices from the line start) and kashida widths
/// (the boxes, with justification, are in [`LineInfo::edges`]).
struct LinePlace {
    order: Vec<usize>,
    kashida: Vec<f64>,
}

/// Kashida opportunities on a line (indices from the line start), at most one per word (its last
/// join, where elongation reads most naturally): the last cell of a right-to-left Arabic grapheme
/// that joins the next letter, in a face with a tatweel glyph, when the two aren't one ligature.
fn kashida_opportunities(p: &ParaShaped, start: usize, end: usize) -> Vec<usize> {
    let mut out: Vec<usize> = Vec::new();
    let mut word_has = false;
    for i in start..end {
        let Some(c) = p.cells.get(i) else { continue };
        if c.ch.is_whitespace() {
            word_has = false;
            continue;
        }
        if !c.boundary || c.level % 2 == 0 || !joins_following(c.ch) {
            continue;
        }
        // The next grapheme on the line.
        let Some(nx) = (i + 1..end).find(|&j| p.cells.get(j).is_some_and(|d| d.boundary)) else {
            continue;
        };
        let Some(d) = p.cells.get(nx) else { continue };
        let same_cluster = d.head == c.head || d.head != nx;
        let tatweel = p
            .faces
            .get(c.face)
            .is_some_and(|f| f.glyph_for('\u{0640}') != 0);
        if joins_preceding(d.ch) && d.face == c.face && !same_cluster && tatweel {
            // A later join in the same word replaces the earlier one.
            if word_has {
                out.pop();
            }
            out.push(nx - 1 - start);
            word_has = true;
        }
    }
    out
}

/// Which side of a boundary a caret belongs to: `Downstream` sticks to the character after it
/// (the default), `Upstream` to the character before it, which differs at direction changes and
/// at the end of a wrapped line.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Affinity {
    Upstream,
    #[default]
    Downstream,
}

/// Caret movement: through the text order, or across the screen.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum MoveMode {
    /// Next/previous grapheme in logical order (`forward` = towards the end of the text).
    #[default]
    Logical,
    /// Next grapheme boundary to the right/left on screen (`forward` = right).
    Visual,
}

impl LineInfo {
    fn len(&self) -> usize {
        self.end.saturating_sub(self.start)
    }
    fn odd(&self, k: usize) -> bool {
        self.levels.get(k).is_some_and(|l| l % 2 == 1)
    }
    /// Leading edge (where its direction begins) of character `k` of the line.
    fn leading(&self, k: usize) -> Option<f64> {
        self.edges
            .get(k)
            .map(|e| if self.odd(k) { e.1 } else { e.0 })
    }
    /// Trailing edge (where its direction ends) of character `k` of the line.
    fn trailing(&self, k: usize) -> Option<f64> {
        self.edges
            .get(k)
            .map(|e| if self.odd(k) { e.0 } else { e.1 })
    }
    fn shift_x(&mut self, dx: f64) {
        for x in &mut self.caret_x {
            *x += dx;
        }
        for e in &mut self.edges {
            e.0 += dx;
            e.1 += dx;
        }
        self.extent.0 += dx;
        self.extent.1 += dx;
    }
    /// Graphemes on the line as (first, end) character indices from the line start.
    fn graphemes(&self) -> Vec<(usize, usize)> {
        let n = self.len();
        let mut out = Vec::new();
        let mut k = 0;
        while k < n {
            let mut e = k + 1;
            while e < n && !self.boundary.get(e).copied().unwrap_or(true) {
                e += 1;
            }
            out.push((k, e));
            k = e;
        }
        out
    }
    /// Visual extent of characters `from..to` (k from the line start).
    fn grapheme_box(&self, from: usize, to: usize) -> Option<(f64, f64)> {
        let es = self.edges.get(from..to)?;
        let l = es.iter().map(|e| e.0).fold(f64::INFINITY, f64::min);
        let r = es.iter().map(|e| e.1).fold(f64::NEG_INFINITY, f64::max);
        (l <= r).then_some((l, r))
    }
    /// Visual x intervals covering paragraph characters `from..to` on this line, left to right
    /// and merged where they touch. Bidi text can make a logical range several boxes.
    pub fn spans(&self, from: usize, to: usize) -> Vec<(f64, f64)> {
        let a = from.max(self.start) - self.start;
        let b = to.min(self.end).saturating_sub(self.start);
        merge_spans(self.edges.get(a..b.max(a)).unwrap_or(&[]).to_vec())
    }
    /// Horizontal extent of paragraph characters `from..to` on this line.
    pub fn span(&self, from: usize, to: usize) -> Option<(f64, f64)> {
        let s = self.spans(from, to);
        Some((s.first()?.0, s.last()?.1))
    }
    /// Caret stops left to right: (x, character offset in the paragraph, affinity).
    fn visual_stops(&self) -> Vec<(f64, usize, Affinity)> {
        let mut gs: Vec<(f64, f64, usize, usize, bool)> = self
            .graphemes()
            .into_iter()
            .filter_map(|(a, b)| {
                self.grapheme_box(a, b)
                    .map(|(l, r)| (l, r, a, b, self.odd(a)))
            })
            .collect();
        gs.sort_by(|x, y| x.0.total_cmp(&y.0));
        let mut out: Vec<(f64, usize, Affinity)> = Vec::with_capacity(gs.len() * 2 + 1);
        let mut push = |s: (f64, usize, Affinity)| {
            if !out
                .last()
                .is_some_and(|l: &(f64, usize, Affinity)| (l.0 - s.0).abs() < 0.01 && l.1 == s.1)
            {
                out.push(s);
            }
        };
        for (l, r, a, b, rtl) in gs {
            let (a, b) = (self.start + a, self.start + b);
            if rtl {
                push((l, b, Affinity::Upstream));
                push((r, a, Affinity::Downstream));
            } else {
                push((l, a, Affinity::Downstream));
                push((r, b, Affinity::Upstream));
            }
        }
        if out.is_empty() {
            out.push((
                self.caret_x.first().copied().unwrap_or(0.0),
                self.start,
                Affinity::Downstream,
            ));
        }
        out
    }
}

/// Non-empty x intervals sorted left to right, merged where they touch.
fn merge_spans(mut v: Vec<(f64, f64)>) -> Vec<(f64, f64)> {
    v.retain(|e| e.1 > e.0);
    v.sort_by(|x, y| x.0.total_cmp(&y.0));
    let mut out: Vec<(f64, f64)> = Vec::with_capacity(v.len());
    for e in v {
        match out.last_mut() {
            Some(last) if e.0 <= last.1 + 0.01 => last.1 = last.1.max(e.1),
            _ => out.push(e),
        }
    }
    out
}

/// A caret position: paragraph and character offset within it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pos {
    pub para: usize,
    pub ch: usize,
}

impl TextLayout {
    /// The line containing a caret position (the later line at a soft wrap boundary).
    pub fn line_of(&self, pos: Pos) -> Option<usize> {
        self.line_of_affine(pos, Affinity::Downstream)
    }
    /// The line containing a caret position: at a soft wrap boundary, the earlier line for an
    /// upstream caret and the later one for a downstream caret.
    pub fn line_of_affine(&self, pos: Pos, affinity: Affinity) -> Option<usize> {
        let mut found = None;
        for (i, l) in self.lines.iter().enumerate() {
            if l.para == pos.para && pos.ch >= l.start && pos.ch <= l.end {
                if affinity == Affinity::Upstream && pos.ch == l.end && pos.ch > l.start {
                    return Some(i);
                }
                found = Some(i);
                if pos.ch < l.end {
                    break;
                }
            }
        }
        found
            .or_else(|| {
                self.lines
                    .iter()
                    .rposition(|l| l.para == pos.para && l.start <= pos.ch)
            })
            .or_else(|| self.lines.iter().rposition(|l| l.para == pos.para))
    }
    /// Caret line segment (x, top, bottom) in shape-local, unrotated coordinates (downstream).
    pub fn caret(&self, pos: Pos) -> Option<(f64, f64, f64)> {
        self.caret_at(pos, Affinity::Downstream)
    }
    /// Caret line segment (x, top, bottom) for a position and affinity: downstream at the leading
    /// edge of the character after the boundary, upstream at the trailing edge of the one before.
    pub fn caret_at(&self, pos: Pos, affinity: Affinity) -> Option<(f64, f64, f64)> {
        let li = self.line_of_affine(pos, affinity)?;
        let l = self.lines.get(li)?;
        let k = pos.ch.clamp(l.start, l.end) - l.start;
        let x = match affinity {
            Affinity::Downstream if k < l.len() => l.leading(k),
            Affinity::Upstream if k > 0 => l.trailing(k - 1),
            _ => None,
        };
        let x = x
            .or_else(|| l.caret_x.get(k).copied())
            .or(l.caret_x.last().copied())?;
        Some((x, l.top, l.bottom))
    }
    /// Nearest caret position for a point.
    pub fn hit(&self, p: Point) -> Pos {
        self.hit_affinity(p).0
    }
    /// Nearest caret position for a point, with the affinity that keeps the caret on the side of
    /// the character that was hit (bidi text has two carets at a direction change).
    pub fn hit_affinity(&self, p: Point) -> (Pos, Affinity) {
        let mut best: Option<&LineInfo> = None;
        for l in &self.lines {
            if p.y >= l.top && p.y < l.bottom {
                // In multi-column bodies pick the line whose column contains x.
                if best.is_none()
                    || p.x
                        >= l.extent
                            .0
                            .min(l.caret_x.first().copied().unwrap_or(l.extent.0))
                            - 4.0
                {
                    best = Some(l);
                }
            }
        }
        let l = match best {
            Some(l) => l,
            None => {
                let first = self.lines.first();
                let last = self.lines.last();
                match (first, last) {
                    (Some(f), _) if p.y < f.top => f,
                    (_, Some(l)) => l,
                    _ => return (Pos::default(), Affinity::Downstream),
                }
            }
        };
        let mut gs: Vec<(f64, f64, usize, usize, bool)> = l
            .graphemes()
            .into_iter()
            .filter_map(|(a, b)| {
                l.grapheme_box(a, b)
                    .map(|(x0, x1)| (x0, x1, a, b, l.odd(a)))
            })
            .collect();
        if gs.is_empty() {
            return (
                Pos {
                    para: l.para,
                    ch: l.start,
                },
                Affinity::Downstream,
            );
        }
        gs.sort_by(|x, y| x.0.total_cmp(&y.0));
        let hit = gs
            .iter()
            .find(|g| p.x >= g.0 && p.x <= g.1 && g.1 > g.0)
            .copied();
        let (g, left_half) = match hit {
            Some(g) => (g, p.x < (g.0 + g.1) / 2.0),
            None => match (gs.first().copied(), gs.last().copied()) {
                (Some(f), _) if p.x < f.0 => (f, true),
                (_, Some(z)) if p.x > z.1 => (z, false),
                // Between zero-width graphemes: the nearest one.
                _ => match gs
                    .iter()
                    .min_by(|a, b| {
                        ((a.0 + a.1) / 2.0 - p.x)
                            .abs()
                            .total_cmp(&((b.0 + b.1) / 2.0 - p.x).abs())
                    })
                    .copied()
                {
                    Some(g) => (g, p.x < (g.0 + g.1) / 2.0),
                    None => {
                        return (
                            Pos {
                                para: l.para,
                                ch: l.start,
                            },
                            Affinity::Downstream,
                        );
                    }
                },
            },
        };
        let (_, _, a, b, rtl) = g;
        let (before, after) = (
            Pos {
                para: l.para,
                ch: l.start + a,
            },
            Pos {
                para: l.para,
                ch: l.start + b,
            },
        );
        // The leading half of a character puts the caret before it, the trailing half after it.
        if left_half != rtl {
            (before, Affinity::Downstream)
        } else {
            (after, Affinity::Upstream)
        }
    }
    /// Move a caret one grapheme: logically (`forward` = towards the end of the text, crossing
    /// paragraphs) or visually (`forward` = to the right on screen, continuing on the next or
    /// previous line in the paragraph's direction at the line's edge).
    pub fn move_caret(
        &self,
        pos: Pos,
        affinity: Affinity,
        forward: bool,
        mode: MoveMode,
    ) -> (Pos, Affinity) {
        if mode == MoveMode::Visual
            && let Some(li) = self.line_of_affine(pos, affinity)
            && let Some(l) = self.lines.get(li)
        {
            let stops = l.visual_stops();
            let cur_x = self.caret_at(pos, affinity).map(|c| c.0).unwrap_or(0.0);
            let idx = stops
                .iter()
                .position(|s| s.1 == pos.ch && s.2 == affinity)
                .or_else(|| stops.iter().position(|s| s.1 == pos.ch))
                .or_else(|| {
                    stops
                        .iter()
                        .enumerate()
                        .min_by(|a, b| (a.1.0 - cur_x).abs().total_cmp(&(b.1.0 - cur_x).abs()))
                        .map(|(i, _)| i)
                });
            if let Some(idx) = idx {
                let mut j = idx;
                loop {
                    let next = if forward {
                        j.checked_add(1)
                    } else {
                        j.checked_sub(1)
                    };
                    let Some(nj) = next else { break };
                    let Some(s) = stops.get(nj) else { break };
                    // Skip stops that wouldn't move the caret on screen or in the text.
                    if s.1 != pos.ch && (s.0 - cur_x).abs() > 0.01 {
                        return (
                            Pos {
                                para: l.para,
                                ch: s.1,
                            },
                            s.2,
                        );
                    }
                    j = nj;
                }
            }
            // Off the line's edge: on to the neighbouring line in reading order.
            let logical_forward = forward != l.rtl;
            let target = if logical_forward {
                li.checked_add(1)
            } else {
                li.checked_sub(1)
            };
            return match target.and_then(|t| self.lines.get(t)) {
                Some(t) if logical_forward => (
                    Pos {
                        para: t.para,
                        ch: t.start,
                    },
                    Affinity::Downstream,
                ),
                Some(t) => (
                    Pos {
                        para: t.para,
                        ch: t.end,
                    },
                    if t.para == l.para {
                        Affinity::Upstream
                    } else {
                        Affinity::Downstream
                    },
                ),
                None => (pos, affinity),
            };
        }
        let Some(b) = self.boundaries.get(pos.para) else {
            return (pos, affinity);
        };
        let len = b.len().saturating_sub(1);
        let ch = pos.ch.min(len);
        let next = if forward {
            (ch + 1..=len).find(|&k| b.get(k).copied().unwrap_or(true))
        } else {
            (0..ch).rev().find(|&k| b.get(k).copied().unwrap_or(true))
        };
        match next {
            Some(k) => (
                Pos {
                    para: pos.para,
                    ch: k,
                },
                Affinity::Downstream,
            ),
            None if forward && pos.para + 1 < self.boundaries.len() => (
                Pos {
                    para: pos.para + 1,
                    ch: 0,
                },
                Affinity::Downstream,
            ),
            None if !forward && pos.para > 0 => {
                let prev = pos.para - 1;
                (
                    Pos {
                        para: prev,
                        ch: self
                            .boundaries
                            .get(prev)
                            .map(|b| b.len().saturating_sub(1))
                            .unwrap_or(0),
                    },
                    Affinity::Downstream,
                )
            }
            None => (Pos { para: pos.para, ch }, Affinity::Downstream),
        }
    }
    /// Selection highlight rectangles between two positions: per line, the union of the visual
    /// boxes of the selected characters (one logical range can be several boxes in bidi text).
    pub fn selection_rects(&self, a: Pos, b: Pos) -> Vec<Rect> {
        let (s, e) = if a <= b { (a, b) } else { (b, a) };
        let mut out = vec![];
        for l in &self.lines {
            let lp = Pos {
                para: l.para,
                ch: l.start,
            };
            let le = Pos {
                para: l.para,
                ch: l.end,
            };
            if le < s || lp > e {
                continue;
            }
            let from = if s > lp { s.ch } else { l.start };
            let to = if e < le { e.ch } else { l.end };
            let mut spans = l.spans(from, to);
            // Selecting across a paragraph end shows a small extra box for the newline, at the
            // paragraph's end side.
            if e.para > l.para && to == l.end {
                let end_x = l.caret_x.last().copied().unwrap_or(l.extent.1);
                spans.push(if l.rtl {
                    (end_x - 6.0, end_x)
                } else {
                    (end_x, end_x + 6.0)
                });
                spans = merge_spans(spans);
            }
            for (x0, x1) in spans {
                if x1 > x0 {
                    out.push(Rect::new(x0, l.top, x1, l.bottom));
                }
            }
        }
        out
    }
    /// Underlines for text an input method is composing, from `a` to `b` (#101): `(x0, x1, y)` per
    /// visual span, a little below each line's baseline (PowerPoint underlines the composition
    /// in place). A composition that wraps gets one underline per line.
    pub fn composition_underlines(&self, a: Pos, b: Pos) -> Vec<(f64, f64, f64)> {
        let (s, e) = if a <= b { (a, b) } else { (b, a) };
        let mut out = vec![];
        if s == e {
            return out;
        }
        for l in &self.lines {
            let lp = Pos {
                para: l.para,
                ch: l.start,
            };
            let le = Pos {
                para: l.para,
                ch: l.end,
            };
            if le <= s || lp >= e {
                continue;
            }
            let from = if s > lp { s.ch } else { l.start };
            let to = if e < le { e.ch } else { l.end };
            // Under the baseline, in the descent, never below the line.
            let y = (l.baseline + (l.bottom - l.baseline) * 0.35).min(l.bottom);
            for (x0, x1) in l.spans(from, to) {
                if x1 > x0 {
                    out.push((x0, x1, y));
                }
            }
        }
        out
    }
    /// Vertical caret movement: the position on the line above/below closest to `x`.
    pub fn vertical(&self, pos: Pos, down: bool, x: f64) -> Pos {
        self.vertical_affine(pos, Affinity::Downstream, down, x).0
    }
    /// The line a caret is on. An upstream caret at the start of a soft-wrapped line (where End
    /// leaves it, after the previous line's trailing spaces) belongs to the line before.
    pub fn line_index(&self, pos: Pos, affinity: Affinity) -> Option<usize> {
        if affinity == Affinity::Upstream && pos.ch > 0 {
            for (i, w) in self.lines.windows(2).enumerate() {
                if let [a, b] = w
                    && b.para == pos.para
                    && a.para == pos.para
                    && b.start == pos.ch
                {
                    return Some(i);
                }
            }
        }
        self.line_of_affine(pos, affinity)
    }
    /// Up/Down from a caret with its affinity: the position on the line above/below nearest `x`.
    pub fn vertical_affine(
        &self,
        pos: Pos,
        affinity: Affinity,
        down: bool,
        x: f64,
    ) -> (Pos, Affinity) {
        let Some(li) = self.line_index(pos, affinity) else {
            return (pos, affinity);
        };
        let target = if down {
            li.checked_add(1)
        } else {
            li.checked_sub(1)
        };
        let Some(l) = target.and_then(|t| self.lines.get(t)) else {
            return (pos, affinity);
        };
        let p = Point::new(x, (l.top + l.bottom) / 2.0);
        let mut h = self.hit(p);
        if h.para != l.para {
            h.para = l.para;
        }
        h.ch = h.ch.clamp(l.start, l.end);
        (h, Affinity::Downstream)
    }
    /// Start/end of the visual line containing `pos` (logical: Home/End).
    pub fn line_bounds(&self, pos: Pos) -> (Pos, Pos) {
        self.line_bounds_affine(pos, Affinity::Downstream)
    }
    /// Start/end of the visual line a caret with this affinity is on.
    pub fn line_bounds_affine(&self, pos: Pos, affinity: Affinity) -> (Pos, Pos) {
        match self
            .line_index(pos, affinity)
            .and_then(|i| self.lines.get(i))
        {
            Some(l) => (
                Pos {
                    para: l.para,
                    ch: l.start,
                },
                Pos {
                    para: l.para,
                    ch: l.end,
                },
            ),
            None => (pos, pos),
        }
    }
    /// Where End puts the caret: after a soft wrap, past the line's trailing spaces at the start
    /// of the next line with upstream affinity (so it is still drawn on this line), else the end
    /// of the paragraph.
    pub fn line_end_caret(&self, pos: Pos, affinity: Affinity) -> (Pos, Affinity) {
        let Some(li) = self.line_index(pos, affinity) else {
            return (pos, Affinity::Downstream);
        };
        let Some(l) = self.lines.get(li) else {
            return (pos, Affinity::Downstream);
        };
        match self.lines.get(li + 1) {
            Some(n) if n.para == l.para && n.start > l.start => (
                Pos {
                    para: l.para,
                    ch: n.start,
                },
                Affinity::Upstream,
            ),
            _ => (
                Pos {
                    para: l.para,
                    ch: l.end,
                },
                Affinity::Downstream,
            ),
        }
    }
    /// The caret to draw (x, top, bottom): an upstream caret after a soft wrap is drawn at the end
    /// of the line it belongs to.
    pub fn caret_drawn(&self, pos: Pos, affinity: Affinity) -> Option<(f64, f64, f64)> {
        let li = self.line_index(pos, affinity)?;
        let l = self.lines.get(li)?;
        if pos.ch > l.end {
            let x = l.caret_x.last().copied()?;
            return Some((x, l.top, l.bottom));
        }
        self.caret_at(pos, affinity)
    }
    /// Bounding box of all glyphs/lines (shape-local).
    pub fn bounds(&self) -> Rect {
        let mut r: Option<Rect> = None;
        for l in &self.lines {
            let lr = Rect::new(l.extent.0, l.top, l.extent.1.max(l.extent.0), l.bottom);
            r = Some(r.map(|a| a.union(lr)).unwrap_or(lr));
        }
        r.unwrap_or(self.inner)
    }
}

/// Height the shape needs so its text fits (Resize shape to fit text): text height + insets.
pub fn fit_height(
    ctx: &Ctx,
    shape: &Shape,
    body: &TextBody,
    rect: Rect,
    fields: &dyn Fields,
) -> f64 {
    let bp = resolve::body(ctx, shape);
    let l = layout(
        ctx,
        shape,
        body,
        &Opts {
            rect,
            fields,
            prompt_color: None,
            no_shrink: true,
        },
    );
    l.content_height + bp.inset_t.unwrap_or(3.6) + bp.inset_b.unwrap_or(3.6)
}

/// Width a non-wrapping text box needs.
pub fn fit_width(
    ctx: &Ctx,
    shape: &Shape,
    body: &TextBody,
    rect: Rect,
    fields: &dyn Fields,
) -> f64 {
    let bp = resolve::body(ctx, shape);
    let wide = Rect::new(rect.x0, rect.y0, rect.x0 + 100_000.0, rect.y1);
    let mut s2 = shape.clone();
    if let Some(t) = s2.text.as_mut() {
        t.body.wrap = Some(false);
    }
    let l = layout(
        ctx,
        &s2,
        body,
        &Opts {
            rect: wide,
            fields,
            prompt_color: None,
            no_shrink: true,
        },
    );
    let w = l
        .lines
        .iter()
        .map(|li| li.start_offset + (li.extent.1 - li.extent.0))
        .fold(0.0, f64::max);
    w + bp.inset_l.unwrap_or(7.2) + bp.inset_r.unwrap_or(7.2) + 1.0
}

#[cfg(test)]
mod tests;