waft-widgets 0.7.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
//! Flutter counterpart: `widgets/app.dart`.
//!
//! [`WidgetsApp`], the widget an application is built from: the navigator, the localizations,
//! the default shortcuts and actions, and the debug banner. `WidgetsApp.router` waits with
//! `router.dart`.

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

use waft_embedder::{AppLifecycleState, Clip, Color, Locale, TargetPlatform, ViewId, ViewRef};
use waft_foundation::{App, DebugFlag, Handle, K_IS_WEB, Listenable, OptionRetained, Ref};
use waft_painting::{AxisDirection, TextStyle};
use waft_scheduler::SchedulerBinding;
use waft_services::{KeyEvent, LogicalKeyboardKey};

use crate::binding::{WidgetsBinding, WidgetsBindingObserverObject, WidgetsBindingObserverRef};
use crate::framework::{
    BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
};
use crate::view::View;
use crate::widgets::actions::{
    ActionRef, Actions, ActivateIntent, AnyAction, ButtonActivateIntent, DismissIntent,
    DoNothingAction, DoNothingAndStopPropagationIntent, DoNothingIntent, PrioritizedAction,
    PrioritizedIntents, VoidCallbackAction, VoidCallbackIntent,
};
use crate::widgets::banner::CheckedModeBanner;
use crate::widgets::basic::{Builder, WidgetBuilder};
use crate::widgets::default_text_editing_shortcuts::{DefaultTextEditingShortcuts, shortcut_map};
use crate::widgets::focus_manager::{KeyEventResult, TraversalEdgeBehavior};
use crate::widgets::focus_scope::{Focus, FocusScope};
use crate::widgets::focus_traversal::{
    DirectionalFocusAction, DirectionalFocusIntent, FocusTraversalGroup, NextFocusAction,
    NextFocusIntent, PreviousFocusAction, PreviousFocusIntent, ReadingOrderTraversalPolicy,
    RequestFocusAction, RequestFocusIntent, TraversalDirection,
};
use crate::widgets::localizations::{
    Localizations, LocalizationsDelegateRef, LocalizationsResolver,
};
use crate::widgets::navigator::{
    NavigationNotification, Navigator, NavigatorObserverRef, NavigatorState, RouteFactory,
    RouteRef, RouteSettings,
};
use crate::widgets::notification_listener::{NotificationListener, NotificationListenerCallback};
use crate::widgets::pages::PageRouteRef;
use crate::widgets::raw_tooltip::RawTooltip;
use crate::widgets::restoration::RootRestorationScope;
use crate::widgets::scrollable_helpers::{ScrollAction, ScrollIncrementType, ScrollIntent};
use crate::widgets::shared_app_data::SharedAppData;
use crate::widgets::shortcuts::{ShortcutMap, ShortcutRegistrar, Shortcuts};
use crate::widgets::tap_region::TapRegionSurface;
use crate::widgets::text::DefaultTextStyle;
use crate::widgets::title::Title;
use crate::widgets::transitions::{ListenableBuilder, TransitionBuilder};

/// The signature of `WidgetsApp.localeListResolutionCallback`.
///
/// A [`LocaleListResolutionCallback`] is responsible for computing the locale of the app's
/// `Localizations` object when the app starts and when user changes the list of
/// locales for the device.
///
/// The `locales` list is the device's preferred locales when the app started, or the
/// device's preferred locales the user selected after the app was started. This list
/// is in order of preference. If this list is null or empty, then Flutter has not yet
/// received the locale information from the platform. The `supported_locales` parameter
/// is just the value of `WidgetsApp.supportedLocales`.
///
/// See also:
///
///  * [`LocaleResolutionCallback`], which takes only one default locale (instead of a list)
///    and is attempted only after this callback fails or is null. [`LocaleListResolutionCallback`]
///    is recommended over [`LocaleResolutionCallback`].
pub type LocaleListResolutionCallback = Rc<dyn Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>>;

/// The signature of `WidgetsApp.localeResolutionCallback`.
///
/// It is recommended to provide a [`LocaleListResolutionCallback`] instead of a
/// [`LocaleResolutionCallback`] when possible, as [`LocaleResolutionCallback`] only
/// receives a subset of the information provided in [`LocaleListResolutionCallback`].
///
/// A [`LocaleResolutionCallback`] is responsible for computing the locale of the app's
/// `Localizations` object when the app starts and when user changes the default
/// locale for the device after [`LocaleListResolutionCallback`] fails or is not provided.
///
/// This callback is also used if the app is created with a specific locale using
/// the `WidgetsApp.new` `locale` parameter.
///
/// The `locale` is either the value of `WidgetsApp.locale`, or the device's default
/// locale when the app started, or the device locale the user selected after the app
/// was started. The default locale is the first locale in the list of preferred
/// locales. If `locale` is null, then Flutter has not yet received the locale
/// information from the platform. The `supported_locales` parameter is just the value of
/// `WidgetsApp.supportedLocales`.
///
/// See also:
///
///  * [`LocaleListResolutionCallback`], which takes a list of preferred locales (instead of one locale).
///    Resolutions by [`LocaleListResolutionCallback`] take precedence over [`LocaleResolutionCallback`].
pub type LocaleResolutionCallback = Rc<dyn Fn(Option<&Locale>, &[Locale]) -> Option<Locale>>;

/// The default locale resolution algorithm.
///
/// Custom resolution algorithms can be provided through
/// `WidgetsApp.localeListResolutionCallback` or
/// `WidgetsApp.localeResolutionCallback`.
///
/// When no custom locale resolution algorithms are provided or if both fail
/// to resolve, Flutter will default to calling this algorithm.
///
/// This algorithm prioritizes speed at the cost of slightly less appropriate
/// resolutions for edge cases.
///
/// This algorithm will resolve to the earliest preferred locale that
/// matches the most fields, prioritizing in the order of perfect match,
/// languageCode+countryCode, languageCode+scriptCode, languageCode-only.
///
/// In the case where a locale is matched by languageCode-only and is not the
/// default (first) locale, the next preferred locale with a
/// perfect match can supersede the languageCode-only match if it exists.
///
/// When a preferredLocale matches more than one supported locale, it will
/// resolve to the first matching locale listed in the supportedLocales.
///
/// When all preferred locales have been exhausted without a match, the first
/// countryCode only match will be returned.
///
/// When no match at all is found, the first (default) locale in
/// `supported_locales` will be returned.
///
/// To summarize, the main matching priority is:
///
///  1. `Locale.languageCode`, `Locale.scriptCode`, and `Locale.countryCode`
///  2. `Locale.languageCode` and `Locale.scriptCode` only
///  3. `Locale.languageCode` and `Locale.countryCode` only
///  4. `Locale.languageCode` only (with caveats, see above)
///  5. `Locale.countryCode` only when all `preferred_locales` fail to match
///  6. Returns the first element of `supported_locales` as a fallback
///
/// This algorithm does not take language distance (how similar languages are to each other)
/// into account, and will not handle edge cases such as resolving `de` to `fr` rather than `zh`
/// when `de` is not supported and `zh` is listed before `fr` (German is closer to French
/// than Chinese).
pub fn basic_locale_list_resolution(
    preferred_locales: Option<&[Locale]>,
    supported_locales: &[Locale],
) -> Locale {
    let first_supported = supported_locales
        .first()
        .expect("supportedLocales must not be empty")
        .clone();
    let Some(preferred_locales) = preferred_locales.filter(|locales| !locales.is_empty()) else {
        return first_supported;
    };
    // The hashmaps below are the 'flattened' representation of the supported locales;
    // only the first supported locale with the same key is kept.
    let mut all_supported_locales: HashMap<String, &Locale> = HashMap::new();
    let mut language_and_country_locales: HashMap<String, &Locale> = HashMap::new();
    let mut language_and_script_locales: HashMap<String, &Locale> = HashMap::new();
    let mut language_locales: HashMap<&str, &Locale> = HashMap::new();
    let mut country_locales: HashMap<Option<&str>, &Locale> = HashMap::new();
    for locale in supported_locales {
        all_supported_locales
            .entry(full_key(locale))
            .or_insert(locale);
        language_and_script_locales
            .entry(language_and_script_key(locale))
            .or_insert(locale);
        language_and_country_locales
            .entry(language_and_country_key(locale))
            .or_insert(locale);
        language_locales
            .entry(&locale.language_code)
            .or_insert(locale);
        country_locales
            .entry(locale.country_code.as_deref())
            .or_insert(locale);
    }

    // Since languageCode-only matches are possibly low quality, we don't return
    // it instantly when we find such a match. We check to see if the next
    // preferred locale in the list has a high accuracy match, and only return
    // the languageCode-only match when a higher accuracy match in the next
    // preferred locale cannot be found.
    let mut matches_language_code: Option<&Locale> = None;
    let mut matches_country_code: Option<&Locale> = None;
    // Loop over user's preferred locales
    for (locale_index, user_locale) in preferred_locales.iter().enumerate() {
        // Look for perfect match.
        if all_supported_locales.contains_key(&full_key(user_locale)) {
            return user_locale.clone();
        }
        // Look for language+script match.
        if user_locale.script_code.is_some()
            && let Some(matched) =
                language_and_script_locales.get(&language_and_script_key(user_locale))
        {
            return (*matched).clone();
        }
        // Look for language+country match.
        if user_locale.country_code.is_some()
            && let Some(matched) =
                language_and_country_locales.get(&language_and_country_key(user_locale))
        {
            return (*matched).clone();
        }
        // If there was a languageCode-only match in the previous iteration's higher
        // ranked preferred locale, we return it if the current userLocale does not
        // have a better match.
        if let Some(matched) = matches_language_code {
            return matched.clone();
        }
        // Look and store language-only match.
        if let Some(&matched) = language_locales.get(user_locale.language_code.as_str()) {
            matches_language_code = Some(matched);
            // Since first (default) locale is usually highly preferred, we will allow
            // a languageCode-only match to be instantly matched. If the next preferred
            // languageCode is the same, we defer hastily returning until the next iteration
            // since at worst it is the same and at best it has a strong match.
            let next_prefers_the_same_language = preferred_locales
                .get(locale_index + 1)
                .is_some_and(|next| next.language_code == user_locale.language_code);
            if locale_index == 0 && !next_prefers_the_same_language {
                return matched.clone();
            }
        }
        // countryCode-only match. When all else except default supported locale fails,
        // attempt to match by country only, as a user is likely to be familiar with a
        // language from their listed country.
        if matches_country_code.is_none()
            && user_locale.country_code.is_some()
            && let Some(&matched) = country_locales.get(&user_locale.country_code.as_deref())
        {
            matches_country_code = Some(matched);
        }
    }
    // When there is no languageCode-only match. Fallback to matching countryCode only. Country
    // fallback only applies on iOS. When there is no countryCode-only match, we return first
    // supported locale.
    matches_language_code
        .or(matches_country_code)
        .cloned()
        .unwrap_or(first_supported)
}

fn full_key(locale: &Locale) -> String {
    format!(
        "{}_{:?}_{:?}",
        locale.language_code, locale.script_code, locale.country_code
    )
}

fn language_and_script_key(locale: &Locale) -> String {
    format!("{}_{:?}", locale.language_code, locale.script_code)
}

fn language_and_country_key(locale: &Locale) -> String {
    format!("{}_{:?}", locale.language_code, locale.country_code)
}

/// The signature of [`WidgetsApp::on_generate_title`].
///
/// Used to generate a value for the app's [`Title::title`], which the device uses
/// to identify the app for the user. The `context` includes the [`WidgetsApp`]'s
/// `Localizations` widget so that this method can be used to produce a
/// localized title.
pub type GenerateAppTitle = Rc<dyn Fn(&mut App, BuildContext) -> String>;

/// The signature of [`WidgetsApp::page_route_builder`].
///
/// Creates a `PageRoute` using the given [`RouteSettings`] and [`WidgetBuilder`].
pub type PageRouteFactory = Rc<dyn Fn(&mut App, &RouteSettings, WidgetBuilder) -> PageRouteRef>;

/// The signature of [`WidgetsApp::on_generate_initial_routes`].
///
/// Creates a series of one or more initial routes.
pub type InitialRouteListFactory = Rc<dyn Fn(&mut App, &str) -> Vec<RouteRef>>;

/// The [`App`] debug flag of [`WidgetsApp::show_performance_overlay_override`].
pub struct ShowPerformanceOverlayOverride;

impl DebugFlag for ShowPerformanceOverlayOverride {}

/// The [`App`] debug flag of [`WidgetsApp::debug_allow_banner_override`].
pub struct DebugAllowBannerOverride;

impl DebugFlag for DebugAllowBannerOverride {
    const DEFAULT: bool = true;
}

/// A convenience widget that wraps a number of widgets that are commonly
/// required for an application.
///
/// One of the primary roles that [`WidgetsApp`] provides is binding the system
/// back button to popping the [`Navigator`] or quitting the application.
///
/// It is used by both `MaterialApp` and `CupertinoApp` to implement base
/// functionality for an app.
///
/// Find references to many of the widgets that [`WidgetsApp`] wraps in the "See
/// also" section.
///
/// See also:
///
///  * [`CheckedModeBanner`], which displays a `Banner` saying "DEBUG" when
///    running in debug mode.
///  * [`DefaultTextStyle`], the text style to apply to descendant `Text` widgets
///    without an explicit style.
///  * `MediaQuery`, which establishes a subtree in which media queries resolve
///    to a `MediaQueryData`.
///  * [`Localizations`], which defines the [`Locale`] for its `child`.
///  * [`Title`], a widget that describes this app in the operating system.
///  * [`Navigator`], a widget that manages a set of child widgets with a stack
///    discipline.
///  * `Overlay`, a widget that manages a `Stack` of entries that can be managed
///    independently.
pub struct WidgetsApp {
    /// See [`Widget::key`](crate::Widget::key).
    pub key: Option<KeyRef>,

    /// A key to use when building the [`Navigator`].
    ///
    /// If a [`navigator_key`](Self::navigator_key) is specified, the [`Navigator`] can be
    /// directly manipulated without first obtaining it from a [`BuildContext`] via
    /// [`Navigator::of`]: from the [`navigator_key`](Self::navigator_key), use the
    /// [`GlobalKey::current_state`] getter.
    ///
    /// If this is changed, a new [`Navigator`] will be created, losing all the
    /// application state in the process; in that case, the
    /// [`navigator_observers`](Self::navigator_observers) must also be changed, since the
    /// previous observers will be attached to the previous navigator.
    ///
    /// The [`Navigator`] is only built if [`on_generate_route`](Self::on_generate_route) is not
    /// `None`; if it is `None`, [`navigator_key`](Self::navigator_key) must also be `None`.
    pub navigator_key: Option<GlobalKey>,

    /// The route generator callback used when the app is navigated to a
    /// named route.
    ///
    /// If this returns `None` when building the routes to handle the specified
    /// [`initial_route`](Self::initial_route), then all the routes are discarded and
    /// [`Navigator::DEFAULT_ROUTE_NAME`] is used instead (`/`). See
    /// [`initial_route`](Self::initial_route).
    ///
    /// During normal app operation, the [`on_generate_route`](Self::on_generate_route) callback
    /// will only be applied to route names pushed by the application, and so should never
    /// return `None`.
    ///
    /// This is used if [`routes`](Self::routes) does not contain the requested route.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`builder`](Self::builder) must not be `None`.
    ///
    /// If this property is not set, either the [`routes`](Self::routes) or
    /// [`home`](Self::home) properties must be set, so that the default handler knows what
    /// routes to build, and [`page_route_builder`](Self::page_route_builder) must be set too, so
    /// that handler knows what transition to build them with.
    pub on_generate_route: Option<RouteFactory>,

    /// The routes generator callback used for generating initial routes if
    /// [`initial_route`](Self::initial_route) is provided.
    ///
    /// If this property is not set, the underlying
    /// [`Navigator::on_generate_initial_routes`] will default to
    /// [`Navigator::default_generate_initial_routes`].
    pub on_generate_initial_routes: Option<InitialRouteListFactory>,

    /// The `PageRoute` generator callback used when the app is navigated to a
    /// named route.
    ///
    /// A `PageRoute` represents the page in a [`Navigator`], so that it can
    /// correctly animate between pages, and to represent the "return value" of
    /// a route (e.g. which button a user selected in a modal dialog).
    ///
    /// This callback can be used, for example, to specify that a `MaterialPageRoute`
    /// or a `CupertinoPageRoute` should be used for building page transitions. It is required
    /// when `home` or `routes` are used and neither `builder` nor `onGenerateRoute` is given,
    /// as Flutter's assert checks; a kit app sets this to its kit's route.
    pub page_route_builder: Option<PageRouteFactory>,

    /// The widget for the default route of the app ([`Navigator::DEFAULT_ROUTE_NAME`],
    /// which is `/`).
    ///
    /// This is the route that is displayed first when the application is started
    /// normally, unless [`initial_route`](Self::initial_route) is specified. It's also the
    /// route that's displayed if the [`initial_route`](Self::initial_route) can't be
    /// displayed.
    ///
    /// If [`home`](Self::home) is specified, then [`routes`](Self::routes) must not include
    /// an entry for `/`, as [`home`](Self::home) takes its place.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`builder`](Self::builder) must not be `None`.
    ///
    /// The difference between using [`home`](Self::home) and using
    /// [`builder`](Self::builder) is that the [`home`](Self::home) subtree is inserted into
    /// the application below a [`Navigator`] (and thus below an `Overlay`, which
    /// [`Navigator`] uses). With [`home`](Self::home), therefore, dialog boxes will work
    /// automatically, the [`routes`](Self::routes) table will be used, and APIs such as
    /// [`Navigator::push`] and [`Navigator::pop`] will work as expected. In contrast, the
    /// widget returned from [`builder`](Self::builder) is inserted _above_ the app's
    /// [`Navigator`] (if any).
    ///
    /// If this property is set, the [`page_route_builder`](Self::page_route_builder) property
    /// must also be set, unless a [`builder`](Self::builder) or
    /// [`on_generate_route`](Self::on_generate_route) is, so that the default route handler
    /// will know what kind of `PageRoute`s to build.
    pub home: Option<WidgetRef>,

    /// The application's top-level routing table.
    ///
    /// When a named route is pushed with [`Navigator::push_named`], the route name is
    /// looked up in this map. If the name is present, the associated
    /// [`WidgetBuilder`] is used to construct a `PageRoute` specified by
    /// [`page_route_builder`](Self::page_route_builder) to perform an appropriate transition,
    /// including `Hero` animations, to the new route.
    ///
    /// If the app only has one page, then you can specify it using [`home`](Self::home)
    /// instead.
    ///
    /// If [`home`](Self::home) is specified, then it implies an entry in this table for the
    /// [`Navigator::DEFAULT_ROUTE_NAME`] route (`/`), and it is an error to
    /// redundantly provide such a route in the [`routes`](Self::routes) table.
    ///
    /// If a route is requested that is not specified in this table (or by
    /// [`home`](Self::home)), then the [`on_generate_route`](Self::on_generate_route) callback
    /// is called to build the page instead.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`builder`](Self::builder) must not be `None`.
    ///
    /// If the routes map is not empty, the [`page_route_builder`](Self::page_route_builder)
    /// property must be set, unless a [`builder`](Self::builder) or
    /// [`on_generate_route`](Self::on_generate_route) is, so that the default route handler
    /// will know what kind of `PageRoute`s to build.
    pub routes: HashMap<String, WidgetBuilder>,

    /// Called when [`on_generate_route`](Self::on_generate_route) fails to generate a route,
    /// except for the [`initial_route`](Self::initial_route).
    ///
    /// This callback is typically used for error handling. For example, this
    /// callback might always generate a "not found" page that describes the route
    /// that wasn't found.
    ///
    /// Unknown routes can arise either from errors in the app or from external
    /// requests to push routes, such as from Android intents.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`builder`](Self::builder) must not be `None`.
    pub on_unknown_route: Option<RouteFactory>,

    /// The callback to use when receiving a [`NavigationNotification`].
    ///
    /// By default this updates the engine with the navigation status and stops
    /// bubbling the notification.
    ///
    /// See also:
    ///
    ///  * [`NotificationListener::on_notification`], which uses this callback.
    pub on_navigation_notification: Option<NotificationListenerCallback<NavigationNotification>>,

    /// The name of the first route to show, if a [`Navigator`] is built.
    ///
    /// Defaults to [`Platform::default_route_name`](waft_embedder::Platform::default_route_name),
    /// which may be overridden by the code that launched the application.
    ///
    /// If the route name starts with a slash, then it is treated as a "deep link",
    /// and before this route is pushed, the routes leading to this one are pushed
    /// also. For example, if the route was `/a/b/c`, then the app would start
    /// with the four routes `/`, `/a`, `/a/b`, and `/a/b/c` loaded, in that order.
    /// Even if the route was just `/a`, the app would start with `/` and `/a`
    /// loaded. You can use the
    /// [`on_generate_initial_routes`](Self::on_generate_initial_routes) property to override
    /// this behavior.
    ///
    /// Intermediate routes aren't required to exist. In the example above, `/a`
    /// and `/a/b` could be skipped if they have no matching route. But `/a/b/c` is
    /// required to have a route, else [`initial_route`](Self::initial_route) is ignored and
    /// [`Navigator::DEFAULT_ROUTE_NAME`] is used instead (`/`). This can happen if the
    /// app is started with an intent that specifies a non-existent route.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`initial_route`](Self::initial_route) must be `None` and
    /// [`builder`](Self::builder) must not be `None`.
    ///
    /// Changing the [`initial_route`](Self::initial_route) will have no effect, as it only
    /// controls the _initial_ route. To change the route while the application is running,
    /// use the [`Navigator`] APIs.
    pub initial_route: Option<String>,

    /// The list of observers for the [`Navigator`] created for this app.
    ///
    /// This list must be replaced by a list of newly-created observers if the
    /// [`navigator_key`](Self::navigator_key) is changed.
    ///
    /// The [`Navigator`] is only built if routes are provided (either via
    /// [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route)); if they are not,
    /// [`navigator_observers`](Self::navigator_observers) must be the empty list and
    /// [`builder`](Self::builder) must not be `None`.
    pub navigator_observers: Vec<NavigatorObserverRef>,

    /// A builder for inserting widgets above the [`Navigator`] but below the
    /// other widgets created by the [`WidgetsApp`] widget, or for replacing the
    /// [`Navigator`] entirely.
    ///
    /// For example, from the [`BuildContext`] passed to this method, the
    /// `Directionality`, [`Localizations`], [`DefaultTextStyle`], `MediaQuery`, etc,
    /// are all available. They can also be overridden in a way that impacts all
    /// the routes in the [`Navigator`].
    ///
    /// This is rarely useful, but can be used in applications that wish to
    /// override those defaults, e.g. to force the application into right-to-left
    /// mode despite being in English, or to override the `MediaQuery` metrics
    /// (e.g. to leave a gap for advertisements shown by a plugin from OEM code).
    ///
    /// For specifically overriding the [`title`](Self::title) with a value based on the
    /// [`Localizations`], consider [`on_generate_title`](Self::on_generate_title) instead.
    ///
    /// The [`builder`](Self::builder) callback is passed two arguments, the [`BuildContext`]
    /// and a [`Navigator`] widget (as `child`).
    ///
    /// If no routes are provided using [`home`](Self::home), [`routes`](Self::routes),
    /// [`on_generate_route`](Self::on_generate_route), or
    /// [`on_unknown_route`](Self::on_unknown_route), the `child` will be `None`, and it is
    /// the responsibility of the [`builder`](Self::builder) to provide the application's
    /// routing machinery.
    ///
    /// If routes _are_ provided using one or more of those properties, then `child` is not
    /// `None`, and the returned value should include the `child` in the widget subtree; if it
    /// does not, then the application will have no [`Navigator`] and the routing related
    /// properties are ignored.
    ///
    /// If [`builder`](Self::builder) is `None`, it is as if a builder was specified that
    /// returned the `child` directly. If it is `None`, routes must be provided using one of
    /// the other properties listed above.
    ///
    /// Unless a [`Navigator`] is provided, either implicitly from
    /// [`builder`](Self::builder) being `None`, or by a [`builder`](Self::builder) including
    /// its `child` argument, or by a [`builder`](Self::builder) explicitly providing a
    /// [`Navigator`] of its own, widgets and APIs such as `Hero`, [`Navigator::push`] and
    /// [`Navigator::pop`], will not function.
    pub builder: Option<TransitionBuilder>,

    /// A one-line description used by the device to identify the app for the user.
    ///
    /// On Android the titles appear above the task manager's app snapshots which are
    /// displayed when the user presses the "recent apps" button. On iOS this
    /// value cannot be used. `CFBundleDisplayName` from the app's `Info.plist` is
    /// referred to instead whenever present, `CFBundleName` otherwise.
    /// On the web it is used as the page title, which shows up in the browser's list of open
    /// tabs.
    ///
    /// To provide a localized title instead, use
    /// [`on_generate_title`](Self::on_generate_title).
    pub title: Option<String>,

    /// If non-`None` this callback function is called to produce the app's
    /// title string, otherwise [`title`](Self::title) is used.
    ///
    /// The [`on_generate_title`](Self::on_generate_title) `context` parameter includes the
    /// [`WidgetsApp`]'s [`Localizations`] widget so that this callback can be used to produce
    /// a localized title.
    ///
    /// The [`on_generate_title`](Self::on_generate_title) callback is called each time the
    /// [`WidgetsApp`] rebuilds.
    pub on_generate_title: Option<GenerateAppTitle>,

    /// The default text style for `Text` in the application.
    pub text_style: Option<TextStyle>,

    /// The primary color to use for the application in the operating system
    /// interface.
    ///
    /// For example, on Android this is the color used for the application in the
    /// application switcher.
    pub color: Color,

    /// The initial locale for this app's [`Localizations`] widget is based
    /// on this value.
    ///
    /// If the `locale` is `None` then the system's locale value is used.
    ///
    /// The value of [`Localizations::locale_of`] will equal this locale if
    /// it matches one of the [`supported_locales`](Self::supported_locales). Otherwise it
    /// will be the first element of [`supported_locales`](Self::supported_locales).
    ///
    /// See also:
    ///
    ///  * [`locale_resolution_callback`](Self::locale_resolution_callback), which can override
    ///    the default [`supported_locales`](Self::supported_locales) matching algorithm.
    ///  * [`localizations_delegates`](Self::localizations_delegates), which collectively define
    ///    all of the localized resources used by this app.
    pub locale: Option<Locale>,

    /// The delegates for this app's [`Localizations`] widget.
    ///
    /// The delegates collectively define all of the localized resources
    /// for this application's [`Localizations`] widget.
    pub localizations_delegates: Option<Vec<LocalizationsDelegateRef>>,

    /// This callback is responsible for choosing the app's locale
    /// when the app is started, and when the user changes the
    /// device's locale.
    ///
    /// When a [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) is
    /// provided, the resolver will first attempt to resolve the locale with it. If the
    /// callback or result is `None`, it will fall back to trying the
    /// [`locale_resolution_callback`](Self::locale_resolution_callback). If both are left
    /// `None` or fail to resolve, the basic fallback algorithm will be used.
    ///
    /// The priority of each available fallback is:
    ///
    ///  1. [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) is
    ///     attempted.
    ///  2. [`locale_resolution_callback`](Self::locale_resolution_callback) is attempted.
    ///  3. [`basic_locale_list_resolution`], the basic resolution algorithm, is attempted last.
    ///
    /// This callback considers the entire list of preferred locales.
    ///
    /// This algorithm should be able to handle a `None` or empty list of preferred locales,
    /// which indicates the platform has not reported locale information yet.
    pub locale_list_resolution_callback: Option<LocaleListResolutionCallback>,

    /// See [`locale_list_resolution_callback`](Self::locale_list_resolution_callback).
    ///
    /// This callback considers only the default locale, which is the first locale
    /// in the preferred locales list. It is preferred to set
    /// [`locale_list_resolution_callback`](Self::locale_list_resolution_callback) over
    /// [`locale_resolution_callback`](Self::locale_resolution_callback) as it provides the
    /// full preferred locales list.
    pub locale_resolution_callback: Option<LocaleResolutionCallback>,

    /// The list of locales that this app has been localized for.
    ///
    /// By default only the American English locale is supported. Apps should
    /// configure this list to match the locales they support.
    ///
    /// The order of the list matters. The default locale resolution algorithm,
    /// [`basic_locale_list_resolution`], attempts to match by the following priority:
    ///
    ///  1. `Locale::language_code`, `Locale::script_code`, and `Locale::country_code`
    ///  2. `Locale::language_code` and `Locale::script_code` only
    ///  3. `Locale::language_code` and `Locale::country_code` only
    ///  4. `Locale::language_code` only
    ///  5. `Locale::country_code` only when all preferred locales fail to match
    ///  6. Returns the first element of [`supported_locales`](Self::supported_locales) as a
    ///     fallback
    ///
    /// When more than one supported locale matches one of these criteria, only
    /// the first matching locale is returned.
    ///
    /// When supporting languages with more than one script, it is recommended
    /// to specify the `Locale::script_code` explicitly. Locales may also be defined without
    /// `Locale::country_code` to specify a generic fallback for a particular script.
    pub supported_locales: Vec<Locale>,

    /// Turns on a performance overlay.
    ///
    /// See also:
    ///
    ///  * <https://flutter.dev/to/performance-overlay>
    pub show_performance_overlay: bool,

    /// Turns on an overlay that shows the accessibility information
    /// reported by the framework.
    pub show_semantics_debugger: bool,

    /// Turns on an overlay that enables inspecting the widget tree.
    ///
    /// The inspector is only available in debug mode as it depends on
    /// `RenderObject.debugDescribeChildren` which should not be called outside of
    /// debug mode.
    pub debug_show_widget_inspector: bool,

    /// Turns on a little "DEBUG" banner in debug mode to indicate
    /// that the app is in debug mode. This is on by default (in
    /// debug mode), to turn it off, set the setter argument to
    /// false. In release mode this has no effect.
    ///
    /// To get this banner in your application if you're not using
    /// [`WidgetsApp`], include a [`CheckedModeBanner`] widget in your app.
    ///
    /// This banner is intended to deter people from complaining that your
    /// app is slow when it's in debug mode. In debug mode, a large number of
    /// expensive diagnostics are enabled to aid in development, and so performance in debug
    /// mode is not representative of what will happen in release mode.
    pub debug_show_checked_mode_banner: bool,

    /// The default map of keyboard shortcuts to intents for the application.
    ///
    /// By default, this is set to [`WidgetsApp::default_shortcuts`].
    ///
    /// Passing this will not replace [`DefaultTextEditingShortcuts`]. These can be
    /// overridden by using a [`Shortcuts`] widget lower in the widget tree.
    ///
    /// See also:
    ///
    ///  * `SingleActivator`, which defines shortcut key combination of a single
    ///    key and modifiers, such as "Delete" or "Control+C".
    ///  * The [`Shortcuts`] widget, which defines a keyboard mapping.
    ///  * The [`Actions`] widget, which defines the mapping from intent to action.
    ///  * The `Intent` and `Action` traits, which allow definition of new actions.
    pub shortcuts: Option<ShortcutMap>,

    /// The default map of intent keys to actions for the application.
    ///
    /// By default, this is the output of [`WidgetsApp::default_actions`]. Specifying
    /// [`actions`](Self::actions) for an app overrides the default, so if you wish to modify
    /// the default [`actions`](Self::actions), you can call [`WidgetsApp::default_actions`]
    /// and modify the resulting map, passing it as the [`actions`](Self::actions) for this
    /// app. You may also add to the bindings, or override specific bindings for a widget
    /// subtree, by adding your own [`Actions`] widget.
    ///
    /// See also:
    ///
    ///  * The [`shortcuts`](Self::shortcuts) parameter, which defines the default set of
    ///    shortcuts for the application.
    ///  * The [`Shortcuts`] widget, which defines a keyboard mapping.
    ///  * The [`Actions`] widget, which defines the mapping from intent to action.
    pub actions: Option<HashMap<TypeId, ActionRef>>,

    /// The identifier to use for state restoration of this app.
    ///
    /// Providing a restoration ID inserts a [`RootRestorationScope`] into the
    /// widget hierarchy, which enables state restoration for descendant widgets.
    ///
    /// Providing a restoration ID also enables the [`Navigator`] built
    /// by the [`WidgetsApp`] to restore its state (i.e. to restore the history
    /// stack of active `Route`s). See the documentation on [`Navigator`] for more
    /// details around state restoration of `Route`s.
    ///
    /// See also:
    ///
    ///  * `RestorationManager`, which explains how state restoration works in
    ///    Flutter.
    pub restoration_scope_id: Option<String>,

    /// Dart's deprecated `useInheritedMediaQuery`. This setting is ignored.
    ///
    /// The widget never introduces its own `MediaQuery`; the `View` widget takes
    /// care of that.
    pub use_inherited_media_query: bool,
}

/// Flutter's message for an app that routes with `home` or `routes` but names no page route:
/// the constructor's assert in a debug build, the first route's panic in a release one.
const PAGE_ROUTE_BUILDER_REQUIRED: &str = "If neither builder nor onGenerateRoute are provided, \
    the pageRouteBuilder must be specified so that the default handler will know what kind of \
    PageRoute transition to build.";

impl WidgetsApp {
    /// Creates a widget that wraps a number of widgets that are commonly
    /// required for an application.
    ///
    /// Most callers will want to use the [`home`](Self::home) or [`routes`](Self::routes)
    /// setters, or both. The [`home`](Self::home) setter is a convenience for the following
    /// [`routes`](Self::routes) map:
    ///
    /// ```text
    /// {"/": |app, context| my_widget}
    /// ```
    ///
    /// It is possible to specify both [`home`](Self::home) and [`routes`](Self::routes), but
    /// only if [`routes`](Self::routes) does _not_ contain an entry for `"/"`. Conversely, if
    /// [`home`](Self::home) is omitted, [`routes`](Self::routes) _must_ contain an entry for
    /// `"/"`.
    ///
    /// If [`home`](Self::home) or [`routes`](Self::routes) are set, the routing implementation
    /// needs to know how to build `PageRoute`s, so the
    /// [`page_route_builder`](Self::page_route_builder) setter must be given one too, unless a
    /// [`builder`](Self::builder) or [`on_generate_route`](Self::on_generate_route) is; Flutter's
    /// assert checks it when the widget is turned into a [`WidgetRef`] in a debug build.
    ///
    /// The [`builder`](Self::builder) setter is designed to provide the ability to wrap the
    /// visible content of the app in some other widget. It is recommended that you use
    /// [`home`](Self::home) rather than [`builder`](Self::builder) if you intend to only
    /// display a single route in your app.
    ///
    /// [`WidgetsApp`] is also able to provide a custom implementation of routing via the
    /// [`on_generate_route`](Self::on_generate_route) and
    /// [`on_unknown_route`](Self::on_unknown_route) setters. These correspond to
    /// [`Navigator::on_generate_route`] and [`Navigator::on_unknown_route`]. If
    /// [`home`](Self::home), [`routes`](Self::routes), and [`builder`](Self::builder) are
    /// unset, or if they fail to create a requested route,
    /// [`on_generate_route`](Self::on_generate_route) will be invoked. If that fails,
    /// [`on_unknown_route`](Self::on_unknown_route) will be invoked.
    ///
    /// The [`supported_locales`](Self::supported_locales) list must have one or more elements.
    /// By default it is `[Locale::new("en").country_code("US")]`.
    ///
    /// The configuration is checked when the widget is turned into a `WidgetRef`: Dart's
    /// constructor asserts run there, because a fluent setter cannot see the fields that are
    /// still to come.
    pub fn new(color: Color) -> WidgetsApp {
        WidgetsApp {
            key: None,
            navigator_key: None,
            on_generate_route: None,
            on_generate_initial_routes: None,
            page_route_builder: None,
            home: None,
            routes: HashMap::new(),
            on_unknown_route: None,
            on_navigation_notification: None,
            initial_route: None,
            navigator_observers: Vec::new(),
            builder: None,
            title: None,
            on_generate_title: None,
            text_style: None,
            color,
            locale: None,
            localizations_delegates: None,
            locale_list_resolution_callback: None,
            locale_resolution_callback: None,
            supported_locales: vec![Locale::new("en").country_code("US")],
            show_performance_overlay: false,
            show_semantics_debugger: false,
            debug_show_widget_inspector: false,
            debug_show_checked_mode_banner: true,
            shortcuts: None,
            actions: None,
            restoration_scope_id: None,
            use_inherited_media_query: false,
        }
    }

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

    /// Dart `WidgetsApp(navigatorKey:)`.
    pub fn navigator_key(mut self, navigator_key: GlobalKey) -> WidgetsApp {
        self.navigator_key = Some(navigator_key);
        self
    }

    /// Dart `WidgetsApp(onGenerateRoute:)`.
    pub fn on_generate_route(
        mut self,
        on_generate_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
    ) -> WidgetsApp {
        self.on_generate_route = Some(Rc::new(on_generate_route));
        self
    }

    /// Dart `WidgetsApp(onGenerateInitialRoutes:)`.
    pub fn on_generate_initial_routes(
        mut self,
        on_generate_initial_routes: impl Fn(&mut App, &str) -> Vec<RouteRef> + 'static,
    ) -> WidgetsApp {
        self.on_generate_initial_routes = Some(Rc::new(on_generate_initial_routes));
        self
    }

    /// Dart `WidgetsApp(pageRouteBuilder:)`, which a [`home`](Self::home) or
    /// [`routes`](Self::routes) app must give unless it also gives a [`builder`](Self::builder)
    /// or [`on_generate_route`](Self::on_generate_route).
    pub fn page_route_builder(
        mut self,
        page_route_builder: impl Fn(&mut App, &RouteSettings, WidgetBuilder) -> PageRouteRef + 'static,
    ) -> WidgetsApp {
        self.page_route_builder = Some(Rc::new(page_route_builder));
        self
    }

    /// Dart `WidgetsApp(home:)`.
    pub fn home<K>(mut self, home: impl IntoWidget<K>) -> WidgetsApp {
        self.home = Some(home.into_widget());
        self
    }

    /// Dart `WidgetsApp(routes:)`.
    pub fn routes(
        mut self,
        routes: impl IntoIterator<Item = (String, WidgetBuilder)>,
    ) -> WidgetsApp {
        self.routes = routes.into_iter().collect();
        self
    }

    /// Dart `WidgetsApp(onUnknownRoute:)`.
    pub fn on_unknown_route(
        mut self,
        on_unknown_route: impl Fn(&mut App, &RouteSettings) -> Option<RouteRef> + 'static,
    ) -> WidgetsApp {
        self.on_unknown_route = Some(Rc::new(on_unknown_route));
        self
    }

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

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

    /// Dart `WidgetsApp(navigatorObservers:)`.
    pub fn navigator_observers(
        mut self,
        navigator_observers: impl IntoIterator<Item = NavigatorObserverRef>,
    ) -> WidgetsApp {
        self.navigator_observers = navigator_observers.into_iter().collect();
        self
    }

    /// Dart `WidgetsApp(builder:)`.
    pub fn builder(
        mut self,
        builder: impl Fn(&mut App, BuildContext, Option<&WidgetRef>) -> WidgetRef + 'static,
    ) -> WidgetsApp {
        self.builder = Some(Rc::new(builder));
        self
    }

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

    /// Dart `WidgetsApp(onGenerateTitle:)`.
    pub fn on_generate_title(
        mut self,
        on_generate_title: impl Fn(&mut App, BuildContext) -> String + 'static,
    ) -> WidgetsApp {
        self.on_generate_title = Some(Rc::new(on_generate_title));
        self
    }

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

    /// Dart `WidgetsApp(locale:)`.
    pub fn locale(mut self, locale: Locale) -> WidgetsApp {
        self.locale = Some(locale);
        self
    }

    /// Dart `WidgetsApp(localizationsDelegates:)`.
    pub fn localizations_delegates(
        mut self,
        localizations_delegates: impl IntoIterator<Item = LocalizationsDelegateRef>,
    ) -> WidgetsApp {
        self.localizations_delegates = Some(localizations_delegates.into_iter().collect());
        self
    }

    /// Dart `WidgetsApp(localeListResolutionCallback:)`.
    pub fn locale_list_resolution_callback(
        mut self,
        locale_list_resolution_callback: impl Fn(Option<&[Locale]>, &[Locale]) -> Option<Locale>
        + 'static,
    ) -> WidgetsApp {
        self.locale_list_resolution_callback = Some(Rc::new(locale_list_resolution_callback));
        self
    }

    /// Dart `WidgetsApp(localeResolutionCallback:)`.
    pub fn locale_resolution_callback(
        mut self,
        locale_resolution_callback: impl Fn(Option<&Locale>, &[Locale]) -> Option<Locale> + 'static,
    ) -> WidgetsApp {
        self.locale_resolution_callback = Some(Rc::new(locale_resolution_callback));
        self
    }

    /// Dart `WidgetsApp(supportedLocales:)`.
    pub fn supported_locales(
        mut self,
        supported_locales: impl IntoIterator<Item = Locale>,
    ) -> WidgetsApp {
        self.supported_locales = supported_locales.into_iter().collect();
        debug_assert!(!self.supported_locales.is_empty());
        self
    }

    /// Dart `WidgetsApp(showPerformanceOverlay:)`.
    pub fn show_performance_overlay(mut self, show_performance_overlay: bool) -> WidgetsApp {
        self.show_performance_overlay = show_performance_overlay;
        self
    }

    /// Dart `WidgetsApp(showSemanticsDebugger:)`.
    pub fn show_semantics_debugger(mut self, show_semantics_debugger: bool) -> WidgetsApp {
        self.show_semantics_debugger = show_semantics_debugger;
        self
    }

    /// Dart `WidgetsApp(debugShowWidgetInspector:)`.
    pub fn debug_show_widget_inspector(mut self, debug_show_widget_inspector: bool) -> WidgetsApp {
        self.debug_show_widget_inspector = debug_show_widget_inspector;
        self
    }

    /// Dart `WidgetsApp(debugShowCheckedModeBanner:)`.
    pub fn debug_show_checked_mode_banner(
        mut self,
        debug_show_checked_mode_banner: bool,
    ) -> WidgetsApp {
        self.debug_show_checked_mode_banner = debug_show_checked_mode_banner;
        self
    }

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

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

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

    /// Dart `WidgetsApp(useInheritedMediaQuery:)`, which is ignored.
    pub fn use_inherited_media_query(mut self, use_inherited_media_query: bool) -> WidgetsApp {
        self.use_inherited_media_query = use_inherited_media_query;
        self
    }

    /// If true, forces the performance overlay to be visible in all instances.
    ///
    /// Used by the `showPerformanceOverlay` VM service extension.
    pub fn show_performance_overlay_override(app: &App) -> bool {
        app.debug_flag::<ShowPerformanceOverlayOverride>()
    }

    /// Sets [`show_performance_overlay_override`](Self::show_performance_overlay_override).
    pub fn set_show_performance_overlay_override(app: &mut App, value: bool) {
        app.set_debug_flag::<ShowPerformanceOverlayOverride>(value);
    }

    /// If false, prevents the debug banner from being visible.
    ///
    /// Used by the `debugAllowBanner` VM service extension.
    ///
    /// This is how `flutter run` turns off the banner when you take a screen shot
    /// with "s".
    pub fn debug_allow_banner_override(app: &App) -> bool {
        app.debug_flag::<DebugAllowBannerOverride>()
    }

    /// Sets [`debug_allow_banner_override`](Self::debug_allow_banner_override).
    pub fn set_debug_allow_banner_override(app: &mut App, value: bool) {
        app.set_debug_flag::<DebugAllowBannerOverride>(value);
    }

    /// Generates the default shortcut key bindings based on the platform.
    ///
    /// Used by [`WidgetsApp`] to assign a default value to
    /// [`shortcuts`](Self::shortcuts).
    pub fn default_shortcuts(app: &App) -> ShortcutMap {
        if K_IS_WEB {
            return default_web_shortcuts();
        }
        match app.platform().target_platform() {
            TargetPlatform::Android
            | TargetPlatform::Fuchsia
            | TargetPlatform::Linux
            | TargetPlatform::Windows => default_shortcuts_table(),
            TargetPlatform::IOS | TargetPlatform::MacOS => default_apple_os_shortcuts(),
        }
    }

    /// The default value of [`actions`](Self::actions).
    pub fn default_actions(app: &mut App) -> HashMap<TypeId, ActionRef> {
        let do_nothing = DoNothingAction::new(app);
        let do_nothing_and_stop_propagation = DoNothingAction::new(app);
        do_nothing_and_stop_propagation.set_consumes_key(app, false);
        let request_focus = RequestFocusAction::new(app);
        let next_focus = NextFocusAction::new(app);
        let previous_focus = PreviousFocusAction::new(app);
        let directional_focus = DirectionalFocusAction::new(app);
        let scroll = ScrollAction::new(app);
        let prioritized = PrioritizedAction::new(app);
        let void_callback = VoidCallbackAction::new(app);
        HashMap::from([
            (TypeId::of::<DoNothingIntent>(), do_nothing.into_erased()),
            (
                TypeId::of::<DoNothingAndStopPropagationIntent>(),
                do_nothing_and_stop_propagation.into_erased(),
            ),
            (
                TypeId::of::<RequestFocusIntent>(),
                request_focus.into_erased(),
            ),
            (TypeId::of::<NextFocusIntent>(), next_focus.into_erased()),
            (
                TypeId::of::<PreviousFocusIntent>(),
                previous_focus.into_erased(),
            ),
            (
                TypeId::of::<DirectionalFocusIntent>(),
                directional_focus.into_erased(),
            ),
            (TypeId::of::<ScrollIntent>(), scroll.into_erased()),
            (
                TypeId::of::<PrioritizedIntents>(),
                prioritized.into_erased(),
            ),
            (
                TypeId::of::<VoidCallbackIntent>(),
                void_callback.into_erased(),
            ),
        ])
    }
}

impl Debug for WidgetsApp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("WidgetsApp")
            .field("title", &self.title)
            .field("color", &self.color)
            .field("locale", &self.locale)
            .field("restorationScopeId", &self.restoration_scope_id)
            .finish_non_exhaustive()
    }
}

impl StatefulWidget for WidgetsApp {
    type State = WidgetsAppState;

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

    fn debug_check_constructor(&self) {
        debug_assert!(
            self.home.is_none() || self.on_generate_initial_routes.is_none(),
            "If onGenerateInitialRoutes is specified, the home argument will be redundant."
        );
        debug_assert!(
            self.home.is_none() || !self.routes.contains_key(Navigator::DEFAULT_ROUTE_NAME),
            "If the home property is specified, the routes table cannot include an entry for \
             \"/\", since it would be redundant."
        );
        debug_assert!(
            self.builder.is_some()
                || self.home.is_some()
                || self.routes.contains_key(Navigator::DEFAULT_ROUTE_NAME)
                || self.on_generate_route.is_some()
                || self.on_unknown_route.is_some(),
            "Either the home property must be specified, or the routes table must include an \
             entry for \"/\", or there must be on onGenerateRoute callback specified, or there \
             must be an onUnknownRoute callback specified, or the builder property must be \
             specified, because otherwise there is nothing to fall back on if the app is \
             started with an intent that specifies an unknown route."
        );
        debug_assert!(
            (self.home.is_some()
                || !self.routes.is_empty()
                || self.on_generate_route.is_some()
                || self.on_unknown_route.is_some())
                || (self.builder.is_some()
                    && self.navigator_key.is_none()
                    && self.initial_route.is_none()
                    && self.navigator_observers.is_empty()),
            "If no route is provided using home, routes, onGenerateRoute, or onUnknownRoute, a \
             non-null callback for the builder property must be provided, and the other \
             navigator-related properties, navigatorKey, initialRoute, and navigatorObservers, \
             must have their initial values (null, null, and the empty list, respectively)."
        );
        debug_assert!(
            self.builder.is_some()
                || self.on_generate_route.is_some()
                || self.page_route_builder.is_some(),
            "{PAGE_ROUTE_BUILDER_REQUIRED}"
        );
    }

    fn create_state(&self) -> WidgetsAppState {
        WidgetsAppState {
            state: StateData::new(),
            navigator: None,
            localizations_resolver: None,
            observer: None,
            app_lifecycle_state: None,
        }
    }
}

/// Dart's `_defaultShortcuts`, whose name the public getter takes.
fn default_shortcuts_table() -> ShortcutMap {
    shortcut_map![
        // Activation
        ENTER => ActivateIntent::new(),
        NUMPAD_ENTER => ActivateIntent::new(),
        SPACE => ActivateIntent::new(),
        GAME_BUTTON_A => ActivateIntent::new(),
        SELECT => ActivateIntent::new(),

        // Dismissal
        ESCAPE => DismissIntent::new(),

        // Keyboard traversal.
        TAB => NextFocusIntent::new(),
        TAB.shift(true) => PreviousFocusIntent::new(),
        ARROW_LEFT => DirectionalFocusIntent::new(TraversalDirection::Left),
        ARROW_RIGHT => DirectionalFocusIntent::new(TraversalDirection::Right),
        ARROW_DOWN => DirectionalFocusIntent::new(TraversalDirection::Down),
        ARROW_UP => DirectionalFocusIntent::new(TraversalDirection::Up),

        // Scrolling
        ARROW_UP.control(true) => ScrollIntent::new(AxisDirection::Up),
        ARROW_DOWN.control(true) => ScrollIntent::new(AxisDirection::Down),
        ARROW_LEFT.control(true) => ScrollIntent::new(AxisDirection::Left),
        ARROW_RIGHT.control(true) => ScrollIntent::new(AxisDirection::Right),
        PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
        PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
    ]
}

/// Default shortcuts for the web platform.
fn default_web_shortcuts() -> ShortcutMap {
    shortcut_map![
        // Activation
        SPACE => PrioritizedIntents::new(vec![
            Rc::new(ActivateIntent::new()),
            Rc::new(ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page)),
        ]),
        // On the web, enter activates buttons, but not other controls.
        ENTER => ButtonActivateIntent::new(),
        NUMPAD_ENTER => ButtonActivateIntent::new(),

        // Dismissal
        ESCAPE => DismissIntent::new(),

        // Keyboard traversal.
        TAB => NextFocusIntent::new(),
        TAB.shift(true) => PreviousFocusIntent::new(),

        // Scrolling
        ARROW_UP => ScrollIntent::new(AxisDirection::Up),
        ARROW_DOWN => ScrollIntent::new(AxisDirection::Down),
        ARROW_LEFT => ScrollIntent::new(AxisDirection::Left),
        ARROW_RIGHT => ScrollIntent::new(AxisDirection::Right),
        PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
        PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
    ]
}

/// Default shortcuts for the macOS and iOS platforms.
fn default_apple_os_shortcuts() -> ShortcutMap {
    shortcut_map![
        // Activation
        ENTER => ActivateIntent::new(),
        NUMPAD_ENTER => ActivateIntent::new(),
        SPACE => ActivateIntent::new(),

        // Dismissal
        ESCAPE => DismissIntent::new(),

        // Keyboard traversal
        TAB => NextFocusIntent::new(),
        TAB.shift(true) => PreviousFocusIntent::new(),
        ARROW_LEFT => DirectionalFocusIntent::new(TraversalDirection::Left),
        ARROW_RIGHT => DirectionalFocusIntent::new(TraversalDirection::Right),
        ARROW_DOWN => DirectionalFocusIntent::new(TraversalDirection::Down),
        ARROW_UP => DirectionalFocusIntent::new(TraversalDirection::Up),

        // Scrolling
        ARROW_UP.meta(true) => ScrollIntent::new(AxisDirection::Up),
        ARROW_DOWN.meta(true) => ScrollIntent::new(AxisDirection::Down),
        ARROW_LEFT.meta(true) => ScrollIntent::new(AxisDirection::Left),
        ARROW_RIGHT.meta(true) => ScrollIntent::new(AxisDirection::Right),
        PAGE_UP => ScrollIntent::new(AxisDirection::Up).r#type(ScrollIncrementType::Page),
        PAGE_DOWN => ScrollIntent::new(AxisDirection::Down).r#type(ScrollIncrementType::Page),
    ]
}

/// Dart's `_WidgetsAppState`.
pub struct WidgetsAppState {
    state: StateData<WidgetsApp>,
    navigator: Option<GlobalKey>,
    localizations_resolver: Option<Ref<LocalizationsResolver>>,
    observer: Option<WidgetsBindingObserverRef>,
    app_lifecycle_state: Option<AppLifecycleState>,
}

impl WidgetsAppState {
    /// The route the navigator starts with.
    ///
    /// If the platform's default route name isn't `/`, it was set intentionally by the host,
    /// and it overrides whatever is in [`WidgetsApp::initial_route`].
    fn initial_route_name(self: Handle<Self>, app: &App) -> String {
        let default_route_name = app.platform().default_route_name();
        if default_route_name != Navigator::DEFAULT_ROUTE_NAME {
            return default_route_name;
        }
        self.widget(app)
            .initial_route
            .clone()
            .unwrap_or(default_route_name)
    }

    /// The default value for [`WidgetsApp::on_navigation_notification`].
    ///
    /// Does nothing and stops bubbling if the app is detached. Otherwise, updates the host of the
    /// view the app is in with [`NavigationNotification::can_handle_pop`] and stops bubbling.
    fn default_on_navigation_notification(
        self: Handle<Self>,
        app: &mut App,
        notification: &NavigationNotification,
    ) -> bool {
        match app.get(self).app_lifecycle_state {
            None | Some(AppLifecycleState::Detached) => {
                // Avoid updating the engine when the app isn't ready.
                true
            }
            Some(
                AppLifecycleState::Inactive
                | AppLifecycleState::Resumed
                | AppLifecycleState::Hidden
                | AppLifecycleState::Paused,
            ) => {
                if let Some(view) = self.view(app) {
                    view.host()
                        .set_framework_handles_back(notification.can_handle_pop);
                }
                true
            }
        }
    }

    /// The view the app is built in, which its navigator's Back and its word on Back are about.
    fn view(self: Handle<Self>, app: &App) -> Option<ViewRef> {
        let id = View::maybe_id_of(app, self.context(app))?;
        app.platform().view(id)
    }

    fn clear_navigator_resource(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).navigator = None;
    }

    fn update_routing(self: Handle<Self>, app: &mut App, old_widget: Option<&WidgetsApp>) {
        if self.uses_navigator(app) {
            let navigator_key = self.widget(app).navigator_key.clone();
            let key_changed =
                old_widget.is_some_and(|old_widget| navigator_key != old_widget.navigator_key);
            if app.get(self).navigator.is_none() || key_changed {
                app.get_mut(self).navigator =
                    Some(navigator_key.unwrap_or_else(|| GlobalKey::object(self.id())));
            }
            debug_assert!(app.get(self).navigator.is_some());
        } else {
            debug_assert!(self.widget(app).builder.is_some());
            self.clear_navigator_resource(app);
        }
        // If we use a navigator, we have a navigator key.
        debug_assert!(self.uses_navigator(app) == app.get(self).navigator.is_some());
    }

    fn uses_navigator(self: Handle<Self>, app: &App) -> bool {
        let widget = self.widget(app);
        widget.home.is_some()
            || !widget.routes.is_empty()
            || widget.on_generate_route.is_some()
            || widget.on_unknown_route.is_some()
    }

    fn on_generate_route(
        self: Handle<Self>,
        app: &mut App,
        settings: &RouteSettings,
    ) -> Option<RouteRef> {
        let widget = self.widget(app);
        let name = settings.name.clone();
        let page_content_builder: Option<WidgetBuilder> = match name.as_deref() {
            Some(Navigator::DEFAULT_ROUTE_NAME) if widget.home.is_some() => {
                Some(Rc::new(move |app: &mut App, _context: BuildContext| {
                    self.widget(app)
                        .home
                        .clone()
                        .expect("the home route is built while WidgetsApp has a home")
                }))
            }
            _ => name
                .as_ref()
                .and_then(|name| widget.routes.get(name))
                .cloned(),
        };

        if let Some(page_content_builder) = page_content_builder {
            let page_route_builder = self
                .widget(app)
                .page_route_builder
                .clone()
                .expect(PAGE_ROUTE_BUILDER_REQUIRED);
            let route = page_route_builder(app, settings, page_content_builder);
            return Some(route.into_erased());
        }
        let on_generate_route = self.widget(app).on_generate_route.clone();
        if let Some(on_generate_route) = on_generate_route {
            return on_generate_route(app, settings);
        }
        None
    }

    fn on_unknown_route(
        self: Handle<Self>,
        app: &mut App,
        settings: &RouteSettings,
    ) -> Option<RouteRef> {
        let on_unknown_route = self
            .widget(app)
            .on_unknown_route
            .clone()
            .unwrap_or_else(|| {
                panic!(
                    "Could not find a generator for route {settings:?} in the WidgetsApp.\n\
                 Make sure your root app widget has provided a way to generate\n\
                 this route.\n\
                 Generators for routes are searched for in the following order:\n\
                 1. For the \"/\" route, the \"home\" property, if non-null, is used.\n\
                 2. Otherwise, the \"routes\" table is used, if it has an entry for the route.\n\
                 3. Otherwise, onGenerateRoute is called. It should return a non-null value \
                 for any valid route not handled by \"home\" and \"routes\".\n\
                 4. Finally if all else fails onUnknownRoute is called.\n\
                 Unfortunately, onUnknownRoute was not set."
                )
            });
        let result = on_unknown_route(app, settings);
        Some(result.expect(
            "The onUnknownRoute callback returned null.\nWhen the WidgetsApp requested a route \
             from its onUnknownRoute callback, the callback returned null. Such callbacks must \
             never return null.",
        ))
    }

    /// The resolver that keeps the app's locale and delegates up to date.
    fn localizations_resolver(self: Handle<Self>, app: &App) -> Handle<LocalizationsResolver> {
        app.get(self)
            .localizations_resolver
            .handle()
            .expect("init_state creates the resolver")
    }

    fn should_update_localizations(self: Handle<Self>, app: &App, old_widget: &WidgetsApp) -> bool {
        let widget = self.widget(app);
        widget.locale != old_widget.locale
            || !same_callback(
                &widget.locale_list_resolution_callback,
                &old_widget.locale_list_resolution_callback,
            )
            || !same_callback(
                &widget.locale_resolution_callback,
                &old_widget.locale_resolution_callback,
            )
            || widget.supported_locales != old_widget.supported_locales
            || !same_delegates(
                &widget.localizations_delegates,
                &old_widget.localizations_delegates,
            )
    }

    fn update_localizations(self: Handle<Self>, app: &mut App, old_widget: &WidgetsApp) {
        if self.should_update_localizations(app, old_widget) {
            let widget = self.widget(app);
            let locale = widget.locale.clone();
            let locale_list_resolution_callback = widget.locale_list_resolution_callback.clone();
            let locale_resolution_callback = widget.locale_resolution_callback.clone();
            let localizations_delegates = widget.localizations_delegates.clone();
            let supported_locales = widget.supported_locales.clone();
            self.localizations_resolver(app).update(
                app,
                locale,
                locale_list_resolution_callback,
                locale_resolution_callback,
                localizations_delegates,
                supported_locales,
            );
        }
    }

    /// Dart's `_usesNavigator` branch of `build`: the navigator and the focus scope over it.
    fn build_navigator(self: Handle<Self>, app: &mut App) -> WidgetRef {
        let navigator = app.get(self).navigator.clone().expect("a navigator key");
        let widget = self.widget(app);
        let observers = widget.navigator_observers.clone();
        let on_generate_initial_routes = widget.on_generate_initial_routes.clone();
        let initial_route = self.initial_route_name(app);
        let mut navigator_widget = Navigator::new()
            .clip_behavior(Clip::None)
            .restoration_scope_id("nav")
            .key(navigator.into())
            .initial_route(initial_route)
            .on_generate_route(move |app, settings| self.on_generate_route(app, settings))
            .on_unknown_route(move |app, settings| self.on_unknown_route(app, settings))
            .observers(observers)
            .route_traversal_edge_behavior(if K_IS_WEB {
                TraversalEdgeBehavior::LeaveFlutterView
            } else {
                TraversalEdgeBehavior::ParentScope
            })
            .reports_route_update_to_engine(true);
        navigator_widget = match on_generate_initial_routes {
            None => navigator_widget
                .on_generate_initial_routes(Navigator::default_generate_initial_routes),
            Some(on_generate_initial_routes) => navigator_widget.on_generate_initial_routes(
                move |app, _navigator, initial_route_name| {
                    on_generate_initial_routes(app, initial_route_name)
                },
            ),
        };
        FocusScope::new(navigator_widget)
            .debug_label("Navigator Scope")
            .autofocus(true)
            .into_widget()
    }
}

/// Dart's `==` on two optional callbacks: the same `Rc` allocation, or both absent.
fn same_callback<T: ?Sized>(one: &Option<Rc<T>>, other: &Option<Rc<T>>) -> bool {
    match (one, other) {
        (None, None) => true,
        (Some(one), Some(other)) => Rc::ptr_eq(one, other),
        _ => false,
    }
}

/// Dart's `==` on two optional delegate lists: pairwise identity, as Dart compares the lists.
fn same_delegates(
    one: &Option<Vec<LocalizationsDelegateRef>>,
    other: &Option<Vec<LocalizationsDelegateRef>>,
) -> bool {
    match (one, other) {
        (None, None) => true,
        (Some(one), Some(other)) => {
            one.len() == other.len()
                && one
                    .iter()
                    .zip(other)
                    .all(|(one, other)| ptr::addr_eq(&raw const **one, &raw const **other))
        }
        _ => false,
    }
}

impl WidgetsBindingObserverObject for WidgetsAppState {
    /// Dart's `WidgetsApp.didPopRoute`: the app's own navigator goes back, if it has one
    /// and it has something to go back to, for a Back in the view the app is built in.
    fn did_pop_route(self: Handle<Self>, app: &mut App, view: ViewId) -> bool {
        if View::maybe_id_of(app, self.context(app)) != Some(view) {
            return false;
        }
        let Some(key) = app.get(self).navigator.clone() else {
            return false;
        };
        let Some(navigator) = key.current_state::<NavigatorState>(app) else {
            return false;
        };
        navigator.maybe_pop(app, None)
    }

    fn did_change_app_lifecycle_state(self: Handle<Self>, app: &mut App, state: AppLifecycleState) {
        app.get_mut(self).app_lifecycle_state = Some(state);
    }
}

impl State for WidgetsAppState {
    type Widget = WidgetsApp;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        let widget = self.widget(app);
        let locale = widget.locale.clone();
        let locale_list_resolution_callback = widget.locale_list_resolution_callback.clone();
        let locale_resolution_callback = widget.locale_resolution_callback.clone();
        let localizations_delegates = widget.localizations_delegates.clone();
        let supported_locales = widget.supported_locales.clone();
        let resolver = LocalizationsResolver::new(
            app,
            locale,
            locale_list_resolution_callback,
            locale_resolution_callback,
            localizations_delegates,
            supported_locales,
        );
        app.get_mut(self).localizations_resolver = Some(resolver);
        self.update_routing(app, None);
        let observer: WidgetsBindingObserverRef = Rc::new(self);
        WidgetsBinding::instance(app).add_observer(app, Rc::clone(&observer));
        app.get_mut(self).observer = Some(observer);
        app.get_mut(self).app_lifecycle_state = SchedulerBinding::lifecycle_state(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &WidgetsApp) {
        self.update_routing(app, Some(old_widget));
        self.update_localizations(app, old_widget);
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        if let Some(observer) = app.get_mut(self).observer.take() {
            WidgetsBinding::instance(app).remove_observer(app, &observer);
        }
        self.localizations_resolver(app).dispose(app);
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        let routing: Option<WidgetRef> =
            self.uses_navigator(app).then(|| self.build_navigator(app));

        let mut result = match self.widget(app).builder.clone() {
            Some(builder) => {
                Builder::new(move |app, context| builder(app, context, routing.as_ref()))
                    .into_widget()
            }
            None => routing.expect("either a builder or a navigator"),
        };

        if let Some(text_style) = self.widget(app).text_style.clone() {
            result = DefaultTextStyle::new(text_style, result).into_widget();
        }

        // The performance overlay, the semantics debugger, and the widget inspector wait; see
        // PORTING.md.

        if cfg!(debug_assertions)
            && self.widget(app).debug_show_checked_mode_banner
            && WidgetsApp::debug_allow_banner_override(app)
        {
            result = CheckedModeBanner::new(result).into_widget();
        }

        // TODO(victorsanni): https://github.com/flutter/flutter/issues/180319
        // Use actions and shortcuts to dismiss tooltips when esc is pressed instead
        // of using a Focus widget.
        result = Focus::new(result)
            .can_request_focus(false)
            .on_key_event(Rc::new(|app, _node, event| {
                if !matches!(event, KeyEvent::Down(_) | KeyEvent::Repeat(_))
                    || event.logical_key() != LogicalKeyboardKey::ESCAPE
                {
                    return KeyEventResult::Ignored;
                }
                if RawTooltip::dismiss_all_tool_tips(app) {
                    KeyEventResult::Handled
                } else {
                    KeyEventResult::Ignored
                }
            }))
            .into_widget();

        let color = self.widget(app).color;
        let title: Option<WidgetRef> = match self.widget(app).on_generate_title.clone() {
            Some(on_generate_title) => {
                let child = result.clone();
                // This Builder exists to provide a context below the Localizations widget.
                // The on_generate_title callback can refer to Localizations via its context
                // parameter.
                Some(
                    Builder::new(move |app, context| {
                        let title = on_generate_title(app, context);
                        Title::new(
                            color.with_values(Some(1.0), None, None, None, None),
                            child.clone(),
                        )
                        .title(title)
                        .into_widget()
                    })
                    .into_widget(),
                )
            }
            // Updating the title element in the DOM is problematic in embedded and multiview
            // modes as the title should be managed by host apps.
            None if self.widget(app).title.is_none() && K_IS_WEB => None,
            None => {
                let title = self.widget(app).title.clone().unwrap_or_default();
                Some(
                    Title::new(
                        color.with_values(Some(1.0), None, None, None, None),
                        result.clone(),
                    )
                    .title(title)
                    .into_widget(),
                )
            }
        };

        let resolver = app
            .get(self)
            .localizations_resolver
            .clone()
            .expect("init_state creates the resolver");
        let localized = title.unwrap_or(result);
        let localizations = ListenableBuilder::new(
            Rc::new(resolver.clone()) as Rc<dyn Listenable>,
            move |app, _context, _child| {
                let locale = resolver.locale(app);
                let delegates = resolver.localizations_delegates(app);
                Localizations::new(locale, delegates)
                    .is_application_level(true)
                    .child(localized.clone())
                    .into_widget()
            },
        );

        let actions = match self.widget(app).actions.clone() {
            Some(actions) => actions,
            None => {
                let mut actions = WidgetsApp::default_actions(app);
                let scroll = ScrollAction::new(app);
                actions.insert(
                    TypeId::of::<ScrollIntent>(),
                    AnyAction::overridable(app, scroll.into_erased(), context),
                );
                actions
            }
        };
        let policy = ReadingOrderTraversalPolicy::new(app).into_erased();
        let shortcuts = match self.widget(app).shortcuts.clone() {
            Some(shortcuts) => shortcuts,
            None => WidgetsApp::default_shortcuts(app),
        };
        let on_navigation_notification = self.widget(app).on_navigation_notification.clone();
        let restoration_scope_id = self.widget(app).restoration_scope_id.clone();

        RootRestorationScope::new(
            restoration_scope_id,
            SharedAppData::new(
                NotificationListener::<NavigationNotification>::new(
                    Shortcuts::new(
                        shortcuts,
                        DefaultTextEditingShortcuts::new(Actions::new(
                            actions,
                            FocusTraversalGroup::new(TapRegionSurface::new(
                                ShortcutRegistrar::new(localizations),
                            ))
                            .policy(policy),
                        )),
                    )
                    .debug_label("<Default WidgetsApp Shortcuts>"),
                )
                .on_notification(move |app, notification| match &on_navigation_notification {
                    Some(on_navigation_notification) => {
                        on_navigation_notification(app, notification)
                    }
                    None => self.default_on_navigation_notification(app, notification),
                })
                .into_widget(),
            ),
        )
        .into_widget()
    }
}

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

    fn locale(language: &str, country: Option<&str>) -> Locale {
        let locale = Locale::new(language);
        match country {
            Some(country) => locale.country_code(country),
            None => locale,
        }
    }

    #[test]
    fn a_perfect_match_wins_over_everything_later_in_the_list() {
        let supported = [
            locale("en", Some("US")),
            locale("fr", Some("FR")),
            locale("zh", Some("CN")),
        ];
        let preferred = [locale("fr", Some("FR")), locale("en", Some("US"))];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            locale("fr", Some("FR"))
        );
    }

    #[test]
    fn a_language_and_script_match_beats_a_language_and_country_match() {
        let supported = [
            locale("zh", Some("CN")),
            Locale::new("zh").script_code("Hant"),
            Locale::new("zh").script_code("Hans"),
        ];
        let preferred = [Locale::new("zh").script_code("Hant").country_code("CN")];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            Locale::new("zh").script_code("Hant")
        );
    }

    #[test]
    fn a_language_only_match_defers_to_a_better_match_for_the_same_language() {
        let supported = [locale("en", Some("US")), locale("en", Some("GB"))];
        // The first preferred locale only matches by language, but the second is a perfect
        // match for the same language, so it supersedes.
        let preferred = [locale("en", Some("AU")), locale("en", Some("GB"))];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            locale("en", Some("GB"))
        );
        // A different language next: the language-only match stands.
        let preferred = [locale("en", Some("AU")), locale("fr", Some("FR"))];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            locale("en", Some("US"))
        );
    }

    #[test]
    fn a_country_only_match_is_the_last_resort_before_the_first_supported_locale() {
        let supported = [locale("en", Some("US")), locale("fr", Some("CA"))];
        let preferred = [locale("de", Some("CA"))];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            locale("fr", Some("CA"))
        );
        let preferred = [locale("de", Some("DE"))];
        assert_eq!(
            basic_locale_list_resolution(Some(&preferred), &supported),
            locale("en", Some("US"))
        );
        assert_eq!(
            basic_locale_list_resolution(None, &supported),
            locale("en", Some("US"))
        );
        assert_eq!(
            basic_locale_list_resolution(Some(&[]), &supported),
            locale("en", Some("US"))
        );
    }

    // ---- WidgetsApp ----

    use std::cell::{Cell, RefCell};
    use std::time::Duration;

    use waft_embedder::TextDirection;
    use waft_painting::PaintingBinding;
    use waft_services::LogicalKeyboardKey;
    use waft_test::{IMPLICIT_VIEW_ID, TestPlatform, TestView};

    use crate::framework::{Notification, StatelessWidget};
    use crate::testing::{
        Finder, TestWidgetsApp, WidgetTester, expect, find, finds_nothing, finds_widgets,
        test_widgets,
    };
    use crate::widgets::actions::IntentRef;
    use crate::widgets::basic::SizedBox;
    use crate::widgets::focus_manager::{AnyFocusNode, FocusManager, FocusNodeLeaf, primary_focus};
    use crate::widgets::focus_scope::Focus;
    use crate::widgets::localizations::WidgetsLocalizations;

    /// The `color` every test app is given.
    const COLOR: Color = Color::new(0xFF2196F3);

    /// A leaf that is easy to find in the element tree.
    #[derive(Debug)]
    struct Marker;

    impl StatelessWidget for Marker {
        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
            SizedBox::new().width(10.0).height(10.0).into_widget()
        }
    }

    /// An [`App`] on a host with no views, for the tables that only read the target platform.
    fn app_of(platform: TargetPlatform) -> Rc<AppCell> {
        AppCell::with_platform(Rc::new(TestPlatform::new().on(platform)))
    }

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

    /// Runs `widget` as the content of every view, and the first frame of each: the
    /// multi-view case's start, which the one-view tester has no counterpart of.
    fn mount_in_every_view(cell: &AppCell, widget: WidgetRef) {
        crate::binding::run_app(&mut cell.borrow_mut(), widget);
        cell.elapse(Duration::ZERO);
        crate::test_harness::pump_every_view(&mut cell.borrow_mut(), Duration::ZERO);
    }

    /// Runs frames of every view until the route transitions have settled.
    fn settle_every_view(app: &mut App) {
        let mut at = Duration::ZERO;
        for _ in 0..20 {
            at += Duration::from_millis(20);
            crate::test_harness::pump_every_view(app, at);
        }
    }

    /// Dart's `find.byType(W, skipOffstage: false)`.
    fn built<W: 'static>() -> Finder {
        find::by_type::<W>().skip_offstage(false)
    }

    /// The intents the shortcuts bind to `key`, in the table's order.
    fn intents_for(shortcuts: &ShortcutMap, key: LogicalKeyboardKey) -> Vec<IntentRef> {
        shortcuts
            .iter()
            .filter(|(activator, _)| {
                activator
                    .triggers()
                    .is_some_and(|triggers| triggers.contains(&key))
            })
            .map(|(_, intent)| Rc::clone(intent))
            .collect()
    }

    #[test]
    fn home_is_shown_by_the_first_route_of_the_navigator_the_app_builds() {
        test_widgets(|tester| {
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Marker)
                    .into_widget(),
            );
            tester.pump_and_settle();
            // The app builds one.
            expect(tester, &built::<Navigator>(), finds_widgets());
            // The home route shows home.
            expect(tester, &built::<Marker>(), finds_widgets());
        });
    }

    /// A second leaf, told apart from [`Marker`].
    #[derive(Debug)]
    struct OtherMarker;

    impl StatelessWidget for OtherMarker {
        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
            SizedBox::new().width(20.0).height(20.0).into_widget()
        }
    }

    // The home route reads `widget.home` when it builds, as Dart's `_onGenerateRoute` does, so
    // a new home shows on the next frame.
    #[test]
    fn pumping_the_app_with_a_new_home_shows_the_new_page() {
        test_widgets(|tester| {
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Marker)
                    .into_widget(),
            );
            tester.pump_and_settle();

            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(OtherMarker)
                    .into_widget(),
            );
            tester.pump_and_settle();
            // The new home shows.
            expect(tester, &built::<OtherMarker>(), finds_widgets());
            // The old home is gone.
            expect(tester, &built::<Marker>(), finds_nothing());
        });
    }

    #[test]
    fn a_routes_table_entry_for_the_default_route_is_the_first_route() {
        test_widgets(|tester| {
            let builder: WidgetBuilder = Rc::new(|_app, _context| Marker.into_widget());
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .routes([(String::from("/"), builder)])
                    .into_widget(),
            );
            tester.pump_and_settle();
            expect(tester, &built::<Marker>(), finds_widgets());
        });
    }

    /// Flutter's assert that a `home` or `routes` app names the page transition it builds with:
    /// checked when the widget is turned into a `WidgetRef`, as Dart's constructor checks it.
    #[test]
    fn a_home_without_a_page_route_builder_panics_at_construction() {
        let panic = std::panic::catch_unwind(|| WidgetsApp::new(COLOR).home(Marker).into_widget())
            .expect_err("a home app needs a page route builder");
        let message = panic
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| panic.downcast_ref::<&str>().copied())
            .unwrap_or_default();
        assert!(
            message.contains("pageRouteBuilder must be specified"),
            "Flutter's message: {message}"
        );
        let panic = std::panic::catch_unwind(|| {
            WidgetsApp::new(COLOR)
                .routes([(
                    String::from("/"),
                    Rc::new(|_app: &mut App, _context: BuildContext| Marker.into_widget())
                        as WidgetBuilder,
                )])
                .into_widget()
        })
        .expect_err("a routes app needs a page route builder");
        let message = panic
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| panic.downcast_ref::<&str>().copied())
            .unwrap_or_default();
        assert!(message.contains("pageRouteBuilder must be specified"));
    }

    #[test]
    fn only_a_builder_needs_no_page_route_builder() {
        test_widgets(|tester| {
            tester.pump_widget(
                WidgetsApp::new(COLOR)
                    .builder(|_app, _context, _child| Marker.into_widget())
                    .into_widget(),
            );
            tester.pump_and_settle();
            expect(tester, &built::<Marker>(), finds_widgets());
        });
    }

    #[test]
    fn a_builder_replaces_the_navigator_and_is_handed_no_child() {
        test_widgets(|tester| {
            let had_child = Rc::new(Cell::new(true));
            let sink = Rc::clone(&had_child);
            tester.pump_widget(
                WidgetsApp::new(COLOR)
                    .builder(move |_app, _context, child| {
                        sink.set(child.is_some());
                        Marker.into_widget()
                    })
                    .into_widget(),
            );
            assert!(!had_child.get(), "no routes, so the builder gets no child");
            expect(tester, &built::<Marker>(), finds_widgets());
            expect(tester, &built::<Navigator>(), finds_nothing());
        });
    }

    #[test]
    fn a_builder_wraps_the_navigator_when_the_app_has_routes() {
        test_widgets(|tester| {
            let had_child = Rc::new(Cell::new(false));
            let sink = Rc::clone(&had_child);
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(SizedBox::shrink())
                    .builder(move |_app, _context, child| {
                        sink.set(child.is_some());
                        child.expect("the navigator").clone()
                    })
                    .into_widget(),
            );
            tester.pump_and_settle();
            assert!(had_child.get());
            expect(tester, &built::<Navigator>(), finds_widgets());
        });
    }

    /// Android's back button and back gesture both arrive here. The app goes back while it
    /// has somewhere to go, and says it did not once it is at the first route, which is how
    /// the host knows to close the activity instead.
    #[test]
    fn a_back_press_pops_the_app_navigator_until_it_is_at_the_first_route() {
        test_widgets(|tester| {
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let sink = Rc::clone(&captured);
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Builder::new(move |_app, context| {
                        sink.set(Some(context));
                        Marker.into_widget()
                    }))
                    .into_widget(),
            );
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            let binding = WidgetsBinding::instance(&mut app);
            assert!(
                !binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
                "at the first route there is nowhere to go back to"
            );

            let context = captured.get().expect("the home built");
            let settings = RouteSettings::new().name("second");
            let route = TestWidgetsApp::default_page_route_builder(
                &mut app,
                &settings,
                Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
            );
            Navigator::of(&mut app, context, false).push(&mut app, route.into_erased());
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();

            assert!(
                binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
                "the pushed route is popped"
            );
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert!(
                !binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID),
                "back at the first route it answers that it did not go back"
            );
        });
    }

    /// Every value the app told `view`'s host of whether it handles back, in order.
    fn framework_handles_backs(view: &TestView) -> Vec<bool> {
        view.test_host().framework_handles_back()
    }

    /// Flutter's app_test.dart, "WidgetsApp calls setFrameworkHandlesBack only when app is
    /// ready".
    #[test]
    fn widgets_app_calls_set_framework_handles_back_only_when_app_is_ready() {
        test_widgets(|tester| {
            // Start in the `resumed` state, where set_framework_handles_back should be called like
            // normal.
            tester.update(|app| {
                SchedulerBinding::handle_app_lifecycle_state_changed(
                    app,
                    AppLifecycleState::Resumed,
                )
            });
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let sink = Rc::clone(&captured);
            tester.pump_widget(
                WidgetsApp::new(COLOR)
                    .builder(move |_app, context, _child| {
                        sink.set(Some(context));
                        Marker.into_widget()
                    })
                    .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let context = captured.get().expect("the builder ran");

            assert!(framework_handles_backs(tester.view()).is_empty());

            NavigationNotification::new(true).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(framework_handles_backs(tester.view()).last(), Some(&true));

            NavigationNotification::new(false).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(framework_handles_backs(tester.view()).last(), Some(&false));

            // Set the app state to inactive, where set_framework_handles_back is still called. This
            // could happen when responding to a tap on a notification when the app is not active and
            // immediately navigating, for example.
            SchedulerBinding::handle_app_lifecycle_state_changed(
                &mut app,
                AppLifecycleState::Inactive,
            );

            let inactive_start_calls_length = framework_handles_backs(tester.view()).len();
            NavigationNotification::new(true).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(
                framework_handles_backs(tester.view()).len(),
                inactive_start_calls_length + 1
            );

            NavigationNotification::new(false).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(
                framework_handles_backs(tester.view()).len(),
                inactive_start_calls_length + 2
            );

            // Set the app state to detached, where set_framework_handles_back shouldn't be called.
            SchedulerBinding::handle_app_lifecycle_state_changed(
                &mut app,
                AppLifecycleState::Detached,
            );

            let final_calls_length = framework_handles_backs(tester.view()).len();
            NavigationNotification::new(true).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(
                framework_handles_backs(tester.view()).len(),
                final_calls_length
            );

            NavigationNotification::new(false).dispatch(&mut app, Some(context));
            drop(app);
            tester.pump_and_settle();
            assert_eq!(
                framework_handles_backs(tester.view()).len(),
                final_calls_length
            );
        });
    }

    /// Flutter's navigator_test.dart, "a single route is already defaulted to false" and
    /// "navigating around a single Navigator with system back", on a `WidgetsApp`.
    #[test]
    fn the_host_hears_whether_the_app_navigator_can_go_back_as_routes_come_and_go() {
        test_widgets(|tester| {
            tester.update(|app| {
                SchedulerBinding::handle_app_lifecycle_state_changed(
                    app,
                    AppLifecycleState::Resumed,
                )
            });
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let sink = Rc::clone(&captured);
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Builder::new(move |_app, context| {
                        sink.set(Some(context));
                        Marker.into_widget()
                    }))
                    .into_widget(),
            );
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(
                framework_handles_backs(tester.view()).last(),
                Some(&false),
                "a single route is already defaulted to false"
            );

            let context = captured.get().expect("the home built");
            let settings = RouteSettings::new().name("/one");
            let route = TestWidgetsApp::default_page_route_builder(
                &mut app,
                &settings,
                Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
            );
            Navigator::of(&mut app, context, false).push(&mut app, route.into_erased());
            drop(app);
            tester.pump_and_settle();
            let mut app = tester.cell.borrow_mut();
            assert_eq!(framework_handles_backs(tester.view()).last(), Some(&true));

            let binding = WidgetsBinding::instance(&mut app);
            assert!(binding.handle_pop_route(&mut app, IMPLICIT_VIEW_ID));
            drop(app);
            tester.pump_and_settle();
            assert_eq!(framework_handles_backs(tester.view()).last(), Some(&false));
        });
    }

    /// Back in one of two views, each with its app, pops that view's navigator alone, and each
    /// view's host hears of its own navigator.
    #[test]
    fn back_in_one_view_pops_that_views_navigator_and_its_host_hears_of_it() {
        let views = [ViewId(0), ViewId(1)]
            .map(|id| Rc::new(TestView::with_pixel_ratio(800.0, 600.0, 2.0).with_id(id)));
        let mut platform = TestPlatform::new().on(TargetPlatform::Android);
        for view in &views {
            platform = platform.with_view(Rc::clone(view) as ViewRef);
        }
        let cell = AppCell::with_platform(Rc::new(platform));
        let mut app = cell.borrow_mut();
        install_fonts(&mut app);
        SchedulerBinding::handle_app_lifecycle_state_changed(&mut app, AppLifecycleState::Resumed);
        let homes: Rc<RefCell<Vec<BuildContext>>> = Rc::default();
        let sink = Rc::clone(&homes);
        drop(app);
        mount_in_every_view(
            &cell,
            TestWidgetsApp::new()
                .color(COLOR)
                .home(Builder::new(move |_app, context| {
                    sink.borrow_mut().push(context);
                    Marker.into_widget()
                }))
                .into_widget(),
        );
        let mut app = cell.borrow_mut();
        settle_every_view(&mut app);
        let home_in = |app: &App, view: ViewId| {
            let homes = homes.borrow();
            *homes
                .iter()
                .find(|home| View::maybe_id_of(app, **home) == Some(view))
                .expect("a home in each view")
        };
        let second = home_in(&app, ViewId(1));
        let settings = RouteSettings::new().name("/one");
        let route = TestWidgetsApp::default_page_route_builder(
            &mut app,
            &settings,
            Rc::new(|_app, _context| SizedBox::shrink().into_widget()),
        );
        Navigator::of(&mut app, second, false).push(&mut app, route.into_erased());
        settle_every_view(&mut app);
        assert_eq!(framework_handles_backs(&views[0]).last(), Some(&false));
        assert_eq!(framework_handles_backs(&views[1]).last(), Some(&true));

        let binding = WidgetsBinding::instance(&mut app);
        assert!(
            !binding.handle_pop_route(&mut app, ViewId(0)),
            "the first view's navigator has nowhere to go back to"
        );
        assert!(binding.handle_pop_route(&mut app, ViewId(1)));
        settle_every_view(&mut app);
        assert_eq!(framework_handles_backs(&views[1]).last(), Some(&false));
    }

    #[test]
    fn the_locale_argument_overrides_the_resolver_and_the_widgets_delegate_is_supplied() {
        test_widgets(|tester| {
            let captured: Rc<Cell<Option<BuildContext>>> = Rc::default();
            let sink = Rc::clone(&captured);
            tester.pump_widget(
                WidgetsApp::new(COLOR)
                    .locale(Locale::new("fr"))
                    .supported_locales([Locale::new("en").country_code("US"), Locale::new("fr")])
                    .builder(move |_app, context, _child| {
                        sink.set(Some(context));
                        Marker.into_widget()
                    })
                    .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let context = captured.get().expect("the builder ran");
            assert_eq!(
                Localizations::locale_of(&mut app, context),
                Locale::new("fr"),
                "the locale argument wins over the platform's locales"
            );
            let localizations = Localizations::of::<dyn WidgetsLocalizations>(&mut app, context)
                .expect("DefaultWidgetsLocalizations");
            assert_eq!(localizations.text_direction(), TextDirection::Ltr);
        });
    }

    #[test]
    fn the_default_shortcuts_bind_tab_to_focus_traversal_on_every_platform() {
        for platform in [
            TargetPlatform::Android,
            TargetPlatform::Fuchsia,
            TargetPlatform::Linux,
            TargetPlatform::Windows,
            TargetPlatform::IOS,
            TargetPlatform::MacOS,
        ] {
            let cell = app_of(platform);
            let app = cell.borrow();
            let shortcuts = WidgetsApp::default_shortcuts(&app);
            let tab = intents_for(&shortcuts, LogicalKeyboardKey::TAB);
            assert_eq!(tab.len(), 2, "{platform:?} binds tab and shift-tab");
            assert!(
                tab[0].as_any().is::<NextFocusIntent>(),
                "{platform:?} binds tab to NextFocusIntent"
            );
            assert!(
                tab[1].as_any().is::<PreviousFocusIntent>(),
                "{platform:?} binds shift-tab to PreviousFocusIntent"
            );
        }
    }

    #[test]
    fn the_apple_default_shortcuts_scroll_with_the_meta_key() {
        let cell = app_of(TargetPlatform::MacOS);
        let app = cell.borrow();
        let shortcuts = WidgetsApp::default_shortcuts(&app);
        let arrow_up = intents_for(&shortcuts, LogicalKeyboardKey::ARROW_UP);
        assert!(arrow_up[0].as_any().is::<DirectionalFocusIntent>());
        assert!(arrow_up[1].as_any().is::<ScrollIntent>());
        let (activator, _) = shortcuts
            .iter()
            .find(|(_, intent)| intent.as_any().is::<ScrollIntent>())
            .expect("a scroll shortcut");
        assert!(
            activator.debug_describe_keys().contains("Meta"),
            "the apple table scrolls with meta, not control"
        );
    }

    #[test]
    fn the_default_actions_request_focus_for_a_request_focus_intent() {
        test_widgets(|tester| {
            tester.pump_widget(
                Focus::new(SizedBox::shrink())
                    .debug_label("target")
                    .into_widget(),
            );
            let mut app = tester.cell.borrow_mut();
            let root_scope = FocusManager::instance(&mut app).root_scope(&app).handle();
            let node: AnyFocusNode = FocusNodeLeaf::as_node(root_scope)
                .descendants(&mut app)
                .into_iter()
                .find(|node| node.debug_label(&app).as_deref() == Some("target"))
                .expect("the focus node");
            let actions = WidgetsApp::default_actions(&mut app);
            let action = actions[&TypeId::of::<RequestFocusIntent>()].handle();
            let kept_node = node.keep(&app);
            action.invoke(&mut app, &RequestFocusIntent::new(kept_node), None);
            app.drain_microtasks();
            assert_eq!(primary_focus(&mut app), Some(node));
        });
    }

    #[test]
    fn the_debug_banner_is_built_unless_it_is_turned_off() {
        test_widgets(|tester| {
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Marker)
                    .into_widget(),
            );
            tester.pump_and_settle();
            // The banner is a debug-mode widget.
            let banner = if cfg!(debug_assertions) {
                finds_widgets()
            } else {
                finds_nothing()
            };
            expect(tester, &built::<CheckedModeBanner>(), banner);
        });
        test_widgets(|tester| {
            tester.pump_widget(
                WidgetsApp::new(COLOR)
                    .page_route_builder(TestWidgetsApp::default_page_route_builder)
                    .home(Marker)
                    .debug_show_checked_mode_banner(false)
                    .into_widget(),
            );
            tester.pump_and_settle();
            expect(tester, &built::<CheckedModeBanner>(), finds_nothing());
        });
    }

    #[test]
    fn a_restoration_scope_id_names_the_root_restoration_scope() {
        test_widgets(|tester| {
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Marker)
                    .restoration_scope_id("app")
                    .into_widget(),
            );
            tester.pump_and_settle();
            let restoration_id = tester.widget(
                built::<RootRestorationScope>().first(),
                |scope: &RootRestorationScope| scope.restoration_id.clone(),
            );
            assert_eq!(restoration_id.as_deref(), Some("app"));
        });
        test_widgets(|tester| {
            tester.pump_widget(
                TestWidgetsApp::new()
                    .color(COLOR)
                    .home(Marker)
                    .into_widget(),
            );
            tester.pump_and_settle();
            let restoration_id = tester.widget(
                built::<RootRestorationScope>().first(),
                |scope: &RootRestorationScope| scope.restoration_id.clone(),
            );
            assert_eq!(restoration_id, None, "restoration stays off");
        });
    }

    #[test]
    fn the_platforms_default_route_name_overrides_the_initial_route() {
        let tester =
            &mut WidgetTester::with_platform(TestPlatform::new().with_default_route("/deep"));
        let deep: WidgetBuilder = Rc::new(|_app, _context| Marker.into_widget());
        tester.pump_widget(
            TestWidgetsApp::new()
                .color(COLOR)
                .initial_route("/ignored")
                .routes([
                    (
                        String::from("/"),
                        Rc::new(|_app: &mut App, _context: BuildContext| {
                            SizedBox::shrink().into_widget()
                        }) as WidgetBuilder,
                    ),
                    (String::from("/deep"), deep),
                ])
                .into_widget(),
        );
        tester.pump_and_settle();
        expect(tester, &built::<Marker>(), finds_widgets());
    }
}