WebBrowser/Session/SessionManager.py

changeset 5782
60874802161b
parent 5780
79d06c98c5c9
child 5783
44a9f08de394
--- a/WebBrowser/Session/SessionManager.py	Sat Jul 01 19:14:01 2017 +0200
+++ b/WebBrowser/Session/SessionManager.py	Sun Jul 02 19:40:39 2017 +0200
@@ -13,8 +13,9 @@
 import json
 
 from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QObject, QTimer, QDir, \
-    QFile, QFileInfo, QFileSystemWatcher, QByteArray
-from PyQt5.QtWidgets import QMenu, QAction, QActionGroup, QApplication
+    QFile, QFileInfo, QFileSystemWatcher, QByteArray, QDateTime
+from PyQt5.QtWidgets import QMenu, QAction, QActionGroup, QApplication, \
+    QInputDialog, QLineEdit
 
 from E5Gui import E5MessageBox
 
@@ -261,7 +262,13 @@
         
         sessionFilesInfoList = QDir(self.getSessionsDirectory()).entryInfoList(
             ["*.json"], QDir.Files, QDir.Time)
+        
         for sessionFileInfo in sessionFilesInfoList:
+            sessionData = self.__readSessionFromFile(
+                sessionFileInfo.absoluteFilePath())
+            if not sessionData or not sessionData["Windows"]:
+                continue
+            
             data = SessionMetaData()
             data.name = sessionFileInfo.baseName()
             data.filePath = sessionFileInfo.canonicalFilePath()
@@ -273,7 +280,11 @@
             if self.__isActive(sessionFileInfo):
                 data.isActive = True
             
-            self.__sessionMetaData.append(data)
+            if data.isDefault:
+                # default session is always first
+                self.__sessionMetaData.insert(0, data)
+            else:
+                self.__sessionMetaData.append(data)
     
     def __isActive(self, filePath):
         """
@@ -324,9 +335,14 @@
             path = act.data()
             self.switchToSession(path)
     
-    def __openSession(self, sessionFilePath, flags=None):
+    def __openSession(self, sessionFilePath, flags=0):
         """
         Private method to open a session from a given session file.
+        
+        @param sessionFilePath name of the session file to get session from
+        @type str
+        @param flags flags determining the open mode
+        @type int
         """
         if self.__isActive(sessionFilePath):
             return
@@ -337,7 +353,9 @@
         
         from WebBrowser.WebBrowserWindow import WebBrowserWindow
         window = WebBrowserWindow.mainWindow()
-        if flags & SessionManager.SwitchSession:
+        
+        if ((flags & SessionManager.SwitchSession) ==
+                SessionManager.SwitchSession):
             # save the current session
             self.writeCurrentSession(self.__lastActiveSession)
             
@@ -349,7 +367,8 @@
                 if win is not window:
                     win.forceClose()
             
-            if not (flags & SessionManager.ReplaceSession):
+            if not ((flags & SessionManager.ReplaceSession) ==
+                    SessionManager.ReplaceSession):
                 self.__lastActiveSession = \
                     QFileInfo(sessionFilePath).canonicalFilePath()
                 self.__sessionMetaData = []
@@ -376,13 +395,97 @@
             QApplication.processEvents()
         QApplication.restoreOverrideCursor()
     
-    def renameSession(self, sessionFilePath="", flags=None):
-        # TODO: implement this
-        pass
+    def renameSession(self, sessionFilePath, flags=0):
+        """
+        Public method to rename or clone a session
+        
+        @param sessionFilePath name of the session file
+        @type str
+        @param flags flags determining a rename or clone operation
+        @type int
+        """
+        from WebBrowser.WebBrowserWindow import WebBrowserWindow
+        
+        suggestedName = QFileInfo(sessionFilePath).baseName()
+        if flags & SessionManager.CloneSession:
+            suggestedName += "_cloned"
+            title = self.tr("Clone Session")
+        else:
+            suggestedName += "_renamed"
+            title = self.tr("Rename Session")
+        newName, ok = QInputDialog.getText(
+            WebBrowserWindow.getWindow(),
+            title,
+            self.tr("Please enter a new name:"),
+            QLineEdit.Normal,
+            suggestedName)
+        
+        if not ok:
+            return
+        
+        if not newName.endswith(".json"):
+            newName += ".json"
+        
+        newSessionPath = os.path.join(self.getSessionsDirectory(), newName)
+        if os.path.exists(newSessionPath):
+            E5MessageBox.information(
+                WebBrowserWindow.getWindow(),
+                title,
+                self.tr("""The session file "{0}" exists already. Please"""
+                        """ enter another name.""").format(newName))
+            self.renameSession(sessionFilePath, flags)
+            return
+        
+        if flags & SessionManager.CloneSession:
+            if not QFile.copy(sessionFilePath, newSessionPath):
+                E5MessageBox.critical(
+                    WebBrowserWindow.getWindow(),
+                    title,
+                    self.tr("""An error occurred while cloning the session"""
+                            """ file."""))
+                return
+        else:
+            if not QFile.rename(sessionFilePath, newSessionPath):
+                E5MessageBox.critical(
+                    WebBrowserWindow.getWindow(),
+                    title,
+                    self.tr("""An error occurred while renaming the session"""
+                            """ file."""))
+                return
+            if self.__isActive(sessionFilePath):
+                self.__lastActiveSession = newSessionPath
+                self.__sessionMetaData = []
     
     def saveSession(self):
-        # TODO: implement this
-        pass
+        """
+        Public method to save the current session.
+        """
+        from WebBrowser.WebBrowserWindow import WebBrowserWindow
+        newName, ok = QInputDialog.getText(
+            WebBrowserWindow.getWindow(),
+            self.tr("Save Session"),
+            self.tr("Please enter a name for the session:"),
+            QLineEdit.Normal,
+            self.tr("Saved Session ({0})").format(
+                QDateTime.currentDateTime().toString("yyyy-MM-dd HH-mm-ss")))
+        
+        if not ok:
+            return
+        
+        if not newName.endswith(".json"):
+            newName += ".json"
+        
+        newSessionPath = os.path.join(self.getSessionsDirectory(), newName)
+        if os.path.exists(newSessionPath):
+            E5MessageBox.information(
+                WebBrowserWindow.getWindow(),
+                self.tr("Save Session"),
+                self.tr("""The session file "{0}" exists already. Please"""
+                        """ enter another name.""").format(newName))
+            self.saveSession()
+            return
+        
+        self.writeCurrentSession(newSessionPath)
     
     def replaceSession(self, sessionFilePath):
         """
@@ -393,9 +496,10 @@
         """
         from WebBrowser.WebBrowserWindow import WebBrowserWindow
         res = E5MessageBox.yesNo(
-            WebBrowserWindow.mainWindow(),
+            WebBrowserWindow.getWindow(),
             self.tr("Restore Backup"),
-            self.tr("""Are you sure you want to replace current session?"""))
+            self.tr("""Are you sure you want to replace the current"""
+                    """ session?"""))
         if res:
             self.__openSession(sessionFilePath, SessionManager.ReplaceSession)
     
@@ -409,18 +513,76 @@
         self.__openSession(sessionFilePath, SessionManager.SwitchSession)
     
     def cloneSession(self, sessionFilePath):
-        # TODO: implement this
-        pass
+        """
+        Public method to clone a session.
+        
+        @param sessionFilePath file name of the session file to be cloned
+        @type str
+        """
+        self.renameSession(sessionFilePath, SessionManager.CloneSession)
     
     def deleteSession(self, sessionFilePath):
-        # TODO: implement this
-        pass
+        """
+        Public method to delete a session.
+        
+        @param sessionFilePath file name of the session file to be deleted
+        @type str        
+        """
+        from WebBrowser.WebBrowserWindow import WebBrowserWindow
+        res = E5MessageBox.yesNo(
+            WebBrowserWindow.getWindow(),
+            self.tr("Delete Session"),
+            self.tr("""Are you sure you want to delete session "{0}"?""")
+            .format(QFileInfo(sessionFilePath).baseName()))
+        if res:
+            QFile.remove(sessionFilePath)
     
     def newSession(self):
-        # TODO: implement this
-        pass
+        """
+        Public method to start a new session.
+        """
+        from WebBrowser.WebBrowserWindow import WebBrowserWindow
+        newName, ok = QInputDialog.getText(
+            WebBrowserWindow.getWindow(),
+            self.tr("New Session"),
+            self.tr("Please enter a name for the new session:"),
+            QLineEdit.Normal,
+            self.tr("New Session ({0})").format(
+                QDateTime.currentDateTime().toString("yyyy-MM-dd HH-mm-ss")))
+        
+        if not ok:
+            return
+        
+        if not newName.endswith(".json"):
+            newName += ".json"
+        
+        newSessionPath = os.path.join(self.getSessionsDirectory(), newName)
+        if os.path.exists(newSessionPath):
+            E5MessageBox.information(
+                WebBrowserWindow.getWindow(),
+                self.tr("New Session"),
+                self.tr("""The session file "{0}" exists already. Please"""
+                        """ enter another name.""").format(newName))
+            self.newSession()
+            return
+        
+        self.writeCurrentSession(self.__lastActiveSession)
+        
+        # create new window for the new session and close all existing windows
+        window = WebBrowserWindow.mainWindow().newWindow()
+        for win in WebBrowserWindow.mainWindows():
+            if win is not window:
+                win.forceClose()
+        
+        self.__lastActiveSession = newSessionPath
+        self.__autoSaveSession()
     
     def showSessionManagerDialog(self):
-        # TODO: implement this
-        pass
-        print("showSessionManagerDialog()")
+        """
+        Public method to show the session manager dialog.
+        """
+        from WebBrowser.WebBrowserWindow import WebBrowserWindow
+        from .SessionManagerDialog import SessionManagerDialog
+        
+        dlg = SessionManagerDialog(WebBrowserWindow.getWindow())
+        dlg.open()

eric ide

mercurial