waft-widgets 0.8.1

Widget framework and widgets for Waft
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
//! Flutter counterpart: `widgets/text.dart`, plus the public `RichText` from `basic.dart`.
//!
//! [`Text`] builds [`RichText`]. Under a [`SelectionContainer`], as under a `SelectableRegion`,
//! it builds a container of its own: a `SelectableTextContainer` whose delegate handles the
//! paragraph's selection, over the foundation in `selectable_region.rs`. `Locale` and `Semantics`
//! wait; see `PORTING.md`.

use std::cmp::Ordering;

use waft_embedder::{Color, FontWeight, TextAlign, TextDirection, TextHeightBehavior};
use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, Ref};
use waft_painting::{
    InlineSpanRef, StrutStyle, TextOverflow, TextScaler, TextSpan, TextStyle, TextWidthBasis,
    transform_rect,
};
use waft_rendering::{
    AnyRenderObject, AnySelectable, RenderBox, RenderHandle, RenderParagraph, SelectedContentRange,
    SelectionEvent, SelectionGeometry, SelectionHandler, SelectionRegistrar, SelectionRegistrarRef,
    SelectionResult,
};
use waft_services::SystemMouseCursors;

use crate::framework::{
    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, MultiChildRenderObjectWidget,
    RenderObjectWidget, State, StateData, StatefulWidget, StatelessWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::{Builder, Directionality, ExcludeSemantics, MouseRegion, Semantics};
use crate::widgets::default_selection_style::DefaultSelectionStyle;
use crate::widgets::inherited_theme::InheritedTheme;
use crate::widgets::media_query::MediaQuery;
use crate::widgets::selectable_region::{
    MultiSelectableSelectionContainerDelegate, MultiSelectableSelectionContainerDelegateBase,
    MultiSelectableSelectionContainerDelegateData, StaticSelectionContainerDelegate,
    StaticSelectionContainerDelegateBase, StaticSelectionContainerDelegateData,
    compare_horizontally, compare_vertically,
};
use crate::widgets::selection_container::{
    SelectionContainer, SelectionContainerDelegate, SelectionContainerDelegateData,
};
use crate::widgets::widget_span::WidgetSpan;

// ---------------------------------------------------------------------------------------------
// DefaultTextStyle

/// The text style to apply to descendant [`Text`] widgets which don't have an explicit style.
///
/// A `MediaQuery` ancestor of a [`Text`] widget may still override the `TextStyle.height`,
/// `TextStyle.letterSpacing`, and `TextStyle.wordSpacing` of the [`TextStyle`] set by this
/// [`DefaultTextStyle`] widget through its `MediaQueryData.lineHeightScaleFactorOverride`,
/// `MediaQueryData.letterSpacingOverride`, and `MediaQueryData.wordSpacingOverride` members.
///
/// See also:
///
///  * `AnimatedDefaultTextStyle`, which animates changes in the text style smoothly over a
///    given duration.
///  * `DefaultTextStyleTransition`, which takes a provided `Animation` to animate changes in
///    text style smoothly over time.
///
/// Dart's named constructor arguments are the fluent setters
/// (`DefaultTextStyle::new(style, child).max_lines(2)`).
#[derive(Clone, Debug)]
pub struct DefaultTextStyle {
    /// See [`InheritedWidget::key`].
    pub key: Option<KeyRef>,
    /// The text style to apply.
    pub style: TextStyle,
    /// How each line of text in the Text widget should be aligned horizontally.
    pub text_align: Option<TextAlign>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    ///
    /// This also decides the `overflow` property's behavior. If this is true or null, the
    /// glyph causing overflow, and those that follow, will not be rendered.
    pub soft_wrap: bool,
    /// How visual overflow should be handled.
    ///
    /// If `soft_wrap` is true or null, the glyph causing overflow, and those that follow,
    /// will not be rendered. Otherwise, it will be shown with the given overflow option.
    pub overflow: TextOverflow,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    ///
    /// If this is non-null, it will override even explicit null values of `Text.max_lines`.
    pub max_lines: Option<i32>,
    /// The strategy to use when calculating the width of the Text.
    ///
    /// See [`TextWidthBasis`] for possible values and their implications.
    pub text_width_basis: TextWidthBasis,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl DefaultTextStyle {
    /// Creates a default text style for the given subtree.
    ///
    /// Consider using `DefaultTextStyle.merge` to inherit styling information from the
    /// current default text style for a given [`BuildContext`].
    ///
    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
    /// not `None`, it must be greater than zero.
    pub fn new<K>(style: TextStyle, child: impl IntoWidget<K>) -> DefaultTextStyle {
        DefaultTextStyle {
            key: None,
            style,
            text_align: None,
            soft_wrap: true,
            overflow: TextOverflow::Clip,
            max_lines: None,
            text_width_basis: TextWidthBasis::Parent,
            text_height_behavior: None,
            child: child.into_widget(),
        }
    }

    /// A default text style that provides fallback values.
    ///
    /// Returned from [`of`](Self::of) when the given [`BuildContext`] doesn't have an
    /// enclosing default text style.
    ///
    /// This constructor creates a [`DefaultTextStyle`] with an invalid `child`, which means
    /// the constructed value cannot be incorporated into the tree.
    pub fn fallback() -> DefaultTextStyle {
        DefaultTextStyle::new(TextStyle::new(), NullWidget)
    }

    /// Creates a default text style that overrides the text styles in scope at this point in
    /// the widget tree.
    ///
    /// The given `style` is merged with the `style` from the default text style for the
    /// [`BuildContext`] where the widget is inserted, and any of the other arguments that are
    /// not `None` replace the corresponding properties on that same default text style.
    ///
    /// This constructor cannot be used to override the `max_lines` property of the ancestor
    /// with the value `None`, since `None` here is used to mean "defer to ancestor". To
    /// replace a non-`None` `max_lines` from an ancestor with the `None` value (to remove the
    /// restriction on number of lines), manually obtain the ambient [`DefaultTextStyle`]
    /// using [`of`](Self::of), then create a new [`DefaultTextStyle`] using
    /// [`new`](Self::new) directly.
    ///
    /// If a `text_height_behavior` is provided, the existing configuration will be replaced
    /// completely. To retain part of the original `text_height_behavior`, manually obtain the
    /// ambient [`DefaultTextStyle`] using [`of`](Self::of).
    ///
    /// Dart's optional named arguments are the setters of the [`DefaultTextStyleMerge`] this
    /// returns.
    pub fn merge<K>(child: impl IntoWidget<K>) -> DefaultTextStyleMerge {
        DefaultTextStyleMerge {
            key: None,
            style: None,
            text_align: None,
            soft_wrap: None,
            overflow: None,
            max_lines: None,
            text_width_basis: None,
            text_height_behavior: None,
            child: child.into_widget(),
        }
    }

    /// Dart `DefaultTextStyle(key:)`.
    pub fn key(mut self, key: KeyRef) -> DefaultTextStyle {
        self.key = Some(key);
        self
    }

    /// Dart `DefaultTextStyle(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyle {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `DefaultTextStyle(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyle {
        self.soft_wrap = soft_wrap;
        self
    }

    /// Dart `DefaultTextStyle(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyle {
        self.overflow = overflow;
        self
    }

    /// Dart `DefaultTextStyle(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyle {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `DefaultTextStyle(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyle {
        self.text_width_basis = text_width_basis;
        self
    }

    /// Dart `DefaultTextStyle(textHeightBehavior:)`.
    pub fn text_height_behavior(
        mut self,
        text_height_behavior: TextHeightBehavior,
    ) -> DefaultTextStyle {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }

    /// The closest instance of this class that encloses the given context.
    ///
    /// If no such instance exists, returns an instance created by
    /// [`fallback`](Self::fallback), which contains fallback values.
    ///
    /// Typical usage is as follows:
    ///
    /// ```text
    /// let style = DefaultTextStyle::of(app, context);
    /// ```
    pub fn of(app: &mut App, context: BuildContext) -> DefaultTextStyle {
        context
            .depend_on_inherited_widget_of_exact_type::<DefaultTextStyle>(app)
            .cloned()
            .unwrap_or_else(DefaultTextStyle::fallback)
    }
}

/// Dart's `DefaultTextStyle.merge(..)` before its optional arguments are known: a `Builder`
/// that merges them into the ambient [`DefaultTextStyle`].
#[derive(Debug)]
pub struct DefaultTextStyleMerge {
    key: Option<KeyRef>,
    style: Option<TextStyle>,
    text_align: Option<TextAlign>,
    soft_wrap: Option<bool>,
    overflow: Option<TextOverflow>,
    max_lines: Option<i32>,
    text_width_basis: Option<TextWidthBasis>,
    text_height_behavior: Option<TextHeightBehavior>,
    child: WidgetRef,
}

impl DefaultTextStyleMerge {
    /// Dart `DefaultTextStyle.merge(key:)`.
    pub fn key(mut self, key: KeyRef) -> DefaultTextStyleMerge {
        self.key = Some(key);
        self
    }

    /// Dart `DefaultTextStyle.merge(style:)`.
    pub fn style(mut self, style: TextStyle) -> DefaultTextStyleMerge {
        self.style = Some(style);
        self
    }

    /// Dart `DefaultTextStyle.merge(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> DefaultTextStyleMerge {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `DefaultTextStyle.merge(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> DefaultTextStyleMerge {
        self.soft_wrap = Some(soft_wrap);
        self
    }

    /// Dart `DefaultTextStyle.merge(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> DefaultTextStyleMerge {
        self.overflow = Some(overflow);
        self
    }

    /// Dart `DefaultTextStyle.merge(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> DefaultTextStyleMerge {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `DefaultTextStyle.merge(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> DefaultTextStyleMerge {
        self.text_width_basis = Some(text_width_basis);
        self
    }

    /// Dart `DefaultTextStyle.merge(textHeightBehavior:)`.
    pub fn text_height_behavior(
        mut self,
        text_height_behavior: TextHeightBehavior,
    ) -> DefaultTextStyleMerge {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }
}

/// The kind tag of [`IntoWidget`] for a [`DefaultTextStyleMerge`].
pub struct DefaultTextStyleMergeKind;

impl IntoWidget<DefaultTextStyleMergeKind> for DefaultTextStyleMerge {
    fn into_widget(self) -> WidgetRef {
        Builder::new(move |app, context| {
            let parent = DefaultTextStyle::of(app, context);
            DefaultTextStyle {
                key: self.key.clone(),
                style: parent.style.merge(self.style.as_ref()),
                text_align: self.text_align.or(parent.text_align),
                soft_wrap: self.soft_wrap.unwrap_or(parent.soft_wrap),
                overflow: self.overflow.unwrap_or(parent.overflow),
                max_lines: self.max_lines.or(parent.max_lines),
                text_width_basis: self.text_width_basis.unwrap_or(parent.text_width_basis),
                text_height_behavior: self.text_height_behavior.or(parent.text_height_behavior),
                child: self.child.clone(),
            }
            .into_widget()
        })
        .into_widget()
    }
}

impl InheritedWidget for DefaultTextStyle {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &DefaultTextStyle) -> bool {
        self.style != old_widget.style
            || self.text_align != old_widget.text_align
            || self.soft_wrap != old_widget.soft_wrap
            || self.overflow != old_widget.overflow
            || self.max_lines != old_widget.max_lines
            || self.text_width_basis != old_widget.text_width_basis
            || self.text_height_behavior != old_widget.text_height_behavior
    }

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        Some(self)
    }
}

impl InheritedTheme for DefaultTextStyle {
    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
        DefaultTextStyle {
            key: None,
            style: self.style.clone(),
            text_align: self.text_align,
            soft_wrap: self.soft_wrap,
            overflow: self.overflow,
            max_lines: self.max_lines,
            text_width_basis: self.text_width_basis,
            text_height_behavior: self.text_height_behavior,
            child,
        }
        .into_widget()
    }
}

/// Dart's `_NullWidget`: the child of [`DefaultTextStyle::fallback`], which must never build.
#[derive(Debug)]
struct NullWidget;

impl StatelessWidget for NullWidget {
    fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        panic!(
            "A DefaultTextStyle constructed with DefaultTextStyle::fallback cannot be \
             incorporated into the widget tree, it is meant only to provide a fallback value \
             returned by DefaultTextStyle::of() when no enclosing default text style is \
             present in a BuildContext."
        );
    }
}

// ---------------------------------------------------------------------------------------------
// DefaultTextHeightBehavior

/// The [`TextHeightBehavior`] that will apply to descendant [`Text`] and `EditableText`
/// widgets which have not explicitly set `Text.text_height_behavior`.
///
/// If there is a [`DefaultTextStyle`] with a non-null `DefaultTextStyle.text_height_behavior`
/// below this widget, the `DefaultTextStyle.text_height_behavior` will be used over this
/// widget's [`TextHeightBehavior`].
///
/// See also:
///
///  * [`DefaultTextStyle`], which defines a [`TextStyle`] to apply to descendant [`Text`]
///    widgets.
#[derive(Debug)]
pub struct DefaultTextHeightBehavior {
    /// See [`InheritedWidget::key`].
    pub key: Option<KeyRef>,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: TextHeightBehavior,
    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl DefaultTextHeightBehavior {
    /// Creates a default text height behavior for the given subtree.
    pub fn new<K>(
        text_height_behavior: TextHeightBehavior,
        child: impl IntoWidget<K>,
    ) -> DefaultTextHeightBehavior {
        DefaultTextHeightBehavior {
            key: None,
            text_height_behavior,
            child: child.into_widget(),
        }
    }

    /// Dart `DefaultTextHeightBehavior(key:)`.
    pub fn key(mut self, key: KeyRef) -> DefaultTextHeightBehavior {
        self.key = Some(key);
        self
    }

    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
    /// context, or `None` if none is found.
    ///
    /// Calling this method will create a dependency on the closest
    /// [`DefaultTextHeightBehavior`] in the `context`, if there is one.
    ///
    /// See also:
    ///
    /// * [`of`](Self::of), which is similar to this method, but asserts if no
    ///   [`DefaultTextHeightBehavior`] ancestor is found.
    pub fn maybe_of(app: &mut App, context: BuildContext) -> Option<TextHeightBehavior> {
        context
            .depend_on_inherited_widget_of_exact_type::<DefaultTextHeightBehavior>(app)
            .map(|widget| widget.text_height_behavior)
    }

    /// The closest instance of [`DefaultTextHeightBehavior`] that encloses the given
    /// context.
    ///
    /// If no such instance exists, this method panics.
    ///
    /// Calling this method will create a dependency on the closest
    /// [`DefaultTextHeightBehavior`] in the `context`.
    ///
    /// See also:
    ///
    /// * [`maybe_of`](Self::maybe_of), which is similar to this method, but returns `None`
    ///   if no [`DefaultTextHeightBehavior`] ancestor is found.
    pub fn of(app: &mut App, context: BuildContext) -> TextHeightBehavior {
        let behavior = Self::maybe_of(app, context);
        behavior.expect(
            "DefaultTextHeightBehavior::of() was called with a context that does not contain \
             a DefaultTextHeightBehavior widget.\n\
             No DefaultTextHeightBehavior widget ancestor could be found starting from the \
             context that was passed to DefaultTextHeightBehavior::of(). This can happen \
             because you are using a widget that looks for a DefaultTextHeightBehavior \
             ancestor, but no such ancestor exists.",
        )
    }
}

impl InheritedWidget for DefaultTextHeightBehavior {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &DefaultTextHeightBehavior) -> bool {
        self.text_height_behavior != old_widget.text_height_behavior
    }

    fn as_inherited_theme(&self) -> Option<&dyn InheritedTheme> {
        Some(self)
    }
}

impl InheritedTheme for DefaultTextHeightBehavior {
    fn wrap(&self, _app: &mut App, _context: BuildContext, child: WidgetRef) -> WidgetRef {
        DefaultTextHeightBehavior::new(self.text_height_behavior, child).into_widget()
    }
}

// ---------------------------------------------------------------------------------------------
// Text

/// A run of text with a single style.
///
/// The [`Text`] widget displays a string of text with single style. The string might break
/// across multiple lines or might all be displayed on the same line depending on the layout
/// constraints.
///
/// The `style` argument is optional. When omitted, the text will use the style from the
/// closest enclosing [`DefaultTextStyle`]. If the given style's `TextStyle.inherit` property
/// is true (the default), the given style will be merged with the closest enclosing
/// [`DefaultTextStyle`]. This merging behavior is useful, for example, to make the text bold
/// while using the default font family and size.
///
/// This example shows how to display text using the [`Text`] widget with the `overflow` set
/// to [`TextOverflow::Ellipsis`].
///
/// ```text
/// Text::new("Hello, how are you?").overflow(TextOverflow::Ellipsis)
/// ```
///
/// Setting `max_lines` to `1` is not equivalent to disabling soft wrapping with `soft_wrap`.
/// This is apparent when using [`TextOverflow::Fade`]: with `max_lines(1)` a second line
/// overflows and the fade appears in a horizontal direction at the bottom; with
/// `soft_wrap(false)` the single line overflows and the fade appears in a vertical direction
/// at the right.
///
/// Using the [`rich`](Self::rich) constructor, the [`Text`] widget can display a paragraph
/// with differently styled [`TextSpan`]s.
///
/// ## Interactivity
///
/// To make [`Text`] react to touch events, wrap it in a `GestureDetector` widget with a
/// `GestureDetector.on_tap` handler.
///
/// To make sections of the text interactive, use [`RichText`] and specify a
/// `TapGestureRecognizer` as the `TextSpan.recognizer` of the relevant part of the text.
///
/// ## Selection
///
/// [`Text`] is not selectable by default. To make a [`Text`] selectable, one can wrap a
/// subtree with a `SelectionArea` widget.
///
/// See also:
///
///  * [`RichText`], which gives you more control over the text styles.
///  * [`DefaultTextStyle`], which sets default styles for [`Text`] widgets.
///
/// Dart's named constructor arguments are the fluent setters
/// (`Text::new("Hi").max_lines(1)`).
#[derive(Debug)]
pub struct Text {
    /// See [`StatelessWidget::key`].
    pub key: Option<KeyRef>,
    /// The text to display.
    ///
    /// This will be `None` if a `text_span` is provided instead.
    pub data: Option<String>,
    /// The text to display as an [`InlineSpan`](waft_painting::InlineSpan).
    ///
    /// This will be `None` if `data` is provided instead.
    pub text_span: Option<InlineSpanRef>,
    /// If non-null, the style to use for this text.
    ///
    /// If the style's "inherit" property is true, the style will be merged with the closest
    /// enclosing [`DefaultTextStyle`]. Otherwise, the style will replace the closest
    /// enclosing [`DefaultTextStyle`].
    pub style: Option<TextStyle>,
    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
    /// layout metrics.
    ///
    /// Omitting or providing `None` will disable strut.
    ///
    /// The user or platform may override this strut's [`StrutStyle::height`] via a
    /// [`MediaQuery`] ancestor's `MediaQueryData.lineHeightScaleFactorOverride`.
    pub strut_style: Option<StrutStyle>,
    /// How the text should be aligned horizontally.
    pub text_align: Option<TextAlign>,
    /// The directionality of the text.
    ///
    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
    /// are interpreted.
    ///
    /// This is also used to disambiguate how to render bidirectional text. For example, if
    /// the `data` is an English phrase followed by a Hebrew phrase, in a
    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
    /// will be on the right and the Hebrew phrase on its left.
    ///
    /// Defaults to the ambient `Directionality`, if any.
    pub text_direction: Option<TextDirection>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    pub soft_wrap: Option<bool>,
    /// How visual overflow should be handled.
    ///
    /// If this is `None`, `TextStyle.overflow` will be used, otherwise the value from the
    /// nearest [`DefaultTextStyle`] ancestor will be used.
    pub overflow: Option<TextOverflow>,
    /// The font scaling strategy to use when laying out and rendering the text.
    pub text_scaler: Option<TextScaler>,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    ///
    /// If this is `None`, but there is an ambient [`DefaultTextStyle`] that specifies an
    /// explicit number for its `DefaultTextStyle.max_lines`, then the [`DefaultTextStyle`]
    /// value will take precedence. You can use a [`RichText`] widget directly to entirely
    /// override the [`DefaultTextStyle`].
    pub max_lines: Option<i32>,
    /// An alternative semantics label for this text.
    ///
    /// If present, the semantics of this widget will contain this value instead
    /// of the actual text. This will overwrite any of the semantics labels applied
    /// directly to the [`TextSpan`]s.
    ///
    /// This is useful for replacing abbreviations or shorthands with the full
    /// text value: `Text::new("$$").semantics_label("Double dollars")`.
    pub semantics_label: Option<String>,
    /// A unique identifier for the semantics node for this widget.
    ///
    /// This is useful for cases where the text widget needs to have a uniquely
    /// identifiable ID that is recognized through the automation tools without
    /// having a dependency on the actual content of the text that can possibly be
    /// dynamic in nature.
    pub semantics_identifier: Option<String>,
    /// Defines how to measure the width of the rendered text.
    pub text_width_basis: Option<TextWidthBasis>,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
    /// The color to use when painting the selection.
    ///
    /// This is ignored if [`SelectionContainer::maybe_of`] returns `None` in the
    /// [`BuildContext`] of this widget.
    ///
    /// If `None`, the ambient [`DefaultSelectionStyle`] is used (if any); failing that, the
    /// selection color defaults to [`DefaultSelectionStyle::DEFAULT_COLOR`].
    pub selection_color: Option<Color>,
}

impl Text {
    /// Creates a text widget.
    ///
    /// If the `style` argument is `None`, the text will use the style from the closest
    /// enclosing [`DefaultTextStyle`].
    ///
    /// The `overflow` property's behavior is affected by the `soft_wrap` argument. If the
    /// `soft_wrap` is true or `None`, the glyph causing overflow, and those that follow, will
    /// not be rendered. Otherwise, it will be shown with the given overflow option.
    pub fn new(data: impl Into<String>) -> Text {
        Text::unstyled(Some(data.into()), None)
    }

    /// Creates a text widget with an [`InlineSpan`](waft_painting::InlineSpan).
    ///
    /// The following subclasses of `InlineSpan` may be used to build rich text:
    ///
    /// * [`TextSpan`]s define text and children `InlineSpan`s.
    /// * `WidgetSpan`s define embedded inline widgets.
    ///
    /// See [`RichText`] which provides a lower-level way to draw text.
    pub fn rich(text_span: InlineSpanRef) -> Text {
        Text::unstyled(None, Some(text_span))
    }

    /// The fields both constructors leave unset.
    fn unstyled(data: Option<String>, text_span: Option<InlineSpanRef>) -> Text {
        Text {
            key: None,
            data,
            text_span,
            style: None,
            strut_style: None,
            text_align: None,
            text_direction: None,
            soft_wrap: None,
            overflow: None,
            text_scaler: None,
            max_lines: None,
            semantics_label: None,
            semantics_identifier: None,
            text_width_basis: None,
            text_height_behavior: None,
            selection_color: None,
        }
    }

    /// Dart `Text(key:)`.
    pub fn key(mut self, key: KeyRef) -> Text {
        self.key = Some(key);
        self
    }

    /// Dart `Text(style:)`.
    pub fn style(mut self, style: TextStyle) -> Text {
        self.style = Some(style);
        self
    }

    /// Dart `Text(strutStyle:)`.
    pub fn strut_style(mut self, strut_style: StrutStyle) -> Text {
        self.strut_style = Some(strut_style);
        self
    }

    /// Dart `Text(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> Text {
        self.text_align = Some(text_align);
        self
    }

    /// Dart `Text(textDirection:)`.
    pub fn text_direction(mut self, text_direction: TextDirection) -> Text {
        self.text_direction = Some(text_direction);
        self
    }

    /// Dart `Text(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> Text {
        self.soft_wrap = Some(soft_wrap);
        self
    }

    /// Dart `Text(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> Text {
        self.overflow = Some(overflow);
        self
    }

    /// Dart `Text(textScaler:)`.
    pub fn text_scaler(mut self, text_scaler: TextScaler) -> Text {
        self.text_scaler = Some(text_scaler);
        self
    }

    /// Dart `Text(maxLines:)`.
    pub fn max_lines(mut self, max_lines: i32) -> Text {
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `Text(semanticsLabel:)`.
    pub fn semantics_label(mut self, semantics_label: impl Into<String>) -> Text {
        self.semantics_label = Some(semantics_label.into());
        self
    }

    /// Dart `Text(semanticsIdentifier:)`.
    pub fn semantics_identifier(mut self, semantics_identifier: impl Into<String>) -> Text {
        self.semantics_identifier = Some(semantics_identifier.into());
        self
    }

    /// Dart `Text(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> Text {
        self.text_width_basis = Some(text_width_basis);
        self
    }

    /// Dart `Text(textHeightBehavior:)`.
    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> Text {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }

    /// Dart `Text(selectionColor:)`.
    pub fn selection_color(mut self, selection_color: Color) -> Text {
        self.selection_color = Some(selection_color);
        self
    }
}

impl StatelessWidget for Text {
    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let default_text_style = DefaultTextStyle::of(app, context);
        let mut effective_text_style = self.style.clone();
        if self.style.as_ref().is_none_or(|style| style.inherit) {
            effective_text_style = Some(default_text_style.style.merge(self.style.as_ref()));
        }
        if MediaQuery::bold_text_of(app, context) {
            let bold = TextStyle::new().font_weight(FontWeight::BOLD);
            effective_text_style = Some(
                effective_text_style
                    .expect("the style is set above")
                    .merge(Some(&bold)),
            );
        }
        // Flutter leaves `MediaQueryData.paragraphSpacingOverride` to its own text components.
        let line_height_scale_factor =
            MediaQuery::maybe_line_height_scale_factor_override_of(app, context);
        let letter_spacing = MediaQuery::maybe_letter_spacing_override_of(app, context);
        let word_spacing = MediaQuery::maybe_word_spacing_override_of(app, context);
        let effective_text_span = apply_text_spacing_overrides(
            line_height_scale_factor,
            letter_spacing,
            word_spacing,
            TextSpan {
                style: effective_text_style.clone(),
                text: self.data.clone(),
                children: self
                    .text_span
                    .as_ref()
                    .map(|text_span| vec![text_span.clone()]),
                ..TextSpan::default()
            },
        );
        let effective_strut_style = self.strut_style.as_ref().map(|strut_style| {
            line_height_scale_factor.map_or_else(
                || strut_style.clone(),
                |height| strut_style.merge(Some(&StrutStyle::new().height(height))),
            )
        });
        let text_scaler = self
            .text_scaler
            .clone()
            .unwrap_or_else(|| MediaQuery::text_scaler_of(app, context));
        let text_height_behavior = self
            .text_height_behavior
            .or(default_text_style.text_height_behavior)
            .or_else(|| DefaultTextHeightBehavior::maybe_of(app, context));
        let text_align = self
            .text_align
            .or(default_text_style.text_align)
            .unwrap_or(TextAlign::Start);
        let soft_wrap = self.soft_wrap.unwrap_or(default_text_style.soft_wrap);
        let overflow = self
            .overflow
            .or(effective_text_style
                .as_ref()
                .and_then(|style| style.overflow))
            .unwrap_or(default_text_style.overflow);
        let text_width_basis = self
            .text_width_basis
            .unwrap_or(default_text_style.text_width_basis);
        let max_lines = self.max_lines.or(default_text_style.max_lines);
        let default_selection_style = DefaultSelectionStyle::of(app, context);
        let selection_color = self
            .selection_color
            .or_else(|| default_selection_style.selection_color.as_deref().copied())
            .unwrap_or(DefaultSelectionStyle::DEFAULT_COLOR);
        let registrar = SelectionContainer::maybe_of(app, context);
        let mut result = if registrar.is_some() {
            // A mouse hovering the selectable text shows the text cursor, as `SelectableRegion`'s
            // text does.
            let cursor = default_selection_style
                .mouse_cursor
                .clone()
                .unwrap_or_else(|| SystemMouseCursors::TEXT.into());
            MouseRegion::new()
                .cursor(cursor)
                .child(SelectableTextContainer {
                    text: effective_text_span,
                    text_align,
                    text_direction: self.text_direction,
                    soft_wrap,
                    overflow,
                    text_scaler,
                    max_lines,
                    text_width_basis,
                    text_height_behavior,
                    strut_style: effective_strut_style,
                    selection_color,
                })
                .into_widget()
        } else {
            let mut rich_text = RichText::new(effective_text_span.into_span())
                .text_align(text_align)
                .soft_wrap(soft_wrap)
                .overflow(overflow)
                .text_scaler(text_scaler)
                .text_width_basis(text_width_basis)
                .selection_color(selection_color);
            // RichText uses Directionality.of to obtain a default if this is None.
            if let Some(text_direction) = self.text_direction {
                rich_text = rich_text.text_direction(text_direction);
            }
            if let Some(max_lines) = max_lines {
                rich_text = rich_text.max_lines(max_lines);
            }
            if let Some(text_height_behavior) = text_height_behavior {
                rich_text = rich_text.text_height_behavior(text_height_behavior);
            }
            if let Some(strut_style) = effective_strut_style {
                rich_text = rich_text.strut_style(strut_style);
            }
            rich_text.into_widget()
        };
        if self.semantics_label.is_some() || self.semantics_identifier.is_some() {
            let mut semantics = Semantics::new();
            if let Some(text_direction) = self.text_direction {
                semantics = semantics.text_direction(text_direction);
            }
            if let Some(semantics_label) = &self.semantics_label {
                semantics = semantics.label(semantics_label.clone());
            }
            if let Some(semantics_identifier) = &self.semantics_identifier {
                semantics = semantics.identifier(semantics_identifier.clone());
            }
            result = semantics
                .child(
                    ExcludeSemantics::new()
                        .excluding(self.semantics_label.is_some())
                        .child(result),
                )
                .into_widget();
        }
        result
    }
}

// ---------------------------------------------------------------------------------------------
// SelectableTextContainer

/// Dart's `_SelectableTextContainer`: the [`SelectionContainer`] a selectable [`Text`] builds, so
/// that its paragraph's selectables register with it and its delegate handles the paragraph's
/// selection.
#[derive(Debug)]
struct SelectableTextContainer {
    text: TextSpan,
    text_align: TextAlign,
    text_direction: Option<TextDirection>,
    soft_wrap: bool,
    overflow: TextOverflow,
    text_scaler: TextScaler,
    max_lines: Option<i32>,
    text_width_basis: TextWidthBasis,
    text_height_behavior: Option<TextHeightBehavior>,
    strut_style: Option<StrutStyle>,
    selection_color: Color,
}

impl StatefulWidget for SelectableTextContainer {
    type State = SelectableTextContainerState;

    fn create_state(&self) -> SelectableTextContainerState {
        SelectableTextContainerState {
            state: StateData::new(),
            selection_delegate: None,
            text_key: GlobalKey::new(),
        }
    }
}

/// The state of a [`SelectableTextContainer`]: Dart's `_SelectableTextContainerState`.
struct SelectableTextContainerState {
    state: StateData<SelectableTextContainer>,
    selection_delegate: Option<Ref<SelectableTextContainerDelegate>>,
    /// The key of the paragraph below, which the delegate finds its `RenderParagraph` by.
    text_key: GlobalKey,
}

impl SelectableTextContainerState {
    fn selection_delegate(
        self: Handle<Self>,
        app: &App,
    ) -> Handle<SelectableTextContainerDelegate> {
        app.get(self)
            .selection_delegate
            .as_ref()
            .expect("the delegate is created in init_state")
            .handle()
    }
}

impl State for SelectableTextContainerState {
    type Widget = SelectableTextContainer;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let text_key = app.get(self).text_key.clone();
        let delegate = SelectableTextContainerDelegate::new(app, text_key);
        app.get_mut(self).selection_delegate = Some(delegate);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let delegate = self.selection_delegate(app);
        MultiSelectableSelectionContainerDelegate::dispose(delegate, app);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let delegate = self.selection_delegate(app).keep(app).into_erased();
        let widget = self.widget(app);
        SelectionContainer::new(
            delegate,
            SelectableRichText {
                text_key: app.get(self).text_key.clone(),
                text: widget.text.clone(),
                text_align: widget.text_align,
                text_direction: widget.text_direction,
                soft_wrap: widget.soft_wrap,
                overflow: widget.overflow,
                text_scaler: widget.text_scaler.clone(),
                max_lines: widget.max_lines,
                text_width_basis: widget.text_width_basis,
                text_height_behavior: widget.text_height_behavior,
                strut_style: widget.strut_style.clone(),
                selection_color: widget.selection_color,
            },
        )
        .into_widget()
    }
}

/// Dart's `_RichText`: the [`RichText`] under the container, which reads the container's
/// registrar and registers the paragraph's selectables with it.
#[derive(Debug)]
struct SelectableRichText {
    text_key: GlobalKey,
    text: TextSpan,
    text_align: TextAlign,
    text_direction: Option<TextDirection>,
    soft_wrap: bool,
    overflow: TextOverflow,
    text_scaler: TextScaler,
    max_lines: Option<i32>,
    text_width_basis: TextWidthBasis,
    text_height_behavior: Option<TextHeightBehavior>,
    strut_style: Option<StrutStyle>,
    selection_color: Color,
}

impl StatelessWidget for SelectableRichText {
    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let registrar = SelectionContainer::maybe_of(app, context)
            .expect("the text's own selection container hosts a registrar");
        let mut rich_text = RichText::new(self.text.clone().into_span())
            .key(KeyRef::Global(self.text_key.clone()))
            .text_align(self.text_align)
            .soft_wrap(self.soft_wrap)
            .overflow(self.overflow)
            .text_scaler(self.text_scaler.clone())
            .text_width_basis(self.text_width_basis)
            .selection_registrar(registrar)
            .selection_color(self.selection_color);
        if let Some(text_direction) = self.text_direction {
            rich_text = rich_text.text_direction(text_direction);
        }
        if let Some(max_lines) = self.max_lines {
            rich_text = rich_text.max_lines(max_lines);
        }
        if let Some(text_height_behavior) = self.text_height_behavior {
            rich_text = rich_text.text_height_behavior(text_height_behavior);
        }
        if let Some(strut_style) = self.strut_style.clone() {
            rich_text = rich_text.strut_style(strut_style);
        }
        rich_text.into_widget()
    }
}

// ---------------------------------------------------------------------------------------------
// SelectableTextContainerDelegate

/// Dart's `_SelectableTextContainerDelegate`: the delegate of a [`Text`]'s selection container.
///
/// It handles the paragraph's selection across the fragments a `WidgetSpan` splits it into, and
/// finds its `RenderParagraph` through the container's global key.
struct SelectableTextContainerDelegate {
    selection_container_delegate: SelectionContainerDelegateData,
    multi_selectable_selection_container_delegate: MultiSelectableSelectionContainerDelegateData,
    static_selection_container_delegate: StaticSelectionContainerDelegateData,
    /// The key of the paragraph this delegate handles the selection of.
    text_key: GlobalKey,
    /// Where each fragment of the paragraph after its first starts in it, recorded when the
    /// selectables change: reading it needs `&mut App`, and `selection` has `&App` (see
    /// `PORTING.md`).
    selectable_content_starts: Vec<(AnySelectable, i32)>,
}

impl SelectableTextContainerDelegate {
    fn new(app: &mut App, text_key: GlobalKey) -> Ref<SelectableTextContainerDelegate> {
        app.create(SelectableTextContainerDelegate {
            selection_container_delegate: SelectionContainerDelegateData::new(),
            multi_selectable_selection_container_delegate:
                MultiSelectableSelectionContainerDelegateData::new(),
            static_selection_container_delegate: StaticSelectionContainerDelegateData::new(),
            text_key,
            selectable_content_starts: Vec::new(),
        })
    }

    /// Dart's `paragraph` getter.
    fn paragraph(self: Handle<Self>, app: &App) -> RenderHandle<RenderParagraph> {
        let context = app
            .get(self)
            .text_key
            .current_context(app)
            .expect("the text's paragraph is in the tree");
        context
            .find_render_object(app)
            .expect("the text's paragraph has a render object")
            .downcast::<RenderParagraph>(app)
            .expect("the text's render object is a RenderParagraph")
    }

    /// Where `selectable` starts in the paragraph, as recorded by
    /// [`record_selectable_content_starts`](Self::record_selectable_content_starts).
    fn selectable_content_start(
        self: Handle<Self>,
        app: &App,
        selectable: AnySelectable,
    ) -> Option<i32> {
        app.get(self)
            .selectable_content_starts
            .iter()
            .find_map(|(held, start)| (*held == selectable).then_some(*start))
    }

    /// Records where each fragment after the paragraph's first starts in it: Flutter reads it
    /// from the fragment's first box when it computes the range, which needs `&mut App` there.
    fn record_selectable_content_starts(self: Handle<Self>, app: &mut App) {
        let selectables = self
            .multi_selectable_selection_container_delegate_data(app)
            .selectables
            .clone();
        let mut starts = Vec::new();
        for (index, selectable) in selectables.iter().enumerate() {
            if index == 0 {
                continue;
            }
            let paragraph = self.paragraph(app);
            if !paragraph.selectable_belongs_to_paragraph(app, *selectable) {
                continue;
            }
            let Some(first_box) = selectable.bounding_boxes(app).into_iter().next() else {
                continue;
            };
            let position = paragraph.get_position_for_offset(app, first_box.center_left());
            starts.push((*selectable, position.offset));
        }
        app.get_mut(self).selectable_content_starts = starts;
    }

    /// Dart's `compareOrder` for a text paragraph: sorts the selectables by their first
    /// bounding box's top left, where the multi-selectable delegate sorts by their union.
    fn compare_top_left_screen_order(
        self: Handle<Self>,
        app: &mut App,
        a: AnySelectable,
        b: AnySelectable,
    ) -> Ordering {
        let rect_a = transform_rect(
            &a.get_transform_to(app, None),
            a.bounding_boxes(app)
                .into_iter()
                .next()
                .expect("a selectable has a bounding box"),
        );
        let rect_b = transform_rect(
            &b.get_transform_to(app, None),
            b.bounding_boxes(app)
                .into_iter()
                .next()
                .expect("a selectable has a bounding box"),
        );
        let result = compare_vertically(rect_a, rect_b);
        if result != Ordering::Equal {
            return result;
        }
        compare_horizontally(rect_a, rect_b)
    }

    /// Dart's `handleSelectParagraph`, whose own body is `_handleSelectParagraph`.
    fn handle_select_paragraph_body(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        let SelectionEvent::SelectParagraph {
            global_position,
            absorb,
        } = event
        else {
            panic!("a paragraph selection event selects a paragraph");
        };
        let global_position = *global_position;
        let selectables = self
            .multi_selectable_selection_container_delegate_data(app)
            .selectables
            .clone();
        if *absorb {
            for selectable in &selectables {
                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                    self,
                    app,
                    *selectable,
                    event,
                );
            }
            let data = self.multi_selectable_selection_container_delegate_data_mut(app);
            data.current_selection_start_index = 0;
            data.current_selection_end_index = selectables.len() as i32 - 1;
            return SelectionResult::Next;
        }

        // First pass: if the position is on a placeholder, dispatch the selection event to the
        // selectable at the location and terminate.
        let paragraph = self.paragraph(app);
        for (index, selectable) in selectables.iter().enumerate() {
            let selectable_is_placeholder =
                !paragraph.selectable_belongs_to_paragraph(app, *selectable);
            if selectable_is_placeholder {
                let boxes = selectable.bounding_boxes(app);
                if !boxes.is_empty() {
                    let transform = selectable.get_transform_to(app, None);
                    for rect in boxes {
                        let global_rect = transform_rect(&transform, rect);
                        if global_rect.contains(global_position) {
                            let data =
                                self.multi_selectable_selection_container_delegate_data_mut(app);
                            data.current_selection_start_index = index as i32;
                            data.current_selection_end_index = index as i32;
                            return MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                                self, app, *selectable, event,
                            );
                        }
                    }
                }
            }
        }

        let mut last_selection_result: Option<SelectionResult> = None;
        let mut found_start = false;
        let mut last_next_index: Option<i32> = None;
        for (index, selectable) in selectables.iter().enumerate() {
            if !paragraph.selectable_belongs_to_paragraph(app, *selectable) {
                if found_start {
                    let synthesized_event = SelectionEvent::SelectParagraph {
                        global_position,
                        absorb: true,
                    };
                    let result =
                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                            self,
                            app,
                            *selectable,
                            &synthesized_event,
                        );
                    if selectables.len() - 1 == index {
                        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
                        data.current_selection_end_index = index as i32;
                        MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(
                            self, app,
                        );
                        return result;
                    }
                }
                continue;
            }
            let existing_geometry = selectable.value(app);
            last_selection_result = Some(
                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                    self,
                    app,
                    *selectable,
                    event,
                ),
            );
            let result = last_selection_result.expect("assigned just now");
            if index == selectables.len() - 1 && result == SelectionResult::Next {
                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
                if found_start {
                    data.current_selection_end_index = index as i32;
                } else {
                    data.current_selection_start_index = index as i32;
                    data.current_selection_end_index = index as i32;
                }
                return SelectionResult::Next;
            }
            if result == SelectionResult::Next {
                if selectable.value(app) == existing_geometry && !found_start {
                    last_next_index = Some(index as i32);
                }
                if selectable.value(app) != existing_geometry && !found_start {
                    let boxes = selectable.bounding_boxes(app);
                    debug_assert!(!boxes.is_empty());
                    let selection_rects = selectable.value(app).selection_rects;
                    debug_assert!(!selection_rects.is_empty());
                    let selection_at_start_of_selectable = boxes[0].overlaps(selection_rects[0]);
                    let start_index = if let Some(last_next_index) = last_next_index
                        && selection_at_start_of_selectable
                    {
                        last_next_index + 1
                    } else if last_next_index.is_none() && selection_at_start_of_selectable {
                        0
                    } else {
                        index as i32
                    };
                    for selectable in &selectables[start_index as usize..index] {
                        let synthesized_event = SelectionEvent::SelectParagraph {
                            global_position,
                            absorb: true,
                        };
                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                            self,
                            app,
                            *selectable,
                            &synthesized_event,
                        );
                    }
                    let data = self.multi_selectable_selection_container_delegate_data_mut(app);
                    data.current_selection_start_index = start_index;
                    found_start = true;
                }
                continue;
            }
            if index == 0 && result == SelectionResult::Previous {
                return SelectionResult::Previous;
            }
            if selectable.value(app) != existing_geometry {
                if !found_start && last_next_index.is_none() {
                    let data = self.multi_selectable_selection_container_delegate_data_mut(app);
                    data.current_selection_start_index = 0;
                    for selectable in &selectables[..index] {
                        let synthesized_event = SelectionEvent::SelectParagraph {
                            global_position,
                            absorb: true,
                        };
                        MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                            self,
                            app,
                            *selectable,
                            &synthesized_event,
                        );
                    }
                }
                let data = self.multi_selectable_selection_container_delegate_data_mut(app);
                data.current_selection_end_index = index as i32;
                // Geometry changed as a result of selecting a paragraph; clear the other
                // selectables to keep the selection in sync.
                MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(self, app);
            }
            return SelectionResult::End;
        }
        debug_assert!(last_selection_result.is_none());
        SelectionResult::End
    }

    /// Dart's `_adjustSelection`: [`MultiSelectableSelectionContainerDelegateBase::adjust_selection`]
    /// with the crossing of the opposite edge that a paragraph selection needs.
    fn adjust_selection(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
        is_end: bool,
    ) -> SelectionResult {
        let selectables = self
            .multi_selectable_selection_container_delegate_data(app)
            .selectables
            .clone();
        let value = SelectionHandler::value(self, app);
        let is_current_edge_within_viewport = if is_end {
            value.end_selection_point.is_some()
        } else {
            value.start_selection_point.is_some()
        };
        let is_opposite_edge_within_viewport = if is_end {
            value.start_selection_point.is_some()
        } else {
            value.end_selection_point.is_some()
        };
        let data = self.multi_selectable_selection_container_delegate_data(app);
        let mut new_index: i32 = if is_end {
            if is_current_edge_within_viewport {
                data.current_selection_end_index
            } else if is_opposite_edge_within_viewport {
                data.current_selection_start_index
            } else {
                0
            }
        } else if is_current_edge_within_viewport {
            data.current_selection_start_index
        } else if is_opposite_edge_within_viewport {
            data.current_selection_end_index
        } else {
            0
        };
        debug_assert!(new_index < selectables.len() as i32 && new_index >= 0);
        let mut forward: Option<bool> = None;
        let mut final_result: Option<SelectionResult> = None;
        while (new_index as usize) < selectables.len() && new_index >= 0 && final_result.is_none() {
            let current_selectable_result =
                MultiSelectableSelectionContainerDelegate::dispatch_selection_event_to_child(
                    self,
                    app,
                    selectables[new_index as usize],
                    event,
                );
            match current_selectable_result {
                SelectionResult::End | SelectionResult::Pending | SelectionResult::None => {
                    final_result = Some(current_selectable_result);
                }
                SelectionResult::Next => {
                    if forward == Some(false) {
                        new_index += 1;
                        final_result = Some(SelectionResult::End);
                    } else if new_index as usize == selectables.len() - 1 {
                        final_result = Some(current_selectable_result);
                    } else {
                        forward = Some(true);
                        new_index += 1;
                    }
                }
                SelectionResult::Previous => {
                    if forward == Some(true) {
                        new_index -= 1;
                        final_result = Some(SelectionResult::End);
                    } else if new_index == 0 {
                        final_result = Some(current_selectable_result);
                    } else {
                        forward = Some(false);
                        new_index -= 1;
                    }
                }
            }
        }
        let data = self.multi_selectable_selection_container_delegate_data_mut(app);
        if is_end {
            let forward_selection =
                data.current_selection_end_index >= data.current_selection_start_index;
            if let Some(forward) = forward
                && ((!forward_selection
                    && forward
                    && new_index >= data.current_selection_start_index)
                    || (forward_selection
                        && !forward
                        && new_index <= data.current_selection_start_index))
            {
                data.current_selection_start_index = data.current_selection_end_index;
            }
            data.current_selection_end_index = new_index;
        } else {
            let forward_selection =
                data.current_selection_end_index >= data.current_selection_start_index;
            if let Some(forward) = forward
                && ((!forward_selection
                    && !forward
                    && new_index <= data.current_selection_end_index)
                    || (forward_selection
                        && forward
                        && new_index >= data.current_selection_end_index))
            {
                data.current_selection_end_index = data.current_selection_start_index;
            }
            data.current_selection_start_index = new_index;
        }
        MultiSelectableSelectionContainerDelegateBase::flush_inactive_selections(self, app);
        final_result.expect("the loop answered a result")
    }

    /// Dart's `_calculateLocalRange`: the selectables' ranges, with a fragment that is not the
    /// paragraph's first offset by where it starts in the paragraph.
    fn calculate_local_range(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
        let data = self.multi_selectable_selection_container_delegate_data(app);
        if data.current_selection_start_index == -1 || data.current_selection_end_index == -1 {
            return None;
        }
        let selectables = data.selectables.clone();
        let mut start_offset = 0i32;
        let mut end_offset = 0i32;
        let mut found_start = false;
        let mut forward_selection =
            data.current_selection_end_index >= data.current_selection_start_index;
        if data.current_selection_end_index == data.current_selection_start_index {
            // Determining the direction is inaccurate when both edges share a selectable; the
            // range within it is the source of truth.
            let range = selectables[data.current_selection_start_index as usize]
                .selection(app)
                .expect("the selectable holding both edges has a selection");
            forward_selection = range.end_offset >= range.start_offset;
        }
        for (index, selectable) in selectables.iter().enumerate() {
            let Some(range) = selectable.selection(app) else {
                if found_start {
                    return Some(SelectedContentRange::new(
                        if forward_selection {
                            start_offset
                        } else {
                            end_offset
                        },
                        if forward_selection {
                            end_offset
                        } else {
                            start_offset
                        },
                    ));
                }
                start_offset += selectable.content_length(app) as i32;
                end_offset = start_offset;
                continue;
            };
            let selection_start_normalized = range.start_offset.min(range.end_offset);
            let selection_end_normalized = range.start_offset.max(range.end_offset);
            if !found_start {
                // A `RenderParagraph` may split its content into several selectables, so a
                // fragment that is not the paragraph's first starts partway through it.
                let should_consider_content_start = index > 0
                    && self
                        .paragraph(app)
                        .selectable_belongs_to_paragraph(app, *selectable);
                let selectable_content_start = if should_consider_content_start {
                    self.selectable_content_start(app, *selectable)
                        .expect("a fragment's start is recorded when the selectables change")
                } else {
                    0
                };
                start_offset += (selection_start_normalized - selectable_content_start).abs();
                end_offset =
                    start_offset + (selection_end_normalized - selection_start_normalized).abs();
                found_start = true;
            } else {
                end_offset += (selection_end_normalized - selection_start_normalized).abs();
            }
        }
        debug_assert!(
            found_start,
            "The start of the selection has not been found despite this selection delegate \
             having an existing currentSelectionStartIndex and currentSelectionEndIndex."
        );
        Some(SelectedContentRange::new(
            if forward_selection {
                start_offset
            } else {
                end_offset
            },
            if forward_selection {
                end_offset
            } else {
                start_offset
            },
        ))
    }
}

impl SelectionContainerDelegate for SelectableTextContainerDelegate {
    fn selection_container_delegate_data(
        self: Handle<Self>,
        app: &App,
    ) -> &SelectionContainerDelegateData {
        &app.get(self).selection_container_delegate
    }

    fn selection_container_delegate_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut SelectionContainerDelegateData {
        &mut app.get_mut(self).selection_container_delegate
    }
}

impl MultiSelectableSelectionContainerDelegate for SelectableTextContainerDelegate {
    crate::multi_selectable_selection_container_delegate_accessors!();

    fn did_change_selectables(self: Handle<Self>, app: &mut App) {
        self.record_selectable_content_starts(app);
        StaticSelectionContainerDelegateBase::did_change_selectables(self, app);
    }

    fn compare_order(
        self: Handle<Self>,
        app: &mut App,
        a: AnySelectable,
        b: AnySelectable,
    ) -> Ordering {
        self.compare_top_left_screen_order(app, a, b)
    }

    fn handle_select_all(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        StaticSelectionContainerDelegateBase::handle_select_all(self, app, event)
    }

    fn handle_select_word(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        StaticSelectionContainerDelegateBase::handle_select_word(self, app, event)
    }

    fn handle_select_paragraph(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        let result = self.handle_select_paragraph_body(app, event);
        StaticSelectionContainerDelegate::did_receive_selection_boundary_events(self, app);
        result
    }

    fn handle_clear_selection(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        StaticSelectionContainerDelegateBase::handle_clear_selection(self, app, event)
    }

    fn handle_selection_edge_update(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        let (global_position, for_end, granularity) = match event {
            SelectionEvent::StartEdgeUpdate {
                global_position,
                granularity,
            } => (*global_position, false, *granularity),
            SelectionEvent::EndEdgeUpdate {
                global_position,
                granularity,
            } => (*global_position, true, *granularity),
            _ => panic!("a selection edge update names an edge"),
        };
        if granularity != waft_rendering::TextGranularity::Paragraph {
            return StaticSelectionContainerDelegateBase::handle_selection_edge_update(
                self, app, event,
            );
        }
        StaticSelectionContainerDelegate::update_last_selection_edge_location(
            self,
            app,
            global_position,
            for_end,
        );
        let selection_index = {
            let data = self.multi_selectable_selection_container_delegate_data(app);
            if for_end {
                data.current_selection_end_index
            } else {
                data.current_selection_start_index
            }
        };
        if selection_index == -1 {
            return StaticSelectionContainerDelegateBase::handle_selection_edge_update(
                self, app, event,
            );
        }
        self.adjust_selection(app, event, for_end)
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        StaticSelectionContainerDelegateBase::dispose(self, app);
    }

    fn ensure_child_updated(self: Handle<Self>, app: &mut App, selectable: AnySelectable) {
        StaticSelectionContainerDelegateBase::ensure_child_updated(self, app, selectable);
    }

    fn dispatch_selection_event_to_child(
        self: Handle<Self>,
        app: &mut App,
        selectable: AnySelectable,
        event: &SelectionEvent,
    ) -> SelectionResult {
        StaticSelectionContainerDelegateBase::dispatch_selection_event_to_child(
            self, app, selectable, event,
        )
    }
}

impl StaticSelectionContainerDelegate for SelectableTextContainerDelegate {
    crate::static_selection_container_delegate_accessors!();
}

impl SelectionHandler for SelectableTextContainerDelegate {
    fn value(self: Handle<Self>, app: &App) -> SelectionGeometry {
        StaticSelectionContainerDelegateBase::value(self, app)
    }

    fn push_handle_layers(
        self: Handle<Self>,
        app: &mut App,
        start_handle: Option<Ref<waft_rendering::LayerLink>>,
        end_handle: Option<Ref<waft_rendering::LayerLink>>,
    ) {
        StaticSelectionContainerDelegateBase::push_handle_layers(
            self,
            app,
            start_handle,
            end_handle,
        );
    }

    fn selected_content(self: Handle<Self>, app: &App) -> Option<waft_rendering::SelectedContent> {
        StaticSelectionContainerDelegateBase::selected_content(self, app)
    }

    fn selection(self: Handle<Self>, app: &App) -> Option<SelectedContentRange> {
        self.calculate_local_range(app)
    }

    fn dispatch_selection_event(
        self: Handle<Self>,
        app: &mut App,
        event: &SelectionEvent,
    ) -> SelectionResult {
        StaticSelectionContainerDelegateBase::dispatch_selection_event(self, app, event)
    }

    fn content_length(self: Handle<Self>, app: &App) -> usize {
        StaticSelectionContainerDelegateBase::content_length(self, app)
    }
}

impl SelectionRegistrar for SelectableTextContainerDelegate {
    crate::static_selection_container_delegate_selection_registrar!();
}

impl ChangeNotifier for SelectableTextContainerDelegate {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self
            .multi_selectable_selection_container_delegate
            .change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self
            .multi_selectable_selection_container_delegate
            .change_notifier
    }
}

// ---------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------
// RichText (basic.dart)

/// Dart's `_OverridingTextStyleTextSpanUtils.applyTextSpacingOverrides`: overrides the text
/// styles of a [`TextSpan`] tree with the `MediaQuery` spacing overrides.
pub(crate) fn apply_text_spacing_overrides(
    line_height_scale_factor: Option<f64>,
    letter_spacing: Option<f64>,
    word_spacing: Option<f64>,
    text_span: TextSpan,
) -> TextSpan {
    if line_height_scale_factor.is_none() && letter_spacing.is_none() && word_spacing.is_none() {
        return text_span;
    }
    let mut override_text_style = TextStyle::new();
    if let Some(height) = line_height_scale_factor {
        override_text_style = override_text_style.height(height);
    }
    if let Some(letter_spacing) = letter_spacing {
        override_text_style = override_text_style.letter_spacing(letter_spacing);
    }
    if let Some(word_spacing) = word_spacing {
        override_text_style = override_text_style.word_spacing(word_spacing);
    }
    apply_text_style_overrides(&override_text_style, &text_span)
}

/// Dart's `_OverridingTextStyleTextSpanUtils._applyTextStyleOverrides`.
fn apply_text_style_overrides(override_text_style: &TextStyle, text_span: &TextSpan) -> TextSpan {
    TextSpan {
        text: text_span.text.clone(),
        children: text_span.children.as_ref().map(|children| {
            children
                .iter()
                .map(|child| match child.as_any().downcast_ref::<TextSpan>() {
                    Some(child) => {
                        apply_text_style_overrides(override_text_style, child).into_span()
                    }
                    None => child.clone(),
                })
                .collect()
        }),
        style: Some(match &text_span.style {
            Some(style) => style.merge(Some(override_text_style)),
            None => override_text_style.clone(),
        }),
        recognizer: text_span.recognizer.clone(),
        mouse_cursor: text_span.mouse_cursor.clone(),
        on_enter: text_span.on_enter.clone(),
        on_exit: text_span.on_exit.clone(),
    }
}

/// A paragraph of rich text.
///
/// The [`RichText`] widget displays text that uses multiple different styles. The text to
/// display is described using a tree of [`TextSpan`] objects, each of which has an
/// associated style that is used for that subtree. The text might break across multiple
/// lines or might all be displayed on the same line depending on the layout constraints.
///
/// Text displayed in a [`RichText`] widget must be explicitly styled. When picking which
/// style to use, consider using [`DefaultTextStyle::of`] the current [`BuildContext`] to
/// provide defaults. For more details on how to style text in a [`RichText`] widget, see the
/// documentation for [`TextStyle`].
///
/// Consider using the [`Text`] widget to integrate with the [`DefaultTextStyle`]
/// automatically. When all the text uses the same style, the default constructor is less
/// verbose. The [`Text::rich`] constructor allows you to style multiple spans with the
/// default text style while still allowing specified styles per span.
///
/// ```text
/// RichText::new(
///     TextSpan::new()
///         .text("Hello ")
///         .style(DefaultTextStyle::of(app, context).style)
///         .children(vec![
///             TextSpan::new().text("bold").style(TextStyle::new().font_weight(FontWeight::BOLD)).into_span(),
///             TextSpan::new().text(" world!").into_span(),
///         ])
///         .into_span(),
/// )
/// ```
///
/// See also:
///
///  * [`TextStyle`], which discusses how to style text.
///  * [`TextSpan`], which is used to describe the text in a paragraph.
///  * [`Text`], which automatically applies the ambient styles described by a
///    [`DefaultTextStyle`] to a single string.
///  * [`Text::rich`], a text widget that provides similar functionality as [`RichText`].
///    [`Text::rich`] will inherit [`TextStyle`] from [`DefaultTextStyle`].
///
/// Dart's named constructor arguments are the fluent setters
/// (`RichText::new(span).text_align(TextAlign::Center)`).
#[derive(Debug)]
pub struct RichText {
    /// See [`RenderObjectWidget::key`].
    pub key: Option<KeyRef>,
    /// The text to display in this widget.
    pub text: InlineSpanRef,
    /// The inline widgets of [`text`](Self::text), its `WidgetSpan`s at
    /// [`text_scaler`](Self::text_scaler), as Dart's constructor extracts them.
    children: Vec<WidgetRef>,
    /// How the text should be aligned horizontally.
    pub text_align: TextAlign,
    /// The directionality of the text.
    ///
    /// This decides how `text_align` values like [`TextAlign::Start`] and [`TextAlign::End`]
    /// are interpreted.
    ///
    /// This is also used to disambiguate how to render bidirectional text. For example, if
    /// the `text` is an English phrase followed by a Hebrew phrase, in a
    /// [`TextDirection::Ltr`] context the English phrase will be on the left and the Hebrew
    /// phrase to its right, while in a [`TextDirection::Rtl`] context, the English phrase
    /// will be on the right and the Hebrew phrase on its left.
    ///
    /// Defaults to the ambient `Directionality`, if any. If there is no ambient
    /// `Directionality`, then this must not be `None`.
    pub text_direction: Option<TextDirection>,
    /// Whether the text should break at soft line breaks.
    ///
    /// If false, the glyphs in the text will be positioned as if there was unlimited
    /// horizontal space.
    pub soft_wrap: bool,
    /// How visual overflow should be handled.
    pub overflow: TextOverflow,
    /// The font scaling strategy to use when laying out and rendering the text.
    pub text_scaler: TextScaler,
    /// An optional maximum number of lines for the text to span, wrapping if necessary. If
    /// the text exceeds the given number of lines, it will be truncated according to
    /// `overflow`.
    ///
    /// If this is 1, text will not wrap. Otherwise, text will be wrapped at the edge of the
    /// box.
    pub max_lines: Option<i32>,
    /// The strut style to use. Strut style defines the strut, which sets minimum vertical
    /// layout metrics.
    pub strut_style: Option<StrutStyle>,
    /// Defines how to measure the width of the rendered text.
    pub text_width_basis: TextWidthBasis,
    /// Defines how to apply `TextStyle.height` over and under text.
    pub text_height_behavior: Option<TextHeightBehavior>,
    /// The [`SelectionRegistrar`](waft_rendering::SelectionRegistrar) this rich text is
    /// subscribed to.
    ///
    /// If this is set, [`selection_color`](Self::selection_color) must be non-null.
    pub selection_registrar: Option<SelectionRegistrarRef>,
    /// The color to use when painting the selection.
    pub selection_color: Option<Color>,
}

impl RichText {
    /// Creates a paragraph of rich text.
    ///
    /// The `max_lines` property may be `None` (and indeed defaults to `None`), but if it is
    /// not `None`, it must be greater than zero.
    ///
    /// The `text_direction`, if `None`, defaults to the ambient `Directionality`, which in
    /// that case must not be null.
    pub fn new(text: InlineSpanRef) -> RichText {
        RichText {
            key: None,
            children: WidgetSpan::extract_from_inline_span(&*text, &TextScaler::NO_SCALING),
            text,
            text_align: TextAlign::Start,
            text_direction: None,
            soft_wrap: true,
            overflow: TextOverflow::Clip,
            text_scaler: TextScaler::NO_SCALING,
            max_lines: None,
            strut_style: None,
            text_width_basis: TextWidthBasis::Parent,
            text_height_behavior: None,
            selection_registrar: None,
            selection_color: None,
        }
    }

    /// Dart `RichText(key:)`.
    pub fn key(mut self, key: KeyRef) -> RichText {
        self.key = Some(key);
        self
    }

    /// Dart `RichText(textAlign:)`.
    pub fn text_align(mut self, text_align: TextAlign) -> RichText {
        self.text_align = text_align;
        self
    }

    /// Dart `RichText(textDirection:)`.
    pub fn text_direction(mut self, text_direction: TextDirection) -> RichText {
        self.text_direction = Some(text_direction);
        self
    }

    /// Dart `RichText(softWrap:)`.
    pub fn soft_wrap(mut self, soft_wrap: bool) -> RichText {
        self.soft_wrap = soft_wrap;
        self
    }

    /// Dart `RichText(overflow:)`.
    pub fn overflow(mut self, overflow: TextOverflow) -> RichText {
        self.overflow = overflow;
        self
    }

    /// Dart `RichText(textScaler:)`.
    pub fn text_scaler(mut self, text_scaler: TextScaler) -> RichText {
        self.children = WidgetSpan::extract_from_inline_span(&*self.text, &text_scaler);
        self.text_scaler = text_scaler;
        self
    }

    /// Dart `RichText(maxLines:)`. Must be greater than zero.
    pub fn max_lines(mut self, max_lines: i32) -> RichText {
        debug_assert!(max_lines > 0);
        self.max_lines = Some(max_lines);
        self
    }

    /// Dart `RichText(strutStyle:)`.
    pub fn strut_style(mut self, strut_style: StrutStyle) -> RichText {
        self.strut_style = Some(strut_style);
        self
    }

    /// Dart `RichText(textWidthBasis:)`.
    pub fn text_width_basis(mut self, text_width_basis: TextWidthBasis) -> RichText {
        self.text_width_basis = text_width_basis;
        self
    }

    /// Dart `RichText(textHeightBehavior:)`.
    pub fn text_height_behavior(mut self, text_height_behavior: TextHeightBehavior) -> RichText {
        self.text_height_behavior = Some(text_height_behavior);
        self
    }

    /// Dart `RichText(selectionRegistrar:)`.
    pub fn selection_registrar(mut self, registrar: SelectionRegistrarRef) -> RichText {
        self.selection_registrar = Some(registrar);
        self
    }

    /// Dart `RichText(selectionColor:)`.
    pub fn selection_color(mut self, color: Color) -> RichText {
        self.selection_color = Some(color);
        self
    }

    /// Dart's `_getDevicePixelRatio`.
    fn device_pixel_ratio(app: &mut App, context: BuildContext) -> f64 {
        MediaQuery::maybe_device_pixel_ratio_of(app, context)
            .or_else(|| View::maybe_of(app, context).map(|view| view.metrics().device_pixel_ratio))
            .unwrap_or(1.0)
    }
}

impl RenderObjectWidget for RichText {
    type RenderObject = RenderParagraph;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn debug_check_constructor(&self) {
        debug_assert!(self.selection_registrar.is_none() || self.selection_color.is_some());
    }

    fn create_render_object(&self, app: &mut App, context: BuildContext) -> AnyRenderObject {
        let text_direction = self
            .text_direction
            .unwrap_or_else(|| Directionality::of(app, context));
        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
        let render_object = RenderParagraph::new(app, self.text.clone(), text_direction, None);
        render_object.set_text_align(app, self.text_align);
        render_object.set_soft_wrap(app, self.soft_wrap);
        render_object.set_overflow(app, self.overflow);
        render_object.set_text_scaler(app, self.text_scaler.clone());
        render_object.set_max_lines(app, self.max_lines);
        render_object.set_text_width_basis(app, self.text_width_basis);
        render_object.set_text_height_behavior(app, self.text_height_behavior);
        render_object.set_strut_style(app, self.strut_style.clone());
        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
        render_object.set_registrar(app, self.selection_registrar.clone());
        render_object.set_selection_color(app, self.selection_color);
        render_object.as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        context: BuildContext,
        render_object: RenderHandle<RenderParagraph>,
    ) {
        let text_direction = self
            .text_direction
            .unwrap_or_else(|| Directionality::of(app, context));
        render_object.set_text(app, self.text.clone());
        render_object.set_text_align(app, self.text_align);
        render_object.set_text_direction(app, text_direction);
        render_object.set_soft_wrap(app, self.soft_wrap);
        render_object.set_overflow(app, self.overflow);
        render_object.set_text_scaler(app, self.text_scaler.clone());
        render_object.set_max_lines(app, self.max_lines);
        render_object.set_text_width_basis(app, self.text_width_basis);
        render_object.set_text_height_behavior(app, self.text_height_behavior);
        render_object.set_strut_style(app, self.strut_style.clone());
        let device_pixel_ratio = Self::device_pixel_ratio(app, context);
        render_object.set_device_pixel_ratio(app, device_pixel_ratio);
        render_object.set_registrar(app, self.selection_registrar.clone());
        render_object.set_selection_color(app, self.selection_color);
    }
}

impl MultiChildRenderObjectWidget for RichText {
    fn children(&self) -> &[WidgetRef] {
        &self.children
    }
}

#[cfg(test)]
mod tests {
    use waft_foundation::AppCell;

    use waft_embedder::{Color, Offset, Rect, Size, TextLeadingDistribution, TextPosition};
    use waft_foundation::ValueKey;
    use waft_painting::{PaintingBinding, transform_point};

    use crate::{PlaceholderDimensions, TextPainter};

    use super::*;
    use crate::test_harness::Harness;
    use crate::widgets::media_query::MediaQueryData;

    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
    fn install_fonts(app: &mut App) {
        let binding = PaintingBinding::instance(app);
        if !binding.has_fonts(app) {
            binding.install_fonts(app, |fonts| {
                fonts.add_source(valo_system_fonts::SystemFonts::load());
            });
        }
    }

    /// Dart tests wrap text in a `Directionality`, which `RichText` requires.
    fn ltr(child: WidgetRef) -> WidgetRef {
        Directionality::new(TextDirection::Ltr, child).into_widget()
    }

    /// Mounts `child` with fonts installed and pumps the first frame.
    fn mount(app: &mut App, child: WidgetRef) -> Harness {
        install_fonts(app);
        let harness = Harness::mount(app, ltr(child));
        harness.pump(app);
        harness
    }

    /// The `RenderParagraph` directly under the test root.
    fn paragraph_under_root(harness: &Harness, app: &App) -> RenderHandle<RenderParagraph> {
        harness
            .render_root(app)
            .child(app)
            .expect("a child")
            .as_object()
            .downcast::<RenderParagraph>(app)
            .expect("a RenderParagraph")
    }

    fn style_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> TextStyle {
        paragraph
            .text(app)
            .style()
            .cloned()
            .expect("Text always styles its span")
    }

    fn plain_text_of(paragraph: RenderHandle<RenderParagraph>, app: &App) -> String {
        paragraph.text(app).to_plain_text(true, true)
    }

    #[test]
    fn a_text_lays_out_a_paragraph_with_the_fallback_style() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, Text::new("Hello").into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        let size = paragraph.size(&app);
        assert!(size.width() > 0.0 && size.height() > 0.0);
        assert_eq!(plain_text_of(paragraph, &app), "Hello");
        assert_eq!(
            style_of(paragraph, &app),
            TextStyle::new(),
            "DefaultTextStyle::fallback"
        );
        assert_eq!(paragraph.text_direction(&app), TextDirection::Ltr);
        assert_eq!(paragraph.text_align(&app), TextAlign::Start);
        assert_eq!(paragraph.max_lines(&app), None);
        assert_eq!(paragraph.overflow(&app), TextOverflow::Clip);
    }

    #[test]
    fn a_rich_text_span_becomes_the_child_of_the_styled_span() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let span = TextSpan::new().text("Hello").into_span();
        let harness = mount(&mut app, Text::rich(span).into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(plain_text_of(paragraph, &app), "Hello");
        assert!(paragraph.size(&app).width() > 0.0);
    }

    #[test]
    fn a_default_text_style_styles_the_text_and_notifies_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        // One Text instance, reused like a `const` widget, so only the default style decides
        // rebuilds.
        let text: WidgetRef = Text::new("Hello").into_widget();
        let styled = |font_size: f64| {
            DefaultTextStyle::new(TextStyle::new().font_size(font_size), text.clone()).into_widget()
        };
        let harness = mount(&mut app, styled(12.0));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(style_of(paragraph, &app).font_size, Some(12.0));
        let small = paragraph.size(&app);

        harness.set_child(&mut app, ltr(styled(24.0)));
        harness.pump(&mut app);
        assert_eq!(
            paragraph_under_root(&harness, &app),
            paragraph,
            "the same paragraph is restyled"
        );
        assert_eq!(style_of(paragraph, &app).font_size, Some(24.0));
        assert!(paragraph.size(&app).height() > small.height());
    }

    #[test]
    fn an_explicit_style_merges_into_the_default_unless_it_does_not_inherit() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let red = Color::from_argb(255, 255, 0, 0);
        let under_default = |style: TextStyle| {
            DefaultTextStyle::new(
                TextStyle::new().font_size(12.0),
                Text::new("Hello").style(style),
            )
            .into_widget()
        };
        let harness = mount(&mut app, under_default(TextStyle::new().color(red)));
        let paragraph = paragraph_under_root(&harness, &app);
        let merged = style_of(paragraph, &app);
        assert_eq!(merged.font_size, Some(12.0));
        assert_eq!(merged.color, Some(red.into()));

        harness.set_child(
            &mut app,
            ltr(under_default(
                TextStyle::new().inherit(false).font_size(30.0),
            )),
        );
        harness.pump(&mut app);
        let replaced = style_of(paragraph, &app);
        assert_eq!(replaced.font_size, Some(30.0));
        assert_eq!(
            replaced.color, None,
            "a non-inheriting style replaces the default"
        );
    }

    #[test]
    fn a_new_string_updates_the_same_paragraph() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, Text::new("Hello").into_widget());
        let paragraph = paragraph_under_root(&harness, &app);
        let short = paragraph.size(&app);

        harness.set_child(&mut app, ltr(Text::new("Hello there, world").into_widget()));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
        assert_eq!(plain_text_of(paragraph, &app), "Hello there, world");
        assert!(paragraph.size(&app).width() > short.width());
    }

    #[test]
    fn max_lines_and_overflow_reach_the_render_object() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(
            &mut app,
            Text::new("Hello")
                .max_lines(2)
                .overflow(TextOverflow::Ellipsis)
                .soft_wrap(false)
                .text_direction(TextDirection::Rtl)
                .text_align(TextAlign::End)
                .into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.max_lines(&app), Some(2));
        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
        assert!(!paragraph.soft_wrap(&app));
        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
        assert_eq!(paragraph.text_align(&app), TextAlign::End);
    }

    #[test]
    fn a_default_text_style_supplies_what_the_text_leaves_unset() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let under_default = |text: Text| {
            DefaultTextStyle::new(TextStyle::new(), text)
                .max_lines(1)
                .overflow(TextOverflow::Fade)
                .text_align(TextAlign::Center)
                .soft_wrap(false)
                .into_widget()
        };
        let harness = mount(&mut app, under_default(Text::new("Hello")));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.max_lines(&app), Some(1));
        assert_eq!(paragraph.overflow(&app), TextOverflow::Fade);
        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
        assert!(!paragraph.soft_wrap(&app));

        harness.set_child(
            &mut app,
            ltr(under_default(Text::new("Hello").max_lines(3))),
        );
        harness.pump(&mut app);
        assert_eq!(
            paragraph.max_lines(&app),
            Some(3),
            "the Text's own value wins"
        );
    }

    #[test]
    fn the_style_overflow_beats_the_default_text_style_overflow() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = mount(
            &mut app,
            DefaultTextStyle::new(
                TextStyle::new(),
                Text::new("Hello").style(TextStyle::new().overflow(TextOverflow::Ellipsis)),
            )
            .overflow(TextOverflow::Fade)
            .into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.overflow(&app), TextOverflow::Ellipsis);
    }

    #[test]
    fn a_default_text_height_behavior_reaches_the_paragraph_and_notifies_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let text: WidgetRef = Text::new("Hello").into_widget();
        let under_behavior = |leading_distribution: TextLeadingDistribution| {
            DefaultTextHeightBehavior::new(
                TextHeightBehavior {
                    leading_distribution,
                    ..TextHeightBehavior::default()
                },
                text.clone(),
            )
            .into_widget()
        };
        let harness = mount(&mut app, under_behavior(TextLeadingDistribution::Even));
        let paragraph = paragraph_under_root(&harness, &app);
        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
        assert_eq!(behavior.leading_distribution, TextLeadingDistribution::Even);

        harness.set_child(
            &mut app,
            ltr(under_behavior(TextLeadingDistribution::Proportional)),
        );
        harness.pump(&mut app);
        let behavior = paragraph.text_height_behavior(&app).expect("inherited");
        assert_eq!(
            behavior.leading_distribution,
            TextLeadingDistribution::Proportional
        );
    }

    #[test]
    fn a_rich_text_forwards_its_configuration_in_place() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let rich = |text: &str| {
            RichText::new(TextSpan::new().text(text).into_span())
                .text_align(TextAlign::Center)
                .text_direction(TextDirection::Rtl)
                .max_lines(1)
                .into_widget()
        };
        let harness = mount(&mut app, rich("Hello"));
        let paragraph = paragraph_under_root(&harness, &app);
        assert_eq!(paragraph.text_align(&app), TextAlign::Center);
        assert_eq!(paragraph.text_direction(&app), TextDirection::Rtl);
        assert_eq!(paragraph.max_lines(&app), Some(1));

        harness.set_child(&mut app, ltr(rich("Goodbye")));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);
        assert_eq!(plain_text_of(paragraph, &app), "Goodbye");
    }

    #[test]
    fn a_changed_key_replaces_the_paragraph_where_the_same_key_keeps_it() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let keyed = |key: &str| {
            Text::new("Hello")
                .key(ValueKey::new(key.to_owned()).into())
                .into_widget()
        };
        let harness = mount(&mut app, keyed("a"));
        let paragraph = paragraph_under_root(&harness, &app);

        harness.set_child(&mut app, ltr(keyed("a")));
        harness.pump(&mut app);
        assert_eq!(paragraph_under_root(&harness, &app), paragraph);

        harness.set_child(&mut app, ltr(keyed("b")));
        harness.pump(&mut app);
        assert_ne!(paragraph_under_root(&harness, &app), paragraph);
    }

    #[test]
    fn a_media_query_bolds_scales_and_spaces_the_text() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let data = MediaQueryData::new()
            .bold_text(true)
            .text_scaler(TextScaler::linear(2.0))
            .line_height_scale_factor_override(1.5)
            .letter_spacing_override(3.0)
            .word_spacing_override(4.0);
        let harness = mount(
            &mut app,
            MediaQuery::new(data, Text::new("Hello")).into_widget(),
        );
        let paragraph = paragraph_under_root(&harness, &app);
        let style = style_of(paragraph, &app);
        assert_eq!(style.font_weight, Some(FontWeight::BOLD));
        assert_eq!(style.height, Some(1.5));
        assert_eq!(style.letter_spacing, Some(3.0));
        assert_eq!(style.word_spacing, Some(4.0));
        assert_eq!(paragraph.text_scaler(&app), TextScaler::linear(2.0));
    }

    // ---- selection ----

    use waft_rendering::{SelectionEvent, SelectionStatus};

    use waft_scheduler::{FrameTarget, SchedulerBinding};

    use crate::testing::{WidgetTester, find, test_widgets};
    use crate::widgets::basic::{Column, SizedBox};
    use crate::widgets::selectable_region::PlainStaticSelectionContainerDelegate;
    use crate::widgets::selection_container::SelectionContainer;

    /// Pumps `texts` in a column under a selection container, as under a `SelectableRegion`, and
    /// answers the container's delegate.
    fn pump_selectable_texts(
        tester: &mut WidgetTester,
        texts: Vec<WidgetRef>,
    ) -> Ref<PlainStaticSelectionContainerDelegate> {
        let delegate = tester.update(PlainStaticSelectionContainerDelegate::new);
        tester.pump_widget(Directionality::new(
            TextDirection::Ltr,
            SelectionContainer::new(delegate.erase(), Column::new().children(texts)),
        ));
        tester.pump_and_settle();
        // The outer container registers itself from a microtask after the frame, so its
        // selectable reaches the delegate at the next frame.
        tester.update(|app| SchedulerBinding::schedule_frame(app, FrameTarget::EveryView));
        tester.pump();
        tester.pump_and_settle();
        delegate
    }

    /// The global position of the caret at `offset` in `paragraph`, five pixels down from the
    /// top of the line.
    fn position_of(
        tester: &mut WidgetTester,
        paragraph: RenderHandle<RenderParagraph>,
        offset: i32,
    ) -> Offset {
        tester.update(|app| {
            let local = paragraph.get_offset_for_caret(app, TextPosition::new(offset), Rect::ZERO)
                + Offset::new(0.0, 5.0);
            transform_point(&paragraph.as_object().get_transform_to(app, None), local)
        })
    }

    /// Sends `event` to `handle`.
    fn dispatch<D: SelectionHandler>(
        tester: &mut WidgetTester,
        handle: Handle<D>,
        event: SelectionEvent,
    ) {
        tester.update(|app| {
            SelectionHandler::dispatch_selection_event(handle, app, &event);
        });
    }

    /// The selected range and status of `handle`.
    fn assert_selection<D: SelectionHandler>(
        tester: &WidgetTester,
        handle: Handle<D>,
        expected_range: Option<(i32, i32)>,
        expected_status: SelectionStatus,
    ) {
        tester.update(|app| {
            let range = SelectionHandler::selection(handle, app);
            assert_eq!(
                range.map(|range| (range.start_offset, range.end_offset)),
                expected_range
            );
            assert_eq!(SelectionHandler::value(handle, app).status, expected_status);
        });
    }

    /// The plain text `handle` has selected, or `None`.
    fn selected_text<D: SelectionHandler>(
        tester: &WidgetTester,
        handle: Handle<D>,
    ) -> Option<String> {
        tester.update(|app| {
            SelectionHandler::selected_content(handle, app).map(|content| content.plain_text)
        })
    }

    /// The paragraph showing `text`.
    fn paragraph_showing(tester: &WidgetTester, text: &str) -> RenderHandle<RenderParagraph> {
        let paragraphs = tester.all::<RenderParagraph>();
        tester.update(|app| {
            *paragraphs
                .iter()
                .find(|paragraph| paragraph.text(app).to_plain_text(true, true) == text)
                .unwrap_or_else(|| panic!("a paragraph showing {text}"))
        })
    }

    /// `paragraph`'s one selection, as its start and end.
    fn paragraph_selection(
        tester: &WidgetTester,
        paragraph: RenderHandle<RenderParagraph>,
    ) -> (i32, i32) {
        tester.update(|app| {
            let selections = paragraph.selections(app);
            assert_eq!(selections.len(), 1, "one selection");
            (selections[0].start(), selections[0].end())
        })
    }

    // selectable_region_test.dart 'onSelectionChanged SelectedContentRange is accurate', now
    // through `Text`, which builds its own selection container.
    #[test]
    fn the_selection_range_covers_the_texts_between_the_edges() {
        test_widgets(|tester| {
            let delegate = pump_selectable_texts(
                tester,
                vec![
                    Text::new("How are you?").into_widget(),
                    Text::new("Good, and you?").into_widget(),
                    Text::new("Fine, thank you.").into_widget(),
                ],
            );
            let paragraphs = tester.all::<RenderParagraph>();
            assert_eq!(paragraphs.len(), 3);
            let start = position_of(tester, paragraphs[0], 4);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_start(start, None),
            );

            let end = position_of(tester, paragraphs[0], 7);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(end, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((4, 7)),
                SelectionStatus::Uncollapsed,
            );

            let end = position_of(tester, paragraphs[0], 10);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(end, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((4, 10)),
                SelectionStatus::Uncollapsed,
            );

            let end = position_of(tester, paragraphs[1], 10);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(end, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((4, 22)),
                SelectionStatus::Uncollapsed,
            );

            let end = position_of(tester, paragraphs[2], 10);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(end, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((4, 36)),
                SelectionStatus::Uncollapsed,
            );

            // A collapsed selection, as a click makes one.
            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
            let point = position_of(tester, paragraphs[0], 3);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_start(point, None),
            );
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(point, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((3, 3)),
                SelectionStatus::Collapsed,
            );

            // A backward selection.
            dispatch(tester, delegate.handle(), SelectionEvent::Clear);
            let start = position_of(tester, paragraphs[2], 4);
            let end = position_of(tester, paragraphs[0], 0);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_start(start, None),
            );
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(end, None),
            );
            assert_selection(
                tester,
                delegate.handle(),
                Some((30, 0)),
                SelectionStatus::Uncollapsed,
            );
        });
    }

    // selectable_region_test.dart 'can select word when selectable is broken up by an
    // unselectable WidgetSpan': the fragment that starts after the span is selected, and the
    // range counts from the paragraph's start.
    #[test]
    fn a_word_after_a_widget_span_is_selected_and_ranged_from_the_paragraph_start() {
        const BEFORE: &str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
        // The 123 characters, then the placeholder, then "Hello, world.": the word is at 124.
        assert_eq!(BEFORE.len(), 123, "as in the test");
        test_widgets(|tester| {
            let span = TextSpan::new()
                .children(vec![
                    TextSpan::new().text(BEFORE).into_span(),
                    WidgetSpan::new(SizedBox::shrink()).into_span(),
                    TextSpan::new().text("Hello, world.").into_span(),
                ])
                .into_span();
            let delegate = pump_selectable_texts(tester, vec![Text::rich(span).into_widget()]);
            let paragraphs = tester.all::<RenderParagraph>();
            assert_eq!(paragraphs.len(), 1);
            let position = position_of(tester, paragraphs[0], 125);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::SelectWord {
                    global_position: position,
                },
            );

            assert_eq!(paragraph_selection(tester, paragraphs[0]), (124, 129));
            assert_eq!(
                selected_text(tester, delegate.handle()),
                Some("Hello".to_string())
            );
            // Dart's range counts the first fragment's whole content and then the distance to
            // where the selected fragment starts in the paragraph, so the placeholder the
            // unselected fragment ends at is not counted.
            assert_selection(
                tester,
                delegate.handle(),
                Some((123, 128)),
                SelectionStatus::Uncollapsed,
            );
        });
    }

    // selectable_region_test.dart 'selects backwards across multiple Text widgets and
    // WidgetSpans via mouse drag': every inner and outer text is fully selected.
    #[test]
    fn a_backward_drag_selects_every_inner_and_outer_text() {
        test_widgets(|tester| {
            let texts = (0..5)
                .map(|index| {
                    let number = index + 1;
                    Text::rich(
                        TextSpan::new()
                            .children(vec![
                                WidgetSpan::new(Text::new(format!("{number}. "))).into_span(),
                                TextSpan::new().text(format!("Item {number}")).into_span(),
                            ])
                            .into_span(),
                    )
                    .key(ValueKey::new(index as usize).into())
                    .into_widget()
                })
                .collect();
            let delegate = pump_selectable_texts(tester, texts);
            let drag_start = tester.get_bottom_right(find::by_key(ValueKey::new(4usize)));
            let drag_end = tester.get_top_left(find::by_key(ValueKey::new(0usize)));
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_start(drag_start, None),
            );
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(drag_end, None),
            );

            for index in 0..5 {
                let number = index + 1;
                let inner = paragraph_showing(tester, &format!("{number}. "));
                let length =
                    tester.update(|app| inner.text(app).to_plain_text(true, true).len() as i32);
                assert_eq!(paragraph_selection(tester, inner), (0, length));

                let outer_text = format!("\u{FFFC}Item {number}");
                let outer = paragraph_showing(tester, &outer_text);
                assert_eq!(
                    paragraph_selection(tester, outer),
                    (1, outer_text.chars().count() as i32)
                );
            }
        });
    }

    // selectable_region_test.dart 'mouse can select multiple widgets on triple click drag when
    // selecting inside a WidgetSpan': a paragraph extension drag selects every line it crosses,
    // and the range counts each inner text's content.
    #[test]
    fn a_paragraph_extension_selects_the_lines_it_crosses() {
        test_widgets(|tester| {
            let texts: Vec<WidgetRef> = (0..5)
                .map(|index| {
                    Text::new(format!("Text widget {}.", (b'A' + index) as char)).into_widget()
                })
                .collect();
            let span = WidgetSpan::new(Column::new().children(texts)).into_span();
            let delegate = pump_selectable_texts(tester, vec![Text::rich(span).into_widget()]);
            let paragraph_c = paragraph_showing(tester, "Text widget C.");
            let paragraph_e = paragraph_showing(tester, "Text widget E.");
            let point_c = position_of(tester, paragraph_c, 2);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::SelectParagraph {
                    global_position: point_c,
                    absorb: false,
                },
            );
            assert_eq!(paragraph_selection(tester, paragraph_c), (0, 14));

            let point_e = position_of(tester, paragraph_e, 5);
            dispatch(
                tester,
                delegate.handle(),
                SelectionEvent::for_end(point_e, Some(waft_rendering::TextGranularity::Paragraph)),
            );
            assert_eq!(paragraph_selection(tester, paragraph_c), (0, 14));
            assert_eq!(
                paragraph_selection(tester, paragraph_showing(tester, "Text widget D.")),
                (0, 14)
            );
            assert_eq!(paragraph_selection(tester, paragraph_e), (0, 14));
            // A, B, C, D and E are 14 characters each; C through E is 28..70.
            assert_selection(
                tester,
                delegate.handle(),
                Some((28, 70)),
                SelectionStatus::Uncollapsed,
            );
        });
    }

    #[test]
    fn force_strut_height_applies_to_widget_spans() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let fonts = PaintingBinding::instance(&mut app).install_flutter_test_fonts(&mut app);
        let span = TextSpan::new()
            .children(vec![
                WidgetSpan::new(crate::widgets::basic::SizedBox::new()).into_span(),
            ])
            .into_span();
        let mut painter = TextPainter::new();
        painter.set_text(Some(span));
        painter.set_text_direction(Some(TextDirection::Ltr));
        painter.set_strut_style(Some(
            StrutStyle::new()
                .height(10.0)
                .font_size(10.0)
                .force_strut_height(true),
        ));
        painter.set_placeholder_dimensions(Some(vec![PlaceholderDimensions::new(
            Size::new(1000.0, 1000.0),
            waft_embedder::PlaceholderAlignment::Bottom,
        )]));
        painter.layout(app.get_mut(fonts), 0.0, f64::INFINITY);
        assert_eq!(painter.height(), 100.0);
    }

    #[test]
    fn text_rich_respects_the_media_query_spacing_overrides_on_its_strut() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let overridden = MediaQuery::new(
            MediaQueryData::new()
                .line_height_scale_factor_override(2.0)
                .letter_spacing_override(2.0)
                .word_spacing_override(2.0),
            Text::rich(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9)),
        )
        .into_widget();
        let harness = mount(&mut app, overridden);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(
            span_style.as_ref().and_then(|style| style.height),
            Some(2.0)
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            Some(2.0)
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            Some(2.0)
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(2.0)
        );

        harness.set_child(
            &mut app,
            ltr(Text::rich(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9))
                .into_widget()),
        );
        harness.pump(&mut app);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            None
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            None
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(0.9)
        );
    }

    #[test]
    fn rich_text_ignores_the_media_query_spacing_overrides() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let overridden = MediaQuery::new(
            MediaQueryData::new()
                .line_height_scale_factor_override(2.0)
                .letter_spacing_override(2.0)
                .word_spacing_override(2.0),
            RichText::new(TextSpan::new().text("Hello").into_span())
                .text_direction(TextDirection::Ltr)
                .strut_style(StrutStyle::new().height(0.9)),
        )
        .into_widget();
        let harness = mount(&mut app, overridden);
        let paragraph = paragraph_under_root(&harness, &app);
        let span_style = paragraph.text(&app).style().cloned();
        assert_eq!(span_style.as_ref().and_then(|style| style.height), None);
        assert_eq!(
            span_style.as_ref().and_then(|style| style.letter_spacing),
            None
        );
        assert_eq!(
            span_style.as_ref().and_then(|style| style.word_spacing),
            None
        );
        assert_eq!(
            paragraph
                .strut_style(&app)
                .and_then(|strut_style| strut_style.height),
            Some(0.9)
        );
    }
}