|
1 # -*- coding: utf-8 -*- |
|
2 |
|
3 # Copyright (c) 2009 Detlev Offenbach <detlev@die-offenbachs.de> |
|
4 # |
|
5 |
|
6 """ |
|
7 Module implementing an auto saver class. |
|
8 """ |
|
9 |
|
10 from PyQt4.QtCore import QObject, QBasicTimer, QTime |
|
11 |
|
12 class AutoSaver(QObject): |
|
13 """ |
|
14 Class implementing the auto saver. |
|
15 """ |
|
16 AUTOSAVE_IN = 1000 * 3 |
|
17 MAXWAIT = 1000 * 15 |
|
18 |
|
19 def __init__(self, parent, save): |
|
20 """ |
|
21 Constructor |
|
22 |
|
23 @param parent reference to the parent object (QObject) |
|
24 @param save slot to be called to perform the save operation |
|
25 """ |
|
26 QObject.__init__(self, parent) |
|
27 |
|
28 if parent is None: |
|
29 raise RuntimeError("AutoSaver: parent must not be None.") |
|
30 |
|
31 self.__save = save |
|
32 |
|
33 self.__timer = QBasicTimer() |
|
34 self.__firstChange = QTime() |
|
35 |
|
36 def changeOccurred(self): |
|
37 """ |
|
38 Public slot handling a change. |
|
39 """ |
|
40 if self.__firstChange.isNull(): |
|
41 self.__firstChange.start() |
|
42 |
|
43 if self.__firstChange.elapsed() > self.MAXWAIT: |
|
44 self.saveIfNeccessary() |
|
45 else: |
|
46 self.__timer.start(self.AUTOSAVE_IN, self) |
|
47 |
|
48 def timerEvent(self, evt): |
|
49 """ |
|
50 Protected method handling timer events. |
|
51 |
|
52 @param evt reference to the timer event (QTimerEvent) |
|
53 """ |
|
54 if evt.timerId() == self.__timer.timerId(): |
|
55 self.saveIfNeccessary() |
|
56 else: |
|
57 QObject.timerEvent(self, evt) |
|
58 |
|
59 def saveIfNeccessary(self): |
|
60 """ |
|
61 Public method to activate the save operation. |
|
62 """ |
|
63 if not self.__timer.isActive(): |
|
64 return |
|
65 |
|
66 self.__timer.stop() |
|
67 self.__firstChange = QTime() |
|
68 self.__save() |