File: hypertreelist.py

package info (click to toggle)
wxpython3.0 3.0.2.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 482,760 kB
  • ctags: 518,293
  • sloc: cpp: 2,127,226; python: 294,045; makefile: 51,942; ansic: 19,033; sh: 3,013; xml: 1,629; perl: 17
file content (4886 lines) | stat: -rw-r--r-- 190,871 bytes parent folder | download | duplicates (2)
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
# --------------------------------------------------------------------------------- #
# HYPERTREELIST wxPython IMPLEMENTATION
# Inspired By And Heavily Based On wx.gizmos.TreeListCtrl.
#
# Andrea Gavana, @ 08 May 2006
# Latest Revision: 30 Jul 2014, 21.00 GMT
#
#
# TODO List
#
# Almost All The Features Of wx.gizmos.TreeListCtrl 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. Add Support For 3-State CheckBoxes (Is That Really Useful?).
#
# 2. Try To Implement A More Flicker-Free Background Image In Cases Like
#    Centered Or Stretched Image (Now HyperTreeList Supports Only Tiled
#    Background Images).
#
# 3. Try To Mimic Windows wx.TreeCtrl Expanding/Collapsing behaviour: HyperTreeList
#    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.
#
# 4. Speed Up General OnPaint Things? I Have No Idea, Here HyperTreeList 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@gmail.com
# andrea.gavana@maerskoil.com
#
# Or, Obviously, To The wxPython Mailing List!!!
#
#
# End Of Comments
# --------------------------------------------------------------------------------- #


"""
:class:`HyperTreeList` is a class that mimics the behaviour of :class:`gizmos.TreeListCtrl`, with
some more functionalities.


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

:class:`HyperTreeList` is a class that mimics the behaviour of :class:`gizmos.TreeListCtrl`, 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-list control.

:class:`HyperTreeList` is somewhat an hybrid between :class:`~lib.agw.customtreectrl.CustomTreeCtrl` and :class:`gizmos.TreeListCtrl`.

In addition to the standard :class:`gizmos.TreeListCtrl` 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 :class:`~lib.agw.customtreectrl.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;
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to a tree item;
* Whatever non-toplevel widget can be attached next to a list item;
* Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style;
* Customized drag and drop images built on the fly;
* Setting the :class:`HyperTreeList` item buttons to a personalized imagelist;
* Setting the :class:`HyperTreeList` check/radio item icons to a personalized imagelist;
* Changing the style of the lines that connect the items (in terms of :class:`Pen` styles);
* Using an image as a :class:`HyperTreeList` background (currently only in "tile" mode);
* Ellipsization of long items when the horizontal space is low, via the ``TR_ELLIPSIZE_LONG_ITEMS``
  style (`New in version 0.9.3`).

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


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

:class:`HyperTreeList` supports all the :class:`gizmos.TreeListCtrl` 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 a style useful to hide the TreeListCtrl header:

- ``TR_NO_HEADER``: hides the :class:`HyperTreeList` header.

And a style related to long items (with a lot of text in them), which can be 
ellipsized:

- ``TR_ELLIPSIZE_LONG_ITEMS``: ellipsizes long items when the horizontal space for
  :class:`HyperTreeList` is low (`New in version 0.9.3`).


All the methods available in :class:`gizmos.TreeListCtrl` are also available in :class:`HyperTreeList`.


Usage
=====

Usage example::

    import wx
    import wx.lib.agw.hypertreelist as HTL

    class MyFrame(wx.Frame):

        def __init__(self, parent):
        
            wx.Frame.__init__(self, parent, -1, "HyperTreeList Demo")

            tree_list = HTL.HyperTreeList(self)
            
            tree_list.AddColumn("First column")

            root = tree_list.AddRoot("Root", ct_type=1)

            parent = tree_list.AppendItem(root, "First child", ct_type=1)
            child = tree_list.AppendItem(parent, "First Grandchild", ct_type=1)
            
            tree_list.AppendItem(root, "Second child", ct_type=1)


    # our normal wxApp-derived class, as usual

    app = wx.App(0)

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

    app.MainLoop()
    


Events
======

All the events supported by :class:`gizmos.TreeListCtrl` are also available in :class:`HyperTreeList`,
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, :class:`HyperTreeList` 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
===================

:class:`HyperTreeList` has been tested on the following platforms:
  * Windows (Windows XP), Vista, 7;
  * Linux
  * Mac


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_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
``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_NO_HEADER``                   0x40000 Use this style to hide the columns header.
``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for :class:`HyperTreeList` columns is low.
``TR_VIRTUAL``                    0x100000 :class:`HyperTreeList` will have virtual behaviour.
============================== =========== ==================================================


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

This class processes the following events:

============================== ==================================================
Event Name                     Description
============================== ==================================================
``EVT_LIST_COL_BEGIN_DRAG``    The user started resizing a column - can be vetoed.
``EVT_LIST_COL_CLICK``         A column has been left-clicked.
``EVT_LIST_COL_DRAGGING``      The divider between columns is being dragged.
``EVT_LIST_COL_END_DRAG``      A column has been resized by the user.
``EVT_LIST_COL_RIGHT_CLICK``   A column has been right-clicked.
``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 :meth:`TreeEvent.Veto() <lib.agw.customtreectrl.TreeEvent.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 :meth:`TreeEvent.Veto() <lib.agw.customtreectrl.TreeEvent.Veto>`.
``EVT_TREE_GET_INFO``          Request information from the application (not implemented in :class:`HyperTreeList`).
``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 :meth:`TreeEvent.Veto() <lib.agw.customtreectrl.TreeEvent.Veto>`.
``EVT_TREE_ITEM_EXPANDED``     The item has been expanded.s
``EVT_TREE_ITEM_EXPANDING``    The item is being expanded. This can be prevented by calling :meth:`TreeEvent.Veto() <lib.agw.customtreectrl.TreeEvent.Veto>`.
``EVT_TREE_ITEM_GETTOOLTIP``   The opportunity to set the item tooltip is being given to the application (call :meth:`TreeEvent.SetToolTip() <lib.agw.customtreectrl.CommandTreeEvent.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 :class:`HyperTreeList`).
``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 :meth:`TreeEvent.Veto() <lib.agw.customtreectrl.TreeEvent.Veto>`.
``EVT_TREE_SET_INFO``          Information is being supplied to the application (not implemented in :class:`HyperTreeList`).
``EVT_TREE_STATE_IMAGE_CLICK`` The state image has been clicked (not implemented in :class:`HyperTreeList`).
============================== ==================================================


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

:class:`HyperTreeList` is distributed under the wxPython license.

Latest Revision: Andrea Gavana @ 30 Jul 2014, 21.00 GMT

Version 1.3

"""

import wx
import wx.gizmos

from customtreectrl import CustomTreeCtrl
from customtreectrl import DragImage, TreeEvent, GenericTreeItem, ChopText
from customtreectrl import TreeEditTimer as TreeListEditTimer
from customtreectrl import EVT_TREE_ITEM_CHECKING, EVT_TREE_ITEM_CHECKED, EVT_TREE_ITEM_HYPERLINK

# Version Info
__version__ = "1.3"

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

_NO_IMAGE = -1

_DEFAULT_COL_WIDTH = 100
_LINEHEIGHT = 10
_LINEATROOT = 5
_MARGIN = 2
_MININDENT = 16
_BTNWIDTH = 9
_BTNHEIGHT = 9
_EXTRA_WIDTH = 4
_EXTRA_HEIGHT = 4

_MAX_WIDTH = 30000  # pixels; used by OnPaint to redraw only exposed items

_DRAG_TIMER_TICKS = 250   # minimum drag wait time in ms
_FIND_TIMER_TICKS = 500   # minimum find wait time in ms
_EDIT_TIMER_TICKS = 250 # minimum edit wait time in ms


# --------------------------------------------------------------------------
# Additional HitTest style
# --------------------------------------------------------------------------
TREE_HITTEST_ONITEMCHECKICON  = 0x4000
""" On the check icon, if present. """

# HyperTreeList styles
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_COLUMN_LINES = 0x1000                                       # put border between columns
""" Use this style to draw a contrasting border between displayed columns. """
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_ELLIPSIZE_LONG_ITEMS = 0x80000                              # to ellipsize long items when horizontal space is low
""" Flag used to ellipsize long items when the horizontal space for :class:`HyperTreeList` columns is low."""
TR_VIRTUAL = 0x100000
""" :class:`HyperTreeList` will have virtual behaviour. """

# --------------------------------------------------------------------------
# Additional HyperTreeList style to hide the header
# --------------------------------------------------------------------------
TR_NO_HEADER = 0x40000
""" Use this style to hide the columns header. """
# --------------------------------------------------------------------------


# --------------------------------------------------------------------------
# Additional HyperTreeList style autosize the columns based on the widest
# width between column header and cells content
# --------------------------------------------------------------------------
LIST_AUTOSIZE_CONTENT_OR_HEADER = -3
# --------------------------------------------------------------------------


def IsBufferingSupported():
    """
    Utility function which checks if a platform handles correctly double
    buffering for the header. Currently returns ``False`` for all platforms
    except Windows XP.
    """

    if wx.Platform != "__WXMSW__":
        return False

    if wx.App.GetComCtl32Version() >= 600:
        if wx.GetOsVersion()[1] > 5:
            # Windows Vista
            return False

        return True

    return False    
    

class TreeListColumnInfo(object):
    """
    Class used to store information (width, alignment flags, colours, etc...) about a
    :class:`HyperTreeList` column header.
    """

    def __init__(self, input="", width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                 image=-1, shown=True, colour=None, edit=False):
        """
        Default class constructor.

        :param `input`: can be a string (representing the column header text) or
         another instance of :class:`TreeListColumnInfo`. In the latter case, all the
         other input parameters are not used;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid :class:`Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        if isinstance(input, basestring):
            self._text = input
            self._width = width
            self._flag = flag
            self._image = image
            self._selected_image = -1
            self._shown = shown
            self._edit = edit
            self._font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
            if colour is None:
                self._colour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOWTEXT)
            else:
                self._colour = colour
                
        else:
    
            self._text = input._text
            self._width = input._width
            self._flag = input._flag
            self._image = input._image
            self._selected_image = input._selected_image
            self._shown = input._shown
            self._edit = input._edit
            self._colour = input._colour
            self._font = input._font
    

    # get/set
    def GetText(self):
        """ Returns the column header label. """
        
        return self._text

    
    def SetText(self, text):
        """
        Sets the column header label.

        :param `text`: the new column header text.
        """

        self._text = text
        return self


    def GetWidth(self):
        """ Returns the column header width in pixels. """

        return self._width 


    def SetWidth(self, width):
        """
        Sets the column header width.

        :param `width`: the column header width, in pixels.
        """

        self._width = width
        return self


    def GetAlignment(self):
        """ Returns the column text alignment. """

        return self._flag

    
    def SetAlignment(self, flag):
        """
        Sets the column text alignment.

        :param `flag`: the alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``,
         ``wx.ALIGN_CENTER``.
        """

        self._flag = flag
        return self 


    def GetColour(self):
        """ Returns the column text colour. """

        return self._colour


    def SetColour(self, colour):
        """
        Sets the column text colour.

        :param `colour`: a valid :class:`Colour` object.
        """

        self._colour = colour
        return self
        

    def GetImage(self):
        """ Returns the column image index. """

        return self._image 


    def SetImage(self, image):
        """
        Sets the column image index.

        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column.
        """

        self._image = image
        return self 


    def GetSelectedImage(self):
        """ Returns the column image index in the selected state. """

        return self._selected_image
    

    def SetSelectedImage(self, image):
        """
        Sets the column image index in the selected state.

        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column when in
         selected state.
        """

        self._selected_image = image
        return self
    

    def IsEditable(self):
        """ Returns ``True`` if the column is editable, ``False`` otherwise. """

        return self._edit

    
    def SetEditable(self, edit):
        """
        Sets the column as editable or non-editable.

        :param `edit`: ``True`` if the column should be editable, ``False`` otherwise.
        """
        
        self._edit = edit
        return self 


    def IsShown(self):
        """ Returns ``True`` if the column is shown, ``False`` if it is hidden. """

        return self._shown

    
    def SetShown(self, shown):
        """
        Sets the column as shown or hidden.

        :param `shown`: ``True`` if the column should be shown, ``False`` if it
         should be hidden.
        """

        self._shown = shown
        return self 


    def SetFont(self, font):
        """
        Sets the column text font.

        :param `font`: a valid :class:`Font` object.
        """

        self._font = font
        return self


    def GetFont(self):
        """ Returns the column text font. """

        return self._font        


#-----------------------------------------------------------------------------
#  TreeListHeaderWindow (internal)
#-----------------------------------------------------------------------------

class TreeListHeaderWindow(wx.Window):
    """ A window which holds the header of :class:`HyperTreeList`. """
    
    def __init__(self, parent, id=wx.ID_ANY, owner=None, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, name="wxtreelistctrlcolumntitles"):
        """
        Default class constructor.

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `owner`: the window owner, in this case an instance of :class:`TreeListMainWindow`;
        :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;
        :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;
        :param `style`: the window style;
        :param `name`: the window name.
        """

        wx.Window.__init__(self, parent, id, pos, size, style, name=name)
        
        self._owner = owner
        self._currentCursor = wx.StockCursor(wx.CURSOR_DEFAULT)
        self._resizeCursor = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._isDragging = False
        self._dirty = False
        self._total_col_width = 0
        self._hotTrackCol = -1
        self._columns = []
        self._headerCustomRenderer = None
        
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)

        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)


    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the header.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._buffered = buffered


    # total width of all columns
    def GetWidth(self):
        """ Returns the total width of all columns. """

        return self._total_col_width 


    # column manipulation
    def GetColumnCount(self):
        """ Returns the total number of columns. """

        return len(self._columns)


    # column information manipulation
    def GetColumn(self, column):
        """
        Returns a column item, an instance of :class:`TreeListItem`.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column]


    def GetColumnText(self, column):
        """
        Returns the column text label.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].GetText()

    
    def SetColumnText(self, column, text):
        """
        Sets the column text label.

        :param `column`: an integer specifying the column index;
        :param `text`: the new column label.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].SetText(text)
    

    def GetColumnAlignment(self, column):
        """
        Returns the column text alignment.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].GetAlignment()
    

    def SetColumnAlignment(self, column, flag):
        """
        Sets the column text alignment.

        :param `column`: an integer specifying the column index;
        :param `flag`: the new text alignment flag.

        :see: :meth:`TreeListColumnInfo.SetAlignment() <TreeListColumnInfo.SetAlignment>` for a list of valid alignment
         flags.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].SetAlignment(flag)
    

    def GetColumnWidth(self, column):
        """
        Returns the column width, in pixels.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].GetWidth()
    

    def GetColumnColour(self, column):
        """
        Returns the column text colour.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].GetColour()


    def SetColumnColour(self, column, colour):
        """
        Sets the column text colour.

        :param `column`: an integer specifying the column index;
        :param `colour`: a valid :class:`Colour` object.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].SetColour(colour)


    def IsColumnEditable(self, column):
        """
        Returns ``True`` if the column is editable, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        return self._columns[column].IsEditable()
    

    def IsColumnShown(self, column):
        """
        Returns ``True`` if the column is shown, ``False`` if it is hidden.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        return self._columns[column].IsShown()
    

    # shift the DC origin to match the position of the main window horz
    # scrollbar: this allows us to always use logical coords
    def AdjustDC(self, dc):
        """
        Shifts the :class:`DC` origin to match the position of the main window horizontal
        scrollbar: this allows us to always use logical coordinates.

        :param `dc`: an instance of :class:`DC`.        
        """
        
        xpix, dummy = self._owner.GetScrollPixelsPerUnit()
        x, dummy = self._owner.GetViewStart()

        # account for the horz scrollbar offset
        dc.SetDeviceOrigin(-x * xpix, 0)


    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`TreeListHeaderWindow`.

        :param `event`: a :class:`PaintEvent` event to be processed.
        """
        
        if self._buffered:
            dc = wx.BufferedPaintDC(self)
        else:
            dc = wx.PaintDC(self)
            
        self.AdjustDC(dc)

        x = 0

        # width and height of the entire header window
        w, h = self.GetClientSize()
        w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
        dc.SetBackgroundMode(wx.TRANSPARENT)

        numColumns = self.GetColumnCount()
        
        for i in xrange(numColumns):

            if x >= w:
                break
        
            if not self.IsColumnShown(i):
                continue # do next column if not shown

            params = wx.HeaderButtonParams()

            column = self.GetColumn(i)
            params.m_labelColour = column.GetColour()
            params.m_labelFont = column.GetFont()

            wCol = column.GetWidth()
            flags = 0
            rect = wx.Rect(x, 0, wCol, h)
            x += wCol

            if i == self._hotTrackCol:
                flags |= wx.CONTROL_CURRENT
            
            params.m_labelText = column.GetText()
            params.m_labelAlignment = column.GetAlignment()

            image = column.GetImage()
            imageList = self._owner.GetImageList()

            if image != -1 and imageList:
                params.m_labelBitmap = imageList.GetBitmap(image)

            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, rect, flags, params)
            else:
                wx.RendererNative.Get().DrawHeaderButton(self, dc, rect, flags,
                                                         wx.HDR_SORT_ICON_NONE, params)
       
        # Fill up any unused space to the right of the columns
        if x < w:
            rect = wx.Rect(x, 0, w-x, h)
            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, rect)
            else:
                wx.RendererNative.Get().DrawHeaderButton(self, dc, rect)
        

    def DrawCurrent(self):
        """ Draws the column resize line on a :class:`ScreenDC`. """
        
        x1, y1 = self._currentX, 0
        x1, y1 = self.ClientToScreen((x1, y1))
        x2 = self._currentX-1
        if wx.Platform == "__WXMSW__":
            x2 += 1 # but why ????

        y2 = 0
        dummy, y2 = self._owner.GetClientSize()
        x2, y2 = self._owner.ClientToScreen((x2, y2))

        dc = wx.ScreenDC()
        dc.SetLogicalFunction(wx.INVERT)
        dc.SetPen(wx.Pen(wx.BLACK, 2, wx.SOLID))
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        self.AdjustDC(dc)
        dc.DrawLine (x1, y1, x2, y2)
        dc.SetLogicalFunction(wx.COPY)
        
        
    def SetCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the method `DrawHeaderButton`
        """

        self._headerCustomRenderer = renderer


    def XToCol(self, x):
        """
        Returns the column that corresponds to the logical input `x` coordinate.

        :param `x`: the `x` position to evaluate.

        :return: The column that corresponds to the logical input `x` coordinate,
         or ``wx.NOT_FOUND`` if there is no column at the `x` position.
        """
        
        colLeft = 0
        numColumns = self.GetColumnCount()
        for col in xrange(numColumns):
        
            if not self.IsColumnShown(col):
                continue 

            column = self.GetColumn(col)

            if x < (colLeft + column.GetWidth()):
                 return col
            
            colLeft += column.GetWidth()
        
        return wx.NOT_FOUND


    def RefreshColLabel(self, col):
        """
        Redraws the column.

        :param `col`: the index of the column to redraw.
        """

        if col >= self.GetColumnCount():
            return
        
        x = idx = width = 0
        while idx <= col:
            
            if not self.IsColumnShown(idx):
                idx += 1
                continue 

            column = self.GetColumn(idx)
            x += width
            width = column.GetWidth()
            idx += 1

        x, dummy = self._owner.CalcScrolledPosition(x, 0)
        self.RefreshRect(wx.Rect(x, 0, width, self.GetSize().GetHeight()))

        
    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`TreeListHeaderWindow`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """

        # we want to work with logical coords
        x, dummy = self._owner.CalcUnscrolledPosition(event.GetX(), 0)
        y = event.GetY()

        if event.Moving():
        
            col = self.XToCol(x)
            if col != self._hotTrackCol:
            
                # Refresh the col header so it will be painted with hot tracking
                # (if supported by the native renderer.)
                self.RefreshColLabel(col)

                # Also refresh the old hot header
                if self._hotTrackCol >= 0:
                    self.RefreshColLabel(self._hotTrackCol)

                self._hotTrackCol = col
            
        if event.Leaving() and self._hotTrackCol >= 0:
        
            # Leaving the window so clear any hot tracking indicator that may be present
            self.RefreshColLabel(self._hotTrackCol)
            self._hotTrackCol = -1
        
        if self._isDragging:

            self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_DRAGGING, event.GetPosition())

            # we don't draw the line beyond our window, but we allow dragging it
            # there
            w, dummy = self.GetClientSize()
            w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
            w -= 6

            # erase the line if it was drawn
            if self._currentX < w:
                self.DrawCurrent()

            if event.ButtonUp():
                self._isDragging = False
                if self.HasCapture():
                    self.ReleaseMouse()
                self._dirty = True
                self.SetColumnWidth(self._column, self._currentX - self._minX)
                self.Refresh()
                self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition())
            else:
                self._currentX = max(self._minX + 7, x)

                # draw in the new location
                if self._currentX < w:
                    self.DrawCurrent()
            
        else: # not dragging

            self._minX = 0
            hit_border = False

            # end of the current column
            xpos = 0

            # find the column where this event occured
            countCol = self.GetColumnCount()

            for column in xrange(countCol):

                if not self.IsColumnShown(column):
                    continue # do next if not shown

                xpos += self.GetColumnWidth(column)
                self._column = column
                if abs (x-xpos) < 3 and y < 22:
                    # near the column border
                    hit_border = True
                    break
                
                if x < xpos:
                    # inside the column
                    break
            
                self._minX = xpos
            
            if event.LeftDown() or event.RightUp():
                if hit_border and event.LeftDown():
                    self._isDragging = True
                    self.CaptureMouse()
                    self._currentX = x
                    self.DrawCurrent()
                    self.SendListEvent(wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG, event.GetPosition())
                else: # click on a column
                    evt = (event.LeftDown() and [wx.wxEVT_COMMAND_LIST_COL_CLICK] or [wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0]
                    self.SendListEvent(evt, event.GetPosition())
                
            elif event.LeftDClick() and hit_border:
                self.SetColumnWidth(self._column, self._owner.GetBestColumnWidth(self._column))
                self.Refresh()

            elif event.Moving():
                
                if hit_border:
                    setCursor = self._currentCursor == wx.STANDARD_CURSOR
                    self._currentCursor = self._resizeCursor
                else:
                    setCursor = self._currentCursor != wx.STANDARD_CURSOR
                    self._currentCursor = wx.STANDARD_CURSOR
                
                if setCursor:
                    self.SetCursor(self._currentCursor)
    

    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for :class:`TreeListHeaderWindow`.

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

        self._owner.SetFocus()


    def SendListEvent(self, evtType, pos):
        """
        Sends a :class:`ListEvent` for the parent window.

        :param `evtType`: the event type;
        :param `pos`: an instance of :class:`Point`.
        """
        
        parent = self.GetParent()
        le = wx.ListEvent(evtType, parent.GetId())
        le.SetEventObject(parent)
        le.m_pointDrag = pos

        # the position should be relative to the parent window, not
        # this one for compatibility with MSW and common sense: the
        # user code doesn't know anything at all about this header
        # window, so why should it get positions relative to it?
        le.m_pointDrag.y -= self.GetSize().y
        le.m_col = self._column
        parent.GetEventHandler().ProcessEvent(le)


    def AddColumnInfo(self, colInfo):
        """
        Appends a column to the :class:`TreeListHeaderWindow`.

        :param `colInfo`: an instance of :class:`TreeListColumnInfo`.
        """
        
        self._columns.append(colInfo)
        self._total_col_width += colInfo.GetWidth()
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True


    def AddColumn(self, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                  image=-1, shown=True, colour=None, edit=False):
        """
        Appends a column to the :class:`TreeListHeaderWindow`.

        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid :class:`Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        colInfo = TreeListColumnInfo(text, width, flag, image, shown, colour, edit)
        self.AddColumnInfo(colInfo)


    def SetColumnWidth(self, column, width):
        """
        Sets the column width, in pixels.

        :param `column`: an integer specifying the column index;
        :param `width`: the new width for the column, in pixels.
        """
        
        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")

        self._total_col_width -= self._columns[column].GetWidth()
        self._columns[column].SetWidth(width)
        self._total_col_width += width
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True


    def InsertColumnInfo(self, before, colInfo):
        """
        Inserts a column to the :class:`TreeListHeaderWindow` at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `colInfo`: an instance of :class:`TreeListColumnInfo`.
        """

        if before < 0 or before >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        self._columns.insert(before, colInfo)
        self._total_col_width += colInfo.GetWidth()
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True


    def InsertColumn(self, before, text, width=_DEFAULT_COL_WIDTH,
                     flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, 
                     edit=False):
        """
        Inserts a column to the :class:`TreeListHeaderWindow` at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid :class:`Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.        
        """
        
        colInfo = TreeListColumnInfo(text, width, flag, image, shown, colour, 
                                     edit)
        self.InsertColumnInfo(before, colInfo)


    def RemoveColumn(self, column):
        """
        Removes a column from the :class:`TreeListHeaderWindow`.

        :param `column`: an integer specifying the column index.
        """

        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        self._total_col_width -= self._columns[column].GetWidth()
        self._columns.pop(column)
        self._owner.AdjustMyScrollbars()
        self._owner._dirty = True


    def SetColumn(self, column, info):
        """
        Sets a column using an instance of :class:`TreeListColumnInfo`.

        :param `column`: an integer specifying the column index;
        :param `info`: an instance of :class:`TreeListColumnInfo`.        
        """
        
        if column < 0 or column >= self.GetColumnCount():
            raise Exception("Invalid column")
        
        w = self._columns[column].GetWidth()
        self._columns[column] = info
        
        if w != info.GetWidth():
            self._total_col_width += info.GetWidth() - w
            self._owner.AdjustMyScrollbars()
        
        self._owner._dirty = True
        

# ---------------------------------------------------------------------------
# TreeListItem
# ---------------------------------------------------------------------------
class TreeListItem(GenericTreeItem):
    """
    This class holds all the information and methods for every single item in
    :class:`HyperTreeList`.

    :note: Subclassed from :class:`GenericTreeItem`.    
    """
    
    def __init__(self, mainWin, parent, text=[], ct_type=0, wnd=None, image=-1, selImage=-1, data=None):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `mainWin`: the main :class:`HyperTreeList` window, in this case an instance
         of :class:`TreeListMainWindow`;
        :param `parent`: the tree item parent (may be ``None`` for root items);
        :param `text`: the tree item text;
        :param `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;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `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 `data`: associate the given Python object `data` with the 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._col_images = []
        self._owner = mainWin

        # We don't know the height here yet.
        self._text_x = 0
        
        GenericTreeItem.__init__(self, parent, text, ct_type, wnd, image, selImage, data)        
 
        self._wnd = [None]             # are we holding a window?
        self._hidden = False
        
        if wnd:
            self.SetWindow(wnd)


    def IsHidden(self):
        """ Returns whether the item is hidden or not. """

        return self._hidden


    def Hide(self, hide):
        """
        Hides/shows the :class:`TreeListItem`.

        :param `hide`: ``True`` to hide the item, ``False`` to show it.
        """

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

        :param `tree`: the main :class:`TreeListMainWindow` instance.
        """

        for child in self._children:
            child.DeleteChildren(tree)
            if tree:
                tree.Delete(child)
            
            if child == tree._selectItem:
                tree._selectItem = None

            # We have to destroy the associated window
            for wnd in child._wnd:
                if wnd:
                    wnd.Hide()
                    wnd.Destroy()
                    
            child._wnd = []

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


    def HitTest(self, point, theCtrl, flags, column, level):
        """
        HitTest method for an item. Called from the main window HitTest.

        :param `point`: the point to test for the hit (an instance of :class:`Point`);
        :param `theCtrl`: the main :class:`TreeListMainWindow` tree;
        :param `flags`: a bitlist of hit locations;
        :param `column`: an integer specifying the column index;
        :param `level`: the item's level inside the tree hierarchy.
        
        :see: :meth:`TreeListMainWindow.HitTest() <TreeListMainWindow.HitTest>` method for the flags explanation.
        """

        # for a hidden root node, don't evaluate it, but do evaluate children
        if not theCtrl.HasAGWFlag(wx.TR_HIDE_ROOT) or level > 0:

            # reset any previous hit infos
            flags = 0
            column = -1
            header_win = theCtrl._owner.GetHeaderWindow()

            # check for right of all columns (outside)
            if point.x > header_win.GetWidth():
                return None, flags, wx.NOT_FOUND

            # evaluate if y-pos is okay
            h = theCtrl.GetLineHeight(self)
            
            if point.y >= self._y and point.y <= self._y + h:

                maincol = theCtrl.GetMainColumn()

                # check for above/below middle
                y_mid = self._y + h/2
                if point.y < y_mid:
                    flags |= wx.TREE_HITTEST_ONITEMUPPERPART
                else:
                    flags |= wx.TREE_HITTEST_ONITEMLOWERPART
                
                # check for button hit
                if self.HasPlus() and theCtrl.HasButtons():
                    bntX = self._x - theCtrl._btnWidth2
                    bntY = y_mid - theCtrl._btnHeight2
                    if ((point.x >= bntX) and (point.x <= (bntX + theCtrl._btnWidth)) and
                        (point.y >= bntY) and (point.y <= (bntY + theCtrl._btnHeight))):
                        flags |= wx.TREE_HITTEST_ONITEMBUTTON
                        column = maincol
                        return self, flags, column

                # check for hit on the check icons
                if self.GetType() != 0:
                    imageWidth = 0
                    numberOfMargins = 1
                    if self.GetCurrentImage() != _NO_IMAGE:
                        imageWidth = theCtrl._imgWidth
                        numberOfMargins += 1
                    chkX = self._text_x - imageWidth - numberOfMargins*_MARGIN - theCtrl._checkWidth
                    chkY = y_mid - theCtrl._checkHeight2
                    if ((point.x >= chkX) and (point.x <= (chkX + theCtrl._checkWidth)) and
                        (point.y >= chkY) and (point.y <= (chkY + theCtrl._checkHeight))):                    
                        flags |= TREE_HITTEST_ONITEMCHECKICON
                        return self, flags, maincol
                    
                # check for image hit
                if self.GetCurrentImage() != _NO_IMAGE:
                    imgX = self._text_x - theCtrl._imgWidth - _MARGIN                        
                    imgY = y_mid - theCtrl._imgHeight2
                    if ((point.x >= imgX) and (point.x <= (imgX + theCtrl._imgWidth)) and
                        (point.y >= imgY) and (point.y <= (imgY + theCtrl._imgHeight))):
                        flags |= wx.TREE_HITTEST_ONITEMICON
                        column = maincol
                        return self, flags, column
                    
                # check for label hit
                if ((point.x >= self._text_x) and (point.x <= (self._text_x + self._width))):
                    flags |= wx.TREE_HITTEST_ONITEMLABEL
                    column = maincol
                    return self, flags, column
                
                # check for indent hit after button and image hit
                if point.x < self._x:
                    flags |= wx.TREE_HITTEST_ONITEMINDENT
                    column = -1 # considered not belonging to main column
                    return self, flags, column
                
                # check for right of label
                end = 0
                for i in xrange(maincol):
                    end += header_win.GetColumnWidth(i)
                    if ((point.x > (self._text_x + self._width)) and (point.x <= end)):
                        flags |= wx.TREE_HITTEST_ONITEMRIGHT
                        column = -1 # considered not belonging to main column
                        return self, flags, column
                
                # else check for each column except main
                x = 0
                for j in xrange(theCtrl.GetColumnCount()):
                    if not header_win.IsColumnShown(j):
                        continue
                    w = header_win.GetColumnWidth(j)
                    if ((j != maincol) and (point.x >= x and point.x < x+w)):
                        flags |= wx.TREE_HITTEST_ONITEMCOLUMN
                        column = j
                        return self, flags, column
                    
                    x += w
                
                # no special flag or column found
                return self, flags, column

            # if children not expanded, return no item
            if not self.IsExpanded():
                return None, flags, wx.NOT_FOUND
        
        # in any case evaluate children
        for child in self._children:
            hit, flags, column = child.HitTest(point, theCtrl, flags, column, level+1)
            if hit:
                return hit, flags, column
        
        # not found
        return None, flags, wx.NOT_FOUND


    def GetText(self, column=None):
        """
        Returns the item text label.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
        
        if len(self._text) > 0:
            if self._owner.IsVirtual():
                return self._owner.GetItemText(self._data, column)
            else:
                return self._text[column]
        
        return ""
    

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

        :param `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) 
         ================================= ========================

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column == self._owner.GetMainColumn():
            return self._images[which]
        
        if column < len(self._col_images):
            return self._col_images[column]

        return _NO_IMAGE


    def GetCurrentImage(self, column=None):
        """
        Returns the current item image.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.        
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column != self._owner.GetMainColumn():
            return self.GetImage(column=column)
        
        image = GenericTreeItem.GetCurrentImage(self)
        return image
    

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

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `text`: a string specifying the new item label.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
    
        if column < len(self._text):
            self._text[column] = text
        elif column < self._owner.GetColumnCount():
            self._text.extend([""] * (column - len(self._text) + 1))
            self._text[column] = text
        

    def SetImage(self, column, image, which):
        """
        Sets the item image for a particular item state.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `image`: an index within the normal image list specifying the image to use;
        :param `which`: the item state.

        :see: :meth:`~TreeListItem.GetImage` for a list of valid item states.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
    
        if column == self._owner.GetMainColumn():
            self._images[which] = image
        elif column < len(self._col_images):
            self._col_images[column] = image
        elif column < self._owner.GetColumnCount():
            self._col_images.extend([_NO_IMAGE] * (column - len(self._col_images) + 1))
            self._col_images[column] = image
        
    
    def GetTextX(self):
        """ Returns the `x` position of the item text. """

        return self._text_x

    
    def SetTextX(self, text_x):
        """
        Sets the `x` position of the item text.

        :param `text_x`: the `x` position of the item text.
        """

        self._text_x = text_x 


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

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if type(self._wnd) != type([]):
            self._wnd = [self._wnd]

        if column < len(self._wnd):
            self._wnd[column] = wnd
        elif column < self._owner.GetColumnCount():
            self._wnd.extend([None] * (column - len(self._wnd) + 1))
            self._wnd[column] = wnd

        if self not in self._owner._itemWithWindow:
            self._owner._itemWithWindow.append(self)
            
        # 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
        # HyperTreeList and the window associated to an item
        # Do better strategies exist?
        wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        
        # We don't show the window if the item is collapsed
        if self._isCollapsed:
            wnd.Show(False)

        # The window is enabled only if the item is enabled                
        wnd.Enable(self._enabled)
        

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

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

        treectrl = self._owner
        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 GetWindow(self, column=None):
        """
        Returns the window associated to the item.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.        
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
        
        if column >= len(self._wnd):
            return None

        return self._wnd[column]        


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

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if column >= len(self._wnd):
            return
        
        if self._wnd[column]:
            self._wnd[column].Destroy()
            self._wnd[column] = None
        

    def GetWindowEnabled(self, column=None):
        """
        Returns whether the window associated with an item is enabled or not.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)

        return self._wnd[column].IsEnabled()


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

        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]

        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)

        self._wnd[column].Enable(enable)


    def GetWindowSize(self, column=None):
        """
        Returns the associated window size.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
        
        if not self._wnd[column]:
            raise Exception("\nERROR: This Item Has No Window Associated At Column %s"%column)
        
        return self._wnd[column].GetSize()   


#-----------------------------------------------------------------------------
# EditTextCtrl (internal)
#-----------------------------------------------------------------------------


class EditCtrl(object):
    """
    Base class for controls used for in-place edit.
    """

    def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
                 value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name="editctrl", **kwargs):
        """
        Default class constructor.

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `owner`: the window owner, in this case an instance of :class:`TreeListMainWindow`;
        :param `value`: the initial value in the control;
        :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;
        :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;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name.
        """
        self._owner = owner
        self._startValue = value
        self._itemEdited = item
        self._finished = False
        
        column = (column is not None and [column] or [self._owner.GetMainColumn()])[0]
        
        self._column = column

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

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

        x = item.GetX()

        if column > 0:
            x = 0
            
        for i in xrange(column):
            if not self._owner.GetParent()._header_win.IsColumnShown(i):
                continue # do next column if not shown
            
            col = self._owner.GetParent()._header_win.GetColumn(i)
            wCol = col.GetWidth()
            x += wCol
        
        x, y = self._owner.CalcScrolledPosition(x+2, item.GetY())

        image_w = image_h = wcheck = hcheck = 0
        image = item.GetCurrentImage(column)

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

        if column > 0:
            checkimage = item.GetCurrentCheckedImage()
            if checkimage is not None:
                wcheck, hcheck = self._owner._imageListCheck.GetSize(checkimage)
                wcheck += 2*_MARGIN

        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 + 2*_MARGIN + wcheck

        super(EditCtrl, self).__init__(parent, id, value, wx.Point(x,y),
                                       wx.Size(w+15, h), 
                                       style=style|wx.SIMPLE_BORDER, 
                                       name=name, **kwargs)
        
        if wx.Platform == "__WXMAC__":
            self.SetFont(owner.GetFont())
            bs = self.GetBestSize()
            self.SetSize((-1, bs.height))

        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)


    def item(self):
        """Returns the item currently edited."""

        return self._itemEdited


    def column(self): 
        """Returns the column currently edited.""" 

        return self._column


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

        self._owner.OnCancelEdit()
        self.Finish()


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

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


    def AcceptChanges(self):
        """Accepts/refuses the changes made 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()
            return True
        else:
            return self._owner.OnAcceptEdit(value)


    def OnKillFocus(self, event):
        """
        Handles the ``wx.EVT_KILL_FOCUS`` event for :class:`EditCtrl`

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

        # We must let the native control handle focus, too, otherwise
        # it could have problems with the cursor (e.g., in wxGTK).
        event.Skip()



class EditTextCtrl(EditCtrl, wx.TextCtrl):
    """
    Text control used for in-place edit.
    """
    
    def __init__(self, parent, id=wx.ID_ANY, item=None, column=None, owner=None,
                 value="", pos=wx.DefaultPosition, size=wx.DefaultSize, style=0,
                 validator=wx.DefaultValidator, name="edittextctrl", **kwargs):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `parent`: the window parent. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `owner`: the window owner, in this case an instance of :class:`TreeListMainWindow`;
        :param `value`: the initial value in the text control;
        :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;
        :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;
        :param `style`: the window style;
        :param `validator`: the window validator;
        :param `name`: the window name.
        """

        super(EditTextCtrl, self).__init__(parent, id, item, column, owner, 
                                           value, pos, size, style, validator, 
                                           name, **kwargs)       
        self.SelectAll()

        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)


    def OnChar(self, event):
        """
        Handles the ``wx.EVT_CHAR`` event for :class:`EditTextCtrl`.

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

        keycode = event.GetKeyCode()

        if keycode in [wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER] and not event.ShiftDown():
            # 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 :class:`EditTextCtrl`.

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

        if not self._finished:

            # auto-grow the textctrl:
            parentSize = self._owner.GetSize()
            myPos = self.GetPosition()
            mySize = self.GetSize()
            
            sx, sy = self.GetTextExtent(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))

        event.Skip()
        
        
        
# ---------------------------------------------------------------------------
# TreeListMainWindow implementation
# ---------------------------------------------------------------------------

class TreeListMainWindow(CustomTreeCtrl):
    """
    This class represents the main window (and thus the main column) in :class:`HyperTreeList`.

    :note: This is a subclass of :class:`~lib.agw.customtreectrl.CustomTreeCtrl`.
    """

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="wxtreelistmainwindow"):
        """
        Default class constructor.
        
        :param `parent`: parent window. Must not be ``None``;
        :param `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;
        :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;
        :param `style`: the underlying :class:`PyScrolledWindow` style;
        :param `agwStyle`: the AGW-specific :class:`TreeListMainWindow` window style. This 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_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for :class:`~lib.agw.customtreectrl.CustomTreeCtrl` is low.
         ``TR_VIRTUAL``                    0x100000 :class:`HyperTreeList` will have virtual behaviour.
         ============================== =========== ==================================================

        :param `validator`: window validator;
        :param `name`: window name.
        """

        self._buffered = False
        
        CustomTreeCtrl.__init__(self, parent, id, pos, size, style, agwStyle, validator, name)
        
        self._shiftItem = None
        self._editItem = None
        self._selectItem = None

        self._curColumn = -1 # no current column
        self._owner = parent
        self._main_column = 0
        self._dragItem = None

        self._imgWidth = self._imgWidth2 = 0
        self._imgHeight = self._imgHeight2 = 0
        self._btnWidth = self._btnWidth2 = 0
        self._btnHeight = self._btnHeight2 = 0
        self._checkWidth = self._checkWidth2 = 0
        self._checkHeight = self._checkHeight2 = 0
        self._agwStyle = agwStyle
        self._current = None

        # TextCtrl initial settings for editable items
        self._editTimer = TreeListEditTimer(self)
        self._left_down_selection = False

        self._dragTimer = wx.Timer(self)
        self._findTimer = wx.Timer(self)
        
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)

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


    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the main window.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._buffered = buffered
        if buffered:
            self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        else:
            self.SetBackgroundStyle(wx.BG_STYLE_SYSTEM)


    def IsVirtual(self):
        """ Returns ``True`` if :class:`TreeListMainWindow` has the ``TR_VIRTUAL`` flag set. """
        
        return self.HasAGWFlag(TR_VIRTUAL)


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

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

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `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) 
         ================================= ========================
        """
        
        column = (column is not None and [column] or [self._main_column])[0]

        if column < 0:
            return _NO_IMAGE

        return item.GetImage(which, column)


    def SetItemImage(self, item, image, column=None, which=wx.TreeItemIcon_Normal):
        """
        Sets the item image for a particular item state.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `image`: an index within the normal image list specifying the image to use;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used;
        :param `which`: the item state.

        :see: :meth:`~TreeListMainWindow.GetItemImage` for a list of valid item states.
        """
        
        column = (column is not None and [column] or [self._main_column])[0]

        if column < 0:
            return
        
        item.SetImage(column, image, which)
        dc = wx.ClientDC(self)
        self.CalculateSize(item, dc)
        self.RefreshLine(item)


    def GetItemWindowEnabled(self, item, column=None):
        """
        Returns whether the window associated with an item is enabled or not.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        return item.GetWindowEnabled(column)


    def GetItemWindow(self, item, column=None):
        """
        Returns the window associated with an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """
        
        return item.GetWindow(column)


    def SetItemWindow(self, item, window, column=None):
        """
        Sets the window associated to an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.

        :note: The window parent should not be the :class:`HyperTreeList` itself, but actually
         an instance of :class:`TreeListMainWindow`. The current solution here is to reparent
         the window to this class.
        """

        # Reparent the window to ourselves
        if window.GetParent() != self:
            window.Reparent(self)
        
        item.SetWindow(window, column)
        if window:
            self._hasWindows = True
        

    def SetItemWindowEnabled(self, item, enable=True, column=None):
        """
        Sets whether the window associated with an item is enabled or not.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        item.SetWindowEnabled(enable, column)


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

    def IsItemVisible(self, item):
        """
        Returns whether the item is visible or not.

        :param `item`: an instance of :class:`TreeListItem`;
        """

        # 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 GetPrevChild(self, item, cookie):
        """
        Returns the previous child of an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :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).

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

        children = item.GetChildren()

        if cookie >= 0:            
            return children[cookie], cookie-1
        else:        
            # there are no more of them
            return None, cookie


    def GetFirstExpandedItem(self):
        """ Returns the first item which is in the expanded state. """

        return self.GetNextExpanded(self.GetRootItem())


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

        :param `item`: an instance of :class:`TreeListItem`.
        """                

        return CustomTreeCtrl.GetNextExpanded(self, item)


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

        :param `item`: an instance of :class:`TreeListItem`.
        """                

        return CustomTreeCtrl.GetPrevExpanded(self, item)


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

        return self.GetNextVisible(self.GetRootItem())


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

        :param `item`: an instance of :class:`TreeListItem`.
        """                

        i = self.GetPrev(item)
        while i:
            if self.IsItemVisible(i):
                return i
            i = self.GetPrev(i)
        
        return None


# ----------------------------------------------------------------------------
# operations
# ----------------------------------------------------------------------------

    def DoInsertItem(self, parent, 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 :class:`TreeListItem` representing the
         item's parent;
        :param `previous`: the index at which we should insert the item;
        :param `text`: the item text label;
        :param `ct_type`: the item type (see :meth:`CustomTreeCtrl.SetItemType() <lib.agw.customtreectrl.CustomTreeCtrl.SetItemType>` for a list of valid
         item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `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 `data`: associate the given Python object `data` with the item.
        :param `separator`: unused at the moment, this parameter is present to comply with
         :meth:`CustomTreeCtrl.DoInsertItem() <lib.agw.customtreectrl.CustomTreeCtrl.DoInsertItem>` changed API.
        """
        
        self._dirty = True # do this first so stuff below doesn't cause flicker
        arr = [""]*self.GetColumnCount()
        arr[self._main_column] = text
        
        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 = TreeListItem(self, parent, arr, ct_type, wnd, image, selImage, data)
        
        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 :class:`TreeListMainWindow`.

        :param `text`: the item text label;
        :param `ct_type`: the item type (see :meth:`CustomTreeCtrl.SetItemType() <lib.agw.customtreectrl.CustomTreeCtrl.SetItemType>`
         for a list of valid item types);
        :param `wnd`: if not ``None``, a non-toplevel window to show next to the item;
        :param `image`: an index within the normal image list specifying the image to
         use for the item in unselected state;
        :param `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 `data`: associate the given Python object `data` with the item.

        .. warning::

           Only one root is allowed to exist in any given instance of :class:`TreeListMainWindow`.
           
        """        

        if self._anchor:
            raise Exception("\nERROR: Tree Can Have Only One Root")

        if wnd is not None and not (self._agwStyle & wx.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._agwStyle & wx.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
        arr = [""]*self.GetColumnCount()
        arr[self._main_column] = text
        self._anchor = TreeListItem(self, None, arr, ct_type, wnd, image, selImage, data)
        
        if wnd is not None:
            self._hasWindows = True
            self._itemWithWindow.append(self._anchor)            
        
        if self.HasAGWFlag(wx.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(wx.TR_MULTIPLE):
            self._current = self._key_current = self._selectItem = self._anchor
            self._current.SetHilight(True)
        
        return self._anchor


    def Delete(self, item):
        """
        Deletes an item.

        :param `item`: an instance of :class:`TreeListItem`.
        """

        if not item:
            raise Exception("\nERROR: Invalid Tree Item. ")
        
        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()

        # don't stay with invalid self._shiftItem or we will crash in the next call to OnChar()
        changeKeyCurrent = False
        itemKey = self._shiftItem
        
        while itemKey:
            if itemKey == item:  # self._shiftItem is a descendant of the item being deleted
                changeKeyCurrent = True
                break
            
            itemKey = itemKey.GetParent()
        
        parent = item.GetParent()
        if parent:
            parent.GetChildren().remove(item)  # remove by value
        
        if changeKeyCurrent:
            self._shiftItem = parent

        self.SendDeleteEvent(item)
        if self._selectItem == item:
            self._selectItem = None

        # Remove the item with window
        if item in self._itemWithWindow:
            for wnd in item._wnd:
                if wnd:
                    wnd.Hide()
                    wnd.Destroy()
                
            item._wnd = []
            self._itemWithWindow.remove(item)
            
        item.DeleteChildren(self)
        del item


    # 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's children.

        :param `item`: an instance of :class:`TreeListItem`.
        """

        if self._editCtrl != None and item != self._editCtrl.item() and self.IsDescendantOf(item, self._editCtrl.item()):
            self._editCtrl.StopEditing()

        if self.IsDescendantOf(item, self._selectItem):
            self._selectItem = item
            
        if item != self._current and self.IsDescendantOf(item, self._current):
            self._current.SetHilight(False)
            self._current = None

            
    def DeleteRoot(self):
        """
        Removes the tree root item (and subsequently all the items in
        :class:`TreeListMainWindow`.
        """

        if self._anchor:

            self._dirty = True

            self._anchor.DeleteChildren(self)
            self.Delete(self._anchor)

            self.SendDeleteEvent(self._anchor)
            self._current = None
            self._selectItem = None
            del self._anchor
            self._anchor = None


    def DeleteAllItems(self):
        """ Delete all items in the :class:`TreeListMainWindow`. """

        self.DeleteRoot()
        

    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """
        
        for child in self._itemWithWindow:
            if not self.IsItemVisible(child):
                for column in xrange(self.GetColumnCount()):
                    wnd = child.GetWindow(column)
                    if wnd and wnd.IsShown():
                        wnd.Hide()
                

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

        :param `item`: an instance of :class:`TreeListItem`;
        :param `enable`: ``True`` to enable the item, ``False`` otherwise;
        :param `torefresh`: whether to redraw the item or not.
        """
        
        if item.IsEnabled() == enable:
            return

        if not enable and item.IsSelected():
            self.DoSelectItem(item, not self.HasAGWFlag(wx.TR_MULTIPLE))

        item.Enable(enable)

        for column in xrange(self.GetColumnCount()):
            wnd = item.GetWindow(column)

            # Handles the eventual window associated to the item        
            if wnd:
                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 :class:`TreeListItem`.
        """

        return item.IsEnabled()
    

    def GetCurrentItem(self):
        """ Returns the current item. """

        return self._current

    
    def GetColumnCount(self):
        """ Returns the total number of columns. """

        return self._owner.GetHeaderWindow().GetColumnCount()


    def SetMainColumn(self, column):
        """
        Sets the :class:`HyperTreeList` main column (i.e. the position of the underlying
        :class:`~lib.agw.customtreectrl.CustomTreeCtrl`.

        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """
        
        if column >= 0 and column < self.GetColumnCount():
            self._main_column = column


    def GetMainColumn(self):
        """
        Returns the :class:`HyperTreeList` main column (i.e. the position of the underlying
        :class:`~lib.agw.customtreectrl.CustomTreeCtrl`.
        """
        
        return self._main_column
    

    def ScrollTo(self, item):
        """
        Scrolls the specified item into view.

        :param `item`: an instance of :class:`TreeListItem`.
        """

        # ensure that the position of the item it calculated in any case
        if self._dirty:
            self.CalculatePositions()

        # now scroll to the item
        xUnit, yUnit = self.GetScrollPixelsPerUnit()
        start_x, start_y = self.GetViewStart()
        start_y *= yUnit
        client_w, client_h = self.GetClientSize ()

        x, y = self._anchor.GetSize (0, 0, self)
        x = self._owner.GetHeaderWindow().GetWidth()
        y += yUnit + 2 # one more scrollbar unit + 2 pixels
        x_pos = self.GetScrollPos(wx.HORIZONTAL)

        if item._y < start_y+3:
            # going down, item should appear at top
            self.SetScrollbars(xUnit, yUnit, (xUnit and [x/xUnit] or [0])[0], (yUnit and [y/yUnit] or [0])[0],
                               x_pos, (yUnit and [item._y/yUnit] or [0])[0])
            
        elif item._y+self.GetLineHeight(item) > start_y+client_h:
            # going up, item should appear at bottom
            item._y += yUnit + 2
            self.SetScrollbars(xUnit, yUnit, (xUnit and [x/xUnit] or [0])[0], (yUnit and [y/yUnit] or [0])[0],
                               x_pos, (yUnit and [(item._y+self.GetLineHeight(item)-client_h)/yUnit] or [0])[0])
        

    def SetDragItem(self, item):
        """
        Sets the specified item as member of a current drag and drop operation.

        :param `item`: an instance of :class:`TreeListItem`.
        """

        prevItem = self._dragItem
        self._dragItem = item
        if prevItem:
            self.RefreshLine(prevItem)
        if self._dragItem:
            self.RefreshLine(self._dragItem)


# ----------------------------------------------------------------------------
# helpers
# ----------------------------------------------------------------------------

    def AdjustMyScrollbars(self):
        """ Internal method used to adjust the :class:`PyScrolledWindow` scrollbars. """

        if self._anchor:
            xUnit, yUnit = self.GetScrollPixelsPerUnit()
            if xUnit == 0:
                xUnit = self.GetCharWidth()
            if yUnit == 0:
                yUnit = self._lineHeight

            x, y = self._anchor.GetSize(0, 0, self)
            y += yUnit + 2 # one more scrollbar unit + 2 pixels
            x_pos = self.GetScrollPos(wx.HORIZONTAL)
            y_pos = self.GetScrollPos(wx.VERTICAL)
            x = self._owner.GetHeaderWindow().GetWidth() + 2
            if x < self.GetClientSize().GetWidth():
                x_pos = 0

            self.SetScrollbars(xUnit, yUnit, x/xUnit, y/yUnit, x_pos, y_pos)
        else:
            self.SetScrollbars(0, 0, 0, 0)
    

    def PaintItem(self, item, dc):
        """
        Actually draws an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `dc`: an instance of :class:`DC`.
        """

        def _paintText(text, textrect, alignment):
            """
            Sub-function to draw multi-lines text label aligned correctly.

            :param `text`: the item text label (possibly multiline);
            :param `textrect`: the label client rectangle;
            :param `alignment`: the alignment for the text label, one of ``wx.ALIGN_LEFT``,
             ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``.
            """
            
            txt = text.splitlines()
            if alignment != wx.ALIGN_LEFT and len(txt):
                yorigin = textrect.Y
                for t in txt:
                    w, h = dc.GetTextExtent(t)
                    plus = textrect.Width - w
                    if alignment == wx.ALIGN_CENTER:
                        plus /= 2
                    dc.DrawLabel(t, wx.Rect(textrect.X + plus, yorigin, w, yorigin+h))
                    yorigin += h
                return
            dc.DrawLabel(text, textrect)
        
        attr = item.GetAttributes()
        
        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        elif item.IsBold():
            dc.SetFont(self._boldFont)
        if item.IsHyperText():
            dc.SetFont(self.GetHyperTextFont())
            if item.GetVisited():
                dc.SetTextForeground(self.GetHyperTextVisitedColour())
            else:
                dc.SetTextForeground(self.GetHyperTextNewColour())

        colText = wx.Colour(*dc.GetTextForeground())
        
        if item.IsSelected():
            if (wx.Platform == "__WXMAC__" and self._hasFocus):
                colTextHilight = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                colTextHilight = wx.SystemSettings_GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)

        else:
            attr = item.GetAttributes()
            if attr and attr.HasTextColour():
                colText = attr.GetTextColour()
            
        if self._vistaselection:
            colText = colTextHilight = wx.BLACK
                
        total_w = self._owner.GetHeaderWindow().GetWidth()
        total_h = self.GetLineHeight(item)
        off_h = (self.HasAGWFlag(wx.TR_ROW_LINES) and [1] or [0])[0]
        off_w = (self.HasAGWFlag(wx.TR_COLUMN_LINES) and [1] or [0])[0]
##        clipper = wx.DCClipper(dc, 0, item.GetY(), total_w, total_h) # only within line

        text_w, text_h, dummy = dc.GetMultiLineTextExtent(item.GetText(self.GetMainColumn()))

        drawItemBackground = False
        # determine background and show it
        if attr and attr.HasBackgroundColour():
            colBg = attr.GetBackgroundColour()
            drawItemBackground = True
        else:
            colBg = self._backgroundColour
        
        dc.SetBrush(wx.Brush(colBg, wx.SOLID))

        if attr and attr.HasBorderColour():
            colBorder = attr.GetBorderColour()
            dc.SetPen(wx.Pen(colBorder, 1, wx.SOLID))
        else:
            dc.SetPen(wx.TRANSPARENT_PEN)

        if self.HasAGWFlag(wx.TR_FULL_ROW_HIGHLIGHT):

            itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)
            
            if item == self._dragItem:
                dc.SetBrush(self._hilightBrush)
                if wx.Platform == "__WXMAC__":
                    dc.SetPen((item == self._dragItem) and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0]

                dc.SetTextForeground(colTextHilight)

            elif item.IsSelected():

                wnd = item.GetWindow(self._main_column)
                wndx = 0
                if wnd:
                    wndx, wndy = item.GetWindowSize(self._main_column)

                itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)
                
                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._owner, dc, itemrect, flags) 
                    else:
                        dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                        dc.SetPen((self._hasFocus and [self._borderPen] or [wx.TRANSPARENT_PEN])[0])
                        dc.DrawRectangleRect(itemrect)
                
                dc.SetTextForeground(colTextHilight)

            # 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:

                itemrect = wx.Rect(0, item.GetY() + off_h, total_w-1, total_h - off_h)
                dc.SetBrush(wx.Brush(colBg, wx.SOLID))
                dc.DrawRectangleRect(itemrect)
                dc.SetTextForeground(colText)
                                                
            else:
                dc.SetTextForeground(colText)

        else:
            
            dc.SetTextForeground(colText)

        text_extraH = (total_h > text_h and [(total_h - text_h)/2] or [0])[0]
        img_extraH = (total_h > self._imgHeight and [(total_h-self._imgHeight)/2] or [0])[0]
        x_colstart = 0
        
        for i in xrange(self.GetColumnCount()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue

            col_w = self._owner.GetHeaderWindow().GetColumnWidth(i)
            dc.SetClippingRegion(x_colstart, item.GetY(), col_w, total_h) # only within column

            image = _NO_IMAGE
            x = image_w = wcheck = hcheck = 0

            if i == self.GetMainColumn():
                x = item.GetX() + _MARGIN
                if self.HasButtons():
                    x += (self._btnWidth-self._btnWidth2) + _LINEATROOT
                else:
                    x -= self._indent/2
                
                if self._imageListNormal:
                    image = item.GetCurrentImage(i)
                    
                if item.GetType() != 0 and self._imageListCheck:
                    checkimage = item.GetCurrentCheckedImage()
                    wcheck, hcheck = self._imageListCheck.GetSize(item.GetType())
                else:
                    wcheck, hcheck = 0, 0
            
            else:
                x = x_colstart + _MARGIN
                image = item.GetImage(column=i)
                
            if image != _NO_IMAGE:
                image_w = self._imgWidth + _MARGIN

            # honor text alignment
            text = item.GetText(i)
            alignment = self._owner.GetHeaderWindow().GetColumn(i).GetAlignment()

            text_w, dummy, dummy = dc.GetMultiLineTextExtent(text)

            if alignment == wx.ALIGN_RIGHT:
                w = col_w - (image_w + wcheck + text_w + off_w + _MARGIN + 1)
                x += (w > 0 and [w] or [0])[0]

            elif alignment == wx.ALIGN_CENTER:
                w = (col_w - (image_w + wcheck + text_w + off_w + _MARGIN))/2
                x += (w > 0 and [w] or [0])[0]
            else:
                if image_w == 0 and wcheck:
                    x += 2*_MARGIN
            
            text_x = x + image_w + wcheck + 1
            
            if i == self.GetMainColumn():
                item.SetTextX(text_x)

            if not self.HasAGWFlag(wx.TR_FULL_ROW_HIGHLIGHT):
                dc.SetBrush((self._hasFocus and [self._hilightBrush] or [self._hilightUnfocusedBrush])[0])
                dc.SetPen((self._hasFocus and [self._borderPen] or [wx.TRANSPARENT_PEN])[0])
                if i == self.GetMainColumn():
                    if item == self._dragItem:
                        if wx.Platform == "__WXMAC__":  # don't draw rect outline if we already have the background colour
                            dc.SetPen((item == self._dragItem and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0])

                        dc.SetTextForeground(colTextHilight)
                        
                    elif item.IsSelected():

                        itemrect = wx.Rect(text_x-2, item.GetY() + off_h, text_w+2*_MARGIN, total_h - off_h)

                        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._owner, dc, itemrect, flags) 
                            else:
                                dc.DrawRectangleRect(itemrect)

                        dc.SetTextForeground(colTextHilight)

                    elif item == self._current:
                        dc.SetPen((self._hasFocus and [wx.BLACK_PEN] or [wx.TRANSPARENT_PEN])[0])
                    
                    # 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:

                        itemrect = wx.Rect(text_x-2, item.GetY() + off_h, text_w+2*_MARGIN, total_h - off_h)
                        dc.SetBrush(wx.Brush(colBg, wx.SOLID))
                        dc.DrawRectangleRect(itemrect)

                    else:
                        dc.SetTextForeground(colText)
    
                else:
                    dc.SetTextForeground(colText)
                
            if self.HasAGWFlag(wx.TR_COLUMN_LINES):  # vertical lines between columns
                pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT), 1, wx.SOLID)
                dc.SetPen((self.GetBackgroundColour() == wx.WHITE and [pen] or [wx.WHITE_PEN])[0])
                dc.DrawLine(x_colstart+col_w-1, item.GetY(), x_colstart+col_w-1, item.GetY()+total_h)
            
            dc.SetBackgroundMode(wx.TRANSPARENT)

            if image != _NO_IMAGE:
                y = item.GetY() + img_extraH
                if wcheck:
                    x += wcheck

                if item.IsEnabled():
                    imglist = self._imageListNormal
                else:
                    imglist = self._grayedImageList
                
                imglist.Draw(image, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

            if wcheck:
                if item.IsEnabled():
                    imglist = self._imageListCheck
                else:
                    imglist = self._grayedCheckList

                if self.HasButtons():  # should the item show a button?
                    btnWidth = self._btnWidth
                else:
                    btnWidth = -self._btnWidth
                
                imglist.Draw(checkimage, dc,
                             item.GetX() + btnWidth + _MARGIN,
                             item.GetY() + ((total_h > hcheck) and [(total_h-hcheck)/2] or [0])[0]+1,
                             wx.IMAGELIST_DRAW_TRANSPARENT)

            text_w, text_h, dummy = dc.GetMultiLineTextExtent(text)
            text_extraH = (total_h > text_h and [(total_h - text_h)/2] or [0])[0]            
            text_y = item.GetY() + text_extraH
            textrect = wx.Rect(text_x, text_y, text_w, text_h)

            if self.HasAGWFlag(TR_ELLIPSIZE_LONG_ITEMS):
                if i == self.GetMainColumn():
                    maxsize = col_w - text_x - _MARGIN
                else:
                    maxsize = col_w - (wcheck + image_w + _MARGIN)

                text = ChopText(dc, text, maxsize)
        
            if not item.IsEnabled():
                foreground = dc.GetTextForeground()
                dc.SetTextForeground(self._disabledColour)
                _paintText(text, textrect, alignment)
                dc.SetTextForeground(foreground)
            else:
                if wx.Platform == "__WXMAC__" and item.IsSelected() and self._hasFocus:
                    dc.SetTextForeground(wx.WHITE)
                _paintText(text, textrect, alignment)

            wnd = item.GetWindow(i)            
            if wnd:
                if text_w == 0:
                    wndx = text_x
                else:
                    wndx = text_x + text_w + 2*_MARGIN
                xa, ya = self.CalcScrolledPosition((0, item.GetY()))
                wndx += xa
                if item.GetHeight() > item.GetWindowSize(i)[1]:
                    ya += (item.GetHeight() - item.GetWindowSize(i)[1])/2
                    
                if not wnd.IsShown():
                    wnd.Show()
                if wnd.GetPosition() != (wndx, ya):
                    wnd.SetPosition((wndx, ya))                
            
            x_colstart += col_w
            dc.DestroyClippingRegion()
        
        # 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, x_maincol):
        """
        Paint a level in the hierarchy of :class:`TreeListMainWindow`.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `dc`: an instance of :class:`DC`;
        :param `level`: the item level in the tree hierarchy;
        :param `y`: the current vertical position in the :class:`PyScrolledWindow`;
        :param `x_maincol`: the horizontal position of the main column.
        """

        if item.IsHidden():
            return y, x_maincol
        
        # Handle hide root (only level 0)
        if self.HasAGWFlag(wx.TR_HIDE_ROOT) and level == 0:
            for child in item.GetChildren():
                y, x_maincol = self.PaintLevel(child, dc, 1, y, x_maincol)
            
            # end after expanding root
            return y, x_maincol
        
        # calculate position of vertical lines
        x = x_maincol + _MARGIN # start of column

        if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
            x += _LINEATROOT # space for lines at root
            
        if self.HasButtons():
            x += (self._btnWidth-self._btnWidth2) # half button space
        else:
            x += (self._indent-self._indent/2)
        
        if self.HasAGWFlag(wx.TR_HIDE_ROOT):
            x += self._indent*(level-1) # indent but not level 1
        else:
            x += self._indent*level # indent according to level
        
        # set position of vertical line
        item.SetX(x)
        item.SetY(y)

        h = self.GetLineHeight(item)
        y_top = y
        y_mid = y_top + (h/2)
        y += h

        exposed_x = dc.LogicalToDeviceX(0)
        exposed_y = dc.LogicalToDeviceY(y_top)

        # horizontal lines between rows?
        draw_row_lines = self.HasAGWFlag(wx.TR_ROW_LINES)

        if self.IsExposed(exposed_x, exposed_y, _MAX_WIDTH, h + draw_row_lines):
            if draw_row_lines:
                total_width = self._owner.GetHeaderWindow().GetWidth()
                # if the background colour is white, choose a
                # contrasting colour for the lines
                pen = wx.Pen(wx.SystemSettings_GetColour(wx.SYS_COLOUR_3DLIGHT), 1, wx.SOLID)
                dc.SetPen((self.GetBackgroundColour() == wx.WHITE and [pen] or [wx.WHITE_PEN])[0])
                dc.DrawLine(0, y_top, total_width, y_top)
                dc.DrawLine(0, y_top+h, total_width, y_top+h)
            
            # draw item
            self.PaintItem(item, dc)

            # restore DC objects
            dc.SetBrush(wx.WHITE_BRUSH)
            dc.SetPen(self._dottedPen)

            # clip to the column width
            clip_width = self._owner.GetHeaderWindow().GetColumn(self._main_column).GetWidth()
##            clipper = wx.DCClipper(dc, x_maincol, y_top, clip_width, 10000)

            if not self.HasAGWFlag(wx.TR_NO_LINES):  # connection lines

                # draw the horizontal line here
                dc.SetPen(self._dottedPen)
                x2 = x - self._indent
                if x2 < (x_maincol + _MARGIN):
                    x2 = x_maincol + _MARGIN
                x3 = x + (self._btnWidth-self._btnWidth2)
                if self.HasButtons():
                    if item.HasPlus():
                        dc.DrawLine(x2, y_mid, x - self._btnWidth2, y_mid)
                        dc.DrawLine(x3, y_mid, x3 + _LINEATROOT, y_mid)
                    else:
                        dc.DrawLine(x2, y_mid, x3 + _LINEATROOT, y_mid)
                else:
                    dc.DrawLine(x2, y_mid, x - self._indent/2, y_mid)
                
            if item.HasPlus() and self.HasButtons():  # should the item show a button?
                
                if self._imageListButtons:

                    # draw the image button here
                    image = wx.TreeItemIcon_Normal
                    if item.IsExpanded():
                        image = wx.TreeItemIcon_Expanded
                    if item.IsSelected():
                        image += wx.TreeItemIcon_Selected - wx.TreeItemIcon_Normal
                    xx = x - self._btnWidth2 + _MARGIN
                    yy = y_mid - self._btnHeight2
                    dc.SetClippingRegion(xx, yy, self._btnWidth, self._btnHeight)
                    self._imageListButtons.Draw(image, dc, xx, yy, wx.IMAGELIST_DRAW_TRANSPARENT)
                    dc.DestroyClippingRegion()

                elif self.HasAGWFlag(wx.TR_TWIST_BUTTONS):

                    # draw the twisty button here
                    dc.SetPen(wx.BLACK_PEN)
                    dc.SetBrush(self._hilightBrush)
                    button = [wx.Point() for j in xrange(3)]
                    if item.IsExpanded():
                        button[0].x = x - (self._btnWidth2+1)
                        button[0].y = y_mid - (self._btnHeight/3)
                        button[1].x = x + (self._btnWidth2+1)
                        button[1].y = button[0].y
                        button[2].x = x
                        button[2].y = button[0].y + (self._btnHeight2+1)
                    else:
                        button[0].x = x - (self._btnWidth/3)
                        button[0].y = y_mid - (self._btnHeight2+1)
                        button[1].x = button[0].x
                        button[1].y = y_mid + (self._btnHeight2+1)
                        button[2].x = button[0].x + (self._btnWidth2+1)
                        button[2].y = y_mid
                    
                    dc.SetClippingRegion(x_maincol + _MARGIN, y_top, clip_width, h)
                    dc.DrawPolygon(button)
                    dc.DestroyClippingRegion()

                else: # if (HasAGWFlag(wxTR_HAS_BUTTONS))

                    rect = wx.Rect(x-self._btnWidth2, y_mid-self._btnHeight2, self._btnWidth, self._btnHeight)
                    flag = (item.IsExpanded() and [wx.CONTROL_EXPANDED] or [0])[0]
                    wx.RendererNative.GetDefault().DrawTreeItemButton(self, dc, rect, flag)        

        # restore DC objects
        dc.SetBrush(wx.WHITE_BRUSH)
        dc.SetPen(self._dottedPen)
        dc.SetTextForeground(wx.BLACK)

        if item.IsExpanded():

            # process lower levels
            if self._imgWidth > 0:
                oldY = y_mid + self._imgHeight2
            else:
                oldY = y_mid + h/2
            
            for child in item.GetChildren():

                y, x_maincol = self.PaintLevel(child, dc, level+1, y, x_maincol)

                # draw vertical line
                if not self.HasAGWFlag(wx.TR_NO_LINES):
                    Y1 = child.GetY() + child.GetHeight()/2
                    dc.DrawLine(x, oldY, x, Y1)

        return y, x_maincol        


# ----------------------------------------------------------------------------
# wxWindows callbacks
# ----------------------------------------------------------------------------

    def OnEraseBackground(self, event):
        """
        Handles the ``wx.EVT_ERASE_BACKGROUND`` event for :class:`TreeListMainWindow`.

        :param `event`: a :class:`EraseEvent` event to be processed.
        """

        # do not paint the background separately in buffered mode.
        if not self._buffered:
            CustomTreeCtrl.OnEraseBackground(self, event)


    def OnPaint(self, event):
        """
        Handles the ``wx.EVT_PAINT`` event for :class:`TreeListMainWindow`.

        :param `event`: a :class:`PaintEvent` event to be processed.
        """

        if self._buffered:

            # paint the background
            dc = wx.BufferedPaintDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
            dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
            if self._backgroundImage:
                self.TileBackground(dc)
            else:
                dc.Clear()

        else:
            dc = wx.PaintDC(self)

        self.PrepareDC(dc)

        if not self._anchor or self.GetColumnCount() <= 0:
            return

        # calculate button size
        if self._imageListButtons:
            self._btnWidth, self._btnHeight = self._imageListButtons.GetSize(0)
        elif self.HasButtons():
            self._btnWidth = _BTNWIDTH
            self._btnHeight = _BTNHEIGHT
        
        self._btnWidth2 = self._btnWidth/2
        self._btnHeight2 = self._btnHeight/2

        # calculate image size
        if self._imageListNormal:
            self._imgWidth, self._imgHeight = self._imageListNormal.GetSize(0)
        
        self._imgWidth2 = self._imgWidth/2
        self._imgHeight2 = self._imgHeight/2

        if self._imageListCheck:
            self._checkWidth, self._checkHeight = self._imageListCheck.GetSize(0)

        self._checkWidth2 = self._checkWidth/2
        self._checkHeight2 = self._checkHeight/2
            
        # calculate indent size
        if self._imageListButtons:
            self._indent = max(_MININDENT, self._btnWidth + _MARGIN)
        elif self.HasButtons():
            self._indent = max(_MININDENT, self._btnWidth + _LINEATROOT)
        
        # set default values
        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        # calculate column start and paint
        x_maincol = 0
        for i in xrange(self.GetMainColumn()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue
            x_maincol += self._owner.GetHeaderWindow().GetColumnWidth(i)
        
        y, x_maincol = self.PaintLevel(self._anchor, dc, 0, 0, x_maincol)


    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 plus the item's column.

        :param `point`: an instance of :class:`Point`, a point to test for hits;
        :param `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: the item (if any, ``None`` otherwise), the `flags` and the column are always
         returned as a tuple.
        """

        w, h = self.GetSize()
        column = -1

        if not isinstance(point, wx.Point):
            point = wx.Point(*point)

        if point.x < 0:
            flags |= wx.TREE_HITTEST_TOLEFT
        if point.x > w:
            flags |= wx.TREE_HITTEST_TORIGHT
        if point.y < 0:
            flags |= wx.TREE_HITTEST_ABOVE
        if point.y > h:
            flags |= wx.TREE_HITTEST_BELOW
        if flags:
            return None, flags, column

        if not self._anchor:
            flags = wx.TREE_HITTEST_NOWHERE
            column = -1
            return None, flags, column
        
        hit, flags, column = self._anchor.HitTest(self.CalcUnscrolledPosition(point), self, flags, column, 0)
        if not hit:
            flags = wx.TREE_HITTEST_NOWHERE
            column = -1
            return None, flags, column
        
        return hit, flags, column


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

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.        
        """

        if not item:
            return

        column = (column is not None and [column] or [self._main_column])[0]
        
        if column < 0 or column >= self.GetColumnCount():
            return

        self._curColumn = column
        self._editItem = item

        te = TreeEvent(wx.wxEVT_COMMAND_TREE_BEGIN_LABEL_EDIT, self._owner.GetId())
        te.SetItem(self._editItem)
        te.SetInt(column)
        te.SetEventObject(self._owner)
        self._owner.GetEventHandler().ProcessEvent(te)

        if not te.IsAllowed():
            return

        # ensure that the position of the item it calculated in any case
        if self._dirty:
            self.CalculatePositions()
            
        if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
            self._editCtrl.StopEditing()
            
        self._editCtrl = self._owner.CreateEditCtrl(item, column) 
        self._editCtrl.SetFocus()
        

    def OnEditTimer(self):
        """ The timer for editing has expired. Start editing. """

        self.EditLabel(self._current, self._curColumn)


    def OnAcceptEdit(self, value):
        """
        Called by :class:`EditTextCtrl`, to accept the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.

        :param `value`: the new value of the item label.        
        """

        # TODO if the validator fails this causes a crash
        le = TreeEvent(wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT, self._owner.GetId())
        le.SetItem(self._editItem)
        le.SetEventObject(self._owner)
        le.SetLabel(value)
        le.SetInt(self._curColumn if self._curColumn >= 0 else 0)
        le._editCancelled = False
        self._owner.GetEventHandler().ProcessEvent(le)

        if not le.IsAllowed():
            return

        if self._curColumn == -1:
            self._curColumn = 0
           
        self.SetItemText(self._editItem, unicode(value), self._curColumn)


    def OnCancelEdit(self):
        """
        Called by :class:`EditCtrl`, to cancel the changes and to send the
        ``EVT_TREE_END_LABEL_EDIT`` event.
        """

        # let owner know that the edit was cancelled
        le = TreeEvent(wx.wxEVT_COMMAND_TREE_END_LABEL_EDIT, self._owner.GetId())
        le.SetItem(self._editItem)
        le.SetEventObject(self._owner)
        le.SetLabel("")
        le._editCancelled = True

        self._owner.GetEventHandler().ProcessEvent(le)

    
    def OnMouse(self, event):
        """
        Handles the ``wx.EVT_MOUSE_EVENTS`` event for :class:`TreeListMainWindow`.

        :param `event`: a :class:`MouseEvent` event to be processed.
        """

        if not self._anchor:
            return

        # 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.RightUp() or event.LeftDClick() or event.Dragging() or \
                event.GetWheelRotation() != 0 or event.Moving()):
            self._owner.GetEventHandler().ProcessEvent(event)
            return
        

        # set focus if window clicked
        if event.LeftDown() or event.RightDown():
            self._hasFocus = True
            self.SetFocusIgnoringChildren()

        # determine event
        p = wx.Point(event.GetX(), event.GetY())
        flags = 0
        item, flags, column = self._anchor.HitTest(self.CalcUnscrolledPosition(p), self, flags, self._curColumn, 0)

        underMouse = item
        underMouseChanged = underMouse != self._underMouse

        if underMouse and (flags & wx.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 = item

        if (event.LeftDown() or event.LeftUp() or event.RightDown() or \
            event.RightUp() or event.LeftDClick() or event.Dragging()):
            if self._editCtrl != None and (item != self._editCtrl.item() or column != self._editCtrl.column()):
                self._editCtrl.StopEditing()

        # 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(wx.wxEVT_COMMAND_TREE_ITEM_GETTOOLTIP, self.GetId())
                hevent.SetItem(hoverItem)
                hevent.SetEventObject(self)

                if self.GetEventHandler().ProcessEvent(hevent) and hevent.IsAllowed():
                    self.SetToolTip(hevent._label)

                if hoverItem.IsHyperText() and (flags & wx.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 only process dragging here
        if event.Dragging():
            
            if self._isDragging:
                if not self._dragImage:
                    # Create the custom draw image from the icons and the text of the item                    
                    self._dragImage = DragImage(self, self._current or item)
                    self._dragImage.BeginDrag(wx.Point(0,0), self)
                    self._dragImage.Show()

                self._dragImage.Move(p)

                if self._countDrag == 0 and item:
                    self._oldItem = self._current
                    self._oldSelection = self._current

                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 and self._oldItem is not None:
                    # Here I am trying to avoid ugly repainting problems... hope it works
                    self.RefreshLine(self._oldItem)
                    self._countDrag = 0
                    
                return # nothing to do, already done

            if item == None:
                return # we need an item to dragging

            # determine drag start
            if self._dragCount == 0:
                self._dragTimer.Start(_DRAG_TIMER_TICKS, wx.TIMER_ONE_SHOT)
            
            self._dragCount += 1
            if self._dragCount < 3:
                return # minimum drag 3 pixel
            if self._dragTimer.IsRunning():
                return

            # we're going to drag
            self._dragCount = 0

            # send drag start event
            command = (event.LeftIsDown() and [wx.wxEVT_COMMAND_TREE_BEGIN_DRAG] or [wx.wxEVT_COMMAND_TREE_BEGIN_RDRAG])[0]
            nevent = TreeEvent(command, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(self._current) # the dragged item
            nevent.SetPoint(p)
            nevent.Veto()         # dragging must be explicit allowed!
            
            if self.GetEventHandler().ProcessEvent(nevent) and nevent.IsAllowed():
                
                # we're going to drag this item
                self._isDragging = True
                self.CaptureMouse()
                self.RefreshSelected()

                # in a single selection control, hide the selection temporarily
                if not (self._agwStyle & wx.TR_MULTIPLE):
                    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)

        elif self._isDragging:  # any other event but not event.Dragging()

            # end dragging
            self._dragCount = 0
            self._isDragging = False
            if self.HasCapture():
                self.ReleaseMouse()
            self.RefreshSelected()

            # send drag end event event
            nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_END_DRAG, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(item) # the item the drag is started
            nevent.SetPoint(p)
            self._owner.GetEventHandler().ProcessEvent(nevent)
            
            if self._dragImage:
                self._dragImage.EndDrag()

            if self._dropTarget:
                self._dropTarget.SetHilight(False)
                self.RefreshLine(self._dropTarget)
                
            if self._oldSelection:
                self._oldSelection.SetHilight(True)
                self.RefreshLine(self._oldSelection)
                self._oldSelection = None

            self._isDragging = False
            self._dropTarget = None
            if self._dragImage:
                self._dragImage = None
            
            self.Refresh()

        elif self._dragCount > 0:  # just in case dragging is initiated

            # end dragging
            self._dragCount = 0

        # we process only the messages which happen on tree items
        if (item == None or not self.IsItemEnabled(item)) and not event.GetWheelRotation():
            self._owner.GetEventHandler().ProcessEvent(event)
            return
        
        # remember item at shift down
        if event.ShiftDown():
            if not self._shiftItem:
                self._shiftItem = self._current
        else:
            self._shiftItem = None
        
        if event.RightUp():

            self.SetFocus()
            nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_RIGHT_CLICK, self._owner.GetId())
            nevent.SetEventObject(self._owner)
            nevent.SetItem(item) # the item clicked
            nevent.SetInt(self._curColumn) # the column clicked
            nevent.SetPoint(p)
            self._owner.GetEventHandler().ProcessEvent(nevent)

        elif event.LeftUp():

            if self._lastOnSame:
                if item == self._current and self._curColumn != -1 and \
                   self._owner.GetHeaderWindow().IsColumnEditable(self._curColumn) and \
                   flags & (wx.TREE_HITTEST_ONITEMLABEL | wx.TREE_HITTEST_ONITEMCOLUMN) and \
                   ((self._editCtrl != None and column != self._editCtrl.column()) or self._editCtrl is None):
                    self._editTimer.Start(_EDIT_TIMER_TICKS, wx.TIMER_ONE_SHOT)
                
                self._lastOnSame = False
            
            if (((flags & wx.TREE_HITTEST_ONITEMBUTTON) or (flags & wx.TREE_HITTEST_ONITEMICON)) and \
                self.HasButtons() and item.HasPlus()):

                # 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         
            
            # determine the selection if not done by left down
            if not self._left_down_selection:
                unselect_others = not ((event.ShiftDown() or event.CmdDown()) and self.HasAGWFlag(wx.TR_MULTIPLE))
                self.DoSelectItem(item, unselect_others, event.ShiftDown())
                self.EnsureVisible (item)
                self._current = self._key_current = item # make the new item the current item
            else:
                self._left_down_selection = False
            
        elif event.LeftDown() or event.RightDown() or event.LeftDClick():

            if column >= 0:
                self._curColumn = column
            
            if event.LeftDown() or event.RightDown():
                self.SetFocus()
                self._lastOnSame = item == self._current
            
            if (((flags & wx.TREE_HITTEST_ONITEMBUTTON) or (flags & wx.TREE_HITTEST_ONITEMICON)) and \
                self.HasButtons() and item.HasPlus()):

                # 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 flags & TREE_HITTEST_ONITEMCHECKICON and event.LeftDown():
                if item.GetType() > 0:
                    if self.IsItem3State(item):
                        checked = self.GetItem3StateValue(item)
                        checked = (checked+1)%3
                    else:
                        checked = not self.IsItemChecked(item)

                    self.CheckItem(item, checked)
                    return
                
            # determine the selection if the current item is not selected
            if not item.IsSelected():
                unselect_others = not ((event.ShiftDown() or event.CmdDown()) and self.HasAGWFlag(wx.TR_MULTIPLE))
                self.DoSelectItem(item, unselect_others, event.ShiftDown())
                self.EnsureVisible(item)
                self._current = self._key_current = item # make the new item the current item
                self._left_down_selection = True
            
            # 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
                self._editTimer.Stop()
                self._lastOnSame = False

                # send activate event first
                nevent = TreeEvent(wx.wxEVT_COMMAND_TREE_ITEM_ACTIVATED, self._owner.GetId())
                nevent.SetEventObject(self._owner)
                nevent.SetItem(item) # the item clicked
                nevent.SetInt(self._curColumn) # the column clicked
                nevent.SetPoint(p)
                if not self._owner.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)
                
        else: # any other event skip just in case

            event.Skip()

        
    def OnScroll(self, event):
        """
        Handles the ``wx.EVT_SCROLLWIN`` event for :class:`TreeListMainWindow`.

        :param `event`: a :class:`ScrollEvent` event to be processed.
        """

        def _updateHeaderWindow(header):
            header.Refresh()
            header.Update()
            
        # Update the header window after this scroll event has fully finished
        # processing, and the scoll action is complete.
        if event.GetOrientation() == wx.HORIZONTAL:
            wx.CallAfter(_updateHeaderWindow, self._owner.GetHeaderWindow())
        event.Skip()
            

    def CalculateSize(self, item, dc):
        """
        Calculates overall position and size of an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `dc`: an instance of :class:`DC`.
        """

        attr = item.GetAttributes()

        if attr and attr.HasFont():
            dc.SetFont(attr.GetFont())
        elif item.IsBold():
            dc.SetFont(self._boldFont)
        else:
            dc.SetFont(self._normalFont)

        text_w = text_h = wnd_w = wnd_h = 0
        for column in xrange(self.GetColumnCount()):
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText(column))
            text_w, text_h = max(w, text_w), max(h, text_h)
            
            wnd = item.GetWindow(column)
            if wnd:
                wnd_h = max(wnd_h, item.GetWindowSize(column)[1])
                if column == self._main_column:
                    wnd_w = item.GetWindowSize(column)[0]

        text_w, dummy, dummy = dc.GetMultiLineTextExtent(item.GetText(self._main_column))
        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 += 2*_MARGIN

        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 += 2*_MARGIN
        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 = max(total_h, wnd_h+2)

        item.SetWidth(image_w+text_w+wcheck+2+wnd_w)
        item.SetHeight(max(total_h, wnd_h+2))

        
    def CalculateLevel(self, item, dc, level, y, x_colstart):
        """
        Calculates the level of an item inside the tree hierarchy.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `dc`: an instance of :class:`DC`;
        :param `level`: the item level in the tree hierarchy;
        :param `y`: the current vertical position inside the :class:`PyScrolledWindow`;
        :param `x_colstart`: the x coordinate at which the item's column starts.
        """

        # calculate position of vertical lines
        x = x_colstart + _MARGIN # start of column
        if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
            x += _LINEATROOT # space for lines at root
        if self.HasButtons():
            x += (self._btnWidth-self._btnWidth2) # half button space
        else:
            x += (self._indent-self._indent/2)
        
        if self.HasAGWFlag(wx.TR_HIDE_ROOT):
            x += self._indent * (level-1) # indent but not level 1
        else:
            x += self._indent * level # indent according to level
        
        # a hidden root is not evaluated, but its children are always
        if self.HasAGWFlag(wx.TR_HIDE_ROOT) and (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, x_colstart)  # recurse
                
            return y

        self.CalculateSize(item, dc)

        # set its position
        item.SetX(x)
        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, x_colstart)  # recurse
        
        return y
    

    def CalculatePositions(self):
        """ Recalculates all the items positions. """
        
        if not self._anchor:
            return

        dc = wx.ClientDC(self)
        self.PrepareDC(dc)

        dc.SetFont(self._normalFont)
        dc.SetPen(self._dottedPen)

        y, x_colstart = 2, 0
        for i in xrange(self.GetMainColumn()):
            if not self._owner.GetHeaderWindow().IsColumnShown(i):
                continue
            x_colstart += self._owner.GetHeaderWindow().GetColumnWidth(i)
        
        self.CalculateLevel(self._anchor, dc, 0, y, x_colstart) # start recursion


    def SetItemText(self, item, text, column=None):
        """
        Sets the item text label.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `text`: a string specifying the new item label;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

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


    def GetItemText(self, item, column=None):
        """
        Returns the item text label.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: if not ``None``, an integer specifying the column index.
         If it is ``None``, the main column index is used.
        """

        if self.IsVirtual():
            return self._owner.OnGetItemText(item, column)
        else:
            return item.GetText(column)
   

    def GetItemWidth(self, item, column):
        """
        Returns the item width.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: an integer specifying the column index.
        """
        
        if not item:
            return 0

        # determine item width
        font = self.GetItemFont(item)
        if not font.IsOk():
            if item.IsBold():
                font = self._boldFont
            elif item.IsItalic():
                font = self._italicFont
            elif item.IsHyperText():
                font = self.GetHyperTextFont()
            else:
                font = self._normalFont

        dc = wx.ClientDC(self)            
        dc.SetFont(font)
        w, h, dummy = dc.GetMultiLineTextExtent(item.GetText(column))
        w += 2*_MARGIN

        # calculate width
        width = w + 2*_MARGIN
        if column == self.GetMainColumn():
            width += _MARGIN
            if self.HasAGWFlag(wx.TR_LINES_AT_ROOT):
                width += _LINEATROOT
            if self.HasButtons():
                width += self._btnWidth + _LINEATROOT
            if item.GetCurrentImage() != _NO_IMAGE:
                width += self._imgWidth

            # count indent level
            level = 0
            parent = item.GetParent()
            root = self.GetRootItem()
            while (parent and (not self.HasAGWFlag(wx.TR_HIDE_ROOT) or (parent != root))):
                level += 1
                parent = parent.GetParent()
            
            if level:
                width += level*self.GetIndent()

        wnd = item.GetWindow(column)
        if wnd:
            width += wnd.GetSize()[0] + 2*_MARGIN

        return width


    def GetBestColumnWidth(self, column, parent=None):
        """
        Returns the best column's width based on the items width in this column.

        :param `column`: an integer specifying the column index;
        :param `parent`: an instance of :class:`TreeListItem`.
        """

        maxWidth, h = self.GetClientSize()
        width = 0

        if maxWidth < 5:
            # Not shown on screen
            maxWidth = 1000

        # get root if on item
        if not parent:
            parent = self.GetRootItem()

        # add root width
        if not self.HasAGWFlag(wx.TR_HIDE_ROOT):
            w = self.GetItemWidth(parent, column)
            if width < w:
                width = w
            if width > maxWidth:
                return maxWidth

        item, cookie = self.GetFirstChild(parent)
        while item:
            w = self.GetItemWidth(item, column)
            if width < w:
                width = w
            if width > maxWidth:
                return maxWidth

            # check the children of this item
            if item.IsExpanded():
                w = self.GetBestColumnWidth(column, item)
                if width < w:
                    width = w
                if width > maxWidth:
                    return maxWidth

            # next sibling
            item, cookie = self.GetNextChild(parent, cookie)
        
        return max(10, width) # Prevent zero column width


    def HideItem(self, item, hide=True):
        """
        Hides/shows an item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `hide`: ``True`` to hide the item, ``False`` to show it.
        """

        item.Hide(hide)
        self.Refresh()
        

#----------------------------------------------------------------------------
# TreeListCtrl - the multicolumn tree control
#----------------------------------------------------------------------------

_methods = ["GetIndent", "SetIndent", "GetSpacing", "SetSpacing", "GetImageList", "GetStateImageList",
            "GetButtonsImageList", "AssignImageList", "AssignStateImageList", "AssignButtonsImageList",
            "SetImageList", "SetButtonsImageList", "SetStateImageList",
            "GetItemText", "GetItemImage", "GetItemPyData", "GetPyData", "GetItemTextColour",
            "GetItemBackgroundColour", "GetItemFont", "SetItemText", "SetItemImage", "SetItemPyData", "SetPyData",
            "SetItemHasChildren", "SetItemBackgroundColour", "SetItemFont", "IsItemVisible", "HasChildren",
            "IsExpanded", "IsSelected", "IsBold", "GetChildrenCount", "GetRootItem", "GetSelection", "GetSelections",
            "GetItemParent", "GetFirstChild", "GetNextChild", "GetPrevChild", "GetLastChild", "GetNextSibling",
            "GetPrevSibling", "GetNext", "GetFirstExpandedItem", "GetNextExpanded", "GetPrevExpanded",
            "GetFirstVisibleItem", "GetNextVisible", "GetPrevVisible", "AddRoot", "PrependItem", "InsertItem",
            "AppendItem", "Delete", "DeleteChildren", "DeleteRoot", "Expand", "ExpandAll", "ExpandAllChildren",
            "Collapse", "CollapseAndReset", "Toggle", "Unselect", "UnselectAll", "SelectItem", "SelectAll",
            "EnsureVisible", "ScrollTo", "HitTest", "GetBoundingRect", "EditLabel", "FindItem", "SelectAllChildren",
            "SetDragItem", "GetColumnCount", "SetMainColumn", "GetHyperTextFont", "SetHyperTextFont",
            "SetHyperTextVisitedColour", "GetHyperTextVisitedColour", "SetHyperTextNewColour", "GetHyperTextNewColour",
            "SetItemVisited", "GetItemVisited", "SetHilightFocusColour", "GetHilightFocusColour", "SetHilightNonFocusColour",
            "GetHilightNonFocusColour", "SetFirstGradientColour", "GetFirstGradientColour", "SetSecondGradientColour",
            "GetSecondGradientColour", "EnableSelectionGradient", "SetGradientStyle", "GetGradientStyle",
            "EnableSelectionVista", "SetBorderPen", "GetBorderPen", "SetConnectionPen", "GetConnectionPen",
            "SetBackgroundImage", "GetBackgroundImage", "SetImageListCheck", "GetImageListCheck", "EnableChildren",
            "EnableItem", "IsItemEnabled", "GetDisabledColour", "SetDisabledColour", "IsItemChecked",
            "UnCheckRadioParent", "CheckItem", "CheckItem2", "AutoToggleChild", "AutoCheckChild", "AutoCheckParent",
            "CheckChilds", "CheckSameLevel", "GetItemWindowEnabled", "SetItemWindowEnabled", "GetItemType",
            "IsDescendantOf", "SetItemHyperText", "IsItemHyperText", "SetItemBold", "SetItemDropHighlight", "SetItemItalic",
            "GetEditControl", "ShouldInheritColours", "GetItemWindow", "SetItemWindow", "SetItemTextColour", "HideItem",
            "DeleteAllItems", "ItemHasChildren", "ToggleItemSelection", "SetItemType", "GetCurrentItem",
            "SetItem3State", "SetItem3StateValue", "GetItem3StateValue", "IsItem3State", "GetPrev"]


class HyperTreeList(wx.PyControl):
    """
    :class:`HyperTreeList` is a class that mimics the behaviour of :class:`gizmos.TreeListCtrl`, 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-list control.
    """
    
    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=wx.TR_DEFAULT_STYLE, validator=wx.DefaultValidator,
                 name="HyperTreeList"):
        """
        Default class constructor.
        
        :param `parent`: parent window. Must not be ``None``;
        :param `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;
        :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;
        :param `style`: the underlying :class:`PyScrolledWindow` style;
        :param `agwStyle`: the AGW-specific :class:`HyperTreeList` window style. This 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_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
         ``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_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for :class:`~lib.agw.customtreectrl.CustomTreeCtrl` is low.
         ``TR_VIRTUAL``                    0x100000 :class:`HyperTreeList` will have virtual behaviour.
         ============================== =========== ==================================================

        :param `validator`: window validator;
        :param `name`: window name.
        """

        wx.PyControl.__init__(self, parent, id, pos, size, style, validator, name)

        self._header_win = None
        self._main_win = None
        self._headerHeight = 0
        self._attr_set = False
        
        main_style = style & ~(wx.SIMPLE_BORDER|wx.SUNKEN_BORDER|wx.DOUBLE_BORDER|
                               wx.RAISED_BORDER|wx.STATIC_BORDER)

        self._agwStyle = agwStyle
        
        self._main_win = TreeListMainWindow(self, -1, wx.Point(0, 0), size, main_style, agwStyle, validator)
        self._main_win._buffered = False

        self._header_win = TreeListHeaderWindow(self, -1, self._main_win, wx.Point(0, 0),
                                                wx.DefaultSize, wx.TAB_TRAVERSAL)
        self._header_win._buffered = False
        
        self.CalculateAndSetHeaderHeight()
        self.Bind(wx.EVT_SIZE, self.OnSize)

        self.SetBuffered(IsBufferingSupported())
        self._main_win.SetAGWWindowStyleFlag(agwStyle)
        

    def SetBuffered(self, buffered):
        """
        Sets/unsets the double buffering for the header and the main window.

        :param `buffered`: ``True`` to use double-buffering, ``False`` otherwise.

        :note: Currently we are using double-buffering only on Windows XP.
        """

        self._main_win.SetBuffered(buffered)
        self._header_win.SetBuffered(buffered)


    def CalculateAndSetHeaderHeight(self):
        """ Calculates the best header height and stores it. """

        if self._header_win:
            h = wx.RendererNative.Get().GetHeaderButtonHeight(self._header_win)
            # only update if changed
            if h != self._headerHeight:
                self._headerHeight = h
                self.DoHeaderLayout()
            

    def DoHeaderLayout(self):
        """ Layouts the header control. """

        w, h = self.GetClientSize()
        has_header = self._agwStyle & TR_NO_HEADER == 0
        
        if self._header_win and has_header:
            self._header_win.SetDimensions(0, 0, w, self._headerHeight)
            self._header_win.Refresh()
        else:
            self._header_win.SetDimensions(0, 0, 0, 0)
        
        if self._main_win and has_header:
            self._main_win.SetDimensions(0, self._headerHeight + 1, w, h - self._headerHeight - 1)
        else:
            self._main_win.SetDimensions(0, 0, w, h)
    

    def OnSize(self, event):
        """
        Handles the ``wx.EVT_SIZE`` event for :class:`HyperTreeList`.

        :param `event`: a :class:`SizeEvent` event to be processed.
        """

        self.DoHeaderLayout()


    def SetFont(self, font):
        """
        Sets the default font for the header window and the main window.

        :param `font`: a valid :class:`Font` object.
        """
        
        if self._header_win:
            self._header_win.SetFont(font)
            self.CalculateAndSetHeaderHeight()
            self._header_win.Refresh()
        
        if self._main_win:
            return self._main_win.SetFont(font)
        else:
            return False


    def SetHeaderFont(self, font):
        """
        Sets the default font for the header window..

        :param `font`: a valid :class:`Font` object.
        """

        if not self._header_win:
            return
        
        for column in xrange(self.GetColumnCount()):
            self._header_win.SetColumn(column, self.GetColumn(column).SetFont(font))

        self._header_win.Refresh()

    
    def SetHeaderCustomRenderer(self, renderer=None):
        """
        Associate a custom renderer with the header - all columns will use it

        :param `renderer`: a class able to correctly render header buttons

        :note: the renderer class **must** implement the method `DrawHeaderButton`
        """

        self._header_win.SetCustomRenderer(renderer)
        

    def SetAGWWindowStyleFlag(self, agwStyle):
        """
        Sets the window style for :class:`HyperTreeList`.

        :param `agwStyle`: 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_COLUMN_LINES``                 0x1000 Use this style to draw a contrasting border between displayed columns.
         ``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_NO_HEADER``                   0x40000 Use this style to hide the columns header.
         ``TR_ELLIPSIZE_LONG_ITEMS``        0x80000 Flag used to ellipsize long items when the horizontal space for :class:`~lib.agw.customtreectrl.CustomTreeCtrl` is low.
         ``TR_VIRTUAL``                    0x100000 :class:`HyperTreeList` will have virtual behaviour.
         ============================== =========== ==================================================
         
        :note: Please note that some styles cannot be changed after the window creation
         and that `Refresh()` might need to be be called after changing the others for
         the change to take place immediately.
        """
        
        if self._main_win:
            self._main_win.SetAGWWindowStyleFlag(agwStyle)

        tmp = self._agwStyle
        self._agwStyle = agwStyle
        if abs(agwStyle - tmp) & TR_NO_HEADER:
            self.DoHeaderLayout()
            

    def GetAGWWindowStyleFlag(self):
        """
        Returns the :class:`HyperTreeList` window style flag.

        :see: :meth:`~HyperTreeList.SetAGWWindowStyleFlag` for a list of valid window styles.
        """

        agwStyle = self._agwStyle
        if self._main_win:
            agwStyle |= self._main_win.GetAGWWindowStyleFlag()
            
        return agwStyle


    def HasAGWFlag(self, flag):
        """
        Returns whether a flag is present in the :class:`HyperTreeList` style.

        :param `flag`: one of the possible :class:`HyperTreeList` window styles.

        :see: :meth:`~HyperTreeList.SetAGWWindowStyleFlag` for a list of possible window style flags.
        """

        agwStyle = self.GetAGWWindowStyleFlag()
        res = (agwStyle & flag and [True] or [False])[0]
        return res


    def SetBackgroundColour(self, colour):
        """
        Changes the background colour of :class:`HyperTreeList`.

        :param `colour`: the colour to be used as the background colour, pass
         :class:`NullColour` to reset to the default colour.

        :note: The background colour is usually painted by the default :class:`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 :meth:`Window.ClearBackground` or :meth:`Window.Refresh` after
         calling this function.

        :note: Overridden from :class:`PyControl`.
        """

        if not self._main_win:
            return False
        
        return self._main_win.SetBackgroundColour(colour)


    def SetForegroundColour(self, colour):
        """
        Changes the foreground colour of :class:`HyperTreeList`.

        :param `colour`: the colour to be used as the foreground colour, pass
         :class:`NullColour` to reset to the default colour.

        :note: Overridden from :class:`PyControl`.         
        """

        if not self._main_win:
            return False
        
        return self._main_win.SetForegroundColour(colour)


    def SetColumnWidth(self, column, width):
        """
        Sets the column width, in pixels.

        :param `column`: an integer specifying the column index;
        :param `width`: the new column width, in pixels.
        """

        if width == wx.LIST_AUTOSIZE_USEHEADER:
        
            font = self._header_win.GetFont()
            dc = wx.ClientDC(self._header_win)
            width, dummy, dummy = dc.GetMultiLineTextExtent(self._header_win.GetColumnText(column))
            # Search TreeListHeaderWindow.OnPaint to understand this:
            width += 2*_EXTRA_WIDTH + _MARGIN
        
        elif width == wx.LIST_AUTOSIZE:
        
            width = self._main_win.GetBestColumnWidth(column)

        elif width == LIST_AUTOSIZE_CONTENT_OR_HEADER:

            width1 = self._main_win.GetBestColumnWidth(column)
            font = self._header_win.GetFont()
            dc = wx.ClientDC(self._header_win)
            width2, dummy, dummy = dc.GetMultiLineTextExtent(self._header_win.GetColumnText(column))
 
            width2 += 2*_EXTRA_WIDTH + _MARGIN
            width = max(width1, width2)


        self._header_win.SetColumnWidth(column, width)
        self._header_win.Refresh()


    def GetColumnWidth(self, column):
        """
        Returns the column width, in pixels.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumnWidth(column)

        
    def SetColumnText(self, column, text):
        """
        Sets the column text label.

        :param `column`: an integer specifying the column index;
        :param `text`: the new column label.
        """

        self._header_win.SetColumnText(column, text)
        self._header_win.Refresh()


    def GetColumnText(self, column):
        """
        Returns the column text label.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumnText(column)


    def AddColumn(self, text, width=_DEFAULT_COL_WIDTH, flag=wx.ALIGN_LEFT,
                  image=-1, shown=True, colour=None, edit=False):
        """
        Appends a column to the :class:`HyperTreeList`.

        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid :class:`Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.
        """

        self._header_win.AddColumn(text, width, flag, image, shown, colour, edit)
        self.DoHeaderLayout()
        

    def AddColumnInfo(self, colInfo):
        """
        Appends a column to the :class:`HyperTreeList`.

        :param `colInfo`: an instance of :class:`TreeListColumnInfo`.
        """

        self._header_win.AddColumnInfo(colInfo)
        self.DoHeaderLayout()


    def InsertColumnInfo(self, before, colInfo):
        """
        Inserts a column to the :class:`HyperTreeList` at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `colInfo`: an instance of :class:`TreeListColumnInfo`.
        """

        self._header_win.InsertColumnInfo(before, colInfo)
        self._header_win.Refresh()


    def InsertColumn(self, before, text, width=_DEFAULT_COL_WIDTH,
                     flag=wx.ALIGN_LEFT, image=-1, shown=True, colour=None, 
                     edit=False):
        """
        Inserts a column to the :class:`HyperTreeList` at the position specified
        by `before`.

        :param `before`: the index at which we wish to insert the new column;
        :param `text`: the column text label;
        :param `width`: the column width in pixels;
        :param `flag`: the column alignment flag, one of ``wx.ALIGN_LEFT``,
         ``wx.ALIGN_RIGHT``, ``wx.ALIGN_CENTER``;
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column;
        :param `shown`: ``True`` to show the column, ``False`` to hide it;
        :param `colour`: a valid :class:`Colour`, representing the text foreground colour
         for the column;
        :param `edit`: ``True`` to set the column as editable, ``False`` otherwise.        
        """

        self._header_win.InsertColumn(before, text, width, flag, image,
                                      shown, colour, edit)
        self._header_win.Refresh()


    def RemoveColumn(self, column):
        """
        Removes a column from the :class:`HyperTreeList`.

        :param `column`: an integer specifying the column index.
        """

        self._header_win.RemoveColumn(column)
        self._header_win.Refresh()


    def SetColumn(self, column, colInfo):
        """
        Sets a column using an instance of :class:`TreeListColumnInfo`.

        :param `column`: an integer specifying the column index;
        :param `info`: an instance of :class:`TreeListColumnInfo`.        
        """

        self._header_win.SetColumn(column, colInfo)
        self._header_win.Refresh()
            

    def GetColumn(self, column):
        """
        Returns an instance of :class:`TreeListColumnInfo` containing column information.

        :param `column`: an integer specifying the column index.
        """
        
        return self._header_win.GetColumn(column)


    def SetColumnImage(self, column, image):
        """
        Sets an image on the specified column.

        :param `column`: an integer specifying the column index.
        :param `image`: an index within the normal image list assigned to
         :class:`HyperTreeList` specifying the image to use for the column.
        """                

        self._header_win.SetColumn(column, self.GetColumn(column).SetImage(image))
        self._header_win.Refresh()


    def GetColumnImage(self, column):
        """
        Returns the image assigned to the specified column.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetImage()


    def SetColumnEditable(self, column, edit):
        """
        Sets the column as editable or non-editable.

        :param `column`: an integer specifying the column index;
        :param `edit`: ``True`` if the column should be editable, ``False`` otherwise.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetEditable(edit))


    def SetColumnShown(self, column, shown):
        """
        Sets the column as shown or hidden.

        :param `column`: an integer specifying the column index;
        :param `shown`: ``True`` if the column should be shown, ``False`` if it
         should be hidden.
        """

        if self._main_win.GetMainColumn() == column:
            shown = True # Main column cannot be hidden
            
        self.SetColumn(column, self.GetColumn(column).SetShown(shown))


    def IsColumnEditable(self, column):
        """
        Returns ``True`` if the column is editable, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).IsEditable()


    def IsColumnShown(self, column):
        """
        Returns ``True`` if the column is shown, ``False`` otherwise.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).IsShown()


    def SetColumnAlignment(self, column, flag):
        """
        Sets the column text alignment.

        :param `column`: an integer specifying the column index;
        :param `flag`: the alignment flag, one of ``wx.ALIGN_LEFT``, ``wx.ALIGN_RIGHT``,
         ``wx.ALIGN_CENTER``.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetAlignment(flag))
        self._header_win.Refresh()


    def GetColumnAlignment(self, column):
        """
        Returns the column text alignment.

        :param `column`: an integer specifying the column index.
        """
        
        return self._header_win.GetColumn(column).GetAlignment()


    def SetColumnColour(self, column, colour):
        """
        Sets the column text colour.

        :param `column`: an integer specifying the column index;
        :param `colour`: a valid :class:`Colour` object.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetColour(colour))
        self._header_win.Refresh()


    def GetColumnColour(self, column):
        """
        Returns the column text colour.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetColour()
                

    def SetColumnFont(self, column, font):
        """
        Sets the column text font.

        :param `column`: an integer specifying the column index;
        :param `font`: a valid :class:`Font` object.
        """

        self._header_win.SetColumn(column, self.GetColumn(column).SetFont(font))
        self._header_win.Refresh()


    def GetColumnFont(self, column):
        """
        Returns the column text font.

        :param `column`: an integer specifying the column index.
        """

        return self._header_win.GetColumn(column).GetFont()


    def Refresh(self, erase=True, rect=None):
        """
        Causes this window, and all of its children recursively (except under wxGTK1
        where this is not implemented), to be repainted. 

        :param `erase`: If ``True``, the background will be erased;
        :param `rect`: If not ``None``, only the given rectangle will be treated as damaged.

        :note: Note that repainting doesn't happen immediately but only during the next
         event loop iteration, if you need to update the window immediately you should
         use `Update` instead.

        :note: Overridden from :class:`PyControl`.         
        """

        self._main_win.Refresh(erase, rect)
        self._header_win.Refresh(erase, rect)


    def SetFocus(self):
        """ This sets the window to receive keyboard input. """
        
        self._main_win.SetFocus() 


    def GetHeaderWindow(self):
        """ Returns the header window, an instance of :class:`TreeListHeaderWindow`. """
        
        return self._header_win
    

    def GetMainWindow(self):
        """ Returns the main window, an instance of :class:`TreeListMainWindow`. """
        
        return self._main_win


    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()`.

        :note: Overridden from :class:`PyControl`.        
        """

        # something is better than nothing...
        return wx.Size(200, 200) # but it should be specified values! FIXME


    def OnGetItemText(self, item, column):
        """
        This function **must** be overloaded in the derived class for a control
        with ``TR_VIRTUAL`` style. It should return the string containing the
        text of the given column for the specified item.

        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: an integer specifying the column index.
        """
        
        return ""


    def SortChildren(self, item):
        """
        Sorts the children of the given item using :meth:`~HyperTreeList.OnCompareItems` method of :class:`HyperTreeList`. 
        You should override that method to change the sort order (the default is ascending
        case-sensitive alphabetical order).

        :param `item`: an instance of :class:`TreeListItem`;
        """

        if not self._attr_set:
            setattr(self._main_win, "OnCompareItems", self.OnCompareItems)
            self._attr_set = True
            
        self._main_win.SortChildren(item)
        

    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 :class:`HyperTreeList`. 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 :class:`TreeListItem`;
        :param `item2`: another instance of :class:`TreeListItem`.

        :note: The base class version compares items alphabetically.
        """

        # do the comparison here, and not delegate to self._main_win, in order
        # to let the user override it

        return self.GetItemText(item1) == self.GetItemText(item2)


    def CreateEditCtrl(self, item, column):
        """
        Create an edit control for editing a label of an item. By default, this
        returns a text control.
        
        Override this function in the derived class to return a different type
        of control.
        
        :param `item`: an instance of :class:`TreeListItem`;
        :param `column`: an integer specifying the column index.
        """

        return EditTextCtrl(self.GetMainWindow(), -1, item, column,
                            self.GetMainWindow(), item.GetText(column),
                            style=self.GetTextCtrlStyle(column))

        
    def GetTextCtrlStyle(self, column):
        """
        Return the style to use for the text control that is used to edit
        labels of items. 
        
        Override this function in the derived class to support a different
        style, e.g. ``wx.TE_MULTILINE``.
        
        :param `column`: an integer specifying the column index.
        """
        
        return self.GetTextCtrlAlignmentStyle(column) | wx.TE_PROCESS_ENTER

        
    def GetTextCtrlAlignmentStyle(self, column):
        """
        Return the alignment style to use for the text control that is used
        to edit labels of items. The alignment style is derived from the 
        column alignment.
        
        :param `column`: an integer specifying the column index.
        """

        header_win = self.GetHeaderWindow()
        alignment = header_win.GetColumnAlignment(column)
        return {wx.ALIGN_LEFT: wx.TE_LEFT, 
                wx.ALIGN_RIGHT: wx.TE_RIGHT, 
                wx.ALIGN_CENTER: wx.TE_CENTER}[alignment]

    
    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, :meth:`Button.GetClassDefaultAttributes` () will typically return the
        values appropriate for a button which will be normally different from those
        returned by, say, :meth:`ListCtrl.GetClassDefaultAttributes` ().

        :note: The :class:`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.
        """

        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)


def create_delegator_for(method):
    """
    Creates a method that forwards calls to `self._main_win` (an instance of :class:`TreeListMainWindow`).

    :param `method`: one method inside the :class:`TreeListMainWindow` local scope.
    """
    
    def delegate(self, *args, **kwargs):
        return getattr(self._main_win, method)(*args, **kwargs)
    return delegate

# Create methods that delegate to self._main_win. This approach allows for
# overriding these methods in possible subclasses of HyperTreeList
for method in _methods:
    setattr(HyperTreeList, method, create_delegator_for(method))