File: VirtualExplorerListviewEx.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 (6334 lines) | stat: -rw-r--r-- 217,375 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
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
unit VirtualExplorerListviewEx;

{==============================================================================
Version 1.4.4
(VirtualShellTools release 1.1.x)

Software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
either express or implied.
The initial developer of this code is Robert Lee.

Requirements:
  - Mike Lischke's Virtual Treeview (VT)
    http://www.lischke-online.de/VirtualTreeview/VT.html
  - Jim Kuenaman's Virtual Shell Tools (VSTools)
    http://groups.yahoo.com/group/VirtualExplorerTree
  - Mike Lischke's Theme Manager 1.9.0 or above (ONLY for Delphi 5 or Delphi 6)
  - Comctl32.dll v.5.81 (Internet Explorer 5.00) or later is required for the VCL
    Listview to work as expected in Thumbnail viewstyle.

Credits:
  Special thanks to Mike Lischke (VT) and Jim Kuenaman (VSTools) for the
  magnificent components they made available to the Delphi community.
  Thanks to (in alphabetical order):
    Aaron, Adem Baba (ImageMagick conversion), Nils Haeck (ImageMagick wrapper),
    Gerald Kder (bugs hunter), Werner Lehmann (Thumbs Cache),
    Bill Miller (HyperVirtualExplorer), Renate Schaaf (Graphics guru),
    Boris Tadjikov (bugs hunter), Milan Vandrovec (CBuilder port),
    Philip Wand, Troy Wolbrink (Unicode support).

Known issues:
  - If the Anchors property is changed at runtime and the ViewStyle is not
    vsxReport SyncOptions must be called.
  - If the node selection is changed at runtime and the ViewStyle is not
    vsxReport SyncSelected must be called.
  - If ComCtrl 6 is used the scrollbars are not invalidated correctly when
    the BevelKind <> bkNone, and the ViewStyle <> vsxReport.
    This is a VCL bug.
  - If ComCtrl 6 is used the Listview standard hints are not correctly painted
    (only the first line is showed), this happens only when ViewStyle <> vsxReport.
    This is a VCL bug.

Development notes:
  - Don't use PaintTo, WinXP doesn't support it.
  - Don't use DrawTextW, Win9x doesn't support it, instead use:
    if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then Windows.DrawText(...)
    else Windows.DrawTextW(...);
  - Don't use Item.DisplayRect, use TUnicodeOwnerDataListView.GetLVItemRect
    instead, ComCtrl 6 returns the item rect adding the item space.
  - Bug in Delphi 5 TGraphic class: when creating a bitmap by using its class
    type (TGraphicClass) it doesn't calls the TBitmap constructor.
    That's because in Delphi 5 the TGraphic.Create is protected, and
    TBitmap.Create is public, so TGraphicClass(ABitmap).Create will NOT call
    TBitmap.Create because it's not visible by TGraphicClass.
    To fix this we need to make it visible by creating a TGraphicClass cracker.
    Fixed in LoadGraphic helper.
    More info on:
    http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00000331.0164178b%40xmission.com

VCL TListview bugs fixed by VELVEx:
  - TListview bug: setting ShowHint to False doesn't disable the hints.
    Fixed in TSyncListView.CMShowHintChanged.
  - TListview bug: if the ClientHeight is too small to fit 2 items the
    PageUp/PageDown key buttons won't work.
    To fix this I had to fake these keys to Up/Down in TSyncListView.KeyDown.
  - TListview bug only in Delphi 7: the Listview invalidates the canvas when
    scrolling, the problem is in ComCtrls.pas: TCustomListView.WMVScroll.
    Fixed in TSyncListView.WMVScroll, I had to call the TWinControl WM_VSCROLL
    handler, sort of inherited-inherited.
    Contact Mike Lischke, this was introduced by D7 ThemeManager engine.
  - TListview bug only in Win2K and WinXP: the Listview Edit control is not
    showed correctly when the font size is large (Height > 15), this is visible
    in vsReport, vsList and vsSmallIcon viewstyles. We must reshow the Edit
    control.
    Fixed in TUnicodeOwnerDataListView.CNNotify with LVN_BEGINLABELEDIT and
    LVN_BEGINLABELEDITW messages.
  - TListview bug only on WinXP using ComCtl 6: a thick black border around
    the edit box is showed when editing an item in the list.
    Fixed in TUnicodeOwnerDataListView.WMCtlColorEdit.
  - OwnerData TListview bug on WinXP using ComCtl 6: it has to invalidate its
    Canvas on resizing.
    Fixed in TUnicodeOwnerDataListView.WMWindowPosChanging.
    This is fixed on Delphi 2005:
    http://qc.borland.com/qc/wc/wc.exe/details?ReportID=5920
  - OwnerData TListview bug on WinXP using ComCtl 6: Item.DisplayRect(drBounds)
    returns an incorrect Rect, the R.Left and R.Right includes the item spacing,
    this problem is related with the selectable space between icons issue.
    This is corrected in TUnicodeOwnerDataListView.GetLVItemIconRect.
  - OwnerData TListview bug on WinXP using ComCtl 6: the white space between
    icons (vsxIcon or vsxThumbs) becomes selectable, but not the space between
    the captions.
    This is related to previous bug.
    Fixed in TUnicodeOwnerDataListView.WndProc.
  - OwnerData TListview bug: when the Listview is small enough to not fit 2 fully
    visible items the PageUp/PageDown buttons don't work.
    Fixed in TSyncListView.KeyDown.
  - OwnerData TListview bug: when Shift-Selecting an item, it just selects all
    the items from the last selected to the current selected, index wise, it
    should box-select the items.
    Fixed in TSyncListView.OwnerDataStateChange, KeyMultiSelectEx and
    MouseMultiSelectEx.
  - OwnerData TListview bug: the OnAdvancedCustomDrawItem event doesn't catch
    cdPostPaint paint stage.
    Fixed in TSyncListView.CNNotify.
  - OwnerData TListview bug: when the Listview is unfocused and a previously
    selected item caption is clicked it enters in editing mode. This is an
    incorrect TListview behavior.
    To fix this issue I set a flag: FPrevEditing in TSyncListView.CMEnter and
    deactivate it in TSyncListView.CanEdit and when the selection changes in
    TSyncListView.CNNotify.
  - OwnerData TListview bug: the virtual TListView raises an AV in vsReport mode.
    Fixed in TSyncListView.LVMInsertColumn and TSyncListView.LVMSetColumn.
  - OwnerData TListview bug: when the icon arrangement is iaLeft the arrow keys
    are scrambled.
    Fixed in TSyncListView.KeyDown.

To Do
  -

History:
21 December 2004 - version 1.4.4
  - Added EditFile method, to easily browse for a file to select it and begin
    to edit it.
  - Fixed incorrect checkboxes sync.
  - Fixed incorrect mouse button click handling when ComCtrls 6 is used,
    thanks to Gabriel Cristescu for reporting this.

27 August 2004 - version 1.4.3
  - Added checkbox support for vsxThumbs viewstyle.
  - Added partial background image support to non vsxReport ViewStyles, the
    background should be loaded in the listview using the ListView_SetBkImage
    API:
    var
      BK: TLVBKImage;
    begin
      // LVBKIF_SOURCE_HBITMAP flag is not supported by ListView_SetBkImage
      // TLVBKImage.hbm is not supported by ListView_SetBkImage
      Fillchar(BK, SizeOf(BK), 0);
      BK.ulFlags := LVBKIF_SOURCE_URL or LVBKIF_STYLE_TILE;
      BK.pszImage := PChar(Edit1.text);
      ListView_SetBkImage(LV.ChildListview.Handle, @BK);
    end;

23 May 2004 - version 1.4.2
  - Added support for toHideOverlay and toRestoreTopNodeOnRefresh properties.
  - Added new property: ThumbsOptions.CacheOptions.CacheProcessing to allow
    ascending or descending sorting of the thread cache processing list.
    When this property is tcpAscending the top files in the listview are
    thumbnailed first.
  - Fixed incorrect selection painting, it now uses the values in
    Colors.FocusedSelectionColor and Colors.UnFocusedSelectionColor.
  - Fixed an incorrect call to OnEditCancelled.
  - Reworked the internal cache events.

5 March 2004 - version 1.4.1
  - Compatible with VSTools 1.1.15
  - Fixed drag and drop synchronization, it now correctly fires OnDragDrop
    event when the ViewStyle <> vsxReport.
  - Fixed incorrect icon spacing when the handle is recreated.

==============================================================================}

interface

{$include ..\Include\Compilers.inc}
{$include ..\Include\VSToolsAddIns.inc}

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, ComCtrls, ImgList,
  Dialogs, Forms, VirtualTrees, VirtualExplorerTree, VirtualShellutilities,
  ActiveX, Commctrl, VirtualUtilities, VirtualUnicodeDefines, VirtualWideStrings,
  ShlObj, VirtualResources, VirtualShellTypes, VirtualSystemImageLists,
  VirtualIconThread, // Got to have it for the Thumbnail thread
  {$IFDEF USEGRAPHICEX} GraphicEx, {$ELSE}
    {$IFDEF USEIMAGEEN} ImageEnIo, {$ELSE}
    {$IFDEF USEIMAGEMAGICK} MagickImage, ImageMagickAPI, {$ENDIF}
    {$ENDIF}
  {$ENDIF}
  VirtualUnicodeControls, JPeg, ComObj;

const
  SCROLL_DELAY_TIMER = 100;
  SCROLL_TIMER = 101;
  WM_VLVEXTHUMBTHREAD = WM_SHELLNOTIFY + 100;

  {
  // TListView Extended Styles
  LVS_EX_LABELTIP     = $00004000;  // Partially hidden captions hint
  LVS_EX_BORDERSELECT = $00008000;  // Highlight the border when selecting items
  // TListView Extended Styles for ComCtl32.dll version 6
  // LVS_EX_DOUBLEBUFFER = $00010000;  // Enables alpha blended selection, defined in VirtualShellTypes
  LVS_EX_HIDELABELS   = $00020000;  // Hide the captions, like Shift clicking Thumbnails viewstyle option in Explorer
  LVS_EX_SINGLEROW    = $00040000;  // Like thumb stripes mode
  LVS_EX_SNAPTOGRID   = $00080000;  // Snaps the icons to grid
  LVS_EX_SIMPLESELECT = $00100000;  // ?
  }

type
  TCustomVirtualExplorerListviewEx = class;
  TThumbsCacheItem = class;
  TThumbsCache = class;

  TIconSpacing = record
    X: Word;
    Y: Word;
  end;

  TIconAttributes = record
    Size: TPoint;
    Spacing: TIconSpacing;
  end;

  TThumbnailState = (
    tsEmpty,           //empty data
    tsProcessing,      //processing thumbnail
    tsValid,           //valid image
    tsInvalid);        //not an image

  TThumbnailBorder = (tbNone, tbRaised, tbDoubleRaised, tbSunken,
    tbDoubleSunken, tbBumped, tbEtched, tbFramed);

  TThumbnailHighlight = (thNone, thSingleColor, thMultipleColors);

  TThumbnailImageLibrary = (timNone, timGraphicEx, timImageEn, timEnvision, timImageMagick);

  TViewStyleEx = (vsxIcon, vsxSmallIcon, vsxList, vsxReport, vsxThumbs);

  TThumbsCacheStorage = (tcsCentral, tcsPerFolder);

  TThumbsCacheProcessing = (tcpAscending, tcpDescending);

  PThumbnailData = ^TThumbnailData;
  TThumbnailData = packed record
    CachePos: integer;
    Reloading: Boolean;
    State: TThumbnailState;
  end;

  PThumbnailThreadData = ^TThumbnailThreadData;
  TThumbnailThreadData = packed record
    ImageWidth: integer;
    ImageHeight: integer;
    State: TThumbnailState;
    MemStream: TMemoryStream;
    CompressedStream: Boolean;
  end;

  TOLEListviewButtonState = (
    LButtonDown,
    RButtonDown,
    MButtonDown
  );
  TOLEListviewButtonStates = set of TOLEListviewButtonState;

  TRectArray = array of TRect;

  TLVThumbsDraw = procedure(Sender: TCustomVirtualExplorerListviewEx; ACanvas: TCanvas;
    ListItem: TListItem; ThumbData: PThumbnailData; AImageRect, ADetailsRect: TRect;
    var DefaultDraw: Boolean) of object;

  TLVThumbsDrawHint = procedure(Sender: TCustomVirtualExplorerListviewEx; HintBitmap: TBitmap;
    Node: PVirtualNode; var DefaultDraw: Boolean) of object;

  TLVThumbsGetDetails = procedure(Sender: TCustomVirtualExplorerListviewEx; Node: PVirtualNode;
    HintDetails: Boolean; var Details: WideString) of object;

  TLVThumbsCacheItemReadEvent = procedure(Sender: TCustomVirtualExplorerListviewEx;
    Filename: WideString; Thumbnail: TBitmap; var DoDefault: Boolean) of object;

  TLVThumbsCacheItemLoadEvent = procedure(Sender: TCustomVirtualExplorerListviewEx;
    NS: TNamespace; CacheItem: TThumbsCacheItem; var DoDefault: Boolean) of object;

  TLVThumbsCacheItemProcessingEvent = procedure(Sender: TCustomVirtualExplorerListviewEx;
    NS: TNamespace; Thumbnail: TBitmap; var ImageWidth, ImageHeight: Integer; var DoDefault: Boolean) of object;

  TLVThumbsCacheEvent = procedure(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList; var DoDefault: Boolean) of object;

  TExtensionsList = class(TWideStringList)
  private
    function GetColors(Index: integer): TColor;
    procedure SetColors(Index: integer; const Value: TColor);
  public
    constructor Create; virtual;
    function Add(const Extension: WideString; HighlightColor: TColor): Integer; reintroduce;
    function AddObject(const S: WideString; AObject: TObject): Integer; override;
    function IndexOf(const S: WideString): Integer; override;
    function DeleteString(const S: WideString): Boolean; virtual;
    property Colors[Index: integer]: TColor read GetColors write SetColors;
  end;

  TBitmapHint = class(THintWindow)
  private
    FHintBitmap: TBitmap;
    FActivating: Boolean;
    procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
    procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
  protected
    procedure Paint; override;
  public
    property Activating: Boolean read FActivating;
    procedure ActivateHint(Rect: TRect; const AHint: string); override;
    procedure ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer); override;
  end;

  TThumbsCacheItem = class
  private
    FFileDateTime: TDateTime;
    FImageWidth: Integer;
    FImageHeight: Integer;
    FExif: WideString;
    FComment: WideString;
    FCompressed: Boolean;
    FThumbImageStream: TMemoryStream;
    FStreamSignature: WideString;
  protected
    FFilename: WideString;
    procedure Changed; virtual;
    function DefaultStreamSignature: WideString; virtual;

    property CompressedThumbImageStream: Boolean read FCompressed write FCompressed;
    property ThumbImageStream: TMemoryStream read FThumbImageStream;
  public
    constructor Create(AFilename: WideString); virtual;
    constructor CreateFromStream(ST: TStream); virtual;
    destructor Destroy; override;
    procedure Assign(CI: TThumbsCacheItem); virtual;
    procedure Fill(AFileDateTime: TDateTime; AExif, AComment: WideString;
      AImageWidth, AImageHeight: Integer; ACompressed: Boolean;
      AThumbImageStream: TMemoryStream);
    function LoadFromStream(ST: TStream): Boolean; virtual;
    procedure SaveToStream(ST: TStream); virtual;

    function ReadBitmap(OutBitmap: TBitmap): Boolean;
    procedure WriteBitmap(ABitmap: TBitmap; CompressIt: Boolean);

    property Comment: WideString read FComment write FComment;
    property Exif: WideString read FExif write FExif;
    property Filename: WideString read FFilename;
    property FileDateTime: TDateTime read FFileDateTime write FFileDateTime;
    property ImageWidth: Integer read FImageWidth write FImageWidth;
    property ImageHeight: Integer read FImageHeight write FImageHeight;
    property StreamSignature: WideString read FStreamSignature;
  end;

  TThumbsCacheItemClass = class of TThumbsCacheItem;

  TThumbsCache = class
  private
    FDirectory: WideString;
    FLoadedFromFile: Boolean;
    FStreamVersion: Integer;
    FSize: Integer;
    FInvalidCount: Integer;
    FThumbWidth: Integer;
    FThumbHeight: Integer;
    FComments: TWideStringList;
    function GetCount: integer;
  protected
    FHeaderFilelist: TWideStringList; //List of filenames encoded like: "filename*comment", it owns TMemoryStreams
    FScreenBuffer: TWideStringList; //List of filenames, owns TBitmaps, it's a cache to speed screen rendering
    function DefaultStreamVersion: integer; virtual;
  public
    constructor Create; virtual;
    destructor Destroy; override;
    procedure Clear;
    function IndexOf(Filename: WideString): integer;
    function Add(Filename: WideString; CI: TThumbsCacheItem): Integer; overload;
    function Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime;
      AImageWidth, AImageHeight: Integer; ACompressIt: Boolean;
      AThumbImage: TBitmap): Integer; overload;
    function Add(Filename, AExif, AComment: WideString; AFileDateTime: TDateTime;
      AImageWidth, AImageHeight: Integer; ACompressed: Boolean;
      AThumbImageStream: TMemoryStream): Integer; overload;
    procedure Assign(AThumbsCache: TThumbsCache);
    function Delete(Filename: WideString): boolean;
    function Read(Index: integer; var OutCacheItem: TThumbsCacheItem): Boolean; overload;
    function Read(Index: integer; OutBitmap: TBitmap): Boolean; overload;
    procedure LoadFromFile(const Filename: WideString); overload;
    procedure LoadFromFile(const Filename: WideString; InvalidFiles: TWideStringList); overload;
    procedure SaveToFile(const Filename: WideString);
    property Directory: WideString read FDirectory write FDirectory;
    property ThumbWidth: integer read FThumbWidth write FThumbWidth;
    property ThumbHeight: integer read FThumbHeight write FThumbHeight;
    property Comments: TWideStringList read FComments;
    property Count: integer read GetCount;  //Count includes the deleted thumbs, ValidCount = Count - InvalidCount
    property InvalidCount: integer read FInvalidCount;
    property LoadedFromFile: boolean read FLoadedFromFile;
    property StreamVersion: integer read FStreamVersion;
    property Size: integer read FSize;
  end;

  TCacheList = class(TWideStringList)
  private
    FCentralFolder: WideString;
    FDefaultFilename: WideString;
    procedure SetCentralFolder(const Value: WideString);
  public
    constructor Create; virtual;
    procedure DeleteAllFiles;
    procedure DeleteInvalidFiles;
    function GetCacheFileToLoad(Dir: Widestring): WideString;
    function GetCacheFileToSave(Dir: Widestring): WideString;
    procedure SaveToFile; reintroduce;
    procedure LoadFromFile; reintroduce;
    property CentralFolder: WideString read FCentralFolder write SetCentralFolder;
    property DefaultFilename: WideString read FDefaultFilename write FDefaultFilename;
  end;

  TThumbsCacheOptions = class(TPersistent)
  private
    FOwner: TCustomVirtualExplorerListviewEx;
    FAutoSave: boolean;
    FAutoLoad: boolean;
    FCompressed: boolean;
    FStorageType: TThumbsCacheStorage;
    FDefaultFilename: WideString;
    FBrowsingFolder: WideString;
    FCacheProcessing: TThumbsCacheProcessing;
    function GetCentralFolder: WideString;
    function GetSize: integer;
    function GetThumbsCount: integer;
    procedure SetBrowsingFolder(const Value: WideString);
    procedure SetCacheProcessing(const Value: TThumbsCacheProcessing);
    procedure SetCentralFolder(const Value: WideString);
    procedure SetCompressed(const Value: boolean);
  protected
    FThumbsCache: TThumbsCache; //Cache of the browsing folder
    FCacheList: TCacheList; //List of cache files
  public
    constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual;
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
    procedure ClearCache(DeleteAllFiles: Boolean = False);
    function GetCacheFileFromCentralFolder(Dir: WideString): WideString;
    function RenameCacheFileFromCentralFolder(Dir, NewDirName: WideString; NewCacheFilename: WideString = ''): Boolean;
    procedure Reload(Node: PVirtualNode); overload;
    procedure Reload(Filename: WideString); overload;
    procedure Load(Force: Boolean = false);
    procedure Save;
    function Read(Node: PVirtualNode; var OutCacheItem: TThumbsCacheItem): Boolean; overload;
    function Read(Filename: WideString; var OutCacheItem: TThumbsCacheItem): Boolean; overload;
    function Read(Node: PVirtualNode; OutBitmap: TBitmap): Boolean; overload;
    function Read(Filename: WideString; OutBitmap: TBitmap): Boolean; overload;

    property Size: integer read GetSize;
    property ThumbsCount: integer read GetThumbsCount;
    property Owner: TCustomVirtualExplorerListviewEx read FOwner;
    property BrowsingFolder: WideString read FBrowsingFolder write SetBrowsingFolder;
  published
    property AutoLoad: boolean read FAutoLoad write FAutoLoad default False;
    property AutoSave: boolean read FAutoSave write FAutoSave default False;
    property DefaultFilename: WideString read FDefaultFilename write FDefaultFilename;
    property StorageType: TThumbsCacheStorage read FStorageType write FStorageType default tcsCentral;
    property CacheProcessing: TThumbsCacheProcessing read FCacheProcessing write SetCacheProcessing default tcpDescending;
    property CentralFolder: WideString read GetCentralFolder write SetCentralFolder;
    property Compressed: boolean read FCompressed write SetCompressed default False;
  end;

  TThumbsOptions = class(TPersistent)
  private
    FOwner: TCustomVirtualExplorerListviewEx;
    FCacheOptions: TThumbsCacheOptions;
    FThumbsIconAtt: TIconAttributes;
    FDetails: Boolean;
    FBorderOnFiles: Boolean;
    FDetailsHeight: Integer;
    FHighlightColor: TColor;
    FBorder: TThumbnailBorder;
    FHighlight: TThumbnailHighlight;
    FLoadAllAtOnce: Boolean;
    FBorderSize: Integer;
    FUseShellExtraction: Boolean;
    FShowSmallIcon: Boolean;
    FShowXLIcons: Boolean;
    FStretch: Boolean;
    FUseSubsampling: Boolean;
    function GetHeight: Integer;
    function GetSpaceHeight: Word;
    function GetSpaceWidth: Word;
    function GetWidth: Integer;
    procedure SetBorder(const Value: TThumbnailBorder);
    procedure SetBorderSize(const Value: Integer);
    procedure SetBorderOnFiles(const Value: Boolean);
    procedure SetDetailedHints(const Value: Boolean);
    procedure SetDetails(const Value: Boolean);
    procedure SetDetailsHeight(const Value: Integer);
    procedure SetHeight(const Value: Integer);
    procedure SetHighlight(const Value: TThumbnailHighlight);
    procedure SetHighlightColor(const Value: TColor);
    procedure SetSpaceHeight(const Value: Word);
    procedure SetSpaceWidth(const Value: Word);
    procedure SetWidth(const Value: Integer);
    procedure SetUseShellExtraction(const Value: Boolean);
    procedure SetShowSmallIcon(const Value: Boolean);
    procedure SetShowXLIcons(const Value: Boolean);
    procedure SetStretch(const Value: Boolean);
    procedure SetUseSubsampling(const Value: Boolean);
    function GetDetailedHints: Boolean;
    function GetHideCaptions: Boolean;
    procedure SetHideCaptions(const Value: Boolean);
  public
    constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual;
    destructor Destroy; override;
    property Owner: TCustomVirtualExplorerListviewEx read FOwner;
  published
    property Border: TThumbnailBorder read FBorder write SetBorder default tbFramed;
    property BorderSize: Integer read FBorderSize write SetBorderSize default 4;
    property BorderOnFiles: Boolean read FBorderOnFiles write SetBorderOnFiles default False;
    property Width: Integer read GetWidth write SetWidth default 120;
    property Height: Integer read GetHeight write SetHeight default 120;
    property SpaceWidth: Word read GetSpaceWidth write SetSpaceWidth default 40;
    property SpaceHeight: Word read GetSpaceHeight write SetSpaceHeight default 40;
    property DetailedHints: Boolean read GetDetailedHints write SetDetailedHints default False;
    property Details: Boolean read FDetails write SetDetails default False;
    property DetailsHeight: Integer read FDetailsHeight write SetDetailsHeight default 40;
    property HideCaptions: Boolean read GetHideCaptions write SetHideCaptions default False;
    property Highlight: TThumbnailHighlight read FHighlight write SetHighlight default thMultipleColors;
    property HighlightColor: TColor read FHighlightColor write SetHighlightColor default $EFD3D3;
    property LoadAllAtOnce: Boolean read FLoadAllAtOnce write FLoadAllAtOnce default False;
    property ShowSmallIcon: Boolean read FShowSmallIcon write SetShowSmallIcon default True;
    property ShowXLIcons: Boolean read FShowXLIcons write SetShowXLIcons default True;
    property UseShellExtraction: Boolean read FUseShellExtraction write SetUseShellExtraction default True;
    property UseSubsampling: Boolean read FUseSubsampling write SetUseSubsampling default True;
    property Stretch: Boolean read FStretch write SetStretch default False;
    property CacheOptions: TThumbsCacheOptions read FCacheOptions write FCacheOptions;
  end;

  TThumbThread = class(TVirtualImageThread)
  private
    FOwner: TCustomVirtualExplorerListviewEx;
    FThumbThreadData: TThumbnailThreadData;
    FThumbCompression: boolean;
    FThumbWidth: integer;
    FThumbHeight: integer;
    FTransparentColor: TColor;
    FThumbStretch: boolean;
    FThumbSubsampling: boolean;
  protected
    procedure ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo); override;
    procedure ExtractedInfoLoad(Info: PVirtualThreadIconInfo); override; // Load Info before being sent to Control(s)
    procedure InvalidateExtraction; override;
    procedure ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc); override;
    function CreateThumbnail(Filename: WideString; var Thumbnail: TBitmap;
      var ImageWidth, ImageHeight: integer; var CompressIt: boolean): Boolean; virtual;
  public
    constructor Create(AOwner: TCustomVirtualExplorerListviewEx); virtual;
    procedure ResetThumbOptions; virtual;
    property ThumbCompression: boolean read FThumbCompression;
    property ThumbWidth: integer read FThumbWidth;
    property ThumbHeight: integer read FThumbHeight;
    property ThumbStretch: boolean read FThumbStretch;
    property ThumbSubsampling: boolean read FThumbSubsampling;
    property TransparentColor: TColor read FTransparentColor;
    property Owner: TCustomVirtualExplorerListviewEx read FOwner;
  end;

  TThumbThreadClass = class of TThumbThread;

  TThumbThreadClassEvent = procedure(Sender: TCustomVirtualExplorerListviewEx; var ThreadClass: TThumbThreadClass) of object;

  //TUnicodeOwnerDataListView adds Unicode support to OWNER-DATA-ONLY TListview
  TUnicodeOwnerDataListView = class(TListView)
  private
    FIsComCtl6: Boolean;
    FHideCaptions: Boolean;
    FEditingItemIndex: Integer;
    procedure SetHideCaptions(const Value: Boolean);
    procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
    procedure WMCtlColorEdit(var Message: TWMCtlColorEdit); message WM_CTLCOLOREDIT;
    procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING;
  protected
    Win32PlatformIsUnicode: boolean;
    PWideFindString: PWideChar;
    CurrentDispInfo: PLVDispInfoW;
    OriginalDispInfoMask: Cardinal;
    procedure WndProc(var Msg: TMessage); override;
    procedure CreateWnd; override;
    procedure CreateWindowHandle(const Params: TCreateParams); override;
    function GetItem(Value: TLVItemW): TListItem;
    function GetItemCaption(Index: Integer): WideString; virtual; abstract;
    function GetHideCaptions: Boolean; virtual;
    property EditingItemIndex: Integer read FEditingItemIndex;
  public
    constructor Create(AOwner: TComponent); override;
    function GetLVItemRect(Index: integer; DisplayCode: TDisplayCode): TRect;
    property HideCaptions: Boolean read GetHideCaptions write SetHideCaptions default False;
    property IsComCtl6: Boolean read FIsComCtl6;
  end;

  //TSyncListView is used to sync VCL LV with VELV
  TSyncListView = class(TUnicodeOwnerDataListView)
  private
    FVETController: TCustomVirtualExplorerListviewEx;
    FSavedPopupNamespace: TNamespace;
    FFirstShiftClicked: Integer;
    FOwnerDataPause: Boolean;
    FSelectionPause: Boolean;
    FInPaintCycle: Boolean;
    FPrevEditing: Boolean;
    FDetailedHints: Boolean;
    FThumbnailHintBitmap: TBitmap;
    FDefaultTooltipsHandle: THandle;
    procedure ContextMenuCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; var Handled: Boolean);
    procedure ContextMenuShowCallback(Namespace: TNamespace; Menu: hMenu; var Allow: Boolean);
    procedure ContextMenuAfterCmdCallback(Namespace: TNamespace; Verb: WideString; MenuItemID: Integer; Successful: Boolean);
    procedure SetDetailedHints(const Value: Boolean);
    procedure UpdateHintHandle;
    procedure CNNotify(var Message: TWMNotify); message CN_NOTIFY;
    procedure CMEnter(var Message: TCMEnter); message CM_ENTER;
    procedure CMExit(var Message: TCMExit); message CM_EXIT;
    procedure CMMouseWheel(var Message: TCMMouseWheel); message CM_MOUSEWHEEL;
    procedure CMShowHintChanged(var Message: TMessage); message CM_SHOWHINTCHANGED;
    procedure LVMSetColumn(var Message: TMessage); message LVM_SETCOLUMN;
    procedure LVMInsertColumn(var Message: TMessage); message LVM_INSERTCOLUMN;
    procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
    procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
  protected
    procedure WndProc(var Msg: TMessage); override;
    procedure WMVScroll(var Message: TWMVScroll); message WM_VSCROLL;
    procedure WMHScroll(var Message: TWMHScroll); message WM_HSCROLL;
    procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
    procedure CMHintShow(var Message: TCMHintShow); message CM_HINTSHOW;

    function OwnerDataFetch(Item: TListItem; Request: TItemRequest): Boolean; override;
    function OwnerDataHint(StartIndex: Integer; EndIndex: Integer): Boolean; override;
    function OwnerDataFind(Find: TItemFind; const FindString: AnsiString;
      const FindPosition: TPoint; FindData: Pointer; StartIndex: Integer;
      Direction: TSearchDirection; Wrap: Boolean): Integer; override;
    function OwnerDataStateChange(StartIndex, EndIndex: Integer; OldState,
      NewState: TItemStates): Boolean; override;

    procedure DoContextPopup(MousePos: TPoint; var Handled: Boolean); override;
    procedure Edit(const Item: TLVItem); override;
    function CanEdit(Item: TListItem): Boolean; override;
    function GetItemCaption(Index: Integer): WideString; override;
    function GetHideCaptions: Boolean; override;
    function IsBackgroundValid: Boolean;

    procedure KeyDown(var Key: Word; Shift: TShiftState); override;
    procedure KeyPress(var Key: Char); override;
    procedure KeyUp(var Key: Word; Shift: TShiftState); override;
    procedure MouseDown(Button: TMouseButton; Shift: TShiftState;
      X: Integer; Y: Integer); override;
    procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer);
      override;
    procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
      Y: Integer); override;
    procedure DblClick; override;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure CreateHandle; override;
    function IsItemGhosted(Item: TListitem): Boolean;
    procedure FetchThumbs(StartIndex, EndIndex: integer);
    procedure UpdateArrangement;
    property DetailedHints: Boolean read FDetailedHints write SetDetailedHints default False;
    property InPaintCycle: Boolean read FInPaintCycle;
    property OwnerDataPause: boolean read FOwnerDataPause write FOwnerDataPause;
    property VETController: TCustomVirtualExplorerListviewEx read FVETController write FVETController;
  end;

  //TOLEListview adds drag & drop support to TSyncListView
  TOLEListview = class(TSyncListView, IDropTarget, IDropSource)
  private
    FDropTargetHelper: IDropTargetHelper;
    FDragDataObject: IDataObject;
    FCurrentDropIndex: integer;
    FDragging: Boolean;
    FMouseButtonState: TOLEListviewButtonStates;
    FAutoScrolling: Boolean;
    FDropped: Boolean;
    FDragItemIndex: integer;

    //Scrolling support
    FScrollDelayTimer: THandle;
    FScrollTimer: THandle;
    FAutoScrollTimerStub: Pointer;    // Stub for timer callback function
    procedure AutoScrollTimerCallback(Window: hWnd; Msg, idEvent: integer; dwTime: Longword); stdcall;
  protected
    procedure ClearTimers;
    procedure CreateDragImage(TotalDragRect: TRect; RectArray: TRectArray; var Bitmap: TBitmap);
    procedure CreateWnd; override;
    procedure DestroyWnd; override;
    function DragEnter(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall;
    function IDropTarget.DragOver = DragOverOLE; // Naming Clash
    procedure DoContextPopup(MousePos: TPoint; var Handled: Boolean); override;
    function DragOverOLE(grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall;
    function Drop(const dataObj: IDataObject; grfKeyState: Longint; pt: TPoint; var dwEffect: Longint): HResult; virtual; stdcall;
    function DragLeave: HResult; virtual; stdcall;
    function GiveFeedback(dwEffect: Longint): HResult; virtual; stdcall;
    function ListIndexToNamespace(ItemIndex: integer): TNamespace;
    function ListItemToNamespace(Item: TListItem; BackGndIfNIL: Boolean): TNamespace;
    function QueryContinueDrag(fEscapePressed: BOOL; grfKeyState: Longint): HResult; virtual; stdcall;

    procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN;
    procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP;
    procedure WMRButtonDown(var Message: TWMRButtonDown); message WM_RBUTTONDOWN;
    procedure WMRButtonUp(var Message: TWMRButtonUp); message WM_RBUTTONUP;
    procedure WMMouseMove(var Message: TWMMouseMove); message WM_MOUSEMOVE;
    procedure WMTimer(var Message: TWMTimer); message WM_TIMER;

    property CurrentDropIndex: integer read FCurrentDropIndex write FCurrentDropIndex default -2;
    property DragDataObject: IDataObject read FDragDataObject write FDragDataObject;
    property DropTargetHelper: IDropTargetHelper read FDropTargetHelper;
    property MouseButtonState: TOLEListviewButtonStates read FMouseButtonState write FMouseButtonState;
    property AutoScrolling: Boolean read FAutoScrolling;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;

    function Dragging: Boolean; reintroduce;
  end;

  TCustomVirtualExplorerListviewEx = class(TVirtualExplorerListview)
  private
    FVisible: boolean;
    FAccumulatedChanging: boolean;
    FViewStyle: TViewStyleEx;
    FThumbThread: TThumbThread;
    FImageLibrary: TThumbnailImageLibrary;
    FExtensionsList: TExtensionsList;
    FShellExtractExtensionsList: TExtensionsList;
    FExtensionsExclusionList: TExtensionsList;
    FOnThumbsDrawBefore, FOnThumbsDrawAfter: TLVThumbsDraw;
    FOnThumbsDrawHint: TLVThumbsDrawHint;
    FOnThumbsGetDetails: TLVThumbsGetDetails;
    FOnThumbsCacheItemAdd: TLVThumbsCacheItemProcessingEvent;
    FOnThumbsCacheItemRead: TLVThumbsCacheItemReadEvent;
    FOnThumbsCacheItemLoad: TLVThumbsCacheItemLoadEvent;
    FOnThumbsCacheItemProcessing: TLVThumbsCacheItemProcessingEvent;
    FOnThumbsCacheLoad: TLVThumbsCacheEvent;
    FOnThumbsCacheSave: TLVThumbsCacheEvent;
    FInternalDataOffset: Cardinal; // offset to the internal data of the ExplorerListviewEx
    FThumbsOptions: TThumbsOptions;
    FOnThumbThreadClass: TThumbThreadClassEvent;

    function GetThumbThread: TThumbThread;
    procedure SetThumbThreadClassEvent(const Value: TThumbThreadClassEvent);
    procedure SetViewStyle(const Value: TViewStyleEx);
    procedure SetVisible(const Value: boolean);
    procedure LVOnAdvancedCustomDrawItem(Sender: TCustomListView;
      Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage;
      var DefaultDraw: Boolean);
    procedure CMBorderChanged(var Message: TMessage); message CM_BORDERCHANGED;
    procedure CMShowHintChanged(var Message: TMessage); message CM_SHOWHINTCHANGED;
  protected
    FListview: TOLEListview;
    FDummyIL: TImageList;

    procedure CreateWnd; override;
    procedure RequestAlign; override;
    procedure SetParent(AParent: TWinControl); override;
    procedure SetZOrder(TopMost: Boolean); override;
    function GetClientRect: TRect; override;
    procedure Notification(AComponent: TComponent; Operation: TOperation); override;
    procedure CMBidimodechanged(var Message: TMessage); message CM_BIDIMODECHANGED;
    procedure CMCtl3DChanged(var Message: TMessage); message CM_CTL3DCHANGED;
    procedure CMColorChanged(var Message: TMessage); message CM_COLORCHANGED;
    procedure CMCursorChanged(var Message: TMessage); message CM_CURSORCHANGED;
    procedure CMEnabledchanged(var Message: TMessage); message CM_ENABLEDCHANGED;
    procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
    procedure WMNCDestroy(var Message: TWMNCDestroy); message WM_NCDESTROY;
    {$IFDEF THREADEDICONS}
    procedure WMVTSetIconIndex(var Msg: TWMVTSetIconIndex); message WM_VTSETICONINDEX;
    {$ENDIF}
    procedure WMVLVExThumbThread(var Message: TMessage); message WM_VLVEXTHUMBTHREAD;

    //VirtualTree methods
    procedure DoInitNode(Parent, Node: PVirtualNode; var InitStates: TVirtualNodeInitStates); override;
    procedure DoFreeNode(Node: PVirtualNode); override;
    procedure RebuildRootNamespace; override;
    procedure DoRootChanging(const NewRoot: TRootFolder; Namespace: TNamespace; var Allow: Boolean); override;
    procedure DoStructureChange(Node: PVirtualNode; Reason: TChangeReason); override;
    procedure ReReadAndRefreshNode(Node: PVirtualNode; SortNode: Boolean); override;
    procedure DoBeforeCellPaint(Canvas: TCanvas; Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect); override;
    function InternalData(Node: PVirtualNode): Pointer;
    function IsAnyEditing: Boolean; override;

    //Thumbnails processing
    function IsValidChildListview: boolean;
    function GetThumbThreadClass: TThumbThreadClass; virtual;

    //Thumbnails cache
    function DoThumbsCacheItemAdd(NS: TNamespace; Thumbnail: TBitmap; ImageWidth, ImageHeight: Integer): Boolean; virtual; // A Thumbnail is about to be added to the cache
    function DoThumbsCacheItemLoad(NS: TNamespace; var CacheItem: TThumbsCacheItem): Boolean; virtual; // A Thumbnail was loaded from the cache
    function DoThumbsCacheItemRead(Filename: WideString; Thumbnail: TBitmap): Boolean; virtual; // A Thumbnail must be read from the cache
    function DoThumbsCacheItemProcessing(NS: TNamespace; Thumbnail: TBitmap; var ImageWidth, ImageHeight: Integer): Boolean; virtual; // A Thumbnail must be created
    function DoThumbsCacheLoad(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; virtual; // The cache was loaded from file
    function DoThumbsCacheSave(Sender: TThumbsCache; CacheFilePath: WideString; Comments: TWideStringList): Boolean; virtual; // The cache is about to be saved

    procedure ResetThumbImageList(ResetSpacing: boolean = True);
    procedure ResetThumbSpacing;
    procedure ResetThumbThread;

    //Thumbnails drawing
    function GetDetailsString(Node: PVirtualNode; ThumbFormatting: Boolean = True): WideString;
    function DoThumbsGetDetails(Node: PVirtualNode; HintDetails: Boolean): WideString;
    procedure DoThumbsDrawBefore(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData;
      AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); virtual;
    procedure DoThumbsDrawAfter(ACanvas: TCanvas; ListItem: TListItem; ThumbData: PThumbnailData;
      AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean); virtual;
    function DoThumbsDrawHint(HintBitmap: TBitmap; Node: PVirtualNode): Boolean;
    procedure DrawThumbBG(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect);
    procedure DrawThumbFocus(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; R: TRect);
    procedure DrawIcon(ACanvas: TCanvas; Item: TListItem; ThumbData: PThumbnailData; RThumb, RDetails: TRect);

    property ViewStyle: TViewStyleEx read FViewStyle write SetViewStyle;
    property ThumbsOptions: TThumbsOptions read FThumbsOptions write FThumbsOptions;
    property ThumbThread: TThumbThread read GetThumbThread;
    property OnThumbThreadClass: TThumbThreadClassEvent read FOnThumbThreadClass write SetThumbThreadClassEvent;
    property OnThumbsCacheItemAdd: TLVThumbsCacheItemProcessingEvent read FOnThumbsCacheItemAdd write FOnThumbsCacheItemAdd;
    property OnThumbsCacheItemLoad: TLVThumbsCacheItemLoadEvent read FOnThumbsCacheItemLoad write FOnThumbsCacheItemLoad;
    property OnThumbsCacheItemRead: TLVThumbsCacheItemReadEvent read FOnThumbsCacheItemRead write FOnThumbsCacheItemRead;
    property OnThumbsCacheItemProcessing: TLVThumbsCacheItemProcessingEvent read FOnThumbsCacheItemProcessing write FOnThumbsCacheItemProcessing;
    property OnThumbsCacheLoad: TLVThumbsCacheEvent read FOnThumbsCacheLoad write FOnThumbsCacheLoad;
    property OnThumbsCacheSave: TLVThumbsCacheEvent read FOnThumbsCacheSave write FOnThumbsCacheSave;
    property OnThumbsDrawBefore: TLVThumbsDraw read FOnThumbsDrawBefore write FOnThumbsDrawBefore;
    property OnThumbsDrawAfter: TLVThumbsDraw read FOnThumbsDrawAfter write FOnThumbsDrawAfter;
    property OnThumbsDrawHint: TLVThumbsDrawHint read FOnThumbsDrawHint write FOnThumbsDrawHint;
    property OnThumbsGetDetails: TLVThumbsGetDetails read FOnThumbsGetDetails write FOnThumbsGetDetails;
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    procedure Loaded; override;

    //VT methods
    procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
    function Focused: Boolean; override;
    procedure SetFocus; override;
    function EditNode(Node: PVirtualNode; Column: TColumnIndex): Boolean; override;
    function EditFile(APath: WideString): Boolean;
    procedure Clear; override;
    procedure CopyToClipBoard; override;
    procedure CutToClipBoard; override;
    function PasteFromClipboard: Boolean; override;
    function InvalidateNode(Node: PVirtualNode): TRect; override;

    //VET methods
    function BrowseToByPIDL(APIDL: PItemIDList; ExpandTarget, SelectTarget, SetFocusToVET,
      CollapseAllFirst: Boolean; ShowAllSiblings: Boolean = True): Boolean; override;
    procedure SelectedFilesDelete; override;
    procedure SelectedFilesPaste(AllowMultipleTargets: Boolean); override;
    procedure SelectedFilesShowProperties; override;

    //Synchronization methods
    procedure SyncInvalidate;
    procedure SyncItemsCount; virtual;
    procedure SyncOptions; virtual;
    procedure SyncSelectedItems(UpdateChildListview: boolean = True);

    //Thumbnails public methods
    procedure FillExtensionsList(FillColors: Boolean = true); virtual;
    function GetThumbDrawingBounds(IncludeThumbDetails, IncludeBorderSize: Boolean): TRect;
    function IsImageFileIndex(FileName: WideString): integer;
    function IsImageFile(FileName: WideString): Boolean; overload;
    function IsImageFile(Node: PVirtualNode): TNamespace; overload;
    function ValidateThumbnail(Node: PVirtualNode; var ThumbData: PThumbnailData): Boolean;
    function ValidateListItem(Node: PVirtualNode; var ListItem: TListItem): Boolean;

    //Public properties
    property ImageLibrary: TThumbnailImageLibrary read FImageLibrary;
    property ChildListview: TOLEListview read FListview;
    property ExtensionsList: TExtensionsList read FExtensionsList;
    property ShellExtractExtensionsList: TExtensionsList read FShellExtractExtensionsList;
    property ExtensionsExclusionList: TExtensionsList read FExtensionsExclusionList;
  published
    property Visible: boolean read FVisible write SetVisible default true;
  end;

  TVirtualExplorerListviewEx = class(TCustomVirtualExplorerListviewEx)
  published
    property ViewStyle;
    property ThumbsOptions;
    property OnThumbThreadClass;
    property OnThumbsCacheItemAdd;
    property OnThumbsCacheItemLoad;
    property OnThumbsCacheItemRead;
    property OnThumbsCacheItemProcessing;
    property OnThumbsCacheLoad;
    property OnThumbsCacheSave;
    property OnThumbsDrawBefore;
    property OnThumbsDrawAfter;
    property OnThumbsDrawHint;
    property OnThumbsGetDetails;
  end;

// Misc helpers
function SpMakeObjectInstance(Method: TWndMethod): Pointer;
procedure SpFreeObjectInstance(ObjectInstance: Pointer);
function SpCompareText(W1, W2: WideString): Boolean;

//Node manipulation helpers
function GetChildByIndex(ParentNode: PVirtualNode; ChildIndex: Cardinal): PVirtualNode;
function IsThumbnailActive(ThumbnailState: TThumbnailState): Boolean;
function SupportsShellExtract(NS: TNamespace): boolean;

//Image manipulation helpers
procedure InitBitmap(OutB: TBitmap; W, H: integer; BackgroundColor: TColor);
procedure SpStretchDraw(G: TGraphic; OutBitmap: TBitmap; DestR: TRect; UseSubsampling: Boolean);
function RectAspectRatio(ImageW, ImageH, ThumbW, ThumbH: integer; Center, Stretch: boolean): TRect;
procedure DrawThumbBorder(ACanvas: TCanvas; ThumbBorder: TThumbnailBorder; R: TRect);
function IsIncompleteJPGError(E: Exception): boolean;
function IsDelphiSupportedImageFile(FileName: WideString): Boolean;
function GetGraphicClass(Filename: WideString): TGraphicClass;
function LoadImageEnGraphic(Filename: WideString; outBitmap: TBitmap): Boolean;
function LoadGraphic(Filename: WideString; outP: TPicture): boolean;
function LoadImage(Filename: WideString; OutP: TPicture): boolean;
function MakeThumbFromFile(Filename: WideString; OutBitmap: TBitmap; ThumbW, ThumbH: integer;
  Center: boolean; BgColor: TColor; Stretch, Subsampling: Boolean; var ImageWidth, ImageHeight: integer): Boolean;

//Stream helpers
function ReadDateTimeFromStream(ST: TStream): TDateTime;
procedure WriteDateTimeToStream(ST: TStream; D: TDateTime);
function ReadIntegerFromStream(ST: TStream): Integer;
procedure WriteIntegerToStream(ST: TStream; I: Integer);
function ReadWideStringFromStream(ST: TStream): WideString;
procedure WriteWideStringToStream(ST: TStream; WS: WideString);
function ReadMemoryStreamFromStream(ST: TStream; MS: TMemoryStream): Boolean;
procedure WriteMemoryStreamToStream(ST: TStream; MS: TMemoryStream);
function ReadBitmapFromStream(ST: TStream; B: TBitmap): Boolean;
procedure WriteBitmapToStream(ST: TStream; B: TBitmap);
procedure ConvertBitmapStreamToJPGStream(MS: TMemoryStream; CompressionQuality: TJPEGQualityRange);
procedure ConvertJPGStreamToBitmapStream(MS: TMemoryStream);
procedure ConvertJPGStreamToBitmap(MS: TMemoryStream; OutBitmap: TBitmap);

implementation
uses
  ShellApi, Math;

var
  SearchCache: PVirtualNode = nil;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ Helpers }

function SpMakeObjectInstance(Method: TWndMethod): Pointer;
begin
{$IFDEF COMPILER_6_UP}
  Result := Classes.MakeObjectInstance(Method);
{$ELSE}
  Result := Forms.MakeObjectInstance(Method);
{$ENDIF}
end;

procedure SpFreeObjectInstance(ObjectInstance: Pointer);
begin
{$IFDEF COMPILER_6_UP}
  Classes.FreeObjectInstance(ObjectInstance);
{$ELSE}
  Forms.FreeObjectInstance(ObjectInstance);
{$ENDIF}
end;

function SpCompareText(W1, W2: WideString): Boolean;
begin
  Result := False;
  if Win32Platform = VER_PLATFORM_WIN32_NT then begin
    if lstrcmpiW_VST(PWideChar(W1), PWideChar(W2)) = 0 then
      Result := True;
  end else
    if AnsiCompareText(W1, W2) = 0 then
      Result := True;
end;

procedure FlushSearchCache;
begin
  SearchCache := nil;
end;

function GetChildByIndex(ParentNode: PVirtualNode; ChildIndex: Cardinal): PVirtualNode;
var
  N: PVirtualNode;
  Count: Cardinal;
begin
  Result := nil;
  Count := ParentNode.ChildCount;
  if ChildIndex >= Count then exit;

  // This speeds up the search drastically
  if Assigned(SearchCache) and Assigned(SearchCache.Parent) and (SearchCache.Parent = ParentNode) then
  begin
    if ChildIndex >= SearchCache.Index then
    begin
      N := SearchCache;
      while Assigned(N) do
        if N.Index = ChildIndex then begin
          Result := N;
          break
        end
        else
          N := N.NextSibling;
    end else
    begin
      N := SearchCache;
      while Assigned(N) do
        if N.Index = ChildIndex then begin
          Result := N;
          break
        end
        else
          N := N.PrevSibling;
    end
  end else
    if ChildIndex <= Count div 2 then begin
      N := ParentNode.FirstChild;
      while Assigned(N) do
        if N.Index = ChildIndex then begin
          Result := N;
          break;
        end
        else
          N := N.NextSibling;
    end
    else begin
      N := ParentNode.LastChild;
      while Assigned(N) do
        if N.Index = ChildIndex then begin
          Result := N;
          break;
        end
        else
          N := N.PrevSibling;
    end;

  SearchCache := Result;
end;

function IsThumbnailActive(ThumbnailState: TThumbnailState): Boolean;
begin
  Result := (ThumbnailState = tsValid) or (ThumbnailState = tsProcessing);
end;

function SupportsShellExtract(NS: TNamespace): boolean;
begin
  Result := Assigned(NS.ExtractImage.ExtractImageInterface);
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ Drawing helpers }

function RectAspectRatio(ImageW, ImageH, ThumbW, ThumbH: integer; Center, Stretch: boolean): TRect;
begin
  Result := Rect(0, 0, 0, 0);
  if (ImageW < 1) or (ImageH < 1) then Exit;

  if (ImageW <= ThumbW) and (ImageH <= ThumbH) and (not Stretch) then begin
    Result.Right := ImageW;
    Result.Bottom := ImageH;
  end
  else begin
    Result.Right := (ThumbH * ImageW) div ImageH;
    if (Result.Right <= ThumbW) then Result.Bottom := ThumbH
    else begin
      Result.Right := ThumbW;
      Result.Bottom := (ThumbW * ImageH) div ImageW;
    end;
  end;

  if Center then
    with Result do begin
      left := (ThumbW - right) div 2;
      top := (ThumbH - bottom) div 2;
      right := left + right;
      bottom := top + bottom;
    end;

  // TJPEGImage doesn't accepts images with 1 pixel width or height
  if Result.Right <= 1 then Result.Right := 2;
  if Result.Bottom <= 1 then Result.Bottom := 2;
end;

procedure InitBitmap(OutB: TBitmap; W, H: integer; BackgroundColor: TColor);
begin
//  OutB.PixelFormat := pf24bit; //do this first!
  OutB.Width := W;
  OutB.Height := H;
  OutB.Canvas.Brush.Color := BackgroundColor;
  OutB.Canvas.Fillrect(Rect(0, 0, W, H));
end;

procedure SpStretchDraw(G: TGraphic; OutBitmap: TBitmap; DestR: TRect; UseSubsampling: Boolean);
// Canvas.StretchDraw is NOT THREADSAFE!!!
// Use StretchBlt instead, we have to use a worker bitmap to do so
var
  Work: TBitmap;
begin
  Work := TBitmap.Create;
  Work.Canvas.Lock;
  try
    // Paint the Picture in Work
    if (G is TJpegImage) or (G is TBitmap) then
      Work.Assign(G) //assign works in this case
    else begin
      Work.Width := G.Width;
      Work.Height := G.Height;
      Work.Canvas.Draw(0, 0, G);
    end;

    if UseSubsampling then
      SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_HALFTONE)
    else
      SetStretchBltMode(OutBitmap.Canvas.Handle, STRETCH_DELETESCANS);

    StretchBlt(OutBitmap.Canvas.Handle,
      DestR.Left, DestR.Top, DestR.Right - DestR.Left, DestR.Bottom - DestR.Top,
      Work.Canvas.Handle, 0, 0, G.Width, G.Height, SRCCopy);
  finally
    Work.Canvas.Unlock;
    Work.Free;
  end;
end;

procedure DrawThumbBorder(ACanvas: TCanvas; ThumbBorder: TThumbnailBorder; R: TRect);
const
  Edge: array [TThumbnailBorder] of Cardinal = (0, BDR_RAISEDINNER, EDGE_RAISED,
    BDR_SUNKENOUTER, EDGE_SUNKEN, EDGE_BUMP, EDGE_ETCHED, 0);
begin
  if ThumbBorder <> tbNone then begin
    Case ThumbBorder of
      tbNone: ;
      tbFramed: begin
        ACanvas.Brush.Color := clBtnFace;
        ACanvas.FrameRect(R);
      end;
    else
      DrawEdge(ACanvas.Handle, R, Edge[ThumbBorder], BF_RECT);
    end;
  end;
end;

function IsIncompleteJPGError(E: Exception): boolean;
var
  S: string;
begin
  S := E.Message;
  Result := (S = 'JPEG error #68') or
            (S = 'JPEG error #67') or
            (S = 'JPEG error #60') or
            (S = 'JPEG error #57');
end;

function IsDelphiSupportedImageFile(FileName: WideString): Boolean;
var
  Ext: WideString;
begin
  Ext := WideLowerCase(ExtractFileExtW(Filename));
  Result := (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') or
    (Ext = '.bmp') or (Ext = '.wmf') or (Ext = '.emf') or (Ext = '.ico');
end;

function GetGraphicClass(Filename: WideString): TGraphicClass;
var
  Ext: WideString;
begin
  Ext := WideLowerCase(ExtractFileExtW(Filename));
  Delete(Ext, 1, 1);

  {$IFDEF USEGRAPHICEX}
  Result := GraphicEx.FileFormatList.GraphicFromExtension(Ext);
  {$ELSE}
    Result := nil;
    if (Ext = 'jpg') or (Ext = 'jpeg') or (Ext = 'jif') then Result := TJpegImage
    else if Ext = 'bmp' then Result := TBitmap
    else if (Ext = 'wmf') or (Ext = 'emf') then Result := TMetafile
    else if Ext = 'ico' then Result := TIcon;
    {$IFDEF USEIMAGEMAGICK}
    if Result = nil then
      Result := MagickImage.MagickFileFormatList.GraphicFromExtension(Ext);
    {$ENDIF}
  {$ENDIF}
end;

function LoadImageEnGraphic(Filename: WideString; outBitmap: TBitmap): Boolean;
// Loads an image file with a unicode name using ImageEn graphic library
{$IFDEF USEIMAGEEN}
var
  B: TBitmap;
  ImageEnIO: TImageEnIO;
  F: TWideFileStream;
{$ENDIF}
begin
  Result := false;
  {$IFDEF USEIMAGEEN}
  ImageEnIO := TImageEnIO.Create(nil);
  try
    ImageEnIO.AttachedBitmap := outBitmap;
    F := TWideFileStream.Create(Filename, fmOpenRead or fmShareDenyNone);
    try
      ImageEnIO.LoadFromStream(F);
      Result := true;
    finally
      F.Free;
    end;
  finally
    ImageEnIO.Free;
  end;
  {$ENDIF}
end;

// Bug in Delphi 5:
// When creating a bitmap by using its class type (TGraphicClass) it doesn't calls
// the TBitmap constructor.
// That's because in Delphi 5 the TGraphic.Create is protected, and TBitmap.Create
// is public, so TGraphicClass(ABitmap).Create will NOT call TBitmap.Create because
// it's not visible by TGraphicClass.
// To fix this we need to make it visible by creating a TGraphicClass cracker.
// More info on:
// http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00000331.0164178b%40xmission.com
type
  TFixedGraphic = class(TGraphic);
  TFixedGraphicClass = class of TFixedGraphic;

function LoadGraphic(Filename: WideString; outP: TPicture): boolean;
// Loads an image file with a unicode name
var
  NewGraphic: TGraphic;
  GraphicClass: TGraphicClass;
  F: TWideFileStream;
  {$IFDEF USEIMAGEEN}
  B: TBitmap;
  {$ENDIF}
begin
  Result := false;

  {$IFDEF USEIMAGEEN}
  B := TBitmap.Create;
  try
    Result := LoadImageEnGraphic(Filename, B);
  finally
    B.Free;
  end;
  {$ELSE}
  GraphicClass := GetGraphicClass(Filename);
  if GraphicClass = nil then
    outP.LoadFromFile(Filename) //try the default loader
  else begin
    F := TWideFileStream.Create(Filename, fmOpenRead or fmShareDenyNone);
    try
      NewGraphic := TFixedGraphicClass(GraphicClass).Create;
      try
        NewGraphic.LoadFromStream(F);
        outP.Graphic := NewGraphic;
        Result := true;
      finally
        NewGraphic.Free;
      end;
    finally
      F.Free;
    end;
  end;
  {$ENDIF}
end;

function LoadImage(Filename: WideString; OutP: TPicture): boolean;
var
  J: TJpegImage;
begin
  Result := false;
  if (Filename = '') or not Assigned(outP) then Exit;

  try
    LoadGraphic(Filename, OutP);
    if OutP.Graphic is TJpegImage then begin
      J := TJpegImage(OutP.Graphic);
      J.DIBNeeded; //load the JPG
    end;
  except
    on E:Exception do
      if not IsIncompleteJPGError(E) then
        raise;
  end;

  Result := true;
end;

function MakeThumbFromFile(Filename: WideString; OutBitmap: TBitmap; ThumbW, ThumbH: integer;
  Center: boolean; BgColor: TColor; Stretch, SubSampling: Boolean; var ImageWidth, ImageHeight: integer): Boolean;
var
  P: TPicture;
  J: TJpegImage;
  DestR: TRect;
  Ext: string;
begin
  Result := false;
  if not Assigned(OutBitmap) then exit;
  Ext := Lowercase(ExtractFileExtW(Filename));

  P := TPicture.create;
  try
    LoadGraphic(Filename, P);
    if P.Graphic <> nil then begin
      ImageWidth := P.Graphic.Width;
      ImageHeight := P.Graphic.Height;
      if (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') then begin
        // 5x faster loading jpegs, try to load just the minimum possible jpg
        // From Danny Thorpe: http://groups.google.com/groups?hl=en&frame=right&th=69a64eafb3ee2b12&seekm=01bdee71%24e5a5ded0%247e018f0a%40agamemnon#link6
        try
          J := TJpegImage(P.graphic);
          J.Performance := jpBestSpeed;
          J.Scale := jsFullSize;
          while ((J.width > ThumbW) or (J.height > ThumbH)) and (J.Scale < jsEighth) do
            J.Scale := Succ(J.Scale);
          if J.Scale <> jsFullSize then
            J.Scale := Pred(J.Scale);

          J.DibNeeded; //now load the JPG
        except
          on E:Exception do
            if not IsIncompleteJPGError(E) then
              Raise;
        end;
      end;
      // Resize the thumb
      // Need to lock/unlock the canvas here
      OutBitmap.Canvas.Lock;
      try
        // init OutBitmap
        DestR := RectAspectRatio(ImageWidth, ImageHeight, ThumbW, ThumbH, Center, Stretch);

        if Center then
          InitBitmap(OutBitmap, ThumbW, ThumbH, BgColor)
        else
          InitBitmap(OutBitmap, DestR.Right, DestR.Bottom, BgColor);

        // StretchDraw is NOT THREADSAFE!!! Use SpStretchDraw instead
        SpStretchDraw(P.Graphic, OutBitmap, DestR, Subsampling);

        Result := True;
      finally
        OutBitmap.Canvas.UnLock;
      end;
    end;
  finally
    P.free;
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ Stream helpers }

function ReadDateTimeFromStream(ST: TStream): TDateTime;
begin
  ST.ReadBuffer(Result, SizeOf(Result));
end;

procedure WriteDateTimeToStream(ST: TStream; D: TDateTime);
begin
  ST.WriteBuffer(D, SizeOf(D));
end;

function ReadIntegerFromStream(ST: TStream): Integer;
begin
  ST.ReadBuffer(Result, SizeOf(Result));
end;

procedure WriteIntegerToStream(ST: TStream; I: Integer);
begin
  ST.WriteBuffer(I, SizeOf(I));
end;

function ReadWideStringFromStream(ST: TStream): WideString;
var
  L: integer;
  WS: WideString;
begin
  Result := '';
  ST.ReadBuffer(L, SizeOf(L));
  SetLength(WS, L);
  ST.ReadBuffer(PWideChar(WS)^, 2 * L);
  Result := WS;
end;

procedure WriteWideStringToStream(ST: TStream; WS: WideString);
var
  L: integer;
begin
  L := Length(WS);
  ST.WriteBuffer(L, SizeOf(L));
  ST.WriteBuffer(PWideChar(WS)^, 2 * L);
end;

function ReadMemoryStreamFromStream(ST: TStream; MS: TMemoryStream): Boolean;
var
  L: integer;
begin
  Result := false;
  ST.ReadBuffer(L, SizeOf(L));
  if L > 0 then begin
    MS.Size := L;
    ST.ReadBuffer(MS.Memory^, L);
    Result := true;
  end;
end;

procedure WriteMemoryStreamToStream(ST: TStream; MS: TMemoryStream);
var
  L: integer;
begin
  L := MS.Size;
  ST.WriteBuffer(L, SizeOf(L));
  ST.WriteBuffer(MS.Memory^, L);
end;

function ReadBitmapFromStream(ST: TStream; B: TBitmap): Boolean;
var
  MS: TMemoryStream;
begin
  Result := false;
  MS := TMemoryStream.Create;
  try
    if ReadMemoryStreamFromStream(ST, MS) then
      if Assigned(B) then begin
        B.LoadFromStream(MS);
        Result := true;
      end;
  finally
    MS.Free;
  end;
end;

procedure WriteBitmapToStream(ST: TStream; B: TBitmap);
var
  L: integer;
  MS: TMemoryStream;
begin
  if Assigned(B) then begin
    MS := TMemoryStream.Create;
    try
      B.SaveToStream(MS);
      WriteMemoryStreamToStream(ST, MS);
    finally
      MS.Free;
    end;
  end
  else begin
    L := 0;
    ST.WriteBuffer(L, SizeOf(L));
  end;
end;

procedure ConvertBitmapStreamToJPGStream(MS: TMemoryStream; CompressionQuality: TJPEGQualityRange);
var
  B: TBitmap;
  J: TJPEGImage;
begin
  B := TBitmap.Create;
  J := TJPEGImage.Create;
  try
    MS.Position := 0;
    B.LoadFromStream(MS);
    //WARNING, first set the JPEG options
    J.CompressionQuality := CompressionQuality; //90 is the default, 60 is the best setting
    //Now assign the Bitmap
    J.Assign(B);
    J.Compress;
    MS.Clear;
    J.SaveToStream(MS);
    MS.Position := 0;
  finally
    B.Free;
    J.Free;
  end;
end;

procedure ConvertJPGStreamToBitmapStream(MS: TMemoryStream);
var
  B: TBitmap;
  J: TJPEGImage;
begin
  B := TBitmap.Create;
  J := TJPEGImage.Create;
  try
    MS.Position := 0;
    J.LoadFromStream(MS);
    B.Assign(J);
    MS.Clear;
    B.SaveToStream(MS);
    MS.Position := 0;
  finally
    B.Free;
    J.Free;
  end;
end;

procedure ConvertJPGStreamToBitmap(MS: TMemoryStream; OutBitmap: TBitmap);
var
  B: TMemoryStream;
begin
  B := TMemoryStream.Create;
  try
    MS.Position := 0;
    B.LoadFromStream(MS);
    MS.Position := 0;
    ConvertJPGStreamToBitmapStream(B);
    OutBitmap.LoadFromStream(B);
  finally
    B.Free;
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TExtensionsList }

constructor TExtensionsList.Create;
begin
  inherited;
  Sorted := True;
end;

function TExtensionsList.Add(const Extension: WideString; HighlightColor: TColor): Integer;
begin
  Result := inherited Add(Extension);
  if Result > -1 then
    Colors[Result] := HighlightColor;
end;

function TExtensionsList.AddObject(const S: WideString; AObject: TObject): Integer;
var
  Aux: WideString;
begin
  Aux := WideLowerCase(S);
  //Add the '.' part of the extension
  if (Length(Aux) > 0) and (Aux[1] <> '.') then
    Aux := '.' + Aux;
  Result := inherited AddObject(Aux, AObject);
end;

function TExtensionsList.IndexOf(const S: WideString): Integer;
var
  Aux: WideString;
begin
  Aux := WideLowerCase(S);
  //Add the '.' part of the extension
  if (Length(Aux) > 0) and (Aux[1] <> '.') then
    Aux := '.' + Aux;
  Result := inherited IndexOf(Aux);
end;

function TExtensionsList.DeleteString(const S: WideString): Boolean;
var
  I: integer;
begin
  I := IndexOf(S);
  if I > -1 then begin
    Delete(I);
    Result := True;
  end
  else
    Result := False;
end;

function TExtensionsList.GetColors(Index: integer): TColor;
begin
  if Assigned(Objects[Index]) then
    Result := TColor(Objects[Index])
  else
    Result := clNone;
end;

procedure TExtensionsList.SetColors(Index: integer; const Value: TColor);
begin
  Objects[Index] := Pointer(Value);
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TBitmapHint }

procedure TBitmapHint.ActivateHint(Rect: TRect; const AHint: string);
begin
  FActivating := True;
  try
    inherited ActivateHint(Rect, AHint);
  finally
    FActivating := False;
  end;
end;

procedure TBitmapHint.ActivateHintData(Rect: TRect; const AHint: string; AData: Pointer);
begin
  //The AData parameter is a bitmap
  FHintBitmap := TBitmap(AData);
  Rect.Right := Rect.Left + FHintBitmap.Width - 2;
  Rect.Bottom := Rect.Top + FHintBitmap.Height - 2;
  inherited ActivateHintData(Rect, AHint, AData);
end;

procedure TBitmapHint.CMTextChanged(var Message: TMessage);
begin
  Message.Result := 1;
end;

procedure TBitmapHint.Paint;
begin
  Canvas.Draw(0, 0, FHintBitmap);
end;

procedure TBitmapHint.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
  //Don't erase the background as this causes flickering
  Paint;
  Message.Result := 1;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TThumbsCache }

constructor TThumbsCache.Create;
begin
  FHeaderFilelist := TWideStringList.Create;
  FHeaderFilelist.OwnsObjects := true;
  FScreenBuffer := TWideStringList.Create;
  FScreenBuffer.OwnsObjects := true;
  FScreenBuffer.Sorted := true;
  FComments := TWideStringList.Create;
  Clear;
end;

destructor TThumbsCache.Destroy;
begin
  Clear;
  FHeaderFilelist.Free;
  FScreenBuffer.Free;
  FComments.Free;
  inherited;
end;

procedure TThumbsCache.Clear;
begin
  FHeaderFilelist.Clear;
  FScreenBuffer.Clear;
  FComments.Clear;

  FStreamVersion := DefaultStreamVersion;
  FLoadedFromFile := false;
  FDirectory := '';
  FSize := 0;
  FInvalidCount := 0;
  FThumbWidth := 0;
  FThumbHeight := 0;
end;

function TThumbsCache.IndexOf(Filename: WideString): Integer;
begin
  Result := FHeaderFilelist.IndexOf(Filename);
end;

function TThumbsCache.Add(Filename: WideString; CI: TThumbsCacheItem): Integer;
begin
  Result := FHeaderFilelist.AddObject(Filename, CI);
  if Result > -1 then
    FSize := FSize + CI.ThumbImageStream.Size;
end;

function TThumbsCache.Add(Filename, AExif, AComment: WideString;
  AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer;
  ACompressIt: Boolean; AThumbImage: TBitmap): Integer;
var
  CI: TThumbsCacheItem;
begin
  Result := -1;
  CI := TThumbsCacheItem.Create(Filename);
  try
    CI.WriteBitmap(AThumbImage, ACompressIt);
    CI.Fill(AFileDateTime, AExif, AComment, AImageWidth, AImageHeight,
      ACompressIt, nil);
    Result := Add(Filename, CI);
  except
    CI.Free;
  end;
end;

function TThumbsCache.Add(Filename, AExif, AComment: WideString;
  AFileDateTime: TDateTime; AImageWidth, AImageHeight: Integer;
  ACompressed: Boolean; AThumbImageStream: TMemoryStream): Integer;
var
  CI: TThumbsCacheItem;
begin
  Result := -1;
  CI := TThumbsCacheItem.Create(Filename);
  try
    CI.Fill(AFileDateTime, AExif, AComment, AImageWidth, AImageHeight,
      ACompressed, AThumbImageStream);
    Result := Add(Filename, CI);
  except
    CI.Free;
  end;
end;

function TThumbsCache.Delete(Filename: WideString): Boolean;
var
  I, J: integer;
  M: TMemoryStream;
begin
  I := IndexOf(Filename);
  Result := I > -1;
  if Result then begin
    M := TThumbsCacheItem(FHeaderFilelist.Objects[I]).ThumbImageStream;
    FSize := FSize - M.Size;

    // Don't delete it from the HeaderFilelist, instead free the ThumbsCacheItem and clear the string
    TThumbsCacheItem(FHeaderFilelist.Objects[I]).Free;
    FHeaderFilelist.Objects[I] := nil;
    FHeaderFilelist[I] := '';
    Inc(FInvalidCount);

    // Delete the ScreenBuffer item
    J := FScreenBuffer.IndexOf(Filename);
    if J > -1 then
      FScreenBuffer.Delete(J);

    Result := true;
  end;
end;

function TThumbsCache.Read(Index: integer; var OutCacheItem: TThumbsCacheItem): Boolean;
begin
  if (Index > -1) and (Index < FHeaderFilelist.Count) then
    OutCacheItem := FHeaderFilelist.Objects[Index] as TThumbsCacheItem
  else
    OutCacheItem := nil;
  Result := Assigned(OutCacheItem);
end;

function TThumbsCache.Read(Index: integer; OutBitmap: TBitmap): Boolean;
var
  CI: TThumbsCacheItem;
  I: integer;
  B: TBitmap;
begin
  Result := false;
  if Read(Index, CI) and Assigned(CI.ThumbImageStream) and Assigned(FScreenBuffer) then begin
    // Retrieve the bitmap from the ScreenBuffer
    I := FScreenBuffer.IndexOf(CI.Filename);
    if I > -1 then begin
      OutBitmap.Assign(TBitmap(FScreenBuffer.Objects[I]));
      Result := true;
    end
    else begin
      CI.ReadBitmap(OutBitmap);

      // Add it to the ScreenBuffer
      B := TBitmap.Create;
      try
        B.Assign(OutBitmap);
        FScreenBuffer.AddObject(CI.Filename, B); // The ScreenBuffer owns the bitmaps
      except
        B.Free;
      end;
      // Set capacity to 50
      while FScreenBuffer.Count > 50 do
        FScreenBuffer.Delete(0); // FIFO list

      Result := true;
    end;
  end;
end;

function TThumbsCache.DefaultStreamVersion: integer;
begin
  // Version 11, has FileDateTime defined as TDateTime, uses TThumbsCacheItem.SaveToStream,
  // has per file compression
  // and stores ThumbWidth/ThumbHeight
  Result := 11;
end;

procedure TThumbsCache.LoadFromFile(const Filename: Widestring);
var
  FileStream: TStream;
  CI: TThumbsCacheItem;
  I, FileCount: integer;
begin
  Clear;
  FileStream := TWideFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
  try
    // Read the header
    FDirectory := ReadWideStringFromStream(FileStream);
    FileCount := ReadIntegerFromStream(FileStream);
    FStreamVersion := ReadIntegerFromStream(FileStream);
    FThumbWidth := ReadIntegerFromStream(FileStream);
    FThumbHeight := ReadIntegerFromStream(FileStream);

    if FStreamVersion = DefaultStreamVersion then begin
      // Read the file list
      for I := 0 to FileCount - 1 do begin
        CI := TThumbsCacheItem.CreateFromStream(FileStream);
        try
          if FileExistsW(CI.Filename) then
            Add(CI.Filename, CI)
          else begin
            // The file is not valid, don't add it
            CI.Free;
          end;
        except
          Inc(FInvalidCount);
          CI.Free;
        end;
      end;
      // Read the comments or extra options
      FComments.LoadFromStream(FileStream);

      FLoadedFromFile := true;
    end;

  finally
    FileStream.Free;
  end;
end;

procedure TThumbsCache.LoadFromFile(const Filename: Widestring; InvalidFiles: TWideStringList);
var
  AuxThumbsCache: TThumbsCache;
  CI, CICopy: TThumbsCacheItem;
  I: integer;
begin
  if not Assigned(InvalidFiles) or (InvalidFiles.Count = 0) then
    LoadFromFile(Filename)
  else begin
    // Tidy the list
    for I := 0 to InvalidFiles.Count - 1 do
      InvalidFiles[I] := WideLowerCase(InvalidFiles[I]);
    InvalidFiles.Sort;
    // Load a cache file and ATTACH only the streams that are NOT in InvalidFiles list
    AuxThumbsCache := TThumbsCache.Create;
    try
      AuxThumbsCache.LoadFromFile(Filename);
      for I := 0 to AuxThumbsCache.Count - 1 do begin
        if AuxThumbsCache.Read(I, CI) and (InvalidFiles.IndexOf(CI.Filename) < 0) then begin
          CICopy := TThumbsCacheItem.Create(CI.Filename);
          try
            CICopy.Assign(CI);
            Self.Add(CI.Filename, CICopy);
          except
            CICopy.Free;
          end;
        end;
      end;

      FLoadedFromFile := true;
    finally
      AuxThumbsCache.Free;
    end;
  end;
end;

procedure TThumbsCache.SaveToFile(const Filename: Widestring);
var
  FileStream: TStream;
  CI: TThumbsCacheItem;
  I: integer;
begin
  FileStream := TWideFileStream.Create(Filename, fmCreate);
  try
    // Write the header
    WriteWideStringToStream(FileStream, Directory);
    WriteIntegerToStream(FileStream, Count - InvalidCount);
    WriteIntegerToStream(FileStream, DefaultStreamVersion);
    WriteIntegerToStream(FileStream, FThumbWidth);
    WriteIntegerToStream(FileStream, FThumbHeight);
    // Write the file list
    FHeaderFilelist.Sort;
    for I := 0 to Count - 1 do
      if FHeaderFilelist[I] <> '' then begin
        Read(I, CI);
        CI.SaveToStream(FileStream);
      end;
    // Save comments or extra options
    FComments.SaveToStream(FileStream);
  finally
    FileStream.Free;
  end;
end;

procedure TThumbsCache.Assign(AThumbsCache: TThumbsCache);
var
  I: integer;
  CI, CICopy: TThumbsCacheItem;
begin
  if Assigned(AThumbsCache) then begin
    Clear;
    Directory := AThumbsCache.Directory;
    FLoadedFromFile := AThumbsCache.LoadedFromFile;
    FStreamVersion := AThumbsCache.StreamVersion;
    FThumbWidth := AThumbsCache.ThumbWidth;
    FThumbHeight := AThumbsCache.ThumbHeight;
    FComments.Assign(AThumbsCache.Comments);

    //Clone
    for I := 0 to AThumbsCache.Count - 1 do begin
      AThumbsCache.Read(I, CI);
      if CI.Filename <> '' then begin
        CICopy := TThumbsCacheItem.Create(CI.Filename);
        try
          CICopy.Assign(CI);
          Self.Add(CI.Filename, CICopy);
        except
          CICopy.Free;
        end;
      end;
    end;
  end;
end;

function TThumbsCache.GetCount: integer;
begin
  Result := FHeaderFilelist.Count;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TCacheList }

function PosRight(SubStr: WideChar; S: WideString): Integer;
// Like Pos function but starting from the last char
var
  I, L: integer;
begin
  Result := -1;
  L := Length(S);
  if L > 0 then
    for I := L downto 1 do
      if S[I] = SubStr then begin
        Result := I;
        Break;
      end;
end;

function NameFromRight(L: TWideStringList; const Index: Integer): WideString;
// Like TWideStringList.Names[] but starting from the last char
var
  P: Integer;
begin
  Result := L[Index];
  P := PosRight('\', Result);
  if P > 0 then SetLength(Result, P)
           else Result := '';
end;

function ValueFromIndexRight(L: TWideStringList; const Index: Integer): WideString;
// Like TWideStringList.ValueFromIndex but starting from the last char
var
  S: WideString;
begin
  Result := '';
  if Index > -1 then begin
    // get name
    S := NameFromRight(L, Index);
    // copy the result
    if S <> '' then
      Result := Copy(L[Index], Length(S) + 2, MaxInt);
  end;
end;

function IndexOfNameRight(L: TWideStringList; const Name: WideString): Integer;
// Like TWideStringList.IndexOfName but starting from the last char
var
  I: integer;
  S: WideString;
begin
  Result := -1;
  for I := 0 to L.Count - 1 do begin
    S := NameFromRight(L, I);
    if S <> '' then
      if SpCompareText(S, Name) then begin
        Result := I;
        Break;
      end;
  end;
end;

function IndexOfValueRight(L: TWideStringList; const Value: WideString): Integer;
// Like TWideStringList.IndexOfValue but starting from the last char
var
  P: Integer;
  I: integer;
begin
  Result := -1;
  for I := 0 to L.Count - 1 do begin
    P := PosRight('\', L[I]);
    if P > 0 then
      if SpCompareText(ValueFromIndexRight(L, I), Value) then begin
        Result := I;
        Break;
      end;
  end;
end;

constructor TCacheList.Create;
begin
  inherited;
  FDefaultFilename := 'CacheList.txt';
  FCentralFolder := '';
end;

function TCacheList.GetCacheFileToSave(Dir: Widestring): WideString;
var
  WCH: PWideChar;
  F, WS: WideString;
  I: integer;
begin
  Result := '';
  if FCentralFolder = '' then exit;

  Dir := IncludeTrailingBackslashW(Dir);
  I := IndexOfNameRight(Self, Dir);
  if I <> -1 then
    Result := FCentralFolder + ValueFromIndexRight(Self, I)
  else begin
    //find a unique file name to store the cache
    if IsDriveW(Dir) then
      WS := Dir[1]
    else begin
      // NameForParsingInFolder
      WS := '';
      WCH := StrRScanW(PWideChar(StripTrailingBackslashW(Dir)), WideChar('\'));
      if Assigned(WCH) then begin
        WCH := WCH + 1; //get rid of the first '\'
        WS := WCH;
      end;
      // Delete all the '=' chars
      WCH := StrScanW(PWideChar(WS), WideChar('='));
      if Assigned(WCH) then begin
        I := Length(WS) - Integer(StrLenW(WCH));
        if I > 0 then
          Dec(I);
        SetLength(WS, I);
        if WS = '' then
          WS := '0';
      end;
    end;
    F := WS + '.cache';

    //find a unique file name
    I := -1;
    while IndexOfValueRight(Self, F) <> -1 do begin
      inc(I);
      F := WS + '.' + inttostr(I) + '.cache';
    end;

    Add(Dir + '=' + F);
    Sort;
    Result := FCentralFolder + F;
  end;
end;

function TCacheList.GetCacheFileToLoad(Dir: Widestring): WideString;
var
  I: integer;
begin
  Result := '';
  if FCentralFolder <> '' then begin
    I := IndexOfNameRight(Self, IncludeTrailingBackslashW(Dir));
    if I <> -1 then
      Result := FCentralFolder + ValueFromIndexRight(Self, I);
  end;
end;

procedure TCacheList.LoadFromFile;
begin
  if FileExistsW(FCentralFolder + DefaultFileName) then
    inherited LoadFromFile(FCentralFolder + DefaultFileName)
  else
    Clear;
end;

procedure TCacheList.SaveToFile;
begin
  DeleteInvalidFiles;
  inherited SaveToFile(FCentralFolder + DefaultFileName);
end;

procedure TCacheList.DeleteAllFiles;
var
  I: integer;
  F: WideString;
begin
  if FCentralFolder = '' then Exit;

  // Delete all the cache files
  for I := 0 to Count - 1 do begin
    F := FCentralFolder + ValueFromIndexRight(Self, I);
    if (F <> '') and FileExistsW(F) then
      DeleteFileW(PWideChar(F));
  end;
  // Delete the cache list file
  F := FCentralFolder + FDefaultFileName;
  if (F <> '') and FileExistsW(F) then
    DeleteFileW(PWideChar(F));
  // Clear the cache list
  Clear;
end;

procedure TCacheList.DeleteInvalidFiles;
var
  I: integer;
  F: WideString;
begin
  if FCentralFolder = '' then Exit;

  // Delete the invalid cache files
  for I := Count - 1 downto 0 do begin
    // Delete the entry if the cache file doesn't exist
    F := FCentralFolder + ValueFromIndexRight(Self, I);
    if (F = '') or not FileExistsW(F) then
      Delete(I)
    else
      // Delete the cache file if the Dir doesn't exist
      if not DirExistsW(NameFromRight(Self, I)) then
        if (F <> '') and FileExistsW(F) then begin
          DeleteFileW(PWideChar(F));
          Delete(I);
        end;
  end;
end;

procedure TCacheList.SetCentralFolder(const Value: WideString);
begin
  if FCentralFolder <> Value then
    if Value = '' then
      FCentralFolder := ''
    else
      FCentralFolder := IncludeTrailingBackslashW(Value);
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TThumbsCacheOptions }

constructor TThumbsCacheOptions.Create(AOwner: TCustomVirtualExplorerListviewEx);
begin
  FOwner := AOwner;
  FThumbsCache := TThumbsCache.Create;
  FCacheList := TCacheList.Create;
  FAutoLoad := False;
  FAutoSave := False;
  FCompressed := False;
  FDefaultFilename := 'Thumbnails.Cache';
  FStorageType := tcsCentral;
  FCacheProcessing := tcpDescending;
end;

destructor TThumbsCacheOptions.Destroy;
begin
  if AutoSave then
    Save; //Save the cache on exit
  FThumbsCache.Free;
  FCacheList.Free;
  inherited;
end;

procedure TThumbsCacheOptions.ClearCache(DeleteAllFiles: Boolean = False);
var
  F: WideString;
begin
  if Assigned(Owner.RootFolderNamespace) and
    SpCompareText(Owner.RootFolderNamespace.NameForParsing, BrowsingFolder) then
  begin
    if DeleteAllFiles then
      case FStorageType of
        tcsPerFolder:
          begin
            F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename;
            if (F <> '') and FileExistsW(F) then
              DeleteFileW(PWideChar(F));
          end;
        tcsCentral:
          FCacheList.DeleteAllFiles;
      end;
    Owner.ResetThumbThread; //reset and reload the thread
  end;
end;

procedure TThumbsCacheOptions.Reload(Node: PVirtualNode);
var
  TD: PThumbnailData;
begin
  if Assigned(Node) and (vsInitialized in Node.States) then
    if Owner.ValidateThumbnail(Node, TD) and (TD.State = tsValid) then begin
      // Reset the TD
      TD.Reloading := True;
      TD.State := tsEmpty;
      // TD.CachePos := -1; don't reset the CachePos
      if Owner.ViewStyle = vsxThumbs then
        Owner.FListview.UpdateItems(Node.Index, Node.Index); //invalidate canvas
    end;
end;

procedure TThumbsCacheOptions.Reload(Filename: WideString);
begin
  Reload(Owner.FindNode(Filename));
end;

procedure TThumbsCacheOptions.Load(Force: boolean);
var
  InvalidFiles: TWideStringList;
  N: PVirtualNode;
  NS: TNamespace;
  TD: PThumbnailData;
  F: WideString;
begin
  F := '';
  case FStorageType of
    tcsPerFolder:
      if FDefaultFilename <> '' then
        F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename;
    tcsCentral:
        F := FCacheList.GetCacheFileToLoad(FBrowsingFolder);
  end;

  if not Owner.DoThumbsCacheLoad(FThumbsCache, F, FThumbsCache.Comments) then
    FThumbsCache.FLoadedFromFile := True
  else
    if FileExistsW(F) then begin
      // Load only the bitmap streams that are not already loaded
      InvalidFiles := TWideStringList.Create;
      try
        // Iterate through the nodes and populate the InvalidFiles with the images filenames.
        if not Force then begin
          N := Owner.RootNode.FirstChild;
          while Assigned(N) do begin
            if (vsInitialized in N.States) and Owner.ValidateNamespace(N, NS) and Owner.ValidateThumbnail(N, TD) then
              if IsThumbnailActive(TD.State) then
                InvalidFiles.Add(WideLowerCase(NS.NameForParsing));
            N := N.NextSibling;
          end;
        end;
        // Load only the bitmap streams that are not already loaded
        FThumbsCache.LoadFromFile(F, InvalidFiles);
      finally
        InvalidFiles.Free;
      end;
    end;
end;

procedure TThumbsCacheOptions.Save;
var
  F: WideString;
begin
  if (FThumbsCache.Count = 0) or not DirExistsW(FBrowsingFolder) then Exit;

  case FStorageType of
    tcsPerFolder:
      if FDefaultFilename <> '' then begin
        F := IncludeTrailingBackslashW(FBrowsingFolder) + FDefaultFilename;
        if Owner.DoThumbsCacheSave(FThumbsCache, F, FThumbsCache.Comments) then
          FThumbsCache.SaveToFile(F);
      end;
    tcsCentral:
      if CentralFolder <> '' then
        if DirExistsW(CentralFolder) or CreateDirW(CentralFolder) then begin
          F := FCacheList.GetCacheFileToSave(FBrowsingFolder);
          if F <> '' then begin
            if Owner.DoThumbsCacheSave(FThumbsCache, F, FThumbsCache.Comments) then
              FThumbsCache.SaveToFile(F);
          end;
          FCacheList.SaveToFile;
        end;
  end;
end;

function TThumbsCacheOptions.Read(Node: PVirtualNode; var OutCacheItem: TThumbsCacheItem): Boolean;
var
  TD: PThumbnailData;
begin
  Result := False;
  if Assigned(FOwner) and FOwner.ValidateThumbnail(Node, TD) then
    if (TD.State = tsValid) and (TD.CachePos > -1) then
      Result := FThumbsCache.Read(TD.CachePos, OutCacheItem);
end;

function TThumbsCacheOptions.Read(Filename: WideString; var OutCacheItem: TThumbsCacheItem): Boolean;
var
  I: integer;
begin
  Result := False;
  I := FThumbsCache.IndexOf(Filename);
  if I > -1 then
    Result := FThumbsCache.Read(I, OutCacheItem);
end;

function TThumbsCacheOptions.Read(Node: PVirtualNode; OutBitmap: TBitmap): Boolean;
var
  TD: PThumbnailData;
begin
  Result := False;
  if Assigned(FOwner) and FOwner.ValidateThumbnail(Node, TD) then
    if (TD.State = tsValid) and (TD.CachePos > -1) then
      Result := FThumbsCache.Read(TD.CachePos, OutBitmap);
end;

function TThumbsCacheOptions.Read(Filename: WideString; OutBitmap: TBitmap): Boolean;
var
  I: integer;
begin
  Result := False;
  I := FThumbsCache.IndexOf(Filename);
  if I > -1 then
    Result := FThumbsCache.Read(I, OutBitmap);
end;

procedure TThumbsCacheOptions.Assign(Source: TPersistent);
begin
  if Source is TThumbsCacheOptions then begin
    AutoLoad := TThumbsCacheOptions(Source).AutoLoad;
    AutoSave := TThumbsCacheOptions(Source).AutoSave;
    DefaultFilename := TThumbsCacheOptions(Source).DefaultFilename;
    StorageType := TThumbsCacheOptions(Source).StorageType;
    CentralFolder := TThumbsCacheOptions(Source).CentralFolder;
  end
  else
    inherited;
end;

function TThumbsCacheOptions.GetCacheFileFromCentralFolder(Dir: WideString): WideString;
begin
  // Gets the corresponding cache file from the central folder
  Result := FCacheList.GetCacheFileToLoad(Dir);
end;

function TThumbsCacheOptions.RenameCacheFileFromCentralFolder(Dir, NewDirName: WideString; NewCacheFilename: WideString = ''): Boolean;
var
  I: integer;
  D, F, PrevF: WideString;
  NS: TNamespace;
begin
  Result := False;

  if Dir <> '' then
    Dir := IncludeTrailingBackslashW(Dir);
  if NewDirName <> '' then
    NewDirName := IncludeTrailingBackslashW(NewDirName);

  I := IndexOfNameRight(FCacheList, Dir);
  if I > -1 then begin
    // Delete the entry
    PrevF := ValueFromIndexRight(FCacheList, I);
    FCacheList.Delete(I);
    // Rename the previous Dir entry for the new one
    if NewDirName <> '' then
      D := NewDirName
    else
      D := Dir;
    // Rename the previous Cache File for the new one
    if NewCacheFilename <> '' then begin
      F := NewCacheFilename;
      FCacheList.Add(D + '=' + F);
    end
    else
      F := ExtractFileNameW(FCacheList.GetCacheFileToSave(D));
    // Update the BrowsingFolder property
    if SpCompareText(IncludeTrailingBackslashW(BrowsingFolder), Dir) then
      BrowsingFolder := D;
    // Rename the file
    if PrevF <> '' then begin
      NS := TNamespace.CreateFromFileName(FCacheList.CentralFolder + PrevF);
      try
        NS.SetNameOf(F);
      finally
        NS.Free;
      end;
    end;

    Result := True;
  end;
end;

function TThumbsCacheOptions.GetSize: integer;
begin
  Result := FThumbsCache.Size;
end;

function TThumbsCacheOptions.GetThumbsCount: integer;
begin
  Result := FThumbsCache.Count - FThumbsCache.InvalidCount;
end;

procedure TThumbsCacheOptions.SetBrowsingFolder(const Value: WideString);
begin
  if FBrowsingFolder <> Value then begin
    FThumbsCache.Directory := Value;
    FBrowsingFolder := Value;
  end;
end;

procedure TThumbsCacheOptions.SetCacheProcessing(const Value: TThumbsCacheProcessing);
begin
  if FCacheProcessing <> Value then begin
    FCacheProcessing := Value;
  end;
end;

function TThumbsCacheOptions.GetCentralFolder: WideString;
begin
  Result := FCacheList.CentralFolder;
end;

procedure TThumbsCacheOptions.SetCentralFolder(const Value: WideString);
begin
  if FCacheList.CentralFolder <> Value then begin
    FCacheList.CentralFolder := Value;
    FCacheList.LoadFromFile;
  end;
end;

procedure TThumbsCacheOptions.SetCompressed(const Value: boolean);
begin
  if FCompressed <> Value then begin
    FCompressed := Value;
    ClearCache(False);
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TThumbsOptions }

constructor TThumbsOptions.Create(AOwner: TCustomVirtualExplorerListviewEx);
begin
  FOwner := AOwner;
  FCacheOptions := TThumbsCacheOptions.Create(AOwner);

  FThumbsIconAtt.Size.X := 120;
  FThumbsIconAtt.Size.Y := 120;
  FThumbsIconAtt.Spacing.X := 40;
  FThumbsIconAtt.Spacing.Y := 40;

  FBorder := tbFramed;
  FBorderSize := 4;
  FDetailsHeight := 40;
  FHighlight := thMultipleColors;
  FHighlightColor := $EFD3D3;
  FShowSmallIcon := True;
  FShowXLIcons := True;
  FUseShellExtraction := True;
  FUseSubSampling := True;
end;

destructor TThumbsOptions.Destroy;
begin
  FCacheOptions.Free;
  inherited;
end;

function TThumbsOptions.GetWidth: Integer;
begin
  Result := FThumbsIconAtt.Size.X;
end;

function TThumbsOptions.GetHeight: Integer;
begin
  Result := FThumbsIconAtt.Size.Y;
end;

function TThumbsOptions.GetSpaceWidth: Word;
begin
  Result := FThumbsIconAtt.Spacing.X;
end;

function TThumbsOptions.GetSpaceHeight: Word;
begin
  Result := FThumbsIconAtt.Spacing.Y;
end;

procedure TThumbsOptions.SetBorder(const Value: TThumbnailBorder);
begin
  if FBorder <> Value then begin
    FBorder := Value;
    if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate;
  end;
end;

procedure TThumbsOptions.SetBorderSize(const Value: Integer);
begin
  if FBorderSize <> Value then begin
    FBorderSize := Value;
    if FBorderSize < 0 then FBorderSize := 0;
    Owner.ResetThumbImageList;
  end;
end;

procedure TThumbsOptions.SetBorderOnFiles(const Value: Boolean);
begin
  if FBorderOnFiles <> Value then begin
    FBorderOnFiles := Value;
    if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate;
  end;
end;

function TThumbsOptions.GetDetailedHints: Boolean;
begin
  Result := Owner.FListview.DetailedHints;
end;

procedure TThumbsOptions.SetDetailedHints(const Value: Boolean);
begin
  Owner.FListview.DetailedHints := Value;
end;

procedure TThumbsOptions.SetDetails(const Value: Boolean);
begin
  if FDetails <> Value then begin
    FDetails := Value;
    Owner.ResetThumbImageList;
  end;
end;

procedure TThumbsOptions.SetDetailsHeight(const Value: Integer);
begin
  if FDetailsHeight <> Value then begin
    FDetailsHeight := Value;
    Owner.ResetThumbImageList;
  end;
end;

procedure TThumbsOptions.SetWidth(const Value: Integer);
begin
  if Value <> FThumbsIconAtt.Size.X then begin
    FThumbsIconAtt.Size.X := Value;
    Owner.ResetThumbImageList;
    Owner.ResetThumbThread; //reset and reload the thread
  end;
end;

procedure TThumbsOptions.SetHeight(const Value: Integer);
begin
  if Value <> FThumbsIconAtt.Size.Y then begin
    FThumbsIconAtt.Size.Y := Value;
    Owner.ResetThumbImageList;
    Owner.ResetThumbThread; //reset and reload the thread
  end;
end;

procedure TThumbsOptions.SetSpaceWidth(const Value: Word);
begin
  if Value <> FThumbsIconAtt.Spacing.X then begin
    FThumbsIconAtt.Spacing.X := Value;
    if Owner.ViewStyle = vsxThumbs then begin
      Owner.ResetThumbSpacing;
      Owner.SyncInvalidate;
    end;
  end;
end;

procedure TThumbsOptions.SetSpaceHeight(const Value: Word);
begin
  if Value <> FThumbsIconAtt.Spacing.Y then begin
    FThumbsIconAtt.Spacing.Y := Value;
    if Owner.ViewStyle = vsxThumbs then begin
      Owner.ResetThumbSpacing;
      Owner.SyncInvalidate;
    end;
  end;
end;

function TThumbsOptions.GetHideCaptions: Boolean;
begin
  Result := Owner.ChildListview.HideCaptions;
end;

procedure TThumbsOptions.SetHideCaptions(const Value: Boolean);
begin
  Owner.ChildListview.HideCaptions := Value;
end;

procedure TThumbsOptions.SetHighlight(const Value: TThumbnailHighlight);
begin
  if FHighlight <> Value then begin
    FHighlight := Value;
    Owner.SyncInvalidate;
  end;
end;

procedure TThumbsOptions.SetHighlightColor(const Value: TColor);
begin
  if FHighlightColor <> Value then begin
    FHighlightColor := Value;
    if FHighlight = thSingleColor then
      Owner.SyncInvalidate;
  end;
end;

procedure TThumbsOptions.SetUseShellExtraction(const Value: Boolean);
begin
  if FUseShellExtraction <> Value then begin
    FUseShellExtraction := Value;
  end;
end;

procedure TThumbsOptions.SetShowSmallIcon(const Value: Boolean);
begin
  if FShowSmallIcon <> Value then begin
    FShowSmallIcon := Value;
    if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate;
  end;
end;

procedure TThumbsOptions.SetShowXLIcons(const Value: Boolean);
begin
  if FShowXLIcons <> Value then begin
    FShowXLIcons := Value;
    if Owner.ViewStyle = vsxThumbs then Owner.SyncInvalidate;
  end;
end;

procedure TThumbsOptions.SetStretch(const Value: Boolean);
begin
  if FStretch <> Value then begin
    FStretch := Value;
    Owner.ResetThumbThread; //reset and reload the thread
  end;
end;

procedure TThumbsOptions.SetUseSubsampling(const Value: Boolean);
begin
  if FUseSubsampling <> Value then begin
    FUseSubsampling := Value;
    Owner.ResetThumbThread;
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TThumbThread }

constructor TThumbThread.Create(AOwner: TCustomVirtualExplorerListviewEx);
begin
  inherited Create(False);
  FOwner := AOwner;
  {$IFDEF DELPHI_7_UP}
  Priority := tpIdle;
  {$ENDIF}
  ResetThumbOptions;
end;

procedure TThumbThread.ExtractedInfoLoad(Info: PVirtualThreadIconInfo);
begin
  inherited;
  // Use the UserData2 Pointer to pass the PThumbnailData to the Control(s)
  GetMem(Info.UserData2, SizeOf(TThumbnailThreadData));
  FillChar(Info.UserData2^, SizeOf(TThumbnailThreadData), #0);

  //Clone the FThumbThreadData
  with PThumbnailThreadData(Info.UserData2)^ do begin
    ImageWidth := FThumbThreadData.ImageWidth;
    ImageHeight := FThumbThreadData.ImageHeight;
    CompressedStream := FThumbThreadData.CompressedStream;
    State := FThumbThreadData.State;
    if Assigned(FThumbThreadData.MemStream) then begin
      MemStream := TMemoryStream.Create;
      MemStream.LoadFromStream(FThumbThreadData.MemStream);
    end;
  end;

  //Clear the FThumbThreadData
  FreeAndNil(FThumbThreadData.MemStream);
  FillChar(FThumbThreadData, SizeOf(FThumbThreadData), #0);
end;

function TThumbThread.CreateThumbnail(Filename: WideString;
  var Thumbnail: TBitmap; var ImageWidth, ImageHeight: integer; var CompressIt: boolean): Boolean;
{$IFDEF USEIMAGEEN}
var
  B: TBitmap;
  DestR: TRect;
{$ENDIF}
begin
  CompressIt := false;
  Result := False;
  try
    {$IFDEF USEIMAGEEN}
    if IsDelphiSupportedImageFile(Filename) then //common image, do default
      Result := MakeThumbFromFile(Filename, Thumbnail, FThumbWidth, FThumbHeight,
        false, FTransparentColor, FThumbStretch, FThumbSubsampling, ImageWidth, ImageHeight)
    else begin
      B := TBitmap.Create;
      try
        if LoadImageEnGraphic(Filename, B) then begin
          ImageWidth := B.Width;
          ImageHeight := B.Height;
          DestR := RectAspectRatio(ImageWidth, ImageHeight, FThumbWidth, FThumbHeight, false, FThumbStretch);
          InitBitmap(Thumbnail, DestR.Right, DestR.Bottom, FTransparentColor);
          // StretchDraw is NOT THREADSAFE!!! Use SpStretchDraw instead
          SpStretchDraw(B, Thumbnail, DestR, true);
          Result := true;
        end;
      finally
        B.Free;
      end;
    end;
    {$ELSE}
    Result := MakeThumbFromFile(Filename, Thumbnail, FThumbWidth, FThumbHeight,
      false, FTransparentColor, FThumbStretch, FThumbSubsampling, ImageWidth, ImageHeight);
    {$ENDIF}
  except
    //don't raise any image errors, just ignore them, the state will be tsInvalid
    FThumbThreadData.State := tsInvalid;
  end;

  CompressIt := Result and (ImageWidth > 200) and (ImageHeight > 200);
end;

procedure TThumbThread.ExtractInfo(PIDL: PItemIDList; Info: PVirtualThreadIconInfo);
var
  Folder, Desktop: IShellFolder;
  OldCB: Word;
  OldPIDL: PItemIDList;
  B: TBitmap;
  AllsOk: Boolean;

  function ExtractImageFromPIDL(OutBitmap: TBitmap): Boolean;
  var
    StrRet: TSTRRET;
    WS, Ext: WideString;
    ExtractImage: IExtractImage;
    Buffer: array[0..MAX_PATH] of WideChar;
    Priority, Flags: Longword;
    Size: TSize;
    Bits: HBitmap;
    ByShellExtract: Boolean;
  begin
    Result := False;
    if Succeeded(Folder.GetDisplayNameOf(OldPIDL, SHGDN_FORADDRESSBAR or SHGDN_FORPARSING, StrRet)) then
    begin
      WS := StrRetToStr(StrRet, OldPIDL);
      Ext := WideLowerCase(ExtractFileExtW(WS));

      // ByShellExtract is hardcoded to LargeIcon, take a look at TSyncListView.OwnerDataHint
      ByShellExtract := Info.LargeIcon;

      if not ByShellExtract then
        Result := CreateThumbnail(WS, OutBitmap, FThumbThreadData.ImageWidth, FThumbThreadData.ImageHeight, FThumbThreadData.CompressedStream)
      else
        // Load it with the Shell IExtract Interface
        // If ThumbsOptions.UseShellExtract = False and the file extension is in
        // ShellExtractExtensionsList then ByShellExtract will be True.
        // Suppose you want just images + html files, then you should turn off
        // UseShellExtract and add '.html' to the ShellExtractExtensionsList.
        if Succeeded(Folder.GetUIObjectOf(0, 1, OldPIDL, IID_IExtractImage, nil, ExtractImage)) then
        begin
          Priority := IEI_PRIORITY_NORMAL;
          Flags := IEIFLAG_ASPECT or IEIFLAG_OFFLINE;
          Size.cx := ThumbWidth;
          Size.cy := ThumbHeight;
          if Succeeded(ExtractImage.GetLocation(Buffer, SizeOf(Buffer), Priority, Size, 32, Flags))
            and Succeeded(ExtractImage.Extract(Bits)) and (Bits <> 0) then
          begin
            OutBitmap.Handle := Bits;
            Result := True;
          end;
        end;
    end;
  end;


begin
  StripLastID(PIDL, OldCB, OldPIDL);
  try
    SHGetDesktopFolder(Desktop);
    {JIM // Special case for the desktop children, plus memory leak fix}
    if PIDL <> OldPIDL then
      AllsOk := Succeeded(Desktop.BindToObject(PIDL, nil, IID_IShellFolder, Folder))
    else begin
      Folder := Desktop;
      AllsOk := Assigned(Folder)
    end;

    if AllsOk then
    begin
      OldPIDL.mkid.cb := OldCB;

      FThumbThreadData.ImageWidth := 0;
      FThumbThreadData.ImageHeight := 0;
      FThumbThreadData.CompressedStream := false;
      FThumbThreadData.State := tsInvalid;
      FThumbThreadData.MemStream := nil;

      B := TBitmap.Create;
      try
        B.Canvas.Lock;
        if ExtractImageFromPIDL(B) then
        begin
          FThumbThreadData.MemStream := TMemoryStream.Create;
          try
            B.SaveToStream(FThumbThreadData.MemStream);
            FThumbThreadData.CompressedStream := FThumbCompression and FThumbThreadData.CompressedStream;
            if FThumbThreadData.CompressedStream then //JPEG compressed
              ConvertBitmapStreamToJPGStream(FThumbThreadData.MemStream, 60);
            FThumbThreadData.State := tsValid;
          except
            FreeAndNil(FThumbThreadData.MemStream);
          end;
        end;
      finally
        B.Canvas.Unlock;
        FreeAndNil(B);
      end;
    end;
  finally
    if Assigned(OldPIDL) then
      OldPIDL.mkid.cb := OldCB
  end
end;

procedure TThumbThread.InvalidateExtraction;
begin
  inherited;
  if Assigned(FThumbThreadData.MemStream) then
  begin
    FreeAndNil(FThumbThreadData.MemStream);
    FillChar(FThumbThreadData, SizeOf(FThumbThreadData), #0)
  end
end;

procedure TThumbThread.ReleaseItem(Item: PVirtualThreadIconInfo; const Malloc: IMalloc);
begin
  if Assigned(Item) then
  begin
    // Will only be valid if the image has been extracted already
    if Assigned(PThumbnailThreadData(Item.UserData2)) then
    begin
      FreeAndNil(PThumbnailThreadData(Item.UserData2).MemStream);
      FreeMem(PThumbnailThreadData(Item.UserData2));
    end;
  end;
  inherited;
end;

procedure TThumbThread.ResetThumbOptions;
begin
  QueryList.LockList;
  try
    FThumbWidth := FOwner.ThumbsOptions.Width;
    FThumbHeight := FOwner.ThumbsOptions.Height;
    FThumbStretch := FOwner.ThumbsOptions.Stretch;
    FThumbSubsampling := FOwner.ThumbsOptions.UseSubsampling;
    FThumbCompression := FOwner.ThumbsOptions.CacheOptions.Compressed;
    FTransparentColor := FOwner.Color;
  finally
    QueryList.UnlockList;
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TUnicodeOwnerDataListView }

constructor TUnicodeOwnerDataListView.Create(AOwner: TComponent);
begin
  inherited;
  FEditingItemIndex := -1;
  OwnerData := true;
  Win32PlatformIsUnicode := (Win32Platform = VER_PLATFORM_WIN32_NT);
  FIsComCtl6 := GetComCtlVersion >= $00060000;
end;

procedure TUnicodeOwnerDataListView.CreateWnd;
begin
  inherited;
  // Enables alpha blended selection if ComCtrl 6 is used
  // Unfortunately the flicker is unbearable
  // if IsComCtl6 then
  //   ListView_SetExtendedListViewStyle(Handle, LVS_EX_DOUBLEBUFFER);
end;

procedure TUnicodeOwnerDataListView.CreateWindowHandle(const Params: TCreateParams);
var
  Column: TLVColumn;
begin
  // Do not call inherited, we need to create the unicode handle
  CreateUnicodeHandle(Self, Params, WC_LISTVIEW);
  if (Win32PlatformIsUnicode) then begin
    ListView_SetUnicodeFormat(Handle, True);
    // the only way I could get editing to work is after a column had been inserted
    Column.mask := 0;
    ListView_InsertColumn(Handle, 0, Column);
    ListView_DeleteColumn(Handle, 0);
  end;
end;

procedure TUnicodeOwnerDataListView.WndProc(var Msg: TMessage);
var
  Item: TListitem;
  P: TPoint;
  R: TRect;
begin
  // OwnerData TListview bug on WinXP using ComCtl 6: the white space between
  // icons (vsxIcon or vsxThumbs) becomes selectable, but not the space between
  // the captions.
  Case Msg.Msg of
    WM_LBUTTONDOWN..WM_MBUTTONDBLCLK:
      if HideCaptions or FIsComCtl6 then begin
        P := Point(Msg.LParamLo, Msg.LParamHi);
        Item := GetItemAt(P.X, P.Y);
        if Assigned(Item) then begin
          // Disallow the click on the caption if HideCaption is true
          if HideCaptions then begin
            R := GetLVItemRect(Item.Index, drLabel);
            if PtInRect(R, P) then
              Exit;
          end;
          // Disallow the click on the left and right side of the Icon when using ComCtrl 6
          if FIsComCtl6 then begin
            R := GetLVItemRect(Item.Index, drBounds);
            if not PtInRect(R, P) then begin
              Selected := nil;
              Exit;
            end;
          end;
        end
      end;
  end;

  inherited;
end;

procedure TUnicodeOwnerDataListView.CNNotify(var Message: TWMNotify);
var
  Item: TListItem;
  S: string;
  LVEditHandle: THandle;
begin
  if (not Win32PlatformIsUnicode) then
    inherited
  else begin
    with Message do
    begin
      Case NMHdr^.code of
        HDN_TRACKW:
          begin
            NMHdr^.code := HDN_TRACKA;
            try
              inherited;
            finally
              NMHdr^.code := HDN_TRACKW;
            end;
          end;
        LVN_GETDISPINFOW:
          begin
            // call inherited without the LVIF_TEXT flag
            CurrentDispInfo := PLVDispInfoW(NMHdr);
            try
              OriginalDispInfoMask := PLVDispInfoW(NMHdr)^.item.mask;
              PLVDispInfoW(NMHdr)^.item.mask := PLVDispInfoW(NMHdr)^.item.mask and (not LVIF_TEXT);
              try
                NMHdr^.code := LVN_GETDISPINFOA;
                try
                  inherited;
                finally
                  NMHdr^.code := LVN_GETDISPINFOW;
                end;
              finally
                PLVDispInfoW(NMHdr)^.item.mask := OriginalDispInfoMask;
              end;
            finally
              CurrentDispInfo := nil;
            end;

            // handle any text info
            with PLVDispInfoW(NMHdr)^.item do
              if ((mask and LVIF_TEXT) <> 0) and (iSubItem = 0) then
                if HideCaptions and (FEditingItemIndex <> iItem) then
                  pszText[0] := #0
                else
                  StrLCopyW(pszText, PWideChar(GetItemCaption(iItem)), cchTextMax - 1);
          end;
        LVN_ODFINDITEMW:
          with PNMLVFindItem(NMHdr)^ do
          begin
            if ((lvfi.flags and LVFI_PARTIAL) <> 0) or ((lvfi.flags and LVFI_STRING) <> 0) then
              PWideFindString := TLVFindInfoW(lvfi).psz
            else
              PWideFindString := nil;
            lvfi.psz := nil;
            NMHdr^.code := LVN_ODFINDITEMA;
            try
              inherited; {will result in call to OwnerDataFind}
            finally
              TLVFindInfoW(lvfi).psz := PWideFindString;
              NMHdr^.code := LVN_ODFINDITEMW;
              PWideFindString := nil;
            end;
          end;
        LVN_BEGINLABELEDITW:
          begin
            Item := GetItem(PLVDispInfoW(NMHdr)^.item);
            if not CanEdit(Item) then Result := 1;
          end;
        LVN_ENDLABELEDITW:
          with PLVDispInfoW(NMHdr)^ do
            if (item.pszText <> nil) and (item.IItem <> -1) then
              Edit(TLVItemA(item));
        LVN_GETINFOTIPW:
          begin
            NMHdr^.code := LVN_GETINFOTIPA;
            try
              inherited;
            finally
              NMHdr^.code := LVN_GETINFOTIPW;
            end;
          end;
        else
          inherited;
      end;
    end;
  end;

  // Handle the edit control:
  // The Edit control is not showed correctly when the font size
  // is large (Height > 15), this is visible in vsReport, vsList and vsSmallIcon
  // viewstyles. We must reshow the Edit control.
  Case Message.NMHdr^.code of
    LVN_GETDISPINFO:  // handle HideCaptions for Ansi text
      if not Win32PlatformIsUnicode and HideCaptions then
          with PLVDispInfoA(Message.NMHdr)^.item do
            if ((mask and LVIF_TEXT) <> 0) and (iSubItem = 0) and (FEditingItemIndex = iItem) then
            pszText[0] := #0;
    LVN_BEGINLABELEDIT, LVN_BEGINLABELEDITW:
      if Message.Result = 0 then begin
        LVEditHandle := ListView_GetEditControl(Handle);
        if LVEditHandle <> 0 then begin
          SetWindowPos(LVEditHandle, 0, 0, 0, 500, 200, SWP_SHOWWINDOW + SWP_NOMOVE);
          if Win32PlatformIsUnicode then begin
            FEditingItemIndex := PLVDispInfoW(Message.NMHdr)^.item.iItem;
            if HideCaptions then
              SendMessageW(LVEditHandle, WM_SETTEXT, 0, Longint(PWideChar(GetItemCaption(FEditingItemIndex))));
          end
          else begin
            FEditingItemIndex := PLVDispInfoA(Message.NMHdr)^.item.iItem;
            if HideCaptions then begin
              S := GetItemCaption(FEditingItemIndex);
              SendMessageA(LVEditHandle, WM_SETTEXT, 0, Longint(PAnsiChar(S)));
            end;
          end;
        end;
      end;
    LVN_ENDLABELEDIT, LVN_ENDLABELEDITW:
      FEditingItemIndex := -1;
  end;
end;

procedure TUnicodeOwnerDataListView.WMCtlColorEdit(var Message: TWMCtlColorEdit);
begin
  Message.Result := DefWindowProc(Handle, Message.Msg, Message.ChildDC, Message.ChildWnd);
end;

procedure TUnicodeOwnerDataListView.WMWindowPosChanging(var Message: TWMWindowPosChanging);
begin
  inherited;
  // Bug in ComCtrl 6 in WinXP, does not redraw on resize
  if FIsComCtl6 then
    InvalidateRect(Handle, nil, False);
end;

function TUnicodeOwnerDataListView.GetItem(Value: TLVItemW): TListItem;
begin
  Result := Items[Value.iItem];
end;

function TUnicodeOwnerDataListView.GetHideCaptions: Boolean;
begin
  Result := FHideCaptions;
end;

procedure TUnicodeOwnerDataListView.SetHideCaptions(const Value: Boolean);
begin
  if Value <> FHideCaptions then begin
    FHideCaptions := Value;
    Invalidate;
  end;
end;

function TUnicodeOwnerDataListView.GetLVItemRect(Index: integer; DisplayCode: TDisplayCode): TRect;
var
  RealWidthHalf: integer;
  Half: integer;
const
  IconSizePlus = 16;
  Codes: array[TDisplayCode] of Longint = (LVIR_BOUNDS, LVIR_ICON, LVIR_LABEL,
    LVIR_SELECTBOUNDS);
begin
  ListView_GetItemRect(Handle, Index, Result, Codes[DisplayCode]);
  if FIsComCtl6 and (DisplayCode <> drLabel) and (ViewStyle = vsIcon) and Assigned(LargeImages) then begin
    // Another WinXP painting issue...
    // Item.displayrect() returns a bigger TRect
    // We need to adjust it here
    RealWidthHalf := (LargeImages.Width + IconSizePlus) div 2;
    Half := (Result.Right - Result.Left) div 2 + Result.Left;
    Result.Left := Half - RealWidthHalf;
    Result.Right := Half + RealWidthHalf;
  end;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TSyncListView }

constructor TSyncListView.Create(AOwner: TComponent);
begin
  inherited;
  FDefaultTooltipsHandle := 0;

  Visible := false;
  ControlStyle := ControlStyle + [csNoDesignVisible];
  HideSelection := false;
  IconOptions.AutoArrange := true;
  FFirstShiftClicked := -1;
  FThumbnailHintBitmap := TBitmap.Create;
end;

destructor TSyncListView.Destroy;
begin
  FThumbnailHintBitmap.Free;
  inherited;
end;

procedure TSyncListView.CreateHandle;
var
  H: THandle;
begin
  inherited;
  H := ListView_GetToolTips(Handle);
  if H <> 0 then
    FDefaultTooltipsHandle := H;
  UpdateHintHandle;

  // Boris: When the handle is recreated the icon spacing is not updated
  if (HandleAllocated) and (VETController.ViewStyle = vsxThumbs) then
    VETController.ResetThumbSpacing;
end;

function TSyncListView.IsItemGhosted(Item: TListitem): Boolean;
var
  Node: PVirtualNode;
begin
  Result := false;
  if Assigned(Item) then
    if Item.Cut then
      Result := true //Hidden file
    else begin
      Node := PVirtualNode(Item.Data);
      if Assigned(Node) and (vsCutOrCopy in Node.States) then
        Result := true; //Marked as Cut or Copy
    end;
end;

procedure TSyncListView.FetchThumbs(StartIndex, EndIndex: integer);
begin
  //Fire the thread to create ALL the thumbnails at once
  if (Items.Count > 0) and (StartIndex > -1) and (StartIndex < Items.Count) and
  (EndIndex > -1) and (EndIndex < Items.Count) then
     OwnerDataHint(StartIndex, EndIndex);
end;

procedure TSyncListView.UpdateArrangement;
var
  i, Max, Temp: integer;
begin
  if Visible then begin
    //Update column size
    if (ViewStyle in [vsSmallIcon, vsList]) and (Items.Count > 0) then begin
      Max := 0;
      for i := 0 to Items.Count - 1 do
      begin
        Temp := TextExtentW(Items[I].Caption, Canvas).cx;
        if Temp > Max then
          Max := Temp;
      end;
      ListView_SetColumnWidth(Handle, 0, Max + SmallImages.Width + 10);
    end;

    //Update arrangement and scrollbars
    Parent.DisableAlign;
    try
      Width := Width + 1;
      Width := Width - 1;
    finally
      Parent.EnableAlign;
    end;
  end;
end;

procedure TSyncListView.CNNotify(var Message: TWMNotify);
var
  TmpItem: TLVItem;
  ChangeEventCalled, DummyB: boolean;
  Node: PVirtualNode;
begin
  //Update Selection and Focused Item in VET
  if (Message.NMHdr^.code = LVN_ITEMCHANGED) and Assigned(VETController) and (not FSelectionPause) then
    with PNMListView(Message.NMHdr)^ do
      if uChanged = LVIF_STATE then
        if not Assigned(Items[iItem]) then begin
          FPrevEditing := false;  //see CMEnter
          FFirstShiftClicked := -1;
          VETController.ClearSelection;
        end
        else begin
          Node := PVirtualNode(Items[iItem].Data);
          if Assigned(Node) then begin
            ChangeEventCalled := false;
            if ((uOldState and LVIS_SELECTED <> 0) and (uNewState and LVIS_SELECTED = 0)) or
               ((uOldState and LVIS_SELECTED = 0) and (uNewState and LVIS_SELECTED <> 0)) then begin
              VETController.Selected[Node] := (uNewState and LVIS_SELECTED <> 0);
              ChangeEventCalled := true; //changing the selection will call the OnChange event
            end;
            if (uOldState and LVIS_FOCUSED = 0) and (uNewState and LVIS_FOCUSED <> 0) then begin
              FPrevEditing := false;  //see CMEnter
              VETController.FocusedNode := Node;
              if not ChangeEventCalled and Assigned(VETController.OnChange) then
                VETController.OnChange(VETController, Node); //call VET event
            end;
          end;
        end;

  // The VCL totally destroys the speed of this message we will take care of it
  if Message.NMHdr^.code <> NM_CUSTOMDRAW then
    inherited;

  // Handle cdPostPaint, Delphi doesn't do it :(
  if (Message.NMHdr^.code = NM_CUSTOMDRAW) and Assigned(Canvas) then
    with PNMCustomDraw(Message.NMHdr)^ do begin
      case PNMCustomDraw(Message.NMHdr)^.dwDrawStage of
        CDDS_PREPAINT:
          if not FInPaintCycle then
            Message.Result := CDRF_SKIPDEFAULT
          else
            Message.Result := CDRF_NOTIFYITEMDRAW;
        CDDS_ITEMPREPAINT:
          begin
            Canvas.Lock;
            try
              //We are drawing an item, NOT a subitem, in a postpaint stage
              FillChar(TmpItem, SizeOf(TmpItem), 0);
              TmpItem.iItem := dwItemSpec;
              DummyB := true;
              Canvas.Handle := hdc;

              //Assign the font and brush
              Canvas.Font.Assign(Font);
              Canvas.Brush.Assign(Brush);

              if Assigned(OnAdvancedCustomDrawItem) then
                OnAdvancedCustomDrawItem(Self, Items[TmpItem.iItem], TCustomDrawState(Word(uItemState)), cdPrePaint , DummyB);

              //Set the font and brush colors
              if IsBackgroundValid then begin
                SetBkMode(hdc, TRANSPARENT);
                with PNMLVCustomDraw(Message.NMHdr)^ do begin
                  clrText := CLR_NONE;
                  clrTextBk := CLR_NONE;
                end;
              end
              else
                with PNMLVCustomDraw(Message.NMHdr)^ do begin
                  clrText := ColorToRGB(Canvas.Font.Color);
                  clrTextBk := ColorToRGB(Canvas.Brush.Color);
                end;

              Canvas.Handle := 0;
            finally
              Canvas.Unlock;
            end;
            Message.Result := CDRF_NOTIFYPOSTPAINT;
          end;
        CDDS_ITEMPOSTPAINT:
          begin
            Canvas.Lock;
            try
             //We are drawing an item, NOT a subitem, in a postpaint stage
              Message.Result := CDRF_DODEFAULT;
              FillChar(TmpItem, SizeOf(TmpItem), 0);
              TmpItem.iItem := dwItemSpec;
              DummyB := true;
              Canvas.Handle := hdc;
              if Assigned(OnAdvancedCustomDrawItem) then
                OnAdvancedCustomDrawItem(Self, Items[TmpItem.iItem], TCustomDrawState(Word(uItemState)), cdPostPaint, DummyB);
              Canvas.Handle := 0;
            finally
              Canvas.Unlock;
            end;
          end;
      end;
    end;

  // Fire OnEditCancelled
  if (Message.NMHdr^.code = LVN_ENDLABELEDITW) and Assigned(VETController.OnEditCancelled) then
    if Win32PlatformIsUnicode then begin
       with PLVDispInfoW(Message.NMHdr)^ do
         if (item.pszText = nil) or (item.IItem = -1) then
           VETController.OnEditCancelled(VETController, 0);
    end
    else begin
       with PLVDispInfo(Message.NMHdr)^ do
         if (item.pszText = nil) or (item.IItem = -1) then
           VETController.OnEditCancelled(VETController, 0);
    end;
end;

procedure TSyncListView.CMEnter(var Message: TCMEnter);
begin
  //When the Listview is unfocused and a previously selected item caption is
  //clicked it enters in editing mode. This is an incorrect TListview behavior.
  //Set a flag, and deactivate it in CanEdit and when the selection changes in CNNotify
  FPrevEditing := true;
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnEnter) then VETController.OnEnter(VETController);
end;

procedure TSyncListView.CMExit(var Message: TCMExit);
begin
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnExit) then VETController.OnExit(VETController);
end;

procedure TSyncListView.CMMouseWheel(var Message: TCMMouseWheel);
var
  I, dy: integer;
begin
  //Scroll by thumbs
  if (VETController.ViewStyle = vsxThumbs) and (Items.Count > 0) and Assigned(Items[0]) then begin
    if (IconOptions.Arrangement = iaTop) then begin
      I := VETController.ThumbsOptions.Height + VETController.ThumbsOptions.SpaceHeight + 8;
      dy := (Message.WheelDelta div WHEEL_DELTA) * I;
      Scroll(0, -dy);
      Message.Result := 1;
    end
    else begin
      I := VETController.ThumbsOptions.Width + VETController.ThumbsOptions.SpaceHeight + 8;
      dy := (Message.WheelDelta div WHEEL_DELTA) * I;
      Scroll(-dy, 0);
      Message.Result := 1;
    end;
  end
  else
    inherited;
end;

procedure TSyncListView.LVMInsertColumn(var Message: TMessage);
begin
  // Fix the VCL bug for XP
  with PLVColumn(Message.LParam)^ do
  begin
    // Fix TListView report mode bug.
    // But this screws up List style ... grrrr
    if (iImage = - 1) and (ViewStyle = vsReport) then
      Mask := Mask and not LVCF_IMAGE;
  end;
  inherited;
end;

procedure TSyncListView.LVMSetColumn(var Message: TMessage);
begin
  // Fix the VCL bug for XP
  with PLVColumn(Message.LParam)^ do
  begin
    // Fix TListView report mode bug.
    // But this screws up List style ... grrrr
    if (iImage = - 1) and (ViewStyle = vsReport) then
      Mask := Mask and not LVCF_IMAGE;
  end;
  inherited;
end;

procedure TSyncListView.WndProc(var Msg: TMessage);
var
  ContextResult: LRESULT;
begin
  inherited;
  if Assigned(VETController) then
    Case Msg.Msg of
      WM_INITMENUPOPUP, WM_DRAWITEM, WM_MEASUREITEM:
        if Assigned(FSavedPopupNamespace) then //show the Send To item in the contextmenu
          FSavedPopupNamespace.HandleContextMenuMsg(Msg.Msg, Msg.WParam, Msg.LParam, ContextResult);
    end;
end;

function TSyncListView.OwnerDataHint(StartIndex, EndIndex: Integer): Boolean;
var
  I, CacheIndex, W, H: integer;
  CI: TThumbsCacheItem;
  WSExt: WideString;
  Node: PVirtualNode;
  NS: TNamespace;
  Data: PThumbnailData;
  B: TBitmap;
  Cache: TThumbsCache;
  ByImageLibrary, ByShellExtract: boolean;
begin
  Result := inherited OwnerDataHint(StartIndex, EndIndex);

  if (csDesigning in ComponentState) or (not Assigned(VETController)) or (OwnerDataPause) or (Items.Count = 0) then
    exit;

  for I := StartIndex to EndIndex do begin
    Node := GetChildByIndex(VETController.RootNode, I); // This is fast enough
    if VETController.ValidateNamespace(Node, NS) then
    begin
      {$IFDEF THREADEDICONS}
      // Call the VET icon thread to pre-load the index
      if not NS.ThreadedIconLoaded and (VETController.ThreadedImagesEnabled) then
      begin
        if not NS.ThreadIconLoading then
        begin
          NS.ThreadIconLoading := True;
          if VETController.ViewStyle = vsxIcon then
            ImageThreadManager.AddNewItem(VETController, WM_VTSETICONINDEX, NS.AbsolutePIDL, True, Node, I)
          else
            ImageThreadManager.AddNewItem(VETController, WM_VTSETICONINDEX, NS.AbsolutePIDL, False, Node, I)
        end;
      end;
      {$ENDIF}

      // Call the thumb thread
      if (VETController.ViewStyle = vsxThumbs) and VETController.ValidateThumbnail(Node, Data) and
        (Data.State = tsEmpty) and (NS.FileSystem) and (not NS.Folder) then
      begin
        Data.State := tsInvalid;
        if not (vsInitialized in Node.States) then
          VETController.InitNode(Node);

        WSExt := ExtractFileExtW(NS.NameForParsing);
        if VETController.ExtensionsExclusionList.IndexOf(WSExt) > -1 then
        begin
          ByImageLibrary := False;
          ByShellExtract := False;
        end else
        begin
          ByImageLibrary := VETController.ExtensionsList.IndexOf(WSExt) > -1;
          ByShellExtract := False;
          if not ByImageLibrary then
            if VETController.ThumbsOptions.UseShellExtraction or (VETController.ShellExtractExtensionsList.IndexOf(WSExt) > -1) then
              ByShellExtract := SupportsShellExtract(NS);
        end;

        if ByImageLibrary or ByShellExtract then
        begin
          Cache := VETController.ThumbsOptions.CacheOptions.FThumbsCache;

          // If the cache was loaded from file we don't need to call the thread :)
          if Cache.LoadedFromFile and not Data.Reloading then begin
            CacheIndex := Cache.IndexOf(NS.NameForParsing);
            if (CacheIndex > -1) and Cache.Read(CacheIndex, CI) then begin
              Data.CachePos := CacheIndex;
              Data.State := tsValid;
              // Update the cache entry if the file was changed
              if not VETController.DoThumbsCacheItemLoad(NS, CI) then
                VETController.ThumbsOptions.CacheOptions.Reload(Node);
            end;
          end
          else begin
            //let the application decide
            if Assigned(VetController.OnThumbsCacheItemRead) then begin
              B := TBitmap.Create;
              try
                if not VETController.DoThumbsCacheItemRead(NS.NameForParsing, B) then begin
                  Data.CachePos := -1;
                  Data.State := tsValid;
                end;
              finally
                B.Free;
              end;
            end;
          end;

          if (Data.State <> tsValid) and Assigned(VETController.ThumbThread) then
          begin
            //Process the thumb outside the thread?
            if Assigned(VetController.OnThumbsCacheItemProcessing) then begin
              B := TBitmap.Create;
              try
                B.Width := VETController.ThumbsOptions.Width;
                B.Height := VETController.ThumbsOptions.Height;
                if not VETController.DoThumbsCacheItemProcessing(NS, B, W, H) then
                  if not Assigned(VETController.OnThumbsCacheItemAdd) or VETController.DoThumbsCacheItemAdd(NS, B, W, H) then begin
                    Data.CachePos := Cache.Add(NS.NameForParsing, '', '', NS.LastWriteDateTime, W, H, False, B);
                    Data.State := tsValid;
                  end;
              finally
                B.Free;
              end;
            end;
            //Call the thread
            if Data.State <> tsValid then begin
              if VETController.ThumbsOptions.LoadAllAtOnce or (VETController.ThumbsOptions.CacheOptions.CacheProcessing = tcpAscending) then
                VETController.ThumbThread.InsertNewItem(VETController, WM_VLVEXTHUMBTHREAD, NS.AbsolutePIDL, ByShellExtract, Node, I) //ByShellExtract hardcoded to LargeIcon parameter
              else
                VETController.ThumbThread.AddNewItem(VETController, WM_VLVEXTHUMBTHREAD, NS.AbsolutePIDL, ByShellExtract, Node, I); //ByShellExtract hardcoded to LargeIcon parameter
              Data.State := tsProcessing; //it should be tsProcessing at first
            end;
          end;
        end;
      end;
    end;
  end;
end;

function TSyncListView.OwnerDataFetch(Item: TListItem; Request: TItemRequest): Boolean;
var
  NS: TNamespace;
  Node: PVirtualNode;
  WS: WideString;
begin
  Result := True;
  if (csDesigning in ComponentState) or (not Assigned(VETController)) or
    (Items.Count = 0) or (Item.Index < 0) or (Item.Index >= Items.Count) then Exit;

  Node := GetChildByIndex(VETController.RootNode, Item.Index); // this is fast enough
  if VETController.ValidateNamespace(Node, NS) then begin
    if not (vsInitialized in Node.States) then
      VETController.InitNode(Node);
    Item.Data := Node; // Keep a reference of the Node

    // Fill the Item caption for W9x, the displayed caption is in unicode.
    WS := NS.NameInFolder;
    FVETController.DoGetVETText(0, Node, NS, WS);
    Item.Caption := WS;

    if irImage in Request then
    begin
      {$IFDEF THREADEDICONS}
      if not (csDesigning in ComponentState) and VETController.ThreadedImagesEnabled and not NS.ThreadedIconLoaded then
      begin
        // Show default images
        if NS.Folder and NS.FileSystem then Item.ImageIndex := VETController.UnknownFolderIconIndex
        else Item.ImageIndex := VETController.UnknownFileIconIndex
      end
      else begin
        if NS.ThreadIconLoading then begin
          if NS.Folder and NS.FileSystem then Item.ImageIndex := VETController.UnknownFolderIconIndex
          else Item.ImageIndex := VETController.UnknownFileIconIndex
        end else
          Item.ImageIndex := NS.GetIconIndex(false, icLarge);
      end;
      {$ELSE}
      Item.ImageIndex := NS.GetIconIndex(false, icLarge);
      {$ENDIF}
      Item.Cut := NS.Ghosted;

      if not (toHideOverlay in VETController.TreeOptions.VETImageOptions) and Assigned(NS.ShellIconOverlayInterface) then
        Item.OverlayIndex := NS.OverlayIndex - 1
      else
        if NS.Link then
          Item.OverlayIndex := 1
        else
          if NS.Share then Item.OverlayIndex := 0
          else Item.OverlayIndex := -1;
    end;
  end;
end;

function TSyncListView.OwnerDataFind(Find: TItemFind;
  const FindString: AnsiString; const FindPosition: TPoint;
  FindData: Pointer; StartIndex: Integer; Direction: TSearchDirection;
  Wrap: Boolean): Integer;
//OnDataFind gets called in response to calls to FindCaption, FindData,
//GetNearestItem, etc. It also gets called for each keystroke sent to the
//ListView (for incremental searching)
var
  I: Integer;
  Found: Boolean;
  Node: PVirtualNode;
  NS: TNamespace;
  WS: WideString;
begin
  Result := -1;
  if Assigned(PWideFindString) then
    WS := PWideFindString
  else
    WS := FindString;

  //search in VET
  if Assigned(VETController) and (not OwnerDataPause) then begin
    I := StartIndex;
    Found := false;
    if (Find = ifExactString) or (Find = ifPartialString) then
    begin
      WS := WideLowerCase(WS);
      repeat
        if I > Items.Count-1 then
          if Wrap then I := 0 else Exit;
        Node := PVirtualNode(Items[I].Data);
        if VETController.ValidateNamespace(Node, NS) then
          Found := Pos(WS, WideLowerCase(NS.NameInFolder)) = 1;
        Inc(I);
      until Found or (I = StartIndex);
      if Found then Result := I-1;
    end;
  end;

  // Fire OnDataFind, don't call inherited
  if Assigned(OnDataFind) then
    OnDataFind(Self, Find, WS, FindPosition, FindData, StartIndex, Direction, Wrap, Result);
end;

function TSyncListView.OwnerDataStateChange(StartIndex, EndIndex: Integer;
  OldState, NewState: TItemStates): Boolean;
begin
  // In OwnerDraw, the selections with the SHIFT and Mouse fire LVN_ODSTATECHANGED
  // and not the the CN_NOTIFY message
  Result := inherited OwnerDataStateChange(StartIndex, EndIndex, OldState, NewState);
  if Assigned(VETController) then begin
    VETController.SyncSelectedItems(False);
    if Assigned(VETController.OnChange) then
      VETController.OnChange(VETController, nil);
  end;
end;

function TSyncListView.GetItemCaption(Index: integer): WideString;
var
  NS: TNamespace;
begin
  Result := '';
  if Assigned(VETController) then
    if FVETController.ValidateNamespace(PVirtualNode(Items[Index].Data), NS) then
    begin
      Result := NS.NameInFolder;
      FVETController.DoGetVETText(0, PVirtualNode(Items[Index].Data), NS, Result);
    end;
end;

function TSyncListView.GetHideCaptions: Boolean;
begin
  Result := (inherited GetHideCaptions);
end;

function TSyncListView.IsBackgroundValid: Boolean;
var
  BK: TLVBKImage;
begin
  Result := False;
  if Assigned(VETController) and (toShowBackground in VETController.TreeOptions.PaintOptions) then
  begin
    Fillchar(BK, SizeOf(BK), 0);
    ListView_GetBkImage(Handle, @BK);
    if BK.ulFlags > 0 then
      Result := True;
  end;
end;

procedure TSyncListView.Edit(const Item: TLVItem);
var
  WS: WideString;
  EditItem: TListItem;
  Node: PVirtualNode;
  NS: TNamespace;
  TD: PThumbnailData;
  ExtChanged: Boolean;
begin
  inherited;
  if (not Win32PlatformIsUnicode) then
    WS := Item.pszText
  else
    WS := TLVItemW(Item).pszText;
  EditItem := GetItem(TLVItemW(Item));
  if Assigned(VETController) and Assigned(EditItem) then begin
    Node := PVirtualNode(EditItem.Data);
    if VETController.ValidateNamespace(Node, NS) and VETController.ValidateThumbnail(Node, TD) then begin
      ExtChanged := not SpCompareText(NS.Extension, ExtractFileExtW(WS));
      if NS.SetNameOf(WS) then begin
        NS.InvalidateCache;
        if ExtChanged then begin
          if TD.State <> tsEmpty then
            TD.State := tsEmpty;
        end;
      end;
      if Assigned(VETController.OnEdited) then VETController.OnEdited(VETController, Node, 0);
    end;
  end;
end;

function TSyncListView.CanEdit(Item: TListItem): Boolean;
var
  Node: PVirtualNode;
begin
  if FPrevEditing or (toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin
    FPrevEditing := false;  //see CMEnter
    Result := false;
  end
  else begin
    Result := inherited CanEdit(Item);
    if Assigned(Item) then begin
      if Assigned(VETController) and Assigned(VetController.OnEditing) then begin
        Node := PVirtualNode(Item.Data);
        VetController.OnEditing(VetController, Node, 0, Result);
      end;
    end;
  end;
end;

function GetSelectionBox(LV: TListview): TRect;
var
  Item: TListItem;
begin
  Result := Rect(0, 0, 0, 0);
  //Find the Top-Left and Bottom-Right of the selection box
  Item := LV.Selected;
  if Assigned(Item) then
  begin
    Result.TopLeft := Item.Position;
    Result.BottomRight := Item.Position;
    while Assigned(Item) do
    begin
      Result.Left := Min(Result.Left, Item.Position.X);
      Result.Top := Min(Result.Top, Item.Position.Y);
      Result.Right := Max(Result.Right, Item.Position.X);
      Result.Bottom := Max(Result.Bottom, Item.Position.Y);
      Item := LV.GetNextItem(Item, sdAll, [isSelected]);
    end;
  end;
end;

function IsPointInRect(R: TRect; P: TPoint): boolean;
begin
  //Alternative to PtInRect, since in PtInRect a point on the right or
  //bottom side is considered outside the rectangle.
  Result := (P.X >= R.Left) and (P.X <= R.Right) and (P.Y >= R.Top) and (P.Y <= R.Bottom);
end;

function KeyMultiSelectEx(LV: TListview; SD: TSearchDirection): boolean;
// The MS Listview control in virtual mode (OwnerData) has a bug when
// Shift-Selecting an item, it just selects all the items from the last
// selected to the current selected, index wise.
// This little function will solve this issue.
// From MSDN:
// For normal Listviews LVN_ITEMCHANGING is triggered for every item that is
// being selected:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_itemchanging.asp
//
// But for ownerdata listviews LVN_ODSTATECHANGED is triggered ONCE with all
// the selected items:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_odstatechanged.asp
//
// The NMLVODSTATECHANGE member has only 2 integers specifying the range of
// selected items, with no differentiation.
// http://msdn.microsoft.com/library/en-us/shellcc/platform/commctls/listview/structures/nmlvodstatechange.asp
var
  Item: TListItem;
  R, RFocused: TRect;
  P: TPoint;
  I, iClicked, iFocused: integer;
begin
  //TSearchDirection = (sdLeft, sdRight, sdAbove, sdBelow, or sdAll);
  //Note: when ItemFocused or Selected is called the TListItem pointer is changed, weird.
  Result := false;
  if Assigned(LV.ItemFocused) and (LV.Items.Count > 1) and (SD <> sdAll) then
  begin
    R := GetSelectionBox(LV);
    iFocused := LV.ItemFocused.Index;

    Item := LV.GetNextItem(LV.ItemFocused, SD, []);
    iClicked := Item.Index;
    if Assigned(LV.Items[iClicked]) and (iClicked <> iFocused) then
    begin
      P := LV.Items[iClicked].Position;
      if IsPointInRect(R, P) then
      begin
        //contract the selection box
        Case SD of
          ComCtrls.sdLeft: R.Right := P.X;
          ComCtrls.sdAbove: R.Bottom := P.Y;
          ComCtrls.sdRight: R.Left := P.X;
          ComCtrls.sdBelow: R.Top := P.Y;
        end;
      end
      else begin
        //expand the selection box
        if P.X < R.Left then R.Left := P.X
        else if P.X > R.Right then R.Right := P.X;
        if P.Y < R.Top then R.Top := P.Y
        else if P.Y > R.Bottom then R.Bottom := P.Y;
      end;

      //Update, select and focus the item
      ListView_GetItemRect(LV.Handle, iFocused, RFocused, LVIR_BOUNDS);
      LV.Items[iClicked].Selected := true;
      LV.Items[iClicked].Focused := true;
      InvalidateRect(LV.Handle, @RFocused, true);

      //Select all items in the selection box and unselect the rest
      for I := 0 to LV.Items.Count-1 do
      begin
        Item := LV.Items[I];
        Item.Selected := IsPointInRect(R, Item.Position);
      end;
      LV.Items[iClicked].MakeVisible(false);
      Result := true;
    end;
  end;
end;

function MouseMultiSelectEx(LV: TListview; iClickedItem, iFirstClicked: integer): boolean;
// The MS Listview control in virtual mode (OwnerData) has a bug when
// Shift-Selecting an item, it just selects all the items from the last
// selected to the current selected, index wise.
// This little function will solve this issue.
// From MSDN:
// For normal Listviews LVN_ITEMCHANGING is triggered for every item that is
// being selected:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_itemchanging.asp
//
// But for ownerdata listviews LVN_ODSTATECHANGED is triggered ONCE with all
// the selected items:
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/listview/notifications/lvn_odstatechanged.asp
//
// The NMLVODSTATECHANGE member has only 2 integers specifying the range of
// selected items, with no differentiation.
// http://msdn.microsoft.com/library/en-us/shellcc/platform/commctls/listview/structures/nmlvodstatechange.asp
var
  Item: TListItem;
  R, RFocused: TRect;
  I, iFocused: integer;
begin
  Result := false;
  if (iClickedItem > -1) and (iClickedItem < LV.Items.Count) then
  begin
    //When ItemFocused is called the Item parameter is changed, weird
    iFocused := LV.ItemFocused.Index;

    if Assigned(LV.ItemFocused) and (LV.Items.Count > 1) then
    begin
      //Update, select and focus the item
      ListView_GetItemRect(LV.Handle, iFocused, RFocused, LVIR_BOUNDS);
      LV.Items[iClickedItem].Selected := true;
      LV.Items[iClickedItem].Focused := true;
      InvalidateRect(LV.Handle, @RFocused, true);

      if (iFirstClicked < 0) or (iFirstClicked > LV.Items.Count-1) then
        iFirstClicked := iFocused;  //from the Focused if there's no FirstClicked

      //Set the selection box from the FirstClicked to the ClickedItem
      R.Left := Min(LV.Items[iClickedItem].Position.X, LV.Items[iFirstClicked].Position.X);
      R.Top := Min(LV.Items[iClickedItem].Position.Y, LV.Items[iFirstClicked].Position.Y);
      R.Right := Max(LV.Items[iClickedItem].Position.X, LV.Items[iFirstClicked].Position.X);
      R.Bottom := Max(LV.Items[iClickedItem].Position.Y, LV.Items[iFirstClicked].Position.Y);

      //Select all items in the selection box and unselect the rest
      for I := 0 to LV.Items.Count-1 do
      begin
        Item := LV.Items[I];
        Item.Selected := IsPointInRect(R, Item.Position);
      end;
      Result := true;
    end;
  end;
end;

procedure TSyncListView.WMLButtonDown(var Message: TWMLButtonDown);
var
  Shift: TShiftState;
  P: TPoint;
  R: TRect;
  Item: TListItem;
  Node: PVirtualNode;
  iClicked: integer;
begin
  //This will solve the MS Listview Shift-Select bug
  Shift := KeysToShiftState(Message.Keys);
  P := Point(Message.XPos, Message.YPos);
  if (MultiSelect) and (ViewStyle in [vsIcon, vsSmallIcon]) and (ssShift in Shift) then
  begin
    Item := GetItemAt(P.X, P.Y);
    if Assigned(Item) then
    begin
      iClicked := Item.Index;
      if SelCount = 0 then
        FFirstShiftClicked := -1
      else
        if SelCount = 1 then
          FFirstShiftClicked := Selected.Index;
      MouseMultiSelectEx(Self, iClicked, FFirstShiftClicked);
    end
    else
      inherited;
  end
  else begin
    // Enable Thumbnail checkbox clicks
    if (Shift = [ssLeft]) and (VETController.ViewStyle = vsxThumbs) and
      (toCheckSupport in VETController.TreeOptions.MiscOptions) then
    begin
      Item := GetItemAt(P.X, P.Y);
      if Assigned(Item) then begin
        Node := PVirtualNode(Item.Data);
        if Assigned(Node) and (Node.CheckType <> VirtualTrees.ctNone) then begin
          R := Item.DisplayRect(drIcon);
          if FIsComCtl6 then
            R.Left := R.Left + VETController.ThumbsOptions.SpaceWidth div 2;
          R.Right := R.Left + 15;
          R.Bottom := R.Top + 15;
          if PtInRect(R, P) then begin
            VETController.CheckState[Node] := VETController.DetermineNextCheckState(Node.CheckType, Node.CheckState);
            InvalidateRect(Handle, @R, True);
            Exit;
          end;
        end;
      end;
    end;

    inherited;
  end;
end;

procedure TSyncListView.KeyDown(var Key: Word; Shift: TShiftState);
var
  I, H: integer;
  Node: PVirtualNode;
  DoDefault: boolean;
begin
  inherited;
  if IsEditing then Exit;

  //If the ClientHeight is to small to fit 2 thumbnails the PageUp/PageDown
  //key buttons won't work.
  //This is a VCL TListview bug, to workaround this I had to fake these keys
  //to Up/Down.
  if (VETController.ViewStyle = vsxThumbs) and (Items.Count > 0)
  and Assigned(ItemFocused) and (Key in [VK_NEXT, VK_PRIOR]) then begin
    H := (VETController.ThumbsOptions.Height + VETController.ThumbsOptions.SpaceHeight) * 2 + 5;
    if ClientHeight < H then begin // if there's not at least 2 full visible items
      Case Key of
        VK_NEXT: Key := VK_DOWN;
        VK_PRIOR: Key := VK_UP;
      end;
    end;
  end;

  //Corrected TListview bug in virtual mode, when the icon arrangement is iaLeft the arrow keys are scrambled
  if IconOptions.Arrangement = iaLeft then
    Case Key of
      VK_UP:    Key := VK_LEFT;
      VK_DOWN:  Key := VK_RIGHT;
      VK_LEFT:  Key := VK_UP;
      VK_RIGHT: Key := VK_DOWN;
    end;

  //This will solve the MS Listview Shift-Select bug
  if (MultiSelect) and (ViewStyle in [vsIcon, vsSmallIcon])
  and (ssShift in Shift) and (Key in [VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT]) then
  begin
    Case Key of
      VK_UP:    KeyMultiSelectEx(Self, ComCtrls.sdAbove);
      VK_DOWN:  KeyMultiSelectEx(Self, ComCtrls.sdBelow);
      VK_LEFT:  KeyMultiSelectEx(Self, ComCtrls.sdLeft);
      VK_RIGHT: KeyMultiSelectEx(Self, ComCtrls.sdRight);
    end;
    Key := 0;
  end
  else
    if Assigned(VETController) then begin //call VET events
      DoDefault := true;
      if Assigned(VETController.OnKeyDown) then
        VETController.OnKeyDown(VETController, Key, Shift);
      if Assigned(VETController.OnKeyAction) then
        VETController.OnKeyAction(VETController, Key, Shift, DoDefault);
      if DoDefault then begin
        Case Key of
          VK_RETURN:
            if (ItemFocused <> nil) and (ItemFocused.Selected) then begin
              VETController.ClearSelection;
              Node := PVirtualNode(ItemFocused.Data);
              if Assigned(Node) then begin
                VETController.Selected[Node] := true;
                VETController.DoShellExecute(Node);
              end;
            end;
          VK_BACK:
            VETController.BrowseToPrevLevel;
          VK_F2:
            if (not ReadOnly) and (ItemFocused <> nil) then
              ItemFocused.EditCaption;
          VK_F5:
            VETController.RefreshTree(toRestoreTopNodeOnRefresh in VETController.TreeOptions.VETMiscOptions);
          VK_DELETE:
            VETController.SelectedFilesDelete;
          Ord('A'), Ord('a'):
            if ssCtrl in Shift then begin
              VETController.SelectAll(true);
              for I := 0 to Items.Count - 1 do
                Items[I].Selected := True;
            end;
          Ord('C'), Ord('c'):
            if ssCtrl in Shift then
              VETController.CopyToClipboard;
          Ord('X'), Ord('x'):
            if ssCtrl in Shift then
              VETController.CutToClipboard;
          Ord('V'), Ord('v'):
            if ssCtrl in Shift then
              VETController.PasteFromClipboard;
          VK_INSERT: // Lefties favorate keys!
            if ssShift in Shift then
              VETController.PasteFromClipboard
            else
              if ssCtrl in Shift then
                VETController.CopyToClipboard;
        end;
      end;
    end;
end;

procedure TSyncListView.KeyPress(var Key: Char);
begin
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnKeyPress) then
    VETController.OnKeyPress(VETController, Key);
end;

procedure TSyncListView.KeyUp(var Key: Word; Shift: TShiftState);
begin
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnKeyUp) then
    VETController.OnKeyUp(VETController, Key, Shift);
end;

procedure TSyncListView.DblClick;
var
  Node: PVirtualNode;
begin
  inherited;
  if Assigned(VETController) then begin
    // Set the selection in the VETController
    Node := nil;
    if Assigned(ItemFocused) and (ItemFocused.Selected) then begin
      Node := PVirtualNode(ItemFocused.Data);
      if Assigned(Node) then begin
        VETController.ClearSelection;
        VETController.FocusedNode := Node;
        VETController.Selected[Node] := True;
      end;
    end;
    // Fire VETController.OnDblClick event
    if Assigned(VETController.OnDblClick) then
      VETController.OnDblClick(VETController);
    // Browse the Node
    if Assigned(Node) then
      VETController.DoShellExecute(Node);
  end;
end;

procedure TSyncListView.MouseDown(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
begin
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnMouseDown) then
    VETController.OnMouseDown(VETController, Button, Shift, X, Y);
end;

procedure TSyncListView.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
  inherited;
  if Assigned(VETController) and Assigned(VETController.OnMouseMove) then
    VETController.OnMouseMove(VETController, Shift, X, Y);
end;

procedure TSyncListView.MouseUp(Button: TMouseButton; Shift: TShiftState;
  X, Y: Integer);
begin
  inherited;
  if Assigned(VETController) then begin
    if Assigned(VETController.OnMouseUp) then
      VETController.OnMouseUp(VETController, Button, Shift, X, Y);
    if Assigned(VETController.OnClick) then
      VETController.OnClick(VETController);
  end;
end;

procedure TSyncListView.ContextMenuCmdCallback(Namespace: TNamespace;
  Verb: WideString; MenuItemID: Integer; var Handled: Boolean);
begin
  Handled := False;
  if Assigned(VETController) and Assigned(VETController.OnContextMenuCmd) then
    VETController.OnContextMenuCmd(VETController, Namespace, Verb, MenuItemID, Handled);
  if (Verb = 'rename') and not Handled then
  begin
    Handled := True;
    if (not ReadOnly) and (ItemFocused <> nil) then
      ItemFocused.EditCaption;
  end;
end;

procedure TSyncListView.ContextMenuShowCallback(Namespace: TNamespace;
  Menu: hMenu; var Allow: Boolean);
begin
  Allow := True;
  if Assigned(VETController) and Assigned(VETController.OnContextMenuShow) then
    VETController.OnContextMenuShow(VETController, Namespace, Menu, Allow);
end;

procedure TSyncListView.ContextMenuAfterCmdCallback(Namespace: TNamespace;
  Verb: WideString; MenuItemID: Integer; Successful: Boolean);
begin
  if Successful then
  begin
    if Verb = 'cut' then
      VETController.MarkNodesCut;
    if Verb = 'copy' then
      VETController.MarkNodesCopied;
    Invalidate;
  end
end;

procedure TSyncListView.DoContextPopup(MousePos: TPoint; var Handled: Boolean);
var
  Node: PVirtualNode;
  Pt: TPoint;
begin
  if Assigned(VETController) and not(toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin
    Pt := ClientToScreen(MousePos);
    if (toContextMenus in VETController.TreeOptions.VETShellOptions) and Assigned(Selected) then begin
      Handled := true;
      //We are going to work on ExplorerLV, first sync the selected items
      VETController.SyncSelectedItems(false);
      Node := VETController.GetFirstSelected;
      //Save the namespace for WM_INITMENUPOPUP, WM_DRAWITEM, WM_MEASUREITEM messages
      if VETController.ValidateNamespace(Node, FSavedPopupNamespace) then
          FSavedPopupNamespace.ShowContextMenuMulti(Self, ContextMenuCmdCallback,
            ContextMenuShowCallback, ContextMenuAfterCmdCallback, VETController.SelectedToNamespaceArray, @Pt,
            VETController.ShellContextSubMenu, VETController.ShellContextSubMenuCaption);
    end
    else
      if Assigned(VETController.PopupMenu) then begin
        Handled := True;
        VETController.PopupMenu.Popup(Pt.x, Pt.y);
      end;
  end;

  if not Handled then
    inherited;
end;

procedure TSyncListView.SetDetailedHints(const Value: Boolean);
begin
  //Disable the tooltip that is shown when an item caption is truncated
  if FDetailedHints <> Value then begin
    if Value then
      VETController.ShowHint := True;
    FDetailedHints := Value;
    UpdateHintHandle;
  end;
end;

procedure TSyncListView.WMPaint(var Message: TWMPaint);
begin
  FInPaintCycle := True;
  inherited;
  FInPaintCycle := False;
end;

procedure TSyncListView.WMVScroll(var Message: TWMVScroll);
  // Local function by Peter Bellow
  // http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&selm=VA.00007ac9.007e7c13%40antispam.compuserve.com
  function FindDynamicMethod( aClass: TClass; anIndex: SmallInt ): Pointer;
  type
    TIndices= Array [1..1024] of SmallInt;
    TProcs  = Array [1..1024] of Pointer;
  var
    pDMT : PWord;
    i, count: Word;
    pIndices : ^TIndices;
    pProcs : ^TProcs;
  begin
    Result := nil;
    If aClass = nil Then
      Exit;
    pDMT := Pointer(aClass);
    // Find pointer to DMT in VMT, first Word is the count of dynamic
    // methods
    pDMT := Pointer(PDword( Integer(pDMT) + vmtDynamicTable )^);
    count := pDMT^;
    pIndices := Pointer( Integer( pDMT ) + 2 );
    pProcs   := Pointer( Integer( pDMT ) + 2 + count * sizeof( smallint ));
    // find handler for anIndex
    for i:= 1 to count do
      if pIndices^[i] = anIndex then begin
        Result := pProcs^[i];
        Break;
      end;
    If Result = nil Then
      Result := FindDynamicMethod( aClass.Classparent, anIndex );
  end;
{$IFDEF DELPHI_7_UP}
var
  oldWMVScroll: procedure(var Message: TWMVScroll) of object;
{$ENDIF}
begin
  // Delphi 7 bug: the Listview invalidates the canvas when Scrolling :(
  // The problem is in ComCtrls.pas: TCustomListView.WMVScroll
  {$IFDEF DELPHI_7_UP}
    // Call the grandfather WM_VSCROLL handler, sort of inherited-inherited
    TMethod(oldWMVScroll).code := FindDynamicMethod(TWincontrol, WM_VSCROLL);
    TMethod(oldWMVScroll).data := Self;
    oldWMVScroll(Message);
  {$ELSE}
    inherited;
  {$ENDIF}

  // Set the focus when the scrollbar is clicked
  if not Focused then
    SetFocus;
end;

procedure TSyncListView.WMHScroll(var Message: TWMHScroll);
begin
  inherited;
  // Set the focus when the scrollbar is clicked
  if not Focused then
    SetFocus;
end;

procedure TSyncListView.UpdateHintHandle;
begin
  if HandleAllocated then begin
    if not ShowHint then
      // VCL TListview bug, setting ShowHint to False doesn't disable the hints
      // We must do this explicitly
      ListView_SetToolTips(Handle, 0)
    else
      if FDetailedHints then
        ListView_SetToolTips(Handle, 0)
      else
        ListView_SetToolTips(Handle, FDefaultTooltipsHandle);
  end;
end;

procedure TSyncListView.CMShowHintChanged(var Message: TMessage);
begin
  inherited;
  // VCL TListview bug, setting ShowHint to False doesn't disable the hints
  // We must do this explicitly
  UpdateHintHandle;
end;

procedure TSyncListView.CMHintShow(var Message: TCMHintShow);
var
  HintInfo: PHintInfo;
  Item: TListItem;
  Node: PVirtualNode;
  NS: TNamespace;
  S: WideString;
  R: TRect;
  P: TPoint;
  OverlayI: integer;
  Style: Cardinal;
begin
  if FDetailedHints and Assigned(VETController) and (VETController.ViewStyle <> vsxReport) then begin
    HintInfo := TCMHintShow(Message).HintInfo;
    Item := GetItemAt(HintInfo.CursorPos.X, HintInfo.CursorPos.Y);
    if Assigned(Item) and VETController.ValidateNamespace(PVirtualNode(Item.Data), NS) then begin
      Node := PVirtualNode(Item.Data);
      //Set the Hint
      HintInfo.HintWindowClass := TBitmapHint; //custom HintWindow class
      HintInfo.HintData := FThumbnailHintBitmap; //TApplication.ActivateHint will pass the data to the HintWindow
      HintInfo.HintStr := Item.Caption;
      HintInfo.CursorRect := GetLVItemRect(Item.Index, drBounds);
      HintInfo.CursorRect.TopLeft := ClientToScreen(HintInfo.CursorRect.TopLeft);
      HintInfo.CursorRect.BottomRight := ClientToScreen(HintInfo.CursorRect.BottomRight);
//        HintInfo.HintPos.X := HintInfo.CursorRect.Left + GetSystemMetrics(SM_CXCURSOR) - 5;
//        HintInfo.HintPos.Y := HintInfo.CursorRect.Top + GetSystemMetrics(SM_CYCURSOR) ;
      HintInfo.HintMaxWidth := ClientWidth;
      HintInfo.HideTimeout := 60000; //1 minute

      //Draw in the hint
      S := VETController.DoThumbsGetDetails(Node, true);
      if S <> '' then begin
        R := Rect(0, 0, 0, 0);

        if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then //Win9x must use AnsiStrings for DrawText
          Windows.DrawText(FThumbnailHintBitmap.Canvas.Handle, PChar(AnsiString(S)), -1, R, DT_CALCRECT)
        else
          Windows.DrawTextW(FThumbnailHintBitmap.Canvas.Handle, PWideChar(S), -1, R, DT_CALCRECT);

        FThumbnailHintBitmap.Width := R.Right + LargeSysImages.Width + 16;
        if R.Bottom >= LargeSysImages.Height then
          FThumbnailHintBitmap.Height := R.Bottom + 8
        else
          FThumbnailHintBitmap.Height := LargeSysImages.Height + 8;
        FThumbnailHintBitmap.Canvas.Font.Color := clInfoText;
        FThumbnailHintBitmap.Canvas.Pen.Color := clBlack;
        FThumbnailHintBitmap.Canvas.Brush.Color := clInfoBk;
        FThumbnailHintBitmap.Canvas.FillRect(Rect(0, 0, FThumbnailHintBitmap.Width, FThumbnailHintBitmap.Height));

        //Custom drawing
        if VETController.DoThumbsDrawHint(FThumbnailHintBitmap, Node) then begin
          P.x := 4;
          P.y := (FThumbnailHintBitmap.Height - LargeSysImages.Height) div 2;
          Style := ILD_TRANSPARENT;

          OverlayI := -1;
          if not (toHideOverlay in VETController.TreeOptions.VETImageOptions) and Assigned(NS.ShellIconOverlayInterface) then
            OverlayI := NS.OverlayIndex - 1
          else
            if NS.Link then
              OverlayI := 1
            else
              if NS.Share then OverlayI := 0;

          if OverlayI > -1 then
            Style := Style or ILD_OVERLAYMASK and Cardinal(IndexToOverlayMask(OverlayI + 1));
          ImageList_DrawEx(LargeSysImages.Handle, NS.GetIconIndex(false, icLarge), FThumbnailHintBitmap.Canvas.Handle, P.x, P.y, 0, 0, CLR_NONE, CLR_NONE, Style);

          OffsetRect(R, LargeSysImages.Width + 8, (FThumbnailHintBitmap.Height - R.Bottom) div 2);
          if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then  //Win9x must use AnsiStrings for DrawText
            Windows.DrawText(FThumbnailHintBitmap.Canvas.Handle, PChar(AnsiString(S)), -1, R, 0)
          else
            Windows.DrawTextW(FThumbnailHintBitmap.Canvas.Handle, PWideChar(S), -1, R, 0);
        end;

        Message.Result := 0;
      end;
    end;
  end
  else
    inherited;
end;

procedure TSyncListView.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
  if IsBackgroundValid then begin
    DefaultHandler(Message);
    Message.Result := 1;
  end
  else
    inherited;
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TOLEListview }

procedure TOLEListview.AutoScrollTimerCallback(Window: hWnd; Msg,
  idEvent: integer; dwTime: Longword);
var
  Pt: TPoint;
begin
  FAutoScrolling := True;
  try
    Pt := Mouse.CursorPos;
    Pt := ScreenToClient(Pt);
    if Pt.y < 20 then
      Scroll(0, -(20 - Pt.y)*2);
    if Pt.y > ClientHeight - 20 then
      Scroll(0, (20 - (ClientHeight - Pt.y)) * 2);
    if Pt.x < 20 then
      Scroll(-(20 - Pt.x)*2, 0);
    if Pt.x > ClientWidth - 20 then
      Scroll((20 - (ClientWidth - Pt.x)) * 2, 0);
  finally
    FAutoScrolling := False;
  end
end;

procedure TOLEListview.ClearTimers;
begin
  if FScrollTimer <> 0 then
  begin
    KillTimer(Handle, FScrollTimer);
    FScrollTimer := 0;
  end;
  if FScrollDelayTimer <> 0 then
  begin
    KillTimer(Handle, FScrollDelayTimer);
    FScrollDelayTimer := 0;
  end;
end;

constructor TOLEListview.Create(AOwner: TComponent);
begin
  inherited;
  CurrentDropIndex := -2;  // -1 = backgound -2 = nothing
  FDragItemIndex := -1;
  FAutoScrollTimerStub := CreateStub(Self, @TOLEListview.AutoScrollTimerCallback);
end;

procedure TOLEListview.CreateDragImage(TotalDragRect: TRect; RectArray: TRectArray; var Bitmap: TBitmap);
var
  i: integer;
  LVBitmap: TBitmap;
  Offset: TPoint;
  R: TRect;
begin
  if Assigned(Bitmap) and (SelCount > 0) then
  begin
    //Get a Bitmap with all the selected items
    LVBitmap := TBitmap.Create;
    Bitmap.Canvas.Lock;
    try
      //update Bitmap size
      Bitmap.Width := TotalDragRect.Right - TotalDragRect.Left;
      Bitmap.Height := TotalDragRect.Bottom - TotalDragRect.Top;
      Bitmap.Canvas.Brush.Color := Self.Color;
      Bitmap.Canvas.FillRect(Rect(0, 0, Bitmap.Width, Bitmap.Height));

      LVBitmap.Width := ClientWidth;
      LVBitmap.Height := ClientHeight;
      LVBitmap.Canvas.Lock; //we need to Lock the canvas in order to use the PaintTo method
      try
        //Don't use PaintTo, WinXP doesn't support it.
        BitBlt(LVBitmap.Canvas.Handle, 0, 0, ClientWidth, ClientHeight, Canvas.Handle, 0, 0, srcCopy);
      finally
        LVBitmap.Canvas.UnLock;
      end;

      Offset.X := TotalDragRect.Left;
      Offset.Y := TotalDragRect.Top;
      //Iterate and CopyRect the selected items
      for I := 0 to Length(RectArray) - 1 do begin
        R := RectArray[I];
        if R.Top <= 0 then R.Top := 0;  //don't draw borders
        if R.Left <= 0 then R.Left := 0;  //don't draw borders
        StretchBlt(Bitmap.Canvas.Handle, R.Left - Offset.x, R.top - Offset.y, R.Right - R.Left, R.Bottom - R.Top,
          LVBitmap.Canvas.Handle, R.Left+2, R.Top+2, R.Right - R.Left+2, R.Bottom - R.Top+2, cmSrcCopy);
      end;
    finally
      Bitmap.Canvas.Unlock;
      LVBitmap.Free;
    end;
  end;
end;

procedure TOLEListview.CreateWnd;
begin
  inherited;
  if not (csDesigning in ComponentState) then
  begin
    CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper, FDropTargetHelper);
    RegisterDragDrop(Handle, Self)
  end
end;

destructor TOLEListview.Destroy;
begin
  ClearTimers;
  if Assigned(FAutoScrollTimerStub) then
    DisposeStub(FAutoScrollTimerStub);
  inherited;
end;

procedure TOLEListview.DoContextPopup(MousePos: TPoint; var Handled: Boolean);
begin
  // Clear the mouse states as the context menu grabs the mouse and never sends us a WM_xMOUSEUP message
  MouseButtonState := [];
  inherited;
end;

procedure TOLEListview.DestroyWnd;
begin
  if not (csDesigning in ComponentState) then
    RevokeDragDrop(Handle);
  inherited;
end;

function TOLEListview.DragEnter(const dataObj: IDataObject;
  grfKeyState: Integer; pt: TPoint; var dwEffect: Integer): HResult;
begin
  if Assigned(DropTargetHelper) then
    DropTargetHelper.DragEnter(Handle, dataObj, Pt, dwEffect);

  DragDataObject := DataObj;

  FScrollDelayTimer := SetTimer(Handle, SCROLL_DELAY_TIMER, VETController.AutoScrollDelay, nil);

  Result := S_OK;
end;

function TOLEListview.Dragging: Boolean;
begin
  Result := FDragging
end;

function TOLEListview.DragLeave: HResult;
var
  TempNS: TNamespace;
  TempItem: TListItem;
begin
  if Assigned(DropTargetHelper) then
    DropTargetHelper.DragLeave;

  ClearTimers;

  TempNS := nil;
  if CurrentDropIndex > -2 then
  begin
    if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then
    begin
      TempItem := Items[CurrentDropIndex];
      TempItem.DropTarget := False;   // DropTarget only hilight caption
      TempNS := ListItemToNamespace(TempItem, True);
    end else
       VETController.ValidateNamespace(VETController.RootNode, TempNS);
    if Assigned(TempNS) then
      TempNS.DragLeave;
  end;
  CurrentDropIndex := -2;
  DragDataObject := nil;
  Result := S_OK;
end;


function TOLEListview.DragOverOLE(grfKeyState: Integer; pt: TPoint; var dwEffect: Integer): HResult;
var
  HitNS, TempNS: TNamespace;
  HitItem, TempItem: TListItem;
  HitIndex: integer;
  ShiftState: TShiftState;
begin
  // Update any drag image
  if Assigned(DropTargetHelper) then
    DropTargetHelper.DragOver(pt, dwEffect);

  Result := S_OK;
  if AutoScrolling or not (toAcceptOLEDrop in VETController.TreeOptions.MiscOptions) or
  (toVETReadOnly in VETController.TreeOptions.VETMiscOptions) then begin
    dwEffect := DROPEFFECT_NONE;
    Exit;
  end;

  ShiftState := KeysToShiftState(grfKeyState);

  // Fire VETController.OnDragOver event
  VETController.DoDragOver(Self, ShiftState, dsDragMove, Pt, dmOnNode, dwEffect);

  Pt := ScreenToClient(Pt);

  HitItem := GetItemAt(Pt.X, Pt.Y);
  HitNS := ListItemToNamespace(HitItem, True);
  if Assigned(HitItem) then
    HitIndex := HitItem.Index
  else
    HitIndex := -1;

  // Don't allow to drop in the dragging item unless Shift, Alt or Ctrl is
  // pressed and the item is inside the listview
  if (HitIndex = FDragItemIndex) and (FDragItemIndex > -1) and (ShiftState * [ssRight, ssShift, ssAlt, ssCtrl] = []) then begin
    if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then
      Items[CurrentDropIndex].DropTarget := False;  // reset highlight caption
    dwEffect := DROPEFFECT_NONE;
    CurrentDropIndex := -2;
    exit;
  end;

  // If the HitIndex  is different that the current drop target then
  // update everything to select the new item (or parent if the drop is "into" the list view
  if (HitIndex <> CurrentDropIndex) then begin
    //<<<<<if GetHitTestInfoAt(Pt.X, Pt.Y) * [htOnIcon, htOnLabel] <> [] then begin
    if HitIndex > -1 then begin
      // Try to enter the new namespace
      Result := HitNS.DragEnter(DragDataObject, grfKeyState, pt, dwEffect);

      // If we can't drop on that namespace then we need to just default to dropping
      // "into" the current list view, i.e. the RootNode of the VT. Otherwise every
      // thing is hunky dory and the HitItem will be selected
      if dwEffect <> DROPEFFECT_NONE then
        HitItem.DropTarget := True    // DropTarget only hilight caption
      else begin
        HitNS.DragLeave;  // Leave the HitItem namespace, not going to use it
        exit; // cancel the drag
      end;
    end;

    // If we were on the background and the hit node does not take drops leave it
    // in the backgound with making any changes
    if CurrentDropIndex <> HitIndex then
    begin
      TempNS := nil;
      if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then begin
        TempItem := Items[CurrentDropIndex];
        TempItem.DropTarget := False;   // reset highlight caption
        TempNS := ListItemToNamespace(TempItem, False);
      end
      else
        VETController.ValidateNamespace(VETController.RootNode, TempNS);

      if Assigned(TempNS) then begin
        // Only drag leave if the current actually was somewhere (-2 means current was over nothing)
        if (CurrentDropIndex > -2) and (CurrentDropIndex < Items.Count) then
          TempNS.DragLeave;
        TempNS := ListIndexToNamespace(HitIndex);
        TempNS.DragEnter(DragDataObject, grfKeyState, pt, dwEffect);
      end;
      CurrentDropIndex := HitIndex
    end
    else begin
      dwEffect := DROPEFFECT_NONE;
    end;
  end
  else begin
    // Don't allow to drop in the background unless Shift, Alt or Ctrl is
    // pressed and the drag item is INSIDE the Listview
    if (HitIndex = -1) and (FDragItemIndex > -1) and (ShiftState * [ssRight, ssShift, ssAlt, ssCtrl] = []) then
      dwEffect := DROPEFFECT_NONE
    else begin
      TempNS := ListIndexToNamespace(CurrentDropIndex);
      if Assigned(TempNS) then
        TempNS.DragOver(grfKeyState, pt, dwEffect);
    end;
  end;
end;

function TOLEListview.Drop(const dataObj: IDataObject;
  grfKeyState: Integer; Pt: TPoint; var dwEffect: Integer): HResult;
var
  TempNS: TNamespace;
  TempItem: TListItem;
  ClientPt: TPoint;
  I: Integer;
begin
  FDropped := True;
  try
    if Assigned(DropTargetHelper) then
      DropTargetHelper.Drop(dataObj, Pt, dwEffect);
    ClearTimers;
    TempNS := nil;

    // Fire VETController.OnDragDrop event
    I := dwEffect;
    ClientPt := ScreenToClient(Pt);
    VETController.DoDragDrop(Self, dataObj, nil, KeysToShiftState(grfKeyState), ClientPt, I, dmOnNode);

    if (CurrentDropIndex > -2) and (I <> DROPEFFECT_NONE) then
    begin
      if (CurrentDropIndex > -1) and (CurrentDropIndex < Items.Count) then
      begin
        TempItem := Items[CurrentDropIndex];
        TempItem.DropTarget := False;   // DropTarget only highlight caption
        TempNS := ListItemToNamespace(TempItem, True);
      end else
         VETController.ValidateNamespace(VETController.RootNode, TempNS);
      if Assigned(TempNS) then
        TempNS.Drop(dataObj, grfKeyState, pt, dwEffect);
    end;
    CurrentDropIndex := -2;
    DragDataObject := nil;
    Result := S_OK;

    // Fire OnDragDrop for the TOLEListview control
    if I <> DROPEFFECT_NONE then
      DragDrop(Self, ClientPt.X, ClientPt.Y);
  finally
    FDropped := False;
  end;
end;

function TOLEListview.GiveFeedback(dwEffect: Integer): HResult;
begin
  Result := DRAGDROP_S_USEDEFAULTCURSORS
end;

function TOLEListview.ListIndexToNamespace(ItemIndex: integer): TNamespace;
// use -1 to get the Listview background namespace
var
  Node: PVirtualNode;
begin
  Result := nil;
  if (ItemIndex > -1) and (ItemIndex < Items.Count) then
  begin
    Node := GetChildByIndex(VETController.RootNode, ItemIndex);  //this is fast enough
    VETController.ValidateNamespace(Node, Result)
  end else
  begin
    if ItemIndex = -1 then
      VETController.ValidateNamespace(VETController.RootNode, Result)
  end
end;

function TOLEListview.ListItemToNamespace(Item: TListItem; BackGndIfNIL: Boolean): TNamespace;
var
  Node: PVirtualNode;
begin
  Result := nil;
  if Assigned(Item) then
  begin
    Node := GetChildByIndex(VETController.RootNode, Item.Index);  //this is fast enough
    VETController.ValidateNamespace(Node, Result)
  end else
  begin
    if BackGndIfNIL then
      VETController.ValidateNamespace(VETController.RootNode, Result)
  end
end;

function TOLEListview.QueryContinueDrag(fEscapePressed: BOOL;
  grfKeyState: Integer): HResult;
begin
  Result := S_OK;

  if fEscapePressed then
    Result := DRAGDROP_S_CANCEL
  else
  if LButtonDown in MouseButtonState then
  begin
    if grfKeyState and MK_LBUTTON > 0 then  // is the LButton flag set?
      Result := S_OK                        // Button is still down
    else
      Result := DRAGDROP_S_DROP;            // Button has been released
  end else
  if RButtonDown in MouseButtonState then
  begin
    if grfKeyState and MK_RBUTTON > 0 then  // is the RButton flag set?
      Result := S_OK                        // Button is still down
    else
      Result := DRAGDROP_S_DROP;            // Button has been released
  end
end;

procedure TOLEListview.WMLButtonDown(var Message: TWMLButtonDown);
begin
  Include(FMouseButtonState, LButtonDown);
  inherited;
end;

procedure TOLEListview.WMLButtonUp(var Message: TWMLButtonUp);
begin
  Exclude(FMouseButtonState, LButtonDown);
  inherited
end;

procedure TOLEListview.WMMouseMove(var Message: TWMMouseMove);
var
  dwOkEffects, dwEffectResult: LongInt;
  DataObject: IDataObject;
  NSArray: TNamespaceArray;
  i: integer;
  Item: TListItem;
  Pt: TPoint;
  DoDrag: Boolean;
  Bitmap: TBitmap;
  DragSourceHelper: IDragSourceHelper;
  SHDragImage: TSHDragImage;
  TotalDragRect, R: TRect;
  RectArray: TRectArray;
  DummyDragObject: TDragObject;
begin
  if MouseButtonState * [LButtonDown, RButtonDown] <> [] then
  begin
    DoDrag := False;
    Pt := SmallPointToPoint(Message.Pos);
    Item := GetItemAt(Pt.X, Pt.Y);

    if Assigned(Item) then
      DoDrag := (GetHitTestInfoAt(Pt.X, Pt.Y) * [htOnLabel, htOnIcon] <> []) and VETController.DoBeforeDrag(Item.Data, -1);

    if DoDrag and (SelCount > 0) then
    begin
      FDragging := DragDetectPlus(Parent.Handle, Pt);
      if Dragging then
      begin
        DummyDragObject := nil;
        // Fire OnStartDrag for the TOLEListview control
        DoStartDrag(DummyDragObject);
        // Fire VETController.OnStartDrag
        VETController.DoStartDrag(DummyDragObject);

        FDragItemIndex := Item.Index;
        Bitmap := TBitmap.Create;
        try
          SetLength(NSArray, SelCount);
          SetLength(RectArray, 1);
          Item := Selected;
          NSArray[0] := ListItemToNamespace(Item, False);
          RectArray[0] := GetLVItemRect(Item.Index, drSelectBounds);
          TotalDragRect := RectArray[0];
          if Assigned(NSArray[0]) then
          begin
            i := 1;
            while (i < SelCount) do
            begin
              Item := GetNextItem(Item, sdAll, [isSelected]);
              NSArray[i] := ListItemToNamespace(Item, False);

              //Add visible items bounds to the RectArray
              R := GetLVItemRect(Item.Index, drSelectBounds);
              if PtInRect(ClientRect, R.TopLeft) then begin
                SetLength(RectArray, i + 1);
                RectArray[i] := R;
                //update TotalDragRect size
                if R.Left < TotalDragRect.Left then TotalDragRect.Left := R.Left;
                if R.Top < TotalDragRect.Top then TotalDragRect.Top := R.Top;
                if R.Right > TotalDragRect.Right then TotalDragRect.Right := R.Right;
                if R.Bottom > TotalDragRect.Bottom then TotalDragRect.Bottom := R.Bottom;
              end;

              Inc(i)
            end;

            DataObject := NSArray[0].DataObjectMulti(NSArray);

            if Succeeded(CoCreateInstance(CLSID_DragDropHelper, nil, CLSCTX_INPROC_SERVER, IID_IDragSourceHelper, DragSourceHelper)) then
            begin
              FillChar(SHDragImage, SizeOf(SHDragImage), #0);
              Bitmap.Width := VETController.DragWidth;
              Bitmap.Height := VETController.DragHeight;
              CreateDragImage(TotalDragRect, RectArray, Bitmap);
              SHDragImage.sizeDragImage.cx := Bitmap.Width;
              SHDragImage.sizeDragImage.cy := Bitmap.Height;
              SHDragImage.ptOffset.X := SmallPointToPoint(Message.Pos).X - TotalDragRect.Left;
              SHDragImage.ptOffset.Y := SmallPointToPoint(Message.Pos).Y - TotalDragRect.Top;
              SHDragImage.ColorRef := ColorToRGB(Color);
              SHDragImage.hbmpDragImage := CopyImage(Bitmap.Handle, IMAGE_BITMAP, 0, 0, LR_COPYRETURNORG);
              if SHDragImage.hbmpDragImage <> 0 then
                if not Succeeded(DragSourceHelper.InitializeFromBitmap(SHDragImage, DataObject)) then
                  DeleteObject(SHDragImage.hbmpDragImage);
            end;

            dwOkEffects := DROPEFFECT_COPY or DROPEFFECT_MOVE or DROPEFFECT_LINK;

            if not FDropped then
              DoDragDrop(DataObject, Self, dwOkEffects, dwEffectResult);
            MouseButtonState := [];
          end
        finally
          FDragging := False;
          Bitmap.Free;
          FDragItemIndex := -1;
          // Fire OnEndDrag for the TOLEListview control
          DoEndDrag(Self, Pt.X, Pt.Y);
          // Fire VETController.OnEndDrag
          VETController.DoEndDrag(Self, Pt.X, Pt.Y);
        end
      end
    end;
  end;
  inherited;
end;

procedure TOLEListview.WMRButtonDown(var Message: TWMRButtonDown);
begin
  Include(FMouseButtonState, RButtonDown);
  inherited;
end;

procedure TOLEListview.WMRButtonUp(var Message: TWMRButtonUp);
begin
  Exclude(FMouseButtonState, RButtonDown);
  inherited;
end;

procedure TOLEListview.WMTimer(var Message: TWMTimer);
begin
  inherited;
  case Message.TimerID of
    SCROLL_DELAY_TIMER:
      begin
        KillTimer(Handle, FScrollDelayTimer);
        FScrollDelayTimer := 0;
        FScrollTimer := SetTimer(Handle, SCROLL_TIMER, VETController.AutoScrollInterval, FAutoScrollTimerStub);
      end;
  end
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TCustomVirtualExplorerListviewEx }

constructor TCustomVirtualExplorerListviewEx.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FImageLibrary := timNone;
  {$IFDEF USEGRAPHICEX} FImageLibrary := timGraphicEx; {$ELSE}
    {$IFDEF USEIMAGEEN} FImageLibrary := timImageEn; {$ELSE}
      {$IFDEF USEENVISION} FImageLibrary := timImageMagick; {$ELSE}
        {$IFDEF USEIMAGEMAGICK} FImageLibrary := timImageMagick; {$ENDIF}
      {$ENDIF}
    {$ENDIF}
  {$ENDIF}

  FInternalDataOffset := AllocateInternalDataArea(SizeOf(TThumbnailData));

  FThumbsOptions := TThumbsOptions.Create(Self);

  FListview := TOLEListview.Create(Self);
  FListview.VETController := Self;
  FListview.OnAdvancedCustomDrawItem := LVOnAdvancedCustomDrawItem;
  FListview.SmallImages := VirtualSystemImageLists.SmallSysImages;

  FDummyIL := TImageList.Create(Self);

  FExtensionsList := TExtensionsList.Create;
  FShellExtractExtensionsList := TExtensionsList.Create;
  FExtensionsExclusionList := TExtensionsList.Create;
  FillExtensionsList;

  FVisible := true;
  FViewStyle := vsxReport;
  FAccumulatedChanging := false;
end;

destructor TCustomVirtualExplorerListviewEx.Destroy;
begin
  {$IFDEF THREADEDICONS}
  if ThreadedImagesEnabled then
    ImageThreadManager.ClearPendingItems(Self, WM_VTSETICONINDEX, Malloc);
  {$ENDIF}
  //The Listview is automatically freed.
  //FreeAndNil(FListview);
  FDummyIL.Free;
  FExtensionsList.Free;
  FShellExtractExtensionsList.Free;
  FExtensionsExclusionList.Free;
  FThumbsOptions.Free;
  FThumbsOptions := nil;


  if Assigned(FThumbThread) then
  begin
    FThumbThread.Priority := tpNormal; //D6 has a Thread bug, we must set the priority to tpNormal before destroying
    FThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc);
    FThumbThread.Terminate;
    FThumbThread.SetEvent;
    FThumbThread.WaitFor;
    FreeAndNil(FThumbThread);
  end;

  inherited;
end;

procedure TCustomVirtualExplorerListviewEx.CreateWnd;
begin
  inherited;
  SyncOptions;
end;

procedure TCustomVirtualExplorerListviewEx.Loaded;
begin
  inherited;
  SyncOptions;
end;

procedure TCustomVirtualExplorerListviewEx.Notification(
  AComponent: TComponent; Operation: TOperation);
begin
  inherited;
  if (Operation = opRemove) and (AComponent = FListView) then
    FListView := nil;
end;

procedure TCustomVirtualExplorerListviewEx.RequestAlign;
begin
  inherited;
  if IsValidChildListview then
    if (FListview.Align <> Align) or (FListview.Anchors <> Anchors) or
       (FListview.Constraints.MaxWidth <> Constraints.MaxWidth) or
       (FListview.Constraints.MaxHeight <> Constraints.MaxHeight) or
       (FListview.Constraints.MinWidth <> Constraints.MinWidth) or
       (FListview.Constraints.MinHeight <> Constraints.MinHeight) then
      SyncOptions;
end;

procedure TCustomVirtualExplorerListviewEx.SetParent(AParent: TWinControl);
begin
  inherited;
  //This is not a compound component, a compound component is a container
  //with 1 or more controls in it.
  //The parent of the child VCL Listview is the Self.Parent, this is so
  //to retain all the properties of TExplorerListview, that means I don't have
  //to copy all these properties and you don't loose usability.
  if Assigned(FListview) and (AParent <> nil) then
    FListview.Parent := AParent;
end;

procedure TCustomVirtualExplorerListviewEx.SetZOrder(TopMost: Boolean);
begin
  inherited;
  if (ViewStyle <> vsxReport) and Assigned(FListview) then
    FListview.SetZOrder(TopMost);
end;

function TCustomVirtualExplorerListviewEx.GetClientRect: TRect;
begin
  if ViewStyle = vsxReport then
    Result := inherited GetClientRect
  else
    Result := FListview.GetClientRect;  
end;

procedure TCustomVirtualExplorerListviewEx.CMShowHintChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.ShowHint := ShowHint;
end;

procedure TCustomVirtualExplorerListviewEx.CMBorderChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then begin
    FListview.BevelEdges := BevelEdges;
    FListview.BevelInner := BevelInner;
    FListview.BevelKind := BevelKind;
    FListview.BevelOuter := BevelOuter;
    FListview.BevelWidth := BevelWidth;
    FListview.BorderWidth := BorderWidth;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.CMBidimodechanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.BiDiMode := BiDiMode;
end;

procedure TCustomVirtualExplorerListviewEx.CMCtl3DChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.Ctl3D := Ctl3D;
end;

procedure TCustomVirtualExplorerListviewEx.CMColorChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.Color := Color;
end;

procedure TCustomVirtualExplorerListviewEx.CMCursorChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.Cursor := Cursor;
end;

procedure TCustomVirtualExplorerListviewEx.CMEnabledchanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.Enabled := Enabled;
end;

procedure TCustomVirtualExplorerListviewEx.CMFontChanged(var Message: TMessage);
begin
  inherited;
  if Assigned(FListview) then FListview.Font.Assign(Font);
end;

procedure TCustomVirtualExplorerListviewEx.WMNCDestroy(var Message: TWMNCDestroy);
begin
  if Assigned(FThumbThread) then
    FThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc);
  inherited;
end;

{$IFDEF THREADEDICONS}
procedure TCustomVirtualExplorerListviewEx.WMVTSetIconIndex(var Msg: TWMVTSetIconIndex);
var
  NS: TNamespace;
  R: TRect;
begin
  if FViewStyle = vsxReport then
    inherited
  else begin
    try
      if ValidateNamespace(Msg.IconInfo.UserData, NS) then
      begin
        NS.SetIconIndexByThread(Msg.IconInfo.IconIndex, True);
        R := FListview.GetLVItemRect(Msg.IconInfo.Tag, drIcon);
        InvalidateRect(FListview.Handle, @R, False);
      end
    finally
      ImageThreadManager.ReleaseItem(Msg.IconInfo, Malloc)
    end
  end;
end;
{$ENDIF}

procedure TCustomVirtualExplorerListviewEx.WMVLVExThumbThread(var Message: TMessage);
var
  TD: PThumbnailData;
  ThumbThreadData: PThumbnailThreadData;
  NS: TNamespace;
  Node: PVirtualNode;
  Info: PVirtualThreadIconInfo;
  B: TBitmap;
  CI: TThumbsCacheItem;
  I: integer;
begin
  Info := PVirtualThreadIconInfo(Message.wParam);

  if Assigned(Info) then
  begin
    try
      ThumbThreadData := PThumbnailThreadData(Info.UserData2);
      if Assigned(ThumbThreadData) then
      begin
        Node := Info.UserData;
        if (ThumbThreadData.State = tsValid) and ValidateNamespace(Node, NS) then
        begin
          if ValidateThumbnail(Node, TD) then
          begin
            TD.State := ThumbThreadData.State;

            if TD.Reloading then begin
              TD.Reloading := False;
              if ThumbsOptions.CacheOptions.FThumbsCache.Read(TD.CachePos, CI) then begin
                I := ThumbsOptions.CacheOptions.FThumbsCache.FScreenBuffer.IndexOf(NS.NameForParsing);
                if I > -1 then
                  ThumbsOptions.CacheOptions.FThumbsCache.FScreenBuffer.Delete(I);
                CI.CompressedThumbImageStream := ThumbThreadData.CompressedStream;
                CI.FThumbImageStream.LoadFromStream(ThumbThreadData.MemStream);
              end;
            end
            else
              if Assigned(OnThumbsCacheItemAdd) then begin
                B := TBitmap.Create;
                try
                  if ThumbThreadData.CompressedStream then
                    ConvertJPGStreamToBitmap(ThumbThreadData.MemStream, B)
                  else
                    B.LoadFromStream(ThumbThreadData.MemStream);
                  if DoThumbsCacheItemAdd(NS, B, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight) then
                    TD.CachePos := ThumbsOptions.CacheOptions.FThumbsCache.Add(NS.NameForParsing,
                      '', '', NS.LastWriteDateTime, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight,
                      ThumbThreadData.CompressedStream, ThumbThreadData.MemStream);
                finally
                  B.Free;
                end;
              end
              else
                TD.CachePos := ThumbsOptions.CacheOptions.FThumbsCache.Add(NS.NameForParsing,
                  '', '', NS.LastWriteDateTime, ThumbThreadData.ImageWidth, ThumbThreadData.ImageHeight,
                  ThumbThreadData.CompressedStream, ThumbThreadData.MemStream);
            //redraw the item
            FListview.UpdateItems(Info.Tag, Info.Tag);
            //Update inmediatly, from ListView_RedrawItems windows help
            FListview.Update;
          end;
        end;
      end;
    finally
      ThumbThread.ReleaseItem(Info, Malloc);
    end;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.DoInitNode(Parent, Node: PVirtualNode;
  var InitStates: TVirtualNodeInitStates);
var
  Data: PThumbnailData;
begin
  if ValidateThumbnail(Node, Data) then begin
    Data.CachePos := -1;
    Data.Reloading := False;
    Data.State := tsEmpty;
  end;
  inherited;
end;

procedure TCustomVirtualExplorerListviewEx.DoFreeNode(Node: PVirtualNode);
begin
  if Assigned(Node) and Assigned(FThumbThread) then
    FThumbThread.ClearPendingItem(Self, Node, WM_VLVEXTHUMBTHREAD, Malloc);
  inherited;
end;

procedure TCustomVirtualExplorerListviewEx.Clear;
begin
  // Clear the cache before we rebuild the tree, called by RebuildRootNamespace
  if Assigned(ThumbsOptions) then begin
    ThumbsOptions.CacheOptions.FThumbsCache.Clear;
    ThumbsOptions.CacheOptions.FThumbsCache.ThumbWidth := ThumbsOptions.Width;
    ThumbsOptions.CacheOptions.FThumbsCache.ThumbHeight := ThumbsOptions.Height;
  end;
  inherited
end;

procedure TCustomVirtualExplorerListviewEx.RebuildRootNamespace;
var
  NS: TNamespace;
begin
  //I was overriding DoRootRebuild to do this, but I need to do it here
  //because in TCustomVirtualExplorerTree.RebuildRootNamespace there's a call
  //to EndUpdate and this fires FListview.OwnerDataHint (via DoStructureChange, Accumulated event).
  if (RebuildRootNamespaceCount = 0) and not (csLoading in ComponentState)
    and Assigned(RootFolderNamespace) and Active then
  begin
    FListview.OwnerDataPause := True; //avoid generating data
    try
      inherited; // We're clear to rebuild the tree, it will call Clear
      FListview.Items.BeginUpdate;
      try
        ThumbsOptions.CacheOptions.BrowsingFolder := RootFolderNamespace.NameForParsing;
        NS := RootFolderNamespace;
        if Assigned(ThumbsOptions.CacheOptions) and ThumbsOptions.CacheOptions.AutoLoad and Assigned(NS) and NS.Folder and NS.FileSystem then
          ThumbsOptions.CacheOptions.Load;

        SyncItemsCount;
        FListview.Selected := nil;
        if FListview.items.count > 0 then
          FListview.ItemFocused := FListview.Items[0];
      finally
        FListview.Items.EndUpdate;
       end;
    finally
      FListview.OwnerDataPause := False;
      FListview.UpdateArrangement;
      if ThumbsOptions.LoadAllAtOnce then
        FListview.FetchThumbs(0, FListview.Items.Count - 1);
    end;
  end;
  FlushSearchCache;
end;

procedure TCustomVirtualExplorerListviewEx.DoRootChanging(
  const NewRoot: TRootFolder; Namespace: TNamespace; var Allow: Boolean);
var
  NS: TNamespace;
begin
  if (RebuildRootNamespaceCount = 0) and not (csLoading in ComponentState) and Active then
    FListview.OwnerDataPause := True; //avoid generating data
  FlushSearchCache;

  inherited DoRootChanging(NewRoot, Namespace, Allow);

  if not Allow and FListview.OwnerDataPause then
    FListview.OwnerDataPause := False;

  if Allow and not (csLoading in Componentstate) and Assigned(ThumbsOptions) and Assigned(ThumbsOptions.CacheOptions) then begin
    NS := RootFolderNamespace;
    if ThumbsOptions.CacheOptions.AutoSave and Assigned(NS) and NS.Folder and NS.FileSystem then
      if (ThumbsOptions.CacheOptions.StorageType = tcsCentral) or not NS.ReadOnly then
        ThumbsOptions.CacheOptions.Save;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.DoStructureChange(Node: PVirtualNode; Reason: TChangeReason);
begin
  inherited;
  if FViewStyle = vsxReport then exit;

  Case Reason of
    crChildAdded:
      begin
        SyncSelectedItems;
        SyncItemsCount;
      end;
    crChildDeleted:
      begin
        SyncSelectedItems;
        SyncItemsCount;
        // Don't catch this when the RootNode is deleted (happens when changing dir)
        if Node <> RootNode then begin
          // Focus the last item if required
          if (FListview.ItemFocused = nil) and (Flistview.Items.Count > 0) then
            FListview.ItemFocused := FListview.Items[Flistview.Items.Count - 1];
          if ViewStyle <> vsxReport then SyncInvalidate;
        end;
      end;
    crAccumulated:
      begin
        SyncSelectedItems;
        if FAccumulatedChanging then begin // Take a look at ReReadAndRefreshNode
          SyncItemsCount;
          // Focus the last item if required
          if (FListview.ItemFocused = nil) and (Flistview.Items.Count > 0) then
            FListview.ItemFocused := FListview.Items[Flistview.Items.Count - 1];
          if ViewStyle <> vsxReport then SyncInvalidate;
        end;
      end;
  end;
  FlushSearchCache;
end;

procedure TCustomVirtualExplorerListviewEx.ReReadAndRefreshNode(Node: PVirtualNode; SortNode: Boolean);
begin
  //This method is called by WM_SHELLNOTIFY and It's responsible of updating
  //the nodes, looking if they were added or deleted.
  //The nodes are updated inside a BeginUpdate/EndUpdate block, when EndUpdate
  //is reached DoStructureChange (with crAccumulated) is called once.
  //We need a flag so DoStructureChange knows who's calling him.
  FAccumulatedChanging := true;
  inherited;
  FAccumulatedChanging := false;
end;

procedure TCustomVirtualExplorerListviewEx.DoBeforeCellPaint(Canvas: TCanvas;
  Node: PVirtualNode; Column: TColumnIndex; CellRect: TRect);
var
  NS: TNamespace;
  I: integer;
begin
  if ValidateNamespace(Node, NS) then
    if ThumbsOptions.Highlight = thMultipleColors then begin
      I := IsImageFileIndex(NS.NameForParsing);
      if I > -1 then
        if FExtensionsList.Colors[I] <> clNone then begin
          Canvas.Brush.Color := FExtensionsList.Colors[I];
          Canvas.FillRect(CellRect);
        end;
    end
    else
      if ThumbsOptions.Highlight = thSingleColor then
        if IsImageFile(NS.NameForParsing) then begin
          Canvas.Brush.Color := ThumbsOptions.HighlightColor;
          Canvas.FillRect(CellRect);
        end;
  inherited;
end;

function TCustomVirtualExplorerListviewEx.InternalData(Node: PVirtualNode): Pointer;
begin
  if Node = nil then
    Result := nil
  else
    Result := PChar(Node) + FInternalDataOffset;
end;

function TCustomVirtualExplorerListviewEx.IsAnyEditing: Boolean;
begin
  Result := (inherited IsAnyEditing) or (IsValidChildListview and FListview.IsEditing);
end;

function TCustomVirtualExplorerListviewEx.ValidateThumbnail(Node: PVirtualNode; var ThumbData: PThumbnailData): Boolean;
begin
  Result := False;
  ThumbData := nil;
  if Assigned(Node) then
  begin
    ThumbData := InternalData(Node);
    Result := Assigned(ThumbData);
  end
end;

function TCustomVirtualExplorerListviewEx.ValidateListItem(Node: PVirtualNode; var ListItem: TListItem): Boolean;
var
  C: Cardinal;
begin
  Result := False;
  ListItem := nil;
  if Assigned(Node) and Assigned(FListview) then
  begin
    if not (vsInitialized in Node.States) then
      InitNode(Node);
    C := FListview.Items.Count;
    if (C > 0) and (Node.Index < C) then
      ListItem := FListview.Items[Node.Index];
    Result := Assigned(ListItem);
  end
end;

function TCustomVirtualExplorerListviewEx.IsValidChildListview: boolean;
begin
  Result := Assigned(FListview) and FListview.HandleAllocated;
end;

procedure TCustomVirtualExplorerListviewEx.SetBounds(ALeft, ATop, AWidth,
  AHeight: Integer);
begin
  inherited;
  if IsValidChildListview then
    if not EqualRect(FListview.BoundsRect, Rect(ALeft, ATop, AWidth, AHeight)) then
      FListview.SetBounds(ALeft, ATop, AWidth, AHeight);
end;

function TCustomVirtualExplorerListviewEx.Focused: Boolean;
begin
  if (ViewStyle <> vsxReport) and IsValidChildListview then
    Result := FListview.Focused
  else
    Result := inherited Focused;
end;

procedure TCustomVirtualExplorerListviewEx.SetFocus;
begin
  if Parent.Visible then begin
    if ViewStyle = vsxReport then
      inherited
    else
      if IsValidChildListview then
        FListview.SetFocus;
  end;
end;

function TCustomVirtualExplorerListviewEx.BrowseToByPIDL(APIDL: PItemIDList;
  ExpandTarget, SelectTarget, SetFocusToVET, CollapseAllFirst: Boolean;
  ShowAllSiblings: Boolean = True): Boolean;
begin
  Result := inherited BrowseToByPIDL(APIDL, ExpandTarget, SelectTarget,
    SetFocusToVET, CollapseAllFirst, ShowAllSiblings);
  if FViewStyle <> vsxReport then SyncSelectedItems;
end;

procedure TCustomVirtualExplorerListviewEx.CopyToClipBoard;
begin
  if FViewStyle <> vsxReport then SyncSelectedItems(false);
  inherited;
end;

procedure TCustomVirtualExplorerListviewEx.CutToClipBoard;
begin
  if FViewStyle <> vsxReport then SyncSelectedItems(false);
  inherited;
end;

function TCustomVirtualExplorerListviewEx.PasteFromClipboard: Boolean;
begin
  if FViewStyle <> vsxReport then SyncSelectedItems(false);
  Result := inherited PasteFromClipboard;
end;

procedure TCustomVirtualExplorerListviewEx.SelectedFilesDelete;
begin
  if FViewStyle <> vsxReport then SyncSelectedItems(false);
  inherited;
end;

procedure TCustomVirtualExplorerListviewEx.SelectedFilesPaste(AllowMultipleTargets: Boolean);
begin
  if not (toVETReadOnly in TreeOptions.VETMiscOptions) then begin
    if FViewStyle <> vsxReport then SyncSelectedItems(false);
    inherited;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.SelectedFilesShowProperties;
begin
  if FViewStyle <> vsxReport then SyncSelectedItems(false);
  inherited;
end;

function TCustomVirtualExplorerListviewEx.EditNode(Node: PVirtualNode;
  Column: TColumnIndex): Boolean;
begin
  Result := false;
  if FViewStyle = vsxReport then
    Result := inherited EditNode(Node, Column)
  else begin
    if Assigned(Node) and not (vsDisabled in Node.States) and
      not (toReadOnly in TreeOptions.MiscOptions) then
    begin
      if not Focused then
        SetFocus;
      FocusedNode := Node;
      if not (vsInitialized in Node.States) then
        InitNode(Node);
      SyncSelectedItems;
      Result := FListview.Items[Node.index].EditCaption;
    end;
  end;
end;

function TCustomVirtualExplorerListviewEx.EditFile(APath: WideString): Boolean;
// Selects a file to edit it.
// APath parameter can be a filename or a full pathname to a file.
// If APath is a filename it searches the file in the current directory.
// If APath is a full pathname it changes the current directory to the APath
// dir and searches the file.
var
  Node: PVirtualNode;
  D: WideString;
begin
  Result := False;
  if Pos(':', APath) = 0 then
    // It's a file, include the current directory
    APath := IncludeTrailingBackslashW(RootFolderNamespace.NameForParsing) + APath
  else begin
    // Browse to the directory if the root is incorrect
    D := ExtractFileDirW(APath);
    if not SpCompareText(RootFolderNamespace.NameForParsing, D) then
      BrowseTo(D);
  end;

  Node := FindNode(APath);
  if Assigned(Node) then begin
    ClearSelection;
    Selected[Node] := True;
    EditNode(Node, 0); // EditNode calls SyncSelected
    Result := True;
  end;
end;

function TCustomVirtualExplorerListviewEx.InvalidateNode(Node: PVirtualNode): TRect;
var
  L: TListItem;
  R: TRect;
begin
  Result := inherited InvalidateNode(Node);
  if Assigned(Node) and (Node.CheckType <> VirtualTrees.ctNone) and not (csDesigning in ComponentState) and
    HandleAllocated and IsValidChildListview and (ViewStyle <> vsxReport) and ValidateListItem(Node, L) then
  begin
    R := L.DisplayRect(drIcon);
    InvalidateRect(FListview.Handle, @R, True);
  end;
end;

procedure TCustomVirtualExplorerListviewEx.SyncInvalidate;
begin
  if ViewStyle = vsxReport then
    Invalidate
  else
    if HandleAllocated and (ViewStyle <> vsxReport) and IsValidChildListview and not (csDesigning in ComponentState) then
      FListview.Invalidate;
end;

procedure TCustomVirtualExplorerListviewEx.SyncItemsCount;
begin
  if HandleAllocated then
    FListview.Items.Count := RootNode.ChildCount;
end;

procedure TCustomVirtualExplorerListviewEx.SyncOptions;
begin
  if Assigned(FListview) then begin
    FListview.SetBounds(left, top, width, height);
    FListview.Align := Align;
    FListview.Anchors := Anchors;
    FListview.Constraints.Assign(Constraints);
    FListview.ReadOnly := not (toEditable in TreeOptions.MiscOptions);
    FListview.MultiSelect := toMultiSelect in TreeOptions.SelectionOptions;
    FListview.PopupMenu := PopupMenu;
    FListview.BorderStyle := BorderStyle;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.SyncSelectedItems(UpdateChildListview: boolean = True);
var
  Node: PVirtualNode;
  LItem: TListItem;
begin
  if not FListview.HandleAllocated then
    Exit;
  //Sync focused and selected items
  if UpdateChildListview then begin
    //Clear the selection, but pause automatic selection sync of TSyncListView.CNNotify
    FListview.FSelectionPause := true; //pause the selection
    try
      //Long captions items doesn't get refreshed, we can't use FListview.Selected := nil;
      LItem := FListview.Selected;
      while Assigned(LItem) do begin
        LItem.Selected := false;
        FListview.UpdateItems(LItem.index, LItem.index);
        LItem := FListview.GetNextItem(LItem, sdAll, [isSelected]);
      end;
    finally
      FListview.FSelectionPause := false; //restore
    end;

    Node := GetFirstSelected;
    while Assigned(Node) do begin
      FListview.Items[Node.index].Selected := true;
      Node := GetNextSelected(Node);
    end;
    if Assigned(FocusedNode) then begin
      FListview.Items[FocusedNode.index].Focused := true;
      FListview.Items[FocusedNode.index].MakeVisible(false);
    end;
  end
  else begin
    ClearSelection;
    LItem := FListview.Selected;
    while Assigned(LItem) do begin
      Node := PVirtualNode(LItem.Data);
      if Assigned(Node) then Selected[Node] := true;
      LItem := FListview.GetNextItem(LItem, sdAll, [isSelected]);
    end;
    if Assigned(FListview.ItemFocused) then
      FocusedNode := PVirtualNode(FListview.ItemFocused.Data);
  end;
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemAdd(NS: TNamespace;
  Thumbnail: TBitmap; ImageWidth, ImageHeight: Integer): Boolean;
begin
  Result := True;
  if Assigned(OnThumbsCacheItemAdd) then
    FOnThumbsCacheItemAdd(Self, NS, Thumbnail, ImageWidth, ImageHeight, Result);
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemLoad(NS: TNamespace;
  var CacheItem: TThumbsCacheItem): Boolean;
begin
  // Update the cache entry if the file was changed
  Result := NS.LastWriteDateTime = CacheItem.FileDateTime;
  if Assigned(OnThumbsCacheItemLoad) then
    FOnThumbsCacheItemLoad(Self, NS, CacheItem, Result);
  CacheItem.FileDateTime := NS.LastWriteDateTime;
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemRead(Filename: WideString;
  Thumbnail: TBitmap): Boolean;
begin
  Result := True;
  if Assigned(OnThumbsCacheItemRead) then
    FOnThumbsCacheItemRead(Self, Filename, Thumbnail, Result);
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheItemProcessing(NS: TNamespace;
  Thumbnail: TBitmap; var ImageWidth, ImageHeight: integer): Boolean;
begin
  Result := True;
  if Assigned(OnThumbsCacheItemProcessing) then
    FOnThumbsCacheItemProcessing(Self, NS, Thumbnail, ImageWidth, ImageHeight, Result);
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheLoad(Sender: TThumbsCache;
  CacheFilePath: WideString; Comments: TWideStringList): Boolean;
begin
  Result := True;
  if Assigned(FOnThumbsCacheLoad) then FOnThumbsCacheLoad(Sender, CacheFilePath, Comments, Result);
end;

function TCustomVirtualExplorerListviewEx.DoThumbsCacheSave(Sender: TThumbsCache;
  CacheFilePath: WideString; Comments: TWideStringList): Boolean;
begin
  Result := True;
  if Assigned(FOnThumbsCacheSave) then FOnThumbsCacheSave(Sender, CacheFilePath, Comments, Result);
end;

function TCustomVirtualExplorerListviewEx.GetDetailsString(Node: PVirtualNode; ThumbFormatting: Boolean = True): WideString;
var
  NS: TNamespace;
  TD: PThumbnailData;
  CI: TThumbsCacheItem;
  S, K, D: WideString;
  I: integer;
begin
  //When ThumbFormatting is true it returns the minimum info available,
  //mantaining the line order.
  Result := '';
  if ValidateNamespace(Node, NS) then begin
    //Image size
    S := '';
    if ValidateThumbnail(Node, TD) and (TD.State = tsValid) and (TD.CachePos > -1) then begin
      if ThumbsOptions.CacheOptions.FThumbsCache.Read(TD.CachePos, CI) and (CI.ImageWidth > 0) and (CI.ImageHeight > 0) then
        S := Format('%dx%d', [CI.ImageWidth, CI.ImageHeight])
    end;
    //File size
    if not NS.Folder then
      K := NS.SizeOfFileKB
    else
      K := '';
    //Modified date
    D := NS.LastWriteTime;
    if D <> '' then begin  //Delete the seconds from the LastWriteTime
      for I := Length(D) downto 0 do
        if D[I] = ':' then break;
      if I > 0 then
        Delete(D, I, Length(D));
    end;

    if ThumbFormatting then begin
      Result := Format('%s' + #13 + '%s' + #13 + '%s', [S, K, D]);
      if Result = #13 + #13 then Result := '';
    end
    else begin
      if NS.NameInFolder <> '' then
        Result := Result + NS.NameInFolder;
      if S <> '' then
        Result := Result + #13 + S;
      if K <> '' then
        Result := Result + #13 + K;
      if D <> '' then
        Result := Result + #13 + D;
    end;
  end;
end;

function TCustomVirtualExplorerListviewEx.DoThumbsGetDetails(Node: PVirtualNode; HintDetails: Boolean): WideString;
begin
  Result := GetDetailsString(Node, not HintDetails);
  if Assigned(FOnThumbsGetDetails) then FOnThumbsGetDetails(Self, Node, HintDetails, Result);
end;

procedure TCustomVirtualExplorerListviewEx.DoThumbsDrawBefore(ACanvas: TCanvas;
  ListItem: TListItem; ThumbData: PThumbnailData;
  AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean);
begin
  if Assigned(OnThumbsDrawBefore) then
    FOnThumbsDrawBefore(Self, ACanvas, ListItem, ThumbData, AImageRect, ADetailsRect, DefaultDraw);
end;

procedure TCustomVirtualExplorerListviewEx.DoThumbsDrawAfter(ACanvas: TCanvas;
  ListItem: TListItem; ThumbData: PThumbnailData;
  AImageRect, ADetailsRect: TRect; var DefaultDraw: Boolean);
begin
  if Assigned(OnThumbsDrawAfter) then
    FOnThumbsDrawAfter(Self, ACanvas, ListItem, ThumbData, AImageRect, ADetailsRect, DefaultDraw);
end;

function TCustomVirtualExplorerListviewEx.DoThumbsDrawHint(HintBitmap: TBitmap; Node: PVirtualNode): Boolean;
begin
  Result := true;
  if Assigned(FOnThumbsDrawHint) then FOnThumbsDrawHint(Self, HintBitmap, Node, Result);
end;

procedure TCustomVirtualExplorerListviewEx.DrawThumbBG(ACanvas: TCanvas;
  Item: TListItem; ThumbData: PThumbnailData; R: TRect);
begin
  if (ThumbData.State = tsValid) or (ThumbsOptions.BorderOnFiles) then begin
    if Item.Selected and (not FListview.IsEditing) then begin
      if FListview.Focused then ACanvas.Brush.Color := Colors.FocusedSelectionColor //selected color
      else ACanvas.Brush.Color := Colors.UnFocusedSelectionColor; //grayed color
    end;
    ACanvas.Fillrect(R);
  end;
end;

procedure DrawFocusRect2(ACanvas: TCanvas; const R: TRect);
var
  DC: HDC;
  C1, C2: TColor;
begin
  DC := ACanvas.Handle;
  C1 := SetTextColor(DC, clBlack);
  C2 := SetBkColor(DC, clWhite);
  Windows.DrawFocusRect(DC, R);
  SetTextColor(DC, C1);
  SetBkColor(DC, C2);
end;

procedure TCustomVirtualExplorerListviewEx.DrawThumbFocus(ACanvas: TCanvas;
  Item: TListItem; ThumbData: PThumbnailData; R: TRect);
begin
  if (ThumbData.State = tsValid) or (ThumbsOptions.BorderOnFiles) then begin
    ACanvas.Brush.Style := bsSolid;
    if FListview.Focused and Item.Focused then
      DrawFocusRect2(ACanvas, R)
    else
      DrawThumbBorder(ACanvas, ThumbsOptions.Border, R);
  end;
end;

procedure DrawImageListIcon(ACanvas: TCanvas; ImgL: TImageList; X, Y: integer; LV: TCustomVirtualExplorerListviewEx; Item: TListItem);
var
  ForeColor, Style: Cardinal;
begin
  if LV.ChildListview.IsItemGhosted(Item) then
    ForeColor := ColorToRGB(LV.ChildListview.Color)
  else
    if ((LV.ViewStyle <> vsxThumbs) or not LV.ThumbsOptions.BorderOnFiles) and LV.ChildListview.Focused and Item.Selected then
      ForeColor := ColorToRGB(clHighlight)
    else
      ForeColor := CLR_NONE;

  if ForeColor = CLR_NONE then Style := ILD_TRANSPARENT
  else Style := ILD_TRANSPARENT or ILD_BLEND;

  if Item.OverlayIndex > -1 then
    Style := Style or ILD_OVERLAYMASK and Cardinal(IndexToOverlayMask(Item.OverlayIndex + 1));

  ImageList_DrawEx(ImgL.Handle, Item.ImageIndex, ACanvas.Handle, X, Y, 0, 0, CLR_NONE, ForeColor, Style);
end;

procedure TCustomVirtualExplorerListviewEx.DrawIcon(ACanvas: TCanvas; Item: TListItem;
  ThumbData: PThumbnailData; RThumb, RDetails: TRect);
var
  X, Y: integer;
  IL: TImageList;
  CacheThumb: TBitmap;
  S: WideString;
  NS: TNamespace;
begin
  //Paint the Thumbs details
  if ThumbsOptions.Details and (ViewStyle = vsxThumbs) then begin
    S := DoThumbsGetDetails(PVirtualNode(Item.Data), false);
    if S <> '' then begin
      ACanvas.Brush.Style := bsClear;
      ACanvas.Font.Size := 8;
      if FListview.Focused and Item.selected then begin
        ACanvas.Font.Color := clHighlightText;
        ACanvas.Brush.Color := clHighlight;
      end;
      if Win32Platform = VER_PLATFORM_WIN32_WINDOWS then  //Win9x must use AnsiStrings for DrawText
        Windows.DrawText(ACanvas.Handle, PChar(AnsiString(S)), -1, RDetails, DT_CENTER)
      else
        Windows.DrawTextW(ACanvas.Handle, PWideChar(S), -1, RDetails, DT_CENTER);
    end;
  end;

  //Paint the Thumbs or Icons
  if (ViewStyle = vsxThumbs) and (ThumbData.State = tsValid) then begin
    CacheThumb := TBitmap.Create;
    try
      if (Assigned(OnThumbsCacheItemRead) and ValidateNamespace(PVirtualNode(Item.Data), NS) and not DoThumbsCacheItemRead(NS.NameForParsing, CacheThumb))
        or ((ThumbData.CachePos > -1) and ThumbsOptions.CacheOptions.FThumbsCache.Read(ThumbData.CachePos, CacheThumb)) then
      begin
        X := RThumb.left + (RThumb.right - RThumb.left - CacheThumb.Width) div 2;
        Y := RThumb.top + (RThumb.bottom - RThumb.top -  CacheThumb.Height) div 2;
        ACanvas.Draw(X, Y, CacheThumb);
      end;
    finally
      CacheThumb.Free;
    end;
  end
  else begin
    Case ViewStyle of
      vsxThumbs:
        if ThumbsOptions.ShowXLIcons and (ThumbsOptions.Width >= 48) and (ThumbsOptions.Height >= 48) then
          IL := VirtualSystemImageLists.ExtraLargeSysImages
        else
          IL := VirtualSystemImageLists.LargeSysImages;
      vsxIcon:
        IL := VirtualSystemImageLists.LargeSysImages
    else
      IL := VirtualSystemImageLists.SmallSysImages;
    end;

    X := RThumb.left + (RThumb.right - RThumb.left - IL.Width) div 2;
    Y := RThumb.top + (RThumb.bottom - RThumb.top - IL.Height) div 2;

    DrawImageListIcon(ACanvas, IL, X, Y, Self, Item);
  end;
end;

procedure TCustomVirtualExplorerListviewEx.LVOnAdvancedCustomDrawItem(Sender: TCustomListView;
  Item: TListItem; State: TCustomDrawState; Stage: TCustomDrawStage; var DefaultDraw: Boolean);
var
  ThumbDefaultDraw: boolean;
  RIcon, R, RThumb, RDetails: TRect;
  Node: PVirtualNode;
  ThumbData: PThumbnailData;
  PaintInfo: TVTPaintInfo;
  B: TBitmap;
  NS: TNamespace;
  I: integer;
begin
  if (ViewStyle = vsxReport) or (not Assigned(FListview)) or (FListview.OwnerDataPause) or
    (FListview.Items.Count = 0) or (Item.Index < 0) or (Item.Index >= FListview.Items.Count) then
      Exit;

  Case Stage of
    cdPrePaint:
      if not Item.Selected then begin
        Node := PVirtualNode(Item.Data);
        if ValidateNamespace(Node, NS) then begin
          Case ThumbsOptions.Highlight of
            thSingleColor:
              if IsImageFile(NS.NameForParsing) then
                Sender.Canvas.Brush.Color := ThumbsOptions.HighlightColor;
            thMultipleColors:
              begin
                I := IsImageFileIndex(NS.NameForParsing);
                if I > -1 then
                  if FExtensionsList.Colors[I] <> clNone then
                    Sender.Canvas.Brush.Color := FExtensionsList.Colors[I];
              end;
          end;
          if not (toNoUseVETColorsProp in TreeOptions.VETFolderOptions) then begin
            if NS.Compressed then Sender.Canvas.Font.Color := VETColors.CompressedTextColor
            else
              if NS.Folder then Sender.Canvas.Font.Color := VETColors.FolderTextColor
              else Sender.Canvas.Font.Color := VETColors.FileTextColor;
          end;
          if Assigned(OnPaintText) then OnPaintText(Self, Sender.Canvas, Node, 0, ttNormal);
        end;
      end;
    cdPostPaint:
      begin
        //In a normal ViewStyle only draw when there's an overlay icon
        if ViewStyle in [vsxIcon, vsxSmallIcon, vsxList] then
          if not (FListview.IsItemGhosted(Item) or (Item.OverlayIndex > -1)) then
            Exit;
        //Do the drawing in a bitmap buffer
        B := TBitmap.Create;
        B.Canvas.Lock;
        try
          RIcon := FListview.GetLVItemRect(Item.index, drIcon);
          R := Rect(0, 0, RIcon.Right - RIcon.Left, RIcon.Bottom - RIcon.Top);
          InitBitmap(B, R.Right, R.Bottom, Self.Color);

          if FListview.IsBackgroundValid then
            B.Canvas.CopyRect(R, Sender.Canvas, RIcon);

          B.Canvas.Brush.Color := Sender.Canvas.Brush.Color;
          if ViewStyle = vsxThumbs then begin
            Node := PVirtualNode(Item.Data);
            if ValidateThumbnail(Node, ThumbData) then begin
              DrawThumbBG(B.Canvas, Item, ThumbData, R);

              if ThumbsOptions.Details then begin
                RThumb :=   Rect(R.Left, R.Top, R.Right, R.Bottom - ThumbsOptions.DetailsHeight);
                RDetails := Rect(R.Left, R.Bottom - ThumbsOptions.DetailsHeight, R.Right, R.Bottom);
              end
              else begin
                RThumb := R;
                RDetails := Rect(0, 0, 0, 0);
              end;

              ThumbDefaultDraw := true;
              DoThumbsDrawBefore(B.Canvas, Item, ThumbData, RThumb, RDetails, ThumbDefaultDraw);
              //if ThumbDefaultDraw and (ThumbData.State <> tsProcessing) then //this will increase the rendering speed, but it looks odd
              if ThumbDefaultDraw then begin
                DrawIcon(B.Canvas, Item, ThumbData, RThumb, RDetails);
                // Draw the checkbox
                if (toCheckSupport in TreeOptions.MiscOptions) and (Node.CheckType <> VirtualTrees.ctNone) then begin
                  PaintInfo.Node := Node;
                  PaintInfo.Canvas := B.Canvas;
                  PaintInfo.ImageInfo[iiCheck].Index := GetCheckImage(Node);
                  PaintInfo.ImageInfo[iiCheck].XPos := 0;
                  PaintInfo.ImageInfo[iiCheck].YPos := 0;
                  PaintCheckImage(PaintInfo);
                end;
              end;

              ThumbDefaultDraw := true;
              DoThumbsDrawAfter(B.Canvas, Item, ThumbData, RThumb, RDetails, ThumbDefaultDraw);
              if ThumbDefaultDraw then begin
                if ThumbsOptions.ShowSmallIcon and (ThumbData.State = tsValid) then
                  DrawImageListIcon(B.Canvas, VirtualSystemImageLists.SmallSysImages, (RThumb.right - RThumb.left - VirtualSystemImageLists.SmallSysImages.Width) - 2, 2, Self, Item);
                DrawThumbFocus(B.Canvas, Item, ThumbData, R);
              end;
            end;
          end
          else begin
            //Listviews in virtual mode doesn't draw overlay images, from:
            //http://groups.google.com/groups?hl=en&selm=7gftob%24aq4%40forums.borland.com
            DrawIcon(B.Canvas, Item, nil, R, R);
          end;

          Sender.Canvas.Lock;
          try
            // The TListview Canvas is very delicate
            // We must set the font color for the default focus painting
            if ColorToRGB(Sender.Canvas.Brush.Color) = 0 then
              Sender.Canvas.Font.Color := clWhite
            else
              Sender.Canvas.Font.Color := clWindowText;
            Sender.Canvas.Draw(RIcon.Left, RIcon.Top, B);
          finally
            Sender.Canvas.UnLock;
          end;
        finally
          B.Canvas.UnLock;
          B.Free;
        end;
      end;
  end;
end;

function TCustomVirtualExplorerListviewEx.GetThumbDrawingBounds(IncludeThumbDetails, IncludeBorderSize: Boolean): TRect;
begin
  //Obtains the REAL Thumbnail drawing Bounds Rect
  //It's like Item.displayrect(dricon)
  if IncludeBorderSize then
    Result := Rect(0, 0, ThumbsOptions.Width + ThumbsOptions.BorderSize * 2, ThumbsOptions.Height + ThumbsOptions.BorderSize * 2)
  else
    Result := Rect(0, 0, ThumbsOptions.Width, ThumbsOptions.Height);
  if IncludeThumbDetails and ThumbsOptions.Details then
    Result.Bottom := Result.Bottom + ThumbsOptions.DetailsHeight;
end;

function TCustomVirtualExplorerListviewEx.IsImageFileIndex(FileName: WideString): integer;
var
  Ext: WideString;
begin
  Result := -1;
  Ext := ExtractFileExtW(FileName);
  if ExtensionsExclusionList.IndexOf(Ext) < 0 then
  begin
    Result := ExtensionsList.IndexOf(Ext);
    if Result < 0 then
      Result := ShellExtractExtensionsList.IndexOf(Ext);
  end;
end;

function TCustomVirtualExplorerListviewEx.IsImageFile(FileName: WideString): Boolean;
begin
  Result := IsImageFileIndex(FileName) > -1;
end;

function TCustomVirtualExplorerListviewEx.IsImageFile(Node: PVirtualNode): TNamespace;
begin
  //Returns the namespace if it's an Image file
  Result := nil;
  if ValidateNamespace(Node, Result) and Result.FileSystem and not Result.Folder then begin
    if not IsImageFile(Result.NameForParsing) then Result := nil;
  end
  else
    Result := nil;
end;

procedure TCustomVirtualExplorerListviewEx.ResetThumbSpacing;
var
  R: TRect;
  W, H: integer;
begin
  //The cx and cy parameters of ListView_SetIconSpacing are relative to the
  //upper-left corner of an icon.
  //Therefore, to set spacing between icons that do not overlap, the cx or cy
  //values must include the size of the icon + the amount of empty space
  //desired between icons. Values that do not include the width of the icon
  //will result in overlaps.
  //When defining the icon spacing, cx and cy must set to 4 or larger.
  //Smaller values will not yield the desired layout.
  //To reset cx and cy to the default spacing, set the lParam value to -1.
  //i.e  SendMessage(FListview.Handle, LVM_SETICONSPACING, 0, -1);
  if ViewStyle = vsxThumbs then begin
    R := GetThumbDrawingBounds(true, true);
    W := R.Right + ThumbsOptions.SpaceWidth;
    H := R.Bottom + ThumbsOptions.SpaceHeight;
    ListView_SetIconSpacing(FListview.Handle, W, H);
    FListview.UpdateArrangement;
    if Assigned(FListview.ItemFocused) then
      FListview.ItemFocused.MakeVisible(false);
  end;
end;

procedure TCustomVirtualExplorerListviewEx.ResetThumbThread;
var
  N: PVirtualNode;
  TD: PThumbnailData;
begin
  //Reset the thread properties and reload
  ThumbThread.QueryList.LockList;
  try
    ThumbThread.ClearPendingItems(Self, WM_VLVEXTHUMBTHREAD, Malloc);
    ThumbThread.ResetThumbOptions;
    ThumbsOptions.CacheOptions.FThumbsCache.Clear;
    ThumbsOptions.CacheOptions.FThumbsCache.ThumbWidth := ThumbsOptions.Width;
    ThumbsOptions.CacheOptions.FThumbsCache.ThumbHeight := ThumbsOptions.Height;

    //Iterate through the nodes and reset the thumb state of valid items
    N := RootNode.FirstChild;
    while Assigned(N) do begin
      if (vsInitialized in N.States) and ValidateThumbnail(N, TD) then
        if IsThumbnailActive(TD.State) then begin
          TD.CachePos := -1;
          TD.Reloading := False;
          TD.State := tsEmpty;
        end;
      N := N.NextSibling;
    end;

  finally
    ThumbThread.QueryList.UnlockList;
  end;

  if ViewStyle = vsxThumbs then
    SyncInvalidate;
end;

procedure TCustomVirtualExplorerListviewEx.SetViewStyle(const Value: TViewStyleEx);
var
  PrevFocused: boolean;
begin
  if FViewStyle <> Value then begin
    SyncOptions;
    FListview.Items.BeginUpdate;
    try
      if not (csDesigning in ComponentState) and FVisible and
      ((FViewStyle = vsxReport) and (Value <> vsxReport)) or
      ((FViewStyle <> vsxReport) and (Value = vsxReport)) then begin
        PrevFocused := Focused;
        Parent.DisableAlign;
        try
          FListview.Visible := Value <> vsxReport;
          inherited Visible := not FListview.Visible;
          if FListview.Visible then //force hiding
            SetWindowPos(Self.Handle, 0, 0, 0, 0, 0, SWP_NOSIZE + SWP_NOMOVE + SWP_NOZORDER + SWP_NOACTIVATE + SWP_HIDEWINDOW);
        finally
          Parent.EnableAlign;
        end;
        //Sync focused and selected items
        if (FViewStyle = vsxReport) and (Value <> vsxReport) then begin
          SyncItemsCount;
          SyncSelectedItems(true);
        end
        else
          if (FViewStyle <> vsxReport) and (Value = vsxReport) then
            SyncSelectedItems(false);
        //Sync the focus
        if PrevFocused then begin
          FViewStyle := Value;
          SetFocus;
        end;
      end;

      FViewStyle := Value;

      //Set the child Listview.ViewStyle, this might look simple but the
      //icon spacing is incorrect if you don't force it.
      //To force correct spacing you should:
      // - Make sure the Listview is visible
      // - Set the correct icon spacing
      //I haven't found a better way, if you do just let me know.

      FListview.LargeImages := nil;

      Case Value of
        vsxThumbs: begin
          ResetThumbImageList(false);
          FListview.LargeImages := FDummyIL;
          FListview.ViewStyle := vsIcon;
          ResetThumbSpacing; //reset the spacing after vsIcon is setted
        end;
        vsxIcon: begin
          FListview.LargeImages := VirtualSystemImageLists.LargeSysImages;
          FListview.ViewStyle := vsIcon;
          ListView_SetIconSpacing(FListview.Handle, GetSystemMetrics(SM_CXICONSPACING),
            GetSystemMetrics(SM_CYICONSPACING));
        end;
        vsxList:
          FListview.ViewStyle := vsList;
        vsxSmallIcon:
          FListview.ViewStyle := vsSmallIcon;
      end;
    finally
      FListview.Items.EndUpdate;
      if Value <> vsxThumbs then
        FListview.UpdateArrangement;
    end;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.SetVisible(const Value: boolean);
begin
  if FVisible <> Value then begin
    FListview.Visible := Value and (FViewStyle <> vsxReport);
    inherited Visible := Value and (not FListview.Visible);
    FVisible := Value;
  end;
end;

function TCustomVirtualExplorerListviewEx.GetThumbThread: TThumbThread;
begin
  if not Assigned(FThumbThread) then
    FThumbThread := GetThumbThreadClass.Create(Self);
  Result := FThumbThread;
end;

function TCustomVirtualExplorerListviewEx.GetThumbThreadClass: TThumbThreadClass;
begin
  Result := nil;
  if Assigned(OnThumbThreadClass) then FOnThumbThreadClass(Self, Result);
  if not Assigned(Result) then
    Result := TThumbThread;
end;

procedure TCustomVirtualExplorerListviewEx.SetThumbThreadClassEvent(const Value: TThumbThreadClassEvent);
begin
  if Assigned(FThumbThread) then
  begin
    FThumbThread.Priority := tpNormal; //D6 has a Thread bug, we must set the priority to tpNormal before destroying
    ResetThumbThread;
    FThumbThread.Terminate;
    FThumbThread.SetEvent;
    FThumbThread.WaitFor;
    FreeAndNil(FThumbThread);
  end;
  FOnThumbThreadClass := Value;
end;

procedure TCustomVirtualExplorerListviewEx.ResetThumbImageList(ResetSpacing: boolean = True);
begin
  if ViewStyle = vsxThumbs then begin
    FDummyIL.Width := ThumbsOptions.Width - 16 + (ThumbsOptions.BorderSize * 2);
    if ThumbsOptions.Details then
      FDummyIL.Height := ThumbsOptions.Height - 4 + (ThumbsOptions.BorderSize * 2) + ThumbsOptions.DetailsHeight
    else
      FDummyIL.Height := ThumbsOptions.Height - 4 + (ThumbsOptions.BorderSize * 2);
    if ResetSpacing then
      ResetThumbSpacing;
  end;
end;

procedure TCustomVirtualExplorerListviewEx.FillExtensionsList(FillColors: Boolean = true);
var
  I: integer;
  Ext: WideString;
{$IFDEF USEGRAPHICEX}
  L: TStringList;
{$ELSE}
  {$IFDEF USEIMAGEMAGICK}
     L: TStringList;
  {$ENDIF}
{$ENDIF}
begin
  FExtensionsList.Clear;
  {$IFDEF USEGRAPHICEX}
  L := TStringList.Create;
  try
    FileFormatList.GetExtensionList(L);
    FExtensionsList.AddStrings(L);
    FExtensionsList.DeleteString('ico'); // Don't add ico
  finally
    L.Free;
  end;
  {$ELSE}
  {$IFDEF USEIMAGEMAGICK}
  L := TStringList.Create;
  try
    if Assigned(MagickFileFormatList) then begin
      MagickFileFormatList.GetExtensionList(L);
      FExtensionsList.AddStrings(L);
      FExtensionsList.DeleteString('ico'); // Don't add ico

      FExtensionsList.DeleteString('pdf'); // TODO -cImageMagick : Stack overflow exception in TMagickImage.LoadFromStream, MagickImage.pas line 744
      FExtensionsList.DeleteString('txt'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728
      FExtensionsList.DeleteString('avi'); // TODO -cImageMagick : infinite loop in BlobToImage: Trace: TMagickImage.LoadFromStream -> StreamToImage -> BlobToImage.
      FExtensionsList.DeleteString('mpg'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728
      FExtensionsList.DeleteString('mpeg'); // TODO -cImageMagick : 'Stream size must be defined' exception in TMagickImage.LoadFromStream (ASize <= 0), line 728
      FExtensionsList.DeleteString('htm'); // TODO -cImageMagick : delegate not supported
      FExtensionsList.DeleteString('html'); // TODO -cImageMagick : delegate not supported
    end;
  finally
    L.Free;
  end;
  {$ELSE}
  with FExtensionsList do begin
    CommaText := '.jpg, .jpeg, .jif, .bmp, .emf, .wmf';
    {$IFDEF USEIMAGEEN}
    CommaText := CommaText + ', .png, .pcx, .tif, .tiff, .gif';
    {$ELSE}
    {$IFDEF USEENVISION}
      //version 1.1
      CommaText := CommaText + ', .png, .pcx, .pcc, .tif, .tiff, .dcx, .tga, .vst, .afi';
      //version 2.0, eps (Encapsulated Postscript) and jp2 (JPEG2000 version)
      //CommaText := CommaText + ', .eps, .jp2'; <<<<<<< still in beta
    {$ENDIF}
    {$ENDIF}    
  end;
  {$ENDIF}
  {$ENDIF}

  if FillColors then begin
    for I := 0 to FExtensionsList.Count - 1 do begin
      Ext := FExtensionsList[I];
      if (Ext = '.jpg') or (Ext = '.jpeg') or (Ext = '.jif') or (Ext = '.jfif') or (Ext = '.jpe') then FExtensionsList.Colors[I] := $BADDDD
      else if (Ext = '.bmp') or (Ext = '.rle') or (Ext = '.dib') then FExtensionsList.Colors[I] := $EFD3D3
      else if (Ext = '.emf') or (Ext = '.wmf') then FExtensionsList.Colors[I] := $7DC7B0
      else if (Ext = '.gif') then FExtensionsList.Colors[I] := $CCDBCC
      else if (Ext = '.png') then FExtensionsList.Colors[I] := $DAB6DA
      else if (Ext = '.tif') or (Ext = '.tiff') or (Ext = '.fax') or (Ext = '.eps') then FExtensionsList.Colors[I] := $DBB5B0
      else if (Ext = '.pcx') or (Ext = '.dcx') or (Ext = '.pcc') or (Ext = '.scr') then FExtensionsList.Colors[I] := $D6D6DB
      else if (Ext = '.tga') or (Ext = '.vst') or (Ext = '.vda') or (Ext = '.win') or (Ext = '.icb') or (Ext = '.afi') then FExtensionsList.Colors[I] := $EFEFD6
      else if (Ext = '.psd') or (Ext = '.pdd') then FExtensionsList.Colors[I] := $D3EFEF
      else if (Ext = '.psp') then FExtensionsList.Colors[I] := $93C0DD
      else if (Ext = '.sgi') or (Ext = '.rgba') or (Ext = '.rgb') or (Ext = '.bw') then FExtensionsList.Colors[I] := $C2BBE3
      else if (Ext = '.rla') or (Ext = '.rpf') then FExtensionsList.Colors[I] := $D3EFEF
      else if (Ext = '.ppm') or (Ext = '.pgm') or (Ext = '.pbm') then FExtensionsList.Colors[I] := $95D4DD
      else if (Ext = '.cel') or (Ext = '.pic') then FExtensionsList.Colors[I] := $AFEFEE
      else if (Ext = '.cut') then FExtensionsList.Colors[I] := $AFEFEE
      else if (Ext = '.pcd') then FExtensionsList.Colors[I] := $AFEFEE;
      // $7DC7B0 = green, $FFBD0B = orange, CFCFCF = grey
    end;
  end;

  ExtensionsExclusionList.CommaText := '.url, .lnk, .ico';
end;

//WMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWMWM
{ TThumbsCacheItem }

constructor TThumbsCacheItem.Create(AFilename: WideString);
begin
  FThumbImageStream := TMemoryStream.Create;
  FStreamSignature := DefaultStreamSignature;
  FFilename := AFilename;
end;

constructor TThumbsCacheItem.CreateFromStream(ST: TStream);
begin
  FThumbImageStream := TMemoryStream.Create;
  FStreamSignature := DefaultStreamSignature;
  LoadFromStream(ST);
end;

destructor TThumbsCacheItem.Destroy;
begin
  FThumbImageStream.Free;
  inherited;
end;

procedure TThumbsCacheItem.Fill(AFileDateTime: TDateTime; AExif, AComment: WideString;
  AImageWidth, AImageHeight: Integer; ACompressed: Boolean;
  AThumbImageStream: TMemoryStream);
begin
  FFileDateTime := AFileDateTime;
  FExif := AExif;
  FComment := AComment;
  FImageWidth := AImageWidth;
  FImageHeight := AImageHeight;
  FCompressed := ACompressed;
  if Assigned(AThumbImageStream) then
    FThumbImageStream.LoadFromStream(AThumbImageStream);

  Changed;
end;

function TThumbsCacheItem.DefaultStreamSignature: WideString;
begin
  // Override this method to change the default stream signature
  // Use the StreamSignature to load or not the custom properties
  // in LoadFromStream.
  Result := '1.4';
end;

procedure TThumbsCacheItem.Assign(CI: TThumbsCacheItem);
begin
  // Override this method to Assign the the custom properties.
  Fill(CI.FileDateTime, CI.Exif, CI.Comment, CI.ImageWidth,
    CI.ImageHeight, CI.CompressedThumbImageStream, CI.ThumbImageStream);
end;

procedure TThumbsCacheItem.Changed;
begin
  // Override this method to set the custom properties.
  // At this point all the properties are filled and valid.
  // The protected FFilename variable is also valid.
end;

function TThumbsCacheItem.LoadFromStream(ST: TStream): Boolean;
begin
  // Override this method to read the properties from the stream
  // Use the StreamSignature to load or not the custom properties
  Result := True;
  FStreamSignature := ReadWideStringFromStream(ST);
  FFilename := ReadWideStringFromStream(ST);
  FFileDateTime := ReadDateTimeFromStream(ST);
  FImageWidth := ReadIntegerFromStream(ST);
  FImageHeight := ReadIntegerFromStream(ST);
  FExif := ReadWideStringFromStream(ST);
  FComment := ReadWideStringFromStream(ST);
  FCompressed := Boolean(ReadIntegerFromStream(ST));
  ReadMemoryStreamFromStream(ST, FThumbImageStream);
end;

procedure TThumbsCacheItem.SaveToStream(ST: TStream);
begin
  // Override this method to write the properties to the stream
  WriteWideStringToStream(ST, FStreamSignature);
  WriteWideStringToStream(ST, FFilename);
  WriteDateTimeToStream(ST, FFileDateTime);
  WriteIntegerToStream(ST, FImageWidth);
  WriteIntegerToStream(ST, FImageHeight);
  WriteWideStringToStream(ST, FExif);
  WriteWideStringToStream(ST, FComment);
  WriteIntegerToStream(ST, Integer(FCompressed));
  WriteMemoryStreamToStream(ST, FThumbImageStream);
end;

function TThumbsCacheItem.ReadBitmap(OutBitmap: TBitmap): Boolean;
begin
  Result := False;
  if Assigned(FThumbImageStream) then
    if FCompressed then
      ConvertJPGStreamToBitmap(FThumbImageStream, OutBitmap) // JPEG compressed, convert to Bitmap
    else begin
      OutBitmap.LoadFromStream(FThumbImageStream);
      FThumbImageStream.Position := 0;
    end;
end;

procedure TThumbsCacheItem.WriteBitmap(ABitmap: TBitmap; CompressIt: Boolean);
begin
  FCompressed := CompressIt;
  ABitmap.SaveToStream(FThumbImageStream);
  if FCompressed then
    ConvertBitmapStreamToJPGStream(FThumbImageStream, 60); //JPEG compressed
end;

end.