persistencemanager.py
28.5 KB
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
# -*- coding: utf-8 -*-#
#!/usr/bin/env python
# --------------------------------------------------------------------------- #
# PersistentControls Library wxPython IMPLEMENTATION
#
# Inspired by the wxWidgets implementation by Vadim Zeitlin.
#
# License: wxWidgets license
#
# Python Code By:
#
# Andrea Gavana, @ 16 Nov 2009
# Latest Revision: 27 Mar 2013, 21.00 GMT
#
# 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
# --------------------------------------------------------------------------- #
"""
This module contains the definitions of `PersistentObject` and `PersistenceManager` objects.
"""
import wx
import os
import warnings
import datetime
import wx.gizmos
from persist_handlers import FindHandler, HasCtrlHandler
from persist_constants import BAD_DEFAULT_NAMES, CONFIG_PATH_SEPARATOR
from persist_constants import PM_DEFAULT_STYLE, PM_PERSIST_CONTROL_VALUE
# ----------------------------------------------------------------------------------- #
class PersistentObject(object):
"""
:class:`PersistentObject`: ABC for anything persistent.
This is the base class for persistent object adapters.
wxPython persistence framework is non-intrusive, i.e. can work with the
classes which have no relationship to nor knowledge of it. To allow this,
an intermediate persistence adapter is used: this is just a simple object
which provides the methods used by :class:`PersistenceManager` to save and restore
the object properties and implements them using the concrete class methods.
You may derive your own classes from :class:`PersistentObject` to implement persistence
support for your common classes, see :ref:`persistent-windows` in the
`__init__.py` file.
"""
def __init__(self, window, persistenceHandler=None):
"""
Default class constructor.
:param `window`: an instance of :class:`Window`;
:param `persistenceHandler`: if not ``None``, this should a custom handler derived
from :class:`~lib.agw.persist.persist_handlers.AbstractHandler`.
"""
self._name = window.GetName()
if not self._name.strip():
raise Exception("Persistent windows should be named! (class=%s)"%window.__class__)
klass = window.__class__
if issubclass(klass, wx.GenericDirCtrl):
self._window = window.GetTreeCtrl()
elif issubclass(klass, wx.gizmos.EditableListBox):
self._window = window.GetListCtrl()
else:
self._window = window
if persistenceHandler is not None:
self._persistentHandler = persistenceHandler(self)
else:
self._persistentHandler = FindHandler(self)
if self._name in BAD_DEFAULT_NAMES:
warnings.warn("Window names should not be defaulted! (class=%s, name=%s)"%(window.__class__, window.GetName()))
def GetName(self):
"""
Returns the string uniquely identifying the window we're associated with
among all the other objects of the same type.
:note: This method is used together with :meth:`~PersistentObject.GetKind` to construct the unique
full name of the object in e.g. a configuration file.
"""
return self._name
def GetWindow(self):
""" Returns the actual associated window. """
return self._window
def GetKind(self):
"""
Returns the string uniquely identifying the objects supported by this adapter.
:note: This method is called from :meth:`~PersistentObject.SaveValue` and :meth:`~PersistentObject.RestoreValue` and normally
returns some short (but not too cryptic) strings, e.g. "Checkbox".
"""
return self._persistentHandler.GetKind()
def Save(self):
"""
Saves the corresponding window settings.
.. note::
This method shouldn't be used directly as it doesn't respect the
global :meth:`PersistenceManager.DisableSaving() <PersistenceManager.DisableSaving>` settings, use :class:`PersistenceManager`
methods with the same name instead.
"""
self._persistentHandler.Save()
def Restore(self):
"""
Restores the corresponding window settings.
:note: This method shouldn't be used directly as it doesn't respect the
global :meth:`PersistenceManager.DisableRestoring() <PersistenceManager.DisableRestoring>` settings, use :class:`PersistenceManager`
methods with the same name instead.
"""
return self._persistentHandler.Restore()
def SaveValue(self, name, value):
"""
Save the specified value using the given name.
:param `name`: the name of the value in the configuration file;
:param `value`: the value to save.
:returns: ``True`` if the value was saved or ``False`` if an error occurred.
"""
return PersistenceManager.Get().SaveValue(self, name, value)
def SaveCtrlValue(self, name, value):
"""
Save the specified value using the given name, should be used only for
controls data value.
:param `name`: the name of the value in the configuration file;
:param `value`: the value to save.
:returns: ``True`` if the value was saved or ``False`` if an error occurred.
"""
return PersistenceManager.Get().SaveCtrlValue(self, name, value)
def RestoreValue(self, name):
"""
Restore the value saved by :meth:`~PersistentObject.SaveValue`.
:param `name`: the same name as was used by :meth:`~PersistentObject.SaveValue`.
:returns: ``True`` if the value was successfully read or ``False`` if
it was not found or an error occurred.
"""
return PersistenceManager.Get().RestoreValue(self, name)
def RestoreCtrlValue(self, name):
"""
Restore the value saved by :meth:`~PersistentObject.SaveCtrlValue`, should be used only for
controls data value.
:param `name`: the same name as was used by :meth:`~PersistentObject.SaveCtrlValue`.
:returns: ``True`` if the value was successfully read or ``False`` if
it was not found or an error occurred.
"""
return PersistenceManager.Get().RestoreCtrlValue(self, name)
# ----------------------------------------------------------------------------------- #
class PersistenceManager(object):
"""
:class:`PersistenceManager`: global aspects of persistent windows.
Provides support for automatically saving and restoring object properties
to persistent storage.
This class is the central element of wxPython persistence framework, see
the :ref:`persistent-overview` in the `__init__.py` file for its overview.
This is a singleton class and its unique instance can be retrieved using
:meth:`PersistenceManager.Get() <PersistenceManager.Get>` method.
"""
def __init__(self):
"""
Default class constructor.
This method should **not** be called directly: you should use the object
obtained by :meth:`PersistenceManager.Get() <PersistenceManager.Get>` and assign manager styles, custom
configuration files and custom configuration handlers using the appropriate
methods in this class.
Interesting attributes you can set for this class are:
- `configFile`: the persistent configuration file for :class:`PersistenceManager`,
a custom file name to which :class:`FileConfig` will access to store and
retrieve UI settings;
- `configKey`: the persistent key name inside the configuration file for
:class:`PersistenceManager`;
- `customConfigHandler`: the persistent configuration handler for :class:`PersistenceManager`;
this attribute is an object capable of saving/restoring UI settings. This
can be a cPickle object or a ConfigObj one, for example.
- `style`: a combination of the following values:
======================================== ==================================
Flag name Description
======================================== ==================================
``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective
``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls
``PM_PERSIST_CONTROL_VALUE`` If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.
``PM_DEFAULT_STYLE`` Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``
======================================== ==================================
:note: UI settings are stored as dictionaries key <=> tuple: the tuple value
contains two items. The first is the value *type* (i.e., float, int, bool etc...)
while the second is the actual key value.
"""
object.__init__(self)
# Specifies custom wx.Config object to use (i.e., custom file names)
self._configFile = None
# Specifies custom key in the wx.Config object to use
self._configKey = None
# Specifies whether a custom config handler exists, so that we will not use
# wx.FileConfig (i.e., ConfigObj, ConfigParser etc...)
self._customConfigHandler = None
# Specifies the PersistenceManager style
self._style = PM_DEFAULT_STYLE
# Set these values to True if we should restore/save the settings (it doesn't
# make much sense to use this class when both of them are False but setting
# one of them to False may make sense in some situations)
self._doSave = True
self._doRestore = True
# Flag set to True when PersistenceManager has restored any window
self._hasRestored = False
# map with the registered objects as keys and associated
# PersistentObjects as values
self._persistentObjects = {}
def Get(self):
""" Accessor to the unique persistence manager object. """
if not hasattr(self, "_instance"):
self._instance = PersistenceManager()
return self._instance
Get = classmethod(Get)
def Free(self):
""" Destructor for the unique persistence manager object. """
if hasattr(self, "_instance"):
del self._instance
Free = classmethod(Free)
def GetManagerStyle(self):
"""
Returns the :class:`PersistenceManager` style.
:see: :meth:`~PersistenceManager.SetManagerStyle` for a list of possible styles.
"""
return self._style
def SetManagerStyle(self, style):
"""
Sets the :class:`PersistenceManager` style.
:param `style`: a combination of the following values:
======================================== ==================================
Flag name Description
======================================== ==================================
``PM_SAVE_RESTORE_AUI_PERSPECTIVES`` If a toplevel window has an AUI manager associated, the manager will save and restore its AUI perspective
``PM_SAVE_RESTORE_TREE_LIST_SELECTIONS`` If set, the manager will save items selections in list and tree controls
``PM_PERSIST_CONTROL_VALUE`` If set, control values will be persisted. This is handy for e.g. applications using a database, where the data (control value) is persisted in the database and persisting it with PM again would only cause confusion.
``PM_DEFAULT_STYLE`` Same as ``PM_SAVE_RESTORE_AUI_PERSPECTIVES``.
======================================== ==================================
"""
self._style = style
def SetPersistenceKey(self, key):
"""
Sets the persistent key name inside the configuration file for :class:`PersistenceManager`.
:param `key`: a short meaningful name for your unique preferences key.
:note: Calling this method has no influence if you are using your own
custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
"""
self._configKey = key
def GetPersistenceKey(self):
"""
Returns the persistent key name inside the configuration file for :class:`PersistenceManager`.
:note: The return value of this method is not used if you are using your own
custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
"""
return self._configKey
def SetPersistenceFile(self, fileName):
"""
Sets the persistent configuration file for :class:`PersistenceManager`.
:param `fileName`: the file name where to store the persistent options.
:note: Calling this method has no influence if you are using your own
custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
"""
self._configFile = fileName
self._persistentObjects = {}
def GetPersistenceFile(self):
"""
Returns the persistent configuration file for :class:`PersistenceManager`.
:note: The return value of this method is not used if you are using your own
custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...).
"""
if self._configFile is not None:
persistenceDir, fileName = os.path.split(self._configFile)
fileName = self._configFile
else:
persistenceDir = self.GetPersistenceDirectory()
fileName = "Persistence_Options"
fileName = os.path.join(persistenceDir, fileName)
if not os.path.exists(persistenceDir):
# Create the data folder, it still doesn't exist
os.makedirs(persistenceDir)
config = wx.FileConfig(localFilename=fileName)
return config
def SetConfigurationHandler(self, handler):
"""
Sets the persistent configuration handler for :class:`PersistenceManager`.
:param `handler`: an object capable of saving/restoring UI settings. This
can be a cPickle object or a ConfigObj one, for example.
:note: UI settings are stored as dictionaries key <=> tuple: the tuple value
contains two items. The first is the value *type* (i.e., float, int, bool etc...)
while the second is the actual key value.
"""
self._customConfigHandler = handler
def GetConfigurationHandler(self):
"""
Returns the persistent configuration handler for :class:`PersistenceManager`.
"""
return self._customConfigHandler
def GetPersistenceDirectory(self):
"""
Returns a default persistent option directory for :class:`PersistenceManager`.
:note: The return value of this method is not used if you are using your own
custom configuration handler (i.e., by using ConfigObj/ConfigParser/cPickle etc...)
or if you have specified a custom configuration file to use with :class:`FileConfig`.
"""
sp = wx.StandardPaths.Get()
return sp.GetUserDataDir()
def Find(self, window):
"""
Checks if the object is registered and return the associated :class:`PersistentObject`
if it is or ``None`` otherwise.
:param `window`: an instance of :class:`Window`.
"""
if window:
# protect for PyDeadObjectError
if window.GetName() in self._persistentObjects:
return window
def Register(self, window, persistenceHandler=None):
"""
Register an object with the manager.
:param `window`: an instance of :class:`Window`;
:param `persistenceHandler`: if not ``None``, this should a custom handler derived
from :class:`~lib.agw.persist.persist_handlers.AbstractHandler`.
.. note::
Note that registering the object doesn't do anything except allowing to call
:meth:`~PersistenceManager.Restore` for it later. If you want to register the object and restore its
properties, use :meth:`~PersistenceManager.RegisterAndRestore`.
.. note::
The manager takes ownership of the :class:`PersistentObject` and will delete it when
it is unregistered.
"""
if self.Find(window):
raise Exception("Object (class=%s, name=%s) is already registered"%(window.__class__, window.GetName()))
name = window.GetName()
self._persistentObjects[name] = PersistentObject(window, persistenceHandler)
return True
def Unregister(self, window):
"""
Unregister the object, this is called by :class:`PersistenceManager` itself so there is
usually no need to do it explicitly.
:param `window`: an instance of :class:`Window`, which must have been previously
registered with :meth:`~PersistenceManager.Register`.
:note: For the persistent windows this is done automatically (via :meth:`~PersistenceManager.SaveAndUnregister`)
when the window is destroyed so you only need to call this function explicitly if you
are using custom persistent objects or if you want to prevent the object properties
from being saved.
:note: This deletes the associated :class:`PersistentObject`.
"""
if not self.Find(window):
return False
name = window.GetName()
self._persistentObjects.pop(name)
return True
def Save(self, window):
"""
Saves the state of an object.
:param `window`: an instance of :class:`Window`.
:note: This methods does nothing if :meth:`~PersistenceManager.DisableSaving` was called.
"""
if not self._doSave:
return False
if not self.Find(window):
return False
name = window.GetName()
self._persistentObjects[name].Save()
return True
def Restore(self, window):
"""
Restores the state of an object.
:param `window`: an instance of :class:`Window`.
:returns: ``True`` if the object properties were restored or ``False`` if nothing
was found to restore or the saved settings were invalid.
:note: This methods does nothing if :meth:`~PersistenceManager.DisableRestoring` was called.
"""
if not self._doRestore:
return False
if not self.Find(window):
return False
name = window.GetName()
return self._persistentObjects[name].Restore()
def DisableSaving(self):
"""
Globally disables saving the persistent properties (enabled by default).
:note: By default, saving properties in :meth:`~PersistenceManager.Save` is enabled but the program
may wish to disable if, for example, it detects that it is running on a
system which shouldn't be modified in any way and so configuration file
(or Windows registry) shouldn't be written to.
"""
self._doSave = False
def DisableRestoring(self):
"""
Globally disables restoring the persistent properties (enabled by default).
:note: By default, restoring properties in :meth:`~PersistenceManager.Restore` is enabled but this
function allows to disable it. This is mostly useful for testing.
"""
self._doRestore = False
def EnableSaving(self):
"""
Globally enables saving the persistent properties (enabled by default).
:note: By default, saving properties in :meth:`~PersistenceManager.Save` is enabled but the program
may wish to disable if, for example, it detects that it is running on a
system which shouldn't be modified in any way and so configuration file
(or Windows registry) shouldn't be written to.
"""
self._doSave = True
def EnableRestoring(self):
"""
Globally enables restoring the persistent properties (enabled by default).
:note: By default, restoring properties in :meth:`~PersistenceManager.Restore` is enabled but this
function allows to disable it. This is mostly useful for testing.
"""
self._doRestore = True
def SaveAndUnregister(self, window=None):
"""
Combines both :meth:`~PersistenceManager.Save` and :meth:`~PersistenceManager.Unregister` calls.
:param `window`: an instance of :class:`Window`. If it is ``None``, all the
windows previously registered are saved and then unregistered.
"""
if window is None:
for name, obj in self._persistentObjects.items():
self.SaveAndUnregister(obj.GetWindow())
return
self.Save(window)
self.Unregister(window)
def RegisterAndRestore(self, window):
"""
Combines both :meth:`~PersistenceManager.Register` and :meth:`~PersistenceManager.Restore` calls.
:param `window`: an instance of :class:`Window`.
"""
return self.Register(window) and self.Restore(window)
def RegisterAndRestoreAll(self, window, children=None):
"""
Recursively registers and restore the state of the input `window` and of
all of its children.
:param `window`: an instance of :class:`Window`;
:param `children`: list of children of the input `window`, on first call it is equal to ``None``.
"""
if children is None:
if HasCtrlHandler(window):
# Control has persist support
self.HasRestoredProp = self.RegisterAndRestore(window)
children = window.GetChildren()
for child in children:
name = child.GetName()
if name not in BAD_DEFAULT_NAMES:
if HasCtrlHandler(child):
# Control has persist support
self.HasRestoredProp = self.RegisterAndRestore(child)
self.RegisterAndRestoreAll(window, child.GetChildren())
return self.HasRestoredProp
def RestoreAll(self, window, children=None):
"""
Recursively restore the state of the input `window` and of
all of its children.
:param `window`: an instance of :class:`Window`;
:param `children`: list of children of the input `window`, on first call it is equal to ``None``.
"""
if children is None:
if HasCtrlHandler(window):
# Control has persist support
self.HasRestoredProp = self.Restore(window)
children = window.GetChildren()
for child in children:
name = child.GetName()
if name not in BAD_DEFAULT_NAMES:
if HasCtrlHandler(child):
# Control has persist support
self.HasRestoredProp = self.Restore(child)
self.RestoreAll(window, child.GetChildren())
return self.HasRestoredProp
def HasRestored(self):
"""
This method returns ``True`` if any of the windows managed by
:class:`PersistenceManager` has had its settings restored.
:returns: ``True`` if any window was restored, ``False`` otherwise.
.. versionadded:: 0.9.7
"""
return self.HasRestoredProp
@property
def HasRestoredProp(self):
"""
This property returns ``True`` if any of the windows managed by
:class:`PersistenceManager` has had its settings restored.
:returns: ``True`` if any window was restored, ``False`` otherwise.
.. versionadded:: 0.9.7
"""
return self._hasRestored
@HasRestoredProp.setter
def HasRestoredProp(self, flag):
"""
This property keeps track if any of the windows managed by
:class:`PersistenceManager` has had its settings restored.
:param boolean `flag`: True will be remembered
"""
if flag:
self._hasRestored = flag
def GetKey(self, obj, keyName):
"""
Returns a correctly formatted key name for the object `obj` and `keyName` parameters.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name.
"""
key = (self._configKey is None and ["Persistence_Options"] or [self._configKey])[0]
key += CONFIG_PATH_SEPARATOR + obj.GetKind()
key += CONFIG_PATH_SEPARATOR + obj.GetName()
key += CONFIG_PATH_SEPARATOR + keyName
return key
def SaveCtrlValue(self, obj, keyName, value):
"""
Check if we persist the widget value, if so pass it to :meth:`~PersistenceManager.DoSaveValue`.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name;
:param `value`: the value to store in the configuration file.
"""
if self._style & PM_PERSIST_CONTROL_VALUE:
return self.DoSaveValue(obj, keyName, value)
def SaveValue(self, obj, keyName, value):
"""
Convenience method, all the action is done in :meth:`~PersistenceManager.DoSaveValue`.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name;
:param `value`: the value to store in the configuration file.
"""
return self.DoSaveValue(obj, keyName, value)
def DoSaveValue(self, obj, keyName, value):
"""
Method used by the persistent objects to save the data.
By default this method simply use :class:`FileConfig` but this behaviour may be
overridden by passing a custom configuration handler in the :class:`PersistenceManager`
constructor.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name;
:param `value`: the value to store in the configuration file.
"""
kind = repr(value.__class__).split("'")[1]
if self._customConfigHandler is not None:
result = self._customConfigHandler.SaveValue(self.GetKey(obj, keyName), repr((kind, str(value))))
else:
config = self.GetPersistenceFile()
result = config.Write(self.GetKey(obj, keyName), repr((kind, str(value))))
config.Flush()
return result
def RestoreCtrlValue(self, obj, keyName):
"""
Check if we persist the widget value, if so pass it to :meth:`~PersistenceManager.DoRestoreValue`.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name.
"""
if self._style & PM_PERSIST_CONTROL_VALUE:
return self.DoRestoreValue(obj, keyName)
def RestoreValue(self, obj, keyName):
"""
Convenience method, all the action is done in :meth:`~PersistenceManager.DoRestoreValue`.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name.
"""
return self.DoRestoreValue(obj, keyName)
def DoRestoreValue(self, obj, keyName):
"""
Method used by the persistent objects to restore the data.
By default this method simply use :class:`FileConfig` but this behaviour may be
overridden by passing a custom config handler in the PersistenceManager
constructor.
:param `obj`: an instance of :class:`PersistentObject`;
:param `keyName`: a string specifying the key name.
"""
if self._customConfigHandler is not None:
result = self._customConfigHandler.RestoreValue(self.GetKey(obj, keyName))
else:
config = self.GetPersistenceFile()
result = config.Read(self.GetKey(obj, keyName))
if result:
kind, result = eval(result)
if kind in ("unicode", "str"):
return result
elif kind == "datetime.date":
y, m, d = result.split("-")
result = datetime.date(int(y), int(m), int(d))
return result
return eval(result)
def AddBadDefaultName(self, name):
"""
Adds a name to the ``BAD_DEFAULT_NAMES`` constant.
:param `name`: a string specifying the control's default name.
"""
global BAD_DEFAULT_NAMES
BAD_DEFAULT_NAMES.append(name)