File: VirtualControls.pas

package info (click to toggle)
mysql-query-browser 1.1.6-1sarge0
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 36,320 kB
  • ctags: 24,680
  • sloc: pascal: 203,479; xml: 136,561; ansic: 47,502; cpp: 28,926; sh: 12,433; objc: 4,823; java: 1,849; php: 1,485; python: 1,225; sql: 1,128; makefile: 872
file content (5130 lines) | stat: -rw-r--r-- 153,638 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
unit VirtualControls;

//----------------------------------------------------------------------------------------------------------------------
//
// Copyright  1995-2001 digital publishing AG
//
//----------------------------------------------------------------------------------------------------------------------
//
// Description:
//   This unit implements extented controls which can hold a virtually unlimited number of entries. These controls do
//   not keep their items internally but query the application whenever necessary.
//
//----------------------------------------------------------------------------------------------------------------------
//
// 09-JAN-2002 fe:
//   - vcoMultiSelection is now really check support
//   - various missing properties now published
//   - TBaseVirtualComboBox.WMNCHitTest was completely wrong (position is in screen coords!)
// 07-DEC-2001 ml:
//   - combobox selection rect fills now entire client area if nothing is selected
// 16-NOV-2001 fe:
//   - WMSizing handler added for popup tree to set cbsResizedOnce instead of DroppedDown
// 06-NOV-2001 ml:
//   - change propagation from popup tree to owner
//   - change handling more compliant to standard combobox
//   - bug fixes
// 05-NOV-2001 ml:
//   - images in list mode
//   - fixed size grip painting in tree popup
//   - minimum size constraint removed (handled by GetDropDownRect)
//   - nc painting improved
// 02-NOV-2001 ml:
//   - painting at design time
// 31-OCT-2001 ml:
//   - correct button hit test (combobox)
//   - ESC handling for combobox
//   - bug fixes
// 29-OCT-2001 ml:
//   - combobox painting (also themed)
//   - combobox sizing
//   - hover/leave for themed combobox window
// 24-OCT-2001 ml:
//   - cleaning up
// 14-SEP-2001 ml:
//   - add JclSysInfo unit to access windows versions
//   - small changes due to renamed event
// 05-SEP-2001 ml:
//   - bug fixes
// 24-AUG-2001 ml:
//   - Delphi 6 compatibility
// 13..14-AUG-2001 ml:
//   - resizing of tree pop up in the combobox with single line border
// 20-JUN-20001 fe:
//   - changes in TBaseVirtualComboBox.CreateParams to avoid doubled border (WS_EX_CLIENTEDGE or WS_BORDER, not both!)
//   - minor changes to DrawEdge parameters to be compatible with regular combo box
//   - SetFocus call on WM_NCLBUTTONDOWN or WM_LBUTTONDOWN
// 02-MAY-2001 ml:
//   - published NodeDataSize, FocusedNode for TreePopup
// 27-APR-2001 ml:
//   - CM_MOUSEBUTTONDOWN in combo box
// 26-APR-2001 ml:
//   - redraw of loosing focus for combo box
// 25-APR-2001 ml:
//   - popup window size fix
//   - initial popup tree visibility fix
// 18-APR-2001 ml:
//   - took further measures to ensure tree popup's initial invisibility
// 02-APR-2001 ml:
//   - tree combo non-client painting
//   - tree combo restructuring (looks now like a normal combo box)
// 30-MAR-2001 ml:
//   - published some more properties and events for the tree combo box
// 06-MAR-2001 ml:
//   - removed NC painting for the Virtual Listbox
//   - bug fixes
// 28-FEB-2001 ml:
//   - popup window handling
//   - key forwarding
//   - intl chars handling
//   - bug fixes
// 23-FEB-2001 ml:
//   - auto update
//   - auto selection
//   - edit handling
//   - bug fixes
// 21..22-FEB-2001 ml:
//   - popup window handling
//   - MultiSelection
//   - base painting and parsing
//   - bu fixes
// 20-FEB-2001 ml:
//   - made the popup treeview visible in object inspector and persistent for direct design time manipulations
//   - wide editor control is used now
//   - bug fixes
// 19-FEB-2001 ml:
//   - removed old virtual combo box because the tree combo box will now take this part
//   - bug fixes
//   - clean up work
// 05-FEB-2001 ml:
//   - adjusted more properties to fit to the changed VT types and properties
//   - bug fixes
// SEP-2000 through JAN-2001
//   - preparation work for tree combo box (base class and handling)
//   - bug fixes
// AUG-98 through OCT-99
//   - TCustomVirtualTreeComboBox and TVirtualTreeComboBox introduction
//   - mouse wheel support for all controls
//   - TVirtualComboBox (general)
//   - TVirtualListBox (general, item cache)
//   - initial version
//----------------------------------------------------------------------------------------------------------------------

interface

uses
  Windows, Graphics, Classes, Controls, ImgList, Messages, StdCtrls, Forms, ExtCtrls, VirtualTrees, EditorW2,
  DPMessages,                                                               
  JwaUxTheme, JwaTmSchema;

type
  TCustomVirtualListBox = class;

  TVirtualListBoxStyle = (
    vlbStandard,
    vlbOwnerDraw
  );

  TDefaultScrollBarMode = (
    sbmRegular,
    sbmFlat,
    sbm3D
  );

  TVLBChangeEvent = procedure(Sender: TObject; Index: Integer; ItemSelected: Boolean) of object;
  TVLBDrawItemEvent = procedure(Sender: TObject; Canvas: TCanvas; Index: Integer; Rect: TRect; Selected,
    Focused: Boolean) of object;
  TVirtualGetItemEvent = procedure(Sender: TObject; Index: Integer; var Text: WideString) of object;
  TVirtualGetImageEvent = procedure(Sender: TObject; Index: Integer; var ImageIndex: Integer) of object;
  TVirtualCompareEvent = procedure(Sender: TObject; Text1, Text2: WideString; var Result: Integer) of object;

  TCustomVirtualListBox = class(TCustomControl)
  private
    FScrollBar: TScrollBar;
    FUseExternScrollBar: Boolean;
    FItemHeight: Integer;
    FItemWidth: Integer;                // Width / Width-ScrollBar.Left
    FLinesInWindow: Integer;            // Set: ItemHeight, SetBounds
    FAutoScroll: Boolean;               // False fr Bitmap-Hintergrund
    FStyle: TVirtualListBoxStyle;
    FIntegralHeight: Boolean;
    FMultiSelect: Boolean;
    FExtendedSelect: Boolean;
    FExtSelectionAnchor,
    FTopIndex: Integer;
    FItemIndex: Integer;
    FItemCount: Integer;
    FSelCount: Integer;
    FSelection: Pointer;
    FEraseBkGnd: Boolean;
    FDefaultScrollBarMode: TDefaultScrollBarMode;
    FScrollBarWidth: Integer;
    FScrollFactor: Single;
    FImages: TImageList;
    FScrollTimer: TTimer;
    FChangeTimer: TTimer;
    FLastChangedIndex: Integer;
    FLastChangedItemSelected: Boolean;
    FCacheIndex: Integer;
    FCache: TStringList;
    FBorderStyle: TBorderStyle;
    FFreezeScroll: Boolean;
    FChangeDelay: Integer;              // use to delay OnChange event

    FOnChange: TVLBChangeEvent;
    FOnDrawItem: TVLBDrawItemEvent;
    FOnGetItem: TVirtualGetItemEvent;
    FOnGetImage: TVirtualGetImageEvent;
    FOnCompare: TVirtualCompareEvent;
    procedure CMFontChanged(var Msg: TMessage); message CM_FONTCHANGED;
    procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL;
    procedure CNKeyDown(var Msg: TWMKey); message CN_KEYDOWN;
    function GetSelected(Index: Integer): Boolean;
    procedure SetBorderStyle(Value: TBorderStyle);
    procedure SetCustomScrollBar(Value: TScrollbar);
    procedure SetDefaultScrollBarMode(Value: TDefaultScrollBarMode);
    procedure SetImages(Value: TImageList);
    procedure SetIntegralHeight(Value: Boolean);
    procedure SetItemCount(Value: Integer);
    procedure SetItemHeight(Value: Integer);
    procedure SetItemIndex(Value: Integer);
    procedure SetMultiSelect(Value: Boolean);
    procedure SetSelected(Index: Integer; Value: Boolean);
    procedure SetStyle(Value: TVirtualListBoxStyle);
    procedure SetTopIndex(Value: Integer);
    procedure SetScrollBar;
    procedure SetScrollBarWidth(Value: Integer);
    procedure WMEraseBkgnd(var Msg: TWMEraseBkgnd); message WM_ERASEBKGND;
    procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS;
    procedure WMLButtonDown(var Msg: TWMLButtonDown); message WM_LBUTTONDOWN;
    procedure WMLButtonUp(var Msg: TWMLButtonUp); message WM_LBUTTONUP;
    procedure WMMouseMove(var Msg: TWMMouseMove); message WM_MOUSEMOVE;
    procedure WMVScroll(var Msg: TWMVScroll); message WM_VSCROLL;
    procedure WMSetFocus(var Msg: TWMSetFocus); message WM_SETFOCUS;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
  protected
    procedure ClearSelection;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure CreateWnd; override;
    procedure DoChange(Index: Integer; ItemSelected: Boolean);
    procedure FillCache(NeededIndex: Integer); virtual;
    function GetItem(Index: Integer): WideString;
    procedure InvalidateBox(All: Boolean);
    procedure InvalidateItem(Index: Integer);
    procedure InvalidateToBottom(Index: Integer);
    procedure MoveSelects(StartIndex, Direction: Integer);
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure OnScrollTimer(Sender: TObject);
    procedure OnChangeTimer(Sender: TObject);
    procedure ScrollBarChange(Sender: TObject);
    procedure ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);
    procedure SelectItem(Index: Integer; Value: Boolean);
    procedure SelectRange(Start, Stop: Integer);
    procedure ToggleItem(Index: Integer);

    // scroll bar handling
    function GetScrollBarPosition: Integer;
    procedure SetScrollBarMin(Value: Integer);
    procedure SetScrollBarMax(Value: Integer);
    procedure SetScrollBarPosition(Value: Integer);
    procedure SetScrollBarLargeChange(Value: Integer);
    procedure SetScrollBarSmallChange(Value: Integer);

    procedure Paint; override;

    property AutoScroll: Boolean read FAutoScroll write FAutoScroll default True;
    property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsNone;
    property ChangeDelay: Integer read FChangeDelay write FChangeDelay;
    property DefaultScrollBarMode: TDefaultScrollBarMode read FDefaultScrollBarMode write SetDefaultScrollBarMode
      default sbmRegular;
    property ExtendedSelect: Boolean read FExtendedSelect write FExtendedSelect default True;
    property EraseBkGnd: Boolean read FEraseBkGnd write FEraseBkGnd default True;
    property Images: TImageList read FImages write SetImages;
    property IntegralHeight: Boolean read FIntegralHeight write SetIntegralHeight default False;
    property ItemCount: Integer read FItemCount write SetItemCount default 0;
    property ItemHeight: Integer read FItemHeight write SetItemHeight default 16;
    property ItemIndex: Integer read FItemIndex write SetItemIndex default -1;
    property MultiSelect: Boolean read FMultiSelect write SetMultiSelect default False;
    property ParentColor default False;
    property ScrollBarWidth: Integer read FScrollBarWidth write SetScrollBarWidth default 13;
    property Style: TVirtualListBoxStyle read FStyle write SetStyle default vlbStandard;

    property OnChange: TVLBChangeEvent read FOnChange write FOnChange;
    property OnCompare: TVirtualCompareEvent read FOnCompare write FOnCompare;
    property OnDrawItem: TVLBDrawItemEvent read FOnDrawItem write FOnDrawItem;
    property OnGetImage: TVirtualGetImageEvent read FOnGetImage write FOnGetImage;
    property OnGetItem: TVirtualGetItemEvent read FOngetItem write FOnGetItem;
  public
    constructor Create(AOwner: TComponent); overload; override;
    constructor Create(AOwner: TComponent; AsPopup: Boolean = False); reintroduce; overload;
    destructor Destroy; override;

    procedure Clear;
    function Find(Text: WideString): Boolean;
    procedure InvalidateCache;
    function ItemAtPos(Pos: TSmallPoint; Existing: Boolean): Integer;
    function ItemRect(Index: Integer): TRect;
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    procedure WndProc(var Message: TMessage); override;

    property FreezeScroll: Boolean read FFreezeScroll write FFreezeScroll;
    property TopIndex: Integer read FTopIndex write SetTopIndex;
    property CustomScrollBar: TScrollBar read FScrollBar write SetCustomScrollBar;
    property Items[Index: Integer]: WideString read GetItem; default;
    property SelectedCount: Integer read FSelCount;
    property Selected[Index: Integer]: Boolean read GetSelected write SetSelected;
  end;

  TVirtualListBox = class(TCustomVirtualListBox)
  published
    property Align;
    property Anchors;
    property AutoScroll;
    property BevelEdges;
    property BevelInner;
    property BevelOuter;
    property BevelKind;
    property BevelWidth;
    property BorderStyle;
    property Color;
    property Constraints;
    property DefaultScrollBarMode;
    property DragCursor;
    property DragMode;
    property Enabled;
    property EraseBkGnd;
    property ExtendedSelect;
    property Font;
    property Images;
    property IntegralHeight;
    property ItemCount;
    property ItemHeight;
    property ItemIndex;
    property MultiSelect;
    property ParentColor default False;
    property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property ScrollBarWidth;
    property ShowHint;
    property Style;
    property TabOrder;
    property TabStop default True;
    property Visible;
    property ChangeDelay;

    property OnChange;
    property OnClick;
    property OnCompare;
    property OnDblClick;
    property OnDragDrop;
    property OnDragOver;
    property OnDrawItem;
    property OnEndDrag;
    property OnEnter;
    property OnExit;
    property OnGetImage;
    property OnGetItem;
    property OnKeyDown;
    property OnKeyPress;
    property OnKeyUp;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnResize;
  end;

  TVirtualComboboxOption = (
    vcoAutoSelect,     // Changes in the edit are directly reflected in the tree.
    vcoAutoUpdate,     // Update text property for every selection/check change in the treeview.
    vcoHotTrack,       // Selection in popup tree follows the mouse pointer.
    vcoMultiSelection  // Allows several items to be selected (actually check boxes are used).
  );
  TVirtualComboboxOptions = set of TVirtualComboboxOption;

const
  DefaultVirtualComboBoxOptions = [];

type
  TBaseVirtualCombobox = class;
  TCustomVirtualTreeComboBox = class;
  
  TWideVCBEdit = class(TWideEditorControl)
  private
    procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL;
    procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
    
    procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
    procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
    procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
    procedure WMSysKeyDown(var Message: TWMSysKeydown); message WM_SYSKEYDOWN;
    procedure CMWantSpecialKey(var Msg: TCMWantSpecialKey); message CM_WANTSPECIALKEY;
  protected
    procedure DoChange; override;
  end;

  TVirtualComboboxStyle = (
    vcsDropDown,
    vcsDropDownList
  );

  TVirtualComboboxState = (
    cbsAutoSelecting,
    cbsCreating,
    cbsDroppedDown,
    cbsResizedOnce,
    cbsModified
  );
  TVirtualComboboxStates = set of TVirtualComboboxState;

  // State of the combo box button depending on enabled state of the control the mouse state.
  TVCButtonState = (
    vbsNormal,
    vbsHot,
    vbsPressed,
    vbsDisabled
  );

  TEditDoubleClickEvent = procedure(Sender: TBaseVirtualCombobox; Shift: TShiftState; Pos: TPoint) of object;

  TBaseVirtualComboBox = class(TCustomControl)
  private
    FOptions: TVirtualComboboxOptions;
    FEditWindow: TWideVCBEdit;
    FMaxLength: Integer;
    FStyle: TVirtualComboboxStyle;
    FStates: TVirtualComboboxStates;
    FButtonState: TVCButtonState;
    FText,                             // normal combobox text
    FIntlChars: WideString;
    FTextHeight: Integer;
    FAlignment: TAlignment;
    FLayout: TTextLayout;
    FBorderStyle: TBorderStyle;
    FDropDownCount: Cardinal;
    FComboTheme,
    FEditTheme: HTHEME;
    FAnimationDuration: Cardinal;                // specifies how long an animation shall take (drop down)

    FOnChange: TNotifyEvent;
    FOnDropDown: TNotifyEvent;
    FOnEditDoubleClick: TEditDoubleClickEvent;
    procedure CloseThemes;
    procedure EndAutoSelecting;
    function GetAutoSelecting: Boolean;
    function GetDroppedDown: Boolean;
    function GetModified: Boolean;
    procedure ReadIntlChars(Reader: TReader);
    procedure ReadText(Reader: TReader);
    procedure SetAlignment(const Value: TAlignment);
    procedure SetAnimationDuration(const Value: Cardinal);
    procedure SetBorderStyle(const Value: TBorderStyle);
    procedure SetDroppedDown(Value: Boolean);
    procedure SetIntlChars(const Value: WideString);
    procedure SetLayout(const Value: TTextLayout);
    procedure SetModified(Value: Boolean);
    procedure SetOptions(Value: TVirtualComboboxOptions);
    procedure SetSelText(const Value: WideString);
    procedure SetStyle(Value: TVirtualComboboxStyle);
    procedure StartAutoSelecting;
    procedure WriteIntlChars(Writer: TWriter);
    procedure WriteText(Writer: TWriter);

    procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
    procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
    procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
    procedure WMKeyUp(var Message: TWMKeyUp); message WM_KEYUP;
    procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
    procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
    procedure WMMouseLeave(var Message: TMessage); message WM_MOUSELEAVE;
    procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
    procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE;
    procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure WMNCLButtonDblClk(var Message: TWMNCLButtonDblClk); message WM_NCLBUTTONDBLCLK;
    procedure WMNCLButtonDown(var Message: TWMNCLButtonDown); message WM_NCLBUTTONDOWN;
    procedure WMNCMouseLeave(var Message: TMessage); message WM_NCMOUSELEAVE;
    procedure WMNCMouseMove(var Message: TWMNCMouseMove); message WM_NCMOUSEMOVE;
    procedure WMNCPaint(var Message: TRealWMNCPaint); message WM_NCPAINT;
    procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
    procedure WMSetFont(var Message: TWMSetFont); message WM_SETFONT;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
    procedure WMThemeChanged(var Message: TMessage); message WM_THEMECHANGED;
  protected
    procedure Changed; virtual;
    procedure CreateParams(var Params: TCreateParams); override;
    procedure CreateWnd; override;
    procedure DefineProperties(Filer: TFiler); override;
    procedure DestroyWnd; override;
    procedure DoSetDroppedDown(Value: Boolean); virtual;
    function Editable: Boolean; virtual;
    procedure EditDoubleClick(var Message: TWMLButtonDblClk);
    function FindItem(const ItemText: WideString): Boolean; virtual;
    function GetPopupWindow: HWND; virtual;
    function GetSelLength: Integer; virtual;
    function GetSelStart: Integer; virtual;
    function GetSelText: WideString; virtual;
    function GetTextRect: TRect; virtual;
    procedure OptionsChanged; virtual;
    procedure RegisterLeaveEvent(IsClientArea: Boolean);
    procedure RepaintWindow(R: PRect = nil);
    procedure SetSelLength(Value: Integer); virtual;
    procedure SetSelStart(Value: Integer); virtual;
    procedure SetText(const Value: WideString); virtual;
    procedure WndProc(var Message: TMessage); override;

    property Alignment: TAlignment read FAlignment write SetAlignment default taLeftJustify;
    property AnimationDuration: Cardinal read FAnimationDuration write SetAnimationDuration default 200;
    property AutoSelecting: Boolean read GetAutoSelecting;
    property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
    property Color default clWindow;
    property DropDownCount: Cardinal read FDropDownCount write FDropDownCount default 8;
    property DroppedDown: Boolean read GetDroppedDown write SetDroppedDown;
    property InternationalCharacters: WideString read FIntlChars write SetIntlChars stored False;
    property Layout: TTextLayout read FLayout write SetLayout default tlTop;
    property Modified: Boolean read GetModified write SetModified;
    property Options: TVirtualComboboxOptions read FOptions write SetOptions default DefaultVirtualComboBoxOptions;
    property ParentColor default False;
    property Style: TVirtualComboboxStyle read FStyle write SetStyle default vcsDropDown;
    property Text: WideString read FText write SetText stored False; // We use own storage methods.

    property OnChange: TNotifyEvent read FOnChange write FOnChange;
    property OnDropDown: TNotifyEvent read FOnDropDown write FOnDropDown;
    property OnEditDoubleClick: TEditDoubleClickEvent read FOnEditDoubleClick write FOnEditDoubleClick;
  public
    constructor Create(AOwner: TComponent); override;

    procedure Clear; virtual;
    procedure ClearSelection;
    procedure CopyToClipBoard;
    procedure CutToClipBoard;
    function GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer; virtual;
    procedure Paint; override;
    procedure PasteFromClipboard;
    procedure SelectAll;
    procedure SetSelTextBuf(Buffer: PChar);

    property PopupWindow: HWND read GetPopupWindow;
    property SelLength: Integer read GetSelLength write SetSelLength;
    property SelStart: Integer read GetSelStart write SetSelStart;
    property SelText: WideString read GetSelText write SetSelText;
  end;

  // These message records are not declared in D5 and lower.
  TWMSizing = packed record
    Msg: Cardinal;
    fwSide: Integer;
    lprc: PRect;
    Result: Integer;
  end;

  TWMCaptureChanged = packed record
    Msg: Cardinal;
    wParam: Integer;
    hwndNewCapture: HWND;
    Result: Integer;
  end;

  TTreePopup = class(TCustomVirtualStringTree)
  private
    FScrollTheme: HTHEME;    // used for the size gripper
    FPopupAbove: Boolean;    // keep the popup position for hit tests

    procedure CloseTheme;
    function GetOptions: TStringTreeOptions;
    function GetOwner: TCustomVirtualTreeComboBox; reintroduce;
    procedure SetOptions(const Value: TStringTreeOptions);

    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
    procedure WMExitSizeMove(var Message: TMessage); message WM_EXITSIZEMOVE;
    procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
    procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
    procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP;
    procedure WMMouseActivate(var Message: TWMMouseActivate); message WM_MOUSEACTIVATE;
    procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
    procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY;
    procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;
    procedure WMNCPaint(var Message: TRealWMNCPaint); message WM_NCPAINT;
    procedure WMSetCursor(var Message: TWMSetCursor); message WM_SETCURSOR;
    procedure WMSizing(var Message: TMessage); message WM_SIZING;
    procedure WMThemeChanged(var Message: TMessage); message WM_THEMECHANGED;
  protected
    procedure CreateParams(var Params: TCreateParams); override;
    procedure CreateWnd; override;
    procedure DoChecked(Node: PVirtualNode); override;
    procedure DoChange(Node: PVirtualNode); override;
    procedure DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); override;
    procedure DoHotChange(Old, New: PVirtualNode); override;
    function GetOptionsClass: TTreeOptionsClass; override;

    property Owner: TCustomVirtualTreeComboBox read GetOwner;
  public
    constructor Create(AOwner: TComponent); override;

    property Canvas;
    property FocusedNode;
  published
    property Alignment;
    property AutoScrollDelay;
    property AutoScrollInterval;
    property Background;
    property BiDiMode;
    property CheckImageKind;
    property Color;
    property Colors;
    property Constraints;
    property CustomCheckImages;
    property DefaultNodeHeight;
    property EditDelay;
    property Font;
    property Header;
    property HintAnimation;
    property HintMode;
    property HotCursor;
    property Indent;
    property Margin;
    property NodeDataSize;
    property TreeOptions: TStringTreeOptions read GetOptions write SetOptions;
    property TextMargin;
    property ParentBiDiMode;
    property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property RootNodeCount;
    property ShowHint;
    property StateImages;
  end;

  TCustomVirtualTreeComboBox = class(TBaseVirtualComboBox)
  private
    FNodes: TNodeArray;
    FTreePopup: TTreePopup;
    FImages: TImageList;
    FImageChangeLink: TChangeLink;     // connections to the image list to get notified about changes
    FSeparator: WideChar;
    FPaintNode: PVirtualNode;          // Helper for painting.

    procedure CompareCaptions(Sender: TBaseVirtualTree; Node: PVirtualNode; Caption: Pointer; var Abort: Boolean);
    procedure CompareCaptionsPartial(Sender: TBaseVirtualTree; Node: PVirtualNode; Caption: Pointer;
      var Abort: Boolean);
    procedure DoNodeChecking(Sender: TBaseVirtualTree; Node: PVirtualNode; Caption: Pointer; var Abort: Boolean);
    function GetDropDownRect(var R: TRect): Boolean;
    function GetOnAfterCellPaint: TVTAfterCellPaintEvent;
    function GetOnAfterItemErase: TVTAfterItemEraseEvent;
    function GetOnAfterItemPaint: TVTAfterItemPaintEvent;
    function GetOnAfterPaint: TVTPaintEvent;
    function GetOnBeforeCellPaint: TVTBeforeCellPaintEvent;
    function GetOnBeforeItemErase: TVTBeforeItemEraseEvent;
    function GetOnBeforeItemPaint: TVTBeforeItemPaintEvent;
    function GetOnBeforePaint: TVTPaintEvent;
    function GetOnChecked: TVTChangeEvent;
    function GetOnChecking: TVTCheckChangingEvent;
    function GetOnCollapsed: TVTChangeEvent;
    function GetOnCollapsing: TVTChangingEvent;
    function GetOnColumnResize: TVTHeaderNotifyEvent;
    function GetOnHeaderDraw: TVTHeaderPaintEvent;
    function GetOnExpanded: TVTChangeEvent;
    function GetOnExpanding: TVTChangingEvent;
    function GetOnFreeNode: TVTFreeNodeEvent;
    function GetOnGetHint: TVSTGetTextEvent;
    function GetOnGetImageIndex: TVTGetImageEvent;
    function GetOnGetNodeDataSize: TVTGetNodeDataSizeEvent;
    function GetOnGetText: TVSTGetTextEvent;
    function GetOnPaintText: TVTPaintText;
    function GetOnHeaderClick: TVTHeaderClickEvent;
    function GetOnInitChildren: TVTInitChildrenEvent;
    function GetOnInitNode: TVTInitNodeEvent;
    procedure ReadSeparator(Reader: TReader);
    procedure ReadTree(Stream: TStream);
    procedure SetImages(const Value: TImageList);
    procedure SetOnAfterCellPaint(const Value: TVTAfterCellPaintEvent);
    procedure SetOnAfterItemErase(const Value: TVTAfterItemEraseEvent);
    procedure SetOnAfterItemPaint(const Value: TVTAfterItemPaintEvent);
    procedure SetOnAfterPaint(const Value: TVTPaintEvent);
    procedure SetOnBeforeCellPaint(const Value: TVTBeforeCellPaintEvent);
    procedure SetOnBeforeItemErase(const Value: TVTBeforeItemEraseEvent);
    procedure SetOnBeforeItemPaint(const Value: TVTBeforeItemPaintEvent);
    procedure SetOnBeforePaint(const Value: TVTPaintEvent);
    procedure SetOnChecked(Value: TVTChangeEvent);
    procedure SetOnChecking(Value: TVTCheckChangingEvent);
    procedure SetOnCollapsed(Value: TVTChangeEvent);
    procedure SetOnCollapsing(Value: TVTChangingEvent);
    procedure SetOnColumnResize(Value: TVTHeaderNotifyEvent);
    procedure SetOnExpanded(Value: TVTChangeEvent);
    procedure SetOnExpanding(Value: TVTChangingEvent);
    procedure SetOnFreeNode(Value: TVTFreeNodeEvent);
    procedure SetOnGetHint(Value: TVSTGetTextEvent);
    procedure SetOnGetImageIndex(Value: TVTGetImageEvent);
    procedure SetOnGetNodeDataSize(Value: TVTGetNodeDataSizeEvent);
    procedure SetOnGetText(Value: TVSTGetTextEvent);
    procedure SetOnPaintText(const Value: TVTPaintText);
    procedure SetOnHeaderClick(Value: TVTHeaderClickEvent);
    procedure SetOnHeaderDraw(Value: TVTHeaderPaintEvent);
    procedure SetOnInitChildren(Value: TVTInitChildrenEvent);
    procedure SetOnInitNode(Value: TVTInitNodeEvent);
    procedure SetSeparator(const Value: WideChar);
    procedure SetTree(const Value: TTreePopup);
    procedure WriteSeparator(Writer: TWriter);
    procedure WriteTree(Stream: TStream);

    procedure CMCancelMode(var Message: TCMCancelMode); message CM_CANCELMODE;
    procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL;
    procedure WMSize(var Message: TWMSize); message WM_SIZE;
  protected
    function ApplicationMessageHook(var Msg: TMessage): Boolean;
    procedure DefineProperties(Filer: TFiler); override;
    procedure DoSetDroppedDown(Value: Boolean); override;
    function GetPopupWindow: HWND; override;
    function GetTextRect: TRect; override;
    procedure ImageListChange(Sender: TObject);
    procedure OptionsChanged; override;
    procedure ParseText;
    procedure ParseTree;
    function BuildTextFromTree: WideString;
    procedure SetText(const Value: WideString); override;

    property Images: TImageList read FImages write SetImages;
    property Separator: WideChar read FSeparator write SetSeparator default ',';
    property TreePopup: TTreePopup read FTreePopup write SetTree stored False;

    property OnAfterCellPaint: TVTAfterCellPaintEvent read GetOnAfterCellPaint write SetOnAfterCellPaint;
    property OnAfterItemErase: TVTAfterItemEraseEvent read GetOnAfterItemErase write SetOnAfterItemErase;
    property OnAfterItemPaint: TVTAfterItemPaintEvent read GetOnAfterItemPaint write SetOnAfterItemPaint;
    property OnAfterPaint: TVTPaintEvent read GetOnAfterPaint write SetOnAfterPaint;
    property OnBeforeCellPaint: TVTBeforeCellPaintEvent read GetOnBeforeCellPaint write SetOnBeforeCellPaint;
    property OnBeforeItemErase: TVTBeforeItemEraseEvent read GetOnBeforeItemErase write SetOnBeforeItemErase;
    property OnBeforeItemPaint: TVTBeforeItemPaintEvent read GetOnBeforeItemPaint write SetOnBeforeItemPaint;
    property OnBeforePaint: TVTPaintEvent read GetOnBeforePaint write SetOnBeforePaint;
    property OnChecked: TVTChangeEvent read GetOnChecked write SetOnChecked;
    property OnChecking: TVTCheckChangingEvent read GetOnChecking write SetOnChecking;
    property OnCollapsed: TVTChangeEvent read GetOnCollapsed write SetOnCollapsed;
    property OnCollapsing: TVTChangingEvent read GetOnCollapsing write SetOnCollapsing;
    property OnColumnResize: TVTHeaderNotifyEvent read GetOnColumnResize write SetOnColumnResize;
    property OnExpanded: TVTChangeEvent read GetOnExpanded write SetOnExpanded;
    property OnExpanding: TVTChangingEvent read GetOnExpanding write SetOnExpanding;
    property OnFreeNode: TVTFreeNodeEvent read GetOnFreeNode write SetOnFreeNode;
    property OnGetHint: TVSTGetTextEvent read GetOnGetHint write SetOnGetHint;
    property OnGetImageIndex: TVTGetImageEvent read GetOnGetImageIndex write SetOnGetImageIndex;
    property OnGetNodeDataSize: TVTGetNodeDataSizeEvent read GetOnGetNodeDataSize write SetOnGetNodeDataSize;
    property OnPaintText: TVTPaintText read GetOnPaintText write SetOnPaintText;
    property OnGetText: TVSTGetTextEvent read GetOnGetText write SetOnGetText;
    property OnHeaderClick: TVTHeaderClickEvent read GetOnHeaderClick write SetOnHeaderClick;
    property OnHeaderDraw: TVTHeaderPaintEvent read GetOnHeaderDraw write SetOnHeaderDraw;
    property OnInitChildren: TVTInitChildrenEvent read GetOnInitChildren write SetOnInitChildren;
    property OnInitNode: TVTInitNodeEvent read GetOnInitNode write SetOnInitNode;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    procedure Clear; override;
    procedure Paint; override;

    property DroppedDown;
    property Nodes: TNodeArray read FNodes;
  published
    property AnimationDuration;
    property TabStop default True;
  end;

  TVirtualTreeComboBox = class(TCustomVirtualTreeComboBox)
  public
    property Canvas;
  published
    property Align;
    property Alignment;
    property Anchors;
    property AutoSize;
    property BiDiMode;
    property BorderStyle;
    property Color;
    property Constraints;
    property Ctl3D;
    property DragCursor;
    property DragKind;
    property DragMode;
    property DropDownCount;
    property Enabled;
    property Font;
    property Images;
    property ImeMode;
    property ImeName;
    property InternationalCharacters;
    property Layout;
    property Options;
    property ParentBiDiMode;
    property ParentColor;
    property ParentFont;
    property ParentShowHint;
    property PopupMenu;
    property Separator;
    property ShowHint;
    property TabOrder;
    property TabStop;
    property TreePopup;
    property Text;
    property Style;
    property Visible;

    property OnChange;
    property OnChecked;
    property OnChecking;
    property OnClick;
    property OnCollapsed;
    property OnCollapsing;
    property OnColumnResize;
    property OnDblClick;
    property OnDragDrop;
    property OnDragOver;
    property OnHeaderDraw;
    property OnDropDown;
    property OnEditDoubleClick;
    property OnEndDock;
    property OnEndDrag;
    property OnEnter;
    property OnExit;
    property OnExpanded;
    property OnExpanding;
    property OnFreeNode;
    property OnGetHint;
    property OnGetImageIndex;
    property OnGetNodeDataSize;
    property OnGetText;
    property OnHeaderClick;
    property OnInitChildren;
    property OnInitNode;
    property OnKeyDown;
    property OnKeyPress;
    property OnKeyUp;
    property OnMouseDown;
    property OnMouseMove;
    property OnMouseUp;
    property OnPaintText;
    property OnStartDock;
    property OnStartDrag;
  end;

  TVirtualStringGrid = class(TCustomVirtualStringTree)
  end;

  TVirtualDrawGrid = class(TCustomVirtualDrawTree)
  end;

//----------------------------------------------------------------------------------------------------------------------

implementation

uses
  CommCtrl, Menus, SysUtils, FlatSB, DPMisc, JclUnicode, JclSysInfo, Math;

var
  // Redeclaration as variable to prevent static binding.
  AnimateWindow: function(hWnd: HWND; dwTime: DWORD; dwFlags: DWORD): BOOL; stdcall;
  
//----------------------------------------------------------------------------------------------------------------------

type
  EVirtualListBoxError = class(Exception);

  TSelection = record
    StartPos,
    EndPos: Integer;
  end;

const
  ScrollBarProp: array[TDefaultScrollBarMode] of Integer = (
    FSB_REGULAR_MODE,
    FSB_FLAT_MODE,
    FSB_ENCARTA_MODE
  );

//----------------- Utility functions ----------------------------------------------------------------------------------


function GetSel(SelP: Pointer; Index: Integer): Boolean; assembler;

// tests the bit at index Index and returns True if set otherwise False

asm
              BT [EAX], EDX
              SETC AL
end;

//----------------------------------------------------------------------------------------------------------------------

function SetSel(SelP: Pointer; Index: Integer): Boolean; assembler;

// sets the bit at index Index and returns True if this was already set before

asm
              BTS [EAX], EDX
              SETC AL
end;

//----------------------------------------------------------------------------------------------------------------------

function ClearSel(SelP: Pointer; Index: Integer): Boolean; assembler;

// resets the bit at index Index and returns True if it was set before

asm
              BTR [EAX], EDX
              SETC AL
end;

//----------------------------------------------------------------------------------------------------------------------

function ToggleSel(SelP: Pointer; Index: Integer): Boolean; assembler;

// inverts the bit at index Index and returns True if it was set before

asm
              BTC [EAX], EDX
              SETC AL
end;

//----------------------------------------------------------------------------------------------------------------------

procedure ShowError(Sender: TObject; Error: WideString);

begin
  if Sender is TCustomVirtualListBox then
    raise EVirtualListBoxError.Create(Error)
  else
    raise Exception.Create(Error); 
end;

//----------------------------------------------------------------------------------------------------------------------

constructor TCustomVirtualListBox.Create(AOwner: TComponent);

begin
  inherited Create(AOwner);
  FDefaultScrollBarMode := sbmRegular;
  FBorderStyle := bsNone;
  TabStop := True;
  ParentColor := False;
  ControlStyle := [csFramed, csDoubleClicks, csClickEvents, csCaptureMouse, csReflector];
  FItemHeight := 16;
  FEraseBkGnd := True;
  FExtendedSelect := True;
  FAutoScroll := True;
  ItemCount := 0;
  FTopIndex := 0;
  FItemIndex := -1;
  FStyle := vlbStandard;
  FCacheIndex := -1;
  FCache := TStringList.Create;
  Width := 100;
  Height := 120;
  Ctl3D := True;
  FScrollbarWidth := GetSystemMetrics(SM_CXVSCROLL);
  FScrollFactor := 1;
  FScrollTimer := TTimer.Create(Self);
  FScrollTimer.Enabled := False;
  FScrollTimer.OnTimer := OnScrollTimer;
  FChangeTimer := TTimer.Create(Self);
  FChangeTimer.Enabled := False;
  FChangeTimer.OnTimer := OnChangeTimer;
end;

//----------------------------------------------------------------------------------------------------------------------

constructor TCustomVirtualListBox.Create(AOwner: TComponent; AsPopup: Boolean);

begin
  inherited Create(AOwner);
  FBorderStyle := bsNone;
  TabStop := True;
  ParentColor := False;
  ControlStyle := [csFramed, csOpaque, csDoubleClicks, csClickEvents, csCaptureMouse, csReflector];
  FItemHeight := 16;
  FEraseBkGnd := True;
  FExtendedSelect := True;
  ItemCount := 0;
  FTopIndex := 0;
  FItemIndex := -1;
  FStyle := vlbStandard;
  FCacheIndex := -1;
  FCache := TStringList.Create;
  Width := 100;
  Height := 120;
  Ctl3D := True;
  FScrollbarWidth := GetSystemMetrics(SM_CXVSCROLL);
  FScrollFactor := 1;
  FScrollTimer := TTimer.Create(Self);
  FScrollTimer.Enabled := False;
  FScrollTimer.OnTimer := OnScrollTImer;
  FChangeTimer := TTimer.Create(Self);
  FChangeTimer.Enabled := False;
  FChangeTimer.OnTimer := OnChangeTimer;
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TCustomVirtualListBox.Destroy;

begin
  FCache.Free;
  FScrollTimer.Free;
  if Assigned(FSelection) then
    FreeMem(FSelection);
  inherited Destroy;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.Clear;

begin
  FExtSelectionAnchor := -1;
  FItemCount := 0;
  ClearSelection;
  if Assigned(FSelection) then
  begin
    FreeMem(FSelection);
    FSelection := nil;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.ClearSelection;

begin
  if Assigned(FSelection) then
    ZeroMemory(FSelection, (FItemCount div 8) + 1);
  FSelCount := 0;
  if Parent <> nil then
    InvalidateBox(False);
  DoChange(-1, False);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetItemIndex(Value: Integer);

var
  InvRect: TRect;
  OldItemIndex: Integer;
  FullLinesInWindow: Integer;

begin
  if (FItemCount > 0) and ((FItemIndex <> Value) or ((Value <> -1) and not GetSel(FSelection, Value))) then
  begin
    if Value > FItemCount - 1 then
      Value := FItemCount - 1;
    if Value < 0 then
      Value := -1;

    InvRect := ItemRect(FItemIndex);
    InvalidateRect(Handle, @InvRect, False);

    OldItemIndex := FItemIndex;
    FItemIndex := Value;
    if not MultiSelect then
    begin
      SelectItem(OldItemIndex, False);
      SelectItem(FItemIndex, True);
      UpdateWindow(Handle);             { this is required for Win9x! }
    end;
    if Value < TopIndex then
      TopIndex := Value
    else
    begin
      FullLinesInWindow := Height div ItemHeight;
      if Value >= (TopIndex + FullLinesInWindow) then
        TopIndex := Value - FullLinesInWindow + 1;
    end;
    InvRect := ItemRect(FItemIndex);
    InvalidateRect(Handle, @InvRect, False);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetBorderStyle(Value: TBorderStyle);

begin
  if Value <> FBorderStyle then
  begin
    FBorderStyle := Value;
    RecreateWnd;
    if not FUseExternScrollBar then
      FlatSB_SetScrollProp(Handle, WSB_PROP_VSTYLE, ScrollBarProp[FDefaultScrollBarMode], True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetCustomScrollBar(Value: TScrollbar);

// for special scrollbars
// Note: (20-SEP-2000 ml) do not use external scrollbars any longer, support will not continue for further controls and
//       will be removed from existing controls.

begin
  FScrollbar := nil;

  if Assigned(Value) then
  begin
    FUseExternScrollBar := True;
    FScrollBar := Value;
    with FScrollBar do
    begin
      Parent := Self;
      Kind := sbVertical;
      OnChange := ScrollBarChange;
      OnScroll := ScrollBarScroll;
    end;
  end
  else
    FUseExternScrollBar := False;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetDefaultScrollBarMode(Value: TDefaultScrollBarMode);

begin
  if FDefaultScrollBarMode <> Value then
  begin
    FDefaultScrollBarMode := Value;
    if not FUseExternScrollBar then
      FlatSB_SetScrollProp(Handle, WSB_PROP_VSTYLE, ScrollBarProp[Value], True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetImages(Value: TImageList);

begin
  if FImages <> Value then
  begin
    FImages := Value;
    Refresh;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetIntegralHeight(Value: Boolean);

begin
  if Value <> FIntegralHeight then
  begin
    FIntegralHeight := Value;
    if Value then
      Height := (Height div FItemHeight) * FItemHeight // ok *** + 4
    else
      SetScrollBar;
    InvalidateBox(True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetItemCount(Value: Integer);

begin
  if FItemCount <> Value then
  begin
    FItemCount := Value;
    if Value = 0 then
      FItemIndex := -1
    else
      FItemIndex := 0;
    if FTopIndex > FItemCount then
      FTopIndex := 0;
    ReallocMem(FSelection, (FItemCount div 8) + 1);
    ZeroMemory(FSelection, (FItemCount div 8) + 1);
    FSelCount := 0;

    FCacheIndex := -1;                  // Anzeige fr Cache neu fllen
    SetScrollBar;
    // Neuzeichnen nur, wenn sich in der Anzeige etwas gendert hat
    if FItemCount < (FTopIndex + FLinesInWindow) then
      Invalidate;
    DoChange(-1, False);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetItemHeight(Value: Integer);

begin
  if (FItemHeight <> Value) and (Value > 0) then
  begin
    FItemHeight := Value;
    if IntegralHeight then
    begin
      FIntegralHeight := False;
      IntegralHeight := True;
    end;
    SetScrollBar;
    InvalidateBox(False);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.CMFontChanged(var Msg: TMessage);

var
  Size: TSize;

begin
  inherited;
  if Style = vlbStandard then
  begin
    Canvas.Font := Font;
    GetTextExtentPoint32(Canvas.Handle, 'A', 1, Size);
    FItemHeight := Size.CY;             // Font.Height does not work here

    if IntegralHeight then
    begin
      FIntegralHeight := False;
      IntegralHeight := True;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetMultiSelect(Value: Boolean);

begin
  if FMultiSelect <> Value then
  begin
    FMultiSelect := Value;
    if not Value then
      ClearSelection;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetStyle(Value: TVirtualListBoxStyle);

begin
  if FStyle <> Value then
  begin
    FStyle := Value;
    InvalidateBox(True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.MoveSelects(StartIndex, Direction: Integer);

var
  I, MaxCount: Integer;

begin
  MaxCount := FItemCount - 1;
  if StartIndex < MaxCount then
    case Direction of
      1:
        for I := MaxCount downto StartIndex + 1 do
          if GetSel(FSelection, I - 1) then
            SetSel(FSelection, I)
          else
            ClearSel(FSelection, I);
      -1:
        for I := StartIndex to MaxCount do
          if GetSel(FSelection, I + 1) then
            SetSel(FSelection, I)
          else
            ClearSel(FSelection, I)

        else
          raise Exception.Create('MoveSelects, Direction <> + / -1');
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.GetSelected(Index: Integer): Boolean;

begin
  if (Index >= 0) and (Index < FItemCount) then
    Result := GetSel(FSelection, Index)
  else
    Result := False;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SelectItem(Index: Integer; Value: Boolean);

var
  InvRect: TRect;

begin
  if Value then
  begin
    if not SetSel(FSelection, Index) then
      Inc(FSelCount);
  end
  else
  begin
    if ClearSel(FSelection, Index) then
      Dec(FSelCount);
  end;

  InvRect := ItemRect(Index);
  InvalidateRect(Handle, @InvRect, False);
  DoChange(Index, Value);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SelectRange(Start, Stop: Integer);

// selektiert einen ganzen Bereich ohne Invalidierung des Clientareas

var
  Diff,
    StartByte,
    StopByte: Integer;

begin
  if Start = Stop then
    SelectItem(Start, True)
  else
  begin
    if Stop < Start then
    begin
      StartByte := Start;
      Start := Stop;
      Stop := StartByte;
    end;
    StartByte := (Start div 8);
    StopByte := (Stop div 8);
    Diff := StopByte - StartByte;

    if Diff = 0 then
      PByteArray(FSelection)[StartByte] := LOBYTE($FF shl (Start mod 8)) and ((1 shl ((Stop mod 8) + 1)) - 1)
    else
    begin
      // erstes Byte
      PByteArray(FSelection)[StartByte] := LOBYTE($FF shl (Start mod 8));
      Inc(StartByte);

      // Zwischenbytes komplett fllen
      if Diff >= 2 then
        FillChar(PByteArray(FSelection)[StartByte], Diff - 1, $FF);

      // letztes Byte
      PByteArray(FSelection)[StopByte] := (1 shl ((Stop mod 8) + 1)) - 1;
    end;
  end;
  DoChange(Stop, True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetSelected(Index: Integer; Value: Boolean);

begin
  if not MultiSelect then
    if Name <> '' then
      ShowError(Self, Name + ': multi selection not enabled')
    else
      ShowError(Self, 'TCustomVirtualListBox: multi selection not enabled');

  if Index = -1 then                    // Spezialfall: Index = -1 whlt alles aus/ab
  begin
    if Value then
    begin
      FillChar(FSelection^, (FItemCount div 8) + 1, $FF);
      FSelCount := FItemCount;
    end
    else
      ClearSelection;
    InvalidateBox(False);
  end
  else
  begin
    if (Index < 0) or (Index > FItemCount) then
      ShowError(Self, 'List index out of bounds');
    SelectItem(Index, Value);
  end;
  DoChange(Index, Value);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetTopIndex(Value: Integer);

var
  PixelsToScroll: Integer;
  ClipScroll,
    InvRect: TRect;
  FullLinesInWindow: Integer;
begin
  FullLinesInWindow := Height div FItemHeight;
  if Value > (FItemCount - FullLinesInWindow) then
    Value := FItemCount - FullLinesInWindow;

  if Value < 0 then
    Value := 0;

  if FTopIndex <> Value then
  begin
    PixelsToScroll := (FTopIndex - Value) * FItemHeight;
    FTopIndex := Value;
    SetScrollBarPosition(Value);
    if (Abs(PixelsToScroll) >= Height) or not AutoScroll then
      InvalidateBox(False)
    else
    begin
      ClipScroll := Rect(0, 0, FItemWidth, FLinesInWindow * FItemHeight);
      ScrollDC(Canvas.Handle, 0, PixelsToScroll, ClipScroll, ClipScroll, 0, @InvRect);
      InvalidateRect(Handle, @InvRect, True);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.Find(Text: WideString): Boolean;

// looks for the given text and scrolls the control accordingly if there is an exact item hit so that the item is in view

  //--------------- local functions -------------------------------------------

  function CompareBinary(S1, S2: PWideChar): Integer;

  // binary WideString comparation

  var
    A, B: PWideChar;

  begin
    if Assigned(S1) and Assigned(S2) then
    begin
      A := S1;
      B := S2;
      // advance until an end is reached or there is an unequality
      while (A^ <> #0) and (B^ <> #0) and (Word(A^) = Word(B^)) do
      begin
        Inc(A);
        Inc(B);
      end;

      // set result depending on values we found
      if Word(A^) = Word(B^) then
        Result := 0
      else
        if (A^ = #0) or (Word(A^) < Word(B^)) then
          Result := -1
        else
          Result := 1;
    end
    else
      Result := 0;
  end;

  //--------------- end local functions ---------------------------------------

var
  L, H,
    I, C: Integer;

begin
  Result := False;
  L := 0;
  H := FItemCount - 1;
  if Assigned(FOnCompare) then
  begin
    while L <= H do
    begin
      I := (L + H) shr 1;
      C := 0;
      try
        FOnCompare(Self, GetItem(I), Text, C);
      except
        Result := False;
        Exit;
      end;
      if C < 0 then
        L := I + 1
      else
      begin
        H := I - 1;
        if C = 0 then
        begin
          Result := True;
          L := I;
        end;
      end;
    end
  end
  else
  begin
    while L <= H do
    begin
      I := (L + H) shr 1;
      C := CompareBinary(PWideChar(GetItem(I)), PWideChar(Text));
      if C < 0 then
        L := I + 1
      else
      begin
        H := I - 1;
        if C = 0 then
        begin
          Result := True;
          L := I;
        end;
      end;
    end;
  end;

  if L < FItemCount then
    ItemIndex := L;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.InvalidateCache;

begin
  // this will actually cause a new cache reread the next time the control is painted
  FCacheIndex := -1;
  Invalidate;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.ItemAtPos(Pos: TSmallPoint; Existing: Boolean): Integer;

begin
  if PtInrect(ClientRect, SmallPointToPoint(Pos)) then
  begin
    Result := FTopIndex + Pos.Y div FItemHeight;
    if Result >= FItemCount then
      if Existing then
        Result := -1
      else
        Result := FItemCount - 1;
  end
  else
    Result := -1;                       // not in the window
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.ItemRect(Index: Integer): TRect;

begin
  if (Index >= FTopIndex) and (Index <= FTopIndex + FLinesInWindow) and
    (Index >= 0) and (Index < FItemCount) then
  begin
    Result := Rect(0, 0, FItemWidth, FItemHeight);
    OffsetRect(Result, 0, (Index - FTopIndex) * FItemHeight);
  end
  else
    // empty listbox
    if Index = 0 then
      Result := Rect(0, 0, FItemWidth, FItemHeight)
    else
      Result := Rect(0, 0, 0, 0);
end;

//--------------------------------------------------------------------------------

procedure TCustomVirtualListBox.CreateParams(var Params: TCreateParams);

begin
  inherited CreateParams(Params);
  with Params do
  begin
    Style := Style and not WS_VISIBLE and not WS_BORDER;
    if FBorderStyle = bsSingle then
    begin
      ControlStyle := ControlStyle - [csFramed];
      ExStyle := ExStyle or WS_EX_CLIENTEDGE;
    end
    else
      ControlStyle := ControlStyle + [csFramed];
    // tool window style, damit das Fenster nicht im Taskbar erscheint, wenn es
    // als Child window des Desktops verwendet wird (siehe Nutzung in TVirtualCustomComboBox)
    ExStyle := ExStyle or WS_EX_TOOLWINDOW;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.CreateWnd;

begin
  inherited CreateWnd;
  if not FUseExternScrollBar then
  begin
    InitializeFlatSB(Handle);
    FlatSB_SetScrollProp(Handle, WSB_PROP_VSTYLE, ScrollBarProp[FDefaultScrollBarMode], True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMSetFocus(var Msg: TWMSetFocus);

var
  YPos: Integer;
  InvRect: TRect;

begin
  inherited;
  if (FItemIndex >= FTopIndex) and (FItemIndex <= (FTopIndex + FLinesInWindow)) then
  begin
    YPos := (ItemIndex - TopIndex) * FItemHeight;
    if Style <> vlbStandard then
    begin
      InvRect := ItemRect(FItemIndex);
      InvalidateRect(Handle, @InvRect, True);
    end
    else
      DrawFocusRect(Canvas.Handle, Rect(0, YPos, FItemWidth, YPos + FItemHeight));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMSize(var Message: TWMSize);

begin
  inherited;
  FCacheIndex := -1;                    // cache needs refill
  SetScrollBar;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMKillFocus;

var
  InvRect: TRect;

begin
  inherited;

  InvRect := ItemRect(FItemIndex);
  InvalidateRect(Handle, @InvRect, True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.FillCache(NeededIndex: Integer);

// fllt gegebenenfalls den internen Cache, je nach bentigtem Index
// wird nur aufgerufen, wenn ein Callback event des Anwenders existiert

var
  I: Integer;
  Result: WideString;

begin
  // Cache neu fllen?
  if (FCacheIndex = -1) or (NeededIndex < FCacheIndex) or
    ((NeededIndex > (FCacheIndex + FLinesInWindow)) and ((FCacheIndex + FLinesInWindow) < FItemCount)) then
  begin
    FCacheIndex := NeededIndex;
    FCache.Clear;
    for I := 0 to FLinesInWindow do
      if (FCacheIndex + I) < FItemCount then
      begin
        FOnGetItem(Self, FCacheIndex + I, Result);
        FCache.Add(Result);
      end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.GetItem(Index: Integer): WideString;

begin
  Result := '';
  if (Index > -1) and (Index < FItemCount) then
    if Assigned(FOnGetItem) then
    begin
      FillCache(Index);
      Result := FCache[Index - FCacheIndex];
    end
    else
      Result := IntToStr(Index);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.InvalidateBox(All: Boolean);

var
  InvRect: TRect;

begin
  if All then
    Invalidate
  else
  begin
    InvRect := Rect(0, 0, FItemWidth, Height);
    InvalidateRect(Handle, @InvRect, True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.InvalidateItem(Index: Integer);

var
  InvRect: TRect;

begin
  InvRect := ItemRect(Index);
  if not IsRectEmpty(InvRect) then
    InvalidateRect(Handle, @InvRect, True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.InvalidateToBottom(Index: Integer);

// redraw window starting with item at Index

var
  InvRect: TRect;

begin
  InvRect := ItemRect(Index);
  if not IsRectEmpty(InvRect) then
  begin
    InvRect.Bottom := Height;
    InvalidateRect(Handle, @InvRect, True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarWidth(Value: Integer);

begin
  if FScrollBarWidth <> Value then
  begin
    FScrollBarWidth := Value;
    if FScrollBarWidth < 0 then
      FScrollBarWidth := 0;
    if FUseExternScrollBar then
      FScrollbar.Width := Value
    else
      FlatSB_SetScrollProp(Handle, WSB_PROP_CXVSCROLL, Value, True);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMEraseBkgnd(var Msg: TWMEraseBkgnd);

begin
  if FEraseBkGnd then
    inherited
  else
    Msg.Result := 1;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualListBox.GetScrollBarPosition: Integer;

var
  ScrollInfo: TScrollInfo;

begin
  if FUseExternScrollBar then
    Result := FScrollbar.Position
  else
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_POS;
      FlatSB_GetScrollInfo(Handle, SB_VERT, ScrollInfo);
      Result := Round(nPos * FScrollFactor);
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarMin(Value: Integer);

var
  ScrollInfo: TScrollInfo;

begin
  if FUseExternScrollBar then
    FScrollbar.Min := Value
  else
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_RANGE;
      FlatSB_GetScrollInfo(Handle, SB_VERT, ScrollInfo);
      nMin := Value;
      FlatSB_SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarMax(Value: Integer);

var
  ScrollInfo: TScrollInfo;

begin
  if FUseExternScrollBar then
    FScrollbar.Max := Value
  else
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_RANGE;
      FlatSB_GetScrollInfo(Handle, SB_VERT, ScrollInfo);
      nMax := Value;
      // WM_SCROLL kann Werte nur bis ~65000 handeln
      if nMax > 65000 then
      begin
        FScrollFactor := nMax / 65000;
        nMax := 65000 + FLinesInWindow;
      end
      else
        FScrollFactor := 1;
      FlatSB_SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarPosition(Value: Integer);

var
  ScrollInfo: TScrollInfo;

begin
  if FUseExternScrollBar then
    FScrollbar.Position := Value
  else
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_POS;
      nPos := Round(Value / FScrollFactor);
      FlatSB_SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarLargeChange(Value: Integer);

var
  ScrollInfo: TScrollInfo;

begin
  if FUseExternScrollBar then
    FScrollbar.LargeChange := Value
  else
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_PAGE;
      nPage := Value;
      FlatSB_SetScrollInfo(Handle, SB_VERT, ScrollInfo, True);
    end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBarSmallChange(Value: Integer);

begin
  if FUseExternScrollBar then
    FScrollbar.SmallChange := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.Paint;

var
  YPos,
  Index,
  ImgIndex,
  LastIndex: Integer;
  ClipRect,
  PaintRect: TRect;
  ShowImages,
  CallOwnerDraw: Boolean;
  Selected: Boolean;
  TextVOffset,
  ImageVOffset: Integer;

begin
  ClipRect := Canvas.ClipRect;
  YPos := 0;
  LastIndex := FTopIndex + FLinesInWindow;
  if (ClientHeight mod ItemHeight) = 0 then
    Dec(LastIndex);

  if LastIndex > FItemCount - 1 then
    LastIndex := FItemCount - 1;

  ShowImages := Assigned(FImages) and Assigned(FOnGetImage);
  CallOwnerDraw := (Style <> vlbStandard) and Assigned(FOnDrawItem);

  TextVOffset := (ItemHeight - Abs(Canvas.Font.Height)) div 2;
  if ShowImages then
    ImageVOffset := (ItemHeight - FImages.Height) div 2
  else
    ImageVOffset := 0;

  for Index := TopIndex to LastIndex do
  begin
    PaintRect := Rect(0, YPos, FItemWidth, YPos + FItemHeight);
    if (PaintRect.Bottom > ClipRect.Top) and (PaintRect.Top < ClipRect.Bottom) then
    begin
      // fllt der Streifen ins ClipRect
      Selected := GetSel(FSelection, Index);

      if CallOwnerDraw then
        OnDrawItem(Self, Canvas, Index, PaintRect, Selected, Index = FItemIndex)
      else
      begin
        // Hintergrund lschen
        Canvas.Brush.Color := Color;
        Canvas.FillRect(PaintRect);

        if Selected then
        begin
          Canvas.Brush.Color := clHighLight;
          Canvas.Font.Color := clHighlightText;
          // selection bar
          if ShowImages then
          begin
            Inc(PaintRect.Left, FImages.Width + 8);
            Canvas.FillRect(PaintRect);
            Dec(PaintRect.Left, FImages.Width + 8);
          end
          else
            Canvas.FillRect(PaintRect);
        end
        else
          Canvas.Font.Color := Font.Color;

        if ShowImages then
        begin
          ImgIndex := -1;
          FOnGetImage(Self, Index, ImgIndex);
          FImages.Draw(Canvas, PaintRect.Left + 5, PaintRect.Top + ImageVOffset, ImgIndex);
          Canvas.TextOut(PaintRect.Left + FImages.Width + 10, PaintRect.Top + TextVOffset, GetItem(Index));
        end
        else
          Canvas.TextOut(PaintRect.Left + 5, PaintRect.Top + TextVOffset, GetItem(Index));
        if Index = FItemIndex then
        begin
          if ShowImages then Inc(PaintRect.Left, FImages.Width + 8);
          DrawFocusRect(Canvas.Handle, PaintRect);
        end;
      end;
    end;
    Inc(YPos, FItemHeight);
  end;

  // erase not yet covered parts of the window if necessary
  if not FEraseBkGnd and (LastIndex < (FTopIndex + FLinesInWindow)) then
  begin
    PaintRect := Bounds(0, (LastIndex - FTopIndex + 1) * FItemHeight, FItemWidth,
      ClipRect.Bottom - (LastIndex - FTopIndex + 1) * FItemHeight);
    Canvas.Brush.Color := Color;
    Canvas.FillRect(PaintRect);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);

begin
  inherited SetBounds(ALeft, ATop, AWidth, AHeight);
  if FUseExternScrollBar then
  begin
    with FScrollBar do
      SetBounds(AWidth - Width, 0, Width, AHeight);
  end;
  SetScrollBar;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.ToggleItem(Index: Integer);

var
  InvRect: TRect;

begin
  if not ToggleSel(FSelection, Index) then
    Inc(FSelCount)
  else
    Dec(FSelCount);

  InvRect := ItemRect(Index);
  InvalidateRect(Handle, @InvRect, False);
  DoChange(Index, GetSel(FSelection, Index));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.Notification(AComponent: TComponent; Operation: TOperation);

begin
  if (AComponent = FImages) and (Operation = opRemove) then
  begin
    FImages := nil;
    Refresh;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.ScrollBarChange(Sender: TObject);

begin
  TopIndex := GetScrollBarPosition;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.ScrollBarScroll(Sender: TObject; ScrollCode: TScrollCode; var ScrollPos: Integer);

begin
  if ScrollCode = scEndScroll then
    SetFocus;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.SetScrollBar;

var
  SBMax: Integer;
  FullLinesInWindow: Integer;
begin
  FullLinesInWindow := Height div ItemHeight;
  FLinesInWindow := FullLinesInWindow;
  if Height mod ItemHeight <> 0 then
    Inc(FLinesInWindow);
  if FLinesInWindow = 0 then
    FLinesInWindow := 1;
  SBMax := FItemCount - FullLinesInWindow;
  if SBMax < 0 then
    SBMax := 0;

  if HandleAllocated then
  begin
    SetScrollBarMax(SBMax);
    FItemWidth := ClientWidth;
    if FUseExternScrollbar then
      Dec(FItemWidth, FScrollBar.Left);
    SetScrollBarLargeChange(1);
  end
  else
    FItemWidth := Width;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.CMMouseWheel(var Message: TCMMouseWheel);

var
  ScrollCount: Integer;

begin
  inherited;
  if Message.Result = 0 then
  begin
    with Message do
    begin
      Result := 1;
      if ssCtrl in ShiftState then
        ScrollCount := WheelDelta div WHEEL_DELTA * FLinesInWindow
      else
        ScrollCount := WheelDelta div WHEEL_DELTA;
      TopIndex := TopIndex - ScrollCount;
      Update;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.CNKeyDown(var Msg: TWMKey);

var
  Shift: Boolean;
  ShiftState: TShiftState;
  CurrItem: Integer;

begin
  ShiftState := KeyDataToShiftState(Msg.KeyData);
  Shift := (ssShift in ShiftState) and (FExtSelectionAnchor <> -1);
  case Msg.CharCode of
    VK_LEFT,
    VK_UP:
      CurrItem := FItemIndex - 1;
    VK_RIGHT,
      VK_DOWN:
      CurrItem := FItemIndex + 1;
    VK_END:
      CurrItem := FItemCount - 1;
    VK_HOME:
      CurrItem := 0;
    VK_PRIOR:
      begin
        CurrItem := FItemIndex - FLinesInWindow + 1;
        if CurrItem < 0 then
          CurrItem := 0;
      end;
    VK_NEXT:
      begin
        CurrItem := FItemIndex + FLinesInWindow - 1;
        if CurrItem > FItemCount - 1 then
          CurrItem := FItemCount - 1;
      end;
    VK_SPACE:
      begin
        if MultiSelect then
        begin
          if not ExtendedSelect then
            ToggleItem(FItemIndex)
          else
          begin
            ClearSelection;
            SelectItem(FItemIndex, True);
          end;
        end;
        CurrItem := -1;
      end;
  else
    inherited;
    CurrItem := -1;
  end;

  if (CurrItem < 0) or (CurrItem > FItemCount - 1) then
    Exit;

  if MultiSelect and ExtendedSelect then
  begin
    if Shift then
    begin
      if not GetSel(FSelection, CurrItem) then
        SelectItem(CurrItem, True)
      else
        SelectItem(FItemIndex, False)
    end
    else
    begin
      if FSelCount = 1 then
        SelectItem(ItemIndex, False)
      else
        ClearSelection;
      SelectItem(CurrItem, True);
      FExtSelectionAnchor := CurrItem;
    end
  end
  else
    FExtSelectionAnchor := CurrItem;

  ItemIndex := CurrItem;                // select will be done by SetItemIndex
  Update;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WndProc(var Message: TMessage);

begin
  // for auto drag mode, let listbox handle itself, instead of TControl
  if not (csDesigning in ComponentState) and ((Message.Msg = WM_LBUTTONDOWN) or
    (Message.Msg = WM_LBUTTONDBLCLK)) and not Dragging then
  begin
    if DragMode = dmAutomatic then
    begin
      if IsControlMouseMsg(TWMMouse(Message)) then
        Exit;
      ControlState := ControlState + [csLButtonDown];
      Dispatch(Message);                {overrides TControl's BeginDrag}
      Exit;
    end;
  end;

  inherited WndProc(Message);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMLButtonDown(var Msg: TWMLButtonDown);

var
  ShiftState: TShiftState;
  CurrIndex: Integer;

begin
  ShiftState := KeysToShiftState(Msg.Keys);
  CurrIndex := ItemAtPos(Msg.Pos, True);

  if (DragMode = dmAutomatic) and FMultiSelect and (ShiftState * [ssShift, ssCtrl] = []) and
    (CurrIndex > -1) and GetSel(FSelection, CurrIndex) then
  begin
    BeginDrag(False);
    Exit;
  end;

  inherited;
  if not Focused then
    SetFocus;

  if CurrIndex = -1 then
    Exit;

  // auto-scroll vorbereiten
  with FScrollTImer do
  begin
    Interval := 300;
    Enabled := True;
  end;

  if MultiSelect then
  begin
    if not ExtendedSelect then
      ToggleItem(CurrIndex)
    else
    begin                               // MultiSelect and ExtendedSelect
      if Msg.Keys and (MK_SHIFT or MK_CONTROL) = 0 then
      begin                             // loke not MultiSelect, but clear of all selects
        ClearSelection;
        SelectItem(CurrIndex, True);
        FExtSelectionAnchor := CurrIndex;
      end
      else
      begin
        if (Msg.Keys and MK_SHIFT) <> 0 then
        begin                           // Ctrl does not matter
          ClearSelection;
          if FExtSelectionAnchor = -1 then
            FExtSelectionAnchor := CurrIndex;
          FSelCount := Abs(FExtSelectionAnchor - CurrIndex) + 1;
          SelectRange(FExtSelectionAnchor, CurrIndex);
        end
        else
        begin                           // Ctrl without Shift
          ToggleItem(CurrIndex);
          FExtSelectionAnchor := CurrIndex;
        end;
      end;
    end;
  end;
  // focus rect & selects for not MultiSelect
  ItemIndex := CurrIndex;
  // synchronize painting
  Update;

  if (DragMode = dmAutomatic) and not (FMultiSelect and ((ssCtrl in ShiftState) or (ssShift in ShiftState))) then
    BeginDrag(False);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMLButtonUp(var Msg: TWMLButtonUp);

begin
  FScrollTimer.Enabled := False;
  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMMouseMove(var Msg: TWMMouseMove);

var
  Shift: TShiftState;
  CurrItem: Integer;

begin
  inherited;
  CurrItem := ItemAtPos(SmallPoint(2, Msg.YPos), True);
  if CurrItem <> ItemIndex then
  begin
    Shift := KeysToShiftState(Msg.Keys);
    // ssLeft in Shift replaced due to problems with drop down list focus
    if csLButtonDown in ControlState then
    begin
      if (CurrItem > -1) and (CurrItem <> ItemIndex) then
      begin
        if not MultiSelect then
        begin
          SelectItem(FItemIndex, False);
          SelectItem(CurrItem, True);
        end
        else
          if ExtendedSelect then
          begin
            ClearSelection;
            FSelCount := Abs(FExtSelectionAnchor - CurrItem) + 1;
            SelectRange(FExtSelectionAnchor, CurrItem);
          end;
        // MultiSelect and not Extended: Focus only
        ItemIndex := CurrItem;
      end;
      UpdateWindow(Handle);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.WMVScroll(var Msg: TWMVScroll);

begin
  case Msg.ScrollCode of
    SB_BOTTOM:
      TopIndex := FItemCount - 1;
    SB_LINEDOWN:
      TopIndex := FTopIndex + 1;
    SB_LINEUP:
      TopIndex := FTopIndex - 1;
    SB_PAGEDOWN:
      TopIndex := FTopIndex + FLinesInWindow;
    SB_PAGEUP:
      TopIndex := FTopIndex - FLinesInWindow;
    SB_THUMBPOSITION:
      TopIndex := Round(Word(Msg.Pos) * FScrollFactor);
    SB_THUMBTRACK:
      TopIndex := Round(Word(Msg.Pos) * FScrollFactor);
    SB_TOP:
      TopIndex := 0;
  end;
  Update;
  Msg.Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.DoChange(Index: Integer; ItemSelected: Boolean);

begin
  if Assigned(FOnChange) then
  begin
    if FChangeDelay > 0 then
    begin
      FChangeTimer.Enabled := False;
      FLastChangedIndex := Index;
      FLastChangedItemSelected := ItemSelected;
      FChangeTimer.Interval := FChangeDelay;
      FChangeTimer.Enabled := True;
    end
    else
      FOnChange(Self, Index, ItemSelected);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.OnChangeTimer(Sender: TObject);

begin
  if Assigned(FOnChange) then
  begin
    FChangeTimer.Enabled := False;
    FOnChange(Self, FLastChangedIndex, FLastChangedItemSelected);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualListBox.OnScrollTimer(Sender: TObject);

// auto scroll while mouse move with selection

var
  MousePos: TPoint;
  Direction: Integer;
  CurrItem,
    dY, dTime: Integer;
  ScrollInfo: TScrollInfo;

begin
  if (FItemCount > FLinesInWindow) and not FFreezeScroll then
  begin
    GetCursorPos(MousePos);
    MapWindowPoints(0, Handle, MousePos, 1);
    with ScrollInfo do
    begin
      FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
      cbSize := SizeOf(TScrollInfo);
      FMask := SIF_ALL;
      FlatSB_GetScrollInfo(Handle, SB_VERT, ScrollInfo);

      if (MousePos.Y > Height) and (nPos < nMax) then
      begin
        Direction := 1;
        dY := MousePos.Y - Height;
      end
      else
        if (MousePos.Y < 0) and (nPos > 0) then
        begin
          Direction := -1;
          dY := -MousePos.Y;
        end
        else
          Exit;

      if dY <= 100 then
        dTime := 110 - dY
      else
        dTime := 10;

      TopIndex := FTopIndex + Round(Direction * Sqr(dY) / 100);
      FScrollTimer.Interval := dTime;
      if Direction > 0 then
        CurrItem := TopIndex + FLinesInWindow
      else
        CurrItem := TopIndex;

      if not MultiSelect then
      begin
        SelectItem(FItemIndex, False);
        SelectItem(CurrItem, True);
      end
      else
        if ExtendedSelect then
        begin
          ClearSelection;
          FSelCount := Abs(FExtSelectionAnchor - CurrItem) + 1;
          SelectRange(FExtSelectionAnchor, CurrItem);
        end;
      ItemIndex := CurrItem;
    end;
  end;
end;

//----------------- TWideVCBEdit ---------------------------------------------------------------------------------------

procedure TWideVCBEdit.CMMouseWheel(var Message: TCMMouseWheel);

begin
  with Owner as TBaseVirtualComboBox do
    WndProc(TMessage(Message));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.WMKeyDown(var Message: TWMKeyDown);

var
  NeedRedirect: Boolean;
  RedirectKeys: set of Byte;
begin
  RedirectKeys := [VK_RETURN, VK_PRIOR, VK_NEXT, VK_UP, VK_DOWN, VK_MULTIPLY, 187, VK_ADD, 189, VK_SUBTRACT, VK_ESCAPE];
  with Owner as TBaseVirtualComboBox do
    if Style = vcsDropDownList then
      RedirectKeys := RedirectKeys + [VK_END, VK_HOME];

  NeedRedirect := (Message.CharCode in RedirectKeys) or GetKeyState(VK_CONTROL) and (Message.CharCode in [VK_INSERT, VK_DELETE]);

  if NeedRedirect then
    with Owner as TBaseVirtualComboBox do
      WndProc(TMessage(Message))
  else
    inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.CMWantSpecialKey(var Msg: TCMWantSpecialKey);
begin
  if not (Msg.CharCode in [VK_TAB, VK_RETURN]) then
    Msg.Result := 1;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.WMKillFocus(var Message: TWMKillFocus);

begin
  inherited;

  with Owner as TBaseVirtualComboBox do
    if Message.FocusedWnd <> Handle then
      WndProc(TMessage(Message));
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.WMLButtonDblClk(var Message: TWMLButtonDblClk);

begin
  inherited;

  with Owner as TBaseVirtualComboBox do
    EditDoubleClick(Message);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.WMSetFocus(var Message: TWMSetFocus);

begin
  inherited;

  with Owner as TBaseVirtualComboBox do
    if Message.FocusedWnd <> Handle then
      RepaintWindow;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.WMSysKeyDown(var Message: TWMSysKeydown);

begin
  inherited;

  case Message.CharCode of
    VK_UP,
    VK_DOWN:
      with Owner as TBaseVirtualComboBox do
        DroppedDown := not DroppedDown;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TWideVCBEdit.DoChange;

var
  CurrentIndex: Integer;

begin
  with Owner as TBaseVirtualComboBox do
    if AutoSelecting then
    begin
      StartAutoSelecting;
      try
        CurrentIndex := CaretIndex;
        Text := Self.Text;
        CaretIndex := CurrentIndex;
      finally
        EndAutoSelecting;
      end;
    end;
end;

//----------------- TBaseVirtualComboBox -------------------------------------------------------------------------------

constructor TBaseVirtualComboBox.Create(AOwner: TComponent);

begin
  inherited Create(AOwner);

  FMaxLength := 0;
  FStyle := vcsDropDown;
  ControlStyle := [csClickEvents, csSetCaption, csDoubleClicks, csReflector];
  Width := 150;
  Height := 25;
  TabStop := True;
  Color := clWindow;
  ParentColor := False;
  FBorderStyle := bsSingle;
  FDropDownCount := 8;
  FAnimationDuration := 200;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CloseThemes;

begin
  if FComboTheme <> 0 then
    CloseThemeData(FComboTheme);
  if FEditTheme <> 0 then
    CloseThemeData(FEditTheme);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.EndAutoSelecting;

begin
  Exclude(FStates, cbsAutoSelecting);
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetDroppedDown: Boolean;

begin
  Result := cbsDroppedDown in FStates;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetAutoSelecting: Boolean;

begin
  Result := cbsAutoSelecting in FStates;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetModified: Boolean;

begin
  Result := cbsModified in FStates;
  if not Result and HandleAllocated and Assigned(FEditWindow) then
    Result := FEditWindow.Modified;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.ReadIntlChars(Reader: TReader);

begin
  case Reader.NextValue of
    vaLString, vaString:
      FIntlChars := Reader.ReadString;
  else
    FIntlChars := Reader.ReadWideString;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.ReadText(Reader: TReader);

begin
  case Reader.NextValue of
    vaLString, vaString:
      FText := Reader.ReadString;
  else
    FText := Reader.ReadWideString;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetAlignment(const Value: TAlignment);

begin
  if FAlignment <> Value then
  begin
    FAlignment := Value;
    if HandleAllocated then
     Invalidate;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetAnimationDuration(const Value: Cardinal);

begin
  FAnimationDuration := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetBorderStyle(const Value: TBorderStyle);

begin
  if FBorderStyle <> Value then
  begin
    FBorderStyle := Value;
    RecreateWnd;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetDroppedDown(Value: Boolean);

begin
  if (cbsDroppedDown in FStates) <> Value then
  begin
    DoSetDroppedDown(Value);
    if Value and Assigned(FOnDropDown) then
      FOnDropDown(Self);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetIntlChars(const Value: WideString);

begin
  FIntlChars := Value;
  if Assigned(FEditWindow) then
    FEditWindow.IntlChars := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetLayout(const Value: TTextLayout);

begin
  if FLayout <> Value then
  begin
    FLayout := Value;
    if HandleAllocated then
      Invalidate;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetModified(Value: Boolean);

begin
  if HandleAllocated and Assigned(FEditWindow) then
    FEditWindow.Modified := Value;

  if Value then
    Include(FStates, cbsModified)
  else
    Exclude(FStates, cbsModified);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetOptions(Value: TVirtualComboboxOptions);

begin
  if FOptions <> Value then
  begin
    FOptions := Value;
    OptionsChanged;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetSelText(const Value: WideString);

begin
  if Assigned(FEditWindow) then
    //FEditWindow.SelText := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetStyle(Value: TVirtualComboboxStyle);

begin
  if FStyle <> Value then
  begin
    FStyle := Value;
    RecreateWnd;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.StartAutoSelecting;

begin
  Include(FStates, cbsAutoSelecting);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WriteIntlChars(Writer: TWriter);

begin
  Writer.WriteWideString(FIntlChars);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WriteText(Writer: TWriter);

begin
  Writer.WriteWideString(FText);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CMEnabledChanged(var Message: TMessage);

begin
  inherited;
  if Enabled then
    FButtonState := vbsNormal
  else
  begin
    FButtonState := vbsDisabled;
    DroppedDown := False;
  end;
  RepaintWindow;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMEraseBkgnd(var Message: TWMEraseBkgnd);

begin
  Message.Result := 1;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMGetDlgCode(var Message: TWMGetDlgCode);

begin
  Message.Result := DLGC_WANTARROWS or DLGC_WANTCHARS;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMKeyDown(var Message: TWMKeyDown);

var
  Shift: TShiftState;

begin
  case Message.CharCode of
    VK_RETURN,
    VK_ESCAPE:
      begin
        DroppedDown := False;
        if Editable then
          FEditWindow.SelectAll;
      end;
    VK_MULTIPLY,
    187,
    VK_ADD,
    189,
    VK_SUBTRACT:
      begin
        Shift := KeyDataToShiftState(Message.KeyData);
        if ssCtrl in Shift then
          with TMessage(Message) do
            Result := SendMessage(PopupWindow, Msg, wParam, lParam);
        Exit;
      end;
  end;

  inherited;
end;

procedure TBaseVirtualComboBox.WMKeyUp(var Message: TWMKeyUp);
begin
  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMKillFocus(var Message: TWMKillFocus);

begin
  RepaintWindow;

  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMLButtonDown(var Message: TWMLButtonDown);

begin
  inherited;
  if not Focused and CanFocus then
    SetFocus;

  if FStyle = vcsDropDownList then
    DroppedDown := not DroppedDown;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMMouseLeave(var Message: TMessage);

// Returns hot button state of the combobox to its normal state.

var
  R: TRect;

begin
  FButtonState := vbsNormal;
  GetWindowRect(Handle, R);
  R.Left := R.Right - GetSystemMetrics(SM_CXVSCROLL) - 2;
  MapWindowPoints(0, Handle, R, 2);
  RepaintWindow(@R);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMMouseMove(var Message: TWMMouseMove);

begin
  inherited;
  if UseThemes then
    RegisterLeaveEvent(True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCCalcSize(var Message: TWMNCCalcSize);

begin
  inherited;

  with Message.CalcSize_Params^ do
  begin
    // Leave space for the drop down arrow.
    // The width of the combobox button is determined by the vertical scrollbar width.
    with RGRC[0] do
      Dec(Right, GetSystemMetrics(SM_CXVSCROLL));
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCDestroy(var Message: TWMNCDestroy);

begin
  CloseThemes;

  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCHitTest(var Message: TWMNCHitTest);
var
  P: TPoint;

begin
  inherited;
  P.X := Message.XPos;
  P.Y := Message.YPos;
  P := ScreenToClient(P);
  if not (csDesigning in ComponentState) and (P.X >= Width - GetSystemMetrics(SM_CXVSCROLL)) then
    Message.Result := HTBORDER
  else
    Message.Result := HTCLIENT;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCLButtonDblClk(var Message: TWMNCLButtonDblClk);

begin
  // Double click messages are to be handled just like mouse clicks.
  WMNCLButtonDown(Message);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCLButtonDown(var Message: TWMNCLButtonDown);

begin                           
  if not (csDesigning in ComponentState) then
  begin
    if not Focused and CanFocus then
      SetFocus;
    // The message coordinates as well as the button coordinates are relative to screen space.
    if Message.XCursor >= GetSystemMetrics(SM_CXVSCROLL) - 2 then
      DroppedDown := not DroppedDown;
  end;
  
  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCMouseLeave(var Message: TMessage);

// Returns hot button state of the combobox to its normal state.

var
  R: TRect;

begin
  FButtonState := vbsNormal;
  GetWindowRect(Handle, R);
  R.Left := R.Right - GetSystemMetrics(SM_CXVSCROLL) - 2;
  MapWindowPoints(0, Handle, R, 2);
  RepaintWindow(@R);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCMouseMove(var Message: TWMNCMouseMove);

begin
  inherited;
  if UseThemes then
    RegisterLeaveEvent(False);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMNCPaint(var Message: TRealWMNCPaint);

var
  R: TRect;
  BitmapHandle: HBitmap;
  Bitmap: Windows.TBitmap;
  DC: HDC;
  Flags: DWORD;
  ButtonStyle,
  EdgeFlags: Cardinal;
  X, Y: Integer;
  ButtonWidth,
  ButtonFlag,
  BorderFlag: Integer;

begin
  Message.Result := 0;

  Flags := DCX_CACHE or DCX_CLIPSIBLINGS or DCX_CLIPCHILDREN or DCX_WINDOW;

  if (Message.Rgn = 1) or not IsWinNT then
    DC := GetDCEx(Handle, 0, Flags)
  else
    DC := GetDCEx(Handle, Message.Rgn, Flags or DCX_INTERSECTRGN);

  try
    R := Rect(0, 0, Width, Height);
    // Determine size of drop down button.
    ButtonWidth := GetSystemMetrics(SM_CXVSCROLL);
    // Exclude the client area from painting.
    if BorderStyle = bsSingle then
      ExcludeClipRect(DC, 2, 2, Width - ButtonWidth - 2, Height - 2)
    else
      ExcludeClipRect(DC, 0, 0, Width - ButtonWidth, Height);

    if UseThemes then
    begin
      // Draw frame.
      if FButtonState = vbsDisabled then
      begin
        ButtonFlag := CBXS_DISABLED;
        BorderFlag := ETS_DISABLED;
      end
      else
      begin
        ButtonFlag := Ord(FButtonState) + 1;
        BorderFlag := ETS_NORMAL;
      end;
      // The disabled border color is not exactly what the system combobox uses, but close enough.
      DrawThemeBackground(FEditTheme, DC, EP_EDITTEXT, BorderFlag, R, @R);
      InflateRect(R, -1, -1);
      // Draw button.
      // The width of the combobox button is determined by the vertical scrollbar width.
      R.Left := R.Right - ButtonWidth;
      DrawThemeBackground(FComboTheme, DC, CP_DROPDOWNBUTTON, ButtonFlag, R, @R);
    end
    else
    begin
      // Draw frame.
      EdgeFlags := BF_ADJUST or BF_RECT or BF_MIDDLE;
      if BorderStyle = bsSingle then
        DrawEdge(DC, R, EDGE_SUNKEN, EdgeFlags);

      // Draw button.
      BitmapHandle := LoadBitmap(0, Pointer(OBM_COMBO));
      GetObject(BitmapHandle, SizeOf(Bitmap), @Bitmap);
      try
        R.Left := R.Right - ButtonWidth;

        X := (R.Left + R.Right - Bitmap.bmWidth) div 2;
        Y := (R.Top + R.Bottom - Bitmap.bmHeight) div 2;

        ButtonStyle := BDR_RAISEDINNER or BDR_RAISEDOUTER;

        if FButtonState = vbsPressed then
        begin
          DrawEdge(DC, R, ButtonStyle, EdgeFlags + BF_FLAT);
          Inc(X);
          Inc(Y);
        end
        else
          DrawEdge(DC, R, ButtonStyle, EdgeFlags);

        DrawState(DC, 0, nil, Integer(BitmapHandle), 0, X, Y, 0, 0, DST_BITMAP or DSS_NORMAL);
      finally
        DeleteObject(BitmapHandle);
      end;
    end;
  finally
    ReleaseDC(Handle, DC);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMSetFocus(var Message: TWMSetFocus);

begin
  inherited;

  if FStyle <> vcsDropDownList then
    SelectAll;
  RepaintWindow;
  if Editable then
    FEditWindow.SetFocus;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMSetFont(var Message: TWMSetFont);

var
  Metrics: TTextMetric;

begin
  inherited;
  Canvas.Font := Font;
  GetTextMetrics(Canvas.Handle, Metrics);
  FTextHeight := Metrics.tmHeight;

  if Assigned(FEditWindow) then
    FEditWindow.Font := Font;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMSize(var Message: TWMSize);

begin
  inherited;

  if Assigned(FEditWindow) then
  begin
    // Center the text vertically in the edit window.
    //FEditWindow.NonClientMargin.Top := (Height - FTextHeight) div 2;
    //FEditWindow.NonClientMargin.Bottom := (Height - FTextHeight) div 2;
  end;
  RepaintWindow;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WMThemeChanged(var Message: TMessage);

// The user has changed the current theme or its enable state.

begin
  CloseThemes;

  if UseThemes then
  begin
    FComboTheme := OpenThemeData(0, 'combobox');
    FEditTheme := OpenThemeData(0, 'edit');
  end;

  RepaintWindow;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.Changed;

begin
  inherited;

  if Assigned(FOnChange) then
    FOnChange(Self);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CreateParams(var Params: TCreateParams);

begin
  inherited CreateParams(Params);

  with Params do
  begin
    Style := Style or WS_CLIPCHILDREN or WS_CLIPSIBLINGS;

    if FBorderStyle = bsSingle then
    begin
      if Ctl3D  then
        ExStyle := ExStyle or WS_EX_CLIENTEDGE
      else
        Style := Style or WS_BORDER;
    end
    else
      Style := Style and not WS_BORDER;

    // We can leave out the redraw flags because we have to repaint the window on resize anyway.
    WindowClass.Style := WindowClass.Style and not (CS_HREDRAW or CS_VREDRAW);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CreateWnd;

begin
  Include(FStates, cbsCreating);
  try
    inherited CreateWnd;
    if UseThemes then
    begin
      FComboTheme := OpenThemeData(0, 'combobox');
      FEditTheme := OpenThemeData(0, 'edit');
    end;

    if not (csDesigning in ComponentState) and (FStyle = vcsDropDown) then
    begin
      FEditWindow := TWideVCBEdit.Create(Self);
      FEditWindow.Parent := Self;
      FEditWindow.Options := [eoCanCopyFrom, eoSingleLine];
      FEditWindow.Align := alClient;
      FEditWindow.Text := Text;
      FEditWindow.BorderStyle := bsNone;
      FEditWindow.IntlChars := FIntlChars;

      FEditWindow.NonClientMargin.Left := 1;
      FEditWindow.NonClientMargin.Right := 1;
      FEditWindow.NonClientMargin.Top := 1;
      FEditWindow.NonClientMargin.Bottom := 1;
    end;

  finally
    Exclude(FStates, cbsCreating);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.DefineProperties(Filer: TFiler);

begin
  inherited;

  Filer.DefineProperty('WideText', ReadText, WriteText, FText <> '');
  Filer.DefineProperty('IntlChars', ReadIntlChars, WriteIntlChars, FIntlChars <> '');
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.DestroyWnd;

begin
  DroppedDown := False;
  FreeAndNil(FEditWindow);
  inherited DestroyWnd;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.DoSetDroppedDown(Value: Boolean);

begin
  if Value <> (cbsDroppedDown in FStates) then
  begin
    if Value then
      Include(FStates, cbsDroppedDown)
    else
      Exclude(FStates, cbsDroppedDown);
    RepaintWindow;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.Editable: Boolean;

begin
  Result := (FStyle = vcsDropDown) and Assigned(FEditWindow);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.EditDoubleClick(var Message: TWMLButtonDblClk);

// This method is called when there is an edit and it has been double clicked. This special feature
// is necessary for the property inspector to start a its edit action.

begin
  if Assigned(FOnEditDoubleClick) then
    FOnEditDoubleClick(Self, KeysToShiftState(Message.Keys), SmallPointToPoint(Message.Pos));
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.FindItem(const ItemText: WideString): Boolean;

begin
  Result := False;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetPopupWindow: HWND;

begin
  Result := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetSelLength: Integer;

begin
  if Editable then
    Result := FEditWindow.SelEnd - FEditWindow.SelStart
  else
    Result := -1;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetSelStart: Integer;

begin
  if Editable then
    Result := FEditWindow.SelStart
  else
    Result := -1;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetSelText: WideString;

begin
  if Editable then
    Result := FEditWindow.SelText
  else
    Result := '';
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetTextRect: TRect;

begin
  Result := ClientRect;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.OptionsChanged;

begin
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.RegisterLeaveEvent(IsClientArea: Boolean);

// If the combobox is currently not dropped down then the hover button state is set (if not yet done)
// and the window is registered for tracking the leave event of the mouse.

const
  TME_NONCLIENT = $00000010; // still not defined in Delphi 6

var
  TrackInfo: CommCtrl.TTrackMouseEvent;

begin
  if not (cbsDroppedDown in FStates) and (FButtonState <> vbsHot) then
  begin
    FButtonState := vbsHot;
    RepaintWindow;

    with TrackInfo do
    begin
      cbSize := SizeOf(TrackInfo);
      dwFlags := TME_LEAVE;
      if not IsClientArea then
        dwFlags := dwFlags or TME_NONCLIENT;
      hwndTrack := Handle;
      dwHoverTime := HOVER_DEFAULT;
    end;
    CommCtrl._TrackMouseEvent(@TrackInfo); // this is a wrapper that either calls TrackMouseEvent or emulates it
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.RepaintWindow(R: PRect = nil);

// Initiates an invalidation and repaint of the window, including the non-client area.
// If R <> nil then it should specify the parts of the window to repaint.

begin
  RedrawWindow(Handle, R, 0, RDW_FRAME or RDW_NOERASE or RDW_NOCHILDREN or RDW_INVALIDATE or RDW_VALIDATE or
    RDW_UPDATENOW);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetSelLength(Value: Integer);

begin
  if Editable then
    FEditWindow.SelEnd := FEditWindow.SelStart + Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetSelStart(Value: Integer);

begin
  if Editable then
    FEditWindow.SelStart := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetText(const Value: WideString);

var
  NewText: WideString;

begin
  if (FStyle = vcsDropDownList) or Editable then
  begin
    if Length(Value) > 0 then
      NewText := WideNormalize(Value, nfC)
    else
      NewText := '';
    if NewText <> FText then
    begin
      FText := NewText;
      if Editable then
        FEditWindow.Text := FText;
      Invalidate;
      Changed;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.WndProc(var Message: TMessage);

begin
  if not (csDesigning in ComponentState) then
  begin
    case Message.Msg of
      WM_KEYFIRST..WM_DEADCHAR:
        begin
          if (Message.Msg = WM_KEYDOWN) and (TWMKeyDown(Message).CharCode in [VK_RETURN, VK_ESCAPE]) then
            DroppedDown := False
          else
            with Message do
              SendMessage(PopupWindow, Msg, wParam, lParam);

          inherited; // otherwise we disable KeyPreview
        end;
      WM_SYSKEYDOWN:
        case TWMSysKeyDown(Message).CharCode of
          VK_UP,
          VK_DOWN:
            DroppedDown := not DroppedDown;
        else
          inherited;
        end;
    else
      inherited;
    end;
  end
  else
    inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.Clear;

begin
  if Assigned(FEditWindow) then
    FEditWindow.Text := '';
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.ClearSelection;

begin
  if Assigned(FEditWindow) then
    FEditWindow.ClearSelection;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CopyToClipBoard;

begin
  if Assigned(FEditWindow) then
    FEditWindow.CopyToClipBoard;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.CutToClipBoard;

begin
  if Assigned(FEditWindow) then
    FEditWindow.CutToClipBoard;
end;

//----------------------------------------------------------------------------------------------------------------------

function TBaseVirtualComboBox.GetSelTextBuf(Buffer: PChar; BufSize: Integer): Integer;

var
  P: PChar;
  StartPos: Integer;

begin
  StartPos := GetSelStart;
  Result := GetSelLength;
  P := StrAlloc(GetTextLen + 1);
  try
    GetTextBuf(P, StrBufSize(P));
    if Result >= BufSize then
      Result := BufSize - 1;
    StrLCopy(Buffer, P + StartPos, Result);
  finally
    StrDispose(P);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.Paint;

var
  R: TRect;
  X, Y: Integer;
  Size: TSize;
  S: WideString;

begin
  with Canvas do
  begin
    // At design time no edit will be created so we have to paint the background in this case too.
    if (FStyle = vcsDropDownList) or (csDesigning in ComponentState) then
    begin
      Font := Self.Font;
      Brush.Color := Color;
      R := GetTextRect;
      FillRect(R);
      if UseThemes then
      begin
        InflateRect(R, -1, -1);
        if Focused and not (cbsDroppedDown in FStates) then
        begin
          Brush.Color := clHighLight;
          FillRect(R);
        end;
      end
      else
      begin
        InflateRect(R, -1, -1);
        if Focused and not (cbsDroppedDown in FStates) then
        begin
          Brush.Color := clHighLight;
          FillRect(R);
          Brush.Color := Color;
          DrawFocusRect(R);
        end;
      end;
      InflateRect(R, -1, -1);

      // Determine text to paint depending on current state.
      S := FText;

      // Paint text according to the alignment and layout values.
      case FAlignment of
        taCenter:
          begin
            GetTextExtentPoint32W(Canvas.Handle, PWideChar(S), Length(S), Size);
            X := (R.Right - R.Left - Size.cx) div 2;
          end;
        taRightJustify:
          begin
            GetTextExtentPoint32W(Canvas.Handle, PWideChar(S), Length(S), Size);
            X := R.Right - R.Left - Size.cx;
          end;
      else
        // taLeftJustify
        X := 0;
      end;
      case FLayout of
        tlCenter:
          Y := (R.Bottom - R.Top - FTextHeight) div 2;
        tlBottom:
          Y := R.Bottom - R.Top - FTextHeight;
      else
        // tlTop
        Y := 0;
      end;

      if Focused and not (cbsDroppedDown in FStates) then
        Font.Color := clWhite;
      SetBkMode(Handle, TRANSPARENT);
      ExtTextOutW(Handle, R.Left + X, R.Top + Y, ETO_CLIPPED, @R, PWideChar(S), Length(S), nil);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.PasteFromClipboard;

begin
  if Assigned(FEditWindow) then
    FEditWindow.PasteFromClipboard;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SelectAll;

begin
  if Assigned(FEditWindow) then
    FEditWindow.SelectAll;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TBaseVirtualComboBox.SetSelTextBuf(Buffer: PChar);

begin
  if Assigned(FEditWindow) then
//    SendMessage(FEditWindow.Handle, EM_REPLACESEL, 0, Integer(Buffer));
end;

//----------------- TTreePopup ----------------------------------------------------------------------------

constructor TTreePopup.Create(AOwner: TComponent);

begin
  inherited Create(AOwner);

  BorderStyle := bsSingle;
  BevelKind := bkNone;

  TreeOptions.PaintOptions := TreeOptions.PaintOptions + [toPopupMode, toThemeAware];

  ScrollBarOptions.ScrollBars := ssBoth;

  Constraints.MinHeight := DefaultNodeHeight;
  Constraints.MinWidth := 2 * GetSystemMetrics(SM_CXVSCROLL);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.CloseTheme;

begin
  if FScrollTheme <> 0 then
    CloseThemeData(FScrollTheme);
  FScrollTheme := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

function TTreePopup.GetOptions: TStringTreeOptions;

begin
  Result := inherited TreeOptions as TStringTreeOptions;
end;

//----------------------------------------------------------------------------------------------------------------------

function TTreePopup.GetOwner: TCustomVirtualTreeComboBox;

begin
  Result := inherited Owner as TCustomVirtualTreeComboBox;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.SetOptions(const Value: TStringTreeOptions);

begin
  inherited TreeOptions.Assign(Value);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.CMMouseLeave(var Message: TMessage);

// Recapture mouse if the tree is currently popped up.

begin
  if Owner.DroppedDown then
  begin
    SetCapture(Self.Handle);
    Windows.SetCursor(Screen.Cursors[crDefault]);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMExitSizeMove(var Message: TMessage);

begin
  Owner.SetFocus;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMKeyDown(var Message: TWMKeyDown);

begin
  if Owner.DroppedDown and (Message.CharCode = VK_ESCAPE) then
    Owner.DroppedDown := False
  else
    inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

const
  SC_SIZELEFT = $F001;
  SC_SIZERIGHT = $F002;
  SC_SIZETOP = $F003;
  SC_SIZETOPLEFT = $F004;
  SC_SIZETOPRIGHT = $F005;
  SC_SIZEBOTTOM = $F006;
  SC_SIZEBOTTOMLEFT = $F007;
  SC_SIZEBOTTOMRIGHT = $F008;
  SC_DRAGMOVE = $F012;

procedure TTreePopup.WMLButtonDown(var Message: TWMLButtonDown);

var
  R: TRect;

begin
  inherited;

  GetWindowRect(Handle, R);
  if not PtInRect(R, ClientToScreen(SmallPointToPoint(Message.Pos))) then
  begin
    Owner.DroppedDown := False;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMLButtonUp(var Message: TWMLButtonUp);

var
  HitInfo: THitInfo;
  WasCaptured,
  IsHit: Boolean;
  P: TPoint;
  R: TRect;

begin
  WasCaptured := GetCapture = Handle;
  inherited;

  // Check first if the mouse is in the tree window at all.
  P := ClientToScreen(SmallPointToPoint(Message.Pos));
  GetWindowRect(Handle, R);
  IsHit := PtInRect(R, P);
  if IsHit then
  begin
    GetHitTestInfoAt(Message.XPos, Message.YPos, True, HitInfo);
    with TreeOptions do
      IsHit := ([hiOnItemLabel, hiOnNormalIcon] * HitInfo.HitPositions <> []) or
        (((toFullRowSelect in SelectionOptions) or (toGridExtensions in MiscOptions)) and
        ([hiOnItemCheckBox, hiOnItemButton] * HitInfo.HitPositions = []) and
        Assigned(HitInfo.HitNode));

    if vcoMultiSelection in Owner.Options then
    begin
      if hiOnItemLabel in HitInfo.HitPositions then
      begin
        if HitInfo.HitNode.CheckState = csUncheckedNormal then
          HitInfo.HitNode.CheckState := csCheckedNormal
        else
          HitInfo.HitNode.CheckState := csUncheckedNormal;
        RepaintNode(HitInfo.HitNode);
        DoChecked(HitInfo.HitNode);
      end;
    end
    else
      if IsHit then
        Owner.DroppedDown := False;
  end
  else
    if WasCaptured then
      SetCapture(Handle);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMMouseActivate(var Message: TWMMouseActivate);

// Prevent window from being activated which would deactivate the owner control and its parent form.

begin
  Message.Result := MA_NOACTIVATE;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMMouseMove(var Message: TWMMouseMove);

var
  R: TRect;

begin
  inherited;

  // Switch off mouse capturing depending on mouse position.
  // This will ensure proper hit testing for the non-client area (resizing!).
  if GetCapture = Handle then
  begin
    GetWindowRect(Handle, R);
    if PtInRect(R, ClientToScreen(SmallPointToPoint(Message.Pos))) then
      ReleaseCapture;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMNCDestroy(var Message: TWMNCDestroy);

begin
  CloseTheme;

  inherited;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMNCHitTest(var Message: TWMNCHitTest);

begin
  inherited;

  with Message do
  begin
    if FPopupAbove then
    begin
      // Popup is shown above the combobox.
      if Abs(YPos - Top) <= 5 then
      begin
        if Abs(XPos - Left - Width) <= 5 then
          Result := HTTOPRIGHT
        else
          Result := HTTOP;
      end
      else
        if Abs(XPos - Left - Width) <= 5 then
          Result := HTRIGHT;
    end
    else
    begin
      // Popup is shown below the combobox.
      if Abs(YPos - Top - Height) <= 5 then
      begin
        if Abs(XPos - Left - Width) <= 5 then
          Result := HTBOTTOMRIGHT
        else
          Result := HTBOTTOM;
      end
      else
        if Abs(XPos - Left - Width) <= 5 then
          Result := HTRIGHT;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMNCPaint(var Message: TRealWMNCPaint);

// Draws a size grip into the little, unsused, right bottom square area.

var
  R: TRect;
  DC: HDC;
  Flags: DWORD;
  SBWidth,
  SBHeight: Integer;

  ScrollInfo: TScrollInfo;

begin
  inherited;

  // Determine whether both scroll bars are visible or not.
  with ScrollInfo do
  begin
    FillChar(ScrollInfo, SizeOf(ScrollInfo), 0);
    cbSize := SizeOf(ScrollInfo);
    fMask := SIF_PAGE or SIF_RANGE;
    GetScrollInfo(Handle, SB_VERT, ScrollInfo);
    if nMax > Integer(nPage) then
      SBWidth := GetSystemMetrics(SM_CXVSCROLL)
    else
      SBWidth := 0;

    nMax := 0;
    nPage := 0;
    GetScrollInfo(Handle, SB_HORZ, ScrollInfo);
    if nMax > Integer(nPage) then
      SBHeight := GetSystemMetrics(SM_CYHSCROLL)
    else
      SBHeight := 0;
  end;

  // Paint size box only if both scrollbars are visible.
  if (SBWidth > 0) and (SBHeight > 0) then
  begin
    Flags := DCX_CACHE or DCX_CLIPSIBLINGS or DCX_CLIPCHILDREN or DCX_WINDOW;

    if (Message.Rgn = 1) or not IsWinNT then
      DC := GetDCEx(Handle, 0, Flags)
    else
      DC := GetDCEx(Handle, Message.Rgn, Flags or DCX_INTERSECTRGN);

    if DC <> 0 then
    try
      R := Rect(Width - SBWidth - 1, Height - SBHeight - 1, Width - 1, Height - 1);
      if UseThemes then
        DrawThemeBackground(FScrollTheme, DC, SBP_SIZEBOX, SZB_RIGHTALIGN, R, @R)
      else
        DrawFrameControl(DC, R, DFC_SCROLL, DFCS_SCROLLSIZEGRIP);
    finally
      ReleaseDC(Handle, DC);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMSetCursor(var Message: TWMSetCursor);

begin
  // The VCL screws up the cursors during resize, hence avoid it.
  DefaultHandler(Message);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMSizing(var Message: TMessage);
begin
  inherited;
  Include(Owner.FStates, cbsResizedOnce); // set whenever the user resizes the popup
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.WMThemeChanged(var Message: TMessage);

// The user has changed the current theme or its enable state.

begin
  CloseTheme;

  if UseThemes then
    FScrollTheme := OpenThemeData(0, 'scrollbar');

  RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_NOERASE or RDW_NOCHILDREN);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.CreateParams(var Params: TCreateParams);

const
  CS_DROPSHADOW = $00020000;
  
begin
  inherited CreateParams(Params);

  with Params do
  begin
    Style := WS_POPUP or WS_BORDER or WS_HSCROLL or WS_VSCROLL;
    ExStyle := ExStyle or WS_EX_TOOLWINDOW or WS_EX_TOPMOST or WS_EX_NOPARENTNOTIFY;

    if IsWinXP then
      with WindowClass do
        Style := Style or CS_DROPSHADOW;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.CreateWnd;

begin
  inherited;

  if UseThemes then
    FScrollTheme := OpenThemeData(0, 'scrollbar');
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.DoChecked(Node: PVirtualNode);

begin
  inherited;

  if vcoAutoUpdate in Owner.FOptions then
    Owner.ParseTree;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.DoChange(Node: PVirtualNode);

var
  DoAutoUpdate: Boolean;
  
begin
  inherited;

  with Owner do
  begin
    DoAutoUpdate := ([vcoAutoUpdate, vcoMultiSelection] * FOptions = [vcoAutoUpdate]) or not (cbsDroppedDown in FStates);
    if DoAutoUpdate and Assigned(Node) and not (cbsAutoSelecting in FStates) then
    begin
      Include(FStates, cbsAutoSelecting);
      try
        Text := Self.Text[Node, Header.MainColumn];
      finally
        Exclude(FStates, cbsAutoSelecting);
      end;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates);
begin
  inherited;
  if vcoMultiSelection in Owner.Options then
    Node.CheckType := ctCheckBox;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TTreePopup.DoHotChange(Old, New: PVirtualNode);

begin
  inherited;

  if vcoHotTrack in Owner.Options then
  begin
    if Assigned(Old) then
      Selected[Old] := False;
    if Assigned(New) then
      Selected[New] := True;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TTreePopup.GetOptionsClass: TTreeOptionsClass;

begin
  Result := TStringTreeOptions;
end;

//----------------- TCustomVirtualTreeComboBox ----------------------------------------------------------------------------

constructor TCustomVirtualTreeComboBox.Create(AOwner: TComponent);

begin
  inherited Create(AOwner);

  FTreePopup := TTreePopup.Create(Self);
  with FTreePopup do
  begin
    // Park the window far outside the screen to avoid it flashing.
    Left := 10000;
    Width := 100;
    ParentWindow := GetDesktopWindow;
    Name := 'TreePopup';
    Visible := False;
    ShowWindow(Handle, SW_HIDE);
  end;

  FImageChangeLink := TChangeLink.Create;
  FImageChangeLink.OnChange := ImageListChange;

  FSeparator := ',';
  FOptions := DefaultVirtualComboBoxOptions;
  
  // The combo box has to hook the main window to get notified when the application becomes inactive.
  if not (csDesigning in ComponentState) then
    Application.HookMainWindow(ApplicationMessageHook);
end;

//----------------------------------------------------------------------------------------------------------------------

destructor TCustomVirtualTreeComboBox.Destroy;

begin
  if not (csDesigning in ComponentState) then
    Application.UnhookMainWindow(ApplicationMessageHook);
  FImageChangeLink.Free;
  FTreePopup.Free; 
  inherited Destroy;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.CompareCaptions(Sender: TBaseVirtualTree; Node: PVirtualNode; Caption: Pointer;
  var Abort: Boolean);

// Callback method to find a node whose text is the same as the current combo box's text.
// Note: Comparation is case insensitive.

var
  AText: WideString;

begin
  with Sender as TTreePopup do
    AText := Text[Node, Header.MainColumn];
  Abort := WideSameText(PWideChar(Caption), AText);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.CompareCaptionsPartial(Sender: TBaseVirtualTree; Node: PVirtualNode;
  Caption: Pointer; var Abort: Boolean);

// Callback method to find a node whose text is the same as the current combo box's text.
// Note: Comparation is case insensitive.

var
  NodeText,
  CurrentText: WideString;


begin
  with Sender as TTreePopup do
    NodeText := Text[Node, Header.MainColumn];
  CurrentText := PWideChar(Caption);
  Abort := StrLICompW(PWideChar(CurrentText), PWideChar(NodeText), Length(CurrentText)) = 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.DoNodeChecking(Sender: TBaseVirtualTree; Node: PVirtualNode; Caption: Pointer; var Abort: Boolean);

// Callback method which compares the given node with the nodes stored in the internal FNodes array.
// If Node is in this list then it is check otherwise unchecked.

const
  CheckState: array[Boolean] of TCheckState = (csUncheckedNormal, csCheckedNormal);

var
  I: Integer;

begin
  I := 0;
  while I < Length(FNodes) do
  begin
    if FNodes[I] = Node then
      Break;
    Inc(I);
  end;

  FTreePopup.CheckState[Node] := CheckState[I < Length(FNodes)];
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetDropDownRect(var R: TRect): Boolean;

// Calculates the position and size of the popup window in screen coordinates and returns True if the window is
// above the combo box otherwise False is returned.

var
  AHeight,
  AWidth: Cardinal;

begin
  if not (cbsResizedOnce in FStates) then
  begin
    // Before calculating the position adjust the height of the tree popup depending on the drop down count value.
    if FTreePopup.VisibleCount < FDropDownCount then
      FTreePopup.ClientHeight := Max(1, FTreePopup.VisibleCount) * FTreePopup.DefaultNodeHeight
    else
      FTreePopup.ClientHeight := FDropDownCount * FTreePopup.DefaultNodeHeight;
  end;
  
  AWidth := FTreePopup.Width;
  AHeight := FTreePopup.Height;

  R.TopLeft := Parent.ClientToScreen(Point(Left, Top + Height));
  Result := (R.Top + Integer(AHeight)) > Screen.Height;
  if Result then
    R.TopLeft := Parent.ClientToScreen(Point(Left, Top - Integer(AHeight)));
  R.Right := R.Left + Integer(AWidth);
  R.Bottom := R.Top + Integer(AHeight);
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnAfterCellPaint: TVTAfterCellPaintEvent;

begin
  Result := FTreePopup.OnAfterCellPaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnAfterItemErase: TVTAfterItemEraseEvent;

begin
  Result := FTreePopup.OnAfterItemErase;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnAfterItemPaint: TVTAfterItemPaintEvent;

begin
  Result := FTreePopup.OnAfterItemPaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnAfterPaint: TVTPaintEvent;

begin
  Result := FTreePopup.OnAfterPaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnBeforeCellPaint: TVTBeforeCellPaintEvent;

begin
  Result := FTreePopup.OnBeforeCellPaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnPaintText: TVTPaintText;
begin
  Result := FTreePopup.OnPaintText;
end;



function TCustomVirtualTreeComboBox.GetOnBeforeItemErase: TVTBeforeItemEraseEvent;

begin
  Result := FTreePopup.OnBeforeItemErase;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnBeforeItemPaint: TVTBeforeItemPaintEvent;

begin
  Result := FTreePopup.OnBeforeItemPaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnBeforePaint: TVTPaintEvent;

begin
  Result := FTreePopup.OnBeforePaint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnChecked: TVTChangeEvent;

begin
  Result := FTreePopup.OnChecked;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnChecking: TVTCheckChangingEvent;

begin
  Result := FTreePopup.OnChecking;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnCollapsed: TVTChangeEvent;

begin
  Result := FTreePopup.OnCollapsed;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnCollapsing: TVTChangingEvent;

begin
  Result := FTreePopup.OnCollapsing;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnColumnResize: TVTHeaderNotifyEvent;

begin
  Result := FTreePopup.OnColumnResize;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnHeaderDraw: TVTHeaderPaintEvent;

begin
  Result := FTreePopup.OnHeaderDraw;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnExpanded: TVTChangeEvent;

begin
  Result := FTreePopup.OnExpanded;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnExpanding: TVTChangingEvent;

begin
  Result := FTreePopup.OnExpanding;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnFreeNode: TVTFreeNodeEvent;

begin
  Result := FTreePopup.OnFreeNode;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnGetHint: TVSTGetTextEvent;

begin
  Result := FTreePopup.OnGetHint;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnGetImageIndex: TVTGetImageEvent;

begin
  Result := FTreePopup.OnGetImageIndex;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnGetNodeDataSize: TVTGetNodeDataSizeEvent;

begin
  Result := FTreePopup.OnGetNodeDataSize;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnGetText: TVSTGetTextEvent;

begin
  Result := FTreePopup.OnGetText;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnHeaderClick: TVTHeaderClickEvent;

begin
  Result := FTreePopup.OnHeaderClick;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnInitChildren: TVTInitChildrenEvent;

begin
  Result := FTreePopup.OnInitChildren;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetOnInitNode: TVTInitNodeEvent;

begin
  Result := FTreePopup.OnInitNode;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.ReadSeparator(Reader: TReader);

var
  Value: WideString;

begin
  case Reader.NextValue of
    vaLString, vaString:
      Value := Reader.ReadString;
  else
    Value := Reader.ReadWideString;
  end;

  if Length(Value) > 0 then
    Separator := Value[1];
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.ReadTree(Stream: TStream);

begin
  Stream.ReadComponent(FTreePopup);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetImages(const Value: TImageList);

begin
  if FImages <> Value then
  begin
    if Assigned(FImages) then
      FImages.UnRegisterChanges(FImageChangeLink);
    FImages := Value;
    FTreePopup.Images := Value;
    if Assigned(FImages) then
      FImages.RegisterChanges(FImageChangeLink);
    if not (csLoading in ComponentState) then
      Invalidate;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------


procedure TCustomVirtualTreeComboBox.SetOnPaintText(const Value: TVTPaintText);
begin
  FTreePopup.OnPaintText := Value;
end;


procedure TCustomVirtualTreeComboBox.SetOnAfterCellPaint(const Value: TVTAfterCellPaintEvent);

begin
  FTreePopup.OnAfterCellPaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnAfterItemErase(const Value: TVTAfterItemEraseEvent);

begin
  FTreePopup.OnAfterItemErase := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnAfterItemPaint(const Value: TVTAfterItemPaintEvent);

begin
  FTreePopup.OnAfterItemPaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnAfterPaint(const Value: TVTPaintEvent);

begin
  FTreePopup.OnAfterPaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnBeforeCellPaint(const Value: TVTBeforeCellPaintEvent);

begin
  FTreePopup.OnBeforeCellPaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnBeforeItemErase(const Value: TVTBeforeItemEraseEvent);

begin
  FTreePopup.OnBeforeItemErase := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnBeforeItemPaint(const Value: TVTBeforeItemPaintEvent);

begin
  FTreePopup.OnBeforeItemPaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnBeforePaint(const Value: TVTPaintEvent);

begin
  FTreePopup.OnBeforePaint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnChecked(Value: TVTChangeEvent);

begin
  FTreePopup.OnChecked := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnChecking(Value: TVTCheckChangingEvent);

begin
  FTreePopup.OnChecking := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnCollapsed(Value: TVTChangeEvent);

begin
  FTreePopup.OnCollapsed := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnCollapsing(Value: TVTChangingEvent);

begin
  FTreePopup.OnCollapsing := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnColumnResize(Value: TVTHeaderNotifyEvent);

begin
  FTreePopup.OnColumnResize := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnExpanded(Value: TVTChangeEvent);

begin
  FTreePopup.OnExpanded := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnExpanding(Value: TVTChangingEvent);

begin
  FTreePopup.OnExpanding := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnFreeNode(Value: TVTFreeNodeEvent);

begin
  FTreePopup.OnFreeNode := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnGetHint(Value: TVSTGetTextEvent);

begin
  FTreePopup.OnGetHint := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnGetImageIndex(Value: TVTGetImageEvent);

begin
  FTreePopup.OnGetImageIndex := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnGetNodeDataSize(Value: TVTGetNodeDataSizeEvent);

begin
  FTreePopup.OnGetNodeDataSize := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnGetText(Value: TVSTGetTextEvent);

begin
  FTreePopup.OnGetText := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnHeaderClick(Value: TVTHeaderClickEvent);

begin
  FTreePopup.OnHeaderClick := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnHeaderDraw(Value: TVTHeaderPaintEvent);

begin
  FTreePopup.OnHeaderDraw := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnInitChildren(Value: TVTInitChildrenEvent);

begin
  FTreePopup.OnInitChildren := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetOnInitNode(Value: TVTInitNodeEvent);

begin
  FTreePopup.OnInitNode := Value;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetSeparator(const Value: WideChar);

begin
  if FSeparator <> Value then
  begin
    FSeparator := Value;
    if not (csLoading in ComponentState) then
      ParseTree;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetTree(const Value: TTreePopup);

begin
  // Fake method to make the tree appear in the object inspector.
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.WriteSeparator(Writer: TWriter);

begin
  with Writer do
    WriteWideString(FSeparator);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.WriteTree(Stream: TStream);

begin
  Stream.WriteComponent(FTreePopup);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.CMCancelMode(var Message: TCMCancelMode);

begin
  if Message.Sender <> Self then
    DroppedDown := False;
  inherited;  //##fe?
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.CMMouseWheel(var Message: TCMMouseWheel);

var
  ScrollCount: Integer;
  Node: PVirtualNode;
  NextNode: function(Node: PVirtualNode): PVirtualNode of object;

begin
  if cbsDroppedDown in FStates then
    FTreePopup.WndProc(TMessage(Message))
  else
  begin
    inherited;

    if Message.Result = 0 then
      with Message, FTreePopup do
      begin
        Result := 1;
        // Advance nodes depending on WheelDelta.
        ScrollCount := -WheelDelta div WHEEL_DELTA;
        Node := FocusedNode;
        if ScrollCount > 0 then
          NextNode := GetNext
        else
        begin
          NextNode := GetPrevious;
          ScrollCount := -ScrollCount;
        end;

        while ScrollCount > 0 do
        begin
          Node := NextNode(Node);
          Dec(ScrollCount);
        end;
        FocusedNode := Node;
        Selected[Node] := True;
      end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.WMSize(var Message: TWMSize);

begin
  inherited;

  FTreePopup.Width := Width;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.ApplicationMessageHook(var Msg: TMessage): Boolean;

// Hides dropdown if user switches to another application.

begin
  Result := False;
  if DroppedDown then
  begin
    if ((Msg.Msg = WM_ACTIVATEAPP) and not TWMActivateApp(Msg).Active) then
    begin
      DroppedDown := False;
      Result := True;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.DefineProperties(Filer: TFiler);

begin
  inherited;

  Filer.DefineProperty('SeparatorData', ReadSeparator, WriteSeparator, FSeparator <> ',');
  Filer.DefineBinaryProperty('TreePopupData', ReadTree, WriteTree, True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.DoSetDroppedDown(Value: Boolean);

const
  StepCount = 32;

var
  I, StepSize: Integer;
  BackBitmap: TBitmap;
  R, ButtonR: TRect;
  ScreenDC: HDC;
  S: WideString;

begin
  inherited;

  if Value then
  begin
    // Paint a pressed button.
    FButtonState := vbsPressed;
    ButtonR := Rect(Width - GetSystemMetrics(SM_CXVSCROLL) - 4, 0, Width, Height);
    RepaintWindow(@ButtonR);

    // Do an animated drop down.
    FTreePopup.FPopupAbove := GetDropDownRect(R);
    with R do
    begin
      BackBitmap := TBitmap.Create;
      BackBitmap.PixelFormat := pf32Bit;
      ScreenDC := GetDC(0);

      try
        BackBitmap.Width := Right - Left;
        BackBitmap.Height := Bottom - Top;
        with FTreePopup do
          ScrollIntoView(FocusedNode, False);
        StepSize := BackBitmap.Height div StepCount;

        if not (IsWin2K or IsWinXP or IsWin98) then
        begin
          with FTreePopup do
            Perform(WM_PRINT, wParam(BackBitmap.Canvas.Handle), PRF_NONCLIENT or PRF_CLIENT);
          if FTreePopup.FPopupAbove then
          begin
            for I := 1 to StepCount do
            begin
              BitBlt(ScreenDC, Left, Top + BackBitmap.Height - I * StepSize, BackBitmap.Width, I * StepSize,
                BackBitmap.Canvas.Handle, 0, 0, SRCCOPY);
              Sleep(1);
            end;
          end
          else
          begin
            for I := 1 to StepCount do
            begin
              BitBlt(ScreenDC, Left, Top, BackBitmap.Width, I * StepSize, BackBitmap.Canvas.Handle, 0, BackBitmap.Height -
                I * StepSize, SRCCOPY);
              Sleep(1);
            end;
          end;
          SetWindowPos(FTreePopup.Handle, 0, Left, Top, Right - Left, Bottom - Top, SWP_SHOWWINDOW or SWP_NOACTIVATE);
        end
        else
        begin
          SetWindowPos(FTreePopup.Handle, 0, Left, Top, Right - Left, Bottom - Top, SWP_NOACTIVATE);
          AnimateWindow(FTreePopup.Handle, FAnimationDuration, AW_BLEND);
          RedrawWindow(FTreePopup.Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE);
        end;
        SetCapture(FTreePopup.Handle);
      finally
        ReleaseDC(0, ScreenDC);
        BackBitmap.Free;
        FButtonState := vbsNormal;
      end;
    end;
    RepaintWindow(@ButtonR);
  end
  else
  begin
    ReleaseCapture;

    //##fe speed up painting before Onchange handle gets called - does it work with vcsDropDown as well?
    S := BuildTextFromTree;
    FText := S;
    RepaintWindow(nil);
    FText := '';
    //##fe

    if IsWin2K or IsWinXP or IsWin98 then
      AnimateWindow(FTreePopup.Handle, FAnimationDuration, AW_BLEND or AW_HIDE)
    else
      ShowWindow(FTreePopup.Handle, SW_HIDE);

    ParseTree;
    SelectAll;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetPopupWindow: HWND;

begin
  Result := FTreePopup.Handle;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.GetTextRect: TRect;

// Returns a smaller text rectangle for list mode if there are images to draw.

begin
  Result := inherited GetTextRect;
  if Assigned(FImages) and not (vcoMultiSelection in FOptions) and Assigned(FPaintNode) then
    Inc(Result.Left, 4 + FImages.Width); // leave a margin of 2 pixels left and right
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.ImageListChange(Sender: TObject);

begin
  if not (csDestroying in ComponentState) then
    Invalidate;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.OptionsChanged;

begin
  inherited;

  with FTreePopup.TreeOptions do
    if vcoMultiselection in Options then
      MiscOptions := MiscOptions + [toCheckSupport, toToggleOnDblClick]
    else
      MiscOptions := MiscOptions - [toCheckSupport, toToggleOnDblClick]
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.ParseText;

// If multi selection is enabled then this method attempts to split the current text of the combobox into
// node caption and checks the appropriate nodes in the tree popup.

  //--------------- local function --------------------------------------------

  procedure AddNodeToList(Node: PVirtualNode);

  // Checks if the given node is already in the internal node list and adds it if not.

  var
    I: Integer;

  begin
    I := 0;
    while I < Length(FNodes) do
    begin
      if Node = FNodes[I] then
        Break;
      Inc(I);
    end;

    if I = Length(FNodes) then
    begin
      SetLength(FNodes, I + 1);
      FNodes[I] := Node;
    end;
  end;

  //--------------- end local function ----------------------------------------

var
  Node: PVirtualNode;
  Head, Tail: PWideChar;
  S: WideString;

begin
  // Free previously collected values.
  FNodes := nil;
  if vcoMultiselection in FOptions then
  begin
    // Multiple items may be given. Set checked state for each corresponding node.
    Head := PWideChar(FText);
    while Head^ <> WideNull do
    begin
      Tail := Head;
      // Skip any white spaces.
      while (Tail^ <> WideNull) and UnicodeIsWhiteSpace(Word(Tail^)) do
        Inc(Tail);

      Head := Tail;
      if Tail^ <> WideNull then
      begin
        // Collect everything until the end of the string or the next separator character.
        while not (Tail^ in [WideNull, FSeparator]) do
          Inc(Tail);
        // If there was a valid string the search for it in the tree.
        if Tail - Head > 0 then
        begin
          SetString(S, Head, Tail - Head);
          Node := FTreePopup.IterateSubtree(nil, CompareCaptions, PWideChar(S), [], True);
          if Assigned(Node) then
            AddNodeToList(Node);
        end;
        // Finally skip separator character and continue with next part.
        if Tail^ = FSeparator then
          Inc(Tail);
        Head := Tail;
      end;
    end;

    // Once the collection is ready we can iterate through the tree and set check states accordingly.
    FTreePopup.IterateSubtree(nil, DoNodeChecking, nil, [], True);
  end
  else
  begin
    // Single select only. Try to find the first corresponding node and select/focus it.
    Node := FTreePopup.IterateSubtree(nil, CompareCaptionsPartial, PWideChar(FText), [], True);
    if Assigned(Node) then
    begin
      SetLength(FNodes, 1);
      FNodes[0] := Node;

      with FTreePopup do
      begin
        VisiblePath[Node] := True;
        FocusedNode := Node;
        Selected[Node] := True;
        ScrollIntoView(Node, False);
      end;
    end
    else
      FTreePopup.ClearSelection;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function TCustomVirtualTreeComboBox.BuildTextFromTree: WideString;

var
  Run: PVirtualNode;

begin
  Result := '';
  with FTreePopup do
  begin
    if vcoMultiselection in FOptions then
    begin
      // Go through all nodes in the tree.
      Run := GetFirst;
      while Assigned(Run) do
      begin
        if Run.CheckState = csCheckedNormal then
          Result := Result + FSeparator + ' ' + Text[Run, Header.MainColumn];
        Run := GetNext(Run);
      end;
      if Length(Result) > 0 then
        Delete(Result, 1, 2);
    end
    else
    begin
      if Assigned(FocusedNode) then
        Result := Text[FocusedNode, Header.MainColumn];
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.ParseTree;

// Collects a list of node captions into the Text property, depending on enabled multiselection.

begin
  Text := BuildTextFromTree;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.SetText(const Value: WideString);

// Whenever new text is set we try to select/check the corresponding item in the popup treeview (if enabled).

begin
  inherited;

  if (vcoAutoSelect in FOptions) and not (cbsAutoSelecting in FStates) then
    ParseText;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.Clear;

begin
  inherited Clear;
  FTreePopup.Clear;
  FNodes := nil;
  Invalidate;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TCustomVirtualTreeComboBox.Paint;

var
  R: TRect;
  Ghosted: Boolean;
  Index: Integer;

begin
  FPaintNode := nil;
  if cbsDroppedDown in FStates then
    FPaintNode := FTreePopup.HotNode;
  if FPaintNode = nil then
    FPaintNode := FTreePopup.GetFirstSelected;

  inherited;

  // If there are images to show then display the image of the currently focused node.
  if Assigned(FImages) and not (vcoMultiSelection in FOptions) then
  begin
    R := GetTextRect;
    R.Right := R.Left;
    R.Left := 0;
    with Canvas do
    begin
      Brush.Color := Color;
      FillRect(R);

      if Assigned(FPaintNode) then
      begin
        FTreePopup.DoGetImageIndex(FPaintNode, ikNormal, FTreePopup.Header.MainColumn, Ghosted, Index);
        if Index > -1 then
          FImages.Draw(Canvas, R.Left + 1, R.Top, Index, Enabled);
      end;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

var
  User32Handle: THandle;

initialization
  InitThemeLibrary;
  if IsWin2K or IsWinXP or IsWin98 then
  begin
    // Bind functions which are not available on all platforms dynamically.
    User32Handle := LoadLibrary('User32.DLL');
    @AnimateWindow := GetProcAddress(User32Handle, 'AnimateWindow');
  end;
finalization
  FreeLibrary(User32Handle);
  FreeThemeLibrary;
end.