vb6parse 1.0.0

vb6parse is a library for parsing and analyzing VB6 code, from projects, to controls, to modules, and forms.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
//! VB6 Control definitions and properties.
//!
//! This module contains the definitions for various VB6 controls,
//! including their properties and enumerations used to represent
//! different settings for these controls.
//! Each control is represented as a struct with associated properties,
//! and enumerations are used to define specific options for properties
//! such as alignment, visibility, and behavior.
//! This module is essential for parsing and representing VB6 forms
//! and their controls in a structured manner.
//!
//! References to official Microsoft documentation are provided for
//! each property and enumeration to ensure accuracy and completeness.
//!
//! Modules for individual controls are also included, each defining
//! the properties specific to that control type.
//!

pub mod checkbox;
pub mod combobox;
pub mod commandbutton;
pub mod custom;
pub mod data;
pub mod dirlistbox;
pub mod drivelistbox;
pub mod filelistbox;
pub mod form;
pub mod form_root;
pub mod frame;
pub mod image;
pub mod label;
pub mod line;
pub mod listbox;
pub mod mdiform;
pub mod menus;
pub mod ole;
pub mod optionbutton;
pub mod picturebox;
pub mod scrollbars;
pub mod shape;
pub mod textbox;
pub mod timer;

use std::convert::{From, TryFrom};
use std::fmt::{Display, Formatter};
use std::str::FromStr;

use num_enum::TryFromPrimitive;
use serde::Serialize;

use crate::errors::{FormError, ErrorKind};
use crate::language::PropertyGroup;

use crate::language::controls::{
    checkbox::CheckBoxProperties,
    combobox::ComboBoxProperties,
    commandbutton::CommandButtonProperties,
    custom::CustomControlProperties,
    data::DataProperties,
    dirlistbox::DirListBoxProperties,
    drivelistbox::DriveListBoxProperties,
    filelistbox::FileListBoxProperties,
    frame::FrameProperties,
    image::ImageProperties,
    label::LabelProperties,
    line::LineProperties,
    listbox::ListBoxProperties,
    menus::{MenuControl, MenuProperties},
    ole::OLEProperties,
    optionbutton::OptionButtonProperties,
    picturebox::PictureBoxProperties,
    scrollbars::ScrollBarProperties,
    shape::ShapeProperties,
    textbox::TextBoxProperties,
    timer::TimerProperties,
};

// Re-export form root types at the controls module level
pub use form_root::{Form, FormRoot, MDIForm};

/// `AutoRedraw` determines if the control is redrawn automatically when something is
/// moved in front of it or if it is redrawn manually.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245029(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum AutoRedraw {
    /// Disables automatic repainting of an object and writes graphics or text
    /// only to the screen. Visual Basic invokes the object's `Paint` event when
    /// necessary to repaint the object.
    ///
    /// This is the default setting.
    #[default]
    Manual = 0,
    /// Enables automatic repainting of a `Form` object or `PictureBox` control.
    /// Graphics and text are written to the screen and to an image stored in memory.
    /// The object doesn't receive `Paint` events; it's repainted when necessary,
    /// using the image stored in memory.
    Automatic = -1,
}

impl TryFrom<&str> for AutoRedraw {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(AutoRedraw::Manual),
            "-1" => Ok(AutoRedraw::Automatic),
            _ => Err(ErrorKind::Form(FormError::InvalidAutoRedraw {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for AutoRedraw {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        AutoRedraw::try_from(s)
    }
}

impl From<bool> for AutoRedraw {
    fn from(value: bool) -> Self {
        if value {
            AutoRedraw::Automatic
        } else {
            AutoRedraw::Manual
        }
    }
}

impl Display for AutoRedraw {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            AutoRedraw::Manual => "Manual",
            AutoRedraw::Automatic => "Automatic",
        };
        write!(f, "{text}")
    }
}

/// `TextDirection` determines the direction in which text is displayed in the control.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa442921(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum TextDirection {
    /// The text is ordered from left to right.
    ///
    /// This is the default setting.
    #[default]
    LeftToRight = 0,
    /// The text is ordered from right to left.
    RightToLeft = -1,
}

impl TryFrom<&str> for TextDirection {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(TextDirection::LeftToRight),
            "-1" => Ok(TextDirection::RightToLeft),
            _ => Err(ErrorKind::Form(FormError::InvalidTextDirection {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for TextDirection {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, ErrorKind> {
        TextDirection::try_from(s)
    }
}

impl From<bool> for TextDirection {
    fn from(value: bool) -> Self {
        if value {
            TextDirection::RightToLeft
        } else {
            TextDirection::LeftToRight
        }
    }
}

impl Display for TextDirection {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            TextDirection::LeftToRight => "Left to Right",
            TextDirection::RightToLeft => "Right to Left",
        };
        write!(f, "{text}")
    }
}

/// `AutoSize` determines if the control is automatically resized to fit its contents.
/// This is used with the `Label` control and the `PictureBox` control.
///
/// In a `PictureBox`, this property is used to determine if the control is automatically resized
/// to fit the size of the picture. If set to `Fixed` the control is not resized and the picture
/// will be scaled or clipped depending on other properties like `SizeMode`.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245034(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum AutoSize {
    /// Keeps the size of the control constant. Contents are clipped when they
    /// exceed the area of the control.
    ///
    /// This is the default setting.
    #[default]
    Fixed = 0,
    /// Automatically resizes the control to display its entire contents.
    Resize = -1,
}

impl TryFrom<&str> for AutoSize {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, ErrorKind> {
        match value {
            "0" => Ok(AutoSize::Fixed),
            "-1" => Ok(AutoSize::Resize),
            _ => Err(ErrorKind::Form(FormError::InvalidAutoSize {
                value: value.to_string(),
            })),
        }
    }
}

impl From<bool> for AutoSize {
    fn from(value: bool) -> Self {
        if value {
            AutoSize::Resize
        } else {
            AutoSize::Fixed
        }
    }
}

impl FromStr for AutoSize {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, ErrorKind> {
        AutoSize::try_from(s)
    }
}

impl Display for AutoSize {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            AutoSize::Fixed => "Fixed",
            AutoSize::Resize => "Resize",
        };
        write!(f, "{text}")
    }
}

/// Determines if a control or form can respond to user-generated events.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa267301(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum Activation {
    /// The control is disabled and will not respond to user-generated events.
    Disabled = 0,
    /// The control is enabled and will respond to user-generated events.
    ///
    /// This is the default setting.
    #[default]
    Enabled = -1,
}

impl From<bool> for Activation {
    fn from(value: bool) -> Self {
        if value {
            Activation::Enabled
        } else {
            Activation::Disabled
        }
    }
}

impl TryFrom<&str> for Activation {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Activation::Disabled),
            "-1" => Ok(Activation::Enabled),
            _ => Err(ErrorKind::Form(FormError::InvalidActivation {
                value: value.to_string(),
            })),
        }
    }
}

impl Display for Activation {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Activation::Disabled => "Disabled",
            Activation::Enabled => "Enabled",
        };
        write!(f, "{text}")
    }
}

/// `TabStop` determines if the control is included in the tab order.
/// In VB6, the `TabStop` property determines whether a control can receive focus
/// when the user navigates through controls using the Tab key.
///
/// When `TabStop` is set to `Included`, the control is included in the tab order
/// and can receive focus when the user presses the Tab key.
///
/// When `TabStop` is set to `ProgrammaticOnly`, the control is skipped in the
/// tab order and cannot receive focus via the Tab key.
/// However, it can still receive focus programmatically or through other user interactions.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445721(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum TabStop {
    /// Bypasses the object when the user is tabbing, although the object still
    /// holds its place in the actual tab order, as determined by the `TabIndex`
    /// property.
    ProgrammaticOnly = 0,
    /// Designates the object as a tab stop.
    ///
    /// This is the default setting.
    #[default]
    Included = -1,
}

impl From<bool> for TabStop {
    fn from(value: bool) -> Self {
        if value {
            TabStop::Included
        } else {
            TabStop::ProgrammaticOnly
        }
    }
}

impl TryFrom<&str> for TabStop {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(TabStop::ProgrammaticOnly),
            "-1" => Ok(TabStop::Included),
            _ => Err(ErrorKind::Form(FormError::InvalidTabStop {
                value: value.to_string(),
            })),
        }
    }
}

impl Display for TabStop {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            TabStop::ProgrammaticOnly => "Programmatic Only",
            TabStop::Included => "Included",
        };
        write!(f, "{text}")
    }
}

/// Determines if the control is visible or hidden.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445768(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum Visibility {
    /// The control is not visible.
    Hidden = 0,
    /// The control is visible.
    ///
    /// This is the default setting.
    #[default]
    Visible = -1,
}

impl TryFrom<&str> for Visibility {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Visibility::Hidden),
            "-1" => Ok(Visibility::Visible),
            _ => Err(ErrorKind::Form(FormError::InvalidVisibility {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Visibility {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Visibility::try_from(s)
    }
}

impl From<bool> for Visibility {
    fn from(value: bool) -> Self {
        if value {
            Visibility::Visible
        } else {
            Visibility::Hidden
        }
    }
}

impl Display for Visibility {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Visibility::Hidden => "Hidden",
            Visibility::Visible => "Visible",
        };
        write!(f, "{text}")
    }
}

/// Determines if the control has a device context.
///
/// A device context is a Windows data structure that defines a set of graphic
/// objects and their associated attributes, and it defines a mapping between
/// the logical coordinates and device coordinates for a particular device, such
/// as a display or printer.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245860(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum HasDeviceContext {
    /// The control does not have a device context.
    NoContext = 0,
    /// The control has a device context.
    ///
    /// This is the default setting.
    #[default]
    HasContext = -1,
}

impl TryFrom<&str> for HasDeviceContext {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(HasDeviceContext::NoContext),
            "-1" => Ok(HasDeviceContext::HasContext),
            _ => Err(ErrorKind::Form(FormError::InvalidHasDeviceContext {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for HasDeviceContext {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        HasDeviceContext::try_from(s)
    }
}

impl From<bool> for HasDeviceContext {
    fn from(value: bool) -> Self {
        if value {
            HasDeviceContext::HasContext
        } else {
            HasDeviceContext::NoContext
        }
    }
}

impl Display for HasDeviceContext {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            HasDeviceContext::NoContext => "No Context",
            HasDeviceContext::HasContext => "Has Context",
        };
        write!(f, "{text}")
    }
}

/// Determines whether the color assigned in the `mask_color` property is used
/// as a mask.
/// That is, if it is used to create transparent regions.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445753(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum UseMaskColor {
    /// The control does not use the mask color.
    ///
    /// This is the default setting.
    #[default]
    DoNotUseMaskColor = 0,
    /// The color assigned to the `mask_color` property is used as a mask,
    /// creating a transparent region wherever that color is.
    UseMaskColor = -1,
}

impl Display for UseMaskColor {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            UseMaskColor::DoNotUseMaskColor => "Do not use Mask Color",
            UseMaskColor::UseMaskColor => "Use Mask Color",
        };
        write!(f, "{text}")
    }
}

/// Determines if the control causes validation.
/// In VB6, the `CausesValidation` property determines whether a control causes validation
/// to occur when the user attempts to move focus from the control.
///
/// If `CausesValidation` is set to `true`, validation occurs when the user attempts to move
/// focus from the control to another control.
///
/// If `CausesValidation` is set to `false`, validation does not occur when the user attempts
/// to move focus from the control to another control.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245065(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum CausesValidation {
    /// The control does not cause validation.
    ///
    /// The control from which the focus has shifted does not fire its `Validate` event.
    No = 0,
    /// The control causes validation.
    /// The control from which the focus has shifted fires its `Validate` event.
    ///
    /// This is the default setting.
    #[default]
    Yes = -1,
}

impl TryFrom<&str> for CausesValidation {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(CausesValidation::No),
            "-1" => Ok(CausesValidation::Yes),
            _ => Err(ErrorKind::Form(FormError::InvalidCausesValidation {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for CausesValidation {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        CausesValidation::try_from(s)
    }
}

impl From<bool> for CausesValidation {
    fn from(value: bool) -> Self {
        if value {
            CausesValidation::Yes
        } else {
            CausesValidation::No
        }
    }
}

impl Display for CausesValidation {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            CausesValidation::No => "No",
            CausesValidation::Yes => "Yes",
        };
        write!(f, "{text}")
    }
}

/// The `Movability` property of a `Form` control determines whether the
/// form can be moved by the user. If the form is not moveable, the user cannot
/// move the form by dragging its title bar or by using the arrow keys.
/// If the form is moveable, the user can move the form by dragging its title
/// bar or by using the arrow keys.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa235194(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    Default,
    TryFromPrimitive,
    serde::Serialize,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum Movability {
    /// The form is not moveable.
    Fixed = 0,
    /// The form is moveable.
    ///
    /// This is the default setting.
    #[default]
    Moveable = -1,
}

impl TryFrom<&str> for Movability {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Movability::Fixed),
            "-1" => Ok(Movability::Moveable),
            _ => Err(ErrorKind::Form(FormError::InvalidMovability {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Movability {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Movability::try_from(s)
    }
}

impl From<bool> for Movability {
    fn from(value: bool) -> Self {
        if value {
            Movability::Moveable
        } else {
            Movability::Fixed
        }
    }
}

impl Display for Movability {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Movability::Fixed => "Fixed",
            Movability::Moveable => "Moveable",
        };
        write!(f, "{text}")
    }
}

/// Determines whether background text and graphics on a `Form` or a `PictureBox`
/// control are displayed in the spaces around characters.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa267490(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    Default,
    TryFromPrimitive,
    serde::Serialize,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum FontTransparency {
    /// Masks existing background graphics and text around the characters of a
    /// font.
    Opaque = 0,
    /// Permits background graphics and text to show around the spaces of the
    /// characters in a font.
    ///
    /// This is the default setting.
    #[default]
    Transparent = -1,
}

impl TryFrom<&str> for FontTransparency {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(FontTransparency::Opaque),
            "-1" => Ok(FontTransparency::Transparent),
            _ => Err(ErrorKind::Form(FormError::InvalidFontTransparency {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for FontTransparency {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        FontTransparency::try_from(s)
    }
}

impl From<bool> for FontTransparency {
    fn from(value: bool) -> Self {
        if value {
            FontTransparency::Transparent
        } else {
            FontTransparency::Opaque
        }
    }
}

impl Display for FontTransparency {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            FontTransparency::Opaque => "Opaque",
            FontTransparency::Transparent => "Transparent",
        };
        write!(f, "{text}")
    }
}

/// Determines whether context-sensitive Help uses the What's This pop-up
/// (provided by Help in 32-bit Windows operating systems) or the main Help
/// window.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445772(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    Default,
    TryFromPrimitive,
    serde::Serialize,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum WhatsThisHelp {
    /// The application uses the F1 key to start Windows Help and load the topic
    /// identified by the `help_context_id` property.
    ///
    /// This is the default setting.
    #[default]
    F1Help = 0,
    /// The application uses one of the "What's This?" access techniques to
    /// start Windows Help and load a topic identified by the
    /// `help_context_id` property.
    WhatsThisHelp = -1,
}

impl TryFrom<&str> for WhatsThisHelp {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(WhatsThisHelp::F1Help),
            "-1" => Ok(WhatsThisHelp::WhatsThisHelp),
            _ => Err(ErrorKind::Form(FormError::InvalidWhatsThisHelp {
                value: value.to_string(),
            })),
        }
    }
}

impl From<bool> for WhatsThisHelp {
    fn from(value: bool) -> Self {
        if value {
            WhatsThisHelp::WhatsThisHelp
        } else {
            WhatsThisHelp::F1Help
        }
    }
}

impl FromStr for WhatsThisHelp {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        WhatsThisHelp::try_from(s)
    }
}

impl Display for WhatsThisHelp {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            WhatsThisHelp::F1Help => "F1Help",
            WhatsThisHelp::WhatsThisHelp => "WhatsThisHelp",
        };
        write!(f, "{text}")
    }
}

/// Determines the type of link used for a DDE conversation and activates the
/// connection.
///
/// Forms allow a destination application to initiate a conversation with a
/// Visual Basic source form as specified by the destination applications
/// `application**|topic!**item` expression.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa235154(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum FormLinkMode {
    /// No DDE interaction. No destination application can initiate a conversation
    /// with the source form as the topic, and no application can poke data to
    /// the form.
    ///
    /// This is the default setting.
    #[default]
    None = 0,
    /// Allows any `Label`, `PictureBox`, or `TextBox` control on a form to supply
    /// data to any destination application that establishes a DDE conversation
    /// with the form. If such a link exists, Visual Basic automatically
    /// notifies the destination whenever the contents of a control are changed.
    /// In addition, a destination application can poke data to any `Label`,
    /// `PictureBox`, or `TextBox` control on the form.
    Source = 1,
}

impl TryFrom<&str> for FormLinkMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(FormLinkMode::None),
            "1" => Ok(FormLinkMode::Source),
            _ => Err(ErrorKind::Form(FormError::InvalidFormLinkMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for FormLinkMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        FormLinkMode::try_from(s)
    }
}

impl From<bool> for FormLinkMode {
    fn from(value: bool) -> Self {
        if value {
            FormLinkMode::Source
        } else {
            FormLinkMode::None
        }
    }
}

impl Display for FormLinkMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            FormLinkMode::None => "None",
            FormLinkMode::Source => "Source",
        };
        write!(f, "{text}")
    }
}

/// Controls the display state of a form from normal, minimized, or maximized.
/// This is used with the `Form` and `MDIForm` controls.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445778(v=vs.60))
#[derive(
    Debug,
    PartialEq,
    Eq,
    Clone,
    serde::Serialize,
    Default,
    TryFromPrimitive,
    Copy,
    Hash,
    PartialOrd,
    Ord,
)]
#[repr(i32)]
pub enum WindowState {
    /// The form is in its normal state.
    ///
    /// This is the default setting.
    #[default]
    Normal = 0,
    /// The form is minimized (minimized to an icon0).
    Minimized = 1,
    /// The form is maximized (enlarged to maximum size).
    Maximized = 2,
}

impl TryFrom<&str> for WindowState {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(WindowState::Normal),
            "1" => Ok(WindowState::Minimized),
            "2" => Ok(WindowState::Maximized),
            _ => Err(ErrorKind::Form(FormError::InvalidWindowState {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for WindowState {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        WindowState::try_from(s)
    }
}

impl Display for WindowState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            WindowState::Normal => "Normal",
            WindowState::Minimized => "Minimized",
            WindowState::Maximized => "Maximized",
        };
        write!(f, "{text}")
    }
}

/// The `StartUpPosition` property of a `Form` or `MDIForm` control determines
/// the initial position of the form when it first appears.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445708(v=vs.60))
#[derive(Debug, PartialEq, Eq, Clone, serde::Serialize, Default, Copy, Hash, PartialOrd, Ord)]
pub enum StartUpPosition {
    /// The form is positioned based on the `client_height`, `client_width`,
    /// `client_top`, and `client_left` properties.
    ///
    /// The `Manual` variant is saved as a 0 in the VB6 file.
    Manual {
        /// The height of the client area of the form.
        client_height: i32,
        /// The width of the client area of the form.
        client_width: i32,
        /// The top position of the client area of the form.
        client_top: i32,
        /// The left position of the client area of the form.
        client_left: i32,
    },
    /// The form is centered in the parent window.
    ///
    /// The `CenterOwner` variant is saved as a 1 in the VB6 file.
    CenterOwner,
    /// The form is centered on the screen.
    ///
    /// The `CenterScreen` variant is saved as a 2 in the VB6 file.
    CenterScreen,
    #[default]
    /// Position in upper-left corner of screen.
    ///
    /// The `WindowsDefault` variant is saved as a 3 in the VB6 file.
    ///
    /// This is the default setting.
    WindowsDefault,
}

impl Display for StartUpPosition {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            StartUpPosition::Manual {
                client_height,
                client_width,
                client_top,
                client_left,
            } => write!(
                f,
                "Manual {{ client height: {client_height}, client width: {client_width}, client top: {client_top}, client left: {client_left} }}"
            ),
            StartUpPosition::CenterOwner => write!(f, "CenterOwner"),
            StartUpPosition::CenterScreen => write!(f, "CenterScreen"),
            StartUpPosition::WindowsDefault => write!(f, "WindowsDefault"),
        }
    }
}

/// Represents either a reference to an external resource within a *.frx file or an embedded value.
///
/// This is used to represent properties that can either be stored directly within the VB6 form file
/// or as a reference to an external resource stored in the associated *.frx file.
///
/// The `Reference` variant contains the filename and offset within the *.frx file where the resource can be found.
/// The `Value` variant contains the actual value of type `T`.
///
/// This is useful for handling properties such as images, icons, or other binary data that may be
/// stored externally to keep the form file size manageable.
#[derive(Debug, PartialEq, Clone, Serialize)]
pub enum ReferenceOrValue<T> {
    Reference { filename: String, offset: u32 },
    Value(T),
}

impl<T> Display for ReferenceOrValue<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ReferenceOrValue::Reference { filename, offset } => {
                write!(f, "Reference {{ filename: {filename}, offset: {offset} }}",)
            }
            ReferenceOrValue::Value(_) => write!(f, "Value"),
        }
    }
}

/// Represents a VB6 control.
#[derive(Debug, PartialEq, Clone, Serialize)]
pub struct Control {
    /// The name of the control.
    name: String,
    /// The tag of the control.
    tag: String,
    /// The index of the control.
    index: i32,
    /// The kind of control.
    kind: ControlKind,
}

impl Control {
    /// Creates a new `Control` with the specified properties.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the control
    /// * `tag` - The tag of the control
    /// * `index` - The index of the control
    /// * `kind` - The kind of control
    ///
    /// # Returns
    ///
    /// A new `Control` instance.
    #[must_use]
    pub fn new(name: String, tag: String, index: i32, kind: ControlKind) -> Self {
        Self {
            name,
            tag,
            index,
            kind,
        }
    }

    /// Returns the name of the control.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the tag of the control.
    #[must_use]
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Returns the index of the control.
    #[must_use]
    pub fn index(&self) -> i32 {
        self.index
    }

    /// Returns a reference to the control kind.
    #[must_use]
    pub fn kind(&self) -> &ControlKind {
        &self.kind
    }

    /// Consumes the control and returns its name.
    #[must_use]
    pub fn into_name(self) -> String {
        self.name
    }

    /// Consumes the control and returns its tag.
    #[must_use]
    pub fn into_tag(self) -> String {
        self.tag
    }

    /// Consumes the control and returns its kind.
    #[must_use]
    pub fn into_kind(self) -> ControlKind {
        self.kind
    }

    /// Consumes the control and returns all of its parts as a tuple.
    ///
    /// # Returns
    ///
    /// A tuple containing `(name, tag, index, kind)`.
    #[must_use]
    pub fn into_parts(self) -> (String, String, i32, ControlKind) {
        (self.name, self.tag, self.index, self.kind)
    }

    /// Sets the name of the control.
    ///
    /// This is primarily used during parsing when the control name needs to be
    /// updated based on attributes (e.g., `VB_Name` attribute in forms).
    pub fn set_name(&mut self, name: String) {
        self.name = name;
    }
}

impl Display for Control {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Control: {} ({})", self.name, self.kind)
    }
}

/// The `ControlKind` determines the specific kind of control that the `Control` represents.
///
/// Each variant contains the properties that are specific to that kind of control.
#[derive(Debug, PartialEq, Clone, Serialize)]
pub enum ControlKind {
    /// A command button control.
    CommandButton {
        /// The properties of the command button control.
        properties: CommandButtonProperties,
    },
    /// A data control.
    Data {
        /// The properties of the data control.
        properties: DataProperties,
    },
    /// A text box control.
    TextBox {
        /// The properties of the text box control.
        properties: TextBoxProperties,
    },
    /// A check box control.
    CheckBox {
        /// The properties of the check box control.
        properties: CheckBoxProperties,
    },
    /// A line control.
    Line {
        /// The properties of the line control.
        properties: LineProperties,
    },
    /// A shape control.
    Shape {
        /// The properties of the shape control.
        properties: ShapeProperties,
    },
    /// A list box control.
    ListBox {
        /// The properties of the list box control.
        properties: ListBoxProperties,
    },
    /// A timer control.
    Timer {
        /// The properties of the timer control.
        properties: TimerProperties,
    },
    /// A label control.
    Label {
        /// The properties of the label control.
        properties: LabelProperties,
    },
    /// A frame control.
    Frame {
        /// The properties of the frame control.
        properties: FrameProperties,
        /// The child controls of the frame control.
        controls: Vec<Control>,
    },
    /// A picture box control.
    PictureBox {
        /// The properties of the picture box control.
        properties: PictureBoxProperties,
        /// The child controls of the picture box control.
        controls: Vec<Control>,
    },
    /// A file list box control.
    FileListBox {
        /// The properties of the file list box control.
        properties: FileListBoxProperties,
    },
    /// A drive list box control.
    DriveListBox {
        /// The properties of the drive list box control.
        properties: DriveListBoxProperties,
    },
    /// A directory list box control.
    DirListBox {
        /// The properties of the directory list box control.
        properties: DirListBoxProperties,
    },
    /// An OLE control.
    Ole {
        /// The properties of the OLE control.
        properties: OLEProperties,
    },
    /// An option button control.
    OptionButton {
        /// The properties of the option button control.
        properties: OptionButtonProperties,
    },
    /// An image control.
    Image {
        /// The properties of the image control.
        properties: ImageProperties,
    },
    /// A combo box control.
    ComboBox {
        /// The properties of the combo box control.
        properties: ComboBoxProperties,
    },
    /// A horizontal scroll bar control.
    HScrollBar {
        /// The properties of the horizontal scroll bar control.
        properties: ScrollBarProperties,
    },
    /// A vertical scroll bar control.
    VScrollBar {
        /// The properties of the vertical scroll bar control.
        properties: ScrollBarProperties,
    },
    /// A menu control.
    Menu {
        /// The properties of the menu control.
        properties: MenuProperties,
        /// The sub-menus of the menu control.
        sub_menus: Vec<MenuControl>,
    },
    /// A custom control.
    Custom {
        /// The properties of the custom control.
        properties: CustomControlProperties,
        /// The property groups of the custom control.
        property_groups: Vec<PropertyGroup>,
    },
}

impl Display for ControlKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ControlKind::CommandButton { .. } => write!(f, "CommandButton"),
            ControlKind::Data { .. } => write!(f, "Data"),
            ControlKind::TextBox { .. } => write!(f, "TextBox"),
            ControlKind::CheckBox { .. } => write!(f, "CheckBox"),
            ControlKind::Line { .. } => write!(f, "Line"),
            ControlKind::Shape { .. } => write!(f, "Shape"),
            ControlKind::ListBox { .. } => write!(f, "ListBox"),
            ControlKind::Timer { .. } => write!(f, "Timer"),
            ControlKind::Label { .. } => write!(f, "Label"),
            ControlKind::Frame { .. } => write!(f, "Frame"),
            ControlKind::PictureBox { .. } => write!(f, "PictureBox"),
            ControlKind::FileListBox { .. } => write!(f, "FileListBox"),
            ControlKind::DriveListBox { .. } => write!(f, "DriveListBox"),
            ControlKind::DirListBox { .. } => write!(f, "DirListBox"),
            ControlKind::Ole { .. } => write!(f, "OLE"),
            ControlKind::OptionButton { .. } => write!(f, "OptionButton"),
            ControlKind::Image { .. } => write!(f, "Image"),
            ControlKind::ComboBox { .. } => write!(f, "ComboBox"),
            ControlKind::HScrollBar { .. } => write!(f, "HScrollBar"),
            ControlKind::VScrollBar { .. } => write!(f, "VScrollBar"),
            ControlKind::Menu { .. } => write!(f, "Menu"),
            ControlKind::Custom { .. } => write!(f, "Custom"),
        }
    }
}

/// Helper methods for `ControlKind`.
impl ControlKind {
    /// Indicates if the control kind is a `Menu`.
    ///
    /// # Returns
    ///
    /// Returns `true` if the control kind is a `Menu`, otherwise `false`.
    #[must_use]
    pub fn is_menu(&self) -> bool {
        matches!(self, ControlKind::Menu { .. })
    }

    /// Indicates if the control kind can contain child controls.
    ///
    /// # Returns
    ///
    /// Returns `true` if the control kind can contain child controls, otherwise `false`.
    #[must_use]
    pub fn can_contain_children(&self) -> bool {
        matches!(
            self,
            ControlKind::Frame { .. } | ControlKind::PictureBox { .. }
        )
    }

    /// Indicates if the control kind can contain menus.
    ///
    /// # Returns
    ///
    /// Returns `true` if the control kind can contain menus, otherwise `false`.
    ///
    /// Note: This always returns `false` for `ControlKind` since `Form` and `MDIForm`
    /// are now top-level types (`FormRoot`), not control kinds.
    #[must_use]
    pub fn can_contain_menus(&self) -> bool {
        false
    }

    /// Indicates if the control kind currently has menus.
    ///
    /// # Returns
    ///
    /// Returns `true` if the control kind has menus, otherwise `false`.
    ///
    /// Note: This always returns `false` for `ControlKind` since only `Form` and `MDIForm`
    /// can have menus, and they are now top-level types (`FormRoot`), not control kinds.
    #[must_use]
    pub fn has_menu(&self) -> bool {
        false
    }

    /// Indicates if the control kind currently has child controls.
    ///
    /// # Returns
    ///
    /// Returns `true` if the control kind has child controls, otherwise `false`.
    #[must_use]
    pub fn has_children(&self) -> bool {
        matches!(
            self,
            ControlKind::Frame { controls, .. } |
            ControlKind::PictureBox { controls, .. } if !controls.is_empty()
        )
    }

    /// Returns an iterator over child controls, if this control type supports children.
    ///
    /// # Returns
    ///
    /// An `Option` containing an iterator over child controls if the control kind supports children, otherwise `None`.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::*;
    /// use vb6parse::language::{Control, ControlKind, MenuControl, MenuProperties};
    ///
    /// let control = Control::new(
    ///     "MyFrame".to_string(),
    ///     "".to_string(),
    ///     0,
    ///     ControlKind::Frame {
    ///         properties: Default::default(),
    ///         controls: vec![],
    ///     },
    /// );
    ///
    /// if let Some(children) = control.kind().children() {
    ///     for child in children {
    ///         println!("Child control: {}", child.name());
    ///     }
    /// };
    /// ```
    #[must_use]
    pub fn children(&self) -> Option<impl Iterator<Item = &Control>> {
        match self {
            ControlKind::Frame { controls, .. } | ControlKind::PictureBox { controls, .. } => {
                Some(controls.iter())
            }
            _ => None,
        }
    }

    /// Returns an iterator over menus, if this control type supports menus.
    ///
    /// # Returns
    ///
    /// An `Option` containing an iterator over menus if the control kind supports menus, otherwise `None`.
    ///
    /// Note: This always returns `None` for `ControlKind` since only `Form` and `MDIForm`
    /// can have menus, and they are now top-level types (`FormRoot`), not control kinds.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::language::{ControlKind, MenuControl, MenuProperties};
    ///
    /// // Menu controls can have sub-menus
    /// let menu_kind = ControlKind::Menu {
    ///     properties: MenuProperties {
    ///         caption: "File".to_string(),
    ///         ..Default::default()
    ///     },
    ///     sub_menus: vec![],
    /// };
    ///
    /// // Most control kinds don't support menus
    /// assert!(menu_kind.menus().is_none());
    /// ```
    /// can have menus, and they are now top-level types (`FormRoot`), not control kinds.
    #[must_use]
    pub fn menus(&self) -> Option<impl Iterator<Item = &MenuControl>> {
        None::<std::iter::Empty<&MenuControl>>
    }

    /// Recursively iterates over all descendant controls, if this control type supports children.
    ///
    /// # Returns
    ///
    /// An iterator over all descendant controls.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::*;
    /// use vb6parse::language::{Control, ControlKind, MenuControl, MenuProperties};
    ///
    /// let control = Control::new(
    ///     "MyFrame".to_string(),
    ///     "".to_string(),
    ///     0,
    ///     ControlKind::Frame {
    ///         properties: Default::default(),
    ///         controls: vec![
    ///             Control::new(
    ///                 "Child1".to_string(),
    ///                 "".to_string(),
    ///                 0,
    ///                 ControlKind::Label {
    ///                     properties: Default::default(),
    ///                 },
    ///             ),
    ///             Control::new(
    ///                 "Child2".to_string(),
    ///                 "".to_string(),
    ///                 1,
    ///                 ControlKind::TextBox {
    ///                     properties: Default::default(),
    ///                 },
    ///             ),
    ///         ],
    ///     },
    /// );
    ///
    /// for child in control.kind().descendants() {
    ///     println!("Child control: {}", child.name());
    /// };
    /// ```
    #[must_use]
    pub fn descendants(&self) -> Box<dyn Iterator<Item = &Control> + '_> {
        Box::new(
            self.children()
                .into_iter()
                .flatten()
                .flat_map(|child| child.descendants()),
        )
    }
}

impl Control {
    /// Returns `true` if the control is a `Menu`.
    #[must_use]
    pub fn is_menu(&self) -> bool {
        self.kind.is_menu()
    }

    /// Returns `true` if the control has a menu.
    #[must_use]
    pub fn has_menu(&self) -> bool {
        self.kind.has_menu()
    }

    /// Returns an iterator over menus, if this control type supports menus.
    ///
    /// # Returns
    ///
    /// An `Option` containing an iterator over menus if the control supports menus, otherwise `None`.
    ///
    /// Note: This always returns `None` since only `Form` and `MDIForm` can have menus,
    /// and they are now top-level types (`FormRoot`), not control kinds.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::language::{Control, ControlKind};
    ///
    /// let control = Control::new(
    ///     "MyButton".to_string(),
    ///     "".to_string(),
    ///     0,
    ///     ControlKind::CommandButton {
    ///         properties: Default::default(),
    ///     },
    /// );
    ///
    /// // Regular controls don't support menus
    /// assert!(control.menus().is_none());
    /// ```
    #[must_use]
    pub fn menus(&self) -> Option<impl Iterator<Item = &MenuControl>> {
        self.kind.menus()
    }

    /// Returns true if this control type can contain menus.
    #[must_use]
    pub fn can_contain_menus(&self) -> bool {
        self.kind.can_contain_menus()
    }

    /// Returns true if this control type can contain child controls.
    #[must_use]
    pub fn can_contain_children(&self) -> bool {
        self.kind.can_contain_children()
    }

    /// Returns an iterator over child controls, if this control type supports children.
    ///
    /// # Returns
    ///
    /// An `Option` containing an iterator over child controls if the control supports children, otherwise `None`.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::*;
    /// use vb6parse::language::{Control, ControlKind, MenuControl, MenuProperties};
    ///
    /// let control = Control::new(
    ///     "MyFrame".to_string(),
    ///     "".to_string(),
    ///     0,
    ///     ControlKind::Frame {
    ///         properties: Default::default(),
    ///         controls: vec![],
    ///     },
    /// );
    ///
    /// if let Some(children) = control.children() {
    ///     for child in children {
    ///         println!("Child control: {}", child.name());
    ///     }
    /// };
    /// ```
    #[must_use]
    pub fn children(&self) -> Option<impl Iterator<Item = &Control>> {
        self.kind.children()
    }

    /// Returns true if this control type can contain child controls.
    #[must_use]
    pub fn has_children(&self) -> bool {
        matches!(
            self.kind,
            ControlKind::Frame { .. } | ControlKind::PictureBox { .. }
        )
    }

    /// Recursively iterates over this control and all descendants.
    ///
    /// # Returns
    ///
    /// An iterator over this control and all descendant controls.
    ///
    /// Example:
    /// ```rust
    /// use vb6parse::*;
    /// use vb6parse::language::{Control, ControlKind, MenuControl, MenuProperties};
    ///
    /// let control = Control::new(
    ///     "MyFrame".to_string(),
    ///     "".to_string(),
    ///     0,
    ///     ControlKind::Frame {
    ///         properties: Default::default(),
    ///         controls: vec![
    ///             Control::new(
    ///                 "Child1".to_string(),
    ///                 "".to_string(),
    ///                 0,
    ///                 ControlKind::Label {
    ///                     properties: Default::default(),
    ///                 },
    ///             ),
    ///             Control::new(
    ///                 "Child2".to_string(),
    ///                 "".to_string(),
    ///                 1,
    ///                 ControlKind::TextBox {
    ///                     properties: Default::default(),
    ///                 },
    ///             ),
    ///         ],
    ///     },
    /// );
    ///
    /// let mut descendants = control.descendants();
    /// while let Some(descendant) = descendants.next() {
    ///     println!("Descendant control: {}", descendant.name());
    /// }
    /// ```
    #[must_use]
    pub fn descendants(&self) -> Box<dyn Iterator<Item = &Control> + '_> {
        Box::new(std::iter::once(self).chain(self.kind.descendants()))
    }
}

/// Determines whether an object is displayed in any size anywhere on a form or
/// whether it's displayed at the top, bottom, left, or right of the form and is
/// automatically sized to fit the form's width.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa267259(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum Align {
    /// The control is not docked to any side of the parent control.
    /// This setting is ignored if the object is on an `MDIForm`.
    ///
    /// This is the default setting in a non-MDI form.
    #[default]
    None = 0,
    /// The top of the control is at the top of the form, and its width is equal
    /// to the form's `ScaleWidth` property setting.
    ///
    /// This is the default setting in an MDI form.
    Top = 1,
    /// The bottom of the control is at the bottom of the form, and its width is
    /// equal to the form's `ScaleWidth` property setting.
    Bottom = 2,
    /// The left side of the control is at the left of the form, and its width
    /// is equal to the form's `ScaleWidth` property setting.
    Left = 3,
    /// The right side of the control is at the right of the form, and its width
    /// is equal to the form's `ScaleWidth` property setting.
    Right = 4,
}

impl TryFrom<&str> for Align {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Align::None),
            "1" => Ok(Align::Top),
            "2" => Ok(Align::Bottom),
            "3" => Ok(Align::Left),
            "4" => Ok(Align::Right),
            _ => Err(ErrorKind::Form(FormError::InvalidAlign {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Align {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Align::try_from(s)
    }
}

impl Display for Align {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Align::None => "None",
            Align::Top => "Top",
            Align::Bottom => "Bottom",
            Align::Left => "Left",
            Align::Right => "Right",
        };
        write!(f, "{text}")
    }
}

/// Determines the alignment of a `CheckBox` or `OptionButton` control.
///
/// This enum is the 'Alignment' property in VB6 specifically for `CheckBox` and
/// `OptionButton` controls only.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa267261(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, TryFromPrimitive, Default, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum JustifyAlignment {
    /// The text is left-aligned. The control is right-aligned.
    ///
    /// This is the default setting.
    #[default]
    LeftJustify = 0,
    /// The text is right-aligned. The control is left-aligned.
    RightJustify = 1,
}

impl TryFrom<&str> for JustifyAlignment {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(JustifyAlignment::LeftJustify),
            "1" => Ok(JustifyAlignment::RightJustify),
            _ => Err(ErrorKind::Form(FormError::InvalidJustifyAlignment {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for JustifyAlignment {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        JustifyAlignment::try_from(s)
    }
}

impl Display for JustifyAlignment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            JustifyAlignment::LeftJustify => "Left Justify",
            JustifyAlignment::RightJustify => "Right Justify",
        };
        write!(f, "{text}")
    }
}

/// The `Alignment` property of a `Label` and `TextBox` control determines
/// the alignment of the text within the control. The `Alignment` property is used
/// to specify how the text is aligned within the control, such as left-aligned,
/// right-aligned, or centered.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa267261(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, TryFromPrimitive, Default, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum Alignment {
    /// The text is left-aligned within the control.
    ///
    /// This is the default setting.
    #[default]
    LeftJustify = 0,
    /// The text is right-aligned within the control.
    RightJustify = 1,
    /// The text is centered within the control.
    Center = 2,
}

impl TryFrom<&str> for Alignment {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Alignment::LeftJustify),
            "1" => Ok(Alignment::RightJustify),
            "2" => Ok(Alignment::Center),
            _ => Err(ErrorKind::Form(FormError::InvalidAlignment {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Alignment {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Alignment::try_from(s)
    }
}

impl Display for Alignment {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Alignment::LeftJustify => "LeftJustify",
            Alignment::RightJustify => "RightJustify",
            Alignment::Center => "Center",
        };
        write!(f, "{text}")
    }
}

/// Indicates whether a `Label` control or the background of a `Shape` control
/// is transparent or opaque.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245038(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum BackStyle {
    /// The transparent background color and any graphics are visible behind the
    /// control.
    Transparent = 0,
    /// The control's `BackColor` property setting fills the control and
    /// obscures any color or graphics behind it.
    ///
    /// This is the default setting.
    #[default]
    Opaque = 1,
}

impl TryFrom<&str> for BackStyle {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(BackStyle::Transparent),
            "1" => Ok(BackStyle::Opaque),
            _ => Err(ErrorKind::Form(FormError::InvalidBackStyle {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for BackStyle {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        BackStyle::try_from(s)
    }
}

impl Display for BackStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            BackStyle::Transparent => "Transparent",
            BackStyle::Opaque => "Opaque",
        };
        write!(f, "{text}")
    }
}

/// The `Appearance` determines whether or not a control is painted at run time
/// with 3D effects.
///
/// Note:
///
/// If set to `ThreeD` (1) at design time, the `Appearance` property draws
/// controls with three-dimensional effects. If the form's `BorderStyle`
/// property is set to `FixedDouble` (vbFixedDouble, or 3), the caption and
/// border of the form are also painted with three-dimensional effects.
///
/// Setting the `Appearance` property to `ThreeD` (1) also causes the form and its
/// controls to have their `BackColor` property set to the color selected for 3D
/// Objects in the `Appearance` tab of the operating system's Display Properties
/// dialog box.
///
/// Setting the `Appearance` property to `ThreeD` (1) for an `MDIForm` object
/// affects only the MDI parent form. To have three-dimensional effects on MDI
/// child forms, you must set each child form's `Appearance` property to
/// `ThreeD` (1).
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa244932(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, TryFromPrimitive, Default, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum Appearance {
    /// The control is painted with a flat style.
    Flat = 0,
    /// The control is painted with a 3D style.
    ///
    /// This is the default setting.
    #[default]
    ThreeD = 1,
}

impl TryFrom<&str> for Appearance {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Appearance::Flat),
            "1" => Ok(Appearance::ThreeD),
            _ => Err(ErrorKind::Form(FormError::InvalidAppearance {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Appearance {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Appearance::try_from(s)
    }
}

impl Display for Appearance {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Appearance::Flat => "Flat",
            Appearance::ThreeD => "ThreeD",
        };
        write!(f, "{text}")
    }
}

/// The `BorderStyle` determines the appearance of the border of a control.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa245047(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum BorderStyle {
    /// The control has no border.
    ///
    /// This is the default setting for `Image` and `Label` controls.
    None = 0,
    /// The control has a single-line border.
    ///
    /// This is the default setting for `PictureBox`, `TextBox`, `OLE` container
    /// controls.
    #[default]
    FixedSingle = 1,
}

impl TryFrom<&str> for BorderStyle {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(BorderStyle::None),
            "1" => Ok(BorderStyle::FixedSingle),
            _ => Err(ErrorKind::Form(FormError::InvalidBorderStyle {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for BorderStyle {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        BorderStyle::try_from(s)
    }
}

impl Display for BorderStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            BorderStyle::None => "None",
            BorderStyle::FixedSingle => "FixedSingle",
        };
        write!(f, "{text}")
    }
}

/// Determines the style of drag and drop operations.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum DragMode {
    /// The control does not support drag and drop operations until
    /// the program manually initiates the drag operation.
    ///
    /// This is the default setting.
    #[default]
    Manual = 0,
    /// The control automatically initiates a drag operation when the
    /// user presses the mouse button on the control.
    Automatic = 1,
}

impl TryFrom<&str> for DragMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(DragMode::Manual),
            "1" => Ok(DragMode::Automatic),
            _ => Err(ErrorKind::Form(FormError::InvalidDragMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for DragMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        DragMode::try_from(s)
    }
}

impl Display for DragMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            DragMode::Manual => "Manual",
            DragMode::Automatic => "Automatic",
        };
        write!(f, "{text}")
    }
}

/// Specifies how the pen (the color used in drawing) interacts with the
/// background.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum DrawMode {
    /// Black pen color is applied over the background.
    Blackness = 1,
    /// Inversion is applied after the combination of the pen and the background color.
    NotMergePen = 2,
    /// The combination of the colors common to the background color and the inverse of the pen.
    MaskNotPen = 3,
    /// Inversion is applied to the pen color.
    NotCopyPen = 4,
    /// The combination of the colors common to the pen and the inverse of the background color.
    MaskPenNot = 5,
    /// Inversion is applied to the background color.
    Invert = 6,
    /// The combination of the colors common to the pen and the background color, but not in both (ie, XOR).
    XorPen = 7,
    /// Inversion is applied to the combination of the colors common to both the pen and the background color.
    NotMaskPen = 8,
    /// The combination of the colors common to the pen and the background color.
    MaskPen = 9,
    /// Inversion of the combination of the colors in the pen and the background color but not in both (ie, NXOR).
    NotXorPen = 10,
    /// No operation is performed. The output remains unchanged. In effect, this turns drawing off (No Operation).
    Nop = 11,
    /// The combination of the display color and the inverse of the pen color.
    MergeNotPen = 12,
    /// The color specified by the `ForeColor` property is applied over the background.
    ///
    /// This is the default setting.
    #[default]
    CopyPen = 13,
    /// The combination of the pen color and inverse of the display color.
    MergePenNot = 14,
    /// the combination of the pen color and the display color.
    MergePen = 15,
    /// White pen color is applied over the background.
    Whiteness = 16,
}

impl TryFrom<&str> for DrawMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "1" => Ok(DrawMode::Blackness),
            "2" => Ok(DrawMode::NotMergePen),
            "3" => Ok(DrawMode::MaskNotPen),
            "4" => Ok(DrawMode::NotCopyPen),
            "5" => Ok(DrawMode::MaskPenNot),
            "6" => Ok(DrawMode::Invert),
            "7" => Ok(DrawMode::XorPen),
            "8" => Ok(DrawMode::NotMaskPen),
            "9" => Ok(DrawMode::MaskPen),
            "10" => Ok(DrawMode::NotXorPen),
            "11" => Ok(DrawMode::Nop),
            "12" => Ok(DrawMode::MergeNotPen),
            "13" => Ok(DrawMode::CopyPen),
            "14" => Ok(DrawMode::MergePenNot),
            "15" => Ok(DrawMode::MergePen),
            "16" => Ok(DrawMode::Whiteness),
            _ => Err(ErrorKind::Form(FormError::InvalidDrawMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for DrawMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        DrawMode::try_from(s)
    }
}

impl Display for DrawMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            DrawMode::Blackness => "Blackness",
            DrawMode::NotMergePen => "Not Merge Pen",
            DrawMode::MaskNotPen => "Mask Not Pen",
            DrawMode::NotCopyPen => "Not Copy Pen",
            DrawMode::MaskPenNot => "Mask Pen Not",
            DrawMode::Invert => "Invert",
            DrawMode::XorPen => "Xor Pen",
            DrawMode::NotMaskPen => "Not Mask Pen",
            DrawMode::MaskPen => "Mask Pen",
            DrawMode::NotXorPen => "Not Xor Pen",
            DrawMode::Nop => "Nop",
            DrawMode::MergeNotPen => "Merge Not Pen",
            DrawMode::CopyPen => "Copy Pen",
            DrawMode::MergePenNot => "Merge Pen Not",
            DrawMode::MergePen => "Merge Pen",
            DrawMode::Whiteness => "Whiteness",
        };
        write!(f, "{text}")
    }
}

/// Determines the line style of any drawing from any graphic method applied by the control.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum DrawStyle {
    /// A solid line.
    ///
    /// This is the default setting.
    #[default]
    Solid = 0,
    /// A dashed line.
    Dash = 1,
    /// A dotted line.
    Dot = 2,
    /// A line that alternates between dashes and dots.
    DashDot = 3,
    /// A line that alternates between dashes and double dots.
    DashDotDot = 4,
    /// Invisible line, transparent interior.
    Transparent = 5,
    /// Invisible line, solid interior.
    InsideSolid = 6,
}

impl TryFrom<&str> for DrawStyle {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(DrawStyle::Solid),
            "1" => Ok(DrawStyle::Dash),
            "2" => Ok(DrawStyle::Dot),
            "3" => Ok(DrawStyle::DashDot),
            "4" => Ok(DrawStyle::DashDotDot),
            "5" => Ok(DrawStyle::Transparent),
            "6" => Ok(DrawStyle::InsideSolid),
            _ => Err(ErrorKind::Form(FormError::InvalidDrawStyle {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for DrawStyle {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        DrawStyle::try_from(s)
    }
}

impl Display for DrawStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            DrawStyle::Solid => "Solid",
            DrawStyle::Dash => "Dash",
            DrawStyle::Dot => "Dot",
            DrawStyle::DashDot => "DashDot",
            DrawStyle::DashDotDot => "DashDotDot",
            DrawStyle::Transparent => "Transparent",
            DrawStyle::InsideSolid => "InsideSolid",
        };
        write!(f, "{text}")
    }
}

/// Determines the appearance of the mouse pointer when it is over the control.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum MousePointer {
    /// Standard pointer. The image is determined by the hovered over object.
    ///
    /// This is the default setting.
    #[default]
    Default = 0,
    /// Arrow pointer.
    Arrow = 1,
    /// Cross-hair pointer.
    Cross = 2,
    /// I-beam pointer.
    IBeam = 3,
    /// Icon pointer. The image is determined by the `MouseIcon` property.
    /// If the `MouseIcon` property is not set, the behavior is the same as the Default setting.
    /// This is a duplicate of Custom (99).
    Icon = 4,
    /// Size all cursor (arrows pointing north, south, east, and west).
    /// This cursor is used to indicate that the control can be resized in any direction.
    Size = 5,
    /// Double arrow pointing northeast and southwest.
    SizeNESW = 6,
    /// Double arrow pointing north and south.
    SizeNS = 7,
    /// Double arrow pointing northwest and southeast.
    SizeNWSE = 8,
    /// Double arrow pointing west and east.
    SizeWE = 9,
    /// Up arrow.
    UpArrow = 10,
    /// Hourglass or wait cursor.
    Hourglass = 11,
    /// "Not" symbol (circle with a diagonal line) on top of the object being dragged.
    /// Indicates an invalid drop target.
    NoDrop = 12,
    /// Arrow with an hourglass.
    ArrowHourglass = 13,
    /// Arrow with a question mark.
    ArrowQuestion = 14,
    /// Size all cursor (arrows pointing north, south, east, and west).
    /// This cursor is used to indicate that the control can be resized in any direction.
    /// Duplicate of Size (5).
    SizeAll = 15,
    /// Uses the icon specified by the `MouseIcon` property.
    /// If the `MouseIcon` property is not set, the behavior is the same as the Default setting.
    /// This is a duplicate of Icon (4).
    Custom = 99,
}

impl TryFrom<&str> for MousePointer {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(MousePointer::Default),
            "1" => Ok(MousePointer::Arrow),
            "2" => Ok(MousePointer::Cross),
            "3" => Ok(MousePointer::IBeam),
            "4" => Ok(MousePointer::Icon),
            "5" => Ok(MousePointer::Size),
            "6" => Ok(MousePointer::SizeNESW),
            "7" => Ok(MousePointer::SizeNS),
            "8" => Ok(MousePointer::SizeNWSE),
            "9" => Ok(MousePointer::SizeWE),
            "10" => Ok(MousePointer::UpArrow),
            "11" => Ok(MousePointer::Hourglass),
            "12" => Ok(MousePointer::NoDrop),
            "13" => Ok(MousePointer::ArrowHourglass),
            "14" => Ok(MousePointer::ArrowQuestion),
            "15" => Ok(MousePointer::SizeAll),
            "99" => Ok(MousePointer::Custom),
            _ => Err(ErrorKind::Form(FormError::InvalidMousePointer {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for MousePointer {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        MousePointer::try_from(s)
    }
}

impl Display for MousePointer {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            MousePointer::Default => "Default",
            MousePointer::Arrow => "Arrow",
            MousePointer::Cross => "Cross",
            MousePointer::IBeam => "IBeam",
            MousePointer::Icon => "Icon",
            MousePointer::Size => "Size",
            MousePointer::SizeNESW => "SizeNESW",
            MousePointer::SizeNS => "SizeNS",
            MousePointer::SizeNWSE => "SizeNWSE",
            MousePointer::SizeWE => "SizeWE",
            MousePointer::UpArrow => "UpArrow",
            MousePointer::Hourglass => "Hourglass",
            MousePointer::NoDrop => "NoDrop",
            MousePointer::ArrowHourglass => "ArrowHourglass",
            MousePointer::ArrowQuestion => "ArrowQuestion",
            MousePointer::SizeAll => "SizeAll",
            MousePointer::Custom => "Custom",
        };
        write!(f, "{text}")
    }
}

/// Determines the style of drag and drop operations.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum OLEDragMode {
    /// The programmer handles all OLE drag/drop events manually.
    ///
    /// This is the default setting.
    #[default]
    Manual = 0,
    /// The control automatically handles all OLE drag/drop events.
    Automatic = 1,
}

impl TryFrom<&str> for OLEDragMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(OLEDragMode::Manual),
            "1" => Ok(OLEDragMode::Automatic),
            _ => Err(ErrorKind::Form(FormError::InvalidOLEDragMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for OLEDragMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        OLEDragMode::try_from(s)
    }
}

impl Display for OLEDragMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            OLEDragMode::Manual => "Manual",
            OLEDragMode::Automatic => "Automatic",
        };
        write!(f, "{text}")
    }
}

/// Determines the style of drop operations.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum OLEDropMode {
    /// The control does not accept any OLE drop operations.
    ///
    /// This is the default setting.
    #[default]
    None = 0,
    /// The programmer handles all OLE drop events manually.
    Manual = 1,
}

impl TryFrom<&str> for OLEDropMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(OLEDropMode::None),
            "1" => Ok(OLEDropMode::Manual),
            _ => Err(ErrorKind::Form(FormError::InvalidOLEDropMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for OLEDropMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        OLEDropMode::try_from(s)
    }
}

impl Display for OLEDropMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            OLEDropMode::None => "None",
            OLEDropMode::Manual => "Manual",
        };
        write!(f, "{text}")
    }
}

/// Determines if the control is clipped to the bounds of the parent control.
/// This is used with the `Form` and `MDIForm` controls.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum ClipControls {
    /// The controls are not clipped to the bounds of the parent control.
    Unbounded = 0,
    /// The controls are clipped to the bounds of the parent control.
    ///
    /// This is the default setting.
    #[default]
    Clipped = 1,
}

impl TryFrom<&str> for ClipControls {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(ClipControls::Unbounded),
            "1" => Ok(ClipControls::Clipped),
            _ => Err(ErrorKind::Form(FormError::InvalidClipControls {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for ClipControls {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        ClipControls::try_from(s)
    }
}

impl Display for ClipControls {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            ClipControls::Unbounded => "Unbounded",
            ClipControls::Clipped => "Clipped",
        };
        write!(f, "{text}")
    }
}

/// Determines if the control uses standard styling or if it uses graphical styling from it's
/// picture properties.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum Style {
    /// The control uses standard styling.
    ///
    /// This is the default setting.
    #[default]
    Standard = 0,
    /// The control uses graphical styling using its appropriate picture properties.
    Graphical = 1,
}

impl TryFrom<&str> for Style {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(Style::Standard),
            "1" => Ok(Style::Graphical),
            _ => Err(ErrorKind::Form(FormError::InvalidStyle {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for Style {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Style::try_from(s)
    }
}

impl Display for Style {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            Style::Standard => "Standard",
            Style::Graphical => "Graphical",
        };
        write!(f, "{text}")
    }
}

/// Determines the fill style of the control for drawing purposes.
/// This is used with the `Form` and `PictureBox` controls.
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum FillStyle {
    /// The background is filled with a solid color.
    Solid = 0,
    /// The background is not filled.
    ///
    /// This is the default setting.
    #[default]
    Transparent = 1,
    /// The background is filled with a horizontal line pattern.
    HorizontalLine = 2,
    /// The background is filled with a vertical line pattern.
    VerticalLine = 3,
    /// The background is filled with a diagonal line pattern.
    UpwardDiagonal = 4,
    /// The background is filled with a diagonal line pattern that goes from the bottom left to the top right.
    /// This is the same as `UpwardDiagonal` but rotated 90 degrees.
    DownwardDiagonal = 5,
    /// The background is filled with a cross-hatch pattern.
    Cross = 6,
    /// The background is filled with a diagonal cross-hatch pattern.
    /// This is the same as `Cross` but rotated 45 degrees.
    DiagonalCross = 7,
}

impl TryFrom<&str> for FillStyle {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(FillStyle::Solid),
            "1" => Ok(FillStyle::Transparent),
            "2" => Ok(FillStyle::HorizontalLine),
            "3" => Ok(FillStyle::VerticalLine),
            "4" => Ok(FillStyle::UpwardDiagonal),
            "5" => Ok(FillStyle::DownwardDiagonal),
            "6" => Ok(FillStyle::Cross),
            "7" => Ok(FillStyle::DiagonalCross),
            _ => Err(ErrorKind::Form(FormError::InvalidFillStyle {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for FillStyle {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        FillStyle::try_from(s)
    }
}

impl Display for FillStyle {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            FillStyle::Solid => "Solid",
            FillStyle::Transparent => "Transparent",
            FillStyle::HorizontalLine => "HorizontalLine",
            FillStyle::VerticalLine => "VerticalLine",
            FillStyle::UpwardDiagonal => "UpwardDiagonal",
            FillStyle::DownwardDiagonal => "DownwardDiagonal",
            FillStyle::Cross => "Cross",
            FillStyle::DiagonalCross => "DiagonalCross",
        };
        write!(f, "{text}")
    }
}

/// Determines the link mode of a control for DDE conversations.
/// This is used with the `Form` control.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa235154(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, TryFromPrimitive, Default, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum LinkMode {
    /// No DDE interaction. No destination application can initiate a conversation
    /// with the source control as the topic, and no application can poke data to
    /// the control.
    #[default]
    None = 0,
    /// Allows any `Label`, `PictureBox`, or `TextBox` control on a form to supply
    /// data to any destination application that establishes a DDE conversation
    /// with the control. If such a link exists, Visual Basic automatically
    /// notifies the destination whenever the contents of a control are changed.
    /// In addition, a destination application can poke data to any `Label`,
    /// `PictureBox`, or `TextBox` control on the form.
    Automatic = 1,
    /// Allows any `Label`, `PictureBox`, or `TextBox` control on a form to supply
    /// data to any destination application that establishes a DDE conversation
    /// with the control. However, Visual Basic does not automatically notify
    /// the destination whenever the contents of a control are changed. In
    /// addition, a destination application can poke data to any `Label`,
    /// `PictureBox`, or `TextBox` control on the form.
    Manual = 2,
    /// Allows any `Label`, `PictureBox`, or `TextBox` control on a form to supply
    /// data to any destination application that establishes a DDE conversation
    /// with the control. Visual Basic automatically notifies the destination
    /// whenever the contents of a control are changed. However, a destination
    /// application cannot poke data to any `Label`, `PictureBox`, or `TextBox`
    /// control on the form.
    Notify = 3,
}

impl TryFrom<&str> for LinkMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(LinkMode::None),
            "1" => Ok(LinkMode::Automatic),
            "2" => Ok(LinkMode::Manual),
            "3" => Ok(LinkMode::Notify),
            _ => Err(ErrorKind::Form(FormError::InvalidLinkMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for LinkMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        LinkMode::try_from(s)
    }
}

impl Display for LinkMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            LinkMode::None => "None",
            LinkMode::Automatic => "Automatic",
            LinkMode::Manual => "Manual",
            LinkMode::Notify => "Notify",
        };
        write!(f, "{text}")
    }
}

/// Determines the multi-select behavior of a `ListBox` control.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa235198(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum MultiSelect {
    /// The user cannot select more than one item in the list box.
    #[default]
    None = 0,
    /// The user can select multiple items in the list box by holding down the
    /// `SHIFT` key while clicking items.
    Simple = 1,
    /// The user can select multiple items in the list box by holding down the
    /// `CTRL` key while clicking items.
    Extended = 2,
}

impl TryFrom<&str> for MultiSelect {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(MultiSelect::None),
            "1" => Ok(MultiSelect::Simple),
            "2" => Ok(MultiSelect::Extended),
            _ => Err(ErrorKind::Form(FormError::InvalidMultiSelect {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for MultiSelect {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        MultiSelect::try_from(s)
    }
}

impl Display for MultiSelect {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            MultiSelect::None => "None",
            MultiSelect::Simple => "Simple",
            MultiSelect::Extended => "Extended",
        };
        write!(f, "{text}")
    }
}

/// Determines the scale mode of the control for sizing and positioning.
/// This is used with the `Form` and `PictureBox` controls.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445668(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum ScaleMode {
    /// Indicates that one or more of the `ScaleHeight`, `ScaleWidth`, `ScaleLeft`, and `ScaleTop` properties are set to custom values.
    User = 0,
    /// The control uses twips as the unit of measurement. (1440 twips per logical inch; 567 twips per logical centimeter).
    #[default]
    Twip = 1,
    /// The control uses Points as the unit of measurement. (72 points per logical inch).
    Point = 2,
    /// The control uses Pixels as the unit of measurement. (The number of pixels per logical inch depends on the system's display settings).
    Pixel = 3,
    /// The control uses Characters as the unit of measurement. Character (horizontal = 120 twips per unit; vertical = 240 twips per unit).
    Character = 4,
    /// The control uses Inches as the unit of measurement.
    Inches = 5,
    /// The control uses Millimeters as the unit of measurement.
    Millimeter = 6,
    /// The control uses Centimeters as the unit of measurement.
    Centimeter = 7,
    /// The control uses `HiMetrics` as the unit of measurement.
    HiMetric = 8,
    /// The control uses the Units used by the control's container to determine the control's position.
    ContainerPosition = 9,
    /// The control uses the Units used by the control's container to determine the control's size.
    ContainerSize = 10,
}

impl FromStr for ScaleMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        ScaleMode::try_from(s)
    }
}

impl TryFrom<&str> for ScaleMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(ScaleMode::User),
            "1" => Ok(ScaleMode::Twip),
            "2" => Ok(ScaleMode::Point),
            "3" => Ok(ScaleMode::Pixel),
            "4" => Ok(ScaleMode::Character),
            "5" => Ok(ScaleMode::Inches),
            "6" => Ok(ScaleMode::Millimeter),
            "7" => Ok(ScaleMode::Centimeter),
            "8" => Ok(ScaleMode::HiMetric),
            "9" => Ok(ScaleMode::ContainerPosition),
            "10" => Ok(ScaleMode::ContainerSize),
            _ => Err(ErrorKind::Form(FormError::InvalidScaleMode {
                value: value.to_string(),
            })),
        }
    }
}

impl Display for ScaleMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            ScaleMode::User => "User",
            ScaleMode::Twip => "Twip",
            ScaleMode::Point => "Point",
            ScaleMode::Pixel => "Pixel",
            ScaleMode::Character => "Character",
            ScaleMode::Inches => "Inches",
            ScaleMode::Millimeter => "Millimeter",
            ScaleMode::Centimeter => "Centimeter",
            ScaleMode::HiMetric => "HiMetric",
            ScaleMode::ContainerPosition => "ContainerPosition",
            ScaleMode::ContainerSize => "ContainerSize",
        };
        write!(f, "{text}")
    }
}

/// Determines how the control sizes the picture within its bounds.
/// This is used with the `Image` and `PictureBox` controls.
///
/// [Reference](https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445695(v=vs.60))
#[derive(
    Debug, PartialEq, Eq, Clone, Serialize, Default, TryFromPrimitive, Copy, Hash, PartialOrd, Ord,
)]
#[repr(i32)]
pub enum SizeMode {
    /// The picture is displayed in its original size. If the picture is larger than
    /// the control, the picture is clipped to fit within the control's bounds.
    ///
    /// If the picture is smaller than the control, the picture is displayed in the
    /// top-left corner of the control, and the remaining area of the control is
    /// left blank.
    #[default]
    Clip = 0,
    /// The picture is stretched or shrunk to fit the control's bounds.
    Stretch = 1,
    /// The control is automatically resized to fit the picture.
    AutoSize = 2,
    /// The picture is stretched or shrunk to fit the control's bounds while maintaining its aspect ratio.
    Zoom = 3,
}

impl TryFrom<&str> for SizeMode {
    type Error = ErrorKind;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        match value {
            "0" => Ok(SizeMode::Clip),
            "1" => Ok(SizeMode::Stretch),
            "2" => Ok(SizeMode::AutoSize),
            "3" => Ok(SizeMode::Zoom),
            _ => Err(ErrorKind::Form(FormError::InvalidSizeMode {
                value: value.to_string(),
            })),
        }
    }
}

impl FromStr for SizeMode {
    type Err = ErrorKind;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        SizeMode::try_from(s)
    }
}

impl Display for SizeMode {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let text = match self {
            SizeMode::Clip => "Clip",
            SizeMode::Stretch => "Stretch",
            SizeMode::AutoSize => "AutoSize",
            SizeMode::Zoom => "Zoom",
        };
        write!(f, "{text}")
    }
}