Utilities/AutoSaver.py

changeset 0
de9c2efb9d02
child 13
1af94a91f439
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Utilities/AutoSaver.py	Mon Dec 28 16:03:33 2009 +0000
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+
+# Copyright (c) 2009 Detlev Offenbach <detlev@die-offenbachs.de>
+#
+
+"""
+Module implementing an auto saver class.
+"""
+
+from PyQt4.QtCore import QObject, QBasicTimer, QTime
+
+class AutoSaver(QObject):
+    """
+    Class implementing the auto saver.
+    """
+    AUTOSAVE_IN = 1000 * 3
+    MAXWAIT     = 1000 * 15
+    
+    def __init__(self, parent, save):
+        """
+        Constructor
+        
+        @param parent reference to the parent object (QObject)
+        @param save slot to be called to perform the save operation
+        """
+        QObject.__init__(self, parent)
+        
+        if parent is None:
+            raise RuntimeError("AutoSaver: parent must not be None.")
+        
+        self.__save = save
+        
+        self.__timer = QBasicTimer()
+        self.__firstChange = QTime()
+    
+    def changeOccurred(self):
+        """
+        Public slot handling a change.
+        """
+        if self.__firstChange.isNull():
+            self.__firstChange.start()
+        
+        if self.__firstChange.elapsed() > self.MAXWAIT:
+            self.saveIfNeccessary()
+        else:
+            self.__timer.start(self.AUTOSAVE_IN, self)
+    
+    def timerEvent(self, evt):
+        """
+        Protected method handling timer events.
+        
+        @param evt reference to the timer event (QTimerEvent)
+        """
+        if evt.timerId() == self.__timer.timerId():
+            self.saveIfNeccessary()
+        else:
+            QObject.timerEvent(self, evt)
+    
+    def saveIfNeccessary(self):
+        """
+        Public method to activate the save operation.
+        """
+        if not self.__timer.isActive():
+            return
+        
+        self.__timer.stop()
+        self.__firstChange = QTime()
+        self.__save()

eric ide

mercurial