summaryrefslogtreecommitdiff
path: root/src/nigui.nim
blob: c8480e53dfac1c744805b7e51512bcd65a4605a8 (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
# NiGui - main file

# This file contains all common code except extra widgets.
# All public procedures are declared here.
# Platform-specific code will added by "include".

# Templates for "include":
template useWindows(): bool = defined(windows) and not defined(forceGtk)
template useGtk(): bool = not useWindows()

# ========================================================================================
#
#                                   Public Declaration
#
# ========================================================================================

# ----------------------------------------------------------------------------------------
#                                     Simple Types
# ----------------------------------------------------------------------------------------

type
  Layout* = enum
    Layout_Horizontal
    Layout_Vertical

  XAlign* = enum
    XAlign_Left
    XAlign_Right
    XAlign_Center
    XAlign_Spread

  YAlign* = enum
    YAlign_Top
    YAlign_Bottom
    YAlign_Center
    YAlign_Spread

  WidthMode* = enum
    WidthMode_Static
    WidthMode_Auto
    WidthMode_Fill
    WidthMode_Expand

  HeightMode* = enum
    HeightMode_Static
    HeightMode_Auto
    HeightMode_Fill
    HeightMode_Expand

  MouseButton* = enum
    MouseButton_Left
    MouseButton_Middle
    MouseButton_Right

  Color* = object
    red*:   byte
    green*: byte
    blue*:  byte
    alpha*: byte

  Spacing* = object
    left*:   int
    right*:  int
    top*:    int
    bottom*: int

  Timer* = distinct int

  Key* = enum
    # Keys with same value than Unicode:
    Key_None       = 0
    Key_Backspace  = 8
    Key_Tab        = 9
    Key_Return     = 13
    Key_Pause      = 19
    Key_CapsLock   = 20
    Key_Escape     = 27
    Key_Space      = 32
    Key_NumberSign = 35
    Key_Plus       = 43
    Key_Comma      = 44
    Key_Minus      = 45
    Key_Point      = 46
    Key_Number0    = 48
    Key_Number1    = 49
    Key_Number2    = 50
    Key_Number3    = 51
    Key_Number4    = 52
    Key_Number5    = 53
    Key_Number6    = 54
    Key_Number7    = 55
    Key_Number8    = 56
    Key_Number9    = 57
    Key_Less       = 60
    Key_A          = 65
    Key_B          = 66
    Key_C          = 67
    Key_D          = 68
    Key_E          = 69
    Key_F          = 70
    Key_G          = 71
    Key_H          = 72
    Key_I          = 73
    Key_J          = 74
    Key_K          = 75
    Key_L          = 76
    Key_M          = 77
    Key_N          = 78
    Key_O          = 79
    Key_P          = 80
    Key_Q          = 81
    Key_R          = 82
    Key_S          = 83
    Key_T          = 84
    Key_U          = 85
    Key_V          = 86
    Key_W          = 87
    Key_X          = 88
    Key_Y          = 89
    Key_Z          = 90
    Key_SuperL     = 91
    Key_SuperR     = 92
    Key_ContextMenu = 93
    Key_Circumflex = 94
    Key_Numpad0    = 96
    Key_Numpad1    = 97
    Key_Numpad2    = 98
    Key_Numpad3    = 99
    Key_Numpad4    = 100
    Key_Numpad5    = 101
    Key_Numpad6    = 102
    Key_Numpad7    = 103
    Key_Numpad8    = 104
    Key_Numpad9    = 105
    Key_NumpadMultiply  = 106
    Key_NumpadAdd       = 107
    Key_NumpadSeparator = 108
    Key_NumpadSubtract  = 109
    Key_NumpadDecimal   = 110
    Key_NumpadDivide    = 111
    Key_F1         = 112
    Key_F2         = 113
    Key_F3         = 114
    Key_F4         = 115
    Key_F5         = 116
    Key_F6         = 117
    Key_F7         = 118
    Key_F8         = 119
    Key_F9         = 120
    Key_F10        = 121
    Key_F11        = 122
    Key_F12        = 123
    Key_F13        = 124
    Key_F14        = 125
    Key_F15        = 126
    Key_F16        = 127
    Key_F17        = 128
    Key_F18        = 129
    Key_F19        = 130
    Key_F20        = 131
    Key_F21        = 132
    Key_F22        = 133
    Key_F23        = 134
    Key_F24        = 135
    Key_NumLock    = 144
    Key_ScrollLock = 145
    Key_AE         = 196
    Key_OE         = 214
    Key_UE         = 220
    Key_SharpS     = 223
    # Not part of Unicode:
    Key_Insert     = 1000
    Key_Delete
    Key_Left
    Key_Right
    Key_Up
    Key_Down
    Key_Home
    Key_End
    Key_PageUp
    Key_PageDown
    Key_ControlL
    Key_ControlR
    Key_AltL
    Key_AltR
    Key_ShiftL
    Key_ShiftR
    Key_Print
    Key_NumpadEnter

const
  inactiveTimer* = 0


# ----------------------------------------------------------------------------------------
#                                   Widget Types 1/3
# ----------------------------------------------------------------------------------------

type
  # Window base type:

  Window* = ref object of RootObj
    fDisposed: bool
    fTitle: string
    fVisible: bool
    fMinimized: bool
    fWidth, fHeight: int
    fClientWidth, fClientHeight: int
    fX, fY: int
    fControl: Control
    fIconPath: string
    fOnDispose: WindowDisposeProc
    fOnCloseClick: CloseClickProc
    fOnResize: ResizeProc
    fOnDropFiles: DropFilesProc
    fOnKeyDown: KeyboardProc

  # Control base type:

  Control* = ref object of RootObj
    fDisposed: bool
    fParentControl: Control # is nil or object of ContainerImpl
    fParentWindow: Window # only set for top level widget
    fIndex: int
    fVisible: bool
    fWidth, fHeight: int
    fX, fY: int
    fWidthMode: WidthMode
    fHeightMode: HeightMode
    fMinWidth, fMinHeight: int
    fMaxWidth, fMaxHeight: int
    fXScrollEnabled, fYScrollEnabled: bool
    fXScrollPos, fYScrollPos: int
    fScrollableWidth, fScrollableHeight: int
    fFontFamily: string
    fFontSize: float
    fFontBold: bool
    fTextColor: Color
    fBackgroundColor: Color
    fUseDefaultFontFamily: bool
    fUseDefaultFontSize: bool
    fUseDefaultTextColor: bool
    fUseDefaultBackgroundColor: bool
    fCanvas: Canvas
    fOnDispose: ControlDisposeProc
    fOnDraw: DrawProc
    fOnMouseButtonDown: MouseButtonProc
    fOnMouseButtonUp: MouseButtonProc
    fOnClick: ClickProc
    # fOnMouseMove: MouseMoveProc
    fOnKeyDown: KeyboardProc
    tag*: string

  # Drawing:

  Canvas* = ref object of RootObj
    fWidth: int
    fHeight: int
    fFontFamily: string
    fFontSize: float
    fFontBold: bool
    fTextColor: Color
    fLineColor: Color
    fLineWidth: float
    fAreaColor: Color

  Image* = ref object of RootObj
    fCanvas: Canvas

  # Window events:

  WindowDisposeEvent* = ref object
    window*: Window
  WindowDisposeProc* = proc(event: WindowDisposeEvent)

  CloseClickEvent* = ref object
    window*: Window
  CloseClickProc* = proc(event: CloseClickEvent)

  ResizeEvent* = ref object
    window*: Window
  ResizeProc* = proc(event: ResizeEvent)

  DropFilesEvent* = ref object
    window*: Window
    files*: seq[string]
  DropFilesProc* = proc(event: DropFilesEvent)

  KeyboardEvent* = ref object
    window*: Window
    control*: Control
    key*: Key
    unicode*: int
    character*: string # UTF-8 character
    handled*: bool
  KeyboardProc* = proc(event: KeyboardEvent)

  # Control events:

  ControlDisposeEvent* = ref object
    control*: Control
  ControlDisposeProc* = proc(event: ControlDisposeEvent)

  DrawEvent* = ref object
    control*: Control
  DrawProc* = proc(event: DrawEvent)

  MouseEvent* = ref object
    control*: Control
    button*: MouseButton
    x*: int
    y*: int
  MouseButtonProc* = proc(event: MouseEvent)

  ClickEvent* = ref object
    control*: Control
  ClickProc* = proc(event: ClickEvent)

  TextChangeEvent* = ref object
    control*: Control
  TextChangeProc* = proc(event: TextChangeEvent)

  ToggleEvent* = ref object
    control*: Control
  ToggleProc* = proc(event: ToggleEvent)

  # Other events:

  ErrorHandlerProc* = proc()

  TimerEvent* = ref object
    timer*: Timer
    data*: pointer
  TimerProc* = proc(event: TimerEvent)

# Platform-specific extension of Window and Control:
when useWindows(): include "nigui/private/windows/platform_types1"
when useGtk():     include "nigui/private/gtk3/platform_types1"


# ----------------------------------------------------------------------------------------
#                                   Widget Types 2/3
# ----------------------------------------------------------------------------------------

type
  # Basic controls:

  Container* = ref object of ControlImpl
    fFrame: Frame
    fChildControls: seq[Control]

  Frame* = ref object of ControlImpl
    fText: string

  Button* = ref object of ControlImpl
    fText: string
    fEnabled: bool

  Checkbox* = ref object of ControlImpl
    fText: string
    fEnabled: bool
    fOnToggle: ToggleProc

  Label* = ref object of ControlImpl
    fText: string

  TextBox* = ref object of ControlImpl
    fEditable: bool
    fOnTextChange: TextChangeProc


# Platform-specific extension:
when useWindows(): include "nigui/private/windows/platform_types2"
when useGtk():     include "nigui/private/gtk3/platform_types2"


# ----------------------------------------------------------------------------------------
#                                   Widget Types 3/3
# ----------------------------------------------------------------------------------------

type
  LayoutContainer* = ref object of ContainerImpl
    fLayout: Layout
    fXAlign: XAlign
    fYAlign: YAlign
    fPadding: int
    fSpacing: int

  TextArea* = ref object of NativeTextBox
    fWrap: bool

# Platform-specific extension:
when useWindows(): include "nigui/private/windows/platform_types3"
when useGtk():     include "nigui/private/gtk3/platform_types3"


# ----------------------------------------------------------------------------------------
#                                    Global Variables
# ----------------------------------------------------------------------------------------

var
  quitOnLastWindowClose* = true
  clickMaxXYMove* = 20

# dummy type and object, needed to use get/set properties
type App = object
var app*: App


# ----------------------------------------------------------------------------------------
#                                  Global/App Procedures
# ----------------------------------------------------------------------------------------

proc init*(app: App)

proc run*(app: App)

proc quit*(app: App)

proc processEvents*(app: App)

proc sleep*(app: App, milliSeconds: float)

proc errorHandler*(app: App): ErrorHandlerProc
proc `errorHandler=`*(app: App, errorHandler: ErrorHandlerProc)

proc defaultBackgroundColor*(app: App): Color
proc `defaultBackgroundColor=`*(app: App, color: Color)

proc defaultTextColor*(app: App): Color
proc `defaultTextColor=`*(app: App, color: Color)

proc defaultFontFamily*(app: App): string
proc `defaultFontFamily=`*(app: App, fontFamily: string)

proc defaultFontSize*(app: App): float
proc `defaultFontSize=`*(app: App, fontSize: float)

proc clipboardText*(app: App): string
proc `clipboardText=`*(app: App, text: string)

proc rgb*(red, green, blue: byte, alpha: byte = 255): Color

proc isDown*(key: Key): bool

proc downKeys*(): seq[Key]

proc scaleToDpi*(val: int): int
proc scaleToDpi*(val: float): float


# ----------------------------------------------------------------------------------------
#                                       Dialogs
# ----------------------------------------------------------------------------------------

proc alert*(window: Window, message: string, title = "Message") {.discardable.}

type OpenFileDialog* = ref object
  title*: string
  directory*: string
  multiple*: bool
  files*: seq[string]

proc newOpenFileDialog*(): OpenFileDialog

method run*(dialog: OpenFileDialog)

type SaveFileDialog* = ref object
  title*: string
  directory*: string
  defaultExtension*: string
  defaultName*: string
  file*: string

proc newSaveFileDialog*(): SaveFileDialog

method run*(dialog: SaveFileDialog)


# ----------------------------------------------------------------------------------------
#                                        Timers
# ----------------------------------------------------------------------------------------

proc startTimer*(milliSeconds: int, timerProc: TimerProc, data: pointer = nil): Timer {.discardable.}

proc startRepeatingTimer*(milliSeconds: int, timerProc: TimerProc, data: pointer = nil): Timer {.discardable.}

proc stop*(timer: var Timer)


# ----------------------------------------------------------------------------------------
#                                        Canvas
# ----------------------------------------------------------------------------------------

proc newCanvas*(control: Control = nil): CanvasImpl

method destroy*(canvas: Canvas)

method width*(canvas: Canvas): int

method height*(canvas: Canvas): int

method fontFamily*(canvas: Canvas): string
method `fontFamily=`*(canvas: Canvas, fontFamily: string)

method fontSize*(canvas: Canvas): float
method `fontSize=`*(canvas: Canvas, fontSize: float)

method fontBold*(canvas: Canvas): bool
method `fontBold=`*(canvas: Canvas, fontBold: bool)

method textColor*(canvas: Canvas): Color
method `textColor=`*(canvas: Canvas, color: Color)

method lineColor*(canvas: Canvas): Color
method `lineColor=`*(canvas: Canvas, color: Color)

method lineWidth*(canvas: Canvas): float
method `lineWidth=`*(canvas: Canvas, width: float)

method areaColor*(canvas: Canvas): Color
method `areaColor=`*(canvas: Canvas, color: Color)

method drawText*(canvas: Canvas, text: string, x, y = 0)

method drawTextCentered*(canvas: Canvas, text: string, x, y = 0, width, height = -1)

method drawLine*(canvas: Canvas, x1, y1, x2, y2: int)

method drawRectArea*(canvas: Canvas, x, y, width, height: int)

method drawRectOutline*(canvas: Canvas, x, y, width, height: int)

method drawEllipseArea*(canvas: Canvas, x, y, width, height: int)

method drawEllipseOutline*(canvas: Canvas, x, y, width, height: int)

method drawArcOutline*(canvas: Canvas, centerX, centerY: int, radius, startAngle, sweepAngle: float)

method fill*(canvas: Canvas)

method drawImage*(canvas: Canvas, image: Image, x, y = 0, width, height = -1)

method setPixel*(canvas: Canvas, x, y: int, color: Color)

method getTextLineWidth*(canvas: Canvas, text: string): int

method getTextLineHeight*(canvas: Canvas): int

method getTextWidth*(canvas: Canvas, text: string): int


# ----------------------------------------------------------------------------------------
#                                        Image
# ----------------------------------------------------------------------------------------

proc newImage*(): Image

method resize*(image: Image, width, height: int)

method loadFromFile*(image: Image, filePath: string)

method saveToBitmapFile*(image: Image, filePath: string)

method saveToPngFile*(image: Image, filePath: string)

method saveToJpegFile*(image: Image, filePath: string, quality = 80)

method width*(image: Image): int

method height*(image: Image): int

method canvas*(image: Image): Canvas

method beginPixelDataAccess*(image: Image): ptr UncheckedArray[byte]

method endPixelDataAccess*(image: Image)


# ----------------------------------------------------------------------------------------
#                                        Window
# ----------------------------------------------------------------------------------------

proc newWindow*(title: string = ""): Window
## Constructor for a Window object.
## If the title is empty, it will be set to the application filename.

proc init*(window: WindowImpl)
## Initialize a WindowImpl object
## Only needed for own constructors.

proc dispose*(window: var Window)
method dispose*(window: Window)

proc disposed*(window: Window): bool

method visible*(window: Window): bool
method `visible=`*(window: Window, visible: bool)

method show*(window: Window)

method showModal*(window: Window, parent: Window)

method hide*(window: Window)

method minimized*(window: Window): bool
method `minimized=`*(window: Window, minimized: bool)

method minimize*(window: Window)

method control*(window: Window): Control
method `control=`*(window: Window, control: Control)

method add*(window: Window, control: Control)

method title*(window: Window): string
method `title=`*(window: Window, title: string)

method x*(window: Window): int
method `x=`*(window: Window, x: int)

method y*(window: Window): int
method `y=`*(window: Window, y: int)

method centerOnScreen*(window: Window)

method width*(window: Window): int
method `width=`*(window: Window, width: int)

method height*(window: Window): int
method `height=`*(window: Window, height: int)

method clientWidth*(window: Window): int

method clientHeight*(window: Window): int

method iconPath*(window: Window): string
method `iconPath=`*(window: Window, iconPath: string)

method closeClick*(window: Window)

method handleResizeEvent*(window: Window, event: ResizeEvent)

method handleKeyDownEvent*(window: Window, event: KeyboardEvent)

method handleDropFilesEvent*(window: Window, event: DropFilesEvent)

method onDispose*(window: Window): WindowDisposeProc
method `onDispose=`*(window: Window, callback: WindowDisposeProc)

method onCloseClick*(window: Window): CloseClickProc
method `onCloseClick=`*(window: Window, callback: CloseClickProc)

method onResize*(window: Window): ResizeProc
method `onResize=`*(window: Window, callback: ResizeProc)

method onDropFiles*(window: Window): DropFilesProc
method `onDropFiles=`*(window: Window, callback: DropFilesProc)

method onKeyDown*(window: Window): KeyboardProc
method `onKeyDown=`*(window: Window, callback: KeyboardProc)


# ----------------------------------------------------------------------------------------
#                                       Control
# ----------------------------------------------------------------------------------------

proc newControl*(): Control

proc init*(control: Control)
proc init*(control: ControlImpl)

proc dispose*(control: var Control)
method dispose*(control: Control)

proc disposed*(control: Control): bool

method visible*(control: Control): bool
method `visible=`*(control: Control, visible: bool)
method show*(control: Control)
method hide*(control: Control)

# Allow the outside to walk over child widgets
method childControls*(control: Control): seq[Control]

method parentControl*(control: Control): Control

method parentWindow*(control: Control): WindowImpl

method width*(control: Control): int
# Set the control's width to a fixed value (sets widthMode to fixed)
method `width=`*(control: Control, width: int)

method height*(control: Control): int
# Set the control's height to a fixed value (sets heightMode to fixed)
method `height=`*(control: Control, height: int)

method minWidth*(control: Control): int
method `minWidth=`*(control: Control, minWidth: int)

method minHeight*(control: Control): int
method `minHeight=`*(control: Control, minHeight: int)

method maxWidth*(control: Control): int
method `maxWidth=`*(control: Control, maxWidth: int)

method maxHeight*(control: Control): int
method `maxHeight=`*(control: Control, maxHeight: int)

# Set the control's width and height without changing widthMode or heightMode
method setSize*(control: Control, width, height: int)

method x*(control: Control): int
method `x=`*(control: Control, x: int)

method y*(control: Control): int
method `y=`*(control: Control, y: int)

method setPosition*(control: Control, x, y: int)

method naturalWidth*(control: Control): int

method naturalHeight*(control: Control): int

method wantedWidth*(control: Control): int

method wantedHeight*(control: Control): int

method focus*(control: Control)

method getTextLineWidth*(control: Control, text: string): int

method getTextLineHeight*(control: Control): int

method getTextWidth*(control: Control, text: string): int

method `widthMode=`*(control: Control, mode: WidthMode)
method widthMode*(control: Control): WidthMode

method heightMode*(control: Control): HeightMode
method `heightMode=`*(control: Control, mode: HeightMode)

method visibleWidth*(control: Control): int

method visibleHeight*(control: Control): int

method xScrollPos*(control: Control): int
method `xScrollPos=`*(control: Control, xScrollPos: int)

method yScrollPos*(control: Control): int
method `yScrollPos=`*(control: Control, yScrollPos: int)

method scrollableWidth*(control: Control): int
method `scrollableWidth=`*(control: Control, scrollableWidth: int)

method scrollableHeight*(control: Control): int
method `scrollableHeight=`*(control: Control, scrollableHeight: int)

method fontFamily*(control: Control): string
method `fontFamily=`*(control: Control, fontFamily: string)
method setFontFamily*(control: Control, fontFamily: string)

method fontSize*(control: Control): float
method `fontSize=`*(control: Control, fontSize: float)
method setFontSize*(control: Control, fontSize: float)

method fontBold*(control: Control): bool
method `fontBold=`*(control: Control, fontBold: bool)
method setFontBold*(control: Control, fontBold: bool)

method backgroundColor*(control: Control): Color
method `backgroundColor=`*(control: Control, color: Color)
method setBackgroundColor*(control: Control, color: Color)
method initStyle*(control: Control)

method textColor*(control: Control): Color
method `textColor=`*(control: Control, color: Color)
method setTextColor*(control: Control, color: Color)

method forceRedraw*(control: Control)

method canvas*(control: Control): Canvas

method handleDrawEvent*(control: Control, event: DrawEvent)

method handleMouseButtonDownEvent*(control: Control, event: MouseEvent)

method handleMouseButtonUpEvent*(control: Control, event: MouseEvent)

method handleClickEvent*(control: Control, event: ClickEvent)

method handleKeyDownEvent*(control: Control, event: KeyboardEvent)

method onDispose*(control: Control): ControlDisposeProc
method `onDispose=`*(control: Control, callback: ControlDisposeProc)

method onDraw*(control: Control): DrawProc
method `onDraw=`*(control: Control, callback: DrawProc)

method onMouseButtonDown*(control: Control): MouseButtonProc
method `onMouseButtonDown=`*(control: Control, callback: MouseButtonProc)

method onMouseButtonUp*(control: Control): MouseButtonProc
method `onMouseButtonUp=`*(control: Control, callback: MouseButtonProc)

method onClick*(control: Control): ClickProc
method `onClick=`*(control: Control, callback: ClickProc)

method onKeyDown*(control: Control): KeyboardProc
method `onKeyDown=`*(control: Control, callback: KeyboardProc)


# ----------------------------------------------------------------------------------------
#                                      Container
# ----------------------------------------------------------------------------------------

proc newContainer*(): Container

proc init*(container: Container)
proc init*(container: ContainerImpl)

method frame*(container: Container): Frame
method `frame=`*(container: Container, frame: Frame)

method add*(container: Container, control: Control)
method remove*(container: Container, control: Control)

method getPadding*(container: Container): Spacing

method setInnerSize*(container: Container, width, height: int)


# ----------------------------------------------------------------------------------------
#                                   LayoutContainer
# ----------------------------------------------------------------------------------------

proc newLayoutContainer*(layout: Layout): LayoutContainer

method layout*(container: LayoutContainer): Layout
method `layout=`*(container: LayoutContainer, layout: Layout)

method xAlign*(container: LayoutContainer): XAlign
method `xAlign=`*(container: LayoutContainer, xAlign: XAlign)

method yAlign*(container: LayoutContainer): YAlign
method `yAlign=`*(container: LayoutContainer, yAlign: YAlign)

method padding*(container: LayoutContainer): int
method `padding=`*(container: LayoutContainer, padding: int)

method spacing*(container: LayoutContainer): int
method `spacing=`*(container: LayoutContainer, spacing: int)


# ----------------------------------------------------------------------------------------
#                                        Frame
# ----------------------------------------------------------------------------------------

proc newFrame*(text = ""): Frame

proc init*(frame: Frame)
proc init*(frame: NativeFrame)

method text*(frame: Frame): string
method `text=`*(frame: Frame, text: string)

method getPadding*(frame: Frame): Spacing


# ----------------------------------------------------------------------------------------
#                                        Button
# ----------------------------------------------------------------------------------------

proc newButton*(text = ""): Button

proc init*(button: Button)
proc init*(button: NativeButton)

method text*(button: Button): string
method `text=`*(button: Button, text: string)

method enabled*(button: Button): bool
method `enabled=`*(button: Button, enabled: bool)


# ----------------------------------------------------------------------------------------
#                                        Checkbox
# ----------------------------------------------------------------------------------------

proc newCheckbox*(text = ""): Checkbox

proc init*(checkbox: Checkbox)
proc init*(checkbox: NativeCheckbox)

method text*(checkbox: Checkbox): string
method `text=`*(checkbox: Checkbox, text: string)

method enabled*(checkbox: Checkbox): bool
method `enabled=`*(checkbox: Checkbox, enabled: bool)

method checked*(checkbox: Checkbox): bool

method `checked=`*(checkbox: Checkbox, checked: bool)

method onToggle*(checkbox: Checkbox): ToggleProc
method `onToggle=`*(checkbox: Checkbox, callback: ToggleProc)

method handleToggleEvent*(checkbox: Checkbox, event: ToggleEvent)


# ----------------------------------------------------------------------------------------
#                                        Label
# ----------------------------------------------------------------------------------------

proc newLabel*(text = ""): Label

proc init*(label: Label)
proc init*(label: NativeLabel)

method text*(label: Label): string
method `text=`*(label: Label, text: string)


# ----------------------------------------------------------------------------------------
#                                       TextBox
# ----------------------------------------------------------------------------------------

proc newTextBox*(text = ""): TextBox

proc init*(textBox: TextBox)
proc init*(textBox: NativeTextBox)

method text*(textBox: TextBox): string
method `text=`*(textBox: TextBox, text: string)

method editable*(textBox: TextBox): bool
method `editable=`*(textBox: TextBox, editable: bool)

method cursorPos*(textBox: TextBox): int
method `cursorPos=`*(textBox: TextBox, cursorPos: int)

method selectionStart*(textBox: TextBox): int
method `selectionStart=`*(textBox: TextBox, selectionStart: int)

method selectionEnd*(textBox: TextBox): int
method `selectionEnd=`*(textBox: TextBox, selectionEnd: int)

method selectedText*(textBox: TextBox): string
method `selectedText=`*(textBox: TextBox, text: string)

method handleTextChangeEvent*(textBox: TextBox, event: TextChangeEvent)

method onTextChange*(textBox: TextBox): TextChangeProc
method `onTextChange=`*(textBox: TextBox, callback: TextChangeProc)


# ----------------------------------------------------------------------------------------
#                                      TextArea
# ----------------------------------------------------------------------------------------

proc newTextArea*(text = ""): TextArea

proc init*(textArea: TextArea)
proc init*(textArea: NativeTextArea)

method addText*(textArea: TextArea, text: string)
method addLine*(textArea: TextArea, text = "")

method scrollToBottom*(textArea: TextArea)

method wrap*(textArea: TextArea): bool
method `wrap=`*(textArea: TextArea, wrap: bool)


# ----------------------------------------------------------------------------------------
#                            Private Procedures Predeclaration
# ----------------------------------------------------------------------------------------

proc raiseError(msg: string)

proc handleException()

proc runMainLoop()

proc init(window: Window)

method destroy(window: Window)

proc triggerRelayout(window: Window)

method destroy(control: Control)

proc triggerRelayout(control: Control)

proc triggerRelayoutIfModeIsAuto(control: Control)

method relayout(control: Control, availableWidth, availableHeight: int)

method realignChildControls(control: Control)

method setControlPosition(container: Container, control: Control, x, y: int)


# ========================================================================================
#
#                                    Implementation
#
# ========================================================================================

import math
import os
import strutils
import times
import unicode


# ----------------------------------------------------------------------------------------
#                                   Global Variables
# ----------------------------------------------------------------------------------------

const
  defaultDpi = 96
  defaultFontSizeForDefaultDpi = 15.0

var
  fErrorHandler: ErrorHandlerProc = nil
  windowList: seq[Window] = @[]
  fScrollbarSize = -1
  fDownKeys: seq[Key] = @[]
  fSystemDpi = defaultDpi

  # Default style:
  fDefaultBackgroundColor: Color # initialized by platform-specific init()
  fDefaultTextColor: Color # initialized by platform-specific init()
  fDefaultFontFamily = ""
  fDefaultFontSize = defaultFontSizeForDefaultDpi


# ----------------------------------------------------------------------------------------
#                                  Global/App Procedures
# ----------------------------------------------------------------------------------------

proc raiseError(msg: string) =
  raise newException(Exception, msg)

proc defaultExceptionHandler() =
  let msg = getCurrentExceptionMsg() & "\p\p" & getStackTrace()
  alert(nil, msg, "Error")
  echo "Error: unhandled exception: ", msg
  quit()

proc handleException() =
  ## Handle an exception raised in runMainLoop().
  ## This is called directly from the Gtk part.
  if fErrorHandler == nil:
    defaultExceptionHandler()
  else:
    fErrorHandler()

proc rgb(red, green, blue: byte, alpha: byte = 255): Color =
  result.red = red
  result.green = green
  result.blue = blue
  result.alpha = alpha

proc sleep(app: App, milliSeconds: float) =
  let t = epochTime() + milliSeconds / 1000
  while epochTime() < t:
    app.processEvents()
    os.sleep(20)

proc run(app: App) =
  while true:
    try:
      runMainLoop()
      break
    except:
      handleException()

proc quit(app: App) = quit()

proc errorHandler(app: App): ErrorHandlerProc = fErrorHandler

proc `errorHandler=`(app: App, errorHandler: ErrorHandlerProc) = fErrorHandler = errorHandler

proc defaultBackgroundColor(app: App): Color = fDefaultBackgroundColor

proc updateBackgroundColor(control: Control) =
  if control.fUseDefaultBackgroundColor and control.backgroundColor != fDefaultBackgroundColor:
    control.setBackgroundColor(fDefaultBackgroundColor)
  for child in control.childControls:
    child.updateBackgroundColor()

proc `defaultBackgroundColor=`(app: App, color: Color) =
  fDefaultBackgroundColor = color
  for window in windowList:
    let control = window.control
    if control != nil:
      control.updateBackgroundColor()

proc defaultTextColor(app: App): Color = fDefaultTextColor

proc updateTextColor(control: Control) =
  if control.fUseDefaultTextColor and control.textColor != fDefaultTextColor:
    control.setTextColor(fDefaultTextColor)
  for child in control.childControls:
    child.updateTextColor()

proc `defaultTextColor=`(app: App, color: Color) =
  fDefaultTextColor = color
  for window in windowList:
    let control = window.control
    if control != nil:
      control.updateTextColor()

proc defaultFontFamily(app: App): string = fDefaultFontFamily

proc updateFontFamily(control: Control) =
  if control.fUseDefaultFontFamily and control.fontFamily != fDefaultFontFamily:
    control.setFontFamily(fDefaultFontFamily)
  for child in control.childControls:
    child.updateFontFamily()

proc `defaultFontFamily=`(app: App, fontFamily: string) =
  fDefaultFontFamily = fontFamily
  for window in windowList:
    let control = window.control
    if control != nil:
      control.updateFontFamily()

proc defaultFontSize(app: App): float = fDefaultFontSize

proc updateFontSize(control: Control) =
  if control.fUseDefaultFontSize and control.fontSize != fDefaultFontSize:
    control.setFontSize(fDefaultFontSize)
  for child in control.childControls:
    child.updateFontSize()

proc `defaultFontSize=`(app: App, fontSize: float) =
  fDefaultFontSize = fontSize
  for window in windowList:
    let control = window.control
    if control != nil:
      control.updateFontSize()

proc newOpenFileDialog(): OpenFileDialog =
  result = new OpenFileDialog
  result.title = "Open File"
  result.directory = getCurrentDir()
  result.files = @[]

proc newSaveFileDialog(): SaveFileDialog =
  result = new SaveFileDialog
  result.title = "Save File"
  result.directory = getCurrentDir()

proc isDown(key: Key): bool = fDownKeys.contains(key)

proc downKeys(): seq[Key] = fDownKeys

proc scaleToDpi(val: int): int = (val * fSystemDpi) div defaultDpi
proc scaleToDpi(val: float): float = val * fSystemDpi.float / defaultDpi.float

proc internalKeyDown(key: Key) =
  if not fDownKeys.contains(key):
    fDownKeys.add(key)

proc internalKeyUp(key: Key) =
  let i = fDownKeys.find(key)
  if i != -1:
    fDownKeys.delete(i)

proc internalAllKeysUp() =
  fDownKeys = @[]


# ----------------------------------------------------------------------------------------
#                                       Canvas
# ----------------------------------------------------------------------------------------

proc newCanvas(control: Control = nil): CanvasImpl =
  result = new CanvasImpl
  result.fLineColor = rgb(0, 0, 0)
  result.fLineWidth = 1
  result.fAreaColor = rgb(0, 0, 0)
  if control == nil:
    result.fFontFamily = app.defaultFontFamily
    result.fFontSize = app.defaultFontSize
    result.fTextColor = app.defaultTextColor
  else:
    result.fFontFamily = control.fontFamily
    result.fFontSize = control.fontSize
    result.fTextColor = control.textColor
    result.fWidth = control.width
    result.fHeight = control.height
    control.fCanvas = result

method destroy(canvas: Canvas) = discard

method width(canvas: Canvas): int = canvas.fWidth

method height(canvas: Canvas): int= canvas.fHeight

method fontFamily(canvas: Canvas): string = canvas.fFontFamily

method `fontFamily=`(canvas: Canvas, fontFamily: string) = canvas.fFontFamily = fontFamily

method fontSize(canvas: Canvas): float = canvas.fFontSize

method `fontSize=`(canvas: Canvas, fontSize: float) = canvas.fFontSize = fontSize

method fontBold(canvas: Canvas): bool = canvas.fFontBold

method `fontBold=`(canvas: Canvas, fontBold: bool) = canvas.fFontBold = fontBold

method textColor(canvas: Canvas): Color = canvas.fTextColor

method `textColor=`(canvas: Canvas, color: Color) = canvas.fTextColor = color

method lineColor(canvas: Canvas): Color = canvas.fLineColor

method `lineColor=`(canvas: Canvas, color: Color) = canvas.fLineColor = color

method lineWidth(canvas: Canvas): float = canvas.fLineWidth

method `lineWidth=`(canvas: Canvas, width: float) = canvas.fLineWidth = width

method areaColor(canvas: Canvas): Color = canvas.fAreaColor

method `areaColor=`(canvas: Canvas, color: Color) = canvas.fAreaColor = color

method getTextLineWidth(canvas: Canvas, text: string): int =
  result = text.len * 7
  # should be overrriden by CanvasImpl

method getTextLineHeight(canvas: Canvas): int =
  result = 20
  # should be overrriden by CanvasImpl

method getTextWidth(canvas: Canvas, text: string): int =
  result = 0
  for line in text.splitLines:
    result = max(result, canvas.getTextLineWidth(line))

method drawTextCentered(canvas: Canvas, text: string, x, y = 0, width, height = -1) =
  var w = width
  if w == -1:
    w = canvas.width
  var h = height
  if h == -1:
    h = canvas.height
  let rx = x + (w - canvas.getTextWidth(text)) div 2
  let ry = y + (h - canvas.getTextLineHeight()) div 2
  canvas.drawText(text, rx, ry)

method fill(canvas: Canvas) = canvas.drawRectArea(0, 0, canvas.width, canvas.height)


# ----------------------------------------------------------------------------------------
#                                        Image
# ----------------------------------------------------------------------------------------

proc newImage(): Image =
  result = new ImageImpl
  result.fCanvas = newCanvas()

method width(image: Image): int = image.canvas.width

method height(image: Image): int = image.canvas.height

method canvas(image: Image): Canvas = image.fCanvas


# ----------------------------------------------------------------------------------------
#                                        Window
# ----------------------------------------------------------------------------------------

proc newWindow(title: string = ""): Window =
  result = new WindowImpl
  result.WindowImpl.init()
  if title != "":
    result.title = title


proc init(window: Window) =
  window.fVisible = false
  window.fWidth = 640 # do not trigger resize
  window.height = 480 # trigger resize
  window.fX = -1 # window will be centered on screen
  window.fY = -1
  window.title = getAppFilename().extractFilename().changeFileExt("")
  var defaultIconPath = getAppFilename().changeFileExt("") & ".png"
  if defaultIconPath.fileExists():
    window.iconPath = defaultIconPath
  windowList.add(window)
  window.triggerRelayout()

method destroy(window: Window) =
  if window.fControl != nil:
    window.fControl.dispose()
  # should be extended by WindowImpl

proc dispose(window: var Window) =
  let w = window
  w.dispose() # force calling "dispose(window: Window)" instead of itself
  window = nil

method dispose(window: Window) =
  let callback = window.onDispose
  if callback != nil:
    var event = new WindowDisposeEvent
    event.window = window
    callback(event)
  window.destroy()
  let i = windowList.find(window)
  windowList.delete(i)
  if quitOnLastWindowClose and windowList.len == 0:
    quit()
  window.fDisposed = true

proc disposed(window: Window): bool = window == nil or window.fDisposed

method title(window: Window): string = window.fTitle

method `title=`(window: Window, title: string) = window.fTitle = title

method control(window: Window): Control = window.fControl

method `control=`(window: Window, control: Control) =
  window.fControl = control
  control.fParentWindow = window
  # should be extended by WindowImpl

method add(window: Window, control: Control) =
  if window.control != nil:
    raiseError("Window can have only one control.")
  window.control = control

method visible(window: Window): bool = window.fVisible

method `visible=`(window: Window, visible: bool) =
  window.fVisible = visible
  if visible:
    window.fMinimized = false
  if window.x == -1 or window.y == -1:
    window.centerOnScreen()
  # should be extended by WindowImpl

method show(window: Window) = window.visible = true

method showModal(window: Window, parent: Window) =
  window.visible = true
  # should be extended by WindowImpl

method hide(window: Window) = window.visible = false

method minimized(window: Window): bool = window.fMinimized

method `minimized=`(window: Window, minimized: bool) =
  if minimized:
    window.minimize()
  else:
    window.show()

method minimize(window: Window) =
  window.fMinimized = true
  # should be extended by WindowImpl

method x(window: Window): int = window.fX

method `x=`(window: Window, x: int) =
  window.fX = x
  # should be extended by WindowImpl

method y(window: Window): int = window.fY

method `y=`(window: Window, y: int) =
  window.fY = y
  # should be extended by WindowImpl

method centerOnScreen(window: Window) =
  discard # has to be implemented in WindowImpl

method width(window: Window): int = window.fWidth

method height(window: Window): int = window.fHeight

method `width=`(window: Window, width: int) =
  window.fWidth = width
  # has to be extended by WindowImpl

method `height=`(window: Window, height: int) =
  window.fHeight = height
  # has to be extended by WindowImpl

method clientWidth(window: Window): int = window.fClientWidth

method clientHeight(window: Window): int = window.fClientHeight

proc triggerRelayout(window: Window) =
  if window.control == nil:
    return
  # echo ""
  # echo "WindowImpl:triggerRelayout()"
  # echo "window size: " & $window.clientWidth & ", " & $window.clientHeight
  window.control.relayout(window.clientWidth, window.clientHeight)

method iconPath(window: Window): string = window.fIconPath

method `iconPath=`(window: Window, iconPath: string) =
  window.fIconPath = iconPath
  # should be extended by WindowImpl

method closeClick(window: Window) =
  # can be overriden by custom window
  let callback = window.onCloseClick
  if callback != nil:
    var event = new CloseClickEvent
    event.window = window
    callback(event)
  else:
    window.dispose() # default action

method handleResizeEvent(window: Window, event: ResizeEvent) =
  # can be overriden by custom window
  let callback = window.onResize
  if callback != nil:
    callback(event)

method handleDropFilesEvent(window: Window, event: DropFilesEvent) =
  # can be overriden by custom window
  let callback = window.onDropFiles
  if callback != nil:
    callback(event)

method handleKeyDownEvent(window: Window, event: KeyboardEvent) =
  # can be overriden by custom window
  let callback = window.onKeyDown
  if callback != nil:
    callback(event)

method onDispose(window: Window): WindowDisposeProc = window.fOnDispose
method `onDispose=`(window: Window, callback: WindowDisposeProc) = window.fOnDispose = callback

method onCloseClick(window: Window): CloseClickProc = window.fOnCloseClick
method `onCloseClick=`(window: Window, callback: CloseClickProc) = window.fOnCloseClick = callback

method onResize(window: Window): ResizeProc = window.fOnResize
method `onResize=`(window: Window, callback: ResizeProc) = window.fOnResize = callback

method onDropFiles(window: Window): DropFilesProc = window.fOnDropFiles
method `onDropFiles=`(window: Window, callback: DropFilesProc) = window.fOnDropFiles = callback

method onKeyDown(window: Window): KeyboardProc = window.fOnKeyDown
method `onKeyDown=`(window: Window, callback: KeyboardProc) = window.fOnKeyDown = callback



# ----------------------------------------------------------------------------------------
#                                       Control
# ----------------------------------------------------------------------------------------

proc newControl(): Control =
  result = new ControlImpl
  result.ControlImpl.init()

proc init(control: Control) =
  control.fWidthMode = WidthMode_Static
  control.fHeightMode = HeightMode_Static
  control.fWidth = 50.scaleToDpi
  control.fheight = 50.scaleToDpi
  control.fScrollableWidth = -1
  control.fScrollableHeight = -1
  control.initStyle()
  control.show()
  # should be extended by ControlImpl

method destroy(control: Control) =
  discard # nothing to do here
  # should be extended by ControlImpl

proc dispose(control: var Control) =
  let c = control
  c.dispose() # force calling "dispose(control: Control)" instead of itself
  control = nil

method dispose(control: Control) =
  let callback = control.onDispose
  if callback != nil:
    var event = new ControlDisposeEvent
    event.control = control
    callback(event)
  control.destroy()
  control.fDisposed = true

proc disposed(control: Control): bool = control == nil or control.fDisposed

method visible(control: Control): bool = control.fVisible

method `visible=`(control: Control, visible: bool) =
  control.fVisible = visible
  control.triggerRelayout()
  # should be extended by ControlImpl

method show(control: Control) = control.visible = true

method hide(control: Control) = control.visible = false

method width(control: Control): int = control.fWidth

method height(control: Control): int = control.fHeight

method `width=`(control: Control, width: int) =
  control.setSize(width, control.fHeight)
  control.widthMode = WidthMode_Static

method `height=`(control: Control, height: int) =
  control.setSize(control.fWidth, height)
  control.heightMode = HeightMode_Static

method minWidth(control: Control): int = control.fMinWidth

method `minWidth=`(control: Control, minWidth: int) =
  control.fMinWidth = minWidth
  control.triggerRelayout()

method minHeight(control: Control): int = control.fMinHeight

method `minHeight=`(control: Control, minHeight: int) =
  control.fMinHeight = minHeight
  control.triggerRelayout()

method maxWidth(control: Control): int = control.fMaxWidth

method `maxWidth=`(control: Control, maxWidth: int) =
  control.fMaxWidth = maxWidth
  control.triggerRelayout()

method maxHeight(control: Control): int = control.fMaxHeight

method `maxHeight=`(control: Control, maxHeight: int) =
  control.fMaxHeight = maxHeight
  control.triggerRelayout()

method setSize(control: Control, width, height: int) =
  control.fWidth = width
  control.fHeight = height
  if control.canvas != nil:
    control.canvas.fWidth = width
    control.canvas.fHeight = height
  control.realignChildControls()
  # should be extended by ControlImpl

method setSize(control: ControlImpl, width, height: int) # required pre declaration

method `x=`(control: Control, x: int) =
  if control.fParentControl == nil:
    raiseError("Control cannot be moved, when it is not inside a container.")
  cast[Container](control.fParentControl).setControlPosition(control, x, control.y)

method x(control: Control): int = control.fX

method `y=`(control: Control, y: int) =
  if control.fParentControl == nil:
    raiseError("Control cannot be moved, when it is not inside a container.")
  cast[Container](control.fParentControl).setControlPosition(control, control.x, y)

method y(control: Control): int = control.fY

method setPosition(control: Control, x, y: int) =
  control.fX = x
  control.fY = y
  # should be extended by ControlImpl

method naturalWidth(control: Control): int = control.width

method naturalHeight(control: Control): int = control.height

method wantedWidth(control: Control): int =
  if control.widthMode == WidthMode_Static:
    result = control.width
  else:
    result = control.naturalWidth
  if result != -1 and control.minWidth > result:
    result = control.minWidth
  if control.maxWidth > 0 and control.maxWidth < result:
    result = control.maxWidth

method wantedHeight(control: Control): int =
  if control.heightMode == HeightMode_Static:
    result = control.height
  else:
    result = control.naturalHeight
  if result != -1 and control.minHeight > result:
    result = control.minHeight
  if control.maxHeight > 0 and control.maxHeight < result:
    result = control.maxHeight

method `widthMode=`(control: Control, mode: WidthMode) =
  control.fWidthMode = mode
  control.triggerRelayout()

method `heightMode=`(control: Control, mode: HeightMode) =
  control.fHeightMode = mode
  control.triggerRelayout()

method widthMode(control: Control): WidthMode = control.fWidthMode

method heightMode(control: Control): HeightMode = control.fHeightMode

method childControls(control: Control): seq[Control] = @[]

method parentControl(control: Control): Control = control.fParentControl

method parentWindow(control: Control): WindowImpl =
  if control.fParentControl == nil:
    result = cast[WindowImpl](control.fParentWindow)
  else:
    result = control.parentControl.parentWindow

proc triggerRelayout(control: Control) =
  var con = control
  while con.parentControl != nil:
    con = con.parentControl
  if con.parentWindow != nil:
    con.parentWindow.triggerRelayout()
  if control.parentControl != nil:
    control.parentControl.triggerRelayout()
  control.realignChildControls()

proc triggerRelayoutIfModeIsAuto(control: Control) =
  if control.widthMode == WidthMode_Auto or control.heightMode == HeightMode_Auto:
    control.triggerRelayout()

method relayout(control: Control, availableWidth, availableHeight: int) =
  # echo ""
  # echo control.tag & ".relayout(): "
  # echo "  available size: " & $availableWidth & ", " & $availableHeight
  var width = control.width
  var height = control.height
  var sizeChanged = false
  if control.widthMode == WidthMode_Auto:
    let naturalWidth = control.naturalWidth
    # echo "  naturalWidth: " & $naturalWidth
    if naturalWidth == -1:
      width = availableWidth
    else:
      width = min(availableWidth, naturalWidth)
    sizeChanged = true
  elif control.widthMode in {WidthMode_Expand, WidthMode_Fill}:
    width = availableWidth
    sizeChanged = true
  if control.heightMode == HeightMode_Auto:
    let naturalHeight = control.naturalHeight
    # echo "  naturalHeight: " & $naturalHeight
    if naturalHeight == -1:
      height = availableHeight
    else:
      height = min(availableHeight, naturalHeight)
    sizeChanged = true
  elif control.heightMode in {HeightMode_Expand, HeightMode_Fill}:
    height = availableHeight
    sizeChanged = true
  if sizeChanged:
    # echo "  new size: " & $width & ", " & $height
    control.setSize(width, height)

method realignChildControls(control: Control) = discard

method focus(control: Control) =
  discard
  # should be overrriden by ControlImpl

method getTextLineWidth(control: Control, text: string): int =
  result = text.len * 7
  # should be overrriden by ControlImpl

method getTextLineHeight(control: Control): int =
  result = 20
  # should be overrriden by ControlImpl

method getTextWidth(control: Control, text: string): int =
  result = 0
  for line in text.splitLines:
    result = max(result, control.getTextLineWidth(line))

method xScrollbarSpace(control: Control): int =
  if control.fYScrollEnabled:
    result.inc(fScrollbarSize)

method yScrollbarSpace(control: Control): int =
  if control.fXScrollEnabled:
    result.inc(fScrollbarSize)

method visibleWidth(control: Control): int =
  result = control.width - control.xScrollbarSpace

method visibleHeight(control: Control): int =
  result = control.height - control.yScrollbarSpace

method xScrollPos(control: Control): int = control.fXScrollPos

method `xScrollPos=`(control: Control, xScrollPos: int) =
  control.fXScrollPos = xScrollPos

method yScrollPos(control: Control): int = control.fYScrollPos

method `yScrollPos=`(control: Control, yScrollPos: int) =
  control.fYScrollPos = yScrollPos

method scrollableWidth(control: Control): int = control.fScrollableWidth

method `scrollableWidth=`(control: Control, scrollableWidth: int) =
  control.fScrollableWidth = scrollableWidth

method scrollableHeight(control: Control): int = control.fScrollableHeight

method `scrollableHeight=`(control: Control, scrollableHeight: int) =
  control.fScrollableHeight = scrollableHeight

method fontFamily(control: Control): string = control.fFontFamily

method `fontFamily=`(control: Control, fontFamily: string) =
  control.setFontFamily(fontFamily)
  control.fUseDefaultFontFamily = false
  control.triggerRelayoutIfModeIsAuto()

method setFontFamily(control: Control, fontFamily: string) =
  control.fFontFamily = fontFamily
  control.triggerRelayoutIfModeIsAuto()
  # should be extended by ControlImpl

method fontSize(control: Control): float = control.fFontSize

method `fontSize=`(control: Control, fontSize: float) =
  control.setFontSize(fontSize)
  control.fUseDefaultFontSize = false
  control.triggerRelayoutIfModeIsAuto()

method setFontSize(control: Control, fontSize: float) =
  control.fFontSize = fontSize
  # should be extended by ControlImpl

method fontBold(control: Control): bool = control.fFontBold

method `fontBold=`(control: Control, fontBold: bool) =
  control.setFontBold(fontBold)
  control.triggerRelayoutIfModeIsAuto()

method setFontBold(control: Control, fontBold: bool) =
  control.fFontBold = fontBold
  # should be extended by ControlImpl

method backgroundColor(control: Control): Color = control.fBackgroundColor

method `backgroundColor=`(control: Control, color: Color) =
  control.setBackgroundColor(color)
  control.fUseDefaultBackgroundColor = false

method setBackgroundColor(control: Control, color: Color) =
  control.fBackgroundColor = color
  control.forceRedraw()
  # should be extended by ControlImpl

method initStyle(control: Control) =
  control.fBackgroundColor = fDefaultBackgroundColor
  control.fTextColor = fDefaultTextColor
  control.setFontFamily(fDefaultFontFamily)
  control.setFontSize(app.defaultFontSize)
  control.fUseDefaultBackgroundColor = true
  control.fUseDefaultTextColor = true
  control.fUseDefaultFontFamily = true
  control.fUseDefaultFontSize = true
  control.triggerRelayoutIfModeIsAuto()

method textColor(control: Control): Color = control.fTextColor

method `textColor=`(control: Control, color: Color) =
  control.setTextColor(color)
  control.fUseDefaultTextColor = false

method setTextColor(control: Control, color: Color) =
  control.fTextColor = color
  control.forceRedraw()
  # should be extended by ControlImpl

method forceRedraw(control: Control) =
  discard
  # should be implemented by ControlImpl

method canvas(control: Control): Canvas = control.fCanvas

method handleDrawEvent(control: Control, event: DrawEvent) =
  # can be overridden by custom control
  let callback = control.onDraw
  if callback != nil:
    callback(event)

method handleMouseButtonDownEvent(control: Control, event: MouseEvent) =
  # can be overridden by custom control
  let callback = control.onMouseButtonDown
  if callback != nil:
    callback(event)

method handleMouseButtonUpEvent(control: Control, event: MouseEvent) =
  # can be overridden by custom control
  let callback = control.onMouseButtonUp
  if callback != nil:
    callback(event)

method handleClickEvent(control: Control, event: ClickEvent) =
  # can be overridden by custom button
  let callback = control.onClick
  if callback != nil:
    callback(event)

method handleKeyDownEvent(control: Control, event: KeyboardEvent) =
  # can be overridden by custom control
  let callback = control.onKeyDown
  if callback != nil:
    callback(event)

method onDispose(control: Control): ControlDisposeProc = control.fOnDispose
method `onDispose=`(control: Control, callback: ControlDisposeProc) = control.fOnDispose = callback

method onDraw(control: Control): DrawProc = control.fOnDraw
method `onDraw=`(control: Control, callback: DrawProc) = control.fOnDraw = callback

method onMouseButtonDown(control: Control): MouseButtonProc = control.fOnMouseButtonDown
method `onMouseButtonDown=`(control: Control, callback: MouseButtonProc) = control.fOnMouseButtonDown = callback

method onMouseButtonUp(control: Control): MouseButtonProc = control.fOnMouseButtonUp
method `onMouseButtonUp=`(control: Control, callback: MouseButtonProc) = control.fOnMouseButtonUp = callback

method onClick(control: Control): ClickProc = control.fOnClick
method `onClick=`(control: Control, callback: ClickProc) = control.fOnClick = callback

method onKeyDown(control: Control): KeyboardProc = control.fOnKeyDown
method `onKeyDown=`(control: Control, callback: KeyboardProc) = control.fOnKeyDown = callback


# ----------------------------------------------------------------------------------------
#                                      Container
# ----------------------------------------------------------------------------------------

proc newContainer(): Container =
  result = new ContainerImpl
  result.ContainerImpl.init()

proc init(container: Container) =
  container.fChildControls = @[]
  container.ControlImpl.init()
  container.fWidthMode = WidthMode_Auto
  container.fHeightMode = HeightMode_Auto

method frame(container: Container): Frame = container.fFrame

method `frame=`(container: Container, frame: Frame) =
  if frame.fParentControl != nil:
    raiseError("Frame can be assigned only to one container.")
  container.fFrame = frame
  if frame != nil:
    frame.fParentControl = container
    container.tag = frame.tag
  container.triggerRelayout()
  if container.frame != nil:
    container.frame.setSize(container.width, container.height)
  # should be extended by NativeFrame

method setSize(container: Container, width, height: int) =
  procCall container.ControlImpl.setSize(width, height)
  if container.frame != nil:
    container.frame.setSize(width, height)

method childControls(container: Container): seq[Control] = container.fChildControls

method add(container: Container, control: Control) =
  if control.fParentControl != nil:
    raiseError("Control can be added only to one container.")
  container.fChildControls.add(control)
  control.fParentControl = container
  control.fIndex = 0
  container.triggerRelayout()

method remove(container: Container, control: Control) =
  discard
  # if container != control.fParentControl:
    # raiseError("control can not be removed because it is not member of the container")
  # else:
    # let startIndex = control.fIndex
    # container.childControls.del(control.fIndex)
    # for i in startIndex..container.childControls.high:
      # container.childControl[i].fIndex = i
    # control.parentControl = nil

method setControlPosition(container: Container, control: Control, x, y: int) =
  control.setPosition(x, y)
  container.triggerRelayout()

method minWidth(container: Container): int =
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    result = max(result, control.x + control.minWidth)
  let padding = container.getPadding()
  result.inc(padding.left)
  result.inc(padding.right)
  result.inc(container.xScrollbarSpace)
  result = max(result, container.fMinWidth)

method minHeight(container: Container): int =
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    result = max(result, control.y + control.minHeight)
  let padding = container.getPadding()
  result.inc(padding.top)
  result.inc(padding.bottom)
  result.inc(container.yScrollbarSpace)
  result = max(result, container.fMinHeight)

method naturalWidth(container: Container): int =
  if container.widthMode == WidthMode_Static:
    return container.width
  if container.widthMode == WidthMode_Expand:
    return -1
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if control.widthMode == WidthMode_Expand:
      return -1
    result = max(result, control.x + control.wantedWidth)
  let padding = container.getPadding()
  result.inc(padding.left)
  result.inc(padding.right)
  result.inc(container.xScrollbarSpace)
  if container.frame != nil and container.frame.visible:
    result = max(result, container.frame.naturalWidth)

method naturalHeight(container: Container): int =
  if container.heightMode == HeightMode_Static:
    return container.height
  if container.heightMode == HeightMode_Expand:
    return -1
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if control.heightMode == HeightMode_Expand:
      return -1
    result = max(result, control.y + control.wantedHeight)
  let padding = container.getPadding()
  result.inc(padding.top)
  result.inc(padding.bottom)
  result.inc(container.yScrollbarSpace)

method getPadding(container: Container): Spacing =
  if container.frame != nil and container.frame.visible:
    result = container.frame.getPadding()

method setInnerSize(container: Container, width, height: int) = discard
  # should be extended by ContainerImpl

method updateInnerSize(container: Container, pInnerWidth, pInnerHeight: int) {.base.} =
  let padding = container.getPadding()
  let clientWidth = container.visibleWidth - padding.left - padding.right
  let clientHeight = container.visibleHeight - padding.top - padding.bottom
  var innerWidth = pInnerWidth
  var innerHeight = pInnerHeight

  discard """ container.xScrollEnabled = innerWidth > clientWidth

  if container.xScrollEnabled and innerHeight + 20 > clientHeight:
    innerHeight.inc(20) # Space for scrollbar
    container.yScrollEnabled = true
  else:
    container.yScrollEnabled = innerHeight > clientHeight
    if container.yScrollEnabled and innerWidth + 20 > clientWidth:
      innerWidth.inc(20) # Space for scrollbar
      container.xScrollEnabled = true """

  # TODO: rework

  innerWidth = max(innerWidth, clientWidth)
  innerHeight = max(innerHeight, clientHeight)

  container.scrollableWidth = innerWidth
  container.scrollableHeight = innerHeight

  container.setInnerSize(innerWidth, innerHeight)

method realignChildControls(container: Container) =
  let padding = container.getPadding()
  var innerWidth = container.wantedWidth
  var innerHeight = container.wantedHeight
  if innerWidth == -1:
    innerWidth = container.width
  if innerHeight == -1:
    innerHeight = container.height
  container.updateInnerSize(innerWidth - padding.left - padding.right - container.xScrollbarSpace, innerHeight - padding.top - padding.bottom - container.yScrollbarSpace)

method `onDraw=`(container: ContainerImpl, callback: DrawProc) = raiseError("ContainerImpl does not allow onDraw.")


# ----------------------------------------------------------------------------------------
#                                   LayoutContainer
# ----------------------------------------------------------------------------------------

proc newLayoutContainer(layout: Layout): LayoutContainer =
  result = new LayoutContainer
  result.init()
  result.layout = layout
  result.xAlign = XAlign_Left
  result.yAlign = YAlign_Top
  result.spacing = 4.scaleToDpi
  result.padding = 2.scaleToDpi

method naturalWidth(container: LayoutContainer): int =
  # echo container.tag & ".naturalWidth"
  if container.widthMode == WidthMode_Static:
    return container.width
  if container.widthMode == WidthMode_Expand:
    return -1
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if control.widthMode == WidthMode_Expand or control.wantedWidth == -1:
      return -1
    if container.layout == Layout_Horizontal:
      result.inc(control.wantedWidth)
    else:
      result = max(result, control.wantedWidth)
  let padding = container.getPadding()
  result.inc(padding.left)
  result.inc(padding.right)
  result.inc(container.padding * 2)
  if container.layout == Layout_Horizontal and container.childControls.len > 1:
    result.inc(container.spacing * (container.childControls.len - 1))
  result.inc(container.xScrollbarSpace)
  if container.frame != nil and container.frame.visible:
    result = max(result, container.frame.naturalWidth)

method naturalHeight(container: LayoutContainer): int =
  if container.heightMode == HeightMode_Static:
    return container.height
  if container.heightMode == HeightMode_Expand:
    return -1
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if control.heightMode == HeightMode_Expand or control.wantedHeight == -1:
      return -1
    if container.layout == Layout_Vertical:
      result.inc(control.wantedHeight)
    else:
      result = max(result, control.wantedHeight)
  let padding = container.getPadding()
  result.inc(padding.top)
  result.inc(padding.bottom)
  result.inc(container.padding * 2)
  result.inc(container.yScrollbarSpace)
  if container.layout == Layout_Vertical and container.childControls.len > 1:
    result.inc(container.spacing * (container.childControls.len - 1))

method minWidth(container: LayoutContainer): int =
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if container.layout == Layout_Horizontal:
      result.inc(control.minWidth)
    else:
      result = max(result, control.minWidth)
  let padding = container.getPadding()
  result.inc(padding.left)
  result.inc(padding.right)
  result.inc(container.padding * 2)
  if container.layout == Layout_Horizontal and container.childControls.len > 1:
    result.inc(container.spacing * (container.childControls.len - 1))
  result.inc(container.xScrollbarSpace)
  result = max(result, container.fMinWidth)

method minHeight(container: LayoutContainer): int =
  result = 0
  for control in container.childControls:
    if not control.visible:
      continue
    if container.layout == Layout_Vertical:
      result.inc(control.minHeight)
    else:
      result = max(result, control.minHeight)
  let padding = container.getPadding()
  result.inc(padding.top)
  result.inc(padding.bottom)
  result.inc(container.padding * 2)
  if container.layout == Layout_Vertical and container.childControls.len > 1:
    result.inc(container.spacing * (container.childControls.len - 1))
  result.inc(container.yScrollbarSpace)
  result = max(result, container.fMinHeight)

method setControlPosition(container: LayoutContainer, control: Control, x, y: int) =
  raiseError("Controls inside a LayoutContainer cannot be moved manually.")

method layout(container: LayoutContainer): Layout = container.fLayout

method `layout=`(container: LayoutContainer, layout: Layout) =
  container.fLayout = layout
  container.triggerRelayout()

method xAlign(container: LayoutContainer): XAlign = container.fXAlign

method `xAlign=`(container: LayoutContainer, xAlign: XAlign) =
  container.fXAlign = xAlign
  container.realignChildControls()

method yAlign(container: LayoutContainer): YAlign = container.fYAlign

method `yAlign=`(container: LayoutContainer, yAlign: YAlign) =
  container.fYAlign = yAlign
  container.realignChildControls()

method padding(container: LayoutContainer): int = container.fPadding

method `padding=`(container: LayoutContainer, padding: int) =
  container.fPadding = padding
  container.triggerRelayout()

method spacing(container: LayoutContainer): int = container.fSpacing

method `spacing=`(container: LayoutContainer, spacing: int) =
  container.fSpacing = spacing
  container.triggerRelayout()

method realignChildControls(container: LayoutContainer) =
  # echo ""
  # echo container.tag & ".realignChildControls()"
  if container.fChildControls.len == 0:
    return
  # echo "  container size: " & $container.width & ", " & $container.height
  let padding = container.getPadding()
  let clientWidth = container.visibleWidth - padding.left - padding.right
  let clientHeight = container.visibleHeight - padding.top - padding.bottom

  # echo "  client size: " & $clientWidth & ", " & $clientHeight
  var minInnerWidth = 0
  var minInnerHeight = 0
  var expandWidthCount = 0
  var expandHeightCount = 0

  # Calculate minimum needed size:
  for control in container.fChildControls:
    if not control.visible:
      continue

    if control.widthMode in {WidthMode_Fill, WidthMode_Expand}:
      if container.layout == Layout_Horizontal:
        minInnerWidth.inc(control.minWidth)
        expandWidthCount.inc

    elif control.widthMode in {WidthMode_Auto , WidthMode_Static}:
      if container.layout == Layout_Horizontal:
        if control.wantedWidth == -1:
          minInnerWidth.inc(control.minWidth)
          expandWidthCount.inc
        else:
          minInnerWidth.inc(control.wantedWidth)
      else:
        if control.wantedWidth == -1:
          expandWidthCount.inc
        else:
          minInnerWidth = max(minInnerWidth, control.wantedWidth)

    if control.heightMode in {HeightMode_Fill, HeightMode_Expand}:
      if container.layout == Layout_Vertical:
        minInnerHeight.inc(control.minHeight)
        expandHeightCount.inc

    elif control.heightMode in {HeightMode_Auto, HeightMode_Static}:
      if container.layout == Layout_Vertical:
        if control.wantedHeight == -1:
          minInnerHeight.inc(control.minHeight)
          expandHeightCount.inc
        else:
          minInnerHeight.inc(control.wantedHeight)
      else:
        if control.wantedHeight == -1:
          expandHeightCount.inc
        else:
          minInnerHeight = max(minInnerHeight, control.wantedHeight)

  # Add padding:
  minInnerWidth.inc(container.padding * 2)
  minInnerHeight.inc(container.padding * 2)

  # Add spacing:
  if container.childControls.len > 1:
    if container.layout == Layout_Horizontal:
      minInnerWidth.inc(container.spacing * (container.childControls.len - 1))
    if container.layout == Layout_Vertical:
      minInnerHeight.inc(container.spacing * (container.childControls.len - 1))

  container.updateInnerSize(minInnerWidth, minInnerHeight)

  let innerWidth = max(minInnerWidth, clientWidth)
  let innerHeight = max(minInnerHeight, clientHeight)

  # Calculate dynamic size:
  var dynamicWidth = clientWidth - minInnerWidth
  var dynamicHeight = clientHeight - minInnerHeight
  dynamicWidth = max(dynamicWidth, 0)
  dynamicHeight = max(dynamicHeight, 0)

  # Move and resize controls:
  var x = container.padding
  var y = container.padding

  if (container.xAlign == XAlign_Center or (container.xAlign == XAlign_Spread and container.childControls.len == 1)) and (container.layout == Layout_Vertical or expandWidthCount == 0):
    x.inc(dynamicWidth div 2)
  elif container.xAlign == XAlign_Right:
    x.inc(dynamicWidth)
  if (container.yAlign == YAlign_Center or (container.yAlign == YAlign_Spread and container.childControls.len == 1)) and (container.layout == Layout_Horizontal or expandHeightCount == 0):
    y.inc(dynamicHeight div 2)
  elif container.yAlign == YAlign_Bottom:
    y.inc(dynamicHeight)

  for control in container.fChildControls:
    if not control.visible:
      continue
    # echo "  child: " & control.tag

    # Size:
    var width = control.width
    var height = control.height
    # echo "size old: " & $width & ", " $height
    if control.widthMode in {WidthMode_Fill, WidthMode_Expand} or control.wantedWidth == -1:
      if container.layout == Layout_Horizontal:
        if expandWidthCount > 0:
          width = control.minWidth + dynamicWidth div expandWidthCount
        else:
          width = control.minWidth + dynamicWidth
      else:
        width = clientWidth - container.padding * 2
    elif control.widthMode == WidthMode_Auto:
      width = control.wantedWidth

    if control.minWidth > width:
      width = control.minWidth
    if control.maxWidth > 0 and control.maxWidth < width:
      width = control.maxWidth

    if control.heightMode in {HeightMode_Fill, HeightMode_Expand} or control.wantedHeight == -1:
      if container.layout == Layout_Vertical:
        if expandHeightCount > 0:
          height = control.minHeight + dynamicHeight div expandHeightCount
        else:
          height = control.minHeight + dynamicHeight
      else:
        height = clientHeight - container.padding * 2
    elif control.heightMode == HeightMode_Auto:
      height = control.wantedHeight

    if control.minHeight > height:
      height = control.minHeight
    if control.maxHeight > 0 and control.maxHeight < height:
      height = control.maxHeight

    if control.width != width or control.height != height:
      # echo "  ", control.tag, "    new size: ", width, ", ", $height
      control.setSize(width, height)

    # Position:
    if container.layout == Layout_Vertical or container.childControls.len == 1:
      if container.xAlign == XAlign_Center:
        x = (innerWidth - width) div 2
      elif container.xAlign == XAlign_Right:
        x = innerWidth - width - container.padding
    if container.layout == Layout_Horizontal or container.childControls.len == 1:
      if container.yAlign == YAlign_Center:
        y = (innerHeight - height) div 2
      elif container.yAlign == YAlign_Bottom:
        y = innerHeight - height - container.padding

    if control.x != x or control.y != y:
      # echo "    new pos: ", x, ", ", $y
      control.setPosition(x, y)

    # Calculate next position:
    case container.layout
    of Layout_Horizontal:
      x.inc(width)
      x.inc(container.spacing)
      if container.xAlign == XAlign_Spread and expandWidthCount == 0 and container.childControls.len > 1:
        x.inc(dynamicWidth div (container.childControls.len - 1))
    of Layout_Vertical:
      y.inc(height)
      y.inc(container.spacing)
      if container.yAlign == YAlign_Spread and expandHeightCount == 0 and container.childControls.len > 1:
        y.inc(dynamicHeight div (container.childControls.len - 1))


# ----------------------------------------------------------------------------------------
#                                        Frame
# ----------------------------------------------------------------------------------------

proc newFrame(text = ""): Frame =
  result = new NativeFrame
  result.NativeFrame.init()
  result.text = text

proc init(frame: Frame) =
  frame.ControlImpl.init()

method text(frame: Frame): string = frame.fText

method `text=`(frame: Frame, text: string) =
  frame.fText = text
  frame.tag = text
  frame.forceRedraw()
  # should be extended by NativeFrame

method getPadding(frame: Frame): Spacing =
  result.left = 4.scaleToDpi
  result.right = 4.scaleToDpi
  result.top = 4.scaleToDpi
  result.bottom = 4.scaleToDpi
  # should be extended by NativeFrame

method `onDraw=`(container: NativeFrame, callback: DrawProc) = raiseError("NativeFrame does not allow onDraw.")


# ----------------------------------------------------------------------------------------
#                                        Button
# ----------------------------------------------------------------------------------------

proc newButton(text = ""): Button =
  result = new NativeButton
  result.NativeButton.init()
  result.text = text

proc init(button: Button) =
  button.ControlImpl.init()
  button.fWidthMode = WidthMode_Auto
  button.fHeightMode = HeightMode_Auto
  button.minWidth = 15.scaleToDpi
  button.minHeight = 15.scaleToDpi
  button.enabled = true

method text(button: Button): string = button.fText

method `text=`(button: Button, text: string) =
  button.fText = text
  button.tag = text
  button.triggerRelayoutIfModeIsAuto()
  button.forceRedraw()
  # should be extended by NativeButton

method naturalWidth(button: Button): int = button.getTextWidth(button.text) + 20.scaleToDpi

method naturalHeight(button: Button): int = button.getTextLineHeight() * button.text.countLines + 12.scaleToDpi

method enabled(button: Button): bool = button.fEnabled

method `enabled=`(button: Button, enabled: bool) = discard
  # has to be implemented by NativeButton

method handleKeyDownEvent*(button: Button, event: KeyboardEvent) =
  if event.key == Key_Return or event.key == Key_Space:
    var clickEvent = new ClickEvent
    clickEvent.control = button
    button.handleClickEvent(clickEvent)


method `onDraw=`(container: NativeButton, callback: DrawProc) = raiseError("NativeButton does not allow onDraw.")


# ----------------------------------------------------------------------------------------
#                                        Checkbox
# ----------------------------------------------------------------------------------------

proc newCheckbox(text = ""): Checkbox =
  result = new NativeCheckbox
  result.NativeCheckbox.init()
  result.text = text

proc init(checkbox: Checkbox) =
  checkbox.ControlImpl.init()
  checkbox.fWidthMode = WidthMode_Auto
  checkbox.fHeightMode = HeightMode_Auto
  checkbox.enabled = true

method text(checkbox: Checkbox): string = checkbox.fText

method `text=`(checkbox: Checkbox, text: string) =
  checkbox.fText = text
  checkbox.tag = text
  checkbox.triggerRelayoutIfModeIsAuto()
  checkbox.forceRedraw()

method naturalWidth(checkbox: Checkbox): int = checkbox.getTextWidth(checkbox.text) + 20.scaleToDpi

method naturalHeight(checkbox: Checkbox): int = checkbox.getTextLineHeight() * checkbox.text.countLines + 12.scaleToDpi

method enabled(checkbox: Checkbox): bool = checkbox.fEnabled

method `enabled=`(checkbox: Checkbox, enabled: bool) = discard
  # has to be implemented by NativeCheckbox

method checked(checkbox: Checkbox): bool = discard
  # has to be implemented by NativeCheckbox

method `checked=`(checkbox: Checkbox, checked: bool) = discard
  # has to be implemented by NativeCheckbox

method handleKeyDownEvent*(checkbox: Checkbox, event: KeyboardEvent) =
  if event.key == Key_Return or event.key == Key_Space:
    checkbox.checked = not checkbox.checked
    var evt = new ToggleEvent
    evt.control = checkbox
    checkbox.handleToggleEvent(evt)
    event.handled = true


method `onDraw=`(checkbox: NativeCheckbox, callback: DrawProc) = raiseError("NativeCheckbox does not allow onDraw.")

method onToggle(checkbox: Checkbox): ToggleProc = checkbox.fOnToggle
method `onToggle=`(checkbox: Checkbox, callback: ToggleProc) = checkbox.fOnToggle = callback

method handleToggleEvent(checkbox: Checkbox, event: ToggleEvent) =
  # can be overridden by custom control
  let callback = checkbox.onToggle
  if callback != nil:
    callback(event)


# ----------------------------------------------------------------------------------------
#                                        Label
# ----------------------------------------------------------------------------------------

proc newLabel(text = ""): Label =
  result = new NativeLabel
  result.NativeLabel.init()
  result.text = text

proc init(label: Label) =
  label.ControlImpl.init()
  label.fWidthMode = WidthMode_Auto
  label.fHeightMode = HeightMode_Auto
  label.minWidth = 10.scaleToDpi
  label.minHeight = 10.scaleToDpi

method text(label: Label): string = label.fText

method `text=`(label: Label, text: string) =
  label.fText = text
  label.tag = text
  label.triggerRelayoutIfModeIsAuto()
  label.forceRedraw()

method naturalWidth(label: Label): int = label.getTextWidth(label.text)

method naturalHeight(label: Label): int = label.getTextLineHeight() * label.text.countLines

method `onDraw=`(container: NativeLabel, callback: DrawProc) = raiseError("NativeLabel does not allow onDraw.")


# ----------------------------------------------------------------------------------------
#                                       TextBox
# ----------------------------------------------------------------------------------------

proc newTextBox(text = ""): TextBox =
  result = new NativeTextBox
  result.NativeTextBox.init()
  result.text = text

proc init(textBox: TextBox) =
  textBox.ControlImpl.init()
  textBox.fWidthMode = WidthMode_Expand
  textBox.fHeightMode = HeightMode_Auto
  textBox.minWidth = 20.scaleToDpi
  textBox.minHeight = 20.scaleToDpi
  textBox.editable = true

method naturalHeight(textBox: TextBox): int = textBox.getTextLineHeight()

method text(textBox: TextBox): string = discard
  # has to be implemented by NativeTextBox

method `text=`(textBox: TextBox, text: string) = discard
  # has to be implemented by NativeTextBox

method `onDraw=`(container: NativeTextBox, callback: DrawProc) = raiseError("NativeTextBox does not allow onDraw.")

method editable(textBox: TextBox): bool = textBox.fEditable

method `editable=`(textBox: TextBox, editable: bool) = discard
  # has to be implemented by NativeTextBox

method cursorPos(textBox: TextBox): int = discard
  # has to be implemented by NativeTextBox

method `cursorPos=`(textBox: TextBox, cursorPos: int) = discard
  # has to be implemented by NativeTextBox

method selectionStart(textBox: TextBox): int = discard
  # has to be implemented by NativeTextBox

method `selectionStart=`(textBox: TextBox, selectionStart: int) = discard
  # has to be implemented by NativeTextBox

method selectionEnd(textBox: TextBox): int = discard
  # has to be implemented by NativeTextBox

method `selectionEnd=`(textBox: TextBox, selectionEnd: int) = discard
  # has to be implemented by NativeTextBox

method selectedText(textBox: TextBox): string =
  result = textBox.text.runeSubStr(textBox.selectionStart, textBox.selectionEnd - textBox.selectionStart)

method `selectedText=`(textBox: TextBox, text: string) =
  let oldCursorPos = textBox.cursorPos
  let oldText = textBox.text
  textBox.text = oldText.runeSubStr(0, textBox.selectionStart) & text & oldText.runeSubStr(textBox.selectionEnd)
  textBox.cursorPos = oldCursorPos

method handleTextChangeEvent(textBox: TextBox, event: TextChangeEvent) =
  # can be overridden by custom control
  let callback = textBox.onTextChange
  if callback != nil:
    callback(event)

method onTextChange(textBox: TextBox): TextChangeProc = textBox.fOnTextChange

method `onTextChange=`(textBox: TextBox, callback: TextChangeProc) = textBox.fOnTextChange = callback


# ----------------------------------------------------------------------------------------
#                                      TextArea
# ----------------------------------------------------------------------------------------

proc newTextArea(text = ""): TextArea =
  result = new NativeTextArea
  result.NativeTextArea.init()
  result.text = text

proc init(textArea: TextArea) =
  textArea.ControlImpl.init()
  textArea.fWidthMode = WidthMode_Expand
  textArea.fHeightMode = HeightMode_Expand
  textArea.minWidth = 20.scaleToDpi
  textArea.minHeight = 20.scaleToDpi
  textArea.wrap = true
  textArea.editable = true

method addText(textArea: TextArea, text: string) = textArea.text = textArea.text & text

method addLine(textArea: TextArea, text = "") = textArea.addtext(text & "\p")

method scrollToBottom(textArea: TextArea) = discard
  # has to be implemented by NativeTextBox

method `onDraw=`(container: NativeTextArea, callback: DrawProc) = raiseError("NativeTextArea does not allow onDraw.")

method wrap(textArea: TextArea): bool = textArea.fWrap

method `wrap=`(textArea: TextArea, wrap: bool) =
  textArea.fWrap = wrap
  # should be extended by NativeTextArea


# ----------------------------------------------------------------------------------------
#                             Platform-specific implementation
# ----------------------------------------------------------------------------------------

when useWindows(): include "nigui/private/windows/platform_impl"
when useGtk():     include "nigui/private/gtk3/platform_impl"