waft-widgets 0.10.0

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
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
//! Flutter counterpart: `widgets/actions.dart`.
//!
//! The action system: [`Intent`] describes what should happen, [`Action`] performs it, the
//! [`Actions`] widget maps one to the other for its descendants, and [`ActionDispatcher`]
//! invokes the action that was found. [`FocusableActionDetector`] combines [`Actions`],
//! `Shortcuts`, `Focus` and `MouseRegion` into the detector a control is built from.

use std::any::{Any, TypeId};
use std::collections::{HashMap, HashSet};
use std::fmt::{self, Debug};
use std::rc::Rc;

use waft_foundation::{
    App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, HandleId, Listener,
    OptionRetained, Ref, Retained, ValueChanged, describe_identity,
};
use waft_scheduler::{FrameCallback, SchedulerBinding, SchedulerPhase};
use waft_services::{MouseCursor, MouseCursorRef};

use crate::framework::{
    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
    WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::MouseRegion;
use crate::widgets::focus_manager::{
    FocusHighlightMode, FocusManager, FocusNodeRef, HighlightModeListener, KeyEventResult,
    primary_focus,
};
use crate::widgets::focus_scope::Focus;
use crate::widgets::media_query::{MediaQuery, NavigationMode};
use crate::widgets::shortcuts::{ShortcutMap, Shortcuts};

/// Returns the parent [`BuildContext`] of a given `context`.
///
/// [`BuildContext`] doesn't have a `parent` accessor, but the parent can be obtained using
/// [`BuildContext::visit_ancestor_elements`](crate::AnyElement::visit_ancestor_elements).
///
/// [`BuildContext::get_element_for_inherited_widget_of_exact_type`](crate::AnyElement::get_element_for_inherited_widget_of_exact_type)
/// returns the same [`BuildContext`] if it happens to be of the correct type. To obtain the
/// previous inherited widget, the search must therefore start from the parent; this is what
/// `get_parent` is used for.
///
/// `get_parent` is O(1), because it always stops at the first ancestor.
fn get_parent(app: &App, context: BuildContext) -> Option<BuildContext> {
    let mut parent = None;
    context.visit_ancestor_elements(app, &mut |ancestor| {
        parent = Some(ancestor);
        false
    });
    parent
}

// ---------------------------------------------------------------------------------------------
// Intent

/// A particular configuration of an [`Action`].
///
/// This trait is what the `Shortcuts::shortcuts` map has as values, and is used by an
/// [`ActionDispatcher`] to look up an action and invoke it, giving it this object to extract
/// configuration information from.
///
/// See also:
///
///  * `Shortcuts`, a widget used to bind key combinations to [`Intent`]s.
///  * [`Actions`], a widget used to map [`Intent`]s to [`Action`]s.
///  * [`Actions::invoke`], which invokes the action associated with a specified [`Intent`]
///    using the [`Actions`] widget that most tightly encloses the given [`BuildContext`].
pub trait Intent: Debug + 'static {
    /// The value behind the erased intent, for the downcast an [`Action`] does to recover its
    /// own intent type.
    fn as_any(&self) -> &dyn Any;

    /// Dart's `intent.runtimeType`: the key an [`Actions`] map is looked up with.
    fn intent_type(&self) -> TypeId {
        self.as_any().type_id()
    }

    /// Dart's `Intent.debugFillProperties`, from `Diagnosticable`: an intent adds its own
    /// fields.
    fn debug_fill_properties(&self, properties: &mut waft_foundation::DiagnosticPropertiesBuilder) {
        let _ = properties;
    }

    /// Dart's `Intent.toStringShort`: the type and the identity.
    fn to_string_short(&self) -> String {
        describe_identity(
            waft_foundation::bare_type_name(std::any::type_name::<Self>()),
            self as *const Self as *const () as usize as u64,
        )
    }

    /// Dart's `Intent.toDiagnosticsNode(name:)`, from `Diagnosticable`.
    fn diagnostics_node(&self, name: Option<String>) -> waft_foundation::DiagnosticableNode {
        let mut builder = DiagnosticPropertiesBuilder::new();
        self.debug_fill_properties(&mut builder);
        waft_foundation::DiagnosticableNode::from_parts(name, self.to_string_short(), builder)
    }

    /// Dart's `Diagnosticable.toString`, which a property holding an intent prints.
    fn diagnostic_string(&self) -> String {
        use waft_foundation::{DiagnosticLevel, DiagnosticsNode, DiagnosticsTreeStyle};
        self.diagnostics_node(None)
            .with_style(DiagnosticsTreeStyle::SingleLine)
            .to_string_with(None, DiagnosticLevel::Info)
    }
}

/// The erased [`Intent`] value: what a field or parameter Dart types as `Intent` becomes.
pub type IntentRef = Rc<dyn Intent>;

/// An intent that is mapped to a [`DoNothingAction`], which, as the name implies, does
/// nothing.
///
/// This intent is mapped to an action in the `WidgetsApp` that does nothing, so that it can be
/// bound to a key in a `Shortcuts` widget in order to disable a key binding made above it in
/// the hierarchy.
///
/// Dart's `Intent.doNothing`.
pub const DO_NOTHING: DoNothingIntent = DoNothingIntent::new();

/// The type argument of an [`Action`]: Dart's `T extends Intent` in `Action<T>`.
///
/// Every [`Intent`] implements it, and so does `dyn Intent`, which is Dart's `Action<Intent>` —
/// an action that handles every intent.
pub trait ActionIntent: 'static {
    /// Dart's `intent is T`.
    fn cast_intent(intent: &dyn Intent) -> Option<&Self>;

    /// This value back as the erased [`Intent`], for the lookups keyed by intent type.
    fn as_intent(&self) -> &dyn Intent;
}

impl<T: Intent> ActionIntent for T {
    fn cast_intent(intent: &dyn Intent) -> Option<&T> {
        intent.as_any().downcast_ref::<T>()
    }

    fn as_intent(&self) -> &dyn Intent {
        self
    }
}

impl ActionIntent for dyn Intent {
    fn cast_intent(intent: &dyn Intent) -> Option<&dyn Intent> {
        Some(intent)
    }

    fn as_intent(&self) -> &dyn Intent {
        self
    }
}

// ---------------------------------------------------------------------------------------------
// Action

/// The kind of callback that an [`Action`] uses to notify of changes to the action's state.
///
/// To register an action listener, call [`Action::add_action_listener`].
pub type ActionListenerCallback = Rc<dyn Fn(&mut App, AnyAction)>;

/// The fields Dart's `Action` declares; every action carries this bag under the field
/// `action`.
pub struct ActionData {
    listeners: Vec<ActionListenerCallback>,
    current_calling_action: Option<ActionRef>,
}

impl ActionData {
    /// The bag of a freshly created action.
    pub fn new() -> ActionData {
        ActionData {
            listeners: Vec::new(),
            current_calling_action: None,
        }
    }
}

impl Default for ActionData {
    fn default() -> ActionData {
        ActionData::new()
    }
}

/// The accessors [`Action`] asks for, for a struct whose bag is the field `action`.
#[macro_export]
macro_rules! action_accessors {
    () => {
        fn action_data(
            self: ::waft_foundation::Handle<Self>,
            app: &::waft_foundation::App,
        ) -> &$crate::ActionData {
            &app.get(self).action
        }

        fn action_data_mut(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
        ) -> &mut $crate::ActionData {
            &mut app.get_mut(self).action
        }
    };
}

/// The overrides a [`ContextAction`] leaf adds to its `impl Action`: the type-erased handle
/// that carries the context through, the two context-less entry points Dart gets from an optional
/// parameter, and the overridable form.
#[macro_export]
macro_rules! context_action_overrides {
    () => {
        fn as_action(self: ::waft_foundation::Handle<Self>) -> $crate::AnyAction {
            $crate::AnyAction::of_context::<Self>(self)
        }

        fn is_enabled(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            intent: &Self::Intent,
        ) -> bool {
            $crate::ContextAction::is_enabled(self, app, intent, None)
        }

        fn invoke(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            intent: &Self::Intent,
        ) -> Option<::std::rc::Rc<dyn ::std::any::Any>> {
            $crate::ContextAction::invoke(self, app, intent, None)
        }

        fn make_overridable_action(
            self: ::waft_foundation::Handle<Self>,
            app: &mut ::waft_foundation::App,
            context: $crate::BuildContext,
        ) -> $crate::ActionRef {
            let default_action: $crate::ActionRef = self.keep(app).into_erased();
            $crate::OverridableContextAction::<Self::Intent>::new(app, default_action, context)
                .into_erased()
        }
    };
}

/// Base trait for an action or command to be performed.
///
/// [`Action`]s are typically invoked as a result of a user action. For example, the `Shortcuts`
/// widget will map a keyboard shortcut into an [`Intent`], which is given to an
/// [`ActionDispatcher`] to map the [`Intent`] to an [`Action`] and invoke it.
///
/// The [`ActionDispatcher`] can invoke an [`Action`] on the primary focus, or without regard
/// for focus.
///
/// ### Action Overriding
///
/// When using a leaf widget to build a more specialized widget, it's sometimes desirable to
/// change the default handling of an [`Intent`] defined in the leaf widget. For instance, a
/// text field's select-all intent by default selects the text it currently contains, but in a
/// US phone number widget that consists of 3 different text fields (area code, prefix and line
/// number), it should instead select the text within all 3 text fields.
///
/// An overridable [`Action`] is a special kind of [`Action`] created using
/// [`AnyAction::overridable`]. It has access to a default [`Action`], and an optional override
/// [`Action`]. It has the same behavior as its override if that exists, and mirrors the
/// behavior of its `default_action` otherwise.
///
/// See also:
///
///  * `Shortcuts`, which is a widget that contains a key map, in which it looks up key
///    combinations in order to invoke actions.
///  * [`Actions`], which is a widget that defines a map of [`Intent`] to [`Action`] and allows
///    redefining of actions for its descendants.
///  * [`ActionDispatcher`], a class that takes an [`Action`] and invokes it, passing a given
///    [`Intent`].
pub trait Action: Sized + 'static {
    /// Dart's type argument `T extends Intent`.
    ///
    /// `dyn Intent` is Dart's `Action<Intent>`: an action that handles every intent.
    type Intent: ActionIntent + ?Sized;

    /// Dart's `Action` fields, held under the field `action`
    /// ([`action_accessors!`](crate::action_accessors)).
    fn action_data(self: Handle<Self>, app: &App) -> &ActionData;

    /// See [`action_data`](Self::action_data).
    fn action_data_mut(self: Handle<Self>, app: &mut App) -> &mut ActionData;

    /// Dart's `Action.debugFillProperties`, from `Diagnosticable`: an action adds its own
    /// fields.
    fn debug_fill_properties(
        self: Handle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        let _ = (self, app, properties);
    }

    /// This action as the erased [`AnyAction`] — what to pass where a Dart API takes an
    /// `Action<Intent>`.
    ///
    /// A [`ContextAction`] overrides this with
    /// [`context_action_overrides!`](crate::context_action_overrides), so that the type-erased
    /// handle carries the invoking context through.
    fn as_action(self: Handle<Self>) -> AnyAction {
        AnyAction::of::<Self>(self)
    }

    /// Gets the type of intent this action responds to.
    fn intent_type() -> TypeId {
        TypeId::of::<Self::Intent>()
    }

    /// The [`Action`] overridden by this [`Action`].
    ///
    /// [`AnyAction::overridable`] creates an overridable [`Action`] that allows itself to be
    /// overridden by the closest ancestor [`Action`], and falls back to its own
    /// `default_action` when no overrides can be found. When an override is present, an
    /// overridable [`Action`] forwards all incoming method calls to the override, and allows
    /// the override to access the `default_action` via its
    /// [`calling_action`](Self::calling_action) property.
    ///
    /// Before forwarding the call to the override, the overridable [`Action`] is responsible
    /// for setting [`calling_action`](Self::calling_action) to its `default_action`, which is
    /// already taken care of by the overridable [`Action`] created using
    /// [`AnyAction::overridable`].
    ///
    /// This property is only set when this [`Action`] is an override of the calling action,
    /// and is currently being invoked from it.
    ///
    /// Invoking the calling action's methods, or accessing its properties, is allowed and does
    /// not introduce infinite loops or infinite recursions.
    fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
        self.action_data(app).current_calling_action.handle()
    }

    /// Sets [`calling_action`](Self::calling_action); overridden by the overridable actions so
    /// that the default action sees it too.
    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
        self.action_data_mut(app).current_calling_action = value;
    }

    /// Returns true if the action is enabled and is ready to be invoked.
    ///
    /// This will be called by the [`ActionDispatcher`] before attempting to invoke the action.
    ///
    /// If the action's enable state depends on a [`BuildContext`], implement [`ContextAction`]
    /// instead.
    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
        let _ = intent;
        self.is_action_enabled(app)
    }

    /// Whether this [`Action`] is inherently enabled.
    ///
    /// If [`is_action_enabled`](Self::is_action_enabled) is false, then this [`Action`] is
    /// disabled for any given [`Intent`].
    ///
    /// If the enabled state changes, overriding implementations must call
    /// [`notify_action_listeners`](Self::notify_action_listeners) to notify any listeners of
    /// the change.
    ///
    /// In the case of an overridable action, accessing this property creates a dependency on
    /// the overridable action's lookup context.
    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
        let _ = app;
        true
    }

    /// Indicates whether this action should treat key events mapped to this action as being
    /// "handled" when it is invoked via the key event.
    ///
    /// If the key is handled, then no other key event handlers in the focus chain will receive
    /// the event.
    ///
    /// If the key event is not handled, it will be passed back to the engine, and continue to
    /// be processed there, allowing text fields and non-Flutter widgets to receive the key
    /// event.
    ///
    /// The default implementation returns true.
    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
        let _ = (app, intent);
        true
    }

    /// Converts the result of [`invoke`](Self::invoke) of this action to a [`KeyEventResult`].
    ///
    /// This is typically used when the action is invoked in response to a keyboard shortcut.
    ///
    /// The `invoke_result` argument is the value returned by [`invoke`](Self::invoke).
    ///
    /// By default, calls [`consumes_key`](Self::consumes_key) and converts the returned boolean
    /// to [`KeyEventResult::Handled`] if it's true, and
    /// [`KeyEventResult::SkipRemainingHandlers`] if it's false.
    fn to_key_event_result(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        invoke_result: Option<&Rc<dyn Any>>,
    ) -> KeyEventResult {
        let _ = invoke_result;
        if self.consumes_key(app, intent) {
            KeyEventResult::Handled
        } else {
            KeyEventResult::SkipRemainingHandlers
        }
    }

    /// Called when the action is to be performed.
    ///
    /// This is called by the [`ActionDispatcher`] when an action is invoked via
    /// [`Actions::invoke`], or when an action is invoked using
    /// [`ActionDispatcher::invoke_action`] directly.
    ///
    /// This method is only meant to be invoked by an [`ActionDispatcher`], and only when
    /// [`is_enabled`](Self::is_enabled) is true.
    ///
    /// To receive the result of invoking an action, it must be invoked using
    /// [`Actions::invoke`], or by invoking it using an [`ActionDispatcher`]. An action invoked
    /// via a `Shortcuts` widget will have its return value ignored.
    ///
    /// If the action's behavior depends on a [`BuildContext`], implement [`ContextAction`]
    /// instead.
    fn invoke(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> Option<Rc<dyn Any>>;

    /// Register a callback to listen for changes to the state of this action.
    ///
    /// If you call this, you must call
    /// [`remove_action_listener`](Self::remove_action_listener) a matching number of times, or
    /// memory leaks will occur. To help manage this and avoid memory leaks, use of the
    /// [`ActionListener`] widget to register and unregister your listener appropriately is
    /// highly recommended.
    fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
        self.action_data_mut(app).listeners.push(listener);
    }

    /// Remove a previously registered closure from the list of closures that are notified when
    /// the object changes.
    ///
    /// If the given listener is not registered, the call is ignored.
    fn remove_action_listener(
        self: Handle<Self>,
        app: &mut App,
        listener: &ActionListenerCallback,
    ) {
        let listeners = &mut self.action_data_mut(app).listeners;
        if let Some(index) = listeners
            .iter()
            .position(|registered| Rc::ptr_eq(registered, listener))
        {
            listeners.remove(index);
        }
    }

    /// Call all the registered listeners.
    ///
    /// Implementations should call this method whenever the object changes, to notify any
    /// clients the object may have changed. Listeners that are added during this iteration
    /// will not be visited. Listeners that are removed during this iteration will not be
    /// visited after they are removed.
    fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
        if self.action_data(app).listeners.is_empty() {
            return;
        }
        // Make a local copy so that a listener can unregister while the list is being iterated
        // over.
        let local_listeners = self.action_data(app).listeners.clone();
        let this = self.as_action();
        for listener in local_listeners {
            let still_registered = self
                .action_data(app)
                .listeners
                .iter()
                .any(|registered| Rc::ptr_eq(registered, &listener));
            if still_registered {
                listener(app, this);
            }
        }
    }

    /// Dart's `Action._makeOverridableAction`: the overridable form of this action, which
    /// [`AnyAction::overridable`] hands back.
    fn make_overridable_action(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
    ) -> ActionRef {
        let default_action: ActionRef = self.keep(app).into_erased();
        OverridableAction::<Self::Intent>::new(app, default_action, context).into_erased()
    }
}

/// An [`Action`] that adds an optional [`BuildContext`] to the
/// [`is_enabled`](Self::is_enabled) and [`invoke`](Self::invoke) methods to be able to provide
/// context to actions.
///
/// [`ActionDispatcher::invoke_action`] checks to see if the action it is invoking is a
/// [`ContextAction`], and if it is, supplies it with a context; the type-erased handle a
/// [`ContextAction`] hands out ([`context_action_overrides!`](crate::context_action_overrides))
/// is what answers that check.
pub trait ContextAction: Action {
    /// Returns true if the action is enabled and is ready to be invoked.
    ///
    /// This will be called by the [`ActionDispatcher`] before attempting to invoke the action.
    ///
    /// The optional `context` parameter is the context of the invocation of the action, and in
    /// the case of an action invoked by a `ShortcutManager`, via a `Shortcuts` widget, will be
    /// the context of the `Shortcuts` widget.
    fn is_enabled(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        context: Option<BuildContext>,
    ) -> bool {
        let _ = (intent, context);
        Action::is_action_enabled(self, app)
    }

    /// Called when the action is to be performed.
    ///
    /// This is called by the [`ActionDispatcher`] when an action is invoked via
    /// [`Actions::invoke`], or when an action is invoked using
    /// [`ActionDispatcher::invoke_action`] directly.
    ///
    /// This method is only meant to be invoked by an [`ActionDispatcher`], and only when
    /// [`is_enabled`](Self::is_enabled) is true.
    ///
    /// The optional `context` parameter is the context of the invocation of the action, and in
    /// the case of an action invoked by a `ShortcutManager`, via a `Shortcuts` widget, will be
    /// the context of the `Shortcuts` widget.
    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>>;
}

/// The vtable's `Action.toKeyEventResult`, over the erased invoke result.
type ToKeyEventResultFn =
    fn(&mut App, HandleId, &dyn Intent, Option<&Rc<dyn Any>>) -> KeyEventResult;

/// The vtable's `Action._invoke`.
type InvokeFn = fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> Option<Rc<dyn Any>>;

/// The vtable of an erased [`AnyAction`]: one `&'static` table per leaf type, built by
/// [`ActionVTable::of`] or [`ActionVTable::of_context`].
struct ActionVTable {
    type_name: fn() -> &'static str,
    intent_type: fn() -> TypeId,
    calling_action: fn(&App, HandleId) -> Option<AnyAction>,
    update_calling_action: fn(&mut App, HandleId, Option<ActionRef>),
    is_enabled: fn(&mut App, HandleId, &dyn Intent, Option<BuildContext>) -> bool,
    is_action_enabled: fn(&mut App, HandleId) -> bool,
    consumes_key: fn(&mut App, HandleId, &dyn Intent) -> bool,
    to_key_event_result: ToKeyEventResultFn,
    invoke: InvokeFn,
    add_action_listener: fn(&mut App, HandleId, ActionListenerCallback),
    remove_action_listener: fn(&mut App, HandleId, &ActionListenerCallback),
    notify_action_listeners: fn(&mut App, HandleId),
    make_overridable_action: fn(&mut App, HandleId, BuildContext) -> ActionRef,
    debug_fill_properties: fn(&App, HandleId, &mut DiagnosticPropertiesBuilder),
}

/// The typed handle for an erased id. Free: nothing is looked up; `get` checks the slot.
fn resolve<L: 'static>(id: HandleId) -> Handle<L> {
    Handle::from_id(id)
}

/// Dart's `_debugCanHandleIntent`, which has to succeed for the leaf to see its own intent.
fn cast_intent<L: Action>(intent: &dyn Intent) -> &L::Intent {
    <L::Intent as ActionIntent>::cast_intent(intent).unwrap_or_else(|| {
        panic!(
            "An Intent of type {:?} cannot be handled by {}: the Intent must be of a subtype \
             of {}.",
            intent,
            std::any::type_name::<L>(),
            std::any::type_name::<L::Intent>()
        )
    })
}

impl ActionVTable {
    /// The table for a plain [`Action`] leaf: Dart's `_isEnabled` / `_invoke` drop the context
    /// because the action is not a `ContextAction`.
    const fn of<L: Action>() -> ActionVTable {
        ActionVTable {
            type_name: std::any::type_name::<L>,
            intent_type: L::intent_type,
            calling_action: |app, id| L::calling_action(resolve(id), app),
            update_calling_action: |app, id, value| {
                L::update_calling_action(resolve(id), app, value)
            },
            is_enabled: |app, id, intent, _context| {
                L::is_enabled(resolve(id), app, cast_intent::<L>(intent))
            },
            is_action_enabled: |app, id| L::is_action_enabled(resolve(id), app),
            consumes_key: |app, id, intent| {
                L::consumes_key(resolve(id), app, cast_intent::<L>(intent))
            },
            to_key_event_result: |app, id, intent, invoke_result| {
                L::to_key_event_result(resolve(id), app, cast_intent::<L>(intent), invoke_result)
            },
            invoke: |app, id, intent, _context| {
                L::invoke(resolve(id), app, cast_intent::<L>(intent))
            },
            add_action_listener: |app, id, listener| {
                L::add_action_listener(resolve(id), app, listener)
            },
            remove_action_listener: |app, id, listener| {
                L::remove_action_listener(resolve(id), app, listener)
            },
            notify_action_listeners: |app, id| L::notify_action_listeners(resolve(id), app),
            make_overridable_action: |app, id, context| {
                L::make_overridable_action(resolve(id), app, context)
            },
            debug_fill_properties: |app, id, properties| {
                L::debug_fill_properties(resolve(id), app, properties)
            },
        }
    }

    /// The table for a [`ContextAction`] leaf: Dart's `_isEnabled` / `_invoke` hand the context
    /// on.
    const fn of_context<L: ContextAction>() -> ActionVTable {
        ActionVTable {
            is_enabled: |app, id, intent, context| {
                ContextAction::is_enabled(resolve::<L>(id), app, cast_intent::<L>(intent), context)
            },
            invoke: |app, id, intent, context| {
                ContextAction::invoke(resolve::<L>(id), app, cast_intent::<L>(intent), context)
            },
            ..ActionVTable::of::<L>()
        }
    }
}

/// Erased `Action<Intent>`: one identity and a static vtable, the fat pointer rustc cannot
/// build for an arena id.
///
/// This is what a field or parameter Dart types as `Action<Intent>` becomes; the leaf stays in
/// the [`App`] under its own type, and [`downcast`](Self::downcast) gets the typed handle back.
///
/// Equality is Dart's `==` on an object reference: two handles are equal exactly when they
/// address the same action.
#[derive(Clone, Copy)]
pub struct AnyAction {
    id: HandleId,
    vtable: &'static ActionVTable,
}

/// A field Dart types as the erased object, kept: AnyAction with its count.
pub type ActionRef = Retained<AnyAction>;

waft_foundation::erased_handle!(AnyAction: Action => Action::as_action);

impl fmt::Debug for AnyAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}({:?})", (self.vtable.type_name)(), self.id)
    }
}

impl AnyAction {
    /// Dart's `Action.toStringShort`: the type and the identity.
    pub fn to_string_short(self) -> String {
        describe_identity(
            waft_foundation::bare_type_name((self.vtable.type_name)()),
            self.id.identity_hash(),
        )
    }

    /// Dart's `action.debugFillProperties`.
    pub fn debug_fill_properties(self, app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        (self.vtable.debug_fill_properties)(app, self.id, properties);
    }

    /// The type-erased handle of a plain [`Action`] leaf; [`Action::as_action`] calls this.
    pub fn of<L: Action>(action: Handle<L>) -> AnyAction {
        AnyAction {
            id: action.id(),
            vtable: const { &ActionVTable::of::<L>() },
        }
    }

    /// The type-erased handle of a [`ContextAction`] leaf;
    /// [`context_action_overrides!`](crate::context_action_overrides) calls this.
    pub fn of_context<L: ContextAction>(action: Handle<L>) -> AnyAction {
        AnyAction {
            id: action.id(),
            vtable: const { &ActionVTable::of_context::<L>() },
        }
    }

    /// Creates an [`Action`] that allows itself to be overridden by the closest ancestor
    /// [`Action`] in the given `context` that handles the same [`Intent`], if one exists.
    ///
    /// When invoked, the resulting [`Action`] tries to find the closest [`Action`] in the given
    /// `context` that handles the same type of [`Intent`] as the `default_action`, then calls
    /// its [`invoke`](Self::invoke) method. When no override [`Action`]s can be found, it
    /// invokes the `default_action`.
    ///
    /// An overridable action delegates everything to its override if one exists, and has the
    /// same behavior as its `default_action` otherwise. For this reason, the override has full
    /// control over whether and how an [`Intent`] should be handled, or a key event should be
    /// consumed. An override [`Action`]'s [`Action::calling_action`] property will be set to
    /// the [`Action`] it currently overrides, giving it access to the default behavior.
    ///
    /// The `context` argument is the [`BuildContext`] to find the override with. It is
    /// typically a [`BuildContext`] above the [`Actions`] widget that contains this overridable
    /// [`Action`].
    ///
    /// The `default_action` argument is the [`Action`] to be invoked where no ancestor
    /// [`Action`]s can be found in `context` that handle the same type of [`Intent`].
    ///
    /// Dart's `Action.overridable`.
    pub fn overridable(
        app: &mut App,
        default_action: ActionRef,
        context: BuildContext,
    ) -> ActionRef {
        default_action.make_overridable_action(app, context)
    }

    /// The arena id behind this handle.
    pub fn id(self) -> HandleId {
        self.id
    }

    /// Dart's `action as T`: the typed handle when this action is a `T`, else `None`.
    pub fn downcast<T: 'static>(self, app: &App) -> Option<Handle<T>> {
        app.handle::<T>(self.id)
    }

    /// See [`Action::intent_type`].
    pub fn intent_type(self) -> TypeId {
        (self.vtable.intent_type)()
    }

    /// See [`Action::calling_action`].
    pub fn calling_action(self, app: &App) -> Option<AnyAction> {
        (self.vtable.calling_action)(app, self.id)
    }

    /// See [`Action::update_calling_action`].
    pub fn update_calling_action(self, app: &mut App, value: Option<ActionRef>) {
        (self.vtable.update_calling_action)(app, self.id, value);
    }

    /// Dart's `Action._isEnabled`: [`ContextAction::is_enabled`] when the action is a
    /// [`ContextAction`], [`Action::is_enabled`] otherwise.
    pub fn is_enabled(
        self,
        app: &mut App,
        intent: &dyn Intent,
        context: Option<BuildContext>,
    ) -> bool {
        (self.vtable.is_enabled)(app, self.id, intent, context)
    }

    /// See [`Action::is_action_enabled`].
    pub fn is_action_enabled(self, app: &mut App) -> bool {
        (self.vtable.is_action_enabled)(app, self.id)
    }

    /// See [`Action::consumes_key`].
    pub fn consumes_key(self, app: &mut App, intent: &dyn Intent) -> bool {
        (self.vtable.consumes_key)(app, self.id, intent)
    }

    /// See [`Action::to_key_event_result`].
    pub fn to_key_event_result(
        self,
        app: &mut App,
        intent: &dyn Intent,
        invoke_result: Option<&Rc<dyn Any>>,
    ) -> KeyEventResult {
        (self.vtable.to_key_event_result)(app, self.id, intent, invoke_result)
    }

    /// Dart's `Action._invoke`: [`ContextAction::invoke`] when the action is a
    /// [`ContextAction`], [`Action::invoke`] otherwise.
    pub fn invoke(
        self,
        app: &mut App,
        intent: &dyn Intent,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        (self.vtable.invoke)(app, self.id, intent, context)
    }

    /// See [`Action::add_action_listener`].
    pub fn add_action_listener(self, app: &mut App, listener: ActionListenerCallback) {
        (self.vtable.add_action_listener)(app, self.id, listener);
    }

    /// See [`Action::remove_action_listener`].
    pub fn remove_action_listener(self, app: &mut App, listener: &ActionListenerCallback) {
        (self.vtable.remove_action_listener)(app, self.id, listener);
    }

    /// See [`Action::notify_action_listeners`].
    pub fn notify_action_listeners(self, app: &mut App) {
        (self.vtable.notify_action_listeners)(app, self.id);
    }

    /// See [`Action::make_overridable_action`].
    fn make_overridable_action(self, app: &mut App, context: BuildContext) -> ActionRef {
        (self.vtable.make_overridable_action)(app, self.id, context)
    }
}

// ---------------------------------------------------------------------------------------------
// ActionListener

/// A helper widget for making sure that listeners on an action are removed properly.
///
/// Listeners on an [`Action`] must have their listener callbacks removed with
/// [`Action::remove_action_listener`] when the listener is disposed of. This widget helps with
/// that, by providing a lifetime for the connection between the
/// [`listener`](Self::listener) and the [`action`](Self::action), and by handling the adding
/// and removing of the [`listener`](Self::listener) at the right points in the widget
/// lifecycle.
///
/// If you listen to an [`Action`] in a widget hierarchy, you should use this widget. If you are
/// using an [`Action`] outside of a widget context, then you must call
/// [`Action::remove_action_listener`] yourself.
pub struct ActionListener {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// The [`ActionListenerCallback`] callback to register with the [`action`](Self::action).
    pub listener: ActionListenerCallback,

    /// The [`Action`] that the callback will be registered with.
    pub action: ActionRef,

    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl ActionListener {
    /// Creates an [`ActionListener`].
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(
        listener: ActionListenerCallback,
        action: ActionRef,
        child: impl IntoWidget<K>,
    ) -> ActionListener {
        ActionListener {
            key: None,
            listener,
            action,
            child: child.into_widget(),
        }
    }

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

impl fmt::Debug for ActionListener {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ActionListener")
            .field("action", &self.action)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for ActionListener {
    type State = ActionListenerState;

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

    fn create_state(&self) -> ActionListenerState {
        ActionListenerState {
            state: StateData::new(),
        }
    }
}

/// Dart's `_ActionListenerState`.
pub struct ActionListenerState {
    state: StateData<ActionListener>,
}

impl State for ActionListenerState {
    type Widget = ActionListener;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
        action.add_action_listener(app, listener);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ActionListener) {
        let widget = self.widget(app);
        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
        if old_widget.action == action && Rc::ptr_eq(&old_widget.listener, &listener) {
            return;
        }
        let (old_action, old_listener) =
            (old_widget.action.handle(), Rc::clone(&old_widget.listener));
        old_action.remove_action_listener(app, &old_listener);
        action.add_action_listener(app, listener);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let (action, listener) = (widget.action.handle(), Rc::clone(&widget.listener));
        action.remove_action_listener(app, &listener);
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        self.widget(app).child.clone()
    }
}

// ---------------------------------------------------------------------------------------------
// CallbackAction

/// The signature of a callback accepted by `CallbackAction::on_invoke`.
///
/// Such callbacks are implementations of [`Action::invoke`]. The returned value is the return
/// value of [`Action::invoke`], the argument is the intent passed to [`Action::invoke`], and so
/// forth.
pub type OnInvokeCallback<T> = Rc<dyn Fn(&mut App, &T) -> Option<Rc<dyn Any>>>;

/// An [`Action`] that takes a callback in order to configure it without having to create an
/// explicit [`Action`] implementation just to call a callback.
///
/// See also:
///
///  * `Shortcuts`, which is a widget that contains a key map, in which it looks up key
///    combinations in order to invoke actions.
///  * [`Actions`], which is a widget that defines a map of [`Intent`] to [`Action`] and allows
///    redefining of actions for its descendants.
///  * [`ActionDispatcher`], a class that takes an [`Action`] and invokes it using a `FocusNode`
///    for context.
pub struct CallbackAction<T: Intent> {
    action: ActionData,

    /// The callback to be called when invoked.
    ///
    /// This is effectively the implementation of [`Action::invoke`].
    on_invoke: OnInvokeCallback<T>,
}

impl<T: Intent> CallbackAction<T> {
    /// A constructor for a [`CallbackAction`].
    ///
    /// The given callback is used as the implementation of [`Action::invoke`].
    pub fn new(app: &mut App, on_invoke: OnInvokeCallback<T>) -> Ref<CallbackAction<T>> {
        app.create(CallbackAction {
            action: ActionData::new(),
            on_invoke,
        })
    }
}

impl<T: Intent> Action for CallbackAction<T> {
    type Intent = T;
    crate::action_accessors!();

    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
        let on_invoke = Rc::clone(&app.get(self).on_invoke);
        on_invoke(app, intent)
    }
}

// ---------------------------------------------------------------------------------------------
// ActionDispatcher

/// The erased [`ActionDispatcher`]: what `Actions::dispatcher` holds.
pub type ActionDispatcherRef = Rc<dyn ActionDispatcher>;

/// An action dispatcher that invokes the actions given to it.
///
/// [`invoke_action`](Self::invoke_action) directly calls [`Action::invoke`] on the [`Action`]
/// object.
///
/// For [`ContextAction`] actions, if no `context` is provided, the [`BuildContext`] of the
/// [`primary_focus`] is used instead.
///
/// Dart's instantiable `const ActionDispatcher()` is [`PlainActionDispatcher`].
///
/// See also:
///
///  * `ShortcutManager`, that uses this class to invoke actions.
///  * `Shortcuts`, which defines key mappings to [`Intent`]s.
///  * [`Actions`], which defines a mapping between an [`Intent`] type and an [`Action`].
pub trait ActionDispatcher: Debug {
    /// Dart's `ActionDispatcher.toStringShort`, which a dump of an [`Actions`] widget prints:
    /// the type and the identity.
    fn to_string_short(&self) -> String {
        describe_identity(
            waft_foundation::bare_type_name(std::any::type_name::<Self>()),
            self as *const Self as *const () as usize as u64,
        )
    }

    /// Invokes the given `action`, passing it the given `intent`.
    ///
    /// The action will be invoked with the given `context`, if given, but only if the action is
    /// a [`ContextAction`]. If no `context` is given, and the action is a [`ContextAction`],
    /// then the context from the [`primary_focus`] is used.
    ///
    /// Returns the object returned from [`Action::invoke`].
    ///
    /// The caller must receive a `true` result from [`AnyAction::is_enabled`] before calling
    /// this function. This function will assert if the action is not enabled when called.
    ///
    /// Consider using [`invoke_action_if_enabled`](Self::invoke_action_if_enabled) to invoke
    /// the action conditionally based on whether it is enabled or not, without having to check
    /// first.
    fn invoke_action(
        &self,
        app: &mut App,
        action: AnyAction,
        intent: &dyn Intent,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
        debug_assert!(
            action.is_enabled(app, intent, target),
            "Action must be enabled when calling invokeAction"
        );
        action.invoke(app, intent, target)
    }

    /// Invokes the given `action`, passing it the given `intent`, but only if the action is
    /// enabled.
    ///
    /// The action will be invoked with the given `context`, if given, but only if the action is
    /// a [`ContextAction`]. If no `context` is given, and the action is a [`ContextAction`],
    /// then the context from the [`primary_focus`] is used.
    ///
    /// The return value has two components. The first is a boolean indicating if the action was
    /// enabled (as per [`AnyAction::is_enabled`]). If this is false, the second return value is
    /// `None`. Otherwise, the second return value is the object returned from
    /// [`Action::invoke`].
    ///
    /// Consider using [`invoke_action`](Self::invoke_action) if the enabled state of the action
    /// is not in question; this avoids calling [`AnyAction::is_enabled`] redundantly.
    fn invoke_action_if_enabled(
        &self,
        app: &mut App,
        action: AnyAction,
        intent: &dyn Intent,
        context: Option<BuildContext>,
    ) -> (bool, Option<Rc<dyn Any>>) {
        let target = context.or_else(|| primary_focus(app).and_then(|node| node.context(app)));
        if action.is_enabled(app, intent, target) {
            return (true, action.invoke(app, intent, target));
        }
        (false, None)
    }
}

/// Dart's instantiable `const ActionDispatcher()`: the dispatcher
/// [`Actions::of`] falls back to.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct PlainActionDispatcher;

impl PlainActionDispatcher {
    /// Creates an action dispatcher that invokes actions directly.
    pub fn new() -> PlainActionDispatcher {
        PlainActionDispatcher
    }
}

impl ActionDispatcher for PlainActionDispatcher {
    /// Dart's `const ActionDispatcher()` names itself `ActionDispatcher`, whatever the Rust
    /// leaf is called.
    fn to_string_short(&self) -> String {
        describe_identity(
            "ActionDispatcher",
            self as *const Self as *const () as usize as u64,
        )
    }
}

// ---------------------------------------------------------------------------------------------
// Actions

/// A widget that maps [`Intent`]s to [`Action`]s to be used by its descendants when invoking an
/// [`Action`].
///
/// Actions are typically invoked using `Shortcuts`. They can also be invoked using
/// [`Actions::invoke`] on a context containing an ambient [`Actions`] widget.
///
/// See also:
///
///  * `Shortcuts`, a widget used to bind key combinations to [`Intent`]s.
///  * [`Intent`], a trait for values that contain configuration information for running an
///    [`Action`].
///  * [`Action`], a trait for containing and defining an invocation of a user action.
///  * [`ActionDispatcher`], the object that this widget uses to manage actions.
pub struct Actions {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// The [`ActionDispatcher`] object that invokes actions.
    ///
    /// This is what is returned from [`Actions::of`], and used by [`Actions::invoke`].
    ///
    /// If this [`dispatcher`](Self::dispatcher) is `None`, then [`Actions::of`] and
    /// [`Actions::invoke`] will look up the tree until they find an [`Actions`] widget that has
    /// a dispatcher set. If no such widget is found, then they will return/use a
    /// [`PlainActionDispatcher`].
    pub dispatcher: Option<ActionDispatcherRef>,

    /// A map of [`Intent`] types to [`Action`] objects that defines which actions this widget
    /// knows about.
    ///
    /// For performance reasons, it is recommended that a pre-built map is passed in here
    /// instead of defining it inline in the build function.
    pub actions: HashMap<TypeId, ActionRef>,

    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl Actions {
    /// Creates an [`Actions`] widget.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(actions: HashMap<TypeId, ActionRef>, child: impl IntoWidget<K>) -> Actions {
        Actions {
            key: None,
            dispatcher: None,
            actions,
            child: child.into_widget(),
        }
    }

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

    /// Dart `Actions(dispatcher:)`.
    pub fn dispatcher(mut self, dispatcher: ActionDispatcherRef) -> Actions {
        self.dispatcher = Some(dispatcher);
        self
    }

    /// Visits the [`Actions`] widget ancestors of the given element. Returns true if the
    /// visitor found what it was looking for.
    fn visit_actions_ancestors(
        app: &mut App,
        context: BuildContext,
        visitor: &mut dyn FnMut(&mut App, BuildContext) -> bool,
    ) -> bool {
        if !context.mounted(app) {
            return false;
        }
        let mut actions_element =
            context.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app);
        while let Some(element) = actions_element {
            if visitor(app, element) {
                break;
            }
            // `get_parent` is needed here because
            // `get_element_for_inherited_widget_of_exact_type` will return itself if it happens
            // to be of the correct type.
            actions_element = get_parent(app, element).and_then(|parent| {
                parent.get_element_for_inherited_widget_of_exact_type::<ActionsScope>(app)
            });
        }
        actions_element.is_some()
    }

    /// Finds the nearest valid [`ActionDispatcher`], or creates a new one if it doesn't find
    /// one.
    fn find_dispatcher(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
        let mut dispatcher: Option<ActionDispatcherRef> = None;
        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
            let found = Actions::scope_of(app, element).dispatcher.clone();
            match found {
                Some(found) => {
                    dispatcher = Some(found);
                    true
                }
                None => false,
            }
        });
        dispatcher.unwrap_or_else(|| Rc::new(PlainActionDispatcher::new()))
    }

    /// The `_ActionsScope` an ancestor element found by
    /// [`visit_actions_ancestors`](Self::visit_actions_ancestors) holds.
    fn scope_of(app: &App, element: BuildContext) -> &ActionsScope {
        crate::framework::downcast_widget::<ActionsScope>(&**element.widget(app))
            .expect("the element of an _ActionsScope holds one")
    }

    /// Returns a handler that invokes the bound action for the given `intent` if the action is
    /// enabled, and returns `None` if the action is not enabled, or no matching action is
    /// found.
    ///
    /// This is intended to be used in widgets which have something similar to an `on_tap`
    /// handler, which takes a `GestureTapCallback`, and can be set to the result of calling
    /// this function.
    ///
    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
    /// actions change, the context will be rebuilt and find the updated action.
    ///
    /// The value returned from [`Action::invoke`] is discarded when the returned callback is
    /// called. If the return value is needed, consider using [`Actions::invoke`] instead.
    pub fn handler(app: &mut App, context: BuildContext, intent: IntentRef) -> Option<Listener> {
        let action = Actions::maybe_find(app, context, intent.intent_type())?;
        if action.is_enabled(app, &*intent, Some(context)) {
            let action = action.keep(app);
            return Some(Listener::new(move |app| {
                // Could be that the action was enabled when the closure was created, but is now
                // no longer enabled, so check again.
                if action.is_enabled(app, &*intent, Some(context)) {
                    Actions::of(app, context).invoke_action(
                        app,
                        action.handle(),
                        &*intent,
                        Some(context),
                    );
                }
            }));
        }
        None
    }

    /// Finds the [`Action`] bound to the given `intent_type` in the given `context`.
    ///
    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
    /// actions change, the context will be rebuilt and find the updated action.
    ///
    /// If no [`Actions`] widget surrounds the given context, or no action is bound to
    /// `intent_type`, this function panics.
    ///
    /// See also:
    ///
    ///  * [`maybe_find`](Self::maybe_find), which is similar to this function, but will return
    ///    `None` if no [`Actions`] ancestor is found.
    pub fn find(app: &mut App, context: BuildContext, intent_type: TypeId) -> AnyAction {
        Actions::maybe_find(app, context, intent_type).expect(
            "Unable to find an action for the given intent type in an Actions widget in the \
             given context.\nActions.find() was called on a context that doesn't contain an \
             Actions widget with a mapping for the given intent type.",
        )
    }

    /// Finds the [`Action`] bound to the given `intent_type` in the given `context`.
    ///
    /// Creates a dependency on the [`Actions`] widget that maps the bound action so that if the
    /// actions change, the context will be rebuilt and find the updated action.
    ///
    /// If no [`Actions`] widget surrounds the given context, this function returns `None`.
    ///
    /// See also:
    ///
    ///  * [`find`](Self::find), which is similar to this function, but will panic if no
    ///    [`Actions`] ancestor is found.
    pub fn maybe_find(
        app: &mut App,
        context: BuildContext,
        intent_type: TypeId,
    ) -> Option<AnyAction> {
        let mut action: Option<AnyAction> = None;
        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
            let result = Actions::get_action_for_intent(app, element, intent_type);
            match result {
                Some(result) => {
                    context.depend_on_inherited_element(app, element, None);
                    action = Some(result);
                    true
                }
                None => false,
            }
        });
        action
    }

    /// Dart's `Actions._maybeFindWithoutDependingOn`.
    fn maybe_find_without_depending_on(
        app: &mut App,
        context: BuildContext,
        intent_type: TypeId,
    ) -> Option<AnyAction> {
        let mut action: Option<AnyAction> = None;
        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
            let result = Actions::get_action_for_intent(app, element, intent_type);
            match result {
                Some(result) => {
                    action = Some(result);
                    true
                }
                None => false,
            }
        });
        action
    }

    /// Dart's `Actions._getActionForIntent`.
    fn get_action_for_intent(
        app: &App,
        element: BuildContext,
        intent_type: TypeId,
    ) -> Option<AnyAction> {
        Actions::scope_of(app, element)
            .actions
            .get(&intent_type)
            .map(Retained::handle)
    }

    /// Returns the [`ActionDispatcher`] associated with the [`Actions`] widget that most tightly
    /// encloses the given [`BuildContext`].
    ///
    /// Will return a newly created [`PlainActionDispatcher`] if no ambient [`Actions`] widget is
    /// found.
    pub fn of(app: &mut App, context: BuildContext) -> ActionDispatcherRef {
        let marker = context
            .depend_on_inherited_widget_of_exact_type::<ActionsScope>(app)
            .and_then(|scope| scope.dispatcher.clone());
        match marker {
            Some(dispatcher) => dispatcher,
            None => Actions::find_dispatcher(app, context),
        }
    }

    /// Invokes the action associated with the given [`Intent`] using the [`Actions`] widget that
    /// most tightly encloses the given [`BuildContext`].
    ///
    /// This method returns the result of invoking the action's [`Action::invoke`] method.
    ///
    /// If the given `intent` doesn't map to an action, then it will look to the next ancestor
    /// [`Actions`] widget in the hierarchy until it reaches the root.
    ///
    /// This method panics if no ambient [`Actions`] widget is found.
    pub fn invoke(
        app: &mut App,
        context: BuildContext,
        intent: &dyn Intent,
    ) -> Option<Rc<dyn Any>> {
        let mut return_value: Option<Rc<dyn Any>> = None;
        let action_found = Actions::visit_actions_ancestors(app, context, &mut |app, element| {
            let result = Actions::get_action_for_intent(app, element, intent.intent_type());
            if let Some(result) = result
                && result.is_enabled(app, intent, Some(context))
            {
                // Invoke the action we found using the relevant dispatcher from the Actions
                // element we found.
                return_value = Actions::find_dispatcher(app, element).invoke_action(
                    app,
                    result,
                    intent,
                    Some(context),
                );
            }
            result.is_some()
        });
        debug_assert!(
            action_found,
            "Unable to find an action for an Intent with type {intent:?} in an Actions widget in \
             the given context."
        );
        return_value
    }

    /// Invokes the action associated with the given [`Intent`] using the [`Actions`] widget that
    /// most tightly encloses the given [`BuildContext`].
    ///
    /// This method returns the result of invoking the action's [`Action::invoke`] method. If no
    /// action mapping was found for the specified intent, or if the first action found was
    /// disabled, or the action itself returns `None` from [`Action::invoke`], then this method
    /// returns `None`.
    ///
    /// If the given `intent` doesn't map to an action, then it will look to the next ancestor
    /// [`Actions`] widget in the hierarchy until it reaches the root. If a suitable [`Action`]
    /// is found but its [`AnyAction::is_enabled`] returns false, the search will stop and this
    /// method will return `None`.
    pub fn maybe_invoke(
        app: &mut App,
        context: BuildContext,
        intent: &dyn Intent,
    ) -> Option<Rc<dyn Any>> {
        let mut return_value: Option<Rc<dyn Any>> = None;
        Actions::visit_actions_ancestors(app, context, &mut |app, element| {
            let result = Actions::get_action_for_intent(app, element, intent.intent_type());
            if let Some(result) = result
                && result.is_enabled(app, intent, Some(context))
            {
                return_value = Actions::find_dispatcher(app, element).invoke_action(
                    app,
                    result,
                    intent,
                    Some(context),
                );
            }
            result.is_some()
        });
        return_value
    }
}

impl fmt::Debug for Actions {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Actions")
            .field("dispatcher", &self.dispatcher)
            .field("actions", &self.actions)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for Actions {
    type State = ActionsState;

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

    fn debug_fill_properties(&self, _app: &App, properties: &mut DiagnosticPropertiesBuilder) {
        properties.add(DiagnosticsProperty::<String>::new(
            "dispatcher",
            self.dispatcher
                .as_ref()
                .map(|dispatcher| dispatcher.to_string_short()),
        ));
        let mut entries: Vec<(String, String)> = self
            .actions
            .iter()
            .map(|(intent_type, action)| (format!("{intent_type:?}"), action.to_string_short()))
            .collect();
        entries.sort();
        let actions = entries
            .into_iter()
            .map(|(intent_type, action)| format!("{intent_type}: {action}"))
            .collect::<Vec<_>>()
            .join(", ");
        properties.add(DiagnosticsProperty::<String>::new(
            "actions",
            Some(format!("{{{actions}}}")),
        ));
    }

    fn create_state(&self) -> ActionsState {
        ActionsState {
            state: StateData::new(),
            listened_actions: HashSet::new(),
            action_changed: None,
            rebuild_key: 0,
        }
    }
}

/// Dart's `_ActionsState`.
pub struct ActionsState {
    state: StateData<Actions>,
    /// The set of actions that this [`Actions`] widget is currently listening to.
    listened_actions: HashSet<ActionRef>,
    /// Dart's `_handleActionChanged` tear-off, kept so that it can be removed again.
    action_changed: Option<ActionListenerCallback>,
    /// Used to tell the marker to rebuild its dependencies when the state of an action in the
    /// map changes.
    rebuild_key: u64,
}

impl ActionsState {
    fn handle_action_changed(self: Handle<Self>, app: &mut App) {
        // Generate a new key so that the marker notifies dependents.
        self.set_state(app, |state| state.rebuild_key += 1);
    }

    fn update_action_listeners(self: Handle<Self>, app: &mut App) {
        let widget_actions: HashSet<ActionRef> =
            self.widget(app).actions.values().cloned().collect();
        let listened = app.get(self).listened_actions.clone();
        let removed_actions: Vec<AnyAction> = listened
            .difference(&widget_actions)
            .map(Retained::handle)
            .collect();
        let added_actions: Vec<AnyAction> = widget_actions
            .difference(&listened)
            .map(Retained::handle)
            .collect();

        let handler = self.action_changed(app);
        for action in removed_actions {
            action.remove_action_listener(app, &handler);
        }
        for action in added_actions {
            action.add_action_listener(app, Rc::clone(&handler));
        }
        app.get_mut(self).listened_actions = widget_actions;
    }

    /// The `Rc` behind Dart's `_handleActionChanged` tear-off, minted once so that every
    /// add / remove pair matches.
    fn action_changed(self: Handle<Self>, app: &mut App) -> ActionListenerCallback {
        if let Some(handler) = app.get(self).action_changed.clone() {
            return handler;
        }
        let handler: ActionListenerCallback =
            Rc::new(move |app: &mut App, _action: AnyAction| self.handle_action_changed(app));
        app.get_mut(self).action_changed = Some(Rc::clone(&handler));
        handler
    }
}

impl State for ActionsState {
    type Widget = Actions;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        self.update_action_listeners(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, _old_widget: &Actions) {
        self.update_action_listeners(app);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let handler = self.action_changed(app);
        for action in std::mem::take(&mut app.get_mut(self).listened_actions) {
            action.remove_action_listener(app, &handler);
        }
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let rebuild_key = app.get(self).rebuild_key;
        let widget = self.widget(app);
        ActionsScope {
            dispatcher: widget.dispatcher.clone(),
            actions: widget.actions.clone(),
            rebuild_key,
            child: widget.child.clone(),
        }
        .into_widget()
    }
}

/// An inherited widget used by the [`Actions`] widget for fast lookup of the [`Actions`] widget
/// information.
#[derive(Debug)]
struct ActionsScope {
    dispatcher: Option<ActionDispatcherRef>,
    actions: HashMap<TypeId, ActionRef>,
    rebuild_key: u64,
    child: WidgetRef,
}

impl InheritedWidget for ActionsScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &ActionsScope) -> bool {
        self.rebuild_key != old_widget.rebuild_key
            || !same_dispatcher(&old_widget.dispatcher, &self.dispatcher)
            || old_widget.actions != self.actions
    }
}

/// Dart's `oldWidget.dispatcher != dispatcher` on a reference type.
fn same_dispatcher(a: &Option<ActionDispatcherRef>, b: &Option<ActionDispatcherRef>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => Rc::ptr_eq(a, b),
        _ => false,
    }
}

// ---------------------------------------------------------------------------------------------
// FocusableActionDetector

/// A widget that combines the functionality of [`Actions`], `Shortcuts`, `MouseRegion` and a
/// `Focus` widget to create a detector that defines actions and key bindings, and provides
/// callbacks for handling focus and hover highlights.
///
/// This widget can be used to give a control the required detection modes for focus and hover
/// handling. It is most often used when authoring a new control widget, and the new control
/// should be enabled for keyboard traversal and activation.
///
/// This widget doesn't have any visual representation, it is just a detector that provides
/// focus and hover capabilities.
///
/// It hosts its own `FocusNode` or uses [`focus_node`](Self::focus_node), if given.
pub struct FocusableActionDetector {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// Is this widget enabled or not.
    ///
    /// If disabled, will not send any notifications needed to update highlight or focus state,
    /// and will not define or respond to any actions or shortcuts.
    ///
    /// When disabled, adds `Focus` to the widget tree, but sets `Focus::can_request_focus` to
    /// false.
    pub enabled: bool,

    /// An optional focus node to use as the focus node for this widget.
    pub focus_node: Option<FocusNodeRef>,

    /// True if this widget will be selected as the initial focus when no other node in its
    /// scope is currently focused.
    pub autofocus: bool,

    /// If false, will make this widget's descendants unfocusable.
    pub descendants_are_focusable: bool,

    /// If false, will make this widget's descendants untraversable.
    pub descendants_are_traversable: bool,

    /// A map of [`Intent`] types to [`Action`] objects that defines which actions this widget
    /// knows about.
    pub actions: Option<HashMap<TypeId, ActionRef>>,

    /// The map of shortcuts that describes the mapping between a key sequence defined by a
    /// `ShortcutActivator` and the [`Intent`] that will be emitted when that key sequence is
    /// pressed.
    pub shortcuts: Option<ShortcutMap>,

    /// A function that will be called when the focus highlight should be shown or hidden.
    ///
    /// This method is not triggered at the unmount of the widget.
    pub on_show_focus_highlight: Option<ValueChanged<bool>>,

    /// A function that will be called when the hover highlight should be shown or hidden.
    ///
    /// This method is not triggered at the unmount of the widget.
    pub on_show_hover_highlight: Option<ValueChanged<bool>>,

    /// A function that will be called when the focus changes.
    ///
    /// Called with true if the [`focus_node`](Self::focus_node) has primary focus.
    pub on_focus_change: Option<ValueChanged<bool>>,

    /// The cursor for a mouse pointer when it enters or is hovering over the widget.
    ///
    /// The [`mouse_cursor`](Self::mouse_cursor) defaults to `MouseCursor.defer`, deferring the
    /// choice of cursor to the next region behind it in hit-test order.
    pub mouse_cursor: MouseCursorRef,

    /// Whether to include semantics from `Focus`.
    ///
    /// Defaults to true.
    pub include_focus_semantics: bool,

    /// The child widget for this [`FocusableActionDetector`] widget.
    pub child: WidgetRef,
}

impl FocusableActionDetector {
    /// Creates a [`FocusableActionDetector`].
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn new<K>(child: impl IntoWidget<K>) -> FocusableActionDetector {
        FocusableActionDetector {
            key: None,
            enabled: true,
            focus_node: None,
            autofocus: false,
            descendants_are_focusable: true,
            descendants_are_traversable: true,
            actions: None,
            shortcuts: None,
            on_show_focus_highlight: None,
            on_show_hover_highlight: None,
            on_focus_change: None,
            mouse_cursor: <dyn MouseCursor>::defer(),
            include_focus_semantics: true,
            child: child.into_widget(),
        }
    }

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

    /// Dart `FocusableActionDetector(enabled:)`.
    pub fn enabled(mut self, enabled: bool) -> FocusableActionDetector {
        self.enabled = enabled;
        self
    }

    /// Dart `FocusableActionDetector(focusNode:)`.
    pub fn focus_node(mut self, focus_node: FocusNodeRef) -> FocusableActionDetector {
        self.focus_node = Some(focus_node);
        self
    }

    /// Dart `FocusableActionDetector(autofocus:)`.
    pub fn autofocus(mut self, autofocus: bool) -> FocusableActionDetector {
        self.autofocus = autofocus;
        self
    }

    /// Dart `FocusableActionDetector(descendantsAreFocusable:)`.
    pub fn descendants_are_focusable(
        mut self,
        descendants_are_focusable: bool,
    ) -> FocusableActionDetector {
        self.descendants_are_focusable = descendants_are_focusable;
        self
    }

    /// Dart `FocusableActionDetector(descendantsAreTraversable:)`.
    pub fn descendants_are_traversable(
        mut self,
        descendants_are_traversable: bool,
    ) -> FocusableActionDetector {
        self.descendants_are_traversable = descendants_are_traversable;
        self
    }

    /// Dart `FocusableActionDetector(actions:)`.
    pub fn actions(mut self, actions: HashMap<TypeId, ActionRef>) -> FocusableActionDetector {
        self.actions = Some(actions);
        self
    }

    /// Dart `FocusableActionDetector(shortcuts:)`.
    pub fn shortcuts(mut self, shortcuts: ShortcutMap) -> FocusableActionDetector {
        self.shortcuts = Some(shortcuts);
        self
    }

    /// Dart `FocusableActionDetector(onShowFocusHighlight:)`.
    pub fn on_show_focus_highlight(
        mut self,
        on_show_focus_highlight: impl Fn(&mut App, bool) + 'static,
    ) -> FocusableActionDetector {
        self.on_show_focus_highlight = Some(Rc::new(on_show_focus_highlight));
        self
    }

    /// Dart `FocusableActionDetector(onShowHoverHighlight:)`.
    pub fn on_show_hover_highlight(
        mut self,
        on_show_hover_highlight: impl Fn(&mut App, bool) + 'static,
    ) -> FocusableActionDetector {
        self.on_show_hover_highlight = Some(Rc::new(on_show_hover_highlight));
        self
    }

    /// Dart `FocusableActionDetector(onFocusChange:)`.
    pub fn on_focus_change(
        mut self,
        on_focus_change: impl Fn(&mut App, bool) + 'static,
    ) -> FocusableActionDetector {
        self.on_focus_change = Some(Rc::new(on_focus_change));
        self
    }

    /// Dart `FocusableActionDetector(mouseCursor:)`.
    pub fn mouse_cursor(mut self, mouse_cursor: MouseCursorRef) -> FocusableActionDetector {
        self.mouse_cursor = mouse_cursor;
        self
    }

    /// Dart `FocusableActionDetector(includeFocusSemantics:)`.
    pub fn include_focus_semantics(
        mut self,
        include_focus_semantics: bool,
    ) -> FocusableActionDetector {
        self.include_focus_semantics = include_focus_semantics;
        self
    }
}

impl fmt::Debug for FocusableActionDetector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FocusableActionDetector")
            .field("enabled", &self.enabled)
            .field("focusNode", &self.focus_node)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for FocusableActionDetector {
    type State = FocusableActionDetectorState;

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

    fn create_state(&self) -> FocusableActionDetectorState {
        FocusableActionDetectorState {
            state: StateData::new(),
            can_show_highlight: false,
            hovering: false,
            focused: false,
            highlight_mode_listener: None,
            // This global key is needed to keep only the necessary widgets in the tree while
            // maintaining the subtree's state.
            mouse_region_key: GlobalKey::new(),
        }
    }
}

/// Dart's `_FocusableActionDetectorState`.
pub struct FocusableActionDetectorState {
    state: StateData<FocusableActionDetector>,
    can_show_highlight: bool,
    hovering: bool,
    focused: bool,
    highlight_mode_listener: Option<HighlightModeListener>,
    mouse_region_key: GlobalKey,
}

/// Dart's `VoidCallback? task` argument of `_mayTriggerCallback`, which mutates the state
/// between the two readings.
type HighlightTask<'a> = &'a dyn Fn(Handle<FocusableActionDetectorState>, &mut App);

/// The state Dart's `_mayTriggerCallback` records before and after its task.
#[derive(Clone, Copy)]
struct HighlightState {
    hover: bool,
    focus: bool,
}

impl FocusableActionDetectorState {
    fn update_highlight_mode(self: Handle<Self>, app: &mut App, _mode: FocusHighlightMode) {
        self.may_trigger_callback(
            app,
            None,
            Some(&|this, app| {
                let mode = FocusManager::instance(app).highlight_mode(app);
                app.get_mut(this).can_show_highlight = match mode {
                    FocusHighlightMode::Touch => false,
                    FocusHighlightMode::Traditional => true,
                };
            }),
        );
    }

    /// Have to have this separate from
    /// [`update_highlight_mode`](Self::update_highlight_mode) because it gets called in
    /// `init_state`, where things aren't mounted yet.
    ///
    /// Since this method is a highlight mode listener, it is only called immediately following
    /// pointer events.
    fn handle_focus_highlight_mode_change(
        self: Handle<Self>,
        app: &mut App,
        mode: FocusHighlightMode,
    ) {
        if !self.mounted(app) {
            return;
        }
        self.update_highlight_mode(app, mode);
    }

    fn handle_mouse_enter(self: Handle<Self>, app: &mut App) {
        if !app.get(self).hovering {
            self.may_trigger_callback(
                app,
                None,
                Some(&|this, app| {
                    app.get_mut(this).hovering = true;
                }),
            );
        }
    }

    fn handle_mouse_exit(self: Handle<Self>, app: &mut App) {
        if app.get(self).hovering {
            self.may_trigger_callback(
                app,
                None,
                Some(&|this, app| {
                    app.get_mut(this).hovering = false;
                }),
            );
        }
    }

    fn handle_focus_change(self: Handle<Self>, app: &mut App, focused: bool) {
        if app.get(self).focused != focused {
            self.may_trigger_callback(
                app,
                None,
                Some(&|this, app| {
                    app.get_mut(this).focused = focused;
                }),
            );
            if let Some(on_focus_change) = self.widget(app).on_focus_change.clone() {
                let focused = app.get(self).focused;
                on_focus_change(app, focused);
            }
        }
    }

    fn should_show_hover_highlight(self: Handle<Self>, app: &App, target_enabled: bool) -> bool {
        app.get(self).hovering && target_enabled && app.get(self).can_show_highlight
    }

    fn can_request_focus(self: Handle<Self>, app: &mut App, target_enabled: bool) -> bool {
        let context = self.context(app);
        match MediaQuery::maybe_navigation_mode_of(app, context) {
            None | Some(NavigationMode::Traditional) => target_enabled,
            Some(NavigationMode::Directional) => true,
        }
    }

    fn should_show_focus_highlight(
        self: Handle<Self>,
        app: &mut App,
        target_enabled: bool,
    ) -> bool {
        app.get(self).focused
            && app.get(self).can_show_highlight
            && self.can_request_focus(app, target_enabled)
    }

    fn highlight_state(self: Handle<Self>, app: &mut App, target_enabled: bool) -> HighlightState {
        HighlightState {
            hover: self.should_show_hover_highlight(app, target_enabled),
            focus: self.should_show_focus_highlight(app, target_enabled),
        }
    }

    /// Record old states, do `task` if given, then compare old states with the new states, and
    /// trigger callbacks if necessary.
    ///
    /// The old states are collected from `old_enabled` if it is provided (Dart passes the whole
    /// `oldWidget`, of which this is the only field read), or the current widget (before doing
    /// `task`) otherwise. The new states are always collected from the current widget.
    fn may_trigger_callback(
        self: Handle<Self>,
        app: &mut App,
        old_enabled: Option<bool>,
        task: Option<HighlightTask<'_>>,
    ) {
        debug_assert!(
            SchedulerBinding::scheduler_phase(app) != SchedulerPhase::PersistentCallbacks
        );
        let old_enabled = old_enabled.unwrap_or_else(|| self.widget(app).enabled);
        let did = self.highlight_state(app, old_enabled);
        if let Some(task) = task {
            task(self, app);
        }
        let enabled = self.widget(app).enabled;
        let do_show = self.highlight_state(app, enabled);
        if did.focus != do_show.focus
            && let Some(callback) = self.widget(app).on_show_focus_highlight.clone()
        {
            callback(app, do_show.focus);
        }
        if did.hover != do_show.hover
            && let Some(callback) = self.widget(app).on_show_hover_highlight.clone()
        {
            callback(app, do_show.hover);
        }
    }
}

impl State for FocusableActionDetectorState {
    type Widget = FocusableActionDetector;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        SchedulerBinding::add_post_frame_callback(
            app,
            FrameCallback::new(move |app, _duration| {
                // Removed within the frame it was made in: Dart's callback then runs on the
                // defunct state and changes nothing, but a Rust handle to it is gone.
                if !self.mounted(app) {
                    return;
                }
                let mode = FocusManager::instance(app).highlight_mode(app);
                self.update_highlight_mode(app, mode);
            }),
            View::maybe_id_of(app, self.context(app)),
        );
        let listener: HighlightModeListener =
            Rc::new(move |app: &mut App, mode| self.handle_focus_highlight_mode_change(app, mode));
        app.get_mut(self).highlight_mode_listener = Some(Rc::clone(&listener));
        FocusManager::instance(app).add_highlight_mode_listener(app, listener);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        if let Some(listener) = app.get_mut(self).highlight_mode_listener.take() {
            FocusManager::instance(app).remove_highlight_mode_listener(app, &listener);
        }
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &FocusableActionDetector) {
        if self.widget(app).enabled != old_widget.enabled {
            let old_enabled = old_widget.enabled;
            SchedulerBinding::add_post_frame_callback(
                app,
                FrameCallback::new(move |app, _duration| {
                    self.may_trigger_callback(app, Some(old_enabled), None);
                }),
                View::maybe_id_of(app, self.context(app)),
            );
        }
    }

    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
        let can_request_focus = {
            let enabled = self.widget(app).enabled;
            self.can_request_focus(app, enabled)
        };
        let widget = self.widget(app);
        let (
            focus_node,
            autofocus,
            descendants_are_focusable,
            descendants_are_traversable,
            include_focus_semantics,
            mouse_cursor,
            child,
            enabled,
        ) = (
            widget.focus_node.clone(),
            widget.autofocus,
            widget.descendants_are_focusable,
            widget.descendants_are_traversable,
            widget.include_focus_semantics,
            Rc::clone(&widget.mouse_cursor),
            widget.child.clone(),
            widget.enabled,
        );
        let mouse_region_key = app.get(self).mouse_region_key.clone();

        let mut focus = Focus::new(child)
            .autofocus(autofocus)
            .descendants_are_focusable(descendants_are_focusable)
            .descendants_are_traversable(descendants_are_traversable)
            .can_request_focus(can_request_focus)
            .on_focus_change(move |app, focused| self.handle_focus_change(app, focused))
            .include_semantics(include_focus_semantics);
        if let Some(focus_node) = focus_node {
            focus = focus.focus_node(focus_node);
        }

        let mut child: WidgetRef = MouseRegion::new()
            .key(mouse_region_key.into())
            .on_enter(Rc::new(move |app, _event| self.handle_mouse_enter(app)))
            .on_exit(Rc::new(move |app, _event| self.handle_mouse_exit(app)))
            .cursor(mouse_cursor)
            .child(focus)
            .into_widget();

        let actions = self.widget(app).actions.clone();
        if let Some(actions) = actions.filter(|actions| enabled && !actions.is_empty()) {
            child = Actions::new(actions, child).into_widget();
        }
        let shortcuts = self.widget(app).shortcuts.clone();
        if let Some(shortcuts) = shortcuts.filter(|shortcuts| enabled && !shortcuts.is_empty()) {
            child = Shortcuts::new(shortcuts, child).into_widget();
        }
        child
    }
}

// ---------------------------------------------------------------------------------------------
// The intents and actions this file declares

/// An [`Intent`] that keeps a callback to be invoked by a [`VoidCallbackAction`] when it
/// receives this intent.
pub struct VoidCallbackIntent {
    /// The callback that is to be called by the [`VoidCallbackAction`] that receives this
    /// intent.
    pub callback: Listener,
}

impl VoidCallbackIntent {
    /// Creates a [`VoidCallbackIntent`].
    pub fn new(callback: Listener) -> VoidCallbackIntent {
        VoidCallbackIntent { callback }
    }
}

impl fmt::Debug for VoidCallbackIntent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("VoidCallbackIntent").finish()
    }
}

impl Intent for VoidCallbackIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Action`] that invokes the callback given to it in the [`VoidCallbackIntent`] passed to
/// it when invoked.
///
/// See also:
///
///  * [`CallbackAction`], which is an action that will invoke a callback with the intent passed
///    to the action's invoke method. The callback is configured on the action, not the intent,
///    like this class.
pub struct VoidCallbackAction {
    action: ActionData,
}

impl VoidCallbackAction {
    /// Creates a [`VoidCallbackAction`].
    pub fn new(app: &mut App) -> Ref<VoidCallbackAction> {
        app.create(VoidCallbackAction {
            action: ActionData::new(),
        })
    }
}

impl Action for VoidCallbackAction {
    type Intent = VoidCallbackIntent;
    crate::action_accessors!();

    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        intent: &VoidCallbackIntent,
    ) -> Option<Rc<dyn Any>> {
        intent.callback.call(app);
        None
    }
}

/// An [`Intent`] that is bound to a [`DoNothingAction`].
///
/// Attaching a [`DoNothingIntent`] to a `Shortcuts` mapping is one way to disable a keyboard
/// shortcut defined by a widget higher in the widget hierarchy and consume any key event that
/// triggers it via a shortcut.
///
/// See also:
///
///  * [`DoNothingAndStopPropagationIntent`], a similar intent that will not handle the key
///    event, but will still keep it from being passed to other key handlers in the focus chain.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DoNothingIntent;

impl DoNothingIntent {
    /// Creates a [`DoNothingIntent`].
    pub const fn new() -> DoNothingIntent {
        DoNothingIntent
    }
}

impl Intent for DoNothingIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Intent`] that is bound to a [`DoNothingAction`], but, in addition to not performing an
/// action, also stops the propagation of the key event bound to this intent to other key event
/// handlers in the focus chain.
///
/// Attaching a [`DoNothingAndStopPropagationIntent`] to a `Shortcuts::shortcuts` mapping is one
/// way to disable a keyboard shortcut defined by a widget higher in the widget hierarchy. In
/// addition, the bound [`DoNothingAction`] will return false from
/// [`Action::consumes_key`], causing the key bound to this intent to be passed on to the
/// platform embedding as "not handled" without passing it to other key handlers in the focus
/// chain (e.g. parent `Shortcuts` widgets higher up in the chain).
///
/// See also:
///
///  * [`DoNothingIntent`], a similar intent that will handle the key event.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DoNothingAndStopPropagationIntent;

impl DoNothingAndStopPropagationIntent {
    /// Creates a [`DoNothingAndStopPropagationIntent`].
    pub const fn new() -> DoNothingAndStopPropagationIntent {
        DoNothingAndStopPropagationIntent
    }
}

impl Intent for DoNothingAndStopPropagationIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Action`] that doesn't perform any action when invoked.
///
/// Attaching a [`DoNothingAction`] to an [`Actions::actions`] mapping is a way to disable an
/// action defined by a widget higher in the widget hierarchy.
///
/// If [`Action::consumes_key`] returns false, then not only will this action do nothing, but it
/// will stop the propagation of the key event used to trigger it to other widgets in the focus
/// chain and tell the embedding that the key wasn't handled, allowing text input fields or
/// other non-Flutter elements to receive that key event. The return value of
/// [`Action::consumes_key`] can be set via the `consumes_key` argument to the constructor.
///
/// This action can be bound to any [`Intent`].
///
/// See also:
///
///  * [`DoNothingIntent`], which is an intent that can be bound to a key set in a `Shortcuts`
///    widget to do nothing.
///  * [`DoNothingAndStopPropagationIntent`], which is an intent that can be bound to a key set
///    in a `Shortcuts` widget to do nothing and also stop key event propagation to other key
///    handlers in the focus chain.
pub struct DoNothingAction {
    action: ActionData,
    consumes_key: bool,
}

impl DoNothingAction {
    /// Creates a [`DoNothingAction`].
    ///
    /// Dart's optional `consumesKey` argument defaults to true.
    pub fn new(app: &mut App) -> Ref<DoNothingAction> {
        app.create(DoNothingAction {
            action: ActionData::new(),
            consumes_key: true,
        })
    }

    /// Dart `DoNothingAction(consumesKey:)`.
    pub fn set_consumes_key(self: Handle<Self>, app: &mut App, consumes_key: bool) {
        app.get_mut(self).consumes_key = consumes_key;
    }
}

impl Action for DoNothingAction {
    type Intent = dyn Intent;
    crate::action_accessors!();

    fn consumes_key(self: Handle<Self>, app: &mut App, _intent: &dyn Intent) -> bool {
        app.get(self).consumes_key
    }

    fn invoke(self: Handle<Self>, _app: &mut App, _intent: &dyn Intent) -> Option<Rc<dyn Any>> {
        None
    }
}

/// An [`Intent`] that activates the currently focused control.
///
/// This intent is bound by default to the space key on all platforms, and also to the enter key
/// on all platforms except the web, where enter doesn't toggle selection. On the web, enter is
/// bound to [`ButtonActivateIntent`] instead.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ActivateIntent;

impl ActivateIntent {
    /// Creates an intent that activates the currently focused control.
    pub const fn new() -> ActivateIntent {
        ActivateIntent
    }
}

impl Intent for ActivateIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Intent`] that activates the currently focused button.
///
/// This intent is bound by default to the enter key on the web, where enter can be used to
/// activate buttons, but not toggle selection. All other platforms bind the enter key to
/// [`ActivateIntent`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ButtonActivateIntent;

impl ButtonActivateIntent {
    /// Creates an intent that activates the currently focused control, if it's a button.
    pub const fn new() -> ButtonActivateIntent {
        ButtonActivateIntent
    }
}

impl Intent for ButtonActivateIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Action`] that activates the currently focused control.
///
/// This is a trait that serves as a base for actions that activate a control. By default, is
/// bound to the enter, game button A, and space keys in the default keyboard map in
/// `WidgetsApp`.
pub trait ActivateAction: Action<Intent = ActivateIntent> {}

/// An [`Intent`] that selects the currently focused control.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SelectIntent;

impl SelectIntent {
    /// Creates an intent that selects the currently focused control.
    pub const fn new() -> SelectIntent {
        SelectIntent
    }
}

impl Intent for SelectIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An action that selects the currently focused control.
///
/// This is a trait that serves as a base for actions that select something. It is not bound to
/// any key by default.
pub trait SelectAction: Action<Intent = SelectIntent> {}

/// An [`Intent`] that dismisses the currently focused widget.
///
/// `WidgetsApp::default_shortcuts` binds this intent to the escape and game button B keys.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct DismissIntent;

impl DismissIntent {
    /// Creates an intent that dismisses the currently focused widget.
    pub const fn new() -> DismissIntent {
        DismissIntent
    }
}

impl Intent for DismissIntent {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Action`] that dismisses the focused widget.
///
/// This is a trait that serves as a base for dismiss actions.
pub trait DismissAction: Action<Intent = DismissIntent> {}

/// An [`Intent`] that evaluates a series of specified
/// [`ordered_intents`](Self::ordered_intents) for execution.
///
/// The first intent that matches an enabled action is used.
#[derive(Debug)]
pub struct PrioritizedIntents {
    /// List of intents to be evaluated in order for execution. When an
    /// [`AnyAction::is_enabled`] returns true, that action will be invoked and progression
    /// through the ordered intents stops.
    pub ordered_intents: Vec<IntentRef>,
}

impl PrioritizedIntents {
    /// Creates an intent that is used with [`PrioritizedAction`] to specify a list of intents,
    /// the first available of which will be used.
    pub fn new(ordered_intents: Vec<IntentRef>) -> PrioritizedIntents {
        PrioritizedIntents { ordered_intents }
    }
}

impl Intent for PrioritizedIntents {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// An [`Action`] that iterates through a list of [`Intent`]s, invoking the first that is
/// enabled.
///
/// [`ContextAction::is_enabled`] must be called before [`ContextAction::invoke`]. Calling it
/// configures the object by seeking the first intent with an enabled action. If the actions
/// have an opportunity to change enabled state, it must be called again before calling
/// [`ContextAction::invoke`].
pub struct PrioritizedAction {
    action: ActionData,
    selected_action: Option<ActionRef>,
    selected_intent: Option<IntentRef>,
}

impl PrioritizedAction {
    /// Creates a [`PrioritizedAction`].
    pub fn new(app: &mut App) -> Ref<PrioritizedAction> {
        app.create(PrioritizedAction {
            action: ActionData::new(),
            selected_action: None,
            selected_intent: None,
        })
    }
}

impl Action for PrioritizedAction {
    type Intent = PrioritizedIntents;
    crate::action_accessors!();
    crate::context_action_overrides!();
}

impl ContextAction for PrioritizedAction {
    fn is_enabled(
        self: Handle<Self>,
        app: &mut App,
        intent: &PrioritizedIntents,
        context: Option<BuildContext>,
    ) -> bool {
        let Some(focus) = primary_focus(app) else {
            return false;
        };
        let Some(focus_context) = focus.context(app) else {
            return false;
        };
        for candidate_intent in intent.ordered_intents.iter() {
            let candidate_action =
                Actions::maybe_find(app, focus_context, candidate_intent.intent_type());
            if let Some(candidate_action) = candidate_action
                && candidate_action.is_enabled(app, &**candidate_intent, context)
            {
                let candidate_action = candidate_action.keep(app);
                let this = app.get_mut(self);
                this.selected_action = Some(candidate_action);
                this.selected_intent = Some(Rc::clone(candidate_intent));
                return true;
            }
        }
        false
    }

    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        _intent: &PrioritizedIntents,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        let selected_action = app
            .get(self)
            .selected_action
            .handle()
            .expect("isEnabled selected an action");
        let selected_intent = app
            .get(self)
            .selected_intent
            .clone()
            .expect("isEnabled selected an intent");
        selected_action.invoke(app, &*selected_intent, context);
        None
    }
}

// ---------------------------------------------------------------------------------------------
// The overridable actions

/// The fields Dart's `_OverridableActionMixin` declares; both overridable actions carry this
/// bag under the field `overridable`.
struct OverridableActionData {
    /// The default action to invoke if an enabled override [`Action`] can't be found using
    /// [`lookup_context`](Self::lookup_context).
    default_action: ActionRef,
    /// The [`BuildContext`] used to find the override of this [`Action`].
    lookup_context: BuildContext,
    // When these are true, this action throws when the override calls this action's method and
    // the override is already being invoked from within it.
    debug_assert_mutually_recursive: bool,
    debug_assert_is_action_enabled_mutually_recursive: bool,
    debug_assert_is_enabled_mutually_recursive: bool,
    debug_assert_consume_key_mutually_recursive: bool,
}

impl OverridableActionData {
    fn new(default_action: ActionRef, lookup_context: BuildContext) -> OverridableActionData {
        OverridableActionData {
            default_action,
            lookup_context,
            debug_assert_mutually_recursive: false,
            debug_assert_is_action_enabled_mutually_recursive: false,
            debug_assert_is_enabled_mutually_recursive: false,
            debug_assert_consume_key_mutually_recursive: false,
        }
    }
}

/// Dart's `_OverridableActionMixin`: the shared bodies of the two overridable actions.
trait OverridableActionMixin: ContextAction {
    /// Dart's `_OverridableActionMixin` fields, held under the field `overridable`.
    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData;

    /// See [`overridable_data`](Self::overridable_data).
    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData;

    /// How to invoke the default action, given the caller `from_action`.
    fn invoke_default_action(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        from_action: Option<AnyAction>,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>>;

    /// Dart's `_getOverrideAction`.
    fn get_override_action(
        self: Handle<Self>,
        app: &mut App,
        intent_type: TypeId,
        declare_dependency: bool,
    ) -> Option<AnyAction> {
        let lookup_context = self.overridable_data(app).lookup_context;
        let override_action = if declare_dependency {
            Actions::maybe_find(app, lookup_context, intent_type)
        } else {
            Actions::maybe_find_without_depending_on(app, lookup_context, intent_type)
        };
        debug_assert!(override_action != Some(Action::as_action(self)));
        override_action
    }

    /// Dart's `_OverridableActionMixin._updateCallingAction`.
    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
        self.action_data_mut(app).current_calling_action = value.clone();
        let default_action = self.overridable_data(app).default_action.handle();
        default_action.update_calling_action(app, value);
    }

    /// Dart's `_OverridableActionMixin._invokeOverride`.
    fn invoke_override(
        self: Handle<Self>,
        app: &mut App,
        override_action: AnyAction,
        intent: &Self::Intent,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_mutually_recursive = true;
        }
        let default_action = self.overridable_data(app).default_action.clone();
        override_action.update_calling_action(app, Some(default_action));
        let return_value = override_action.invoke(app, intent.as_intent(), context);
        override_action.update_calling_action(app, None);
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_mutually_recursive = false;
        }
        return_value
    }

    /// Dart's `_OverridableActionMixin.invoke`.
    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        let intent_type = intent.as_intent().intent_type();
        let override_action = self.get_override_action(app, intent_type, false);
        match override_action {
            None => {
                let calling = self.action_data(app).current_calling_action.handle();
                self.invoke_default_action(app, intent, calling, context)
            }
            Some(override_action) => self.invoke_override(app, override_action, intent, context),
        }
    }

    /// Dart's `_OverridableActionMixin._isOverrideActionEnabled`.
    fn is_override_action_enabled(
        self: Handle<Self>,
        app: &mut App,
        override_action: AnyAction,
    ) -> bool {
        debug_assert!(
            !self
                .overridable_data(app)
                .debug_assert_is_action_enabled_mutually_recursive
        );
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_is_action_enabled_mutually_recursive = true;
        }
        let default_action = self.overridable_data(app).default_action.clone();
        override_action.update_calling_action(app, Some(default_action));
        let is_override_enabled = override_action.is_action_enabled(app);
        override_action.update_calling_action(app, None);
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_is_action_enabled_mutually_recursive = false;
        }
        is_override_enabled
    }

    /// Dart's `_OverridableActionMixin.isActionEnabled`.
    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
        let intent_type = TypeId::of::<Self::Intent>();
        let override_action = self.get_override_action(app, intent_type, true);
        match override_action {
            Some(override_action) => self.is_override_action_enabled(app, override_action),
            None => self
                .overridable_data(app)
                .default_action
                .is_action_enabled(app),
        }
    }

    /// Dart's `_OverridableActionMixin.isEnabled`.
    fn is_enabled(
        self: Handle<Self>,
        app: &mut App,
        intent: &Self::Intent,
        context: Option<BuildContext>,
    ) -> bool {
        debug_assert!(
            !self
                .overridable_data(app)
                .debug_assert_is_enabled_mutually_recursive
        );
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_is_enabled_mutually_recursive = true;
        }

        let erased = intent.as_intent();
        let override_action = self.get_override_action(app, erased.intent_type(), false);
        let default_action = self.overridable_data(app).default_action.clone();
        if let Some(override_action) = override_action {
            override_action.update_calling_action(app, Some(default_action.clone()));
        }
        let return_value = override_action
            .unwrap_or(default_action.handle())
            .is_enabled(app, intent.as_intent(), context);
        if let Some(override_action) = override_action {
            override_action.update_calling_action(app, None);
        }
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_is_enabled_mutually_recursive = false;
        }
        return_value
    }

    /// Dart's `_OverridableActionMixin.consumesKey`.
    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &Self::Intent) -> bool {
        debug_assert!(
            !self
                .overridable_data(app)
                .debug_assert_consume_key_mutually_recursive
        );
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_consume_key_mutually_recursive = true;
        }
        let erased = intent.as_intent();
        let override_action = self.get_override_action(app, erased.intent_type(), false);
        let default_action = self.overridable_data(app).default_action.clone();
        if let Some(override_action) = override_action {
            override_action.update_calling_action(app, Some(default_action.clone()));
        }
        let is_enabled = override_action
            .unwrap_or(default_action.handle())
            .consumes_key(app, intent.as_intent());
        if let Some(override_action) = override_action {
            override_action.update_calling_action(app, None);
        }
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_consume_key_mutually_recursive = false;
        }
        is_enabled
    }
}

/// Dart's `_OverridableAction`: the overridable form of a plain [`Action`].
pub struct OverridableAction<T: ActionIntent + ?Sized> {
    action: ActionData,
    overridable: OverridableActionData,
    intent: std::marker::PhantomData<fn(&T)>,
}

impl<T: ActionIntent + ?Sized> OverridableAction<T> {
    /// Dart's `_OverridableAction(defaultAction:, lookupContext:)`; reached through
    /// [`AnyAction::overridable`].
    pub fn new(
        app: &mut App,
        default_action: ActionRef,
        lookup_context: BuildContext,
    ) -> Ref<OverridableAction<T>> {
        app.create(OverridableAction::<T> {
            action: ActionData::new(),
            overridable: OverridableActionData::new(default_action, lookup_context),
            intent: std::marker::PhantomData,
        })
    }
}

impl<T: ActionIntent + ?Sized> Action for OverridableAction<T> {
    type Intent = T;
    crate::action_accessors!();

    fn debug_fill_properties(
        self: Handle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        properties.add(DiagnosticsProperty::<String>::new(
            "defaultAction",
            Some(app.get(self).overridable.default_action.to_string_short()),
        ));
    }

    fn as_action(self: Handle<Self>) -> AnyAction {
        AnyAction::of_context::<Self>(self)
    }

    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        ContextAction::is_enabled(self, app, intent, None)
    }

    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
        ContextAction::invoke(self, app, intent, None)
    }

    fn make_overridable_action(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
    ) -> ActionRef {
        let default_action = self.overridable_data(app).default_action.clone();
        OverridableAction::<T>::new(app, default_action, context).into_erased()
    }

    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
        OverridableActionMixin::update_calling_action(self, app, value);
    }

    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
        OverridableActionMixin::is_action_enabled(self, app)
    }

    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        OverridableActionMixin::consumes_key(self, app, intent)
    }
}

impl<T: ActionIntent + ?Sized> ContextAction for OverridableAction<T> {
    fn is_enabled(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        context: Option<BuildContext>,
    ) -> bool {
        OverridableActionMixin::is_enabled(self, app, intent, context)
    }

    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        OverridableActionMixin::invoke(self, app, intent, context)
    }
}

impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableAction<T> {
    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
        &app.get(self).overridable
    }

    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
        &mut app.get_mut(self).overridable
    }

    fn invoke_default_action(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        _from_action: Option<AnyAction>,
        _context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        let default_action = self.overridable_data(app).default_action.handle();
        default_action.invoke(app, intent.as_intent(), None)
    }
}

/// Dart's `_OverridableContextAction`: the overridable form of a [`ContextAction`].
pub struct OverridableContextAction<T: ActionIntent + ?Sized> {
    action: ActionData,
    overridable: OverridableActionData,
    intent: std::marker::PhantomData<fn(&T)>,
}

impl<T: ActionIntent + ?Sized> OverridableContextAction<T> {
    /// Dart's `_OverridableContextAction(defaultAction:, lookupContext:)`; reached through
    /// [`AnyAction::overridable`].
    pub fn new(
        app: &mut App,
        default_action: ActionRef,
        lookup_context: BuildContext,
    ) -> Ref<OverridableContextAction<T>> {
        app.create(OverridableContextAction::<T> {
            action: ActionData::new(),
            overridable: OverridableActionData::new(default_action, lookup_context),
            intent: std::marker::PhantomData,
        })
    }
}

impl<T: ActionIntent + ?Sized> Action for OverridableContextAction<T> {
    type Intent = T;
    crate::action_accessors!();

    fn as_action(self: Handle<Self>) -> AnyAction {
        AnyAction::of_context::<Self>(self)
    }

    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        ContextAction::is_enabled(self, app, intent, None)
    }

    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
        ContextAction::invoke(self, app, intent, None)
    }

    fn make_overridable_action(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
    ) -> ActionRef {
        let default_action = self.overridable_data(app).default_action.clone();
        OverridableContextAction::<T>::new(app, default_action, context).into_erased()
    }

    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
        OverridableActionMixin::update_calling_action(self, app, value);
    }

    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
        OverridableActionMixin::is_action_enabled(self, app)
    }

    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        OverridableActionMixin::consumes_key(self, app, intent)
    }
}

impl<T: ActionIntent + ?Sized> ContextAction for OverridableContextAction<T> {
    fn is_enabled(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        context: Option<BuildContext>,
    ) -> bool {
        OverridableActionMixin::is_enabled(self, app, intent, context)
    }

    fn invoke(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        OverridableActionMixin::invoke(self, app, intent, context)
    }
}

impl<T: ActionIntent + ?Sized> OverridableActionMixin for OverridableContextAction<T> {
    fn overridable_data(self: Handle<Self>, app: &App) -> &OverridableActionData {
        &app.get(self).overridable
    }

    fn overridable_data_mut(self: Handle<Self>, app: &mut App) -> &mut OverridableActionData {
        &mut app.get_mut(self).overridable
    }

    /// Wraps the default [`Action`] together with the calling context in case the override is
    /// not a [`ContextAction`] and thus has no access to the calling [`BuildContext`].
    fn invoke_override(
        self: Handle<Self>,
        app: &mut App,
        override_action: AnyAction,
        intent: &T,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        debug_assert!(context.is_some());
        debug_assert!(!self.overridable_data(app).debug_assert_mutually_recursive);
        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_mutually_recursive = true;
        }

        let default_action = self.overridable_data(app).default_action.clone();
        let invoke_context = context.expect("an overridable context action is invoked with one");
        let wrapped_default =
            ContextActionToActionAdapter::<T>::new(app, invoke_context, default_action);
        override_action.update_calling_action(app, Some(wrapped_default.into_erased()));
        let return_value = override_action.invoke(app, intent.as_intent(), context);
        override_action.update_calling_action(app, None);

        if cfg!(debug_assertions) {
            self.overridable_data_mut(app)
                .debug_assert_mutually_recursive = false;
        }
        return_value
    }

    fn invoke_default_action(
        self: Handle<Self>,
        app: &mut App,
        intent: &T,
        _from_action: Option<AnyAction>,
        context: Option<BuildContext>,
    ) -> Option<Rc<dyn Any>> {
        let default_action = self.overridable_data(app).default_action.handle();
        default_action.invoke(app, intent.as_intent(), context)
    }
}

/// Dart's `_ContextActionToActionAdapter`: a plain [`Action`] that calls a [`ContextAction`]
/// with a fixed context.
struct ContextActionToActionAdapter<T: ActionIntent + ?Sized> {
    action: ActionData,
    invoke_context: BuildContext,
    wrapped: ActionRef,
    intent: std::marker::PhantomData<fn(&T)>,
}

impl<T: ActionIntent + ?Sized> ContextActionToActionAdapter<T> {
    fn new(
        app: &mut App,
        invoke_context: BuildContext,
        wrapped: ActionRef,
    ) -> Ref<ContextActionToActionAdapter<T>> {
        app.create(ContextActionToActionAdapter::<T> {
            action: ActionData::new(),
            invoke_context,
            wrapped,
            intent: std::marker::PhantomData,
        })
    }
}

impl<T: ActionIntent + ?Sized> Action for ContextActionToActionAdapter<T> {
    type Intent = T;
    crate::action_accessors!();

    fn update_calling_action(self: Handle<Self>, app: &mut App, value: Option<ActionRef>) {
        let wrapped = app.get(self).wrapped.handle();
        wrapped.update_calling_action(app, value);
    }

    fn calling_action(self: Handle<Self>, app: &App) -> Option<AnyAction> {
        app.get(self).wrapped.calling_action(app)
    }

    fn is_enabled(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        let (wrapped, invoke_context) = {
            let this = app.get(self);
            (this.wrapped.handle(), this.invoke_context)
        };
        wrapped.is_enabled(app, intent.as_intent(), Some(invoke_context))
    }

    fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
        app.get(self).wrapped.is_action_enabled(app)
    }

    fn consumes_key(self: Handle<Self>, app: &mut App, intent: &T) -> bool {
        let wrapped = app.get(self).wrapped.handle();
        wrapped.consumes_key(app, intent.as_intent())
    }

    fn add_action_listener(self: Handle<Self>, app: &mut App, listener: ActionListenerCallback) {
        self.action_data_mut(app)
            .listeners
            .push(Rc::clone(&listener));
        let wrapped = app.get(self).wrapped.handle();
        wrapped.add_action_listener(app, listener);
    }

    fn remove_action_listener(
        self: Handle<Self>,
        app: &mut App,
        listener: &ActionListenerCallback,
    ) {
        let listeners = &mut self.action_data_mut(app).listeners;
        if let Some(index) = listeners
            .iter()
            .position(|registered| Rc::ptr_eq(registered, listener))
        {
            listeners.remove(index);
        }
        let wrapped = app.get(self).wrapped.handle();
        wrapped.remove_action_listener(app, listener);
    }

    fn notify_action_listeners(self: Handle<Self>, app: &mut App) {
        app.get(self).wrapped.notify_action_listeners(app);
    }

    fn invoke(self: Handle<Self>, app: &mut App, intent: &T) -> Option<Rc<dyn Any>> {
        let (wrapped, invoke_context) = {
            let this = app.get(self);
            (this.wrapped.handle(), this.invoke_context)
        };
        wrapped.invoke(app, intent.as_intent(), Some(invoke_context))
    }
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};

    use waft_embedder::Offset;

    use super::*;
    use crate::testing::{TestPointer, test_widgets};
    use crate::widgets::basic::{Builder, SizedBox};
    use crate::widgets::focus_manager::{FocusHighlightStrategy, FocusNodeLeaf};

    #[derive(Debug)]
    struct CountIntent {
        amount: i32,
    }

    impl Intent for CountIntent {
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[derive(Debug)]
    struct OtherIntent;

    impl Intent for OtherIntent {
        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    /// An action that records that it ran and doubles the intent's amount.
    struct CountAction {
        action: ActionData,
        log: Rc<RefCell<Vec<String>>>,
        name: &'static str,
        enabled: bool,
    }

    impl CountAction {
        fn new(
            app: &mut App,
            log: &Rc<RefCell<Vec<String>>>,
            name: &'static str,
        ) -> Ref<CountAction> {
            app.create(CountAction {
                action: ActionData::new(),
                log: Rc::clone(log),
                name,
                enabled: true,
            })
        }

        fn set_enabled(self: Handle<Self>, app: &mut App, enabled: bool) {
            app.get_mut(self).enabled = enabled;
            self.notify_action_listeners(app);
        }
    }

    impl Action for CountAction {
        type Intent = CountIntent;
        crate::action_accessors!();

        fn is_action_enabled(self: Handle<Self>, app: &mut App) -> bool {
            app.get(self).enabled
        }

        fn invoke(self: Handle<Self>, app: &mut App, intent: &CountIntent) -> Option<Rc<dyn Any>> {
            let (log, name) = {
                let this = app.get(self);
                (Rc::clone(&this.log), this.name)
            };
            log.borrow_mut().push(format!("{name}:{}", intent.amount));
            Some(Rc::new(intent.amount * 2))
        }
    }

    fn map(intent_type: TypeId, action: ActionRef) -> HashMap<TypeId, ActionRef> {
        HashMap::from([(intent_type, action)])
    }

    /// A `Builder` that records its own context.
    fn probe(sink: &Rc<Cell<Option<BuildContext>>>) -> WidgetRef {
        let sink = Rc::clone(sink);
        Builder::new(move |_app, context| {
            sink.set(Some(context));
            SizedBox::shrink().into_widget()
        })
        .into_widget()
    }

    fn as_i32(result: Option<Rc<dyn Any>>) -> Option<i32> {
        result.and_then(|value| value.downcast_ref::<i32>().copied())
    }

    #[test]
    fn invoke_reaches_the_nearest_actions_widget_that_maps_the_intent() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let log: Rc<RefCell<Vec<String>>> = Rc::default();
            let outer = CountAction::new(&mut app, &log, "outer");
            let inner = CountAction::new(&mut app, &log, "inner");
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            drop(app);
            tester.pump_widget(
                Actions::new(
                    map(TypeId::of::<CountIntent>(), outer.erase()),
                    Actions::new(
                        map(TypeId::of::<CountIntent>(), inner.erase()),
                        probe(&captured),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let context = captured.get().expect("the builder ran");

            let result = Actions::invoke(&mut app, context, &CountIntent { amount: 2 });
            assert_eq!(*log.borrow(), ["inner:2"]);
            assert_eq!(as_i32(result), Some(4));

            // A disabled action still stops the search, so nothing is invoked.
            inner.set_enabled(&mut app, false);
            log.borrow_mut().clear();
            let result = Actions::maybe_invoke(&mut app, context, &CountIntent { amount: 3 });
            assert!(log.borrow().is_empty());
            assert_eq!(as_i32(result), None);
        });
    }

    #[test]
    fn invoke_walks_past_an_actions_widget_that_does_not_map_the_intent() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let log: Rc<RefCell<Vec<String>>> = Rc::default();
            let outer = CountAction::new(&mut app, &log, "outer");
            let unrelated = DoNothingAction::new(&mut app);
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            drop(app);
            tester.pump_widget(
                Actions::new(
                    map(TypeId::of::<CountIntent>(), outer.erase()),
                    Actions::new(
                        map(TypeId::of::<OtherIntent>(), unrelated.erase()),
                        probe(&captured),
                    ),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let context = captured.get().expect("the builder ran");

            let result = Actions::invoke(&mut app, context, &CountIntent { amount: 5 });
            assert_eq!(*log.borrow(), ["outer:5"]);
            assert_eq!(as_i32(result), Some(10));
        });
    }

    #[test]
    fn maybe_find_returns_the_bound_action_and_handler_only_when_it_is_enabled() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let log: Rc<RefCell<Vec<String>>> = Rc::default();
            let action = CountAction::new(&mut app, &log, "action");
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            drop(app);
            tester.pump_widget(
                Actions::new(
                    map(TypeId::of::<CountIntent>(), action.erase()),
                    probe(&captured),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let context = captured.get().expect("the builder ran");

            assert_eq!(
                Actions::maybe_find(&mut app, context, TypeId::of::<CountIntent>()),
                Some(Action::as_action(action.handle()))
            );
            assert_eq!(
                Actions::maybe_find(&mut app, context, TypeId::of::<OtherIntent>()),
                None
            );

            let intent: IntentRef = Rc::new(CountIntent { amount: 7 });
            let handler = Actions::handler(&mut app, context, Rc::clone(&intent))
                .expect("an enabled action has a handler");
            handler.call(&mut app);
            assert_eq!(*log.borrow(), ["action:7"]);

            action.set_enabled(&mut app, false);
            assert!(Actions::handler(&mut app, context, intent).is_none());
        });
    }

    #[test]
    fn an_overridable_action_prefers_the_override_above_its_lookup_context() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let log: Rc<RefCell<Vec<String>>> = Rc::default();
            let override_action = CountAction::new(&mut app, &log, "override");
            let default_action = CountAction::new(&mut app, &log, "default");
            let outer_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let outer_sink = Rc::clone(&outer_context);
            let inner_sink = Rc::clone(&inner_context);
            drop(app);
            tester.pump_widget(
                Actions::new(
                    map(TypeId::of::<CountIntent>(), override_action.erase()),
                    Builder::new(move |_app, context| {
                        outer_sink.set(Some(context));
                        probe(&inner_sink)
                    }),
                )
                .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let lookup_context = outer_context.get().expect("the builder ran");

            let overridable =
                AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
            let intent = CountIntent { amount: 1 };
            overridable.invoke(&mut app, &intent, Some(lookup_context));
            assert_eq!(*log.borrow(), ["override:1"]);

            // With no override above the lookup context, the default action runs.
        });
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            let log: Rc<RefCell<Vec<String>>> = Rc::default();
            let default_action = CountAction::new(&mut app, &log, "default");
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            drop(app);
            tester.pump_widget(probe(&captured));
            let mut app = tester.cell.borrow_mut();
            let lookup_context = captured.get().expect("the builder ran");
            let intent = CountIntent { amount: 1 };
            let overridable =
                AnyAction::overridable(&mut app, default_action.erase(), lookup_context);
            overridable.invoke(&mut app, &intent, Some(lookup_context));
            assert_eq!(*log.borrow(), ["default:1"]);
        });
    }

    #[test]
    fn the_detector_reports_the_focus_highlight() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            FocusManager::instance(&mut app)
                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
            let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
            let focused: Rc<RefCell<Vec<bool>>> = Rc::default();
            let highlight_sink = Rc::clone(&focus_highlights);
            let focus_sink = Rc::clone(&focused);
            drop(app);
            tester.pump_widget(
                FocusableActionDetector::new(SizedBox::expand())
                    .autofocus(true)
                    .on_show_focus_highlight(move |_app, show| {
                        highlight_sink.borrow_mut().push(show)
                    })
                    .on_focus_change(move |_app, has_focus| focus_sink.borrow_mut().push(has_focus))
                    .into_widget(),
            );
            // The post-frame callback `init_state` registered decides whether a highlight may show.
            tester.pump();

            assert_eq!(*focused.borrow(), [true]);
            assert_eq!(*focus_highlights.borrow(), [true]);
        });
    }

    #[test]
    fn the_detector_reports_the_hover_highlight() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            FocusManager::instance(&mut app)
                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
            let hover_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
            let sink = Rc::clone(&hover_highlights);
            drop(app);
            tester.pump_widget(
                FocusableActionDetector::new(SizedBox::expand())
                    .on_show_hover_highlight(move |_app, show| sink.borrow_mut().push(show))
                    .into_widget(),
            );
            tester.pump();

            let mut mouse = TestPointer::mouse(1, 0);
            tester.move_to(&mut mouse, Offset::new(10.0, 10.0), false);
            assert_eq!(*hover_highlights.borrow(), [true]);

            tester.move_to(&mut mouse, Offset::new(10_000.0, 10_000.0), false);
            assert_eq!(*hover_highlights.borrow(), [true, false]);
        });
    }

    #[test]
    fn a_disabled_detector_shows_no_highlight() {
        test_widgets(|tester| {
            let mut app = tester.cell.borrow_mut();
            FocusManager::instance(&mut app)
                .set_highlight_strategy(&mut app, FocusHighlightStrategy::AlwaysTraditional);
            let focus_highlights: Rc<RefCell<Vec<bool>>> = Rc::default();
            let sink = Rc::clone(&focus_highlights);
            let node = crate::FocusNode::new(&mut app);
            let detector = |enabled: bool, sink: Rc<RefCell<Vec<bool>>>| {
                FocusableActionDetector::new(SizedBox::expand())
                    .enabled(enabled)
                    .focus_node(node.erase())
                    .autofocus(true)
                    .on_show_focus_highlight(move |_app, show| sink.borrow_mut().push(show))
                    .into_widget()
            };
            drop(app);
            tester.pump_widget(detector(false, Rc::clone(&sink)));
            tester.pump();
            let mut app = tester.cell.borrow_mut();
            // A disabled detector sets `Focus.canRequestFocus` to false, so nothing is focused.
            node.request_focus(&mut app, None);
            app.drain_microtasks();
            assert!(!node.has_primary_focus(&app));
            assert!(focus_highlights.borrow().is_empty());

            drop(app);
            tester.pump_widget(detector(true, Rc::clone(&sink)));
            tester.pump();
            let mut app = tester.cell.borrow_mut();
            node.request_focus(&mut app, None);
            app.drain_microtasks();
            assert!(node.has_primary_focus(&app));
            assert_eq!(*focus_highlights.borrow(), [true]);
        });
    }
}

#[cfg(test)]
mod diagnostics_tests {
    use std::collections::HashMap;

    use waft_rendering::testing::ignoring_hash_codes;

    use super::*;
    use crate::Container;
    use crate::testing::describe_properties;

    /// `actions_test.dart`, "default Intent debugFillProperties".
    #[test]
    fn a_default_intent_adds_no_properties() {
        let intent = ActivateIntent;
        assert_eq!(
            describe_properties(|properties| intent.debug_fill_properties(properties)),
            Vec::<String>::new()
        );
    }

    /// `actions_test.dart`, "default Actions debugFillProperties".
    #[test]
    fn the_default_actions_describe_their_dispatcher_and_empty_map() {
        let actions = Actions::new(HashMap::new(), Container::new())
            .dispatcher(Rc::new(PlainActionDispatcher::new()));
        let cell = waft_foundation::AppCell::new();
        let app = cell.borrow();
        let description =
            describe_properties(|properties| actions.debug_fill_properties(&app, properties));
        assert_eq!(description.len(), 2);
        assert_eq!(
            ignoring_hash_codes(&description.join("\n")),
            "dispatcher: ActionDispatcher#00000\nactions: {}"
        );
    }
}