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
//! Extendable, retained mode, graphics API agnostic UI library with lots (35+) of built-in widgets, HiDPI support,
//! rich layout system and many more.
//!
//! ## Basic Concepts
//!
//! FyroxUI is quite complex UI library and before using it, you should understand basic concepts of it. Especially,
//! if you're got used to immediate-mode UIs.
//!
//! ### Stateful
//!
//! **Stateful UI* means that we can create and destroy widgets when we need to, it is the opposite approach of
//! **immediate-mode** or **stateless UIs** when you don't have long-lasting state for your widgets
//! (usually stateless UI hold its state only for one or few frames).
//!
//! Stateful UI is much more powerful and flexible, it allows you to have complex layout system without having to
//! create hacks to create complex layout as you'd do in immediate-mode UIs. It is also much faster in terms of
//! performance. Stateful UI is a must for complex user interfaces that requires rich layout and high performance.
//!
//! ### Node-based architecture
//!
//! Every user interface could be represented as a set of small blocks that have hierarchical bonding between each
//! other. For example a button could be represented using two parts: a background and a foreground. Usually the background
//! is just a simple rectangle (either a vector or bitmap), and a foreground is a text. The text (the foreground widget)
//! is a child object of the rectangle (the background widget). These two widgets forms another, more complex widget that
//! we call button.
//!
//! Such approach allows us to modify the look of the button as we wish, we can create a button with image background,
//! or with any vector image, or even other widgets. The foreground can be anything too, it can also contain its own
//! complex hierarchy, like a pair of an icon with a text and so on.
//!
//! ### Composition
//!
//! Every widget in the engine uses composition to build more complex widgets. All widgets (and respective builders) contains
//! `Widget` instance inside, it provides basic functionality the widget such as layout information, hierarchy, default
//! foreground and background brushes (their usage depends on derived widget), render and layout transform and so on.
//!
//! ### Message passing
//!
//! The engine uses message passing mechanism for UI logic. What does that mean? Let's see at the button from the
//! previous section and imagine we want to change its text. To do that we need to explicitly "tell" the button's text
//! widget to change its content to something new. This is done by sending a message to the widget.
//!
//! There is no "classic" callbacks to handle various types of messages, which may come from widgets. Instead, you should write
//! your own message dispatcher where you'll handle all messages. Why so? At first - decoupling, in this case business logic
//! is decoupled from the UI. You just receive messages one-by-one and do specific logic. The next reason is that any
//! callback would require context capturing which could be somewhat restrictive - since you need to share context with the
//! UI, it would force you to wrap it in `Rc<RefCell<..>>`/`Arc<Mutex<..>>`.
//!
//! ### Message routing strategies
//!
//! Message passing mechanism works in pair with various routing strategies that allows you to define how the message
//! will "travel" across the tree of nodes.
//!
//! 1. Bubble - a message starts its way from a widget and goes up on hierarchy until it reaches the root node of the hierarchy.
//! Nodes that lies outside that path won't receive the message. This is the most important message routing strategy, that
//! is used for **every** node by default.
//! 2. Direct - a message passed directly to every node that are capable to handle it. There is actual routing in this
//! case. Direct routing is used in rare cases when you need to catch a message outside its normal "bubble" route. It is **off**
//! by default for every widget, but can be enabled on per-widget instance basis.
//!
//! ## Widgets Overview
//!
//! The following subsections explains how to use every widget built into FyroxUI. We will order them by primary function to
//! help introduce them to new users.
//!
//! ### Containers
//!
//! The Container widgets primary purpose is to contain other widgets. They are mostly used as a tool to layout the UI in
//! visually different ways.
//!
//! * [`crate::stack_panel::StackPanel`]: The Stack Panel arranges widgets in a linear fashion, either vertically or horizontally
//! depending on how it's setup.
//! * [`crate::wrap_panel::WrapPanel`]: The Wrap Panel arranges widgets in a linear fashion but if it overflows the widgets are
//! continued adjacent to the first line. Can arrange widgets either vertically or horizontally depending on how it's setup.
//! * [`crate::grid::Grid`]: The Grid arranges widgets into rows and columns with given size constraints.
//! * [`crate::canvas::Canvas`]: The Canvas arranges widgets at their desired positions; it has infinite size and does not restrict
//! their children widgets position and size.
//! * [`crate::window::Window`]: The Window holds other widgets in a panel that can be configured at setup to be move-able,
//! expanded and contracted via user input, exited, and have a displayed label. The window has a title bar to assist with these
//! features.
//! * [`crate::messagebox::MessageBox`]: The Message Box is a Window that has been streamlined to show standard confirmation/information
//! dialogues, for example, closing a document with unsaved changes. It has a title, some text, and a fixed set of buttons (Yes, No,
//! Cancel in different combinations).
//! * [`crate::menu::Menu`]: The Menu is a root container for Menu Items, an example could be a menu strip with File, Edit, View, etc
//! items.
//! * [`crate::popup::Popup`]: The Popup is a panel that locks input to its content while it is open. A simple example of it could be a
//! context menu.
//! * [`crate::scroll_viewer::ScrollViewer`]: The ScrollViewer is a wrapper for Scroll Panel that adds two scroll bars to it.
//! * [`crate::scroll_panel::ScrollPanel`]: The Scroll Panel is a panel that allows you apply some offset to children widgets. It
//! is used to create "scrollable" area in conjunction with the Scroll Viewer.
//! * [`crate::expander::Expander`]: The Expander handles hiding and showing multiple panels of widgets in an according style UI element.
//! Multiple panels can be shown or hidden at any time based on user input.
//! * [`crate::tab_control::TabControl`]: The Tab Control handles hiding several panels of widgets, only showing the one that the user
//! has selected.
//! * [`crate::dock::DockingManager`]: The Docking manager allows you to dock windows and hold them in-place.
//! * [`crate::tree::Tree`]: The Tree allows you to create views for hierarchical data.
//! * [`crate::screen::Screen`]: The Screen widgets always has its bounds match the current screen size
//! thus making it possible to create widget hierarchy that always fits the screen bounds.
//!
//!
//! ### Visual
//!
//! The Visual widgets primary purpose is to provide the user feedback generally without the user directly interacting with them.
//!
//! * [`crate::text::Text`]: The Text widget is used to display a string to the user.
//! * [`crate::image::Image`]: The Image widget is used to display a pixel image to the user.
//! * [`crate::vector_image::VectorImage`]: The Vector Image is used to render vector instructions as a graphical element.
//! * [`crate::rect::RectEditor`]: The Rect allows you to specify numeric values for X, Y, Width, and Height of a rectangle.
//! * [`crate::progress_bar::ProgressBar`]: The Progress Bar shows a bar whose fill state can be adjusted to indicate visually how full
//! something is, for example how close to 100% is a loading process.
//! * [`crate::decorator::Decorator`]: The Decorator is used to style any widget. It has support for different styles depending on various
//! events like mouse hover or click.
//! * [`crate::border::Border`]: The Border widget is used in conjunction with the Decorator widget to provide configurable boarders to
//! any widget for styling purposes.
//!
//! ### Controls
//!
//! Control widgets primary purpose is to provide users with intractable UI elements to control some aspect of the program.
//!
//! * [`crate::border::Border`]: The Button provides a press-able control that can contain other UI elements, for example a Text
//! or Image Widget.
//! * [`crate::check_box::CheckBox`]: The Check Box is a toggle-able control that can contain other UI elements, for example a Text
//! or Image Widget.
//! * [`crate::text_box::TextBox`]: The Text Box is a control that allows the editing of text.
//! * [`crate::scroll_bar::ScrollBar`]: The Scroll Bar provides a scroll bar like control that can be used on it's own as a data input or with
//! certain other widgets to provide content scrolling capabilities.
//! * [`crate::numeric::NumericUpDown`]: The Numeric Field provides the ability to adjust a number via increment and decrement buttons or direct
//! input. The number can be constrained to remain inside a specific range or have a specific step.
//! * [`crate::range::RangeEditor`]: The Range allows the user to edit a numeric range - specify its begin and end values.
//! * [`crate::list_view::ListView`]: The List View provides a control where users can select from a list of items.
//! * [`crate::dropdown_list::DropdownList`]: The Drop-down List is a control which shows the currently selected item and provides a drop-down
//! list to select an item.
//! * [`crate::file_browser::FileBrowser`]: The File Browser is a tree view of the file system allowing the user to select a file or folder.
//! * [`crate::curve::CurveEditor`]: The CurveEditor allows editing parametric curves - adding points, and setting up transitions (constant,
//! linear, cubic) between them.
//! * [`crate::inspector::Inspector`]: The Inspector automatically creates and handles the input of UI elements based on a populated Inspector
//! Context given to it allowing the user to adjust values of a variety of models without manually creating UI's for each type.
//!
//! ## Examples
//!
//! A simple usage example could be the following code:
//!
//! ```rust
//! use fyrox_ui::{
//!     button::{ButtonBuilder, ButtonMessage},
//!     core::algebra::Vector2,
//!     widget::WidgetBuilder,
//!     UserInterface,
//! };
//!
//! // Create the UI first.
//! let mut ui = UserInterface::new(Vector2::new(1024.0, 768.0));
//!
//! // Add some widgets.
//! let button = ButtonBuilder::new(WidgetBuilder::new())
//!     .with_text("Click Me!")
//!     .build(&mut ui.build_ctx());
//!
//! // Poll the messages coming from the widgets and react to them.
//! while let Some(message) = ui.poll_message() {
//!     if let Some(ButtonMessage::Click) = message.data() {
//!         if message.destination() == button {
//!             println!("The button was clicked!");
//!         }
//!     }
//! }
//! ```
//!
//! **Important**: This example **does not** include any drawing or OS event processing! It is because this
//! crate is OS- and GAPI-agnostic and do not create native OS windows and cannot draw anything on screen.
//! For more specific examples, please see `examples` of the crate.

#![forbid(unsafe_code)]
#![allow(irrefutable_let_patterns)]
#![allow(clippy::float_cmp)]
#![allow(clippy::upper_case_acronyms)]
#![allow(clippy::from_over_into)]
#![allow(clippy::new_without_default)]
#![allow(clippy::too_many_arguments)]
#![allow(clippy::type_complexity)]

pub use copypasta;
pub use fyrox_core as core;
use message::TouchPhase;

mod alignment;
pub mod bit;
pub mod border;
pub mod brush;
mod build;
pub mod button;
pub mod canvas;
pub mod check_box;
pub mod color;
mod control;
pub mod curve;
pub mod decorator;
pub mod dock;
pub mod draw;
pub mod dropdown_list;
pub mod expander;
pub mod file_browser;
pub mod font;
pub mod formatted_text;
pub mod grid;
pub mod image;
pub mod inspector;
pub mod key;
pub mod list_view;
pub mod loader;
pub mod menu;
pub mod message;
pub mod messagebox;
pub mod nine_patch;
mod node;
pub mod numeric;
pub mod path;
pub mod popup;
pub mod progress_bar;
pub mod range;
pub mod rect;
pub mod screen;
pub mod scroll_bar;
pub mod scroll_panel;
pub mod scroll_viewer;
pub mod searchbar;
pub mod stack_panel;
pub mod tab_control;
pub mod text;
pub mod text_box;
mod thickness;
pub mod tree;
pub mod utils;
pub mod uuid;
pub mod vec;
pub mod vector_image;
pub mod widget;
pub mod window;
pub mod wrap_panel;

use crate::{
    brush::Brush,
    canvas::Canvas,
    constructor::WidgetConstructorContainer,
    container::WidgetContainer,
    core::{
        algebra::{Matrix3, Vector2},
        color::Color,
        math::Rect,
        pool::{Handle, Pool},
        reflect::prelude::*,
        scope_profile,
        visitor::prelude::*,
    },
    core::{parking_lot::Mutex, pool::Ticket, uuid::Uuid, uuid_provider, TypeUuidProvider},
    draw::{CommandTexture, Draw, DrawingContext},
    font::FontResource,
    font::BUILT_IN_FONT,
    message::{
        ButtonState, CursorIcon, KeyboardModifiers, MessageDirection, MouseButton, OsEvent,
        UiMessage,
    },
    popup::{Placement, PopupMessage},
    widget::{Widget, WidgetBuilder, WidgetMessage},
};
use copypasta::ClipboardContext;
use fxhash::{FxHashMap, FxHashSet};
use fyrox_resource::{io::ResourceIo, manager::ResourceManager, ResourceData};
use serde::{Deserialize, Serialize};
use std::{
    any::Any,
    cell::{Cell, Ref, RefCell, RefMut},
    collections::{btree_set::BTreeSet, hash_map::Entry, VecDeque},
    error::Error,
    fmt::{Debug, Formatter},
    ops::DerefMut,
    path::Path,
    sync::{
        mpsc::{self, Receiver, Sender, TryRecvError},
        Arc,
    },
};
use strum_macros::{AsRefStr, EnumString, EnumVariantNames};

pub use alignment::*;
pub use build::*;
pub use control::*;
use fyrox_resource::io::FsResourceIo;
pub use node::*;
pub use thickness::*;

// TODO: Make this part of UserInterface struct.
pub const COLOR_COAL_BLACK: Color = Color::opaque(10, 10, 10);
pub const COLOR_DARKEST: Color = Color::opaque(20, 20, 20);
pub const COLOR_DARKER: Color = Color::opaque(30, 30, 30);
pub const COLOR_DARK: Color = Color::opaque(40, 40, 40);
pub const COLOR_PRIMARY: Color = Color::opaque(50, 50, 50);
pub const COLOR_LIGHT: Color = Color::opaque(70, 70, 70);
pub const COLOR_LIGHTER: Color = Color::opaque(85, 85, 85);
pub const COLOR_LIGHTEST: Color = Color::opaque(100, 100, 100);
pub const COLOR_BRIGHT: Color = Color::opaque(130, 130, 130);
pub const COLOR_BRIGHT_BLUE: Color = Color::opaque(80, 118, 178);
pub const COLOR_TEXT: Color = Color::opaque(220, 220, 220);
pub const COLOR_FOREGROUND: Color = Color::WHITE;

pub const BRUSH_COAL_BLACK: Brush = Brush::Solid(COLOR_COAL_BLACK);
pub const BRUSH_DARKEST: Brush = Brush::Solid(COLOR_DARKEST);
pub const BRUSH_DARKER: Brush = Brush::Solid(COLOR_DARKER);
pub const BRUSH_DARK: Brush = Brush::Solid(COLOR_DARK);
pub const BRUSH_PRIMARY: Brush = Brush::Solid(COLOR_PRIMARY);
pub const BRUSH_LIGHT: Brush = Brush::Solid(COLOR_LIGHT);
pub const BRUSH_LIGHTER: Brush = Brush::Solid(COLOR_LIGHTER);
pub const BRUSH_LIGHTEST: Brush = Brush::Solid(COLOR_LIGHTEST);
pub const BRUSH_BRIGHT: Brush = Brush::Solid(COLOR_BRIGHT);
pub const BRUSH_BRIGHT_BLUE: Brush = Brush::Solid(COLOR_BRIGHT_BLUE);
pub const BRUSH_TEXT: Brush = Brush::Solid(COLOR_TEXT);
pub const BRUSH_FOREGROUND: Brush = Brush::Solid(COLOR_FOREGROUND);

#[derive(Default, Reflect, Debug)]
struct RcUiNodeHandleInner {
    handle: Handle<UiNode>,
    #[reflect(hidden)]
    sender: Option<Sender<UiMessage>>,
}

impl Visit for RcUiNodeHandleInner {
    fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
        self.handle.visit(name, visitor)?;

        if visitor.is_reading() {
            self.sender = Some(
                visitor
                    .blackboard
                    .get::<Sender<UiMessage>>()
                    .expect("Ui message sender must be provided for correct deserialization!")
                    .clone(),
            );
        }

        Ok(())
    }
}

impl Drop for RcUiNodeHandleInner {
    fn drop(&mut self) {
        let _ = self
            .sender
            .as_ref()
            .expect("Sender must be set!")
            .send(WidgetMessage::remove(
                self.handle,
                MessageDirection::ToWidget,
            ));
    }
}

/// Reference counted handle to a widget. It is used to automatically destroy the widget it points
/// to when the reference counter reaches zero. It's main usage in the library is to store handles
/// to context menus, that could be shared across multiple widgets.
#[derive(Clone, Default, Visit, Reflect)]
pub struct RcUiNodeHandle(Arc<Mutex<RcUiNodeHandleInner>>);

impl Debug for RcUiNodeHandle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        writeln!(
            f,
            "RcUiNodeHandle - {}:{} with {} uses",
            self.0.lock().handle.index(),
            self.0.lock().handle.generation(),
            Arc::strong_count(&self.0)
        )
    }
}

impl PartialEq for RcUiNodeHandle {
    fn eq(&self, other: &Self) -> bool {
        let a = self.0.lock().handle;
        let b = other.0.lock().handle;
        a == b
    }
}

impl RcUiNodeHandle {
    /// Creates a new reference counted widget handle.
    #[inline]
    pub fn new(handle: Handle<UiNode>, sender: Sender<UiMessage>) -> Self {
        Self(Arc::new(Mutex::new(RcUiNodeHandleInner {
            handle,
            sender: Some(sender),
        })))
    }

    /// Returns the inner handle.
    #[inline]
    pub fn handle(&self) -> Handle<UiNode> {
        self.0.lock().handle
    }
}

/// Orientation of something.
#[derive(
    Copy,
    Clone,
    Debug,
    PartialEq,
    Eq,
    Visit,
    Reflect,
    Default,
    Serialize,
    Deserialize,
    AsRefStr,
    EnumString,
    EnumVariantNames,
)]
pub enum Orientation {
    /// Vertical orientation. This is default value.
    #[default]
    Vertical,
    /// Horizontal orientation.
    Horizontal,
}

uuid_provider!(Orientation = "1c6ad1b0-3f4c-48be-87dd-6929cb3577bf");

type NodeHandle = Handle<UiNode>;

/// Node handle mapping is used to map handles when copying an arbitrary hierarchy of widgets. This
/// is needed, because internally, widgets could contain handles to some other widgets which must
/// point to their respective copies when a widget hierarchy was copied.
#[derive(Default)]
pub struct NodeHandleMapping {
    /// Internal old-handle-to-new-handle mapping.
    pub hash_map: FxHashMap<NodeHandle, NodeHandle>,
}

impl NodeHandleMapping {
    /// Adds new old -> new mapping.
    pub fn add_mapping(&mut self, old: Handle<UiNode>, new: Handle<UiNode>) {
        self.hash_map.insert(old, new);
    }

    /// Tries to fetch new handle of a node using its old handle.
    pub fn resolve(&self, old: &mut Handle<UiNode>) {
        // None handles aren't mapped.
        if old.is_some() {
            if let Some(clone) = self.hash_map.get(old) {
                *old = *clone;
            }
        }
    }

    /// The same as [`Self::resolve`], but for case when a handle is wrapped into [`Cell`].
    pub fn resolve_cell(&self, old: &mut Cell<Handle<UiNode>>) {
        // None handles aren't mapped.
        if Cell::get(old).is_some() {
            if let Some(clone) = self.hash_map.get(&old.get()) {
                Cell::set(old, *clone)
            }
        }
    }

    /// The same as [`Self::resolve`], but for case when you have a slice of handles.
    pub fn resolve_slice(&self, slice: &mut [Handle<UiNode>]) {
        for item in slice {
            self.resolve(item);
        }
    }
}

#[derive(Default, Clone)]
pub struct NodeStatistics(pub FxHashMap<&'static str, isize>);

impl NodeStatistics {
    pub fn new(ui: &UserInterface) -> NodeStatistics {
        let mut statistics = Self::default();
        for node in ui.nodes.iter() {
            statistics
                .0
                .entry(BaseControl::type_name(&*node.0))
                .and_modify(|counter| *counter += 1)
                .or_insert(1);
        }
        statistics
    }

    fn unite_type_names(&self, prev_stats: &NodeStatistics) -> BTreeSet<&'static str> {
        let mut union = BTreeSet::default();
        for stats in [self, prev_stats] {
            for &type_name in stats.0.keys() {
                union.insert(type_name);
            }
        }
        union
    }

    fn count_of(&self, type_name: &str) -> isize {
        self.0.get(type_name).cloned().unwrap_or_default()
    }

    pub fn print_diff(&self, prev_stats: &NodeStatistics, show_unchanged: bool) {
        println!("**** Diff UI Node Statistics ****");
        for type_name in self.unite_type_names(prev_stats) {
            let count = self.count_of(type_name);
            let prev_count = prev_stats.count_of(type_name);
            let delta = count - prev_count;
            if delta != 0 || show_unchanged {
                println!("{}: \x1b[93m{}\x1b[0m", type_name, delta);
            }
        }
    }

    pub fn print_changed(&self, prev_stats: &NodeStatistics) {
        println!("**** Changed UI Node Statistics ****");
        for type_name in self.unite_type_names(prev_stats) {
            let count = self.count_of(type_name);
            let prev_count = prev_stats.count_of(type_name);
            if count - prev_count != 0 {
                println!("{}: \x1b[93m{}\x1b[0m", type_name, count);
            }
        }
    }
}

#[derive(Visit, Reflect, Debug, Clone)]
pub struct DragContext {
    pub is_dragging: bool,
    pub drag_node: Handle<UiNode>,
    pub click_pos: Vector2<f32>,
    pub drag_preview: Handle<UiNode>,
}

impl Default for DragContext {
    fn default() -> Self {
        Self {
            is_dragging: false,
            drag_node: Default::default(),
            click_pos: Vector2::new(0.0, 0.0),
            drag_preview: Default::default(),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Visit, Reflect)]
pub struct MouseState {
    pub left: ButtonState,
    pub right: ButtonState,
    pub middle: ButtonState,
    // TODO Add rest of buttons
}

impl Default for MouseState {
    fn default() -> Self {
        Self {
            left: ButtonState::Released,
            right: ButtonState::Released,
            middle: ButtonState::Released,
        }
    }
}

#[derive(Copy, Clone, Visit, Reflect, Debug, Default)]
pub struct RestrictionEntry {
    /// Handle to UI node to which picking must be restricted to.
    pub handle: Handle<UiNode>,

    /// A flag that tells UI to stop iterating over picking stack.
    /// There are two use cases: chain of menus (popups) and set of modal windows. In case of
    /// menus you need to restrict picking to an entire chain, but leave possibility to select
    /// any menu in the chain. In case of multiple modal windows you need to restrict picking
    /// individually per window, not allowing to pick anything behind modal window, but still
    /// save restrictions in the entire chain of modal windows so if topmost closes, restriction
    /// will be on previous one and so on.
    pub stop: bool,
}

#[derive(Clone, Debug)]
struct TooltipEntry {
    tooltip: RcUiNodeHandle,
    /// Time remaining until this entry should disappear (in seconds).
    time: f32,
    /// Maximum time that it should be kept for
    /// This is stored here as well, because when hovering
    /// over the tooltip, we don't know the time it should stay for and
    /// so we use this to refresh the timer.
    max_time: f32,
}
impl TooltipEntry {
    fn new(tooltip: RcUiNodeHandle, time: f32) -> TooltipEntry {
        Self {
            tooltip,
            time,
            max_time: time,
        }
    }

    fn decrease(&mut self, amount: f32) {
        self.time -= amount;
    }

    fn should_display(&self) -> bool {
        self.time > 0.0
    }
}

#[derive(Debug)]
pub enum LayoutEvent {
    MeasurementInvalidated(Handle<UiNode>),
    ArrangementInvalidated(Handle<UiNode>),
    VisibilityChanged(Handle<UiNode>),
}

#[derive(Clone, Debug, Visit, Reflect, Default)]
struct DoubleClickEntry {
    timer: f32,
    click_count: u32,
}

struct Clipboard(Option<RefCell<ClipboardContext>>);

impl Debug for Clipboard {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Clipboard")
    }
}

#[derive(Visit, Reflect, Debug)]
pub struct UserInterface {
    screen_size: Vector2<f32>,
    nodes: Pool<UiNode, WidgetContainer>,
    #[visit(skip)]
    #[reflect(hidden)]
    drawing_context: DrawingContext,
    visual_debug: bool,
    root_canvas: Handle<UiNode>,
    picked_node: Handle<UiNode>,
    prev_picked_node: Handle<UiNode>,
    captured_node: Handle<UiNode>,
    keyboard_focus_node: Handle<UiNode>,
    cursor_position: Vector2<f32>,
    #[visit(skip)]
    #[reflect(hidden)]
    receiver: Receiver<UiMessage>,
    #[visit(skip)]
    #[reflect(hidden)]
    sender: Sender<UiMessage>,
    stack: Vec<Handle<UiNode>>,
    picking_stack: Vec<RestrictionEntry>,
    #[visit(skip)]
    #[reflect(hidden)]
    bubble_queue: VecDeque<Handle<UiNode>>,
    drag_context: DragContext,
    mouse_state: MouseState,
    keyboard_modifiers: KeyboardModifiers,
    cursor_icon: CursorIcon,
    #[visit(skip)]
    #[reflect(hidden)]
    active_tooltip: Option<TooltipEntry>,
    #[visit(skip)]
    #[reflect(hidden)]
    preview_set: FxHashSet<Handle<UiNode>>,
    #[visit(skip)]
    #[reflect(hidden)]
    clipboard: Clipboard,
    #[visit(skip)]
    #[reflect(hidden)]
    layout_events_receiver: Receiver<LayoutEvent>,
    #[visit(skip)]
    #[reflect(hidden)]
    layout_events_sender: Sender<LayoutEvent>,
    #[visit(skip)]
    need_update_global_transform: bool,
    #[visit(skip)]
    #[reflect(hidden)]
    pub default_font: FontResource,
    #[visit(skip)]
    #[reflect(hidden)]
    double_click_entries: FxHashMap<MouseButton, DoubleClickEntry>,
    pub double_click_time_slice: f32,
}

impl Clone for UserInterface {
    fn clone(&self) -> Self {
        let (sender, receiver) = mpsc::channel();
        let (layout_events_sender, layout_events_receiver) = mpsc::channel();
        let mut nodes = Pool::new();
        for (handle, node) in self.nodes.pair_iter() {
            let mut clone = node.clone_boxed();
            clone.layout_events_sender = Some(layout_events_sender.clone());
            nodes.spawn_at_handle(handle, UiNode(clone)).unwrap();
        }

        Self {
            screen_size: self.screen_size,
            nodes,
            drawing_context: self.drawing_context.clone(),
            visual_debug: self.visual_debug,
            root_canvas: self.root_canvas,
            picked_node: self.picked_node,
            prev_picked_node: self.prev_picked_node,
            captured_node: self.captured_node,
            keyboard_focus_node: self.keyboard_focus_node,
            cursor_position: self.cursor_position,
            receiver,
            sender,
            stack: self.stack.clone(),
            picking_stack: self.picking_stack.clone(),
            bubble_queue: self.bubble_queue.clone(),
            drag_context: self.drag_context.clone(),
            mouse_state: self.mouse_state,
            keyboard_modifiers: self.keyboard_modifiers,
            cursor_icon: self.cursor_icon,
            active_tooltip: self.active_tooltip.clone(),
            preview_set: self.preview_set.clone(),
            clipboard: Clipboard(ClipboardContext::new().ok().map(RefCell::new)),
            layout_events_receiver,
            layout_events_sender,
            need_update_global_transform: self.need_update_global_transform,
            default_font: self.default_font.clone(),
            double_click_entries: self.double_click_entries.clone(),
            double_click_time_slice: self.double_click_time_slice,
        }
    }
}

impl Default for UserInterface {
    fn default() -> Self {
        Self::new(Vector2::new(100.0, 100.0))
    }
}

fn is_on_screen(node: &UiNode, nodes: &Pool<UiNode, WidgetContainer>) -> bool {
    // Crawl up on tree and check if current bounds are intersects with every screen bound
    // of parents chain. This is needed because some control can move their children outside of
    // their bounds (like scroll viewer, etc.) and single intersection test of parent bounds with
    // current bounds is not enough.
    let bounds = node.clip_bounds();
    let mut parent = node.parent();
    while parent.is_some() {
        let parent_node = nodes.borrow(parent);
        if !parent_node.clip_bounds().intersects(bounds) {
            return false;
        }
        parent = parent_node.parent();
    }
    true
}

fn draw_node(
    nodes: &Pool<UiNode, WidgetContainer>,
    node_handle: Handle<UiNode>,
    drawing_context: &mut DrawingContext,
) {
    scope_profile!();

    let node = &nodes[node_handle];
    if !node.is_globally_visible() {
        return;
    }

    if !is_on_screen(node, nodes) {
        return;
    }

    let start_index = drawing_context.get_commands().len();

    let pushed = if !is_node_enabled(nodes, node_handle) {
        drawing_context.push_opacity(0.4);
        true
    } else if let Some(opacity) = node.opacity() {
        drawing_context.push_opacity(opacity);
        true
    } else {
        false
    };

    drawing_context.transform_stack.push(node.visual_transform);

    node.draw(drawing_context);

    let end_index = drawing_context.get_commands().len();
    for i in start_index..end_index {
        node.command_indices.borrow_mut().push(i);
    }

    // Continue on children
    for &child_node in node.children().iter() {
        // Do not continue render of top-most nodes - they'll be rendered in separate pass.
        if !nodes[child_node].is_draw_on_top() {
            draw_node(nodes, child_node, drawing_context);
        }
    }

    drawing_context.transform_stack.pop();

    if pushed {
        drawing_context.pop_opacity();
    }
}

fn is_node_enabled(nodes: &Pool<UiNode, WidgetContainer>, handle: Handle<UiNode>) -> bool {
    let root_node = &nodes[handle];
    let mut enabled = root_node.enabled();
    let mut parent = root_node.parent();
    while parent.is_some() {
        let node = &nodes[parent];
        if !node.enabled() {
            enabled = false;
            break;
        }
        parent = node.parent();
    }
    enabled
}

#[derive(Debug)]
pub struct SubGraph {
    pub root: (Ticket<UiNode>, UiNode),

    pub descendants: Vec<(Ticket<UiNode>, UiNode)>,

    pub parent: Handle<UiNode>,
}

impl UserInterface {
    pub fn new(screen_size: Vector2<f32>) -> UserInterface {
        let (sender, receiver) = mpsc::channel();
        Self::new_with_channel(sender, receiver, screen_size)
    }

    pub fn new_with_channel(
        sender: Sender<UiMessage>,
        receiver: Receiver<UiMessage>,
        screen_size: Vector2<f32>,
    ) -> UserInterface {
        let (layout_events_sender, layout_events_receiver) = mpsc::channel();
        let mut ui = UserInterface {
            screen_size,
            sender,
            receiver,
            visual_debug: false,
            captured_node: Handle::NONE,
            root_canvas: Handle::NONE,
            nodes: Pool::new(),
            cursor_position: Vector2::new(0.0, 0.0),
            drawing_context: DrawingContext::new(),
            picked_node: Handle::NONE,
            prev_picked_node: Handle::NONE,
            keyboard_focus_node: Handle::NONE,
            stack: Default::default(),
            picking_stack: Default::default(),
            bubble_queue: Default::default(),
            drag_context: Default::default(),
            mouse_state: Default::default(),
            keyboard_modifiers: Default::default(),
            cursor_icon: Default::default(),
            active_tooltip: Default::default(),
            preview_set: Default::default(),
            clipboard: Clipboard(ClipboardContext::new().ok().map(RefCell::new)),
            layout_events_receiver,
            layout_events_sender,
            need_update_global_transform: Default::default(),
            default_font: BUILT_IN_FONT.clone(),
            double_click_entries: Default::default(),
            double_click_time_slice: 0.5, // 500 ms is standard in most operating systems.
        };
        ui.root_canvas = ui.add_node(UiNode::new(Canvas {
            widget: WidgetBuilder::new().build(),
        }));
        ui.keyboard_focus_node = ui.root_canvas;
        ui
    }

    pub fn keyboard_modifiers(&self) -> KeyboardModifiers {
        self.keyboard_modifiers
    }

    pub fn build_ctx(&mut self) -> BuildContext<'_> {
        self.into()
    }

    #[inline]
    pub fn capture_mouse(&mut self, node: Handle<UiNode>) -> bool {
        if self.captured_node.is_none() {
            self.captured_node = node;
            true
        } else {
            false
        }
    }

    #[inline]
    pub fn release_mouse_capture(&mut self) {
        self.captured_node = Handle::NONE;
    }

    #[inline]
    pub fn get_drawing_context(&self) -> &DrawingContext {
        &self.drawing_context
    }

    #[inline]
    pub fn get_drawing_context_mut(&mut self) -> &mut DrawingContext {
        &mut self.drawing_context
    }

    pub fn is_node_enabled(&self, handle: Handle<UiNode>) -> bool {
        is_node_enabled(&self.nodes, handle)
    }

    fn update_global_visibility(&mut self, from: Handle<UiNode>) {
        scope_profile!();

        self.stack.clear();
        self.stack.push(from);
        while let Some(node_handle) = self.stack.pop() {
            let (widget, parent) = self
                .nodes
                .try_borrow_dependant_mut(node_handle, |n| n.parent());

            if let Some(widget) = widget {
                self.stack.extend_from_slice(widget.children());

                let visibility = if let Some(parent) = parent {
                    widget.visibility() && parent.is_globally_visible()
                } else {
                    widget.visibility()
                };

                if widget.prev_global_visibility != visibility {
                    let _ = self
                        .layout_events_sender
                        .send(LayoutEvent::MeasurementInvalidated(node_handle));
                    let _ = self
                        .layout_events_sender
                        .send(LayoutEvent::ArrangementInvalidated(node_handle));
                }

                widget.set_global_visibility(visibility);
            }
        }
    }

    fn update_visual_transform(&mut self) {
        scope_profile!();

        self.stack.clear();
        self.stack.push(self.root_canvas);
        while let Some(node_handle) = self.stack.pop() {
            let (widget, parent) = self
                .nodes
                .try_borrow_dependant_mut(node_handle, |n| n.parent());

            let widget = widget.unwrap();

            if widget.is_globally_visible() {
                self.stack.extend_from_slice(widget.children());

                let mut layout_transform = widget.layout_transform;

                layout_transform[6] = widget.actual_local_position().x;
                layout_transform[7] = widget.actual_local_position().y;

                let visual_transform = if let Some(parent) = parent {
                    parent.visual_transform * widget.render_transform * layout_transform
                } else {
                    widget.render_transform * layout_transform
                };

                widget.visual_transform = visual_transform;
            }
        }
    }

    pub fn screen_size(&self) -> Vector2<f32> {
        self.screen_size
    }

    pub fn set_screen_size(&mut self, screen_size: Vector2<f32>) {
        self.screen_size = screen_size;
    }

    fn handle_layout_events(&mut self) {
        fn invalidate_recursive_up(
            nodes: &Pool<UiNode, WidgetContainer>,
            node: Handle<UiNode>,
            callback: fn(&UiNode),
        ) {
            if let Some(node_ref) = nodes.try_borrow(node) {
                (callback)(node_ref);
                if node_ref.parent().is_some() {
                    invalidate_recursive_up(nodes, node_ref.parent(), callback);
                }
            }
        }

        while let Ok(layout_event) = self.layout_events_receiver.try_recv() {
            match layout_event {
                LayoutEvent::MeasurementInvalidated(node) => {
                    invalidate_recursive_up(&self.nodes, node, |node_ref| {
                        node_ref.measure_valid.set(false)
                    });
                }
                LayoutEvent::ArrangementInvalidated(node) => {
                    invalidate_recursive_up(&self.nodes, node, |node_ref| {
                        node_ref.arrange_valid.set(false)
                    });
                    self.need_update_global_transform = true;
                }
                LayoutEvent::VisibilityChanged(node) => {
                    self.update_global_visibility(node);
                }
            }
        }
    }

    pub fn invalidate_layout(&mut self) {
        for node in self.nodes.iter_mut() {
            node.invalidate_layout();
        }
    }

    pub fn update(&mut self, screen_size: Vector2<f32>, dt: f32) {
        scope_profile!();

        self.screen_size = screen_size;

        for entry in self.double_click_entries.values_mut() {
            entry.timer -= dt;
        }

        self.handle_layout_events();

        self.measure_node(self.root_canvas, screen_size);
        let arrangement_changed = self.arrange_node(
            self.root_canvas,
            &Rect::new(0.0, 0.0, screen_size.x, screen_size.y),
        );

        if self.need_update_global_transform {
            self.update_visual_transform();
            self.need_update_global_transform = false;
        }

        if arrangement_changed {
            self.calculate_clip_bounds(
                self.root_canvas,
                Rect::new(0.0, 0.0, self.screen_size.x, self.screen_size.y),
            );
        }

        let sender = self.sender.clone();
        for node in self.nodes.iter_mut() {
            node.update(dt, &sender, self.screen_size)
        }

        self.update_tooltips(dt);

        if !self.drag_context.is_dragging {
            // Try to fetch new cursor icon starting from current picked node. Traverse
            // tree up until cursor with different value is found.
            self.cursor_icon = CursorIcon::default();
            let mut handle = self.picked_node;
            while handle.is_some() {
                let node = &self.nodes[handle];
                if let Some(cursor) = node.cursor() {
                    self.cursor_icon = cursor;
                    break;
                }
                handle = node.parent();
            }
        }
    }

    pub fn cursor(&self) -> CursorIcon {
        self.cursor_icon
    }

    pub fn draw(&mut self) -> &DrawingContext {
        scope_profile!();

        self.drawing_context.clear();

        for node in self.nodes.iter_mut() {
            node.command_indices.get_mut().clear();
        }

        // Draw everything except top-most nodes.
        draw_node(&self.nodes, self.root_canvas, &mut self.drawing_context);

        // Render top-most nodes in separate pass.
        // TODO: This may give weird results because of invalid nesting.
        self.stack.clear();
        self.stack.push(self.root());
        while let Some(node_handle) = self.stack.pop() {
            let node = &self.nodes[node_handle];

            if !is_on_screen(node, &self.nodes) {
                continue;
            }

            if node.is_draw_on_top() {
                draw_node(&self.nodes, node_handle, &mut self.drawing_context);
            }
            for &child in node.children() {
                self.stack.push(child);
            }
        }

        // Debug info rendered on top of other.
        if self.visual_debug {
            if self.picked_node.is_some() {
                let bounds = self.nodes.borrow(self.picked_node).screen_bounds();
                self.drawing_context.push_rect(&bounds, 1.0);
                self.drawing_context.commit(
                    bounds,
                    Brush::Solid(Color::WHITE),
                    CommandTexture::None,
                    None,
                );
            }

            if self.keyboard_focus_node.is_some() {
                let bounds = self.nodes.borrow(self.keyboard_focus_node).screen_bounds();
                self.drawing_context.push_rect(&bounds, 1.0);
                self.drawing_context.commit(
                    bounds,
                    Brush::Solid(Color::GREEN),
                    CommandTexture::None,
                    None,
                );
            }
        }

        &self.drawing_context
    }

    pub fn clipboard(&self) -> Option<Ref<ClipboardContext>> {
        self.clipboard.0.as_ref().map(|v| v.borrow())
    }

    pub fn clipboard_mut(&self) -> Option<RefMut<ClipboardContext>> {
        self.clipboard.0.as_ref().map(|v| v.borrow_mut())
    }

    pub fn arrange_node(&self, handle: Handle<UiNode>, final_rect: &Rect<f32>) -> bool {
        scope_profile!();

        let node = self.node(handle);

        if node.is_arrange_valid() && node.prev_arrange.get() == *final_rect {
            return false;
        }

        if node.visibility() {
            node.prev_arrange.set(*final_rect);

            let margin = node.margin().axes_margin();

            let mut size = Vector2::new(
                (final_rect.w() - margin.x).max(0.0),
                (final_rect.h() - margin.y).max(0.0),
            );

            let available_size = size;

            if node.horizontal_alignment() != HorizontalAlignment::Stretch {
                size.x = size.x.min(node.desired_size().x - margin.x);
            }
            if node.vertical_alignment() != VerticalAlignment::Stretch {
                size.y = size.y.min(node.desired_size().y - margin.y);
            }

            if node.width() > 0.0 {
                size.x = node.width();
            }
            if node.height() > 0.0 {
                size.y = node.height();
            }

            size = transform_size(size, &node.layout_transform);

            size = node.arrange_override(self, size);

            size.x = size.x.min(final_rect.w());
            size.y = size.y.min(final_rect.h());

            let transformed_rect =
                Rect::new(0.0, 0.0, size.x, size.y).transform(&node.layout_transform);

            size = transformed_rect.size;

            let mut origin =
                final_rect.position - transformed_rect.position + node.margin().offset();

            match node.horizontal_alignment() {
                HorizontalAlignment::Center | HorizontalAlignment::Stretch => {
                    origin.x += (available_size.x - size.x) * 0.5;
                }
                HorizontalAlignment::Right => origin.x += available_size.x - size.x,
                _ => (),
            }

            match node.vertical_alignment() {
                VerticalAlignment::Center | VerticalAlignment::Stretch => {
                    origin.y += (available_size.y - size.y) * 0.5;
                }
                VerticalAlignment::Bottom => origin.y += available_size.y - size.y,
                _ => (),
            }

            node.commit_arrange(origin, size);
        }

        true
    }

    pub fn measure_node(&self, handle: Handle<UiNode>, available_size: Vector2<f32>) -> bool {
        scope_profile!();

        let node = self.node(handle);

        if node.is_measure_valid() && node.prev_measure.get() == available_size {
            return false;
        }

        if node.visibility() {
            node.prev_measure.set(available_size);

            let axes_margin = node.margin().axes_margin();
            let mut inner_size = available_size - axes_margin;
            inner_size.x = inner_size.x.max(0.0);
            inner_size.y = inner_size.y.max(0.0);

            let mut size = Vector2::new(
                if node.width() > 0.0 {
                    node.width()
                } else {
                    inner_size.x
                },
                if node.height() > 0.0 {
                    node.height()
                } else {
                    inner_size.y
                },
            );

            size = transform_size(size, &node.layout_transform);

            size.x = size.x.clamp(node.min_size().x, node.max_size().x);
            size.y = size.y.clamp(node.min_size().y, node.max_size().y);

            let mut desired_size = node.measure_override(self, size);

            desired_size = Rect::new(0.0, 0.0, desired_size.x, desired_size.y)
                .transform(&node.layout_transform)
                .size;

            if !node.width().is_nan() {
                desired_size.x = node.width();
            }
            if !node.height().is_nan() {
                desired_size.y = node.height();
            }

            desired_size.x = desired_size.x.clamp(node.min_size().x, node.max_size().x);
            desired_size.y = desired_size.y.clamp(node.min_size().y, node.max_size().y);

            desired_size += axes_margin;

            desired_size.x = desired_size.x.min(available_size.x);
            desired_size.y = desired_size.y.min(available_size.y);

            node.commit_measure(desired_size);
        } else {
            node.commit_measure(Vector2::new(0.0, 0.0));
        }

        true
    }

    fn is_node_clipped(&self, node_handle: Handle<UiNode>, pt: Vector2<f32>) -> bool {
        scope_profile!();

        let mut clipped = true;

        let widget = self.nodes.borrow(node_handle);

        if widget.is_globally_visible() {
            clipped = !widget.clip_bounds().contains(pt);

            if !clipped {
                for command_index in widget.command_indices.borrow().iter() {
                    if let Some(command) = self.drawing_context.get_commands().get(*command_index) {
                        if let Some(geometry) = command.clipping_geometry.as_ref() {
                            if geometry.is_contains_point(pt) {
                                clipped = false;
                                break;
                            }
                        }
                    }
                }
            }

            // Point can be clipped by parent's clipping geometry.
            if !widget.parent().is_none() && !clipped {
                clipped |= self.is_node_clipped(widget.parent(), pt);
            }
        }

        clipped
    }

    fn is_node_contains_point(&self, node_handle: Handle<UiNode>, pt: Vector2<f32>) -> bool {
        scope_profile!();

        let widget = self.nodes.borrow(node_handle);

        if !widget.is_globally_visible() {
            return false;
        }

        if !self.is_node_clipped(node_handle, pt) {
            for command_index in widget.command_indices.borrow().iter() {
                if let Some(command) = self.drawing_context.get_commands().get(*command_index) {
                    if self.drawing_context.is_command_contains_point(command, pt) {
                        return true;
                    }
                }
            }
        }

        false
    }

    fn pick_node(
        &self,
        node_handle: Handle<UiNode>,
        pt: Vector2<f32>,
        level: &mut i32,
    ) -> Handle<UiNode> {
        scope_profile!();

        let widget = self.nodes.borrow(node_handle);

        if !widget.is_hit_test_visible()
            || !widget.enabled()
            || !widget.clip_bounds().intersects(Rect {
                position: Default::default(),
                size: self.screen_size,
            })
        {
            return Handle::NONE;
        }

        let (mut picked, mut topmost_picked_level) = if self.is_node_contains_point(node_handle, pt)
        {
            (node_handle, *level)
        } else {
            (Handle::NONE, 0)
        };

        for child_handle in widget.children() {
            *level += 1;
            let picked_child = self.pick_node(*child_handle, pt, level);
            if picked_child.is_some() && *level > topmost_picked_level {
                topmost_picked_level = *level;
                picked = picked_child;
            }
        }

        picked
    }

    pub fn cursor_position(&self) -> Vector2<f32> {
        self.cursor_position
    }

    pub fn hit_test_unrestricted(&self, pt: Vector2<f32>) -> Handle<UiNode> {
        // We're not restricted to any node, just start from root.
        let mut level = 0;
        self.pick_node(self.root_canvas, pt, &mut level)
    }

    pub fn hit_test(&self, pt: Vector2<f32>) -> Handle<UiNode> {
        scope_profile!();

        if self.nodes.is_valid_handle(self.captured_node) {
            self.captured_node
        } else if self.picking_stack.is_empty() {
            self.hit_test_unrestricted(pt)
        } else {
            // We have some picking restriction chain.
            // Go over picking stack and try each entry. This will help with picking
            // in a series of popups, especially in menus where may be many open popups
            // at the same time.
            for root in self.picking_stack.iter().rev() {
                if self.nodes.is_valid_handle(root.handle) {
                    let mut level = 0;
                    let picked = self.pick_node(root.handle, pt, &mut level);
                    if picked.is_some() {
                        return picked;
                    }
                }
                if root.stop {
                    break;
                }
            }
            Handle::NONE
        }
    }

    /// Searches a node down on tree starting from give root that matches a criteria
    /// defined by a given func.
    pub fn find_by_criteria_down<Func>(
        &self,
        node_handle: Handle<UiNode>,
        func: &Func,
    ) -> Handle<UiNode>
    where
        Func: Fn(&UiNode) -> bool,
    {
        if let Some(node) = self.nodes.try_borrow(node_handle) {
            if func(node) {
                return node_handle;
            }

            for child_handle in node.children() {
                let result = self.find_by_criteria_down(*child_handle, func);

                if result.is_some() {
                    return result;
                }
            }
        }

        Handle::NONE
    }

    /// Searches a node up on tree starting from given root that matches a criteria
    /// defined by a given func.
    pub fn find_by_criteria_up<Func>(
        &self,
        node_handle: Handle<UiNode>,
        func: Func,
    ) -> Handle<UiNode>
    where
        Func: Fn(&UiNode) -> bool,
    {
        if let Some(node) = self.nodes.try_borrow(node_handle) {
            if func(node) {
                return node_handle;
            }

            if node.parent().is_some() {
                return self.find_by_criteria_up(node.parent(), func);
            }
        }

        Handle::NONE
    }

    /// Checks if specified node is a child of some other node on `root_handle`. This method
    /// is useful to understand if some event came from some node down by tree.
    pub fn is_node_child_of(
        &self,
        node_handle: Handle<UiNode>,
        root_handle: Handle<UiNode>,
    ) -> bool {
        self.nodes
            .borrow(root_handle)
            .has_descendant(node_handle, self)
    }

    /// Recursively calculates clipping bounds for every node.
    fn calculate_clip_bounds(&self, node: Handle<UiNode>, parent_bounds: Rect<f32>) {
        let node = &self.nodes[node];

        let screen_bounds = if node.clip_to_bounds {
            node.screen_bounds()
        } else {
            Rect::new(0.0, 0.0, self.screen_size.x, self.screen_size.y)
        };

        node.clip_bounds.set(screen_bounds.clip_by(parent_bounds));

        for &child in node.children() {
            self.calculate_clip_bounds(child, node.clip_bounds.get());
        }
    }

    /// Checks if specified node is a direct child of some other node on `root_handle`.
    pub fn is_node_direct_child_of(
        &self,
        node_handle: Handle<UiNode>,
        root_handle: Handle<UiNode>,
    ) -> bool {
        for child_handle in self.nodes.borrow(root_handle).children() {
            if *child_handle == node_handle {
                return true;
            }
        }
        false
    }

    /// Searches a node by name up on tree starting from given root node.
    pub fn find_by_name_up(&self, node_handle: Handle<UiNode>, name: &str) -> Handle<UiNode> {
        self.find_by_criteria_up(node_handle, |node| node.name() == name)
    }

    /// Searches a node by name down on tree starting from given root node.
    pub fn find_by_name_down(&self, node_handle: Handle<UiNode>, name: &str) -> Handle<UiNode> {
        self.find_by_criteria_down(node_handle, &|node| node.name() == name)
    }

    /// Searches a node by name down on tree starting from root canvas.
    pub fn find_by_name_down_from_root(&self, name: &str) -> Handle<UiNode> {
        self.find_by_criteria_down(self.root_canvas, &|node| node.name() == name)
    }

    /// Searches a node by name up on tree starting from given root node and tries to borrow it if exists.
    pub fn borrow_by_name_up(&self, start_node_handle: Handle<UiNode>, name: &str) -> &UiNode {
        self.nodes
            .borrow(self.find_by_name_up(start_node_handle, name))
    }

    /// Searches a node by name down on tree starting from given root node and tries to borrow it if exists.
    pub fn borrow_by_name_down(&self, start_node_handle: Handle<UiNode>, name: &str) -> &UiNode {
        self.nodes
            .borrow(self.find_by_name_down(start_node_handle, name))
    }

    /// Searches for a node up on tree that satisfies some criteria and then borrows
    /// shared reference.
    ///
    /// # Panics
    ///
    /// It will panic if there no node that satisfies given criteria.
    pub fn borrow_by_criteria_up<Func>(
        &self,
        start_node_handle: Handle<UiNode>,
        func: Func,
    ) -> &UiNode
    where
        Func: Fn(&UiNode) -> bool,
    {
        self.nodes
            .borrow(self.find_by_criteria_up(start_node_handle, func))
    }

    pub fn try_borrow_by_criteria_up<Func>(
        &self,
        start_node_handle: Handle<UiNode>,
        func: Func,
    ) -> Option<&UiNode>
    where
        Func: Fn(&UiNode) -> bool,
    {
        self.nodes
            .try_borrow(self.find_by_criteria_up(start_node_handle, func))
    }

    pub fn try_borrow_by_type_up<T>(
        &self,
        node_handle: Handle<UiNode>,
    ) -> Option<(Handle<UiNode>, &T)>
    where
        T: Control,
    {
        if let Some(node) = self.nodes.try_borrow(node_handle) {
            let casted = node.cast::<T>();
            if let Some(casted) = casted {
                return Some((node_handle, casted));
            }

            if node.parent().is_some() {
                return self.try_borrow_by_type_up(node.parent());
            }
        }

        None
    }

    /// Returns instance of message sender which can be used to push messages into queue
    /// from other threads.
    pub fn sender(&self) -> Sender<UiMessage> {
        self.sender.clone()
    }

    pub fn send_message(&self, message: UiMessage) {
        self.sender.send(message).unwrap()
    }

    // Puts node at the end of children list of a parent node.
    //
    // # Notes
    //
    // Node will be topmost *only* on same hierarchy level! So if you have a floating
    // window (for example) and a window embedded into some other control (yes this is
    // possible) then floating window won't be the topmost.
    fn make_topmost(&mut self, node: Handle<UiNode>) {
        let parent = self.node(node).parent();
        if parent.is_some() {
            let parent = &mut self.nodes[parent];
            parent.remove_child(node);
            parent.add_child(node, false);
        }
    }

    fn make_lowermost(&mut self, node: Handle<UiNode>) {
        let parent = self.node(node).parent();
        if parent.is_some() {
            let parent = &mut self.nodes[parent];
            parent.remove_child(node);
            parent.add_child(node, true);
        }
    }

    fn bubble_message(&mut self, message: &mut UiMessage) {
        scope_profile!();

        // Dispatch event using bubble strategy. Bubble routing means that message will go
        // from specified destination up on tree to tree root.
        // Gather chain of nodes from source to root.
        self.bubble_queue.clear();
        self.bubble_queue.push_back(message.destination());
        let mut parent = self.nodes[message.destination()].parent();
        while parent.is_some() && self.nodes.is_valid_handle(parent) {
            self.bubble_queue.push_back(parent);
            parent = self.nodes[parent].parent();
        }

        while let Some(handle) = self.bubble_queue.pop_front() {
            let (ticket, mut node) = self.nodes.take_reserve(handle);
            node.handle_routed_message(self, message);
            self.nodes.put_back(ticket, node);
        }
    }

    /// Extracts UI event one-by-one from common queue. Each extracted event will go to *all*
    /// available nodes first and only then will be moved outside of this method. This is one
    /// of most important methods which must be called each frame of your game loop, otherwise
    /// UI will not respond to any kind of events and simply speaking will just not work.
    pub fn poll_message(&mut self) -> Option<UiMessage> {
        match self.receiver.try_recv() {
            Ok(mut message) => {
                // Destination node may be destroyed at the time we receive message,
                // we have skip processing of such messages.
                if !self.nodes.is_valid_handle(message.destination()) {
                    return Some(message);
                }

                if message.need_perform_layout() {
                    self.update(self.screen_size, 0.0);
                }

                for &handle in self.preview_set.iter() {
                    if let Some(node_ref) = self.nodes.try_borrow(handle) {
                        node_ref.preview_message(self, &mut message);
                    }
                }

                self.bubble_message(&mut message);

                if let Some(msg) = message.data::<WidgetMessage>() {
                    match msg {
                        WidgetMessage::ZIndex(_) => {
                            // Keep order of children of a parent node of a node that changed z-index
                            // the same as z-index of children.
                            if let Some(parent) =
                                self.try_get_node(message.destination()).map(|n| n.parent())
                            {
                                self.stack.clear();
                                for child in self.nodes.borrow(parent).children() {
                                    self.stack.push(*child);
                                }

                                let nodes = &mut self.nodes;
                                self.stack.sort_by(|a, b| {
                                    let z_a = nodes.borrow(*a).z_index();
                                    let z_b = nodes.borrow(*b).z_index();
                                    z_a.cmp(&z_b)
                                });

                                let parent = self.nodes.borrow_mut(parent);
                                parent.clear_children();
                                for child in self.stack.iter() {
                                    parent.add_child(*child, false);
                                }
                            }
                        }
                        WidgetMessage::Focus => {
                            if self.nodes.is_valid_handle(message.destination())
                                && message.direction() == MessageDirection::ToWidget
                            {
                                self.request_focus(message.destination());
                            }
                        }
                        WidgetMessage::Unfocus => {
                            if self.nodes.is_valid_handle(message.destination())
                                && message.direction() == MessageDirection::ToWidget
                            {
                                self.request_focus(self.root_canvas);
                            }
                        }
                        WidgetMessage::Topmost => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                self.make_topmost(message.destination());
                            }
                        }
                        WidgetMessage::Lowermost => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                self.make_lowermost(message.destination());
                            }
                        }
                        WidgetMessage::Unlink => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                self.unlink_node(message.destination());

                                let node = &self.nodes[message.destination()];
                                let new_position = node.screen_position();
                                self.send_message(WidgetMessage::desired_position(
                                    message.destination(),
                                    MessageDirection::ToWidget,
                                    new_position,
                                ));
                            }
                        }
                        &WidgetMessage::LinkWith(parent) => {
                            if self.nodes.is_valid_handle(message.destination())
                                && self.nodes.is_valid_handle(parent)
                            {
                                self.link_nodes(message.destination(), parent, false);
                            }
                        }
                        &WidgetMessage::LinkWithReverse(parent) => {
                            if self.nodes.is_valid_handle(message.destination())
                                && self.nodes.is_valid_handle(parent)
                            {
                                self.link_nodes(message.destination(), parent, true);
                            }
                        }
                        WidgetMessage::Remove => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                self.remove_node(message.destination());
                            }
                        }
                        WidgetMessage::ContextMenu(context_menu) => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                let node = self.nodes.borrow_mut(message.destination());
                                node.set_context_menu(context_menu.clone());
                            }
                        }
                        WidgetMessage::Tooltip(tooltip) => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                let node = self.nodes.borrow_mut(message.destination());
                                node.set_tooltip(tooltip.clone());
                            }
                        }
                        WidgetMessage::Center => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                let node = self.node(message.destination());
                                let size = node.actual_initial_size();
                                let parent = node.parent();
                                let parent_size = if parent.is_some() {
                                    self.node(parent).actual_initial_size()
                                } else {
                                    self.screen_size
                                };

                                self.send_message(WidgetMessage::desired_position(
                                    message.destination(),
                                    MessageDirection::ToWidget,
                                    (parent_size - size).scale(0.5),
                                ));
                            }
                        }
                        WidgetMessage::AdjustPositionToFit => {
                            if self.nodes.is_valid_handle(message.destination()) {
                                let node = self.node(message.destination());
                                let mut position = node.actual_local_position();
                                let size = node.actual_initial_size();
                                let parent = node.parent();
                                let parent_size = if parent.is_some() {
                                    self.node(parent).actual_initial_size()
                                } else {
                                    self.screen_size
                                };

                                if position.x < 0.0 {
                                    position.x = 0.0;
                                }
                                if position.x + size.x > parent_size.x {
                                    position.x -= (position.x + size.x) - parent_size.x;
                                }
                                if position.y < 0.0 {
                                    position.y = 0.0;
                                }
                                if position.y + size.y > parent_size.y {
                                    position.y -= (position.y + size.y) - parent_size.y;
                                }

                                self.send_message(WidgetMessage::desired_position(
                                    message.destination(),
                                    MessageDirection::ToWidget,
                                    position,
                                ));
                            }
                        }
                        WidgetMessage::Align {
                            relative_to,
                            horizontal_alignment,
                            vertical_alignment,
                            margin,
                        } => {
                            if let (Some(node), Some(relative_node)) = (
                                self.try_get_node(message.destination()),
                                self.try_get_node(*relative_to),
                            ) {
                                // Calculate new anchor point in screen coordinate system.
                                let relative_node_screen_size = relative_node.screen_bounds().size;
                                let relative_node_screen_position = relative_node.screen_position();
                                let node_screen_size = node.screen_bounds().size;

                                let mut screen_anchor_point = Vector2::default();
                                match horizontal_alignment {
                                    HorizontalAlignment::Stretch => {
                                        // Do nothing.
                                    }
                                    HorizontalAlignment::Left => {
                                        screen_anchor_point.x =
                                            relative_node_screen_position.x + margin.left;
                                    }
                                    HorizontalAlignment::Center => {
                                        screen_anchor_point.x = relative_node_screen_position.x
                                            + (relative_node_screen_size.x
                                                + node_screen_size.x
                                                + margin.left
                                                + margin.right)
                                                * 0.5;
                                    }
                                    HorizontalAlignment::Right => {
                                        screen_anchor_point.x = relative_node_screen_position.x
                                            + relative_node_screen_size.x
                                            - node_screen_size.x
                                            - margin.right;
                                    }
                                }

                                match vertical_alignment {
                                    VerticalAlignment::Stretch => {
                                        // Do nothing.
                                    }
                                    VerticalAlignment::Top => {
                                        screen_anchor_point.y =
                                            relative_node_screen_position.y + margin.top;
                                    }
                                    VerticalAlignment::Center => {
                                        screen_anchor_point.y = relative_node_screen_position.y
                                            + (relative_node_screen_size.y
                                                + node_screen_size.y
                                                + margin.top
                                                + margin.bottom)
                                                * 0.5;
                                    }
                                    VerticalAlignment::Bottom => {
                                        screen_anchor_point.y = relative_node_screen_position.y
                                            + (relative_node_screen_size.y
                                                - node_screen_size.y
                                                - margin.bottom);
                                    }
                                }

                                if let Some(parent) = self.try_get_node(node.parent()) {
                                    // Transform screen anchor point into the local coordinate system
                                    // of the parent node.
                                    let local_anchor_point =
                                        parent.screen_to_local(screen_anchor_point);
                                    self.send_message(WidgetMessage::desired_position(
                                        message.destination(),
                                        MessageDirection::ToWidget,
                                        local_anchor_point,
                                    ));
                                }
                            }
                        }
                        WidgetMessage::MouseDown { button, .. } => {
                            if *button == MouseButton::Right {
                                if let Some(picked) = self.nodes.try_borrow(self.picked_node) {
                                    // Get the context menu from the current node or a parent node
                                    let (context_menu, target) = if picked.context_menu().is_some()
                                    {
                                        (picked.context_menu(), self.picked_node)
                                    } else {
                                        let parent_handle = picked.find_by_criteria_up(self, |n| {
                                            n.context_menu().is_some()
                                        });

                                        if let Some(parent) = self.nodes.try_borrow(parent_handle) {
                                            (parent.context_menu(), parent_handle)
                                        } else {
                                            (None, Handle::NONE)
                                        }
                                    };

                                    // Display context menu
                                    if let Some(context_menu) = context_menu {
                                        self.send_message(PopupMessage::placement(
                                            context_menu.handle(),
                                            MessageDirection::ToWidget,
                                            Placement::Cursor(target),
                                        ));
                                        self.send_message(PopupMessage::open(
                                            context_menu.handle(),
                                            MessageDirection::ToWidget,
                                        ));
                                    }
                                }
                            }
                        }
                        _ => {}
                    }
                }

                Some(message)
            }
            Err(e) => match e {
                TryRecvError::Empty => None,
                TryRecvError::Disconnected => unreachable!(),
            },
        }
    }

    pub fn screen_to_root_canvas_space(&self, position: Vector2<f32>) -> Vector2<f32> {
        self.node(self.root()).screen_to_local(position)
    }

    fn show_tooltip(&self, tooltip: RcUiNodeHandle) {
        self.send_message(WidgetMessage::visibility(
            tooltip.handle(),
            MessageDirection::ToWidget,
            true,
        ));
        self.send_message(WidgetMessage::topmost(
            tooltip.handle(),
            MessageDirection::ToWidget,
        ));
        self.send_message(WidgetMessage::desired_position(
            tooltip.handle(),
            MessageDirection::ToWidget,
            self.screen_to_root_canvas_space(self.cursor_position() + Vector2::new(0.0, 16.0)),
        ));
        self.send_message(WidgetMessage::adjust_position_to_fit(
            tooltip.handle(),
            MessageDirection::ToWidget,
        ));
    }

    fn replace_or_update_tooltip(&mut self, tooltip: RcUiNodeHandle, time: f32) {
        if let Some(entry) = self.active_tooltip.as_mut() {
            if entry.tooltip == tooltip {
                // Keep current visible.
                entry.time = time;
            } else {
                let old_tooltip = entry.tooltip.clone();

                entry.tooltip = tooltip.clone();
                self.show_tooltip(tooltip);

                // Hide previous.
                self.send_message(WidgetMessage::visibility(
                    old_tooltip.handle(),
                    MessageDirection::ToWidget,
                    false,
                ));
            }
        } else {
            self.show_tooltip(tooltip.clone());
            self.active_tooltip = Some(TooltipEntry::new(tooltip, time));
        }
    }

    /// Find any tooltips that are being hovered and activate them.
    /// As well, update their time.
    fn update_tooltips(&mut self, dt: f32) {
        let sender = &self.sender;
        if let Some(entry) = self.active_tooltip.as_mut() {
            entry.decrease(dt);
            if !entry.should_display() {
                // This uses sender directly since we're currently mutably borrowing
                // visible_tooltips
                sender
                    .send(WidgetMessage::visibility(
                        entry.tooltip.handle(),
                        MessageDirection::ToWidget,
                        false,
                    ))
                    .unwrap();

                self.active_tooltip = None;
            }
        }

        // Check for hovering over a widget with a tooltip, or hovering over a tooltip.
        let mut handle = self.picked_node;
        while let Some(node) = self.nodes.try_borrow(handle) {
            // Get the parent to avoid the problem with having a immutable access here and a
            // mutable access later
            let parent = node.parent();

            if let Some(tooltip) = node.tooltip() {
                // They have a tooltip, we stop here and use that.
                let tooltip_time = node.tooltip_time();
                self.replace_or_update_tooltip(tooltip, tooltip_time);
                break;
            } else if let Some(entry) = self.active_tooltip.as_mut() {
                if entry.tooltip.handle() == handle {
                    // The current node was a tooltip.
                    // We refresh the timer back to the stored max time.
                    entry.time = entry.max_time;
                    break;
                }
            }

            handle = parent;
        }
    }

    pub fn captured_node(&self) -> Handle<UiNode> {
        self.captured_node
    }

    // Tries to set new picked node (a node under the cursor) and returns `true` if the node was
    // changed.
    fn try_set_picked_node(&mut self, node: Handle<UiNode>) -> bool {
        if self.picked_node != node {
            self.picked_node = node;
            self.reset_double_click_entries();
            true
        } else {
            false
        }
    }

    fn reset_double_click_entries(&mut self) {
        for entry in self.double_click_entries.values_mut() {
            entry.timer = self.double_click_time_slice;
            entry.click_count = 0;
        }
    }

    fn request_focus(&mut self, new_focused: Handle<UiNode>) {
        if self.keyboard_focus_node != new_focused {
            if self.keyboard_focus_node.is_some() {
                self.send_message(WidgetMessage::unfocus(
                    self.keyboard_focus_node,
                    MessageDirection::FromWidget,
                ));
            }

            self.keyboard_focus_node = new_focused;

            if self.keyboard_focus_node.is_some() {
                self.send_message(WidgetMessage::focus(
                    self.keyboard_focus_node,
                    MessageDirection::FromWidget,
                ));
            }
        }
    }

    /// Translates raw window event into some specific UI message. This is one of the
    /// most important methods of UI. You must call it each time you received a message
    /// from a window.
    pub fn process_os_event(&mut self, event: &OsEvent) -> bool {
        let mut event_processed = false;

        match event {
            &OsEvent::MouseInput { button, state, .. } => {
                match button {
                    MouseButton::Left => self.mouse_state.left = state,
                    MouseButton::Right => self.mouse_state.right = state,
                    MouseButton::Middle => self.mouse_state.middle = state,
                    _ => {}
                }

                match state {
                    ButtonState::Pressed => {
                        let picked_changed =
                            self.try_set_picked_node(self.hit_test(self.cursor_position));

                        let mut emit_double_click = false;
                        if !picked_changed {
                            match self.double_click_entries.entry(button) {
                                Entry::Occupied(e) => {
                                    let entry = e.into_mut();
                                    if entry.timer > 0.0 {
                                        entry.click_count += 1;
                                        if entry.click_count >= 2 {
                                            entry.click_count = 0;
                                            entry.timer = self.double_click_time_slice;
                                            emit_double_click = true;
                                        }
                                    } else {
                                        entry.timer = self.double_click_time_slice;
                                        entry.click_count = 1;
                                    }
                                }
                                Entry::Vacant(entry) => {
                                    // A button was clicked for the first time, no double click
                                    // in this case.
                                    entry.insert(DoubleClickEntry {
                                        timer: self.double_click_time_slice,
                                        click_count: 1,
                                    });
                                }
                            }
                        }

                        // Try to find draggable node in hierarchy starting from picked node.
                        if self.picked_node.is_some() {
                            self.stack.clear();
                            self.stack.push(self.picked_node);
                            while let Some(handle) = self.stack.pop() {
                                let node = &self.nodes[handle];
                                if node.is_drag_allowed() {
                                    self.drag_context.drag_node = handle;
                                    self.stack.clear();
                                    break;
                                } else if node.parent().is_some() {
                                    self.stack.push(node.parent());
                                }
                            }
                            self.drag_context.click_pos = self.cursor_position;
                        }

                        self.request_focus(self.picked_node);

                        if self.picked_node.is_some() {
                            self.send_message(WidgetMessage::mouse_down(
                                self.picked_node,
                                MessageDirection::FromWidget,
                                self.cursor_position,
                                button,
                            ));
                            event_processed = true;
                        }

                        // Make sure double click will be emitted after mouse down event.
                        if emit_double_click {
                            self.send_message(WidgetMessage::double_click(
                                self.picked_node,
                                MessageDirection::FromWidget,
                                button,
                            ));
                        }
                    }
                    ButtonState::Released => {
                        if self.picked_node.is_some() {
                            self.send_message(WidgetMessage::mouse_up(
                                self.picked_node,
                                MessageDirection::FromWidget,
                                self.cursor_position,
                                button,
                            ));

                            if self.drag_context.is_dragging {
                                self.drag_context.is_dragging = false;
                                self.cursor_icon = CursorIcon::Default;

                                // Try to find node with drop allowed in hierarchy starting from picked node.
                                self.stack.clear();
                                self.stack.push(self.picked_node);
                                while let Some(handle) = self.stack.pop() {
                                    let node = &self.nodes[handle];
                                    if node.is_drop_allowed() {
                                        self.send_message(WidgetMessage::drop(
                                            handle,
                                            MessageDirection::FromWidget,
                                            self.drag_context.drag_node,
                                        ));
                                        self.stack.clear();
                                        break;
                                    } else if node.parent().is_some() {
                                        self.stack.push(node.parent());
                                    }
                                }
                            }
                            self.drag_context.drag_node = Handle::NONE;
                            if self.nodes.is_valid_handle(self.drag_context.drag_preview) {
                                self.remove_node(self.drag_context.drag_preview);
                                self.drag_context.drag_preview = Default::default();
                            }

                            event_processed = true;
                        }
                    }
                }
            }
            OsEvent::CursorMoved { position } => {
                self.cursor_position = *position;
                self.try_set_picked_node(self.hit_test(self.cursor_position));

                if !self.drag_context.is_dragging
                    && self.mouse_state.left == ButtonState::Pressed
                    && self.picked_node.is_some()
                    && self.drag_context.drag_node.is_some()
                    && (self.drag_context.click_pos - *position).norm() > 5.0
                {
                    self.drag_context.drag_preview =
                        self.copy_node_with_limit(self.drag_context.drag_node, Some(30));
                    self.nodes[self.drag_context.drag_preview].set_opacity(Some(0.5));

                    // Make preview nodes invisible for hit test.
                    let mut stack = vec![self.drag_context.drag_preview];
                    while let Some(handle) = stack.pop() {
                        let preview_node = &mut self.nodes[handle];
                        preview_node.hit_test_visibility = false;
                        stack.extend_from_slice(preview_node.children());
                    }

                    self.drag_context.is_dragging = true;

                    self.send_message(WidgetMessage::drag_started(
                        self.picked_node,
                        MessageDirection::FromWidget,
                        self.drag_context.drag_node,
                    ));

                    self.cursor_icon = CursorIcon::Crosshair;
                }

                if self.drag_context.is_dragging
                    && self.nodes.is_valid_handle(self.drag_context.drag_preview)
                {
                    self.send_message(WidgetMessage::desired_position(
                        self.drag_context.drag_preview,
                        MessageDirection::ToWidget,
                        *position,
                    ));
                }

                // Fire mouse leave for previously picked node
                if self.picked_node != self.prev_picked_node && self.prev_picked_node.is_some() {
                    let prev_picked_node = self.nodes.borrow_mut(self.prev_picked_node);
                    if prev_picked_node.is_mouse_directly_over {
                        prev_picked_node.is_mouse_directly_over = false;
                        self.send_message(WidgetMessage::mouse_leave(
                            self.prev_picked_node,
                            MessageDirection::FromWidget,
                        ));
                    }
                }

                if self.picked_node.is_some() {
                    let picked_node = self.nodes.borrow_mut(self.picked_node);
                    if !picked_node.is_mouse_directly_over {
                        picked_node.is_mouse_directly_over = true;
                        self.send_message(WidgetMessage::mouse_enter(
                            self.picked_node,
                            MessageDirection::FromWidget,
                        ));
                    }

                    // Fire mouse move
                    self.send_message(WidgetMessage::mouse_move(
                        self.picked_node,
                        MessageDirection::FromWidget,
                        self.cursor_position,
                        self.mouse_state,
                    ));

                    if self.drag_context.is_dragging {
                        self.send_message(WidgetMessage::drag_over(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            self.drag_context.drag_node,
                        ));
                    }

                    event_processed = true;
                }
            }
            OsEvent::MouseWheel(_, y) => {
                if self.picked_node.is_some() {
                    self.send_message(WidgetMessage::mouse_wheel(
                        self.picked_node,
                        MessageDirection::FromWidget,
                        self.cursor_position,
                        *y,
                    ));

                    event_processed = true;
                }
            }
            OsEvent::KeyboardInput {
                button,
                state,
                text,
            } => {
                if self.keyboard_focus_node.is_some() {
                    match state {
                        ButtonState::Pressed => {
                            self.send_message(WidgetMessage::key_down(
                                self.keyboard_focus_node,
                                MessageDirection::FromWidget,
                                *button,
                            ));

                            if !text.is_empty() {
                                self.send_message(WidgetMessage::text(
                                    self.keyboard_focus_node,
                                    MessageDirection::FromWidget,
                                    text.clone(),
                                ));
                            }
                        }
                        ButtonState::Released => self.send_message(WidgetMessage::key_up(
                            self.keyboard_focus_node,
                            MessageDirection::FromWidget,
                            *button,
                        )),
                    }

                    event_processed = true;
                }
            }
            &OsEvent::KeyboardModifiers(modifiers) => {
                // TODO: Is message needed for focused node?
                self.keyboard_modifiers = modifiers;
            }
            OsEvent::Touch {
                phase,
                location,
                force,
                id,
            } => match phase {
                TouchPhase::Started => {
                    self.cursor_position = *location;
                    let picked_changed =
                        self.try_set_picked_node(self.hit_test(self.cursor_position));

                    let mut emit_double_tap = false;
                    if !picked_changed {
                        match self.double_click_entries.entry(MouseButton::Left) {
                            Entry::Occupied(e) => {
                                let entry = e.into_mut();
                                if entry.timer > 0.0 {
                                    entry.click_count += 1;
                                    if entry.click_count >= 2 {
                                        entry.click_count = 0;
                                        entry.timer = self.double_click_time_slice;
                                        emit_double_tap = true;
                                    }
                                } else {
                                    entry.timer = self.double_click_time_slice;
                                    entry.click_count = 1;
                                }
                            }
                            Entry::Vacant(entry) => {
                                // A button was clicked for the first time, no double click
                                // in this case.
                                entry.insert(DoubleClickEntry {
                                    timer: self.double_click_time_slice,
                                    click_count: 1,
                                });
                            }
                        }
                    }

                    // Try to find draggable node in hierarchy starting from picked node.
                    if self.picked_node.is_some() {
                        self.stack.clear();
                        self.stack.push(self.picked_node);
                        while let Some(handle) = self.stack.pop() {
                            let node = &self.nodes[handle];
                            if node.is_drag_allowed() {
                                self.drag_context.drag_node = handle;
                                self.stack.clear();
                                break;
                            } else if node.parent().is_some() {
                                self.stack.push(node.parent());
                            }
                        }
                        self.drag_context.click_pos = self.cursor_position;
                    }

                    self.request_focus(self.picked_node);

                    if self.picked_node.is_some() {
                        self.send_message(WidgetMessage::touch_started(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            self.cursor_position,
                            *force,
                            *id,
                        ));
                        event_processed = true;
                    }

                    // Make sure double click will be emitted after mouse down event.
                    if emit_double_tap {
                        self.send_message(WidgetMessage::double_tap(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            *location,
                            *force,
                            *id,
                        ));
                    }
                }
                TouchPhase::Moved => {
                    self.cursor_position = *location;
                    self.try_set_picked_node(self.hit_test(self.cursor_position));

                    // Try to find draggable node in hierarchy starting from picked node.
                    if self.picked_node.is_some() {
                        self.stack.clear();
                        self.stack.push(self.picked_node);
                        while let Some(handle) = self.stack.pop() {
                            let node = &self.nodes[handle];
                            if node.is_drag_allowed() {
                                self.drag_context.drag_node = handle;
                                self.stack.clear();
                                break;
                            } else if node.parent().is_some() {
                                self.stack.push(node.parent());
                            }
                        }
                        self.drag_context.click_pos = self.cursor_position;
                    }

                    self.request_focus(self.picked_node);

                    if self.picked_node.is_some() {
                        self.send_message(WidgetMessage::touch_moved(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            self.cursor_position,
                            *force,
                            *id,
                        ));
                        event_processed = true;
                    }
                }
                TouchPhase::Ended => {
                    if self.picked_node.is_some() {
                        self.send_message(WidgetMessage::touch_ended(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            self.cursor_position,
                            *id,
                        ));

                        if self.drag_context.is_dragging {
                            self.drag_context.is_dragging = false;

                            // Try to find node with drop allowed in hierarchy starting from picked node.
                            self.stack.clear();
                            self.stack.push(self.picked_node);
                            while let Some(handle) = self.stack.pop() {
                                let node = &self.nodes[handle];
                                if node.is_drop_allowed() {
                                    self.send_message(WidgetMessage::drop(
                                        handle,
                                        MessageDirection::FromWidget,
                                        self.drag_context.drag_node,
                                    ));
                                    self.stack.clear();
                                    break;
                                } else if node.parent().is_some() {
                                    self.stack.push(node.parent());
                                }
                            }
                        }
                        self.drag_context.drag_node = Handle::NONE;
                        if self.nodes.is_valid_handle(self.drag_context.drag_preview) {
                            self.remove_node(self.drag_context.drag_preview);
                            self.drag_context.drag_preview = Default::default();
                        }

                        event_processed = true;
                    }
                }
                TouchPhase::Cancelled => {
                    if self.picked_node.is_some() {
                        self.send_message(WidgetMessage::touch_cancelled(
                            self.picked_node,
                            MessageDirection::FromWidget,
                            self.cursor_position,
                            *id,
                        ));

                        if self.drag_context.is_dragging {
                            self.drag_context.is_dragging = false;
                            self.cursor_icon = CursorIcon::Default;
                            self.stack.clear();
                        }
                        self.drag_context.drag_node = Handle::NONE;
                        if self.nodes.is_valid_handle(self.drag_context.drag_preview) {
                            self.remove_node(self.drag_context.drag_preview);
                            self.drag_context.drag_preview = Default::default();
                        }

                        event_processed = true;
                    }
                }
            },
        }

        self.prev_picked_node = self.picked_node;

        for i in 0..self.nodes.get_capacity() {
            let handle = self.nodes.handle_from_index(i);

            if let Some(node_ref) = self.nodes.try_borrow(handle) {
                if node_ref.handle_os_events {
                    let (ticket, mut node) = self.nodes.take_reserve(handle);

                    node.handle_os_event(handle, self, event);

                    self.nodes.put_back(ticket, node);
                }
            }
        }

        event_processed
    }

    pub fn nodes(&self) -> &Pool<UiNode, WidgetContainer> {
        &self.nodes
    }

    pub fn root(&self) -> Handle<UiNode> {
        self.root_canvas
    }

    pub fn add_node(&mut self, mut node: UiNode) -> Handle<UiNode> {
        let children = node.children().to_vec();
        node.clear_children();
        let node_handle = self.nodes.spawn(node);
        if self.root_canvas.is_some() {
            self.link_nodes(node_handle, self.root_canvas, false);
        }
        for child in children {
            self.link_nodes(child, node_handle, false)
        }
        let node = self.nodes[node_handle].deref_mut();
        node.layout_events_sender = Some(self.layout_events_sender.clone());
        if node.preview_messages {
            self.preview_set.insert(node_handle);
        }
        node.handle = node_handle;
        node_handle
    }

    /// Extracts a widget from the user interface and reserves its handle. It is used to temporarily take
    /// ownership over the widget, and then put the widget back using the returned ticket. Extracted
    /// widget is detached from its parent!
    #[inline]
    pub fn take_reserve(&mut self, handle: Handle<UiNode>) -> (Ticket<UiNode>, UiNode) {
        self.unlink_node_internal(handle);
        self.nodes.take_reserve(handle)
    }

    /// Puts the widget back by the given ticket. Attaches it back to the root canvas of the user interface.
    #[inline]
    pub fn put_back(&mut self, ticket: Ticket<UiNode>, node: UiNode) -> Handle<UiNode> {
        let handle = self.nodes.put_back(ticket, node);
        self.link_nodes(handle, self.root_canvas, false);
        handle
    }

    /// Makes a widget handle vacant again.
    #[inline]
    pub fn forget_ticket(&mut self, ticket: Ticket<UiNode>, node: UiNode) -> UiNode {
        self.nodes.forget_ticket(ticket);
        node
    }

    /// Extracts sub-graph starting from the given widget. All handles to extracted widgets
    /// becomes reserved and will be marked as "occupied", an attempt to borrow a widget
    /// at such handle will result in panic!. Please note that root widget will be
    /// detached from its parent!
    #[inline]
    pub fn take_reserve_sub_graph(&mut self, root: Handle<UiNode>) -> SubGraph {
        // Take out descendants first.
        let mut descendants = Vec::new();
        let root_ref = &mut self.nodes[root];
        let mut stack = root_ref.children().to_vec();
        let parent = root_ref.parent;
        while let Some(handle) = stack.pop() {
            stack.extend_from_slice(self.nodes[handle].children());
            descendants.push(self.nodes.take_reserve(handle));
        }

        SubGraph {
            // Root must be extracted with detachment from its parent (if any).
            root: self.take_reserve(root),
            descendants,
            parent,
        }
    }

    /// Puts previously extracted sub-graph into the user interface. Handles to widgets will become valid
    /// again. After that you probably want to re-link returned handle with its previous parent.
    #[inline]
    pub fn put_sub_graph_back(&mut self, sub_graph: SubGraph) -> Handle<UiNode> {
        for (ticket, node) in sub_graph.descendants {
            self.nodes.put_back(ticket, node);
        }

        let (ticket, node) = sub_graph.root;
        let root_handle = self.put_back(ticket, node);

        self.link_nodes(root_handle, sub_graph.parent, false);

        root_handle
    }

    /// Forgets the entire sub-graph making handles to widgets invalid.
    #[inline]
    pub fn forget_sub_graph(&mut self, sub_graph: SubGraph) {
        for (ticket, _) in sub_graph.descendants {
            self.nodes.forget_ticket(ticket);
        }
        let (ticket, _) = sub_graph.root;
        self.nodes.forget_ticket(ticket);
    }

    pub fn push_picking_restriction(&mut self, restriction: RestrictionEntry) {
        if let Some(top) = self.top_picking_restriction() {
            assert_ne!(top.handle, restriction.handle);
        }
        self.picking_stack.push(restriction);
    }

    pub fn remove_picking_restriction(&mut self, node: Handle<UiNode>) {
        if let Some(pos) = self.picking_stack.iter().position(|h| h.handle == node) {
            self.picking_stack.remove(pos);
        }
    }

    pub fn picking_restriction_stack(&self) -> &[RestrictionEntry] {
        &self.picking_stack
    }

    /// Removes all picking restrictions.
    pub fn drop_picking_restrictions(&mut self) {
        self.picking_stack.clear();
    }

    pub fn top_picking_restriction(&self) -> Option<RestrictionEntry> {
        self.picking_stack.last().cloned()
    }

    /// Use WidgetMessage::remove(...) to remove node.
    fn remove_node(&mut self, node: Handle<UiNode>) {
        self.unlink_node_internal(node);

        let sender = self.sender.clone();
        let mut stack = vec![node];
        while let Some(handle) = stack.pop() {
            if self.prev_picked_node == handle {
                self.prev_picked_node = Handle::NONE;
            }
            if self.picked_node == handle {
                self.try_set_picked_node(Handle::NONE);
            }
            if self.captured_node == handle {
                self.captured_node = Handle::NONE;
            }
            if self.keyboard_focus_node == handle {
                self.keyboard_focus_node = Handle::NONE;
            }
            self.remove_picking_restriction(handle);

            let node_ref = self.nodes.borrow(handle);
            stack.extend_from_slice(node_ref.children());

            // Notify node that it is about to be deleted so it will have a chance to remove
            // other widgets (like popups).
            node_ref.on_remove(&sender);

            self.nodes.free(handle);
            self.preview_set.remove(&handle);
        }
    }

    pub fn drag_context(&self) -> &DragContext {
        &self.drag_context
    }

    /// Links the specified child widget with the specified parent widget.
    #[inline]
    pub fn link_nodes(
        &mut self,
        child_handle: Handle<UiNode>,
        parent_handle: Handle<UiNode>,
        in_front: bool,
    ) {
        assert_ne!(child_handle, parent_handle);
        self.unlink_node_internal(child_handle);
        self.nodes[child_handle].set_parent(parent_handle);
        self.nodes[parent_handle].add_child(child_handle, in_front);
    }

    /// Unlinks the specified widget from its parent, so the widget will become root.
    #[inline]
    fn unlink_node_internal(&mut self, node_handle: Handle<UiNode>) {
        // Replace parent handle of child
        let node = self.nodes.borrow_mut(node_handle);
        let parent_handle = node.parent();
        if parent_handle.is_some() {
            node.set_parent(Handle::NONE);

            // Remove child from parent's children list
            self.nodes[parent_handle].remove_child(node_handle);
        }
    }

    /// Unlinks specified node from its parent and attaches back to root canvas.
    ///
    /// Use [WidgetMessage::remove](enum.WidgetMessage.html#method.remove) to unlink
    /// a node at runtime!
    #[inline]
    pub fn unlink_node(&mut self, node_handle: Handle<UiNode>) {
        self.unlink_node_internal(node_handle);
        self.link_nodes(node_handle, self.root_canvas, false);
    }

    #[inline]
    pub fn node(&self, node_handle: Handle<UiNode>) -> &UiNode {
        self.nodes.borrow(node_handle)
    }

    #[inline]
    pub fn try_get_node(&self, node_handle: Handle<UiNode>) -> Option<&UiNode> {
        self.nodes.try_borrow(node_handle)
    }

    #[inline]
    pub fn node_mut(&mut self, node_handle: Handle<UiNode>) -> &mut UiNode {
        self.nodes.borrow_mut(node_handle)
    }

    #[inline]
    pub fn try_get_node_mut(&mut self, node_handle: Handle<UiNode>) -> Option<&mut UiNode> {
        self.nodes.try_borrow_mut(node_handle)
    }

    pub fn copy_node(&mut self, node: Handle<UiNode>) -> Handle<UiNode> {
        let mut map = NodeHandleMapping::default();

        let root = self.copy_node_recursive(node, &mut map);

        for &node_handle in map.hash_map.values() {
            self.nodes[node_handle].resolve(&map);
        }

        root
    }

    #[allow(clippy::unnecessary_to_owned)] // False positive
    fn copy_node_recursive(
        &mut self,
        node_handle: Handle<UiNode>,
        map: &mut NodeHandleMapping,
    ) -> Handle<UiNode> {
        let node = self.nodes.borrow(node_handle);
        let mut cloned = UiNode(node.clone_boxed());

        let mut cloned_children = Vec::new();
        for child in node.children().to_vec() {
            cloned_children.push(self.copy_node_recursive(child, map));
        }

        cloned.set_children(cloned_children);
        let copy_handle = self.add_node(cloned);
        map.add_mapping(node_handle, copy_handle);
        copy_handle
    }

    pub fn copy_node_to(
        &self,
        node: Handle<UiNode>,
        dest: &mut UserInterface,
    ) -> (Handle<UiNode>, NodeHandleMapping) {
        let mut map = NodeHandleMapping::default();

        let root = self.copy_node_to_recursive(node, dest, &mut map);

        for &node_handle in map.hash_map.values() {
            dest.nodes[node_handle].resolve(&map);
        }

        (root, map)
    }

    fn copy_node_to_recursive(
        &self,
        node_handle: Handle<UiNode>,
        dest: &mut UserInterface,
        map: &mut NodeHandleMapping,
    ) -> Handle<UiNode> {
        let node = self.nodes.borrow(node_handle);
        let children = node.children.clone();

        let mut cloned = UiNode(node.clone_boxed());
        cloned.children.clear();
        cloned.parent = Handle::NONE;
        let cloned_node_handle = dest.add_node(cloned);

        for child in children {
            let cloned_child_node_handle = self.copy_node_to_recursive(child, dest, map);
            dest.link_nodes(cloned_child_node_handle, cloned_node_handle, false);
        }

        map.add_mapping(node_handle, cloned_node_handle);
        cloned_node_handle
    }

    pub fn copy_node_with_limit(
        &mut self,
        node: Handle<UiNode>,
        limit: Option<usize>,
    ) -> Handle<UiNode> {
        let mut map = NodeHandleMapping::default();
        let mut counter = 0;

        let root = self.copy_node_recursive_with_limit(node, &mut map, limit, &mut counter);

        for &node_handle in map.hash_map.values() {
            self.nodes[node_handle].resolve(&map);
        }

        root
    }

    #[allow(clippy::unnecessary_to_owned)] // False positive
    fn copy_node_recursive_with_limit(
        &mut self,
        node_handle: Handle<UiNode>,
        map: &mut NodeHandleMapping,
        limit: Option<usize>,
        counter: &mut usize,
    ) -> Handle<UiNode> {
        if let Some(limit) = limit {
            if *counter >= limit {
                return Default::default();
            }
        }

        let node = self.nodes.borrow(node_handle);
        let mut cloned = UiNode(node.clone_boxed());

        let mut cloned_children = Vec::new();
        for child in node.children().to_vec() {
            let cloned_child = self.copy_node_recursive_with_limit(child, map, limit, counter);
            if cloned_child.is_some() {
                cloned_children.push(cloned_child);
            } else {
                break;
            }
        }

        cloned.set_children(cloned_children);
        let copy_handle = self.add_node(cloned);
        map.add_mapping(node_handle, copy_handle);

        *counter += 1;

        copy_handle
    }

    pub fn save(&mut self, path: &Path) -> Result<Visitor, VisitError> {
        let mut visitor = Visitor::new();
        self.visit("Ui", &mut visitor)?;
        visitor.save_binary(path)?;
        Ok(visitor)
    }

    #[allow(clippy::arc_with_non_send_sync)]
    pub async fn load_from_file<P: AsRef<Path>>(
        path: P,
        resource_manager: ResourceManager,
    ) -> Result<Self, VisitError> {
        Self::load_from_file_ex(
            path,
            Arc::new(WidgetConstructorContainer::new()),
            resource_manager,
            &FsResourceIo,
        )
        .await
    }

    #[allow(clippy::arc_with_non_send_sync)]
    pub async fn load_from_file_ex<P: AsRef<Path>>(
        path: P,
        constructors: Arc<WidgetConstructorContainer>,
        resource_manager: ResourceManager,
        io: &dyn ResourceIo,
    ) -> Result<Self, VisitError> {
        let mut visitor = Visitor::load_from_memory(&io.load_file(path.as_ref()).await?)?;
        let (sender, receiver) = mpsc::channel();
        visitor.blackboard.register(constructors);
        visitor.blackboard.register(Arc::new(sender.clone()));
        visitor.blackboard.register(Arc::new(resource_manager));
        let mut ui = UserInterface::new_with_channel(sender, receiver, Vector2::new(100.0, 100.0));
        ui.visit("Ui", &mut visitor)?;
        for widget in ui.nodes.iter_mut() {
            widget.layout_events_sender = Some(ui.layout_events_sender.clone());
            widget.invalidate_layout();
        }
        Ok(ui)
    }
}

fn is_approx_zero(v: f32) -> bool {
    v.abs() <= 10.0 * f32::EPSILON
}

fn are_close(value1: f32, value2: f32) -> bool {
    //in case they are Infinities (then epsilon check does not work)
    if value1 == value2 {
        return true;
    }
    // This computes (|value1-value2| / (|value1| + |value2| + 10.0)) < DBL_EPSILON
    let eps = (value1.abs() + value2.abs() + 10.0) * f32::EPSILON;
    let delta = value1 - value2;
    (-eps < delta) && (eps > delta)
}

fn greater_than_or_close(value1: f32, value2: f32) -> bool {
    (value1 > value2) || are_close(value1, value2)
}

fn less_than_or_close(value1: f32, value2: f32) -> bool {
    (value1 < value2) || are_close(value1, value2)
}

/// Calculates a new size for the rect after transforming it with the given matrix. Basically it
/// finds a new rectangle that can contain the rotated rectangle.
///
/// # Origin
///
/// Original code was taken from WPF source code (FindMaximalAreaLocalSpaceRect) and ported to Rust.
/// It handles a lot of edge cases that could occur due to the fact that the UI uses a lot of
/// special floating-point constants like Infinity or NaN. If there would be no such values, simple
/// `rect.transform(&matrix).size` could be used.
fn transform_size(transform_space_bounds: Vector2<f32>, matrix: &Matrix3<f32>) -> Vector2<f32> {
    // X (width) and Y (height) constraints for axis-aligned bounding box in dest. space
    let mut x_constr: f32 = transform_space_bounds.x;
    let mut y_constr: f32 = transform_space_bounds.y;

    //if either of the sizes is 0, return 0,0 to avoid doing math on an empty rect (bug 963569)
    if is_approx_zero(x_constr) || is_approx_zero(y_constr) {
        return Vector2::new(0.0, 0.0);
    }

    let x_constr_infinite = x_constr.is_infinite();
    let y_constr_infinite = y_constr.is_infinite();

    if x_constr_infinite && y_constr_infinite {
        return Vector2::new(f32::INFINITY, f32::INFINITY);
    } else if x_constr_infinite
    //assume square for one-dimensional constraint
    {
        x_constr = y_constr;
    } else if y_constr_infinite {
        y_constr = x_constr;
    }

    // We only deal with nonsingular matrices here. The nonsingular matrix is the one
    // that has inverse (determinant != 0).
    if !matrix.is_invertible() {
        return Vector2::new(0.0, 0.0);
    }

    let a = matrix[(0, 0)];
    let b = matrix[(0, 1)];
    let c = matrix[(1, 0)];
    let d = matrix[(1, 1)];

    // Result width and height (in child/local space)
    let mut w;
    let mut h;

    // because we are dealing with nonsingular transform matrices,
    // we have (b==0 || c==0) XOR (a==0 || d==0)

    if is_approx_zero(b) || is_approx_zero(c) {
        // (b==0 || c==0) ==> a!=0 && d!=0

        let y_cover_d = if y_constr_infinite {
            f32::INFINITY
        } else {
            (y_constr / d).abs()
        };
        let x_cover_a = if x_constr_infinite {
            f32::INFINITY
        } else {
            (x_constr / a).abs()
        };

        if is_approx_zero(b) {
            if is_approx_zero(c) {
                // Case: b=0, c=0, a!=0, d!=0

                // No constraint relation; use maximal width and height

                h = y_cover_d;
                w = x_cover_a;
            } else {
                // Case: b==0, a!=0, c!=0, d!=0

                // Maximizing under line (hIntercept=xConstr/c, wIntercept=xConstr/a)
                // BUT we still have constraint: h <= yConstr/d

                h = (0.5 * (x_constr / c).abs()).min(y_cover_d);
                w = x_cover_a - ((c * h) / a);
            }
        } else {
            // Case: c==0, a!=0, b!=0, d!=0

            // Maximizing under line (hIntercept=yConstr/d, wIntercept=yConstr/b)
            // BUT we still have constraint: w <= xConstr/a

            w = (0.5 * (y_constr / b).abs()).min(x_cover_a);
            h = y_cover_d - ((b * w) / d);
        }
    } else if is_approx_zero(a) || is_approx_zero(d) {
        // (a==0 || d==0) ==> b!=0 && c!=0

        let y_cover_b = (y_constr / b).abs();
        let x_cover_c = (x_constr / c).abs();

        if is_approx_zero(a) {
            if is_approx_zero(d) {
                // Case: a=0, d=0, b!=0, c!=0

                // No constraint relation; use maximal width and height

                h = x_cover_c;
                w = y_cover_b;
            } else {
                // Case: a==0, b!=0, c!=0, d!=0

                // Maximizing under line (hIntercept=yConstr/d, wIntercept=yConstr/b)
                // BUT we still have constraint: h <= xConstr/c

                h = (0.5 * (y_constr / d).abs()).min(x_cover_c);
                w = y_cover_b - ((d * h) / b);
            }
        } else {
            // Case: d==0, a!=0, b!=0, c!=0

            // Maximizing under line (hIntercept=xConstr/c, wIntercept=xConstr/a)
            // BUT we still have constraint: w <= yConstr/b

            w = (0.5 * (x_constr / a).abs()).min(y_cover_b);
            h = x_cover_c - ((a * w) / c);
        }
    } else {
        let x_cover_a = (x_constr / a).abs(); // w-intercept of x-constraint line.
        let x_cover_c = (x_constr / c).abs(); // h-intercept of x-constraint line.

        let y_cover_b = (y_constr / b).abs(); // w-intercept of y-constraint line.
        let y_cover_d = (y_constr / d).abs(); // h-intercept of y-constraint line.

        // The tighest constraint governs, so we pick the lowest constraint line.
        //
        //   The optimal point (w,h) for which Area = w*h is maximized occurs halfway
        //   to each intercept.

        w = y_cover_b.min(x_cover_a) * 0.5;
        h = x_cover_c.min(y_cover_d) * 0.5;

        if (greater_than_or_close(x_cover_a, y_cover_b) && less_than_or_close(x_cover_c, y_cover_d))
            || (less_than_or_close(x_cover_a, y_cover_b)
                && greater_than_or_close(x_cover_c, y_cover_d))
        {
            // Constraint lines cross; since the most restrictive constraint wins,
            // we have to maximize under two line segments, which together are discontinuous.
            // Instead, we maximize w*h under the line segment from the two smallest endpoints.

            // Since we are not (except for in corner cases) on the original constraint lines,
            // we are not using up all the available area in transform space.  So scale our shape up
            // until it does in at least one dimension.

            let child_bounds_tr = Rect::new(0.0, 0.0, w, h).transform(matrix);
            let expand_factor =
                (x_constr / child_bounds_tr.size.x).min(y_constr / child_bounds_tr.size.y);

            if !expand_factor.is_nan() && !expand_factor.is_infinite() {
                w *= expand_factor;
                h *= expand_factor;
            }
        }
    }

    Vector2::new(w, h)
}

uuid_provider!(UserInterface = "0d065c93-ef9c-4dd2-9fe7-e2b33c1a21b6");

impl ResourceData for UserInterface {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    fn type_uuid(&self) -> Uuid {
        <Self as TypeUuidProvider>::type_uuid()
    }

    fn save(&mut self, path: &Path) -> Result<(), Box<dyn Error>> {
        self.save(path)?;
        Ok(())
    }

    fn can_be_saved(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod test {
    use crate::message::{ButtonState, KeyCode};
    use crate::{
        border::BorderBuilder,
        core::algebra::{Rotation2, UnitComplex, Vector2},
        message::MessageDirection,
        text_box::TextBoxBuilder,
        transform_size,
        widget::{WidgetBuilder, WidgetMessage},
        OsEvent, UserInterface,
    };

    #[test]
    fn test_transform_size() {
        let input = Vector2::new(100.0, 100.0);
        let transform =
            Rotation2::from(UnitComplex::from_angle(45.0f32.to_radians())).to_homogeneous();
        let transformed = transform_size(input, &transform);
        dbg!(input, transformed);
    }

    #[test]
    fn center() {
        let screen_size = Vector2::new(1000.0, 1000.0);
        let widget_size = Vector2::new(100.0, 100.0);
        let mut ui = UserInterface::new(screen_size);
        let widget = BorderBuilder::new(
            WidgetBuilder::new()
                .with_width(widget_size.x)
                .with_height(widget_size.y),
        )
        .build(&mut ui.build_ctx());
        ui.update(screen_size, 0.0); // Make sure layout was calculated.
        ui.send_message(WidgetMessage::center(widget, MessageDirection::ToWidget));
        while ui.poll_message().is_some() {}
        ui.update(screen_size, 0.0);
        let expected_position = (screen_size - widget_size).scale(0.5);
        let actual_position = ui.node(widget).actual_local_position();
        assert_eq!(actual_position, expected_position);
    }

    #[test]
    fn test_keyboard_focus() {
        let screen_size = Vector2::new(1000.0, 1000.0);
        let mut ui = UserInterface::new(screen_size);

        let text_box = TextBoxBuilder::new(WidgetBuilder::new()).build(&mut ui.build_ctx());

        // Make sure layout was calculated.
        ui.update(screen_size, 0.0);

        assert!(ui.poll_message().is_none());

        ui.send_message(WidgetMessage::focus(text_box, MessageDirection::ToWidget));

        // Ensure that the message has gotten in the queue.
        assert_eq!(
            ui.poll_message(),
            Some(WidgetMessage::focus(text_box, MessageDirection::ToWidget))
        );
        // Root must be unfocused right before new widget is focused.
        assert_eq!(
            ui.poll_message(),
            Some(WidgetMessage::unfocus(
                ui.root(),
                MessageDirection::FromWidget
            ))
        );
        // Finally there should be a response from newly focused node.
        assert_eq!(
            ui.poll_message(),
            Some(WidgetMessage::focus(text_box, MessageDirection::FromWidget))
        );

        // Do additional check - emulate key press of "A" and check if the focused text box has accepted it.
        ui.process_os_event(&OsEvent::KeyboardInput {
            button: KeyCode::KeyA,
            state: ButtonState::Pressed,
            text: "A".to_string(),
        });

        let msg = WidgetMessage::key_down(text_box, MessageDirection::FromWidget, KeyCode::KeyA);
        msg.set_handled(true);
        assert_eq!(ui.poll_message(), Some(msg));

        assert_eq!(
            ui.poll_message(),
            Some(WidgetMessage::text(
                text_box,
                MessageDirection::FromWidget,
                'A'.to_string()
            ))
        );

        assert!(ui.poll_message().is_none());
    }
}