We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
QtWebKit: Handle visibility API
See https://github.com/OtterBrowser/otter-browser/commit/6500972092a562e23271ccf9aff4fdeed21d8290


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qutebrowser/browser/webkit/webview.py`
Content:
```
1 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2 
3 # Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
4 #
5 # This file is part of qutebrowser.
6 #
7 # qutebrowser is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # qutebrowser is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.
19 
20 """The main browser widgets."""
21 
22 import sys
23 
24 from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl
25 from PyQt5.QtGui import QPalette
26 from PyQt5.QtWidgets import QStyleFactory
27 from PyQt5.QtWebKit import QWebSettings
28 from PyQt5.QtWebKitWidgets import QWebView, QWebPage, QWebFrame
29 
30 from qutebrowser.config import config
31 from qutebrowser.keyinput import modeman
32 from qutebrowser.utils import log, usertypes, utils, qtutils, objreg, debug
33 from qutebrowser.browser.webkit import webpage
34 
35 
36 class WebView(QWebView):
37 
38     """Custom QWebView subclass with qutebrowser-specific features.
39 
40     Attributes:
41         tab: The WebKitTab object for this WebView
42         hintmanager: The HintManager instance for this view.
43         scroll_pos: The current scroll position as (x%, y%) tuple.
44         win_id: The window ID of the view.
45         _tab_id: The tab ID of the view.
46         _old_scroll_pos: The old scroll position.
47 
48     Signals:
49         scroll_pos_changed: Scroll percentage of current tab changed.
50                             arg 1: x-position in %.
51                             arg 2: y-position in %.
52         shutting_down: Emitted when the view is shutting down.
53     """
54 
55     scroll_pos_changed = pyqtSignal(int, int)
56     shutting_down = pyqtSignal()
57 
58     def __init__(self, win_id, tab_id, tab, parent=None):
59         super().__init__(parent)
60         if sys.platform == 'darwin' and qtutils.version_check('5.4'):
61             # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-42948
62             # See https://github.com/The-Compiler/qutebrowser/issues/462
63             self.setStyle(QStyleFactory.create('Fusion'))
64         # FIXME:qtwebengine this is only used to set the zoom factor from
65         # the QWebPage - we should get rid of it somehow (signals?)
66         self.tab = tab
67         self.win_id = win_id
68         self.scroll_pos = (-1, -1)
69         self._old_scroll_pos = (-1, -1)
70         self._set_bg_color()
71         self._tab_id = tab_id
72 
73         page = webpage.BrowserPage(self.win_id, self._tab_id, tab.data,
74                                    parent=self)
75         self.setPage(page)
76 
77         mode_manager = objreg.get('mode-manager', scope='window',
78                                   window=win_id)
79         mode_manager.entered.connect(self.on_mode_entered)
80         mode_manager.left.connect(self.on_mode_left)
81         objreg.get('config').changed.connect(self._set_bg_color)
82 
83     def __repr__(self):
84         url = utils.elide(self.url().toDisplayString(QUrl.EncodeUnicode), 100)
85         return utils.get_repr(self, tab_id=self._tab_id, url=url)
86 
87     def __del__(self):
88         # Explicitly releasing the page here seems to prevent some segfaults
89         # when quitting.
90         # Copied from:
91         # https://code.google.com/p/webscraping/source/browse/webkit.py#325
92         try:
93             self.setPage(None)
94         except RuntimeError:
95             # It seems sometimes Qt has already deleted the QWebView and we
96             # get: RuntimeError: wrapped C/C++ object of type WebView has been
97             # deleted
98             pass
99 
100     @config.change_filter('colors', 'webpage.bg')
101     def _set_bg_color(self):
102         """Set the webpage background color as configured.
103 
104         FIXME:qtwebengine
105         For QtWebEngine, doing the same has no effect, so we do it in here.
106         """
107         col = config.get('colors', 'webpage.bg')
108         palette = self.palette()
109         if col is None:
110             col = self.style().standardPalette().color(QPalette.Base)
111         palette.setColor(QPalette.Base, col)
112         self.setPalette(palette)
113 
114     def shutdown(self):
115         """Shut down the webview."""
116         self.shutting_down.emit()
117         # We disable javascript because that prevents some segfaults when
118         # quitting it seems.
119         log.destroy.debug("Shutting down {!r}.".format(self))
120         settings = self.settings()
121         settings.setAttribute(QWebSettings.JavascriptEnabled, False)
122         self.stop()
123         self.page().shutdown()
124 
125     def openurl(self, url):
126         """Open a URL in the browser.
127 
128         Args:
129             url: The URL to load as QUrl
130         """
131         self.load(url)
132         if url.scheme() == 'qute':
133             frame = self.page().mainFrame()
134             frame.javaScriptWindowObjectCleared.connect(self.add_js_bridge)
135 
136     @pyqtSlot()
137     def add_js_bridge(self):
138         """Add the javascript bridge for qute:... pages."""
139         frame = self.sender()
140         if not isinstance(frame, QWebFrame):
141             log.webview.error("Got non-QWebFrame {!r} in "
142                               "add_js_bridge!".format(frame))
143             return
144 
145         if frame.url().scheme() == 'qute':
146             bridge = objreg.get('js-bridge')
147             frame.addToJavaScriptWindowObject('qute', bridge)
148 
149     @pyqtSlot(usertypes.KeyMode)
150     def on_mode_entered(self, mode):
151         """Ignore attempts to focus the widget if in any status-input mode.
152 
153         FIXME:qtwebengine
154         For QtWebEngine, doing the same has no effect, so we do it in here.
155         """
156         if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
157                     usertypes.KeyMode.yesno]:
158             log.webview.debug("Ignoring focus because mode {} was "
159                               "entered.".format(mode))
160             self.setFocusPolicy(Qt.NoFocus)
161 
162     @pyqtSlot(usertypes.KeyMode)
163     def on_mode_left(self, mode):
164         """Restore focus policy if status-input modes were left.
165 
166         FIXME:qtwebengine
167         For QtWebEngine, doing the same has no effect, so we do it in here.
168         """
169         if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,
170                     usertypes.KeyMode.yesno]:
171             log.webview.debug("Restoring focus policy because mode {} was "
172                               "left.".format(mode))
173         self.setFocusPolicy(Qt.WheelFocus)
174 
175     def createWindow(self, wintype):
176         """Called by Qt when a page wants to create a new window.
177 
178         This function is called from the createWindow() method of the
179         associated QWebPage, each time the page wants to create a new window of
180         the given type. This might be the result, for example, of a JavaScript
181         request to open a document in a new window.
182 
183         Args:
184             wintype: This enum describes the types of window that can be
185                      created by the createWindow() function.
186 
187                      QWebPage::WebBrowserWindow: The window is a regular web
188                                                  browser window.
189                      QWebPage::WebModalDialog: The window acts as modal dialog.
190 
191         Return:
192             The new QWebView object.
193         """
194         debug_type = debug.qenum_key(QWebPage, wintype)
195         log.webview.debug("createWindow with type {}".format(debug_type))
196         if wintype == QWebPage.WebModalDialog:
197             log.webview.warning("WebModalDialog requested, but we don't "
198                                 "support that!")
199         tabbed_browser = objreg.get('tabbed-browser', scope='window',
200                                     window=self.win_id)
201         # pylint: disable=protected-access
202         return tabbed_browser.tabopen(background=False)._widget
203 
204     def paintEvent(self, e):
205         """Extend paintEvent to emit a signal if the scroll position changed.
206 
207         This is a bit of a hack: We listen to repaint requests here, in the
208         hope a repaint will always be requested when scrolling, and if the
209         scroll position actually changed, we emit a signal.
210 
211         QtWebEngine has a scrollPositionChanged signal, so it's not needed
212         there.
213 
214         Args:
215             e: The QPaintEvent.
216 
217         Return:
218             The superclass event return value.
219         """
220         frame = self.page().mainFrame()
221         new_pos = (frame.scrollBarValue(Qt.Horizontal),
222                    frame.scrollBarValue(Qt.Vertical))
223         if self._old_scroll_pos != new_pos:
224             self._old_scroll_pos = new_pos
225             m = (frame.scrollBarMaximum(Qt.Horizontal),
226                  frame.scrollBarMaximum(Qt.Vertical))
227             perc = (round(100 * new_pos[0] / m[0]) if m[0] != 0 else 0,
228                     round(100 * new_pos[1] / m[1]) if m[1] != 0 else 0)
229             self.scroll_pos = perc
230             self.scroll_pos_changed.emit(*perc)
231         # Let superclass handle the event
232         super().paintEvent(e)
233 
234     def contextMenuEvent(self, e):
235         """Save a reference to the context menu so we can close it.
236 
237         This is not needed for QtWebEngine, so it's in here.
238         """
239         menu = self.page().createStandardContextMenu()
240         self.shutting_down.connect(menu.close)
241         modeman.instance(self.win_id).entered.connect(menu.close)
242         menu.exec_(e.globalPos())
243
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qutebrowser/browser/webkit/webview.py b/qutebrowser/browser/webkit/webview.py
--- a/qutebrowser/browser/webkit/webview.py
+++ b/qutebrowser/browser/webkit/webview.py
@@ -72,6 +72,14 @@
 
         page = webpage.BrowserPage(self.win_id, self._tab_id, tab.data,
                                    parent=self)
+
+        try:
+            page.setVisibilityState(
+                QWebPage.VisibilityStateVisible if self.isVisible()
+                else QWebPage.VisibilityStateHidden)
+        except AttributeError:
+            pass
+
         self.setPage(page)
 
         mode_manager = objreg.get('mode-manager', scope='window',
@@ -240,3 +248,35 @@
         self.shutting_down.connect(menu.close)
         modeman.instance(self.win_id).entered.connect(menu.close)
         menu.exec_(e.globalPos())
+
+    def showEvent(self, e):
+        """Extend showEvent to set the page visibility state to visible.
+
+        Args:
+            e: The QShowEvent.
+
+        Return:
+            The superclass event return value.
+        """
+        try:
+            self.page().setVisibilityState(QWebPage.VisibilityStateVisible)
+        except AttributeError:
+            pass
+
+        super().showEvent(e)
+
+    def hideEvent(self, e):
+        """Extend hideEvent to set the page visibility state to hidden.
+
+        Args:
+            e: The QHideEvent.
+
+        Return:
+            The superclass event return value.
+        """
+        try:
+            self.page().setVisibilityState(QWebPage.VisibilityStateHidden)
+        except AttributeError:
+            pass
+
+        super().hideEvent(e)

{"golden_diff": "diff --git a/qutebrowser/browser/webkit/webview.py b/qutebrowser/browser/webkit/webview.py\n--- a/qutebrowser/browser/webkit/webview.py\n+++ b/qutebrowser/browser/webkit/webview.py\n@@ -72,6 +72,14 @@\n \n         page = webpage.BrowserPage(self.win_id, self._tab_id, tab.data,\n                                    parent=self)\n+\n+        try:\n+            page.setVisibilityState(\n+                QWebPage.VisibilityStateVisible if self.isVisible()\n+                else QWebPage.VisibilityStateHidden)\n+        except AttributeError:\n+            pass\n+\n         self.setPage(page)\n \n         mode_manager = objreg.get('mode-manager', scope='window',\n@@ -240,3 +248,35 @@\n         self.shutting_down.connect(menu.close)\n         modeman.instance(self.win_id).entered.connect(menu.close)\n         menu.exec_(e.globalPos())\n+\n+    def showEvent(self, e):\n+        \"\"\"Extend showEvent to set the page visibility state to visible.\n+\n+        Args:\n+            e: The QShowEvent.\n+\n+        Return:\n+            The superclass event return value.\n+        \"\"\"\n+        try:\n+            self.page().setVisibilityState(QWebPage.VisibilityStateVisible)\n+        except AttributeError:\n+            pass\n+\n+        super().showEvent(e)\n+\n+    def hideEvent(self, e):\n+        \"\"\"Extend hideEvent to set the page visibility state to hidden.\n+\n+        Args:\n+            e: The QHideEvent.\n+\n+        Return:\n+            The superclass event return value.\n+        \"\"\"\n+        try:\n+            self.page().setVisibilityState(QWebPage.VisibilityStateHidden)\n+        except AttributeError:\n+            pass\n+\n+        super().hideEvent(e)\n", "issue": "QtWebKit: Handle visibility API\nSee https://github.com/OtterBrowser/otter-browser/commit/6500972092a562e23271ccf9aff4fdeed21d8290\n\n", "before_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"The main browser widgets.\"\"\"\n\nimport sys\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl\nfrom PyQt5.QtGui import QPalette\nfrom PyQt5.QtWidgets import QStyleFactory\nfrom PyQt5.QtWebKit import QWebSettings\nfrom PyQt5.QtWebKitWidgets import QWebView, QWebPage, QWebFrame\n\nfrom qutebrowser.config import config\nfrom qutebrowser.keyinput import modeman\nfrom qutebrowser.utils import log, usertypes, utils, qtutils, objreg, debug\nfrom qutebrowser.browser.webkit import webpage\n\n\nclass WebView(QWebView):\n\n    \"\"\"Custom QWebView subclass with qutebrowser-specific features.\n\n    Attributes:\n        tab: The WebKitTab object for this WebView\n        hintmanager: The HintManager instance for this view.\n        scroll_pos: The current scroll position as (x%, y%) tuple.\n        win_id: The window ID of the view.\n        _tab_id: The tab ID of the view.\n        _old_scroll_pos: The old scroll position.\n\n    Signals:\n        scroll_pos_changed: Scroll percentage of current tab changed.\n                            arg 1: x-position in %.\n                            arg 2: y-position in %.\n        shutting_down: Emitted when the view is shutting down.\n    \"\"\"\n\n    scroll_pos_changed = pyqtSignal(int, int)\n    shutting_down = pyqtSignal()\n\n    def __init__(self, win_id, tab_id, tab, parent=None):\n        super().__init__(parent)\n        if sys.platform == 'darwin' and qtutils.version_check('5.4'):\n            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-42948\n            # See https://github.com/The-Compiler/qutebrowser/issues/462\n            self.setStyle(QStyleFactory.create('Fusion'))\n        # FIXME:qtwebengine this is only used to set the zoom factor from\n        # the QWebPage - we should get rid of it somehow (signals?)\n        self.tab = tab\n        self.win_id = win_id\n        self.scroll_pos = (-1, -1)\n        self._old_scroll_pos = (-1, -1)\n        self._set_bg_color()\n        self._tab_id = tab_id\n\n        page = webpage.BrowserPage(self.win_id, self._tab_id, tab.data,\n                                   parent=self)\n        self.setPage(page)\n\n        mode_manager = objreg.get('mode-manager', scope='window',\n                                  window=win_id)\n        mode_manager.entered.connect(self.on_mode_entered)\n        mode_manager.left.connect(self.on_mode_left)\n        objreg.get('config').changed.connect(self._set_bg_color)\n\n    def __repr__(self):\n        url = utils.elide(self.url().toDisplayString(QUrl.EncodeUnicode), 100)\n        return utils.get_repr(self, tab_id=self._tab_id, url=url)\n\n    def __del__(self):\n        # Explicitly releasing the page here seems to prevent some segfaults\n        # when quitting.\n        # Copied from:\n        # https://code.google.com/p/webscraping/source/browse/webkit.py#325\n        try:\n            self.setPage(None)\n        except RuntimeError:\n            # It seems sometimes Qt has already deleted the QWebView and we\n            # get: RuntimeError: wrapped C/C++ object of type WebView has been\n            # deleted\n            pass\n\n    @config.change_filter('colors', 'webpage.bg')\n    def _set_bg_color(self):\n        \"\"\"Set the webpage background color as configured.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        col = config.get('colors', 'webpage.bg')\n        palette = self.palette()\n        if col is None:\n            col = self.style().standardPalette().color(QPalette.Base)\n        palette.setColor(QPalette.Base, col)\n        self.setPalette(palette)\n\n    def shutdown(self):\n        \"\"\"Shut down the webview.\"\"\"\n        self.shutting_down.emit()\n        # We disable javascript because that prevents some segfaults when\n        # quitting it seems.\n        log.destroy.debug(\"Shutting down {!r}.\".format(self))\n        settings = self.settings()\n        settings.setAttribute(QWebSettings.JavascriptEnabled, False)\n        self.stop()\n        self.page().shutdown()\n\n    def openurl(self, url):\n        \"\"\"Open a URL in the browser.\n\n        Args:\n            url: The URL to load as QUrl\n        \"\"\"\n        self.load(url)\n        if url.scheme() == 'qute':\n            frame = self.page().mainFrame()\n            frame.javaScriptWindowObjectCleared.connect(self.add_js_bridge)\n\n    @pyqtSlot()\n    def add_js_bridge(self):\n        \"\"\"Add the javascript bridge for qute:... pages.\"\"\"\n        frame = self.sender()\n        if not isinstance(frame, QWebFrame):\n            log.webview.error(\"Got non-QWebFrame {!r} in \"\n                              \"add_js_bridge!\".format(frame))\n            return\n\n        if frame.url().scheme() == 'qute':\n            bridge = objreg.get('js-bridge')\n            frame.addToJavaScriptWindowObject('qute', bridge)\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_entered(self, mode):\n        \"\"\"Ignore attempts to focus the widget if in any status-input mode.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,\n                    usertypes.KeyMode.yesno]:\n            log.webview.debug(\"Ignoring focus because mode {} was \"\n                              \"entered.\".format(mode))\n            self.setFocusPolicy(Qt.NoFocus)\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_left(self, mode):\n        \"\"\"Restore focus policy if status-input modes were left.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,\n                    usertypes.KeyMode.yesno]:\n            log.webview.debug(\"Restoring focus policy because mode {} was \"\n                              \"left.\".format(mode))\n        self.setFocusPolicy(Qt.WheelFocus)\n\n    def createWindow(self, wintype):\n        \"\"\"Called by Qt when a page wants to create a new window.\n\n        This function is called from the createWindow() method of the\n        associated QWebPage, each time the page wants to create a new window of\n        the given type. This might be the result, for example, of a JavaScript\n        request to open a document in a new window.\n\n        Args:\n            wintype: This enum describes the types of window that can be\n                     created by the createWindow() function.\n\n                     QWebPage::WebBrowserWindow: The window is a regular web\n                                                 browser window.\n                     QWebPage::WebModalDialog: The window acts as modal dialog.\n\n        Return:\n            The new QWebView object.\n        \"\"\"\n        debug_type = debug.qenum_key(QWebPage, wintype)\n        log.webview.debug(\"createWindow with type {}\".format(debug_type))\n        if wintype == QWebPage.WebModalDialog:\n            log.webview.warning(\"WebModalDialog requested, but we don't \"\n                                \"support that!\")\n        tabbed_browser = objreg.get('tabbed-browser', scope='window',\n                                    window=self.win_id)\n        # pylint: disable=protected-access\n        return tabbed_browser.tabopen(background=False)._widget\n\n    def paintEvent(self, e):\n        \"\"\"Extend paintEvent to emit a signal if the scroll position changed.\n\n        This is a bit of a hack: We listen to repaint requests here, in the\n        hope a repaint will always be requested when scrolling, and if the\n        scroll position actually changed, we emit a signal.\n\n        QtWebEngine has a scrollPositionChanged signal, so it's not needed\n        there.\n\n        Args:\n            e: The QPaintEvent.\n\n        Return:\n            The superclass event return value.\n        \"\"\"\n        frame = self.page().mainFrame()\n        new_pos = (frame.scrollBarValue(Qt.Horizontal),\n                   frame.scrollBarValue(Qt.Vertical))\n        if self._old_scroll_pos != new_pos:\n            self._old_scroll_pos = new_pos\n            m = (frame.scrollBarMaximum(Qt.Horizontal),\n                 frame.scrollBarMaximum(Qt.Vertical))\n            perc = (round(100 * new_pos[0] / m[0]) if m[0] != 0 else 0,\n                    round(100 * new_pos[1] / m[1]) if m[1] != 0 else 0)\n            self.scroll_pos = perc\n            self.scroll_pos_changed.emit(*perc)\n        # Let superclass handle the event\n        super().paintEvent(e)\n\n    def contextMenuEvent(self, e):\n        \"\"\"Save a reference to the context menu so we can close it.\n\n        This is not needed for QtWebEngine, so it's in here.\n        \"\"\"\n        menu = self.page().createStandardContextMenu()\n        self.shutting_down.connect(menu.close)\n        modeman.instance(self.win_id).entered.connect(menu.close)\n        menu.exec_(e.globalPos())\n", "path": "qutebrowser/browser/webkit/webview.py"}], "after_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"The main browser widgets.\"\"\"\n\nimport sys\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl\nfrom PyQt5.QtGui import QPalette\nfrom PyQt5.QtWidgets import QStyleFactory\nfrom PyQt5.QtWebKit import QWebSettings\nfrom PyQt5.QtWebKitWidgets import QWebView, QWebPage, QWebFrame\n\nfrom qutebrowser.config import config\nfrom qutebrowser.keyinput import modeman\nfrom qutebrowser.utils import log, usertypes, utils, qtutils, objreg, debug\nfrom qutebrowser.browser.webkit import webpage\n\n\nclass WebView(QWebView):\n\n    \"\"\"Custom QWebView subclass with qutebrowser-specific features.\n\n    Attributes:\n        tab: The WebKitTab object for this WebView\n        hintmanager: The HintManager instance for this view.\n        scroll_pos: The current scroll position as (x%, y%) tuple.\n        win_id: The window ID of the view.\n        _tab_id: The tab ID of the view.\n        _old_scroll_pos: The old scroll position.\n\n    Signals:\n        scroll_pos_changed: Scroll percentage of current tab changed.\n                            arg 1: x-position in %.\n                            arg 2: y-position in %.\n        shutting_down: Emitted when the view is shutting down.\n    \"\"\"\n\n    scroll_pos_changed = pyqtSignal(int, int)\n    shutting_down = pyqtSignal()\n\n    def __init__(self, win_id, tab_id, tab, parent=None):\n        super().__init__(parent)\n        if sys.platform == 'darwin' and qtutils.version_check('5.4'):\n            # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-42948\n            # See https://github.com/The-Compiler/qutebrowser/issues/462\n            self.setStyle(QStyleFactory.create('Fusion'))\n        # FIXME:qtwebengine this is only used to set the zoom factor from\n        # the QWebPage - we should get rid of it somehow (signals?)\n        self.tab = tab\n        self.win_id = win_id\n        self.scroll_pos = (-1, -1)\n        self._old_scroll_pos = (-1, -1)\n        self._set_bg_color()\n        self._tab_id = tab_id\n\n        page = webpage.BrowserPage(self.win_id, self._tab_id, tab.data,\n                                   parent=self)\n\n        try:\n            page.setVisibilityState(\n                QWebPage.VisibilityStateVisible if self.isVisible()\n                else QWebPage.VisibilityStateHidden)\n        except AttributeError:\n            pass\n\n        self.setPage(page)\n\n        mode_manager = objreg.get('mode-manager', scope='window',\n                                  window=win_id)\n        mode_manager.entered.connect(self.on_mode_entered)\n        mode_manager.left.connect(self.on_mode_left)\n        objreg.get('config').changed.connect(self._set_bg_color)\n\n    def __repr__(self):\n        url = utils.elide(self.url().toDisplayString(QUrl.EncodeUnicode), 100)\n        return utils.get_repr(self, tab_id=self._tab_id, url=url)\n\n    def __del__(self):\n        # Explicitly releasing the page here seems to prevent some segfaults\n        # when quitting.\n        # Copied from:\n        # https://code.google.com/p/webscraping/source/browse/webkit.py#325\n        try:\n            self.setPage(None)\n        except RuntimeError:\n            # It seems sometimes Qt has already deleted the QWebView and we\n            # get: RuntimeError: wrapped C/C++ object of type WebView has been\n            # deleted\n            pass\n\n    @config.change_filter('colors', 'webpage.bg')\n    def _set_bg_color(self):\n        \"\"\"Set the webpage background color as configured.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        col = config.get('colors', 'webpage.bg')\n        palette = self.palette()\n        if col is None:\n            col = self.style().standardPalette().color(QPalette.Base)\n        palette.setColor(QPalette.Base, col)\n        self.setPalette(palette)\n\n    def shutdown(self):\n        \"\"\"Shut down the webview.\"\"\"\n        self.shutting_down.emit()\n        # We disable javascript because that prevents some segfaults when\n        # quitting it seems.\n        log.destroy.debug(\"Shutting down {!r}.\".format(self))\n        settings = self.settings()\n        settings.setAttribute(QWebSettings.JavascriptEnabled, False)\n        self.stop()\n        self.page().shutdown()\n\n    def openurl(self, url):\n        \"\"\"Open a URL in the browser.\n\n        Args:\n            url: The URL to load as QUrl\n        \"\"\"\n        self.load(url)\n        if url.scheme() == 'qute':\n            frame = self.page().mainFrame()\n            frame.javaScriptWindowObjectCleared.connect(self.add_js_bridge)\n\n    @pyqtSlot()\n    def add_js_bridge(self):\n        \"\"\"Add the javascript bridge for qute:... pages.\"\"\"\n        frame = self.sender()\n        if not isinstance(frame, QWebFrame):\n            log.webview.error(\"Got non-QWebFrame {!r} in \"\n                              \"add_js_bridge!\".format(frame))\n            return\n\n        if frame.url().scheme() == 'qute':\n            bridge = objreg.get('js-bridge')\n            frame.addToJavaScriptWindowObject('qute', bridge)\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_entered(self, mode):\n        \"\"\"Ignore attempts to focus the widget if in any status-input mode.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,\n                    usertypes.KeyMode.yesno]:\n            log.webview.debug(\"Ignoring focus because mode {} was \"\n                              \"entered.\".format(mode))\n            self.setFocusPolicy(Qt.NoFocus)\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_left(self, mode):\n        \"\"\"Restore focus policy if status-input modes were left.\n\n        FIXME:qtwebengine\n        For QtWebEngine, doing the same has no effect, so we do it in here.\n        \"\"\"\n        if mode in [usertypes.KeyMode.command, usertypes.KeyMode.prompt,\n                    usertypes.KeyMode.yesno]:\n            log.webview.debug(\"Restoring focus policy because mode {} was \"\n                              \"left.\".format(mode))\n        self.setFocusPolicy(Qt.WheelFocus)\n\n    def createWindow(self, wintype):\n        \"\"\"Called by Qt when a page wants to create a new window.\n\n        This function is called from the createWindow() method of the\n        associated QWebPage, each time the page wants to create a new window of\n        the given type. This might be the result, for example, of a JavaScript\n        request to open a document in a new window.\n\n        Args:\n            wintype: This enum describes the types of window that can be\n                     created by the createWindow() function.\n\n                     QWebPage::WebBrowserWindow: The window is a regular web\n                                                 browser window.\n                     QWebPage::WebModalDialog: The window acts as modal dialog.\n\n        Return:\n            The new QWebView object.\n        \"\"\"\n        debug_type = debug.qenum_key(QWebPage, wintype)\n        log.webview.debug(\"createWindow with type {}\".format(debug_type))\n        if wintype == QWebPage.WebModalDialog:\n            log.webview.warning(\"WebModalDialog requested, but we don't \"\n                                \"support that!\")\n        tabbed_browser = objreg.get('tabbed-browser', scope='window',\n                                    window=self.win_id)\n        # pylint: disable=protected-access\n        return tabbed_browser.tabopen(background=False)._widget\n\n    def paintEvent(self, e):\n        \"\"\"Extend paintEvent to emit a signal if the scroll position changed.\n\n        This is a bit of a hack: We listen to repaint requests here, in the\n        hope a repaint will always be requested when scrolling, and if the\n        scroll position actually changed, we emit a signal.\n\n        QtWebEngine has a scrollPositionChanged signal, so it's not needed\n        there.\n\n        Args:\n            e: The QPaintEvent.\n\n        Return:\n            The superclass event return value.\n        \"\"\"\n        frame = self.page().mainFrame()\n        new_pos = (frame.scrollBarValue(Qt.Horizontal),\n                   frame.scrollBarValue(Qt.Vertical))\n        if self._old_scroll_pos != new_pos:\n            self._old_scroll_pos = new_pos\n            m = (frame.scrollBarMaximum(Qt.Horizontal),\n                 frame.scrollBarMaximum(Qt.Vertical))\n            perc = (round(100 * new_pos[0] / m[0]) if m[0] != 0 else 0,\n                    round(100 * new_pos[1] / m[1]) if m[1] != 0 else 0)\n            self.scroll_pos = perc\n            self.scroll_pos_changed.emit(*perc)\n        # Let superclass handle the event\n        super().paintEvent(e)\n\n    def contextMenuEvent(self, e):\n        \"\"\"Save a reference to the context menu so we can close it.\n\n        This is not needed for QtWebEngine, so it's in here.\n        \"\"\"\n        menu = self.page().createStandardContextMenu()\n        self.shutting_down.connect(menu.close)\n        modeman.instance(self.win_id).entered.connect(menu.close)\n        menu.exec_(e.globalPos())\n\n    def showEvent(self, e):\n        \"\"\"Extend showEvent to set the page visibility state to visible.\n\n        Args:\n            e: The QShowEvent.\n\n        Return:\n            The superclass event return value.\n        \"\"\"\n        try:\n            self.page().setVisibilityState(QWebPage.VisibilityStateVisible)\n        except AttributeError:\n            pass\n\n        super().showEvent(e)\n\n    def hideEvent(self, e):\n        \"\"\"Extend hideEvent to set the page visibility state to hidden.\n\n        Args:\n            e: The QHideEvent.\n\n        Return:\n            The superclass event return value.\n        \"\"\"\n        try:\n            self.page().setVisibilityState(QWebPage.VisibilityStateHidden)\n        except AttributeError:\n            pass\n\n        super().hideEvent(e)\n", "path": "qutebrowser/browser/webkit/webview.py"}]}