Source

wxPython / wx / lib / agw / customtreectrl.py

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
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
# --------------------------------------------------------------------------------- #
# CUSTOMTREECTRL wxPython IMPLEMENTATION
# Inspired By And Heavily Based On wxGenericTreeCtrl.
#
# Andrea Gavana, @ 17 May 2006
# Latest Revision: 29 Nov 2011, 15.00 GMT
#
#
# TODO List
#
# Almost All The Features Of wx.TreeCtrl Are Available, And There Is Practically
# No Limit In What Could Be Added To This Class. The First Things That Comes
# To My Mind Are:
#
# 1. Try To Implement A More Flicker-Free Background Image In Cases Like
#    Centered Or Stretched Image (Now CustomTreeCtrl Supports Only Tiled
#    Background Images).
#
# 2. Try To Mimic Windows wx.TreeCtrl Expanding/Collapsing behaviour: CustomTreeCtrl
#    Suddenly Expands/Collapses The Nodes On Mouse Click While The Native Control
#    Has Some Kind Of "Smooth" Expanding/Collapsing, Like A Wave. I Don't Even
#    Know Where To Start To Do That.
#
# 3. Speed Up General OnPaint Things? I Have No Idea, Here CustomTreeCtrl Is Quite
#    Fast, But We Should See On Slower Machines.
#
#
# For All Kind Of Problems, Requests Of Enhancements And Bug Reports, Please
# Write To Me At:
#
# andrea.gavana@maerskoil.com
# andrea.gavana@gmail.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #


"""
L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with some more
enhancements.


Description
===========

L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
same base functionalities plus some more enhancements. This class does not rely on
the native control, as it is a full owner-drawn tree control.
Apart of the base functionalities of L{CustomTreeCtrl} (described below), in addition
to the standard `wx.TreeCtrl` behaviour this class supports:

* CheckBox-type items: checkboxes are easy to handle, just selected or unselected
  state with no particular issues in handling the item's children;
* Added support for 3-state value checkbox items;
* RadioButton-type items: since I elected to put radiobuttons in L{CustomTreeCtrl}, I
  needed some way to handle them, that made sense. So, I used the following approach:
  
  - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
    only one of a set of radiobuttons that share a common parent can be checked at
    once. If a radiobutton node becomes checked, then all of its peer radiobuttons
    must be unchecked.
  - If a radiobutton node becomes unchecked, then all of its child nodes will become
    inactive.

* Hyperlink-type items: they look like an hyperlink, with the proper mouse cursor on
  hovering;
* Multiline text items (**note**: to add a newline character in a multiline item, press
  ``Shift`` + ``Enter`` as the ``Enter`` key alone is consumed by L{CustomTreeCtrl} to finish
  the editing and ``Ctrl`` + ``Enter`` is consumed by the platform for tab navigation);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item;
* Possibility to horizontally align the widgets attached to tree items on the
  same tree level.
* Possibility to align the widgets attached to tree items to the rightmost edge of L{CustomTreeCtrl};
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style;
* Customized drag and drop images built on the fly;
* Setting the L{CustomTreeCtrl} item buttons to a personalized imagelist;
* Setting the L{CustomTreeCtrl} check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of `wx.Pen` styles);
* Using an image as a L{CustomTreeCtrl} background (currently only in "tile" mode);
* Adding images to any item in the leftmost area of the L{CustomTreeCtrl} client window.
* Separator-type items which are simply visual indicators that are meant to set apart
  or divide tree items, with the following caveats:

  - Separator items should not have children, labels, data or an associated window;
  - You can change the color of individual separators by using L{SetItemTextColour}, or you can use
    L{SetSeparatorColour} to change the color of all separators. The default separator colour
    is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
  - Separators can be selected just like any other tree item;
  - Separators cannot have text;
  - Separators cannot have children;
  - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.


And a lot more. Check the demo for an almost complete review of the functionalities.


Base Functionalities
====================

L{CustomTreeCtrl} supports all the `wx.TreeCtrl` styles, except:

- ``TR_EXTENDED``: supports for this style is on the todo list (am I sure of this?).

Plus it has 3 more styles to handle checkbox-type items:

- ``TR_AUTO_CHECK_CHILD``: automatically checks/unchecks the item children;
- ``TR_AUTO_CHECK_PARENT``: automatically checks/unchecks the item parent;
- ``TR_AUTO_TOGGLE_CHILD``: automatically toggles the item children.

And two styles you can use to force the horizontal alignment of all the widgets
attached to the tree items:

- ``TR_ALIGN_WINDOWS``: aligns horizontally the windows belonging to the item on the
  same tree level.
- ``TR_ALIGN_WINDOWS_RIGHT``: aligns to the rightmost position the windows belonging
  to the item on the same tree level.
    
All the methods available in `wx.TreeCtrl` are also available in L{CustomTreeCtrl}.


Usage
=====

Usage example::

    import wx
    import wx.lib.agw.customtreectrl as CT

    class MyFrame(wx.Frame):

        def __init__(self, parent):

            wx.Frame.__init(self, parent, -1, "CustomTreeCtrl Demo")        

            # Create a CustomTreeCtrl instance
            custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)
            
            # Add a root node to it
            root = custom_tree.AddRoot("The Root Item")            

            # Create an image list to add icons next to an item
            il = wx.ImageList(16, 16)
            fldridx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FOLDER,      wx.ART_OTHER, 16))
            fldropenidx = il.Add(wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN,   wx.ART_OTHER, 16))
            fileidx     = il.Add(wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, 16))

            custom_tree.SetImageList(il)
            
            custom_tree.SetItemImage(root, fldridx, wx.TreeItemIcon_Normal)
            custom_tree.SetItemImage(root, fldropenidx, wx.TreeItemIcon_Expanded)

            for x in range(15):
                child = custom_tree.AppendItem(root, "Item %d" % x)
                custom_tree.SetItemImage(child, fldridx, wx.TreeItemIcon_Normal)
                custom_tree.SetItemImage(child, fldropenidx, wx.TreeItemIcon_Expanded)

                for y in range(5):
                    last = custom_tree.AppendItem(child, "item %d-%s" % (x, chr(ord("a")+y)))
                    custom_tree.SetItemImage(last, fldridx, wx.TreeItemIcon_Normal)
                    custom_tree.SetItemImage(last, fldropenidx, wx.TreeItemIcon_Expanded)

                    for z in range(5):
                        item = custom_tree.AppendItem(last,  "item %d-%s-%d" % (x, chr(ord("a")+y), z))
                        custom_tree.SetItemImage(item, fileidx, wx.TreeItemIcon_Normal)
                        custom_tree.SetItemImage(item, smileidx, wx.TreeItemIcon_Selected)

            custom_tree.Expand(self.root)


    # our normal wxApp-derived class, as usual

    app = wx.PySimpleApp()

    frame = MyFrame(None)
    app.SetTopWindow(frame)
    frame.Show()

    app.MainLoop()


        
Events
======

All the events supported by `wx.TreeCtrl` are also available in L{CustomTreeCtrl}, with
a few exceptions:

- ``EVT_TREE_GET_INFO`` (don't know what this means);
- ``EVT_TREE_SET_INFO`` (don't know what this means);
- ``EVT_TREE_ITEM_MIDDLE_CLICK`` (not implemented, but easy to add);
- ``EVT_TREE_STATE_IMAGE_CLICK`` (no need for that, look at the checking events below).

Plus, L{CustomTreeCtrl} supports the events related to the checkbutton-type items:

- ``EVT_TREE_ITEM_CHECKING``: an item is being checked;
- ``EVT_TREE_ITEM_CHECKED``: an item has been checked.

And to hyperlink-type items:

- ``EVT_TREE_ITEM_HYPERLINK``: an hyperlink item has been clicked (this event is sent
  after the ``EVT_TREE_SEL_CHANGED`` event).


Supported Platforms
===================

L{CustomTreeCtrl} has been tested on the following platforms:
  * Windows (Windows XP);
  * GTK (Thanks to Michele Petrazzo);
  * Mac OS (Thanks to John Jackson).


Window Styles
=============

This class supports the following window styles:

============================== =========== ==================================================
Window Styles                  Hex Value   Description
============================== =========== ==================================================
``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
============================== =========== ==================================================


Events Processing
=================

This class processes the following events:

============================== ==================================================
Event Name                     Description
============================== ==================================================
``EVT_TREE_BEGIN_DRAG``        Begin dragging with the left mouse button.
``EVT_TREE_BEGIN_LABEL_EDIT``  Begin editing a label. This can be prevented by calling L{Veto}.
``EVT_TREE_BEGIN_RDRAG``       Begin dragging with the right mouse button.
``EVT_TREE_DELETE_ITEM``       Delete an item.
``EVT_TREE_END_DRAG``          End dragging with the left or right mouse button.
``EVT_TREE_END_LABEL_EDIT``    End editing a label. This can be prevented by calling L{Veto}.
``EVT_TREE_GET_INFO``          Request information from the application (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_ACTIVATED``    The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard.
``EVT_TREE_ITEM_CHECKED``      A checkbox or radiobox type item has been checked.
``EVT_TREE_ITEM_CHECKING``     A checkbox or radiobox type item is being checked.
``EVT_TREE_ITEM_COLLAPSED``    The item has been collapsed.
``EVT_TREE_ITEM_COLLAPSING``   The item is being collapsed. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.
``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling L{Veto}.
``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`).
``EVT_TREE_ITEM_HYPERLINK``    An hyperlink type item has been clicked.
``EVT_TREE_ITEM_MENU``         The context menu for the selected item has been requested, either by a right click or by using the menu key.
``EVT_TREE_ITEM_MIDDLE_CLICK`` The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_ITEM_RIGHT_CLICK``  The user has clicked the item with the right mouse button.
``EVT_TREE_KEY_DOWN``          A key has been pressed.
``EVT_TREE_SEL_CHANGED``       Selection has changed.
``EVT_TREE_SEL_CHANGING``      Selection is changing. This can be prevented by calling L{Veto}.
``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in L{CustomTreeCtrl}).
``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in L{CustomTreeCtrl}).
============================== ==================================================


License And Version
===================

L{CustomTreeCtrl} is distributed under the wxPython license. 

Latest Revision: Andrea Gavana @ 29 Nov 2011, 15.00 GMT

Version 2.5

"""

# Version Info
__version__ = "2.5"

import wx
from wx.lib.expando import ExpandoTextCtrl

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

_NO_IMAGE = -1
_PIXELS_PER_UNIT = 10

# Start editing the current item after half a second (if the mouse hasn't
# been clicked/moved)
_DELAY = 500

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# ----------------------------------------------------------------------------
# Constants
# ----------------------------------------------------------------------------

# Enum for different images associated with a treectrl item
TreeItemIcon_Normal = 0              # not selected, not expanded
""" The tree item is not selected and not expanded. """
TreeItemIcon_Selected = 1            #     selected, not expanded
""" The tree item is selected and not expanded. """
TreeItemIcon_Expanded = 2            # not selected,     expanded
""" The tree item is not selected but expanded. """
TreeItemIcon_SelectedExpanded = 3    #     selected,     expanded
""" The tree item is selected and expanded. """
TreeItemIcon_Checked = 0             # check button,     checked
""" The item's check button is checked. """
TreeItemIcon_NotChecked = 1          # check button, not checked
""" The item's check button is not checked. """
TreeItemIcon_Undetermined = 2        # check button, undetermined
""" The item's check button is in undetermined state (used only for a 3-state check button). """
TreeItemIcon_Flagged = 3             # radio button,     selected
""" The item's radio button is checked. """
TreeItemIcon_NotFlagged = 4          # radio button, not selected
""" The item's radio button is not checked. """

# ----------------------------------------------------------------------------
# CustomTreeCtrl flags
# ----------------------------------------------------------------------------

TR_NO_BUTTONS = wx.TR_NO_BUTTONS                               # for convenience
""" For convenience to document that no buttons are to be drawn. """
TR_HAS_BUTTONS = wx.TR_HAS_BUTTONS                             # draw collapsed/expanded btns
""" Use this style to show + and - buttons to the left of parent items. """
TR_NO_LINES = wx.TR_NO_LINES                                   # don't draw lines at all
""" Use this style to hide vertical level connectors. """
TR_LINES_AT_ROOT = wx.TR_LINES_AT_ROOT                         # connect top-level nodes
""" Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is""" \
""" set and ``TR_NO_LINES`` is not set. """
TR_TWIST_BUTTONS = wx.TR_TWIST_BUTTONS                         # still used by wxTreeListCtrl
""" Use old Mac-twist style buttons. """
TR_SINGLE = wx.TR_SINGLE                                       # for convenience
""" For convenience to document that only one item may be selected at a time. Selecting another""" \
""" item causes the current selection, if any, to be deselected. This is the default. """
TR_MULTIPLE = wx.TR_MULTIPLE                                   # can select multiple items
""" Use this style to allow a range of items to be selected. If a second range is selected,""" \
""" the current range, if any, is deselected. """
TR_EXTENDED = wx.TR_EXTENDED                                   # TODO: allow extended selection
""" Use this style to allow disjoint items to be selected. (Only partially implemented;""" \
""" may not work in all cases). """
TR_HAS_VARIABLE_ROW_HEIGHT = wx.TR_HAS_VARIABLE_ROW_HEIGHT     # what it says
""" Use this style to cause row heights to be just big enough to fit the content.""" \
""" If not set, all rows use the largest row height. The default is that this flag is unset. """
TR_EDIT_LABELS = wx.TR_EDIT_LABELS                             # can edit item labels
""" Use this style if you wish the user to be able to edit labels in the tree control. """
TR_ROW_LINES = wx.TR_ROW_LINES                                 # put border around items
""" Use this style to draw a contrasting border between displayed rows. """
TR_HIDE_ROOT = wx.TR_HIDE_ROOT                                 # don't display root node
""" Use this style to suppress the display of the root node, effectively causing the""" \
""" first-level nodes to appear as a series of root nodes. """
TR_FULL_ROW_HIGHLIGHT = wx.TR_FULL_ROW_HIGHLIGHT               # highlight full horz space
""" Use this style to have the background colour and the selection highlight extend """ \
""" over the entire horizontal row of the tree control window. """

TR_AUTO_CHECK_CHILD = 0x04000                                  # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are checked/unchecked as well. """
TR_AUTO_TOGGLE_CHILD = 0x08000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a parent item is checked/unchecked""" \
""" its children are toggled accordingly. """
TR_AUTO_CHECK_PARENT = 0x10000                                 # only meaningful for checkboxes
""" Only meaningful foe checkbox-type items: when a child item is checked/unchecked""" \
""" its parent item is checked/unchecked as well. """
TR_ALIGN_WINDOWS = 0x20000                                     # to align windows horizontally for items at the same level
""" Flag used to align windows (in items with windows) at the same horizontal position. """
TR_ALIGN_WINDOWS_RIGHT = 0x40000                               # to align windows to the rightmost edge of CustomTreeCtrl
""" Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}."""

TR_DEFAULT_STYLE = wx.TR_DEFAULT_STYLE                         # default style for the tree control
""" The set of flags that are closest to the defaults for the native control for a""" \
""" particular toolkit. """

# Values for the `flags` parameter of CustomTreeCtrl.HitTest() which determine
# where exactly the specified point is situated:

TREE_HITTEST_ABOVE            = wx.TREE_HITTEST_ABOVE
TREE_HITTEST_BELOW            = wx.TREE_HITTEST_BELOW
TREE_HITTEST_NOWHERE          = wx.TREE_HITTEST_NOWHERE
# on the button associated with an item.
TREE_HITTEST_ONITEMBUTTON     = wx.TREE_HITTEST_ONITEMBUTTON
# on the bitmap associated with an item.
TREE_HITTEST_ONITEMICON       = wx.TREE_HITTEST_ONITEMICON
# on the indent associated with an item.
TREE_HITTEST_ONITEMINDENT     = wx.TREE_HITTEST_ONITEMINDENT
# on the label (string) associated with an item.
TREE_HITTEST_ONITEMLABEL      = wx.TREE_HITTEST_ONITEMLABEL
# on the right of the label associated with an item.
TREE_HITTEST_ONITEMRIGHT      = wx.TREE_HITTEST_ONITEMRIGHT
# on the label (string) associated with an item.
TREE_HITTEST_ONITEMSTATEICON  = wx.TREE_HITTEST_ONITEMSTATEICON
# on the left of the CustomTreeCtrl.
TREE_HITTEST_TOLEFT           = wx.TREE_HITTEST_TOLEFT
# on the right of the CustomTreeCtrl.
TREE_HITTEST_TORIGHT          = wx.TREE_HITTEST_TORIGHT
# on the upper part (first half) of the item.
TREE_HITTEST_ONITEMUPPERPART  = wx.TREE_HITTEST_ONITEMUPPERPART
# on the lower part (second half) of the item.
TREE_HITTEST_ONITEMLOWERPART  = wx.TREE_HITTEST_ONITEMLOWERPART
# on the check icon, if present
TREE_HITTEST_ONITEMCHECKICON  = 0x4000
# anywhere on the item
TREE_HITTEST_ONITEM  = TREE_HITTEST_ONITEMICON | TREE_HITTEST_ONITEMLABEL | TREE_HITTEST_ONITEMCHECKICON

TREE_ITEMTYPE_NORMAL = 0
TREE_ITEMTYPE_CHECK = 1
TREE_ITEMTYPE_RADIO = 2

# Background Image Style
_StyleTile = 0
_StyleStretch = 1

# Windows Vista Colours
_rgbSelectOuter = wx.Colour(170, 200, 245)
_rgbSelectInner = wx.Colour(230, 250, 250)
_rgbSelectTop = wx.Colour(210, 240, 250)
_rgbSelectBottom = wx.Colour(185, 215, 250)
_rgbNoFocusTop = wx.Colour(250, 250, 250)
_rgbNoFocusBottom = wx.Colour(235, 235, 235)
_rgbNoFocusOuter = wx.Colour(220, 220, 220)
_rgbNoFocusInner = wx.Colour(245, 245, 245)

# Flags for wx.RendererNative
_CONTROL_EXPANDED = 8
_CONTROL_CURRENT = 16
            

# ----------------------------------------------------------------------------
# CustomTreeCtrl events and binding for handling them
# ----------------------------------------------------------------------------

wxEVT_TREE_BEGIN_DRAG = wx.wxEVT_COMMAND_TREE_BEGIN_DRAG
wxEVT_TREE_BEGIN_RDRAG = wx.wxEVT_COMMAND_TREE_BEGIN_RDRAG
wxEVT_TREE_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT
wxEVT_TREE_END_LABEL_EDIT = wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT
wxEVT_TREE_DELETE_ITEM = wx.wxEVT_COMMAND_TREE_DELETE_ITEM
wxEVT_TREE_GET_INFO = wx.wxEVT_COMMAND_TREE_GET_INFO
wxEVT_TREE_SET_INFO = wx.wxEVT_COMMAND_TREE_SET_INFO
wxEVT_TREE_ITEM_EXPANDED = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDED
wxEVT_TREE_ITEM_EXPANDING = wx.wxEVT_COMMAND_TREE_ITEM_EXPANDING
wxEVT_TREE_ITEM_COLLAPSED = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSED
wxEVT_TREE_ITEM_COLLAPSING = wx.wxEVT_COMMAND_TREE_ITEM_COLLAPSING
wxEVT_TREE_SEL_CHANGED = wx.wxEVT_COMMAND_TREE_SEL_CHANGED
wxEVT_TREE_SEL_CHANGING = wx.wxEVT_COMMAND_TREE_SEL_CHANGING
wxEVT_TREE_KEY_DOWN = wx.wxEVT_COMMAND_TREE_KEY_DOWN
wxEVT_TREE_ITEM_ACTIVATED = wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED
wxEVT_TREE_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK
wxEVT_TREE_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_TREE_ITEM_MIDDLE_CLICK
wxEVT_TREE_END_DRAG = wx.wxEVT_COMMAND_TREE_END_DRAG
wxEVT_TREE_STATE_IMAGE_CLICK = wx.wxEVT_COMMAND_TREE_STATE_IMAGE_CLICK
wxEVT_TREE_ITEM_GETTOOLTIP = wx.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP
wxEVT_TREE_ITEM_MENU = wx.wxEVT_COMMAND_TREE_ITEM_MENU
wxEVT_TREE_ITEM_CHECKING = wx.NewEventType()
wxEVT_TREE_ITEM_CHECKED = wx.NewEventType()
wxEVT_TREE_ITEM_HYPERLINK = wx.NewEventType()

EVT_TREE_BEGIN_DRAG = wx.EVT_TREE_BEGIN_DRAG
""" Begin dragging with the left mouse button. """
EVT_TREE_BEGIN_RDRAG = wx.EVT_TREE_BEGIN_RDRAG
""" Begin dragging with the right mouse button. """
EVT_TREE_BEGIN_LABEL_EDIT = wx.EVT_TREE_BEGIN_LABEL_EDIT
""" Begin editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_END_LABEL_EDIT = wx.EVT_TREE_END_LABEL_EDIT
""" End editing a label. This can be prevented by calling L{Veto}. """
EVT_TREE_DELETE_ITEM = wx.EVT_TREE_DELETE_ITEM
""" Delete an item. """
EVT_TREE_GET_INFO = wx.EVT_TREE_GET_INFO
""" Request information from the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_SET_INFO = wx.EVT_TREE_SET_INFO
""" Information is being supplied to the application (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_EXPANDED = wx.EVT_TREE_ITEM_EXPANDED
""" The item has been expanded. """
EVT_TREE_ITEM_EXPANDING = wx.EVT_TREE_ITEM_EXPANDING
""" The item is being expanded. This can be prevented by calling L{Veto}. """
EVT_TREE_ITEM_COLLAPSED = wx.EVT_TREE_ITEM_COLLAPSED
""" The item has been collapsed. """
EVT_TREE_ITEM_COLLAPSING = wx.EVT_TREE_ITEM_COLLAPSING
""" The item is being collapsed. This can be prevented by calling L{Veto}. """
EVT_TREE_SEL_CHANGED = wx.EVT_TREE_SEL_CHANGED
""" Selection has changed. """
EVT_TREE_SEL_CHANGING = wx.EVT_TREE_SEL_CHANGING
""" Selection is changing. This can be prevented by calling L{Veto}. """
EVT_TREE_KEY_DOWN = wx.EVT_TREE_KEY_DOWN
""" A key has been pressed. """
EVT_TREE_ITEM_ACTIVATED = wx.EVT_TREE_ITEM_ACTIVATED
""" The item has been activated, i.e. chosen by double clicking it with mouse or from keyboard. """
EVT_TREE_ITEM_RIGHT_CLICK = wx.EVT_TREE_ITEM_RIGHT_CLICK
""" The user has clicked the item with the right mouse button. """
EVT_TREE_ITEM_MIDDLE_CLICK = wx.EVT_TREE_ITEM_MIDDLE_CLICK
""" The user has clicked the item with the middle mouse button (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_END_DRAG = wx.EVT_TREE_END_DRAG
""" End dragging with the left or right mouse button. """
EVT_TREE_STATE_IMAGE_CLICK = wx.EVT_TREE_STATE_IMAGE_CLICK
""" The state image has been clicked (not implemented in L{CustomTreeCtrl}). """
EVT_TREE_ITEM_GETTOOLTIP = wx.EVT_TREE_ITEM_GETTOOLTIP
""" The opportunity to set the item tooltip is being given to the application (call `TreeEvent.SetToolTip`). """
EVT_TREE_ITEM_MENU = wx.EVT_TREE_ITEM_MENU
""" The context menu for the selected item has been requested, either by a right click or by using the menu key. """
EVT_TREE_ITEM_CHECKING = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKING, 1)
""" A checkbox or radiobox type item is being checked. """
EVT_TREE_ITEM_CHECKED = wx.PyEventBinder(wxEVT_TREE_ITEM_CHECKED, 1)
""" A checkbox or radiobox type item has been checked. """
EVT_TREE_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_TREE_ITEM_HYPERLINK, 1)
""" An hyperlink type item has been clicked. """


# ----------------------------------------------------------------------------

def MakeDisabledBitmap(original):
    """
    Creates a disabled-looking bitmap starting from the input one.

    :param `original`: an instance of `wx.Bitmap` to be greyed-out.

    :return: An instance of `wx.Bitmap`, containing a disabled-looking
     representation of the original item image.
    """
    
    img = original.ConvertToImage()
    return wx.BitmapFromImage(img.ConvertToGreyscale())

# ----------------------------------------------------------------------------

def DrawTreeItemButton(win, dc, rect, flags):
    """
    Draw the expanded/collapsed icon for a tree control item.

    :param `win`: an instance of `wx.Window`;
    :param `dc`: an instance of `wx.DC`;
    :param `wx.Rect` `rect`: the client rectangle where to draw the tree item button;
    :param integer `flags`: contains ``wx.CONTROL_EXPANDED`` bit for expanded tree items.

    :note: This is a simple replacement of `wx.RendererNative.DrawTreeItemButton`.

    :note: This method is never used in wxPython versions newer than 2.6.2.1.    
    """

    # white background
    dc.SetPen(wx.GREY_PEN)
    dc.SetBrush(wx.WHITE_BRUSH)
    dc.DrawRectangleRect(rect)

    # black lines
    xMiddle = rect.x + rect.width/2
    yMiddle = rect.y + rect.height/2

    # half of the length of the horz lines in "-" and "+"
    halfWidth = rect.width/2 - 2
    dc.SetPen(wx.BLACK_PEN)
    dc.DrawLine(xMiddle - halfWidth, yMiddle,
                xMiddle + halfWidth + 1, yMiddle)

    if not flags & _CONTROL_EXPANDED:
    
        # turn "-" into "+"
        halfHeight = rect.height/2 - 2
        dc.DrawLine(xMiddle, yMiddle - halfHeight,
                    xMiddle, yMiddle + halfHeight + 1)


def EventFlagsToSelType(style, shiftDown=False, ctrlDown=False):
    """
    Translate the key or mouse event flag to the type of selection we
    are dealing with.

    :param integer `style`: the main L{CustomTreeCtrl} window style flag;
    :param bool `shiftDown`: ``True`` if the ``Shift`` key is pressed, ``False`` otherwise;
    :param bool `ctrlDown`: ``True`` if the ``Ctrl`` key is pressed, ``False`` otherwise;

    :return: A 3-elements tuple, with the following elements:
    
     - `is_multiple`: ``True`` if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` flag set, ``False`` otherwise;
     - `extended_select`: ``True`` if the ``Shift`` key is pressend and if L{CustomTreeCtrl} has the
       ``TR_MULTIPLE`` flag set, ``False`` otherwise;
     - `unselect_others`: ``True`` if the ``Ctrl`` key is pressend and if L{CustomTreeCtrl} has the
       ``TR_MULTIPLE`` flag set, ``False`` otherwise.
    """

    is_multiple = (style & TR_MULTIPLE) != 0
    extended_select = shiftDown and is_multiple
    unselect_others = not (extended_select or (ctrlDown and is_multiple))

    return is_multiple, extended_select, unselect_others

    
#---------------------------------------------------------------------------
# DragImage Implementation
# This Class Handles The Creation Of A Custom Image In Case Of Item Drag
# And Drop.
#---------------------------------------------------------------------------

class DragImage(wx.DragImage):
    """
    This class handles the creation of a custom image in case of item drag
    and drop.
    """

    def __init__(self, treeCtrl, item):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `treeCtrl`: the parent L{CustomTreeCtrl};
        :param `item`: one of the tree control item (an instance of L{GenericTreeItem}).
        """
        
        text = item.GetText()
        font = item.Attr().GetFont()
        colour = item.Attr().GetTextColour()
        if not colour:
            colour = wx.BLACK
        if not font:
            font = treeCtrl._normalFont
    
        backcolour = treeCtrl.GetBackgroundColour()
        r, g, b = int(backcolour.Red()), int(backcolour.Green()), int(backcolour.Blue())
        backcolour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._backgroundColour = backcolour

        tempdc = wx.ClientDC(treeCtrl)
        tempdc.SetFont(font)
        width, height, dummy = tempdc.GetMultiLineTextExtent(text + "M")
        
        image = item.GetCurrentImage()

        image_w, image_h = 0, 0
        wcheck, hcheck = 0, 0
        itemcheck = None
        itemimage = None
        ximagepos = 0
        yimagepos = 0
        xcheckpos = 0
        ycheckpos = 0
        
        if image != _NO_IMAGE:    
            if treeCtrl._imageListNormal:
                image_w, image_h = treeCtrl._imageListNormal.GetSize(image)
                image_w += 4
                itemimage = treeCtrl._imageListNormal.GetBitmap(image)
            
        checkimage = item.GetCurrentCheckedImage()

        if checkimage is not None:
            if treeCtrl._imageListCheck:
                wcheck, hcheck = treeCtrl._imageListCheck.GetSize(checkimage)
                wcheck += 4
                itemcheck = treeCtrl._imageListCheck.GetBitmap(checkimage)

        total_h = max(hcheck, height)
        total_h = max(image_h, total_h)
                
        if image_w:
            ximagepos = wcheck
            yimagepos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0]

        if checkimage is not None:
            xcheckpos = 2
            ycheckpos = ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0] + 2

        extraH = ((total_h > height) and [(total_h - height)/2] or [0])[0]
        
        xtextpos = wcheck + image_w
        ytextpos = extraH

        total_h = max(image_h, hcheck)
        total_h = max(total_h, height)
        
        if total_h < 30:
            total_h += 2            # at least 2 pixels
        else:
            total_h += total_h/10   # otherwise 10% extra spacing

        total_w = image_w + wcheck + width

        self._total_w = total_w
        self._total_h = total_h
        self._itemimage = itemimage
        self._itemcheck = itemcheck
        self._text = text
        self._colour = colour
        self._font = font
        self._xtextpos = xtextpos
        self._ytextpos = ytextpos
        self._ximagepos = ximagepos
        self._yimagepos = yimagepos
        self._xcheckpos = xcheckpos
        self._ycheckpos = ycheckpos
        self._textwidth = width
        self._textheight = height
        self._extraH = extraH
        
        self._bitmap = self.CreateBitmap()

        wx.DragImage.__init__(self, self._bitmap)


    def CreateBitmap(self):
        """
        Actually creates the drag and drop bitmap for L{DragImage}.

        :return: An instance of L{DragImage}, a close representation of the item's
         appearance (i.e., a screenshot of the item).
        """

        memory = wx.MemoryDC()

        bitmap = wx.EmptyBitmap(self._total_w, self._total_h)
        memory.SelectObject(bitmap)

        if wx.Platform == '__WXMAC__':
            memory.SetBackground(wx.TRANSPARENT_BRUSH)
        else:
            memory.SetBackground(wx.Brush(self._backgroundColour))
        memory.SetBackgroundMode(wx.TRANSPARENT)
        memory.SetFont(self._font)
        memory.SetTextForeground(self._colour)
        memory.Clear()

        if self._itemimage:
            memory.DrawBitmap(self._itemimage, self._ximagepos, self._yimagepos, True)

        if self._itemcheck:
            memory.DrawBitmap(self._itemcheck, self._xcheckpos, self._ycheckpos, True)

        textrect = wx.Rect(self._xtextpos, self._ytextpos+self._extraH, self._textwidth, self._textheight)
        memory.DrawLabel(self._text, textrect)

        memory.SelectObject(wx.NullBitmap)
        
        # Gtk and Windows unfortunatly don't do so well with transparent
        # drawing so this hack corrects the image to have a transparent
        # background.
        if wx.Platform != '__WXMAC__':
            timg = bitmap.ConvertToImage()
            if not timg.HasAlpha():
                timg.InitAlpha()
            for y in xrange(timg.GetHeight()):
                for x in xrange(timg.GetWidth()):
                    pix = wx.Colour(timg.GetRed(x, y),
                                    timg.GetGreen(x, y),
                                    timg.GetBlue(x, y))
                    if pix == self._backgroundColour:
                        timg.SetAlpha(x, y, 0)
            bitmap = timg.ConvertToBitmap()
        return bitmap        

    
# ----------------------------------------------------------------------------
# TreeItemAttr: a structure containing the visual attributes of an item
# ----------------------------------------------------------------------------

class TreeItemAttr(object):
    """
    Creates the item attributes (text colour, background colour and font).

    :note: This class is inspired by the wxWidgets generic implementation of `wx.TreeItemAttr`.
    """
    
    def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `colText`: the text colour, an instance of `wx.Colour`;
        :param `colBack`: the tree item background colour, an instance of `wx.Colour`;
        :param `font`: the tree item font, an instance of `wx.Font`.
        """
        
        self._colText = colText
        self._colBack = colBack
        self._font = font

    # setters
    def SetTextColour(self, colText):
        """
        Sets the text colour attribute.

        :param `colText`: an instance of `wx.Colour`.
        """
        
        self._colText = colText


    def SetBackgroundColour(self, colBack):
        """
        Sets the item background colour attribute.

        :param `colBack`: an instance of `wx.Colour`.
        """
        
        self._colBack = colBack

        
    def SetFont(self, font):
        """
        Sets the item font attribute.

        :param `font`: an instance of `wx.Font`.
        """
        
        self._font = font

        
    # accessors
    def HasTextColour(self):
        """
        Returns whether the attribute has text colour.

        :return: ``True`` if the text colour attribute has been set, ``False`` otherwise.
        """
        
        return self._colText != wx.NullColour


    def HasBackgroundColour(self):
        """
        Returns whether the attribute has background colour.

        :return: ``True`` if the background colour attribute has been set, ``False`` otherwise.
        """
        
        return self._colBack != wx.NullColour


    def HasFont(self):
        """
        Returns whether the attribute has font.

        :return: ``True`` if the font attribute has been set, ``False`` otherwise.
        """

        return self._font != wx.NullFont


    # getters
    def GetTextColour(self):
        """
        Returns the attribute text colour.

        :return: An instance of `wx.Colour`.
        """
        
        return self._colText

    
    def GetBackgroundColour(self):
        """
        Returns the attribute background colour.

        :return: An instance of `wx.Colour`.
        """

        return self._colBack

    
    def GetFont(self):
        """
        Returns the attribute font.

        :return: An instance of `wx.Font`.
        """

        return self._font


# ----------------------------------------------------------------------------
# CommandTreeEvent Is A Special Subclassing Of wx.PyCommandEvent
#
# NB: Note That Not All The Accessors Make Sense For All The Events, See The
# Event Description Below. 
# ----------------------------------------------------------------------------

class CommandTreeEvent(wx.PyCommandEvent):
    """
    L{CommandTreeEvent} is a special subclassing of `wx.PyCommandEvent`.

    :note: Not all the accessors make sense for all the events, see the event description for every method in this class. 
    """
    
    def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,
                 label=None, **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param integer `evtType`: the event type;
        :param integer `evtId`: the event identifier;
        :param `item`: an instance of L{GenericTreeItem};
        :param integer `evtKey`: a character ordinal;
        :param `point`: an instance of `wx.Point`;
        :param string `label`: a L{GenericTreeItem} text label.
        """

        wx.PyCommandEvent.__init__(self, evtType, evtId, **kwargs)
        self._item = item
        self._evtKey = evtKey
        self._pointDrag = point
        self._label = label
        

    def GetItem(self):
        """
        Gets the item on which the operation was performed or the newly selected
        item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.

        :return: An instance of L{GenericTreeItem}.
        """
        
        return self._item

    
    def SetItem(self, item):
        """
        Sets the item on which the operation was performed or the newly selected
        item for ``EVT_TREE_SEL_CHANGED`` and ``EVT_TREE_SEL_CHANGING`` events.

        :param `item`: an instance of L{GenericTreeItem}.        
        """

        self._item = item


    def GetOldItem(self):
        """
        Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and
        ``EVT_TREE_SEL_CHANGING`` events.

        :return: An instance of L{GenericTreeItem}.
        """

        return self._itemOld
    

    def SetOldItem(self, item):
        """
        Returns the previously selected item for ``EVT_TREE_SEL_CHANGED`` and
        ``EVT_TREE_SEL_CHANGING`` events.

        :param `item`: an instance of L{GenericTreeItem}.        
        """
        
        self._itemOld = item


    def GetPoint(self):
        """
        Returns the point where the mouse was when the drag operation started
        (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)
        or the click position.

        :return: An instance of `wx.Point`.
        """

        return self._pointDrag

    
    def SetPoint(self, pt):
        """
        Sets the point where the mouse was when the drag operation started
        (for ``EVT_TREE_BEGIN_DRAG`` and ``EVT_TREE_BEGIN_RDRAG`` events only)
        or the click position.

        :param `pt`: an instance of `wx.Point`.        
        """
        
        self._pointDrag = pt


    def GetKeyEvent(self):
        """
        Returns the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).

        :return: An instance of `wx.KeyEvent`.
        """
        
        return self._evtKey


    def GetKeyCode(self):
        """
        Returns the virtual key code. ASCII events return normal ASCII values, while
        non-ASCII events return values such as ``wx.WXK_LEFT`` for the left cursor key.

        This method is for ``EVT_TREE_KEY_DOWN`` events only.
        
        :return: An integer representing the virtual key code.

        :note: In Unicode build, the returned value is meaningful only if the user entered
         a character that can be represented in current locale's default charset. You can
         obtain the corresponding Unicode character using `GetUnicodeKey`.        
        """

        return self._evtKey.GetKeyCode()

    
    def SetKeyEvent(self, event):
        """
        Sets the keyboard data (for ``EVT_TREE_KEY_DOWN`` event only).

        :param `event`: a L{TreeEvent} event to be processed.
        """

        self._evtKey = event
        

    def GetLabel(self):
        """
        Returns the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :return: A string containing the item text.
        """

        return self._label

    
    def SetLabel(self, label):
        """
        Sets the item text (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :param string `label`: a string containing the new item text.        
        """

        self._label = label


    def IsEditCancelled(self):
        """
        Returns the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :return: ``True`` is the item editing has been cancelled, ``False`` otherwise.
        """

        return self._editCancelled


    def SetEditCanceled(self, editCancelled):
        """
        Sets the edit cancel flag (for ``EVT_TREE_BEGIN_LABEL_EDIT`` and
        ``EVT_TREE_END_LABEL_EDIT`` events only).

        :param bool `editCancelled`: ``True`` to cancel the editing, ``False`` otherwise.        
        """

        self._editCancelled = editCancelled


    def SetToolTip(self, toolTip):
        """
        Sets the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).

        :param string `tooltip`: a string representing the item tooltip.
        """

        self._label = toolTip

        
    def GetToolTip(self):
        """
        Returns the tooltip for the item (for ``EVT_TREE_ITEM_GETTOOLTIP`` events).

        :return: A string containing the item tooltip.
        """

        return self._label
    

# ----------------------------------------------------------------------------
# TreeEvent is a special class for all events associated with tree controls
#
# NB: note that not all accessors make sense for all events, see the event
#     descriptions below
# ----------------------------------------------------------------------------

class TreeEvent(CommandTreeEvent):
    """
    L{TreeEvent} is a special class for all events associated with tree controls.
    
    :note: Not all accessors make sense for all events, see the event descriptions below.
    """
    def __init__(self, evtType, evtId, item=None, evtKey=None, point=None,
                 label=None, **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param integer `evtType`: the event type;
        :param integer `evtId`: the event identifier;
        :param `item`: an instance of L{GenericTreeItem};
        :param integer `evtKey`: a character ordinal;
        :param `point`: an instance of `wx.Point`;
        :param string `label`: a L{GenericTreeItem} text label.
        """

        CommandTreeEvent.__init__(self, evtType, evtId, item, evtKey, point, label, **kwargs)
        self.notify = wx.NotifyEvent(evtType, evtId)


    def GetNotifyEvent(self):
        """
        Returns the actual `wx.NotifyEvent`.

        :return: An instance of `wx.NotifyEvent`.
        """
        
        return self.notify


    def IsAllowed(self):
        """
        Returns ``True`` if the change is allowed (L{Veto} hasn't been called) or
        ``False`` otherwise (if it was).
        """

        return self.notify.IsAllowed()


    def Veto(self):
        """
        Prevents the change announced by this event from happening.

        :note: It is in general a good idea to notify the user about the reasons
         for vetoing the change because otherwise the applications behaviour (which
         just refuses to do what the user wants) might be quite surprising.
        """

        self.notify.Veto()


    def Allow(self):
        """
        This is the opposite of L{Veto}: it explicitly allows the event to be processed.
        For most events it is not necessary to call this method as the events are
        allowed anyhow but some are forbidden by default (this will be mentioned
        in the corresponding event description).
        """

        self.notify.Allow()
        
    
# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeEditTimer
# -----------------------------------------------------------------------------

class TreeEditTimer(wx.Timer):
    """ Timer used for enabling in-place edit."""

    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).
        """
        
        wx.Timer.__init__(self)
        self._owner = owner        


    def Notify(self):
        """ The timer has expired, starts the item editing. """

        self._owner.OnEditTimer()


# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeTextCtrl
# This Is The Temporary ExpandoTextCtrl Created When You Edit The Text Of An Item
# -----------------------------------------------------------------------------

class TreeTextCtrl(ExpandoTextCtrl):
    """
    Control used for in-place edit.

    This is a subclass of `wx.lib.expando.ExpandoTextCtrl` as L{CustomTreeCtrl} supports multiline
    text items.

    :note: To add a newline character in a multiline item, press ``Shift`` + ``Enter`` as the ``Enter``
     key alone is consumed by L{CustomTreeCtrl} to finish the editing and ``Ctrl`` + ``Enter`` is
     consumed by the platform for tab navigation.
    """

    def __init__(self, owner, item=None):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the control parent (an instance of L{CustomTreeCtrl});
        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` when the item has an associated image but the parent
         L{CustomTreeCtrl} does not have a `wx.ImageList` assigned.
        """
        
        self._owner = owner
        self._itemEdited = item
        self._startValue = item.GetText()
        self._finished = False
        self._aboutToFinish = False
        self._currentValue = self._startValue

        w = self._itemEdited.GetWidth()
        h = self._itemEdited.GetHeight()

        wnd = self._itemEdited.GetWindow()
        if wnd:
            w = w - self._itemEdited.GetWindowSize()[0]
            h = 0

        x, y = self._owner.CalcScrolledPosition(item.GetX(), item.GetY())

        image_h = 0
        image_w = 0

        image = item.GetCurrentImage()

        if image != _NO_IMAGE:
    
            if self._owner._imageListNormal:
                image_w, image_h = self._owner._imageListNormal.GetSize(image)
                image_w += 4
        
            else:
        
                raise Exception("\n ERROR: You Must Create An Image List To Use Images!")

        checkimage = item.GetCurrentCheckedImage()

        if checkimage is not None:
            wcheck, hcheck = self._owner._imageListCheck.GetSize(checkimage)
            wcheck += 4
        else:
            wcheck = hcheck = 0

        if wnd:
            h = max(hcheck, image_h)
            dc = wx.ClientDC(self._owner)
            h = max(h, dc.GetTextExtent("Aq")[1])
            h = h + 2
            
        # FIXME: what are all these hardcoded 4, 8 and 11s really?
        x += image_w + wcheck
        w -= image_w + 4 + wcheck

        expandoStyle = wx.WANTS_CHARS
        if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
            expandoStyle |= wx.SIMPLE_BORDER
            xSize, ySize = w + 25, h
        else:
            expandoStyle |= wx.SUNKEN_BORDER
            xSize, ySize = w + 25, h+2
            
        ExpandoTextCtrl.__init__(self, self._owner, wx.ID_ANY, self._startValue,
                                 wx.Point(x - 4, y), wx.Size(xSize, ySize),
                                 expandoStyle)

        if wx.Platform == "__WXMAC__":
            self.SetFont(owner.GetFont())
            bs = self.GetBestSize()
            self.SetSize((-1, bs.height))
        
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
    

    def AcceptChanges(self):
        """
        Accepts/rejects the changes made by the user.

        :return: ``True`` if the changes to the item text have been accepted, ``False``
         if they have been rejected (i.e., vetoed by the user).
        """

        value = self.GetValue()

        if value == self._startValue:
            # nothing changed, always accept
            # when an item remains unchanged, the owner
            # needs to be notified that the user decided
            # not to change the tree item label, and that
            # the edit has been cancelled
            self._owner.OnCancelEdit(self._itemEdited)
            return True

        if not self._owner.OnAcceptEdit(self._itemEdited, value):
            # vetoed by the user
            return False

        # accepted, do rename the item
        self._owner.SetItemText(self._itemEdited, value)
        
        return True


    def Finish(self):
        """ Finish editing. """

        if not self._finished:        
            self._finished = True
            self._owner.SetFocusIgnoringChildren()
            self._owner.ResetEditControl()
        

    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for L{TreeTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        keycode = event.GetKeyCode()
        shiftDown = event.ShiftDown()

        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER]:
            if shiftDown:
                event.Skip()
            else:
                self._aboutToFinish = True
                self.SetValue(self._currentValue)
                # Notify the owner about the changes
                self.AcceptChanges()
                # Even if vetoed, close the control (consistent with MSW)
                wx.CallAfter(self.Finish)

        elif keycode == wx.WXK_ESCAPE:
            self.StopEditing()

        else:
            event.Skip()
    

    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for L{TreeTextCtrl}.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        if not self._finished:

            # auto-grow the textctrl:
            parentSize = self._owner.GetSize()
            myPos = self.GetPosition()
            mySize = self.GetSize()

            dc = wx.ClientDC(self)
            sx, sy, dummy = dc.GetMultiLineTextExtent(self.GetValue() + "M")

            if myPos.x + sx > parentSize.x:
                sx = parentSize.x - myPos.x
            if mySize.x > sx:
                sx = mySize.x
                
            self.SetSize((sx, -1))
            self._currentValue = self.GetValue()

        event.Skip()


    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{TreeTextCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """
        
        if not self._finished and not self._aboutToFinish:
        
            # We must finish regardless of success, otherwise we'll get
            # focus problems:
            
            if not self.AcceptChanges():
                self._owner.OnCancelEdit(self._itemEdited)
        
        # We must let the native text control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()


    def StopEditing(self):
        """ Suddenly stops the editing. """

        self._owner.OnCancelEdit(self._itemEdited)
        self.Finish()
        
    
    def item(self):
        """
        Returns the item currently edited.

        :return: An instance of L{GenericTreeItem}.
        """

        return self._itemEdited 


# -----------------------------------------------------------------------------
# Auxiliary Classes: TreeFindTimer
# Timer Used To Clear CustomTreeCtrl._findPrefix If No Key Was Pressed For A
# Sufficiently Long Time.
# -----------------------------------------------------------------------------

class TreeFindTimer(wx.Timer):
    """
    Timer used to clear the L{CustomTreeCtrl} `_findPrefix` attribute if no
    key was pressed for a sufficiently long time.
    """

    def __init__(self, owner):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `owner`: the `wx.Timer` owner (an instance of L{CustomTreeCtrl}).        
        """

        wx.Timer.__init__(self)
        self._owner = owner


    def Notify(self):
        """ The timer has expired, clear the `_findPrefix` attribute in L{CustomTreeCtrl}. """

        self._owner._findPrefix = ""


# -----------------------------------------------------------------------------
# GenericTreeItem Implementation.
# This Class Holds All The Information And Methods For Every Single Item In
# CustomTreeCtrl.
# -----------------------------------------------------------------------------

class GenericTreeItem(object):
    """
    This class holds all the information and methods for every single item in
    L{CustomTreeCtrl}. This is a generic implementation of `wx.TreeItem`.
    """
    
    def __init__(self, parent, text="", ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `parent`: the tree item parent, an instance of L{GenericTreeItem} (may
         be ``None`` for root items);
        :param string `text`: the tree item text;
        :param integer `ct_type`: the tree item kind. May be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item, an instance of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise. 

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:
         
         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.


        :note: Separator items should not have children, labels, data or an associated window.
         Other issues/features associated to separator items:
         
         - You can change the color of individual separators by using L{CustomTreeCtrl.SetItemTextColour},
           or you can use L{CustomTreeCtrl.SetSeparatorColour} to change the color of all
           separators. The default separator colour is that returned by `wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT)`;
         - Separators can be selected just like any other tree item;
         - Separators cannot have text;
         - Separators cannot have children;
         - Separators cannot be edited via the ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

        """
        
        # since there can be very many of these, we save size by chosing
        # the smallest representation for the elements and by ordering
        # the members to avoid padding.
        self._text = text       # label to be rendered for item
        self._data = data       # user-provided data

        self._children  = []    # list of children
        self._parent = parent   # parent of this item

        self._attr = None       # attributes???

        self._separator = separator        

        # tree ctrl images for the normal, selected, expanded and
        # expanded+selected states
        self._images = [-1, -1, -1, -1]
        self._images[TreeItemIcon_Normal] = image
        self._images[TreeItemIcon_Selected] = selImage
        self._images[TreeItemIcon_Expanded] = _NO_IMAGE
        self._images[TreeItemIcon_SelectedExpanded] = _NO_IMAGE

        self._checkedimages = [None, None, None, None, None]
        self._leftimage = _NO_IMAGE

        self._x = 0             # (virtual) offset from top
        self._y = 0             # (virtual) offset from left
        self._width = 0         # width of this item
        self._height = 0        # height of this item

        self._isCollapsed = True
        self._hasHilight = False    # same as focused
        self._hasPlus = False       # used for item which doesn't have
                                    # children but has a [+] button
        self._isBold = False        # render the label in bold font
        self._isItalic = False      # render the label in italic font
        self._ownsAttr = False      # delete attribute when done
        self._type = ct_type        # item type: 0=normal, 1=check, 2=radio
        self._is3State = False      # true for 3-state checkbox items
        self._checked = 0           # only meaningful for check and radio items
        self._enabled = True        # flag to enable/disable an item
        self._hypertext = False     # indicates if the item is hypertext
        self._visited = False       # visited state for an hypertext item

        if self._type > 0:
            # do not construct the array for normal items
            self._checkedimages[TreeItemIcon_Checked] = 0
            self._checkedimages[TreeItemIcon_NotChecked] = 1
            self._checkedimages[TreeItemIcon_Undetermined] = 2
            self._checkedimages[TreeItemIcon_Flagged] = 3
            self._checkedimages[TreeItemIcon_NotFlagged] = 4
        
        if parent:
            if parent.GetType() == 2 and not parent.IsChecked():
                # if the node parent is a radio not enabled, we are disabled
                self._enabled = False

        self._wnd = wnd             # are we holding a window?

        if wnd:
            self.SetWindow(wnd)
        

    def IsOk(self):
        """
        Returns whether the item is ok or not.

        :note: This method always returns ``True``, it has been added for
         backward compatibility with the wxWidgets C++ implementation.
        """
        
        return True
    

    def IsSeparator(self):
        """
        Returns whether the item is meant to be an horizontal line separator or not.

        :return: ``True`` if this item is a separator, ``False`` otherwise.
        """

        return self._separator
    

    def GetChildren(self):
        """
        Returns the item's children.

        :return: A Python list containing instances of L{GenericTreeItem}, representing
         this item's children.
        """

        return self._children 


    def GetText(self):
        """
        Returns the item text.

        :return: A string containing the item text.
        """

        return self._text 


    def GetImage(self, which=TreeItemIcon_Normal):
        """
        Returns the item image for a particular item state.

        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected) 
         ================================= ========================

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.
        """
        
        return self._images[which] 


    def GetCheckedImage(self, which=TreeItemIcon_Checked):
        """
        Returns the item check image.

        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Checked``          To get the checkbox checked item image
         ``TreeItemIcon_NotChecked``       To get the checkbox unchecked item image
         ``TreeItemIcon_Undetermined``     To get the checkbox undetermined state item image
         ``TreeItemIcon_Flagged``          To get the radiobutton checked image
         ``TreeItemIcon_NotFlagged``       To get the radiobutton unchecked image
         ================================= ========================

        :return: An integer index that can be used to retrieve the item check image inside
         a `wx.ImageList`.

        :note: This method is meaningful only for radio & check items.
        """

        return self._checkedimages[which]


    def GetLeftImage(self):
        """
        Returns the leftmost image associated to this item, i.e. the image on the
        leftmost part of the client area of L{CustomTreeCtrl}.

        :return: An integer index that can be used to retrieve the item leftmost image inside
         a `wx.ImageList`.
        """

        return self._leftimage
    

    def GetData(self):
        """
        Returns the data associated to this item.

        :return: A Python object representing the item data, or ``None`` if no data
         has been assigned to this item.
        """
        
        return self._data 


    def SetImage(self, image, which):
        """
        Sets the item image.

        :param integer `image`: an index within the normal image list specifying the image to use;
        :param integer `which`: the image kind.
        
        :see: L{GetImage} for a description of the `which` parameter.
        """

        self._images[which] = image


    def SetLeftImage(self, image):
        """
        Sets the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param integer `image`: an index within the left image list specifying the image to
         use for the item in the leftmost part of the client area.
        """

        self._leftimage = image

        
    def SetData(self, data):
        """
        Sets the data associated to this item.

        :param object `data`: can be any Python object.
        """

        self._data = data 


    def SetHasPlus(self, has=True):
        """
        Sets whether an item has the 'plus' button.

        :param bool `has`: ``True`` to set the 'plus' button on the item, ``False`` otherwise.
        """

        self._hasPlus = has 


    def SetBold(self, bold):
        """
        Sets the item font bold.

        :parameter bool `bold`: ``True`` to have a bold font item, ``False`` otherwise.
        """

        self._isBold = bold 


    def SetItalic(self, italic):
        """
        Sets the item font italic.

        :parameter bool `italic`: ``True`` to have an italic font item, ``False`` otherwise.
        """

        self._isItalic = italic
        

    def GetX(self):
        """ Returns the `x` position on an item, in logical coordinates. """

        return self._x 


    def GetY(self):
        """ Returns the `y` position on an item, in logical coordinates. """

        return self._y 


    def SetX(self, x):
        """
        Sets the `x` position on an item, in logical coordinates.

        :param integer `x`: an integer specifying the x position of the item.
        """

        self._x = x 


    def SetY(self, y):
        """
        Sets the `y` position on an item, in logical coordinates.

        :param integer `y`: an integer specifying the y position of the item.
        """

        self._y = y 


    def GetHeight(self):
        """ Returns the height of the item, in pixels. """

        return self._height 


    def GetWidth(self):
        """ Returns the width of the item, in pixels. """

        return self._width 


    def SetHeight(self, h):
        """
        Sets the item's height.

        :param integer `h`: an integer specifying the item's height, in pixels.
        """

        self._height = h

        
    def SetWidth(self, w):
        """
        Sets the item's width.

        :param integer `w`: an integer specifying the item's width, in pixels.
        """

        self._width = w 


    def SetWindow(self, wnd):
        """
        Sets the window associated to the item.

        :param `wnd`: a non-toplevel window to be displayed next to the item, any
         subclass of `wx.Window`.

        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
        """

        if self.IsSeparator() and wnd is not None:
            raise Exception("Separator items can not have an associated window")

        self._wnd = wnd

        if wnd.GetSizer():      # the window is a complex one hold by a sizer
            size = wnd.GetBestSize()
        else:                   # simple window, without sizers
            size = wnd.GetSize()

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # CustomTreeCtrl and the window associated to an item
        # Do better strategies exist?
        self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        
        self._height = size.GetHeight() + 2
        self._width = size.GetWidth()
        self._windowsize = size
        
        # We don't show the window if the item is collapsed
        if self._isCollapsed:
            self._wnd.Show(False)

        # The window is enabled only if the item is enabled                
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled


    def GetWindow(self):
        """
        Returns the window associated to the item (if any).

        :return: An instance of any `wx.Window` derived class, excluding top-level windows.
        """

        return self._wnd        


    def DeleteWindow(self):
        """ Deletes the window associated to the item (if any). """

        if self._wnd:
            self._wnd.Destroy()
            self._wnd = None
        

    def GetWindowEnabled(self):
        """
        Returns whether the associated window is enabled or not.

        :return: ``True`` if the associated window is enabled, ``False`` if it is disabled.

        :raise: `Exception` when the item has no associated window.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        return self._windowenabled


    def SetWindowEnabled(self, enable=True):
        """
        Sets whether the associated window is enabled or not.

        :param bool `enable`: ``True`` to enable the associated window, ``False`` to disable it.

        :raise: `Exception` when the item has no associated window.
        """

        if not self._wnd:
            raise Exception("\nERROR: This Item Has No Window Associated")

        self._windowenabled = enable
        self._wnd.Enable(enable)


    def GetWindowSize(self):
        """ Returns the associated window size. """
        
        return self._windowsize        


    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for the window associated with the item.

        :param `event`: a `wx.FocusEvent` event to be processed.        
        """

        treectrl = self._wnd.GetParent()
        select = treectrl.GetSelection()

        # If the window is associated to an item that currently is selected
        # (has focus) we don't kill the focus. Otherwise we do it.
        if select != self:
            treectrl._hasFocus = False
        else:
            treectrl._hasFocus = True
            
        event.Skip()


    def GetType(self):
        """
        Returns the item type.

        :see: L{SetType} and L{__init__} for a description of valid item types.        
        """

        return self._type
    

    def SetType(self, ct_type):
        """
        Sets the item type.

        :param integer `ct_type`: may be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:
         
         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.
        """

        self._type = ct_type


    def SetHyperText(self, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param bool `hyper`: ``True`` to set hypertext behaviour, ``False`` otherwise.
        """
        
        self._hypertext = hyper


    def SetVisited(self, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param bool `visited`: ``True`` to set a hypertext item as visited, ``False`` otherwise.
        """

        self._visited = visited


    def GetVisited(self):
        """ Returns whether an hypertext item was visited or not. """

        return self._visited        


    def IsHyperText(self):
        """ Returns whether the item is hypetext or not. """

        return self._hypertext
    

    def GetParent(self):
        """
        Gets the item parent (another instance of L{GenericTreeItem} or ``None`` for
        root items.

        :return: An instance of L{GenericTreeItem} or ``None`` for root items.        
        """

        return self._parent 


    def Insert(self, child, index):
        """
        Inserts an item in the item children list for this item.

        :param `child`: an instance of L{GenericTreeItem};
        :param integer `index`: the index at which we should insert the new child.
        """
        
        self._children.insert(index, child) 


    def Expand(self):
        """ Expands the item. """

        self._isCollapsed = False 
        

    def Collapse(self):
        """ Collapses the item. """

        self._isCollapsed = True
            

    def SetHilight(self, set=True):
        """
        Sets the item focus/unfocus.

        :param bool `set`: ``True`` to set the focus to the item, ``False`` otherwise.    
        """

        self._hasHilight = set 


    def HasChildren(self):
        """
        Returns whether the item has children or not.

        :return: ``True`` if the item has children, ``False`` otherwise.
        """

        return len(self._children) > 0


    def IsSelected(self):
        """
        Returns whether the item is selected or not.

        :return: ``True`` if the item is selected, ``False`` otherwise.
        """

        return self._hasHilight != 0 


    def IsExpanded(self):
        """
        Returns whether the item is expanded or not.

        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
        """

        return not self._isCollapsed 


    def GetValue(self):
        """
        Returns whether the item is checked or not.

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """

        if self.Is3State():
            return self.Get3StateValue()
        
        return self._checked        


    def Get3StateValue(self):
        """
        Gets the state of a 3-state checkbox item.

        :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``
         when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined
         state. 

        :raise: `Exception` when the item is not a 3-state checkbox item.

        :note: This method raises an exception when the function is used with a 2-state
         checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        if not self.Is3State():
            raise Exception("Get3StateValue can only be used with 3-state checkbox items.")

        return self._checked        


    def Is3State(self):
        """
        Returns whether or not the checkbox item is a 3-state checkbox.

        :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a
         2-state checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return self._is3State
    

    def Set3StateValue(self, state):
        """
        Sets the checkbox item to the given `state`.

        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
         (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

        :raise: `Exception` when the item is not a 3-state checkbox item.

        :note: This method raises an exception when the checkbox item is a 2-state checkbox
         and setting the state to ``wx.CHK_UNDETERMINED``.

        :note: This method is meaningful only for checkbox-like items.
        """

        if not self._is3State and state == wx.CHK_UNDETERMINED:
            raise Exception("Set3StateValue can only be used with 3-state checkbox items.")

        self._checked = state


    def Set3State(self, allow):
        """
        Sets whether the item has a 3-state value checkbox assigned to it or not.

        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
         to a 2-state checkbox.

        :return: ``True`` if the change was successful, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like items.
        """

        if self._type != 1:
            return False

        self._is3State = allow
        return True
            

    def IsChecked(self):
        """
        This is just a maybe more readable synonym for L{GetValue}.
        Returns whether the item is checked or not.

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """

        return self.GetValue()


    def Check(self, checked=True):
        """
        Checks/unchecks an item.

        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.        

        :note: This is meaningful only for checkbox-like and radiobutton-like items.
        """
        
        self._checked = checked        


    def HasPlus(self):
        """
        Returns whether the item has the plus button or not.

        :return: ``True`` if the item has a 'plus' mark, ``False`` otherwise.
        """

        return self._hasPlus or self.HasChildren() 


    def IsBold(self):
        """
        Returns whether the item font is bold or not.

        :return: ``True`` if the item has bold text, ``False`` otherwise.
        """

        return self._isBold != 0 


    def IsItalic(self):
        """
        Returns whether the item font is italic or not.

        :return: ``True`` if the item has italic text, ``False`` otherwise.
        """

        return self._isItalic != 0 


    def Enable(self, enable=True):
        """
        Enables/disables the item.

        :param bool `enable`: ``True`` to enable the item, ``False`` to disable it.
        """

        self._enabled = enable


    def IsEnabled(self):
        """
        Returns whether the item is enabled or not.

        :return: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        return self._enabled
    

    def GetAttributes(self):
        """
        Returns the item attributes (font, colours, etc...).

        :return: An instance of L{TreeItemAttr}.
        """

        return self._attr 


    def Attr(self):
        """
        Creates a new attribute (font, colours, etc...) for this item.

        :return: An instance of L{TreeItemAttr}.
        """
    
        if not self._attr:
        
            self._attr = TreeItemAttr()
            self._ownsAttr = True
        
        return self._attr

    
    def SetAttributes(self, attr):
        """
        Sets the item attributes (font, colours, etc...).

        :param `attr`: an instance of L{TreeItemAttr}.
        """
    
        if self._ownsAttr:
             del self._attr
             
        self._attr = attr
        self._ownsAttr = False

    
    def AssignAttributes(self, attr):
        """
        Assigns the item attributes (font, colours, etc...) for this item.

        :param `attr`: an instance of L{TreeItemAttr}.
        """
    
        self.SetAttributes(attr)
        self._ownsAttr = True


    def DeleteChildren(self, tree):
        """
        Deletes the item children.

        :param `tree`: the main L{CustomTreeCtrl} instance.
        """

        for child in self._children:
            if tree:
                tree.SendDeleteEvent(child)

            child.DeleteChildren(tree)
            
            if child == tree._select_me:
                tree._select_me = None

            # We have to destroy the associated window
            wnd = child.GetWindow()
            if wnd:
                wnd.Destroy()
                child._wnd = None

            if child in tree._itemWithWindow:
                tree._itemWithWindow.remove(child)
                
            del child
        
        self._children = []


    def SetText(self, text):
        """
        Sets the item text.

        :param string `text`: the new item label.

        :raise: `Exception` if the item is a separator.        
        """

        if self.IsSeparator():
            raise Exception("Separator items can not have text")

        self._text = text


    def GetChildrenCount(self, recursively=True):
        """
        Gets the number of children of this item.

        :param bool `recursively`: if ``True``, returns the total number of descendants,
         otherwise only one level of children is counted.
        """

        count = len(self._children)
        
        if not recursively:
            return count

        total = count

        for n in xrange(count):
            total += self._children[n].GetChildrenCount()
        
        return total


    def GetSize(self, x, y, theButton):
        """
        Returns the item size.

        :param integer `x`: the current item's x position;
        :param integer `y`: the current item's y position;
        :param `theButton`: an instance of the main L{CustomTreeCtrl}.

        :return: A tuple of (`x`, `y`) dimensions, in pixels, representing the
         item's width and height.
        """

        bottomY = self._y + theButton.GetLineHeight(self)

        if y < bottomY:
            y = bottomY

        width = self._x + self._width
        
        if x < width:
            x = width

        if self.IsExpanded():
            for child in self._children:
                x, y = child.GetSize(x, y, theButton)
            
        return x, y        


    def HitTest(self, point, theCtrl, flags=0, level=0):
        """
        L{HitTest} method for an item. Called from the main window L{CustomTreeCtrl.HitTest}.

        :param `point`: the point to test for the hit (an instance of `wx.Point`);
        :param `theCtrl`: the main L{CustomTreeCtrl} tree;
        :param integer `flags`: a bitlist of hit locations;
        :param integer `level`: the item's level inside the tree hierarchy.
        
        :see: L{CustomTreeCtrl.HitTest} method for the flags explanation.
        """
        
        # for a hidden root node, don't evaluate it, but do evaluate children
        if not (level == 0 and theCtrl.HasAGWFlag(TR_HIDE_ROOT)):
        
            # evaluate the item
            h = theCtrl.GetLineHeight(self)
            
            if point.y > self._y and point.y < self._y + h:
            
                y_mid = self._y + h/2

                if point.y < y_mid:
                    flags |= TREE_HITTEST_ONITEMUPPERPART
                else:
                    flags |= TREE_HITTEST_ONITEMLOWERPART

                xCross = self._x - theCtrl.GetSpacing()

                if wx.Platform == "__WXMAC__":
                    # according to the drawing code the triangels are drawn
                    # at -4 , -4  from the position up to +10/+10 max
                    if point.x > xCross-4 and point.x < xCross+10 and point.y > y_mid-4 and \
                       point.y < y_mid+10 and self.HasPlus() and theCtrl.HasButtons():

                        flags |= TREE_HITTEST_ONITEMBUTTON
                        return self, flags
                else:
                    # 5 is the size of the plus sign
                    if point.x > xCross-6 and point.x < xCross+6 and point.y > y_mid-6 and \
                       point.y < y_mid+6 and self.HasPlus() and theCtrl.HasButtons():

                        flags |= TREE_HITTEST_ONITEMBUTTON
                        return self, flags

                if point.x >= self._x and point.x <= self._x + self._width:

                    image_w = -1
                    wcheck = 0

                    # assuming every image (normal and selected) has the same size!
                    if self.GetImage() != _NO_IMAGE and theCtrl._imageListNormal:
                        image_w, image_h = theCtrl._imageListNormal.GetSize(self.GetImage())

                    if self.GetCheckedImage() is not None:
                        wcheck, hcheck = theCtrl._imageListCheck.GetSize(self.GetCheckedImage())

                    if wcheck and point.x <= self._x + wcheck + 1:
                        flags |= TREE_HITTEST_ONITEMCHECKICON
                        return self, flags

                    if image_w != -1 and point.x <= self._x + wcheck + image_w + 1:
                        flags |= TREE_HITTEST_ONITEMICON
                    else:
                        flags |= TREE_HITTEST_ONITEMLABEL

                    return self, flags

                if point.x < self._x:
                    if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                        flags |= TREE_HITTEST_ONITEM
                    else:
                        flags |= TREE_HITTEST_ONITEMINDENT
                if point.x > self._x + self._width:
                    if theCtrl.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                        flags |= TREE_HITTEST_ONITEM
                    else:
                        flags |= TREE_HITTEST_ONITEMRIGHT
                        
                return self, flags
            
            # if children are expanded, fall through to evaluate them
            if self._isCollapsed:
                return None, 0
        
        # evaluate children
        for child in self._children:
            res, flags = child.HitTest(point, theCtrl, flags, level + 1)
            if res != None:
                return res, flags

        return None, 0


    def GetCurrentImage(self):
        """
        Returns the current item image.

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.
        """

        image = _NO_IMAGE
        
        if self.IsExpanded():
        
            if self.IsSelected():
            
                image = self._images[TreeItemIcon_SelectedExpanded]

            if image == _NO_IMAGE:
            
                # we usually fall back to the normal item, but try just the
                # expanded one (and not selected) first in this case
                image = self._images[TreeItemIcon_Expanded]
        
        else: # not expanded
        
            if self.IsSelected():
                image = self._images[TreeItemIcon_Selected]
        
        # maybe it doesn't have the specific image we want,
        # try the default one instead
        if image == _NO_IMAGE:
            image = self._images[TreeItemIcon_Normal]

        return image


    def GetCurrentCheckedImage(self):
        """
        Returns the current item check image.

        :return: An integer index that can be used to retrieve the item check image inside
         a `wx.ImageList`.
        """

        if self._type == 0:
            return None

        checked = self.IsChecked()
        
        if checked > 0:
            if self._type == 1:     # Checkbox
                if checked == wx.CHK_CHECKED:
                    return self._checkedimages[TreeItemIcon_Checked]
                else:
                    return self._checkedimages[TreeItemIcon_Undetermined]                    
            else:                   # Radiobutton
                return self._checkedimages[TreeItemIcon_Flagged]
        else:
            if self._type == 1:     # Checkbox
                return self._checkedimages[TreeItemIcon_NotChecked]
            else:                   # Radiobutton
                return self._checkedimages[TreeItemIcon_NotFlagged]
            

# -----------------------------------------------------------------------------
# CustomTreeCtrl Main Implementation.
# This Is The Main Class.
# -----------------------------------------------------------------------------

class CustomTreeCtrl(wx.PyScrolledWindow):
    """
    L{CustomTreeCtrl} is a class that mimics the behaviour of `wx.TreeCtrl`, with almost the
    same base functionalities plus some more enhancements. This class does not rely on
    the native control, as it is a full owner-drawn tree control.
    """

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="CustomTreeCtrl"):
        """
        Default class constructor.
        
        :param `wx.Window` `parent`: parent window. Must not be ``None``;
        :param integer `id`: window identifier. A value of -1 indicates a default value;
        :param `pos`: the control position. A value of (-1, -1) indicates a default position,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `pos`: tuple or `wx.Point`
        :param `size`: the control size. A value of (-1, -1) indicates a default size,
         chosen by either the windowing system or wxPython, depending on platform;
        :type `size`: tuple or `wx.Size`
        :param integer `style`: the underlying `wx.PyScrolledWindow` style;
        :param integer `agwStyle`: the AGW-specific window style for L{CustomTreeCtrl}. It can be a
         combination of the following bits:
        
         ============================== =========== ==================================================
         Window Styles                  Hex Value   Description
         ============================== =========== ==================================================
         ``TR_NO_BUTTONS``                      0x0 For convenience to document that no buttons are to be drawn.
         ``TR_SINGLE``                          0x0 For convenience to document that only one item may be selected at a time. Selecting another item causes the current selection, if any, to be deselected. This is the default.
         ``TR_HAS_BUTTONS``                     0x1 Use this style to show + and - buttons to the left of parent items.
         ``TR_NO_LINES``                        0x4 Use this style to hide vertical level connectors.
         ``TR_LINES_AT_ROOT``                   0x8 Use this style to show lines between root nodes. Only applicable if ``TR_HIDE_ROOT`` is set and ``TR_NO_LINES`` is not set.
         ``TR_DEFAULT_STYLE``                   0x9 The set of flags that are closest to the defaults for the native control for a particular toolkit.
         ``TR_TWIST_BUTTONS``                  0x10 Use old Mac-twist style buttons.
         ``TR_MULTIPLE``                       0x20 Use this style to allow a range of items to be selected. If a second range is selected, the current range, if any, is deselected.
         ``TR_EXTENDED``                       0x40 Use this style to allow disjoint items to be selected. (Only partially implemented; may not work in all cases).
         ``TR_HAS_VARIABLE_ROW_HEIGHT``        0x80 Use this style to cause row heights to be just big enough to fit the content. If not set, all rows use the largest row height. The default is that this flag is unset.
         ``TR_EDIT_LABELS``                   0x200 Use this style if you wish the user to be able to edit labels in the tree control.
         ``TR_ROW_LINES``                     0x400 Use this style to draw a contrasting border between displayed rows.
         ``TR_HIDE_ROOT``                     0x800 Use this style to suppress the display of the root node, effectively causing the first-level nodes to appear as a series of root nodes.
         ``TR_FULL_ROW_HIGHLIGHT``           0x2000 Use this style to have the background colour and the selection highlight extend  over the entire horizontal row of the tree control window.
         ``TR_AUTO_CHECK_CHILD``             0x4000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are checked/unchecked as well.
         ``TR_AUTO_TOGGLE_CHILD``            0x8000 Only meaningful foe checkbox-type items: when a parent item is checked/unchecked its children are toggled accordingly.
         ``TR_AUTO_CHECK_PARENT``           0x10000 Only meaningful foe checkbox-type items: when a child item is checked/unchecked its parent item is checked/unchecked as well.
         ``TR_ALIGN_WINDOWS``               0x20000 Flag used to align windows (in items with windows) at the same horizontal position.
         ``TR_ALIGN_WINDOWS_RIGHT``         0x40000 Flag used to align windows (in items with windows) to the rightmost edge of L{CustomTreeCtrl}.
         ============================== =========== ==================================================

        :param `wx.Validator` `validator`: window validator;
        :param string `name`: window name.
        """
        
        self._current = self._key_current = self._anchor = self._select_me = None
        self._hasFocus = False
        self._dirty = False

        # Default line height: it will soon be changed
        self._lineHeight = 10
        # Item indent wrt parent
        self._indent = 15
        # item horizontal spacing between the start and the text
        self._spacing = 18

        # Brushes for focused/unfocused items (also gradient type)
        self._hilightBrush = wx.Brush(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT))
        btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        self._hilightUnfocusedBrush = wx.Brush(btnshadow)
        r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()
        backcolour = (max((r >> 1) - 20, 0),
                      max((g >> 1) - 20, 0),
                      max((b >> 1) - 20, 0))
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._hilightUnfocusedBrush2 = wx.Brush(backcolour)

        # image list for icons
        self._imageListNormal = self._imageListButtons = self._imageListState = self._imageListCheck = self._imageListLeft = None
        self._ownsImageListNormal = self._ownsImageListButtons = self._ownsImageListState = self._ownsImageListLeft = False

        # Drag and drop initial settings
        self._dragCount = 0
        self._countDrag = 0
        self._isDragging = False
        self._dropTarget = self._oldSelection = None
        self._dragImage = None
        self._underMouse = None

        # EditCtrl initial settings for editable items        
        self._editCtrl = None
        self._editTimer = None

        # This one allows us to handle Freeze() and Thaw() calls        
        self._freezeCount = 0

        self._findPrefix = ""
        self._findTimer = None

        self._dropEffectAboveItem = False
        self._lastOnSame = False

        # Default normal and bold fonts for an item
        self._hasFont = True
        self._normalFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        family = self._normalFont.GetFamily()
        if family == wx.FONTFAMILY_UNKNOWN:
            family = wx.FONTFAMILY_SWISS
        self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,
                                 self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),
                                 self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,
                                   wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),
                                   self._normalFont.GetFaceName(), self._normalFont.GetEncoding())

        # Hyperlinks things
        self._hypertextfont = wx.Font(self._normalFont.GetPointSize(), family,
                                      self._normalFont.GetStyle(), wx.NORMAL, True,
                                      self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._hypertextnewcolour = wx.BLUE
        self._hypertextvisitedcolour = wx.Colour(200, 47, 200)
        self._isonhyperlink = False

        # Default CustomTreeCtrl background colour.    
        self._backgroundColour = wx.WHITE
        
        # Background image settings
        self._backgroundImage = None
        self._imageStretchStyle = _StyleTile

        # Disabled items colour        
        self._disabledColour = wx.Colour(180, 180, 180)

        # Gradient selection colours        
        self._firstcolour = colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
        self._secondcolour = wx.WHITE
        self._usegradients = False
        self._gradientstyle = 0   # Horizontal Gradient

        # Vista Selection Styles
        self._vistaselection = False

        # To speed up ExpandAll and SelectAll
        self._sendEvent = True

        # Connection lines style
        grey = (160,160,160)
        if wx.Platform != "__WXMAC__":
            self._dottedPen = wx.Pen(grey, 1, wx.USER_DASH)
            self._dottedPen.SetDashes([1,1])
            self._dottedPen.SetCap(wx.CAP_BUTT)
        else:
            self._dottedPen = wx.Pen(grey, 1)

        # Pen Used To Draw The Border Around Selected Items
        self._borderPen = wx.BLACK_PEN
        self._cursor = wx.StockCursor(wx.CURSOR_ARROW)
        
        # For Appended Windows
        self._hasWindows = False
        self._itemWithWindow = []
        
        if wx.Platform == "__WXMAC__":
            agwStyle &= ~TR_LINES_AT_ROOT
            agwStyle |= TR_NO_LINES
            
            platform, major, minor = wx.GetOsVersion()
            if major < 10:
                agwStyle |= TR_ROW_LINES

        # A constant to use my translation of RendererNative.DrawTreeItemButton
        # if the wxPython version is less than 2.6.2.1.
        if _VERSION_STRING < "2.6.2.1":
            self._drawingfunction = DrawTreeItemButton
        else:
            self._drawingfunction = wx.RendererNative.Get().DrawTreeItemButton

        # Set the separator pen default colour
        self._separatorPen = wx.Pen(wx.SystemSettings.GetColour(wx.SYS_COLOUR_GRAYTEXT))

        # Create our container... at last!    
        wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)

        self._agwStyle = agwStyle
        
        # Create the default check image list        
        self.SetImageListCheck(16, 16)

        # If the tree display has no buttons, but does have
        # connecting lines, we can use a narrower layout.
        # It may not be a good idea to force this...
        if not self.HasButtons() and not self.HasAGWFlag(TR_NO_LINES):
            self._indent= 10
            self._spacing = 10
        
        self.SetValidator(validator)

        attr = self.GetDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)
        
        if not self._hasFont:
            self.SetOwnFont(attr.font)

        self.SetSize(size)

        # Bind the events
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(EVT_TREE_ITEM_GETTOOLTIP, self.OnGetToolTip)
        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

        # Sets the focus to ourselves: this is useful if you have items
        # with associated widgets.
        self.SetFocus()


    def AcceptsFocus(self):
        """
        Can this window be given focus by mouse click?

        :note: This method always returns ``True`` as we always accept focus from
         mouse click.

        :note: Overridden from `wx.PyScrolledWindow`.
        """

        # overridden base class method, allows this ctrl to
        # participate in the tab-order, etc.  It's overridable because
        # of deriving this class from wx.PyScrolledWindow...
        return True
    

    def OnDestroy(self, event):
        """
        Handles the ``wx.EVT_WINDOW_DESTROY`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.WindowDestroyEvent` event to be processed.        
        """

        # Here there may be something I miss... do I have to destroy
        # something else?
        if self._editTimer and self._editTimer.IsRunning():
            self._editTimer.Stop()
            del self._editTimer
            self._editTimer = None

        if self._findTimer and self._findTimer.IsRunning():
            self._findTimer.Stop()
            del self._findTimer

        event.Skip()


    def GetControlBmp(self, checkbox=True, checked=False, enabled=True, x=16, y=16):
        """
        Returns a native looking checkbox or radio button bitmap.
        
        :param bool `checkbox`: ``True`` to get a checkbox image, ``False`` for a radiobutton one;
        :param bool `checked`: ``True`` if the control is marked, ``False`` if it is not;
        :param bool `enabled`: ``True`` if the control is enabled, ``False`` if it is not;
        :param integer `x`: the width of the bitmap;
        :param integer `y`: the height of the bitmap.

        :return: An instance of `wx.Bitmap`, representing a native looking checkbox or radiobutton.        
        """

        bmp = wx.EmptyBitmap(x, y)
        mdc = wx.MemoryDC(bmp)
        mask = wx.Colour(0xfe, 0xfe, 0xfe)
        mdc.SetBackground(wx.Brush(mask))
        mdc.Clear()
        
        render = wx.RendererNative.Get()

        if checked == wx.CHK_CHECKED:
            flag = wx.CONTROL_CHECKED
        elif checked == wx.CHK_UNDETERMINED:
            flag = wx.CONTROL_UNDETERMINED
        else:
            flag = 0

        if not enabled:
            flag |= wx.CONTROL_DISABLED

        if checkbox:
            render.DrawCheckBox(self, mdc, (0, 0, x, y), flag)
        else:
            if _VERSION_STRING < "2.9":
                render.DrawRadioButton(self, mdc, (0, 0, x, y), flag)
            else:
                render.DrawRadioBitmap(self, mdc, (0, 0, x, y), flag)

        mdc.SelectObject(wx.NullBitmap)
        bmp.SetMaskColour(mask)
        return bmp


    def GetCount(self):
        """ Returns the global number of items in the tree. """

        if not self._anchor:
            # the tree is empty
            return 0

        count = self._anchor.GetChildrenCount()
        
        if not self.HasAGWFlag(TR_HIDE_ROOT):
            # take the root itself into account
            count = count + 1
        
        return count


    def GetIndent(self):
        """ Returns the item indentation, in pixels. """

        return self._indent

    
    def GetSpacing(self):
        """ Returns the spacing between the start and the text, in pixels. """

        return self._spacing


    def GetRootItem(self):
        """ Returns the root item, an instance of L{GenericTreeItem}. """

        return self._anchor


    def GetSelection(self):
        """
        Returns the current selection.

        :return: An instance of L{GenericTreeItem}.
        
        :note:

         This method is valid only with the style ``TR_SINGLE`` set. Use
         L{GetSelections} for multiple-selections trees.
        """

        return self._current


    def ToggleItemSelection(self, item):
        """
        Toggles the item selection.

        :param `item`: an instance of L{GenericTreeItem}.
        """
        
        self.SelectItem(item, not self.IsSelected(item))


    def EnableChildren(self, item, enable=True):
        """
        Enables/disables the item children.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the children, ``False`` to disable them.

        :note: This method is used internally.        
        """

        torefresh = False
        if item.IsExpanded():
            torefresh = True

        if item.GetType() == 2 and enable and not item.IsChecked():
            # We hit a radiobutton item not checked, we don't want to
            # enable the children
            return
        
        child, cookie = self.GetFirstChild(item)
        while child:
            self.EnableItem(child, enable, torefresh=torefresh)
            # Recurse on tree
            if child.GetType != 2 or (child.GetType() == 2 and item.IsChecked()):
                self.EnableChildren(child, enable)
            (child, cookie) = self.GetNextChild(item, cookie)


    def EnableItem(self, item, enable=True, torefresh=True):
        """
        Enables/disables an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the item, ``False`` to disable it;
        :param bool `torefresh`: whether to redraw the item or not.
        """

        if item.IsEnabled() == enable:
            return

        if not enable and item.IsSelected():
            self.SelectItem(item, False)

        item.Enable(enable)
        wnd = item.GetWindow()

        # Handles the eventual window associated to the item        
        if wnd:
            wndenable = item.GetWindowEnabled()
            wnd.Enable(enable)
        
        if torefresh:
            # We have to refresh the item line
            dc = wx.ClientDC(self)
            self.CalculateSize(item, dc)
            self.RefreshLine(item)
                

    def IsItemEnabled(self, item):
        """
        Returns whether an item is enabled or disabled.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.IsEnabled()        


    def SetDisabledColour(self, colour):
        """
        Sets the colour for items in a disabled state.

        :param `colour`: a valid `wx.Colour` instance.
        """
        
        self._disabledColour = colour
        self._dirty = True


    def GetDisabledColour(self):
        """
        Returns the colour for items in a disabled state.

        :return: An instance of `wx.Colour`.
        """

        return self._disabledColour        
        

    def IsItemChecked(self, item):
        """
        Returns whether an item is checked or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is in a 'checked' state, ``False`` otherwise.
        
        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        return item.IsChecked()


    def GetItem3StateValue(self, item):
        """
        Gets the state of a 3-state checkbox item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``wx.CHK_UNCHECKED`` when the checkbox is unchecked, ``wx.CHK_CHECKED``
         when it is checked and ``wx.CHK_UNDETERMINED`` when it's in the undetermined
         state. 

        :note: This method raises an exception when the function is used with a 2-state
         checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Get3StateValue()


    def IsItem3State(self, item):
        """
        Returns whether or not the checkbox item is a 3-state checkbox.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if this checkbox is a 3-state checkbox, ``False`` if it's a
         2-state checkbox item.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Is3State()
    

    def SetItem3StateValue(self, item, state):
        """
        Sets the checkbox item to the given `state`.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED``
         (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed).

        :note: This method raises an exception when the checkbox item is a 2-state checkbox
         and setting the state to ``wx.CHK_UNDETERMINED``.

        :note: This method is meaningful only for checkbox-like items.
        """

        item.Set3StateValue(state)


    def SetItem3State(self, item, allow):
        """
        Sets whether the item has a 3-state value checkbox assigned to it or not.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `allow`: ``True`` to set an item as a 3-state checkbox, ``False`` to set it
         to a 2-state checkbox.

        :return: ``True`` if the change was successful, ``False`` otherwise.

        :note: This method is meaningful only for checkbox-like items.
        """

        return item.Set3State(allow)
    

    def CheckItem2(self, item, checked=True, torefresh=False):
        """
        Used internally to avoid ``EVT_TREE_ITEM_CHECKED`` events.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it;
        :param bool `torefresh`: whether to redraw the item or not.
        """

        if item.GetType() == 0:
            return
        
        item.Check(checked)

        if torefresh:
            dc = wx.ClientDC(self)
            self.CalculateSize(item, dc)
            self.RefreshLine(item)
        

    def UnCheckRadioParent(self, item, checked=False):
        """
        Used internally to handle radio node parent correctly.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.
        """

        e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        
        if self.GetEventHandler().ProcessEvent(e):
            return False

        item.Check(checked)
        self.RefreshLine(item)
        self.EnableChildren(item, checked)
        e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)

        return True        
        

    def CheckItem(self, item, checked=True):
        """
        Actually checks/uncheks an item, sending (eventually) the two
        events ``EVT_TREE_ITEM_CHECKING`` and ``EVT_TREE_ITEM_CHECKED``.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: for a radiobutton-type item, ``True`` to check it, ``False``
         to uncheck it. For a checkbox-type item, it can be one of ``wx.CHK_UNCHECKED``
         when the checkbox is unchecked, ``wx.CHK_CHECKED`` when it is checked and
         ``wx.CHK_UNDETERMINED`` when it's in the undetermined state.
        """

        # Should we raise an error here?!?        
        if item.GetType() == 0:
            return

        if item.GetType() == 2:    # it's a radio button
            if not checked and item.IsChecked():  # Try To Unckeck?
                return
            else:
                if not self.UnCheckRadioParent(item, checked):
                    return

                self.CheckSameLevel(item, False)
                return
            
        # Radiobuttons are done, let's handle checkbuttons...
        e = TreeEvent(wxEVT_TREE_ITEM_CHECKING, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        
        if self.GetEventHandler().ProcessEvent(e):
            # Blocked by user
            return 

        if item.Is3State():
            item.Set3StateValue(checked)
        else:
            item.Check(checked)
            
        dc = wx.ClientDC(self)
        self.RefreshLine(item)

        if self.HasAGWFlag(TR_AUTO_CHECK_CHILD):
            ischeck = self.IsItemChecked(item)
            self.AutoCheckChild(item, ischeck)
        if self.HasAGWFlag(TR_AUTO_CHECK_PARENT):
            ischeck = self.IsItemChecked(item)
            self.AutoCheckParent(item, ischeck)
        elif self.HasAGWFlag(TR_AUTO_TOGGLE_CHILD):
            self.AutoToggleChild(item)

        e = TreeEvent(wxEVT_TREE_ITEM_CHECKED, self.GetId())
        e.SetItem(item)
        e.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(e)


    def AutoToggleChild(self, item):
        """
        Transverses the tree and toggles the items.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """
        
        child, cookie = self.GetFirstChild(item)

        torefresh = False
        if item.IsExpanded():
            torefresh = True

        # Recurse on tree            
        while child:
            if child.GetType() == 1 and child.IsEnabled():
                self.CheckItem2(child, not child.IsChecked(), torefresh=torefresh)
            self.AutoToggleChild(child)
            (child, cookie) = self.GetNextChild(item, cookie)


    def AutoCheckChild(self, item, checked):
        """
        Transverses the tree and checks/unchecks the items.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """        

        (child, cookie) = self.GetFirstChild(item)

        torefresh = False
        if item.IsExpanded():
            torefresh = True
            
        while child:
            if child.GetType() == 1 and child.IsEnabled():
                self.CheckItem2(child, checked, torefresh=torefresh)
            self.AutoCheckChild(child, checked)
            (child, cookie) = self.GetNextChild(item, cookie)


    def AutoCheckParent(self, item, checked):
        """
        Traverses up the tree and checks/unchecks parent items.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.
        """

        parent = item.GetParent()
        if not parent or parent.GetType() != 1:
            return

        (child, cookie) = self.GetFirstChild(parent)
        while child:
            if child.GetType() == 1 and child.IsEnabled():
                if checked != child.IsChecked():
                    return
            (child, cookie) = self.GetNextChild(parent, cookie)

        self.CheckItem2(parent, checked, torefresh=True)
        self.AutoCheckParent(parent, checked)


    def CheckChilds(self, item, checked=True):
        """
        Programatically check/uncheck item children.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for checkbox-like and radiobutton-like items.

        :note: This method does not generate ``EVT_TREE_ITEM_CHECKING`` and
         ``EVT_TREE_ITEM_CHECKED`` events.
        """
        
        if checked == None:
            self.AutoToggleChild(item)
        else:
            self.AutoCheckChild(item, checked)


    def CheckSameLevel(self, item, checked=False):
        """
        Uncheck radio items which are on the same level of the checked one.
        Used internally.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `checked`: ``True`` to check an item, ``False`` to uncheck it.

        :note: This method is meaningful only for radiobutton-like items.
        """

        parent = item.GetParent()

        if not parent:
            return

        torefresh = False
        if parent.IsExpanded():
            torefresh = True
        
        (child, cookie) = self.GetFirstChild(parent)
        while child:
            if child.GetType() == 2 and child != item:
                self.CheckItem2(child, checked, torefresh=torefresh)
                if child.GetType != 2 or (child.GetType() == 2 and child.IsChecked()):
                    self.EnableChildren(child, checked)
            (child, cookie) = self.GetNextChild(parent, cookie)


    def EditLabel(self, item):
        """
        Starts editing an item label.

        :param `item`: an instance of L{GenericTreeItem}.
        """
        
        self.Edit(item)

        
    def ShouldInheritColours(self):
        """
        Return ``True`` from here to allow the colours of this window to be
        changed by `InheritAttributes`, returning ``False`` forbids inheriting them
        from the parent window.
        
        The base class version returns ``False``, but this method is overridden in
        `wx.Control` where it returns ``True``.

        L{CustomTreeCtrl} does not inherit colours from anyone.
        """

        return False        


    def SetIndent(self, indent):
        """
        Sets the indentation for L{CustomTreeCtrl}.

        :param integer `indent`: an integer representing the indentation for the items in the tree.
        """

        self._indent = indent
        self._dirty = True


    def SetSpacing(self, spacing):
        """
        Sets the spacing between items in L{CustomTreeCtrl}.

        :param integer `spacing`: an integer representing the spacing between items in the tree.
        """
        
        self._spacing = spacing
        self._dirty = True


    def HasChildren(self, item):
        """
        Returns whether an item has children or not.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return len(item.GetChildren()) > 0


    def GetChildrenCount(self, item, recursively=True):
        """
        Returns the item children count.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `recursively`: if ``True``, returns the total number of descendants,
         otherwise only one level of children is counted.
        """

        return item.GetChildrenCount(recursively)


    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if L{CustomTreeCtrl} has the `flag` bit set.

        :param integer `flag`: any possible window style for L{CustomTreeCtrl}.

        :see: The L{__init__} method for the `flag` parameter description.
        """

        return self._agwStyle & flag        
        

    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the L{CustomTreeCtrl} window style.

        :param integer `agwStyle`: the new L{CustomTreeCtrl} window style.
        
        :see: The L{__init__} method for the `agwStyle` parameter description.
        """
        
        # Do not try to expand the root node if it hasn't been created yet
        if self._anchor and not self.HasAGWFlag(TR_HIDE_ROOT) and agwStyle & TR_HIDE_ROOT:
        
            # if we will hide the root, make sure children are visible
            self._anchor.SetHasPlus()
            self._anchor.Expand()
            self.CalculatePositions()
        
        # right now, just sets the styles.  Eventually, we may
        # want to update the inherited styles, but right now
        # none of the parents has updatable styles

        if self.HasAGWFlag(TR_MULTIPLE) and not (agwStyle & TR_MULTIPLE):
            selections = self.GetSelections()
            for select in selections[0:-1]:
                self.SelectItem(select, False)

        self._agwStyle = agwStyle
        self._dirty = True


    def GetAGWWindowStyleFlag(self):
        """
        Returns the L{CustomTreeCtrl} style.

        :see: The L{__init__} method for a list of possible style flags.
        """

        return self._agwStyle
    

    def HasButtons(self):
        """
        Returns whether L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set.

        :return: ``True`` if L{CustomTreeCtrl} has the ``TR_HAS_BUTTONS`` flag set,
         ``False`` otherwise.
        """

        return self.HasAGWFlag(TR_HAS_BUTTONS)


# -----------------------------------------------------------------------------
# functions to work with tree items
# -----------------------------------------------------------------------------

    def GetItemText(self, item):
        """
        Returns the item text.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.GetText()
    

    def GetItemImage(self, item, which=TreeItemIcon_Normal):
        """
        Returns the item image.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `which`: can be one of the following bits:

         ================================= ========================
         Item State                        Description
         ================================= ========================
         ``TreeItemIcon_Normal``           To get the normal item image
         ``TreeItemIcon_Selected``         To get the selected item image (i.e. the image which is shown when the item is currently selected)
         ``TreeItemIcon_Expanded``         To get the expanded image (this only makes sense for items which have children - then this image is shown when the item is expanded and the normal image is shown when it is collapsed)
         ``TreeItemIcon_SelectedExpanded`` To get the selected expanded image (which is shown when an expanded item is currently selected) 
         ================================= ========================

        :return: An integer index that can be used to retrieve the item image inside
         a `wx.ImageList`.         
        """

        return item.GetImage(which)


    def GetItemLeftImage(self, item):
        """
        Returns the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An integer index that can be used to retrieve the item leftmost image inside
         a `wx.ImageList`.
        """

        return item.GetLeftImage()


    def GetPyData(self, item):
        """
        Returns the data associated to an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: A Python object representing the item data, or ``None`` if no data
         has been assigned to this item.
        """

        return item.GetData()

    GetItemPyData = GetPyData 


    def GetItemTextColour(self, item):
        """
        Returns the item text colour or separator horizontal line colour.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Colour`.
        """

        return item.Attr().GetTextColour()


    def GetItemBackgroundColour(self, item):
        """
        Returns the item background colour.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Colour`.
        """

        return item.Attr().GetBackgroundColour()


    def GetItemFont(self, item):
        """
        Returns the item font.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Font`.
        """

        font = item.Attr().GetFont()
        if font.IsOk():
            return font

        return wx.NullFont


    def IsItemHyperText(self, item):
        """
        Returns whether an item is hypertext or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is hypertext-like, ``False`` otherwise.
        """

        return item.IsHyperText()


    def SetItemText(self, item, text):
        """
        Sets the item text.

        :param `item`: an instance of L{GenericTreeItem};
        :param string `text`: the new item label.

        :raise: `Exception` if the input `item` is a separator.        
        """

        if item.IsSeparator():
            raise Exception("Separator items can not have text")
        
        dc = wx.ClientDC(self)
        item.SetText(text)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)


    def SetItemImage(self, item, image, which=TreeItemIcon_Normal):
        """
        Sets the item image, depending on the item state.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in the state specified by the `which` parameter;
        :param integer `which`: the item state.

        :see: L{GetItemImage} for an explanation of the `which` parameter.        
        """

        item.SetImage(image, which)

        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)


    def SetItemLeftImage(self, item, image):
        """
        Sets the item leftmost image, i.e. the image associated to the item on the leftmost
        part of the L{CustomTreeCtrl} client area.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `image`: an index within the left image list specifying the image to
         use for the item in the leftmost part of the client area.
        """

        item.SetLeftImage(image)

        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)


    def SetPyData(self, item, data):
        """
        Sets the data associated to an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param object `data`: can be any Python object.
        """

        item.SetData(data)

    SetItemPyData = SetPyData
    

    def SetItemHasChildren(self, item, has=True):
        """
        Forces the appearance/disappearance of the button next to the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `has`: ``True`` to have a button next to an item, ``False`` otherwise.
        """
        
        item.SetHasPlus(has)
        self.RefreshLine(item)


    def SetItemBold(self, item, bold=True):
        """
        Sets the item font as bold/unbold.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `bold`: ``True`` to set the item font as bold, ``False`` otherwise.
        """

        # avoid redrawing the tree if no real change
        if item.IsBold() != bold:
            item.SetBold(bold)
            self._dirty = True
    

    def SetItemItalic(self, item, italic=True):
        """
        Sets the item font as italic/non-italic.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `italic`: ``True`` to set the item font as italic, ``False`` otherwise.
        """

        if item.IsItalic() != italic:
            item.SetItalic(italic)
            self._dirty = True


    def SetItemDropHighlight(self, item, highlight=True):
        """
        Gives the item the visual feedback for drag and drop operations.
        This is useful when something is dragged from outside the L{CustomTreeCtrl}.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `highlight`: ``True`` to highlight the dragged items, ``False`` otherwise.
        """

        if highlight:
            bg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)
            fg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)

        item.Attr().SetTextColour(fg)
        item.Attr.SetBackgroundColour(bg)
        self.RefreshLine(item)


    def SetItemTextColour(self, item, colour):
        """
        Sets the item text colour or separator horizontal line colour.

        :param `item`: an instance of L{GenericTreeItem};
        :param `colour`: a valid `wx.Colour` instance.
        """

        item.Attr().SetTextColour(colour)
        self.RefreshLine(item)
        

    def SetItemBackgroundColour(self, item, colour):
        """
        Sets the item background colour.

        :param `item`: an instance of L{GenericTreeItem};
        :param `colour`: a valid `wx.Colour` instance.
        """

        item.Attr().SetBackgroundColour(colour)
        self.RefreshLine(item)


    def SetItemHyperText(self, item, hyper=True):
        """
        Sets whether the item is hypertext or not.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """

        item.SetHyperText(hyper)
        self.RefreshLine(item)
        

    def SetItemFont(self, item, font):
        """
        Sets the item font.

        :param `item`: an instance of L{GenericTreeItem};
        :param `font`: a valid `wx.Font` instance.
        """

        item.Attr().SetFont(font)
        self._dirty = True
        

    def SetFont(self, font):
        """
        Sets the L{CustomTreeCtrl} font.

        :param `font`: a valid `wx.Font` instance.

        :note: Overridden from `wx.PyScrolledWindow`.        
        """

        wx.PyScrolledWindow.SetFont(self, font)

        self._normalFont = font 
        family = self._normalFont.GetFamily()
        if family == wx.FONTFAMILY_UNKNOWN:
            family = wx.FONTFAMILY_SWISS
        self._boldFont = wx.Font(self._normalFont.GetPointSize(), family,
                                 self._normalFont.GetStyle(), wx.BOLD, self._normalFont.GetUnderlined(),
                                 self._normalFont.GetFaceName(), self._normalFont.GetEncoding())
        self._italicFont = wx.Font(self._normalFont.GetPointSize(), family,
                                   wx.FONTSTYLE_ITALIC, wx.NORMAL, self._normalFont.GetUnderlined(),
                                   self._normalFont.GetFaceName(), self._normalFont.GetEncoding())

        return True


    def GetHyperTextFont(self):
        """
        Returns the font used to render hypertext items.

        :return: An instance of `wx.Font`.

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextfont        


    def SetHyperTextFont(self, font):
        """
        Sets the font used to render hypertext items.

        :param `font`: a valid `wx.Font` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextfont = font
        self._dirty = True
        

    def SetHyperTextNewColour(self, colour):
        """
        Sets the colour used to render a non-visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextnewcolour = colour
        self._dirty = True


    def GetHyperTextNewColour(self):
        """
        Returns the colour used to render a non-visited hypertext item.

        :return: An instance of `wx.Colour`.

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextnewcolour


    def SetHyperTextVisitedColour(self, colour):
        """
        Sets the colour used to render a visited hypertext item.

        :param `colour`: a valid `wx.Colour` instance.

        :note: This method is meaningful only for hypertext-like items.
        """

        self._hypertextvisitedcolour = colour
        self._dirty = True


    def GetHyperTextVisitedColour(self):
        """
        Returns the colour used to render a visited hypertext item.

        :return: An instance of `wx.Colour`.

        :note: This method is meaningful only for hypertext-like items.
        """

        return self._hypertextvisitedcolour


    def SetItemVisited(self, item, visited=True):
        """
        Sets whether an hypertext item was visited.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.

        :note: This method is meaningful only for hypertext-like items.
        """

        item.SetVisited(visited)
        self.RefreshLine(item)


    def GetItemVisited(self, item):
        """
        Returns whether an hypertext item was visited.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the hypertext item has been visited, ``False`` otherwise.

        :note: This method is meaningful only for hypertext-like items.
        """

        return item.GetVisited()            


    def SetHilightFocusColour(self, colour):
        """
        Sets the colour used to highlight focused selected items.

        :param `colour`: a valid `wx.Colour` instance.
        
        :note: This is applied only if gradient and Windows Vista selection
         styles are disabled.
        """

        self._hilightBrush = wx.Brush(colour)
        self.RefreshSelected()
            

    def SetHilightNonFocusColour(self, colour):
        """
        Sets the colour used to highlight unfocused selected items.

        :param `colour`: a valid `wx.Colour` instance.
        
        :note: This is applied only if gradient and Windows Vista selection
         styles are disabled.
        """

        self._hilightUnfocusedBrush = wx.Brush(colour)
        self.RefreshSelected()


    def GetHilightFocusColour(self):
        """
        Returns the colour used to highlight focused selected items.

        :return: An instance of `wx.Colour`.
        
        :note: This is used only if gradient and Windows Vista selection
         styles are disabled.
        """

        return self._hilightBrush.GetColour()
            

    def GetHilightNonFocusColour(self):
        """
        Returns the colour used to highlight unfocused selected items.

        :return: An instance of `wx.Colour`.

        :note: This is used only if gradient and Windows Vista selection
         styles are disabled.
        """
        
        return self._hilightUnfocusedBrush.GetColour()

    
    def SetFirstGradientColour(self, colour=None):
        """
        Sets the first gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHT``.
        """
        
        if colour is None:
            colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT)

        self._firstcolour = colour
        if self._usegradients:
            self.RefreshSelected()
            

    def SetSecondGradientColour(self, colour=None):
        """
        Sets the second gradient colour for gradient-style selections.

        :param `colour`: if not ``None``, a valid `wx.Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the L{CustomTreeCtrl}
         background colour.
        """

        if colour is None:
            # No colour given, generate a slightly darker from the
            # CustomTreeCtrl background colour
            colour = self.GetBackgroundColour()
            r, g, b = int(colour.Red()), int(colour.Green()), int(colour.Blue())
            colour = ((r >> 1) + 20, (g >> 1) + 20, (b >> 1) + 20)
            colour = wx.Colour(colour[0], colour[1], colour[2])

        self._secondcolour = colour

        if self._usegradients:
            self.RefreshSelected()


    def GetFirstGradientColour(self):
        """
        Returns the first gradient colour for gradient-style selections.

        :return: An instance of `wx.Colour`.
        """
        
        return self._firstcolour


    def GetSecondGradientColour(self):
        """
        Returns the second gradient colour for gradient-style selections.

        :return: An instance of `wx.Colour`.
        """
        
        return self._secondcolour


    def EnableSelectionGradient(self, enable=True):
        """
        Globally enables/disables drawing of gradient selections.

        :param bool `enable`: ``True`` to enable gradient-style selections, ``False``
         to disable it.

        :note: Calling this method disables any Vista-style selection previously
         enabled.
        """

        self._usegradients = enable
        self._vistaselection = False
        self.RefreshSelected()
        

    def SetGradientStyle(self, vertical=0):
        """
        Sets the gradient style for gradient-style selections.

        :param integer `vertical`: ``0`` for horizontal gradient-style selections, ``1`` for vertical
         gradient-style selections.
        """

        # 0 = Horizontal, 1 = Vertical
        self._gradientstyle = vertical

        if self._usegradients:
            self.RefreshSelected()


    def GetGradientStyle(self):
        """
        Returns the gradient style for gradient-style selections.

        :return: ``0`` for horizontal gradient-style selections, ``1`` for vertical
         gradient-style selections.
        """

        return self._gradientstyle


    def EnableSelectionVista(self, enable=True):
        """
        Globally enables/disables drawing of Windows Vista selections.

        :param bool `enable`: ``True`` to enable Vista-style selections, ``False`` to
         disable it.

        :note: Calling this method disables any gradient-style selection previously
         enabled.
        """

        self._usegradients = False
        self._vistaselection = enable
        self.RefreshSelected()


    def SetBorderPen(self, pen):
        """
        Sets the pen used to draw the selected item border.

        :param `pen`: an instance of `wx.Pen`.
        
        :note: The border pen is not used if the Windows Vista selection style is applied.
        """

        self._borderPen = pen
        self.RefreshSelected()


    def GetBorderPen(self):
        """
        Returns the pen used to draw the selected item border.

        :return: An instance of `wx.Pen`.

        :note: The border pen is not used if the Windows Vista selection style is applied.
        """

        return self._borderPen


    def SetConnectionPen(self, pen):
        """
        Sets the pen used to draw the connecting lines between items.

        :param `pen`: an instance of `wx.Pen`.
        """

        self._dottedPen = pen
        self._dirty = True


    def GetConnectionPen(self):
        """
        Returns the pen used to draw the connecting lines between items.

        :return: An instance of `wx.Pen`.
        """

        return self._dottedPen


    def SetBackgroundImage(self, image):
        """
        Sets the L{CustomTreeCtrl} background image.

        :param `image`: if not ``None``, an instance of `wx.Bitmap`.

        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.        
        """

        self._backgroundImage = image
        self.Refresh()
        

    def GetBackgroundImage(self):
        """
        Returns the L{CustomTreeCtrl} background image (if any).

        :return: An instance of `wx.Bitmap` if a background image is present, ``None`` otherwise.
        
        :note: At present, the background image can only be used in "tile" mode.

        :todo: Support background images also in stretch and centered modes.        
        """

        return self._backgroundImage        
    

    def SetSeparatorColour(self, colour):
        """
        Sets the pen colour for separator-type items.

        :param `colour`: a valid instance of `wx.Colour`.
        """

        self._separatorPen = wx.Pen(colour, 1)
        self.Refresh()


    def GetSeparatorColour(self, colour):
        """
        Returns the pen colour for separator-type items.

        :return: An instance of `wx.Colour` representing the separator pen colour.
        """

        return self._separatorPen.GetColour()


    def IsItemSeparator(self, item):
        """
        Returns whether an item is of separator type or not.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        return item.IsSeparator()
        

    def GetItemWindow(self, item):
        """
        Returns the window associated to the item (if any).

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of `wx.Window` if the item has an associated window, ``None`` otherwise.        
        """

        return item.GetWindow()


    def SetItemWindow(self, item, wnd):
        """
        Sets the window for the given item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item.

        :raise: `Exception` if the input `item` is a separator and `wnd` is not ``None``.
        """

        if item.IsSeparator() and wnd is not None:
            raise Exception("Separator items can not have an associated window")

        if wnd is not None:
            self._hasWindows = True
            if item not in self._itemWithWindow:
                self._itemWithWindow.append(item)
            else:
                self.DeleteItemWindow(item)
        else:
            self.DeleteItemWindow(item)
                
        item.SetWindow(wnd)
        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()
       

    def DeleteItemWindow(self, item):
        """
        Deletes the window associated to an item (if any).

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.GetWindow() is None:
            return

        item.DeleteWindow()
        if item in self._itemWithWindow:
            self._itemWithWindow.remove(item)
        

    def GetItemWindowEnabled(self, item):
        """
        Returns whether the window associated to the item is enabled.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has an associated window and this window is
         enabled, ``False`` in all other cases.
        """

        return item.GetWindowEnabled()


    def SetItemWindowEnabled(self, item, enable=True):
        """
        Enables/disables the window associated to the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `enable`: ``True`` to enable the associated window, ``False`` to
         disable it.
        """

        item.SetWindowEnabled(enable)


    def GetItemType(self, item):
        """
        Returns the item type.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An integer representing the item type.
        
        :see: L{SetItemType} for a description of valid item types.        
        """

        return item.GetType()


    def SetItemType(self, item, ct_type):
        """
        Sets the item type.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `ct_type`: may be one of the following integers:

         =============== =========================================
         `ct_type` Value Description
         =============== =========================================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== =========================================

        :note: Regarding radiobutton-type items (with `ct_type` = 2), the following
         approach is used:
         
         - All peer-nodes that are radiobuttons will be mutually exclusive. In other words,
           only one of a set of radiobuttons that share a common parent can be checked at
           once. If a radiobutton node becomes checked, then all of its peer radiobuttons
           must be unchecked.
         - If a radiobutton node becomes unchecked, then all of its child nodes will become
           inactive.

        """

        item.SetType(ct_type)
        self.CalculatePositions()
        self.Refresh()


# -----------------------------------------------------------------------------
# item status inquiries
# -----------------------------------------------------------------------------

    def IsVisible(self, item):
        """
        Returns whether the item is visible or not (i.e., its hierarchy is expanded
        enough to show the item).
        
        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is visible, ``False`` if it is hidden.
        """

        # An item is only visible if it's not a descendant of a collapsed item
        parent = item.GetParent()

        while parent:
        
            if not parent.IsExpanded():
                return False
            
            parent = parent.GetParent()
        
        startX, startY = self.GetViewStart()
        clientSize = self.GetClientSize()

        rect = self.GetBoundingRect(item)
        
        if not rect:
            return False
        if rect.GetWidth() == 0 or rect.GetHeight() == 0:
            return False
        if rect.GetBottom() < 0 or rect.GetTop() > clientSize.y:
            return False
        if rect.GetRight() < 0 or rect.GetLeft() > clientSize.x:
            return False

        return True


    def ItemHasChildren(self, item):
        """
        Returns whether the item has children or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has children, ``False`` otherwise.
        """

        # consider that the item does have children if it has the "+" button: it
        # might not have them (if it had never been expanded yet) but then it
        # could have them as well and it's better to err on this side rather than
        # disabling some operations which are restricted to the items with
        # children for an item which does have them
        return item.HasPlus()


    def IsExpanded(self, item):
        """
        Returns whether the item is expanded or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is expanded, ``False`` if it is collapsed.
        """

        return item.IsExpanded()


    def IsSelected(self, item):
        """
        Returns whether the item is selected or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item is selected, ``False`` otherwise.
        """

        return item.IsSelected()


    def IsBold(self, item):
        """
        Returns whether the item font is bold or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has bold text, ``False`` otherwise.
        """

        return item.IsBold()


    def IsItalic(self, item):
        """
        Returns whether the item font is italic or not.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: ``True`` if the item has italic text, ``False`` otherwise.
        """

        return item.IsItalic()


# -----------------------------------------------------------------------------
# navigation
# -----------------------------------------------------------------------------

    def GetItemParent(self, item):
        """
        Returns the item parent (can be ``None`` for root items).

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` for root items.        
        """

        return item.GetParent()


    def GetFirstChild(self, item):
        """
        Returns the item's first child and an integer value 'cookie'.
        Call L{GetNextChild} for the next child using this very 'cookie' return
        value as an input.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        cookie = 0
        return self.GetNextChild(item, cookie)


    def GetNextChild(self, item, cookie):
        """
        Returns the item's next child.

        :param `item`: an instance of L{GenericTreeItem};
        :param `cookie`: a parameter which is opaque for the application but is necessary
         for the library to make these functions reentrant (i.e. allow more than one
         enumeration on one and the same object simultaneously).

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if there are no
         further children, and as second value an integer parameter 'cookie'.

        :note: This method returns ``None`` if there are no further children.
        """

        children = item.GetChildren()

        # it's ok to cast cookie to size_t, we never have indices big enough to
        # overflow "void *"

        if cookie < len(children):
            
            return children[cookie], cookie+1
        
        else:
        
            # there are no more of them
            return None, cookie
    

    def GetLastChild(self, item):
        """
        Returns the item last child.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further children.
        """

        children = item.GetChildren()
        return (len(children) == 0 and [None] or [children[-1]])[0]


    def GetNextSibling(self, item):
        """
        Returns the next sibling of an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further siblings.

        :note: This method returns ``None`` if there are no further siblings.
        """

        i = item
        parent = i.GetParent()
        
        if parent == None:
        
            # root item doesn't have any siblings
            return None
        
        siblings = parent.GetChildren()
        index = siblings.index(i)
        
        n = index + 1
        return (n == len(siblings) and [None] or [siblings[n]])[0]


    def GetPrevSibling(self, item):
        """
        Returns the previous sibling of an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further siblings.

        :note: This method returns ``None`` if there are no further siblings.
        """

        i = item
        parent = i.GetParent()
        
        if parent == None:
        
            # root item doesn't have any siblings
            return None
        
        siblings = parent.GetChildren()
        index = siblings.index(i)

        return (index == 0 and [None] or [siblings[index-1]])[0]


    def GetNext(self, item):
        """
        Returns the next item. Only for internal use right now.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         further items.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        i = item

        # First see if there are any children.
        children = i.GetChildren()
        if len(children) > 0:
             return children[0]
        else:
             # Try a sibling of this or ancestor instead
             p = item
             toFind = None
             while p and not toFind:
                  toFind = self.GetNextSibling(p)
                  p = self.GetItemParent(p)
                  
             return toFind


    def GetPrev(self, item):
        """
        Returns the previous item. Only for internal use right now.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem}        
        """

        # Look for a previous sibling of this item
        prevSibling = self.GetPrevSibling(item)
        if prevSibling:

            # return it's last child or itself if has not got any children
            if len(prevSibling.GetChildren()) > 0:
                return self.GetLastChild(prevSibling)

            return prevSibling

        # item has not got a previous sibling, return it's parent
        return self.GetItemParent(item)


    def GetNextExpanded(self, item):
        """
        Returns the next expanded item after the input one.

        :param `item`: an instance of L{TreeListItem}.
        """                

        nextSibling = self.GetNextSibling(item)
        if nextSibling:
            if nextSibling.IsExpanded():
                return nextSibling

            return self.GetNextExpanded(prevSibling)
            
        return None


    def GetPrevExpanded(self, item):
        """
        Returns the previous expanded item before the input one.

        :param `item`: an instance of L{TreeListItem}.
        """                

        prevSibling = self.GetPrevSibling(item)
        if prevSibling:
            if prevSibling.IsExpanded():
                return prevSibling

            return self.GetPrevExpanded(prevSibling)
            
        return None
                 

    def GetFirstVisibleItem(self):
        """
        Returns the first visible item.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         visible items.
        """

        id = self.GetRootItem()
        if not id:
            return id

        while id:
            if self.IsVisible(id):
                return id
            id = self.GetNext(id)

        return None


    def GetNextVisible(self, item):
        """
        Returns the next visible item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         next visible items.
        """

        id = item

        while id:
            id = self.GetNext(id)
            if id and self.IsVisible(id):
                return id
            
        return None


    def GetPrevVisible(self, item):
        """
        Returns the previous visible item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: An instance of L{GenericTreeItem} or ``None`` if there are no
         previous visible items.
        """
 
        # find a previous sibling or parent which is visible
        lastGoodItem = self.GetPrevSibling(item)
        if not lastGoodItem or not self.IsVisible(lastGoodItem):
            parent = self.GetItemParent(item)
            rootHidden = self.HasAGWFlag(TR_HIDE_ROOT)
            rootItem = self.GetRootItem()
 
            while parent and not (rootHidden and parent == rootItem):
                if self.IsVisible(parent):
                    lastGoodItem = parent
                    break
                parent = self.GetItemParent(parent)

            if not lastGoodItem:
                return None
            
        # test if found item has visible children, if so and if the found item is not the 
        # parent of the current item traverse the found item to the last visible child
        if not self.HasChildren(lastGoodItem) or not self.IsExpanded(lastGoodItem) or \
           (self.GetItemParent(item) == lastGoodItem):
            return lastGoodItem
        
        lastChild = self.GetLastChild(lastGoodItem)
        while lastChild and self.IsVisible(lastChild):
            lastGoodItem = lastChild
            lastChild = self.GetLastChild(lastGoodItem)
 
        return lastGoodItem


    def ResetEditControl(self):
        """ Called by L{TreeTextCtrl} when it marks itself for deletion. """

        if self._editCtrl is not None:
            self._editCtrl.Destroy()
            self._editCtrl = None

        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()


    def FindItem(self, idParent, prefixOrig):
        """
        Finds the first item starting with the given prefix after the given parent.

        :param integer `idParent`: an instance of L{GenericTreeItem};
        :param string `prefixOrig`: a string containing the item text prefix.

        :return: An instance of L{GenericTreeItem} or ``None`` if no item has been found.        
        """

        # match is case insensitive as this is more convenient to the user: having
        # to press Shift-letter to go to the item starting with a capital letter
        # would be too bothersome
        prefix = prefixOrig.lower()

        # determine the starting point: we shouldn't take the current item (this
        # allows to switch between two items starting with the same letter just by
        # pressing it) but we shouldn't jump to the next one if the user is
        # continuing to type as otherwise he might easily skip the item he wanted
        id = idParent

        if len(prefix) == 1:
            id = self.GetNext(id)
        
        # look for the item starting with the given prefix after it
        while id and not self.GetItemText(id).lower().startswith(prefix):
        
            id = self.GetNext(id)
        
        # if we haven't found anything...
        if not id:
        
            # ... wrap to the beginning
            id = self.GetRootItem()
            if self.HasAGWFlag(TR_HIDE_ROOT):
                # can't select virtual root
                id = self.GetNext(id)
                if idParent == self.GetRootItem(): 
                    # no tree item selected and idParent is not reachable 
                    return id 
            
            # and try all the items (stop when we get to the one we started from)
            while id != idParent and not self.GetItemText(id).lower().startswith(prefix):
                id = self.GetNext(id)
            
        return id


# -----------------------------------------------------------------------------
# operations
# -----------------------------------------------------------------------------

    def DoInsertItem(self, parentId, previous, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Actually inserts an item in the tree.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param integer `previous`: the index at which we should insert the item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
         subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise. 

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` in the following cases:

         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
           set for L{CustomTreeCtrl};
         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
           flag has not been set for L{CustomTreeCtrl};
         - The `ct_type` attribute is less than ``0`` or greater than ``2``;
         - The parent item is a separator;
         - The item is a separator but it has text or an associated window.


        :note: Separator items should not have children, text labels or an associated window.        
        """

        if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if text.find("\n") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if ct_type < 0 or ct_type > 2:
            raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")

        if separator:
            if wnd:
                raise Exception("Separator items can not have associated windows")
            if text.strip():
                raise Exception("Separator items can not text labels")
        
        parent = parentId
        
        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)
        
        self._dirty = True     # do this first so stuff below doesn't cause flicker

        item = GenericTreeItem(parent, text, ct_type, wnd, image, selImage, data, separator)
        
        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(item)
        
        parent.Insert(item, previous)

        return item


    def AddRoot(self, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Adds a root item to the L{CustomTreeCtrl}.

        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param  integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` in the following cases:

         - There already is a root item in the tree;
         - The item window is not ``None`` but the ``TR_HAS_VARIABLE_ROW_HEIGHT`` flag has not been
           set for L{CustomTreeCtrl};
         - The item has multiline text (with line-breaks in it) but the ``TR_HAS_VARIABLE_ROW_HEIGHT``
           flag has not been set for L{CustomTreeCtrl};
         - The `ct_type` attribute is less than ``0`` or greater than ``2``.

        :warning: only one root is allowed to exist in any given instance of L{CustomTreeCtrl}.
        """

        if self._anchor:
            raise Exception("\nERROR: Tree Can Have Only One Root")

        if wnd is not None and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert Controls You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if text.find("\n") >= 0 and not self.HasAGWFlag(TR_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("\nERROR: In Order To Append/Insert A MultiLine Text You Have To Use The Style TR_HAS_VARIABLE_ROW_HEIGHT")

        if ct_type < 0 or ct_type > 2:
            raise Exception("\nERROR: Item Type Should Be 0 (Normal), 1 (CheckBox) or 2 (RadioButton). ")

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        self._anchor = GenericTreeItem(None, text, ct_type, wnd, image, selImage, data)
        
        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(self._anchor)            
        
        if self.HasAGWFlag(TR_HIDE_ROOT):
        
            # if root is hidden, make sure we can navigate
            # into children
            self._anchor.SetHasPlus()
            self._anchor.Expand()
            self.CalculatePositions()
        
        if not self.HasAGWFlag(TR_MULTIPLE):
        
            self._current = self._key_current = self._anchor
            self._current.SetHilight(True)
        
        return self._anchor


    def PrependItem(self, parent, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Prepends an item as a first child of parent.

        :param `parent`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item, any
         subclass of `wx.Window` except top-level windows;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.        
        """

        return self.DoInsertItem(parent, 0, text, ct_type, wnd, image, selImage, data, separator)


    def InsertItemByItem(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param `idPrevious`: an instance of L{GenericTreeItem} representing the
         previous item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.
        
        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :raise: `Exception` if the previous item is not a sibling.        

        :see: L{DoInsertItem} for other possible exceptions generated by this method.
        """
                
        parent = parentId
        
        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)
        
        index = -1
        if idPrevious:

            try:
                index = parent.GetChildren().index(idPrevious)
            except:
                raise Exception("ERROR: Previous Item In CustomTreeCtrl.InsertItem() Is Not A Sibling")

        return self.DoInsertItem(parentId, index+1, text, ct_type, wnd, image, selImage, data, separator)


    def InsertItemByIndex(self, parentId, idPrevious, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param `idPrevious`: the index at which we should insert the new item;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item;
        :param bool `separator`: ``True`` if the item is a separator, ``False`` otherwise.
        
        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """
        
        parent = parentId
        
        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)
        
        return self.DoInsertItem(parentId, idPrevious, text, ct_type, wnd, image, selImage, data, separator)


    def InsertItem(self, parentId, input, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None, separator=False):
        """
        Inserts an item after the given previous.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
         the input parameters.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        if type(input) == type(1):
            return self.InsertItemByIndex(parentId, input, text, ct_type, wnd, image, selImage, data, separator)
        else:
            return self.InsertItemByItem(parentId, input, text, ct_type, wnd, image, selImage, data, separator)
            

    def AppendItem(self, parentId, text, ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Appends an item as a last child of its parent.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         item's parent;
        :param string `text`: the item text label;
        :param integer `ct_type`: the item type (see L{SetItemType} for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item,
         any subclass of `wx.Window`;
        :param integer `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param integer `selImage`: an index within the normal image list specifying the image to
         use for the item in selected state; if `image` > -1 and `selImage` is -1, the
         same image is used for both selected and unselected items;
        :param object `data`: associate the given Python object `data` with the item.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """
        
        parent = parentId
        
        if not parent:
            # should we give a warning here?
            return self.AddRoot(text, ct_type, wnd, image, selImage, data)
        
        return self.DoInsertItem(parent, len(parent.GetChildren()), text, ct_type, wnd, image, selImage, data)


    def AppendSeparator(self, parentId):
        """
        Appends an horizontal line separator as a last child of its parent.

        :param `parentId`: an instance of L{GenericTreeItem} representing the
         separator's parent.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        parent = parentId
        return self.DoInsertItem(parent, len(parent.GetChildren()), "", separator=True)


    def InsertSeparator(self, parentId, input):
        """
        Inserts a separator item after the given previous.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{InsertItemByIndex} and L{InsertItemByItem} for an explanation of
         the input parameters.

        :see: L{DoInsertItem} for possible exceptions generated by this method.
        """

        return self.InsertItem(parentId, input, "", separator=True)
        

    def PrependSeparator(self, parent):
        """
        Prepends a separator item as a first child of parent.

        :param `parent`: an instance of L{GenericTreeItem} representing the
         item's parent.

        :return: An instance of L{GenericTreeItem} upon successful insertion.

        :see: L{DoInsertItem} for possible exceptions generated by this method.        
        """

        return self.PrependItem(parent, 0, separator=True)


    def SendDeleteEvent(self, item):
        """
        Actually sends the ``EVT_TREE_DELETE_ITEM`` event.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        event = TreeEvent(wxEVT_TREE_DELETE_ITEM, self.GetId())
        event._item = item
        event.SetEventObject(self)
        self.GetEventHandler().ProcessEvent(event)


    def IsDescendantOf(self, parent, item):
        """
        Checks if the given item is under another one in the tree hierarchy.

        :param `parent`: an instance of L{GenericTreeItem}, representing the possible
         parent of `item`;
        :param `item`: another instance of L{GenericTreeItem}.

        :return: ``True`` if `item` is a descendant of `parent`, ``False`` otherwise.        
        """

        while item:
        
            if item == parent:
            
                # item is a descendant of parent
                return True
            
            item = item.GetParent()
        
        return False


    # Don't leave edit or selection on a child which is about to disappear
    def ChildrenClosing(self, item):
        """
        We are about to destroy the item children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
            self._editCtrl.StopEditing()
        
        if item != self._key_current and self.IsDescendantOf(item, self._key_current):
            self._key_current = None
        
        if self.IsDescendantOf(item, self._select_me):
            self._select_me = item
        
        if item != self._current and self.IsDescendantOf(item, self._current):
            self._current.SetHilight(False)
            self._current = None
            self._select_me = item


    def DeleteChildren(self, item):
        """
        Delete all the item's children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        self.ChildrenClosing(item)
        item.DeleteChildren(self)


    def Delete(self, item):
        """
        Deletes an item.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method sends the ``EVT_TREE_DELETE_ITEM`` event.        
        """

        self._dirty = True     # do this first so stuff below doesn't cause flicker

        if self._editCtrl != None and self.IsDescendantOf(item, self._editCtrl.item()):
            # can't delete the item being edited, cancel editing it first
            self._editCtrl.StopEditing()
        
        parent = item.GetParent()

        # don't keep stale pointers around!
        if self.IsDescendantOf(item, self._key_current):
        
            # Don't silently change the selection:
            # do it properly in idle time, so event
            # handlers get called.

            # self._key_current = parent
            self._key_current = None
        
        # self._select_me records whether we need to select
        # a different item, in idle time.
        if self._select_me and self.IsDescendantOf(item, self._select_me):
            self._select_me = parent
        
        if self.IsDescendantOf(item, self._current):
        
            # Don't silently change the selection:
            # do it properly in idle time, so event
            # handlers get called.

            # self._current = parent
            self._current = None
            self._select_me = parent
        
        # remove the item from the tree
        if parent:
        
            parent.GetChildren().remove(item)  # remove by value
        
        else: # deleting the root
        
            # nothing will be left in the tree
            self._anchor = None
        
        # and delete all of its children and the item itself now
        item.DeleteChildren(self)
        self.SendDeleteEvent(item)

        if item == self._select_me:
            self._select_me = None

        # Remove the item with window
        if item in self._itemWithWindow:
            wnd = item.GetWindow()
            wnd.Hide()
            wnd.Destroy()
            item._wnd = None
            self._itemWithWindow.remove(item)
            
        del item


    def DeleteAllItems(self):
        """ Deletes all items in the L{CustomTreeCtrl}. """

        if self._anchor:
            self.Delete(self._anchor)
        

    def Expand(self, item):
        """
        Expands an item, sending a ``EVT_TREE_ITEM_EXPANDING`` and
        ``EVT_TREE_ITEM_EXPANDED`` events.

        :param `item`: an instance of L{GenericTreeItem}.        

        :raise: `Exception` if you try to expand a hidden root (i.e., when the ``TR_HIDE_ROOT``
         style is set for L{CustomTreeCtrl}).
        """
        
        if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
             raise Exception("\nERROR: Can't Expand An Hidden Root. ")

        if not item.HasPlus():
            return

        if item.IsExpanded():
            return

        if self._sendEvent:
            event = TreeEvent(wxEVT_TREE_ITEM_EXPANDING, self.GetId())
            event._item = item
            event.SetEventObject(self)

            if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
                # cancelled by program
                return
    
        item.Expand()
        
        if not self._sendEvent:
            # We are in ExpandAll/ExpandAllChildren
            return

        self.CalculatePositions()
        self.RefreshSubtree(item)

        if self._hasWindows:
            # We hide the associated window here, we may show it after
            self.HideWindows()
            
        event.SetEventType(wxEVT_TREE_ITEM_EXPANDED)
        self.GetEventHandler().ProcessEvent(event)


    def ExpandAllChildren(self, item):
        """
        Expands all the items children of the input item.

        :param `item`: an instance of L{GenericTreeItem}.

        :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and
         ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the
         control would be too slow then.
        """

        self._sendEvent = False        
        if not self.HasAGWFlag(TR_HIDE_ROOT) or item != self.GetRootItem():
            self.Expand(item)
            if not self.IsExpanded(item):
                self._sendEvent = True
                return
        
        child, cookie = self.GetFirstChild(item)
        
        while child:
            self.ExpandAllChildren(child)
            child, cookie = self.GetNextChild(item, cookie)

        self._sendEvent = True
        

    def ExpandAll(self):
        """
        Expands all L{CustomTreeCtrl} items.

        :note: This method suppresses the ``EVT_TREE_ITEM_EXPANDING`` and
         ``EVT_TREE_ITEM_EXPANDED`` events because expanding many items int the
         control would be too slow then.
        """

        if self._anchor:
            self.ExpandAllChildren(self._anchor)

        self._sendEvent = True
        self._dirty = True
        

    def Collapse(self, item):
        """
        Collapse an item, sending a ``EVT_TREE_ITEM_COLLAPSING`` and
        ``EVT_TREE_ITEM_COLLAPSED`` events.

        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` if you try to collapse a hidden root (i.e., when the ``TR_HIDE_ROOT``
         style is set for L{CustomTreeCtrl}).
        """
        
        if self.HasAGWFlag(TR_HIDE_ROOT) and item == self.GetRootItem():
             raise Exception("\nERROR: Can't Collapse An Hidden Root. ")

        if not item.IsExpanded():
            return

        event = TreeEvent(wxEVT_TREE_ITEM_COLLAPSING, self.GetId())
        event._item = item
        event.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            # cancelled by program
            return
    
        self.ChildrenClosing(item)
        item.Collapse()

        self.CalculatePositions()
        self.Refresh()

        if self._hasWindows:
            self.HideWindows()

        self.AdjustMyScrollbars()            
            
        event.SetEventType(wxEVT_TREE_ITEM_COLLAPSED)
        self.GetEventHandler().ProcessEvent(event)


    def CollapseAndReset(self, item):
        """
        Collapse the given item and deletes its children.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        self.Collapse(item)
        self.DeleteChildren(item)


    def Toggle(self, item):
        """
        Toggles the item state (collapsed/expanded).

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.IsExpanded():
            self.Collapse(item)
        else:
            self.Expand(item)


    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """
        
        for child in self._itemWithWindow:
            if not self.IsVisible(child):
                wnd = child.GetWindow()
                if wnd:
                    wnd.Hide()
            

    def Unselect(self):
        """ Unselects the current selection. """

        if self._current:
            self._current.SetHilight(False)
            self.RefreshLine(self._current)

        self._current = None
        self._select_me = None


    def UnselectAllChildren(self, item):
        """
        Unselects all the children of the given item.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if item.IsSelected():
            item.SetHilight(False)
            self.RefreshLine(item)
        
        if item.HasChildren():
            for child in item.GetChildren():
                self.UnselectAllChildren(child)


    def SelectAllChildren(self, item):
        """
        Selects all the children of the given item.

        :param `item`: an instance of L{GenericTreeItem}.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.        
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectAllChildren can be used only with multiple selection enabled.")
        
        if not item.IsSelected():
            item.SetHilight(True)
            self.RefreshLine(item)
        
        if item.HasChildren():
            for child in item.GetChildren():
                self.SelectAllChildren(child)            


    def UnselectAll(self):
        """ Unselect all the items. """

        rootItem = self.GetRootItem()

        # the tree might not have the root item at all
        if rootItem:
            self.UnselectAllChildren(rootItem)

        self.Unselect()        


    def SelectAll(self):
        """
        Selects all the item in the tree.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectAll can be used only with multiple selection enabled.")
        
        rootItem = self.GetRootItem()

        # the tree might not have the root item at all
        if rootItem:
            self.SelectAllChildren(rootItem)

                
    # Recursive function !
    # To stop we must have crt_item<last_item
    # Algorithm :
    # Tag all next children, when no more children,
    # Move to parent (not to tag)
    # Keep going... if we found last_item, we stop.

    def TagNextChildren(self, crt_item, last_item, select):
        """ Used internally. """

        parent = crt_item.GetParent()

        if parent == None: # This is root item
            return self.TagAllChildrenUntilLast(crt_item, last_item, select)

        children = parent.GetChildren()
        index = children.index(crt_item)
        
        count = len(children)
        
        for n in xrange(index+1, count):
            if self.TagAllChildrenUntilLast(children[n], last_item, select):
                return True

        return self.TagNextChildren(parent, last_item, select)


    def TagAllChildrenUntilLast(self, crt_item, last_item, select):
        """ Used internally. """

        crt_item.SetHilight(select)
        self.RefreshLine(crt_item)

        if crt_item == last_item:
            return True

        if crt_item.HasChildren():        
            for child in crt_item.GetChildren():
                if self.TagAllChildrenUntilLast(child, last_item, select):
                    return True
            
        return False


    def SelectItemRange(self, item1, item2):
        """
        Selects all the items between `item1` and `item2`.

        :param `item1`: an instance of L{GenericTreeItem}, representing the first
         item in the range to select;
        :param `item2`: an instance of L{GenericTreeItem}, representing the last
         item in the range to select.

        :raise: `Exception` if used without the ``TR_EXTENDED`` or ``TR_MULTIPLE`` style set.
        
        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.         
        """

        if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):
            raise Exception("SelectItemRange can be used only with multiple selection enabled.")
        
        self._select_me = None

        # item2 is not necessary after item1
        # choice first' and 'last' between item1 and item2
        first = (item1.GetY() < item2.GetY() and [item1] or [item2])[0]
        last = (item1.GetY() < item2.GetY() and [item2] or [item1])[0]

        select = self._current.IsSelected()

        if self.TagAllChildrenUntilLast(first, last, select):
            return

        self.TagNextChildren(first, last, select)


    def DoSelectItem(self, item, unselect_others=True, extended_select=False):
        """
        Actually selects/unselects an item, sending ``EVT_TREE_SEL_CHANGING`` and
        ``EVT_TREE_SEL_CHANGED`` events.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `unselect_others`: if ``True``, all the other selected items are
         unselected.
        :param bool `extended_select`: ``True`` if the L{CustomTreeCtrl} is using the
         ``TR_EXTENDED`` style.
        """

        self._select_me = None

        is_single = not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE)

        # to keep going anyhow !!!
        if is_single:
            if item.IsSelected():
                # Handles hypertext items
                self.HandleHyperLink(item)
                return # nothing else to do
            unselect_others = True
            extended_select = False
        
        elif unselect_others and item.IsSelected():
        
            # selection change if there is more than one item currently selected
            if len(self.GetSelections()) == 1:
                # Handles hypertext items
                self.HandleHyperLink(item)
                return

        event = TreeEvent(wxEVT_TREE_SEL_CHANGING, self.GetId())
        event._item = item
        event._itemOld = self._current
        event.SetEventObject(self)
        # TODO : Here we don't send any selection mode yet !

        if self.GetEventHandler().ProcessEvent(event) and not event.IsAllowed():
            return

        parent = self.GetItemParent(item)
        while parent:
            if not self.IsExpanded(parent):
                self.Expand(parent)

            parent = self.GetItemParent(parent)
        
        # ctrl press
        if unselect_others:
            if is_single:
                self.Unselect() # to speed up thing
            else:
                self.UnselectAll()

        # shift press
        if extended_select:
            if not self._current:
                self._current = self._key_current = self.GetRootItem()
            
            # don't change the mark (self._current)
            self.SelectItemRange(self._current, item)
        
        else:
        
            select = True # the default

            # Check if we need to toggle hilight (ctrl mode)
            if not unselect_others:
                select = not item.IsSelected()

            self._current = self._key_current = item
            self._current.SetHilight(select)
            self.RefreshLine(self._current)
        
        # This can cause idle processing to select the root
        # if no item is selected, so it must be after the
        # selection is set
        self.EnsureVisible(item)

        event.SetEventType(wxEVT_TREE_SEL_CHANGED)
        self.GetEventHandler().ProcessEvent(event)

        # Handles hypertext items
        self.HandleHyperLink(item)
        

    def SelectItem(self, item, select=True):
        """
        Selects/deselects an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `select`: ``True`` to select an item, ``False`` to deselect it.
        """
        
        if select:
        
            self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE))
        
        else: # deselect
        
            item.SetHilight(False)
            self.RefreshLine(item)

    
    def FillArray(self, item, array=[]):
        """
        Internal function. Used to populate an array of selected items when
        the style ``TR_MULTIPLE`` is used.

        :param `item`: an instance of L{GenericTreeItem};
        :param list `array`: a Python list containing the selected items.

        :return: A Python list containing the selected items.
        """

        if not array:
            array = []
            
        if item.IsSelected():
            array.append(item)

        if item.HasChildren() and item.IsExpanded():
            for child in item.GetChildren():
                array = self.FillArray(child, array)
        
        return array
    

    def GetSelections(self):
        """
        Returns a list of selected items.

        :note: This method can be used only if L{CustomTreeCtrl} has the ``TR_MULTIPLE`` or ``TR_EXTENDED``
         style set.

        :return: A Python list containing the selected items, all instances of L{GenericTreeItem}.
        """

        array = []
        idRoot = self.GetRootItem()
        if idRoot:
            array = self.FillArray(idRoot, array)
        
        #else: the tree is empty, so no selections

        return array


    def HandleHyperLink(self, item):
        """
        Handles the hyperlink items, sending the ``EVT_TREE_ITEM_HYPERLINK`` event.

        :param `item`: an instance of L{GenericTreeItem}.        
        """

        if self.IsItemHyperText(item):
            event = TreeEvent(wxEVT_TREE_ITEM_HYPERLINK, self.GetId())
            event._item = item
            self.GetEventHandler().ProcessEvent(event)
        

    def EnsureVisible(self, item):
        """
        Scrolls and/or expands items to ensure that the given item is visible.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        # first expand all parent branches
        parent = item.GetParent()

        if self.HasAGWFlag(TR_HIDE_ROOT):
            while parent and parent != self._anchor:
                self.Expand(parent)
                parent = parent.GetParent()
        else:
            while parent:
                self.Expand(parent)
                parent = parent.GetParent()
            
        self.ScrollTo(item)


    def ScrollTo(self, item):
        """
        Scrolls the specified item into view.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if not item:
            return

        # We have to call this here because the label in
        # question might just have been added and no screen
        # update taken place.
        if self._dirty:
            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Update()
        else:
            wx.YieldIfNeeded()

        # now scroll to the item
        item_y = item.GetY()
        start_x, start_y = self.GetViewStart()
        start_y *= _PIXELS_PER_UNIT

        client_w, client_h = self.GetClientSize()

        x, y = 0, 0

        if item_y < start_y+3:
        
            # going down
            x, y = self._anchor.GetSize(x, y, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            # Item should appear at top
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, item_y/_PIXELS_PER_UNIT)
        
        elif item_y+self.GetLineHeight(item) > start_y+client_h:
        
            # going up
            x, y = self._anchor.GetSize(x, y, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            item_y += _PIXELS_PER_UNIT+2
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            # Item should appear at bottom
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, (item_y+self.GetLineHeight(item)-client_h)/_PIXELS_PER_UNIT )


    def OnCompareItems(self, item1, item2):
        """
        Returns whether 2 items have the same text.
        
        Override this function in the derived class to change the sort order of the items
        in the L{CustomTreeCtrl}. The function should return a negative, zero or positive
        value if the first item is less than, equal to or greater than the second one.

        :param `item1`: an instance of L{GenericTreeItem};
        :param `item2`: another instance of L{GenericTreeItem}.

        :return: The return value is negative if `item1` < `item2`, zero if `item1` == `item2`
         and strictly positive if `item1` < `item2`.
        
        :note: The base class version compares items alphabetically.
        """

        return cmp(self.GetItemText(item1), self.GetItemText(item2))


    def SortChildren(self, item):
        """
        Sorts the children of the given item using the L{OnCompareItems} method of
        L{CustomTreeCtrl}. 

        :param `item`: an instance of L{GenericTreeItem}.
        
        :note: You should override the L{OnCompareItems} method in your derived class to change
         the sort order (the default is ascending case-sensitive alphabetical order).
        """

        children = item.GetChildren()
        
        if len(children) > 1:
            self._dirty = True
            children.sort(self.OnCompareItems)
        

    def GetImageList(self):
        """
        Returns the normal image list associated with L{CustomTreeCtrl}.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListNormal


    def GetButtonsImageList(self):
        """
        Returns the buttons image list associated with L{CustomTreeCtrl} (from
        which application-defined button images are taken).

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListButtons


    def GetStateImageList(self):
        """
        Returns the state image list associated with L{CustomTreeCtrl} (from which
        application-defined state images are taken).

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListState


    def GetImageListCheck(self):
        """
        Returns the image list used to build the check/radio buttons in L{CustomTreeCtrl}.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListCheck        


    def GetLeftImageList(self):
        """
        Returns the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :return: An instance of `wx.ImageList`.
        """

        return self._imageListLeft


    def CalculateLineHeight(self):
        """ Calculates the height of a line. """

        dc = wx.ClientDC(self)
        self._lineHeight = dc.GetCharHeight() 

        if self._imageListNormal:
        
            # Calculate a self._lineHeight value from the normal Image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListNormal.GetImageCount()

            for i in xrange(n):
            
                width, height = self._imageListNormal.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height
            
        if self._imageListButtons:
        
            # Calculate a self._lineHeight value from the Button image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListButtons.GetImageCount()

            for i in xrange(n):
            
                width, height = self._imageListButtons.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._imageListCheck:
        
            # Calculate a self._lineHeight value from the check/radio image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListCheck.GetImageCount()

            for i in xrange(n):
            
                width, height = self._imageListCheck.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height

        if self._imageListLeft:
        
            # Calculate a self._lineHeight value from the leftmost image sizes.
            # May be toggle off. Then CustomTreeCtrl will spread when
            # necessary (which might look ugly).
            n = self._imageListLeft.GetImageCount()

            for i in xrange(n):
            
                width, height = self._imageListLeft.GetSize(i)

                if height > self._lineHeight:
                    self._lineHeight = height
        
        if self._lineHeight < 30:
            self._lineHeight += 2                 # at least 2 pixels
        else:
            self._lineHeight += self._lineHeight/10   # otherwise 10% extra spacing


    def SetImageList(self, imageList):
        """
        Sets the normal image list for L{CustomTreeCtrl}.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        if self._ownsImageListNormal:
            del self._imageListNormal
            
        self._imageListNormal = imageList
        self._ownsImageListNormal = False
        self._dirty = True
        
        # Don't do any drawing if we're setting the list to NULL,
        # since we may be in the process of deleting the tree control.
        if imageList:
            self.CalculateLineHeight()

            # We gray out the image list to use the grayed icons with disabled items
            sz = imageList.GetSize(0)
            self._grayedImageList = wx.ImageList(sz[0], sz[1], True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedImageList.Add(newbmp)


    def SetLeftImageList(self, imageList):
        """
        Sets the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self._imageListLeft = imageList
        self._ownsImageListLeft = False
        self._dirty = True
        
        # Don't do any drawing if we're setting the list to NULL,
        # since we may be in the process of deleting the tree control.
        if imageList:
            self.CalculateLineHeight()

            # We gray out the image list to use the grayed icons with disabled items
            sz = imageList.GetSize(0)
            self._grayedImageListLeft = wx.ImageList(sz[0], sz[1], True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedImageListLeft.Add(newbmp)
        

    def SetStateImageList(self, imageList):
        """
        Sets the state image list for L{CustomTreeCtrl} (from which application-defined
        state images are taken).

        :param `imageList`: an instance of `wx.ImageList`.
        """
        
        if self._ownsImageListState:
            del self._imageListState

        self._imageListState = imageList
        self._ownsImageListState = False


    def SetButtonsImageList(self, imageList):
        """
        Sets the buttons image list for L{CustomTreeCtrl} (from which application-defined
        button images are taken).

        :param `imageList`: an instance of `wx.ImageList`.
        """

        if self._ownsImageListButtons:
            del self._imageListButtons
            
        self._imageListButtons = imageList
        self._ownsImageListButtons = False
        self._dirty = True
        self.CalculateLineHeight()


    def SetImageListCheck(self, sizex, sizey, imglist=None):
        """
        Sets the checkbox/radiobutton image list.

        :param integer `sizex`: the width of the bitmaps in the `imglist`, in pixels;
        :param integer `sizey`: the height of the bitmaps in the `imglist`, in pixels;
        :param `imglist`: an instance of `wx.ImageList`.
        """

        # Image list to hold disabled versions of each control
        self._grayedCheckList = wx.ImageList(sizex, sizey, True, 0)

        if imglist is None:
            
            self._imageListCheck = wx.ImageList(sizex, sizey)

            # Get the Checkboxes
            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=True,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=True,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=False,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=False,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=True,
                                                        checked=2,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=True,
                                                         checked=2,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            # Get the Radio Buttons
            self._imageListCheck.Add(self.GetControlBmp(checkbox=False,
                                                        checked=True,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,
                                                         checked=True,
                                                         enabled=False,
                                                         x=sizex, y=sizey))

            self._imageListCheck.Add(self.GetControlBmp(checkbox=False,
                                                        checked=False,
                                                        enabled=True,
                                                        x=sizex, y=sizey))
            self._grayedCheckList.Add(self.GetControlBmp(checkbox=False,
                                                        checked=False,
                                                        enabled=False,
                                                        x=sizex, y=sizey))

        else:

            sizex, sizey = imglist.GetSize(0)
            self._imageListCheck = imglist

            for ii in xrange(self._imageListCheck.GetImageCount()):
                
                bmp = self._imageListCheck.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayedCheckList.Add(newbmp)

        self._dirty = True

        if imglist:
            self.CalculateLineHeight()


    def AssignImageList(self, imageList):
        """
        Assigns the normal image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetImageList(imageList)
        self._ownsImageListNormal = True


    def AssignStateImageList(self, imageList):
        """
        Assigns the state image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetStateImageList(imageList)
        self._ownsImageListState = True


    def AssignButtonsImageList(self, imageList):
        """
        Assigns the button image list.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetButtonsImageList(imageList)
        self._ownsImageListButtons = True


    def AssignLeftImageList(self, imageList):
        """
        Assigns the image list for L{CustomTreeCtrl} filled with images to be used on
        the leftmost part of the client area. Any item can have a leftmost image associated
        with it.

        :param `imageList`: an instance of `wx.ImageList`.
        """

        self.SetLeftImageList(imageList)
        self._ownsImageListLeft = True


# -----------------------------------------------------------------------------
# helpers
# -----------------------------------------------------------------------------

    def AdjustMyScrollbars(self):
        """ Internal method used to adjust the `wx.PyScrolledWindow` scrollbars. """

        if self._anchor:
        
            x, y = self._anchor.GetSize(0, 0, self)
            y += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x += _PIXELS_PER_UNIT + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            y_pos = self.GetScrollPos(wx.VERTICAL)
            self.SetScrollbars(_PIXELS_PER_UNIT, _PIXELS_PER_UNIT, x/_PIXELS_PER_UNIT, y/_PIXELS_PER_UNIT, x_pos, y_pos)
        
        else:
        
            self.SetScrollbars(0, 0, 0, 0)
    

    def GetLineHeight(self, item):
        """
        Returns the line height for the given item.

        :param `item`: an instance of L{GenericTreeItem}.

        :return: the item height, in pixels.        
        """

        if self.GetAGWWindowStyleFlag() & TR_HAS_VARIABLE_ROW_HEIGHT:
            return int(item.GetHeight())
        else:
            return int(self._lineHeight)


    def DrawVerticalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from top to bottom.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        if hasfocus:
            col2 = self._secondcolour
            col1 = self._firstcolour
        else:
            col2 = self._hilightUnfocusedBrush.GetColour()
            col1 = self._hilightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.height)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        
        for y in xrange(rect.y, rect.y + rect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)                
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x, y, rect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep
        
        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)


    def DrawHorizontalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from left to right.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients

        if hasfocus:
            col2 = self._secondcolour
            col1 = self._firstcolour
        else:
            col2 = self._hilightUnfocusedBrush.GetColour()
            col1 = self._hilightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.width)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for x in xrange(rect.x, rect.x + rect.width):
            currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(x, rect.y, 1, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)
        

    def DrawVistaRectangle(self, dc, rect, hasfocus):
        """
        Draws the selected item(s) with the Windows Vista style.

        :param `dc`: an instance of `wx.DC`;
        :param `wx.Rect` `rect`: the rectangle to be filled with the gradient shading;
        :param bool `hasfocus`: ``True`` if the main L{CustomTreeCtrl} has focus, ``False``
         otherwise.
        """

        if hasfocus:
            
            outer = _rgbSelectOuter
            inner = _rgbSelectInner
            top = _rgbSelectTop
            bottom = _rgbSelectBottom

        else:
            
            outer = _rgbNoFocusOuter
            inner = _rgbNoFocusInner
            top = _rgbNoFocusTop
            bottom = _rgbNoFocusBottom

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()

        bdrRect = wx.Rect(*rect.Get())
        filRect = wx.Rect(*rect.Get())
        filRect.Deflate(1,1)
        
        r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
        r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())

        flrect = float(filRect.height)
        if flrect < 1:
            flrect = self._lineHeight

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        dc.SetPen(wx.TRANSPARENT_PEN)
        
        for y in xrange(filRect.y, filRect.y + filRect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(filRect.x, y, filRect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep
        
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(outer))
        dc.DrawRoundedRectangleRect(bdrRect, 3)
        bdrRect.Deflate(1, 1)
        dc.SetPen(wx.Pen(inner))
        dc.DrawRoundedRectangleRect(bdrRect, 2)

        dc.SetPen(oldpen)
        dc.SetBrush(oldbrush)


    def PaintItem(self, item, dc, level, align):
        """
        Actually draws an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================
        """

        attr = item.GetAttributes()
        
        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        else:
            if item.IsBold():
                dc.SetFont(self._boldFont)
            elif item.IsItalic():
                dc.SetFont(self._italicFont)
        if item.IsHyperText():
            dc.SetFont(self.GetHyperTextFont())
            if item.GetVisited():
                dc.SetTextForeground(self.GetHyperTextVisitedColour())
            else:
                dc.SetTextForeground(self.GetHyperTextNewColour())
                    
        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
        w, h = self.GetClientSize()
        
        image = item.GetCurrentImage()
        checkimage = item.GetCurrentCheckedImage()
        leftimage = _NO_IMAGE
        separator = item.IsSeparator()
        
        if self._imageListLeft:
            leftimage = item.GetLeftImage()
            
        image_w, image_h = 0, 0

        if image != _NO_IMAGE:
        
            if self._imageListNormal:
            
                image_w, image_h = self._imageListNormal.GetSize(image)
                image_w += 4
            
            else:
            
                image = _NO_IMAGE

        if item.GetType() != 0:
            wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())
            wcheck += 4
        else:
            wcheck, hcheck = 0, 0

        if leftimage != _NO_IMAGE:
            l_image_w, l_image_h = self._imageListLeft.GetSize(leftimage)
            
        total_h = self.GetLineHeight(item)
        drawItemBackground = False
            
        if item.IsSelected():
        
            # under mac selections are only a rectangle in case they don't have the focus
            if wx.Platform == "__WXMAC__":
                if not self._hasFocus:
                    dc.SetBrush(wx.TRANSPARENT_BRUSH) 
                    dc.SetPen(wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHT), 1, wx.SOLID)) 
                else:
                    dc.SetBrush(self._hilightBrush) 
            else:
                    dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                    drawItemBackground = True
        else:
            if attr and attr.HasBackgroundColour():
                drawItemBackground = True
                colBg = attr.GetBackgroundColour()
            else:
                colBg = self._backgroundColour
            
            dc.SetBrush(wx.Brush(colBg, wx.SOLID))
            dc.SetPen(wx.TRANSPARENT_PEN)
        
        offset = (self.HasAGWFlag(TR_ROW_LINES) and [1] or [0])[0]
        
        if self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
            x = 0

            itemrect = wx.Rect(x, item.GetY()+offset, w, total_h-offset)
            
            if item.IsSelected():
                if self._usegradients:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                elif self._vistaselection:
                    self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                else:
                    if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                        flags = wx.CONTROL_SELECTED
                        if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                        wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags) 
                    else:
                        dc.DrawRectangleRect(itemrect)
            else:
               if drawItemBackground:
                   minusicon = wcheck + image_w - 2
                   itemrect = wx.Rect(item.GetX()+minusicon,
                                      item.GetY()+offset,
                                      item.GetWidth()-minusicon,
                                      total_h-offset)
                   dc.DrawRectangleRect(itemrect)
                
        else:

            if item.IsSelected():
            
                # If it's selected, and there's an image, then we should
                # take care to leave the area under the image painted in the
                # background colour.

                wnd = item.GetWindow()
                wndx = 0
                if wnd:
                    wndx, wndy = item.GetWindowSize()

                if separator:
                    item_width = w
                else:
                    item_width = item.GetWidth() - image_w - wcheck + 2 - wndx
                    
                itemrect = wx.Rect(item.GetX() + wcheck + image_w - 2,
                                   item.GetY()+offset,
                                   item_width,
                                   total_h-offset)

                if self._usegradients:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                elif self._vistaselection:
                    self.DrawVistaRectangle(dc, itemrect, self._hasFocus)
                else:
                    if wx.Platform in ["__WXGTK2__", "__WXMAC__"]:
                        flags = wx.CONTROL_SELECTED
                        if self._hasFocus: flags = flags | wx.CONTROL_FOCUSED
                        wx.RendererNative.Get().DrawItemSelectionRect(self, dc, itemrect, flags) 
                    else:
                        dc.DrawRectangleRect(itemrect)
                            
            # On GTK+ 2, drawing a 'normal' background is wrong for themes that
            # don't allow backgrounds to be customized. Not drawing the background,
            # except for custom item backgrounds, works for both kinds of theme.
            elif drawItemBackground:

                minusicon = wcheck + image_w - 2

                if separator:
                    item_width = w
                else:
                    item_width = item.GetWidth()-minusicon,
                
                itemrect = wx.Rect(item.GetX()+minusicon,
                                   item.GetY()+offset,
                                   item_width,
                                   total_h-offset)
                                
                if self._usegradients and self._hasFocus:
                    if self._gradientstyle == 0:   # Horizontal
                        self.DrawHorizontalGradient(dc, itemrect, self._hasFocus)
                    else:                          # Vertical
                        self.DrawVerticalGradient(dc, itemrect, self._hasFocus)
                else:
                    dc.DrawRectangleRect(itemrect)
                        
        if image != _NO_IMAGE:
        
            dc.SetClippingRegion(item.GetX(), item.GetY(), wcheck+image_w-2, total_h)
            if item.IsEnabled():
                imglist = self._imageListNormal
            else:
                imglist = self._grayedImageList

            imglist.Draw(image, dc,
                         item.GetX() + wcheck,
                         item.GetY() + ((total_h > image_h) and [(total_h-image_h)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)
            
            dc.DestroyClippingRegion()

        if wcheck:
            if item.IsEnabled():
                imglist = self._imageListCheck
            else:
                imglist = self._grayedCheckList
                
            imglist.Draw(checkimage, dc,
                         item.GetX(),
                         item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)

        if leftimage != _NO_IMAGE:
            if item.IsEnabled():
                imglist = self._imageListLeft
            else:
                imglist = self._grayedImageListLeft

            imglist.Draw(leftimage, dc,
                         4,
                         item.GetY() + ((total_h > l_image_h) and [(total_h-l_image_h)/2] or [0])[0],
                         wx.IMAGELIST_DRAW_TRANSPARENT)

        dc.SetBackgroundMode(wx.TRANSPARENT)
        extraH = ((total_h > text_h) and [(total_h - text_h)/2] or [0])[0]

        textrect = wx.Rect(wcheck + image_w + item.GetX(), item.GetY() + extraH, text_w, text_h)
        
        if not item.IsEnabled():
            foreground = dc.GetTextForeground()
            dc.SetTextForeground(self._disabledColour)
            dc.DrawLabel(item.GetText(), textrect)
            dc.SetTextForeground(foreground)
        else:
            if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
                dc.SetTextForeground(wx.WHITE)
            dc.DrawLabel(item.GetText(), textrect)

        wnd = item.GetWindow()
        if wnd:
            wndx = wcheck + image_w + item.GetX() + text_w + 4
            xa, ya = self.CalcScrolledPosition((0, item.GetY()))
            wndx += xa
            if item.GetHeight() > item.GetWindowSize()[1]:
                ya += (item.GetHeight() - item.GetWindowSize()[1])/2

            if align == 1:
                # Horizontal alignment of windows
                if level in self.absoluteWindows:
                    wndx = self.absoluteWindows[level] + item.GetX() + 2
                    
            elif align == 2:
                # Rightmost alignment of windows
                wndx = w - item.GetWindowSize().x - 2
                
            if not wnd.IsShown():
                wnd.Show()
            if wnd.GetPosition() != (wndx, ya):
                wnd.SetPosition((wndx, ya))

        if separator:
            oldPen = dc.GetPen()

            if item.IsEnabled():
                if attr and attr.HasTextColour():
                    separatorPen = wx.Pen(attr.GetTextColour(), 1)
                else:
                    separatorPen = self._separatorPen
            else:
                separatorPen = wx.GREY_PEN
                    
            dc.SetPen(separatorPen)
            dc.DrawLine(item.GetX()+2, item.GetY()+total_h/2, w, item.GetY()+total_h/2)
            dc.SetPen(oldPen)
            
        # restore normal font
        dc.SetFont(self._normalFont)
        

    # Now y stands for the top of the item, whereas it used to stand for middle !
    def PaintLevel(self, item, dc, level, y, align):
        """
        Paint a level in the hierarchy of L{CustomTreeCtrl}.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `y`: the current vertical position in the `wx.PyScrolledWindow`;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        """

        x = level*self._indent

        left_image_list = 0
        if self._imageListLeft:
            left_image_list += self._imageListLeft.GetBitmap(0).GetWidth()
            
        x += left_image_list
        
        if not self.HasAGWFlag(TR_HIDE_ROOT):
        
            x += self._indent
        
        elif level == 0:
        
            # always expand hidden root
            origY = y
            children = item.GetChildren()
            count = len(children)
            
            if count > 0:
                n = 0
                while n < count:
                    oldY = y
                    y = self.PaintLevel(children[n], dc, 1, y, align)
                    n = n + 1

                if not self.HasAGWFlag(TR_NO_LINES) and self.HasAGWFlag(TR_LINES_AT_ROOT) and count > 0:
                
                    # draw line down to last child
                    origY += self.GetLineHeight(children[0])>>1
                    oldY += self.GetLineHeight(children[n-1])>>1
                    oldPen = dc.GetPen()
                    dc.SetPen(self._dottedPen)
                    dc.DrawLine(3, origY, 3, oldY)
                    dc.SetPen(oldPen)
                
            return y
        
        item.SetX(x+self._spacing)
        item.SetY(y)

        h = self.GetLineHeight(item)
        y_top = y
        y_mid = y_top + (h>>1)
        y += h

        exposed_x = dc.LogicalToDeviceX(0)
        exposed_y = dc.LogicalToDeviceY(y_top)

        if self.IsExposed(exposed_x, exposed_y, 10000, h):  # 10000 = very much
            if wx.Platform == "__WXMAC__":
                # don't draw rect outline if we already have the
                # background colour under Mac
                pen = ((item.IsSelected() and self._hasFocus) and [self._borderPen] or [wx.TRANSPARENT_PEN])[0]
            else:
                pen = self._borderPen

            if item.IsSelected():
                if (wx.Platform == "__WXMAC__" and self._hasFocus):
                    colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
                else:
                    colText = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                attr = item.GetAttributes()
                if attr and attr.HasTextColour():
                    colText = attr.GetTextColour()
                else:
                    colText = self.GetForegroundColour()

            if self._vistaselection:
                colText = wx.BLACK
            
            # prepare to draw
            dc.SetTextForeground(colText)
            dc.SetPen(pen)
            oldpen = pen

            # draw
            self.PaintItem(item, dc, level, align)

            if self.HasAGWFlag(TR_ROW_LINES):
            
                # if the background colour is white, choose a
                # contrasting colour for the lines
                medium_grey = wx.Pen(wx.Colour(200, 200, 200))
                dc.SetPen(((self.GetBackgroundColour() == wx.WHITE) and [medium_grey] or [wx.WHITE_PEN])[0])
                dc.DrawLine(0, y_top, 10000, y_top)
                dc.DrawLine(0, y, 10000, y)
            
            # restore DC objects
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.SetTextForeground(wx.BLACK)

            if not self.HasAGWFlag(TR_NO_LINES):
            
                # draw the horizontal line here
                dc.SetPen(self._dottedPen)
                x_start = x
                if x > self._indent+left_image_list:
                    x_start -= self._indent
                elif self.HasAGWFlag(TR_LINES_AT_ROOT):
                    x_start = 3
                dc.DrawLine(x_start, y_mid, x + self._spacing, y_mid)
                dc.SetPen(oldpen)            

            # should the item show a button?
            if item.HasPlus() and self.HasButtons():
            
                if self._imageListButtons:
                
                    # draw the image button here
                    image_h = 0
                    image_w = 0
                    image = (item.IsExpanded() and [TreeItemIcon_Expanded] or [TreeItemIcon_Normal])[0]
                    if item.IsSelected():
                        image += TreeItemIcon_Selected - TreeItemIcon_Normal

                    image_w, image_h = self._imageListButtons.GetSize(image)
                    xx = x - image_w/2
                    yy = y_mid - image_h/2

                    dc.SetClippingRegion(xx, yy, image_w, image_h)
                    self._imageListButtons.Draw(image, dc, xx, yy,
                                                wx.IMAGELIST_DRAW_TRANSPARENT)
                    dc.DestroyClippingRegion()
                    
                else: # no custom buttons

                    if self.HasAGWFlag(TR_TWIST_BUTTONS):
                        # We draw something like the Mac twist buttons
                        
                        dc.SetPen(wx.BLACK_PEN)
                        dc.SetBrush(self._hilightBrush)
                        button = [wx.Point(), wx.Point(), wx.Point()]
                        
                        if item.IsExpanded():
                            button[0].x = x - 5
                            button[0].y = y_mid - 3
                            button[1].x = x + 5
                            button[1].y = button[0].y
                            button[2].x = x
                            button[2].y = button[0].y + 6
                        else:
                            button[0].x = x - 3
                            button[0].y = y_mid - 5
                            button[1].x = button[0].x
                            button[1].y = y_mid + 5
                            button[2].x = button[0].x + 5
                            button[2].y = y_mid
                        
                        dc.DrawPolygon(button)

                    else:
                        # These are the standard wx.TreeCtrl buttons as wx.RendererNative knows
                        
                        wImage = 9
                        hImage = 9

                        flag = 0

                        if item.IsExpanded():
                            flag |= _CONTROL_EXPANDED
                        if item == self._underMouse:
                            flag |= _CONTROL_CURRENT

                        self._drawingfunction(self, dc, wx.Rect(x - wImage/2, y_mid - hImage/2,wImage, hImage), flag)
                
        if item.IsExpanded():
        
            children = item.GetChildren()
            count = len(children)
            
            if count > 0:
            
                n = 0
                level = level + 1

                while n < count:
                    oldY = y
                    y = self.PaintLevel(children[n], dc, level, y, align)
                    n = n + 1
                    
                if not self.HasAGWFlag(TR_NO_LINES) and count > 0:
                
                    # draw line down to last child
                    oldY += self.GetLineHeight(children[n-1])>>1
                    if self.HasButtons():
                        y_mid += 5

                    # Only draw the portion of the line that is visible, in case it is huge
                    xOrigin, yOrigin = dc.GetDeviceOrigin()
                    yOrigin = abs(yOrigin)
                    width, height = self.GetClientSize()

                    # Move end points to the begining/end of the view?
                    if y_mid < yOrigin:
                        y_mid = yOrigin
                    if oldY > yOrigin + height:
                        oldY = yOrigin + height

                    # after the adjustments if y_mid is larger than oldY then the line
                    # isn't visible at all so don't draw anything
                    if y_mid < oldY:
                        dc.SetPen(self._dottedPen)
                        dc.DrawLine(x, y_mid, x, oldY)
                
        return y


# -----------------------------------------------------------------------------
# wxWidgets callbacks
# -----------------------------------------------------------------------------

    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.PaintEvent` event to be processed.
        """

        dc = wx.PaintDC(self)
        self.PrepareDC(dc)

        if not self._anchor:
            return

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        align = 0
        
        if self.HasAGWFlag(TR_ALIGN_WINDOWS):
            align = 1
        elif self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
            align = 2
            
        y = 2
        self.PaintLevel(self._anchor, dc, 0, y, align)


    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.SizeEvent` event to be processed.
        """

        if self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT) and self._itemWithWindow:
            self.RefreshItemWithWindows()
        else:
            self.RefreshSelected()
            
        event.Skip()
        

    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.EraseEvent` event to be processed.
        """

        # Can we actually do something here (or in OnPaint()) To Handle
        # background images that are stretchable or always centered?
        # I tried but I get enormous flickering...
        
        if not self._backgroundImage:
            event.Skip()
            return

        if self._imageStretchStyle == _StyleTile:
            dc = event.GetDC()

            if not dc:
                dc = wx.ClientDC(self)
                rect = self.GetUpdateRegion().GetBox()
                dc.SetClippingRect(rect)

            self.TileBackground(dc)


    def TileBackground(self, dc):
        """
        Tiles the background image to fill all the available area.

        :param `dc`: an instance of `wx.DC`.

        :todo: Support background images also in stretch and centered modes.        
        """

        sz = self.GetClientSize()
        w = self._backgroundImage.GetWidth()
        h = self._backgroundImage.GetHeight()

        x = 0

        while x < sz.width:
            y = 0

            while y < sz.height:
                dc.DrawBitmap(self._backgroundImage, x, y, True)
                y = y + h

            x = x + w        
        

    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self._hasFocus = True
        self.RefreshSelected()
        event.Skip()


    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for L{CustomTreeCtrl}.

        :param `event`: a `wx.FocusEvent` event to be processed.
        """

        self._hasFocus = False
        self.RefreshSelected()
        event.Skip()


    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for L{CustomTreeCtrl}, sending a
        ``EVT_TREE_KEY_DOWN`` event.

        :param `event`: a `wx.KeyEvent` event to be processed.
        """

        te = TreeEvent(wxEVT_TREE_KEY_DOWN, self.GetId())
        te._evtKey = event
        te.SetEventObject(self)
        
        if self.GetEventHandler().ProcessEvent(te):
            # intercepted by the user code
            return

        if self._current is None or self._key_current is None:
        
            self._current = self._key_current = self.GetFirstVisibleItem()
        
        # how should the selection work for this event?
        is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),
                                                                            event.ShiftDown(), event.CmdDown())

        # + : Expand
        # - : Collaspe
        # * : Expand all/Collapse all
        # ' ' | return : activate
        # up    : go up (not last children!)
        # down  : go down
        # left  : go to parent
        # right : open if parent and go next
        # home  : go to root
        # end   : go to last item without opening parents
        # alnum : start or continue searching for the item with this prefix
        
        keyCode = event.GetKeyCode()

        if keyCode in [ord("+"), wx.WXK_ADD]:       # "+"
            if self._current.HasPlus() and not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):
                self.Expand(self._current)
                
        elif keyCode in [ord("*"), wx.WXK_MULTIPLY]:  # "*"
            if not self.IsExpanded(self._current) and self.IsItemEnabled(self._current):
                # expand all
                self.ExpandAll(self._current)

        elif keyCode in [ord("-"), wx.WXK_SUBTRACT]:  # "-"
            if self.IsExpanded(self._current):
                self.Collapse(self._current)
            
        elif keyCode == wx.WXK_MENU:
            # Use the item's bounding rectangle to determine position for the event
            itemRect = self.GetBoundingRect(self._current, True)
            event = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())
            event._item = self._current
            # Use the left edge, vertical middle
            event._pointDrag = wx.Point(itemRect.GetX(), itemRect.GetY() + itemRect.GetHeight()/2)
            event.SetEventObject(self)
            self.GetEventHandler().ProcessEvent(event)
                
        elif keyCode in [wx.WXK_RETURN, wx.WXK_SPACE, wx.WXK_NUMPAD_ENTER]:

            if not self.IsItemEnabled(self._current):
                event.Skip()
                return
            
            if not event.HasModifiers():
                event = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())
                event._item = self._current
                event.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(event)

                if keyCode == wx.WXK_SPACE and self.GetItemType(self._current) > 0:
                    if self.IsItem3State(self._current):
                        checked = self.GetItem3StateValue(self._current)
                        checked = (checked+1)%3
                    else:
                        checked = not self.IsItemChecked(self._current)
                        
                    self.CheckItem(self._current, checked)
        
            # in any case, also generate the normal key event for this key,
            # even if we generated the ACTIVATED event above: this is what
            # wxMSW does and it makes sense because you might not want to
            # process ACTIVATED event at all and handle Space and Return
            # directly (and differently) which would be impossible otherwise
            event.Skip()

        # up goes to the previous sibling or to the last
        # of its children if it's expanded
        elif keyCode == wx.WXK_UP:
            prev = self.GetPrevSibling(self._key_current)
            if not prev:
                prev = self.GetItemParent(self._key_current)
                if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):
                    return
                
                if prev:
                    current = self._key_current
                    # TODO: Huh?  If we get here, we'd better be the first child of our parent.  How else could it be?
                    if current == self.GetFirstChild(prev)[0] and self.IsItemEnabled(prev):
                        # otherwise we return to where we came from
                        self.DoSelectItem(prev, unselect_others, extended_select)
                        self._key_current = prev
                
            else:
                current = self._key_current
                
                # We are going to another parent node
                while self.IsExpanded(prev) and self.HasChildren(prev):
                    child = self.GetLastChild(prev)
                    if child:
                        prev = child
                        current = prev
                
                # Try to get the previous siblings and see if they are active
                while prev and not self.IsItemEnabled(prev):
                    prev = self.GetPrevSibling(prev)

                if not prev:
                    # No previous siblings active: go to the parent and up
                    prev = self.GetItemParent(current)
                    while prev and not self.IsItemEnabled(prev):
                        prev = self.GetItemParent(prev)
                        
                if prev:
                    self.DoSelectItem(prev, unselect_others, extended_select)
                    self._key_current = prev

        # left arrow goes to the parent
        elif keyCode == wx.WXK_LEFT:
            
            prev = self.GetItemParent(self._current)
            if prev == self.GetRootItem() and self.HasAGWFlag(TR_HIDE_ROOT):            
                # don't go to root if it is hidden
                prev = self.GetPrevSibling(self._current)

            if self.IsExpanded(self._current):
                self.Collapse(self._current)
            else:
                if prev and self.IsItemEnabled(prev):
                    self.DoSelectItem(prev, unselect_others, extended_select)
                
        elif keyCode == wx.WXK_RIGHT:
            # this works the same as the down arrow except that we
            # also expand the item if it wasn't expanded yet
            if self.IsExpanded(self._current) and self.HasChildren(self._current):
                child, cookie = self.GetFirstChild(self._key_current)
                if self.IsItemEnabled(child):
                    self.DoSelectItem(child, unselect_others, extended_select)
                    self._key_current = child
            else:
                self.Expand(self._current)
            # fall through

        elif keyCode == wx.WXK_DOWN:
            if self.IsExpanded(self._key_current) and self.HasChildren(self._key_current):

                child = self.GetNextActiveItem(self._key_current)
                
                if child:
                    self.DoSelectItem(child, unselect_others, extended_select)
                    self._key_current = child   
                
            else:
                
                next = self.GetNextSibling(self._key_current)
    
                if not next:
                    current = self._key_current
                    while current and not next:
                        current = self.GetItemParent(current)
                        if current:
                            next = self.GetNextSibling(current)
                            if not next or not self.IsItemEnabled(next):
                                next = None

                else:
                    while next and not self.IsItemEnabled(next):
                        next = self.GetNext(next)
                    
                if next:
                    self.DoSelectItem(next, unselect_others, extended_select)
                    self._key_current = next
                    

        # <End> selects the last visible tree item
        elif keyCode == wx.WXK_END:
            
            last = self.GetRootItem()

            while last and self.IsExpanded(last):
            
                lastChild = self.GetLastChild(last)

                # it may happen if the item was expanded but then all of
                # its children have been deleted - so IsExpanded() returned
                # true, but GetLastChild() returned invalid item
                if not lastChild:
                    break

                last = lastChild
            
            if last and self.IsItemEnabled(last):
            
                self.DoSelectItem(last, unselect_others, extended_select)
                
        # <Home> selects the root item
        elif keyCode == wx.WXK_HOME:
                
            prev = self.GetRootItem()
            
            if not prev:
                return

            if self.HasAGWFlag(TR_HIDE_ROOT):
                prev, cookie = self.GetFirstChild(prev)
                if not prev:
                    return

            if self.IsItemEnabled(prev):
                self.DoSelectItem(prev, unselect_others, extended_select)
        
        else:
            
            if not event.HasModifiers() and ((keyCode >= ord('0') and keyCode <= ord('9')) or \
                                             (keyCode >= ord('a') and keyCode <= ord('z')) or \
                                             (keyCode >= ord('A') and keyCode <= ord('Z'))):
            
                # find the next item starting with the given prefix
                ch = chr(keyCode)
                id = self.FindItem(self._current, self._findPrefix + ch)
                
                if not id:
                    # no such item
                    return

                if self.IsItemEnabled(id):                
                    self.SelectItem(id)
                self._findPrefix += ch

                # also start the timer to reset the current prefix if the user
                # doesn't press any more alnum keys soon -- we wouldn't want
                # to use this prefix for a new item search
                if not self._findTimer:
                    self._findTimer = TreeFindTimer(self)
                
                self._findTimer.Start(_DELAY, wx.TIMER_ONE_SHOT)
            
            else:
            
                event.Skip()


    def GetNextActiveItem(self, item, down=True):
        """
        Returns the next active item. Used Internally at present.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `down`: ``True`` to search downwards in the hierarchy for an active item,
         ``False`` to search upwards.

        :return: An instance of L{GenericTreeItem} if an active item has been found or
         ``None`` if none has been found.
        """
        
        if down:
            sibling = self.GetNextSibling
        else:
            sibling = self.GetPrevSibling
                
        if self.GetItemType(item) == 2 and not self.IsItemChecked(item):
            # Is an unchecked radiobutton... all its children are inactive
            # try to get the next/previous sibling
            found = 0                 

            while 1:
                child = sibling(item)
                if (child and self.IsItemEnabled(child)) or not child:
                    break
                item = child

        else:
            # Tha's not a radiobutton... but some of its children can be
            # inactive
            child, cookie = self.GetFirstChild(item)
            while child and not self.IsItemEnabled(child):
                child, cookie = self.GetNextChild(item, cookie)
                
        if child and self.IsItemEnabled(child):
            return child
            
        return None
    

    def HitTest(self, point, flags=0):
        """
        Calculates which (if any) item is under the given point, returning the tree item
        at this point plus extra information flags.

        :param `point`: an instance of `wx.Point`, a point to test for hits;
        :param integer `flags`: a bitlist of the following values:

         ================================== =============== =================================
         HitTest Flags                      Hex Value       Description
         ================================== =============== =================================
         ``TREE_HITTEST_ABOVE``                         0x1 Above the client area
         ``TREE_HITTEST_BELOW``                         0x2 Below the client area
         ``TREE_HITTEST_NOWHERE``                       0x4 No item has been hit
         ``TREE_HITTEST_ONITEMBUTTON``                  0x8 On the button associated to an item
         ``TREE_HITTEST_ONITEMICON``                   0x10 On the icon associated to an item
         ``TREE_HITTEST_ONITEMINDENT``                 0x20 On the indent associated to an item
         ``TREE_HITTEST_ONITEMLABEL``                  0x40 On the label (string) associated to an item
         ``TREE_HITTEST_ONITEM``                       0x50 Anywhere on the item
         ``TREE_HITTEST_ONITEMRIGHT``                  0x80 On the right of the label associated to an item
         ``TREE_HITTEST_TOLEFT``                      0x200 On the left of the client area
         ``TREE_HITTEST_TORIGHT``                     0x400 On the right of the client area
         ``TREE_HITTEST_ONITEMUPPERPART``             0x800 On the upper part (first half) of the item
         ``TREE_HITTEST_ONITEMLOWERPART``            0x1000 On the lower part (second half) of the item
         ``TREE_HITTEST_ONITEMCHECKICON``            0x2000 On the check/radio icon, if present
         ================================== =============== =================================

        :return: A tuple with the first value being an instance of L{GenericTreeItem} or ``None`` if
         no item has been hit-tested, and as second value an integer parameter `flag`.

        :note: both the item (if any, ``None`` otherwise) and the `flags` are always returned as a tuple.
        """
        
        w, h = self.GetSize()
        flags = 0
        
        if point.x < 0:
            flags |= TREE_HITTEST_TOLEFT
        if point.x > w:
            flags |= TREE_HITTEST_TORIGHT
        if point.y < 0:
            flags |= TREE_HITTEST_ABOVE
        if point.y > h:
            flags |= TREE_HITTEST_BELOW

        if flags:
            return None, flags
 
        if self._anchor == None:
            flags = TREE_HITTEST_NOWHERE
            return None, flags
        
        hit, flags = self._anchor.HitTest(self.CalcUnscrolledPosition(point), self, flags, 0)

        if hit == None:        
            flags = TREE_HITTEST_NOWHERE
            return None, flags

        if not self.IsItemEnabled(hit):
            return None, flags

        return hit, flags


    def GetBoundingRect(self, item, textOnly=False):
        """
        Retrieves the rectangle bounding the item.

        :param `item`: an instance of L{GenericTreeItem};
        :param bool `textOnly`: if ``True``, only the rectangle around the item's label will
         be returned, otherwise the item's image is also taken into account.

        :return: An instance of `wx.Rect`.
        
        :note: The rectangle coordinates are logical, not physical ones. So, for example,
         the `x` coordinate may be negative if the tree has a horizontal scrollbar and its
         position is not ``0``.
        """
    
        i = item

        startX, startY = self.GetViewStart()
        rect = wx.Rect()

        rect.x = i.GetX() - startX*_PIXELS_PER_UNIT
        rect.y = i.GetY() - startY*_PIXELS_PER_UNIT
        rect.width = i.GetWidth()
        rect.height = self.GetLineHeight(i)

        return rect


    def Edit(self, item):
        """
        Internal function. Starts the editing of an item label, sending a
        ``EVT_TREE_BEGIN_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem}.

        :warning: Separator-type items can not be edited.        
        """

        if item.IsSeparator():
            return
        
        te = TreeEvent(wxEVT_TREE_BEGIN_LABEL_EDIT, self.GetId())
        te._item = item
        te.SetEventObject(self)
        if self.GetEventHandler().ProcessEvent(te) and not te.IsAllowed():
            # vetoed by user
            return
    
        # We have to call this here because the label in
        # question might just have been added and no screen
        # update taken place.
        if self._dirty:
            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Update()
            else:
                wx.YieldIfNeeded()

        if self._editCtrl != None and item != self._editCtrl.item():
            self._editCtrl.StopEditing()

        self._editCtrl = TreeTextCtrl(self, item=item)
        self._editCtrl.SetFocus()

 
    def GetEditControl(self):
        """
        Returns a pointer to the edit L{TreeTextCtrl} if the item is being edited or
        ``None`` otherwise (it is assumed that no more than one item may be edited
        simultaneously).        
        """
        
        return self._editCtrl


    def OnAcceptEdit(self, item, value):
        """
        Called by L{TreeTextCtrl}, to accept the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem};
        :param string `value`: the new value of the item label.

        :return: ``True`` if the editing has not been vetoed, ``False`` otherwise.        
        """

        le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())
        le._item = item
        le.SetEventObject(self)
        le._label = value
        le._editCancelled = False

        return not self.GetEventHandler().ProcessEvent(le) or le.IsAllowed()
    

    def OnCancelEdit(self, item):
        """
        Called by L{TreeTextCtrl}, to cancel the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `item`: an instance of L{GenericTreeItem}.        
        """

        # let owner know that the edit was cancelled
        le = TreeEvent(wxEVT_TREE_END_LABEL_EDIT, self.GetId())
        le._item = item
        le.SetEventObject(self)
        le._label = ""
        le._editCancelled = True

        self.GetEventHandler().ProcessEvent(le)


    def OnEditTimer(self):
        """ The timer for editing has expired. Start editing. """
        
        self.Edit(self._current)


    def OnMouse(self, event):
        """
        Handles a bunch of ``wx.EVT_MOUSE_EVENTS`` events for L{CustomTreeCtrl}.

        :param `event`: a `wx.MouseEvent` event to be processed.
        """

        if not self._anchor:
            return

        pt = self.CalcUnscrolledPosition(event.GetPosition())

        # Is the mouse over a tree item button?
        flags = 0
        thisItem, flags = self._anchor.HitTest(pt, self, flags, 0)
        underMouse = thisItem
        underMouseChanged = underMouse != self._underMouse

        if underMouse and (flags & TREE_HITTEST_ONITEM) and not event.LeftIsDown() and \
           not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
            underMouse = underMouse
        else:
            underMouse = None

        if underMouse != self._underMouse:
            if self._underMouse:
                # unhighlight old item
                self._underMouse = None
             
            self._underMouse = underMouse

        # Determines what item we are hovering over and need a tooltip for
        hoverItem = thisItem

        # We do not want a tooltip if we are dragging, or if the edit timer is running
        if underMouseChanged and not self._isDragging and (not self._editTimer or not self._editTimer.IsRunning()):
            
            if hoverItem is not None:
                # Ask the tree control what tooltip (if any) should be shown
                hevent = TreeEvent(wxEVT_TREE_ITEM_GETTOOLTIP, self.GetId())
                hevent._item = hoverItem
                hevent.SetEventObject(self)

                if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():
                    self.SetToolTip(hevent._label)

                if hoverItem.IsHyperText() and (flags & TREE_HITTEST_ONITEMLABEL) and hoverItem.IsEnabled():
                    self.SetCursor(wx.StockCursor(wx.CURSOR_HAND))
                    self._isonhyperlink = True
                else:
                    if self._isonhyperlink:
                        self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
                        self._isonhyperlink = False
                
        # we process left mouse up event (enables in-place edit), right down
        # (pass to the user code), left dbl click (activate item) and
        # dragging/moving events for items drag-and-drop

        if not (event.LeftDown() or event.LeftUp() or event.RightDown() or event.LeftDClick() or \
                event.Dragging() or ((event.Moving() or event.RightUp()) and self._isDragging)):
        
            event.Skip()
            return
                    
        flags = 0
        item, flags = self._anchor.HitTest(pt, self, flags, 0)

        if event.Dragging() and not self._isDragging and ((flags & TREE_HITTEST_ONITEMICON) or (flags & TREE_HITTEST_ONITEMLABEL)):
        
            if self._dragCount == 0:
                self._dragStart = pt

            self._countDrag = 0
            self._dragCount = self._dragCount + 1

            if self._dragCount != 3:
                # wait until user drags a bit further...
                return
            
            command = (event.RightIsDown() and [wxEVT_TREE_BEGIN_RDRAG] or [wxEVT_TREE_BEGIN_DRAG])[0]

            nevent = TreeEvent(command, self.GetId())
            nevent._item = self._current
            nevent.SetEventObject(self)
            newpt = self.CalcScrolledPosition(pt)
            nevent.SetPoint(newpt)

            # by default the dragging is not supported, the user code must
            # explicitly allow the event for it to take place
            nevent.Veto()

            if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed():
                
                # we're going to drag this item
                self._isDragging = True

                # remember the old cursor because we will change it while
                # dragging
                self._oldCursor = self._cursor

                # in a single selection control, hide the selection temporarily
                if not (self.GetAGWWindowStyleFlag() & TR_MULTIPLE):
                    self._oldSelection = self.GetSelection()

                    if self._oldSelection:
                    
                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)
                else:
                    selections = self.GetSelections()
                    if len(selections) == 1:
                        self._oldSelection = selections[0]
                        self._oldSelection.SetHilight(False)
                        self.RefreshLine(self._oldSelection)

                if self._dragImage:
                    del self._dragImage

                # Create the custom draw image from the icons and the text of the item                    
                self._dragImage = DragImage(self, self._current)
                self._dragImage.BeginDrag(wx.Point(0,0), self)
                self._dragImage.Show()
                self._dragImage.Move(self.CalcScrolledPosition(pt))
            
        elif event.Dragging() and self._isDragging:

            self._dragImage.Move(self.CalcScrolledPosition(pt))

            if self._countDrag == 0 and item:
                self._oldItem = item

            if item != self._dropTarget:
                    
                # unhighlight the previous drop target
                if self._dropTarget:
                    self._dropTarget.SetHilight(False)
                    self.RefreshLine(self._dropTarget)
                if item:
                    item.SetHilight(True)
                    self.RefreshLine(item)
                    self._countDrag = self._countDrag + 1
                self._dropTarget = item

                self.Update()

            if self._countDrag >= 3:
                # Here I am trying to avoid ugly repainting problems... hope it works
                self.RefreshLine(self._oldItem)
                self._countDrag = 0

        elif (event.LeftUp() or event.RightUp()) and self._isDragging:

            if self._dragImage:
                self._dragImage.EndDrag()

            if self._dropTarget:
                self._dropTarget.SetHilight(False)
                
            if self._oldSelection:
            
                self._oldSelection.SetHilight(True)
                self.RefreshLine(self._oldSelection)
                self._oldSelection = None
            
            # generate the drag end event
            event = TreeEvent(wxEVT_TREE_END_DRAG, self.GetId())
            event._item = item
            event._pointDrag = self.CalcScrolledPosition(pt)
            event.SetEventObject(self)

            self.GetEventHandler().ProcessEvent(event)

            self._isDragging = False
            self._dropTarget = None
            
            self.SetCursor(self._oldCursor)

            if wx.Platform in ["__WXMSW__", "__WXMAC__"]:
                self.Refresh()
            else:
                # Probably this is not enough on GTK. Try a Refresh() if it does not work.
                wx.YieldIfNeeded()
        
        else:

            # If we got to this point, we are not dragging or moving the mouse.
            # Because the code in carbon/toplevel.cpp will only set focus to the tree
            # if we skip for EVT_LEFT_DOWN, we MUST skip this event here for focus to work.
            # We skip even if we didn't hit an item because we still should
            # restore focus to the tree control even if we didn't exactly hit an item.
            if event.LeftDown():
                self._hasFocus = True
                self.SetFocusIgnoringChildren()
                event.Skip()
            
            # here we process only the messages which happen on tree items

            self._dragCount = 0

            if item == None:
                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()
                return  # we hit the blank area

            if event.RightDown():
                
                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()

                self._hasFocus = True
                self.SetFocusIgnoringChildren()
                    
                # If the item is already selected, do not update the selection.
                # Multi-selections should not be cleared if a selected item is clicked.
                if not self.IsSelected(item):
                
                    self.DoSelectItem(item, True, False)

                nevent = TreeEvent(wxEVT_TREE_ITEM_RIGHT_CLICK, self.GetId())
                nevent._item = item
                nevent._pointDrag = self.CalcScrolledPosition(pt)
                nevent.SetEventObject(self)
                event.Skip(not self.GetEventHandler().ProcessEvent(nevent))

                # Consistent with MSW (for now), send the ITEM_MENU *after*
                # the RIGHT_CLICK event. TODO: This behaviour may change.
                nevent2 = TreeEvent(wxEVT_TREE_ITEM_MENU, self.GetId())
                nevent2._item = item
                nevent2._pointDrag = self.CalcScrolledPosition(pt)
                nevent2.SetEventObject(self)
                self.GetEventHandler().ProcessEvent(nevent2)
            
            elif event.LeftUp():
            
                # this facilitates multiple-item drag-and-drop

                if self.HasAGWFlag(TR_MULTIPLE):
                
                    selections = self.GetSelections()

                    if len(selections) > 1 and not event.CmdDown() and not event.ShiftDown():
                    
                        self.DoSelectItem(item, True, False)
                    
                if self._lastOnSame:
                
                    if item == self._current and (flags & TREE_HITTEST_ONITEMLABEL) and self.HasAGWFlag(TR_EDIT_LABELS):
                    
                        if self._editTimer:
                        
                            if self._editTimer.IsRunning():
                                
                                self._editTimer.Stop()
                        
                        else:
                        
                            self._editTimer = TreeEditTimer(self)
                        
                        self._editTimer.Start(_DELAY, True)
                    
                    self._lastOnSame = False
                
            
            else: # !RightDown() && !LeftUp() ==> LeftDown() || LeftDClick()

                if not item or not item.IsEnabled():
                    if self._editCtrl != None and item != self._editCtrl.item():
                        self._editCtrl.StopEditing()
                    return

                if self._editCtrl != None and item != self._editCtrl.item():
                    self._editCtrl.StopEditing()

                self._hasFocus = True
                self.SetFocusIgnoringChildren()
                
                if event.LeftDown():
                
                    self._lastOnSame = item == self._current
                    
                if flags & TREE_HITTEST_ONITEMBUTTON:
                
                    # only toggle the item for a single click, double click on
                    # the button doesn't do anything (it toggles the item twice)
                    if event.LeftDown():
                    
                        self.Toggle(item)
                    
                    # don't select the item if the button was clicked
                    return

                if item.GetType() > 0 and (flags & TREE_HITTEST_ONITEMCHECKICON):

                    if event.LeftDown():
                        if flags & TREE_HITTEST_ONITEM and self.HasAGWFlag(TR_FULL_ROW_HIGHLIGHT):
                            self.DoSelectItem(item, not self.HasAGWFlag(TR_MULTIPLE))

                        if self.IsItem3State(item):
                            checked = self.GetItem3StateValue(item)
                            checked = (checked+1)%3
                        else:
                            checked = not self.IsItemChecked(item)
                            
                        self.CheckItem(item, checked)
                        
                    return                                            

                # clear the previously selected items, if the
                # user clicked outside of the present selection.
                # otherwise, perform the deselection on mouse-up.
                # this allows multiple drag and drop to work.
                # but if Cmd is down, toggle selection of the clicked item
                if not self.IsSelected(item) or event.CmdDown():

                    if flags & TREE_HITTEST_ONITEM:
                        # how should the selection work for this event?
                        if item.IsHyperText():
                            self.SetItemVisited(item, True)
                        
                        is_multiple, extended_select, unselect_others = EventFlagsToSelType(self.GetAGWWindowStyleFlag(),
                                                                                            event.ShiftDown(),
                                                                                            event.CmdDown())

                        self.DoSelectItem(item, unselect_others, extended_select)

                # Handle hyperlink items... which are a bit odd sometimes
                elif self.IsSelected(item) and item.IsHyperText():
                    self.HandleHyperLink(item)
                    
                # For some reason, Windows isn't recognizing a left double-click,
                # so we need to simulate it here.  Allow 200 milliseconds for now.
                if event.LeftDClick():
                
                    # double clicking should not start editing the item label
                    if self._editTimer:
                        self._editTimer.Stop()

                    self._lastOnSame = False

                    # send activate event first
                    nevent = TreeEvent(wxEVT_TREE_ITEM_ACTIVATED, self.GetId())
                    nevent._item = item
                    nevent._pointDrag = self.CalcScrolledPosition(pt)
                    nevent.SetEventObject(self)
                    if not self.GetEventHandler().ProcessEvent(nevent):
                    
                        # if the user code didn't process the activate event,
                        # handle it ourselves by toggling the item when it is
                        # double clicked
##                        if item.HasPlus():
                        self.Toggle(item)
                        

    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call `wx.Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        # Check if we need to select the root item
        # because nothing else has been selected.
        # Delaying it means that we can invoke event handlers
        # as required, when a first item is selected.
        if not self.HasAGWFlag(TR_MULTIPLE) and not self.GetSelection():
        
            if self._select_me:
                self.SelectItem(self._select_me)
            elif self.GetRootItem():
                self.SelectItem(self.GetRootItem())
        
        # after all changes have been done to the tree control,
        # we actually redraw the tree when everything is over

        if not self._dirty:
            return
        if self._freezeCount:
            return

        self._dirty = False

        self.CalculatePositions()
        self.Refresh()
        self.AdjustMyScrollbars()

#        event.Skip()        


    def CalculateSize(self, item, dc, level=-1, align=0):
        """
        Calculates overall position and size of an item.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        """

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        else:
            if item.IsBold():
                dc.SetFont(self._boldFont)
            elif item.IsItalic():
                dc.SetFont(self._italicFont)
            else:
                dc.SetFont(self._normalFont)

        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText())
        text_h+=2

        # restore normal font
        dc.SetFont(self._normalFont)

        image_w, image_h = 0, 0
        image = item.GetCurrentImage()

        if image != _NO_IMAGE:
        
            if self._imageListNormal:
            
                image_w, image_h = self._imageListNormal.GetSize(image)
                image_w += 4

        total_h = ((image_h > text_h) and [image_h] or [text_h])[0]

        checkimage = item.GetCurrentCheckedImage()
        if checkimage is not None:
            wcheck, hcheck = self._imageListCheck.GetSize(checkimage)
            wcheck += 4
        else:
            wcheck = 0           

        if total_h < 30:
            total_h += 2            # at least 2 pixels
        else:
            total_h += total_h/10   # otherwise 10% extra spacing

        if total_h > self._lineHeight:
            self._lineHeight = total_h

        wnd = item.GetWindow()
        if not wnd:
            totalWidth = image_w+text_w+wcheck+2
            totalHeight = total_h
        else:
            totalWidth = item.GetWindowSize()[0]+image_w+text_w+wcheck+2
            totalHeight = max(total_h, item.GetWindowSize()[1])

        if level >= 0 and wnd:
            if align == 0:
                if level in self.absoluteWindows:
                    self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)
                else:
                    self.absoluteWindows[level] = image_w+text_w+wcheck+2
            elif align == 1:
                self.absoluteWindows[level] = max(self.absoluteWindows[level], image_w+text_w+wcheck+2)

        if item.IsSeparator():
            totalWidth = self.GetClientSize()[0]
            totalHeight = total_h
            
        item.SetWidth(totalWidth)
        item.SetHeight(totalHeight)


    def CalculateLevel(self, item, dc, level, y, align=0):
        """
        Calculates the level of an item inside the tree hierarchy.

        :param `item`: an instance of L{GenericTreeItem};
        :param `dc`: an instance of `wx.DC`;
        :param integer `level`: the item level in the tree hierarchy;
        :param integer `y`: the current vertical position inside the `wx.PyScrolledWindow`;
        :param integer `align`: an integer specifying the alignment type:

         =============== =========================================
         `align` Value   Description
         =============== =========================================
                0        No horizontal alignment of windows (in items with windows).
                1        Windows (in items with windows) are aligned at the same horizontal position.
                2        Windows (in items with windows) are aligned at the rightmost edge of L{CustomTreeCtrl}.
         =============== =========================================

        :return: The new `y` vertical position inside the `wx.PyScrolledWindow`.
        """

        x = level*self._indent
        
        if not self.HasAGWFlag(TR_HIDE_ROOT):
        
            x += self._indent
        
        elif level == 0:
        
            # a hidden root is not evaluated, but its
            # children are always calculated
            children = item.GetChildren()
            count = len(children)
            level = level + 1
            for n in xrange(count):
                y = self.CalculateLevel(children[n], dc, level, y, align)  # recurse
                
            return y
        
        self.CalculateSize(item, dc, level, align)

        # set its position
        item.SetX(x+self._spacing)
        item.SetY(y)
        y += self.GetLineHeight(item)

        if not item.IsExpanded():
            # we don't need to calculate collapsed branches
            return y

        children = item.GetChildren()
        count = len(children)
        level = level + 1
        for n in xrange(count):
            y = self.CalculateLevel(children[n], dc, level, y, align)  # recurse
        
        return y
    

    def CalculatePositions(self):
        """ Calculates all the positions of the visible items. """

        if not self._anchor:
            return

        self.absoluteWindows = {}
        
        dc = wx.ClientDC(self)
        self.PrepareDC(dc)

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)
        y = 2
        y = self.CalculateLevel(self._anchor, dc, 0, y) # start recursion
        
        if self.HasAGWFlag(TR_ALIGN_WINDOWS) or self.HasAGWFlag(TR_ALIGN_WINDOWS_RIGHT):
            align = (self.HasAGWFlag(TR_ALIGN_WINDOWS) and [1] or [2])[0]
            y = 2
            y = self.CalculateLevel(self._anchor, dc, 0, y, align) # start recursion


    def RefreshSubtree(self, item):
        """
        Refreshes a damaged subtree of an item.
        
        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._dirty:
            return
        if self._freezeCount:
            return

        client = self.GetClientSize()

        rect = wx.Rect()
        x, rect.y = self.CalcScrolledPosition(0, item.GetY())
        rect.width = client.x
        rect.height = client.y

        self.Refresh(True, rect)
        self.AdjustMyScrollbars()


    def RefreshLine(self, item):
        """
        Refreshes a damaged item line.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._dirty:
            return
        if self._freezeCount:
            return

        rect = wx.Rect()
        x, rect.y = self.CalcScrolledPosition(0, item.GetY())
        rect.width = self.GetClientSize().x
        rect.height = self.GetLineHeight(item)

        self.Refresh(True, rect)


    def RefreshSelected(self):
        """ Refreshes a damaged selected item line. """

        if self._freezeCount:
            return

        # TODO: this is awfully inefficient, we should keep the list of all
        #       selected items internally, should be much faster
        if self._anchor:
            self.RefreshSelectedUnder(self._anchor)


    def RefreshSelectedUnder(self, item):
        """
        Refreshes the selected items under the given item.

        :param `item`: an instance of L{GenericTreeItem}.
        """

        if self._freezeCount:
            return

        if item.IsSelected():
            self.RefreshLine(item)

        children = item.GetChildren()
        for child in children:
            self.RefreshSelectedUnder(child)
    

    def RefreshItemWithWindows(self, item=None):
        """
        Refreshes the items with which a window is associated.

        :param `item`: an instance of L{GenericTreeItem}. If `item` is ``None``, then the
         recursive refresh starts from the root node.
         
        :note: This method is called only if the style ``TR_ALIGN_WINDOWS_RIGHT`` is used.
        """

        if self._freezeCount:
            return

        if item is None:
            if self._anchor:
                self.RefreshItemWithWindows(self._anchor)
                return

        wnd = item.GetWindow()            
        if wnd and wnd.IsShown():
            self.RefreshLine(item)

        children = item.GetChildren()
        for child in children:
            self.RefreshItemWithWindows(child)


    def Freeze(self):
        """
        Freeze L{CustomTreeCtrl}.

        Freezes the window or, in other words, prevents any updates from taking place
        on screen, the window is not redrawn at all. L{Thaw} must be called to reenable
        window redrawing. Calls to these two functions may be nested.

        :note: This method is useful for visual appearance optimization (for example,
         it is a good idea to use it before doing many large text insertions in a row
         into a `wx.TextCtrl` under wxGTK) but is not implemented on all platforms nor
         for all controls so it is mostly just a hint to wxWidgets and not a mandatory
         directive.
        """

        self._freezeCount = self._freezeCount + 1


    def Thaw(self):
        """
        Thaw L{CustomTreeCtrl}.

        Reenables window updating after a previous call to L{Freeze}. To really thaw the
        control, it must be called exactly the same number of times as L{Freeze}.

        :raise: `Exception` if L{Thaw} has been called without an un-matching L{Freeze}.        
        """

        if self._freezeCount == 0:
            raise Exception("\nERROR: Thawing Unfrozen Tree Control?")

        self._freezeCount = self._freezeCount - 1
        
        if not self._freezeCount:
            self.Refresh()
    

    # ----------------------------------------------------------------------------
    # changing colours: we need to refresh the tree control
    # ----------------------------------------------------------------------------

    def SetBackgroundColour(self, colour):
        """
        Changes the background colour of L{CustomTreeCtrl}.

        :param `colour`: the colour to be used as the background colour, pass
         `wx.NullColour` to reset to the default colour.

        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
         the new colour, ``True`` otherwise.
         
        :note: The background colour is usually painted by the default `wx.EraseEvent`
         event handler function under Windows and automatically under GTK.

        :note: Setting the background colour does not cause an immediate refresh, so
         you may wish to call `wx.Window.ClearBackground` or `wx.Window.Refresh` after
         calling this function.

        :note: Overridden from `wx.PyScrolledWindow`.         
        """

        if not wx.PyScrolledWindow.SetBackgroundColour(self, colour):
            return False

        if self._freezeCount:
            return True

        self.Refresh()

        return True


    def SetForegroundColour(self, colour):
        """
        Changes the foreground colour of L{CustomTreeCtrl}.

        :param `colour`: the colour to be used as the foreground colour, pass
         `wx.NullColour` to reset to the default colour.

        :return: ``False`` if the underlying `wx.PyScrolledWindow` does not accept
         the new colour, ``True`` otherwise.

        :note: Overridden from `wx.PyScrolledWindow`.         
        """

        if not wx.PyScrolledWindow.SetForegroundColour(self, colour):
            return False

        if self._freezeCount:
            return True

        self.Refresh()

        return True

    
    def OnGetToolTip(self, event):
        """
        Process the tooltip event, to speed up event processing. Does not actually
        get a tooltip.

        :param `event`: a L{TreeEvent} event to be processed.        
        """

        event.Veto()


    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same size
        as it would have after a call to `Fit()`.

        :return: An instance of `wx.Size`.
        
        :note: Overridden from `wx.PyScrolledWindow`.
        """
                
        # something is better than nothing...
        # 100x80 is what the MSW version will get from the default
        # wxControl::DoGetBestSize

        return wx.Size(100, 80)

        
    def GetMaxWidth(self, respect_expansion_state=True):
        """
        Returns the maximum width of the L{CustomTreeCtrl}.
        
        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
         children) will be measured. Otherwise all the items are expanded and
         their width measured.

        :return: the maximum width of L{CustomTreeCtrl}, in pixels.         
        """

        self.Freeze()
        
        root = self.GetRootItem()
        rect = self.GetBoundingRect(root, True)

        # It looks like the space between the "+" and the node
        # rect occupies 4 pixels approximatively
        maxwidth = rect.x + rect.width + 4
        lastheight = rect.y + rect.height
        
        if not self.IsExpanded(root):
            if respect_expansion_state:
                return maxwidth

        if not respect_expansion_state:
            self.ExpandAll()

        maxwidth, lastheight = self.RecurseOnChildren(root, maxwidth, respect_expansion_state)

        self.Thaw()
        
        return maxwidth
    

    def RecurseOnChildren(self, item, maxwidth, respect_expansion_state):
        """
        Recurses over all the children of the spcified items, calculating their
        maximum width.

        :param `item`: an instance of L{GenericTreeItem};
        :param integer `maxwidth`: the current maximum width for L{CustomTreeCtrl}, in pixels;
        :param bool `respect_expansion_state`: if ``True``, only the expanded items (and their
         children) will be measured. Otherwise all the items are expanded and
         their width measured.

        :return: A tuple containing the maximum width and item height, in pixels.         
        """
        
        child, cookie = self.GetFirstChild(item)
        lastheight = 0

        while child:

            rect = self.GetBoundingRect(child, True)
            
            # It looks like the space between the "+" and the node
            # rect occupies 4 pixels approximatively
            maxwidth = max(maxwidth, rect.x + rect.width + 4)
            lastheight = rect.y + rect.height
            
            if self.IsExpanded(child) or not respect_expansion_state:
                maxwidth, lastheight = self.RecurseOnChildren(child, maxwidth, respect_expansion_state)
            
            child, cookie = self.GetNextChild(item, cookie)

        return maxwidth, lastheight

    
    def GetClassDefaultAttributes(self):
        """
        Returns the default font and colours which are used by the control. This is
        useful if you want to use the same font or colour in your own control as in
        a standard control -- which is a much better idea than hard coding specific
        colours or fonts which might look completely out of place on the users system,
        especially if it uses themes.

        This static method is "overridden'' in many derived classes and so calling,
        for example, `wx.Button.GetClassDefaultAttributes()` will typically return the
        values appropriate for a button which will be normally different from those
        returned by, say, `wx.ListCtrl.GetClassDefaultAttributes()`.

        :return: An instance of `wx.VisualAttributes`.
        
        :note: The `wx.VisualAttributes` structure has at least the fields `font`,
         `colFg` and `colBg`. All of them may be invalid if it was not possible to
         determine the default control appearance or, especially for the background
         colour, if the field doesn't make sense as is the case for `colBg` for the
         controls with themed background.

        :note: Overridden from `wx.PyControl`.         
        """

        attr = wx.VisualAttributes()
        attr.colFg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        attr.colBg = wx.SystemSettings_GetColour(wx.SYS_COLOUR_LISTBOX)
        attr.font  = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        return attr

    GetClassDefaultAttributes = classmethod(GetClassDefaultAttributes)