Added an 'unselect' alternative for Qt < 5.7.0 to the new web browser and added possibility to save the current page in various formats.

Mon, 03 Oct 2016 19:02:45 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Mon, 03 Oct 2016 19:02:45 +0200
changeset 5194
4750c83cc718
parent 5193
04ba3ea482fe
child 5195
a282431c01fc

Added an 'unselect' alternative for Qt < 5.7.0 to the new web browser and added possibility to save the current page in various formats.

WebBrowser/AdBlock/AdBlockRule.py file | annotate | diff | comparison | revisions
WebBrowser/Download/DownloadItem.py file | annotate | diff | comparison | revisions
WebBrowser/WebBrowserView.py file | annotate | diff | comparison | revisions
WebBrowser/WebBrowserWindow.py file | annotate | diff | comparison | revisions
--- a/WebBrowser/AdBlock/AdBlockRule.py	Sat Oct 01 15:12:23 2016 +0200
+++ b/WebBrowser/AdBlock/AdBlockRule.py	Mon Oct 03 19:02:45 2016 +0200
@@ -11,7 +11,7 @@
 
 import re
 
-from PyQt5.QtCore import Qt, QRegExp
+from PyQt5.QtCore import qVersion, Qt, QRegExp
 from PyQt5.QtWebEngineCore import QWebEngineUrlRequestInfo
 
 
@@ -532,6 +532,10 @@
         match = (
             req.resourceType() ==
             QWebEngineUrlRequestInfo.ResourceTypeSubResource)
+        if qVersion() >= "5.7.0":
+            match = match or (
+                req.resourceType() ==
+                QWebEngineUrlRequestInfo.ResourceTypePluginResource)
         
         if self.__objectSubrequestException:
             return not match
--- a/WebBrowser/Download/DownloadItem.py	Sat Oct 01 15:12:23 2016 +0200
+++ b/WebBrowser/Download/DownloadItem.py	Mon Oct 03 19:02:45 2016 +0200
@@ -9,8 +9,10 @@
 
 from __future__ import unicode_literals
 
-from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QTime, QFileInfo, QUrl, \
-    PYQT_VERSION_STR
+import os
+
+from PyQt5.QtCore import pyqtSlot, pyqtSignal, qVersion, Qt, QTime, QUrl, \
+    QStandardPaths, QFileInfo
 from PyQt5.QtGui import QPalette, QDesktopServices
 from PyQt5.QtWidgets import QWidget, QStyle, QDialog
 from PyQt5.QtWebEngineWidgets import QWebEngineDownloadItem
@@ -24,6 +26,7 @@
 
 import UI.PixmapCache
 import Utilities.MimeTypes
+import Globals
 
 
 class DownloadItem(QWidget, Ui_DownloadItem):
@@ -121,6 +124,15 @@
         if self.__gettingFileName:
             return
         
+        if qVersion() >= "5.7.0":
+            savePage = self.__downloadItem.savePageFormat() != \
+                        QWebEngineDownloadItem.UnknownSaveFormat
+        else:
+            savePage = self.__downloadItem.path().lower().endswith(
+                (".mhtml", ".mht"))
+        
+        documentLocation = QStandardPaths.writableLocation(
+            QStandardPaths.DocumentsLocation)
         downloadDirectory = WebBrowserWindow\
             .downloadManager().downloadDirectory()
         
@@ -131,13 +143,14 @@
             ask = False
         else:
             defaultFileName, originalFileName = \
-                self.__saveFileName(downloadDirectory)
+                self.__saveFileName(
+                    documentLocation if savePage else downloadDirectory)
             fileName = defaultFileName
             self.__originalFileName = originalFileName
             ask = True
         self.__autoOpen = False
         
-        if not originalFileName.lower().endswith(".mhtml"):
+        if not savePage:
             from .DownloadAskActionDialog import DownloadAskActionDialog
             url = self.__downloadItem.url()
             mimetype = Utilities.MimeTypes.mimeType(originalFileName)
@@ -168,36 +181,72 @@
                 return
         
             self.__autoOpen = dlg.getAction() == "open"
+            
+            tempLocation = QStandardPaths.writableLocation(
+                QStandardPaths.TempLocation)
+            fileName = tempLocation + '/' + \
+                QFileInfo(fileName).completeBaseName()
+            
+            if ask and not self.__autoOpen:
+                self.__gettingFileName = True
+                fileName = E5FileDialog.getSaveFileName(
+                    None,
+                    self.tr("Save File"),
+                    defaultFileName,
+                    "")
+                self.__gettingFileName = False
         else:
             self.__autoOpen = False
-        
-        if PYQT_VERSION_STR >= "5.0.0":
-            from PyQt5.QtCore import QStandardPaths
-            tempLocation = QStandardPaths.standardLocations(
-                QStandardPaths.TempLocation)[0]
-        else:
-            from PyQt5.QtGui import QDesktopServices
-            tempLocation = QDesktopServices.storageLocation(
-                QDesktopServices.TempLocation)
-        fileName = tempLocation + '/' + \
-            QFileInfo(fileName).completeBaseName()
-        
-        if ask and not self.__autoOpen:
+            
+            filterList = [
+                self.tr("Web Archive (*.mhtml *.mht)"),
+                self.tr("HTML File (*.html *.htm)"),
+                self.tr("HTML File with all resources (*.html *.htm)"),
+            ]
+            extensionsList = [
+                # tuple of extensions for *nix and Windows
+                # keep in sync with filters list
+                (".mhtml", ".mht"),
+                (".html", ".htm"),
+                (".html", ".htm"),
+            ]
             self.__gettingFileName = True
-            fileName = E5FileDialog.getSaveFileName(
+            fileName, selectedFilter = E5FileDialog.getSaveFileNameAndFilter(
                 None,
-                self.tr("Save File"),
+                self.tr("Save Web Page"),
                 defaultFileName,
-                "")
+                ";;".join(filterList),
+                None)
             self.__gettingFileName = False
-            if not fileName:
-                self.progressBar.setVisible(False)
-                self.on_stopButton_clicked()
-                self.filenameLabel.setText(
-                    self.tr("Download canceled: {0}")
-                        .format(QFileInfo(defaultFileName).fileName()))
-                self.__canceledFileSelect = True
-                return
+            if fileName:
+                index = filterList.index(selectedFilter)
+                if index == 0:
+                    self.__downloadItem.setSavePageFormat(
+                        QWebEngineDownloadItem.MimeHtmlSaveFormat)
+                elif index == 1:
+                    self.__downloadItem.setSavePageFormat(
+                        QWebEngineDownloadItem.SingleHtmlSaveFormat)
+                else:
+                    self.__downloadItem.setSavePageFormat(
+                        QWebEngineDownloadItem.CompleteHtmlSaveFormat)
+                extension = os.path.splitext(fileName)[1]
+                if not extension:
+                    # add the platform specific default extension
+                    if Globals.isWindowsPlatform():
+                        extensionsIndex = 1
+                    else:
+                        extensionsIndex = 0
+                    extensions = extensionsList[index]
+                    fileName += extensions[extensionsIndex]
+        
+        if not fileName:
+            self.progressBar.setVisible(False)
+            self.on_stopButton_clicked()
+            self.filenameLabel.setText(
+                self.tr("Download canceled: {0}")
+                    .format(QFileInfo(defaultFileName).fileName()))
+            self.__canceledFileSelect = True
+            return
         
         fileInfo = QFileInfo(fileName)
         WebBrowserWindow.downloadManager()\
@@ -235,7 +284,7 @@
         if endName:
             origName += '.' + endName
         
-        name = directory + baseName
+        name = os.path.join(directory, baseName)
         if endName:
             name += '.' + endName
         return name, origName
--- a/WebBrowser/WebBrowserView.py	Sat Oct 01 15:12:23 2016 +0200
+++ b/WebBrowser/WebBrowserView.py	Mon Oct 03 19:02:45 2016 +0200
@@ -14,8 +14,10 @@
 except NameError:
     pass
 
+import os
+
 from PyQt5.QtCore import pyqtSignal, QUrl, QFileInfo, Qt, QTimer, QEvent, \
-    QPoint, QDateTime
+    QPoint, QDateTime, qVersion
 from PyQt5.QtGui import QDesktopServices, QClipboard, QIcon, \
     QContextMenuEvent, QPixmap
 from PyQt5.QtWidgets import qApp, QStyle, QMenu, QApplication
@@ -34,6 +36,7 @@
 
 import Preferences
 import UI.PixmapCache
+import Utilities
 
 
 class WebBrowserView(QWebEngineView):
@@ -164,9 +167,14 @@
             self.__mw.newTab(name)
             return
         
-        if not name.scheme():
-            name.setUrl(Preferences.getWebBrowser("DefaultScheme") +
-                        name.toString())
+        if not name.scheme() and not os.path.exists(name.toString()):
+            name.setScheme(Preferences.getWebBrowser("DefaultScheme"))
+        else:
+            if Utilities.isWindowsPlatform():
+                name.setUrl("file:///" + Utilities.fromNativeSeparators(
+                    name.toString()))
+            else:
+                name.setUrl("file://" + name.toString())
         
         if len(name.scheme()) == 1 or \
            name.scheme() == "file":
@@ -184,10 +192,7 @@
                     .format(name.toLocalFile()))
                 return
 
-            if name.toLocalFile().endswith(".pdf") or \
-               name.toLocalFile().endswith(".PDF") or \
-               name.toLocalFile().endswith(".chm") or \
-               name.toLocalFile().endswith(".CHM"):
+            if name.toLocalFile().lower().endswith((".pdf", ".chm")):
                 started = QDesktopServices.openUrl(name)
                 if not started:
                     E5MessageBox.critical(
@@ -210,10 +215,7 @@
                     .format(name.toString()))
             return
         else:
-            if name.toString().endswith(".pdf") or \
-               name.toString().endswith(".PDF") or \
-               name.toString().endswith(".chm") or \
-               name.toString().endswith(".CHM"):
+            if name.toString().lower().endswith((".pdf", ".chm")):
                 started = QDesktopServices.openUrl(name)
                 if not started:
                     E5MessageBox.critical(
@@ -317,7 +319,12 @@
         """
         Public slot to clear the current selection.
         """
-        self.triggerPageAction(QWebEnginePage.Unselect)
+        if qVersion() >= "5.7.0":
+            self.triggerPageAction(QWebEnginePage.Unselect)
+        else:
+            self.page().runJavaScript(
+                "window.getSelection().empty()",
+                WebBrowserPage.SafeJsWorld)
     
     def isForwardAvailable(self):
         """
--- a/WebBrowser/WebBrowserWindow.py	Sat Oct 01 15:12:23 2016 +0200
+++ b/WebBrowser/WebBrowserWindow.py	Mon Oct 03 19:02:45 2016 +0200
@@ -978,22 +978,19 @@
             self.selectAllAct.triggered.connect(self.__selectAll)
         self.__actions.append(self.selectAllAct)
         
-        if hasattr(QWebEnginePage, "Unselect"):
-            self.unselectAct = E5Action(
-                self.tr('Unselect'),
-                self.tr('Unselect'),
-                QKeySequence(self.tr("Ctrl+Shift+A", "Edit|Unselect")),
-                0, self, 'webbrowser_edit_unselect')
-            self.unselectAct.setStatusTip(self.tr('Clear current selection'))
-            self.unselectAct.setWhatsThis(self.tr(
-                """<b>Unselect</b>"""
-                """<p>Clear the selection of the current browser.</p>"""
-            ))
-            if not self.__initShortcutsOnly:
-                self.unselectAct.triggered.connect(self.__unselect)
-            self.__actions.append(self.unselectAct)
-        else:
-            self.unselectAct = None
+        self.unselectAct = E5Action(
+            self.tr('Unselect'),
+            self.tr('Unselect'),
+            QKeySequence(self.tr("Alt+Ctrl+A", "Edit|Unselect")),
+            0, self, 'webbrowser_edit_unselect')
+        self.unselectAct.setStatusTip(self.tr('Clear current selection'))
+        self.unselectAct.setWhatsThis(self.tr(
+            """<b>Unselect</b>"""
+            """<p>Clear the selection of the current browser.</p>"""
+        ))
+        if not self.__initShortcutsOnly:
+            self.unselectAct.triggered.connect(self.__unselect)
+        self.__actions.append(self.unselectAct)
         
         self.findAct = E5Action(
             self.tr('Find...'),
@@ -1803,8 +1800,7 @@
         menu.addAction(self.pasteAct)
         menu.addSeparator()
         menu.addAction(self.selectAllAct)
-        if self.unselectAct is not None:
-            menu.addAction(self.unselectAct)
+        menu.addAction(self.unselectAct)
         menu.addSeparator()
         menu.addAction(self.findAct)
         menu.addAction(self.findNextAct)
@@ -2245,7 +2241,7 @@
             self,
             self.tr("Open File"),
             "",
-            self.tr("HTML Files (*.html *.htm *.mhtml);;"
+            self.tr("HTML Files (*.html *.htm *.mhtml *.mht);;"
                     "PDF Files (*.pdf);;"
                     "CHM Files (*.chm);;"
                     "All Files (*)"
@@ -2265,7 +2261,7 @@
             self,
             self.tr("Open File"),
             "",
-            self.tr("HTML Files (*.html *.htm *.mhtml);;"
+            self.tr("HTML Files (*.html *.htm *.mhtml *.mht);;"
                     "PDF Files (*.pdf);;"
                     "CHM Files (*.chm);;"
                     "All Files (*)"

eric ide

mercurial