File: ultimatelistctrl.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 (13726 lines) | stat: -rw-r--r-- 467,548 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
# --------------------------------------------------------------------------------- #
# ULTIMATELISTCTRL wxPython IMPLEMENTATION
# Inspired by and heavily based on the wxWidgets C++ generic version of wxListCtrl.
#
# Andrea Gavana, @ 08 May 2009
# Latest Revision: 30 Jul 2014, 21.00 GMT
#
#
# TODO List
#
# 1)  Subitem selection;
# 2)  Watermark? (almost, does not work very well :-( );
# 3)  Groups? (Maybe, check ObjectListView);
# 4)  Scrolling items as headers and footers;
# 5)  Alpha channel for text/background of items;
# 6)  Custom renderers for headers/footers (done);
# 7)  Fading in and out on mouse motion (a la Windows Vista Aero);
# 8)  Sub-text for headers/footers (grey text below the header/footer text);
# 9)  Fixing the columns to the left or right side of the control layout;
# 10) Skins for header and scrollbars (implemented for headers/footers).
#
#
# 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
# --------------------------------------------------------------------------------- #


"""
Description
===========

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

In addition to the standard :class:`ListCtrl` behaviour this class supports:


Appearance
==========

* Multiple images for items/subitems;
* Images can be of any size and not limited to a single specific pair of `width`, `height`
  as it is the case of :class:`ImageList`. Simply use :class:`PyImageList` instead of :class:`ImageList`
  to add your images.
* Font, colour, background, custom renderers and formatting for items and subitems;
* Ability to add persistent data to an item using meth:~UltimateListCtrl.SetItemPyData` and meth:~UltimateListCtrl.GetItemPyData`:
  the data can be any Python object and not necessarily an integer as in :class:`ListCtrl`;
* CheckBox-type items and subitems;
* RadioButton-type items and subitems;
* Overflowing items/subitems, a la :class:`grid.Grid`, i.e. an item/subitem may overwrite neighboring
  items/subitems if its text would not normally fit in the space allotted to it;
* Hyperlink-type items and subitems: they look like an hyperlink, with the proper mouse
  cursor on hovering;
* Multiline text items and subitems;
* Variable row heights depending on the item/subitem kind/text/window;
* User defined item/subitem renderers: these renderer classes **must** implement the methods
  `DrawSubItem`, `GetLineHeight` and `GetSubItemWidth` (see the demo);
* Enabling/disabling items (together with their plain or grayed out icons);
* Whatever non-toplevel widget can be attached next to an item/subitem;
* Column headers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column headers can have their own checkbox/radiobutton;
* Column footers are fully customizable in terms of icons, colour, font, alignment etc...;
* Column footers can have their own checkbox/radiobutton;
* Ability to hide/show columns;
* Default selection style, gradient (horizontal/vertical) selection style and Windows
  Vista selection style.


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


Usage
=====

Usage example::

    import sys
    
    import wx 
    import wx.lib.agw.ultimatelistctrl as ULC

    class MyFrame(wx.Frame): 

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

            list = ULC.UltimateListCtrl(self, wx.ID_ANY, agwStyle=wx.LC_REPORT|wx.LC_VRULES|wx.LC_HRULES|wx.LC_SINGLE_SEL) 

            list.InsertColumn(0, "Column 1") 
            list.InsertColumn(1, "Column 2") 

            index = list.InsertStringItem(sys.maxint, "Item 1") 
            list.SetStringItem(index, 1, "Sub-item 1") 

            index = list.InsertStringItem(sys.maxint, "Item 2") 
            list.SetStringItem(index, 1, "Sub-item 2") 

            choice = wx.Choice(list, -1, choices=["one", "two"]) 
            index = list.InsertStringItem(sys.maxint, "A widget") 

            list.SetItemWindow(index, 1, choice, expand=True) 

            sizer = wx.BoxSizer(wx.VERTICAL) 
            sizer.Add(list, 1, wx.EXPAND) 
            self.SetSizer(sizer) 


    # our normal wxApp-derived class, as usual

    app = wx.App(0)

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

    app.MainLoop()



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

This class supports the following window styles:

===============================  =========== ====================================================================================================
Window Styles                    Hex Value   Description
===============================  =========== ====================================================================================================
``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
``ULC_ICON``                             0x4 Large icon view, with optional labels.
``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
``ULC_NO_HEADER``                      0x800 No header in report mode.
``ULC_NO_SORT_HEADER``                0x1000 No Docs.
``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
===============================  =========== ====================================================================================================


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

This class processes the following events:

======================================== ====================================================================================================
Event Name                               Description
======================================== ====================================================================================================
``EVT_LIST_BEGIN_DRAG``                  Begin dragging with the left mouse button.
``EVT_LIST_BEGIN_RDRAG``                 Begin dragging with the right mouse button.
``EVT_LIST_BEGIN_LABEL_EDIT``            Begin editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_END_LABEL_EDIT``              Finish editing a label. This can be prevented by calling `Veto()`.
``EVT_LIST_DELETE_ITEM``                 An item was deleted.
``EVT_LIST_DELETE_ALL_ITEMS``            All items were deleted.
``EVT_LIST_KEY_DOWN``                    A key has been pressed.
``EVT_LIST_INSERT_ITEM``                 An item has been inserted.
``EVT_LIST_COL_CLICK``                   A column (`m_col`) has been left-clicked.
``EVT_LIST_COL_RIGHT_CLICK``             A column (`m_col`) has been right-clicked.
``EVT_LIST_COL_BEGIN_DRAG``              The user started resizing a column - can be vetoed.
``EVT_LIST_COL_END_DRAG``                The user finished resizing a column.
``EVT_LIST_COL_DRAGGING``                The divider between columns is being dragged.
``EVT_LIST_ITEM_SELECTED``               The item has been selected.
``EVT_LIST_ITEM_DESELECTED``             The item has been deselected.
``EVT_LIST_ITEM_RIGHT_CLICK``            The right mouse button has been clicked on an item.
``EVT_LIST_ITEM_MIDDLE_CLICK``           The middle mouse button has been clicked on an item.
``EVT_LIST_ITEM_ACTIVATED``              The item has been activated (``ENTER`` or double click).
``EVT_LIST_ITEM_FOCUSED``                The currently focused item has changed.
``EVT_LIST_CACHE_HINT``                  Prepare cache for a virtual list control.
``EVT_LIST_ITEM_CHECKING``               An item/subitem is being checked.
``EVT_LIST_ITEM_CHECKED``                An item/subitem has been checked.
``EVT_LIST_COL_CHECKING``                A column header is being checked.
``EVT_LIST_COL_CHECKED``                 A column header has being checked.
``EVT_LIST_FOOTER_CHECKING``             A column footer is being checked.
``EVT_LIST_FOOTER_CHECKED``              A column footer has being checked.
``EVT_LIST_ITEM_HYPERLINK``              An hyperlink item has been clicked.
``EVT_LIST_FOOTER_CLICK``                The user left-clicked on a column footer.
``EVT_LIST_FOOTER_RIGHT_CLICK``          The user right-clicked on a column footer.
``EVT_LIST_ITEM_LEFT_CLICK``             Send a left-click event after an item is selected.
``EVT_LIST_END_DRAG``                    Notify an end-drag operation.
======================================== ====================================================================================================


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

UltimateListCtrl has been tested on the following platforms:
  * Windows (Windows XP);


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

UltimateListCtrl is distributed under the wxPython license.

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

Version 0.8

"""

import wx
import math
import bisect
import types
import zlib
import cStringIO

from wx.lib.expando import ExpandoTextCtrl

# Version Info
__version__ = "0.8"

# wxPython version string
_VERSION_STRING = wx.VERSION_STRING

# ----------------------------------------------------------------------------
# UltimateListCtrl constants
# ----------------------------------------------------------------------------

# style flags
ULC_VRULES                  = wx.LC_VRULES
""" Draws light vertical rules between rows in report mode. """
ULC_HRULES                  = wx.LC_HRULES
""" Draws light horizontal rules between rows in report mode. """
ULC_ICON                    = wx.LC_ICON
ULC_SMALL_ICON              = wx.LC_SMALL_ICON
ULC_LIST                    = wx.LC_LIST
ULC_REPORT                  = wx.LC_REPORT
ULC_TILE                    = 0x10000

ULC_ALIGN_TOP               = wx.LC_ALIGN_TOP
ULC_ALIGN_LEFT              = wx.LC_ALIGN_LEFT
ULC_AUTOARRANGE             = wx.LC_AUTOARRANGE
ULC_VIRTUAL                 = wx.LC_VIRTUAL
ULC_EDIT_LABELS             = wx.LC_EDIT_LABELS
ULC_NO_HEADER               = wx.LC_NO_HEADER
ULC_NO_SORT_HEADER          = wx.LC_NO_SORT_HEADER
ULC_SINGLE_SEL              = wx.LC_SINGLE_SEL
ULC_SORT_ASCENDING          = wx.LC_SORT_ASCENDING
ULC_SORT_DESCENDING         = wx.LC_SORT_DESCENDING

ULC_NO_HIGHLIGHT            = 0x20000
ULC_STICKY_HIGHLIGHT        = 0x40000
ULC_STICKY_NOSELEVENT       = 0x80000
ULC_SEND_LEFTCLICK          = 0x100000
ULC_HAS_VARIABLE_ROW_HEIGHT = 0x200000

ULC_AUTO_CHECK_CHILD    = 0x400000     # only meaningful for checkboxes
ULC_AUTO_TOGGLE_CHILD   = 0x800000     # only meaningful for checkboxes
ULC_AUTO_CHECK_PARENT   = 0x1000000    # only meaningful for checkboxes
ULC_SHOW_TOOLTIPS       = 0x2000000    # shows tooltips on items with ellipsis (...)
ULC_HOT_TRACKING        = 0x4000000    # enable hot tracking on mouse motion
ULC_BORDER_SELECT       = 0x8000000    # changes border colour whan an item is selected, instead of highlighting the item
ULC_TRACK_SELECT        = 0x10000000   # Enables hot-track selection in a list control. Hot track selection means that an item
                                       # is automatically selected when the cursor remains over the item for a certain period
                                       # of time. The delay is retrieved on Windows using the win32api call
                                       # win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME), and is defaulted to 400ms
                                       # on other platforms. This style applies to all styles of UltimateListCtrl. 
ULC_HEADER_IN_ALL_VIEWS = 0x20000000   # Show column headers in all view modes
ULC_NO_FULL_ROW_SELECT  = 0x40000000   # When an item is selected, the only the item in the first column is highlighted
ULC_FOOTER              = 0x80000000   # Show a footer too (only when header is present)
ULC_USER_ROW_HEIGHT     = 0x100000000  # Allows to set a custom row height (one value for all the items, only in report mode).

ULC_MASK_TYPE  = ULC_ICON | ULC_SMALL_ICON | ULC_LIST | ULC_REPORT | ULC_TILE
ULC_MASK_ALIGN = ULC_ALIGN_TOP | ULC_ALIGN_LEFT
ULC_MASK_SORT  = ULC_SORT_ASCENDING | ULC_SORT_DESCENDING

# for compatibility only
ULC_USER_TEXT = ULC_VIRTUAL

# Omitted because
#  (a) too much detail
#  (b) not enough style flags
#  (c) not implemented anyhow in the generic version
#
# ULC_NO_SCROLL
# ULC_NO_LABEL_WRAP
# ULC_OWNERDRAW_FIXED
# ULC_SHOW_SEL_ALWAYS

# Mask flags to tell app/GUI what fields of UltimateListItem are valid
ULC_MASK_STATE         =      wx.LIST_MASK_STATE
ULC_MASK_TEXT          =      wx.LIST_MASK_TEXT
ULC_MASK_IMAGE         =      wx.LIST_MASK_IMAGE
ULC_MASK_DATA          =      wx.LIST_MASK_DATA
ULC_SET_ITEM           =      wx.LIST_SET_ITEM
ULC_MASK_WIDTH         =      wx.LIST_MASK_WIDTH
ULC_MASK_FORMAT        =      wx.LIST_MASK_FORMAT
ULC_MASK_FONTCOLOUR    =      0x0080
ULC_MASK_FONT          =      0x0100
ULC_MASK_BACKCOLOUR    =      0x0200
ULC_MASK_KIND          =      0x0400
ULC_MASK_ENABLE        =      0x0800
ULC_MASK_CHECK         =      0x1000
ULC_MASK_HYPERTEXT     =      0x2000
ULC_MASK_WINDOW        =      0x4000
ULC_MASK_PYDATA        =      0x8000
ULC_MASK_SHOWN         =      0x10000
ULC_MASK_RENDERER      =      0x20000
ULC_MASK_OVERFLOW      =      0x40000
ULC_MASK_FOOTER_TEXT   =      0x80000
ULC_MASK_FOOTER_IMAGE  =      0x100000
ULC_MASK_FOOTER_FORMAT =      0x200000
ULC_MASK_FOOTER_FONT   =      0x400000
ULC_MASK_FOOTER_CHECK  =      0x800000
ULC_MASK_FOOTER_KIND   =      0x1000000
ULC_MASK_TOOLTIP       =      0x2000000

# State flags for indicating the state of an item
ULC_STATE_DONTCARE    =   wx.LIST_STATE_DONTCARE
ULC_STATE_DROPHILITED =   wx.LIST_STATE_DROPHILITED      # MSW only
ULC_STATE_FOCUSED     =   wx.LIST_STATE_FOCUSED
ULC_STATE_SELECTED    =   wx.LIST_STATE_SELECTED
ULC_STATE_CUT         =   wx.LIST_STATE_CUT              # MSW only
ULC_STATE_DISABLED    =   wx.LIST_STATE_DISABLED         # OS2 only
ULC_STATE_FILTERED    =   wx.LIST_STATE_FILTERED         # OS2 only
ULC_STATE_INUSE       =   wx.LIST_STATE_INUSE            # OS2 only
ULC_STATE_PICKED      =   wx.LIST_STATE_PICKED           # OS2 only
ULC_STATE_SOURCE      =   wx.LIST_STATE_SOURCE           # OS2 only

# Hit test flags, used in HitTest
ULC_HITTEST_ABOVE           = wx.LIST_HITTEST_ABOVE            # Above the client area.
ULC_HITTEST_BELOW           = wx.LIST_HITTEST_BELOW            # Below the client area.
ULC_HITTEST_NOWHERE         = wx.LIST_HITTEST_NOWHERE          # In the client area but below the last item.
ULC_HITTEST_ONITEMICON      = wx.LIST_HITTEST_ONITEMICON       # On the bitmap associated with an item.
ULC_HITTEST_ONITEMLABEL     = wx.LIST_HITTEST_ONITEMLABEL      # On the label (string) associated with an item.
ULC_HITTEST_ONITEMRIGHT     = wx.LIST_HITTEST_ONITEMRIGHT      # In the area to the right of an item.
ULC_HITTEST_ONITEMSTATEICON = wx.LIST_HITTEST_ONITEMSTATEICON  # On the state icon for a tree view item that is in a user-defined state.
ULC_HITTEST_TOLEFT          = wx.LIST_HITTEST_TOLEFT           # To the left of the client area.
ULC_HITTEST_TORIGHT         = wx.LIST_HITTEST_TORIGHT          # To the right of the client area.
ULC_HITTEST_ONITEMCHECK     = 0x1000                           # On the checkbox (if any)

ULC_HITTEST_ONITEM = ULC_HITTEST_ONITEMICON | ULC_HITTEST_ONITEMLABEL | ULC_HITTEST_ONITEMSTATEICON | ULC_HITTEST_ONITEMCHECK

# Flags for GetNextItem (MSW only except ULC_NEXT_ALL)
ULC_NEXT_ABOVE = wx.LIST_NEXT_ABOVE         # Searches for an item above the specified item
ULC_NEXT_ALL   = wx.LIST_NEXT_ALL           # Searches for subsequent item by index
ULC_NEXT_BELOW = wx.LIST_NEXT_BELOW         # Searches for an item below the specified item
ULC_NEXT_LEFT  = wx.LIST_NEXT_LEFT          # Searches for an item to the left of the specified item
ULC_NEXT_RIGHT = wx.LIST_NEXT_RIGHT         # Searches for an item to the right of the specified item

# Alignment flags for Arrange (MSW only except ULC_ALIGN_LEFT)
ULC_ALIGN_DEFAULT      = wx.LIST_ALIGN_DEFAULT
ULC_ALIGN_SNAP_TO_GRID = wx.LIST_ALIGN_SNAP_TO_GRID

# Column format (MSW only except ULC_FORMAT_LEFT)
ULC_FORMAT_LEFT   = wx.LIST_FORMAT_LEFT
ULC_FORMAT_RIGHT  = wx.LIST_FORMAT_RIGHT
ULC_FORMAT_CENTRE = wx.LIST_FORMAT_CENTRE
ULC_FORMAT_CENTER = ULC_FORMAT_CENTRE

# Autosize values for SetColumnWidth
ULC_AUTOSIZE = wx.LIST_AUTOSIZE
ULC_AUTOSIZE_USEHEADER = wx.LIST_AUTOSIZE_USEHEADER      # partly supported by generic version
ULC_AUTOSIZE_FILL = -3

# Flag values for GetItemRect
ULC_RECT_BOUNDS = wx.LIST_RECT_BOUNDS
ULC_RECT_ICON   = wx.LIST_RECT_ICON
ULC_RECT_LABEL  = wx.LIST_RECT_LABEL

# Flag values for FindItem (MSW only)
ULC_FIND_UP    = wx.LIST_FIND_UP
ULC_FIND_DOWN  = wx.LIST_FIND_DOWN
ULC_FIND_LEFT  = wx.LIST_FIND_LEFT
ULC_FIND_RIGHT = wx.LIST_FIND_RIGHT

# Items/subitems rect
ULC_GETSUBITEMRECT_WHOLEITEM = wx.LIST_GETSUBITEMRECT_WHOLEITEM

# ----------------------------------------------------------------------------
# UltimateListCtrl event macros
# ----------------------------------------------------------------------------

wxEVT_COMMAND_LIST_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_BEGIN_DRAG
wxEVT_COMMAND_LIST_BEGIN_RDRAG = wx.wxEVT_COMMAND_LIST_BEGIN_RDRAG
wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT
wxEVT_COMMAND_LIST_END_LABEL_EDIT = wx.wxEVT_COMMAND_LIST_END_LABEL_EDIT
wxEVT_COMMAND_LIST_DELETE_ITEM = wx.wxEVT_COMMAND_LIST_DELETE_ITEM
wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS = wx.wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS
wxEVT_COMMAND_LIST_ITEM_SELECTED = wx.wxEVT_COMMAND_LIST_ITEM_SELECTED
wxEVT_COMMAND_LIST_ITEM_DESELECTED = wx.wxEVT_COMMAND_LIST_ITEM_DESELECTED
wxEVT_COMMAND_LIST_KEY_DOWN = wx.wxEVT_COMMAND_LIST_KEY_DOWN
wxEVT_COMMAND_LIST_INSERT_ITEM = wx.wxEVT_COMMAND_LIST_INSERT_ITEM
wxEVT_COMMAND_LIST_COL_CLICK = wx.wxEVT_COMMAND_LIST_COL_CLICK
wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK
wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK = wx.wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK
wxEVT_COMMAND_LIST_ITEM_ACTIVATED = wx.wxEVT_COMMAND_LIST_ITEM_ACTIVATED
wxEVT_COMMAND_LIST_CACHE_HINT = wx.wxEVT_COMMAND_LIST_CACHE_HINT
wxEVT_COMMAND_LIST_COL_RIGHT_CLICK = wx.wxEVT_COMMAND_LIST_COL_RIGHT_CLICK
wxEVT_COMMAND_LIST_COL_BEGIN_DRAG = wx.wxEVT_COMMAND_LIST_COL_BEGIN_DRAG
wxEVT_COMMAND_LIST_COL_DRAGGING = wx.wxEVT_COMMAND_LIST_COL_DRAGGING
wxEVT_COMMAND_LIST_COL_END_DRAG = wx.wxEVT_COMMAND_LIST_COL_END_DRAG
wxEVT_COMMAND_LIST_ITEM_FOCUSED = wx.wxEVT_COMMAND_LIST_ITEM_FOCUSED

wxEVT_COMMAND_LIST_FOOTER_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_FOOTER_CHECKED = wx.NewEventType()

wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_CHECKED = wx.NewEventType()
wxEVT_COMMAND_LIST_ITEM_HYPERLINK = wx.NewEventType()
wxEVT_COMMAND_LIST_END_DRAG = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKING = wx.NewEventType()
wxEVT_COMMAND_LIST_COL_CHECKED = wx.NewEventType()

EVT_LIST_BEGIN_DRAG = wx.EVT_LIST_BEGIN_DRAG
EVT_LIST_BEGIN_RDRAG = wx.EVT_LIST_BEGIN_RDRAG
EVT_LIST_BEGIN_LABEL_EDIT = wx.EVT_LIST_BEGIN_LABEL_EDIT
EVT_LIST_END_LABEL_EDIT = wx.EVT_LIST_END_LABEL_EDIT
EVT_LIST_DELETE_ITEM = wx.EVT_LIST_DELETE_ITEM
EVT_LIST_DELETE_ALL_ITEMS = wx.EVT_LIST_DELETE_ALL_ITEMS
EVT_LIST_KEY_DOWN = wx.EVT_LIST_KEY_DOWN
EVT_LIST_INSERT_ITEM = wx.EVT_LIST_INSERT_ITEM
EVT_LIST_COL_CLICK = wx.EVT_LIST_COL_CLICK
EVT_LIST_COL_RIGHT_CLICK = wx.EVT_LIST_COL_RIGHT_CLICK
EVT_LIST_COL_BEGIN_DRAG = wx.EVT_LIST_COL_BEGIN_DRAG
EVT_LIST_COL_END_DRAG = wx.EVT_LIST_COL_END_DRAG
EVT_LIST_COL_DRAGGING = wx.EVT_LIST_COL_DRAGGING
EVT_LIST_ITEM_SELECTED = wx.EVT_LIST_ITEM_SELECTED
EVT_LIST_ITEM_DESELECTED = wx.EVT_LIST_ITEM_DESELECTED
EVT_LIST_ITEM_RIGHT_CLICK = wx.EVT_LIST_ITEM_RIGHT_CLICK
EVT_LIST_ITEM_MIDDLE_CLICK = wx.EVT_LIST_ITEM_MIDDLE_CLICK
EVT_LIST_ITEM_ACTIVATED = wx.EVT_LIST_ITEM_ACTIVATED
EVT_LIST_ITEM_FOCUSED = wx.EVT_LIST_ITEM_FOCUSED
EVT_LIST_CACHE_HINT = wx.EVT_LIST_CACHE_HINT

EVT_LIST_ITEM_LEFT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, 1)
EVT_LIST_ITEM_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKING, 1)
EVT_LIST_ITEM_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_CHECKED, 1)
EVT_LIST_ITEM_HYPERLINK = wx.PyEventBinder(wxEVT_COMMAND_LIST_ITEM_HYPERLINK, 1)
EVT_LIST_END_DRAG = wx.PyEventBinder(wxEVT_COMMAND_LIST_END_DRAG, 1)
EVT_LIST_COL_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKING, 1)
EVT_LIST_COL_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_COL_CHECKED, 1)

EVT_LIST_FOOTER_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CLICK, 1)
EVT_LIST_FOOTER_RIGHT_CLICK = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK, 1)
EVT_LIST_FOOTER_CHECKING = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKING, 1)
EVT_LIST_FOOTER_CHECKED = wx.PyEventBinder(wxEVT_COMMAND_LIST_FOOTER_CHECKED, 1)

# NOTE: If using the wxExtListBox visual attributes works everywhere then this can
# be removed, as well as the #else case below.

_USE_VISATTR = 0


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

SCROLL_UNIT_X = 15
SCROLL_UNIT_Y = 15

# the spacing between the lines (in report mode)
LINE_SPACING = 0

# extra margins around the text label
EXTRA_WIDTH = 4
EXTRA_HEIGHT = 4

if wx.Platform == "__WXGTK__":
    EXTRA_HEIGHT = 6

# margin between the window and the items
EXTRA_BORDER_X = 2
EXTRA_BORDER_Y = 2

# offset for the header window
HEADER_OFFSET_X = 1
HEADER_OFFSET_Y = 1

# margin between rows of icons in [small] icon view
MARGIN_BETWEEN_ROWS = 6

# when autosizing the columns, add some slack
AUTOSIZE_COL_MARGIN = 10

# default and minimal widths for the header columns
WIDTH_COL_DEFAULT = 80
WIDTH_COL_MIN = 10

# the space between the image and the text in the report mode
IMAGE_MARGIN_IN_REPORT_MODE = 5

# the space between the image and the text in the report mode in header
HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2

# and the width of the icon, if any
MARGIN_BETWEEN_TEXT_AND_ICON = 2

# Background Image Style
_StyleTile = 0
_StyleStretch = 1

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

# Mouse hover time for track selection
HOVER_TIME = 400
if wx.Platform == "__WXMSW__":
    try:
        import win32gui, win32con
        HOVER_TIME = win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)
    except ImportError:
        pass


# For PyImageList
IL_FIXED_SIZE = 0
IL_VARIABLE_SIZE = 1

# Python integers, to make long types to work with CreateListItem
INTEGER_TYPES = [types.IntType, types.LongType]


# ----------------------------------------------------------------------------
# Functions
# ----------------------------------------------------------------------------

# Utility method
def to_list(input):
    """
    Converts the input data into a Python list.

    :param `input`: can be an integer or a Python list (in which case nothing will
     be done to `input`.
    """

    if isinstance(input, types.ListType):
        return input
    elif isinstance(input, types.IntType):
        return [input]
    else:
        raise Exception("Invalid parameter passed to `to_list`: only integers and list are accepted.")
        

def CheckVariableRowHeight(listCtrl, text):
    """
    Checks whether a `text` contains multiline strings and if the `listCtrl` window
    style is compatible with multiline strings.

    :param `listCtrl`: an instance of :class:`UltimateListCtrl`;
    :param `text`: the text to analyze.
    """

    if not listCtrl.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
        if "\n" in text:
            raise Exception("Multiline text items are not allowed without the ULC_HAS_VARIABLE_ROW_HEIGHT style.")


def CreateListItem(itemOrId, col):
    """
    Creates a new instance of :class:`UltimateListItem`.

    :param `itemOrId`: can be an instance of :class:`UltimateListItem` or an integer;
    :param `col`: the item column.
    """

    if type(itemOrId) in INTEGER_TYPES:
        item = UltimateListItem()
        item._itemId = itemOrId
        item._col = col
    else:
        item = itemOrId

    return item


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

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

    :param `original`: an instance of :class:`Bitmap` to be greyed-out.
    """
    
    img = original.ConvertToImage()
    return wx.BitmapFromImage(img.ConvertToGreyscale())

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


#----------------------------------------------------------------------
def GetdragcursorData():
    """ Returns the drag and drop cursor image as a decompressed stream of characters. """

    return zlib.decompress(
"x\xda\xeb\x0c\xf0s\xe7\xe5\x92\xe2b``\xe0\xf5\xf4p\t\x02\xd2\xa2@,\xcf\xc1\
\x06$9z\xda>\x00)\xce\x02\x8f\xc8b\x06\x06na\x10fd\x985G\x02(\xd8W\xe2\x1aQ\
\xe2\x9c\x9f\x9b\x9b\x9aW\xc2\x90\xec\x11\xe4\xab\x90\x9cQ\x9a\x97\x9d\x93\
\x9a\xa7`l\xa4\x90\x99\x9e\x97_\x94\x9a\xc2\xeb\x18\xec\xec\xe9i\xa5\xa0\xa7\
W\xa5\xaa\x07\x01P:7\x1eH\xe4\xe8\xe9\xd9\x808\x11\xbc\x1e\xae\x11V\n\x06@`\
\xeehd\n\xa2-\x0c,\x8cA\xb4\x9b\t\x94o\xe2b\x08\xa2\xcd\\L\xdd@\xb4\xab\x85\
\x993\x886v\xb6p\x02\xd1\x86N\xa6\x16\x12\xf7~\xdf\x05\xbal\xa9\xa7\x8bcH\
\xc5\x9c3W9\xb9\x1a\x14\x04X/\xec\xfc\xbft\xed\x02\xa5\xf4\xc2m\xfa*<N\x17??\
\x0frqy\x9c\xd3\xb2f5\xaf\x89\x8f9Gk\xbc\x08\xa7\xbf\x06\x97\x98\x06S\xd8E\
\xbd\x9cE\xb2\x15\x9da\x89\xe2k\x0f\x9c\xb6|\x1a\xea\x14X\x1d6G\x83E\xe7\x9c\
\x1dO\xa8\xde\xb6\x84l\x15\x9eS\xcf\xc2tf\x15\xde\xf7\xb5\xb2]\xf0\x96+\xf5@\
D\x90\x1d\xef19_\xf5\xde5y\xb6+\xa7\xdeZ\xfbA\x9bu\x9f`\xffD\xafYn\xf6\x9eW\
\xeb>\xb6\x7f\x98\\U\xcb\xf5\xd5\xcb\x9a'\xe7\xf4\xd7\x0b\xba\x9e\xdb\x17E\
\xfdf\x97Z\xcb\xcc\xc0\xf0\xff?3\xc3\x92\xabN\x8arB\xc7\x8f\x03\x1d\xcc\xe0\
\xe9\xea\xe7\xb2\xce)\xa1\t\x00B7|\x00" )


def GetdragcursorBitmap():
    """ Returns the drag and drop cursor image as a :class:`Bitmap`. """

    return wx.BitmapFromImage(GetdragcursorImage())


def GetdragcursorImage():
    """ Returns the drag and drop cursor image as a :class:`Image`. """

    stream = cStringIO.StringIO(GetdragcursorData())
    return wx.ImageFromStream(stream)


#-----------------------------------------------------------------------------
#  PyImageList
#-----------------------------------------------------------------------------

class PyImageList(object):
    """
    A :class:`PyImageList` contains a list of images. Images can have masks for
    transparent drawing, and can be made from a variety of sources including
    bitmaps and icons.

    :class:`PyImageList` is used in conjunction with :class:`UltimateListCtrl`.

    :note: The main improvements that :class:`PyImageList` introduces is the removal
     of the limitation of same-size images inside the image list. If you use
     the style ``IL_VARIABLE_SIZE`` then each image can have any size (in terms
     of width and height).
    """
    
    def __init__(self, width, height, mask=True, initialCount=1, style=IL_VARIABLE_SIZE):
        """
        Default class constructor.

        :param `width`: the width of the images in the image list, in pixels (unused
         if you specify the ``IL_VARIABLE_SIZE`` style;
        :param `height`: the height of the images in the image list, in pixels (unused
         if you specify the ``IL_VARIABLE_SIZE`` style;
        :param `mask`: ``True`` if masks should be created for all images (unused in
         :class:`PyImageList`);
        :param `initialCount`: the initial size of the list (unused in :class:`PyImageList`);
        :param `style`: can be one of the following bits:

         ==================== ===== =================================
         Style Flag           Value Description
         ==================== ===== =================================
         ``IL_FIXED_SIZE``        0 All the images in :class:`PyImageList` have the same size (width, height)
         ``IL_VARIABLE_SIZE``     1 Each image can have any size (in terms of width and height)
         ==================== ===== =================================

        """         

        self._width = width
        self._height = height
        self._mask = mask
        self._initialCount = 1
        self._style = style

        self._images = []
        

    def GetImageCount(self):
        """ Returns the number of images in the list. """

        return len(self._images)



    def Add(self, bitmap):
        """
        Adds a new image or images using a bitmap.

        :param `bitmap`: a valid :class:`Bitmap` object.

        :return: The new zero-based image index.

        :note: If the bitmap is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        index = len(self._images)
        
        # Mimic behavior of Windows ImageList_Add that automatically breaks up the added
        # bitmap into sub-images of the correct size

        if self._style & IL_FIXED_SIZE:

            if self._width > 0 and bitmap.GetWidth() > self._width and \
               bitmap.GetHeight() >= self._height:
                
                numImages = bitmap.GetWidth()/self._width
                for subIndex in xrange(numImages):
                    rect = wx.Rect(self._width * subIndex, 0, self._width, self._height)
                    tmpBmp = bitmap.GetSubBitmap(rect)
                    self._images.append(tmpBmp)
                
            else:
                
                self._images.append(bitmap)
        else:
        
            self._images.append(bitmap)

        if self._width == 0 and self._height == 0:
            self._width = bitmap.GetWidth()
            self._height = bitmap.GetHeight()

        return index


    def AddIcon(self, icon):
        """
        Adds a new image using an icon.

        :param `icon`: a valid :class:`Icon` object.

        :return: The new zero-based image index.

        :note: If the icon is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the icon will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        return self.Add(wx.BitmapFromIcon(icon))


    def AddWithColourMask(self, bitmap, maskColour):
        """
        Adds a new image or images using a bitmap and a colour mask.

        :param `bitmap`: a valid :class:`Bitmap` object;
        :param `colour`: an instance of :class:`Colour`, a colour indicating which parts
         of the image are transparent.

        :return: The new zero-based image index.

        :note: If the bitmap is wider than the images in the list and you are not using
         the ``IL_VARIABLE_SIZE`` style, then the bitmap will automatically be split
         into smaller images, each matching the dimensions of the image list.
        """

        img = bitmap.ConvertToImage()
        img.SetMaskColour(maskColour.Red(), maskColour.Green(), maskColour.Blue())
        
        return self.Add(wx.BitmapFromImage(img))


    def GetBitmap(self, index):
        """
        Returns the bitmap corresponding to the given `index`, or :class:`NullBitmap`
        if the index is invalid.

        :param `index`: the bitmap index.
        """

        if index >= len(self._images):
            return wx.NullBitmap
        
        return self._images[index]


    def GetIcon(self, index):
        """
        Returns the icon corresponding to the given `index`, or :class:`NullIcon`
        if the index is invalid.

        :param `index`: the icon index.
        """

        if index >= len(self._images):
            return wx.NullIcon
        
        return wx.IconFromBitmap(self._images[index])
        

    def Replace(self, index, bitmap):
        """
        Replaces the existing image with the new bitmap.

        :param `index`: the index at which the image should be replaced;
        :param `bitmap`: the new bitmap to add to the image list, an instance of
         :class:`Bitmap`.
        """
        
        if index >= len(self._images):
            raise Exception("Wrong index in image list")
        
        self._images[index] = bitmap

        return True


    def ReplaceIcon(self, index, icon):
        """
        Replaces the existing image with the new icon.

        :param `index`: the index at which the image should be replaced;
        :param `icon`: the new icon to add to the image list, an instance of
         :class:`Icon`.
        """

        return self.Replace(index, wx.BitmapFromIcon(icon))


    def Remove(self, index):
        """
        Removes the image at the given position.

        :param `index`: the zero-based index of the image to be removed.
        """

        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        self._images.pop(index)
        return True


    def RemoveAll(self):
        """ Removes all the images in the list. """

        self._images = []
        return True


    def GetSize(self, index):
        """
        Retrieves the size of an image in the list.

        :param `index`: the zero-based index of the image.

        :return: a tuple of `(width, height)` properties of the chosen bitmap.        
        """
                
        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        bmp = self._images[index]
        return bmp.GetWidth(), bmp.GetHeight()


    def Draw(self, index, dc, x, y, flags, solidBackground=True):
        """
        Draws a specified image onto a device context.

        :param `index`: the image index, starting from zero;
        :param `dc`: an instance of :class:`DC`;
        :param `x`: x position on the device context;
        :param `y`: y position on the device context;
        :param `flags`: how to draw the image. A bitlist of a selection of the following:

         ================================= =======================================
         Flag Paarameter                   Description
         ================================= =======================================
         ``wx.IMAGELIST_DRAW_NORMAL``      Draw the image normally
         ``wx.IMAGELIST_DRAW_TRANSPARENT`` Draw the image with transparency
         ``wx.IMAGELIST_DRAW_SELECTED``    Draw the image in selected state
         ``wx.IMAGELIST_DRAW_FOCUSED``     Draw the image in a focused state
         ================================= =======================================

        :param `solidBackground`: currently unused.
        """
        
        if index >= len(self._images):
            raise Exception("Wrong index in image list")

        bmp = self._images[index]    
        dc.DrawBitmap(bmp, x, y, (flags & wx.IMAGELIST_DRAW_TRANSPARENT) > 0)

        return True


class SelectionStore(object):
    """
    SelectionStore is used to store the selected items in the virtual
    controls, i.e. it is well suited for storing even when the control contains
    a huge (practically infinite) number of items.

    Of course, internally it still has to store the selected items somehow (as
    an array currently) but the advantage is that it can handle the selection
    of all items (common operation) efficiently and that it could be made even
    smarter in the future (e.g. store the selections as an array of ranges +
    individual items) without changing its API.
    """

    def __init__(self):
        """ Default class constructor. """

        # the array of items whose selection state is different from default
        self._itemsSel = []
        # the default state: normally, False (i.e. off) but maybe set to true if
        # there are more selected items than non selected ones - this allows to
        # handle selection of all items efficiently
        self._defaultState = False
        # the total number of items we handle
        self._count  = 0

    # special case of SetItemCount(0)
    def Clear(self):
        """ Clears the number of selected items. """

        self._itemsSel = []
        self._count = 0
        self._defaultState = False

    # return the total number of selected items
    def GetSelectedCount(self):
        """ Return the total number of selected items. """
        
        return (self._defaultState and [self._count - len(self._itemsSel)] or [len(self._itemsSel)])[0]


    def IsSelected(self, item):
        """
        Returns ``True`` if the given item is selected.

        :param `item`: the item to check for selection state.
        """

        isSel = item in self._itemsSel

        # if the default state is to be selected, being in m_itemsSel means that
        # the item is not selected, so we have to inverse the logic
        return (self._defaultState and [not isSel] or [isSel])[0]


    def SelectItem(self, item, select=True):
        """
        Selects the given item.

        :param `item`: the item to select;
        :param `select`: ``True`` to select the item, ``False`` otherwise.

        :return: ``True`` if the items selection really changed.
        """

        # search for the item ourselves as like this we get the index where to
        # insert it later if needed, so we do only one search in the array instead
        # of two (adding item to a sorted array requires a search)
        index = bisect.bisect_right(self._itemsSel, item)
        isSel = index < len(self._itemsSel) and self._itemsSel[index] == item

        if select != self._defaultState:
            
            if item not in self._itemsSel:
                bisect.insort_right(self._itemsSel, item)
                return True
        
        else: # reset to default state
        
            if item in self._itemsSel:
                self._itemsSel.remove(item)
                return True
            
        return False


    def SelectRange(self, itemFrom, itemTo, select=True):
        """
        Selects a range of items.

        :param `itemFrom`: the first index of the selection range;
        :param `itemTo`: the last index of the selection range;
        :param `select`: ``True`` to select the items, ``False`` otherwise.
        
        :return: ``True`` and fill the `itemsChanged` array with the indices of items
         which have changed state if "few" of them did, otherwise return ``False``
         (meaning that too many items changed state to bother counting them individually).
        """
    
        # 100 is hardcoded but it shouldn't matter much: the important thing is
        # that we don't refresh everything when really few (e.g. 1 or 2) items
        # change state
        MANY_ITEMS = 100

        # many items (> half) changed state
        itemsChanged = []        

        # are we going to have more [un]selected items than the other ones?
        if itemTo - itemFrom > self._count/2:

            if select != self._defaultState:
            
                # the default state now becomes the same as 'select'
                self._defaultState = select

                # so all the old selections (which had state select) shouldn't be
                # selected any more, but all the other ones should
                selOld = self._itemsSel[:]
                self._itemsSel = []

                # TODO: it should be possible to optimize the searches a bit
                #       knowing the possible range

                for item in xrange(itemFrom):
                    if item not in selOld:
                        self._itemsSel.append(item)
                
                for item in xrange(itemTo + 1, self._count):
                    if item not in selOld:
                        self._itemsSel.append(item)

            else: # select == self._defaultState
            
                # get the inclusive range of items between itemFrom and itemTo
                count = len(self._itemsSel)
                start = bisect.bisect_right(self._itemsSel, itemFrom)
                end = bisect.bisect_right(self._itemsSel, itemTo)

                if itemFrom < start:
                    start = itemFrom

                if start == count or self._itemsSel[start] < itemFrom:
                    start += 1
                
                if end == count or self._itemsSel[end] > itemTo:
                    end -= 1

                if start <= end:
                
                    # delete all of them (from end to avoid changing indices)
                    for i in xrange(end, start-1, -1):
                        if itemsChanged:
                            if len(itemsChanged) > MANY_ITEMS:
                                # stop counting (see comment below)
                                itemsChanged = []
                            else:                            
                                itemsChanged.append(self._itemsSel[i])
                            
                        self._itemsSel.pop(i)
                else:
                    self._itemsSel = []

        else: # "few" items change state
        
            if itemsChanged:
                itemsChanged = []

            # just add the items to the selection
            for item in xrange(itemFrom, itemTo+1):
                if self.SelectItem(item, select) and itemsChanged:
                    itemsChanged.append(item)
                    if len(itemsChanged) > MANY_ITEMS:
                        # stop counting them, we'll just eat gobs of memory
                        # for nothing at all - faster to refresh everything in
                        # this case
                        itemsChanged = []

        # we set it to None if there are many items changing state
        return itemsChanged


    def OnItemDelete(self, item):
        """
        Must be called when an item is deleted.

        :param `item`: the item that is being deleted.
        """

        count = len(self._itemsSel)
        i = bisect.bisect_right(self._itemsSel, item)

        if i < count and self._itemsSel[i] == item:
            # this item itself was in m_itemsSel, remove it from there
            self._itemsSel.pop(i)

            count -= 1
        
        # and adjust the index of all which follow it
        while i < count:

            i += 1        
            self._itemsSel[i] -= 1
        

    def SetItemCount(self, count):
        """
        Sets the total number of items we handle.

        :param `count`: the total number of items we handle.
        """

        # forget about all items whose indices are now invalid if the size
        # decreased
        if count < self._count:
            for i in xrange(len(self._itemsSel), 0, -1):
                if self._itemsSel[i - 1] >= count:
                    self._itemsSel.pop(i - 1)
            
        # remember the new number of items
        self._count = count


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

class UltimateListItemAttr(object):
    """
    Represents the attributes (colour, font, ...) of a :class:`UltimateListCtrl`
    :class:`UltimateListItem`.
    """
    
    def __init__(self, colText=wx.NullColour, colBack=wx.NullColour, font=wx.NullFont,
                 enabled=True, footerColText=wx.NullColour, footerColBack=wx.NullColour,
                 footerFont=wx.NullFont):
        """
        Default class constructor.

        :param `colText`: the item text colour;
        :param `colBack`: the item background colour;
        :param `font`: the item font;
        :param `enabled`: ``True`` if the item should be enabled, ``False`` if it is disabled;
        :param `footerColText`: for footer items, the item text colour;
        :param `footerColBack`: for footer items, the item background colour;
        :param `footerFont`: for footer items, the item font.
        """
        
        self._colText = colText
        self._colBack = colBack
        self._font = font
        self._enabled = enabled

        self._footerColText = footerColText
        self._footerColBack = footerColBack
        self._footerFont = footerFont


    # setters
    def SetTextColour(self, colText):
        """
        Sets a new text colour.

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


    def SetBackgroundColour(self, colBack):
        """
        Sets a new background colour.

        :param `colBack`: an instance of :class:`Colour`.
        """

        self._colBack = colBack


    def SetFont(self, font):
        """
        Sets a new font for the item.

        :param `font`: an instance of :class:`Font`.
        """

        self._font = font


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

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

        self._enabled = enable        


    def SetFooterTextColour(self, colText):
        """
        Sets a new footer item text colour.

        :param `colText`: an instance of :class:`Colour`.
        """

        self._footerColText = colText


    def SetFooterBackgroundColour(self, colBack):
        """
        Sets a new footer item background colour.

        :param `colBack`: an instance of :class:`Colour`.
        """

        self._footerColBack = colBack


    def SetFooterFont(self, font):
        """
        Sets a new font for the footer item.

        :param `font`: an instance of :class:`Font`.
        """

        self._footerFont = font


    # accessors
    def HasTextColour(self):
        """ Returns ``True`` if the currently set text colour is valid. """
        
        return self._colText.Ok()


    def HasBackgroundColour(self):
        """ Returns ``True`` if the currently set background colour is valid. """

        return self._colBack.Ok()


    def HasFont(self):
        """ Returns ``True`` if the currently set font is valid. """

        return self._font.Ok()


    def HasFooterTextColour(self):
        """
        Returns ``True`` if the currently set text colour for the footer item
        is valid.
        """

        return self._footerColText.Ok()


    def HasFooterBackgroundColour(self):
        """
        Returns ``True`` if the currently set background colour for the footer item
        is valid.
        """

        return self._footerColBack.Ok()


    def HasFooterFont(self):
        """
        Returns ``True`` if the currently set font for the footer item
        is valid.
        """

        return self._footerFont.Ok()


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

        return self._colText


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

        return self._colBack


    def GetFont(self):
        """ Returns the currently set item font. """

        return self._font


    def GetFooterTextColour(self):
        """ Returns the currently set text colour for a footer item. """

        return self._footerColText


    def GetFooterBackgroundColour(self):
        """ Returns the currently set background colour for a footer item. """

        return self._footerColBack


    def GetFooterFont(self):
        """ Returns the currently set font for a footer item. """

        return self._footerFont


    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled. """

        return self._enabled        

# ----------------------------------------------------------------------------
# UltimateListItem: the item or column info, used to exchange data with UltimateListCtrl
# ----------------------------------------------------------------------------

class UltimateListItem(wx.Object):
    """ This class stores information about a :class:`UltimateListCtrl` item or column. """
    
    def __init__(self, item=None):
        """
        Default class constructor.

        :param `item`: if not ``None``, another instance of :class:`UltimateListItem`.
        """
        
        if not item:
            self.Init()
            self._attr = None
        else:
            self._mask = item._mask              # Indicates what fields are valid
            self._itemId = item._itemId          # The zero-based item position
            self._col = item._col                # Zero-based column, if in report mode
            self._state = item._state            # The state of the item
            self._stateMask = item._stateMask    # Which flags of self._state are valid (uses same flags)
            self._text = item._text              # The label/header text
            self._tooltip = item._tooltip        # The label/header tooltip text
            self._image = item._image[:]         # The zero-based indexes into an image list
            self._data = item._data              # App-defined data
            self._pyData = item._pyData          # Python-specific data
            self._format = item._format          # left, right, centre
            self._width = item._width            # width of column
            self._colour = item._colour          # item text colour
            self._font = item._font              # item font
            self._checked = item._checked        # The checking state for the item (if kind > 0)
            self._kind = item._kind              # Whether it is a normal, checkbox-like or a radiobutton-like item
            self._enabled = item._enabled        # Whether the item is enabled or not
            self._hypertext = item._hypertext    # indicates if the item is hypertext
            self._visited = item._visited        # visited state for an hypertext item
            self._wnd = item._wnd
            self._windowenabled = item._windowenabled
            self._windowsize = item._windowsize
            self._isColumnShown = item._isColumnShown
            self._customRenderer = item._customRenderer
            self._overFlow = item._overFlow
            self._footerChecked = item._footerChecked
            self._footerFormat = item._footerFormat
            self._footerImage = item._footerImage
            self._footerKind = item._footerKind
            self._footerText = item._footerText
            self._expandWin = item._expandWin
            self._attr = None

            # copy list item attributes
            if item.HasAttributes():
                self._attr = item.GetAttributes()[:]

    # resetting
    def Clear(self):
        """ Resets the item state to the default. """
        
        self.Init()
        self._text = ""
        self.ClearAttributes()


    def ClearAttributes(self):
        """ Deletes the item attributes if they have been stored. """
        
        if self._attr:
            del self._attr
            self._attr = None

    # setters
    def SetMask(self, mask):
        """
        Sets the mask of valid fields.

        :param `mask`: any combination of the following bits:

         ============================ ========= ==============================
         Mask Bits                    Hex Value Description
         ============================ ========= ==============================
         ``ULC_MASK_STATE``                 0x1 :meth:`~UltimateListItem.GetState` is valid
         ``ULC_MASK_TEXT``                  0x2 :meth:`~UltimateListItem.GetText` is valid
         ``ULC_MASK_IMAGE``                 0x4 :meth:`~UltimateListItem.GetImage` is valid
         ``ULC_MASK_DATA``                  0x8 :meth:`~UltimateListItem.GetData` is valid
         ``ULC_MASK_WIDTH``                0x20 :meth:`~UltimateListItem.GetWidth` is valid
         ``ULC_MASK_FORMAT``               0x40 :meth:`~UltimateListItem.GetFormat` is valid
         ``ULC_MASK_FONTCOLOUR``           0x80 :meth:`~UltimateListItem.GetTextColour` is valid
         ``ULC_MASK_FONT``                0x100 :meth:`~UltimateListItem.GetFont` is valid
         ``ULC_MASK_BACKCOLOUR``          0x200 :meth:`~UltimateListItem.GetBackgroundColour` is valid
         ``ULC_MASK_KIND``                0x400 :meth:`~UltimateListItem.GetKind` is valid
         ``ULC_MASK_ENABLE``              0x800 :meth:`~UltimateListItem.IsEnabled` is valid
         ``ULC_MASK_CHECK``              0x1000 :meth:`~UltimateListItem.IsChecked` is valid
         ``ULC_MASK_HYPERTEXT``          0x2000 :meth:`~UltimateListItem.IsHyperText` is valid
         ``ULC_MASK_WINDOW``             0x4000 :meth:`~UltimateListItem.GetWindow` is valid
         ``ULC_MASK_PYDATA``             0x8000 :meth:`~UltimateListItem.GetPyData` is valid
         ``ULC_MASK_SHOWN``             0x10000 :meth:`~UltimateListItem.IsShown` is valid
         ``ULC_MASK_RENDERER``          0x20000 :meth:`~UltimateListItem.GetCustomRenderer` is valid
         ``ULC_MASK_OVERFLOW``          0x40000 :meth:`~UltimateListItem.GetOverFlow` is valid
         ``ULC_MASK_FOOTER_TEXT``       0x80000 :meth:`~UltimateListItem.GetFooterText` is valid
         ``ULC_MASK_FOOTER_IMAGE``     0x100000 :meth:`~UltimateListItem.GetFooterImage` is valid
         ``ULC_MASK_FOOTER_FORMAT``    0x200000 :meth:`~UltimateListItem.GetFooterFormat` is valid
         ``ULC_MASK_FOOTER_FONT``      0x400000 :meth:`~UltimateListItem.GetFooterFont` is valid
         ``ULC_MASK_FOOTER_CHECK``     0x800000 :meth:`~UltimateListItem.IsFooterChecked` is valid
         ``ULC_MASK_FOOTER_KIND``     0x1000000 :meth:`~UltimateListItem.GetFooterKind` is valid
         ============================ ========= ==============================
        
        """
        
        self._mask = mask


    def SetId(self, id):
        """
        Sets the zero-based item position.

        :param `id`: the zero-based item position.
        """
        
        self._itemId = id


    def SetColumn(self, col):
        """
        Sets the zero-based column.

        :param `col`: the zero-based column.
        
        :note: This method is neaningful only in report mode.
        """
        
        self._col = col


    def SetState(self, state):
        """
        Sets the item state flags.

        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :note: The valid state flags are influenced by the value of the state mask.

        :see: :meth:`~UltimateListItem.SetStateMask`
        """
        
        self._mask |= ULC_MASK_STATE
        self._state = state
        self._stateMask |= state


    def SetStateMask(self, stateMask):
        """
        Sets the bitmask that is used to determine which of the state flags are
        to be set.

        :param `stateMask`: the state bitmask.
        
        :see: :meth:`~UltimateListItem.SetState` for a list of valid state bits.
        """
        
        self._stateMask = stateMask


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

        :param `text`: the text label for the item.
        """
        
        self._mask |= ULC_MASK_TEXT
        self._text = text
        
        
    def SetToolTip(self, text):
        """
        Sets the tooltip text for the item.

        :param `text`: the tooltip text for the item.
        """
        self._mask |= ULC_MASK_TOOLTIP
        self._tooltip = text


    def SetImage(self, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """
        
        self._mask |= ULC_MASK_IMAGE
        if image is None:
            image = []
            
        self._image = to_list(image)


    def SetData(self, data):
        """
        Sets client data for the item.

        :param `data`: the client data associated to the item.
        
        :note: Please note that client data is associated with the item and not
         with subitems.
        """
        
        self._mask |= ULC_MASK_DATA
        self._data = data


    def SetPyData(self, pyData):
        """
        Sets data for the item, which can be any Python object.

        :param `data`: any Python object associated to the item.
        
        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        self._mask |= ULC_MASK_PYDATA
        self._pyData = pyData
        

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

        :param `width`: the column width.

        :note: This method is meaningful only for column headers in report mode.
        """
        
        self._mask |= ULC_MASK_WIDTH
        self._width = width


    def SetAlign(self, align):
        """
        Sets the alignment for the item.

        :param `align`: one of the following bits:

         ============================ ========= ==============================
         Alignment Bits               Hex Value Description
         ============================ ========= ==============================
         ``ULC_FORMAT_LEFT``                0x0 The item is left-aligned
         ``ULC_FORMAT_RIGHT``               0x1 The item is right-aligned
         ``ULC_FORMAT_CENTRE``              0x2 The item is centre-aligned
         ``ULC_FORMAT_CENTER``              0x2 The item is center-aligned
         ============================ ========= ==============================

        """
        
        self._mask |= ULC_MASK_FORMAT
        self._format = align


    def SetTextColour(self, colText):
        """
        Sets the text colour for the item.

        :param `colText`: a valid :class:`Colour` object.
        """
        
        self.Attributes().SetTextColour(colText)


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

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

        self.Attributes().SetBackgroundColour(colBack)


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

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

        self.Attributes().SetFont(font)


    def SetFooterTextColour(self, colText):
        """
        Sets the text colour for the footer item.

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

        self.Attributes().SetFooterTextColour(colText)


    def SetFooterBackgroundColour(self, colBack):
        """
        Sets the background colour for the footer item.

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

        self.Attributes().SetFooterBackgroundColour(colBack)


    def SetFooterFont(self, font):
        """
        Sets the font for the footer item.

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

        self.Attributes().SetFooterFont(font)


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

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

        self.Attributes().Enable(enable)        

    # accessors
    def GetMask(self):
        """
        Returns a bit mask indicating which fields of the structure are valid.

        :see: :meth:`~UltimateListItem.SetMask` for a list of valid bit masks.
        """
        
        return self._mask


    def GetId(self):
        """ Returns the zero-based item position. """
        
        return self._itemId


    def GetColumn(self):
        """
        Returns the zero-based column.

        :note: This method is meaningful only in report mode.
        """

        return self._col


    def GetFormat(self):
        """ Returns the header item format. """

        return self._format


    def GetState(self):
        """
        Returns a bit field representing the state of the item.

        :see: :meth:`~UltimateListItem.SetState` for a list of valid item states.
        """
        
        return self._state & self._stateMask


    def GetText(self):
        """ Returns the label/header text. """

        return self._text

    
    def GetToolTip(self):
        """ Returns the label/header tooltip. """

        return self._tooltip


    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.
        """
        
        return self._image


    def GetData(self):
        """
        Returns client data associated with the control.

        :note: Please note that client data is associated with the item and not
         with subitems.
        """
        
        return self._data


    def GetPyData(self):
        """
        Returns data for the item, which can be any Python object.

        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        return self._pyData
    

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

        :note: This method is meaningful only for column headers in report mode.
        """

        return self._width


    def GetAlign(self):
        """
        Returns the alignment for the item.

        :see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment bits.
        """
        
        return self._format


    def GetAttributes(self):
        """ Returns the associated :class:`UltimateListItemAttr` attributes. """

        return self._attr


    def HasAttributes(self):
        """ Returns ``True`` if the item has attributes associated with it. """

        return self._attr != None


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

        return (self.HasAttributes() and [self._attr.GetTextColour()] or [wx.NullColour])[0]


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

        return (self.HasAttributes() and [self._attr.GetBackgroundColour()] or [wx.NullColour])[0]


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

        return (self.HasAttributes() and [self._attr.GetFont()] or [wx.NullFont])[0]


    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled. """

        return (self.HasAttributes() and [self._attr.IsEnabled()] or [True])[0]
    
    # creates self._attr if we don't have it yet
    def Attributes(self):
        """
        Returns the associated attributes if they exist, or create a new :class:`UltimateListItemAttr`
        structure and associate it with this item.
        """
        
        if not self._attr:
            self._attr = UltimateListItemAttr()

        return self._attr


    def SetKind(self, kind): 
        """
        Sets the item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._mask |= ULC_MASK_KIND
        self._kind = kind
        

    def GetKind(self):
        """
        Returns the item kind.

        :see: :meth:`~UltimateListItem.SetKind` for a valid list of item's kind.
        """

        return self._kind
    

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

        return self._checked


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

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio items.
        """

        self._mask |= ULC_MASK_CHECK
        self._checked = checked


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

        return self._isColumnShown
    

    def SetShown(self, shown=True):
        """
        Sets an item as shown/hidden.

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

        self._mask |= ULC_MASK_SHOWN
        self._isColumnShown = shown

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

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


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

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

        self._mask |= ULC_MASK_HYPERTEXT
        self._visited = visited


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

        return self._visited        


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

        return self._hypertext


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

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        self._mask |= ULC_MASK_WINDOW
        self._wnd = wnd

        listCtrl = wnd.GetParent()
        mainWin = listCtrl._mainWin
        
        wnd.Reparent(mainWin)

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

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # UltimateListCtrl and the window associated to an item
        # Do better strategies exist?
        self._wnd.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)        
        self._windowsize = size
        
        # The window is enabled only if the item is enabled                
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled
        self._expandWin = expand

        mainWin._hasWindows = True
        mainWin._itemWithWindow.append(self)

        # This is needed as otherwise widgets that should be invisible
        # are shown at the top left corner of ULC
        mainWin.HideWindows()
        mainWin.Refresh()
        

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

        return self._wnd        


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

        if self._wnd:
            listCtrl = self._wnd.GetParent()            
            if self in listCtrl._itemWithWindow:
                listCtrl._itemWithWindow.remove(self)        
            self._wnd.Destroy()
            self._wnd = None
        

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

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

        return self._windowenabled


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

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

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

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


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


    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`. 
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer


    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer
    

    def SetOverFlow(self, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.        
        """
        
        self._mask |= ULC_MASK_OVERFLOW
        self._overFlow = over


    def GetOverFlow(self):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        """

        return self._overFlow
    
        
    def Init(self):
        """ Initializes an empty :class:`UltimateListItem`. """

        self._mask = 0
        self._itemId = 0
        self._col = 0
        self._state = 0
        self._stateMask = 0
        self._image = []
        self._data = 0
        self._pyData = None
        self._text = ""
        self._tooltip = ""

        self._format = ULC_FORMAT_CENTRE
        self._width = 0

        self._colour = wx.Colour(0, 0, 0)
        self._font = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)

        self._kind = 0
        self._checked = False
        self._enabled = True

        self._hypertext = False    # indicates if the item is hypertext
        self._visited = False      # visited state for an hypertext item

        self._wnd = None
        self._windowenabled = False
        self._windowsize = wx.Size()
        self._isColumnShown = True

        self._customRenderer = None
        self._overFlow = False
        self._footerChecked = False
        self._footerFormat = ULC_FORMAT_CENTRE
        self._footerImage = []
        self._footerKind = 0
        self._footerText = ""
        self._expandWin = False


    def SetFooterKind(self, kind): 
        """
        Sets the footer item kind.

        :see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
        """

        self._mask |= ULC_MASK_FOOTER_KIND
        self._footerKind = kind
        

    def GetFooterKind(self):
        """
        Returns the footer item kind.

        :see: :meth:`~UltimateListItem.SetKind` for a list of valid items kind.
        """

        return self._footerKind
    

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

        return self._footerChecked


    def CheckFooter(self, checked=True):
        """
        Checks/unchecks a footer item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio footer items.
        """

        self._mask |= ULC_MASK_FOOTER_CHECK
        self._footerChecked = checked


    def GetFooterFormat(self):
        """ Returns the footer item format. """

        return self._footerFormat


    def SetFooterFormat(self, format):
        """
        Sets the footer item format.

        :param `format`: the footer item format.
        """

        self._mask |= ULC_MASK_FOOTER_FORMAT
        self._footerFormat = format


    def GetFooterText(self):
        """ Returns the footer text. """

        return self._footerText


    def SetFooterText(self, text):
        """
        Sets the text label for the footer item.

        :param `text`: the text label for the footer item.
        """

        self._mask |= ULC_MASK_FOOTER_TEXT
        self._footerText = text


    def GetFooterImage(self):
        """
        Returns the zero-based index of the image associated with the footer item into
        the image list.
        """

        return self._footerImage


    def SetFooterImage(self, image):
        """
        Sets the zero-based index of the image associated with the footer item into the
        image list.

        :param `image`: the zero-based index of the image associated with the footer item
         into the image list.
        """

        self._mask |= ULC_MASK_FOOTER_IMAGE
        self._footerImage = to_list(image)


    def GetFooterTextColour(self):
        """ Returns the footer item text colour. """

        return (self.HasAttributes() and [self._attr.GetFooterTextColour()] or [wx.NullColour])[0]


    def GetFooterBackgroundColour(self):
        """ Returns the footer item background colour. """

        return (self.HasAttributes() and [self._attr.GetFooterBackgroundColour()] or [wx.NullColour])[0]


    def GetFooterFont(self):
        """ Returns the footer item font. """

        return (self.HasAttributes() and [self._attr.GetFooterFont()] or [wx.NullFont])[0]


    def SetFooterAlign(self, align):
        """
        Sets the alignment for the footer item.

        :see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
        """

        self._mask |= ULC_MASK_FOOTER_FORMAT
        self._footerFormat = align


    def GetFooterAlign(self):
        """
        Returns the alignment for the footer item.

        :see: :meth:`~UltimateListItem.SetAlign` for a list of valid alignment flags.
        """

        return self._footerFormat
    

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

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

        listCtrl = self._wnd.GetParent()
        select = listCtrl.GetItemState(self._itemId, ULC_STATE_SELECTED)

        # 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 not select:
            listCtrl._hasFocus = False
        else:
            listCtrl._hasFocus = True

        listCtrl.SetFocus()
            
        event.Skip()

# ----------------------------------------------------------------------------
# ListEvent - the event class for the UltimateListCtrl notifications
# ----------------------------------------------------------------------------

class CommandListEvent(wx.PyCommandEvent):
    """
    A list event holds information about events associated with :class:`UltimateListCtrl`
    objects.
    """
    
    def __init__(self, commandTypeOrEvent=None, winid=0):
        """
        Default class constructor.
        For internal use: do not call it in your code!

        :param `commandTypeOrEvent`: the event type or another instance of
         :class:`PyCommandEvent`;
        :param `winid`: the event identifier.
        """

        if type(commandTypeOrEvent) == types.IntType:

            wx.PyCommandEvent.__init__(self, commandTypeOrEvent, winid)

            self.m_code = 0
            self.m_oldItemIndex = 0
            self.m_itemIndex = 0
            self.m_col = 0
            self.m_pointDrag = wx.Point()
            self.m_item = UltimateListItem()
            self.m_editCancelled = False

        else:

            wx.PyCommandEvent.__init__(self, commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())
            self.m_code = commandTypeOrEvent.m_code
            self.m_oldItemIndex = commandTypeOrEvent.m_oldItemIndex
            self.m_itemIndex = commandTypeOrEvent.m_itemIndex
            self.m_col = commandTypeOrEvent.m_col
            self.m_pointDrag = commandTypeOrEvent.m_pointDrag
            self.m_item = commandTypeOrEvent.m_item
            self.m_editCancelled = commandTypeOrEvent.m_editCancelled


    def GetKeyCode(self):
        """ Returns the key code if the event is a keypress event. """

        return self.m_code


    def GetIndex(self):
        """ Returns the item index. """

        return self.m_itemIndex


    def GetColumn(self):
        """
        Returns the column position: it is only used with ``COL`` events.

        For the column dragging events, it is the column to the left of the divider
        being dragged, for the column click events it may be -1 if the user clicked
        in the list control header outside any column.
        """
        
        return self.m_col


    def GetPoint(self):
        """ Returns the position of the mouse pointer if the event is a drag event. """
        
        return self.m_pointDrag


    def GetLabel(self):
        """ Returns the (new) item label for ``EVT_LIST_END_LABEL_EDIT`` event. """
        
        return self.m_item._text


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

        return self.m_item._text


    def GetImage(self):
        """ Returns the item image. """

        return self.m_item._image


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

        return self.m_item._data


    def GetMask(self):
        """ Returns the item mask. """

        return self.m_item._mask


    def GetItem(self):
        """ Returns the item itself. """

        return self.m_item


    # for wxEVT_COMMAND_LIST_CACHE_HINT only
    def GetCacheFrom(self):
        """
        Returns the first item which the list control advises us to cache.

        :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
        """

        return self.m_oldItemIndex


    def GetCacheTo(self):
        """
        Returns the last item (inclusive) which the list control advises us to cache.

        :note: This method is meaningful for ``EVT_LIST_CACHE_HINT`` event only.
        """

        return self.m_itemIndex


    # was label editing canceled? (for wxEVT_COMMAND_LIST_END_LABEL_EDIT only)
    def IsEditCancelled(self):
        """
        Returns ``True`` if it the label editing has been cancelled by the user
        (:meth:`~CommandListEvent.GetLabel` returns an empty string in this case but it doesn't allow
        the application to distinguish between really cancelling the edit and
        the admittedly rare case when the user wants to rename it to an empty
        string).

        :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
        """

        return self.m_editCancelled


    def SetEditCanceled(self, editCancelled):
        """
        Sets the item editing as cancelled/not cancelled.

        :param `editCancelled`: ``True`` to set the item editing as cancelled, ``False``
         otherwise.

        :note: This method only makes sense for ``EVT_LIST_END_LABEL_EDIT`` messages.
        """

        self.m_editCancelled = editCancelled



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

class UltimateListEvent(CommandListEvent):
    """
    A list event holds information about events associated with :class:`UltimateListCtrl`
    objects.
    """

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

        :param `commandTypeOrEvent`: the event type or another instance of
         :class:`PyCommandEvent`;
        :param `winid`: the event identifier.
        """

        CommandListEvent.__init__(self, commandTypeOrEvent, winid)

        if type(commandTypeOrEvent) == types.IntType:
            self.notify = wx.NotifyEvent(commandTypeOrEvent, winid)
        else:
            self.notify = wx.NotifyEvent(commandTypeOrEvent.GetEventType(), commandTypeOrEvent.GetId())

        
    def GetNotifyEvent(self):
        """ Returns the actual :class:`NotifyEvent`. """
        
        return self.notify


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

        return self.notify.IsAllowed()


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

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

        self.notify.Veto()


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

        self.notify.Allow()

        
# ============================================================================
# private classes
# ============================================================================

#-----------------------------------------------------------------------------
#  ColWidthInfo (internal)
#-----------------------------------------------------------------------------

class ColWidthInfo(object):
    """ A simple class which holds information about :class:`UltimateListCtrl` columns. """

    def __init__(self, w=0, needsUpdate=True):
        """
        Default class constructor

        :param `w`: the initial width of the column;
        :param `needsUpdate`: ``True`` if the column needs refreshing, ``False``
         otherwise.
        """

        self._nMaxWidth = w
        self._bNeedsUpdate = needsUpdate


#-----------------------------------------------------------------------------
#  UltimateListItemData (internal)
#-----------------------------------------------------------------------------

class UltimateListItemData(object):
    """
    A simple class which holds information about :class:`UltimateListItem` visual
    attributes (client rectangles, positions, etc...).
    """

    def __init__(self, owner):
        """
        Default class constructor

        :param `owner`: an instance of :class:`UltimateListCtrl`.
        """

        # the list ctrl we are in
        self._owner = owner
        self.Init()

        # the item coordinates are not used in report mode, instead this pointer
        # is None and the owner window is used to retrieve the item position and
        # size

        if owner.InReportView():
            self._rect = None
        else:
            self._rect = wx.Rect()


    def SetImage(self, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """

        self._image = to_list(image)


    def SetData(self, data):
        """
        Sets client data for the item.

        :param `data`: the client data associated to the item.
        
        :note: Please note that client data is associated with the item and not
         with subitems.
        """

        self._data = data


    def HasText(self):
        """ Returns ``True`` if the item text is not the empty string. """
        
        return self._text != ""


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

        return self._text
    
    
    def GetToolTip(self):
        """ Returns the item tooltip. """

        return self._tooltip


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

        return self._backColour
    

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

        return self._colour


    def GetFont(self):
        """ Returns the currently set font. """

        return (self._hasFont and [self._font] or [wx.NullFont])[0]


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

        :param `text`: the text label for the item.
        """

        self._text = text


    def SetToolTip(self, tooltip):
        """
        Sets the tooltip for the item

        :param `tooltip`: the tooltip text
        """

        self._tooltip = tooltip


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

        :param `colour`: an instance of :class:`Colour`.
        """

        if colour == wx.NullColour or colour == None:
            if self._hasColour:
                self._hasColour = False
                del self._colour
            return
        
        self._hasColour = True
        self._colour = colour


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

        :param `font`: an instance of :class:`Font`.
        """

        if font == wx.NullFont:
            self._hasFont = False
            del self._font
            return
        
        self._hasFont = True
        self._font = font


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

        :param `colour`: an instance of :class:`Colour`.
        """

        if colour == wx.NullColour:
            self._hasBackColour = False
            del self._backColour
            return
        
        self._hasBackColour = True
        self._backColour = colour
        

    # we can't use empty string for measuring the string width/height, so
    # always return something
    def GetTextForMeasuring(self):
        """
        Returns the item text or a simple string if the item text is the
        empty string.
        """
        
        s = self.GetText()
        if not s.strip():
            s = 'H'

        return s


    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.
        """

        return self._image


    def HasImage(self):
        """ Returns ``True`` if the item has at least one image associated with it. """
        
        return len(self._image) > 0


    def SetKind(self, kind): 
        """
        Sets the item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._kind = kind
        

    def GetKind(self):
        """
        Returns the item kind.

        :see: :meth:`~UltimateListItemData.SetKind` for a list of valid item kinds.
        """

        return self._kind
    

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

        return self._checked


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

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio items.
        """

        self._checked = checked
        

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

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


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

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

        self._visited = visited


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

        return self._visited        


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

        return self._hypertext


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

        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        self._mask |= ULC_MASK_WINDOW
        self._wnd = wnd

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

        # We have to bind the wx.EVT_SET_FOCUS for the associated window
        # No other solution to handle the focus changing from an item in
        # UltimateListCtrl and the window associated to an item
        # Do better strategies exist?
        self._windowsize = size
        
        # The window is enabled only if the item is enabled                
        self._wnd.Enable(self._enabled)
        self._windowenabled = self._enabled
        self._expandWin = expand


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

        return self._wnd        


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

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

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

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

        return self._windowenabled


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

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

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

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


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

    
    def SetAttr(self, attr):
        """
        Sets the item attributes.

        :param `attr`: an instance of :class:`UltimateListItemAttr`.
        """

        self._attr = attr


    def GetAttr(self):
        """ Returns the item attributes. """

        return self._attr


    def HasColour(self):
        """ Returns ``True`` if the currently set text colour is valid. """

        return self._hasColour


    def HasFont(self):
        """ Returns ``True`` if the currently set font is valid. """

        return self._hasFont


    def HasBackgroundColour(self):
        """ Returns ``True`` if the currently set background colour is valid. """

        return self._hasBackColour


    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`. 
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer


    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer
    

    def SetOverFlow(self, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.        
        """

        self._mask |= ULC_MASK_OVERFLOW
        self._overFlow = over


    def GetOverFlow(self):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        """

        return self._overFlow
    

    def Init(self):
        """ Initializes the item data structure. """

        # the item image or -1
        self._image = []
        # user data associated with the item
        self._data = 0
        self._pyData = None
        self._colour = wx.Colour(0, 0, 0)
        self._hasColour = False
        self._hasFont = False
        self._hasBackColour = False
        self._text = ""
        self._tooltip = ""
        
        # kind = 0: normal item
        # kind = 1: checkbox-type item
        self._kind = 0
        self._checked = False

        self._enabled = True
        
        # custom attributes or None
        self._attr = None

        self._hypertext = False
        self._visited = False

        self._wnd = None
        self._windowenabled = True
        self._windowsize = wx.Size()
        self._isColumnShown = True
        self._customRenderer = None
        self._overFlow = False
        self._expandWin = False


    def SetItem(self, info):
        """
        Sets information about the item.

        :param `info`: an instance of :class:`UltimateListItemData`.
        """

        if info._mask & ULC_MASK_TEXT:
            CheckVariableRowHeight(self._owner, info._text)
            self.SetText(info._text)
            
        if info._mask & ULC_MASK_TOOLTIP:
            self.SetToolTip(info._tooltip)

        if info._mask & ULC_MASK_KIND:
            self._kind = info._kind

        if info._mask & ULC_MASK_CHECK:
            self._checked = info._checked

        if info._mask & ULC_MASK_ENABLE:
            self._enabled = info._enabled
            
        if info._mask & ULC_MASK_IMAGE:
            self._image = info._image[:]

        if info._mask & ULC_MASK_DATA:
            self._data = info._data

        if info._mask & ULC_MASK_PYDATA:
            self._pyData = info._pyData
        
        if info._mask & ULC_MASK_HYPERTEXT:
            self._hypertext = info._hypertext
            self._visited = info._visited
            
        if info._mask & ULC_MASK_FONTCOLOUR:
            self.SetColour(info.GetTextColour())

        if info._mask & ULC_MASK_FONT:
            self.SetFont(info.GetFont())

        if info._mask & ULC_MASK_BACKCOLOUR:
            self.SetBackgroundColour(info.GetBackgroundColour())

        if info._mask & ULC_MASK_WINDOW:
            self._wnd = info._wnd
            self._windowenabled = info._windowenabled
            self._windowsize = info._windowsize
            self._expandWin = info._expandWin

        if info._mask & ULC_MASK_SHOWN:
            self._isColumnShown = info._isColumnShown

        if info._mask & ULC_MASK_RENDERER:
            self._customRenderer = info._customRenderer

        if info._mask & ULC_MASK_OVERFLOW:
            self._overFlow = info._overFlow
            
        if info.HasAttributes():

            if self._attr:
                self._attr = info.GetAttributes()
            else:
                self._attr = UltimateListItemAttr(info.GetTextColour(), info.GetBackgroundColour(),
                                                  info.GetFont(), info.IsEnabled(), info.GetFooterTextColour(),
                                                  info.GetFooterBackgroundColour(), info.GetFooterFont())

        if self._rect:

            self._rect.x = -1
            self._rect.y = -1
            self._rect.height = 0
            self._rect.width = info._width


    def SetPosition(self, x, y):
        """
        Sets the item position.

        :param `x`: the item `x` position;
        :param `y`: the item `y` position.
        """

        self._rect.x = x
        self._rect.y = y


    def SetSize(self, width, height):
        """
        Sets the item size.

        :param `width`: the item width, in pixels;
        :param `height`: the item height, in pixels.
        """

        if width != -1:
            self._rect.width = width
        if height != -1:
            self._rect.height = height


    def IsHit(self, x, y):
        """
        Returns ``True`` if the input position is inside the item client rectangle.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        return wx.Rect(self.GetX(), self.GetY(), self.GetWidth(), self.GetHeight()).Contains((x, y))


    def GetX(self):
        """ Returns the item `x` position. """
        
        return self._rect.x


    def GetY(self):
        """ Returns the item `y` position. """

        return self._rect.y


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

        return self._rect.width


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

        return self._rect.height


    def GetItem(self, info):
        """
        Returns information about the item.

        :param `info`: an instance of :class:`UltimateListItemData`.
        """

        mask = info._mask
        if not mask:
            # by default, get everything for backwards compatibility
            mask = -1

        if mask & ULC_MASK_TEXT:
            info._text = self._text
        if mask & ULC_MASK_TOOLTIP:
            info._tooltip = self._tooltip
        if mask & ULC_MASK_IMAGE:
            info._image = self._image[:]
        if mask & ULC_MASK_DATA:
            info._data = self._data
        if mask & ULC_MASK_PYDATA:
            info._pyData = self._pyData
        if info._mask & ULC_MASK_FONT:
            info.SetFont(self.GetFont())
        if mask & ULC_MASK_KIND:
            info._kind = self._kind
        if mask & ULC_MASK_CHECK:
            info._checked = self._checked
        if mask & ULC_MASK_ENABLE:
            info._enabled = self._enabled
        if mask & ULC_MASK_HYPERTEXT:
            info._hypertext = self._hypertext
            info._visited = self._visited
        if mask & ULC_MASK_WINDOW:
            info._wnd = self._wnd
            info._windowenabled = self._windowenabled
            info._windowsize = self._windowsize
            info._expandWin = self._expandWin
        if mask & ULC_MASK_SHOWN:
            info._isColumnShown = self._isColumnShown
        if mask & ULC_MASK_RENDERER:
            info._customRenderer = self._customRenderer
        if mask & ULC_MASK_OVERFLOW:
            info._overFlow = self._overFlow

        if self._attr:

            if self._attr.HasTextColour():
                info.SetTextColour(self._attr.GetTextColour())
            if self._attr.HasBackgroundColour():
                info.SetBackgroundColour(self._attr.GetBackgroundColour())
            if self._attr.HasFont():
                info.SetFont(self._attr.GetFont())
            info.Enable(self._attr.IsEnabled())

        return info


    def IsEnabled(self):
        """ Returns ``True`` if the item is enabled, ``False`` if it is disabled. """

        return self._enabled


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

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

        self._enabled = enable        
        

#-----------------------------------------------------------------------------
#  UltimateListHeaderData (internal)
#-----------------------------------------------------------------------------

class UltimateListHeaderData(object):
    """
    A simple class which holds information about :class:`UltimateListItem` visual
    attributes for the header/footer items (client rectangles, positions, etc...).
    """

    def __init__(self, item=None):
        """
        Default class constructor.
        
        :param `item`: another instance of :class:`UltimateListHeaderData`.
        """

        self.Init()

        if item:
            self.SetItem(item)


    def HasText(self):
        """ Returns ``True`` if the currently set text colour is valid. """

        return self._text != ""


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

        return self._text
   
    
    def GetToolTip(self):
        """ Returns the header/footer item tooltip. """

        return self._tooltip


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

        :param `text`: the new header/footer text.
        """

        self._text = text
        
        
    def SetToolTip(self, tip):
        """
        Sets the header/footer item tooltip.

        :param `tip`: the new header/footer tooltip.
        """

        self._tip = tip

        
    def GetFont(self):
        """ Returns the header/footer item font. """
        
        return self._font
    

    def Init(self):
        """ Initializes the header/footer item. """

        self._mask = 0
        self._image = []
        self._format = 0
        self._width = 0
        self._xpos = 0
        self._ypos = 0
        self._height = 0
        self._text = ""
        self._tooltip = ""
        self._kind = 0
        self._checked = False
        self._font = wx.NullFont
        self._state = 0
        self._isColumnShown = True
        self._customRenderer = None

        self._footerImage = []
        self._footerFormat = 0
        self._footerText = ""
        self._footerKind = 0
        self._footerChecked = False
        self._footerFont = wx.NullFont
        

    def SetItem(self, item):
        """
        Sets information about the header/footer item.

        :param `info`: an instance of :class:`UltimateListHeaderData`.
        """

        self._mask = item._mask

        if self._mask & ULC_MASK_TEXT:
            self._text = item._text
            
        if self._mask & ULC_MASK_TOOLTIP:
            self._tooltip = item._tooltip

        if self._mask & ULC_MASK_FOOTER_TEXT:
            self._footerText = item._footerText

        if self._mask & ULC_MASK_IMAGE:
            self._image = item._image[:]

        if self._mask & ULC_MASK_FOOTER_IMAGE:
            self._footerImage = item._footerImage[:]

        if self._mask & ULC_MASK_FORMAT:
            self._format = item._format

        if self._mask & ULC_MASK_FOOTER_FORMAT:
            self._footerFormat = item._footerFormat

        if self._mask & ULC_MASK_WIDTH:
            self.SetWidth(item._width)

        if self._mask & ULC_MASK_FONT:
            self._font = item._font

        if self._mask & ULC_MASK_FOOTER_FONT:
            self._footerFont = item._footerFont
            
        if self._mask & ULC_MASK_FOOTER_KIND:
            self._footerKind = item._footerKind
            self._footerChecked = item._footerChecked

        if self._mask & ULC_MASK_KIND:
            self._kind = item._kind
            self._checked = item._checked

        if self._mask & ULC_MASK_CHECK:
            self._kind = item._kind
            self._checked = item._checked

        if self._mask & ULC_MASK_FOOTER_CHECK:
            self._footerKind = item._footerKind
            self._footerChecked = item._footerChecked

        if self._mask & ULC_MASK_STATE:
            self.SetState(item._state)

        if self._mask & ULC_MASK_SHOWN:
            self._isColumnShown = item._isColumnShown
            
        if self._mask & ULC_MASK_RENDERER:
            self._customRenderer = item._customRenderer


    def SetState(self, flag):
        """
        Sets the item state flags.

        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        """

        self._state = flag


    def SetPosition(self, x, y):
        """
        Sets the header/footer item position.

        :param `x`: the item `x` position;
        :param `y`: the item `y` position.
        """

        self._xpos = x
        self._ypos = y


    def SetHeight(self, h):
        """
        Sets the header/footer item height, in pixels.

        :param `h`: an integer value representing the header/footer height.
        """

        self._height = h


    def SetWidth(self, w):
        """
        Sets the header/footer item width, in pixels.

        :param `w`: an integer value representing the header/footer width.
        """

        self._width = w

        if self._width < 0:
            self._width = WIDTH_COL_DEFAULT
        elif self._width < WIDTH_COL_MIN:
            self._width = WIDTH_COL_MIN


    def SetFormat(self, format):
        """
        Sets the header item format.

        :param `format`: the header item format.
        """
        
        self._format = format


    def SetFooterFormat(self, format):
        """
        Sets the footer item format.

        :param `format`: the footer item format.
        """

        self._footerFormat = format
        

    def HasImage(self):
        """
        Returns ``True`` if the header item has at least one image associated
        with it.
        """

        return len(self._image) > 0


    def HasFooterImage(self):
        """
        Returns ``True`` if the footer item has at least one image associated
        with it.
        """

        return len(self._footerImage) > 0
    

    def IsHit(self, x, y):
        """
        Returns ``True`` if the input position is inside the item client rectangle.

        :param `x`: the `x` mouse position;
        :param `y`: the `y` mouse position.
        """

        return ((x >= self._xpos) and (x <= self._xpos+self._width) and (y >= self._ypos) and (y <= self._ypos+self._height))


    def GetItem(self, item):
        """
        Returns information about the item.

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

        item._mask = self._mask
        item._text = self._text
        item._tooltip = self._tooltip
        item._image = self._image[:]
        item._format = self._format
        item._width = self._width
        if self._font:
            item._font = self._font
            item.Attributes().SetFont(self._font)

        item._kind = self._kind
        item._checked = self._checked
        item._state = self._state
        item._isColumnShown = self._isColumnShown

        item._footerImage = self._footerImage
        item._footerFormat = self._footerFormat
        item._footerText = self._footerText
        item._footerKind = self._footerKind
        item._footerChecked = self._footerChecked
        item._footerFont = self._footerFont
        item._customRenderer = self._customRenderer

        return item


    def GetState(self):
        """
        Returns a bit field representing the state of the item.

        :see: :meth:`~UltimateListHeaderData.SetState` for a list of valid item states.
        """

        return self._state

    
    def GetImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the header item into the image list.
        """

        return self._image


    def GetFooterImage(self):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the footer item into the image list.
        """

        return self._footerImage
    

    def GetWidth(self):
        """ Returns the header/footer item width, in pixels. """
        
        return self._width


    def GetFormat(self):
        """ Returns the header item format. """

        return self._format


    def GetFooterFormat(self):
        """ Returns the footer item format. """

        return self._footerFormat


    def SetFont(self, font):
        """
        Sets a new font for the header item.

        :param `font`: an instance of :class:`Font`.
        """

        self._font = font
        

    def SetFooterFont(self, font):
        """
        Sets a new font for the footer item.

        :param `font`: an instance of :class:`Font`.
        """

        self._footerFont = font


    def SetKind(self, kind): 
        """
        Sets the header item kind.

        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        self._kind = kind
        

    def SetFooterKind(self, kind): 
        """
        Sets the footer item kind.

        :param `kind`: the footer item kind.

        :see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
        """

        self._footerKind = kind


    def GetKind(self):
        """
        Returns the header item kind.

        :see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
        """

        return self._kind
    

    def GetFooterKind(self):
        """
        Returns the footer item kind.

        :see: :meth:`~UltimateListHeaderData.SetKind` for a list of valid item kinds.
        """

        return self._footerKind


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

        return self._checked


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

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio header items.
        """

        self._checked = checked


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

        return self._footerChecked


    def CheckFooter(self, check=True):
        """
        Checks/unchecks a footer item.

        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio footer items.
        """

        self._footerChecked = check

        
    def SetCustomRenderer(self, renderer):
        """
        Associate a custom renderer to this item.

        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`. 
        """

        self._mask |= ULC_MASK_RENDERER
        self._customRenderer = renderer


    def GetCustomRenderer(self):
        """ Returns the custom renderer associated with this item (if any). """

        return self._customRenderer
            

#-----------------------------------------------------------------------------
#  GeometryInfo (internal)
#  this is not used in report view
#-----------------------------------------------------------------------------

class GeometryInfo(object):
    """
    A simple class which holds items geometries for :class:`UltimateListCtrl` not in
    report mode.
    """

    def __init__(self):
        """ Default class constructor. """

        # total item rect
        self._rectAll = wx.Rect()

        # label only
        self._rectLabel = wx.Rect()

        # icon only
        self._rectIcon = wx.Rect()

        # the part to be highlighted
        self._rectHighlight = wx.Rect()

        # the checkbox/radiobutton rect (if any)
        self._rectCheck = wx.Rect()

    # extend all our rects to be centered inside the one of given width
    def ExtendWidth(self, w):
        """
        Extends all our rectangles to be centered inside the one of given width.

        :param `w`: the given width.
        """

        if self._rectAll.width > w:
            raise Exception("width can only be increased")

        self._rectAll.width = w
        self._rectLabel.x = self._rectAll.x + (w - self._rectLabel.width)/2
        self._rectIcon.x = self._rectAll.x + (w - self._rectIcon.width)/2
        self._rectHighlight.x = self._rectAll.x + (w - self._rectHighlight.width)/2


#-----------------------------------------------------------------------------
#  UltimateListLineData (internal)
#-----------------------------------------------------------------------------

class UltimateListLineData(object):
    """ A simple class which holds line geometries for :class:`UltimateListCtrl`. """

    def __init__(self, owner):
        """
        Default class constructor.

        :param `owner`: an instance of :class:`UltimateListCtrl`.
        """

        # the list of subitems: only may have more than one item in report mode
        self._items = []

        # is this item selected? [NB: not used in virtual mode]
        self._highlighted = False

        # back pointer to the list ctrl
        self._owner = owner
        self._height = self._width = self._x = self._y = -1

        if self.InReportView():

            self._gi = None

        else:

            self._gi = GeometryInfo()

        if self.GetMode() in [ULC_REPORT, ULC_TILE] or self.HasMode(ULC_HEADER_IN_ALL_VIEWS):
            self.InitItems(self._owner.GetColumnCount())
        else:
            self.InitItems(1)


    def SetReportView(self, inReportView):
        """
        Sets whether :class:`UltimateListLineData` is in report view or not.

        :param `inReportView`: ``True`` to set :class:`UltimateListLineData` in report view, ``False``
         otherwise.
        """

        # we only need m_gi when we're not in report view so update as needed
        if inReportView:

            del self._gi
            self._gi = None
            
        else:

            self._gi = GeometryInfo()


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

        return self._height


    def SetHeight(self, height):
        """
        Sets the line height.

        :param `height`: the new line height.
        """

        self._height = height


    def GetWidth(self):
        """ Returns the line width. """

        return self._width


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

        :param `width`: the new line width.
        """

        self._width = width


    def GetX(self):
        """ Returns the line `x` position. """

        return self._x


    def SetX(self, x):
        """
        Sets the line `x` position.

        :param `x`: the new line `x` position.
        """

        self._x = x       


    def GetY(self):
        """ Returns the line `y` position. """

        return self._y        


    def SetY(self, y):
        """
        Sets the line `y` position.

        :param `y`: the new line `y` position.
        """

        self._y = y


    def ResetDimensions(self):
        """ Resets the line dimensions (client rectangle). """

        self._height = self._width = self._x = self._y = -1        

    
    def HasImage(self, col=0):
        """
        Returns ``True`` if the first item in the line has at least one image
        associated with it.
        """

        return self.GetImage(col) != []


    def HasText(self):
        """
        Returns ``True`` if the text of first item in the line is not the empty
        string.
        """

        return self.GetText(0) != ""


    def IsHighlighted(self):
        """ Returns ``True`` if the line is highlighted. """

        if self.IsVirtual():
            raise Exception("unexpected call to IsHighlighted")

        return self._highlighted


    def GetMode(self):
        """ Returns the current highlighting mode. """

        return self._owner.GetListCtrl().GetAGWWindowStyleFlag() & ULC_MASK_TYPE


    def HasMode(self, mode):
        """
        Returns ``True`` if the parent :class:`UltimateListCtrl` has the window
        style specified by `mode`.

        :param `mode`: the window style to check.
        """

        return self._owner.GetListCtrl().HasAGWFlag(mode)
        

    def InReportView(self):
        """ Returns ``True`` if the parent :class:`UltimateListCtrl` is in report view. """
        
        return self._owner.HasAGWFlag(ULC_REPORT)


    def IsVirtual(self):
        """ Returns ``True`` if the parent :class:`UltimateListCtrl` has the ``ULC_VIRTUAL`` style set. """

        return self._owner.IsVirtual()


    def CalculateSize(self, dc, spacing):
        """
        Calculates the line size and item positions.

        :param `dc`: an instance of :class:`DC`;
        :param `spacing`: the spacing between the items, in pixels.
        """

        item = self._items[0]
        mode = self.GetMode()

        if mode in [ULC_ICON, ULC_SMALL_ICON]:

            self._gi._rectAll.width = spacing

            s = item.GetText()

            if not s:

                lh = -1
                self._gi._rectLabel.width = 0
                self._gi._rectLabel.height = 0

            else:

                lw, lh = dc.GetTextExtent(s)
                lw += EXTRA_WIDTH
                lh += EXTRA_HEIGHT

                self._gi._rectAll.height = spacing + lh

                if lw > spacing:
                    self._gi._rectAll.width = lw

                self._gi._rectLabel.width = lw
                self._gi._rectLabel.height = lh

            if item.HasImage():

                w, h = self._owner.GetImageSize(item.GetImage())
                self._gi._rectIcon.width = w + 8
                self._gi._rectIcon.height = h + 8

                if self._gi._rectIcon.width > self._gi._rectAll.width:
                    self._gi._rectAll.width = self._gi._rectIcon.width
                if self._gi._rectIcon.height + lh > self._gi._rectAll.height - 4:
                    self._gi._rectAll.height = self._gi._rectIcon.height + lh + 4

            if item.HasText():

                self._gi._rectHighlight.width = self._gi._rectLabel.width
                self._gi._rectHighlight.height = self._gi._rectLabel.height

            else:

                self._gi._rectHighlight.width = self._gi._rectIcon.width
                self._gi._rectHighlight.height = self._gi._rectIcon.height
                
        elif mode == ULC_LIST:

            s = item.GetTextForMeasuring()

            lw, lh = dc.GetTextExtent(s)
            lw += EXTRA_WIDTH
            lh += EXTRA_HEIGHT

            self._gi._rectLabel.width = lw
            self._gi._rectLabel.height = lh

            self._gi._rectAll.width = lw
            self._gi._rectAll.height = lh

            if item.HasImage():

                w, h = self._owner.GetImageSize(item.GetImage())
                h += 4
                self._gi._rectIcon.width = w
                self._gi._rectIcon.height = h

                self._gi._rectAll.width += 4 + w

                if h > self._gi._rectAll.height:
                    self._gi._rectAll.height = h

            if item.GetKind() in [1, 2]:

                w, h = self._owner.GetCheckboxImageSize()
                h += 4
                self._gi._rectCheck.width = w
                self._gi._rectCheck.height = h

                self._gi._rectAll.width += 4 + w
                
                if h > self._gi._rectAll.height:
                    self._gi._rectAll.height = h
                
            self._gi._rectHighlight.width = self._gi._rectAll.width
            self._gi._rectHighlight.height = self._gi._rectAll.height

        elif mode == ULC_REPORT:
            raise Exception("unexpected call to SetSize")

        else:
            raise Exception("unknown mode")


    def SetPosition(self, x, y, spacing):
        """
        Sets the line position.

        :param `x`: the current `x` coordinate;
        :param `y`: the current `y` coordinate;
        :param `spacing`: the spacing between items, in pixels.
        """

        item = self._items[0]
        mode = self.GetMode()

        if mode in [ULC_ICON, ULC_SMALL_ICON]:

            self._gi._rectAll.x = x
            self._gi._rectAll.y = y

            if item.HasImage():

                self._gi._rectIcon.x = self._gi._rectAll.x + 4 + (self._gi._rectAll.width - self._gi._rectIcon.width)/2
                self._gi._rectIcon.y = self._gi._rectAll.y + 4

            if item.HasText():

                if self._gi._rectLabel.width > spacing:
                    self._gi._rectLabel.x = self._gi._rectAll.x + 2
                else:
                    self._gi._rectLabel.x = self._gi._rectAll.x + 2 + (spacing/2) - (self._gi._rectLabel.width/2)
                    
                self._gi._rectLabel.y = self._gi._rectAll.y + self._gi._rectAll.height + 2 - self._gi._rectLabel.height
                self._gi._rectHighlight.x = self._gi._rectLabel.x - 2
                self._gi._rectHighlight.y = self._gi._rectLabel.y - 2

            else:

                self._gi._rectHighlight.x = self._gi._rectIcon.x - 4
                self._gi._rectHighlight.y = self._gi._rectIcon.y - 4

        elif mode == ULC_LIST:

            self._gi._rectAll.x = x
            self._gi._rectAll.y = y

            wcheck = hcheck = 0
            
            if item.GetKind() in [1, 2]:
                wcheck, hcheck = self._owner.GetCheckboxImageSize()
                wcheck += 2
                self._gi._rectCheck.x = self._gi._rectAll.x + 2
                self._gi._rectCheck.y = self._gi._rectAll.y + 2
                
            self._gi._rectHighlight.x = self._gi._rectAll.x
            self._gi._rectHighlight.y = self._gi._rectAll.y
            self._gi._rectLabel.y = self._gi._rectAll.y + 2

            if item.HasImage():

                self._gi._rectIcon.x = self._gi._rectAll.x + wcheck + 2
                self._gi._rectIcon.y = self._gi._rectAll.y + 2
                self._gi._rectLabel.x = self._gi._rectAll.x + 6 + self._gi._rectIcon.width + wcheck

            else:

                self._gi._rectLabel.x = self._gi._rectAll.x + 2 + wcheck

        elif mode == ULC_REPORT:
            raise Exception("unexpected call to SetPosition")

        else:
            raise Exception("unknown mode")


    def InitItems(self, num):
        """
        Initializes the list of items.

        :param `num`: the initial number of items to store.
        """

        for i in xrange(num):
            self._items.append(UltimateListItemData(self._owner))


    def SetItem(self, index, info):
        """
        Sets information about the item.

        :param `index`: the index of the item;
        :param `info`: an instance of :class:`UltimateListItem`.
        """

        item = self._items[index]
        item.SetItem(info)


    def GetItem(self, index, info):
        """
        Returns information about the item.

        :param `index`: the index of the item;
        :param `info`: an instance of :class:`UltimateListItem`.
        """

        item = self._items[index]
        return item.GetItem(info)


    def GetText(self, index):
        """
        Returns the item text at the position `index`.

        :param `index`: the index of the item.
        """
        
        item = self._items[index]
        return item.GetText()


    def SetText(self, index, s):
        """
        Sets the item text at the position `index`.

        :param `index`: the index of the item;
        :param `s`: the new item text.
        """

        item = self._items[index]
        item.SetText(s)


    def GetToolTip(self, index):
        """
        Returns the item tooltip at the position `index`.

        :param `index`: the index of the item.
        """
        
        item = self._items[index]
        return item.GetToolTip()


    def SetToolTip(self, index, s):
        """
        Sets the item tooltip at the position `index`.

        :param `index`: the index of the item;
        :param `s`: the new item tooltip.
        """

        item = self._items[index]
        item.SetToolTip(s)


    def SetImage(self, index, image):
        """
        Sets the zero-based indexes of the images associated with the item into the
        image list.

        :param `index`: the index of the item;
        :param `image`: a Python list with the zero-based indexes of the images
         associated with the item into the image list.
        """

        item = self._items[index]
        item.SetImage(image)


    def GetImage(self, index=0):
        """
        Returns a Python list with the zero-based indexes of the images associated
        with the item into the image list.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.GetImage()


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

        :param `index`: the index of the item;
        :param `checked`: ``True`` to check an item, ``False`` to uncheck it.
        
        :note: This method is meaningful only for check and radio items.
        """

        item = self._items[index]
        item.Check(checked)


    def SetKind(self, index, kind=0):
        """
        Sets the item kind.

        :param `index`: the index of the item;        
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = self._items[index]
        item.SetKind(kind)
                

    def GetKind(self, index=0):
        """
        Returns the item kind.

        :param `index`: the index of the item.

        :see: :meth:`~UltimateListLineData.SetKind` for a list of valid item kinds.
        """

        item = self._items[index]
        return item.GetKind()


    def IsChecked(self, index):
        """
        Returns whether the item is checked or not.

        :param `index`: the index of the item.
        """

        item = self._items[index]
        return item.IsChecked()


    def SetColour(self, index, c):
        """
        Sets the text colour for the item.

        :param `index`: the index of the item;
        :param `c`: an instance of :class:`Colour`.
        """

        item = self._items[index]
        item.SetColour(c)


    def GetAttr(self):
        """
        Returns an instance of :class:`UltimateListItemAttr` associated with the first item
        in the line.
        """
        
        item = self._items[0]
        return item.GetAttr()


    def SetAttr(self, attr):
        """
        Sets an instance of :class:`UltimateListItemAttr` to the first item in the line.

        :param `attr`: an instance of :class:`UltimateListItemAttr`.
        """

        item = self._items[0]
        item.SetAttr(attr)


    def SetAttributes(self, dc, attr, highlighted):
        """
        Sets various attributes to the input device context.

        :param `dc`: an instance of :class:`DC`;
        :param `attr`: an instance of :class:`UltimateListItemAttr`;
        :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise.
        """
        
        listctrl = self._owner.GetParent()

        # fg colour
        # don't use foreground colour for drawing highlighted items - this might
        # make them completely invisible (and there is no way to do bit
        # arithmetics on wxColour, unfortunately)

        if not self._owner.HasAGWFlag(ULC_BORDER_SELECT) and not self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
            if highlighted:
                if wx.Platform == "__WXMAC__":
                    if self._owner.HasFocus():
                        colText = wx.WHITE
                    else:
                        colText = wx.BLACK
                else:
                    colText = wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHTTEXT)
            else:
                if attr and attr.HasTextColour():
                    colText = attr.GetTextColour()
                else:
                    colText = listctrl.GetForegroundColour()
        elif attr and attr.HasTextColour():
            colText = attr.GetTextColour()
        else:
            colText = listctrl.GetForegroundColour()

        dc.SetTextForeground(colText)

        # font
        if attr and attr.HasFont():
            font = attr.GetFont()
        else:
            font = listctrl.GetFont()

        dc.SetFont(font)

        # bg colour
        hasBgCol = attr and attr.HasBackgroundColour()

        if highlighted or hasBgCol:
            if highlighted:
                dc.SetBrush(self._owner.GetHighlightBrush())
            else:
                dc.SetBrush(wx.Brush(attr.GetBackgroundColour(), wx.SOLID))

            dc.SetPen(wx.TRANSPARENT_PEN)

            return True

        return False


    def Draw(self, line, dc):
        """
        Draws the line on the specified device context.

        :param `line`: an instance of :class:`UltimateListLineData`;
        :param `dc`: an instance of :class:`DC`.
        """

        item = self._items[0]
        highlighted = self.IsHighlighted()

        attr = self.GetAttr()

        useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
        useVista = self._owner._vistaselection
        hasFocus = self._owner._hasFocus
        borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
        drawn = False

        if self.SetAttributes(dc, attr, highlighted):
            drawn = True

            if not borderOnly:

                if useGradient:
                    if gradientStyle == 0:
                        # horizontal gradient
                        self.DrawHorizontalGradient(dc, self._gi._rectAll, hasFocus)
                    else:
                        # vertical gradient
                        self.DrawVerticalGradient(dc, self._gi._rectAll, hasFocus)
                elif useVista:
                    # Vista selection style
                    self.DrawVistaRectangle(dc, self._gi._rectAll, hasFocus)
                else:
                    if highlighted:
                        flags = wx.CONTROL_SELECTED
                        if self._owner.HasFocus() and wx.Platform == "__WXMAC__":
                            flags |= wx.CONTROL_FOCUSED

                        wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, self._gi._rectHighlight, flags)
                    else:
                        dc.DrawRectangleRect(self._gi._rectHighlight)

        else:

            if borderOnly:
                dc.SetBrush(wx.WHITE_BRUSH)
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.DrawRectangleRect(self._gi._rectAll)

        if item.GetKind() in [1, 2]:
            rectCheck = self._gi._rectCheck
            self._owner.DrawCheckbox(dc, rectCheck.x, rectCheck.y, item.GetKind(), item.IsChecked(), item.IsEnabled())

        if item.HasImage():
            # centre the image inside our rectangle, this looks nicer when items
            # ae aligned in a row
            rectIcon = self._gi._rectIcon
            self._owner.DrawImage(item.GetImage()[0], dc, rectIcon.x, rectIcon.y, True)

        if item.HasText():
            rectLabel = self._gi._rectLabel

            dc.SetClippingRect(rectLabel)
            dc.DrawText(item.GetText(), rectLabel.x, rectLabel.y)
            dc.DestroyClippingRegion()

        if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
            if line == self._owner._newHotCurrent and not drawn:
                r = wx.Rect(*self._gi._rectAll)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(wx.NamedColour("orange")))
                dc.DrawRoundedRectangleRect(r, 3)

        if borderOnly and drawn:
            dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            r = wx.Rect(*self._gi._rectAll)
            r.x += 1
            r.y += 1
            r.width -= 1
            r.height -= 1
            dc.DrawRoundedRectangleRect(r, 4)
            

    def HideItemWindow(self, item):
        """
        If the input item has a window associated with it, hide it.

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

        wnd = item.GetWindow()
        if wnd and wnd.IsShown():
            wnd.Hide()
                

    def DrawInReportMode(self, dc, line, rect, rectHL, highlighted, current, enabled, oldPN, oldBR):
        """
        Draws the line on the specified device context when the parent :class:`UltimateListCtrl`
        is in report mode.

        :param `dc`: an instance of :class:`DC`;
        :param `line`: an instance of :class:`UltimateListLineData`;
        :param `rect`: the item client rectangle;
        :param `rectHL`: the item client rectangle when the item is highlighted;
        :param `highlighted`: ``True`` if the item is highlighted, ``False`` otherwise;
        :param `current`: ``True`` if the item is the current item;
        :param `enabled`: ``True`` if the item is enabled, ``False`` otherwise;
        :param `oldPN`: an instance of :class:`Pen`, to save and restore at the end of
         the drawing;
        :param `oldBR`: an instance of :class:`Brush`, to save and restore at the end of
         the drawing.     
        """

        attr = self.GetAttr()

        useGradient, gradientStyle = self._owner._usegradients, self._owner._gradientstyle
        highlightedtextcolour = self._owner._highlightedtextcolour
        
        useVista = self._owner._vistaselection
        hasFocus = self._owner._hasFocus
        borderOnly = self._owner.HasAGWFlag(ULC_BORDER_SELECT)
        nofullRow = self._owner.HasAGWFlag(ULC_NO_FULL_ROW_SELECT)
        
        drawn = False
        dc.SetBrush(wx.TRANSPARENT_BRUSH)

        if nofullRow:
            
            x = rect.x + HEADER_OFFSET_X
            y = rect.y
            height = rect.height

            for col, item in enumerate(self._items):

                width = self._owner.GetColumnWidth(col)
                if self._owner.IsColumnShown(col):
                    paintRect = wx.Rect(x, y, self._owner.GetColumnWidth(col)-2*HEADER_OFFSET_X, rect.height)
                    break

                xOld = x
                x += width

        else:

            paintRect = wx.Rect(*rectHL)            
        
        if self.SetAttributes(dc, attr, highlighted) and enabled:
            
            drawn = True
                                
            if not borderOnly:
            
                if useGradient:
                    if gradientStyle == 0:
                        # horizontal gradient
                        self.DrawHorizontalGradient(dc, paintRect, hasFocus)
                    else:
                        # vertical gradient
                        self.DrawVerticalGradient(dc, paintRect, hasFocus)
                elif useVista:
                    # Vista selection style
                    self.DrawVistaRectangle(dc, paintRect, hasFocus)
                else:
                    if highlighted:
                        flags = wx.CONTROL_SELECTED
                        if hasFocus:
                            flags |= wx.CONTROL_FOCUSED
                        if current:
                            flags |= wx.CONTROL_CURRENT
                           
                        wx.RendererNative.Get().DrawItemSelectionRect(self._owner, dc, paintRect, flags)                        
                    else:
                        dc.DrawRectangleRect(paintRect)

        else:
    
            if borderOnly:

                dc.SetBrush(wx.WHITE_BRUSH)
                dc.SetPen(wx.TRANSPARENT_PEN)
                dc.DrawRectangleRect(paintRect)

        x = rect.x + HEADER_OFFSET_X
        y = rect.y
        height = rect.height
        boldFont = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        boldFont.SetWeight(wx.BOLD)

        for col, item in enumerate(self._items):
          
            if not self._owner.IsColumnShown(col):
                self.HideItemWindow(item)
                continue
            
            width = self._owner.GetColumnWidth(col)
            xOld = x
            x += width

            if item.GetCustomRenderer():
                customRect = wx.Rect(xOld-HEADER_OFFSET_X, rect.y, width, rect.height)
                item.GetCustomRenderer().DrawSubItem(dc, customRect, line, highlighted, enabled)
                continue

            overflow = item.GetOverFlow() and item.HasText()
            
            if item.GetKind() in [1, 2]:
                
                # We got a checkbox-type item
                ix, iy = self._owner.GetCheckboxImageSize()
                checked = item.IsChecked()
                self._owner.DrawCheckbox(dc, xOld, y + (height-iy+1)/2, item.GetKind(), checked, enabled)
                xOld += ix
                width -= ix
                
            if item.HasImage():

                images = item.GetImage()
                
                for img in images:
                    
                    ix, iy = self._owner.GetImageSize([img])
                    self._owner.DrawImage(img, dc, xOld, y + (height-iy)/2, enabled)
                    
                    xOld += ix
                    width -= ix

##                if images:
##                    width -= IMAGE_MARGIN_IN_REPORT_MODE - MARGIN_BETWEEN_TEXT_AND_ICON

            wnd = item.GetWindow()
            xSize = 0
            if wnd:
                xSize, ySize = item.GetWindowSize()
                wndx = xOld - HEADER_OFFSET_X + width - xSize - 3
                xa, ya = self._owner.CalcScrolledPosition((0, rect.y))
                wndx += xa
                if rect.height > ySize and not item._expandWin:
                    ya += (rect.height - ySize)/2

            itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, width-xSize-HEADER_OFFSET_X, rect.height)
            if overflow:
                itemRect = wx.Rect(xOld-2*HEADER_OFFSET_X, rect.y, rectHL.width-xSize-HEADER_OFFSET_X, rect.height)

            dc.SetClippingRect(itemRect)
            
            if item.HasBackgroundColour():
                dc.SetBrush(wx.Brush(item.GetBackgroundColour()))
                dc.SetPen(wx.Pen(item.GetBackgroundColour()))
                dc.DrawRectangleRect(itemRect)
                dc.SetBrush(oldBR)
                dc.SetPen(oldPN)

            if item.HasText():

                coloured = item.HasColour()
                
                c = dc.GetTextForeground()
                oldTF = wx.Colour(c.Red(),c.Green(),c.Blue())
                oldFT = dc.GetFont()

                font = item.HasFont()

                if not enabled:
                    dc.SetTextForeground(self._owner.GetDisabledTextColour())
                else:
                    if coloured:
                        dc.SetTextForeground(item.GetColour())
                    elif useVista and drawn:
                        dc.SetTextForeground(wx.BLACK)

                    if highlightedtextcolour and current:
                        dc.SetTextForeground(highlightedtextcolour)

                if item.IsHyperText():
                    dc.SetFont(self._owner.GetHyperTextFont())
                    if item.GetVisited():
                        dc.SetTextForeground(self._owner.GetHyperTextVisitedColour())
                    else:
                        dc.SetTextForeground(self._owner.GetHyperTextNewColour())
                else:
                    if font:
                        dc.SetFont(item.GetFont())

                itemRect = wx.Rect(itemRect.x+MARGIN_BETWEEN_TEXT_AND_ICON, itemRect.y, itemRect.width-8, itemRect.height)                    
                self.DrawTextFormatted(dc, item.GetText(), line, col, itemRect, overflow)

                if coloured:
                    dc.SetTextForeground(oldTF)

                if font:
                    dc.SetFont(oldFT)

            dc.DestroyClippingRegion()

            if wnd:
                if not wnd.IsShown():
                    wnd.Show()
                    
                if item._expandWin:
                    wRect = wx.Rect(*itemRect)
                    wRect.x += xa + 2
                    wRect.width = width - 8
                    wRect.y = ya + 2
                    wRect.height -= 4
                    if wnd.GetRect() != wRect: 
                        wnd.SetRect(wRect)
                else:
                    if wnd.GetPosition() != (wndx, ya):
                        wnd.SetPosition((wndx, ya))

        if self._owner.HasAGWFlag(ULC_HOT_TRACKING):
            if line == self._owner._newHotCurrent and not drawn:
                r = wx.Rect(*paintRect)
                r.y += 1
                r.height -= 1
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                dc.SetPen(wx.Pen(wx.NamedColour("orange")))
                dc.DrawRoundedRectangleRect(r, 3)
                dc.SetPen(oldPN)

        if borderOnly and drawn:
            dc.SetPen(wx.Pen(wx.Colour(0, 191, 255), 2))
            dc.SetBrush(wx.TRANSPARENT_BRUSH)
            rect = wx.Rect(*paintRect)
            rect.y += 1
            rect.height -= 1
            dc.DrawRoundedRectangleRect(rect, 3)
            dc.SetPen(oldPN)
            

    def DrawTextFormatted(self, dc, text, row, col, itemRect, overflow):
        """
        Draws the item text, correctly formatted.

        :param `dc`: an instance of :class:`DC`;
        :param `text`: the item text;
        :param `row`: the line number to which this item belongs to;
        :param `col`: the column number to which this item belongs to;
        :param `itemRect`: the item client rectangle;
        :param `overflow`: ``True`` if the item should overflow into neighboring columns,
         ``False`` otherwise.
        """
        # determine if the string can fit inside the current width
        w, h, dummy = dc.GetMultiLineTextExtent(text)
        width = itemRect.width

        shortItems = self._owner._shortItems
        tuples = (row, col)

        # it can, draw it using the items alignment
        item = self._owner.GetColumn(col)
        align = item.GetAlign()

        if align == ULC_FORMAT_RIGHT:
            textAlign = wx.ALIGN_RIGHT
        elif align == ULC_FORMAT_CENTER:
            textAlign = wx.ALIGN_CENTER
        else:
            textAlign = wx.ALIGN_LEFT

        if w <= width:
            
            if tuples in shortItems:
                shortItems.remove(tuples)

            dc.DrawLabel(text, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)
            
        else: # otherwise, truncate and add an ellipsis if possible

            if tuples not in shortItems:
                shortItems.append(tuples)
                
            # determine the base width
            ellipsis = "..."
            base_w, h = dc.GetTextExtent(ellipsis)

            # continue until we have enough space or only one character left

            newText = text.split("\n")
            theText = ""

            for text in newText:
            
                lenText = len(text)
                drawntext = text
                w, dummy = dc.GetTextExtent(text)

                while lenText > 1:

                    if w + base_w <= width:
                        break

                    w_c, h_c = dc.GetTextExtent(drawntext[-1])
                    drawntext = drawntext[0:-1]
                    lenText -= 1
                    w -= w_c
                
                # if still not enough space, remove ellipsis characters
                while len(ellipsis) > 0 and w + base_w > width:
                    ellipsis = ellipsis[0:-1]
                    base_w, h = dc.GetTextExtent(ellipsis)

                theText += drawntext + ellipsis + "\n"

            theText = theText.rstrip()
            # now draw the text                
            dc.DrawLabel(theText, itemRect, textAlign|wx.ALIGN_CENTER_VERTICAL)


    def DrawVerticalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from top to bottom.

        :param `dc`: an instance of :class:`DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients
        if hasfocus:
            col2 = self._owner._secondcolour
            col1 = self._owner._firstcolour
        else:
            col2 = self._owner._highlightUnfocusedBrush.GetColour()
            col1 = self._owner._highlightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.height)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        
        for y in xrange(rect.y, rect.y + rect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)                
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(rect.x, y, rect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep
        
        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)


    def DrawHorizontalGradient(self, dc, rect, hasfocus):
        """
        Gradient fill from colour 1 to colour 2 from left to right.

        :param `dc`: an instance of :class:`DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
         otherwise.
        """

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()
        dc.SetPen(wx.TRANSPARENT_PEN)

        # calculate gradient coefficients

        if hasfocus:
            col2 = self._owner._secondcolour
            col1 = self._owner._firstcolour
        else:
            col2 = self._owner._highlightUnfocusedBrush.GetColour()
            col1 = self._owner._highlightUnfocusedBrush2.GetColour()

        r1, g1, b1 = int(col1.Red()), int(col1.Green()), int(col1.Blue())
        r2, g2, b2 = int(col2.Red()), int(col2.Green()), int(col2.Blue())

        flrect = float(rect.width)

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0

        for x in xrange(rect.x, rect.x + rect.width):
            currCol = (int(r1 + rf), int(g1 + gf), int(b1 + bf))
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(x, rect.y, 1, rect.height)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep

        dc.SetPen(oldpen)
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.DrawRectangleRect(rect)
        dc.SetBrush(oldbrush)
        

    def DrawVistaRectangle(self, dc, rect, hasfocus):
        """
        Draws the selected item(s) with the Windows Vista style.

        :param `dc`: an instance of :class:`DC`;
        :param `rect`: the rectangle to be filled with the gradient shading;
        :param `hasfocus`: ``True`` if the main :class:`UltimateListCtrl` has focus, ``False``
         otherwise.
        """

        if hasfocus:
            
            outer = _rgbSelectOuter
            inner = _rgbSelectInner
            top = _rgbSelectTop
            bottom = _rgbSelectBottom

        else:
            
            outer = _rgbNoFocusOuter
            inner = _rgbNoFocusInner
            top = _rgbNoFocusTop
            bottom = _rgbNoFocusBottom

        oldpen = dc.GetPen()
        oldbrush = dc.GetBrush()

        bdrRect = wx.Rect(*rect.Get())
        filRect = wx.Rect(*rect.Get())
        filRect.Deflate(1,1)
        
        r1, g1, b1 = int(top.Red()), int(top.Green()), int(top.Blue())
        r2, g2, b2 = int(bottom.Red()), int(bottom.Green()), int(bottom.Blue())

        flrect = float(filRect.height)
        if flrect < 1:
            flrect = self._owner._lineHeight

        rstep = float((r2 - r1)) / flrect
        gstep = float((g2 - g1)) / flrect
        bstep = float((b2 - b1)) / flrect

        rf, gf, bf = 0, 0, 0
        dc.SetPen(wx.TRANSPARENT_PEN)
        
        for y in xrange(filRect.y, filRect.y + filRect.height):
            currCol = (r1 + rf, g1 + gf, b1 + bf)
            dc.SetBrush(wx.Brush(currCol, wx.SOLID))
            dc.DrawRectangle(filRect.x, y, filRect.width, 1)
            rf = rf + rstep
            gf = gf + gstep
            bf = bf + bstep
        
        dc.SetBrush(wx.TRANSPARENT_BRUSH)
        dc.SetPen(wx.Pen(outer))
        dc.DrawRoundedRectangleRect(bdrRect, 3)
        bdrRect.Deflate(1, 1)
        dc.SetPen(wx.Pen(inner))
        dc.DrawRoundedRectangleRect(bdrRect, 2)

        dc.SetPen(oldpen)
        dc.SetBrush(oldbrush)

        
    def Highlight(self, on):
        """
        Sets the current line as highlighted or not highlighted.

        :param `on`: ``True`` to set the current line as highlighted, ``False``
         otherwise.
        """

        if on == self._highlighted:
            return False

        self._highlighted = on

        return True


    def ReverseHighlight(self):
        """
        Reverses the line highlighting, switching it off if it was on and vice-versa.
        """

        self.Highlight(not self.IsHighlighted())



#-----------------------------------------------------------------------------
#  UltimateListHeaderWindow (internal)
#-----------------------------------------------------------------------------

class UltimateListHeaderWindow(wx.PyControl):
    """
    This class holds the header window for :class:`UltimateListCtrl`.
    """

    def __init__(self, win, id, owner, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, validator=wx.DefaultValidator,
                 name="UltimateListCtrlcolumntitles", isFooter=False):
        """
        Default class constructor.
        
        :param `parent`: parent window. Must not be ``None``;
        :param `id`: window identifier. A value of -1 indicates a default value;
        :param `owner`: an instance of :class:`UltimateListCtrl`;
        :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;
        :param `isFooter`: ``True`` if the :class:`UltimateListHeaderWindow` is in a footer
         position, ``False`` otherwise.
        """
        
        wx.PyControl.__init__(self, win, id, pos, size, style|wx.NO_BORDER, validator, name)

        self._isFooter = isFooter
        self._owner = owner
        self._currentCursor = wx.NullCursor
        self._resizeCursor = wx.StockCursor(wx.CURSOR_SIZEWE)
        self._isDragging = False
        self._headerHeight = None
        self._footerHeight = None
       
        # Custom renderer for every column
        self._headerCustomRenderer = None
       
        # column being resized or -1
        self._column = -1

        # divider line position in logical (unscrolled) coords
        self._currentX = 0

        # minimal position beyond which the divider line can't be dragged in
        # logical coords
        self._minX = 0

        # needs refresh
        self._dirty = False
        self._hasFont = False
        self._sendSetColumnWidth = False
        self._colToSend = -1
        self._widthToSend = 0
        self._leftDown = False
        self._enter = False
        self._currentColumn = -1

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnterWindow)
        self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeaveWindow)

        if _USE_VISATTR:

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

        else:

            self.SetOwnForegroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT))
            self.SetOwnBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE))

            if not self._hasFont:
                self.SetOwnFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT))


    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 methods `DrawHeaderButton`
          and `GetForegroundColor`. 
        """

        if not self._owner.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")
        
        self._headerCustomRenderer = renderer


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

        if not self._isFooter:
            if self._headerHeight is not None:
                self.GetParent()._headerHeight = self._headerHeight
                return wx.Size(200, self._headerHeight)
        else:
            if self._footerHeight is not None:
                self.GetParent()._footerHeight = self._footerHeight
                return wx.Size(200, self._footerHeight)
        
        w, h, d, dummy = self.GetFullTextExtent("Hg")
        maxH = self.GetTextHeight()
        nativeH = wx.RendererNative.Get().GetHeaderButtonHeight(self.GetParent())

        if not self._isFooter:
            maxH = max(max(h, maxH), nativeH)
            maxH += d
            self.GetParent()._headerHeight = maxH
        else:
            maxH = max(h, nativeH)
            maxH += d
            self.GetParent()._footerHeight = maxH
            
        return wx.Size(200, maxH)


    def GetWindowHeight(self):
        """ Returns the :class:`UltimateListHeaderWindow` height, in pixels. """

        return self.DoGetBestSize()
    

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

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

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

        return self._owner.IsColumnShown(column)

    
    # 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 GetTextHeight(self):
        """ Returns the column text height, in pixels. """

        maxH = 0
        numColumns = self._owner.GetColumnCount()
        dc = wx.ClientDC(self)
        for i in xrange(numColumns):
            
            if not self.IsColumnShown(i):
                continue

            item = self._owner.GetColumn(i)
            if item.GetFont().IsOk():
                dc.SetFont(item.GetFont())
            else:
                dc.SetFont(self.GetFont())
                        
            wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(item.GetText())
            maxH = max(maxH, hLabel)

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

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

        dc = wx.BufferedPaintDC(self)
        # width and height of the entire header window
        w, h = self.GetClientSize()
        w, dummy = self._owner.CalcUnscrolledPosition(w, 0)
        dc.SetBrush(wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.DrawRectangle(0, -1, w, h+2)
        
        self.AdjustDC(dc)

        dc.SetBackgroundMode(wx.TRANSPARENT)
        dc.SetTextForeground(self.GetForegroundColour())

        x = HEADER_OFFSET_X

        numColumns = self._owner.GetColumnCount()
        item = UltimateListItem()
        renderer = wx.RendererNative.Get()
        enabled = self.GetParent().IsEnabled()
        virtual = self._owner.IsVirtual()
        isFooter = self._isFooter

        for i in xrange(numColumns):
            
            # Reset anything in the dc that a custom renderer might have changed
            dc.SetTextForeground(self.GetForegroundColour())

            if x >= w:
                break

            if not self.IsColumnShown(i):
                continue # do next column if not shown
            
            item = self._owner.GetColumn(i)
            wCol = item._width

            cw = wCol
            ch = h

            flags = 0
            if not enabled:
                flags |= wx.CONTROL_DISABLED

            # NB: The code below is not really Mac-specific, but since we are close
            # to 2.8 release and I don't have time to test on other platforms, I
            # defined this only for wxMac. If this behavior is desired on
            # other platforms, please go ahead and revise or remove the #ifdef.

            if "__WXMAC__" in wx.PlatformInfo:
                if not virtual and item._mask & ULC_MASK_STATE and item._state & ULC_STATE_SELECTED:
                    flags |= wx.CONTROL_SELECTED
            
            if i == 0:
               flags |= wx.CONTROL_SPECIAL # mark as first column

            if i == self._currentColumn:
                if self._leftDown:
                    flags |= wx.CONTROL_PRESSED
                else:
                    if self._enter:
                        flags |= wx.CONTROL_CURRENT
           
            # the width of the rect to draw: make it smaller to fit entirely
            # inside the column rect
            header_rect = wx.Rect(x, HEADER_OFFSET_Y-1, cw, ch)

            if self._headerCustomRenderer != None:
               self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, flags)
              
               # The custom renderer will specify the color to draw the header text and buttons
               dc.SetTextForeground(self._headerCustomRenderer.GetForegroundColour())
                
            elif item._mask & ULC_MASK_RENDERER: 
               item.GetCustomRenderer().DrawHeaderButton(dc, header_rect, flags)
              
               # The custom renderer will specify the color to draw the header text and buttons
               dc.SetTextForeground(item.GetCustomRenderer().GetForegroundColour())
            else:
                renderer.DrawHeaderButton(self, dc, header_rect, flags)


            # see if we have enough space for the column label
            if isFooter:
                if item.GetFooterFont().IsOk():
                    dc.SetFont(item.GetFooterFont())
                else:
                    dc.SetFont(self.GetFont())
            else:
                if item.GetFont().IsOk():
                    dc.SetFont(item.GetFont())
                else:
                    dc.SetFont(self.GetFont())

            wcheck = hcheck = 0
            kind = (isFooter and [item.GetFooterKind()] or [item.GetKind()])[0]
            checked = (isFooter and [item.IsFooterChecked()] or [item.IsChecked()])[0]
            
            if kind in [1, 2]:
                # We got a checkbox-type item
                ix, iy = self._owner.GetCheckboxImageSize()
                # We draw it on the left, always
                self._owner.DrawCheckbox(dc, x + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, kind, checked, enabled)
                wcheck += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
                cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            # for this we need the width of the text
            text = (isFooter and [item.GetFooterText()] or [item.GetText()])[0]
            wLabel, hLabel, dummy = dc.GetMultiLineTextExtent(text)
            wLabel += 2*EXTRA_WIDTH

            # and the width of the icon, if any
            image = (isFooter and [item._footerImage] or [item._image])[0]

            if image:
                imageList = self._owner._small_image_list
                if imageList:
                    for img in image:
                        if img >= 0:
                            ix, iy = imageList.GetSize(img)
                            wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            else:

                imageList = None

            # ignore alignment if there is not enough space anyhow
            align = (isFooter and [item.GetFooterAlign()] or [item.GetAlign()])[0]                                                          
            align = (wLabel < cw and [align] or [ULC_FORMAT_LEFT])[0]

            if align == ULC_FORMAT_LEFT:
                xAligned = x + wcheck

            elif align == ULC_FORMAT_RIGHT:
                xAligned = x + cw - wLabel - HEADER_OFFSET_X

            elif align == ULC_FORMAT_CENTER:
                xAligned = x + wcheck + (cw - wLabel)/2

            # if we have an image, draw it on the right of the label
            if imageList:
                for indx, img in enumerate(image):
                    if img >= 0:
                        imageList.Draw(img, dc,
                                       xAligned + wLabel - (ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE)*(indx+1),
                                       HEADER_OFFSET_Y + (h - 4 - iy)/2,
                                       wx.IMAGELIST_DRAW_TRANSPARENT)

                        cw -= ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

            # draw the text clipping it so that it doesn't overwrite the column
            # boundary
            dc.SetClippingRegion(x, HEADER_OFFSET_Y, cw, h - 4)
            self.DrawTextFormatted(dc, text, wx.Rect(xAligned+EXTRA_WIDTH, HEADER_OFFSET_Y, cw-EXTRA_WIDTH, h-4))
            
            x += wCol
            dc.DestroyClippingRegion()

        # Fill in what's missing to the right of the columns, otherwise we will
        # leave an unpainted area when columns are removed (and it looks better)
        if x < w:
            header_rect = wx.Rect(x, HEADER_OFFSET_Y, w - x, h)
            if self._headerCustomRenderer != None:
                # Why does the custom renderer need this adjustment??
                header_rect.x = header_rect.x - 1
                header_rect.y = header_rect.y - 1
                self._headerCustomRenderer.DrawHeaderButton(dc, header_rect, wx.CONTROL_DIRTY)
            else:
                renderer.DrawHeaderButton(self, dc, header_rect, wx.CONTROL_DIRTY) # mark as last column


    def DrawTextFormatted(self, dc, text, rect):
        """
        Draws the item text, correctly formatted.

        :param `dc`: an instance of :class:`DC`;
        :param `text`: the item text;
        :param `rect`: the item client rectangle.
        """

        # determine if the string can fit inside the current width
        w, h, dummy = dc.GetMultiLineTextExtent(text)
        width = rect.width

        if w <= width:
            
            dc.DrawLabel(text, rect, wx.ALIGN_CENTER_VERTICAL)

        else:
            
            # determine the base width
            ellipsis = "..."
            base_w, h = dc.GetTextExtent(ellipsis)

            # continue until we have enough space or only one character left

            newText = text.split("\n")
            theText = ""

            for text in newText:
            
                lenText = len(text)
                drawntext = text
                w, dummy = dc.GetTextExtent(text)

                while lenText > 1:

                    if w + base_w <= width:
                        break

                    w_c, h_c = dc.GetTextExtent(drawntext[-1])
                    drawntext = drawntext[0:-1]
                    lenText -= 1
                    w -= w_c
                
                # if still not enough space, remove ellipsis characters
                while len(ellipsis) > 0 and w + base_w > width:
                    ellipsis = ellipsis[0:-1]
                    base_w, h = dc.GetTextExtent(ellipsis)

                theText += drawntext + ellipsis + "\n"

            theText = theText.rstrip()
            dc.DrawLabel(theText, rect, wx.ALIGN_CENTER_VERTICAL)
    

    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call :meth:`Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        wx.PyControl.OnInternalIdle(self)

        if self._isFooter:
            return
        
        if self._sendSetColumnWidth:
            self._owner.SetColumnWidth(self._colToSend, self._widthToSend)
            self._sendSetColumnWidth = False

    
    def DrawCurrent(self):
        """ Force the redrawing of the column window. """

        self._sendSetColumnWidth = True
        self._colToSend = self._column
        self._widthToSend = self._currentX - self._minX


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

        :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()

        columnX, columnY = x, y        

        if self._isDragging:

            self.SendListEvent(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.ReleaseMouse()
                self._isDragging = False
                self._dirty = True
                self._owner.SetColumnWidth(self._column, self._currentX - self._minX)
                self.SendListEvent(wxEVT_COMMAND_LIST_COL_END_DRAG, event.GetPosition())

            else:

                if x > self._minX + 7:
                    self._currentX = x
                else:
                    self._currentX = self._minX + 7

                # 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 occurred
            countCol = self._owner.GetColumnCount()
            broken = False
            tipCol = -1

            for col in xrange(countCol):

                if not self.IsColumnShown(col):
                    continue
                
                xpos += self._owner.GetColumnWidth(col)
                self._column = col

                if abs(x-xpos) < 3 and y < 22:
                    # near the column border
                    hit_border = True
                    broken = True
                    tipCol = col
                    break

                if x < xpos:
                    # inside the column
                    broken = True
                    tipCol = col
                    break

                self._minX = xpos

            if not broken:
                self._column = -1

            if tipCol >= 0:
                # First check to see if we have a tooltip to display    
                colItem = self._owner.GetColumn(col)
                if colItem.GetToolTip() != "":
                    self.SetToolTipString(colItem.GetToolTip())
                else:
                    self.SetToolTipString("")
                
            if event.LeftUp():
                self._leftDown = False
                self.Refresh()
                
            if event.LeftDown() or event.RightUp():

                if hit_border and event.LeftDown():

                    if not self._isFooter:

                        if self.SendListEvent(wxEVT_COMMAND_LIST_COL_BEGIN_DRAG,
                                              event.GetPosition()):

                            self._isDragging = True
                            self._currentX = x
                            self.CaptureMouse()
                            self.DrawCurrent()

                    #else: column resizing was vetoed by the user code

                else: # click on a column

                     # record the selected state of the columns
                    if event.LeftDown():
                        
                        for i in xrange(self._owner.GetColumnCount()):

                            if not self.IsColumnShown(col):
                                continue
                            
                            colItem = self._owner.GetColumn(i)
                            state = colItem.GetState()

                            if i == self._column:
                                colItem.SetState(state | ULC_STATE_SELECTED)
                                theX = x
                            else:
                                colItem.SetState(state & ~ULC_STATE_SELECTED)

                            self._leftDown = True
                            self._owner.SetColumn(i, colItem)
                            x += self._owner.GetColumnWidth(i)

                        if self.HandleColumnCheck(self._column, event.GetPosition()):
                            return

                    if not self._isFooter:
                        self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_COL_CLICK] or \
                                            [wxEVT_COMMAND_LIST_COL_RIGHT_CLICK])[0], event.GetPosition())
                    else:
                        self.SendListEvent((event.LeftDown() and [wxEVT_COMMAND_LIST_FOOTER_CLICK] or \
                                            [wxEVT_COMMAND_LIST_FOOTER_RIGHT_CLICK])[0], event.GetPosition())
                        
                    self._leftDown = True
                    self._currentColumn = self._column

            elif event.Moving():

                setCursor = False

                if not self._isFooter:
                    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)
                else:
                    column = self.HitTestColumn(columnX, columnY)
                    self._enter = True
                    self._currentColumn = column

                    if _VERSION_STRING < "2.9":
                        leftDown = wx.GetMouseState().LeftDown()
                    else:
                        leftDown = wx.GetMouseState().LeftIsDown()

                    self._leftDown = leftDown

                    self.Refresh()                                            

            elif event.ButtonDClick():                

                self.HandleColumnCheck(self._column, event.GetPosition())
                

    def HandleColumnCheck(self, column, pos):
        """
        Handles the case in which a column contains a checkbox-like item.

        :param `column`: the column index;
        :param `pos`: the mouse position.
        """
        
        if column < 0 or column >= self._owner.GetColumnCount():
            return False
        
        colItem = self._owner.GetColumn(column)
        # Let's see if it is a checkbox-type item

        kind = (self._isFooter and [colItem.GetFooterKind()] or [colItem.GetKind()])[0]
        if kind not in [1, 2]:
            return False

        x = HEADER_OFFSET_X
        
        for i in xrange(self._owner.GetColumnCount()):

            if not self.IsColumnShown(i):
                continue

            if i == self._column:
                theX = x
                break
            x += self._owner.GetColumnWidth(i)

        parent = self.GetParent()
        
        w, h = self.GetClientSize()
        ix, iy = self._owner.GetCheckboxImageSize()
        rect = wx.Rect(theX + HEADER_OFFSET_X, HEADER_OFFSET_Y + (h - 4 - iy)/2, ix, iy)
        
        if rect.Contains(pos):
            # User clicked on the checkbox
            evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKING] or [wxEVT_COMMAND_LIST_COL_CHECKING])[0]
            if self.SendListEvent(evt, pos):
                # No veto for the item checking
                if self._isFooter:
                    isChecked = colItem.IsFooterChecked()
                    colItem.CheckFooter(not isChecked)                    
                else:
                    isChecked = colItem.IsChecked()
                    colItem.Check(not isChecked)
                    
                self._owner.SetColumn(column, colItem)
                evt = (self._isFooter and [wxEVT_COMMAND_LIST_FOOTER_CHECKED] or [wxEVT_COMMAND_LIST_COL_CHECKED])[0]
                self.SendListEvent(evt, pos)
                self.RefreshRect(rect)

                if self._isFooter:
                    return True
                
                if parent.HasAGWFlag(ULC_AUTO_CHECK_CHILD):
                    self._owner.AutoCheckChild(isChecked, self._column)
                elif parent.HasAGWFlag(ULC_AUTO_TOGGLE_CHILD):
                    self._owner.AutoToggleChild(self._column)

                return True

        return False


    def OnEnterWindow(self, event):
        """
        Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`UltimateListHeaderWindow`.

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

        x, y = self._owner.CalcUnscrolledPosition(*self.ScreenToClient(wx.GetMousePosition()))
        column = self.HitTestColumn(x, y)

        if _VERSION_STRING < "2.9":
            leftDown = wx.GetMouseState().LeftDown()
        else:
            leftDown = wx.GetMouseState().LeftIsDown()

        self._leftDown = leftDown
        self._enter = column >= 0 and column < self._owner.GetColumnCount()
        self._currentColumn = column
        self.Refresh()


    def OnLeaveWindow(self, event):
        """
        Handles the ``wx.EVT_LEAVE_WINDOW`` event for :class:`UltimateListHeaderWindow`.

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

        self._enter = False
        self._leftDown = False
        
        self._currentColumn = -1
        self.Refresh()


    def HitTestColumn(self, x, y):
        """
        HitTest method for column headers.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :return: The column index if any column client rectangle contains the mouse
         position, ``wx.NOT_FOUND`` otherwise.
        """
        
        xOld = 0
        
        for i in xrange(self._owner.GetColumnCount()):
            if not self.IsColumnShown(i):
                continue
                            
            xOld += self._owner.GetColumnWidth(i)
            if x <= xOld:
                return i

        return -1            
                
        
    def OnSetFocus(self, event):
        """
        Handles the ``wx.EVT_SET_FOCUS`` event for :class:`UltimateListHeaderWindow`.

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

        self._owner.SetFocusIgnoringChildren()
        self._owner.Update()


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

        :param `eventType`: the event type;
        :param `pos`: an instance of :class:`Point`.
        """

        parent = self.GetParent()
        le = UltimateListEvent(eventType, 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
        return (not parent.GetEventHandler().ProcessEvent(le) or le.IsAllowed())


    def GetOwner(self):
        """ Returns the header window owner, an instance of :class:`UltimateListCtrl`. """

        return self._owner



#-----------------------------------------------------------------------------
#  UltimateListRenameTimer (internal)
#-----------------------------------------------------------------------------

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

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

        :param `owner`: an instance of :class:`UltimateListCtrl`.
        """
        
        wx.Timer.__init__(self)
        self._owner = owner        


    def Notify(self):
        """ The timer has expired. """

        self._owner.OnRenameTimer()
        

#-----------------------------------------------------------------------------
#  UltimateListTextCtrl (internal)
#-----------------------------------------------------------------------------

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

    This is a subclass of `ExpandoTextCtrl` as :class:`UltimateListCtrl` supports multiline
    text items.

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

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

        :param `owner`: the control parent (an instance of :class:`UltimateListCtrl` );
        :param `itemEdit`: an instance of :class:`UltimateListItem`.
        """

        self._startValue = owner.GetItemText(itemEdit)
        self._currentValue = self._startValue
        
        self._itemEdited = itemEdit

        self._owner = owner
        self._finished = False
        self._aboutToFinish = False

        rectLabel = owner.GetLineLabelRect(itemEdit)
        rectLabel.x, rectLabel.y = self._owner.CalcScrolledPosition(rectLabel.x, rectLabel.y)
        xSize, ySize = rectLabel.width + 10, rectLabel.height

        expandoStyle = wx.WANTS_CHARS
        if wx.Platform in ["__WXGTK__", "__WXMAC__"]:
            expandoStyle |= wx.SIMPLE_BORDER
        else:
            expandoStyle |= wx.SUNKEN_BORDER
            
        ExpandoTextCtrl.__init__(self, owner, -1, self._startValue, wx.Point(rectLabel.x, rectLabel.y),
                                 wx.Size(xSize, ySize), expandoStyle)

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


    def AcceptChanges(self):
        """ Accepts/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.OnRenameCancelled(self._itemEdited)
            return True

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

        # accepted, do rename the item
        self._owner.SetItemText(self._itemEdited, value)
        
        if value.count("\n") != self._startValue.count("\n"):
            self._owner.ResetLineDimensions()
            self._owner.Refresh()
        
        return True


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

        try:
            if not self._finished:
                self._finished = True
                self._owner.SetFocusIgnoringChildren()
                self._owner.ResetTextControl()
        except wx.PyDeadObjectError:
            return
        

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

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

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

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

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

        else:
            event.Skip()
    

    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for :class:`UltimateListTextCtrl`.

        :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()

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

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

        event.Skip()


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

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


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

        self._owner.OnRenameCancelled(self._itemEdited)
        self.Finish()


#-----------------------------------------------------------------------------
#  UltimateListMainWindow (internal)
#-----------------------------------------------------------------------------

class UltimateListMainWindow(wx.PyScrolledWindow):
    """
    This is the main widget implementation of :class:`UltimateListCtrl`.
    """
    
    def __init__(self, parent, id, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0, agwStyle=0, name="listctrlmainwindow"):
        """
        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` window style;
        :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================

        :param `name`: the window name.
        """
        
        wx.PyScrolledWindow.__init__(self, parent, id, pos, size, style|wx.HSCROLL|wx.VSCROLL, name)

        # the list of column objects
        self._columns = []

        # the array of all line objects for a non virtual list control (for the
        # virtual list control we only ever use self._lines[0])
        self._lines = []

        # currently focused item or -1
        self._current = -1

        # the number of lines per page
        self._linesPerPage = 0
        
        # Automatically resized column - this column expands to fill the width of the window
        self._resizeColumn = -1
        self._resizeColMinWidth = None
        
        # this flag is set when something which should result in the window
        # redrawing happens (i.e. an item was added or deleted, or its appearance
        # changed) and OnPaint() doesn't redraw the window while it is set which
        # allows to minimize the number of repaintings when a lot of items are
        # being added. The real repainting occurs only after the next OnIdle()
        # call
        self._dirty = False
        self._parent = parent
        self.Init()

        self._highlightBrush = wx.Brush(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT), wx.SOLID)
        
        btnshadow = wx.SystemSettings_GetColour(wx.SYS_COLOUR_BTNSHADOW)
        self._highlightUnfocusedBrush = wx.Brush(btnshadow, wx.SOLID)
        r, g, b = btnshadow.Red(), btnshadow.Green(), btnshadow.Blue()
        backcolour = (max((r >> 1) - 20, 0),
                      max((g >> 1) - 20, 0),
                      max((b >> 1) - 20, 0))
        backcolour = wx.Colour(backcolour[0], backcolour[1], backcolour[2])
        self._highlightUnfocusedBrush2 = wx.Brush(backcolour)
        
        self.SetScrollbars(0, 0, 0, 0, 0, 0)

        attr = wx.ListCtrl.GetClassDefaultAttributes()
        self.SetOwnForegroundColour(attr.colFg)
        self.SetOwnBackgroundColour(attr.colBg)        
        self.SetOwnFont(attr.font)

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
        self.Bind(wx.EVT_MOUSE_EVENTS, self.OnMouse)
        self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus)
        self.Bind(wx.EVT_CHAR, self.OnChar)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)        
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
        self.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
        self.Bind(wx.EVT_TIMER, self.OnHoverTimer, self._hoverTimer)
        

    def Init(self):
        """ Initializes the :class:`UltimateListMainWindow` widget. """
        
        self._dirty = True
        self._countVirt = 0
        self._lineFrom = None
        self._lineTo = - 1
        self._linesPerPage = 0

        self._headerWidth = 0
        self._lineHeight = 0
        self._userLineHeight = None
        
        self._small_image_list = None
        self._normal_image_list = None

        self._small_spacing = 30
        self._normal_spacing = 40

        self._hasFocus = False
        self._dragCount = 0
        self._isCreated = False

        self._lastOnSame = False
        self._renameTimer = UltimateListRenameTimer(self)
        self._textctrl = None

        self._current = -1
        self._lineLastClicked = -1
        self._lineSelectSingleOnUp = -1
        self._lineBeforeLastClicked = -1

        self._dragStart = wx.Point(-1, -1)
        self._aColWidths = []

        self._selStore = SelectionStore()
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)

        # Background image settings
        self._backgroundImage = None
        self._imageStretchStyle = _StyleTile

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

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

        # Vista Selection Styles
        self._vistaselection = False

        # Selected/highlighted item text color. Leave unset for ForegroundColor to always apply, even for selected item
        self._highlightedtextcolour = None

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

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

        self._itemWithWindow = []
        self._hasWindows = False
        self._shortItems = []

        self._isDragging = False
        self._cursor = wx.STANDARD_CURSOR

        image = GetdragcursorImage()

        # since this image didn't come from a .cur file, tell it where the hotspot is
        image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 1)
        image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1)

        # make the image into a cursor
        self._dragCursor = wx.CursorFromImage(image)
        self._dragItem = None
        self._dropTarget = None

        self._oldHotCurrent = None
        self._newHotCurrent = None

        self._waterMark = None

        self._hoverTimer = wx.Timer(self, wx.ID_ANY)
        self._hoverItem = -1


    def GetMainWindowOfCompositeControl(self):
        """ Returns the :class:`UltimateListMainWindow` parent. """
        
        return self.GetParent()


    def DoGetBestSize(self):
        """
        Gets the size which best suits the window: for a control, it would be the
        minimal size which doesn't truncate the control, for a panel - the same size
        as it would have after a call to `Fit()`.
        """

        return wx.Size(100, 80)
    

    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if the window has the given `flag` bit set.

        :param `flag`: the bit to check.

        :see: :meth:`UltimateListCtrl.SetSingleStyle() <UltimateListCtrl.SetSingleStyle>` for a list of valid flags.
        """

        return self._parent.HasAGWFlag(flag)


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

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

        return self.GetColumn(column).IsShown()


    # return True if this is a virtual list control
    def IsVirtual(self):
        """ Returns ``True`` if the window has the ``ULC_VIRTUAL`` style set. """

        return self.HasAGWFlag(ULC_VIRTUAL)


    # return True if the control is in report mode
    def InReportView(self):
        """ Returns ``True`` if the window is in report mode. """

        return self.HasAGWFlag(ULC_REPORT)


    def InTileView(self):
        """
        Returns ``True`` if the window is in tile mode (partially implemented).

        .. todo:: Fully implement tile view for :class:`UltimateListCtrl`.        
        """

        return self.HasAGWFlag(ULC_TILE)        

    # return True if we are in single selection mode, False if multi sel
    def IsSingleSel(self):
        """ Returns ``True`` if we are in single selection mode, ``False`` if multi selection. """
        
        return self.HasAGWFlag(ULC_SINGLE_SEL)


    def HasFocus(self):
        """ Returns ``True`` if the window has focus. """
        
        return self._hasFocus

    
    # do we have a header window?
    def HasHeader(self):
        """ Returns ``True`` if the header window is shown. """

        if (self.InReportView() or self.InTileView()) and not self.HasAGWFlag(ULC_NO_HEADER):
            return True
        if self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
            return True

        return False


    # do we have a footer window?
    def HasFooter(self):
        """ Returns ``True`` if the footer window is shown. """

        if self.HasHeader() and self.HasAGWFlag(ULC_FOOTER):
            return True

        return False


    # toggle the line state and refresh it
    def ReverseHighlight(self, line):
        """
        Toggles the line state and refreshes it.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """
        
        self.HighlightLine(line, not self.IsHighlighted(line))
        self.RefreshLine(line)


    def SetUserLineHeight(self, height):
        """
        Sets a custom value for the :class:`UltimateListMainWindow` item height.

        :param `height`: the custom height for all the items, in pixels.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            self._userLineHeight = height
            return

        raise Exception("SetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")        
        

    def GetUserLineHeight(self):
        """
        Returns the custom value for the :class:`UltimateListMainWindow` item height, if previously set with
        :meth:`~UltimateListMainWindow.SetUserLineHeight`.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            return self._userLineHeight

        raise Exception("GetUserLineHeight can only be used with styles ULC_REPORT and ULC_USER_ROW_HEIGHT set.")        


    # get the size of the total line rect
    def GetLineSize(self, line):
        """
        Returns the size of the total line client rectangle.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """
        
        return self.GetLineRect(line).GetSize()


    # bring the current item into view
    def MoveToFocus(self):
        """ Brings tyhe current item into view. """

        self.MoveToItem(self._current)


    def GetColumnCount(self):
        """ Returns the total number of columns in the :class:`UltimateListCtrl`. """

        return len(self._columns)


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

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

        info = UltimateListItem()
        info._mask = ULC_MASK_TEXT
        info._itemId = item
        info = self.GetItem(info)

        return info._text


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `value`: the new item text.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_TEXT
        info._itemId = item
        info._text = value

        self.SetItem(info)


    def IsEmpty(self):
        """ Returns ``True`` if the window has no items in it. """

        return self.GetItemCount() == 0


    def ResetCurrent(self):
        """ Resets the current item to ``None``. """

        self.ChangeCurrent(-1)


    def HasCurrent(self):
        """
        Returns ``True`` if the current item has been set, either programmatically
        or by user intervention.
        """

        return self._current != -1


    # override base class virtual to reset self._lineHeight when the font changes
    def SetFont(self, font):
        """
        Overridden base class virtual to reset the line height when the font changes.

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

        :note: Overridden from :class:`PyScrolledWindow`.        
        """
        
        if not wx.PyScrolledWindow.SetFont(self, font):
            return False

        self._lineHeight = 0
        self.ResetLineDimensions()

        return True


    def ResetLineDimensions(self, force=False):
        """
        Resets the line dimensions, so that client rectangles and positions are
        recalculated.

        :param `force`: ``True`` to reset all line dimensions.
        """

        if (self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT) and not self.IsVirtual()) or force:
            for l in xrange(self.GetItemCount()):
                line = self.GetLine(l)
                line.ResetDimensions()
        
    # these are for UltimateListLineData usage only
    # get the backpointer to the list ctrl
    def GetListCtrl(self):
        """ Returns the parent widget, an instance of :class:`UltimateListCtrl`. """

        return self.GetParent()


    # get the brush to use for the item highlighting
    def GetHighlightBrush(self):
        """ Returns the brush to use for the item highlighting. """
        
        return (self._hasFocus and [self._highlightBrush] or [self._highlightUnfocusedBrush])[0]


    # get the line data for the given index
    def GetLine(self, n):
        """
        Returns the line data for the given index.

        :param `n`: the line index.
        """

        if self.IsVirtual():

            self.CacheLineData(n)
            n = 0

        return self._lines[n]


    # force us to recalculate the range of visible lines
    def ResetVisibleLinesRange(self, reset=False):
        """
        Forces us to recalculate the range of visible lines.

        :param `reset`: ``True`` to reset all line dimensions, which will then be
         recalculated.
        """

        self._lineFrom = -1
        if self.IsShownOnScreen() and reset:
            self.ResetLineDimensions()

           
    # Called on EVT_SIZE to resize the _resizeColumn to fill the width of the window
    def ResizeColumns(self):
        """
        If ``ULC_AUTOSIZE_FILL`` was passed to :meth:`UltimateListCtrl.SetColumnWidth() <UltimateListCtrl.SetColumnWidth>` then
        that column's width will be expanded to fill the window on a resize event.

        Called by :meth:`UltimateListCtrl.OnSize() <UltimateListCtrl.OnSize>` when the window is resized.
        """

        if not self: # Avoid PyDeadObjectErrors on Mac
            return
        
        if self._resizeColumn == -1:
            return
            
            
        numCols = self.GetColumnCount()
        if numCols == 0: return # Nothing to resize.
        
        resizeCol = self._resizeColumn

        if self._resizeColMinWidth == None:
            self._resizeColMinWidth = self.GetColumnWidth(resizeCol)

        # We're showing the vertical scrollbar -> allow for scrollbar width
        # NOTE: on GTK, the scrollbar is included in the client size, but on
        # Windows it is not included
        listWidth = self.GetClientSize().width
        if wx.Platform != '__WXMSW__':
            if self.GetItemCount() > self.GetCountPerPage():
                scrollWidth = wx.SystemSettings_GetMetric(wx.SYS_VSCROLL_X)
                listWidth = listWidth - scrollWidth

        totColWidth = 0 # Width of all columns except last one.
        for col in range(numCols):
            if col != (resizeCol) and self.IsColumnShown(col):
                totColWidth = totColWidth + self.GetColumnWidth(col)

        resizeColWidth = self.GetColumnWidth(resizeCol)

        if totColWidth + self._resizeColMinWidth > listWidth:
            # We haven't got the width to show the last column at its minimum
            # width -> set it to its minimum width and allow the horizontal
            # scrollbar to show.
            self.SetColumnWidth(resizeCol, self._resizeColMinWidth)
            return

        # Resize the last column to take up the remaining available space.
        self.SetColumnWidth(resizeCol, listWidth - totColWidth)


    # get the colour to be used for drawing the rules
    def GetRuleColour(self):
        """ Returns the colour to be used for drawing the horizontal and vertical rules. """

        return wx.SystemSettings.GetColour(wx.SYS_COLOUR_3DLIGHT)


    def SetReportView(self, inReportView):
        """
        Sets whether :class:`UltimateListCtrl` is in report view or not.

        :param `inReportView`: ``True`` to set :class:`UltimateListCtrl` in report view, ``False``
         otherwise.
        """

        for line in self._lines:
            line.SetReportView(inReportView)


    def CacheLineData(self, line):
        """
        Saves the current line attributes.

        :param `line`: an instance of :class:`UltimateListLineData`.

        :note: This method is used only if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL``
         style set.
        """

        listctrl = self.GetListCtrl()
        ld = self.GetDummyLine()

        countCol = self.GetColumnCount()
        for col in xrange(countCol):
            ld.SetText(col, listctrl.OnGetItemText(line, col))
            ld.SetToolTip(col, listctrl.OnGetItemToolTip(line, col))
            ld.SetColour(col, listctrl.OnGetItemTextColour(line, col))
            ld.SetImage(col, listctrl.OnGetItemColumnImage(line, col))
            kind = listctrl.OnGetItemColumnKind(line, col)
            ld.SetKind(col, kind)
            if kind > 0:
                ld.Check(col, listctrl.OnGetItemColumnCheck(line, col))

        ld.SetAttr(listctrl.OnGetItemAttr(line))


    def GetDummyLine(self):
        """
        Returns a dummy line.

        :note: This method is used only if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL``
         style set.
        """
        
        if self.IsEmpty():
            raise Exception("invalid line index")

        if not self.IsVirtual():
            raise Exception("GetDummyLine() shouldn't be called")

        # we need to recreate the dummy line if the number of columns in the
        # control changed as it would have the incorrect number of fields
        # otherwise
        if len(self._lines) > 0 and len(self._lines[0]._items) != self.GetColumnCount():
            self._lines = []

        if not self._lines:
            line = UltimateListLineData(self)
            self._lines.append(line)

        return self._lines[0]


# ----------------------------------------------------------------------------
# line geometry (report mode only)
# ----------------------------------------------------------------------------

    def GetLineHeight(self, item=None):
        """
        Returns the line height for a specific item.

        :param `item`: if not ``None``, an instance of :class:`UltimateListItem`.
        """

        # we cache the line height as calling GetTextExtent() is slow

        if self.HasAGWFlag(ULC_REPORT) and self.HasAGWFlag(ULC_USER_ROW_HEIGHT):
            if self._userLineHeight is not None:
                return self._userLineHeight
            
        if item is None or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            
            if not self._lineHeight:
                dc = wx.ClientDC(self)
                dc.SetFont(self.GetFont())

                dummy, y = dc.GetTextExtent("H")
                if self._small_image_list and self._small_image_list.GetImageCount():
                    iw, ih = self._small_image_list.GetSize(0)
                    y = max(y, ih)

                y += EXTRA_HEIGHT
                self._lineHeight = y + LINE_SPACING

            return self._lineHeight
                
        else:

            line = self.GetLine(item)
            LH = line.GetHeight()
            if LH != -1:
                return LH

            dc = wx.ClientDC(self)
            
            allTextY = 0
            
            for col, items in enumerate(line._items):

                if items.GetCustomRenderer():
                    allTextY = max(allTextY, items.GetCustomRenderer().GetLineHeight())
                    continue

                if items.HasFont():
                    dc.SetFont(items.GetFont())
                else:
                    dc.SetFont(self.GetFont())

                text_x, text_y, dummy = dc.GetMultiLineTextExtent(items.GetText())
                allTextY = max(text_y, allTextY)

                if items.GetWindow():
                    xSize, ySize = items.GetWindowSize()
                    allTextY = max(allTextY, ySize)

                if self._small_image_list and self._small_image_list.GetImageCount():
                    for img in items._image:
                        iw, ih = self._small_image_list.GetSize(img)
                        allTextY = max(allTextY, ih)

            allTextY += EXTRA_HEIGHT
            line.SetHeight(allTextY)

            return allTextY


    def GetLineY(self, line):
        """
        Returns the line `y` position.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if self.IsVirtual():
            return LINE_SPACING + line*self.GetLineHeight()
        
        lineItem = self.GetLine(line)
        lineY = lineItem.GetY()
        if lineY != -1:
            return lineY
        
        lineY = 0
        for l in xrange(line):
            lineY += self.GetLineHeight(l)

        lineItem.SetY(LINE_SPACING + lineY)
        return LINE_SPACING + lineY


    def GetLineRect(self, line):
        """
        Returns the line client rectangle.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectAll

        rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line), self.GetHeaderWidth(), self.GetLineHeight(line))
        return rect


    def GetLineLabelRect(self, line, col=0):
        """
        Returns the line client rectangle for the item text only.
        Note this is the full column width unless an image or 
        checkbox exists. It is not the width of the text itself

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectLabel

        image_x = 0
        image_width = 0
       
        for c in range(col):
            image_x += self.GetColumnWidth(c)
        
        item = self.GetLine(line)
        if item.HasImage(col):
            ix, iy = self.GetImageSize(item.GetImage(col))
            image_x     += ix
            image_width  = ix

        if item.GetKind(col) in [1, 2]:
            image_x     += self.GetCheckboxImageSize()[0]
            image_width += self.GetCheckboxImageSize()[0]
            
        rect = wx.Rect(image_x + HEADER_OFFSET_X, self.GetLineY(line), self.GetColumnWidth(col) - image_width, self.GetLineHeight(line))
        return rect
    

    def GetLineIconRect(self, line):
        """
        Returns the line client rectangle for the item image only.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectIcon

        ld = self.GetLine(line)

        image_x = HEADER_OFFSET_X
        if ld.GetKind() in [1, 2]:
            image_x += self.GetCheckboxImageSize()[0]
            
        rect = wx.Rect(image_x, self.GetLineY(line), *self.GetImageSize(ld.GetImage()))
        return rect


    def GetLineCheckboxRect(self, line):
        """
        Returns the line client rectangle for the item checkbox image only.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if not self.InReportView():
            return self.GetLine(line)._gi._rectCheck
        
        ld = self.GetLine(line)
        LH = self.GetLineHeight(line)
        wcheck, hcheck = self.GetCheckboxImageSize()
        rect = wx.Rect(HEADER_OFFSET_X, self.GetLineY(line) + LH/2 - hcheck/2, wcheck, hcheck)
        return rect
    

    def GetLineHighlightRect(self, line):
        """
        Returns the line client rectangle when the line is highlighted.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        return (self.InReportView() and [self.GetLineRect(line)] or [self.GetLine(line)._gi._rectHighlight])[0]


    def HitTestLine(self, line, x, y):
        """
        HitTest method for a :class:`UltimateListCtrl` line.

        :param `line`: an instance of :class:`UltimateListLineData`;
        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :return: a tuple of values, representing the item hit and a hit flag. The
         hit flag can be one of the following bits:

         =============================== ========= ================================
         HitTest Flag                    Hex Value Description
         =============================== ========= ================================
         ``ULC_HITTEST_ABOVE``                 0x1 Above the client area
         ``ULC_HITTEST_BELOW``                 0x2 Below the client area
         ``ULC_HITTEST_NOWHERE``               0x4 In the client area but below the last item
         ``ULC_HITTEST_ONITEM``              0x2a0 Anywhere on the item (text, icon, checkbox image)
         ``ULC_HITTEST_ONITEMICON``           0x20 On the bitmap associated with an item
         ``ULC_HITTEST_ONITEMLABEL``          0x80 On the label (string) associated with an item
         ``ULC_HITTEST_ONITEMRIGHT``         0x100 In the area to the right of an item
         ``ULC_HITTEST_ONITEMSTATEICON``     0x200 On the state icon for a list view item that is in a user-defined state
         ``ULC_HITTEST_TOLEFT``              0x400 To the left of the client area
         ``ULC_HITTEST_TORIGHT``             0x800 To the right of the client area
         ``ULC_HITTEST_ONITEMCHECK``        0x1000 On the item checkbox (if any)
         =============================== ========= ================================
        
        """

        ld = self.GetLine(line)

        if self.InReportView():# and not self.IsVirtual():

            lineY = self.GetLineY(line)
            xstart = HEADER_OFFSET_X
            
            for col, item in enumerate(ld._items):

                if not self.IsColumnShown(col):
                    continue
                
                width = self.GetColumnWidth(col)
                xOld = xstart
                xstart += width
                ix = 0

                #if (line, col) in self._shortItems:
                    #rect = wx.Rect(xOld, lineY, width, self.GetLineHeight(line))
                rect = self.GetLineLabelRect(line,col)
                if rect.Contains((x, y)):
                    newItem = self.GetParent().GetItem(line, col)
                    return newItem, ULC_HITTEST_ONITEMLABEL
               
                if item.GetKind() in [1, 2]:
                    # We got a checkbox-type item
                    ix, iy = self.GetCheckboxImageSize()
                    LH = self.GetLineHeight(line)
                    rect = wx.Rect(xOld, lineY + LH/2 - iy/2, ix, iy)
                    if rect.Contains((x, y)):
                        newItem = self.GetParent().GetItem(line, col)
                        return newItem, ULC_HITTEST_ONITEMCHECK
                    
                if item.IsHyperText():
                    start, end = self.GetItemTextSize(item)
                    rect = wx.Rect(xOld+start, lineY, end, self.GetLineHeight(line))
                    if rect.Contains((x, y)):
                        newItem = self.GetParent().GetItem(line, col)
                        return newItem, ULC_HITTEST_ONITEMLABEL
                    
                    xOld += ix
                
        if ld.HasImage() and self.GetLineIconRect(line).Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMICON
        
        # VS: Testing for "ld.HasText() || InReportView()" instead of
        #     "ld.HasText()" is needed to make empty lines in report view
        #     possible
        if ld.HasText() or self.InReportView():
            if self.InReportView():
                rect = self.GetLineRect(line)
            else:
                checkRect = self.GetLineCheckboxRect(line)
                if checkRect.Contains((x, y)):
                    return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMCHECK

                rect = self.GetLineLabelRect(line)
                
        if rect.Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEMLABEL

        rect = self.GetLineRect(line)
        if rect.Contains((x, y)):
            return self.GetParent().GetItem(line), ULC_HITTEST_ONITEM

        return None, 0


# ----------------------------------------------------------------------------
# highlight (selection) handling
# ----------------------------------------------------------------------------

    def IsHighlighted(self, line):
        """
        Returns ``True`` if the input line is highlighted.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if self.IsVirtual():

            return self._selStore.IsSelected(line)

        else: # !virtual

            ld = self.GetLine(line)
            return ld.IsHighlighted()


    def HighlightLines(self, lineFrom, lineTo, highlight=True):
        """
        Highlights a range of lines in :class:`UltimateListCtrl`.

        :param `lineFrom`: an integer representing the first line to highlight;
        :param `lineTo`: an integer representing the last line to highlight;
        :param `highlight`: ``True`` to highlight the lines, ``False`` otherwise.
        """

        if self.IsVirtual():
            linesChanged = self._selStore.SelectRange(lineFrom, lineTo, highlight)
            if not linesChanged:
                # many items changed state, refresh everything
                self.RefreshLines(lineFrom, lineTo)

            else: # only a few items changed state, refresh only them

                for n in xrange(len(linesChanged)):
                    self.RefreshLine(linesChanged[n])

        else: # iterate over all items in non report view

            for line in xrange(lineFrom, lineTo+1):
                if self.HighlightLine(line, highlight):
                    self.RefreshLine(line)


    def HighlightLine(self, line, highlight=True):
        """
        Highlights a line in :class:`UltimateListCtrl`.

        :param `line`: an instance of :class:`UltimateListLineData`;
        :param `highlight`: ``True`` to highlight the line, ``False`` otherwise.
        """

        changed = False

        if self.IsVirtual():

            changed = self._selStore.SelectItem(line, highlight)

        else: # !virtual

            ld = self.GetLine(line)
            changed = ld.Highlight(highlight)

        dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)

        if changed and not dontNotify:
            self.SendNotify(line, (highlight and [wxEVT_COMMAND_LIST_ITEM_SELECTED] or [wxEVT_COMMAND_LIST_ITEM_DESELECTED])[0])

        return changed


    def RefreshLine(self, line):
        """
        Redraws the input line.

        :param `line`: an instance of :class:`UltimateListLineData`.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()
            if line < visibleFrom or line > visibleTo:
                return

        rect = self.GetLineRect(line)
        rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)
        self.RefreshRect(rect)


    def RefreshLines(self, lineFrom, lineTo):
        """
        Redraws a range of lines in :class:`UltimateListCtrl`.

        :param `lineFrom`: an integer representing the first line to refresh;
        :param `lineTo`: an integer representing the last line to refresh.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()

            if lineFrom < visibleFrom:
                lineFrom = visibleFrom
            if lineTo > visibleTo:
                lineTo = visibleTo

            rect = wx.Rect()
            rect.x = 0
            rect.y = self.GetLineY(lineFrom)
            rect.width = self.GetClientSize().x
            rect.height = self.GetLineY(lineTo) - rect.y + self.GetLineHeight(lineTo)

            rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)
            self.RefreshRect(rect)

        else: # !report

            # TODO: this should be optimized...
            for line in xrange(lineFrom, lineTo+1):
                self.RefreshLine(line)


    def RefreshAfter(self, lineFrom):
        """
        Redraws all the lines after the input one.

        :param `lineFrom`: an integer representing the first line to refresh.
        """

        if self.InReportView():

            visibleFrom, visibleTo = self.GetVisibleLinesRange()

            if lineFrom < visibleFrom:
                lineFrom = visibleFrom
            elif lineFrom > visibleTo:
                return

            rect = wx.Rect()
            rect.x = 0
            rect.y = self.GetLineY(lineFrom)
            rect.x, rect.y  = self.CalcScrolledPosition(rect.x, rect.y)

            size = self.GetClientSize()
            rect.width = size.x
            # refresh till the bottom of the window
            rect.height = size.y - rect.y

            self.RefreshRect(rect)

        else: # !report

            # TODO: how to do it more efficiently?
            self._dirty = True


    def RefreshSelected(self):
        """ Redraws the selected lines. """

        if self.IsEmpty():
            return

        if self.InReportView():

            fromm, to = self.GetVisibleLinesRange()

        else: # !virtual

            fromm = 0
            to = self.GetItemCount() - 1

        if self.HasCurrent() and self._current >= fromm and self._current <= to:
            self.RefreshLine(self._current)

        for line in xrange(fromm, to+1):
            # NB: the test works as expected even if self._current == -1
            if line != self._current and self.IsHighlighted(line):
                self.RefreshLine(line)


    def HideWindows(self):
        """ Hides the windows associated to the items. Used internally. """
        
        for child in self._itemWithWindow:
            wnd = child.GetWindow()
            if wnd:
                wnd.Hide()


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

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

        # Note: a wxPaintDC must be constructed even if no drawing is
        # done (a Windows requirement).
        dc = wx.BufferedPaintDC(self)
        
        dc.SetBackgroundMode(wx.TRANSPARENT)
        
        self.PrepareDC(dc)

        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.SetPen(wx.TRANSPARENT_PEN)
        dc.Clear()
        
        self.TileBackground(dc)
        self.PaintWaterMark(dc)

        if self.IsEmpty():
            # nothing to draw or not the moment to draw it
            return
        
        if self._dirty:
            # delay the repainting until we calculate all the items positions
            self.RecalculatePositions(False)

        useVista, useGradient = self._vistaselection, self._usegradients
        dev_x, dev_y = self.CalcScrolledPosition(0, 0)

        dc.SetFont(self.GetFont())
        
        if self.InReportView():
            visibleFrom, visibleTo = self.GetVisibleLinesRange()
        
            # mrcs: draw additional items
            if visibleFrom > 0:
                visibleFrom -= 1

            if visibleTo < self.GetItemCount() - 1:
                visibleTo += 1

            xOrig = dc.LogicalToDeviceX(0)
            yOrig = dc.LogicalToDeviceY(0)

            # tell the caller cache to cache the data
            if self.IsVirtual():

                evCache = UltimateListEvent(wxEVT_COMMAND_LIST_CACHE_HINT, self.GetParent().GetId())
                evCache.SetEventObject(self.GetParent())
                evCache.m_oldItemIndex = visibleFrom
                evCache.m_itemIndex = visibleTo
                self.GetParent().GetEventHandler().ProcessEvent(evCache)

            no_highlight = self.HasAGWFlag(ULC_NO_HIGHLIGHT)

            for line in xrange(visibleFrom, visibleTo+1):
                rectLine = self.GetLineRect(line)

                if not self.IsExposed(rectLine.x + xOrig, rectLine.y + yOrig, rectLine.width, rectLine.height):
                    # don't redraw unaffected lines to avoid flicker
                    continue

                theLine = self.GetLine(line)
                enabled = theLine.GetItem(0, CreateListItem(line, 0)).IsEnabled()
                oldPN, oldBR = dc.GetPen(), dc.GetBrush()
                theLine.DrawInReportMode(dc, line, rectLine,
                                         self.GetLineHighlightRect(line),
                                         self.IsHighlighted(line) and not no_highlight,
                                         line==self._current, enabled, oldPN, oldBR)

            if self.HasAGWFlag(ULC_HRULES):
                pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID)
                clientSize = self.GetClientSize()

                # Don't draw the first one
                start = (visibleFrom > 0 and [visibleFrom] or [1])[0]

                dc.SetPen(pen)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                for i in xrange(start, visibleTo+1):
                    lineY = self.GetLineY(i)
                    dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x, lineY)

                # Draw last horizontal rule
                if visibleTo == self.GetItemCount() - 1:
                    lineY = self.GetLineY(visibleTo) + self.GetLineHeight(visibleTo)
                    dc.SetPen(pen)
                    dc.SetBrush(wx.TRANSPARENT_BRUSH)
                    dc.DrawLine(0 - dev_x, lineY, clientSize.x - dev_x , lineY)

            # Draw vertical rules if required
            if self.HasAGWFlag(ULC_VRULES) and not self.IsEmpty():
                pen = wx.Pen(self.GetRuleColour(), 1, wx.SOLID)

                firstItemRect = self.GetItemRect(visibleFrom)
                lastItemRect = self.GetItemRect(visibleTo)
                x = firstItemRect.GetX()
                dc.SetPen(pen)
                dc.SetBrush(wx.TRANSPARENT_BRUSH)
                for col in xrange(self.GetColumnCount()):
                    
                    if not self.IsColumnShown(col):
                        continue

                    colWidth = self.GetColumnWidth(col)
                    x += colWidth
                    
                    x_pos = x - dev_x
                    if col < self.GetColumnCount()-1:
                        x_pos -= 2

                    dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y, x_pos, lastItemRect.GetBottom() + 1 - dev_y)


        else: # !report

            for i in xrange(self.GetItemCount()):
                self.GetLine(i).Draw(i, dc)

        if wx.Platform not in ["__WXMAC__", "__WXGTK__"]:
            # Don't draw rect outline under Mac at all.
            # Draw it elsewhere on GTK
            if self.HasCurrent():
                if self._hasFocus and not self.HasAGWFlag(ULC_NO_HIGHLIGHT) and not useVista and not useGradient \
                   and not self.HasAGWFlag(ULC_BORDER_SELECT) and not self.HasAGWFlag(ULC_NO_FULL_ROW_SELECT):
                    dc.SetPen(wx.BLACK_PEN)
                    dc.SetBrush(wx.TRANSPARENT_BRUSH)
                    dc.DrawRectangleRect(self.GetLineHighlightRect(self._current))

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

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

        :note: This method is intentionally empty to reduce flicker.        
        """

        pass
    

    def TileBackground(self, dc):
        """
        Tiles the background image to fill all the available area.

        :param `dc`: an instance of :class:`DC`.

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

        if not self._backgroundImage:
            return

        if self._imageStretchStyle != _StyleTile:
            # Can we actually do something here (or in OnPaint()) To Handle
            # background images that are stretchable or always centered?
            # I tried but I get enormous flickering...
            return

        sz = self.GetClientSize()
        w = self._backgroundImage.GetWidth()
        h = self._backgroundImage.GetHeight()

        x = 0

        while x < sz.width:
            y = 0

            while y < sz.height:
                dc.DrawBitmap(self._backgroundImage, x, y, True)
                y = y + h

            x = x + w


    def PaintWaterMark(self, dc):
        """
        Draws a watermark at the bottom right of :class:`UltimateListCtrl`.

        :param `dc`: an instance of :class:`DC`.

        .. todo:: Better support for this is needed.
        """

        if not self._waterMark:
            return

        width, height = self.CalcUnscrolledPosition(*self.GetClientSize())
        
        bitmapW = self._waterMark.GetWidth()
        bitmapH = self._waterMark.GetHeight()

        x = width - bitmapW - 5
        y = height - bitmapH - 5

        dc.DrawBitmap(self._waterMark, x, y, True)
        
        
    def HighlightAll(self, on=True):
        """
        Highlights/unhighlights all the lines in :class:`UltimateListCtrl`.

        :param `on`: ``True`` to highlight all the lines, ``False`` to unhighlight them.
        """

        if self.IsSingleSel():

            if on:
                raise Exception("can't do this in a single sel control")

            # we just have one item to turn off
            if self.HasCurrent() and self.IsHighlighted(self._current):
                self.HighlightLine(self._current, False)
                self.RefreshLine(self._current)

        else: # multi sel
            if not self.IsEmpty():
                self.HighlightLines(0, self.GetItemCount() - 1, on)


    def OnChildFocus(self, event):
        """
        Handles the ``wx.EVT_CHILD_FOCUS`` event for :class:`UltimateListMainWindow`.

        :param `event`: a :class:`ChildFocusEvent` event to be processed.

        .. note::

           This method is intentionally empty to prevent the default handler in
           :class:`PyScrolledWindow` from needlessly scrolling the window when the edit
           control is dismissed.
           
        """

        # Do nothing here.  This prevents the default handler in wx.PyScrolledWindow
        # from needlessly scrolling the window when the edit control is
        # dismissed.  See ticket #9563.

        pass
    

    def SendNotify(self, line, command, point=wx.DefaultPosition):
        """
        Actually sends a :class:`UltimateListEvent`.

        :param `line`: an instance of :class:`UltimateListLineData`;
        :param `command`: the event type to send;
        :param `point`: an instance of :class:`Point`.
        """

        bRet = True
        le = UltimateListEvent(command, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = line

        # set only for events which have position
        if point != wx.DefaultPosition:
            le.m_pointDrag = point

        # don't try to get the line info for virtual list controls: the main
        # program has it anyhow and if we did it would result in accessing all
        # the lines, even those which are not visible now and this is precisely
        # what we're trying to avoid
        if not self.IsVirtual():

            if line != -1:
                self.GetLine(line).GetItem(0, le.m_item)

            #else: this happens for wxEVT_COMMAND_LIST_ITEM_FOCUSED event

            #else: there may be no more such item

        self.GetParent().GetEventHandler().ProcessEvent(le)
        bRet = le.IsAllowed()

        return bRet


    def ChangeCurrent(self, current):
        """
        Changes the current line to the specified one.

        :param `current`: an integer specifying the index of the current line.
        """        

        self._current = current

        # as the current item changed, we shouldn't start editing it when the
        # "slow click" timer expires as the click happened on another item
        if self._renameTimer.IsRunning():
            self._renameTimer.Stop()
        
        self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_FOCUSED)


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

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

        if item < 0 or item >= self.GetItemCount():
            raise Exception("wrong index in UltimateListCtrl.EditLabel()")

        le = UltimateListEvent(wxEVT_COMMAND_LIST_BEGIN_LABEL_EDIT, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = item
        data = self.GetLine(item)
        le.m_item = data.GetItem(0, le.m_item)

        self._textctrl = UltimateListTextCtrl(self, item)

        if self.GetParent().GetEventHandler().ProcessEvent(le) and not le.IsAllowed():
            # vetoed by user code
            return

        # We have to call this here because the label in question might just have
        # been added and no screen update taken place.
        if self._dirty:
            wx.SafeYield()
            # Pending events dispatched by wx.SafeYield might have changed the item
            # count
            if item >= self.GetItemCount():
                return None

        # modified
        self._textctrl.SetFocus()

        return self._textctrl


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

        if not self.HasCurrent():
            raise Exception("unexpected rename timer")

        self.EditLabel(self._current)


    def OnRenameAccept(self, itemEdit, value):
        """
        Called by :class:`UltimateListTextCtrl`, to accept the changes and to send the
        ``EVT_LIST_END_LABEL_EDIT`` event.

        :param `itemEdit`: an instance of :class:`UltimateListItem`;
        :param `value`: the new value of the item label.        
        """

        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = itemEdit

        data = self.GetLine(itemEdit)

        le.m_item = data.GetItem(0, le.m_item)
        le.m_item._text = value
        
        return not self.GetParent().GetEventHandler().ProcessEvent(le) or le.IsAllowed()


    def OnRenameCancelled(self, itemEdit):
        """
        Called by :class:`UltimateListTextCtrl`, to cancel the changes and to send the
        ``EVT_LIST_END_LABEL_EDIT`` event.

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

        # let owner know that the edit was cancelled
        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_LABEL_EDIT, self.GetParent().GetId())
        le.SetEditCanceled(True)

        le.SetEventObject(self.GetParent())
        le.m_itemIndex = itemEdit

        data = self.GetLine(itemEdit)
        le.m_item = data.GetItem(0, le.m_item)

        self.GetEventHandler().ProcessEvent(le)


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

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

        if wx.Platform == "__WXMAC__":
            # On wxMac we can't depend on the EVT_KILL_FOCUS event to properly
            # shutdown the edit control when the mouse is clicked elsewhere on the
            # listctrl because the order of events is different (or something like
            # that,) so explicitly end the edit if it is active.
            if event.LeftDown() and self._textctrl:
                self._textctrl.AcceptChanges()
                self._textctrl.Finish()

        if event.LeftDown():
            self.SetFocusIgnoringChildren()

        event.SetEventObject(self.GetParent())
        if self.GetParent().GetEventHandler().ProcessEvent(event):
            return

        if event.GetEventType() == wx.wxEVT_MOUSEWHEEL:
            # let the base handle mouse wheel events.
            self.Refresh()
            event.Skip()
            return

        if self.IsEmpty():
            if event.RightDown():
                self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())

                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
                                             self.ClientToScreen(event.GetPosition()))
                evtCtx.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(evtCtx)

            return

        if self._dirty:
            return

        if not (event.Dragging() or event.ButtonDown() or event.LeftUp() or \
                event.ButtonDClick() or event.Moving() or event.RightUp()):
            return

        x = event.GetX()
        y = event.GetY()
        x, y = self.CalcUnscrolledPosition(x, y)

        # where did we hit it (if we did)?
        hitResult = 0
        newItem = None
        count = self.GetItemCount()

        if self.InReportView():
            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                current = y/self.GetLineHeight()
                if current < count:
                    newItem, hitResult = self.HitTestLine(current, x, y)
                else:
                    return
            else:
                for current in xrange(count):
                    newItem, hitResult = self.HitTestLine(current, x, y)
                    if hitResult:
                        break
        else:
            # TODO: optimize it too! this is less simple than for report view but
            #       enumerating all items is still not a way to do it!!
            for current in xrange(count):
                newItem, hitResult = self.HitTestLine(current, x, y)
                if hitResult:
                    break

        theItem = None
        
        if not self.IsVirtual():
            theItem = CreateListItem(current, 0)
            theItem = self.GetItem(theItem)
        
        if event.GetEventType() == wx.wxEVT_MOTION and not event.Dragging():

            if current >= 0 and current < count and self.HasAGWFlag(ULC_TRACK_SELECT) and not self._hoverTimer.IsRunning():
                self._hoverItem = current
                self._hoverTimer.Start(HOVER_TIME, wx.TIMER_ONE_SHOT)
                
            if newItem and newItem.IsHyperText() and (hitResult & ULC_HITTEST_ONITEMLABEL) and theItem and theItem.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

            if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and hitResult:
                if not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

            if self.HasAGWFlag(ULC_SHOW_TOOLTIPS):
                if newItem and hitResult & ULC_HITTEST_ONITEMLABEL:
                    r,c = (newItem._itemId, newItem._col)
                    line = self.GetLine(r)
                    tt = line.GetToolTip(c)
                    if tt and not tt == "":
                        if self.GetToolTip() and self.GetToolTip().GetTip() != tt:  
                            self.SetToolTipString(tt)
                    elif (r,c) in self._shortItems: # if the text didn't fit in the column
                        text = newItem.GetText()
                        if self.GetToolTip() and self.GetToolTip().GetTip() != text:                            
                            self.SetToolTipString(text)
                    else:
                        self.SetToolTipString("")
                else:
                    self.SetToolTipString("")

            if self.HasAGWFlag(ULC_HOT_TRACKING):
                if hitResult:
                    if self._oldHotCurrent != current:                        
                        if self._oldHotCurrent is not None:
                            self.RefreshLine(self._oldHotCurrent)
                        self._newHotCurrent = current
                        self.RefreshLine(self._newHotCurrent)
                        self._oldHotCurrent = current
                
            event.Skip()
            return

        if event.Dragging():
            
            if not self._isDragging:

                if self._lineLastClicked == -1 or not hitResult or not theItem or not theItem.IsEnabled():
                    return

                if self._dragCount == 0:
                    # we have to report the raw, physical coords as we want to be
                    # able to call HitTest(event.m_pointDrag) from the user code to
                    # get the item being dragged
                    self._dragStart = event.GetPosition()

                self._dragCount += 1

                if self._dragCount != 3:
                    return

                command = (event.RightIsDown() and [wxEVT_COMMAND_LIST_BEGIN_RDRAG] or [wxEVT_COMMAND_LIST_BEGIN_DRAG])[0]
                le = UltimateListEvent(command, self.GetParent().GetId())
                le.SetEventObject(self.GetParent())
                le.m_itemIndex = self._lineLastClicked
                le.m_pointDrag = self._dragStart
                self.GetParent().GetEventHandler().ProcessEvent(le)

                # we're going to drag this item
                self._isDragging = True
                self._dragItem = current

                # remember the old cursor because we will change it while
                # dragging
                self._oldCursor = self._cursor
                self.SetCursor(self._dragCursor)
                    
            else:

                if current != self._dropTarget:
                    
                    self.SetCursor(self._dragCursor)
                    # unhighlight the previous drop target
                    if self._dropTarget is not None:
                        self.RefreshLine(self._dropTarget)

                    move = current
                    if self._dropTarget:
                        move = (current > self._dropTarget and [current+1] or [current-1])[0]

                    self._dropTarget = current
                    self.MoveToItem(move)

                else:

                    if self._dragItem == current:
                        self.SetCursor(wx.StockCursor(wx.CURSOR_NO_ENTRY))                    

            if self.HasAGWFlag(ULC_REPORT) and self._dragItem != current:
                self.DrawDnDArrow()

            return
        
        else:
            
            self._dragCount = 0

        if theItem and not theItem.IsEnabled():
            self.DragFinish(event)
            event.Skip()
            return

        if not hitResult:
            # outside of any item
            if event.RightDown():
                self.SendNotify(-1, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition())
                evtCtx = wx.ContextMenuEvent(wx.wxEVT_CONTEXT_MENU, self.GetParent().GetId(),
                                             self.ClientToScreen(event.GetPosition()))
                evtCtx.SetEventObject(self.GetParent())
                self.GetParent().GetEventHandler().ProcessEvent(evtCtx)
            else:
                self.HighlightAll(False)
                self.DragFinish(event)

            return

        forceClick = False
        if event.ButtonDClick():
            if self._renameTimer.IsRunning():
                self._renameTimer.Stop()
                
            self._lastOnSame = False

            if current == self._lineLastClicked:
                self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

                if newItem and newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):
                    self.CheckItem(newItem, not self.IsItemChecked(newItem))

                return

            else:

                # The first click was on another item, so don't interpret this as
                # a double click, but as a simple click instead
                forceClick = True

        if event.LeftUp():

            if self.DragFinish(event):
                return
            if self._lineSelectSingleOnUp != - 1:
                # select single line
                self.HighlightAll(False)
                self.ReverseHighlight(self._lineSelectSingleOnUp)

            if self._lastOnSame:
                if (current == self._current) and (hitResult == ULC_HITTEST_ONITEMLABEL) and self.HasAGWFlag(ULC_EDIT_LABELS):
                    if not self.InReportView() or self.GetLineLabelRect(current).Contains((x, y)):
                        # This wx.SYS_DCLICK_MSEC is not yet wrapped in wxPython...
                        # dclick = wx.SystemSettings.GetMetric(wx.SYS_DCLICK_MSEC)
                        # m_renameTimer->Start(dclick > 0 ? dclick : 250, True)
                        self._renameTimer.Start(250, True)

            self._lastOnSame = False
            self._lineSelectSingleOnUp = -1

        elif event.RightUp():
            
            if self.DragFinish(event):
                return
                
        else:

            # This is necessary, because after a DnD operation in
            # from and to ourself, the up event is swallowed by the
            # DnD code. So on next non-up event (which means here and
            # now) self._lineSelectSingleOnUp should be reset.
            self._lineSelectSingleOnUp = -1

        if event.RightDown():

            if self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_RIGHT_CLICK, event.GetPosition()):
                self._lineBeforeLastClicked = self._lineLastClicked
                self._lineLastClicked = current
                # If the item is already selected, do not update the selection.
                # Multi-selections should not be cleared if a selected item is clicked.

                if not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

                # Allow generation of context menu event
                event.Skip()

        elif event.MiddleDown():
            self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_MIDDLE_CLICK)

        elif event.LeftDown() or forceClick:
            self._lineBeforeLastClicked = self._lineLastClicked
            self._lineLastClicked = current

            oldCurrent = self._current
            oldWasSelected = self.IsHighlighted(self._current)

            cmdModifierDown = event.CmdDown()
            if self.IsSingleSel() or not (cmdModifierDown or event.ShiftDown()):
                if self.IsSingleSel() or not self.IsHighlighted(current):
                    self.HighlightAll(False)
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)
                    
                else: # multi sel & current is highlighted & no mod keys
                    self._lineSelectSingleOnUp = current
                    self.ChangeCurrent(current) # change focus

            else: # multi sel & either ctrl or shift is down
                if cmdModifierDown:
                    self.ChangeCurrent(current)
                    self.ReverseHighlight(self._current)

                elif event.ShiftDown():
                    self.ChangeCurrent(current)
                    lineFrom, lineTo = oldCurrent, current
                    shift = 0

                    if lineTo < lineFrom:
                        lineTo = lineFrom
                        lineFrom = self._current

                        if not self.IsHighlighted(lineFrom):
                            shift = 1
                        
                        for i in xrange(lineFrom+1, lineTo+1):
                            if self.IsHighlighted(i):
                                self.HighlightLine(i, False)
                                self.RefreshLine(i)
                                lineTo -= 1
                                
                    self.HighlightLines(lineFrom, lineTo+shift)

                else: # !ctrl, !shift

                    # test in the enclosing if should make it impossible
                    raise Exception("how did we get here?")
            
            if newItem:
                if event.LeftDown():
                    if newItem.GetKind() in [1, 2] and (hitResult & ULC_HITTEST_ONITEMCHECK):                    
                        self.CheckItem(newItem, not self.IsItemChecked(newItem))
                    if newItem.IsHyperText():
                        self.SetItemVisited(newItem, True)
                        self.HandleHyperLink(newItem)
                    
            if self._current != oldCurrent:
                self.RefreshLine(oldCurrent)

            # forceClick is only set if the previous click was on another item
            self._lastOnSame = not forceClick and (self._current == oldCurrent) and oldWasSelected

            if self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT) and self.HasAGWFlag(ULC_SEND_LEFTCLICK):
                self.SendNotify(current, wxEVT_COMMAND_LIST_ITEM_LEFT_CLICK, event.GetPosition())


    def DrawDnDArrow(self):
        """ Draws a drag and drop visual representation of an arrow. """
        
        dc = wx.ClientDC(self)
        lineY = self.GetLineY(self._dropTarget)
        width = self.GetTotalWidth()
        
        dc.SetPen(wx.Pen(wx.BLACK, 2))
        x, y = self.CalcScrolledPosition(HEADER_OFFSET_X, lineY+2*HEADER_OFFSET_Y)

        tri1 = [wx.Point(x+1, y-2), wx.Point(x+1, y+4), wx.Point(x+4, y+1)]
        tri2 = [wx.Point(x+width-1, y-2), wx.Point(x+width-1, y+4), wx.Point(x+width-4, y+1)]
        dc.DrawPolygon(tri1)
        dc.DrawPolygon(tri2)
        
        dc.DrawLine(x, y+1, width, y+1)
        

    def DragFinish(self, event):
        """
        A drag and drop operation has just finished.

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

        if not self._isDragging:
            return False
        
        self._isDragging = False
        self._dragCount = 0
        self._dragItem = None
        self.SetCursor(self._oldCursor)
        self.Refresh()

        le = UltimateListEvent(wxEVT_COMMAND_LIST_END_DRAG, self.GetParent().GetId())
        le.SetEventObject(self.GetParent())
        le.m_itemIndex = self._dropTarget
        le.m_pointDrag = event.GetPosition()
        self.GetParent().GetEventHandler().ProcessEvent(le)

        return True
    

    def HandleHyperLink(self, item):
        """
        Handles the hyperlink items, sending the ``EVT_LIST_ITEM_HYPERLINK`` event.

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

        if self.IsItemHyperText(item):
            self.SendNotify(item._itemId, wxEVT_COMMAND_LIST_ITEM_HYPERLINK)


    def OnHoverTimer(self, event):
        """
        Handles the ``wx.EVT_TIMER`` event for :class:`UltimateListMainWindow`.

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

        x, y = self.ScreenToClient(wx.GetMousePosition())
        x, y = self.CalcUnscrolledPosition(x, y)
        item, hitResult = self.HitTestLine(self._hoverItem, x, y)

        if item and item._itemId == self._hoverItem:
            if not self.IsHighlighted(self._hoverItem):
                
                dontNotify = self.HasAGWFlag(ULC_STICKY_HIGHLIGHT) and self.HasAGWFlag(ULC_STICKY_NOSELEVENT)
                if not dontNotify:
                    self.SendNotify(self._hoverItem, wxEVT_COMMAND_LIST_ITEM_SELECTED)
            
                self.HighlightAll(False)
                self.ChangeCurrent(self._hoverItem)
                self.ReverseHighlight(self._current)


    def MoveToItem(self, item):
        """
        Scrolls the input item into view.

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

        if item == -1:
            return

        if item >= self.GetItemCount():
            item = self.GetItemCount() - 1
            
        rect = self.GetLineRect(item)
        client_w, client_h = self.GetClientSize()
        hLine = self.GetLineHeight(item)

        view_x = SCROLL_UNIT_X*self.GetScrollPos(wx.HORIZONTAL)
        view_y = hLine*self.GetScrollPos(wx.VERTICAL)

        if self.InReportView():

            # the next we need the range of lines shown it might be different, so
            # recalculate it
            self.ResetVisibleLinesRange()

            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):            

                if rect.y < view_y:
                    self.Scroll(-1, rect.y/hLine)
                if rect.y+rect.height+5 > view_y+client_h:
                    self.Scroll(-1, (rect.y+rect.height-client_h+hLine)/hLine)

                if wx.Platform == "__WXMAC__":
                    # At least on Mac the visible lines value will get reset inside of
                    # Scroll *before* it actually scrolls the window because of the
                    # Update() that happens there, so it will still have the wrong value.
                    # So let's reset it again and wait for it to be recalculated in the
                    # next paint event.  I would expect this problem to show up in wxGTK
                    # too but couldn't duplicate it there.  Perhaps the order of events
                    # is different...  --Robin
                    self.ResetVisibleLinesRange()
        
            else:

                view_y = SCROLL_UNIT_Y*self.GetScrollPos(wx.VERTICAL)
                start_y, height = rect.y, rect.height

                if start_y < view_y:
                    while start_y > view_y:
                        start_y -= SCROLL_UNIT_Y

                    self.Scroll(-1, start_y/SCROLL_UNIT_Y)
                    
                if start_y + height > view_y + client_h:
                    while start_y + height < view_y + client_h:
                        start_y += SCROLL_UNIT_Y

                    self.Scroll(-1, (start_y+height-client_h+SCROLL_UNIT_Y)/SCROLL_UNIT_Y)
                    
        else: # !report


            sx = sy = -1

            if rect.x-view_x < 5:
                sx = (rect.x - 5)/SCROLL_UNIT_X
            if rect.x+rect.width-5 > view_x+client_w:
                sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X)/SCROLL_UNIT_X

            if rect.y-view_y < 5:
                sy = (rect.y - 5)/hLine
            if rect.y + rect.height - 5 > view_y + client_h:
                sy = (rect.y + rect.height - client_h + hLine)/hLine

            self.Scroll(sx, sy)
        

# ----------------------------------------------------------------------------
# keyboard handling
# ----------------------------------------------------------------------------

    def GetNextActiveItem(self, item, down=True):
        """
        Returns the next active item. Used Internally at present.

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `down`: ``True`` to search downwards for an active item, ``False``
         to search upwards.
        """

        count = self.GetItemCount()
        initialItem = item
        
        while 1:
            if item >= count or item < 0:
                return initialItem

            listItem = CreateListItem(item, 0)
            listItem = self.GetItem(listItem, 0)
            if listItem.IsEnabled():
                return item
            
            item = (down and [item+1] or [item-1])[0]


    def OnArrowChar(self, newCurrent, event):
        """
        Handles the keyboard arrows key events.

        :param `newCurrent`: an integer specifying the new current item;
        :param `event`: a :class:`KeyEvent` event to be processed.
        """

        oldCurrent = self._current
        newCurrent = self.GetNextActiveItem(newCurrent, newCurrent > oldCurrent)
        
        # in single selection we just ignore Shift as we can't select several
        # items anyhow
        if event.ShiftDown() and not self.IsSingleSel():

            self.ChangeCurrent(newCurrent)

            # refresh the old focus to remove it
            self.RefreshLine(oldCurrent)

            # select all the items between the old and the new one
            if oldCurrent > newCurrent:
                newCurrent = oldCurrent
                oldCurrent = self._current

            self.HighlightLines(oldCurrent, newCurrent)

        else: # !shift

            # all previously selected items are unselected unless ctrl is held
            # in a multi-selection control
            if not event.ControlDown() or self.IsSingleSel():
                self.HighlightAll(False)

            self.ChangeCurrent(newCurrent)

            # refresh the old focus to remove it
            self.RefreshLine(oldCurrent)

            if not event.ControlDown() or self.IsSingleSel():
                self.HighlightLine(self._current, True)

        self.RefreshLine(self._current)
        self.MoveToFocus()


    def SetEventAttrs(self, oldEvent, newEvent):
        """
        Copies (almost) all of the ``m_*`` attributes from the original :class:`KeyEvent` event
        to the copy (`newEvent`). Successfully passes the key codes to the application
        as expected.

        :param `oldEvent`: the original :class:`KeyEvent` event to be processed;
        :param `newEvent`: the new :class:`KeyEvent` event to be processed.

        .. todo::

           Find out why getting `m_rawFlags` returns a Python ``long`` but the setter
           expects to receive an ``unsigned int``.


        .. versionadded:: 0.9.5
        """

        if _VERSION_STRING < '2.9':

            attributes = ['m_altDown', 'm_controlDown', 'm_keyCode',
                          'm_metaDown', 'm_rawCode', 'm_scanCode',
                          'm_shiftDown', 'm_x', 'm_y']

            for attr in attributes:
                setattr(newEvent, attr, getattr(oldEvent, attr))

        else:
            # 2.9.something
            methods = ['AltDown', 'ControlDown', 'MetaDown', 'ShiftDown']

            for meth in methods:
                eval('newEvent.Set%s(oldEvent.%s())'%(meth, meth))

            attributes = ['m_keyCode', 'm_rawCode', 'm_x', 'm_y']

            for attr in attributes:
                setattr(newEvent, attr, getattr(oldEvent, attr))
            

    def OnKeyDown(self, event):
        """
        Handles the ``wx.EVT_KEY_DOWN`` event for :class:`UltimateListMainWindow`.

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

        parent = self.GetParent()

        # we propagate the key event upwards
        ke = wx.KeyEvent(event.GetEventType())
        self.SetEventAttrs(event, ke)
        
        ke.SetEventObject(parent)
        if parent.GetEventHandler().ProcessEvent(ke):
            event.Skip()
            return

        event.Skip()
    

    def OnKeyUp(self, event):
        """
        Handles the ``wx.EVT_KEY_UP`` event for :class:`UltimateListMainWindow`.

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

        parent = self.GetParent()

        # we propagate the key event upwards
        ke = wx.KeyEvent(event.GetEventType())
        self.SetEventAttrs(event, ke)

        ke.SetEventObject(parent)
        if parent.GetEventHandler().ProcessEvent(ke):
            return

        event.Skip()
                

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

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

        parent = self.GetParent()

        if self.IsVirtual() and self.GetItemCount() == 0:
            event.Skip()
            return

        # we send a list_key event up        
        if self.HasCurrent():
            le = UltimateListEvent(wxEVT_COMMAND_LIST_KEY_DOWN, self.GetParent().GetId())
            le.m_itemIndex = self._current
            le.m_item = self.GetLine(self._current).GetItem(0, le.m_item)
            le.m_code = event.GetKeyCode()
            le.SetEventObject(parent)
            parent.GetEventHandler().ProcessEvent(le)

        keyCode = event.GetKeyCode()
        if  keyCode not in [wx.WXK_UP, wx.WXK_DOWN, wx.WXK_RIGHT, wx.WXK_LEFT, \
                            wx.WXK_PAGEUP, wx.WXK_PAGEDOWN, wx.WXK_END, wx.WXK_HOME]:

            # propagate the char event upwards
            ke = wx.KeyEvent(event.GetEventType())
            self.SetEventAttrs(event, ke)
            ke.SetEventObject(parent)
            if parent.GetEventHandler().ProcessEvent(ke):
                return
        
        if event.GetKeyCode() == wx.WXK_TAB:
            nevent = wx.NavigationKeyEvent()
            nevent.SetWindowChange(event.ControlDown())
            nevent.SetDirection(not event.ShiftDown())
            nevent.SetEventObject(self.GetParent().GetParent())
            nevent.SetCurrentFocus(self._parent)
            if self.GetParent().GetParent().GetEventHandler().ProcessEvent(nevent):
                return

        # no item . nothing to do
        if not self.HasCurrent():
            event.Skip()
            return

        keyCode = event.GetKeyCode()
        
        if keyCode == wx.WXK_UP:
            if self._current > 0:
                self.OnArrowChar(self._current - 1, event)
                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                    self._dirty = True

        elif keyCode == wx.WXK_DOWN:
            if self._current < self.GetItemCount() - 1:
                self.OnArrowChar(self._current + 1, event)
                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                    self._dirty = True

        elif keyCode == wx.WXK_END:
            if not self.IsEmpty():
                self.OnArrowChar(self.GetItemCount() - 1, event)
                self._dirty = True

        elif keyCode == wx.WXK_HOME:
            if not self.IsEmpty():
                self.OnArrowChar(0, event)
                self._dirty = True

        elif keyCode == wx.WXK_PRIOR:
            steps = (self.InReportView() and [self._linesPerPage - 1] or [self._current % self._linesPerPage])[0]
            index = self._current - steps
            
            if index < 0:
                index = 0

            self.OnArrowChar(index, event)
            self._dirty = True

        elif keyCode == wx.WXK_NEXT:

            steps = (self.InReportView() and [self._linesPerPage - 1] or [self._linesPerPage - (self._current % self._linesPerPage) - 1])[0]
            index = self._current + steps
            count = self.GetItemCount()
            
            if index >= count:
                index = count - 1

            self.OnArrowChar(index, event)
            self._dirty = True

        elif keyCode == wx.WXK_LEFT:
            if not self.InReportView():

                index = self._current - self._linesPerPage
                if index < 0:
                    index = 0

                self.OnArrowChar(index, event)

        elif keyCode == wx.WXK_RIGHT:
            if not self.InReportView():

                index = self._current + self._linesPerPage
                count = self.GetItemCount()
                
                if index >= count:
                    index = count - 1

                self.OnArrowChar(index, event)

        elif keyCode == wx.WXK_SPACE:
            if self.IsSingleSel():

                if event.ControlDown():
                    self.ReverseHighlight(self._current)
                else: # normal space press
                    self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

            else:
                # select it in ReverseHighlight() below if unselected
                self.ReverseHighlight(self._current)

        elif keyCode in [wx.WXK_RETURN, wx.WXK_EXECUTE, wx.WXK_NUMPAD_ENTER]:
            self.SendNotify(self._current, wxEVT_COMMAND_LIST_ITEM_ACTIVATED)

        else:
            event.Skip()


# ----------------------------------------------------------------------------
# focus handling
# ----------------------------------------------------------------------------

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

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

        if self.GetParent():
            event = wx.FocusEvent(wx.wxEVT_SET_FOCUS, self.GetParent().GetId())
            event.SetEventObject(self.GetParent())
            if self.GetParent().GetEventHandler().ProcessEvent(event):
                return

        # wxGTK sends us EVT_SET_FOCUS events even if we had never got
        # EVT_KILL_FOCUS before which means that we finish by redrawing the items
        # which are already drawn correctly resulting in horrible flicker - avoid
        # it
        if not self._hasFocus:
            self._hasFocus = True
            self.Refresh()


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

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

        if self.GetParent():
            event = wx.FocusEvent(wx.wxEVT_KILL_FOCUS, self.GetParent().GetId())
            event.SetEventObject(self.GetParent())
            if self.GetParent().GetEventHandler().ProcessEvent(event):
                return

        self._hasFocus = False
        self.Refresh()


    def DrawImage(self, index, dc, x, y, enabled):
        """
        Draws one of the item images.

        :param `index`: the index of the image inside the image list;
        :param `dc`: an instance of :class:`DC`;
        :param `x`: the x position where to draw the image;
        :param `y`: the y position where to draw the image;
        :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
            imgList = (enabled and [self._normal_image_list] or [self._normal_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)

        elif self.InReportView() and self._small_image_list:
            imgList = (enabled and [self._small_image_list] or [self._small_grayed_image_list])[0]
            imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)


    def DrawCheckbox(self, dc, x, y, kind, checked, enabled):
        """
        Draws the item checkbox/radiobutton image.

        :param `dc`: an instance of :class:`DC`;
        :param `x`: the x position where to draw the image;
        :param `y`: the y position where to draw the image;
        :param `kind`: may be one of the following integers:

          =============== ==========================
          Item Kind       Description
          =============== ==========================
                 0        A normal item
                 1        A checkbox-like item
                 2        A radiobutton-type item
          =============== ==========================

        :param `checked`: ``True`` if the item is checked, ``False`` otherwise;
        :param `enabled`: ``True`` if the item is enabled, ``False`` if it is disabled.
        """

        imgList = (enabled and [self._image_list_check] or [self._grayed_check_list])[0]
        if kind == 1:
            # checkbox
            index = (checked and [0] or [1])[0]
        else:
            # radiobutton
            index = (checked and [2] or [3])[0]

        imgList.Draw(index, dc, x, y, wx.IMAGELIST_DRAW_TRANSPARENT)
            

    def GetCheckboxImageSize(self):
        """ Returns the checkbox/radiobutton image size. """

        bmp = self._image_list_check.GetBitmap(0)
        return bmp.GetWidth(), bmp.GetHeight()
    

    def GetImageSize(self, index):
        """
        Returns the image size for the item.

        :param `index`: the image index.
        """

        width = height = 0

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:

            for indx in index:
                w, h = self._normal_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.HasAGWFlag(ULC_LIST) and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        elif self.InReportView() and self._small_image_list:

            for indx in index:
                w, h = self._small_image_list.GetSize(indx)
                width += w + MARGIN_BETWEEN_TEXT_AND_ICON
                height = max(height, h)

        return width, height


    def GetTextLength(self, s):
        """
        Returns the text width for the input string.

        :param `s`: the string to measure.
        """

        dc = wx.ClientDC(self)
        dc.SetFont(self.GetFont())

        lw, lh, dummy = dc.GetMultiLineTextExtent(s)

        return lw + AUTOSIZE_COL_MARGIN


    def SetImageList(self, imageList, which):
        """
        Sets the image list associated with the control.

        :param `imageList`: an instance of :class:`ImageList` or an instance of :class:`PyImageList`;
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using :class:`PyImageList` enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
         
        """

        self._dirty = True

        if isinstance(imageList, PyImageList):
            # We have a custom PyImageList with variable image sizes
            cls = PyImageList
        else:
            cls = wx.ImageList

        # calc the spacing from the icon size
        width = height = 0
        if imageList and imageList.GetImageCount():
            width, height = imageList.GetSize(0)

        if which == wx.IMAGE_LIST_NORMAL:
            self._normal_image_list = imageList
            self._normal_grayed_image_list = cls(width, height, True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._normal_grayed_image_list.Add(newbmp)

            self._normal_spacing = width + 8

        if which == wx.IMAGE_LIST_SMALL:
            self._small_image_list = imageList
            self._small_spacing = width + 14

            self._small_grayed_image_list = cls(width, height, True, 0)

            for ii in xrange(imageList.GetImageCount()):
                bmp = imageList.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._small_grayed_image_list.Add(newbmp)

        self._lineHeight = 0  # ensure that the line height will be recalc'd        
        self.ResetLineDimensions()


    def SetImageListCheck(self, sizex, sizey, imglist=None):
        """
        Sets the checkbox/radiobutton image list.

        :param `sizex`: the width of the bitmaps in the `imglist`;
        :param `sizey`: the height of the bitmaps in the `imglist`;
        :param `imglist`: an instance of :class:`ImageList`.
        """

        # Image list to hold disabled versions of each control
        self._grayed_check_list = wx.ImageList(sizex, sizey, True, 0)

        if imglist is None:
            
            self._image_list_check = wx.ImageList(sizex, sizey)

            # Get the Checkboxes
            self._image_list_check.Add(self.GetControlBmp(checkbox=True,
                                                          checked=True,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
                                                           checked=True,
                                                           enabled=False,
                                                           x=sizex, y=sizey))

            self._image_list_check.Add(self.GetControlBmp(checkbox=True,
                                                          checked=False,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=True,
                                                           checked=False,
                                                           enabled=False,
                                                           x=sizex, y=sizey))
            # Get the Radio Buttons
            self._image_list_check.Add(self.GetControlBmp(checkbox=False,
                                                          checked=True,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
                                                           checked=True,
                                                           enabled=False,
                                                           x=sizex, y=sizey))

            self._image_list_check.Add(self.GetControlBmp(checkbox=False,
                                                          checked=False,
                                                          enabled=True,
                                                          x=sizex, y=sizey))
            self._grayed_check_list.Add(self.GetControlBmp(checkbox=False,
                                                           checked=False,
                                                           enabled=False,
                                                           x=sizex, y=sizey))
        else:

            sizex, sizey = imglist.GetSize(0)
            self._image_list_check = imglist

            for ii in xrange(self._image_list_check.GetImageCount()):
                
                bmp = self._image_list_check.GetBitmap(ii)
                newbmp = MakeDisabledBitmap(bmp)
                self._grayed_check_list.Add(newbmp)

        self._dirty = True

        if imglist:
            self.RecalculatePositions()


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

        bmp = wx.EmptyBitmap(x, y)
        mdc = wx.MemoryDC(bmp)
        mdc.SetBrush(wx.BLACK_BRUSH)
        mdc.Clear()
        
        render = wx.RendererNative.Get()

        if checked:
            flag = wx.CONTROL_CHECKED
        else:
            flag = 0

        if not enabled:
            flag |= wx.CONTROL_DISABLED


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

        mdc.SelectObject(wx.NullBitmap)
        return bmp


    def SetItemSpacing(self, spacing, isSmall=False):
        """
        Sets the spacing between item texts and icons.

        :param `spacing`: the spacing between item texts and icons, in pixels;
        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        self._dirty = True
        
        if isSmall:
            self._small_spacing = spacing
        else:
            self._normal_spacing = spacing


    def GetItemSpacing(self, isSmall=False):
        """
        Returns the spacing between item texts and icons, in pixels.

        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        return (isSmall and [self._small_spacing] or [self._normal_spacing])[0]


# ----------------------------------------------------------------------------
# columns
# ----------------------------------------------------------------------------

    def SetColumn(self, col, item):
        """
        Sets information about this column.

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

        column = self._columns[col]

        if item._width == ULC_AUTOSIZE_USEHEADER:
            item._width = self.GetTextLength(item._text)

        column.SetItem(item)

        headerWin = self.GetListCtrl()._headerWin
        if headerWin:
            headerWin._dirty = True

        self._dirty = True

        # invalidate it as it has to be recalculated
        self._headerWidth = 0


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

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``ULC_AUTOSIZE_FILL`` (-3). 
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms). 
         ``ULC_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        :note: In small or normal icon view, col must be -1, and the column width
         is set for all columns.
        """
        
        if col < 0:
            raise Exception("invalid column index")

        if not self.InReportView() and not self.InTileView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):
            raise Exception("SetColumnWidth() can only be called in report/tile modes or with the ULC_HEADER_IN_ALL_VIEWS flag set.")

        self._dirty = True
        headerWin = self.GetListCtrl()._headerWin
        footerWin = self.GetListCtrl()._footerWin
        
        if headerWin:
            headerWin._dirty = True

        if footerWin:
            footerWin._dirty = True

        column = self._columns[col]
        count = self.GetItemCount()

        if width == ULC_AUTOSIZE_FILL:
            
            width = self.GetColumnWidth(col)
            if width == 0:
                width = WIDTH_COL_DEFAULT
            self._resizeColumn = col
            
        elif width == ULC_AUTOSIZE_USEHEADER:

            width = self.GetTextLength(column.GetText())
            width += 2*EXTRA_WIDTH

            if column.GetKind() in [1, 2]:
                ix, iy = self._owner.GetCheckboxImageSize()
                width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE
                
            # check for column header's image availability
            images = column.GetImage()
            for img in images:
                if self._small_image_list:
                    ix, iy = self._small_image_list.GetSize(img)
                    width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE

        elif width == ULC_AUTOSIZE:

            if self.IsVirtual() or not self.InReportView():
                # TODO: determine the max width somehow...
                width = WIDTH_COL_DEFAULT

            else: # !virtual

                maxW = AUTOSIZE_COL_MARGIN

                #  if the cached column width isn't valid then recalculate it
                if self._aColWidths[col]._bNeedsUpdate:

                    for i in xrange(count):

                        line = self.GetLine(i)
                        itemData = line._items[col]
                        item = UltimateListItem()

                        item = itemData.GetItem(item)
                        itemWidth = self.GetItemWidthWithImage(item)
                        if itemWidth > maxW and not item._overFlow:
                            maxW = itemWidth
                            
                    self._aColWidths[col]._bNeedsUpdate = False
                    self._aColWidths[col]._nMaxWidth = maxW

                maxW = self._aColWidths[col]._nMaxWidth
                width = maxW + AUTOSIZE_COL_MARGIN

        column.SetWidth(width)

        # invalidate it as it has to be recalculated
        self._headerWidth = 0
        self._footerWidth = 0

        if footerWin:
            footerWin.Refresh()


    def GetHeaderWidth(self):
        """ Returns the header window width, in pixels. """

        if not self._headerWidth:

            count = self.GetColumnCount()
            for col in xrange(count):

                if not self.IsColumnShown(col):
                    continue
                
                self._headerWidth += self.GetColumnWidth(col)

        if self.HasAGWFlag(ULC_FOOTER):
            self._footerWidth = self._headerWidth
            
        return self._headerWidth


    def GetColumn(self, col):
        """
        Returns information about this column.

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

        item = UltimateListItem()
        column = self._columns[col]                
        item = column.GetItem(item)

        return item
    

    def GetColumnWidth(self, col):
        """
        Returns the column width for the input column.

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

        column = self._columns[col]
        return column.GetWidth()


    def GetTotalWidth(self):
        """ Returns the total width of the columns in :class:`UltimateListCtrl`. """

        width = 0
        for column in self._columns:
            width += column.GetWidth()

        return width            

# ----------------------------------------------------------------------------
# item state
# ----------------------------------------------------------------------------

    def SetItem(self, item):
        """
        Sets information about the item.

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

        id = item._itemId
        
        if id < 0 or id >= self.GetItemCount():
            raise Exception("invalid item index in SetItem")

        if not self.IsVirtual():

            line = self.GetLine(id)
            line.SetItem(item._col, item)

            # Set item state if user wants
            if item._mask & ULC_MASK_STATE:
                self.SetItemState(item._itemId, item._state, item._state)

            if self.InReportView():

                #  update the Max Width Cache if needed
                width = self.GetItemWidthWithImage(item)

                if width > self._aColWidths[item._col]._nMaxWidth:
                    self._aColWidths[item._col]._nMaxWidth = width
                    self._aColWidths[item._col]._bNeedsUpdate = True

        if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            line.ResetDimensions()

        # update the item on screen
        if self.InReportView():
            rectItem = self.GetItemRect(id)
            self.RefreshRect(rectItem)
            

    def SetItemStateAll(self, state, stateMask):
        """
        Sets the item state flags for all the items.

        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :param `stateMask`: the bitmask for the state flag.
        
        :note: The valid state flags are influenced by the value of the state mask.
        """

        if self.IsEmpty():
            return

        # first deal with selection
        if stateMask & ULC_STATE_SELECTED:

            # set/clear select state
            if self.IsVirtual():

                # optimized version for virtual listctrl.
                self._selStore.SelectRange(0, self.GetItemCount() - 1, state==ULC_STATE_SELECTED)
                self.Refresh()

            elif state & ULC_STATE_SELECTED:

                count = self.GetItemCount()
                for i in xrange(count):
                    self.SetItemState(i, ULC_STATE_SELECTED, ULC_STATE_SELECTED)
                    
            else:

                # clear for non virtual (somewhat optimized by using GetNextItem())
                i = -1
                while 1:
                    i += 1
                    if self.GetNextItem(i, ULC_NEXT_ALL, ULC_STATE_SELECTED) == -1:
                        break

                    self.SetItemState(i, 0, ULC_STATE_SELECTED)

        if self.HasCurrent() and state == 0 and stateMask & ULC_STATE_FOCUSED:

            # unfocus all: only one item can be focussed, so clearing focus for
            # all items is simply clearing focus of the focussed item.
            self.SetItemState(self._current, state, stateMask)

        #(setting focus to all items makes no sense, so it is not handled here.)


    def SetItemState(self, litem, state, stateMask):
        """
        Sets the item state flags for the input item.

        :param `litem`: the index of the item; if defaulted to -1, the state flag
         will be set for all the items;
        :param `state`: the item state flag;        
        :param `stateMask`: the bitmask for the state flag.
        
        :see: :meth:`~UltimateListMainWindow.SetItemStateAll` for a list of valid state flags.
        """

        if litem == -1:
            self.SetItemStateAll(state, stateMask)
            return

        if litem < 0 or litem >= self.GetItemCount():
            raise Exception("invalid item index in SetItemState")

        oldCurrent = self._current
        item = litem    # safe because of the check above

        # do we need to change the focus?
        if stateMask & ULC_STATE_FOCUSED:

            if state & ULC_STATE_FOCUSED:

                # don't do anything if this item is already focused
                if item != self._current:

                    self.ChangeCurrent(item)

                    if oldCurrent != - 1:

                        if self.IsSingleSel():

                            self.HighlightLine(oldCurrent, False)

                        self.RefreshLine(oldCurrent)

                    self.RefreshLine(self._current)

            else: # unfocus

                # don't do anything if this item is not focused
                if item == self._current:

                    self.ResetCurrent()

                    if self.IsSingleSel():

                        # we must unselect the old current item as well or we
                        # might end up with more than one selected item in a
                        # single selection control
                        self.HighlightLine(oldCurrent, False)

                    self.RefreshLine(oldCurrent)

        # do we need to change the selection state?
        if stateMask & ULC_STATE_SELECTED:

            on = (state & ULC_STATE_SELECTED) != 0

            if self.IsSingleSel():

                if on:

                    # selecting the item also makes it the focused one in the
                    # single sel mode
                    if self._current != item:

                        self.ChangeCurrent(item)

                        if oldCurrent != - 1:

                            self.HighlightLine(oldCurrent, False)
                            self.RefreshLine(oldCurrent)

                else: # off

                    # only the current item may be selected anyhow
                    if item != self._current:
                        return

            if self.HighlightLine(item, on):
                self.RefreshLine(item)


    def GetItemState(self, item, stateMask):
        """
        Returns the item state flags for the input item.

        :param `item`: the index of the item;
        :param `stateMask`: the bitmask for the state flag.
        
        :see: :meth:`~UltimateListMainWindow.SetItemStateAll` for a list of valid state flags.
        """

        if item < 0 or item >= self.GetItemCount():
            raise Exception("invalid item index in GetItemState")

        ret = ULC_STATE_DONTCARE

        if stateMask & ULC_STATE_FOCUSED:
            if item == self._current:
                ret |= ULC_STATE_FOCUSED

        if stateMask & ULC_STATE_SELECTED:
            if self.IsHighlighted(item):
                ret |= ULC_STATE_SELECTED

        return ret


    def GetItem(self, item, col=0):
        """
        Returns the information about the input item.

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `col`: the column to which the item belongs to.
        """

        if item._itemId < 0 or item._itemId >= self.GetItemCount():
            raise Exception("invalid item index in GetItem")

        line = self.GetLine(item._itemId)
        item = line.GetItem(col, item)
        
        # Get item state if user wants it
        if item._mask & ULC_MASK_STATE:
            item._state = self.GetItemState(item._itemId, ULC_STATE_SELECTED | ULC_STATE_FOCUSED)

        return item


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `checked`: ``True`` to check an item, ``False`` to uncheck it;
        :param `sendEvent`: ``True`` to send a {UltimateListEvent}, ``False`` otherwise.

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

        # Should we raise an error here?!?        
        if item.GetKind() == 0 or not item.IsEnabled():
            return

        if sendEvent:
            
            parent = self.GetParent()
            le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKING, parent.GetId())
            le.m_itemIndex = item._itemId
            le.m_item = item
            le.SetEventObject(parent)
            
            if parent.GetEventHandler().ProcessEvent(le):
                # Blocked by user
                return 
        
        item.Check(checked)
        self.SetItem(item)
        self.RefreshLine(item._itemId)

        if not sendEvent:
            return
        
        le = UltimateListEvent(wxEVT_COMMAND_LIST_ITEM_CHECKED, parent.GetId())
        le.m_itemIndex = item._itemId
        le.m_item = item
        le.SetEventObject(parent)
        parent.GetEventHandler().ProcessEvent(le)


    def AutoCheckChild(self, isChecked, column):
        """
        Checks/unchecks all the items.

        :param `isChecked`: ``True`` to check the items, ``False`` to uncheck them;
        :param `column`: the column to which the items belongs to.

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

        for indx in xrange(self.GetItemCount()):
            item = CreateListItem(indx, column)
            newItem = self.GetItem(item, column)
            self.CheckItem(newItem, not isChecked, False)
        

    def AutoToggleChild(self, column):
        """
        Toggles all the items.

        :param `column`: the column to which the items belongs to.

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

        for indx in xrange(self.GetItemCount()):
            item = CreateListItem(indx, column)
            newItem = self.GetItem(item, column)

            if newItem.GetKind() != 1:
                continue
            
            self.CheckItem(newItem, not item.IsChecked(), False)


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

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

        item = self.GetItem(item, item._col)
        return item.IsChecked()


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

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

        item = self.GetItem(item, item._col)
        return item.IsEnabled()


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `enable`: ``True`` to enable the item, ``False`` otherwise.
        """

        item = self.GetItem(item, 0)
        if item.IsEnabled() == enable:
            return False

        item.Enable(enable)

        wnd = item.GetWindow()
        # Handles the eventual window associated to the item        
        if wnd:
            wnd.Enable(enable)
        
        self.SetItem(item)

        return True
    
                
    def GetItemKind(self, item):
        """
        Returns the item kind.

        :param `item`: an instance of :class:`UltimateListItem`.

        :see: :meth:`~UltimateListMainWindow.SetItemKind` for a list of valid item kinds.
        """

        item = self.GetItem(item, item._col)
        return item.GetKind()
                

    def SetItemKind(self, item, kind):
        """
        Sets the item kind.

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = self.GetItem(item, item._col)
        item.SetKind(kind)
        self.SetItem(item)

        return True
    

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

        :param `item`: an instance of :class:`UltimateListItem`.
        """
        
        item = self.GetItem(item, item._col)
        return item.IsHyperText()


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """

        item = self.GetItem(item, item._col)
        item.SetHyperText(hyper)
        self.SetItem(item)

        return True
    

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

        return self._hypertextfont        


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

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

        self._hypertextfont = font
        self._dirty = True
        

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

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

        self._hypertextnewcolour = colour
        self._dirty = True


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

        return self._hypertextnewcolour


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

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

        self._hypertextvisitedcolour = colour
        self._dirty = True


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

        return self._hypertextvisitedcolour


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
        """

        newItem = self.GetItem(item, item._col)
        newItem.SetVisited(visited)
        self.SetItem(newItem)
        self.RefreshLine(item)

        return True


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

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

        item = self.GetItem(item, item._col)
        return item.GetVisited()


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

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

        item = self.GetItem(item, item._col)
        return item.GetWindow()


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `wnd`: if not ``None``, a non-toplevel window to be displayed next to
         the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.
        """

        if not self.InReportView() or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("Widgets are only allowed in report mode and with the ULC_HAS_VARIABLE_ROW_HEIGHT style.")
        
        item = self.GetItem(item, item._col)

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

        item.SetWindow(wnd, expand)
        self.SetItem(item)
        self.RecalculatePositions()
        self.Refresh()
       

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

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

        if item.GetWindow() is None:
            return

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

        self.SetItem(item)
        self.RecalculatePositions()
        

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

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

        item = self.GetItem(item, item._col)
        return item.GetWindowEnabled()


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

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `enable`: ``True`` to enable the associated window, ``False`` to
         disable it.
        """

        item = self.GetItem(item, item._col)
        item.SetWindowEnabled(enable)
        self.SetItem(item)
        self.Refresh()

        
    def SetColumnCustomRenderer(self, col=0, renderer=None):
        """
        Associate a custom renderer to this column's header

        :param `col`: the column index.
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`. 
        """

        self._columns[col].SetCustomRenderer(renderer)


    def GetColumnCustomRenderer(self, col):
        """
        Returns the custom renderer used to draw the column header

        :param `col`: the column index.
        """

        return self._columns[col].GetCustomRenderer()


    def GetItemCustomRenderer(self, item):
        """
        Returns the custom renderer used to draw the input item (if any).

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

        item = self.GetItem(item, item._col)
        return item.GetCustomRenderer()


    def SetItemCustomRenderer(self, item, renderer=None):
        """
        Associate a custom renderer to this item.

        :param `item`: an instance of :class:`UltimateListItem`;
        :param `renderer`: a class able to correctly render the item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`. 
        """

        item = self.GetItem(item, item._col)
        item.SetCustomRenderer(renderer)
        self.SetItem(item)
        self.ResetLineDimensions()
        self.Refresh()


    def GetItemOverFlow(self, item):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

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

        item = self.GetItem(item, item._col)
        return item.GetOverFlow()


    def SetItemOverFlow(self, item, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        
        :param `item`: an instance of :class:`UltimateListItem`;
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.        
        """

        item = self.GetItem(item, item._col)
        item.SetOverFlow(over)
        self.SetItem(item)
        self.Refresh()


# ----------------------------------------------------------------------------
# item count
# ----------------------------------------------------------------------------

    def GetItemCount(self):
        """ Returns the number of items in the :class:`UltimateListCtrl`. """
        
        return (self.IsVirtual() and [self._countVirt] or [len(self._lines)])[0]


    def SetItemCount(self, count):
        """
        This method can only be used with virtual :class:`UltimateListCtrl`. It is used to
        indicate to the control the number of items it contains. After calling it,
        the main program should be ready to handle calls to various item callbacks
        (such as :meth:`UltimateListCtrl.OnGetItemText() <UltimateListCtrl.OnGetItemText>`) for all items in the range from 0 to `count`.

        :param `count`: the total number of items in :class:`UltimateListCtrl`.        
        """
        
        self._selStore.SetItemCount(count)
        self._countVirt = count

        self.ResetVisibleLinesRange()

        # scrollbars must be reset
        self._dirty = True


    def GetSelectedItemCount(self):
        """ Returns the number of selected items in :class:`UltimateListCtrl`. """

        # deal with the quick case first
        if self.IsSingleSel():
            return (self.HasCurrent() and [self.IsHighlighted(self._current)] or [False])[0]

        # virtual controls remmebers all its selections itself
        if self.IsVirtual():
            return self._selStore.GetSelectedCount()

        # TODO: we probably should maintain the number of items selected even for
        #       non virtual controls as enumerating all lines is really slow...
        countSel = 0
        count = self.GetItemCount()
        for line in xrange(count):
            if self.GetLine(line).IsHighlighted():
                countSel += 1

        return countSel


# ----------------------------------------------------------------------------
# item position/size
# ----------------------------------------------------------------------------

    def GetViewRect(self):
        """
        Returns the rectangle taken by all items in the control. In other words,
        if the controls client size were equal to the size of this rectangle, no
        scrollbars would be needed and no free space would be left.

        :note: This function only works in the icon and small icon views, not in
         list or report views.
        """
        
        if self.HasAGWFlag(ULC_LIST):
            raise Exception("UltimateListCtrl.GetViewRect() not implemented for list view")

        # we need to find the longest/tallest label
        xMax = yMax = 0
        count = self.GetItemCount()
        
        if count:
            for i in xrange(count):
                # we need logical, not physical, coordinates here, so use
                # GetLineRect() instead of GetItemRect()
                r = self.GetLineRect(i)
                x, y = r.GetRight(), r.GetBottom()

                if x > xMax:
                    xMax = x
                if y > yMax:
                    yMax = y

        # some fudge needed to make it look prettier
        xMax += 2*EXTRA_BORDER_X
        yMax += 2*EXTRA_BORDER_Y

        # account for the scrollbars if necessary
        sizeAll = self.GetClientSize()
        if xMax > sizeAll.x:
            yMax += wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
        if yMax > sizeAll.y:
            xMax += wx.SystemSettings.GetMetric(wx.SYS_VSCROLL_X)

        return wx.Rect(0, 0, xMax, yMax)


    def GetSubItemRect(self, item, subItem):
        """
        Returns the rectangle representing the size and position, in physical coordinates,
        of the given subitem, i.e. the part of the row `item` in the column `subItem`.

        :param `item`: the row in which the item lives;
        :param `subItem`: the column in which the item lives. If set equal to the special
         value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
         :meth:`~UltimateListMainWindow.GetItemRect`.
        
        :note: This method is only meaningful when the :class:`UltimateListCtrl` is in the
         report mode.        
        """

        if not self.InReportView() and subItem == ULC_GETSUBITEMRECT_WHOLEITEM:
            raise Exception("GetSubItemRect only meaningful in report view")

        if item < 0 or item >= self.GetItemCount():
            raise Exception("invalid item in GetSubItemRect")

        # ensure that we're laid out, otherwise we could return nonsense
        if self._dirty:
            self.RecalculatePositions(True)
            
        rect = self.GetLineRect(item)

        # Adjust rect to specified column
        if subItem != ULC_GETSUBITEMRECT_WHOLEITEM:
            if subItem < 0 or subItem >= self.GetColumnCount():
                raise Exception("invalid subItem in GetSubItemRect")

            for i in xrange(subItem):
                rect.x += self.GetColumnWidth(i)

            rect.width = self.GetColumnWidth(subItem)

        rect.x, rect.y = self.CalcScrolledPosition(rect.x, rect.y)
        return rect

        
    def GetItemRect(self, item):
        """
        Returns the rectangle representing the item's size and position, in physical
        coordinates.

        :param `item`: the row in which the item lives.
        """
        
        return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM)
    

    def GetItemPosition(self, item):
        """
        Returns the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives.
        """
        
        rect = self.GetItemRect(item)
        return wx.Point(rect.x, rect.y)


# ----------------------------------------------------------------------------
# geometry calculation
# ----------------------------------------------------------------------------

    def RecalculatePositions(self, noRefresh=False):
        """
        Recalculates all the items positions, and sets the scrollbars positions
        too.

        :param `noRefresh`: ``True`` to avoid calling `Refresh`, ``False`` otherwise.
        """

        count = self.GetItemCount()

        if self.HasAGWFlag(ULC_ICON) and self._normal_image_list:
            iconSpacing = self._normal_spacing
        elif self.HasAGWFlag(ULC_SMALL_ICON) and self._small_image_list:
            iconSpacing = self._small_spacing
        else:
            iconSpacing = 0

        # Note that we do not call GetClientSize() here but
        # GetSize() and subtract the border size for sunken
        # borders manually. This is technically incorrect,
        # but we need to know the client area's size WITHOUT
        # scrollbars here. Since we don't know if there are
        # any scrollbars, we use GetSize() instead. Another
        # solution would be to call SetScrollbars() here to
        # remove the scrollbars and call GetClientSize() then,
        # but this might result in flicker and - worse - will
        # reset the scrollbars to 0 which is not good at all
        # if you resize a dialog/window, but don't want to
        # reset the window scrolling. RR.
        # Furthermore, we actually do NOT subtract the border
        # width as 2 pixels is just the extra space which we
        # need around the actual content in the window. Other-
        # wise the text would e.g. touch the upper border. RR.
        clientWidth, clientHeight = self.GetSize()

        if self.InReportView():

            self.ResetVisibleLinesRange()
            
            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                # all lines have the same height and we scroll one line per step

                lineHeight = self.GetLineHeight()
                entireHeight = count*lineHeight + LINE_SPACING
                decrement = 0
                if entireHeight > self.GetClientSize()[1]:
                    decrement = SCROLL_UNIT_X

                self._linesPerPage = clientHeight/lineHeight

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
                                   (entireHeight + lineHeight - 1)/lineHeight,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

            else:

                if count > 0:
                    entireHeight = self.GetLineY(count-1) + self.GetLineHeight(count-1) + LINE_SPACING
                    lineFrom, lineTo = self.GetVisibleLinesRange()
                    self._linesPerPage = lineTo - lineFrom + 1
                else:
                    lineHeight = self.GetLineHeight()
                    entireHeight = count*lineHeight + LINE_SPACING
                    self._linesPerPage = clientHeight/lineHeight

                decrement = 0
                if entireHeight > self.GetClientSize()[1]:
                    decrement = SCROLL_UNIT_X
                    
                self.SetScrollbars(SCROLL_UNIT_X, SCROLL_UNIT_Y,
                                   (self.GetHeaderWidth()-decrement)/SCROLL_UNIT_X,
                                   (entireHeight + SCROLL_UNIT_Y - 1)/SCROLL_UNIT_Y,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

        else: # !report

            dc = wx.ClientDC(self)
            dc.SetFont(self.GetFont())

            lineHeight = self.GetLineHeight()

            # we have 3 different layout strategies: either layout all items
            # horizontally/vertically (ULC_ALIGN_XXX styles explicitly given) or
            # to arrange them in top to bottom, left to right (don't ask me why
            # not the other way round...) order
            if self.HasAGWFlag(ULC_ALIGN_LEFT | ULC_ALIGN_TOP):
                
                x = EXTRA_BORDER_X
                y = EXTRA_BORDER_Y
                widthMax = 0

                for i in xrange(count):

                    line = self.GetLine(i)
                    line.CalculateSize(dc, iconSpacing)
                    line.SetPosition(x, y, iconSpacing)

                    sizeLine = self.GetLineSize(i)

                    if self.HasAGWFlag(ULC_ALIGN_TOP):

                        if sizeLine.x > widthMax:
                            widthMax = sizeLine.x

                        y += sizeLine.y

                    else: # ULC_ALIGN_LEFT

                        x += sizeLine.x + MARGIN_BETWEEN_ROWS

                if self.HasAGWFlag(ULC_ALIGN_TOP):

                    # traverse the items again and tweak their sizes so that they are
                    # all the same in a row
                    for i in xrange(count):

                        line = self.GetLine(i)
                        line._gi.ExtendWidth(widthMax)

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (x + SCROLL_UNIT_X)/SCROLL_UNIT_X,
                                   (y + lineHeight)/lineHeight,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   self.GetScrollPos(wx.VERTICAL),
                                   True)

            else: # "flowed" arrangement, the most complicated case

                # at first we try without any scrollbars, if the items don't fit into
                # the window, we recalculate after subtracting the space taken by the
                # scrollbar

                entireWidth = 0

                for tries in xrange(2):

                    entireWidth = 2*EXTRA_BORDER_X

                    if tries == 1:

                        # Now we have decided that the items do not fit into the
                        # client area, so we need a scrollbar
                        entireWidth += SCROLL_UNIT_X

                    x = EXTRA_BORDER_X
                    y = EXTRA_BORDER_Y
                    maxWidthInThisRow = 0

                    self._linesPerPage = 0
                    currentlyVisibleLines = 0

                    for i in xrange(count):

                        currentlyVisibleLines += 1
                        line = self.GetLine(i)
                        line.CalculateSize(dc, iconSpacing)
                        line.SetPosition(x, y, iconSpacing)

                        sizeLine = self.GetLineSize(i)

                        if maxWidthInThisRow < sizeLine.x:
                            maxWidthInThisRow = sizeLine.x

                        y += sizeLine.y
                        if currentlyVisibleLines > self._linesPerPage:
                            self._linesPerPage = currentlyVisibleLines

                        if y + sizeLine.y >= clientHeight:

                            currentlyVisibleLines = 0
                            y = EXTRA_BORDER_Y
                            maxWidthInThisRow += MARGIN_BETWEEN_ROWS
                            x += maxWidthInThisRow
                            entireWidth += maxWidthInThisRow
                            maxWidthInThisRow = 0

                        # We have reached the last item.
                        if i == count - 1:
                            entireWidth += maxWidthInThisRow

                        if tries == 0 and entireWidth + SCROLL_UNIT_X > clientWidth:
                            clientHeight -= wx.SystemSettings.GetMetric(wx.SYS_HSCROLL_Y)
                            self._linesPerPage = 0
                            break

                        if i == count - 1:
                            break  # Everything fits, no second try required.

                self.SetScrollbars(SCROLL_UNIT_X, lineHeight,
                                   (entireWidth + SCROLL_UNIT_X)/SCROLL_UNIT_X,
                                   0,
                                   self.GetScrollPos(wx.HORIZONTAL),
                                   0,
                                   True)

        self._dirty = False
        if not noRefresh:
            self.RefreshAll()


    def RefreshAll(self):
        """ Refreshes the entire :class:`UltimateListCtrl`. """

        self._dirty = False
        self.Refresh()

        headerWin = self.GetListCtrl()._headerWin
        if headerWin and headerWin._dirty:
            headerWin._dirty = False
            headerWin.Refresh()


    def UpdateCurrent(self):
        """ Updates the current line selection. """

        if not self.HasCurrent() and not self.IsEmpty():
            self.ChangeCurrent(0)


    def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
        """
        Searches for an item with the given `geometry` or `state`, starting from `item`
        but excluding the `item` itself.

        :param `item`: the item at which starting the search. If set to -1, the first
         item that matches the specified flags will be returned.
        :param `geometry`: can be one of:

         =================== ========= =================================
         Geometry Flag       Hex Value Description
         =================== ========= =================================
         ``ULC_NEXT_ABOVE``        0x0 Searches for an item above the specified item
         ``ULC_NEXT_ALL``          0x1 Searches for subsequent item by index
         ``ULC_NEXT_BELOW``        0x2 Searches for an item below the specified item
         ``ULC_NEXT_LEFT``         0x3 Searches for an item to the left of the specified item
         ``ULC_NEXT_RIGHT``        0x4 Searches for an item to the right of the specified item
         =================== ========= =================================
        
        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================


        :return: The first item with given `state` following `item` or -1 if no such item found.

        :note: This function may be used to find all selected items in the
         control like this::
              
             item = -1
                        
             while 1:
                 item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)
                   
                 if item == -1:
                     break
                
                 # This item is selected - do whatever is needed with it

                 wx.LogMessage("Item %ld is selected."%item)

                  
        """

        ret = item
        maxI = self.GetItemCount()

        # notice that we start with the next item (or the first one if item == -1)
        # and this is intentional to allow writing a simple loop to iterate over
        # all selected items
        ret += 1
        
        if ret == maxI:
            # this is not an error because the index was ok initially, just no
            # such item
            return -1

        if not state:
            # any will do
            return ret

        for line in xrange(ret, maxI):
            if state & ULC_STATE_FOCUSED and line == self._current:
                return line

            if state & ULC_STATE_SELECTED and self.IsHighlighted(line):
                return line

        return -1


# ----------------------------------------------------------------------------
# deleting stuff
# ----------------------------------------------------------------------------

    def DeleteItem(self, lindex):
        """
        Deletes the specified item.

        :param `lindex`: the index of the item to delete.
        
        :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
         being deleted.
        """

        count = self.GetItemCount()
        if lindex < 0 or lindex >= self.GetItemCount():
            raise Exception("invalid item index in DeleteItem")

        # we don't need to adjust the index for the previous items
        if self.HasCurrent() and self._current >= lindex:

            # if the current item is being deleted, we want the next one to
            # become selected - unless there is no next one - so don't adjust
            # self._current in this case
            if self._current != lindex or self._current == count - 1:
                self._current -= 1

        if self.InReportView():

            #  mark the Column Max Width cache as dirty if the items in the line
            #  we're deleting contain the Max Column Width
            line = self.GetLine(lindex)
            item = UltimateListItem()
            
            for i in xrange(len(self._columns)):
                itemData = line._items[i]
                item = itemData.GetItem(item)
                itemWidth = self.GetItemWidthWithImage(item)

                if itemWidth >= self._aColWidths[i]._nMaxWidth:
                    self._aColWidths[i]._bNeedsUpdate = True

                if item.GetWindow():
                    self.DeleteItemWindow(item)

            self.ResetVisibleLinesRange(True)
            self._current = -1

        self.SendNotify(lindex, wxEVT_COMMAND_LIST_DELETE_ITEM)
        
        if self.IsVirtual():
            self._countVirt -= 1
            self._selStore.OnItemDelete(lindex)

        else:
            self._lines.pop(lindex)

        # we need to refresh the (vert) scrollbar as the number of items changed
        self._dirty = True        
        self._lineHeight = 0
        self.ResetLineDimensions(True)
        self.RecalculatePositions()
        self.RefreshAfter(lindex)


    def DeleteColumn(self, col):
        """
        Deletes the specified column.

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

        self._columns.pop(col)
        self._dirty = True

        if not self.IsVirtual():
            # update all the items
            for i in xrange(len(self._lines)):
                line = self.GetLine(i)
                line._items.pop(col)

        if self.InReportView():   #  we only cache max widths when in Report View
            self._aColWidths.pop(col)
            
        # invalidate it as it has to be recalculated
        self._headerWidth = 0


    def DoDeleteAllItems(self):
        """ Actually performs the deletion of all the items. """
        
        if self.IsEmpty():
            # nothing to do - in particular, don't send the event
            return

        self.ResetCurrent()

        # to make the deletion of all items faster, we don't send the
        # notifications for each item deletion in this case but only one event
        # for all of them: this is compatible with wxMSW and documented in
        # DeleteAllItems() description

        event = UltimateListEvent(wxEVT_COMMAND_LIST_DELETE_ALL_ITEMS, self.GetParent().GetId())
        event.SetEventObject(self.GetParent())
        self.GetParent().GetEventHandler().ProcessEvent(event)

        if self.IsVirtual():
            self._countVirt = 0
            self._selStore.Clear()

        if self.InReportView():
            self.ResetVisibleLinesRange(True)
            for i in xrange(len(self._aColWidths)):
                self._aColWidths[i]._bNeedsUpdate = True

        for item in self._itemWithWindow[:]:
            if item.GetWindow():
                self.DeleteItemWindow(item)

        self._lines = []
        self._itemWithWindow = []
        self._hasWindows = False


    def DeleteAllItems(self):
        """
        Deletes all items in the :class:`UltimateListCtrl`.

        :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
         deleting many items from the control would be too slow then (unlike :meth:`~UltimateListMainWindow.DeleteItem`).
        """
        
        self.DoDeleteAllItems()
        self.RecalculatePositions()


    def DeleteEverything(self):
        """ Deletes all items in the :class:`UltimateListCtrl`, resetting column widths to zero. """
        
        self.DeleteAllItems()

        count = len(self._columns)
        for n in xrange(count):
            self.DeleteColumn(0)
        
        self.RecalculatePositions()
        self.GetListCtrl().Refresh()


# ----------------------------------------------------------------------------
# scanning for an item
# ----------------------------------------------------------------------------

    def EnsureVisible(self, index):
        """
        Ensures this item is visible.

        :param `index`: the index of the item to scroll into view.
        """

        if index < 0 or index >= self.GetItemCount():
            raise Exception("invalid item index in EnsureVisible")

        # We have to call this here because the label in question might just have
        # been added and its position is not known yet
        if self._dirty:
            self.RecalculatePositions(True)

        self.MoveToItem(index)


    def FindItem(self, start, string, partial=False):
        """
        Find an item whose label matches this string.

        :param `start`: the starting point of the input `string` or the beginning
         if `start` is -1;
        :param `string`: the string to look for matches;
        :param `partial`: if ``True`` then this method will look for items which
         begin with `string`.

        :note: The string comparison is case insensitive.         
        """
        
        if start < 0:
            start = 0

        str_upper = string.upper()
        count = self.GetItemCount()

        for i in xrange(start, count):
            line = self.GetLine(i)
            text = line.GetText(0)
            line_upper = text.upper()
            if not partial:
                if line_upper == str_upper:
                    return i
            else:
                if line_upper.find(str_upper) == 0:
                    return i

        return wx.NOT_FOUND


    def FindItemData(self, start, data):
        """
        Find an item whose data matches this data.

        :param `start`: the starting point of the input `data` or the beginning
         if `start` is -1;
        :param `data`: the data to look for matches.
        """
        
        if start < 0:
            start = 0

        count = self.GetItemCount()
        
        for i in xrange(start, count):
            line = self.GetLine(i)
            item = UltimateListItem()
            item = line.GetItem(0, item)
            
            if item._data == data:
                return i

        return wx.NOT_FOUND


    def FindItemAtPos(self, pt):
        """
        Find an item nearest this position.

        :param `pt`: an instance of :class:`Point`.        
        """
        
        topItem, dummy = self.GetVisibleLinesRange()
        p = self.GetItemPosition(self.GetItemCount()-1)
        
        if p.y == 0:
            return topItem

        id = int(math.floor(pt.y*float(self.GetItemCount()-topItem-1)/p.y+topItem))
        
        if id >= 0 and id < self.GetItemCount():
            return id

        return wx.NOT_FOUND


    def HitTest(self, x, y):
        """
        HitTest method for a :class:`UltimateListCtrl`.

        :param `x`: the mouse `x` position;
        :param `y`: the mouse `y` position.

        :see: :meth:`~UltimateListMainWindow.HitTestLine` for a list of return flags.        
        """
        
        x, y = self.CalcUnscrolledPosition(x, y)
        count = self.GetItemCount()

        if self.InReportView():
            if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
                current = y/self.GetLineHeight()
                if current < count:
                    newItem, flags = self.HitTestLine(current, x, y)
                    if flags:
                        return current, flags
            else:
                for current in xrange(self._lineFrom, count):
                    newItem, flags = self.HitTestLine(current, x, y)
                    if flags:
                        return current, flags
            
        else:
            # TODO: optimize it too! this is less simple than for report view but
            #       enumerating all items is still not a way to do it!!
            for current in xrange(count):
                newItem, flags = self.HitTestLine(current, x, y)
                if flags:
                    return current, flags

        return wx.NOT_FOUND, None


# ----------------------------------------------------------------------------
# adding stuff
# ----------------------------------------------------------------------------

    def InsertItem(self, item):
        """
        Inserts an item into :class:`UltimateListCtrl`.

        :param `item`: an instance of :class:`UltimateListItem`.
        """
        
        if self.IsVirtual():
            raise Exception("can't be used with virtual control")

        count = self.GetItemCount()
        if item._itemId < 0:
            raise Exception("invalid item index")

        CheckVariableRowHeight(self, item._text)
            
        if item._itemId > count:
            item._itemId = count

        id = item._itemId
        self._dirty = True

        if self.InReportView():
            self.ResetVisibleLinesRange(True)

            # calculate the width of the item and adjust the max column width
            pWidthInfo = self._aColWidths[item.GetColumn()]
            width = self.GetItemWidthWithImage(item)
            item.SetWidth(width)
            
            if width > pWidthInfo._nMaxWidth:
                pWidthInfo._nMaxWidth = width

        line = UltimateListLineData(self)
        line.SetItem(item._col, item)

        self._lines.insert(id, line)
        self._dirty = True

        # If an item is selected at or below the point of insertion, we need to
        # increment the member variables because the current row's index has gone
        # up by one
        if self.HasCurrent() and self._current >= id:
            self._current += 1

        self.SendNotify(id, wxEVT_COMMAND_LIST_INSERT_ITEM)
        self.RefreshLines(id, self.GetItemCount() - 1)


    def InsertColumn(self, col, item):
        """
        Inserts a column into :class:`UltimateListCtrl`.

        :param `col`: the column index at which we wish to insert a new column;
        :param `item`: an instance of :class:`UltimateListItem`.

        :return: the index at which the column has been inserted.
        
        :note: This method is meaningful only if :class:`UltimateListCtrl` has the ``ULC_REPORT``
         or the ``ULC_TILE`` styles set.
        """

        self._dirty = True

        if self.InReportView() or self.InTileView() or self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS):

            if item._width == ULC_AUTOSIZE_USEHEADER:
                item._width = self.GetTextLength(item._text)

            column = UltimateListHeaderData(item)
            colWidthInfo = ColWidthInfo()

            insert = (col >= 0) and (col < len(self._columns))
                
            if insert:
                self._columns.insert(col, column)
                self._aColWidths.insert(col, colWidthInfo)
                idx = col

            else:

                self._columns.append(column)
                self._aColWidths.append(colWidthInfo)
                idx = len(self._columns)-1

            if not self.IsVirtual():

                # update all the items
                for i in xrange(len(self._lines)):
                    line = self.GetLine(i)
                    data = UltimateListItemData(self)
                    if insert:
                        line._items.insert(col, data)
                    else:
                        line._items.append(data)

            # invalidate it as it has to be recalculated
            self._headerWidth = 0
            return idx


    def GetItemWidthWithImage(self, item):
        """
        Returns the item width, in pixels, considering the item text and its images.

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

        if item.GetCustomRenderer():
            return item.GetCustomRenderer().GetSubItemWidth()

        width = 0
        dc = wx.ClientDC(self)

        if item.GetFont().IsOk():
            font = item.GetFont()
        else:
            font = self.GetFont()
            
        dc.SetFont(font)

        if item.GetKind() in [1, 2]:
            ix, iy = self.GetCheckboxImageSize()
            width += ix

        if item.GetImage():
            ix, iy = self.GetImageSize(item.GetImage())
            width += ix + IMAGE_MARGIN_IN_REPORT_MODE

        if item.GetText():
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText())
            width += w

        if item.GetWindow():
            width += item._windowsize.x + 5

        return width


    def GetItemTextSize(self, item):
        """
        Returns the item width, in pixels, considering only the item text.

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

        width = ix = iy = start = end = 0
        dc = wx.ClientDC(self)

        if item.HasFont():
            font = item.GetFont()
        else:
            font = self.GetFont()
            
        dc.SetFont(font)

        if item.GetKind() in [1, 2]:
            ix, iy = self.GetCheckboxImageSize()
            start += ix

        if item.GetImage():
            ix, iy = self.GetImageSize(item.GetImage())
            start += ix + IMAGE_MARGIN_IN_REPORT_MODE

        if item.GetText():
            w, h, dummy = dc.GetMultiLineTextExtent(item.GetText())
            end = w

        return start, end


# ----------------------------------------------------------------------------
# sorting
# ----------------------------------------------------------------------------

    def OnCompareItems(self, line1, line2):
        """
        Returns whether 2 lines have the same index.
        
        Override this function in the derived class to change the sort order of the items
        in the :class:`UltimateListCtrl`. The function should return a negative, zero or positive
        value if the first line is less than, equal to or greater than the second one.

        :param `line1`: an instance of :class:`UltimateListItem`;
        :param `line2`: another instance of :class:`UltimateListItem`.

        :note: The base class version compares lines by their index.
        """

        item = UltimateListItem()
        item1 = line1.GetItem(0, item)
        item = UltimateListItem()
        item2 = line2.GetItem(0, item)
        
        data1 = item1._data
        data2 = item2._data

        if self.__func:
            return self.__func(data1, data2)
        else:
            return cmp(data1, data2)


    def SortItems(self, func):
        """
        Call this function to sort the items in the :class:`UltimateListCtrl`. Sorting is done
        using the specified function `func`. This function must have the
        following prototype::

            def OnCompareItems(self, line1, line2):

                DoSomething(line1, line2)
                # function code            


        It is called each time when the two items must be compared and should return 0
        if the items are equal, negative value if the first item is less than the second
        one and positive value if the first one is greater than the second one.

        :param `func`: the method to use to sort the items. The default is to use the
         :meth:`~UltimateListMainWindow.OnCompareItems` method.
        """

        self.HighlightAll(False)
        self.ResetCurrent()

        if self._hasWindows:
            self.HideWindows()

        if not func:
            self.__func = None
        else:
            self.__func = func

        self._lines.sort(self.OnCompareItems)
        
        if self.IsShownOnScreen():
            self._dirty = True
            self._lineHeight = 0
            self.ResetLineDimensions(True)

        self.RecalculatePositions(True)


# ----------------------------------------------------------------------------
# scrolling
# ----------------------------------------------------------------------------

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

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

        event.Skip()

        # update our idea of which lines are shown when we redraw the window the
        # next time
        self.ResetVisibleLinesRange()
        
        if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            wx.CallAfter(self.RecalculatePositions, True)

        if event.GetOrientation() == wx.HORIZONTAL:
            lc = self.GetListCtrl()

            if self.HasHeader():
                lc._headerWin.Refresh()
                lc._headerWin.Update()
                
            if self.HasFooter():
                lc._footerWin.Refresh()
                lc._footerWin.Update()
                
        
    def GetCountPerPage(self):
        """
        Returns the number of items that can fit vertically in the visible area
        of the :class:`UltimateListCtrl` (list or report view) or the total number of
        items in the list control (icon or small icon view).
        """
        
        if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            if not self._linesPerPage:
                self._linesPerPage = self.GetClientSize().y/self.GetLineHeight()

            return self._linesPerPage

        visibleFrom, visibleTo = self.GetVisibleLinesRange()
        self._linesPerPage = visibleTo - visibleFrom + 1
            
        return self._linesPerPage


    def GetVisibleLinesRange(self):
        """
        Returns the range of visible items on screen.

        :note: This method can be used only if :class:`UltimateListCtrl` has the ``ULC_REPORT``
         style set.
        """

        if not self.InReportView():
            raise Exception("this is for report mode only")

        if self._lineFrom == -1:
            
            count = self.GetItemCount()
            
            if count:

                if self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):

                    view_x, view_y = self.GetViewStart()
                    view_y *= SCROLL_UNIT_Y

                    for i in xrange(0, count):
                        rc = self.GetLineY(i)
                        if rc > view_y:
                            self._lineFrom = i - 1
                            break

                    if self._lineFrom < 0:
                        self._lineFrom = 0
                                            
                    self._lineTo = self._lineFrom                        
                    clientWidth, clientHeight = self.GetClientSize()
                    
                    for i in xrange(self._lineFrom, count):
                        rc = self.GetLineY(i) + self.GetLineHeight(i)
                        if rc > view_y + clientHeight - 5:
                            break
                        self._lineTo += 1

                else:
                    
                    # No variable row height
                    self._lineFrom = self.GetScrollPos(wx.VERTICAL)

                    # this may happen if SetScrollbars() hadn't been called yet
                    if self._lineFrom >= count:
                        self._lineFrom = count - 1

                    self._lineTo = self._lineFrom + self._linesPerPage

                # we redraw one extra line but this is needed to make the redrawing
                # logic work when there is a fractional number of lines on screen
                if self._lineTo >= count:
                    self._lineTo = count - 1

            else: # empty control

                self._lineFrom = -1
                self._lineTo = -1

        return self._lineFrom, self._lineTo


    def ResetTextControl(self):
        """ Called by :class:`UltimateListTextCtrl` when it marks itself for deletion."""

        self._textctrl.Destroy()
        self._textctrl = None

        self.RecalculatePositions()
        self.Refresh()


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

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

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

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

        :param `colour`: if not ``None``, a valid :class:`Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the :class:`UltimateListCtrl`
         background colour.
        """

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

        self._secondcolour = colour

        if self._usegradients:
            self.RefreshSelected()


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


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


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

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

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

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

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

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

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

        if self._usegradients:
            self.RefreshSelected()


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

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

        return self._gradientstyle


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

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

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

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


    def SetSelectedTextColour(self, colour=None):
        """
        Sets the colour of text applied to an item when it is selected. 
        If this method is not called, text color of selected items will be
        the system value ``wx.SYS_COLOUR_HIGHLIGHTTEXT``, or the color set on 
        the item with SetTextColour.

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

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

    def GetSelectedTextColour(self):
        """ Returns the colour applied to text when an item is selected. """
        
        return self._highlightedtextcolour


    def SetBackgroundImage(self, image):
        """
        Sets the :class:`UltimateListCtrl` background image.

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

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

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

        self._backgroundImage = image
        self.Refresh()
        

    def GetBackgroundImage(self):
        """
        Returns the :class:`UltimateListCtrl` background image (if any).

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

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

        return self._backgroundImage


    def SetWaterMark(self, watermark):
        """
        Sets the :class:`UltimateListCtrl` watermark image to be displayed in the bottom
        right part of the window.

        :param `watermark`: if not ``None``, an instance of :class:`Bitmap`.

        .. todo:: Better support for this is needed.        
        """        

        self._waterMark = watermark
        self.Refresh()
        

    def GetWaterMark(self):
        """
        Returns the :class:`UltimateListCtrl` watermark image (if any), displayed in the
        bottom right part of the window.

        .. todo:: Better support for this is needed.        
        """

        return self._waterMark
    

    def SetDisabledTextColour(self, colour):
        """
        Sets the items disabled colour.

        :param `colour`: an instance of :class:`Colour`.
        """
        
        # Disabled items colour        
        self._disabledColour = colour
        self.Refresh()


    def GetDisabledTextColour(self):
        """ Returns the items disabled colour. """

        return self._disabledColour


    def ScrollList(self, dx, dy):
        """
        Scrolls the :class:`UltimateListCtrl`.

        :param `dx`: if in icon, small icon or report view mode, specifies the number
         of pixels to scroll. If in list view mode, `dx` specifies the number of
         columns to scroll.
        :param `dy`: always specifies the number of pixels to scroll vertically.
        """

        if not self.InReportView():
            # TODO: this should work in all views but is not implemented now
            return False

        top, bottom = self.GetVisibleLinesRange()

        if bottom == -1:
            return 0

        self.ResetVisibleLinesRange()

        if not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            hLine = self.GetLineHeight()
            self.Scroll(-1, top + dy/hLine)
        else:
            self.Scroll(-1, top + dy/SCROLL_UNIT_Y)

        if wx.Platform == "__WXMAC__":
            # see comment in MoveToItem() for why we do this
            self.ResetVisibleLinesRange()

        return True
    
# -------------------------------------------------------------------------------------
# UltimateListCtrl
# -------------------------------------------------------------------------------------

class UltimateListCtrl(wx.PyControl):
    """
    UltimateListCtrl is a class that mimics the behaviour of :class:`ListCtrl`, 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 list control.
    """

    def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition, size=wx.DefaultSize,
                 style=0, agwStyle=0, validator=wx.DefaultValidator, name="UltimateListCtrl"):
        """
        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:`PyControl` window style;
        :param `agwStyle`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================

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

        self._imageListNormal = None
        self._imageListSmall = None
        self._imageListState = None

        if not agwStyle & ULC_MASK_TYPE:
            raise Exception("UltimateListCtrl style should have exactly one mode bit set")

        if not (agwStyle & ULC_REPORT) and agwStyle & ULC_HAS_VARIABLE_ROW_HEIGHT:
            raise Exception("Style ULC_HAS_VARIABLE_ROW_HEIGHT can only be used in report, non-virtual mode")

        if agwStyle & ULC_STICKY_HIGHLIGHT and agwStyle & ULC_TRACK_SELECT:
            raise Exception("Styles ULC_STICKY_HIGHLIGHT and ULC_TRACK_SELECT can not be combined")

        if agwStyle & ULC_NO_HEADER and agwStyle & ULC_HEADER_IN_ALL_VIEWS:
            raise Exception("Styles ULC_NO_HEADER and ULC_HEADER_IN_ALL_VIEWS can not be combined")

        if agwStyle & ULC_USER_ROW_HEIGHT and (agwStyle & ULC_REPORT) == 0:
            raise Exception("Style ULC_USER_ROW_HEIGHT can be used only with ULC_REPORT")
        
        wx.PyControl.__init__(self, parent, id, pos, size, style|wx.CLIP_CHILDREN, validator, name)

        self._mainWin = None
        self._headerWin = None
        self._footerWin = None
        
        self._headerHeight = wx.RendererNative.Get().GetHeaderButtonHeight(self)
        self._footerHeight = self._headerHeight

        if wx.Platform == "__WXGTK__":
            style &= ~wx.BORDER_MASK
            style |= wx.BORDER_THEME
        else:
            if style & wx.BORDER_THEME:
                style -= wx.BORDER_THEME

        self._agwStyle = agwStyle
        if style & wx.SUNKEN_BORDER:
            style -= wx.SUNKEN_BORDER
            
        self._mainWin = UltimateListMainWindow(self, wx.ID_ANY, wx.Point(0, 0), wx.DefaultSize, style, agwStyle)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self._mainWin, 1, wx.GROW)
        self.SetSizer(sizer)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        
        self.CreateOrDestroyHeaderWindowAsNeeded()
        self.CreateOrDestroyFooterWindowAsNeeded()

        self.SetInitialSize(size)
        wx.CallAfter(self.Layout)
        

    def CreateOrDestroyHeaderWindowAsNeeded(self):
        """ Creates or destroys the header window depending on the window style flags. """

        needs_header = self.HasHeader()
        has_header = self._headerWin is not None
        
        if needs_header == has_header:
            return

        if needs_header:

            self._headerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
                                                       wx.Point(0, 0),
                                                       wx.DefaultSize,
                                                       wx.TAB_TRAVERSAL, isFooter=False)

            # ----------------------------------------------------
            # How do you translate all this blah-blah to wxPython?
            # ----------------------------------------------------
            #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
            #        wxFont font
            #if wxOSX_USE_ATSU_TEXT
            #        font.MacCreateFromThemeFont( kThemeSmallSystemFont )
            #else
            #        font.MacCreateFromUIFont( kCTFontSystemFontType )
            #endif
            #        m_headerWin->SetFont( font )
            #endif

            self.GetSizer().Prepend(self._headerWin, 0, wx.GROW)

        else:

            self.GetSizer().Detach(self._headerWin)
            self._headerWin.Destroy()
            self._headerWin = None
            

    def CreateOrDestroyFooterWindowAsNeeded(self):
        """ Creates or destroys the footer window depending on the window style flags. """

        needs_footer = self.HasFooter()
        has_footer = self._footerWin is not None
        
        if needs_footer == has_footer:
            return

        if needs_footer:

            self._footerWin = UltimateListHeaderWindow(self, wx.ID_ANY, self._mainWin,
                                                       wx.Point(0, 0),
                                                       wx.DefaultSize,
                                                       wx.TAB_TRAVERSAL, isFooter=True)

            # ----------------------------------------------------
            # How do you translate all this blah-blah to wxPython?
            # ----------------------------------------------------
            #if defined( __WXMAC__ ) && wxOSX_USE_COCOA_OR_CARBON
            #        wxFont font
            #if wxOSX_USE_ATSU_TEXT
            #        font.MacCreateFromThemeFont( kThemeSmallSystemFont )
            #else
            #        font.MacCreateFromUIFont( kCTFontSystemFontType )
            #endif
            #        m_headerWin->SetFont( font )
            #endif

            self.GetSizer().Add(self._footerWin, 0, wx.GROW)

        else:

            self.GetSizer().Detach(self._footerWin)
            self._footerWin.Destroy()
            self._footerWin = None


    def HasHeader(self):
        """ Returns ``True`` if :class:`UltimateListCtrl` has a header window. """

        return self._mainWin.HasHeader()
    

    def HasFooter(self):
        """ Returns ``True`` if :class:`UltimateListCtrl` has a footer window. """

        return self._mainWin.HasFooter()


    def GetDefaultBorder(self):
        """ Returns the default window border. """

        return wx.BORDER_THEME


    def SetSingleStyle(self, style, add=True):
        """
        Adds or removes a single window style.

        :param `style`: can be one of the following bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ===============================  =========== ====================================================================================================
         
        :param `add`: ``True`` to add the window style, ``False`` to remove it.

        :note: The style ``ULC_VIRTUAL`` can not be set/unset after construction.
        """

        if style & ULC_VIRTUAL:
            raise Exception("ULC_VIRTUAL can't be [un]set")
        
        flag = self.GetAGWWindowStyleFlag()

        if add:

            if style & ULC_MASK_TYPE:
                flag &= ~(ULC_MASK_TYPE | ULC_VIRTUAL)
            if style & ULC_MASK_ALIGN:
                flag &= ~ULC_MASK_ALIGN
            if style & ULC_MASK_SORT:
                flag &= ~ULC_MASK_SORT

        if add:
            flag |= style
        else:
            flag &= ~style

        # some styles can be set without recreating everything (as happens in
        # SetAGWWindowStyleFlag() which calls ListMainWindow.DeleteEverything())
        if not style & ~(ULC_HRULES | ULC_VRULES):
            self.Refresh()
            self.SetAGWWindowStyleFlag(self, flag)
        else:
            self.SetAGWWindowStyleFlag(flag)


    def GetAGWWindowStyleFlag(self):
        """
        Returns the :class:`UltimateListCtrl` AGW-specific style flag.
        
        :see: :meth:`~UltimateListCtrl.SetAGWWindowStyleFlag` for a list of possible style flags.
        """
        
        return self._agwStyle
    
    
    def SetAGWWindowStyleFlag(self, style):
        """
        Sets the :class:`UltimateListCtrl` AGW-specific style flag.

        :param `style`: the AGW-specific window style; can be almost any combination of the following
         bits:

         ===============================  =========== ====================================================================================================
         Window Styles                    Hex Value   Description
         ===============================  =========== ====================================================================================================
         ``ULC_VRULES``                           0x1 Draws light vertical rules between rows in report mode.
         ``ULC_HRULES``                           0x2 Draws light horizontal rules between rows in report mode.
         ``ULC_ICON``                             0x4 Large icon view, with optional labels.
         ``ULC_SMALL_ICON``                       0x8 Small icon view, with optional labels.
         ``ULC_LIST``                            0x10 Multicolumn list view, with optional small icons. Columns are computed automatically, i.e. you don't set columns as in ``ULC_REPORT``. In other words, the list wraps, unlike a :class:`ListBox`.
         ``ULC_REPORT``                          0x20 Single or multicolumn report view, with optional header.
         ``ULC_ALIGN_TOP``                       0x40 Icons align to the top. Win32 default, Win32 only.
         ``ULC_ALIGN_LEFT``                      0x80 Icons align to the left.
         ``ULC_AUTOARRANGE``                    0x100 Icons arrange themselves. Win32 only.
         ``ULC_VIRTUAL``                        0x200 The application provides items text on demand. May only be used with ``ULC_REPORT``.
         ``ULC_EDIT_LABELS``                    0x400 Labels are editable: the application will be notified when editing starts.
         ``ULC_NO_HEADER``                      0x800 No header in report mode.
         ``ULC_NO_SORT_HEADER``                0x1000 No Docs.
         ``ULC_SINGLE_SEL``                    0x2000 Single selection (default is multiple).
         ``ULC_SORT_ASCENDING``                0x4000 Sort in ascending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_SORT_DESCENDING``               0x8000 Sort in descending order. (You must still supply a comparison callback in :meth:`ListCtrl.SortItems`.)
         ``ULC_TILE``                         0x10000 Each item appears as a full-sized icon with a label of one or more lines beside it (partially implemented).
         ``ULC_NO_HIGHLIGHT``                 0x20000 No highlight when an item is selected.
         ``ULC_STICKY_HIGHLIGHT``             0x40000 Items are selected by simply hovering on them, with no need to click on them.
         ``ULC_STICKY_NOSELEVENT``            0x80000 Don't send a selection event when using ``ULC_STICKY_HIGHLIGHT`` style.
         ``ULC_SEND_LEFTCLICK``              0x100000 Send a left click event when an item is selected.
         ``ULC_HAS_VARIABLE_ROW_HEIGHT``     0x200000 The list has variable row heights.
         ``ULC_AUTO_CHECK_CHILD``            0x400000 When a column header has a checkbox associated, auto-check all the subitems in that column.
         ``ULC_AUTO_TOGGLE_CHILD``           0x800000 When a column header has a checkbox associated, toggle all the subitems in that column.
         ``ULC_AUTO_CHECK_PARENT``          0x1000000 Only meaningful foe checkbox-type items: when an item is checked/unchecked its column header item is checked/unchecked as well.
         ``ULC_SHOW_TOOLTIPS``              0x2000000 Show tooltips for ellipsized items/subitems (text too long to be shown in the available space) containing the full item/subitem text.
         ``ULC_HOT_TRACKING``               0x4000000 Enable hot tracking of items on mouse motion.
         ``ULC_BORDER_SELECT``              0x8000000 Changes border colour whan an item is selected, instead of highlighting the item.
         ``ULC_TRACK_SELECT``              0x10000000 Enables hot-track selection in a list control. Hot track selection means that an item is automatically selected when the cursor remains over the item for a certain period of time. The delay is retrieved on Windows using the `win32api` call `win32gui.SystemParametersInfo(win32con.SPI_GETMOUSEHOVERTIME)`, and is defaulted to 400ms on other platforms. This style applies to all views of `UltimateListCtrl`.
         ``ULC_HEADER_IN_ALL_VIEWS``       0x20000000 Show column headers in all view modes.
         ``ULC_NO_FULL_ROW_SELECT``        0x40000000 When an item is selected, the only the item in the first column is highlighted.
         ``ULC_FOOTER``                    0x80000000 Show a footer too (only when header is present).
         ``ULC_USER_ROW_HEIGHT``          0x100000000 Allows to set a custom row height (one value for all the items, only in report mode).
         ===============================  =========== ====================================================================================================
         """        

        if style & ULC_HAS_VARIABLE_ROW_HEIGHT and not self.HasAGWFlag(ULC_REPORT):
            raise Exception("ULC_HAS_VARIABLE_ROW_HEIGHT style can be used only in report mode")
        
        wasInReportView = self.HasAGWFlag(ULC_REPORT)
        self._agwStyle = style

        if self._mainWin:

            inReportView = (style & ULC_REPORT) != 0

            if inReportView != wasInReportView:
                # we need to notify the main window about this change as it must
                # update its data structures
                self._mainWin.SetReportView(inReportView)

            self.CreateOrDestroyHeaderWindowAsNeeded()
            self.CreateOrDestroyFooterWindowAsNeeded()
            self.GetSizer().Layout()
        
        if style & ULC_HAS_VARIABLE_ROW_HEIGHT:
            self._mainWin.ResetLineDimensions()
            self._mainWin.ResetVisibleLinesRange()

        self.Refresh()


    def HasAGWFlag(self, flag):
        """
        Returns ``True`` if the window has the given flag bit set.

        :param `flag`: the window style to check.

        :see: :meth:`~UltimateListCtrl.SetAGWWindowStyleFlag` for a list of valid window styles.        
        """
        
        return self._agwStyle & flag
            

    def SetUserLineHeight(self, height):
        """
        Sets a custom value for the :class:`UltimateListCtrl` item height.

        :param `height`: the custom height for all the items, in pixels.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self._mainWin:
            self._mainWin.SetUserLineHeight(height)
        

    def GetUserLineHeight(self):
        """
        Returns the custom value for the :class:`UltimateListCtrl` item height, if previously set with
        :meth:`~UltimateListCtrl.SetUserLineHeight`.

        :note: This method can be used only with ``ULC_REPORT`` and ``ULC_USER_ROW_HEIGHT`` styles set.
        """

        if self._mainWin:
            return self._mainWin.GetUserLineHeight()


    def GetColumn(self, col):
        """
        Returns information about this column.

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

        return self._mainWin.GetColumn(col)


    def SetColumn(self, col, item):
        """
        Sets information about this column.

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

        self._mainWin.SetColumn(col, item)
        return True


    def GetColumnWidth(self, col):
        """
        Returns the column width for the input column.

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

        return self._mainWin.GetColumnWidth(col)


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

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3). 
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms). 
         ``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        :note: In small or normal icon view, col must be -1, and the column width
         is set for all columns.
        """

        self._mainWin.SetColumnWidth(col, width)
        return True


    def GetCountPerPage(self):
        """
        Returns the number of items that can fit vertically in the visible area
        of the :class:`UltimateListCtrl` (list or report view) or the total number of
        items in the list control (icon or small icon view).
        """

        return self._mainWin.GetCountPerPage()  # different from Windows ?


    def GetItem(self, itemOrId, col=0):
        """
        Returns the information about the input item.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or an integer specifying
         the item index;
        :param `col`: the column to which the item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItem(item, col)


    def SetItem(self, info):
        """
        Sets the information about the input item.

        :param `info`: an instance of :class:`UltimateListItem`.
        """

        self._mainWin.SetItem(info)
        return True


    def SetStringItem(self, index, col, label, imageIds=[], it_kind=0):
        """
        Sets a string or image at the given location.

        :param `index`: the item index;
        :param `col`: the column to which the item belongs to;
        :param `label`: the item text;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind. May be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================
         
        """
        
        info = UltimateListItem()
        info._text = label
        info._mask = ULC_MASK_TEXT

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind
            
        info._itemId = index        
        info._col = col

        for ids in to_list(imageIds):
            if ids > -1:
                info._image.append(ids)

        if info._image:
            info._mask |= ULC_MASK_IMAGE

        self._mainWin.SetItem(info)
        return index


    def GetItemState(self, item, stateMask):
        """
        Returns the item state flags for the input item.

        :param `item`: the index of the item;
        :param `stateMask`: the bitmask for the state flag.
        
        :see: :meth:`~UltimateListCtrl.SetItemState` for a list of valid state flags.
        """

        return self._mainWin.GetItemState(item, stateMask)


    def SetItemState(self, item, state, stateMask):
        """
        Sets the item state flags for the input item.

        :param `item`: the index of the item; if defaulted to -1, the state flag
         will be set for all the items;
        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================

        :param `stateMask`: the bitmask for the state flag.
        
        """

        self._mainWin.SetItemState(item, state, stateMask)
        return True


    def SetItemImage(self, item, image, selImage=-1):
        """
        Sets a Python list of image indexes associated with the item.

        :param `item`: an integer specifying the item index;
        :param `image`: a Python list of indexes into the image list associated
         with the :class:`UltimateListCtrl`. In report view, this only sets the images
         for the first column;
        :param `selImage`: not used at present.
        """
        
        return self.SetItemColumnImage(item, 0, image)


    def SetItemColumnImage(self, item, column, image):
        """
        Sets a Python list of image indexes associated with the item in the input
        column.

        :param `item`: an integer specifying the item index;
        :param `column`: the column to which the item belongs to;
        :param `image`: a Python list of indexes into the image list associated
         with the :class:`UltimateListCtrl`. 
        """

        info = UltimateListItem()
        info._image = to_list(image)
        info._mask = ULC_MASK_IMAGE
        info._itemId = item
        info._col = column
        self._mainWin.SetItem(info)
        
        return True


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

        :param `item`: an instance of :class:`UltimateListItem` or an integer specifying
         the item index.
        """

        return self._mainWin.GetItemText(item)


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

        :param `item`: an instance of :class:`UltimateListItem` or an integer specifying
         the item index;
        :param `text`: the new item text.
        """

        self._mainWin.SetItemText(item, text)


    def GetItemData(self, item):
        """
        Gets the application-defined data associated with this item.

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

        info = UltimateListItem()
        info._mask = ULC_MASK_DATA
        info._itemId = item
        self._mainWin.GetItem(info)
        return info._data


    def SetItemData(self, item, data):
        """
        Sets the application-defined data associated with this item.

        :param `item`: an integer specifying the item index;
        :param `data`: the data to be associated with the input item.

        :note: This function cannot be used to associate pointers with
         the control items, use :meth:`~UltimateListCtrl.SetItemPyData` instead.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_DATA
        info._itemId = item
        info._data = data
        self._mainWin.SetItem(info)
        return True


    def GetItemPyData(self, item):
        """
        Returns the data for the item, which can be any Python object.

        :param `item`: an integer specifying the item index.
        
        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_PYDATA
        info._itemId = item
        self._mainWin.GetItem(info)
        return info._pyData


    def SetItemPyData(self, item, pyData):
        """
        Sets the data for the item, which can be any Python object.

        :param `item`: an integer specifying the item index;
        :param `pyData`: any Python object.
        
        :note: Please note that Python data is associated with the item and not
         with subitems.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_PYDATA
        info._itemId = item
        info._pyData = pyData
        self._mainWin.SetItem(info)
        return True
    

    SetPyData = SetItemPyData
    GetPyData = GetItemPyData


    def GetViewRect(self):
        """
        Returns the rectangle taken by all items in the control. In other words,
        if the controls client size were equal to the size of this rectangle, no
        scrollbars would be needed and no free space would be left.

        :note: This function only works in the icon and small icon views, not in
         list or report views.
        """

        return self._mainWin.GetViewRect()


    def GetItemRect(self, item, code=ULC_RECT_BOUNDS):
        """
        Returns the rectangle representing the item's size and position, in physical
        coordinates.

        :param `item`: the row in which the item lives;
        :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.
        """

        return self.GetSubItemRect(item, ULC_GETSUBITEMRECT_WHOLEITEM, code)


    def GetSubItemRect(self, item, subItem, code):
        """
        Returns the rectangle representing the size and position, in physical coordinates,
        of the given subitem, i.e. the part of the row `item` in the column `subItem`.

        :param `item`: the row in which the item lives;
        :param `subItem`: the column in which the item lives. If set equal to the special
         value ``ULC_GETSUBITEMRECT_WHOLEITEM`` the return value is the same as for
         :meth:`~UltimateListCtrl.GetItemRect`;
        :param `code`: one of ``ULC_RECT_BOUNDS``, ``ULC_RECT_ICON``, ``ULC_RECT_LABEL``.
        
        :note: This method is only meaningful when the :class:`UltimateListCtrl` is in the
         report mode.        
        """

        rect = self._mainWin.GetSubItemRect(item, subItem)
        if self._mainWin.HasHeader():
            rect.y += self._headerHeight + 1

        return rect


    def GetItemPosition(self, item):
        """
        Returns the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives.
        """

        return self._mainWin.GetItemPosition(item)


    def SetItemPosition(self, item, pos):
        """
        Sets the position of the item, in icon or small icon view.

        :param `item`: the row in which the item lives;
        :param `pos`: the item position.

        :note: This method is currently unimplemented and does nothing.        
        """

        return False


    def GetItemCount(self):
        """ Returns the number of items in the :class:`UltimateListCtrl`. """

        return self._mainWin.GetItemCount()


    def GetColumnCount(self):
        """ Returns the total number of columns in the :class:`UltimateListCtrl`. """

        return self._mainWin.GetColumnCount()


    def SetItemSpacing(self, spacing, isSmall=False):
        """
        Sets the spacing between item texts and icons.

        :param `spacing`: the spacing between item texts and icons, in pixels;
        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        self._mainWin.SetItemSpacing(spacing, isSmall)


    def GetItemSpacing(self, isSmall=False):
        """
        Returns the spacing between item texts and icons, in pixels.

        :param `isSmall`: ``True`` if using a ``wx.IMAGE_LIST_SMALL`` image list,
         ``False`` if using a ``wx.IMAGE_LIST_NORMAL`` image list.
        """

        return self._mainWin.GetItemSpacing(isSmall)


    def SetItemTextColour(self, item, col):
        """
        Sets the item text colour.

        :param `item`: the index of the item;
        :param `col`: a valid :class:`Colour` object.
        """
        
        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        info.SetTextColour(col)
        self._mainWin.SetItem(info)


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

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        
        return info.GetTextColour()


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

        :param `item`: the index of the item;
        :param `col`: a valid :class:`Colour` object.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        info.SetBackgroundColour(col)
        self._mainWin.SetItem(info)


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

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        return info.GetBackgroundColour()


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

        :param `item`: the index of the item;
        :param `f`: a valid :class:`Font` object.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        info.SetFont(f)
        info.SetBackgroundColour(self.GetItemBackgroundColour(item))
        self._mainWin.SetItem(info)


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

        :param `item`: the index of the item.
        """

        info = UltimateListItem()
        info._itemId = item
        info = self._mainWin.GetItem(info)
        return info.GetFont()


    def GetSelectedItemCount(self):
        """ Returns the number of selected items in :class:`UltimateListCtrl`. """

        return self._mainWin.GetSelectedItemCount()


    def GetTextColour(self):
        """ Returns the :class:`UltimateListCtrl` foreground colour. """

        return self.GetForegroundColour()


    def SetTextColour(self, col):
        """
        Sets the :class:`UltimateListCtrl` foreground colour.

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

        self.SetForegroundColour(col)


    def GetTopItem(self):
        """ Gets the index of the topmost visible item when in list or report view. """

        top, dummy = self._mainWin.GetVisibleLinesRange()
        return top


    def GetNextItem(self, item, geometry=ULC_NEXT_ALL, state=ULC_STATE_DONTCARE):
        """
        Searches for an item with the given `geometry` or `state`, starting from `item`
        but excluding the `item` itself.

        :param `item`: the item at which starting the search. If set to -1, the first
         item that matches the specified flags will be returned.
        :param `geometry`: can be one of:

         =================== ========= =================================
         Geometry Flag       Hex Value Description
         =================== ========= =================================
         ``ULC_NEXT_ABOVE``        0x0 Searches for an item above the specified item
         ``ULC_NEXT_ALL``          0x1 Searches for subsequent item by index
         ``ULC_NEXT_BELOW``        0x2 Searches for an item below the specified item
         ``ULC_NEXT_LEFT``         0x3 Searches for an item to the left of the specified item
         ``ULC_NEXT_RIGHT``        0x4 Searches for an item to the right of the specified item
         =================== ========= =================================
        
        :param `state`: any combination of the following bits:
        
         ============================ ========= ==============================
         State Bits                   Hex Value Description
         ============================ ========= ==============================
         ``ULC_STATE_DONTCARE``             0x0 Don't care what the state is
         ``ULC_STATE_DROPHILITED``          0x1 The item is highlighted to receive a drop event
         ``ULC_STATE_FOCUSED``              0x2 The item has the focus
         ``ULC_STATE_SELECTED``             0x4 The item is selected
         ``ULC_STATE_CUT``                  0x8 The item is in the cut state
         ``ULC_STATE_DISABLED``            0x10 The item is disabled
         ``ULC_STATE_FILTERED``            0x20 The item has been filtered
         ``ULC_STATE_INUSE``               0x40 The item is in use
         ``ULC_STATE_PICKED``              0x80 The item has been picked
         ``ULC_STATE_SOURCE``             0x100 The item is a drag and drop source
         ============================ ========= ==============================


        :return: The first item with given `state` following `item` or -1 if no such item found.

        :note: This function may be used to find all selected items in the
         control like this::
              
             item = -1
                        
             while 1:
                 item = listctrl.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)
                   
                 if item == -1:
                     break
                
                 # This item is selected - do whatever is needed with it

                 wx.LogMessage("Item %ld is selected."%item)


        """

        return self._mainWin.GetNextItem(item, geometry, state)


    def GetImageList(self, which):
        """
        Returns the image list associated with the control.

        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note:

         As :class:`UltimateListCtrl` allows you to use a standard :class:`ImageList` or
         :class:`PyImageList`, the returned object depends on which kind of image list you
         chose.
        """

        if which == wx.IMAGE_LIST_NORMAL:
            return self._imageListNormal

        elif which == wx.IMAGE_LIST_SMALL:
            return self._imageListSmall

        elif which == wx.IMAGE_LIST_STATE:
            return self._imageListState

        return None


    def SetImageList(self, imageList, which):
        """
        Sets the image list associated with the control.

        :param `imageList`: an instance of :class:`ImageList` or an instance of :class:`PyImageList`;
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using :class:`PyImageList` enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
         
        """

        if which == wx.IMAGE_LIST_NORMAL:
            self._imageListNormal = imageList

        elif which == wx.IMAGE_LIST_SMALL:
            self._imageListSmall = imageList

        elif which == wx.IMAGE_LIST_STATE:
            self._imageListState = imageList

        self._mainWin.SetImageList(imageList, which)


    def AssignImageList(self, imageList, which):
        """
        Assigns the image list associated with the control.

        :param `imageList`: an instance of :class:`ImageList` or an instance of :class:`PyImageList`;
        :param `which`: one of ``wx.IMAGE_LIST_NORMAL``, ``wx.IMAGE_LIST_SMALL``,
         ``wx.IMAGE_LIST_STATE`` (the last is unimplemented).

        :note: Using :class:`PyImageList` enables you to have images of different size inside the
         image list. In your derived class, instead of doing this::

             imageList = wx.ImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)

         You should do this::

             imageList = PyImageList(16, 16)
             imageList.Add(someBitmap)
             self.SetImageList(imageList, wx.IMAGE_LIST_SMALL)
         
        """

        self.SetImageList(imageList, which)


    def Arrange(self, flag):
        """
        Arranges the items in icon or small icon view.

        :param `flag`: one of the following bits:

         ========================== ========= ===============================
         Alignment Flag             Hex Value Description
         ========================== ========= ===============================
         ``ULC_ALIGN_DEFAULT``            0x0 Default alignment
         ``ULC_ALIGN_SNAP_TO_GRID``       0x3 Snap to grid
         ========================== ========= ===============================

        :note: This method is currently unimplemented and does nothing.
        """


        return 0


    def DeleteItem(self, item):
        """
        Deletes the specified item.

        :param `item`: the index of the item to delete.
        
        :note: This function sends the ``EVT_LIST_DELETE_ITEM`` event for the item
         being deleted.
        """

        self._mainWin.DeleteItem(item)
        return True


    def DeleteAllItems(self):
        """
        Deletes all items in the :class:`UltimateListCtrl`.

        :note: This function does not send the ``EVT_LIST_DELETE_ITEM`` event because
         deleting many items from the control would be too slow then (unlike :meth:`~UltimateListCtrl.DeleteItem`).
        """

        self._mainWin.DeleteAllItems()
        return True


    def DeleteAllColumns(self):
        """ Deletes all the column in :class:`UltimateListCtrl`. """

        count = len(self._mainWin._columns)
        for n in xrange(count):
            self.DeleteColumn(0)

        return True


    def ClearAll(self):
        """ Deletes everything in :class:`UltimateListCtrl`. """

        self._mainWin.DeleteEverything()


    def DeleteColumn(self, col):
        """
        Deletes the specified column.

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

        self._mainWin.DeleteColumn(col)
        return True


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

        :param `item`: the index of the item to edit.
        """

        self._mainWin.EditLabel(item)


    def EnsureVisible(self, item):
        """
        Ensures this item is visible.

        :param `index`: the index of the item to scroll into view.
        """

        self._mainWin.EnsureVisible(item)
        return True


    def FindItem(self, start, str, partial=False):
        """
        Find an item whose label matches this string.

        :param `start`: the starting point of the input `string` or the beginning
         if `start` is -1;
        :param `string`: the string to look for matches;
        :param `partial`: if ``True`` then this method will look for items which
         begin with `string`.

        :note: The string comparison is case insensitive.         
        """

        return self._mainWin.FindItem(start, str, partial)


    def FindItemData(self, start, data):
        """
        Find an item whose data matches this data.

        :param `start`: the starting point of the input `data` or the beginning
         if `start` is -1;
        :param `data`: the data to look for matches.
        """

        return self._mainWin.FindItemData(start, data)


    def FindItemAtPos(self, start, pt):
        """
        Find an item nearest this position.

        :param `pt`: an instance of :class:`Point`.        
        """

        return self._mainWin.FindItemAtPos(pt)


    def HitTest(self, pointOrTuple):
        """
        HitTest method for a :class:`UltimateListCtrl`.

        :param `pointOrTuple`: an instance of :class:`Point` or a tuple representing
         the mouse `x`, `y` position.

        :see: :meth:`UltimateListMainWindow.HitTestLine() <UltimateListMainWindow.HitTestLine>` for a list of return flags.        
        """

        if isinstance(pointOrTuple, wx.Point):
            x, y = pointOrTuple.x, pointOrTuple.y
        else:
            x, y = pointOrTuple

        return self._mainWin.HitTest(x, y)


    def InsertItem(self, info):
        """
        Inserts an item into :class:`UltimateListCtrl`.

        :param `info`: an instance of :class:`UltimateListItem`.
        """

        self._mainWin.InsertItem(info)
        return info._itemId


    def InsertStringItem(self, index, label, it_kind=0):
        """
        Inserts a string item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `label`: the item text;
        :param `it_kind`: the item kind.

        :see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._text = label
        info._mask = ULC_MASK_TEXT

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind

        info._itemId = index
        return self.InsertItem(info)


    def InsertImageItem(self, index, imageIds, it_kind=0):
        """
        Inserts an image item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind.

        :see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._mask = ULC_MASK_IMAGE

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind
        
        info._image = to_list(imageIds)
        info._itemId = index
        
        return self.InsertItem(info)


    def InsertImageStringItem(self, index, label, imageIds, it_kind=0):
        """
        Inserts an image+string item at the given location.

        :param `index`: the index at which we wish to insert the item;
        :param `label`: the item text;
        :param `imageIds`: a Python list containing the image indexes for the
         images associated to this item;
        :param `it_kind`: the item kind.

        :see: :meth:`~UltimateListCtrl.SetStringItem` for a list of valid item kinds.
        """

        info = UltimateListItem()
        info._text = label
        info._image = to_list(imageIds)
        info._mask = ULC_MASK_TEXT | ULC_MASK_IMAGE

        if it_kind:
            info._mask |= ULC_MASK_KIND
            info._kind = it_kind
        
        info._itemId = index
        return self.InsertItem(info)


    def InsertColumnInfo(self, col, item):
        """
        Inserts a column into :class:`UltimateListCtrl`.

        :param `col`: the column index at which we wish to insert a column;
        :param `item`: an instance of :class:`UltimateListItem`.

        :return: the index at which the column has been inserted.
        """

        if not self._mainWin.InReportView() and not self.HasAGWFlag(ULC_HEADER_IN_ALL_VIEWS) and \
           not self._mainWin.InTileView():
            raise Exception("Can't add column in non report/tile modes or without the ULC_HEADER_IN_ALL_VIEWS style set")

        idx = self._mainWin.InsertColumn(col, item)
        if self._headerWin:
            self._headerWin.Refresh()

        return idx


    def InsertColumn(self, col, heading, format=ULC_FORMAT_LEFT, width=-1):
        """
        Inserts a column into :class:`UltimateListCtrl`.

        :param `col`: the column index at which we wish to insert a column;
        :param `heading`: the header text;
        :param `format`: the column alignment flag. This can be one of the following
         bits:

         ============================ ========= ==============================
         Alignment Bits               Hex Value Description
         ============================ ========= ==============================
         ``ULC_FORMAT_LEFT``                0x0 The item is left-aligned
         ``ULC_FORMAT_RIGHT``               0x1 The item is right-aligned
         ``ULC_FORMAT_CENTRE``              0x2 The item is centre-aligned
         ``ULC_FORMAT_CENTER``              0x2 The item is center-aligned
         ============================ ========= ==============================

        :param `width`: can be a width in pixels or ``wx.LIST_AUTOSIZE`` (-1) or
         ``wx.LIST_AUTOSIZE_USEHEADER`` (-2) or ``LIST_AUTOSIZE_FILL`` (-3). 
         ``wx.LIST_AUTOSIZE`` will resize the column to the length of its longest
         item. ``wx.LIST_AUTOSIZE_USEHEADER`` will resize the column to the
         length of the header (Win32) or 80 pixels (other platforms). 
         ``LIST_AUTOSIZE_FILL`` will resize the column fill the remaining width
         of the window.

        :return: the index at which the column has been inserted.
        """
        
        item = UltimateListItem()
        item._mask = ULC_MASK_TEXT | ULC_MASK_FORMAT | ULC_MASK_FONT
        item._text = heading
        
        if width >= -2:
            item._mask |= ULC_MASK_WIDTH
            item._width = width

        item._format = format

        return self.InsertColumnInfo(col, item)


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

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

        if self._headerWin:
            return self._mainWin.IsColumnShown(column)

        raise Exception("Showing/hiding columns works only with the header shown")


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

        :param `column`: an integer specifying the column index;
        :param `shown`: ``True`` to show the column, ``False`` to hide it.
        """

        col = self.GetColumn(column)
        col._mask |= ULC_MASK_SHOWN
        col.SetShown(shown)
        self._mainWin.SetColumn(column, col)
        self.Update()

        
    def ScrollList(self, dx, dy):
        """
        Scrolls the :class:`UltimateListCtrl`.

        :param `dx`: if in icon, small icon or report view mode, specifies the number
         of pixels to scroll. If in list view mode, `dx` specifies the number of
         columns to scroll.
        :param `dy`: always specifies the number of pixels to scroll vertically.
        """

        return self._mainWin.ScrollList(dx, dy)


# Sort items.
# The return value is a negative number if the first item should precede the second
# item, a positive number of the second item should precede the first,
# or zero if the two items are equivalent.

    def SortItems(self, func=None):
        """
        Call this function to sort the items in the :class:`UltimateListCtrl`. Sorting is done
        using the specified function `func`. This function must have the
        following prototype::

            def OnCompareItems(self, line1, line2):

                DoSomething(line1, line2)
                # function code            


        It is called each time when the two items must be compared and should return 0
        if the items are equal, negative value if the first item is less than the second
        one and positive value if the first one is greater than the second one.

        :param `func`: the method to use to sort the items. The default is to use the
         :meth:`UltimateListMainWindow.OnCompareItems() <UltimateListMainWindow.OnCompareItems>` method.
        """

        self._mainWin.SortItems(func)
        wx.CallAfter(self.Refresh)
        
        return True
        
            
# ----------------------------------------------------------------------------
# event handlers
# ----------------------------------------------------------------------------

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

        :param `event`: a :class:`SizeEvent` event to be processed.
        """
        
        if not self.IsShownOnScreen():
            # We don't have the proper column sizes until we are visible so 
            # use CallAfter to resize the columns on the first display
            if self._mainWin:
                wx.CallAfter(self._mainWin.ResizeColumns)
        
        if not self._mainWin:
            return

        # We need to override OnSize so that our scrolled
        # window a) does call Layout() to use sizers for
        # positioning the controls but b) does not query
        # the sizer for their size and use that for setting
        # the scrollable area as set that ourselves by
        # calling SetScrollbar() further down.

        self.DoLayout()
        

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

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

        if self._mainWin:
            self._mainWin.SetFocusIgnoringChildren()
            self._mainWin.Update()
            event.Skip()


    def OnInternalIdle(self):
        """
        This method is normally only used internally, but sometimes an application
        may need it to implement functionality that should not be disabled by an
        application defining an `OnIdle` handler in a derived class.

        This method may be used to do delayed painting, for example, and most
        implementations call :meth:`Window.UpdateWindowUI` in order to send update events
        to the window in idle time.
        """

        wx.PyControl.OnInternalIdle(self)

        # do it only if needed
        if self._mainWin and self._mainWin._dirty:
            self._mainWin._shortItems = []
            self._mainWin.RecalculatePositions()


# ----------------------------------------------------------------------------
# font/colours
# ----------------------------------------------------------------------------

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

        :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 self._mainWin:
            self._mainWin.SetBackgroundColour(colour)
            self._mainWin._dirty = True

        return True


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

        :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 wx.PyControl.SetForegroundColour(self, colour):
            return False

        if self._mainWin:
            self._mainWin.SetForegroundColour(colour)
            self._mainWin._dirty = True

        if self._headerWin:
            self._headerWin.SetForegroundColour(colour)

        return True


    def SetFont(self, font):
        """
        Sets the :class:`UltimateListCtrl` font.

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

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

        if not wx.PyControl.SetFont(self, font):
            return False

        if self._mainWin:
            self._mainWin.SetFont(font)
            self._mainWin._dirty = True

        if self._headerWin:
            self._headerWin.SetFont(font)

        self.Refresh()

        return True


    def GetClassDefaultAttributes(self, variant):
        """
        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.

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

        attr = wx.VisualAttributes()
        attr.colFg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOXTEXT)
        attr.colBg = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)
        attr.font  = wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)
        return attr


    def GetScrolledWin(self):
        """ Returns the header window owner. """

        return self._headerWin.GetOwner()


# ----------------------------------------------------------------------------
# methods forwarded to self._mainWin
# ----------------------------------------------------------------------------

    def SetDropTarget(self, dropTarget):
        """
        Associates a drop target with this window.
        If the window already has a drop target, it is deleted.

        :param `dropTarget`: an instance of :class:`DropTarget`.

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

        self._mainWin.SetDropTarget(dropTarget)


    def GetDropTarget(self):
        """
        Returns the associated drop target, which may be ``None``.

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

        return self._mainWin.GetDropTarget()


    def SetCursor(self, cursor):
        """
        Sets the window's cursor. 

        :param `cursor`: specifies the cursor that the window should normally display.
         The `cursor` may be :class:`NullCursor` in which case the window cursor will be
         reset back to default.

        :note: The window cursor also sets it for the children of the window implicitly.

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

        return (self._mainWin and [self._mainWin.SetCursor(cursor)] or [False])[0]


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

        :note: Overridden from :class:`PyControl`.
        """
        
        return (self._mainWin and [self._mainWin.GetBackgroundColour()] or [wx.NullColour])[0]


    def GetForegroundColour(self):
        """
        Returns the foreground colour of the window.

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

        return (self._mainWin and [self._mainWin.GetForegroundColour()] or [wx.NullColour])[0]


    def PopupMenu(self, menu, pos=wx.DefaultPosition):
        """
        Pops up the given `menu` at the specified coordinates, relative to this window,
        and returns control when the user has dismissed the menu. If a menu item is
        selected, the corresponding menu event is generated and will be processed as
        usual. If the coordinates are not specified, the current mouse cursor position
        is used.

        :param `menu`: an instance of :class:`Menu` to pop up;
        :param `pos`: the position where the menu will appear.

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

        return self._mainWin.PopupMenu(menu, pos)


    def ClientToScreen(self, pointOrTuple):
        """
        Converts to screen coordinates from coordinates relative to this window.

        :param `pointOrTuple`: an instance of :class:`Point` or a tuple representing the
         `x`, `y` coordinates for this point.

        :return: the coordinates relative to the screen.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._mainWin.ClientToScreen(*pointOrTuple)


    def ClientToScreenXY(self, x, y):
        """
        Converts to screen coordinates from coordinates relative to this window.

        :param `x`: an integer specifying the `x` client coordinate;        
        :param `y`: an integer specifying the `y` client coordinate.

        :return: the coordinates relative to the screen.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._mainWin.ClientToScreen(x, y)


    def ScreenToClient(self, pointOrTuple):
        """
        Converts from screen to client window coordinates.

        :param `pointOrTuple`: an instance of :class:`Point` or a tuple representing the
         `x`, `y` coordinates for this point.

        :return: the coordinates relative to this window.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._mainWin.ScreenToClient(*pointOrTuple)


    def ScreenToClientXY(self, x, y):
        """
        Converts from screen to client window coordinates.

        :param `x`: an integer specifying the `x` screen coordinate;        
        :param `y`: an integer specifying the `y` screen coordinate.

        :return: the coordinates relative to this window.
        
        :note: Overridden from :class:`PyControl`.
        """

        return self._mainWin.ScreenToClient(x, y)


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

        # The test in window.cpp fails as we are a composite
        # window, so it checks against "this", but not self._mainWin.
        if wx.Window.FindFocus() != self:
            self._mainWin.SetFocusIgnoringChildren()


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

        # Something is better than nothing...
        # 100x80 is what the MSW version will get from the default
        # wx.Control.DoGetBestSize
        return wx.Size(100, 80)


# ----------------------------------------------------------------------------
# virtual list control support
# ----------------------------------------------------------------------------

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

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemText not supposed to be called")
    
    
    def OnGetItemTextColour(self, item, col):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return a :class:`Colour` object or ``None`` for
        the default color.

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemTextColour not supposed to be called")


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

        :param `item`: an integer specifying the item index;
        :param `col`: the column index to which the item belongs to.
        """

        # this is a pure virtual function, in fact - which is not really pure
        # because the controls which are not virtual don't need to implement it
        raise Exception("UltimateListCtrl.OnGetItemToolTip not supposed to be called")
    

    def OnGetItemImage(self, item):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style having an image list (if the control doesn't have an
        image list, it is not necessary to overload it). It should return a Python
        list of indexes representing the images associated to the input item or an
        empty list for no images.

        :param `item`: an integer specifying the item index;

        :note: In a control with ``ULC_REPORT`` style, :meth:`~UltimateListCtrl.OnGetItemImage` only gets called
         for the first column of each line.

        :note: The base class version always returns an empty Python list.
        """

        if self.GetImageList(wx.IMAGE_LIST_SMALL):
            raise Exception("List control has an image list, OnGetItemImage should be overridden.")

        return []


    def OnGetItemColumnImage(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return a Python list of
        indexes representing the images associated to the input item or an empty list
        for no images.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty Python list.
        """

        if column == 0:
            return self.OnGetItemImage(item)

        return []


    def OnGetItemAttr(self, item):
        """
        This function may be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the attribute for the specified
        item or ``None`` to use the default appearance parameters.

        :param `item`: an integer specifying the item index.

        :note:

         :class:`UltimateListCtrl` will not delete the pointer or keep a reference of it.
         You can return the same :class:`UltimateListItemAttr` pointer for every
         :meth:`~UltimateListCtrl.OnGetItemAttr` call.

        :note: The base class version always returns ``None``.
        """

        if item < 0 or item > self.GetItemCount():
            raise Exception("Invalid item index in OnGetItemAttr()")

        # no attributes by default
        return None


    def OnGetItemCheck(self, item):
        """
        This function may be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return whether a checkbox-like item or
        a radiobutton-like item is checked or unchecked.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty list.
        """

        return []


    def OnGetItemColumnCheck(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` and ``ULC_REPORT`` style. It should return whether a
        checkbox-like item or a radiobutton-like item in the column header is checked
        or unchecked.
        
        :param `item`: an integer specifying the item index.

        :note: The base class version always returns an empty Python list.
        """

        if column == 0:
            return self.OnGetItemCheck(item)

        return []        


    def OnGetItemKind(self, item):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the item kind for the input item.

        :param `item`: an integer specifying the item index.

        :note: The base class version always returns 0 (a standard item).

        :see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
        """

        return 0


    def OnGetItemColumnKind(self, item, column=0):
        """
        This function **must** be overloaded in the derived class for a control with
        ``ULC_VIRTUAL`` style. It should return the item kind for the input item in
        the header window.

        :param `item`: an integer specifying the item index;
        :param `column`: the column index.

        :note: The base class version always returns 0 (a standard item).

        :see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
        """

        if column == 0:
            return self.OnGetItemKind(item)

        return 0
    

    def SetItemCount(self, count):
        """
        Sets the total number of items we handle.

        :param `count`: the total number of items we handle.
        """

        if not self._mainWin.IsVirtual():
            raise Exception("This is for virtual controls only")

        self._mainWin.SetItemCount(count)


    def RefreshItem(self, item):
        """
        Redraws the given item.

        :param `item`: an integer specifying the item index;

        :note: This is only useful for the virtual list controls as without calling
         this function the displayed value of the item doesn't change even when the
         underlying data does change.
        """

        self._mainWin.RefreshLine(item)


    def RefreshItems(self, itemFrom, itemTo):
        """
        Redraws the items between `itemFrom` and `itemTo`.
        The starting item must be less than or equal to the ending one.

        Just as :meth:`~UltimateListCtrl.RefreshItem` this is only useful for virtual list controls

        :param `itemFrom`: the first index of the refresh range;
        :param `itemTo`: the last index of the refresh range.
        """
        
        self._mainWin.RefreshLines(itemFrom, itemTo)


#
# Generic UltimateListCtrl is more or less a container for two other
# windows which drawings are done upon. These are namely
# 'self._headerWin' and 'self._mainWin'.
# Here we override 'virtual wxWindow::Refresh()' to mimic the
# behaviour UltimateListCtrl has under wxMSW.
#

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

        :param `eraseBackground`: 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 :meth:`~UltimateListCtrl.Update` instead.

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

        if not rect:

            # The easy case, no rectangle specified.
            if self._headerWin:
                self._headerWin.Refresh(eraseBackground)

            if self._mainWin:
                self._mainWin.Refresh(eraseBackground)

        else:

            # Refresh the header window
            if self._headerWin:

                rectHeader = self._headerWin.GetRect()
                rectHeader.Intersect(rect)
                if rectHeader.GetWidth() and rectHeader.GetHeight():
                    x, y = self._headerWin.GetPosition()
                    rectHeader.OffsetXY(-x, -y)
                    self._headerWin.Refresh(eraseBackground, rectHeader)

            # Refresh the main window
            if self._mainWin:

                rectMain = self._mainWin.GetRect()
                rectMain.Intersect(rect)
                if rectMain.GetWidth() and rectMain.GetHeight():
                    x, y = self._mainWin.GetPosition()
                    rectMain.OffsetXY(-x, -y)
                    self._mainWin.Refresh(eraseBackground, rectMain)


    def Update(self):
        """
        Calling this method immediately repaints the invalidated area of the window
        and all of its children recursively while this would usually only happen when
        the flow of control returns to the event loop.

        :note: This function doesn't invalidate any area of the window so nothing
         happens if nothing has been invalidated (i.e. marked as requiring a redraw).
         Use :meth:`~UltimateListCtrl.Refresh` first if you want to immediately redraw the window unconditionally.

        :note: Overridden from :class:`PyControl`.         
        """
        
        self._mainWin.ResetVisibleLinesRange(True)
        wx.PyControl.Update(self)


    def GetEditControl(self):
        """
        Returns a pointer to the edit :class:`UltimateListTextCtrl` if the item is being edited or
        ``None`` otherwise (it is assumed that no more than one item may be edited
        simultaneously).
        """

        retval = None

        if self._mainWin:
            retval = self._mainWin.GetEditControl()

        return retval


    def Select(self, idx, on=True):
        """
        Selects/deselects an item.

        :param `idx`: the index of the item to select;
        :param `on`: ``True`` to select the item, ``False`` to deselect it.
        """

        item = CreateListItem(idx, 0)
        item = self._mainWin.GetItem(item, 0)
        if not item.IsEnabled():
            return

        if on:
            state = ULC_STATE_SELECTED
        else:
            state = 0

                    
        self.SetItemState(idx, state, ULC_STATE_SELECTED)


    def Focus(self, idx):
        """
        Focus and show the given item.

        :param `idx`: the index of the item to be focused.
        """

        self.SetItemState(idx, ULC_STATE_FOCUSED, ULC_STATE_FOCUSED)
        self.EnsureVisible(idx)


    def GetFocusedItem(self):
        """ Returns the currently focused item or -1 if none is focused. """
        
        return self.GetNextItem(-1, ULC_NEXT_ALL, ULC_STATE_FOCUSED)


    def GetFirstSelected(self):
        """ Return first selected item, or -1 when none is selected. """
        
        return self.GetNextSelected(-1)


    def GetNextSelected(self, item):
        """
        Returns subsequent selected items, or -1 when no more are selected.

        :param `item`: the index of the item.
        """

        return self.GetNextItem(item, ULC_NEXT_ALL, ULC_STATE_SELECTED)


    def IsSelected(self, idx):
        """
        Returns ``True`` if the item is selected.

        :param `idx`: the index of the item to check for selection.
        """
        
        return (self.GetItemState(idx, ULC_STATE_SELECTED) & ULC_STATE_SELECTED) != 0


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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.IsItemChecked(item)


    def IsItemEnabled(self, itemOrId, col=0):
        """
        Returns whether an item is enabled or not.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)        
        return self._mainWin.IsItemEnabled(item)


    def GetItemKind(self, itemOrId, col=0):
        """
        Returns the item kind.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.

        :see: :meth:`~UltimateListCtrl.SetItemKind` for a list of valid item kinds.
        """
        
        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemKind(item)


    def SetItemKind(self, itemOrId, col=0, kind=0):
        """
        Sets the item kind.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `kind`: may be one of the following integers:

         =============== ==========================
         Item Kind       Description
         =============== ==========================
                0        A normal item
                1        A checkbox-like item
                2        A radiobutton-type item
         =============== ==========================

        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemKind(item, kind)
    

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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `enable`: ``True`` to enable the item, ``False`` otherwise.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.EnableItem(item, enable)
        

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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """
        
        item = CreateListItem(itemOrId, col)
        return self._mainWin.IsItemHyperText(item)


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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `hyper`: ``True`` to have an item with hypertext behaviour, ``False`` otherwise.
        """
        
        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemHyperText(item, hyper)

    def SetColumnToolTip(self, col, tip):
        """
        Sets the tooltip for the column header

        :param `col`: the column index;
        :param `tip`: the tooltip text
        """
       
        item = self.GetColumn(col)
        item.SetToolTip(tip)
        self.SetColumn(col, item)
        

    def SetColumnImage(self, col, image):
        """
        Sets one or more images to the specified column.

        :param `col`: the column index;
        :param `image`: a Python list containing the image indexes for the
         images associated to this column item.
        """
        
        item = self.GetColumn(col)
        # preserve all other attributes too

        item.SetMask(ULC_MASK_STATE      |
                     ULC_MASK_TEXT       |
                     ULC_MASK_IMAGE      |
                     ULC_MASK_DATA       |
                     ULC_SET_ITEM        |
                     ULC_MASK_WIDTH      |
                     ULC_MASK_FORMAT     |
                     ULC_MASK_FONTCOLOUR |
                     ULC_MASK_FONT       |
                     ULC_MASK_BACKCOLOUR |
                     ULC_MASK_KIND       |
                     ULC_MASK_CHECK      
                     )
        item.SetImage(image)
        self.SetColumn(col, item)


    def ClearColumnImage(self, col):
        """
        Clears all the images in the specified column.

        :param `col`: the column index;
        """
        
        self.SetColumnImage(col, -1)


    def Append(self, entry):
        """
        Append an item to the :class:`UltimateListCtrl`.

        :param `entry`: should be a sequence with an item for each column.
        """
        
        if entry:
            if wx.USE_UNICODE:
                cvtfunc = unicode
            else:
                cvtfunc = str
            pos = self.GetItemCount()
            self.InsertStringItem(pos, cvtfunc(entry[0]))
            for i in range(1, len(entry)):
                self.SetStringItem(pos, i, cvtfunc(entry[i]))
                
            return pos


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

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

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

        :param `colour`: if not ``None``, a valid :class:`Colour` instance. Otherwise,
         the colour generated is a slightly darker version of the :class:`UltimateListCtrl`
         background colour.
        """

        self._mainWin.SetSecondGradientColour(colour)


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


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


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

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

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

        self._mainWin.EnableSelectionGradient(enable)
        

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

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

        self._mainWin.SetGradientStyle(vertical)


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

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

        return self._mainWin.GetGradientStyle()


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

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

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

        self._mainWin.EnableSelectionVista(enable)


    def SetSelectedTextColour(self, colour=None):
        """
        Sets the colour of text applied to an item when it is selected. 
        If this method is not called, text color of selected items will be
        the system value ``wx.SYS_COLOUR_HIGHLIGHTTEXT``, or the color set on 
        the item with SetTextColour.

        :param `colour`: if not ``None``, a valid :class:`Colour` instance. Otherwise,
         the colour is taken from the system value ``wx.SYS_COLOUR_HIGHLIGHTTEXT``.
        """
        
        self._mainWin.SetSelectedTextColour(colour)


    def GetSelectedTextColour(self):
        """ Returns the colour applied to text when an item is selected. """
        
        return self._mainWin.GetSelectedTextColour()


    def SetBackgroundImage(self, image=None):
        """
        Sets the :class:`UltimateListCtrl` background image.

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

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

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

        self._mainWin.SetBackgroundImage(image)
        

    def GetBackgroundImage(self):
        """
        Returns the :class:`UltimateListCtrl` background image (if any).

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

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

        return self._mainWin.GetBackgroundImage()


    def SetWaterMark(self, watermark=None):
        """
        Sets the :class:`UltimateListCtrl` watermark image to be displayed in the bottom
        right part of the window.

        :param `watermark`: if not ``None``, an instance of :class:`Bitmap`.

        .. todo:: Better support for this is needed.        
        """        

        self._mainWin.SetWaterMark(watermark)
        

    def GetWaterMark(self):
        """
        Returns the :class:`UltimateListCtrl` watermark image (if any), displayed in the
        bottom right part of the window.

        .. todo:: Better support for this is needed.        
        """

        return self._mainWin.GetWaterMark()


    def SetDisabledTextColour(self, colour):
        """
        Sets the items disabled colour.

        :param `colour`: an instance of :class:`Colour`.
        """

        self._mainWin.SetDisabledTextColour(colour)


    def GetDisabledTextColour(self):
        """ Returns the items disabled colour. """

        return self._mainWin.GetDisabledTextColour()


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

        return self._mainWin.GetHyperTextFont()


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

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

        self._mainWin.SetHyperTextFont(font)
        

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

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

        self._mainWin.SetHyperTextNewColour(colour)
        

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

        return self._mainWin.GetHyperTextNewColour()


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

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

        self._mainWin.SetHyperTextVisitedColour(colour)
        

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

        return self._mainWin.GetHyperTextVisitedColour()


    def SetItemVisited(self, itemOrId, col=0, visited=True):
        """
        Sets whether an hypertext item was visited or not.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `visited`: ``True`` to mark an hypertext item as visited, ``False`` otherwise.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemVisited(item, visited)
    

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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemVisited(item)


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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemWindow(item)


    def SetItemWindow(self, itemOrId, col=0, wnd=None, expand=False):
        """
        Sets the window for the given item.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `wnd`: a non-toplevel window to be displayed next to the item;
        :param `expand`: ``True`` to expand the column where the item/subitem lives,
         so that the window will be fully visible.        
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemWindow(item, wnd, expand)
       

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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.DeleteItemWindow(item)
        

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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemWindowEnabled(item)


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

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `enable`: ``True`` to enable the associated window, ``False`` to disable it.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemWindowEnabled(item, enable)


    def GetItemCustomRenderer(self, itemOrId, col=0):
        """
        Returns the custom renderer used to draw the input item (if any).

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemCustomRenderer(item)


    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 methods `DrawHeaderButton`
         and `GetForegroundColor`. 
        """

        if not self.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")
        
        self._headerWin.SetCustomRenderer(renderer)

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

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

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`. 
        """

        if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_FOOTER):
            raise Exception("Custom renderers can only be used on with style = ULC_REPORT | ULC_FOOTER")
       
        self._footerWin.SetCustomRenderer(renderer)


    def SetColumnCustomRenderer(self, col=0, renderer=None):
        """
        Associate a custom renderer to this column's header.

        :param `col`: the column index.
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawHeaderButton`
         and `GetForegroundColor`. 
        """

        if not self.HasAGWFlag(ULC_REPORT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT")
        
        return self._mainWin.SetCustomRenderer(col, renderer)


    def SetItemCustomRenderer(self, itemOrId, col=0, renderer=None):
        """
        Associate a custom renderer to this item.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `renderer`: a class able to correctly render the input item.

        :note: the renderer class **must** implement the methods `DrawSubItem`,
         `GetLineHeight` and `GetSubItemWidth`. 
        """

        if not self.HasAGWFlag(ULC_REPORT) or not self.HasAGWFlag(ULC_HAS_VARIABLE_ROW_HEIGHT):
            raise Exception("Custom renderers can be used on with style = ULC_REPORT | ULC_HAS_VARIABLE_ROW_HEIGHT")
        
        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemCustomRenderer(item, renderer)


    def SetItemOverFlow(self, itemOrId, col=0, over=True):
        """
        Sets the item in the overflow/non overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.
        
        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to;
        :param `over`: ``True`` to set the item in a overflow state, ``False`` otherwise.        
        """

        if not self.HasAGWFlag(ULC_REPORT) or self._mainWin.IsVirtual():
            raise Exception("Overflowing items can be used only in report, non-virtual mode")

        item = CreateListItem(itemOrId, col)
        return self._mainWin.SetItemOverFlow(item, over)
                

    def GetItemOverFlow(self, itemOrId, col=0):
        """
        Returns if the item is in the overflow state.

        An item/subitem may overwrite neighboring items/subitems if its text would
        not normally fit in the space allotted to it.

        :param `itemOrId`: an instance of :class:`UltimateListItem` or the item index;
        :param `col`: the column index to which the input item belongs to.
        """

        item = CreateListItem(itemOrId, col)
        return self._mainWin.GetItemOverFlow(item)


    def IsVirtual(self):
        """ Returns ``True`` if the :class:`UltimateListCtrl` has the ``ULC_VIRTUAL`` style set. """

        return self._mainWin.IsVirtual()


    def GetScrollPos(self, orientation):
        """
        Returns the scrollbar position.

        :param int `orientation`: defines for which scrollbar we ask the position.
         May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.
        
        :note: This method is forwarded to :class:`UltimateListMainWindow`.
        """

        if self._mainWin:
            return self._mainWin.GetScrollPos(orientation)

        return 0
    

    def SetScrollPos(self, orientation, pos, refresh=True):
        """
        Sets the scrollbar position.

        :param `orientation`: determines the scrollbar whose position is to be set.
         May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``;
        :param `pos`: the scrollbar position in scroll units;
        :param `refresh`: ``True`` to redraw the scrollbar, ``False`` otherwise.

        :note: This method is forwarded to :class:`UltimateListMainWindow`.
        """

        if self._mainWin:
            self._mainWin.SetScrollPos(orientation, pos, refresh)
        

    def GetScrollThumb(self, orientation):
        """
        Returns the scrollbar size in pixels.

        :param `orientation`: determines the scroll thumb whose position is to be retrieved.
         May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.

        :note: This method is forwarded to :class:`UltimateListMainWindow`.
        """

        if self._mainWin:
            return self._mainWin.GetScrollThumb(orientation)

        return 0


    def GetScrollRange(self, orientation):
        """
        Returns the scrollbar range in pixels.

        :param `orientation`: determines the scroll range whose position is to be retrieved.
         May be ``wx.HORIZONTAL`` or ``wx.VERTICAL``.

        :note: This method is forwarded to :class:`UltimateListMainWindow`.
        """

        if self._mainWin:
            return self._mainWin.GetScrollRange(orientation)

        return 0


    def SetHeaderHeight(self, height):
        """
        Sets the :class:`UltimateListHeaderWindow` height, in pixels. This overrides the default
        header window size derived from :class:`RendererNative`. If `height` is ``None``, the
        default behaviour is restored.

        :param `height`: the header window height, in pixels (if it is ``None``, the default
         height obtained using :class:`RendererNative` is used).
        """

        if not self._headerWin:
            return

        if height is not None and height < 1:
            raise Exception("Invalid height passed to SetHeaderHeight: %s"%repr(height))
        
        self._headerWin._headerHeight = height
        self.DoLayout()


    def GetHeaderHeight(self):
        """ Returns the :class:`UltimateListHeaderWindow` height, in pixels. """

        if not self._headerWin:
            return -1

        return self._headerWin.GetWindowHeight()
    

    def SetFooterHeight(self, height):
        """
        Sets the :class:`UltimateListHeaderWindow` height, in pixels. This overrides the default
        footer window size derived from :class:`RendererNative`. If `height` is ``None``, the
        default behaviour is restored.

        :param `height`: the footer window height, in pixels (if it is ``None``, the default
         height obtained using :class:`RendererNative` is used).
        """

        if not self._footerWin:
            return

        if height is not None and height < 1:
            raise Exception("Invalid height passed to SetFooterHeight: %s"%repr(height))
        
        self._footerWin._footerHeight = height
        self.DoLayout()


    def GetFooterHeight(self):
        """ Returns the :class:`UltimateListHeaderWindow` height, in pixels. """

        if not self._footerWin:
            return -1

        return self._headerWin.GetWindowHeight()


    def DoLayout(self):
        """
        Layouts the header, main and footer windows. This is an auxiliary method to avoid code
        duplication.
        """

        self.Layout()
        
        self._mainWin.ResizeColumns()
        self._mainWin.ResetVisibleLinesRange(True)
        self._mainWin.RecalculatePositions()
        self._mainWin.AdjustScrollbars()

        if self._headerWin:
            self._headerWin.Refresh()
            
        if self._footerWin:
            self._footerWin.Refresh()