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