File: persist_handlers.py

package info (click to toggle)
wxpython3.0 3.0.1.1+dfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 481,208 kB
  • ctags: 520,541
  • sloc: cpp: 2,126,470; python: 293,214; makefile: 51,927; ansic: 19,032; sh: 3,011; xml: 1,629; perl: 17
file content (2618 lines) | stat: -rw-r--r-- 77,270 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
# -*- coding: utf-8 -*-#
#!/usr/bin/env python
"""
This module contains different classes which handle different kind of saving/restoring
actions depending on the widget kind.
"""

import wx
import types
import datetime

import wx.aui
import wx.combo
import wx.calendar as calendar
import wx.gizmos
try:
    import wx.media
except ImportError:
    pass

import wx.lib.scrolledpanel as scrolled
import wx.lib.expando as expando
import wx.lib.buttons as buttons
import wx.lib.masked as masked
import wx.lib.colourselect as csel

import wx.lib.agw.aui as AUI
import wx.lib.agw.cubecolourdialog as CCD
import wx.lib.agw.customtreectrl as CT
import wx.lib.agw.flatmenu as FM
import wx.lib.agw.flatnotebook as FNB
import wx.lib.agw.floatspin as FS
import wx.lib.agw.foldpanelbar as FPB
import wx.lib.agw.hypertreelist as HTL
import wx.lib.agw.knobctrl as KC
import wx.lib.agw.labelbook as LBK
import wx.lib.agw.pycollapsiblepane as PCP

try:
    import wx.lib.agw.shapedbutton as SB
    hasSB = True
except:
    hasSB = False
    pass

import wx.lib.agw.ultimatelistctrl as ULC

import persistencemanager as PM

from persist_constants import *


def PyDate2wxDate(date):
    """
    Transforms a datetime.date object into a :class:`DateTime` one.

    :param `date`: a `datetime.date` object.
    """
    
    tt = date.timetuple()
    dmy = (tt[2], tt[1]-1, tt[0])
    return wx.DateTimeFromDMY(*dmy)


def wxDate2PyDate(date):
    """
    Transforms a :class:`DateTime` object into a `datetime.date` one.

    :param date: a :class:`DateTime` object.
    """

    if date.IsValid():
        ymd = map(int, date.FormatISODate().split('-'))
        return datetime.date(*ymd)
    else:
        return None


def CreateFont(font):
    """
    Creates a tuple of 7 :class:`Font` attributes from the `font` input parameter.

    :param `font`: a :class:`Font` instance.

    :returns: A tuple of 7 :class:`Font` attributes from the `font` input parameter.
    """
    
    return font.GetPointSize(), font.GetFamily(), font.GetStyle(), font.GetWeight(), \
           font.GetUnderlined(), font.GetFaceName(), font.GetEncoding()


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

class AbstractHandler(object):
    """
    Base class for persistent windows, uses the window name as persistent name by
    default and automatically reacts to the window destruction.

    .. note::

       This is an abstract class. If you wish to add another (custom) handler
       for your widgets, you should derive from :class:`AbstractHandler` and override
       the :meth:`Save() <AbstractHandler.Save>`,
       :meth:`Restore() <AbstractHandler.Restore>` and
       :meth:`GetKind() <AbstractHandler.GetKind>` methods.
       
    """
    
    def __init__(self, pObject):
        """
        Default class constructor.

        :param `pObject`: a :class:`~lib.agw.persist.persistencemanager.PersistentObject` containing information about the
         persistent widget.
        """

        object.__init__(self)
        self._pObject = pObject
        self._window = pObject.GetWindow()


    def Save(self):
        """
        Saves the widget's settings by calling :meth:`PersistentObject.SaveValue() <lib.agw.persist.persistencemanager.PersistentObject.SaveValue>`, which in
        turns calls :meth:`PersistenceManager.SaveValue() <lib.agw.persist.persistencemanager.PersistenceManager.SaveValue>`.

        :note: This method must be overridden in derived classes.        
        """

        pass


    def Restore(self):
        """
        Restores the widget's settings by calling :meth:`PersistentObject.RestoreValue() <lib.agw.persist.persistencemanager.PersistentObject.RestoreValue>`, which in
        turns calls :meth:`PersistenceManager.RestoreValue() <lib.agw.persist.persistencemanager.PersistenceManager.RestoreValue>`.

        :note: This method must be overridden in derived classes.        
        """

        pass


    def GetKind(self):
        """
        Returns a short and meaningful *string* description of your widget.

        :note: This method must be overridden in derived classes.        
        """

        pass
        

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

class BookHandler(AbstractHandler):
    """
    Supports saving/restoring book control selection.

    This class handles the following wxPython widgets:
    
    - :class:`Toolbook`;
    - :class:`Choicebook`;
    - :class:`Listbook`;
    - :class:`Treebook` (except for opened tree branches, see :class:`TreebookHandler` for this);
    - :class:`Notebook`;
    - :class:`lib.agw.aui.auibook.AuiNotebook`;
    - :class:`lib.agw.flatnotebook.FlatNotebook`;
    - :class:`lib.agw.labelbook.LabelBook`;
    - :class:`lib.agw.labelbook.FlatImageBook`.

    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        book, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_BOOK_SELECTION, book.GetSelection())

        if issubclass(book.__class__, AUI.AuiNotebook):
            manager = PM.PersistenceManager.Get()
            if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
                # Allowed to save and restore perspectives
                perspective = book.SavePerspective()                    
                obj.SaveValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE, perspective)


    def Restore(self):

        book, obj = self._window, self._pObject
        sel = obj.RestoreValue(PERSIST_BOOK_SELECTION)

        retVal = True
        if issubclass(book.__class__, AUI.AuiNotebook):
            manager = PM.PersistenceManager.Get()
            if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
                retVal = False
                # Allowed to save and restore perspectives
                perspective = obj.RestoreValue(PERSIST_BOOK_AGW_AUI_PERSPECTIVE)
                if perspective is not None:
                    retVal = book.LoadPerspective(perspective)
                    wx.CallAfter(book.Refresh)

        if sel is not None:
            if sel >= 0 and sel < book.GetPageCount():
                book.SetSelection(sel)
                return True and retVal

        return False


    def GetKind(self):

        return PERSIST_BOOK_KIND
    

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

class TreebookHandler(BookHandler):
    """
    Supports saving/restoring open tree branches.

    This class handles the following wxPython widgets:
    
    - :class:`Treebook` (except for page selection, see :class:`BookHandler` for this).
    
    """
    
    def __init__(self, pObject):

        BookHandler.__init__(self, pObject)
        

    def Save(self):

        book, obj = self._window, self._pObject

        expanded = ""
        for page in xrange(book.GetPageCount()):
            if book.IsNodeExpanded(page):
                if expanded:
                    expanded += PERSIST_SEP

                expanded += "%u"%page

        obj.SaveValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES, expanded)
        
        return BookHandler.Save(self)
    

    def Restore(self):

        book, obj = self._window, self._pObject

        expanded = obj.RestoreValue(PERSIST_TREEBOOK_EXPANDED_BRANCHES)

        if expanded:
            indices = expanded.split(PERSIST_SEP)
            pageCount = book.GetPageCount()
            
            for indx in indices:
                idx = int(indx)
                if idx >= 0 and idx < pageCount:
                    book.ExpandNode(idx)
        
        return BookHandler.Restore(self)


    def GetKind(self):

        return PERSIST_TREEBOOK_KIND


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

class AUIHandler(AbstractHandler):
    """
    Supports saving/restoring :class:`lib.agw.aui.framemanager.AuiManager` and :class:`wx.aui.AuiManager`
    perspectives.
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        # Save the AUI perspectives if PersistenceManager allows it
        eventHandler = self._window.GetEventHandler()

        isAGWAui = isinstance(eventHandler, AUI.AuiManager)
        isAui = isinstance(eventHandler, wx.aui.AuiManager)
        if not isAui and not isAGWAui:
            return True
        
        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
            # Allowed to save and restore perspectives
            perspective = eventHandler.SavePerspective()
            if isAGWAui:
                name = PERSIST_AGW_AUI_PERSPECTIVE
            else:
                name = PERSIST_AUI_PERSPECTIVE
                
            self._pObject.SaveValue(name, perspective)

        return True
    

    def Restore(self):

        # Restore the AUI perspectives if PersistenceManager allows it
        eventHandler = self._window.GetEventHandler()
        restoreCodeCaption = False

        isAGWAui = isinstance(eventHandler, AUI.AuiManager)
        isAui = isinstance(eventHandler, wx.aui.AuiManager)
        if not isAui and not isAGWAui:
            return True
        
        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_AUI_PERSPECTIVES:
            # Allowed to save and restore perspectives
            if isAGWAui:
                name = PERSIST_AGW_AUI_PERSPECTIVE
                restoreCodeCaption = manager.GetManagerStyle()
                restoreCodeCaption &= ~(PM_RESTORE_CAPTION_FROM_CODE)
            else:
                name = PERSIST_AUI_PERSPECTIVE
                
            perspective = self._pObject.RestoreValue(name)
            if perspective is not None:
                if restoreCodeCaption:
                    eventHandler.LoadPerspective(perspective,
                                                 restorecaption=True)
                else:
                    eventHandler.LoadPerspective(perspective)
                return True
            
        return True


    def GetKind(self):

        return PERSIST_AUIPERSPECTIVE_KIND


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

class TLWHandler(AUIHandler):
    """
    Supports saving/restoring window position and size as well as
    maximized/iconized/restore state for toplevel windows.

    This class handles the following wxPython widgets:
    
    - All :class:`Frame` derived classes;
    - All :class:`Dialog` derived classes.

    |
    
    In addition, if the toplevel window has an associated AuiManager (whether it is 
    :class:`~lib.agw.aui.framemanager.AuiManager` or :class:`wx.aui.AuiManager`) and
    :class:`~lib.agw.persist.persistencemanager.PersistenceManager`
    has the ``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` style set (the default), this class
    will also save and restore AUI perspectives using the underlying :class:`AUIHandler`
    class.

    """
    
    def __init__(self, pObject):

        AUIHandler.__init__(self, pObject)
        

    def Save(self):

        tlw, obj = self._window, self._pObject

        pos = tlw.GetScreenPosition()
        obj.SaveValue(PERSIST_TLW_X, pos.x)
        obj.SaveValue(PERSIST_TLW_Y, pos.y)
        
        # Notice that we use GetSize() here and not GetClientSize() because
        # the latter doesn't return correct results for the minimized windows
        # (at least not under Windows)
        #
        # Of course, it shouldn't matter anyhow usually, the client size
        # should be preserved as well unless the size of the decorations
        # changed between the runs
        size = tlw.GetSize()
        obj.SaveValue(PERSIST_TLW_W, size.x)
        obj.SaveValue(PERSIST_TLW_H, size.y)

        obj.SaveValue(PERSIST_TLW_MAXIMIZED, tlw.IsMaximized())
        obj.SaveValue(PERSIST_TLW_ICONIZED, tlw.IsIconized())

        return AUIHandler.Save(self)
    

    def Restore(self):

        tlw, obj = self._window, self._pObject

        x, y = obj.RestoreValue(PERSIST_TLW_X), obj.RestoreValue(PERSIST_TLW_Y)
        w, h = obj.RestoreValue(PERSIST_TLW_W), obj.RestoreValue(PERSIST_TLW_H)

        hasPos = x is not None and y is not None
        hasSize = w is not None and h is not None
        
        if hasPos:
            # To avoid making the window completely invisible if it had been
            # shown on a monitor which was disconnected since the last run
            # (this is pretty common for notebook with external displays)
            #
            # NB: we should allow window position to be (slightly) off screen,
            #     it's not uncommon to position the window so that its upper
            #     left corner has slightly negative coordinate
            if wx.Display.GetFromPoint(wx.Point(x, y)) != wx.NOT_FOUND or \
               (hasSize and wx.Display.GetFromPoint(wx.Point(x+w, y+h)) != wx.NOT_FOUND):
                tlw.Move(wx.Point(x, y), wx.SIZE_ALLOW_MINUS_ONE)

            # else: should we try to adjust position/size somehow?

        if hasSize:
            tlw.SetSize((w, h))

        # Note that the window can be both maximized and iconized
        maximized = obj.RestoreValue(PERSIST_TLW_MAXIMIZED)
        if maximized:
            tlw.Maximize()

        iconized = obj.RestoreValue(PERSIST_TLW_ICONIZED)
        if iconized:
            tlw.Iconize()

        # The most important property of the window that we restore is its
        # size, so disregard the value of hasPos here
        return (hasSize and AUIHandler.Restore(self))
    

    def GetKind(self):

        return PERSIST_TLW_KIND


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

class CheckBoxHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`CheckBox` state.

    This class handles the following wxPython widgets:
    
    - :class:`CheckBox`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        check, obj = self._window, self._pObject

        if check.Is3State():
            obj.SaveCtrlValue(PERSIST_CHECKBOX_3STATE, check.Get3StateValue())
        else:
            obj.SaveCtrlValue(PERSIST_CHECKBOX, check.GetValue())
                    
        return True
    

    def Restore(self):

        check, obj = self._window, self._pObject

        if check.Is3State():
            value = obj.RestoreCtrlValue(PERSIST_CHECKBOX_3STATE)
            if value is not None:
                check.Set3StateValue(value)
                return True
        else:
            value = obj.RestoreCtrlValue(PERSIST_CHECKBOX)
            if value is not None:
                check.SetValue(value)
                return True
        
        return False


    def GetKind(self):

        return PERSIST_CHECKBOX_KIND


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

class ListBoxHandler(AbstractHandler):
    """
    Supports saving/restoring selected items in :class:`ListBox`, :class:`ListCtrl`, :class:`ListView`,
    :class:`VListBox`, :class:`HtmlListBox`, :class:`SimpleHtmlListBox`, :class:`gizmos.EditableListBox`.

    This class handles the following wxPython widgets:
    
    - :class:`ListBox`;
    - :class:`ListCtrl` (only for selected items. For column sizes see :class:`ListCtrlHandler`);
    - :class:`ListView` (only for selected items. For column sizes see :class:`ListCtrlHandler`);
    - :class:`VListBox`;
    - :class:`HtmlListBox`;
    - :class:`SimpleHtmlListBox`;
    - :class:`gizmos.EditableListBox`.    
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)


    def GetSelections(self, listBox):
        """
        Returns a list of selected items for :class:`ListBox`, :class:`ListCtrl`, :class:`ListView`,
        :class:`VListBox`, :class:`HtmlListBox`, :class:`SimpleHtmlListBox`, :class:`gizmos.EditableListBox`.

        :param `listBox`: an instance of :class:`ListBox`, :class:`ListCtrl`, :class:`ListView`,
         :class:`VListBox`, :class:`HtmlListBox`, :class:`SimpleHtmlListBox`, :class:`gizmos.EditableListBox`..
        """

        indices = []
        if isinstance(listBox, (wx.HtmlListBox, wx.SimpleHtmlListBox)):
            if listBox.GetSelectedCount() == 0:
                return indices
        else:
            if listBox.GetSelectedItemCount() == 0:
                return indices

        isVirtual = issubclass(listBox.__class__, wx.VListBox)
        
        if isVirtual:
            # This includes wx.SimpleHtmlListBox and wx.HtmlListBox
            if listBox.GetWindowStyleFlag() & wx.LB_SINGLE:
                selection = listBox.GetSelection()
                return (selection >= 0 and [selection] or [indices])[0]
        else:
            # wx.ListCtrl
            if listBox.GetWindowStyleFlag() & wx.LC_SINGLE_SEL:
                selection = listBox.GetSelection()
                return (selection >= 0 and [selection] or [indices])[0]

        if isVirtual:
            item, cookie = listBox.GetFirstSelected()
            while item != wx.NOT_FOUND:
                indices.append(item)
                item, cookie = listBox.GetNextSelected(cookie)

            return indices                

        lastFound = -1
        # Loop until told to stop        
        while 1:
            index = listBox.GetNextItem(lastFound, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
            if index == wx.NOT_FOUND:
                # No item selected
                break
            else:
                # Found one item, append to the list of condemned
                lastFound = index
                indices.append(index)

        return indices
        

    def Save(self):

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True
        
        listBox, obj = self._window, self._pObject

        if issubclass(listBox.__class__, wx.ListBox):
            selections = listBox.GetSelections()
        else:
            selections = self.GetSelections(listBox)
            
        obj.SaveValue(PERSIST_LISTBOX_SELECTIONS, selections)
        return True
    

    def Restore(self):

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True

        listBox, obj = self._window, self._pObject

        isVirtual = issubclass(listBox.__class__, wx.VListBox) or isinstance(listBox, wx.CheckListBox)
        isHtml = isinstance(listBox, wx.HtmlListBox)
        if isVirtual and not isHtml:
            count = listBox.GetCount()
        else:
            count = listBox.GetItemCount()
            
        selections = obj.RestoreValue(PERSIST_LISTBOX_SELECTIONS)
        
        if selections is not None:
            for index in selections:
                if index < count:
                    listBox.Select(index)

            return True

        return False        
    

    def GetKind(self):

        return PERSIST_LISTBOX_KIND


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

class ListCtrlHandler(ListBoxHandler):
    """
    Supports saving/restoring selected items and column sizes in :class:`ListCtrl`.

    This class handles the following wxPython widgets:
    
    - :class:`ListCtrl` (only for column sizes. For selected items see :class:`ListBoxHandler`);
    - :class:`ListView` (only for column sizes. For selected items see :class:`ListBoxHandler`).
    """
    
    def __init__(self, pObject):

        ListBoxHandler.__init__(self, pObject)
        

    def Save(self):

        listCtrl, obj = self._window, self._pObject

        retVal = ListBoxHandler.Save(self)
        
        if not listCtrl.InReportView():
            return retVal
        
        colSizes = []
        for col in xrange(listCtrl.GetColumnCount()):
            colSizes.append(listCtrl.GetColumnWidth(col))
            
        obj.SaveValue(PERSIST_LISTCTRL_COLWIDTHS, colSizes)

        return retVal
    

    def Restore(self):

        listCtrl, obj = self._window, self._pObject
        
        retVal = ListBoxHandler.Restore(self)

        if not listCtrl.InReportView():
            return retVal
        
        colSizes = obj.RestoreValue(PERSIST_LISTCTRL_COLWIDTHS)
        if colSizes is None:
            return False
        
        count = listCtrl.GetColumnCount()
        for col, size in enumerate(colSizes):
            if col < count:
                listCtrl.SetColumnWidth(col, size)

        return retVal
    

    def GetKind(self):

        return PERSIST_LISTCTRL_KIND


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

class CheckListBoxHandler(ListBoxHandler):
    """
    Supports saving/restoring checked and selected items in :class:`CheckListBox`.

    This class handles the following wxPython widgets:
    
    - :class:`CheckListBox` (only for checked items. For selected items see :class:`ListBoxHandler`).

    """
    
    def __init__(self, pObject):

        ListBoxHandler.__init__(self, pObject)
        

    def Save(self):

        checkList, obj = self._window, self._pObject

        checked = []
        for index in xrange(checkList.GetCount()):
            if checkList.IsChecked(index):
                checked.append(index)

        obj.SaveValue(PERSIST_CHECKLIST_CHECKED, checked)

        return ListBoxHandler.Save(self)
        

    def Restore(self):

        checkList, obj = self._window, self._pObject
        
        checked = obj.RestoreValue(PERSIST_CHECKLIST_CHECKED)
        count = checkList.GetCount()
        if checked is not None:
            for index in checked:
                if index < count:
                    checkList.Check(index)
        
        return ListBoxHandler.Restore(self)


    def GetKind(self):

        return PERSIST_CHECKLISTBOX_KIND


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

class ChoiceComboHandler(AbstractHandler):
    """
    Supports saving/restoring :class:`Choice`, :class:`ComboBox` and :class:`combo.OwnerDrawnComboBox`
    selection.

    This class handles the following wxPython widgets:
    
    - :class:`Choice`;
    - :class:`ComboBox`;
    - :class:`combo.OwnerDrawnComboBox`.

    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        combo, obj = self._window, self._pObject

        value = combo.GetStringSelection()
        obj.SaveCtrlValue(PERSIST_CHOICECOMBO_SELECTION, value)
        return True


    def Restore(self):

        combo, obj = self._window, self._pObject
        
        value = obj.RestoreCtrlValue(PERSIST_CHOICECOMBO_SELECTION)
        if value is not None:
            if value in combo.GetStrings():
                combo.SetStringSelection(value)

            return True

        return False
    

    def GetKind(self):

        return PERSIST_CHOICECOMBO_KIND


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

class FoldPanelBarHandler(AbstractHandler):
    """
    Supports saving/restoring of :class:`lib.agw.foldpanelbar.FoldPanelBar`.

    This class handles the following wxPython widgets

    - :class:`lib.agw.foldpanelbar.FoldPanelBar`
    """
  
    def __init__(self, pObject):
    
        AbstractHandler.__init__(self, pObject)
    

    def Save(self):
    
        fpb, obj = self._window, self._pObject
        expanded = [fpb.GetFoldPanel(i).IsExpanded() for i in xrange(fpb.GetCount())]
        obj.SaveValue(PERSIST_FOLDPANELBAR_EXPANDED, expanded)

        return True

  
    def Restore(self):
    
        fpb, obj = self._window, self._pObject
        expanded = obj.RestoreValue(PERSIST_FOLDPANELBAR_EXPANDED)

        if expanded is None:
            return False
        else:
            for idx, expand in enumerate(expanded):
                panel = fpb.GetFoldPanel(idx)
                if expand:
                    fpb.Expand(panel)
                else:
                    fpb.Collapse(panel)

            return True
  
  
    def GetKind(self):
    
        return PERSIST_FOLDPANELBAR_KIND


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

class RadioBoxHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`RadioBox` state.

    This class handles the following wxPython widgets:
    
    - :class:`RadioBox`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        radio, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_RADIOBOX_SELECTION, radio.GetSelection())
        return True
                    

    def Restore(self):

        radio, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_RADIOBOX_SELECTION)
        if value is not None:
            if value < radio.GetCount():
                radio.SetSelection(value)
                return True
        
        return False


    def GetKind(self):

        return PERSIST_RADIOBOX_KIND


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

class RadioButtonHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`RadioButton` state.

    This class handles the following wxPython widgets:
    
    - :class:`RadioButton`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        radio, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_RADIOBUTTON_VALUE, radio.GetValue())
        return True
                    

    def Restore(self):

        radio, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_RADIOBUTTON_VALUE)
        if value is not None:
            radio.SetValue(value)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_RADIOBUTTON_KIND


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

class ScrolledWindowHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`ScrolledWindow` / :class:`lib.scrolledpanel.ScrolledPanel`
    scroll position.

    This class handles the following wxPython widgets:
    
    - :class:`ScrolledWindow`;
    - :class:`lib.scrolledpanel.ScrolledPanel`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        scroll, obj = self._window, self._pObject
        
        scrollPos = scroll.GetScrollPos(wx.HORIZONTAL)
        obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_H, scrollPos)
        scrollPos = scroll.GetScrollPos(wx.VERTICAL)
        obj.SaveValue(PERSIST_SCROLLEDWINDOW_POS_V, scrollPos)
        return True


    def Restore(self):

        scroll, obj = self._window, self._pObject
        hpos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_H)
        vpos = obj.RestoreValue(PERSIST_SCROLLEDWINDOW_POS_V)

        if hpos:
            scroll.SetScrollPos(wx.HORIZONTAL, hpos)
        if vpos:
            scroll.SetScrollPos(wx.VERTICAL, vpos, True)
            
        return True


    def GetKind(self):

        return PERSIST_SCROLLEDWINDOW_KIND


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

class SliderHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`Slider` / :class:`lib.agw.knobctrl.KnobCtrl` thumb position.

    This class handles the following wxPython widgets:
    
    - :class:`Slider`;
    - :class:`lib.agw.knobctrl.KnobCtrl`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        slider, obj = self._window, self._pObject        
        obj.SaveCtrlValue(PERSIST_SLIDER_VALUE, slider.GetValue())
        return True


    def Restore(self):

        slider, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_SLIDER_VALUE)

        if issubclass(slider.__class__, wx.Slider):
            minVal, maxVal = slider.GetMin(), slider.GetMax()
        else:
            # KnobCtrl
            minVal, maxVal = slider.GetMinValue(), slider.GetMaxValue()
            
        if value is not None:
            if value >= minVal and value <= maxVal:
                slider.SetValue(value)
                return True
        
        return False


    def GetKind(self):

        return PERSIST_SLIDER_KIND


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

class SpinHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`SpinButton` / :class:`SpinCtrl` value.

    This class handles the following wxPython widgets:
    
    - :class:`SpinCtrl`;
    - :class:`SpinButton`.    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        spin, obj = self._window, self._pObject        
        obj.SaveCtrlValue(PERSIST_SPIN_VALUE, spin.GetValue())
        return True
    

    def Restore(self):

        spin, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_SPIN_VALUE)

        if value is not None:
            minVal, maxVal = spin.GetMin(), spin.GetMax()
            if value >= minVal and value <= maxVal:
                spin.SetValue(value)
                return True
        
        return False


    def GetKind(self):

        return PERSIST_SPIN_KIND


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

class SplitterHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`SplitterWindow` splitter position.

    This class handles the following wxPython widgets:
    
    - :class:`SplitterWindow`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        splitter, obj = self._window, self._pObject        
        obj.SaveValue(PERSIST_SPLITTER_POSITION, splitter.GetSashPosition())
        return True
    

    def Restore(self):

        splitter, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_SPLITTER_POSITION)

        if value is None:
            return False

        if not splitter.IsSplit():
            return False
                
        width, height = splitter.GetClientSize()
        minPaneSize = splitter.GetMinimumPaneSize()
        direction = splitter.GetSplitMode()

        if direction == wx.SPLIT_HORIZONTAL:
            # Top and bottom panes
            if value > height - minPaneSize:
                return False
        else:
            # Left and right panes
            if value > width - minPaneSize:
                return False
            
        splitter.SetSashPosition(value)
        return True
        

    def GetKind(self):

        return PERSIST_SPLITTER_KIND


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

class TextCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`TextCtrl` entered string.

    This class handles the following wxPython widgets:
    
    - :class:`TextCtrl`;
    - :class:`SearchCtrl`;
    - :class:`lib.expando.ExpandoTextCtrl`;
    - :class:`lib.masked.textctrl.TextCtrl`;
    - :class:`lib.masked.combobox.ComboBox`;
    - :class:`lib.masked.ipaddrctrl.IpAddrCtrl`;
    - :class:`lib.masked.timectrl.TimeCtrl`;
    - :class:`lib.masked.numctrl.NumCtrl`;
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        text, obj = self._window, self._pObject        
        obj.SaveCtrlValue(PERSIST_TEXTCTRL_VALUE, text.GetValue())
        return True
    

    def Restore(self):

        text, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_TEXTCTRL_VALUE)

        if value is not None:
            text.ChangeValue(value)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_TEXTCTRL_KIND


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

class ToggleButtonHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`ToggleButton` and friends state.

    This class handles the following wxPython widgets:

    - :class:`ToggleButton`;
    - :class:`lib.buttons.GenToggleButton`;
    - :class:`lib.buttons.GenBitmapToggleButton`;
    - :class:`lib.buttons.GenBitmapTextToggleButton`;
    - :class:`lib.agw.shapedbutton.SToggleButton`;
    - :class:`lib.agw.shapedbutton.SBitmapToggleButton`;
    - :class:`lib.agw.shapedbutton.SBitmapTextToggleButton`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        toggle, obj = self._window, self._pObject        
        obj.SaveValue(PERSIST_TOGGLEBUTTON_TOGGLED, toggle.GetValue())
        return True
    

    def Restore(self):

        toggle, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_TOGGLEBUTTON_TOGGLED)

        if value is not None:
            toggle.SetValue(value)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_TOGGLEBUTTON_KIND

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

class TreeCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`TreeCtrl` expansion state, selections and
    checked items state (meaningful only for :class:`lib.agw.customtreectrl.CustomTreeCtrl`).

    This class handles the following wxPython widgets:

    - :class:`TreeCtrl`;
    - :class:`GenericDirCtrl`;
    - :class:`lib.agw.customtreectrl.CustomTreeCtrl`;
    - :class:`lib.agw.hypertreelist.HyperTreeList`;    

    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        self._isTreeList = isinstance(pObject.GetWindow(), wx.gizmos.TreeListCtrl)
        

    def GetItemChildren(self, item=None, recursively=False):
        """
        Return the children of item as a list.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item;
        :param `recursively`: whether to recurse into the item hierarchy or not.
        """

        if not item:
            item = self._window.GetRootItem()
            if not item:
                return []

        children = []
        child, cookie = self._window.GetFirstChild(item)

        while child and child.IsOk():
            children.append(child)
            if recursively:
                children.extend(self.GetItemChildren(child, True))
            child, cookie = self._window.GetNextChild(item, cookie)

        return children


    def GetIndexOfItem(self, item):
        """
        Return the index of item.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item;
        """
        
        parent = self._window.GetItemParent(item)
        if parent:
            parentIndices = self.GetIndexOfItem(parent)
            ownIndex = self.GetItemChildren(parent).index(item)
            return parentIndices + (ownIndex,)
        else:
            return ()
        

    def GetItemIdentity(self, item):
        """
        Return a hashable object that represents the identity of the
        item. By default this returns the position of the item in the 
        tree. You may want to override this to return the item label 
        (if you know that labels are unique and don't change), or return 
        something that represents the underlying domain object, e.g. 
        a database key.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item;        
        """

        return self.GetIndexOfItem(item)
 

    def GetExpansionState(self):
        """
        Returns list of expanded items. Expanded items are coded as determined by
        the result of :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GetExpansionStateOfChildren(root)
        else:
            return self.GetExpansionStateOfItem(root)


    def SetExpansionState(self, listOfExpandedItems):
        """
        Expands all tree items whose identity, as determined by :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`,
        is present in the list and collapses all other tree items.

        :param `listOfExpandedItems`: a list of expanded :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetExpansionStateOfChildren(listOfExpandedItems, root)
        else:
            self.SetExpansionStateOfItem(listOfExpandedItems, root)


    def GetSelectionState(self):
        """
        Returns a list of selected items. Selected items are coded as determined by
        the result of :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GeSelectionStateOfChildren(root)
        else:
            return self.GetSelectionStateOfItem(root)


    def SetSelectionState(self, listOfSelectedItems):
        """
        Selects all tree items whose identity, as determined by :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`,
        is present in the list and unselects all other tree items.

        :param `listOfSelectedItems`: a list of selected :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetSelectedStateOfChildren(listOfSelectedItems, root)
        else:
            self.SetSelectedStateOfItem(listOfSelectedItems, root)

            
    def GetCheckedState(self):
        """
        Returns a list of checked items. Checked items are coded as determined by
        the result of :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`.
        
        :note:

         This is meaningful only for :class:`~lib.agw.customtreectrl.CustomTreeCtrl` and
         :class:`~lib.agw.hypertreelist.HyperTreeList`.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return []
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            return self.GetCheckedStateOfChildren(root)
        else:
            return self.GetCheckedStateOfItem(root)


    def SetCheckedState(self, listOfCheckedItems):
        """
        Checks all tree items whose identity, as determined by :meth:`TreeCtrlHandler.GetItemIdentity() <TreeCtrlHandler.GetItemIdentity>`, is present
        in the list and unchecks all other tree items.
        
        :param `listOfCheckedItems`: a list of checked :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items.

        :note:

         This is meaningful only for :class:`~lib.agw.customtreectrl.CustomTreeCtrl` and
         :class:`~lib.agw.hypertreelist.HyperTreeList`.
        """
        
        root = self._window.GetRootItem()
        if not root:
            return
        if self._window.HasFlag(wx.TR_HIDE_ROOT):
            self.SetCheckedStateOfChildren(listOfCheckedItems, root)
        else:
            self.SetCheckedStateOfItem(listOfCheckedItems, root)


    def GetExpansionStateOfItem(self, item):
        """
        Returns the expansion state of a tree item.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfExpandedItems = []
        if self._window.IsExpanded(item):
            listOfExpandedItems.append(self.GetItemIdentity(item))
            listOfExpandedItems.extend(self.GetExpansionStateOfChildren(item))
            
        return listOfExpandedItems


    def GetExpansionStateOfChildren(self, item):
        """
        Returns the expansion state of the children of a tree item.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfExpandedItems = []
        for child in self.GetItemChildren(item):
            listOfExpandedItems.extend(self.GetExpansionStateOfItem(child))

        return listOfExpandedItems


    def GetCheckedStateOfItem(self, item):
        """
        Returns the checked/unchecked state of a tree item.

        :param `item`: a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfCheckedItems = []
        if self._window.IsItemChecked(item):
            listOfCheckedItems.append(self.GetItemIdentity(item))
            
        listOfCheckedItems.extend(self.GetCheckedStateOfChildren(item))
            
        return listOfCheckedItems


    def GetCheckedStateOfChildren(self, item):
        """
        Returns the checked/unchecked state of the children of a tree item.

        :param `item`: a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfCheckedItems = []
        for child in self.GetItemChildren(item):
            listOfCheckedItems.extend(self.GetCheckedStateOfItem(child))

        return listOfCheckedItems


    def GetSelectionStateOfItem(self, item):
        """
        Returns the selection state of a tree item.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfSelectedItems = []
        if self._window.IsSelected(item):
            listOfSelectedItems.append(self.GetItemIdentity(item))
            
        listOfSelectedItems.extend(self.GetSelectionStateOfChildren(item))
        return listOfSelectedItems


    def GetSelectionStateOfChildren(self, item):
        """
        Returns the selection state of the children of a tree item.

        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        listOfSelectedItems = []
        for child in self.GetItemChildren(item):
            listOfSelectedItems.extend(self.GetSelectionStateOfItem(child))

        return listOfSelectedItems


    def SetExpansionStateOfItem(self, listOfExpandedItems, item):
        """
        Sets the expansion state of a tree item (expanded or collapsed).

        :param `listOfExpandedItems`: a list of expanded :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        if self.GetItemIdentity(item) in listOfExpandedItems:
            self._window.Expand(item)
            self.SetExpansionStateOfChildren(listOfExpandedItems, item)
        else:
            self._window.Collapse(item)


    def SetExpansionStateOfChildren(self, listOfExpandedItems, item):
        """
        Sets the expansion state of the children of a tree item (expanded or collapsed).

        :param `listOfExpandedItems`: a list of expanded :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """

        for child in self.GetItemChildren(item):
            self.SetExpansionStateOfItem(listOfExpandedItems, child)


    def SetCheckedStateOfItem(self, listOfCheckedItems, item):
        """
        Sets the checked/unchecked state of a tree item.

        :param `listOfCheckedItems`: a list of checked :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """

        if self.GetItemIdentity(item) in listOfCheckedItems:
            self._window.CheckItem2(item, True)
        else:
            self._window.CheckItem2(item, False)

        self.SetCheckedStateOfChildren(listOfCheckedItems, item)


    def SetCheckedStateOfChildren(self, listOfCheckedItems, item):
        """
        Sets the checked/unchecked state of the children of a tree item.

        :param `listOfCheckedItems`: a list of checked :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """

        for child in self.GetItemChildren(item):
            self.SetCheckedStateOfItem(listOfCheckedItems, child)


    def SetSelectedStateOfItem(self, listOfSelectedItems, item):
        """
        Sets the selection state of a tree item.

        :param `listOfSelectedItems`: a list of selected :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """

        if self.GetItemIdentity(item) in listOfSelectedItems:
            if self._isTreeList:
                self._window.SelectItem(item, unselect_others=False)
            else:
                self._window.SelectItem(item)

        self.SetSelectedStateOfChildren(listOfSelectedItems, item)


    def SetSelectedStateOfChildren(self, listOfSelectedItems, item):
        """
        Sets the selection state of the children of a tree item.

        :param `listOfSelectedItems`: a list of selected :class:`TreeCtrl` or
         :class:`~lib.agw.customtreectrl.CustomTreeCtrl` items;
        :param `item`: a :class:`TreeCtrl` item or a :class:`~lib.agw.customtreectrl.CustomTreeCtrl` item.
        """
        
        for child in self.GetItemChildren(item):
            self.SetSelectedStateOfItem(listOfSelectedItems, child)


    def Save(self):

        tree, obj = self._window, self._pObject

        obj.SaveCtrlValue(PERSIST_TREECTRL_EXPANSION, self.GetExpansionState())

        if issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):
            obj.SaveCtrlValue(PERSIST_TREECTRL_CHECKED_ITEMS, self.GetCheckedState())
            
        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS == 0:
            # We don't want to save selected items
            return True
    
        obj.SaveCtrlValue(PERSIST_TREECTRL_SELECTIONS, self.GetSelectionState())
        return True
    

    def Restore(self):

        tree, obj = self._window, self._pObject
        expansion = obj.RestoreCtrlValue(PERSIST_TREECTRL_EXPANSION)
        selections = obj.RestoreCtrlValue(PERSIST_TREECTRL_SELECTIONS)
        
        if expansion is not None:
            self.SetExpansionState(expansion)

        manager = PM.PersistenceManager.Get()
        if manager.GetManagerStyle() & PM_SAVE_RESTORE_TREE_LIST_SELECTIONS:
            # We want to restore selected items
            if selections is not None:
                self.SetSelectionState(selections)

        if not issubclass(tree.__class__, (HTL.HyperTreeList, CT.CustomTreeCtrl)):
            return (expansion is not None and selections is not None)

        checked = obj.RestoreCtrlValue(PERSIST_TREECTRL_CHECKED_ITEMS)
        if checked is not None:
            self.SetCheckedState(checked)
            
        return (expansion is not None and selections is not None and checked is not None)


    def GetKind(self):

        return PERSIST_TREECTRL_KIND


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

class TreeListCtrlHandler(TreeCtrlHandler):
    """
    Supports saving/restoring a :class:`gizmos.TreeListCtrl` / :class:`lib.agw.hypertreelist.HyperTreeList` expansion state,
    selections, column widths and checked items state (meaningful only for :class:`~lib.agw.hypertreelist.HyperTreeList`).

    This class handles the following wxPython widgets:

    - :class:`gizmos.TreeListCtrl`;
    - :class:`lib.agw.hypertreelist.HyperTreeList`.
    
    """
    
    def __init__(self, pObject):

        TreeCtrlHandler.__init__(self, pObject)

            
    def Save(self):

        treeList, obj = self._window, self._pObject

        colSizes = []
        for col in xrange(treeList.GetColumnCount()):
            colSizes.append(treeList.GetColumnWidth(col))
        
        obj.SaveValue(PERSIST_TREELISTCTRL_COLWIDTHS, colSizes)

        return TreeCtrlHandler.Save(self)
    

    def Restore(self):

        treeList, obj = self._window, self._pObject
        colSizes = obj.RestoreValue(PERSIST_TREELISTCTRL_COLWIDTHS)
        retVal = False

        count = treeList.GetColumnCount()        
        if colSizes is not None:
            retVal = True
            for col, size in enumerate(colSizes):
                if col < count:
                    treeList.SetColumnWidth(col, size)
                
        return (retVal and TreeCtrlHandler.Restore(self))
    

    def GetKind(self):

        return PERSIST_TREELISTCTRL_KIND


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

class CalendarCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`calendar.CalendarCtrl` date.

    This class handles the following wxPython widgets:

    - :class:`lib.calendar.CalendarCtrl`.

    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        calend, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_CALENDAR_DATE, wxDate2PyDate(calend.GetDate()))
        return True
    

    def Restore(self):

        calend, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_CALENDAR_DATE)

        if value is not None:
            calend.SetDate(PyDate2wxDate(value))
            return True
        
        return False


    def GetKind(self):

        return PERSIST_CALENDAR_KIND


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

class CollapsiblePaneHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`CollapsiblePane` / :class:`lib.agw.pycollapsiblepane.PyCollapsiblePane` state.

    This class handles the following wxPython widgets:

    - :class:`CollapsiblePane`;
    - :class:`lib.agw.pycollapsiblepane.PyCollapsiblePane`.    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        collPane, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_COLLAPSIBLE_STATE, collPane.IsCollapsed())
        return True
    

    def Restore(self):

        collPane, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_COLLAPSIBLE_STATE)

        if value is not None:
            collPane.Collapse(value)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_COLLAPSIBLE_KIND


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

class DatePickerHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`DatePickerCtrl` / :class:`GenericDatePickerCtrl` date.

    This class handles the following wxPython widgets:

    - :class:`DatePickerCtrl`;
    - :class:`GenericDatePickerCtrl`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        datePicker, obj = self._window, self._pObject
        obj.SaveCtrlValue(PERSIST_DATEPICKER_DATE, wxDate2PyDate(datePicker.GetValue()))
        return True
    

    def Restore(self):

        datePicker, obj = self._window, self._pObject
        value = obj.RestoreCtrlValue(PERSIST_DATEPICKER_DATE)

        if value is not None:
            datePicker.SetValue(PyDate2wxDate(value))
            return True
        
        return False


    def GetKind(self):

        return PERSIST_DATEPICKER_KIND


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

class MediaCtrlHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`media.MediaCtrl` movie position, volume and playback
    rate.

    This class handles the following wxPython widgets:

    - :class:`media.MediaCtrl`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        mediaCtrl, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_MEDIA_POS, mediaCtrl.Tell())
        obj.SaveValue(PERSIST_MEDIA_VOLUME, mediaCtrl.GetVolume())
        obj.SaveValue(PERSIST_MEDIA_RATE, mediaCtrl.GetPlaybackRate())
        return True
    

    def Restore(self):

        mediaCtrl, obj = self._window, self._pObject
        position = obj.RestoreValue(PERSIST_MEDIA_POS)
        volume = obj.RestoreValue(PERSIST_MEDIA_VOLUME)
        rate = obj.RestoreValue(PERSIST_MEDIA_RATE)
        
        if position is not None:
            mediaCtrl.Seek(position)

        if volume is not None:
            mediaCtrl.SetVolume(volume)

        if rate is not None:
            mediaCtrl.SetPlaybackRate(rate)
        
        return (osition is not None and volume is not None and rate is not None)


    def GetKind(self):

        return PERSIST_MEDIA_KIND


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

class ColourPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`ColourPickerCtrl` / :class:`lib.colourselect.ColourSelect` colour.

    This class handles the following wxPython widgets:

    - :class:`ColourPickerCtrl`;
    - :class:`lib.colourselect.ColourSelect`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        colPicker, obj = self._window, self._pObject
        obj.SaveValue(PERSIST_COLOURPICKER_COLOUR, colPicker.GetColour().Get(includeAlpha=True))
        return True
    

    def Restore(self):

        colPicker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_COLOURPICKER_COLOUR)

        if value is not None:
            colPicker.SetColour(wx.Colour(*value))
            return True
        
        return False


    def GetKind(self):

        return PERSIST_COLOURPICKER_KIND


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

class FileDirPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`FilePickerCtrl` / :class:`DirPickerCtrl` path.

    This class handles the following wxPython widgets:

    - :class:`FilePickerCtrl`;
    - :class:`DirPickerCtrl`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        picker, obj = self._window, self._pObject

        path = picker.GetPath()        
        if issubclass(picker.__class__, wx.FileDialog):
            if picker.GetWindowStyleFlag() & wx.FD_MULTIPLE:
                path = picker.GetPaths()
            
        obj.SaveValue(PERSIST_FILEDIRPICKER_PATH, path)
        return True
    

    def Restore(self):

        picker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FILEDIRPICKER_PATH)

        if value is not None:
            if issubclass(picker.__class__, wx.FileDialog):
                if type(value) == types.ListType:
                    value = value[-1]
                        
            picker.SetPath(value)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_FILEDIRPICKER_KIND


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

class FontPickerHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`FontPickerCtrl` font.

    This class handles the following wxPython widgets:

    - :class:`FontPickerCtrl`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        picker, obj = self._window, self._pObject
        
        font = picker.GetSelectedFont()
        if not font.IsOk():
            return False
        
        fontData = CreateFont(font)                                 
        obj.SaveValue(PERSIST_FONTPICKER_FONT, fontData)
        return True
    

    def Restore(self):

        picker, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FONTPICKER_FONT)

        if value is not None:
            font = wx.Font(*value)
            if font.IsOk():
                picker.SetSelectedFont(font)
                return True
        
        return False


    def GetKind(self):

        return PERSIST_FONTPICKER_KIND


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

class FileHistoryHandler(AbstractHandler):
    """
    Supports saving/restoring a :class:`FileHistory` list of file names.

    This class handles the following wxPython widgets:

    - :class:`FileHistory`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        history, obj = self._window, self._pObject
        
        paths = []
        for indx in xrange(history.GetCount()):
            paths.append(history.GetHistoryFile(indx))
            
        obj.SaveValue(PERSIST_FILEHISTORY_PATHS, paths)
        return True
    

    def Restore(self):

        history, obj = self._window, self._pObject
        value = obj.RestoreValue(PERSIST_FILEHISTORY_PATHS)

        if value is not None:
            count = history.GetMaxFiles()
            for indx, path in enumerate(value):
                if indx < count:
                    history.AddFileToHistory(path)
            return True
        
        return False


    def GetKind(self):

        return PERSIST_FILEHISTORY_KIND


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

class MenuBarHandler(AbstractHandler):
    """
    Supports saving/restoring the :class:`MenuBar` and :class:`lib.agw.flatmenu.FlatMenuBar` items state.

    This class handles the following wxPython widgets:

    - :class:`MenuBar`;
    - :class:`lib.agw.flatmenu.FlatMenuBar`.
    
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        bar, obj = self._window, self._pObject
        menuCount = bar.GetMenuCount()

        if menuCount == 0:
            # Nothing to save
            return False

        checkRadioItems = {}
        for indx in xrange(menuCount):
            menu = bar.GetMenu(indx)
            for item in menu.GetMenuItems():
                if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:
                    checkRadioItems[item.GetId()] = item.IsChecked()
            
        obj.SaveValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS, checkRadioItems)
        return True


    def Restore(self):

        bar, obj = self._window, self._pObject
        menuCount = bar.GetMenuCount()

        if menuCount == 0:
            # Nothing to restore
            return False

        checkRadioItems = obj.RestoreValue(PERSIST_MENUBAR_CHECKRADIO_ITEMS)

        if checkRadioItems is None:
            return False
        
        retVal = True
        for indx in xrange(menuCount):
            menu = bar.GetMenu(indx)
            for item in menu.GetMenuItems():
                if item.GetKind() in [wx.ITEM_CHECK, wx.ITEM_RADIO]:
                    itemId = item.GetId()
                    if itemId in checkRadioItems:
                        item.Check(checkRadioItems[itemId])
                    else:
                        retVal = False

        return retVal                        
        

    def GetKind(self):

        return PERSIST_MENUBAR_KIND


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

class ToolBarHandler(AbstractHandler):
    """
    Supports saving/restoring the :class:`lib.agw.aui.auibar.AuiToolBar` items state.

    This class handles the following wxPython widgets:

    - :class:`lib.agw.aui.auibar.AuiToolBar`.

    .. todo::

       Find a way to handle :class:`ToolBar` UI settings as it has been done for
       :class:`lib.agw.aui.auibar.AuiToolBar`: currently :class:`ToolBar` doesn't seem
       to have easy access to the underlying toolbar tools.
       
    """
    
    def __init__(self, pObject):

        AbstractHandler.__init__(self, pObject)
        

    def Save(self):

        bar, obj = self._window, self._pObject
        toolCount = bar.GetToolCount()

        if toolCount == 0:
            # Nothing to save
            return False

        checkRadioItems = {}
        for indx in xrange(toolCount):
            tool = bar.FindToolByIndex(indx)
            if tool is not None:
                if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:
                    checkRadioItems[tool.GetId()] = tool.GetState() & AUI.AUI_BUTTON_STATE_CHECKED
            
        obj.SaveValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS, checkRadioItems)
        return True
    

    def Restore(self):

        bar, obj = self._window, self._pObject
        toolCount = bar.GetToolCount()

        if toolCount == 0:
            # Nothing to save
            return False

        checkRadioItems = obj.RestoreValue(PERSIST_TOOLBAR_CHECKRADIO_ITEMS)

        if checkRadioItems is None:
            return False
        
        for indx in xrange(toolCount):
            tool = bar.FindToolByIndex(indx)
            if tool is not None:
                toolId = tool.GetId()
                if toolId in checkRadioItems:
                    if tool.GetKind() in [AUI.ITEM_CHECK, AUI.ITEM_RADIO]:
                        state = checkRadioItems[toolId]
                        if state & AUI.AUI_BUTTON_STATE_CHECKED:                            
                            tool.SetState(tool.GetState() | AUI.AUI_BUTTON_STATE_CHECKED)
                        else:
                            tool.SetState(tool.GetState() & ~AUI.AUI_BUTTON_STATE_CHECKED)
                            
        return True
        

    def GetKind(self):

        return PERSIST_TOOLBAR_KIND
    
# ----------------------------------------------------------------------------------- #

class FileDirDialogHandler(TLWHandler, FileDirPickerHandler):
    """
    Supports saving/restoring a :class:`DirDialog` / :class:`FileDialog` path.

    This class handles the following wxPython widgets:

    - :class:`DirDialog`;
    - :class:`FileDialog`.
    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        FileDirPickerHandler.__init__(self, pObject)
        

    def Save(self):

        tlw = TLWHandler.Save(self)
        fdp = FileDirPickerHandler.Save(self)
        
        return (tlw and fdp)
    

    def Restore(self):

        tlw = TLWHandler.Restore(self)
        fdp = FileDirPickerHandler.Restore(self)
        return (tlw and fdp)
        

    def GetKind(self):

        return PERSIST_FILEDIRPICKER_KIND


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

class FindReplaceHandler(TLWHandler):
    """
    Supports saving/restoring a :class:`FindReplaceDialog` data (search string, replace string
    and flags).

    This class handles the following wxPython widgets:

    - :class:`FindReplaceDialog`.

    .. todo:: Find a way to properly save and restore dialog data (:class:`ColourDialog`, :class:`FontDialog` etc...).

    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        

    def Save(self):

        findDialog, obj = self._window, self._pObject
        data = findDialog.GetData()
                                         
        obj.SaveValue(PERSIST_FINDREPLACE_FLAGS, data.GetFlags())
        obj.SaveValue(PERSIST_FINDREPLACE_SEARCH, data.GetFindString())
        obj.SaveValue(PERSIST_FINDREPLACE_REPLACE, data.GetReplaceString())

        return TLWHandler.Save(self)
    

    def Restore(self):

        findDialog, obj = self._window, self._pObject
        
        flags = obj.RestoreValue(PERSIST_FINDREPLACE_FLAGS)
        search = obj.RestoreValue(PERSIST_FINDREPLACE_SEARCH)
        replace = obj.RestoreValue(PERSIST_FINDREPLACE_REPLACE)

        data = findDialog.GetData()
        if flags is not None:
            data.SetFlags(flags)
        if search is not None:
            data.SetFindString(search)
        if replace is not None:
            data.SetReplaceString(replace)

        retVal = TLWHandler.Restore(self)
        
        return (flags is not None and search is not None and replace is not None and retVal)


    def GetKind(self):

        return PERSIST_FINDREPLACE_KIND


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

class FontDialogHandler(TLWHandler):
    """
    Supports saving/restoring a :class:`FontDialog` data (effects, symbols, colour, font, help).

    This class handles the following wxPython widgets:

    - :class:`FontDialog`.
    
    .. todo:: Find a way to properly save and restore dialog data (:class:`ColourDialog`, :class:`FontDialog` etc...).

    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        

    def Save(self):

        fontDialog, obj = self._window, self._pObject
        data = fontDialog.GetFontData()
        
        obj.SaveValue(PERSIST_FONTDIALOG_EFFECTS, data.GetEnableEffects())
        obj.SaveValue(PERSIST_FONTDIALOG_SYMBOLS, data.GetAllowSymbols())
        obj.SaveValue(PERSIST_FONTDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))
        obj.SaveValue(PERSIST_FONTDIALOG_FONT, CreateFont(data.GetChosenFont()))
        obj.SaveValue(PERSIST_FONTDIALOG_HELP, data.GetShowHelp())

        return TLWHandler.Save(self)
    

    def Restore(self):

        fontDialog, obj = self._window, self._pObject
        data = fontDialog.GetFontData()

        effects = obj.RestoreValue(PERSIST_FONTDIALOG_EFFECTS)
        symbols = obj.RestoreValue(PERSIST_FONTDIALOG_SYMBOLS)
        colour = obj.RestoreValue(PERSIST_FONTDIALOG_COLOUR)
        font = obj.RestoreValue(PERSIST_FONTDIALOG_FONT)
        help = obj.RestoreValue(PERSIST_FONTDIALOG_HELP)

        if effects is not None:
            data.EnableEffects(effects)
        if symbols is not None:
            data.SetAllowSymbols(symbols)
        if colour is not None:
            data.SetColour(wx.Colour(*colour))
        if font is not None:
            data.SetInitialFont(wx.Font(*font))
        if help is not None:
            data.SetShowHelp(help)
            
        return (effects is not None and symbols is not None and colour is not None and \
                font is not None and help is not None and TLWHandler.Restore(self))


    def GetKind(self):

        return PERSIST_FONTDIALOG_KIND


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

class ColourDialogHandler(TLWHandler):
    """
    Supports saving/restoring a :class:`ColourDialog` data (colour, custom colours and full
    choice in the dialog).

    This class handles the following wxPython widgets:

    - :class:`ColourDialog`;
    - :class:`lib.agw.cubecolourdialog.CubeColourDialog`.

    .. todo:: Find a way to properly save and restore dialog data (:class:`ColourDialog`, :class:`FontDialog` etc...).

    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        

    def Save(self):

        colDialog, obj = self._window, self._pObject
        data = colDialog.GetColourData()

        obj.SaveValue(PERSIST_COLOURDIALOG_COLOUR, data.GetColour().Get(includeAlpha=True))
        obj.SaveValue(PERSIST_COLOURDIALOG_CHOOSEFULL, data.GetChooseFull())

        customColours = []
        for indx in xrange(15):
            colour = data.GetCustomColour(indx)
            if not colour.IsOk() or colour == wx.WHITE:
                break
            
            customColours.append(colour.Get(includeAlpha=True))
        
        obj.SaveValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS, customColours)

        return TLWHandler.Save(self)
    

    def Restore(self):

        colDialog, obj = self._window, self._pObject
        data = colDialog.GetColourData()

        colour = obj.RestoreValue(PERSIST_COLOURDIALOG_COLOUR)
        chooseFull = obj.RestoreValue(PERSIST_COLOURDIALOG_CHOOSEFULL)
        customColours = obj.RestoreValue(PERSIST_COLOURDIALOG_CUSTOMCOLOURS)

        if colour is not None:
            data.SetColour(wx.Colour(*colour))
        if chooseFull is not None:
            data.SetChooseFull(chooseFull)
        if customColours is not None:
            for indx, colour in enumerate(customColours):
                data.SetCustomColour(indx, colour)
            
        return (colour is not None and chooseFull is not None and customColours is not None \
                and TLWHandler.Restore(self))


    def GetKind(self):

        return PERSIST_COLOURDIALOG_KIND


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

class ChoiceDialogHandler(TLWHandler):
    """
    Supports saving/restoring a :class:`MultiChoiceDialog` / :class:`SingleChoiceDialog` choices.

    This class handles the following wxPython widgets:

    - :class:`SingleChoiceDialog`;
    - :class:`MultiChoiceDialog`.
    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        

    def Save(self):

        dialog, obj = self._window, self._pObject

        if issubclass(dialog.__class__, wx.SingleChoiceDialog):
            selections = dialog.GetSelection()
            selections = (selections >= 0 and [selections] or [[]])[0]
        else:
            selections = dialog.GetSelections()
            
        obj.SaveValue(PERSIST_CHOICEDIALOG_SELECTIONS, selections)
        return True
    

    def Restore(self):

        dialog, obj = self._window, self._pObject
        selections = obj.RestoreValue(PERSIST_CHOICEDIALOG_SELECTIONS)

        if selections is None:
            return False
        
        if issubclass(dialog.__class__, wx.SingleChoiceDialog):
            if selections:
                dialog.SetSelection(selections[-1])
        else:
            dialog.SetSelections(selections)

        return True
    

    def GetKind(self):

        return PERSIST_CHOICEDIALOG_KIND


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

class TextEntryHandler(TLWHandler, TextCtrlHandler):
    """
    Supports saving/restoring a :class:`TextEntryDialog` string.

    This class handles the following wxPython widgets:

    - :class:`TextEntryDialog`;
    - :class:`PasswordEntryDialog`.
    """
    
    def __init__(self, pObject):

        TLWHandler.__init__(self, pObject)
        TextCtrlHandler.__init__(self, pObject)
        

    def Save(self):

        tlw = TLWHandler.Save(self)
        txt = TextCtrlHandler.Save(self)
        return (tlw and txt)
    

    def Restore(self):

        tlw = TLWHandler.Restore(self)
        txt = TextCtrlHandler.Restore(self)
        return (tlw and txt)
        

    def GetKind(self):

        return PERSIST_TLW_KIND

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


HANDLERS = [
    ("BookHandler", (wx.BookCtrlBase, wx.aui.AuiNotebook, AUI.AuiNotebook, FNB.FlatNotebook,
                    LBK.LabelBook, LBK.FlatImageBook)),
    ("TLWHandler", (wx.TopLevelWindow, )),
    ("CheckBoxHandler", (wx.CheckBox, )), 
    ("TreeCtrlHandler", (wx.TreeCtrl, wx.GenericDirCtrl, CT.CustomTreeCtrl)), 
    ("MenuBarHandler", (wx.MenuBar, FM.FlatMenuBar)), 
    ("ToolBarHandler", (AUI.AuiToolBar, )),
    ("ListBoxHandler", (wx.ListBox, wx.VListBox, wx.HtmlListBox, wx.SimpleHtmlListBox,
                        wx.gizmos.EditableListBox)), 
    ("ListCtrlHandler", (wx.ListCtrl, wx.ListView)),  #ULC.UltimateListCtrl (later)
    ("ChoiceComboHandler", (wx.Choice, wx.ComboBox, wx.combo.OwnerDrawnComboBox)), 
    ("RadioBoxHandler", (wx.RadioBox, )), 
    ("RadioButtonHandler", (wx.RadioButton, )), 
    ("ScrolledWindowHandler", (wx.ScrolledWindow, scrolled.ScrolledPanel)), 
    ("SliderHandler", (wx.Slider, KC.KnobCtrl)), 
    ("SpinHandler", (wx.SpinButton, wx.SpinCtrl, FS.FloatSpin)), 
    ("SplitterHandler", (wx.SplitterWindow, )), 
    ("TextCtrlHandler", (wx.TextCtrl, wx.SearchCtrl, expando.ExpandoTextCtrl, masked.TextCtrl,
                        masked.ComboBox, masked.IpAddrCtrl, masked.TimeCtrl, masked.NumCtrl)), 
    ("TreeListCtrlHandler", (HTL.HyperTreeList, wx.gizmos.TreeListCtrl)), 
    ("CalendarCtrlHandler", (calendar.CalendarCtrl, )), 
    ("CollapsiblePaneHandler", (wx.CollapsiblePane, PCP.PyCollapsiblePane)), 
    ("AUIHandler", (wx.Panel, )),
    ("DatePickerHandler", (wx.DatePickerCtrl, wx.GenericDatePickerCtrl)), 
    ("ColourPickerHandler", (wx.ColourPickerCtrl, csel.ColourSelect)), 
    ("FileDirPickerHandler", (wx.FilePickerCtrl, wx.DirPickerCtrl)), 
    ("FontPickerHandler", (wx.FontPickerCtrl, )), 
    ("FileHistoryHandler", (wx.FileHistory, )), 
    ("ToggleButtonHandler", (wx.ToggleButton, buttons.GenToggleButton,
                            buttons.GenBitmapToggleButton, buttons.GenBitmapTextToggleButton)), 
    ]

if hasattr(wx, 'media'):
    HANDLERS.append(("MediaCtrlHandler", (wx.media.MediaCtrl, )))

STANDALONE_HANDLERS = [
    ("TreebookHandler", (wx.Treebook, )), 
    ("CheckListBoxHandler", (wx.CheckListBox, )), 
    ("FileDirDialogHandler", (wx.DirDialog, wx.FileDialog)), 
    ("FindReplaceHandler", (wx.FindReplaceDialog, )), 
    ("FontDialogHandler", (wx.FontDialog, )), 
    ("ColourDialogHandler", (wx.ColourDialog, CCD.CubeColourDialog)), 
    ("ChoiceDialogHandler", (wx.SingleChoiceDialog, wx.MultiChoiceDialog)), 
    ("TextEntryHandler", (wx.TextEntryDialog, wx.PasswordEntryDialog)), 
    ]

if hasSB:
    HANDLERS[-1] = ("ToggleButtonHandler", (wx.ToggleButton, buttons.GenToggleButton,
                                            buttons.GenBitmapToggleButton,
                                            buttons.GenBitmapTextToggleButton,
                                            SB.SToggleButton, SB.SBitmapToggleButton,
                                            SB.SBitmapTextToggleButton))
    
# ----------------------------------------------------------------------------------- #

def FindHandler(pObject):
    """
    Finds a suitable handler for the input `Persistent Object` depending on the
    widget kind.

    :param `pObject`: an instance of :class:`~lib.agw.persist.persistencemanager.PersistentObject` class.
    """

    window = pObject.GetWindow()
    klass = window.__class__

    if hasattr(window, "_persistentHandler"):
        # if control has a handler, just return it
        return window._persistentHandler
    
    for handler, subclasses in STANDALONE_HANDLERS:
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return eval(handler)(pObject)
    
    for handler, subclasses in HANDLERS:
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return eval(handler)(pObject)

    raise Exception("Unsupported persistent handler (class=%s, name=%s)"%(klass, window.GetName()))

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

def HasCtrlHandler(control):
    """
    Is there a suitable handler for this control

    :param `control`: the control instance to check if a handler for it exists.
    """

    klass = control.__class__

    if hasattr(control, "_persistentHandler"):
        # if control has a handler, just return it
        return True
    
    for handler, subclasses in STANDALONE_HANDLERS:
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return True
    
    for handler, subclasses in HANDLERS:
        for subclass in subclasses:
            if issubclass(klass, subclass):
                return True

    return False