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