aboutsummaryrefslogtreecommitdiff
path: root/CruUI-Generate/cru_ui.hpp
blob: 35c7abeb0efb654e27d0eb0d7a05b59ff03994e4 (plain)
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
#pragma once
//--------------------------------------------------------
//-------begin of file: src\any_map.hpp
//--------------------------------------------------------

#include <any>
#include <unordered_map>
#include <functional>
#include <optional>
#include <typeinfo>

//--------------------------------------------------------
//-------begin of file: src\base.hpp
//--------------------------------------------------------

// ReSharper disable once CppUnusedIncludeDirective
//--------------------------------------------------------
//-------begin of file: src\global_macros.hpp
//--------------------------------------------------------

#ifdef _DEBUG
#define CRU_DEBUG
#endif

#ifdef CRU_DEBUG
#define CRU_DEBUG_LAYOUT
#endif
//--------------------------------------------------------
//-------end of file: src\global_macros.hpp
//--------------------------------------------------------


#include <string>
#include <stdexcept>
#include <string_view>
#include <chrono>
#include <optional>
// ReSharper disable once CppUnusedIncludeDirective
#include <type_traits>

namespace cru
{
    template<typename T> struct type_tag {};

    //typedefs
    using String = std::wstring;
    using MultiByteString = std::string;

    using StringView = std::wstring_view;
    using MultiByteStringView = std::string_view;

    using FloatSecond = std::chrono::duration<double, std::chrono::seconds::period>;

    enum class FlowControl
    {
        Continue,
        Break
    };


    class Object
    {
    public:
        Object() = default;
        Object(const Object&) = default;
        Object& operator = (const Object&) = default;
        Object(Object&&) = default;
        Object& operator = (Object&&) = default;
        virtual ~Object() = default;
    };

    struct Interface
    {
        virtual ~Interface() = default;
    };

    [[noreturn]] inline void UnreachableCode()
    {
        throw std::logic_error("Unreachable code.");
    }

    MultiByteString ToUtf8String(const StringView& string);

    inline void Require(const bool condition, const MultiByteStringView& error_message)
    {
        if (!condition)
            throw std::invalid_argument(error_message.data());
    }

    template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
    float Coerce(const T n, const std::optional<T> min, const std::optional<T> max)
    {
        if (min.has_value() && n < min.value())
            return min.value();
        if (max.has_value() && n > max.value())
            return max.value();
        return n;
    }

    template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
    float Coerce(const T n, const std::nullopt_t, const std::optional<T> max)
    {
        if (max.has_value() && n > max.value())
            return max.value();
        return n;
    }

    template <typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>>
    float Coerce(const T n, const std::optional<T> min, const std::nullopt_t)
    {
        if (min.has_value() && n < min.value())
            return min.value();
        return n;
    }

}
//--------------------------------------------------------
//-------end of file: src\base.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\format.hpp
//--------------------------------------------------------


namespace cru
{
    namespace details
    {
        constexpr StringView PlaceHolder(type_tag<String>)
        {
            return StringView(L"{}");
        }

        constexpr MultiByteStringView PlaceHolder(type_tag<MultiByteString>)
        {
            return MultiByteStringView("{}");
        }

        template<typename TString>
        void FormatInternal(TString& string)
        {
            const auto find_result = string.find(PlaceHolder(type_tag<TString>{}));
            if (find_result != TString::npos)
                throw std::invalid_argument("There is more placeholders than args.");
        }

        template<typename TString, typename T, typename... TRest>
        void FormatInternal(TString& string, const T& arg, const TRest&... args)
        {
            const auto find_result = string.find(PlaceHolder(type_tag<TString>{}));
            if (find_result == TString::npos)
                throw std::invalid_argument("There is less placeholders than args.");

            string.replace(find_result, 2, FormatToString(arg, type_tag<TString>{}));
            FormatInternal<TString>(string, args...);
        }
    }

    template<typename... T>
    String Format(const StringView& format, const T&... args)
    {
        String result(format);
        details::FormatInternal<String>(result, args...);
        return result;
    }

    template<typename... T>
    MultiByteString Format(const MultiByteStringView& format, const T&... args)
    {
        MultiByteString result(format);
        details::FormatInternal<MultiByteString>(result, args...);
        return result;
    }

#define CRU_FORMAT_NUMBER(type) \
    inline String FormatToString(const type number, type_tag<String>) \
    { \
        return std::to_wstring(number); \
    } \
    inline MultiByteString FormatToString(const type number, type_tag<MultiByteString>) \
    { \
        return std::to_string(number); \
    }

    CRU_FORMAT_NUMBER(int)
    CRU_FORMAT_NUMBER(short)
    CRU_FORMAT_NUMBER(long)
    CRU_FORMAT_NUMBER(long long)
    CRU_FORMAT_NUMBER(unsigned int)
    CRU_FORMAT_NUMBER(unsigned short)
    CRU_FORMAT_NUMBER(unsigned long)
    CRU_FORMAT_NUMBER(unsigned long long)
    CRU_FORMAT_NUMBER(float)
    CRU_FORMAT_NUMBER(double)

#undef CRU_FORMAT_NUMBER

    inline StringView FormatToString(const String& string, type_tag<String>)
    {
        return string;
    }

    inline MultiByteString FormatToString(const MultiByteString& string, type_tag<MultiByteString>)
    {
        return string;
    }

    inline StringView FormatToString(const StringView& string, type_tag<String>)
    {
        return string;
    }

    inline MultiByteStringView FormatToString(const MultiByteStringView& string, type_tag<MultiByteString>)
    {
        return string;
    }

    inline StringView FormatToString(const wchar_t* string, type_tag<String>)
    {
        return StringView(string);
    }

    inline MultiByteStringView FormatToString(const char* string, type_tag<MultiByteString>)
    {
        return MultiByteString(string);
    }
}
//--------------------------------------------------------
//-------end of file: src\format.hpp
//--------------------------------------------------------


namespace cru
{
    // A map with String as key and any type as value.
    // It also has notification when value with specified key changed.
    class AnyMap : public Object
    {
    public:
        using ListenerToken = long;
        using Listener = std::function<void(const std::any&)>;

        AnyMap() = default;
        AnyMap(const AnyMap& other) = delete;
        AnyMap(AnyMap&& other) = delete;
        AnyMap& operator=(const AnyMap& other) = delete;
        AnyMap& operator=(AnyMap&& other) = delete;
        ~AnyMap() override = default;


        // return the value if the value exists and the type of value is T.
        // return a null optional if value doesn't exists.
        // throw std::runtime_error if type is mismatch.
        template <typename T>
        std::optional<T> GetOptionalValue(const String& key) const
        {
            try
            {
                const auto find_result = map_.find(key);
                if (find_result != map_.cend())
                {
                    const auto& value = find_result->second.first;
                    if (value.has_value())
                        return std::any_cast<T>(value);
                    return std::nullopt;
                }
                return std::nullopt;
            }
            catch (const std::bad_any_cast&)
            {
                throw std::runtime_error(Format("Value of key \"{}\" in AnyMap is not of the type {}.", ToUtf8String(key), typeid(T).name()));
            }
        }

        // return the value if the value exists and the type of value is T.
        // throw if value doesn't exists. (different from "GetOptionalValue").
        // throw std::runtime_error if type is mismatch.
        template <typename T>
        T GetValue(const String& key) const
        {
            const auto optional_value = GetOptionalValue<T>(key);
            if (optional_value.has_value())
                return optional_value.value();
            else
                throw std::runtime_error(Format("Key \"{}\" does not exists in AnyMap.", ToUtf8String(key)));
        }

        // Set the value of key, and trigger all related listeners.
        template <typename T>
        void SetValue(const String& key, T&& value)
        {
            auto& p = map_[key];
            p.first = std::make_any<T>(std::forward<T>(value));
            InvokeListeners(p.second, p.first);
        }

        // Remove the value of the key.
        void ClearValue(const String& key)
        {
            auto& p = map_[key];
            p.first = std::any{};
            InvokeListeners(p.second, std::any{});
        }

        // Add a listener which is called when value of key is changed.
        // Return a token used to remove the listener.
        ListenerToken RegisterValueChangeListener(const String& key, const Listener& listener);

        // Remove a listener by token.
        void UnregisterValueChangeListener(ListenerToken token);

    private:
        void InvokeListeners(std::list<ListenerToken>& listener_list, const std::any& value);

    private:
        std::unordered_map<String, std::pair<std::any, std::list<ListenerToken>>> map_{};
        std::unordered_map<ListenerToken, Listener> listeners_{};
        ListenerToken current_listener_token_ = 0;
    };
}
//--------------------------------------------------------
//-------end of file: src\any_map.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\application.hpp
//--------------------------------------------------------

//--------------------------------------------------------
//-------begin of file: src\system_headers.hpp
//--------------------------------------------------------


//include system headers

#define NOMINMAX
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <windowsx.h>

#pragma comment(lib, "D3D11.lib")
#include <d3d11.h>

#pragma comment(lib, "D2d1.lib")
#include <d2d1_1.h>

#pragma comment(lib, "DWrite.lib")
#include <dwrite.h>

#include <dxgi1_2.h>
#include <wrl/client.h>
//--------------------------------------------------------
//-------end of file: src\system_headers.hpp
//--------------------------------------------------------
#include <memory>
#include <optional>
#include <functional>
#include <typeindex>
#include <type_traits>


#ifdef CRU_DEBUG
#include <unordered_set>
#endif

namespace cru 
{
    class Application;

    namespace ui
    {
        class WindowClass;
    }


    class GodWindow : public Object
    {
    public:
        explicit GodWindow(Application* application);
        GodWindow(const GodWindow& other) = delete;
        GodWindow(GodWindow&& other) = delete;
        GodWindow& operator=(const GodWindow& other) = delete;
        GodWindow& operator=(GodWindow&& other) = delete;
        ~GodWindow() override;

        HWND GetHandle() const
        {
            return hwnd_;
        }

        std::optional<LRESULT> HandleGodWindowMessage(HWND hwnd, int msg, WPARAM w_param, LPARAM l_param);

    private:
        std::unique_ptr<ui::WindowClass> god_window_class_;
        HWND hwnd_;
    };

    class Application : public Object
    {
    public:
        static Application* GetInstance();
    private:
        static Application* instance_;

    public:
        explicit Application(HINSTANCE h_instance);
        Application(const Application&) = delete;
        Application(Application&&) = delete;
        Application& operator = (const Application&) = delete;
        Application& operator = (Application&&) = delete;
        ~Application() override;

    public:
        int Run();
        void Quit(int quit_code);


        HINSTANCE GetInstanceHandle() const
        {
            return h_instance_;
        }

        GodWindow* GetGodWindow() const
        {
            return god_window_.get();
        }

        // Resolve a singleton.
        // All singletons will be delete in reverse order of resolve.
        template<typename T, typename = std::enable_if_t<std::is_base_of_v<Object, T>>>
        T* ResolveSingleton(const std::function<T*(Application*)>& creator)
        {
            const auto& index = std::type_index{typeid(T)};
            const auto find_result = singleton_map_.find(index);
            if (find_result != singleton_map_.cend())
                return static_cast<T*>(find_result->second);

#ifdef CRU_DEBUG
            const auto type_find_result = singleton_type_set_.find(index);
            if (type_find_result != singleton_type_set_.cend())
                throw std::logic_error("The singleton of that type is being constructed. This may cause a dead recursion.");
            singleton_type_set_.insert(index);
#endif

            auto singleton = creator(this);
            singleton_map_.emplace(index, static_cast<Object*>(singleton));
            singleton_list_.push_back(singleton);
            return singleton;
        }

    private:
        HINSTANCE h_instance_;

        std::unique_ptr<GodWindow> god_window_;

        std::unordered_map<std::type_index, Object*> singleton_map_;
        std::list<Object*> singleton_list_; // used for reverse destroy.
#ifdef CRU_DEBUG
        std::unordered_set<std::type_index> singleton_type_set_; // used for dead recursion.
#endif
    };


    void InvokeLater(const std::function<void()>& action);
}
//--------------------------------------------------------
//-------end of file: src\application.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\exception.hpp
//--------------------------------------------------------

#include <optional>



namespace cru {
    class HResultError : public std::runtime_error
    {
    public:
        explicit HResultError(HRESULT h_result, std::optional<MultiByteStringView> additional_message = std::nullopt);
        HResultError(const HResultError& other) = default;
        HResultError(HResultError&& other) = default;
        HResultError& operator=(const HResultError& other) = default;
        HResultError& operator=(HResultError&& other) = default;
        ~HResultError() override = default;

        HRESULT GetHResult() const
        {
            return h_result_;
        }

    private:
        HRESULT h_result_;
    };

    inline void ThrowIfFailed(const HRESULT h_result) {
        if (FAILED(h_result))
            throw HResultError(h_result);
    }

    inline void ThrowIfFailed(const HRESULT h_result, const MultiByteStringView& message) {
        if (FAILED(h_result))
            throw HResultError(h_result, message);
    }

    class Win32Error : public std::runtime_error
    {
    public:
        explicit Win32Error(DWORD error_code, std::optional<MultiByteStringView> additional_message = std::nullopt);
        Win32Error(const Win32Error& other) = default;
        Win32Error(Win32Error&& other) = default;
        Win32Error& operator=(const Win32Error& other) = default;
        Win32Error& operator=(Win32Error&& other) = default;
        ~Win32Error() override = default;

        HRESULT GetErrorCode() const
        {
            return error_code_;
        }

    private:
        DWORD error_code_;
    };
}
//--------------------------------------------------------
//-------end of file: src\exception.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\timer.hpp
//--------------------------------------------------------


#include <map>
#include <chrono>
#include <functional>
#include <optional>


namespace cru
{
    using TimerAction = std::function<void()>;

    class TimerManager : public Object
    {
    public:
        static TimerManager* GetInstance();

    private:
        TimerManager() = default;
    public:
        TimerManager(const TimerManager& other) = delete;
        TimerManager(TimerManager&& other) = delete;
        TimerManager& operator=(const TimerManager& other) = delete;
        TimerManager& operator=(TimerManager&& other) = delete;
        ~TimerManager() override = default;

        UINT_PTR CreateTimer(UINT milliseconds, bool loop, const TimerAction& action);
        void KillTimer(UINT_PTR id);
        std::optional<std::pair<bool, TimerAction>> GetAction(UINT_PTR id);

    private:
        std::map<UINT_PTR, std::pair<bool, TimerAction>> map_{};
        UINT_PTR current_count_ = 0;
    };

    class TimerTask
    {
        friend TimerTask SetTimeout(std::chrono::milliseconds milliseconds, const TimerAction& action);
        friend TimerTask SetInterval(std::chrono::milliseconds milliseconds, const TimerAction& action);

    private:
        explicit TimerTask(UINT_PTR id);

    public:
        TimerTask(const TimerTask& other) = default;
        TimerTask(TimerTask&& other) = default;
        TimerTask& operator=(const TimerTask& other) = default;
        TimerTask& operator=(TimerTask&& other) = default;
        ~TimerTask() = default;

        void Cancel() const;

    private:
        UINT_PTR id_;
    };

    TimerTask SetTimeout(std::chrono::milliseconds milliseconds, const TimerAction& action);
    TimerTask SetInterval(std::chrono::milliseconds milliseconds, const TimerAction& action);
}
//--------------------------------------------------------
//-------end of file: src\timer.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\window.hpp
//--------------------------------------------------------

#include <map>
#include <list>
#include <memory>

//--------------------------------------------------------
//-------begin of file: src\ui\control.hpp
//--------------------------------------------------------

#include <unordered_map>
#include <any>
#include <utility>

//--------------------------------------------------------
//-------begin of file: src\ui\ui_base.hpp
//--------------------------------------------------------

#include <optional>


namespace cru::ui
{
    struct Point
    {
        constexpr static Point Zero()
        {
            return Point(0, 0);
        }

        constexpr Point() = default;
        constexpr Point(const float x, const float y) : x(x), y(y) { }

        float x = 0;
        float y = 0;
    };

    constexpr bool operator==(const Point& left, const Point& right)
    {
        return left.x == right.x && left.y == right.y;
    }

    constexpr bool operator!=(const Point& left, const Point& right)
    {
        return !(left == right);
    }

    struct Size
    {
        constexpr static Size Zero()
        {
            return Size(0, 0);
        }

        constexpr Size() = default;
        constexpr Size(const float width, const float height) : width(width), height(height) { }

        float width = 0;
        float height = 0;
    };

    constexpr Size operator + (const Size& left, const Size& right)
    {
        return Size(left.width + right.width, left.height + right.height);
    }

    constexpr Size operator - (const Size& left, const Size& right)
    {
        return Size(left.width - right.width, left.height - right.height);
    }

    constexpr bool operator==(const Size& left, const Size& right)
    {
        return left.width == right.width && left.height == right.height;
    }

    constexpr bool operator!=(const Size& left, const Size& right)
    {
        return !(left == right);
    }

    struct Thickness
    {
        constexpr static Thickness Zero()
        {
            return Thickness(0);
        }

        constexpr Thickness() : Thickness(0) { }

        constexpr explicit Thickness(const float width)
            : left(width), top(width), right(width), bottom(width) { }

        constexpr explicit Thickness(const float horizontal, const float vertical)
            : left(horizontal), top(vertical), right(horizontal), bottom(vertical) { }

        constexpr Thickness(const float left, const float top, const float right, const float bottom)
            : left(left), top(top), right(right), bottom(bottom) { }

        float GetHorizontalTotal() const
        {
            return left + right;
        }

        float GetVerticalTotal() const
        {
            return top + bottom;
        }

        float Validate() const
        {
            return left >= 0.0 && top >= 0.0 && right >= 0.0 && bottom >= 0.0;
        }

        float left;
        float top;
        float right;
        float bottom;
    };

    struct Rect
    {
        constexpr Rect() = default;
        constexpr Rect(const float left, const float top, const float width, const float height)
            : left(left), top(top), width(width), height(height) { }
        constexpr Rect(const Point& lefttop, const Size& size)
            : left(lefttop.x), top(lefttop.y), width(size.width), height(size.height) { }

        constexpr static Rect FromVertices(const float left, const float top, const float right, const float bottom)
        {
            return Rect(left, top, right - left, bottom - top);
        }

        constexpr float GetRight() const
        {
            return left + width;
        }

        constexpr float GetBottom() const
        {
            return top + height;
        }

        constexpr Point GetLeftTop() const
        {
            return Point(left, top);
        }

        constexpr Point GetRightBottom() const
        {
            return Point(left + width, top + height);
        }

        constexpr Size GetSize() const
        {
            return Size(width, height);
        }

        constexpr Rect Shrink(const Thickness& thickness) const
        {
            return Rect(left + thickness.left, top + thickness.top, width - thickness.GetHorizontalTotal(), height - thickness.GetVerticalTotal());
        }

        constexpr bool IsPointInside(const Point& point) const
        {
            return
                point.x >= left &&
                point.x < GetRight() &&
                point.y >= top &&
                point.y < GetBottom();
        }

        float left = 0.0f;
        float top = 0.0f;
        float width = 0.0f;
        float height = 0.0f;
    };

    enum class MouseButton
    {
        Left,
        Right,
        Middle
    };

    struct TextRange
    {
        constexpr static std::optional<TextRange> FromTwoSides(unsigned first, unsigned second)
        {
            if (first > second)
                return std::make_optional<TextRange>(second, first - second);
            if (first < second)
                return std::make_optional<TextRange>(first, second - first);
            return std::nullopt;
        }

        constexpr static std::pair<unsigned, unsigned> ToTwoSides(std::optional<TextRange> text_range, unsigned default_position = 0)
        {
            if (text_range.has_value())
                return std::make_pair(text_range.value().position, text_range.value().position + text_range.value().count);
            return std::make_pair(default_position, default_position);
        }

        constexpr TextRange() = default;
        constexpr TextRange(const unsigned position, const unsigned count)
            : position(position), count(count)
        {

        }

        unsigned position = 0;
        unsigned count = 0;
    };

    bool IsKeyDown(int virtual_code);
    bool IsKeyToggled(int virtual_code);
    bool IsAnyMouseButtonDown();
}
//--------------------------------------------------------
//-------end of file: src\ui\ui_base.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\layout_base.hpp
//--------------------------------------------------------

#include <unordered_set>


namespace cru::ui
{
    class Control;
    class Window;

    enum class Alignment
    {
        Center,
        Start,
        End
    };

    enum class MeasureMode
    {
        Exactly,
        Content,
        Stretch
    };

    enum class RectRange
    {
        Content, // content excluding padding, border and margin
        Padding, // only including content and padding
        HalfBorder, // including content, padding and half border
        FullBorder, // including content, padding and full border
        Margin // including content, padding, border and margin
    };

    struct LayoutSideParams final
    {
        constexpr static LayoutSideParams Exactly(const float length, const Alignment alignment = Alignment::Center)
        {
            return LayoutSideParams(MeasureMode::Exactly, length, alignment);
        }

        constexpr static LayoutSideParams Content(const Alignment alignment = Alignment::Center)
        {
            return LayoutSideParams(MeasureMode::Content, 0, alignment);
        }

        constexpr static LayoutSideParams Stretch(const Alignment alignment = Alignment::Center)
        {
            return LayoutSideParams(MeasureMode::Stretch, 0, alignment);
        }

        constexpr LayoutSideParams() = default;

        constexpr explicit LayoutSideParams(const MeasureMode mode, const float length, const Alignment alignment)
            : length(length), mode(mode), alignment(alignment)
        {

        }

        constexpr bool Validate() const
        {
            if (length < 0.0)
                return false;
            if (min.has_value() && min.value() < 0.0)
                return false;
            if (max.has_value() && max.value() < 0.0)
                return false;
            if (min.has_value() && max.has_value() && min.value() > max.value())
                return false;
            return true;
        }

        // only used in exactly mode, specify the exactly side length of content.
        float length = 0.0;
        MeasureMode mode = MeasureMode::Content;
        Alignment alignment = Alignment::Center;

        // min and max specify the min/max side length of content.
        // they are used as hint and respect the actual size that content needs.
        // when mode is exactly, length is coerced into the min-max range.
        std::optional<float> min = std::nullopt;
        std::optional<float> max = std::nullopt;
    };

    struct BasicLayoutParams final
    {
        BasicLayoutParams() = default;
        BasicLayoutParams(const BasicLayoutParams&) = default;
        BasicLayoutParams(BasicLayoutParams&&) = default;
        BasicLayoutParams& operator = (const BasicLayoutParams&) = default;
        BasicLayoutParams& operator = (BasicLayoutParams&&) = default;
        ~BasicLayoutParams() = default;

        bool Validate() const
        {
            return width.Validate() && height.Validate() && margin.Validate() && padding.Validate();
        }

        LayoutSideParams width;
        LayoutSideParams height;
        Thickness padding;
        Thickness margin;
    };


    class LayoutManager : public Object
    {
    public:
        static LayoutManager* GetInstance();
    private:
        LayoutManager() = default;
    public:
        LayoutManager(const LayoutManager& other) = delete;
        LayoutManager(LayoutManager&& other) = delete;
        LayoutManager& operator=(const LayoutManager& other) = delete;
        LayoutManager& operator=(LayoutManager&& other) = delete;
        ~LayoutManager() override = default;


        //*************** region: position cache ***************

        //Mark position cache of the control and its descendants invalid,
        //(which is saved as an auto-managed list internal)
        //and send a message to refresh them.
        void InvalidateControlPositionCache(Control* control);

        //Refresh position cache of the control and its descendants whose cache
        //has been marked as invalid.
        void RefreshInvalidControlPositionCache();

        //Refresh position cache of the control and its descendants immediately.
        static void RefreshControlPositionCache(Control* control);

    private:
        static void RefreshControlPositionCacheInternal(Control* control, const Point& parent_lefttop_absolute);

    private:
        std::unordered_set<Control*> cache_invalid_controls_;
        std::unordered_set<Window*> layout_invalid_windows_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\layout_base.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\events\ui_event.hpp
//--------------------------------------------------------

#include <optional>

//--------------------------------------------------------
//-------begin of file: src\cru_event.hpp
//--------------------------------------------------------

#include <type_traits>
#include <functional>
#include <unordered_map>


namespace cru {
	//Base class of all event args.
	class BasicEventArgs : public Object
	{
	public:
		explicit BasicEventArgs(Object* sender)
            : sender_(sender)
		{
		    
		}
	    BasicEventArgs(const BasicEventArgs& other) = default;
	    BasicEventArgs(BasicEventArgs&& other) = default;
	    BasicEventArgs& operator=(const BasicEventArgs& other) = default;
	    BasicEventArgs& operator=(BasicEventArgs&& other) = default;
		~BasicEventArgs() override = default;

		//Get the sender of the event.
		Object* GetSender() const
		{
            return sender_;
		}

	private:
		Object* sender_;
	};


	//A non-copyable non-movable Event class.
	//It stores a list of event handlers.
	//TArgsType must be subclass of BasicEventArgs.
    template<typename TArgsType>
    class Event
	{
    public:
		static_assert(std::is_base_of_v<BasicEventArgs, TArgsType>,
			"TArgsType must be subclass of BasicEventArgs.");


        using ArgsType = TArgsType;
        using EventHandler = std::function<void(ArgsType&)>;
        using EventHandlerToken = long;

        Event() = default;
        Event(const Event&) = delete;
        Event& operator = (const Event&) = delete;
        Event(Event&&) = delete;
        Event& operator = (Event&&) = delete;
        ~Event() = default;

        EventHandlerToken AddHandler(const EventHandler& handler)
		{
            const auto token = current_token_++;
		    handlers_.emplace(token, handler);
            return token;
		}

		void RemoveHandler(const EventHandlerToken token) {
			auto find_result = handlers_.find(token);
			if (find_result != handlers_.cend())
				handlers_.erase(find_result);
		}

		void Raise(ArgsType& args) {
			for (const auto& handler : handlers_)
				(handler.second)(args);
		}

        bool IsNoHandler() const
		{
		    return handlers_.empty();
		}

    private:
        std::unordered_map<EventHandlerToken, EventHandler> handlers_;

        EventHandlerToken current_token_ = 0;
    };
}
//--------------------------------------------------------
//-------end of file: src\cru_event.hpp
//--------------------------------------------------------

namespace cru::ui
{
    class Control;
}

namespace cru::ui::events
{
    class UiEventArgs : public BasicEventArgs
    {
    public:
        UiEventArgs(Object* sender, Object* original_sender)
            : BasicEventArgs(sender), original_sender_(original_sender)
        {

        }

        UiEventArgs(const UiEventArgs& other) = default;
        UiEventArgs(UiEventArgs&& other) = default;
        UiEventArgs& operator=(const UiEventArgs& other) = default;
        UiEventArgs& operator=(UiEventArgs&& other) = default;
        ~UiEventArgs() override = default;

        Object* GetOriginalSender() const
        {
            return original_sender_;
        }

    private:
        Object* original_sender_;
    };


    class MouseEventArgs : public UiEventArgs
    {
    public:
        MouseEventArgs(Object* sender, Object* original_sender, const std::optional<Point>& point = std::nullopt)
            : UiEventArgs(sender, original_sender), point_(point)
        {

        }
        MouseEventArgs(const MouseEventArgs& other) = default;
        MouseEventArgs(MouseEventArgs&& other) = default;
        MouseEventArgs& operator=(const MouseEventArgs& other) = default;
        MouseEventArgs& operator=(MouseEventArgs&& other) = default;
        ~MouseEventArgs() override = default;

        Point GetPoint(Control* control, RectRange range = RectRange::Content) const;

    private:
        std::optional<Point> point_;
    };


    class MouseButtonEventArgs : public MouseEventArgs
    {
    public:
        MouseButtonEventArgs(Object* sender, Object* original_sender, const Point& point, const MouseButton button)
            : MouseEventArgs(sender, original_sender, point), button_(button)
        {

        }
        MouseButtonEventArgs(const MouseButtonEventArgs& other) = default;
        MouseButtonEventArgs(MouseButtonEventArgs&& other) = default;
        MouseButtonEventArgs& operator=(const MouseButtonEventArgs& other) = default;
        MouseButtonEventArgs& operator=(MouseButtonEventArgs&& other) = default;
        ~MouseButtonEventArgs() override = default;

        MouseButton GetMouseButton() const
        {
            return button_;
        }

    private:
        MouseButton button_;
    };


    class DrawEventArgs : public UiEventArgs
    {
    public:
        DrawEventArgs(Object* sender, Object* original_sender, ID2D1DeviceContext* device_context)
            : UiEventArgs(sender, original_sender), device_context_(device_context)
        {

        }
        DrawEventArgs(const DrawEventArgs& other) = default;
        DrawEventArgs(DrawEventArgs&& other) = default;
        DrawEventArgs& operator=(const DrawEventArgs& other) = default;
        DrawEventArgs& operator=(DrawEventArgs&& other) = default;
        ~DrawEventArgs() = default;

        ID2D1DeviceContext* GetDeviceContext() const
        {
            return device_context_;
        }

    private:
        ID2D1DeviceContext * device_context_;
    };


    class PositionChangedEventArgs : public UiEventArgs
    {
    public:
        PositionChangedEventArgs(Object* sender, Object* original_sender, const Point& old_position, const Point& new_position)
            : UiEventArgs(sender, original_sender), old_position_(old_position), new_position_(new_position)
        {

        }
        PositionChangedEventArgs(const PositionChangedEventArgs& other) = default;
        PositionChangedEventArgs(PositionChangedEventArgs&& other) = default;
        PositionChangedEventArgs& operator=(const PositionChangedEventArgs& other) = default;
        PositionChangedEventArgs& operator=(PositionChangedEventArgs&& other) = default;
        ~PositionChangedEventArgs() override = default;

        Point GetOldPosition() const
        {
            return old_position_;
        }

        Point GetNewPosition() const
        {
            return new_position_;
        }

    private:
        Point old_position_;
        Point new_position_;
    };


    class SizeChangedEventArgs : public UiEventArgs
    {
    public:
        SizeChangedEventArgs(Object* sender, Object* original_sender, const Size& old_size, const Size& new_size)
            : UiEventArgs(sender, original_sender), old_size_(old_size), new_size_(new_size)
        {

        }
        SizeChangedEventArgs(const SizeChangedEventArgs& other) = default;
        SizeChangedEventArgs(SizeChangedEventArgs&& other) = default;
        SizeChangedEventArgs& operator=(const SizeChangedEventArgs& other) = default;
        SizeChangedEventArgs& operator=(SizeChangedEventArgs&& other) = default;
        ~SizeChangedEventArgs() override = default;

        Size GetOldSize() const
        {
            return old_size_;
        }

        Size GetNewSize() const
        {
            return new_size_;
        }

    private:
        Size old_size_;
        Size new_size_;
    };

    class FocusChangeEventArgs : public UiEventArgs
    {
    public:
        FocusChangeEventArgs(Object* sender, Object* original_sender, const bool is_window = false)
            : UiEventArgs(sender, original_sender), is_window_(is_window)
        {

        }
        FocusChangeEventArgs(const FocusChangeEventArgs& other) = default;
        FocusChangeEventArgs(FocusChangeEventArgs&& other) = default;
        FocusChangeEventArgs& operator=(const FocusChangeEventArgs& other) = default;
        FocusChangeEventArgs& operator=(FocusChangeEventArgs&& other) = default;
        ~FocusChangeEventArgs() override = default;

        // Return whether the focus change is caused by the window-wide focus change.
        bool IsWindow() const
        {
            return is_window_;
        }

    private:
        bool is_window_;
    };

    class ToggleEventArgs : public UiEventArgs
    {
    public:
        ToggleEventArgs(Object* sender, Object* original_sender, bool new_state)
            : UiEventArgs(sender, original_sender), new_state_(new_state)
        {

        }
        ToggleEventArgs(const ToggleEventArgs& other) = default;
        ToggleEventArgs(ToggleEventArgs&& other) = default;
        ToggleEventArgs& operator=(const ToggleEventArgs& other) = default;
        ToggleEventArgs& operator=(ToggleEventArgs&& other) = default;
        ~ToggleEventArgs() override = default;

        bool GetNewState() const
        {
            return new_state_;
        }

    private:
        bool new_state_;
    };

    struct WindowNativeMessage
    {
        HWND hwnd;
        int msg;
        WPARAM w_param;
        LPARAM l_param;
    };

    class WindowNativeMessageEventArgs : public UiEventArgs
    {
    public:
        WindowNativeMessageEventArgs(Object* sender, Object* original_sender, const WindowNativeMessage& message)
            : UiEventArgs(sender, original_sender), message_(message), result_(std::nullopt)
        {

        }
        WindowNativeMessageEventArgs(const WindowNativeMessageEventArgs& other) = default;
        WindowNativeMessageEventArgs(WindowNativeMessageEventArgs&& other) = default;
        WindowNativeMessageEventArgs& operator=(const WindowNativeMessageEventArgs& other) = default;
        WindowNativeMessageEventArgs& operator=(WindowNativeMessageEventArgs&& other) = default;
        ~WindowNativeMessageEventArgs() override = default;

        WindowNativeMessage GetWindowMessage() const
        {
            return message_;
        }

        std::optional<LRESULT> GetResult() const
        {
            return result_;
        }

        void SetResult(const std::optional<LRESULT> result)
        {
            result_ = result;
        }

    private:
        WindowNativeMessage message_;
        std::optional<LRESULT> result_;
    };

    class KeyEventArgs : public UiEventArgs
    {
    public:
        KeyEventArgs(Object* sender, Object* original_sender, int virtual_code)
            : UiEventArgs(sender, original_sender), virtual_code_(virtual_code)
        {
        }
        KeyEventArgs(const KeyEventArgs& other) = default;
        KeyEventArgs(KeyEventArgs&& other) = default;
        KeyEventArgs& operator=(const KeyEventArgs& other) = default;
        KeyEventArgs& operator=(KeyEventArgs&& other) = default;
        ~KeyEventArgs() override = default;

        int GetVirtualCode() const
        {
            return virtual_code_;
        }

    private:
        int virtual_code_;
    };

    class CharEventArgs : public UiEventArgs
    {
    public:
        CharEventArgs(Object* sender, Object* original_sender, wchar_t c)
            : UiEventArgs(sender, original_sender), c_(c)
        {
        }
        CharEventArgs(const CharEventArgs& other) = default;
        CharEventArgs(CharEventArgs&& other) = default;
        CharEventArgs& operator=(const CharEventArgs& other) = default;
        CharEventArgs& operator=(CharEventArgs&& other) = default;
        ~CharEventArgs() override = default;

        wchar_t GetChar() const
        {
            return c_;
        }

    private:
        wchar_t c_;
    };

    using UiEvent = Event<UiEventArgs>;
    using MouseEvent = Event<MouseEventArgs>;
    using MouseButtonEvent = Event<MouseButtonEventArgs>;
    using DrawEvent = Event<DrawEventArgs>;
    using PositionChangedEvent = Event<PositionChangedEventArgs>;
    using SizeChangedEvent = Event<SizeChangedEventArgs>;
    using FocusChangeEvent = Event<FocusChangeEventArgs>;
    using ToggleEvent = Event<ToggleEventArgs>;
    using WindowNativeMessageEvent = Event<WindowNativeMessageEventArgs>;
    using KeyEvent = Event<KeyEventArgs>;
    using CharEvent = Event<CharEventArgs>;
}
//--------------------------------------------------------
//-------end of file: src\ui\events\ui_event.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\border_property.hpp
//--------------------------------------------------------




namespace cru::ui
{
    class BorderProperty final
    {
    public:
        BorderProperty();
        explicit BorderProperty(Microsoft::WRL::ComPtr<ID2D1Brush> brush);
        BorderProperty(Microsoft::WRL::ComPtr<ID2D1Brush> brush, float width, float radius_x, float radius_y, Microsoft::WRL::ComPtr<ID2D1StrokeStyle> stroke_style = nullptr);
        BorderProperty(const BorderProperty& other) = default;
        BorderProperty(BorderProperty&& other) = default;
        BorderProperty& operator=(const BorderProperty& other) = default;
        BorderProperty& operator=(BorderProperty&& other) = default;
        ~BorderProperty() = default;


        Microsoft::WRL::ComPtr<ID2D1Brush> GetBrush() const
        {
            return brush_;
        }

        float GetStrokeWidth() const
        {
            return stroke_width_;
        }

        Microsoft::WRL::ComPtr<ID2D1StrokeStyle> GetStrokeStyle() const
        {
            return stroke_style_;
        }

        float GetRadiusX() const
        {
            return radius_x_;
        }

        float GetRadiusY() const
        {
            return radius_y_;
        }

        void SetBrush(Microsoft::WRL::ComPtr<ID2D1Brush> brush)
        {
            Require(brush == nullptr, "Brush of BorderProperty mustn't be null.");
            brush_ = std::move(brush);
        }

        void SetStrokeWidth(const float stroke_width)
        {
            Require(stroke_width >= 0.0f, "Stroke width must be no less than 0.");
            stroke_width_ = stroke_width;
        }

        void SetStrokeStyle(Microsoft::WRL::ComPtr<ID2D1StrokeStyle> stroke_style)
        {
            stroke_style_ = std::move(stroke_style);
        }

        void SetRadiusX(const float radius_x)
        {
            Require(radius_x >= 0.0f, "Radius-x must be no less than 0.");
            radius_x_ = radius_x;
        }

        void SetRadiusY(const float radius_y)
        {
            Require(radius_y >= 0.0f, "Radius-y must be no less than 0.");
            radius_y_ = radius_y;
        }

    private:
        Microsoft::WRL::ComPtr<ID2D1Brush> brush_;
        float stroke_width_ = 1.0f;
        float radius_x_ = 0.0f;
        float radius_y_ = 0.0f;
        Microsoft::WRL::ComPtr<ID2D1StrokeStyle> stroke_style_ = nullptr;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\border_property.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\cursor.hpp
//--------------------------------------------------------

#include <memory>


namespace cru::ui
{
    class Cursor : public Object
    {
    public:
        using Ptr = std::shared_ptr<Cursor>;

        Cursor(HCURSOR handle, bool auto_release);
        Cursor(const Cursor& other) = delete;
        Cursor(Cursor&& other) = delete;
        Cursor& operator=(const Cursor& other) = delete;
        Cursor& operator=(Cursor&& other) = delete;
        ~Cursor() override;

        HCURSOR GetHandle() const
        {
            return handle_;
        }

    private:
        HCURSOR handle_;
        bool auto_release_;
    };

    namespace cursors
    {
        extern Cursor::Ptr arrow;
        extern Cursor::Ptr hand;
        extern Cursor::Ptr i_beam;        
    }
}
//--------------------------------------------------------
//-------end of file: src\ui\cursor.hpp
//--------------------------------------------------------

namespace cru::ui
{
    class Control;
    class Window;


    //the position cache
    struct ControlPositionCache
    {
        //The lefttop relative to the ancestor.
        Point lefttop_position_absolute;
    };

    class Control : public Object
    {
        friend class Window;
        friend class LayoutManager;

    protected:
        struct WindowConstructorTag {}; //Used for constructor for class Window. 

        explicit Control(bool container = false);

        // Used only for creating Window. It will set window_ as window.
        Control(WindowConstructorTag, Window* window);

    public:
        Control(const Control& other) = delete;
        Control(Control&& other) = delete;
        Control& operator=(const Control& other) = delete;
        Control& operator=(Control&& other) = delete;
        ~Control() override;

    public:

        //*************** region: tree ***************
        virtual StringView GetControlType() const = 0;

        bool IsContainer() const
        {
            return is_container_;
        }

        //Get parent of control, return nullptr if it has no parent.
        Control* GetParent() const
        {
            return parent_;
        }

        //Return a immutable vector of all children.
        const std::vector<Control*>& GetChildren() const;

        //Add a child at tail.
        void AddChild(Control* control);

        //Add a child before the position.
        void AddChild(Control* control, int position);

        //Remove a child.
        void RemoveChild(Control* child);

        //Remove a child at specified position.
        void RemoveChild(int position);

        //Get the ancestor of the control.
        Control* GetAncestor();

        //Get the window if attached, otherwise, return nullptr.
        Window* GetWindow() const
        {
            return window_;
        }

        //Traverse the tree rooted the control including itself.
        void TraverseDescendants(const std::function<void(Control*)>& predicate);

        //*************** region: position and size ***************
        // Position and size part must be isolated from layout part.
        // All the operations in this part must be done independently.
        // And layout part must use api of this part.

        //Get the lefttop relative to its parent.
        virtual Point GetPositionRelative();

        //Set the lefttop relative to its parent.
        virtual void SetPositionRelative(const Point& position);

        //Get the actual size.
        virtual Size GetSize();

        //Set the actual size directly without re-layout.
        virtual void SetSize(const Size& size);

        //Get lefttop relative to ancestor. This is only valid when
        //attached to window. Notice that the value is cached.
        //You can invalidate and recalculate it by calling "InvalidatePositionCache". 
        Point GetPositionAbsolute() const;

        //Local point to absolute point.
        Point ControlToWindow(const Point& point) const;

        //Absolute point to local point.
        Point WindowToControl(const Point& point) const;

        // Default implement in Control is test point in border geometry's
        // fill and stroke with width of border.
        virtual bool IsPointInside(const Point& point);


        //*************** region: graphic ***************

        //Draw this control and its child controls.
        void Draw(ID2D1DeviceContext* device_context);

        virtual void Repaint();

        Microsoft::WRL::ComPtr<ID2D1Brush> GetForegroundBrush() const
        {
            return foreground_brush_;
        }

        void SetForegroundBrush(Microsoft::WRL::ComPtr<ID2D1Brush> foreground_brush)
        {
            foreground_brush_ = std::move(foreground_brush);
            Repaint();
        }

        Microsoft::WRL::ComPtr<ID2D1Brush> GetBackgroundBrush() const
        {
            return background_brush_;
        }

        void SetBackgroundBrush(Microsoft::WRL::ComPtr<ID2D1Brush> background_brush)
        {
            background_brush_ = std::move(background_brush);
            Repaint();
        }


        //*************** region: focus ***************

        bool RequestFocus();

        bool HasFocus();

        bool IsFocusOnPressed() const
        {
            return is_focus_on_pressed_;
        }

        void SetFocusOnPressed(const bool value)
        {
            is_focus_on_pressed_ = value;
        }

        //*************** region: layout ***************

        void InvalidateLayout();

        void Measure(const Size& available_size);

        void Layout(const Rect& rect);

        Size GetDesiredSize() const;

        void SetDesiredSize(const Size& desired_size);

        BasicLayoutParams* GetLayoutParams()
        {
            return &layout_params_;
        }

        Rect GetRect(RectRange range);

        Point TransformPoint(const Point& point, RectRange from = RectRange::Margin, RectRange to = RectRange::Content);

        //*************** region: border ***************

        BorderProperty& GetBorderProperty()
        {
            return border_property_;
        }

        void InvalidateBorder();

        bool IsBordered() const
        {
            return is_bordered_;
        }

        void SetBordered(bool bordered);


        //*************** region: additional properties ***************
        AnyMap* GetAdditionalPropertyMap()
        {
            return &additional_property_map_;
        }

        
        //*************** region: cursor ***************
        // If cursor is set to null, then it uses parent's cursor.
        // Window's cursor can't be null.

        Cursor::Ptr GetCursor() const
        {
            return cursor_;
        }

        void SetCursor(const Cursor::Ptr& cursor);


        //*************** region: events ***************
        //Raised when mouse enter the control.
        events::MouseEvent mouse_enter_event;
        //Raised when mouse is leave the control.
        events::MouseEvent mouse_leave_event;
        //Raised when mouse is move in the control.
        events::MouseEvent mouse_move_event;
        //Raised when a mouse button is pressed in the control.
        events::MouseButtonEvent mouse_down_event;
        //Raised when a mouse button is released in the control.
        events::MouseButtonEvent mouse_up_event;
        //Raised when a mouse button is pressed in the control and released in the control with mouse not leaving it between two operations.
        events::MouseButtonEvent mouse_click_event;

        events::KeyEvent key_down_event;
        events::KeyEvent key_up_event;
        events::CharEvent char_event;

        events::FocusChangeEvent get_focus_event;
        events::FocusChangeEvent lose_focus_event;

        events::DrawEvent draw_content_event;
        events::DrawEvent draw_background_event;
        events::DrawEvent draw_foreground_event;

        events::PositionChangedEvent position_changed_event;
        events::SizeChangedEvent size_changed_event;

    protected:
        //Invoked when a child is added. Overrides should invoke base.
        virtual void OnAddChild(Control* child);
        //Invoked when a child is removed. Overrides should invoke base.
        virtual void OnRemoveChild(Control* child);

        //Invoked when the control is attached to a window. Overrides should invoke base.
        virtual void OnAttachToWindow(Window* window);
        //Invoked when the control is detached to a window. Overrides should invoke base.
        virtual void OnDetachToWindow(Window* window);

    private:
        void OnDrawCore(ID2D1DeviceContext* device_context);

    protected:

        //*************** region: graphic events ***************
        virtual void OnDrawContent(ID2D1DeviceContext* device_context);
        virtual void OnDrawForeground(ID2D1DeviceContext* device_context);
        virtual void OnDrawBackground(ID2D1DeviceContext* device_context);

        // For a event, the window event system will first dispatch event to core functions.
        // Therefore for particular controls, you should do essential actions in core functions,
        // and override version should invoke base version. The base core function
        // in "Control" class will call corresponding non-core function and call "Raise" on
        // event objects. So user custom actions should be done by overriding non-core function
        // and calling the base version is optional.

        //*************** region: position and size event ***************
        virtual void OnPositionChanged(events::PositionChangedEventArgs& args);
        virtual void OnSizeChanged(events::SizeChangedEventArgs& args);

        virtual void OnPositionChangedCore(events::PositionChangedEventArgs& args);
        virtual void OnSizeChangedCore(events::SizeChangedEventArgs& args);

        void RaisePositionChangedEvent(events::PositionChangedEventArgs& args);
        void RaiseSizeChangedEvent(events::SizeChangedEventArgs& args);

        void RegenerateBorderGeometry();

        //*************** region: mouse event ***************
        virtual void OnMouseEnter(events::MouseEventArgs& args);
        virtual void OnMouseLeave(events::MouseEventArgs& args);
        virtual void OnMouseMove(events::MouseEventArgs& args);
        virtual void OnMouseDown(events::MouseButtonEventArgs& args);
        virtual void OnMouseUp(events::MouseButtonEventArgs& args);
        virtual void OnMouseClick(events::MouseButtonEventArgs& args);

        virtual void OnMouseEnterCore(events::MouseEventArgs& args);
        virtual void OnMouseLeaveCore(events::MouseEventArgs& args);
        virtual void OnMouseMoveCore(events::MouseEventArgs& args);
        virtual void OnMouseDownCore(events::MouseButtonEventArgs& args);
        virtual void OnMouseUpCore(events::MouseButtonEventArgs& args);
        virtual void OnMouseClickCore(events::MouseButtonEventArgs& args);

        void RaiseMouseEnterEvent(events::MouseEventArgs& args);
        void RaiseMouseLeaveEvent(events::MouseEventArgs& args);
        void RaiseMouseMoveEvent(events::MouseEventArgs& args);
        void RaiseMouseDownEvent(events::MouseButtonEventArgs& args);
        void RaiseMouseUpEvent(events::MouseButtonEventArgs& args);
        void RaiseMouseClickEvent(events::MouseButtonEventArgs& args);

        virtual void OnMouseClickBegin(MouseButton button);
        virtual void OnMouseClickEnd(MouseButton button);

        //*************** region: keyboard event ***************
        virtual void OnKeyDown(events::KeyEventArgs& args);
        virtual void OnKeyUp(events::KeyEventArgs& args);
        virtual void OnChar(events::CharEventArgs& args);

        virtual void OnKeyDownCore(events::KeyEventArgs& args);
        virtual void OnKeyUpCore(events::KeyEventArgs& args);
        virtual void OnCharCore(events::CharEventArgs& args);

        void RaiseKeyDownEvent(events::KeyEventArgs& args);
        void RaiseKeyUpEvent(events::KeyEventArgs& args);
        void RaiseCharEvent(events::CharEventArgs& args);

        //*************** region: focus event ***************
        virtual void OnGetFocus(events::FocusChangeEventArgs& args);
        virtual void OnLoseFocus(events::FocusChangeEventArgs& args);

        virtual void OnGetFocusCore(events::FocusChangeEventArgs& args);
        virtual void OnLoseFocusCore(events::FocusChangeEventArgs& args);

        void RaiseGetFocusEvent(events::FocusChangeEventArgs& args);
        void RaiseLoseFocusEvent(events::FocusChangeEventArgs& args);

        //*************** region: layout ***************
        Size OnMeasureCore(const Size& available_size);
        void OnLayoutCore(const Rect& rect);

        virtual Size OnMeasureContent(const Size& available_size);
        virtual void OnLayoutContent(const Rect& rect);

    private:
        // Only for layout manager to use.
        // Check if the old position is updated to current position.
        // If not, then a notify of position change and update will
        // be done.
        void CheckAndNotifyPositionChanged();

        void ThrowIfNotContainer() const
        {
            if (!is_container_)
                throw std::runtime_error("You can't perform such operation on a non-container control.");
        }

    private:
        bool is_container_;

    protected:
        Window * window_ = nullptr; // protected for Window class to write it as itself in constructor.

    private:
        Control * parent_ = nullptr;
        std::vector<Control*> children_{};

        // When position is changed and notification hasn't been
        // sent, it will be the old position. When position is changed
        // more than once, it will be the oldest position since last
        // notification. If notification has been sent, it will be updated
        // to position_.
        Point old_position_ = Point::Zero();
        Point position_ = Point::Zero();
        Size size_ = Size::Zero();

        ControlPositionCache position_cache_{};

        bool is_mouse_inside_ = false;

        std::unordered_map<MouseButton, bool> is_mouse_click_valid_map_
        {
            { MouseButton::Left, true },
            { MouseButton::Middle, true },
            { MouseButton::Right, true }
        }; // used for clicking determination

        BasicLayoutParams layout_params_{};
        Size desired_size_ = Size::Zero();

        bool is_bordered_ = false;
        BorderProperty border_property_;

        Microsoft::WRL::ComPtr<ID2D1Geometry> border_geometry_ = nullptr;
        Microsoft::WRL::ComPtr<ID2D1Geometry> in_border_geometry_ = nullptr; //used for foreground and background brush.

        Microsoft::WRL::ComPtr<ID2D1Brush> foreground_brush_ = nullptr;
        Microsoft::WRL::ComPtr<ID2D1Brush> background_brush_ = nullptr;

        AnyMap additional_property_map_{};

        bool is_focus_on_pressed_ = true;

#ifdef CRU_DEBUG_LAYOUT
        Microsoft::WRL::ComPtr<ID2D1Geometry> margin_geometry_;
        Microsoft::WRL::ComPtr<ID2D1Geometry> padding_geometry_;
#endif

        Cursor::Ptr cursor_{};
    };

    // Find the lowest common ancestor.
    // Return nullptr if "left" and "right" are not in the same tree.
    Control* FindLowestCommonAncestor(Control* left, Control* right);

    // Return the ancestor if one control is the ancestor of the other one, otherwise nullptr.
    Control* IsAncestorOrDescendant(Control* left, Control* right);

    template <typename TControl, typename... Args>
    TControl* CreateWithLayout(const LayoutSideParams& width, const LayoutSideParams& height, Args&&... args)
    {
        static_assert(std::is_base_of_v<Control, TControl>, "TControl is not a control class.");
        TControl* control = TControl::Create(std::forward<Args>(args)...);
        control->GetLayoutParams()->width = width;
        control->GetLayoutParams()->height = height;
        return control;
    }


    template <typename TControl, typename... Args>
    TControl* CreateWithLayout(const Thickness& padding, const Thickness& margin, Args&&... args)
    {
        static_assert(std::is_base_of_v<Control, TControl>, "TControl is not a control class.");
        TControl* control = TControl::Create(std::forward<Args>(args)...);
        control->GetLayoutParams()->padding = padding;
        control->GetLayoutParams()->margin = margin;
        return control;
    }

    template <typename TControl, typename... Args>
    TControl* CreateWithLayout(const LayoutSideParams& width, const LayoutSideParams& height, const Thickness& padding, const Thickness& margin, Args&&... args)
    {
        static_assert(std::is_base_of_v<Control, TControl>, "TControl is not a control class.");
        TControl* control = TControl::Create(std::forward<Args>(args)...);
        control->GetLayoutParams()->width = width;
        control->GetLayoutParams()->height = height;
        control->GetLayoutParams()->padding = padding;
        control->GetLayoutParams()->margin = margin;
        return control;
    }

    using ControlList = std::initializer_list<Control*>;
}
//--------------------------------------------------------
//-------end of file: src\ui\control.hpp
//--------------------------------------------------------

namespace cru::graph
{
    class WindowRenderTarget;
}

namespace cru::ui
{
    class WindowClass : public Object
    {
    public:
        WindowClass(const String& name, WNDPROC window_proc, HINSTANCE h_instance);
        WindowClass(const WindowClass& other) = delete;
        WindowClass(WindowClass&& other) = delete;
        WindowClass& operator=(const WindowClass& other) = delete;
        WindowClass& operator=(WindowClass&& other) = delete;
        ~WindowClass() override = default;


        const wchar_t* GetName() const
        {
            return name_.c_str();
        }

        ATOM GetAtom() const
        {
            return atom_;
        }

    private:
        String name_;
        ATOM atom_;
    };

    class WindowManager : public Object
    {
    public:
        static WindowManager* GetInstance();
    private:
        WindowManager();
    public:
        WindowManager(const WindowManager& other) = delete;
        WindowManager(WindowManager&& other) = delete;
        WindowManager& operator=(const WindowManager& other) = delete;
        WindowManager& operator=(WindowManager&& other) = delete;
        ~WindowManager() override = default;


        //Get the general window class for creating ordinary window.
        WindowClass* GetGeneralWindowClass() const
        {
            return general_window_class_.get();
        }

        //Register a window newly created.
        //This function adds the hwnd to hwnd-window map.
        //It should be called immediately after a window was created.
        void RegisterWindow(HWND hwnd, Window* window);

        //Unregister a window that is going to be destroyed.
        //This function removes the hwnd from the hwnd-window map.
        //It should be called immediately before a window is going to be destroyed,
        void UnregisterWindow(HWND hwnd);

        //Return a pointer to the Window object related to the HWND or nullptr if the hwnd is not in the map.
        Window* FromHandle(HWND hwnd);

        std::vector<Window*> GetAllWindows() const;

    private:
        std::unique_ptr<WindowClass> general_window_class_;
        std::map<HWND, Window*> window_map_;
    };



    class Window final : public Control
    {
        friend class WindowManager;
    public:
        static constexpr auto control_type = L"Window";

    public:
        static Window* CreateOverlapped();
        static Window* CreatePopup(Window* parent, bool caption = false);

    private:
        struct tag_overlapped_constructor {};
        struct tag_popup_constructor {};

        explicit Window(tag_overlapped_constructor);
        Window(tag_popup_constructor, Window* parent, bool caption);

        void AfterCreateHwnd(WindowManager* window_manager);

    public:
        Window(const Window& other) = delete;
        Window(Window&& other) = delete;
        Window& operator=(const Window& other) = delete;
        Window& operator=(Window&& other) = delete;
        ~Window() override;

    public:
        StringView GetControlType() const override final;

        void SetDeleteThisOnDestroy(bool value);

        //*************** region: handle ***************

        //Get the handle of the window. Return null if window is invalid.
        HWND GetWindowHandle() const
        {
            return hwnd_;
        }

        //Return if the window is still valid, that is, hasn't been closed or destroyed.
        bool IsWindowValid() const
        {
            return hwnd_ != nullptr;
        }


        //*************** region: window operations ***************

        Window* GetParentWindow() const
        {
            return parent_window_;
        }

        //Close and destroy the window if the window is valid.
        void Close();

        //Send a repaint message to the window's message queue which may make the window repaint.
        void Repaint() override;

        //Show the window.
        void Show();

        //Hide thw window.
        void Hide();

        //Get the client size.
        Size GetClientSize();

        //Set the client size and repaint.
        void SetClientSize(const Size& size);

        //Get the rect of the window containing frame.
        //The lefttop of the rect is relative to screen lefttop.
        Rect GetWindowRect();

        //Set the rect of the window containing frame.
        //The lefttop of the rect is relative to screen lefttop.
        void SetWindowRect(const Rect& rect);

        //Set the lefttop of the window relative to screen.
        void SetWindowPosition(const Point& position);

        Point PointToScreen(const Point& point);

        Point PointFromScreen(const Point& point);

        //Handle the raw window message.
        //Return true if the message is handled and get the result through "result" argument.
        //Return false if the message is not handled.
        bool HandleWindowMessage(HWND hwnd, int msg, WPARAM w_param, LPARAM l_param, LRESULT& result);

        //*************** region: mouse ***************

        Point GetMousePosition();

        Control* GetMouseHoverControl() const
        {
            return mouse_hover_control_;
        }

        //*************** region: position and size ***************

        //Always return (0, 0) for a window.
        Point GetPositionRelative() override final;

        //This method has no effect for a window.
        void SetPositionRelative(const Point& position) override final;

        //Get the size of client area for a window.
        Size GetSize() override final;

        //This method has no effect for a window. Use SetClientSize instead.
        void SetSize(const Size& size) override final;

        //Override. If point is in client area, it is in window.
        bool IsPointInside(const Point& point) override final;

        //*************** region: layout ***************

        void WindowInvalidateLayout();

        void Relayout();

        void SetSizeFitContent(const Size& max_size = Size(1000, 1000));

        //*************** region: functions ***************

        //Refresh control list.
        //It should be invoked every time a control is added or removed from the tree.
        void RefreshControlList();

        //Get the most top control at "point".
        Control* HitTest(const Point& point);


        //*************** region: focus ***************

        //Request focus for specified control.
        bool RequestFocusFor(Control* control);

        //Get the control that has focus.
        Control* GetFocusControl();


        //*************** region: mouse capture ***************

        Control* CaptureMouseFor(Control* control);
        Control* ReleaseCurrentMouseCapture();

        
        //*************** region: cursor ***************
        void UpdateCursor();

        //*************** region: debug ***************
#ifdef CRU_DEBUG_LAYOUT
        bool IsDebugLayout() const
        {
            return debug_layout_;
        }

        void SetDebugLayout(bool value);
#endif
 
    public:
        //*************** region: events ***************
        events::UiEvent activated_event;
        events::UiEvent deactivated_event;
 
        events::WindowNativeMessageEvent native_message_event;
 
    private:
        //*************** region: native operations ***************
 
        //Get the client rect in pixel.
        RECT GetClientRectPixel();
 
        bool IsMessageInQueue(UINT message);
 
        void SetCursorInternal(HCURSOR cursor);
 
 
        //*************** region: native messages ***************
 
        void OnDestroyInternal();
        void OnPaintInternal();
        void OnResizeInternal(int new_width, int new_height);
 
        void OnSetFocusInternal();
        void OnKillFocusInternal();
 
        void OnMouseMoveInternal(POINT point);
        void OnMouseLeaveInternal();
        void OnMouseDownInternal(MouseButton button, POINT point);
        void OnMouseUpInternal(MouseButton button, POINT point);
 
        void OnKeyDownInternal(int virtual_code);
        void OnKeyUpInternal(int virtual_code);
        void OnCharInternal(wchar_t c);
 
        void OnActivatedInternal();
        void OnDeactivatedInternal();
 
        //*************** region: event dispatcher helper ***************
 
        template<typename EventArgs>
        using EventMethod = void (Control::*)(EventArgs&);
 
        // Dispatch the event.
        // 
        // This will invoke the "event_method" of the control and its parent and parent's
        // parent ... (until "last_receiver" if it's not nullptr) with appropriate args.
        //
        // Args is of type "EventArgs". The first init argument is "sender", which is
        // automatically bound to each receiving control. The second init argument is
        // "original_sender", which is unchanged. And "args" will be perfectly forwarded
        // as the rest arguments.
        template<typename EventArgs, typename... Args>
        void DispatchEvent(Control* original_sender, EventMethod<EventArgs> event_method, Control* last_receiver, Args&&... args)
        {
            auto control = original_sender;
            while (control != nullptr && control != last_receiver)
            {
                EventArgs event_args(control, original_sender, std::forward<Args>(args)...);
                (control->*event_method)(event_args);
                control = control->GetParent();
            }
        }
 
        void DispatchMouseHoverControlChangeEvent(Control* old_control, Control * new_control, const Point& point);
 
    private:
        bool delete_this_on_destroy_ = true;

        HWND hwnd_ = nullptr;
        Window* parent_window_ = nullptr;
        std::shared_ptr<graph::WindowRenderTarget> render_target_{};
 
        std::list<Control*> control_list_{};
 
        Control* mouse_hover_control_ = nullptr;
 
        bool window_focus_ = false;
        Control* focus_control_ = this; // "focus_control_" can't be nullptr
 
        Control* mouse_capture_control_ = nullptr;

        bool is_layout_invalid_ = false;

#ifdef CRU_DEBUG_LAYOUT
        bool debug_layout_ = false;
#endif
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\window.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\cru_debug.hpp
//--------------------------------------------------------

#include <functional>


namespace cru::debug
{
    void DebugMessage(const StringView& message);

#ifdef CRU_DEBUG
    inline void DebugTime(const std::function<void()>& action, const StringView& hint_message)
    {
        const auto before = std::chrono::steady_clock::now();
        action();
        const auto after = std::chrono::steady_clock::now();
        const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(after - before);
        DebugMessage(Format(L"{}: {}ms.\n", hint_message, duration.count()));
    }

    template<typename TReturn>
    TReturn DebugTime(const std::function<TReturn()>& action, const StringView& hint_message)
    {
        const auto before = std::chrono::steady_clock::now();
        auto&& result = action();
        const auto after = std::chrono::steady_clock::now();
        const auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(after - before);
        DebugMessage(Format(L"{}: {}ms.\n", hint_message, duration.count()));
        return std::move(result);
    }
#else
    inline void DebugTime(const std::function<void()>& action, const StringView& hint_message)
    {
        action();
    }

    template<typename TReturn>
    TReturn DebugTime(const std::function<TReturn()>& action, const StringView& hint_message)
    {
        return action();
    }
#endif
}
//--------------------------------------------------------
//-------end of file: src\cru_debug.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\linear_layout.hpp
//--------------------------------------------------------


namespace cru::ui::controls
{
    // Min length of main side in layout params is of no meaning.
    // All children will layout from start and redundant length is blank.
    class LinearLayout : public Control
    {
    public:
        static constexpr auto control_type = L"LinearLayout";

        enum class Orientation
        {
            Horizontal,
            Vertical
        };

        static LinearLayout* Create(const Orientation orientation = Orientation::Vertical, const std::initializer_list<Control*>& children = std::initializer_list<Control*>())
        {
            const auto linear_layout = new LinearLayout(orientation);
                        for (const auto control : children)
                linear_layout->AddChild(control);
            return linear_layout;
        }

    protected:
        explicit LinearLayout(Orientation orientation = Orientation::Vertical);

    public:
        LinearLayout(const LinearLayout& other) = delete;
        LinearLayout(LinearLayout&& other) = delete;
        LinearLayout& operator=(const LinearLayout& other) = delete;
        LinearLayout& operator=(LinearLayout&& other) = delete;
        ~LinearLayout() override = default;

        StringView GetControlType() const override final;

    protected:
        Size OnMeasureContent(const Size& available_size) override;
        void OnLayoutContent(const Rect& rect) override;

    private:
        Orientation orientation_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\linear_layout.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\text_block.hpp
//--------------------------------------------------------

//--------------------------------------------------------
//-------begin of file: src\ui\controls\text_control.hpp
//--------------------------------------------------------


namespace cru::ui::controls
{
    class TextControl : public Control
    {
    protected:
        TextControl(
            const Microsoft::WRL::ComPtr<IDWriteTextFormat>& init_text_format,
            const Microsoft::WRL::ComPtr<ID2D1Brush>& init_brush
        );
    public:
        TextControl(const TextControl& other) = delete;
        TextControl(TextControl&& other) = delete;
        TextControl& operator=(const TextControl& other) = delete;
        TextControl& operator=(TextControl&& other) = delete;
        ~TextControl() override = default;

        String GetText() const
        {
            return text_;
        }

        void SetText(const String& text);

        Microsoft::WRL::ComPtr<ID2D1Brush> GetBrush() const
        {
            return brush_;
        }

        void SetBrush(const Microsoft::WRL::ComPtr<ID2D1Brush>& brush);

        Microsoft::WRL::ComPtr<IDWriteTextFormat> GetTextFormat() const
        {
            return text_format_;
        }

        void SetTextFormat(const Microsoft::WRL::ComPtr<IDWriteTextFormat>& text_format);

        bool IsSelectable() const
        {
            return is_selectable_;
        }

        std::optional<TextRange> GetSelectedRange() const
        {
            return selected_range_;
        }

        void SetSelectedRange(std::optional<TextRange> text_range);

        void ClearSelection()
        {
            SetSelectedRange(std::nullopt);
        }

    protected:
        void SetSelectable(bool is_selectable);

    protected:
        void OnSizeChangedCore(events::SizeChangedEventArgs& args) override final;
        void OnDrawContent(ID2D1DeviceContext* device_context) override;

        void OnMouseDownCore(events::MouseButtonEventArgs& args) override final;
        void OnMouseMoveCore(events::MouseEventArgs& args) override final;
        void OnMouseUpCore(events::MouseButtonEventArgs& args) override final;

        void OnLoseFocusCore(events::FocusChangeEventArgs& args) override;

        Size OnMeasureContent(const Size& available_size) override;


        virtual void RequestChangeCaretPosition(unsigned position);

    private:
        void OnTextChangedCore(const String& old_text, const String& new_text);

        void RecreateTextLayout();

        // param point is the mouse point relative to this control.
        void UpdateCursor(const std::optional<Point>& point);

    private:
        String text_;

        Microsoft::WRL::ComPtr<ID2D1Brush> brush_;
        Microsoft::WRL::ComPtr<ID2D1Brush> selection_brush_;
        Microsoft::WRL::ComPtr<IDWriteTextFormat> text_format_;
    protected:
        Microsoft::WRL::ComPtr<IDWriteTextLayout> text_layout_;

    private:
        bool is_selectable_ = false;

        bool is_selecting_ = false;
        unsigned mouse_down_position_ = 0;
        std::optional<TextRange> selected_range_ = std::nullopt;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\text_control.hpp
//--------------------------------------------------------

namespace cru::ui::controls
{
    class TextBlock : public TextControl
    {
    public:
        static constexpr auto control_type = L"TextBlock";

        static TextBlock* Create(const String& text = L"")
        {
            const auto text_block = new TextBlock();
            text_block->SetText(text);
            return text_block;
        }

    protected:
        TextBlock();
    public:
        TextBlock(const TextBlock& other) = delete;
        TextBlock(TextBlock&& other) = delete;
        TextBlock& operator=(const TextBlock& other) = delete;
        TextBlock& operator=(TextBlock&& other) = delete;
        ~TextBlock() override = default;

        StringView GetControlType() const override final;

        using TextControl::SetSelectable; // Make this public.
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\text_block.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\toggle_button.hpp
//--------------------------------------------------------


namespace cru::ui::controls
{
    class ToggleButton : public Control
    {
    public:
        static constexpr auto control_type = L"ToggleButton";

        static ToggleButton* Create()
        {
            return new ToggleButton();
        }

    protected:
        ToggleButton();

    public:
        ToggleButton(const ToggleButton& other) = delete;
        ToggleButton(ToggleButton&& other) = delete;
        ToggleButton& operator=(const ToggleButton& other) = delete;
        ToggleButton& operator=(ToggleButton&& other) = delete;
        ~ToggleButton() override = default;

        StringView GetControlType() const override final;

        bool IsPointInside(const Point& point) override;

        bool GetState() const
        {
            return state_;
        }

        void SetState(bool state);

        void Toggle();

    public:
        events::ToggleEvent toggle_event;

    protected:
        virtual void OnToggle(events::ToggleEventArgs& args);

    protected:
        void OnDrawContent(ID2D1DeviceContext* device_context) override;

        void OnMouseClickCore(events::MouseButtonEventArgs& args) override;

        Size OnMeasureContent(const Size& available_size) override;

    private:
        void RaiseToggleEvent(bool new_state);

    private:
        bool state_ = false;

        float current_circle_position_;

        Microsoft::WRL::ComPtr<ID2D1RoundedRectangleGeometry> frame_path_;
        Microsoft::WRL::ComPtr<ID2D1Brush> on_brush_;
        Microsoft::WRL::ComPtr<ID2D1Brush> off_brush_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\toggle_button.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\button.hpp
//--------------------------------------------------------

#include <initializer_list>


namespace cru::ui::controls
{
    class Button : public Control
    {
    public:
        static constexpr auto control_type = L"Button";

        static Button* Create(const std::initializer_list<Control*>& children = std::initializer_list<Control*>())
        {
            const auto button = new Button();
            for (const auto control : children)
                button->AddChild(control);
            return button;
        }

    protected:
        Button();

    public:
        Button(const Button& other) = delete;
        Button(Button&& other) = delete;
        Button& operator=(const Button& other) = delete;
        Button& operator=(Button&& other) = delete;
        ~Button() override = default;

        StringView GetControlType() const override final;

    protected:
        void OnMouseClickBegin(MouseButton button) override final;
        void OnMouseClickEnd(MouseButton button) override final;

    private:
        BorderProperty normal_border_;
        BorderProperty pressed_border_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\button.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\text_box.hpp
//--------------------------------------------------------


namespace cru::ui::controls
{
    class TextBox : public TextControl
    {
    public:
        static constexpr auto control_type = L"TextBox";

        static TextBox* Create()
        {
            return new TextBox();
        }

    protected:
        TextBox();
    public:
        TextBox(const TextBox& other) = delete;
        TextBox(TextBox&& other) = delete;
        TextBox& operator=(const TextBox& other) = delete;
        TextBox& operator=(TextBox&& other) = delete;
        ~TextBox() override;

        StringView GetControlType() const override final;

    protected:
        void OnDrawContent(ID2D1DeviceContext* device_context) override;

        void OnGetFocusCore(events::FocusChangeEventArgs& args) override final;
        void OnLoseFocusCore(events::FocusChangeEventArgs& args) override final;

        void OnKeyDownCore(events::KeyEventArgs& args) override final;
        void OnCharCore(events::CharEventArgs& args) override final;

        void RequestChangeCaretPosition(unsigned position) override final;

    private:
        // return true if left
        bool GetCaretSelectionSide() const;
        void ShiftLeftSelectionRange(int count);
        void ShiftRightSelectionRange(int count);

    private:
        unsigned caret_position_ = 0;
        std::optional<TimerTask> caret_timer_{};
        Microsoft::WRL::ComPtr<ID2D1Brush> caret_brush_;
        bool is_caret_show_ = false;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\text_box.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\list_item.hpp
//--------------------------------------------------------

#include <map>
#include <initializer_list>


namespace cru::ui::controls
{
    class ListItem : public Control
    {
    public:
        static constexpr auto control_type = L"ListItem";

        enum class State
        {
            Normal,
            Hover,
            Select
        };

    private:
        struct StateBrush
        {
            Microsoft::WRL::ComPtr<ID2D1Brush> border_brush;
            Microsoft::WRL::ComPtr<ID2D1Brush> fill_brush;
        };

    public:
        static ListItem* Create(const std::initializer_list<Control*>& children)
        {
            const auto list_item = new ListItem();
            for (auto control : children)
                list_item->AddChild(control);
            return list_item;
        }

    private:
        ListItem();
    public:
        ListItem(const ListItem& other) = delete;
        ListItem(ListItem&& other) = delete;
        ListItem& operator=(const ListItem& other) = delete;
        ListItem& operator=(ListItem&& other) = delete;
        ~ListItem() override = default;

        StringView GetControlType() const override;

        State GetState() const
        {
            return state_;
        }

        void SetState(State state);

    protected:
        void OnDrawForeground(ID2D1DeviceContext* device_context) override;

        void OnMouseEnterCore(events::MouseEventArgs& args) override final;
        void OnMouseLeaveCore(events::MouseEventArgs& args) override final;
        void OnMouseClickCore(events::MouseButtonEventArgs& args) override final;

    private:
        State state_ = State::Normal;
        std::map<State, StateBrush> brushes_{};
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\list_item.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\controls\popup_menu.hpp
//--------------------------------------------------------

#include <vector>
#include <utility>
#include <functional>


namespace cru::ui
{
    class Window;
}

namespace cru::ui::controls
{
    using MenuItemInfo = std::pair<String, std::function<void()>>;

    Window* CreatePopupMenu(const Point& anchor, const std::vector<MenuItemInfo>& items, Window* parent = nullptr);
}
//--------------------------------------------------------
//-------end of file: src\ui\controls\popup_menu.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\graph\graph.hpp
//--------------------------------------------------------

#include <memory>
#include <functional>



namespace cru::graph
{
    class GraphManager;

    //Represents a window render target.
    class WindowRenderTarget : public Object
    {
    public:
        WindowRenderTarget(GraphManager* graph_manager, HWND hwnd);
        WindowRenderTarget(const WindowRenderTarget& other) = delete;
        WindowRenderTarget(WindowRenderTarget&& other) = delete;
        WindowRenderTarget& operator=(const WindowRenderTarget& other) = delete;
        WindowRenderTarget& operator=(WindowRenderTarget&& other) = delete;
        ~WindowRenderTarget() override;

    public:
        //Get the graph manager that created the render target.
        GraphManager* GetGraphManager() const
        {
            return graph_manager_;
        }

        //Get the d2d device context.
        inline Microsoft::WRL::ComPtr<ID2D1DeviceContext> GetD2DDeviceContext() const;

        //Get the target bitmap which can be set as the ID2D1DeviceContext's target.
        Microsoft::WRL::ComPtr<ID2D1Bitmap1> GetTargetBitmap() const
        {
            return target_bitmap_;
        }

        //Resize the underlying buffer.
        void ResizeBuffer(int width, int height);

        //Set this render target as the d2d device context's target.
        void SetAsTarget();

        //Present the data of the underlying buffer to the window.
        void Present();

    private:
        void CreateTargetBitmap();

    private:
        GraphManager* graph_manager_;
        Microsoft::WRL::ComPtr<IDXGISwapChain1> dxgi_swap_chain_;
        Microsoft::WRL::ComPtr<ID2D1Bitmap1> target_bitmap_;
    };

    struct Dpi
    {
        float x;
        float y;
    };

    class GraphManager final : public Object
    {
    public:
        static GraphManager* GetInstance();

    private:
        GraphManager();
    public:
        GraphManager(const GraphManager& other) = delete;
        GraphManager(GraphManager&& other) = delete;
        GraphManager& operator=(const GraphManager& other) = delete;
        GraphManager& operator=(GraphManager&& other) = delete;
        ~GraphManager() override;

    public:
        Microsoft::WRL::ComPtr<ID2D1Factory1> GetD2D1Factory() const
        {
            return d2d1_factory_;
        }

        Microsoft::WRL::ComPtr<ID2D1DeviceContext> GetD2D1DeviceContext() const
        {
            return d2d1_device_context_;
        }

        Microsoft::WRL::ComPtr<ID3D11Device> GetD3D11Device() const
        {
            return d3d11_device_;
        }

        Microsoft::WRL::ComPtr<IDXGIFactory2> GetDxgiFactory() const
        {
            return dxgi_factory_;
        }

        Microsoft::WRL::ComPtr<IDWriteFactory> GetDWriteFactory() const
        {
            return dwrite_factory_;
        }


        //Create a window render target with the HWND.
        std::shared_ptr<WindowRenderTarget> CreateWindowRenderTarget(HWND hwnd);

        //Get the desktop dpi.
        Dpi GetDpi() const;

        //Reload system metrics including desktop dpi.
        void ReloadSystemMetrics();

        Microsoft::WRL::ComPtr<IDWriteFontCollection> GetSystemFontCollection() const
        {
            return dwrite_system_font_collection_.Get();
        }

    private:
        Microsoft::WRL::ComPtr<ID3D11Device> d3d11_device_;
        Microsoft::WRL::ComPtr<ID3D11DeviceContext> d3d11_device_context_;
        Microsoft::WRL::ComPtr<ID2D1Factory1> d2d1_factory_;
        Microsoft::WRL::ComPtr<ID2D1Device> d2d1_device_;
        Microsoft::WRL::ComPtr<ID2D1DeviceContext> d2d1_device_context_;
        Microsoft::WRL::ComPtr<IDXGIFactory2> dxgi_factory_;

        Microsoft::WRL::ComPtr<IDWriteFactory> dwrite_factory_;
        Microsoft::WRL::ComPtr<IDWriteFontCollection> dwrite_system_font_collection_;
    };

    inline int DipToPixelInternal(const float dip, const float dpi)
    {
        return static_cast<int>(dip * dpi / 96.0f);
    }

    inline int DipToPixelX(const float dip_x)
    {
        return DipToPixelInternal(dip_x, GraphManager::GetInstance()->GetDpi().x);
    }

    inline int DipToPixelY(const float dip_y)
    {
        return DipToPixelInternal(dip_y, GraphManager::GetInstance()->GetDpi().y);
    }

    inline float DipToPixelInternal(const int pixel, const float dpi)
    {
        return static_cast<float>(pixel) * 96.0f / dpi;
    }

    inline float PixelToDipX(const int pixel_x)
    {
        return DipToPixelInternal(pixel_x, GraphManager::GetInstance()->GetDpi().x);
    }

    inline float PixelToDipY(const int pixel_y)
    {
        return DipToPixelInternal(pixel_y, GraphManager::GetInstance()->GetDpi().y);
    }

    Microsoft::WRL::ComPtr<ID2D1DeviceContext> WindowRenderTarget::GetD2DDeviceContext() const
    {
        return graph_manager_->GetD2D1DeviceContext();
    }

    inline void WithTransform(ID2D1DeviceContext* device_context, const D2D1_MATRIX_3X2_F matrix, const std::function<void(ID2D1DeviceContext*)>& action)
    {
        D2D1_MATRIX_3X2_F old_transform;
        device_context->GetTransform(&old_transform);
        device_context->SetTransform(old_transform * matrix);
        action(device_context);
        device_context->SetTransform(old_transform);
    }

    Microsoft::WRL::ComPtr<ID2D1SolidColorBrush> CreateSolidColorBrush(const D2D1_COLOR_F& color);
}
//--------------------------------------------------------
//-------end of file: src\graph\graph.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\ui_manager.hpp
//--------------------------------------------------------



namespace cru::graph
{
    class GraphManager;
}

namespace cru::ui
{
    struct CaretInfo
    {
        std::chrono::milliseconds caret_blink_duration;
        float half_caret_width;
    };


    class PredefineResources : public Object
    {
    public:
        explicit PredefineResources(graph::GraphManager* graph_manager);
        PredefineResources(const PredefineResources& other) = delete;
        PredefineResources(PredefineResources&& other) = delete;
        PredefineResources& operator=(const PredefineResources& other) = delete;
        PredefineResources& operator=(PredefineResources&& other) = delete;
        ~PredefineResources() override = default;

        //region BorderProperty
        Microsoft::WRL::ComPtr<ID2D1Brush> border_property_brush;

        //region Button
        BorderProperty button_normal_border;
        BorderProperty button_press_border;

        //region TextControl
        Microsoft::WRL::ComPtr<ID2D1Brush> text_control_selection_brush;

        //region TextBox
        BorderProperty text_box_border;
        Microsoft::WRL::ComPtr<ID2D1Brush> text_box_text_brush;
        Microsoft::WRL::ComPtr<IDWriteTextFormat> text_box_text_format;
        Microsoft::WRL::ComPtr<ID2D1Brush> text_box_caret_brush;

        //region TextBlock
        Microsoft::WRL::ComPtr<ID2D1Brush> text_block_text_brush;
        Microsoft::WRL::ComPtr<IDWriteTextFormat> text_block_text_format;

        //region ToggleButton
        Microsoft::WRL::ComPtr<ID2D1Brush> toggle_button_on_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> toggle_button_off_brush;

        //region ListItem
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_normal_border_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_normal_fill_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_hover_border_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_hover_fill_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_select_border_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> list_item_select_fill_brush;


#ifdef CRU_DEBUG_LAYOUT
        //region debug
        Microsoft::WRL::ComPtr<ID2D1Brush> debug_layout_out_border_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> debug_layout_margin_brush;
        Microsoft::WRL::ComPtr<ID2D1Brush> debug_layout_padding_brush;
#endif
    };

    class UiManager : public Object
    {
    public:
        static UiManager* GetInstance();
    private:
        UiManager();
    public:
        UiManager(const UiManager& other) = delete;
        UiManager(UiManager&& other) = delete;
        UiManager& operator=(const UiManager& other) = delete;
        UiManager& operator=(UiManager&& other) = delete;
        ~UiManager() override = default;

        CaretInfo GetCaretInfo() const
        {
            return caret_info_;
        }

        const PredefineResources* GetPredefineResources() const
        {
            return &predefine_resources_;
        }

    private:
        CaretInfo caret_info_;

        PredefineResources predefine_resources_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\ui_manager.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\convert_util.hpp
//--------------------------------------------------------



namespace cru::ui
{
    inline D2D1_POINT_2F Convert(const Point& point)
    {
        return D2D1::Point2F(point.x, point.y);
    }

    inline D2D1_RECT_F Convert(const Rect& rect)
    {
        return D2D1::RectF(rect.left, rect.top, rect.left + rect.width, rect.top + rect.height);
    }
}
//--------------------------------------------------------
//-------end of file: src\ui\convert_util.hpp
//--------------------------------------------------------
//--------------------------------------------------------
//-------begin of file: src\ui\animations\animation.hpp
//--------------------------------------------------------

#include <unordered_map>


namespace cru::ui::animations
{
    using AnimationTimeUnit = FloatSecond;

    struct IAnimationDelegate : virtual Interface
    {
        virtual void Cancel() = 0;
    };

    using AnimationDelegatePtr = std::shared_ptr<IAnimationDelegate>;

    using AnimationStepHandler = std::function<void(AnimationDelegatePtr, double)>;
    using AnimationStartHandler = std::function<void(AnimationDelegatePtr)>;
    using AnimationFinishHandler = std::function<void()>;
    using AnimationCancelHandler = std::function<void()>;

    namespace details
    {
        class Animation;
        using AnimationPtr = std::unique_ptr<Animation>;

        class AnimationInfo
        {
        public:
            AnimationInfo(String tag, const AnimationTimeUnit duration)
                : tag(std::move(tag)),
                  duration(duration)
            {

            }
            AnimationInfo(const AnimationInfo& other) = default;
            AnimationInfo(AnimationInfo&& other) = default;
            AnimationInfo& operator=(const AnimationInfo& other) = default;
            AnimationInfo& operator=(AnimationInfo&& other) = default;
            ~AnimationInfo() = default;

            String tag;
            AnimationTimeUnit duration;
            std::vector<AnimationStepHandler> step_handlers{};
            std::vector<AnimationStartHandler> start_handlers{};
            std::vector<AnimationFinishHandler> finish_handlers{};
            std::vector<AnimationCancelHandler> cancel_handlers{};
        };

        class AnimationManager : public Object
        {
        public:
            static AnimationManager* GetInstance();
        private:
            AnimationManager();
        public:
            AnimationManager(const AnimationManager& other) = delete;
            AnimationManager(AnimationManager&& other) = delete;
            AnimationManager& operator=(const AnimationManager& other) = delete;
            AnimationManager& operator=(AnimationManager&& other) = delete;
            ~AnimationManager() override;

            AnimationDelegatePtr CreateAnimation(AnimationInfo info);
            void RemoveAnimation(const String& tag);

        private:
            void SetTimer();
            void KillTimer();

        private:
            std::unordered_map<String, AnimationPtr> animations_;
            std::optional<TimerTask> timer_;
        };
    }

    class AnimationBuilder : public Object
    {
    public:
        AnimationBuilder(String tag, const AnimationTimeUnit duration)
            : info_(std::move(tag), duration)
        {

        }

        AnimationBuilder& AddStepHandler(const AnimationStepHandler& handler)
        {
            CheckValid();
            info_.step_handlers.push_back(handler);
            return *this;
        }

        AnimationBuilder& AddStartHandler(const AnimationStartHandler& handler)
        {
            CheckValid();
            info_.start_handlers.push_back(handler);
            return *this;
        }

        AnimationBuilder& AddFinishHandler(const AnimationFinishHandler& handler)
        {
            CheckValid();
            info_.finish_handlers.push_back(handler);
            return *this;
        }

        AnimationBuilder& AddCancelHandler(const AnimationCancelHandler& handler)
        {
            CheckValid();
            info_.cancel_handlers.push_back(handler);
            return *this;
        }

        AnimationDelegatePtr Start();

    private:
        void CheckValid() const
        {
            if (!valid_)
                throw std::runtime_error("The animation builder is invalid.");
        }

        bool valid_ = true;
        details::AnimationInfo info_;
    };
}
//--------------------------------------------------------
//-------end of file: src\ui\animations\animation.hpp
//--------------------------------------------------------