1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
//! Types for storing and interacting with values in Widgets.

use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::fmt::{self, Debug, Display};
use std::future::Future;
use std::hash::{BuildHasher, Hash};
use std::ops::{Add, AddAssign, Deref, DerefMut, Not};
use std::str::FromStr;
use std::sync::{Arc, Weak};
use std::task::{Poll, Waker};
use std::thread::{self, ThreadId};
use std::time::{Duration, Instant};

use ahash::AHashSet;
use alot::{LotId, Lots};
use intentional::Assert;
use kempt::{Map, Sort};
use parking_lot::{Condvar, Mutex, MutexGuard};

use crate::animation::{AnimationHandle, DynamicTransition, IntoAnimate, LinearInterpolate, Spawn};
use crate::context::{self, Trackable, WidgetContext};
use crate::utils::WithClone;
use crate::widget::{
    MakeWidget, MakeWidgetWithTag, OnceCallback, WidgetId, WidgetInstance, WidgetList,
};
use crate::widgets::{Label, Radio, Select, Space, Switcher};
use crate::window::WindowHandle;

/// A source of one or more `T` values.
pub trait Source<T> {
    /// Maps the contents with read-only access, providing access to the value's
    /// [`Generation`].
    fn try_map_generational<R>(
        &self,
        map: impl FnOnce(DynamicGuard<'_, T, true>) -> R,
    ) -> Result<R, DeadlockError>;

    /// Maps the contents with read-only access, providing access to the value's
    /// [`Generation`].
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    fn map_generational<R>(&self, map: impl FnOnce(DynamicGuard<'_, T, true>) -> R) -> R {
        self.try_map_generational(map).expect("deadlocked")
    }

    /// Returns the current generation of the value.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn generation(&self) -> Generation {
        self.map_generational(|g| g.generation())
    }

    /// Maps the contents with read-only access.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    fn map_ref<R>(&self, map: impl FnOnce(&T) -> R) -> R {
        self.map_generational(|gen| map(&*gen))
    }

    /// Returns a clone of the currently contained value.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn get(&self) -> T
    where
        T: Clone,
    {
        self.map_ref(T::clone)
    }

    /// Maps the contents with read-only access.
    fn try_map_ref<R>(&self, map: impl FnOnce(&T) -> R) -> Result<R, DeadlockError> {
        self.try_map_generational(|gen| map(&*gen))
    }

    /// Returns a clone of the currently contained value.
    fn try_get(&self) -> Result<T, DeadlockError>
    where
        T: Clone,
    {
        self.try_map_generational(|gen| gen.clone())
    }

    /// Returns a clone of the currently contained value.
    ///
    /// `context` will be invalidated when the value is updated.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn get_tracking_redraw(&self, context: &WidgetContext<'_>) -> T
    where
        T: Clone,
        Self: Trackable + Sized,
    {
        context.redraw_when_changed(self);
        self.get()
    }

    /// Returns a clone of the currently contained value.
    ///
    /// `context` will be invalidated when the value is updated.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn get_tracking_invalidate(&self, context: &WidgetContext<'_>) -> T
    where
        T: Clone,
        Self: Trackable + Sized,
    {
        context.invalidate_when_changed(self);
        self.get()
    }

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// source's contents are updated.
    ///
    /// `for_each` will not be invoked with the currently stored value.
    ///
    /// Returning `Err(CallbackDisconnected)` will prevent the callback from
    /// being invoked again.
    fn for_each_subsequent_generational_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static;

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// source's contents are updated.
    ///
    /// `for_each` will not be invoked with the currently stored value.
    fn for_each_subsequent_generational<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) + Send + 'static,
    {
        self.for_each_subsequent_generational_try(move |value| {
            for_each(value);
            Ok(())
        })
    }

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// source's contents are updated.
    ///
    /// `for_each` will not be invoked with the currently stored value.
    ///
    /// Returning `Err(CallbackDisconnected)` will prevent the callback from
    /// being invoked again.
    fn for_each_subsequent_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.for_each_subsequent_generational_try(move |gen| for_each(&*gen))
    }

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// source's contents are updated.
    ///
    /// `for_each` will not be invoked with the currently stored value.
    fn for_each_subsequent<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) + Send + 'static,
    {
        self.for_each_subsequent_try(move |value| {
            for_each(value);
            Ok(())
        })
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    ///
    /// Returning `Err(CallbackDisconnected)` will prevent the callback from
    /// being invoked again.
    fn for_each_generational_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static,
    {
        self.map_generational(&mut for_each)
            .expect("initial for_each invocation failed");
        self.for_each_subsequent_generational_try(for_each)
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    fn for_each_generational<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) + Send + 'static,
    {
        self.for_each_generational_try(move |value| {
            for_each(value);
            Ok(())
        })
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    ///
    /// Returning `Err(CallbackDisconnected)` will prevent the callback from
    /// being invoked again.
    fn for_each_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.for_each_generational_try(move |gen| for_each(&*gen))
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    fn for_each<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) + Send + 'static,
    {
        self.for_each_try(move |value| {
            for_each(value);
            Ok(())
        })
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    ///
    /// Returning `Err(CallbackDisconnected)` will prevent the callback from
    /// being invoked again.
    fn for_each_generational_cloned_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(GenerationalValue<T>) -> Result<(), CallbackDisconnected> + Send + 'static;

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    fn for_each_cloned_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(T) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.for_each_generational_cloned_try(move |gen| for_each(gen.value))
    }

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    fn for_each_cloned<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(T) + Send + 'static,
    {
        self.for_each_cloned_try(move |value| {
            for_each(value);
            Ok(())
        })
    }

    /// Returns a new dynamic that contains the updated contents of this dynamic
    /// at most once every `period`.
    #[must_use]
    fn debounced_every(&self, period: Duration) -> Dynamic<T>
    where
        T: PartialEq + Clone + Send + Sync + 'static,
    {
        let debounced = Dynamic::new(self.get());
        let mut debounce = Debounce::new(debounced.clone(), period);
        let callback = self.for_each_cloned(move |value| debounce.update(value));
        debounced.set_source(callback);
        debounced
    }

    /// Returns a new dynamic that contains the updated contents of this dynamic
    /// delayed by `period`. Each time this value is updated, the delay is
    /// reset.
    #[must_use]
    fn debounced_with_delay(&self, period: Duration) -> Dynamic<T>
    where
        T: PartialEq + Clone + Send + Sync + 'static,
    {
        let debounced = Dynamic::new(self.get());
        let mut debounce = Debounce::new(debounced.clone(), period).extending();
        let callback = self.for_each_cloned(move |value| debounce.update(value));
        debounced.set_source(callback);
        debounced
    }

    /// Creates a new dynamic value that contains the result of invoking `map`
    /// each time this value is changed.
    fn map_each_generational<R, F>(&self, mut map: F) -> Dynamic<R>
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'a, T, true>) -> R + Send + 'static,
        R: PartialEq + Send + 'static,
    {
        let mapped = Dynamic::new(self.map_generational(&mut map));
        let mapped_weak = mapped.downgrade();
        mapped.set_source(self.for_each_generational_try(move |value| {
            let mapped = mapped_weak.upgrade().ok_or(CallbackDisconnected)?;
            mapped.set(map(value));
            Ok(())
        }));
        mapped
    }

    /// Creates a new dynamic value that contains the result of invoking `map`
    /// each time this value is changed.
    fn map_each<R, F>(&self, mut map: F) -> Dynamic<R>
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) -> R + Send + 'static,
        R: PartialEq + Send + 'static,
    {
        self.map_each_generational(move |gen| map(&*gen))
    }

    /// Creates a new dynamic value that contains the result of invoking `map`
    /// each time this value is changed.
    fn map_each_cloned<R, F>(&self, mut map: F) -> Dynamic<R>
    where
        T: Clone + Send + 'static,
        F: FnMut(T) -> R + Send + 'static,
        R: PartialEq + Send + 'static,
    {
        let mapped = Dynamic::new(map(self.get()));
        let mapped_weak = mapped.downgrade();
        mapped.set_source(self.for_each_cloned_try(move |value| {
            let mapped = mapped_weak.upgrade().ok_or(CallbackDisconnected)?;
            mapped.set(map(value));
            Ok(())
        }));
        mapped
    }

    /// Returns a new [`Dynamic`] that contains a clone of each value from
    /// `self`.
    ///
    /// The returned dynamic does not hold a strong reference to `self`,
    /// ensuring that `self` can be cleaned up even if the returned dynamic
    /// still exists.
    fn weak_clone(&self) -> Dynamic<T>
    where
        T: Clone + Send + 'static,
    {
        let mapped = Dynamic::new(self.get());
        let mapped_weak = mapped.downgrade();

        mapped.set_source(
            self.for_each_cloned_try(move |value| {
                let mapped = mapped_weak.upgrade().ok_or(CallbackDisconnected)?;
                *mapped.lock() = value.clone();
                Ok(())
            })
            .weak(),
        );
        mapped
    }

    /// Returns a new dynamic that is updated using `U::from(T.clone())` each
    /// time `self` is updated.
    #[must_use]
    fn map_each_into<U>(&self) -> Dynamic<U>
    where
        U: PartialEq + From<T> + Send + 'static,
        T: Clone + Send + 'static,
    {
        self.map_each(|value| U::from(value.clone()))
    }

    /// Returns a new dynamic that is updated using `U::from(&T)` each
    /// time `self` is updated.
    #[must_use]
    fn map_each_to<U>(&self) -> Dynamic<U>
    where
        U: PartialEq + for<'a> From<&'a T> + Send + 'static,
        T: Clone + Send + 'static,
    {
        self.map_each(|value| U::from(value))
    }
}

/// A destination for values of type `T`.
pub trait Destination<T> {
    /// Maps the contents with exclusive access. Before returning from this
    /// function, all observers will be notified that the contents have been
    /// updated.
    fn try_map_mut<R>(&self, map: impl FnOnce(Mutable<'_, T>) -> R) -> Result<R, DeadlockError>;

    /// Maps the contents with exclusive access. Before returning from this
    /// function, all observers will be notified that the contents have been
    /// updated.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    fn map_mut<R>(&self, map: impl FnOnce(Mutable<'_, T>) -> R) -> R {
        self.try_map_mut(map).expect("deadlocked")
    }

    /// Replaces the contents with `new_value` if `new_value` is different than
    /// the currently stored value. If the value is updated, the previous
    /// contents are returned.
    ///
    ///
    /// Before returning from this function, all observers will be notified that
    /// the contents have been updated.
    ///
    /// # Errors
    ///
    /// - [`ReplaceError::NoChange`]: Returned when `new_value` is equal to the
    /// currently stored value.
    /// - [`ReplaceError::Deadlock`]: Returned when the current thread already
    ///       has exclusive access to the contents of this dynamic.
    fn try_replace(&self, new_value: T) -> Result<T, ReplaceError<T>>
    where
        T: PartialEq,
    {
        match self.try_map_mut(|mut value| {
            if *value == new_value {
                Err(ReplaceError::NoChange(new_value))
            } else {
                Ok(std::mem::replace(&mut *value, new_value))
            }
        }) {
            Ok(old) => old,
            Err(DeadlockError) => Err(ReplaceError::Deadlock),
        }
    }

    /// Replaces the contents with `new_value`, returning the previous contents.
    /// Before returning from this function, all observers will be notified that
    /// the contents have been updated.
    ///
    /// If the calling thread has exclusive access to the contents of this
    /// dynamic, this call will return None and the value will not be updated.
    /// If detecting this is important, use [`Self::try_replace()`].
    fn replace(&self, new_value: T) -> Option<T>
    where
        T: PartialEq,
    {
        self.try_replace(new_value).ok()
    }

    /// Stores `new_value` in this dynamic. Before returning from this function,
    /// all observers will be notified that the contents have been updated.
    ///
    /// If the calling thread has exclusive access to the contents of this
    /// dynamic, this call will return None and the value will not be updated.
    /// If detecting this is important, use [`Self::try_replace()`].
    fn set(&self, new_value: T)
    where
        T: PartialEq,
    {
        let _old = self.replace(new_value);
    }

    /// Replaces the current value with `new_value` if the current value is
    /// equal to `expected_current`.
    ///
    /// Returns `Ok` with the overwritten value upon success.
    ///
    /// # Errors
    ///
    /// - [`TryCompareSwapError::Deadlock`]: This operation would result in a
    ///       thread deadlock.
    /// - [`TryCompareSwapError::CurrentValueMismatch`]: The current value did
    ///       not match `expected_current`. The `T` returned is a clone of the
    ///       currently stored value.
    fn try_compare_swap(
        &self,
        expected_current: &T,
        new_value: T,
    ) -> Result<T, TryCompareSwapError<T>>
    where
        T: Clone + PartialEq,
    {
        match self.try_map_mut(|mut value| {
            if &*value == expected_current {
                Ok(std::mem::replace(&mut *value, new_value))
            } else {
                Err(TryCompareSwapError::CurrentValueMismatch(value.clone()))
            }
        }) {
            Ok(old) => old,
            Err(_) => Err(TryCompareSwapError::Deadlock),
        }
    }

    /// Replaces the current value with `new_value` if the current value is
    /// equal to `expected_current`.
    ///
    /// Returns `Ok` with the overwritten value upon success.
    ///
    /// # Errors
    ///
    /// Returns `Err` with the currently stored value when `expected_current`
    /// does not match the currently stored value.
    fn compare_swap(&self, expected_current: &T, new_value: T) -> Result<T, T>
    where
        T: Clone + PartialEq,
    {
        match self.try_compare_swap(expected_current, new_value) {
            Ok(old) => Ok(old),
            Err(TryCompareSwapError::Deadlock) => unreachable!("deadlocked"),
            Err(TryCompareSwapError::CurrentValueMismatch(value)) => Err(value),
        }
    }

    /// Updates the value to the result of invoking [`Not`] on the current
    /// value. This function returns the new value.
    #[allow(clippy::must_use_candidate)]
    fn toggle(&self) -> T
    where
        T: Not<Output = T> + Clone,
    {
        self.map_mut(|mut value| {
            *value = !value.clone();
            value.clone()
        })
    }

    /// Returns the currently stored value, replacing the current contents with
    /// `T::default()`.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn take(&self) -> T
    where
        Self: Source<T>,
        T: Default,
    {
        self.map_mut(|mut value| std::mem::take(&mut *value))
    }

    /// Checks if the currently stored value is different than `T::default()`,
    /// and if so, returns `Some(self.take())`.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    fn take_if_not_default(&self) -> Option<T>
    where
        T: Default + PartialEq,
    {
        let default = T::default();
        self.map_mut(|mut value| {
            if *value == default {
                None
            } else {
                Some(std::mem::replace(&mut *value, default))
            }
        })
    }
}

impl<T> Source<T> for Arc<DynamicData<T>> {
    fn try_map_generational<R>(
        &self,
        map: impl FnOnce(DynamicGuard<'_, T, true>) -> R,
    ) -> Result<R, DeadlockError> {
        let state = self.state()?;
        Ok(map(DynamicGuard {
            guard: DynamicOrOwnedGuard::Dynamic(state),
            accessed_mut: false,
            prevent_notifications: false,
        }))
    }

    fn for_each_subsequent_generational_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'a, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static,
    {
        let this = WeakDynamic(Arc::downgrade(self));
        dynamic_for_each(self, move || {
            let this = this.upgrade().ok_or(CallbackDisconnected)?;
            this.map_generational(&mut for_each)?;
            Ok(())
        })
    }

    fn for_each_generational_cloned_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(GenerationalValue<T>) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        let this = WeakDynamic(Arc::downgrade(self));
        dynamic_for_each(self, move || {
            let this = this.upgrade().ok_or(CallbackDisconnected)?;

            if let Ok(value) = this.try_map_generational(|g| g.guard.clone()) {
                for_each(value)?;
            }

            Ok(())
        })
    }
}

impl<T> Source<T> for Dynamic<T> {
    fn try_map_generational<R>(
        &self,
        map: impl FnOnce(DynamicGuard<'_, T, true>) -> R,
    ) -> Result<R, DeadlockError> {
        self.0.try_map_generational(map)
    }

    fn for_each_subsequent_generational_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static,
    {
        self.0.for_each_subsequent_generational_try(for_each)
    }

    fn for_each_generational_cloned_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(GenerationalValue<T>) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.0.for_each_generational_cloned_try(for_each)
    }
}

impl<T> Source<T> for DynamicReader<T> {
    fn try_map_generational<R>(
        &self,
        map: impl FnOnce(DynamicGuard<'_, T, true>) -> R,
    ) -> Result<R, DeadlockError> {
        self.source.try_map_generational(|generational| {
            *self.read_generation.lock() = generational.generation();
            map(generational)
        })
    }

    fn for_each_subsequent_generational_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static,
    {
        self.source.for_each_subsequent_generational_try(for_each)
    }

    fn for_each_generational_cloned_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(GenerationalValue<T>) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.source.for_each_generational_cloned_try(for_each)
    }
}

impl<T> Destination<T> for Dynamic<T> {
    fn try_map_mut<R>(&self, map: impl FnOnce(Mutable<'_, T>) -> R) -> Result<R, DeadlockError> {
        self.0.map_mut(map)
    }
}

/// A `mut` reference to `T` that tracks whether the contents have been accessed
/// through `DerefMut`.
#[derive(Debug)]
pub struct Mutable<'a, T> {
    value: &'a mut T,
    mutated: Mutated<'a>,
}

#[derive(Debug)]
enum Mutated<'a> {
    External(&'a mut bool),
    Ignored,
}

impl Mutated<'_> {
    fn set(&mut self, mutated: bool) {
        match self {
            Self::External(value) => **value = mutated,
            Self::Ignored => {}
        }
    }
}

impl<T> Deref for Mutable<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.value
    }
}

impl<T> DerefMut for Mutable<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.mutated.set(true);
        self.value
    }
}

impl<'a, T> Mutable<'a, T> {
    /// Creates a new wrapper that sets `mutated` to true when `DerefMut` is
    /// used to access `value`.
    #[must_use]
    pub fn new(value: &'a mut T, mutated: &'a mut bool) -> Self {
        *mutated = false;
        Self {
            value,
            mutated: Mutated::External(mutated),
        }
    }
}

impl<'a, T> From<&'a mut T> for Mutable<'a, T> {
    fn from(value: &'a mut T) -> Self {
        Self {
            value,
            mutated: Mutated::Ignored,
        }
    }
}

/// A unique, reactive value.
///
/// This type is useful for situations where a value is owned by exactly one
/// type but needs to have reactivity through [`Source`]/[`Destination`].
///
/// A [`Dynamic`] utilizes a [`Arc`] + [`Mutex`] to support updating its values
/// from multiple threads. This type utilizes a [`RefCell`], preventing it from
/// being shared between multiple threads.
#[derive(Default)]
pub struct Owned<T> {
    wrapped: RefCell<GenerationalValue<T>>,
    callbacks: Arc<OwnedCallbacks<T>>,
}

impl<T> Owned<T> {
    /// Returns a new reactive value.
    pub fn new(value: T) -> Self {
        Self {
            wrapped: RefCell::new(GenerationalValue {
                value,
                generation: Generation::default(),
            }),
            callbacks: Arc::default(),
        }
    }

    /// Borrows the contents of this value with read-only access.
    pub fn borrow(&self) -> OwnedRef<'_, T> {
        OwnedRef(self.wrapped.borrow())
    }

    /// Borrows the contents of this value with exclusive access.
    ///
    /// When the returned type is accessed through [`DerefMut`], all associated
    /// reactive callbacks will be invoked upon dropping the returned
    /// [`OwnedMut`].
    pub fn borrow_mut(&mut self) -> OwnedMut<'_, T> {
        OwnedMut {
            borrowed: self.wrapped.borrow_mut(),
            accessed_mut: false,
            owned: self,
        }
    }

    /// Returns the contained value.
    pub fn into_inner(self) -> T {
        self.wrapped.into_inner().value
    }
}

impl<T> Source<T> for Owned<T> {
    fn try_map_generational<R>(
        &self,
        map: impl FnOnce(DynamicGuard<'_, T, true>) -> R,
    ) -> Result<R, DeadlockError> {
        Ok(map(DynamicGuard {
            guard: DynamicOrOwnedGuard::Owned(self.wrapped.borrow_mut()),
            accessed_mut: false,
            prevent_notifications: false,
        }))
    }

    fn for_each_subsequent_generational_try<F>(&self, for_each: F) -> CallbackHandle
    where
        T: Send + 'static,
        F: for<'a> FnMut(DynamicGuard<'a, T, true>) -> Result<(), CallbackDisconnected>
            + Send
            + 'static,
    {
        let mut callbacks = self.callbacks.active.lock();
        CallbackHandle(CallbackHandleInner::Single(CallbackHandleData {
            id: Some(callbacks.push(Box::new(for_each))),
            owner: None,
            callbacks: self.callbacks.clone(),
        }))
    }

    fn for_each_generational_cloned_try<F>(&self, mut for_each: F) -> CallbackHandle
    where
        T: Clone + Send + 'static,
        F: FnMut(GenerationalValue<T>) -> Result<(), CallbackDisconnected> + Send + 'static,
    {
        self.for_each_generational_try(move |gen| for_each(gen.guard.clone()))
    }
}

impl<T> Destination<T> for Owned<T>
where
    T: 'static,
{
    fn try_map_mut<R>(&self, map: impl FnOnce(Mutable<'_, T>) -> R) -> Result<R, DeadlockError> {
        let mut updated = false;
        let result = map(Mutable::new(
            &mut self.wrapped.borrow_mut().value,
            &mut updated,
        ));
        if updated {
            self.callbacks.invoke(&mut &self.wrapped, |wrapped| {
                DynamicOrOwnedGuard::Owned(wrapped.borrow_mut())
            });
        }
        Ok(result)
    }
}

/// A read-only reference to the value in an [`Owned`].
pub struct OwnedRef<'a, T>(Ref<'a, GenerationalValue<T>>)
where
    T: 'static;

impl<T> Deref for OwnedRef<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// An exclusive reference to the value contained in an [`Owned`].
///
/// This type tracks if the referenced value is accessed through [`DerefMut`].
/// If it is, reactive callbacks associated with the [`Owned`] value will be
/// invoked.
pub struct OwnedMut<'a, T>
where
    T: 'static,
{
    owned: &'a Owned<T>,
    borrowed: RefMut<'a, GenerationalValue<T>>,
    accessed_mut: bool,
}

impl<T> Deref for OwnedMut<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.borrowed.value
    }
}

impl<T> DerefMut for OwnedMut<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.accessed_mut = true;
        &mut self.borrowed.value
    }
}

impl<T> Drop for OwnedMut<'_, T>
where
    T: 'static,
{
    fn drop(&mut self) {
        if self.accessed_mut {
            self.owned.callbacks.invoke(&mut self.borrowed, |borrowed| {
                DynamicOrOwnedGuard::OwnedRef(&mut *borrowed)
            });
        }
    }
}

struct OwnedCallbacks<T> {
    active: Mutex<Lots<Box<dyn OwnedCallbackFn<T>>>>,
}

impl<T> Default for OwnedCallbacks<T> {
    fn default() -> Self {
        Self {
            active: Mutex::default(),
        }
    }
}

impl<T> OwnedCallbacks<T>
where
    T: 'static,
{
    pub fn invoke<'a, U>(
        &self,
        user: &'a mut U,
        value: impl for<'b> Fn(&'b mut U) -> DynamicOrOwnedGuard<'b, T>,
    ) {
        let mut callbacks = self.active.lock();
        callbacks.drain_filter(|callback| {
            callback
                .updated(DynamicGuard {
                    guard: value(user),
                    accessed_mut: false,
                    prevent_notifications: false,
                })
                .is_err()
        });
    }
}

impl<T> CallbackCollection for OwnedCallbacks<T>
where
    T: 'static,
{
    fn remove(&self, id: LotId) {
        self.active.lock().remove(id);
    }
}

trait OwnedCallbackFn<T>: Send + 'static {
    fn updated(&mut self, value: DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected>;
}

impl<F, T> OwnedCallbackFn<T> for F
where
    F: for<'a> FnMut(DynamicGuard<'a, T, true>) -> Result<(), CallbackDisconnected>
        + Send
        + 'static,
{
    fn updated(&mut self, value: DynamicGuard<'_, T, true>) -> Result<(), CallbackDisconnected> {
        self(value)
    }
}

/// An instance of a value that provides APIs to observe and react to its
/// contents.
pub struct Dynamic<T>(Arc<DynamicData<T>>);

impl<T> Dynamic<T> {
    /// Creates a new instance wrapping `value`.
    pub fn new(value: T) -> Self {
        Self(Arc::new(DynamicData {
            state: Mutex::new(State::new(value)),
            during_callback_state: Mutex::default(),
            sync: Condvar::default(),
        }))
    }

    pub(crate) fn as_ptr(&self) -> *const () {
        Arc::as_ptr(&self.0).cast()
    }

    /// Returns a weak reference to this dynamic.
    ///
    /// This is powered by [`Arc`]/[`Weak`] and follows the same semantics for
    /// reference counting.
    #[must_use]
    pub fn downgrade(&self) -> WeakDynamic<T> {
        WeakDynamic::from(self)
    }

    /// Returns the number [`Dynamic`]s that point to this same value.
    ///
    /// The returned count includes `self`.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn instances(&self) -> usize {
        Arc::strong_count(&self.0) - self.readers()
    }

    /// Returns the number of [`DynamicReader`]s for this value.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn readers(&self) -> usize {
        self.state().expect("deadlocked").readers
    }

    /// Returns a new dynamic that has its contents linked with `self` by the
    /// pair of mapping functions provided.
    ///
    /// When the returned dynamic is updated, `r_into_t` will be invoked. This
    /// function accepts `&R` and can return `T`, or `Option<T>`. If a value is
    /// produced, `self` will be updated with the new value.
    ///
    /// When `self` is updated, `t_into_r` will be invoked. This function
    /// accepts `&T` and can return `R` or `Option<R>`. If a value is produced,
    /// the returned dynamic will be updated with the new value.
    ///
    /// # Panics
    ///
    /// This function panics if calling `t_into_r` with the current contents of
    /// the Dynamic produces a `None` value. This requirement is only for the
    /// first invocation, and it is guaranteed to occur before this function
    /// returns.
    pub fn linked<R, TIntoR, TIntoRResult, RIntoT, RIntoTResult>(
        &self,
        mut t_into_r: TIntoR,
        mut r_into_t: RIntoT,
    ) -> Dynamic<R>
    where
        T: PartialEq + Send + 'static,
        R: PartialEq + Send + 'static,
        TIntoRResult: Into<Option<R>> + Send + 'static,
        RIntoTResult: Into<Option<T>> + Send + 'static,
        TIntoR: FnMut(&T) -> TIntoRResult + Send + 'static,
        RIntoT: FnMut(&R) -> RIntoTResult + Send + 'static,
    {
        let r = Dynamic::new(
            self.map_ref(|v| t_into_r(v))
                .into()
                .expect("t_into_r must succeed with the current value"),
        );
        let r_weak = r.downgrade();
        r.set_source(self.for_each_try(move |t| {
            let r = r_weak.upgrade().ok_or(CallbackDisconnected)?;
            if let Some(update) = t_into_r(t).into() {
                r.set(update);
            }
            Ok(())
        }));

        // The linked dynamic holds a reference to the original, since it's
        // being created from the original.
        let t = self.clone();
        self.set_source(r.for_each_try(move |r| {
            if let Some(update) = r_into_t(r).into() {
                let _result = t.replace(update);
            }
            Ok(())
        }));

        r
    }

    /// Creates a [linked](Self::linked) dynamic containing a `String`.
    ///
    /// When `self` is updated, [`ToString::to_string()`] will be called to
    /// produce a new string value to store in the returned dynamic.
    ///
    /// When the returned dynamic is updated, [`str::parse`](std::str) is called
    /// to produce a new `T`. If an error is returned, `self` will not be
    /// updated. Otherwise, `self` will be updated with the produced value.
    #[must_use]
    pub fn linked_string(&self) -> Dynamic<String>
    where
        T: ToString + FromStr + PartialEq + Send + 'static,
    {
        self.linked(ToString::to_string, |s: &String| s.parse().ok())
    }

    /// Sets the current `source` for this dynamic with `source`.
    ///
    /// A dynamic can have multiple source callbacks.
    ///
    /// This ensures that `source` stays active as long as any clones of `self`
    /// are alive.
    pub fn set_source(&self, source: CallbackHandle) {
        self.state().assert("deadlocked").source_callback += source;
    }

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// value's contents are updated. This function returns `self`.
    #[must_use]
    pub fn with_for_each<F>(self, for_each: F) -> Self
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) + Send + 'static,
    {
        self.for_each(for_each).persist();
        self
    }

    /// A helper function that invokes `with_clone` with a clone of self. This
    /// code may produce slightly more readable code.
    ///
    /// ```rust
    /// use cushy::value::{Dynamic, Source};
    ///
    /// let value = Dynamic::new(1);
    ///
    /// // Using with_clone
    /// value.with_clone(|value| {
    ///     std::thread::spawn(move || {
    ///         println!("{}", value.get());
    ///     })
    /// });
    ///
    /// // Using an explicit clone
    /// std::thread::spawn({
    ///     let value = value.clone();
    ///     move || {
    ///         println!("{}", value.get());
    ///     }
    /// });
    ///
    /// println!("{}", value.get());
    /// ````
    pub fn with_clone<R>(&self, with_clone: impl FnOnce(Self) -> R) -> R {
        with_clone(self.clone())
    }

    /// Returns a new reference-based reader for this dynamic value.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn create_reader(&self) -> DynamicReader<T> {
        self.state().expect("deadlocked").readers += 1;
        DynamicReader {
            source: self.0.clone(),
            read_generation: Mutex::new(self.0.state().expect("deadlocked").wrapped.generation),
        }
    }

    /// Converts this [`Dynamic`] into a reader.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn into_reader(self) -> DynamicReader<T> {
        self.create_reader()
    }

    /// Returns an exclusive reference to the contents of this dynamic.
    ///
    /// This call will block until all other guards for this dynamic have been
    /// dropped.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn lock(&self) -> DynamicGuard<'_, T> {
        self.lock_inner()
    }

    /// Returns an exclusive reference to the contents of this dynamic.
    ///
    /// This call will block until all other guards for this dynamic have been
    /// dropped.
    ///
    /// # Errors
    ///
    /// Returns an error if the current thread already holds a lock to this
    /// dynamic.
    pub fn try_lock(&self) -> Result<DynamicGuard<'_, T>, DeadlockError> {
        Ok(DynamicGuard {
            guard: DynamicOrOwnedGuard::Dynamic(self.0.state()?),
            accessed_mut: false,
            prevent_notifications: false,
        })
    }

    fn lock_inner<const READONLY: bool>(&self) -> DynamicGuard<'_, T, READONLY> {
        DynamicGuard {
            guard: DynamicOrOwnedGuard::Dynamic(self.0.state().expect("deadlocked")),
            accessed_mut: false,
            prevent_notifications: false,
        }
    }

    fn state(&self) -> Result<DynamicMutexGuard<'_, T>, DeadlockError> {
        self.0.state()
    }

    /// Returns a pending transition for this value to `new_value`.
    pub fn transition_to(&self, new_value: T) -> DynamicTransition<T>
    where
        T: LinearInterpolate + Clone + Send + Sync,
    {
        DynamicTransition {
            dynamic: self.clone(),
            new_value,
        }
    }

    /// Returns a new [`Radio`] that updates this dynamic to `widget_value` when
    /// pressed. `label` is drawn next to the checkbox and is also clickable to
    /// select the radio.
    #[must_use]
    pub fn new_radio(&self, widget_value: T, label: impl MakeWidget) -> Radio<T>
    where
        Self: Clone,
        // Technically this trait bound isn't necessary, but it prevents trying
        // to call new_radio on unsupported types. The MakeWidget/Widget
        // implementations require these bounds (and more).
        T: Clone + PartialEq,
    {
        Radio::new(widget_value, self.clone(), label)
    }

    /// Returns a new [`Select`] that updates this dynamic to `widget_value`
    /// when pressed. `label` is drawn next to the checkbox and is also
    /// clickable to select the widget.
    #[must_use]
    pub fn new_select(&self, widget_value: T, label: impl MakeWidget) -> Select<T>
    where
        Self: Clone,
        // Technically this trait bound isn't necessary, but it prevents trying
        // to call new_select on unsupported types. The MakeWidget/Widget
        // implementations require these bounds (and more).
        T: Clone + PartialEq,
    {
        Select::new(widget_value, self.clone(), label)
    }

    /// Validates the contents of this dynamic using the `check` function,
    /// returning a dynamic that contains the validation status.
    #[must_use]
    pub fn validate_with<E, Valid>(&self, mut check: Valid) -> Dynamic<Validation>
    where
        T: Send + 'static,
        Valid: for<'a> FnMut(&'a T) -> Result<(), E> + Send + 'static,
        E: Display,
    {
        let validation = Dynamic::new(Validation::None);
        let callback = self.for_each({
            let validation = validation.clone();
            move |value| {
                validation.set(match check(value) {
                    Ok(()) => Validation::Valid,
                    Err(err) => Validation::Invalid(err.to_string()),
                });
            }
        });
        validation.set_source(callback);
        validation
    }
}

/// An error returned from [`Dynamic::try_compare_swap`].
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum TryCompareSwapError<T> {
    /// The dynamic is already locked for exclusive access by the current
    /// thread. This operation would result in a deadlock.
    Deadlock,
    /// The current value did not match the expected value. This variant's value
    /// is the value at the time of comparison.
    CurrentValueMismatch(T),
}

impl<T> Debug for Dynamic<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&DebugDynamicData(&self.0), f)
    }
}

impl Dynamic<WidgetInstance> {
    /// Returns a new [`Switcher`] widget whose contents is the value of this
    /// dynamic.
    #[must_use]
    pub fn into_switcher(self) -> Switcher {
        self.into_reader().into_switcher()
    }

    /// Returns a new [`Switcher`] widget whose contents is the value of this
    /// dynamic.
    #[must_use]
    pub fn to_switcher(&self) -> Switcher {
        self.create_reader().into_switcher()
    }
}

impl DynamicReader<WidgetInstance> {
    /// Returns a new [`Switcher`] widget whose contents is the value of this
    /// dynamic reader.
    #[must_use]
    pub fn into_switcher(self) -> Switcher {
        Switcher::new(self)
    }

    /// Returns a new [`Switcher`] widget whose contents is the value of this
    /// dynamic reader.
    #[must_use]
    pub fn to_switcher(&self) -> Switcher {
        Switcher::new(self.clone())
    }
}

impl MakeWidgetWithTag for Dynamic<WidgetInstance> {
    fn make_with_tag(self, id: crate::widget::WidgetTag) -> WidgetInstance {
        self.into_switcher().make_with_tag(id)
    }
}

impl MakeWidgetWithTag for Dynamic<Option<WidgetInstance>> {
    fn make_with_tag(self, id: crate::widget::WidgetTag) -> WidgetInstance {
        self.map_each(|widget| {
            widget
                .as_ref()
                .map_or_else(|| Space::clear().make_widget(), Clone::clone)
        })
        .make_with_tag(id)
    }
}

impl<T> context::sealed::Trackable for Dynamic<T> {
    fn inner_redraw_when_changed(&self, handle: WindowHandle) {
        self.0.redraw_when_changed(handle);
    }

    fn inner_invalidate_when_changed(&self, handle: WindowHandle, id: WidgetId) {
        self.0.invalidate_when_changed(handle, id);
    }
}

impl<T> Eq for Dynamic<T> {}

impl<T> PartialEq for Dynamic<T> {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.0, &other.0)
    }
}

impl<T> Default for Dynamic<T>
where
    T: Default,
{
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T> Clone for Dynamic<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T> Drop for Dynamic<T> {
    fn drop(&mut self) {
        // Ignoring deadlocks here allows complex flows to work properly, and
        // the only issue is that `on_disconnect` will not fire if during a map
        // callback on a `DynamicReader` the final reference to the source
        // `Dynamic`.
        if let Ok(mut state) = self.state() {
            if Arc::strong_count(&self.0) == state.readers + 1 {
                let cleanup = state.cleanup();
                drop(state);
                drop(cleanup);

                self.0.sync.notify_all();
            }
        } else {
            // In the event that this is the rare edge case and a reader is
            // blocking, we want to signal that we've dropped the final
            // reference.
            self.0.sync.notify_all();
        }
    }
}

impl<T> From<Dynamic<T>> for DynamicReader<T> {
    fn from(value: Dynamic<T>) -> Self {
        value.create_reader()
    }
}

impl From<&str> for Dynamic<String> {
    fn from(value: &str) -> Self {
        Dynamic::from(value.to_string())
    }
}

impl From<String> for Dynamic<String> {
    fn from(value: String) -> Self {
        Dynamic::new(value)
    }
}

struct DynamicMutexGuard<'a, T> {
    dynamic: &'a DynamicData<T>,
    guard: MutexGuard<'a, State<T>>,
}

impl<T> Debug for DynamicMutexGuard<'_, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.guard.debug("DynamicMutexGuard", f)
    }
}

impl<'a, T> DynamicMutexGuard<'a, T> {
    fn unlocked(&mut self, while_unlocked: impl FnOnce()) {
        let previous_state = self.dynamic.during_callback_state.lock().take();
        MutexGuard::unlocked(&mut self.guard, while_unlocked);

        *self.dynamic.during_callback_state.lock() = previous_state;
    }
}

impl<'a, T> Drop for DynamicMutexGuard<'a, T> {
    fn drop(&mut self) {
        let mut during_state = self.dynamic.during_callback_state.lock();
        *during_state = None;
        drop(during_state);
        self.dynamic.sync.notify_all();
    }
}

impl<'a, T> Deref for DynamicMutexGuard<'a, T> {
    type Target = State<T>;

    fn deref(&self) -> &Self::Target {
        &self.guard
    }
}
impl<'a, T> DerefMut for DynamicMutexGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.guard
    }
}

#[derive(Debug)]
struct LockState {
    locked_thread: ThreadId,
}

struct DynamicData<T> {
    state: Mutex<State<T>>,
    during_callback_state: Mutex<Option<LockState>>,
    sync: Condvar,
}

impl<T> DynamicData<T> {
    fn state(&self) -> Result<DynamicMutexGuard<'_, T>, DeadlockError> {
        let mut during_sync = self.during_callback_state.lock();

        let current_thread_id = std::thread::current().id();
        let guard = loop {
            match self.state.try_lock() {
                Some(g) => break g,
                None => loop {
                    match &*during_sync {
                        Some(state) if state.locked_thread == current_thread_id => {
                            return Err(DeadlockError)
                        }
                        Some(_) => {
                            self.sync.wait(&mut during_sync);
                        }
                        None => break,
                    }
                },
            }
        };
        *during_sync = Some(LockState {
            locked_thread: current_thread_id,
        });
        Ok(DynamicMutexGuard {
            dynamic: self,
            guard,
        })
    }

    pub fn redraw_when_changed(&self, window: WindowHandle) {
        let mut state = self.state().expect("deadlocked");
        state.invalidation.windows.insert(window);
    }

    pub fn invalidate_when_changed(&self, window: WindowHandle, widget: WidgetId) {
        let mut state = self.state().expect("deadlocked");
        state.invalidation.widgets.insert((window, widget));
    }

    pub fn map_mut<R>(&self, map: impl FnOnce(Mutable<T>) -> R) -> Result<R, DeadlockError> {
        let mut state = self.state()?;
        let (old, callbacks) = {
            let state = &mut *state;
            let mut changed = false;
            let result = map(Mutable::new(&mut state.wrapped.value, &mut changed));
            let callbacks = changed.then(|| state.note_changed());

            (result, callbacks)
        };
        drop(state);
        drop(callbacks);

        self.sync.notify_all();

        Ok(old)
    }
}

fn dynamic_for_each<T, F>(this: &Arc<DynamicData<T>>, map: F) -> CallbackHandle
where
    F: for<'a> FnMut() -> Result<(), CallbackDisconnected> + Send + 'static,
    T: Send + 'static,
{
    let state = this.state().expect("deadlocked");
    let mut data = state.callbacks.callbacks.lock();
    CallbackHandle(CallbackHandleInner::Single(CallbackHandleData {
        id: Some(data.callbacks.push(Box::new(map))),
        owner: Some(this.clone()),
        callbacks: state.callbacks.clone(),
    }))
}

/// A callback function is no longer connected to its source.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct CallbackDisconnected;

struct DebugDynamicData<'a, T>(&'a Arc<DynamicData<T>>);

impl<T> Debug for DebugDynamicData<'_, T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0.state() {
            Ok(state) => state.debug("Dynamic", f),
            Err(_) => f.debug_tuple("Dynamic").field(&"<unable to lock>").finish(),
        }
    }
}

/// An error occurred while updating a value in a [`Dynamic`].
pub enum ReplaceError<T> {
    /// The value was already equal to the one set.
    NoChange(T),
    /// The current thread already has exclusive access to this dynamic.
    Deadlock,
}

/// A deadlock occurred accessing a [`Dynamic`].
///
/// Currently Cushy is only able to detect deadlocks where a single thread tries
/// to lock the same [`Dynamic`] multiple times.
#[derive(Debug)]
pub struct DeadlockError;

impl std::error::Error for DeadlockError {}

impl Display for DeadlockError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("a deadlock was detected")
    }
}

trait CallbackCollection: Send + Sync + 'static {
    fn remove(&self, id: LotId);
}

/// A handle to a callback installed on a [`Dynamic`]. When dropped, the
/// callback will be uninstalled.
///
/// To prevent the callback from ever being uninstalled, use
/// [`Self::persist()`].
#[must_use = "Callbacks are disconnected once the associated CallbackHandle is dropped. Consider using `CallbackHandle::persist()` to prevent the callback from being disconnected."]
pub struct CallbackHandle(CallbackHandleInner);

impl Default for CallbackHandle {
    fn default() -> Self {
        Self(CallbackHandleInner::None)
    }
}

enum CallbackHandleInner {
    None,
    Single(CallbackHandleData),
    Multi(Vec<CallbackHandleData>),
}

trait ReferencedDynamic: Sync + Send + 'static {}
impl<T> ReferencedDynamic for T where T: Sync + Send + 'static {}

struct CallbackHandleData {
    id: Option<LotId>,
    owner: Option<Arc<dyn ReferencedDynamic>>,
    callbacks: Arc<dyn CallbackCollection>,
}

impl Debug for CallbackHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut tuple = f.debug_tuple("CallbackHandle");
        match &self.0 {
            CallbackHandleInner::None => {}
            CallbackHandleInner::Single(handle) => {
                tuple.field(&handle.id);
            }
            CallbackHandleInner::Multi(handles) => {
                for handle in handles {
                    tuple.field(&handle.id);
                }
            }
        }

        tuple.finish()
    }
}

impl CallbackHandle {
    /// Persists the callback so that it will always be invoked until the
    /// dynamic is freed.
    pub fn persist(self) {
        match self.0 {
            CallbackHandleInner::None => {}
            CallbackHandleInner::Single(mut handle) => {
                let _id = handle.id.take();
                drop(handle);
            }
            CallbackHandleInner::Multi(handles) => {
                for handle in handles {
                    handle.persist();
                }
            }
        }
    }

    /// Drops any references to owning [`Dynamic`]s associated with this
    /// callback.
    ///
    /// This enables creating weak connections between callback graphs.
    pub fn forget_owners(&mut self) {
        match &mut self.0 {
            CallbackHandleInner::None => {}
            CallbackHandleInner::Single(handle) => {
                handle.owner = None;
            }
            CallbackHandleInner::Multi(handles) => {
                for handle in handles {
                    handle.owner = None;
                }
            }
        }
    }

    /// Drops any references to owning [`Dynamic`]s associated with this
    /// callback, and returns self.
    ///
    /// This uses [`Self::forget_owners()`].
    pub fn weak(mut self) -> Self {
        self.forget_owners();
        self
    }
}

impl Eq for CallbackHandle {}

impl PartialEq for CallbackHandle {
    fn eq(&self, other: &Self) -> bool {
        match (&self.0, &other.0) {
            (CallbackHandleInner::None, CallbackHandleInner::None) => true,
            (CallbackHandleInner::Single(this), CallbackHandleInner::Single(other)) => {
                this == other
            }
            (CallbackHandleInner::Multi(this), CallbackHandleInner::Multi(other)) => this == other,
            _ => false,
        }
    }
}

impl CallbackHandleData {
    fn persist(mut self) {
        let _id = self.id.take();
        drop(self);
    }
}

impl Drop for CallbackHandleData {
    fn drop(&mut self) {
        if let Some(id) = self.id {
            self.callbacks.remove(id);
        }
    }
}

impl PartialEq for CallbackHandleData {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id && Arc::ptr_eq(&self.callbacks, &other.callbacks)
    }
}

impl Add for CallbackHandle {
    type Output = Self;

    fn add(mut self, rhs: Self) -> Self::Output {
        self += rhs;
        self
    }
}

impl AddAssign for CallbackHandle {
    fn add_assign(&mut self, rhs: Self) {
        match (&mut self.0, rhs.0) {
            (_, CallbackHandleInner::None) => {}
            (CallbackHandleInner::None, other) => {
                self.0 = other;
            }
            (CallbackHandleInner::Single(_), CallbackHandleInner::Single(other)) => {
                let CallbackHandleInner::Single(single) =
                    std::mem::replace(&mut self.0, CallbackHandleInner::Multi(vec![other]))
                else {
                    unreachable!("just matched")
                };
                let CallbackHandleInner::Multi(multi) = &mut self.0 else {
                    unreachable!("just replaced")
                };
                multi.push(single);
            }
            (CallbackHandleInner::Single(_), CallbackHandleInner::Multi(multi)) => {
                let CallbackHandleInner::Single(single) =
                    std::mem::replace(&mut self.0, CallbackHandleInner::Multi(multi))
                else {
                    unreachable!("just matched")
                };
                let CallbackHandleInner::Multi(multi) = &mut self.0 else {
                    unreachable!("just replaced")
                };
                multi.push(single);
            }
            (CallbackHandleInner::Multi(this), CallbackHandleInner::Single(single)) => {
                this.push(single);
            }
            (CallbackHandleInner::Multi(this), CallbackHandleInner::Multi(mut other)) => {
                this.append(&mut other);
            }
        }
    }
}

#[derive(Default)]
struct InvalidationState {
    windows: AHashSet<WindowHandle>,
    widgets: AHashSet<(WindowHandle, WidgetId)>,
    wakers: Vec<Waker>,
}

impl InvalidationState {
    fn invoke(&mut self) {
        for (window, widget) in self.widgets.drain() {
            window.invalidate(widget);
        }
        for window in self.windows.drain() {
            window.redraw();
        }
        for waker in self.wakers.drain(..) {
            waker.wake();
        }
    }

    fn extend(&mut self, other: &mut InvalidationState) {
        self.widgets.extend(other.widgets.drain());
        self.windows.extend(other.windows.drain());

        for waker in other.wakers.drain(..) {
            if !self
                .wakers
                .iter()
                .any(|existing| existing.will_wake(&waker))
            {
                self.wakers.push(waker);
            }
        }
    }
}

struct State<T> {
    wrapped: GenerationalValue<T>,
    source_callback: CallbackHandle,
    callbacks: Arc<ChangeCallbacksData>,
    invalidation: InvalidationState,
    on_disconnect: Option<Vec<OnceCallback>>,
    readers: usize,
}

impl<T> State<T> {
    fn new(value: T) -> Self {
        Self {
            wrapped: GenerationalValue {
                value,
                generation: Generation::default(),
            },
            callbacks: Arc::default(),
            invalidation: InvalidationState {
                windows: AHashSet::new(),
                wakers: Vec::new(),
                widgets: AHashSet::new(),
            },
            readers: 0,
            on_disconnect: Some(Vec::new()),
            source_callback: CallbackHandle::default(),
        }
    }

    fn note_changed(&mut self) -> ChangeCallbacks {
        self.wrapped.generation = self.wrapped.generation.next();

        if !InvalidationBatch::take_invalidations(&mut self.invalidation) {
            self.invalidation.invoke();
        }

        ChangeCallbacks {
            data: self.callbacks.clone(),
            changed_at: Instant::now(),
        }
    }

    fn debug(&self, name: &str, f: &mut fmt::Formatter<'_>) -> fmt::Result
    where
        T: Debug,
    {
        f.debug_struct(name)
            .field("value", &self.wrapped.value)
            .field("generation", &self.wrapped.generation.0)
            .finish()
    }

    #[must_use]
    fn cleanup(&mut self) -> StateCleanup {
        StateCleanup {
            on_disconnect: self.on_disconnect.take(),
            wakers: std::mem::take(&mut self.invalidation.wakers),
        }
    }
}

impl<T> Drop for State<T> {
    fn drop(&mut self) {
        // Ensure any disconnections that didn't fire due to deadlocking still
        // are invoked.
        drop(self.cleanup());
    }
}

struct StateCleanup {
    on_disconnect: Option<Vec<OnceCallback>>,
    wakers: Vec<Waker>,
}

impl Drop for StateCleanup {
    fn drop(&mut self) {
        for on_disconnect in self.on_disconnect.take().into_iter().flatten() {
            on_disconnect.invoke(());
        }

        for waker in self.wakers.drain(..) {
            waker.wake();
        }
    }
}

impl<T> Debug for State<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("State")
            .field("wrapped", &self.wrapped)
            .field("readers", &self.readers)
            .finish_non_exhaustive()
    }
}

#[derive(Default)]
struct ChangeCallbacksData {
    callbacks: Mutex<CallbacksList>,
    currently_executing: Mutex<Option<ThreadId>>,
    sync: Condvar,
}

impl CallbackCollection for ChangeCallbacksData {
    fn remove(&self, id: LotId) {
        let mut data = self.callbacks.lock();
        data.callbacks.remove(id);
    }
}

struct CallbacksList {
    callbacks: Lots<Box<dyn ValueCallback>>,
    invoked_at: Instant,
}

impl Default for CallbacksList {
    fn default() -> Self {
        Self {
            callbacks: Lots::new(),
            invoked_at: Instant::now(),
        }
    }
}

struct ChangeCallbacks {
    data: Arc<ChangeCallbacksData>,
    changed_at: Instant,
}

impl Drop for ChangeCallbacks {
    fn drop(&mut self) {
        let mut currently_executing = self.data.currently_executing.lock();
        let current_thread = thread::current().id();
        loop {
            match &*currently_executing {
                None => {
                    // No other thread is executing these callbacks. Set this
                    // thread as the current executor so that we can prevent
                    // infinite cycles.
                    *currently_executing = Some(current_thread);
                    drop(currently_executing);

                    // Invoke the callbacks
                    let mut state = self.data.callbacks.lock();
                    // If the callbacks have already been invoked by another
                    // thread such that the callbacks observed the value our
                    // thread wrote, we can skip the callbacks.
                    if state.invoked_at < self.changed_at {
                        state.invoked_at = Instant::now();
                        // Invoke all callbacks, removing those that report an
                        // error.
                        state
                            .callbacks
                            .drain_filter(|callback| callback.changed().is_err());
                    }
                    drop(state);

                    // Remove ourselves as the current executor, notifying any
                    // other threads that are waiting.
                    currently_executing = self.data.currently_executing.lock();
                    *currently_executing = None;
                    drop(currently_executing);
                    self.data.sync.notify_all();

                    return;
                }
                Some(executing) if executing == &current_thread => {
                    // The callbacks are already running, and they triggered
                    // again. We ignore this rather than trying to continue to
                    // propagate because this can only be caused by a cycle
                    // happening during a callback already executing.
                    return;
                }
                Some(_) => {
                    self.data.sync.wait(&mut currently_executing);
                }
            }
        }
    }
}

trait ValueCallback: Send {
    fn changed(&mut self) -> Result<(), CallbackDisconnected>;
}

impl<F> ValueCallback for F
where
    F: for<'a> FnMut() -> Result<(), CallbackDisconnected> + Send + 'static,
{
    fn changed(&mut self) -> Result<(), CallbackDisconnected> {
        self()
    }
}

/// A value stored in a [`Dynamic`] with its [`Generation`].
#[derive(Default, Clone, Debug, Eq, PartialEq)]
pub struct GenerationalValue<T> {
    /// The stored value.
    pub value: T,
    generation: Generation,
}

impl<T> GenerationalValue<T> {
    /// Returns the generation of this value.
    ///
    /// Each time a [`Dynamic`] is updated, the generation is also updated. This
    /// value can be used to track whether a particular value has been observed.
    pub const fn generation(&self) -> Generation {
        self.generation
    }

    /// Returns a new instance containing the result of invoking `map` with
    /// `self.value`.
    ///
    /// The returned instance will have the same generation as this instance.
    pub fn map<U>(self, map: impl FnOnce(T) -> U) -> GenerationalValue<U> {
        GenerationalValue {
            value: map(self.value),
            generation: self.generation,
        }
    }

    /// Returns a new instance containing the result of invoking `map` with
    /// `&self.value`.
    ///
    /// The returned instance will have the same generation as this instance.
    pub fn map_ref<U>(&self, map: impl for<'a> FnOnce(&'a T) -> U) -> GenerationalValue<U> {
        GenerationalValue {
            value: map(&self.value),
            generation: self.generation,
        }
    }
}

impl<T> Deref for GenerationalValue<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.value
    }
}

impl<T> DerefMut for GenerationalValue<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.value
    }
}

#[derive(Debug)]
enum DynamicOrOwnedGuard<'a, T> {
    Dynamic(DynamicMutexGuard<'a, T>),
    Owned(RefMut<'a, GenerationalValue<T>>),
    OwnedRef(&'a mut GenerationalValue<T>),
}
impl<'a, T> DynamicOrOwnedGuard<'a, T> {
    fn note_changed(&mut self) -> Option<ChangeCallbacks> {
        match self {
            Self::Dynamic(guard) => Some(guard.note_changed()),
            Self::Owned(_) | Self::OwnedRef(_) => None,
        }
    }

    fn unlocked(&mut self, while_unlocked: impl FnOnce()) {
        match self {
            Self::Dynamic(guard) => guard.unlocked(while_unlocked),
            Self::Owned(_) | Self::OwnedRef(_) => while_unlocked(),
        }
    }
}

impl<'a, T> Deref for DynamicOrOwnedGuard<'a, T> {
    type Target = GenerationalValue<T>;

    fn deref(&self) -> &Self::Target {
        match self {
            Self::Dynamic(guard) => &guard.wrapped,
            Self::Owned(r) => r,
            Self::OwnedRef(r) => r,
        }
    }
}

impl<'a, T> DerefMut for DynamicOrOwnedGuard<'a, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            Self::Dynamic(guard) => &mut guard.wrapped,
            Self::Owned(r) => r,
            Self::OwnedRef(r) => r,
        }
    }
}

/// An exclusive reference to the contents of a [`Dynamic`].
///
/// If the contents are accessed through [`DerefMut`], all obververs will be
/// notified of a change when this guard is dropped.
#[derive(Debug)]
pub struct DynamicGuard<'a, T, const READONLY: bool = false> {
    guard: DynamicOrOwnedGuard<'a, T>,
    accessed_mut: bool,
    prevent_notifications: bool,
}

impl<T, const READONLY: bool> DynamicGuard<'_, T, READONLY> {
    /// Returns the generation of the value at the time of locking the dynamic.
    ///
    /// Even if this guard accesses the data through [`DerefMut`], this value
    /// will remain unchanged while the guard is held.
    #[must_use]
    pub fn generation(&self) -> Generation {
        self.guard.generation
    }

    /// Prevent any access through [`DerefMut`] from triggering change
    /// notifications.
    pub fn prevent_notifications(&mut self) {
        self.prevent_notifications = true;
    }
}

impl<'a, T, const READONLY: bool> Deref for DynamicGuard<'a, T, READONLY> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.guard.value
    }
}

impl<'a, T> DerefMut for DynamicGuard<'a, T, false> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.accessed_mut = true;
        &mut self.guard.value
    }
}

impl<T, const READONLY: bool> Drop for DynamicGuard<'_, T, READONLY> {
    fn drop(&mut self) {
        if self.accessed_mut && !self.prevent_notifications {
            let callbacks = self.guard.note_changed();
            self.guard.unlocked(|| drop(callbacks));
        }
    }
}

/// A weak reference to a [`Dynamic`].
///
/// This is powered by [`Arc`]/[`Weak`] and follows the same semantics for
/// reference counting.
pub struct WeakDynamic<T>(Weak<DynamicData<T>>);

impl<T> WeakDynamic<T> {
    /// Returns the [`Dynamic`] this weak reference points to, unless no
    /// remaining [`Dynamic`] instances exist for the underlying value.
    #[must_use]
    pub fn upgrade(&self) -> Option<Dynamic<T>> {
        self.0.upgrade().map(Dynamic)
    }
}
impl<T> Debug for WeakDynamic<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(strong) = self.upgrade() {
            Debug::fmt(&strong, f)
        } else {
            f.debug_tuple("WeakDynamic")
                .field(&"<pending drop>")
                .finish()
        }
    }
}

impl<'a, T> From<&'a Dynamic<T>> for WeakDynamic<T> {
    fn from(value: &'a Dynamic<T>) -> Self {
        Self(Arc::downgrade(&value.0))
    }
}

impl<T> From<Dynamic<T>> for WeakDynamic<T> {
    fn from(value: Dynamic<T>) -> Self {
        Self::from(&value)
    }
}

impl<T> Clone for WeakDynamic<T> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<T> Eq for WeakDynamic<T> {}

impl<T> PartialEq for WeakDynamic<T> {
    fn eq(&self, other: &Self) -> bool {
        Weak::ptr_eq(&self.0, &other.0)
    }
}

impl<T> PartialEq<Dynamic<T>> for WeakDynamic<T> {
    fn eq(&self, other: &Dynamic<T>) -> bool {
        Weak::as_ptr(&self.0) == Arc::as_ptr(&other.0)
    }
}

impl<T> PartialEq<WeakDynamic<T>> for Dynamic<T> {
    fn eq(&self, other: &WeakDynamic<T>) -> bool {
        Arc::as_ptr(&self.0) == Weak::as_ptr(&other.0)
    }
}

/// A reader of a [`Dynamic<T>`] that tracks the last generation accessed.
pub struct DynamicReader<T> {
    source: Arc<DynamicData<T>>,
    read_generation: Mutex<Generation>,
}

impl<T> DynamicReader<T> {
    /// Returns an read-only, exclusive reference to the contents of this
    /// dynamic.
    ///
    /// This call will block until all other guards for this dynamic have been
    /// dropped.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn lock(&self) -> DynamicGuard<'_, T, true> {
        DynamicGuard {
            guard: DynamicOrOwnedGuard::Dynamic(self.source.state().expect("deadlocked")),
            accessed_mut: false,
            prevent_notifications: false,
        }
    }

    /// Returns the current generation that has been accessed through this
    /// reader.
    #[must_use]
    pub fn read_generation(&self) -> Generation {
        *self.read_generation.lock()
    }

    /// Returns true if the dynamic has been modified since the last time the
    /// value was accessed through this reader.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    #[must_use]
    pub fn has_updated(&self) -> bool {
        self.source.state().expect("deadlocked").wrapped.generation != self.read_generation()
    }

    /// Blocks the current thread until the contained value has been updated or
    /// there are no remaining writers for the value.
    ///
    /// Returns true if a newly updated value was discovered.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    pub fn block_until_updated(&self) -> bool {
        assert!(
            self.source
                .during_callback_state
                .lock()
                .as_ref()
                .map_or(true, |state| state.locked_thread
                    != std::thread::current().id()),
            "deadlocked"
        );
        let mut state = self.source.state.lock();
        loop {
            if state.wrapped.generation != self.read_generation() {
                return true;
            } else if state.readers == Arc::strong_count(&self.source)
                || state.on_disconnect.is_none()
            {
                return false;
            }

            // Wait for a notification of a change, which is synch
            self.source.sync.wait(&mut state);
        }
    }

    /// Returns true if this reader still has any writers connected to it.
    #[must_use]
    pub fn connected(&self) -> bool {
        let state = self.source.state.lock();
        state.readers < Arc::strong_count(&self.source) && state.on_disconnect.is_some()
    }

    /// Suspends the current async task until the contained value has been
    /// updated or there are no remaining writers for the value.
    ///
    /// Returns true if a newly updated value was discovered.
    pub fn wait_until_updated(&self) -> BlockUntilUpdatedFuture<'_, T> {
        BlockUntilUpdatedFuture(self)
    }

    /// Invokes `on_disconnect` when no instances of `Dynamic<T>` exist.
    ///
    /// This callback will be invoked even if this `DynamicReader` has been
    /// dropped.
    ///
    /// # Panics
    ///
    /// This function panics if this value is already locked by the current
    /// thread.
    pub fn on_disconnect<OnDisconnect>(&self, on_disconnect: OnDisconnect)
    where
        OnDisconnect: FnOnce() + Send + 'static,
    {
        let mut state = self.source.state().expect("deadlocked");

        if let Some(callbacks) = &mut state.on_disconnect {
            callbacks.push(OnceCallback::new(|()| on_disconnect()));
        }
    }
}

impl<T> context::sealed::Trackable for DynamicReader<T> {
    fn inner_redraw_when_changed(&self, handle: WindowHandle) {
        self.source.redraw_when_changed(handle);
    }

    fn inner_invalidate_when_changed(&self, handle: WindowHandle, id: WidgetId) {
        self.source.invalidate_when_changed(handle, id);
    }
}

impl<T> Debug for DynamicReader<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DynamicReader")
            .field("source", &DebugDynamicData(&self.source))
            .field("read_generation", &self.read_generation().0)
            .finish()
    }
}

impl<T> Clone for DynamicReader<T> {
    fn clone(&self) -> Self {
        self.source.state().expect("deadlocked").readers += 1;
        Self {
            source: self.source.clone(),
            read_generation: Mutex::new(self.read_generation()),
        }
    }
}

impl<T> Drop for DynamicReader<T> {
    fn drop(&mut self) {
        let mut state = self.source.state().expect("deadlocked");
        state.readers -= 1;
    }
}

/// Suspends the current async task until the contained value has been
/// updated or there are no remaining writers for the value.
///
/// Yeilds true if a newly updated value was discovered.
#[derive(Debug)]
#[must_use = "futures must be .await'ed to be executed"]
pub struct BlockUntilUpdatedFuture<'a, T>(&'a DynamicReader<T>);

impl<'a, T> Future for BlockUntilUpdatedFuture<'a, T> {
    type Output = bool;

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
        let mut state = self.0.source.state().expect("deadlocked");
        if state.wrapped.generation != self.0.read_generation() {
            return Poll::Ready(true);
        } else if state.readers == Arc::strong_count(&self.0.source)
            || state.on_disconnect.is_none()
        {
            return Poll::Ready(false);
        }

        state.invalidation.wakers.push(cx.waker().clone());
        Poll::Pending
    }
}

#[test]
fn disconnecting_reader_from_dynamic() {
    let value = Dynamic::new(1);
    let ref_reader = value.create_reader();
    drop(value);
    assert!(!ref_reader.block_until_updated());
}

#[test]
fn disconnecting_reader_threaded() {
    let a = Dynamic::new(1);
    let a_reader = a.create_reader();
    let b = Dynamic::new(1);
    let b_reader = b.create_reader();

    let thread = std::thread::spawn(move || {
        b.set(2);

        assert!(a_reader.block_until_updated());
        assert_eq!(a_reader.get(), 2);
        assert!(!a_reader.block_until_updated());
    });

    // Wait for the thread to set b to 2.
    assert!(b_reader.block_until_updated());
    assert_eq!(b_reader.get(), 2);

    // Set a to 2 and drop the handle.
    a.set(2);
    drop(a);

    thread.join().unwrap();
}

#[test]
fn disconnecting_reader_async() {
    let a = Dynamic::new(1);
    let a_reader = a.create_reader();
    let b = Dynamic::new(1);
    let b_reader = b.create_reader();

    let async_thread = std::thread::spawn(move || {
        pollster::block_on(async move {
            // Set b to 2, allowing the thread to execute its code.
            b.set(2);

            assert!(a_reader.wait_until_updated().await);
            assert_eq!(a_reader.get(), 2);
            assert!(!a_reader.wait_until_updated().await);
        });
    });

    // Wait for the pollster thread to set b to 2.
    assert!(b_reader.block_until_updated());
    assert_eq!(b_reader.get(), 2);

    // Set a to 2 and drop the handle.
    a.set(2);
    drop(a);

    async_thread.join().unwrap();
}

/// A tag that represents an individual revision of a [`Dynamic`] value.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct Generation(usize);

impl Generation {
    /// Returns the next tag.
    #[must_use]
    pub fn next(self) -> Self {
        Self(self.0.wrapping_add(1))
    }
}

/// A type that can convert into a `ReadOnly<T>`.
pub trait IntoReadOnly<T> {
    /// Returns `self` as a `ReadOnly`.
    fn into_read_only(self) -> ReadOnly<T>;
}

impl<T> IntoReadOnly<T> for T {
    fn into_read_only(self) -> ReadOnly<T> {
        ReadOnly::Constant(self)
    }
}

impl<T> IntoReadOnly<T> for ReadOnly<T> {
    fn into_read_only(self) -> ReadOnly<T> {
        self
    }
}

impl<T> IntoReadOnly<T> for Value<T> {
    fn into_read_only(self) -> ReadOnly<T> {
        match self {
            Value::Constant(value) => ReadOnly::Constant(value),
            Value::Dynamic(dynamic) => ReadOnly::Reader(dynamic.into_reader()),
        }
    }
}

impl<T> IntoReadOnly<T> for Dynamic<T> {
    fn into_read_only(self) -> ReadOnly<T> {
        self.create_reader().into_read_only()
    }
}

impl<T> IntoReadOnly<T> for DynamicReader<T> {
    fn into_read_only(self) -> ReadOnly<T> {
        ReadOnly::Reader(self)
    }
}

impl<T> IntoReadOnly<T> for Owned<T> {
    fn into_read_only(self) -> ReadOnly<T> {
        ReadOnly::Constant(self.into_inner())
    }
}

/// A type that can be converted into a [`DynamicReader<T>`].
pub trait IntoReader<T> {
    /// Returns this value as a reader.
    fn into_reader(self) -> DynamicReader<T>;

    /// Returns `self` being `Display`ed in a [`Label`] widget.
    fn into_label(self) -> Label<T>
    where
        Self: Sized,
        T: Debug + Display + Send + 'static,
    {
        Label::new(self.into_reader())
    }

    /// Returns `self` being `Display`ed in a [`Label`] widget.
    fn to_label(&self) -> Label<T>
    where
        Self: Clone,
        T: Debug + Display + Send + 'static,
    {
        self.clone().into_label()
    }
}

impl<T> IntoReader<T> for Dynamic<T> {
    fn into_reader(self) -> DynamicReader<T> {
        self.into_reader()
    }
}

impl<T> IntoReader<T> for DynamicReader<T> {
    fn into_reader(self) -> DynamicReader<T> {
        self
    }
}

/// A type that can convert into a `Dynamic<T>`.
pub trait IntoDynamic<T> {
    /// Returns `self` as a dynamic.
    fn into_dynamic(self) -> Dynamic<T>;
}

impl<T> IntoDynamic<T> for Dynamic<T> {
    fn into_dynamic(self) -> Dynamic<T> {
        self
    }
}

impl<T, F> IntoDynamic<T> for F
where
    F: FnMut(&T) + Send + 'static,
    T: Default + Send + 'static,
{
    /// Returns [`Dynamic::default()`] with `self` installed as a for-each
    /// callback.
    fn into_dynamic(self) -> Dynamic<T> {
        Dynamic::default().with_for_each(self)
    }
}

/// A type that can be the source of a [`Switcher`] widget.
pub trait Switchable<T>: IntoDynamic<T> + Sized {
    /// Returns a new [`Switcher`] whose contents is the result of invoking
    /// `map` each time `self` is updated.
    fn switcher<F>(self, map: F) -> Switcher
    where
        F: FnMut(&T, &Dynamic<T>) -> WidgetInstance + Send + 'static,
        T: Send + 'static,
    {
        Switcher::mapping(self, map)
    }

    /// Returns a new [`Switcher`] whose contents switches between the values
    /// contained in `map` using the value in `self` as the key.
    fn switch_between<Collection>(self, map: Collection) -> Switcher
    where
        Collection: GetWidget<T> + Send + 'static,
        T: Send + 'static,
    {
        Switcher::mapping(self, move |key, _| {
            map.get(key)
                .map_or_else(|| Space::clear().make_widget(), Clone::clone)
        })
    }
}

/// A collection of widgets that can be queried by `Key`.
pub trait GetWidget<Key> {
    /// Returns the widget associated with `key`, if found.
    fn get<'a>(&'a self, key: &Key) -> Option<&'a WidgetInstance>;
}

impl<Key, State> GetWidget<Key> for HashMap<Key, WidgetInstance, State>
where
    Key: Hash + Eq,
    State: BuildHasher,
{
    fn get<'a>(&'a self, key: &Key) -> Option<&'a WidgetInstance> {
        HashMap::get(self, key)
    }
}

impl<Key> GetWidget<Key> for Map<Key, WidgetInstance>
where
    Key: Sort,
{
    fn get<'a>(&'a self, key: &Key) -> Option<&'a WidgetInstance> {
        Map::get(self, key)
    }
}

impl GetWidget<usize> for WidgetList {
    fn get<'a>(&'a self, key: &usize) -> Option<&'a WidgetInstance> {
        (**self).get(*key)
    }
}

impl GetWidget<usize> for Vec<WidgetInstance> {
    fn get<'a>(&'a self, key: &usize) -> Option<&'a WidgetInstance> {
        (**self).get(*key)
    }
}

impl<T, W> Switchable<T> for W where W: IntoDynamic<T> {}

/// A value that can only be read from.
pub enum ReadOnly<T> {
    /// A value that will not ever change externally.
    Constant(T),
    /// A value that is read from a dynamic.
    Reader(DynamicReader<T>),
}

impl<T> ReadOnly<T> {
    /// Returns a clone of the currently stored value.
    #[must_use]
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        match self {
            Self::Constant(value) => value.clone(),
            Self::Reader(value) => value.get(),
        }
    }

    /// Returns the current generation of the data stored, if the contained
    /// value is [`Dynamic`].
    pub fn generation(&self) -> Option<Generation> {
        match self {
            Self::Constant(_) => None,
            Self::Reader(value) => Some(value.generation()),
        }
    }

    /// Maps the current contents to `map` and returns the result.
    pub fn map<R>(&self, map: impl FnOnce(&T) -> R) -> R {
        match self {
            Self::Constant(value) => map(value),
            Self::Reader(dynamic) => dynamic.map_ref(map),
        }
    }

    /// Returns a new value that is updated using `U::from(T.clone())` each time
    /// `self` is updated.
    #[must_use]
    pub fn map_each<R, F>(&self, mut map: F) -> ReadOnly<R>
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) -> R + Send + 'static,
        R: PartialEq + Send + 'static,
    {
        match self {
            Self::Constant(value) => ReadOnly::Constant(map(value)),
            Self::Reader(dynamic) => ReadOnly::Reader(dynamic.map_each(map).into_reader()),
        }
    }
}

impl<T> From<DynamicReader<T>> for ReadOnly<T> {
    fn from(value: DynamicReader<T>) -> Self {
        Self::Reader(value)
    }
}

impl<T> From<Dynamic<T>> for ReadOnly<T> {
    fn from(value: Dynamic<T>) -> Self {
        Self::from(value.into_reader())
    }
}

impl<T> From<Owned<T>> for ReadOnly<T> {
    fn from(value: Owned<T>) -> Self {
        Self::Constant(value.into_inner())
    }
}

impl<T> Debug for ReadOnly<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Constant(arg0) => Debug::fmt(arg0, f),
            Self::Reader(arg0) => Debug::fmt(arg0, f),
        }
    }
}

/// A value that may be either constant or dynamic.
pub enum Value<T> {
    /// A value that will not ever change externally.
    Constant(T),
    /// A value that may be updated externally.
    Dynamic(Dynamic<T>),
}

impl<T> Value<T> {
    /// Returns a [`Value::Dynamic`] containing `value`.
    pub fn dynamic(value: T) -> Self {
        Self::Dynamic(Dynamic::new(value))
    }

    /// Maps the current contents to `map` and returns the result.
    pub fn map<R>(&self, map: impl FnOnce(&T) -> R) -> R {
        match self {
            Value::Constant(value) => map(value),
            Value::Dynamic(dynamic) => dynamic.map_ref(map),
        }
    }

    /// Maps the current contents to `map` and returns the result.
    ///
    /// If `self` is a dynamic, `context` will be invalidated when the value is
    /// updated.
    pub fn map_tracking_redraw<R>(
        &self,
        context: &WidgetContext<'_>,
        map: impl FnOnce(&T) -> R,
    ) -> R {
        match self {
            Value::Constant(value) => map(value),
            Value::Dynamic(dynamic) => {
                context.redraw_when_changed(dynamic);
                dynamic.map_ref(map)
            }
        }
    }

    /// Maps the current contents to `map` and returns the result.
    ///
    /// If `self` is a dynamic, `context` will be invalidated when the value is
    /// updated.
    pub fn map_tracking_invalidate<R>(
        &self,
        context: &WidgetContext<'_>,
        map: impl FnOnce(&T) -> R,
    ) -> R {
        match self {
            Value::Constant(value) => map(value),
            Value::Dynamic(dynamic) => {
                context.invalidate_when_changed(dynamic);
                dynamic.map_ref(map)
            }
        }
    }

    /// Maps the current contents with exclusive access and returns the result.
    pub fn map_mut<R>(&mut self, map: impl FnOnce(Mutable<'_, T>) -> R) -> R {
        match self {
            Value::Constant(value) => map(Mutable::from(value)),
            Value::Dynamic(dynamic) => dynamic.map_mut(map),
        }
    }

    /// Returns a new value that is updated using `U::from(T.clone())` each time
    /// `self` is updated.
    #[must_use]
    pub fn map_each<R, F>(&self, mut map: F) -> Value<R>
    where
        T: Send + 'static,
        F: for<'a> FnMut(&'a T) -> R + Send + 'static,
        R: PartialEq + Send + 'static,
    {
        match self {
            Value::Constant(value) => Value::Constant(map(value)),
            Value::Dynamic(dynamic) => Value::Dynamic(dynamic.map_each(map)),
        }
    }

    /// Returns a clone of the currently stored value.
    pub fn get(&self) -> T
    where
        T: Clone,
    {
        self.map(Clone::clone)
    }

    /// Returns a clone of the currently stored value.
    ///
    /// If `self` is a dynamic, `context` will be refreshed when the value is
    /// updated.
    pub fn get_tracking_redraw(&self, context: &WidgetContext<'_>) -> T
    where
        T: Clone,
    {
        self.map_tracking_redraw(context, Clone::clone)
    }

    /// Returns a clone of the currently stored value.
    ///
    /// If `self` is a dynamic, `context` will be invalidated when the value is
    /// updated.
    pub fn get_tracking_invalidate(&self, context: &WidgetContext<'_>) -> T
    where
        T: Clone,
    {
        self.map_tracking_invalidate(context, Clone::clone)
    }

    /// Returns the current generation of the data stored, if the contained
    /// value is [`Dynamic`].
    pub fn generation(&self) -> Option<Generation> {
        match self {
            Value::Constant(_) => None,
            Value::Dynamic(value) => Some(value.generation()),
        }
    }
}

impl<T> crate::context::sealed::Trackable for ReadOnly<T> {
    fn inner_invalidate_when_changed(&self, handle: WindowHandle, id: WidgetId) {
        if let ReadOnly::Reader(dynamic) = self {
            dynamic.inner_invalidate_when_changed(handle, id);
        }
    }

    fn inner_redraw_when_changed(&self, handle: WindowHandle) {
        if let ReadOnly::Reader(dynamic) = self {
            dynamic.inner_redraw_when_changed(handle);
        }
    }
}

impl<T> crate::context::sealed::Trackable for Value<T> {
    fn inner_invalidate_when_changed(&self, handle: WindowHandle, id: WidgetId) {
        if let Value::Dynamic(dynamic) = self {
            dynamic.inner_invalidate_when_changed(handle, id);
        }
    }

    fn inner_redraw_when_changed(&self, handle: WindowHandle) {
        if let Value::Dynamic(dynamic) = self {
            dynamic.inner_redraw_when_changed(handle);
        }
    }
}

impl<T> From<Dynamic<T>> for Value<T> {
    fn from(value: Dynamic<T>) -> Self {
        Self::Dynamic(value)
    }
}

impl<T> IntoDynamic<T> for Value<T> {
    fn into_dynamic(self) -> Dynamic<T> {
        match self {
            Value::Constant(value) => Dynamic::new(value),
            Value::Dynamic(value) => value,
        }
    }
}

impl<T> Debug for Value<T>
where
    T: Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Constant(arg0) => Debug::fmt(arg0, f),
            Self::Dynamic(arg0) => Debug::fmt(arg0, f),
        }
    }
}

impl<T> Clone for Value<T>
where
    T: Clone,
{
    fn clone(&self) -> Self {
        match self {
            Self::Constant(arg0) => Self::Constant(arg0.clone()),
            Self::Dynamic(arg0) => Self::Dynamic(arg0.clone()),
        }
    }
}

impl<T> Default for Value<T>
where
    T: Default,
{
    fn default() -> Self {
        Self::Constant(T::default())
    }
}

/// A type that can be converted into a [`Value`].
pub trait IntoValue<T> {
    /// Returns this type as a [`Value`].
    fn into_value(self) -> Value<T>;
}

impl<T> IntoValue<T> for T {
    fn into_value(self) -> Value<T> {
        Value::Constant(self)
    }
}

impl<'a> IntoValue<String> for &'a str {
    fn into_value(self) -> Value<String> {
        Value::Constant(self.to_owned())
    }
}

impl<'a> IntoReadOnly<String> for &'a str {
    fn into_read_only(self) -> ReadOnly<String> {
        ReadOnly::Constant(self.to_string())
    }
}

impl<T> IntoValue<T> for Dynamic<T> {
    fn into_value(self) -> Value<T> {
        Value::Dynamic(self)
    }
}

impl<T> IntoValue<T> for &'_ Dynamic<T> {
    fn into_value(self) -> Value<T> {
        Value::Dynamic(self.clone())
    }
}

impl<T> IntoValue<T> for Value<T> {
    fn into_value(self) -> Value<T> {
        self
    }
}

impl<T> IntoValue<Option<T>> for T {
    fn into_value(self) -> Value<Option<T>> {
        Value::Constant(Some(self))
    }
}

/// A type that can have a `for_each` operation applied to it.
pub trait ForEach<T> {
    /// The borrowed representation of T to pass into the `for_each` function.
    type Ref<'a>;

    /// Invokes `for_each` with the current contents and each time this source's
    /// contents are updated.
    fn for_each<F>(&self, for_each: F) -> CallbackHandle
    where
        F: for<'a> FnMut(Self::Ref<'a>) + Send + 'static;

    /// Attaches `for_each` to this value so that it is invoked each time the
    /// source's contents are updated.
    ///
    /// `for_each` will not be invoked with the currently stored value.
    fn for_each_subsequent<F>(&self, for_each: F) -> CallbackHandle
    where
        F: for<'a> FnMut(Self::Ref<'a>) + Send + 'static;
}

macro_rules! impl_tuple_for_each {
    ($($type:ident $source:ident $field:tt $var:ident),+) => {
        impl<$($type,$source,)+> ForEach<($($type,)+)> for ($(&$source,)+)
        where
            $(
                $source: DynamicRead<$type> + Source<$type> + Clone + Send + 'static,
                $type: Send + 'static,
            )+
        {
            type Ref<'a> = ($(&'a $type,)+);

            #[allow(unused_mut)]
            fn for_each<F>(&self, mut for_each: F) -> CallbackHandle
            where
                F: for<'a> FnMut(Self::Ref<'a>) + Send + 'static,
            {
                {
                    $(let $var = self.$field.read();)+
                    for_each(($(&$var,)+));
                };
                self.for_each_subsequent(for_each)
            }

            #[allow(unused_mut)]
            fn for_each_subsequent<F>(&self, mut for_each: F) -> CallbackHandle
            where
                F: for<'a> FnMut(Self::Ref<'a>) + Send + 'static,
            {
                let mut handles = CallbackHandle::default();
                impl_tuple_for_each!(self for_each handles [] [$($type $field $var),+]);
                handles
            }
        }
    };
    ($self:ident $for_each:ident $handles:ident [] [$type:ident $field:tt $var:ident]) => {
        $handles += $self.$field.for_each(move |field| $for_each((field,)));
    };
    ($self:ident $for_each:ident $handles:ident [] [$($type:ident $field:tt $var:ident),+]) => {
        let $for_each = Arc::new(Mutex::new($for_each));
        $(let $var = $self.$field.clone();)*


        impl_tuple_for_each!(invoke $self $for_each $handles [] [$($type $field $var),+]);
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // List of all tuple fields that have already been positioned as the focused call
        [$($ltype:ident $lfield:tt $lvar:ident),*]
        //
        [$type:ident $field:tt $var:ident, $($rtype:ident $rfield:tt $rvar:ident),+]
    ) => {
        impl_tuple_for_each!(
            invoke
            $self $for_each $handles
            $type $field $var
            [$($ltype $lfield $lvar,)* $type $field $var, $($rtype $rfield $rvar),+]
            [$($ltype $lfield $lvar,)* $($rtype $rfield $rvar),+]
        );
        impl_tuple_for_each!(
            invoke
            $self $for_each $handles
            [$($ltype $lfield $lvar,)* $type $field $var]
            [$($rtype $rfield $rvar),+]
        );
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // List of all tuple fields that have already been positioned as the focused call
        [$($ltype:ident $lfield:tt $lvar:ident),+]
        //
        [$type:ident $field:tt $var:ident]
    ) => {
        impl_tuple_for_each!(
            invoke
            $self $for_each $handles
            $type $field $var
            [$($ltype $lfield $lvar,)+ $type $field $var]
            [$($ltype $lfield $lvar),+]
        );
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // Tuple field that for_each is being invoked on
        $type:ident $field:tt $var:ident
        // The list of all tuple fields in this invocation, in the correct order.
        [$($atype:ident $afield:tt $avar:ident),+]
        // The list of tuple fields excluding the one being invoked.
        [$($rtype:ident $rfield:tt $rvar:ident),+]
    ) => {
        $handles += $var.for_each_subsequent((&$for_each, $(&$rvar,)+).with_clone(|(for_each, $($rvar,)+)| {
            move |$var: &$type| {
                $(let $rvar = $rvar.read();)+
                let mut for_each =
                    for_each.lock();
                (for_each)(($(&$avar,)+));
            }
        }));
    };
}

/// Read access to a value stored in a [`Dynamic`].
pub trait DynamicRead<T> {
    /// Returns a guard that provides exclusive, read-only access to the value
    /// contained wihtin this dynamic.
    fn read(&self) -> DynamicGuard<'_, T, true>;
}

impl<T> DynamicRead<T> for Dynamic<T> {
    fn read(&self) -> DynamicGuard<'_, T, true> {
        self.lock_inner()
    }
}

impl<T> DynamicRead<T> for DynamicReader<T> {
    fn read(&self) -> DynamicGuard<'_, T, true> {
        self.lock()
    }
}

impl_all_tuples!(impl_tuple_for_each, 2);

/// A type that can create a `Dynamic<U>` from a `T` passed into a mapping
/// function.
pub trait MapEach<T, U> {
    /// The borrowed representation of `T` passed into the mapping function.
    type Ref<'a>
    where
        T: 'a;

    /// Apply `map_each` to each value in `self`, storing the result in the
    /// returned dynamic.
    fn map_each<F>(&self, map_each: F) -> Dynamic<U>
    where
        F: for<'a> FnMut(Self::Ref<'a>) -> U + Send + 'static;
}

macro_rules! impl_tuple_map_each {
    ($($type:ident $source:ident $field:tt $var:ident),+) => {
        impl<U, $($type,$source),+> MapEach<($($type,)+), U> for ($(&$source,)+)
        where
            U: PartialEq + Send + 'static,
            $(
                $type: Send + 'static,
                $source: DynamicRead<$type> + Source<$type> + Clone + Send + 'static,
            )+
        {
            type Ref<'a> = ($(&'a $type,)+);

            fn map_each<F>(&self, mut map_each: F) -> Dynamic<U>
            where
                F: for<'a> FnMut(Self::Ref<'a>) -> U + Send + 'static,
            {
                let dynamic = {
                    $(let $var = self.$field.read();)+

                    Dynamic::new(map_each(($(&$var,)+)))
                };
                dynamic.set_source(self.for_each({
                    let dynamic = dynamic.clone();

                    move |tuple| {
                        dynamic.set(map_each(tuple));
                    }
                }));
                dynamic
            }
        }
    };
}

impl_all_tuples!(impl_tuple_map_each, 2);

/// A type that can have a `for_each` operation applied to it.
pub trait ForEachCloned<T> {
    /// Apply `for_each` to each value contained within `self`.
    fn for_each_cloned<F>(&self, for_each: F) -> CallbackHandle
    where
        F: for<'a> FnMut(T) + Send + 'static;
}

macro_rules! impl_tuple_for_each_cloned {
    ($($type:ident $source:ident $field:tt $var:ident),+) => {
        impl<$($type,$source,)+> ForEachCloned<($($type,)+)> for ($(&$source,)+)
        where
            $(
                $type: Clone + Send + 'static,
                $source: Source<$type> + Clone + Send + 'static,
            )+
        {

            #[allow(unused_mut)]
            fn for_each_cloned<F>(&self, mut for_each: F) -> CallbackHandle
            where
                F: for<'a> FnMut(($($type,)+)) + Send + 'static,
            {
                let mut handles = CallbackHandle::default();
                impl_tuple_for_each_cloned!(self for_each handles [] [$($type $field $var),+]);
                handles
            }
        }
    };
    ($self:ident $for_each:ident $handles:ident [] [$type:ident $field:tt $var:ident]) => {
        $handles += $self.$field.for_each_cloned(move |field| $for_each((field,)));
    };
    ($self:ident $for_each:ident $handles:ident [] [$($type:ident $field:tt $var:ident),+]) => {
        let $for_each = Arc::new(Mutex::new($for_each));
        $(let $var = $self.$field.clone();)*


        impl_tuple_for_each_cloned!(invoke $self $for_each $handles [] [$($type $field $var),+]);
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // List of all tuple fields that have already been positioned as the focused call
        [$($ltype:ident $lfield:tt $lvar:ident),*]
        //
        [$type:ident $field:tt $var:ident, $($rtype:ident $rfield:tt $rvar:ident),+]
    ) => {
        impl_tuple_for_each_cloned!(
            invoke
            $self $for_each $handles
            $type $field $var
            [$($ltype $lfield $lvar,)* $type $field $var, $($rtype $rfield $rvar),+]
            [$($ltype $lfield $lvar,)* $($rtype $rfield $rvar),+]
        );
        impl_tuple_for_each_cloned!(
            invoke
            $self $for_each $handles
            [$($ltype $lfield $lvar,)* $type $field $var]
            [$($rtype $rfield $rvar),+]
        );
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // List of all tuple fields that have already been positioned as the focused call
        [$($ltype:ident $lfield:tt $lvar:ident),+]
        //
        [$type:ident $field:tt $var:ident]
    ) => {
        impl_tuple_for_each_cloned!(
            invoke
            $self $for_each $handles
            $type $field $var
            [$($ltype $lfield $lvar,)+ $type $field $var]
            [$($ltype $lfield $lvar),+]
        );
    };
    (
        invoke
        // Identifiers used from the outer method
        $self:ident $for_each:ident $handles:ident
        // Tuple field that for_each is being invoked on
        $type:ident $field:tt $var:ident
        // The list of all tuple fields in this invocation, in the correct order.
        [$($atype:ident $afield:tt $avar:ident),+]
        // The list of tuple fields excluding the one being invoked.
        [$($rtype:ident $rfield:tt $rvar:ident),+]
    ) => {
        $handles += $var.for_each_cloned((&$for_each, $(&$rvar,)+).with_clone(|(for_each, $($rvar,)+)| {
            move |$var: $type| {
                $(let $rvar = $rvar.get();)+
                if let Some(mut for_each) =
                    for_each.try_lock() {
                (for_each)(($($avar,)+));
                    }
            }
        }));
    };
}

impl_all_tuples!(impl_tuple_for_each_cloned, 2);

/// A type that can create a `Dynamic<U>` from a `T` passed into a mapping
/// function.
pub trait MapEachCloned<T, U> {
    /// Apply `map_each` to each value in `self`, storing the result in the
    /// returned dynamic.
    fn map_each_cloned<F>(&self, map_each: F) -> Dynamic<U>
    where
        F: for<'a> FnMut(T) -> U + Send + 'static;
}

macro_rules! impl_tuple_map_each_cloned {
    ($($type:ident $source:ident $field:tt $var:ident),+) => {
        impl<U, $($type,$source),+> MapEachCloned<($($type,)+), U> for ($(&$source,)+)
        where
            U: PartialEq + Send + 'static,
            $(
                $type: Clone + Send + 'static,
                $source: Source<$type> + Clone + Send + 'static,
            )+
        {

            fn map_each_cloned<F>(&self, mut map_each: F) -> Dynamic<U>
            where
                F: for<'a> FnMut(($($type,)+)) -> U + Send + 'static,
            {
                let dynamic = {
                    $(let $var = self.$field.get();)+

                    Dynamic::new(map_each(($($var,)+)))
                };
                dynamic.set_source(self.for_each_cloned({
                    let dynamic = dynamic.clone();

                    move |tuple| {
                        dynamic.set(map_each(tuple));
                    }
                }));
                dynamic
            }
        }
    };
}

impl_all_tuples!(impl_tuple_map_each_cloned, 2);

/// The status of validating data.
#[derive(Debug, Default, Clone, Eq, PartialEq)]
pub enum Validation {
    /// No validation has been performed yet.
    ///
    /// This status represents that the data is still in its initial state, so
    /// errors should be delayed until it is changed.
    #[default]
    None,
    /// The data is valid.
    Valid,
    /// The data is invalid. The string contains a human-readable message.
    Invalid(String),
}

impl Validation {
    /// Returns the effective text to display along side the field.
    ///
    /// When there is a validation error, it is returned, otherwise the hint is
    /// returned.
    #[must_use]
    pub fn message<'a>(&'a self, hint: &'a str) -> &'a str {
        match self {
            Validation::None | Validation::Valid => hint,
            Validation::Invalid(err) => err,
        }
    }

    /// Returns true if there is a validation error.
    #[must_use]
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Invalid(_))
    }

    /// Returns the result of merging both validations.
    #[must_use]
    pub fn and(&self, other: &Self) -> Self {
        match (self, other) {
            (Validation::Valid, Validation::Valid) => Validation::Valid,
            (Validation::Invalid(error), _) | (_, Validation::Invalid(error)) => {
                Validation::Invalid(error.clone())
            }
            (Validation::None, _) | (_, Validation::None) => Validation::None,
        }
    }
}

impl<T, E> IntoDynamic<Validation> for Dynamic<Result<T, E>>
where
    T: Send + 'static,
    E: Display + Send + 'static,
{
    fn into_dynamic(self) -> Dynamic<Validation> {
        self.map_each(|result| match result {
            Ok(_) => Validation::Valid,
            Err(err) => Validation::Invalid(err.to_string()),
        })
    }
}

/// A grouping of validations that can be checked simultaneously.
#[derive(Debug, Default, Clone)]
pub struct Validations {
    state: Dynamic<ValidationsState>,
    invalid: Dynamic<usize>,
}

#[derive(Default, Debug, Eq, PartialEq, Clone)]
enum ValidationsState {
    #[default]
    Initial,
    Resetting,
    Checked,
    Disabled,
}

impl Validations {
    /// Validates `dynamic`'s contents using `check`, returning a dynamic
    /// containing the validation status.
    ///
    /// The validation is linked with `self` such that checking `self`'s
    /// validation status will include this validation.
    #[must_use]
    pub fn validate<T, E, Valid>(
        &self,
        dynamic: &Dynamic<T>,
        mut check: Valid,
    ) -> Dynamic<Validation>
    where
        T: Send + 'static,
        Valid: for<'a> FnMut(&'a T) -> Result<(), E> + Send + 'static,
        E: Display,
    {
        let validation = Dynamic::new(Validation::None);
        let mut message_mapping = Self::map_to_message(move |value| check(value));
        let error_message = dynamic.map_each_generational(move |gen| message_mapping(&gen.guard));

        validation.set_source((&self.state, &error_message).for_each_cloned({
            let mut f = self.generate_validation(dynamic);
            let validation = validation.clone();

            move |(current_state, message)| {
                validation.set(f(current_state, message));
            }
        }));

        validation
    }

    /// Returns a dynamic validation status that is created by transforming the
    /// `Err` variant of `result` using [`Display`].
    ///
    /// The validation is linked with `self` such that checking `self`'s
    /// validation status will include this validation.
    #[must_use]
    pub fn validate_result<T, E>(
        &self,
        result: impl IntoDynamic<Result<T, E>>,
    ) -> Dynamic<Validation>
    where
        T: Send + 'static,
        E: Display + Send + 'static,
    {
        let result = result.into_dynamic();
        let error_message = result.map_each(move |value| match value {
            Ok(_) => None,
            Err(err) => Some(err.to_string()),
        });

        self.validate(&error_message, |error_message| match error_message {
            None => Ok(()),
            Some(message) => Err(message.clone()),
        })
    }

    fn map_to_message<T, E, Valid>(
        mut check: Valid,
    ) -> impl for<'a> FnMut(&'a GenerationalValue<T>) -> GenerationalValue<Option<String>> + Send + 'static
    where
        T: Send + 'static,
        Valid: for<'a> FnMut(&'a T) -> Result<(), E> + Send + 'static,
        E: Display,
    {
        move |value| {
            value.map_ref(|value| match check(value) {
                Ok(()) => None,
                Err(err) => Some(err.to_string()),
            })
        }
    }

    fn generate_validation<T>(
        &self,
        dynamic: &Dynamic<T>,
    ) -> impl FnMut(ValidationsState, GenerationalValue<Option<String>>) -> Validation
    where
        T: Send + 'static,
    {
        self.invalid.map_mut(|mut invalid| *invalid += 1);

        let invalid_count = self.invalid.clone();
        let dynamic = dynamic.clone();
        let mut initial_generation = dynamic.generation();
        let mut invalid = true;

        move |current_state, generational| {
            let new_invalid = match (&current_state, &generational.value) {
                (ValidationsState::Disabled, _) | (_, None) => false,
                (_, Some(_)) => true,
            };
            if invalid != new_invalid {
                if new_invalid {
                    invalid_count.map_mut(|mut invalid| *invalid += 1);
                } else {
                    invalid_count.map_mut(|mut invalid| *invalid -= 1);
                }
                invalid = new_invalid;
            }
            let new_status = if let Some(err) = generational.value {
                Validation::Invalid(err.to_string())
            } else {
                Validation::Valid
            };
            match current_state {
                ValidationsState::Resetting => {
                    initial_generation = dynamic.generation();
                    Validation::None
                }
                ValidationsState::Initial if initial_generation == dynamic.generation() => {
                    Validation::None
                }
                _ => new_status,
            }
        }
    }

    /// Returns a builder that can be used to create validations that only run
    /// when `condition` is true.
    pub fn when(&self, condition: impl IntoDynamic<bool>) -> WhenValidation<'_> {
        WhenValidation {
            validations: self,
            condition: condition.into_dynamic(),
            not: false,
        }
    }

    /// Returns a builder that can be used to create validations that only run
    /// when `condition` is false.
    pub fn when_not(&self, condition: impl IntoDynamic<bool>) -> WhenValidation<'_> {
        WhenValidation {
            validations: self,
            condition: condition.into_dynamic(),
            not: true,
        }
    }

    /// Returns true if this set of validations are all valid.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.invoke_callback((), &mut |()| true)
    }

    fn invoke_callback<T, R, F>(&self, t: T, handler: &mut F) -> R
    where
        F: FnMut(T) -> R + Send + 'static,
        R: Default,
    {
        let _result = self
            .state
            .compare_swap(&ValidationsState::Initial, ValidationsState::Checked);
        if self.invalid.get() == 0 {
            handler(t)
        } else {
            R::default()
        }
    }

    /// Returns a function that invokes `handler` only when all tracked
    /// validations are valid.
    ///
    /// The returned function can be use in a
    /// [`Callback`](crate::widget::Callback).
    ///
    /// When the contents are invalid, `R::default()` is returned.
    pub fn when_valid<T, R, F>(self, mut handler: F) -> impl FnMut(T) -> R + Send + 'static
    where
        F: FnMut(T) -> R + Send + 'static,
        R: Default,
    {
        move |t: T| self.invoke_callback(t, &mut handler)
    }

    /// Resets the validation status for all related validations.
    pub fn reset(&self) {
        self.state.set(ValidationsState::Resetting);
        self.state.set(ValidationsState::Initial);
    }
}

/// A builder for validations that only run when a precondition is met.
pub struct WhenValidation<'a> {
    validations: &'a Validations,
    condition: Dynamic<bool>,
    not: bool,
}

impl WhenValidation<'_> {
    /// Validates `dynamic`'s contents using `check`, returning a dynamic
    /// containing the validation status.
    ///
    /// The validation is linked with `self` such that checking `self`'s
    /// validation status will include this validation.
    ///
    /// Each change to `dynamic` is validated, but the result of the validation
    /// will be ignored if the required prerequisite isn't met.
    #[must_use]
    pub fn validate<T, E, Valid>(
        &self,
        dynamic: &Dynamic<T>,
        mut check: Valid,
    ) -> Dynamic<Validation>
    where
        T: Send + 'static,
        Valid: for<'a> FnMut(&'a T) -> Result<(), E> + Send + 'static,
        E: Display,
    {
        let validation = Dynamic::new(Validation::None);
        let mut map_to_message = Validations::map_to_message(move |value| check(value));
        let error_message =
            dynamic.map_each_generational(move |generational| map_to_message(&generational.guard));
        let mut f = self.validations.generate_validation(dynamic);
        let not = self.not;

        (&self.condition, &self.validations.state, &error_message).map_each_cloned({
            let validation = validation.clone();
            move |(condition, state, message)| {
                let enabled = if not { !condition } else { condition };
                let state = if enabled {
                    state
                } else {
                    ValidationsState::Disabled
                };
                let result = f(state, message);
                if enabled {
                    validation.set(result);
                } else {
                    validation.set(Validation::None);
                }
            }
        });

        validation
    }

    /// Returns a dynamic validation status that is created by transforming the
    /// `Err` variant of `result` using [`Display`].
    ///
    /// The validation is linked with `self` such that checking `self`'s
    /// validation status will include this validation.
    #[must_use]
    pub fn validate_result<T, E>(
        &self,
        result: impl IntoDynamic<Result<T, E>>,
    ) -> Dynamic<Validation>
    where
        T: Send + 'static,
        E: Display + Send + 'static,
    {
        let result = result.into_dynamic();
        let error_message = result.map_each(move |value| match value {
            Ok(_) => None,
            Err(err) => Some(err.to_string()),
        });

        self.validate(&error_message, |error_message| match error_message {
            None => Ok(()),
            Some(message) => Err(message.clone()),
        })
    }
}

struct Debounce<T> {
    destination: Dynamic<T>,
    period: Duration,
    delay: Option<AnimationHandle>,
    buffer: Dynamic<T>,
    extend: bool,
    _callback: Option<CallbackHandle>,
}

impl<T> Debounce<T>
where
    T: Clone + PartialEq + Send + Sync + 'static,
{
    pub fn new(destination: Dynamic<T>, period: Duration) -> Self {
        Self {
            buffer: Dynamic::new(destination.get()),
            destination,
            period,
            delay: None,
            extend: false,
            _callback: None,
        }
    }

    pub fn extending(mut self) -> Self {
        self.extend = true;
        self
    }

    pub fn update(&mut self, value: T) {
        if self.buffer.replace(value).is_some() {
            let create_delay = if self.extend {
                true
            } else {
                self.delay
                    .as_ref()
                    .map_or(true, AnimationHandle::is_complete)
            };

            if create_delay {
                let destination = self.destination.clone();
                let buffer = self.buffer.clone();
                self.delay = Some(
                    self.period
                        .on_complete(move || {
                            destination.set(buffer.get());
                        })
                        .spawn(),
                );
            }
        }
    }
}

/// A batch of invalidations across one or more windows.
///
/// This type helps background tasks synchronize when to invalidate or redraw a
/// widget. Without this type, if a tracked dynamic is changed, the window is
/// immediately sent a request to redraw itself. These requests are batched to
/// ensure efficiency, but if a background task is updating several dynamics
/// independent of one another, it may desire that those updates only trigger
/// one redraw per "step".
///
/// The closure invoked by [`InvalidationBatch::batch`] will gather all
/// invalidations into a single batch that can be executed by the handle
/// provided or automatically when the closure returns.
pub struct InvalidationBatch<'a>(&'a RefCell<InvalidationBatchGuard>);

#[derive(Default)]
struct InvalidationBatchGuard {
    nesting: usize,
    state: InvalidationState,
}

thread_local! {
    static GUARD: RefCell<InvalidationBatchGuard> = RefCell::default();
}

impl InvalidationBatch<'_> {
    /// Executes `batched` gathering all tracked invalidations into a shared
    /// batch.
    ///
    /// The closure accepts an `&InvalidationBatch<'_>` parameter which can be
    /// used to [`invoke()`](Self::invoke) the batch on-demand while during
    /// `batched`.
    ///
    /// This function supports nested invocation. When nested, only the
    /// outermost batch can manually invoke. When the outermost batch's callback
    /// ends, any pending invalidations are invoked automatically.
    pub fn batch(batched: impl FnOnce(&InvalidationBatch<'_>)) {
        GUARD.with(|guard| {
            let mut batch = guard.borrow_mut();
            batch.nesting += 1;
            drop(batch);

            batched(&InvalidationBatch(guard));

            let mut batch = guard.borrow_mut();
            batch.nesting -= 1;
            if batch.nesting == 0 {
                batch.state.invoke();
            }
        });
    }

    /// Invokes all pending invalidations.
    ///
    /// This function is a no-op if `self` is a nested batch. Only the root
    /// batch of each thread can trigger invalidations manually.
    pub fn invoke(&self) {
        let mut batch = self.0.borrow_mut();
        if batch.nesting == 1 {
            batch.state.invoke();
        }
    }

    #[must_use]
    fn take_invalidations(state: &mut InvalidationState) -> bool {
        GUARD.with(|guard| {
            let mut batch = guard.borrow_mut();
            if batch.nesting > 0 {
                // A batch is active on this thread
                batch.state.extend(state);
                true
            } else {
                false
            }
        })
    }
}

#[test]
fn map_cycle_is_finite() {
    crate::initialize_tracing();
    let a = Dynamic::new(0_usize);

    // This callback updates a each time a is updated with a + 1, causing an
    // infinite cycle if not broken by Cushy.
    a.for_each_cloned({
        let a = a.clone();
        move |current| {
            a.set(current + 1);
        }
    })
    .persist();

    // Cushy will invoke the callback for the first set call, but the set call
    // within the callback will not cause the callback to be invoked again.
    // Thus, we expect setting the value to 1 to result in `a` containing 2.
    a.set(1);
    assert_eq!(a.get(), 2);
}

#[test]
fn compare_swap() {
    let dynamic = Dynamic::new(1);
    assert_eq!(dynamic.compare_swap(&1, 2), Ok(1));
    assert_eq!(dynamic.compare_swap(&1, 0), Err(2));
    assert_eq!(dynamic.compare_swap(&2, 0), Ok(2));
    assert_eq!(dynamic.get(), 0);
}

#[test]
fn ref_counts() {
    let dynamic = Dynamic::new(1);
    assert_eq!(dynamic.instances(), 1);

    let second = dynamic.clone();
    assert_eq!(dynamic.instances(), 2);

    assert_eq!(dynamic.readers(), 0);
    let reader = second.into_reader();
    assert_eq!(dynamic.instances(), 1);
    assert_eq!(dynamic.readers(), 1);

    // Test that once the last instance is dropped that the reader is no longer
    // connected and that on_disconnect gets invoked.
    assert!(reader.connected());
    let invoked = Dynamic::new(false);
    reader.on_disconnect({
        let invoked = invoked.clone();
        move || {
            invoked.set(true);
        }
    });
    drop(dynamic);

    assert!(invoked.get());
    assert!(!reader.connected());
}

#[test]
fn linked_short_circuit() {
    let usize = Dynamic::new(0_usize);
    let string = usize.linked_string();

    string.map_ref(|s| assert_eq!(s, "0"));
    string.set(String::from("1"));
    assert_eq!(usize.get(), 1);
    usize.set(2);
    string.map_ref(|s| assert_eq!(s, "2"));
}

#[test]
fn graph_shortcircuit() {
    let a = Dynamic::new(0_usize);
    let doubled = a.map_each_cloned(|a| a * 2);
    let quadrupled = doubled.map_each_cloned(|a| a * 2);
    a.set_source(quadrupled.for_each_cloned({
        let a = a.clone();
        move |quad| a.set(quad / 4)
    }));

    assert_eq!(a.get(), 0);
    assert_eq!(quadrupled.get(), 0);
    a.set(1);
    assert_eq!(quadrupled.get(), 4);
    quadrupled.set(16);
    assert_eq!(a.get(), 4);
    assert_eq!(doubled.get(), 8);
}