diff options
author | Florian Bruhin <me@the-compiler.org> | 2021-08-26 16:47:12 +0200 |
---|---|---|
committer | Florian Bruhin <me@the-compiler.org> | 2021-08-26 16:47:12 +0200 |
commit | ac9d67cce0dbecdde14c474db855243e9746ba04 (patch) | |
tree | b564440308dc40b8ae40209a33cb1c47c95e17c6 /qutebrowser/browser | |
parent | ba30ac2af0860a8c92503179f6867ab0b46e3d31 (diff) | |
download | qutebrowser-ac9d67cce0dbecdde14c474db855243e9746ba04.tar.gz qutebrowser-ac9d67cce0dbecdde14c474db855243e9746ba04.zip |
Automatically rewrite enums
See #5904
Diffstat (limited to 'qutebrowser/browser')
39 files changed, 508 insertions, 508 deletions
diff --git a/qutebrowser/browser/browsertab.py b/qutebrowser/browser/browsertab.py index 04ebf321f..e3583d2c8 100644 --- a/qutebrowser/browser/browsertab.py +++ b/qutebrowser/browser/browsertab.py @@ -279,7 +279,7 @@ class AbstractPrinting: if utils.is_mac: # For some reason we get a segfault when using open() on macOS ret = diag.exec() - if ret == QDialog.Accepted: + if ret == QDialog.DialogCode.Accepted: do_print() else: diag.open(do_print) @@ -538,9 +538,9 @@ class AbstractCaret(QObject): def _follow_enter(self, tab: bool) -> None: """Follow a link by faking an enter press.""" if tab: - self._tab.fake_key_press(Qt.Key_Enter, modifier=Qt.ControlModifier) + self._tab.fake_key_press(Qt.Key.Key_Enter, modifier=Qt.KeyboardModifier.ControlModifier) else: - self._tab.fake_key_press(Qt.Key_Enter) + self._tab.fake_key_press(Qt.Key.Key_Enter) def follow_selected(self, *, tab: bool = False) -> None: raise NotImplementedError @@ -1154,10 +1154,10 @@ class AbstractTab(QWidget): def fake_key_press(self, key: Qt.Key, - modifier: Qt.KeyboardModifier = Qt.NoModifier) -> None: + modifier: Qt.KeyboardModifier = Qt.KeyboardModifier.NoModifier) -> None: """Send a fake key event to this tab.""" - press_evt = QKeyEvent(QEvent.KeyPress, key, modifier, 0, 0, 0) - release_evt = QKeyEvent(QEvent.KeyRelease, key, modifier, + press_evt = QKeyEvent(QEvent.Type.KeyPress, key, modifier, 0, 0, 0) + release_evt = QKeyEvent(QEvent.Type.KeyRelease, key, modifier, 0, 0, 0) self.send_event(press_evt) self.send_event(release_evt) @@ -1232,7 +1232,7 @@ class AbstractTab(QWidget): try: qurl = self.url() url = qurl.toDisplayString( - QUrl.EncodeUnicode) # type: ignore[arg-type] + QUrl.ComponentFormattingOption.EncodeUnicode) # type: ignore[arg-type] except (AttributeError, RuntimeError) as exc: url = '<{}>'.format(exc.__class__.__name__) else: diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index 291e51822..42bd795a9 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -192,21 +192,21 @@ class CommandDispatcher: what's configured in 'tabs.select_on_remove'. Return: - QTabBar.SelectLeftTab, QTabBar.SelectRightTab, or None if no change + QTabBar.SelectionBehavior.SelectLeftTab, QTabBar.SelectionBehavior.SelectRightTab, or None if no change should be made. """ cmdutils.check_exclusive((prev, next_, opposite), 'pno') if prev: - return QTabBar.SelectLeftTab + return QTabBar.SelectionBehavior.SelectLeftTab elif next_: - return QTabBar.SelectRightTab + return QTabBar.SelectionBehavior.SelectRightTab elif opposite: conf_selection = config.val.tabs.select_on_remove - if conf_selection == QTabBar.SelectLeftTab: - return QTabBar.SelectRightTab - elif conf_selection == QTabBar.SelectRightTab: - return QTabBar.SelectLeftTab - elif conf_selection == QTabBar.SelectPreviousTab: + if conf_selection == QTabBar.SelectionBehavior.SelectLeftTab: + return QTabBar.SelectionBehavior.SelectRightTab + elif conf_selection == QTabBar.SelectionBehavior.SelectRightTab: + return QTabBar.SelectionBehavior.SelectLeftTab + elif conf_selection == QTabBar.SelectionBehavior.SelectPreviousTab: raise cmdutils.CommandError( "-o is not supported with 'tabs.select_on_remove' set to " "'last-used'!") @@ -669,9 +669,9 @@ class CommandDispatcher: assert what in ['url', 'pretty-url'], what if what == 'pretty-url': - flags = QUrl.RemovePassword | QUrl.DecodeReserved + flags = QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.DecodeReserved else: - flags = QUrl.RemovePassword | QUrl.FullyEncoded + flags = QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded url = QUrl(self._current_url()) url_query = QUrlQuery() @@ -1155,7 +1155,7 @@ class CommandDispatcher: except qtutils.QtValueError: pass else: - env['QUTE_URL'] = url.toString(QUrl.FullyEncoded) + env['QUTE_URL'] = url.toString(QUrl.ComponentFormattingOption.FullyEncoded) try: runner = userscripts.run_async( @@ -1286,8 +1286,8 @@ class CommandDispatcher: current page's url. """ if url is None: - url = self._current_url().toString(QUrl.RemovePassword | - QUrl.FullyEncoded) + url = self._current_url().toString(QUrl.UrlFormattingOption.RemovePassword | + QUrl.ComponentFormattingOption.FullyEncoded) try: objreg.get('bookmark-manager').delete(url) except KeyError: @@ -1749,8 +1749,8 @@ class CommandDispatcher: raise cmdutils.CommandError(str(e)) for keyinfo in sequence: - press_event = keyinfo.to_event(QEvent.KeyPress) - release_event = keyinfo.to_event(QEvent.KeyRelease) + press_event = keyinfo.to_event(QEvent.Type.KeyPress) + release_event = keyinfo.to_event(QEvent.Type.KeyRelease) if global_: window = QApplication.focusWindow() @@ -1857,9 +1857,9 @@ class CommandDispatcher: if not window.isFullScreen(): window.state_before_fullscreen = window.windowState() if enter: - window.setWindowState(window.windowState() | Qt.WindowFullScreen) + window.setWindowState(window.windowState() | Qt.WindowState.WindowFullScreen) else: - window.setWindowState(window.windowState() ^ Qt.WindowFullScreen) + window.setWindowState(window.windowState() ^ Qt.WindowState.WindowFullScreen) log.misc.debug('state before fullscreen: {}'.format( debug.qflags_key(Qt, window.state_before_fullscreen))) diff --git a/qutebrowser/browser/downloads.py b/qutebrowser/browser/downloads.py index ff12a7b53..b76c906b8 100644 --- a/qutebrowser/browser/downloads.py +++ b/qutebrowser/browser/downloads.py @@ -45,7 +45,7 @@ class ModelRole(enum.IntEnum): """Custom download model roles.""" - item = Qt.UserRole + item = Qt.ItemDataRole.UserRole # Remember the last used directory @@ -188,7 +188,7 @@ def get_filename_question(*, suggested_filename, url, parent=None): q.title = "Save file to:" q.text = "Please enter a location for <b>{}</b>".format( html.escape(url.toDisplayString())) - q.url = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + q.url = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) q.mode = usertypes.PromptMode.download q.completed.connect(q.deleteLater) q.default = _path_suggestion(suggested_filename) @@ -1266,10 +1266,10 @@ class DownloadModel(QAbstractListModel): idx = self.index(self.rowCount() - 1) return idx - def headerData(self, section, orientation, role=Qt.DisplayRole): + def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole): """Simple constant header.""" - if (section == 0 and orientation == Qt.Horizontal and - role == Qt.DisplayRole): + if (section == 0 and orientation == Qt.Orientation.Horizontal and + role == Qt.ItemDataRole.DisplayRole): return "Downloads" else: return "" @@ -1283,15 +1283,15 @@ class DownloadModel(QAbstractListModel): return None item = self[index.row()] - if role == Qt.DisplayRole: + if role == Qt.ItemDataRole.DisplayRole: data: Any = str(item) - elif role == Qt.ForegroundRole: + elif role == Qt.ItemDataRole.ForegroundRole: data = item.get_status_color('fg') - elif role == Qt.BackgroundRole: + elif role == Qt.ItemDataRole.BackgroundRole: data = item.get_status_color('bg') elif role == ModelRole.item: data = item - elif role == Qt.ToolTipRole: + elif role == Qt.ItemDataRole.ToolTipRole: if item.error_msg is None: data = None else: @@ -1303,11 +1303,11 @@ class DownloadModel(QAbstractListModel): def flags(self, index): """Override flags so items aren't selectable. - The default would be Qt.ItemIsEnabled | Qt.ItemIsSelectable. + The default would be Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable. """ if not index.isValid(): return Qt.ItemFlags() - return Qt.ItemIsEnabled | Qt.ItemNeverHasChildren + return Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemNeverHasChildren def rowCount(self, parent=QModelIndex()): """Get count of active downloads.""" diff --git a/qutebrowser/browser/downloadview.py b/qutebrowser/browser/downloadview.py index 0c76161f7..2cbd16d42 100644 --- a/qutebrowser/browser/downloadview.py +++ b/qutebrowser/browser/downloadview.py @@ -62,11 +62,11 @@ class DownloadView(QListView): if not utils.is_mac: self.setStyle(QStyleFactory.create('Fusion')) stylesheet.set_register(self) - self.setResizeMode(QListView.Adjust) - self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) - self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) - self.setFocusPolicy(Qt.NoFocus) - self.setFlow(QListView.LeftToRight) + self.setResizeMode(QListView.ResizeMode.Adjust) + self.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) + self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Fixed) + self.setFocusPolicy(Qt.FocusPolicy.NoFocus) + self.setFlow(QListView.Flow.LeftToRight) self.setSpacing(1) self._menu = None model.rowsInserted.connect(self._update_geometry) @@ -74,7 +74,7 @@ class DownloadView(QListView): model.dataChanged.connect(self._update_geometry) self.setModel(model) self.setWrapping(True) - self.setContextMenuPolicy(Qt.CustomContextMenu) + self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) self.customContextMenuRequested.connect(self.show_context_menu) self.clicked.connect(self.on_clicked) diff --git a/qutebrowser/browser/eventfilter.py b/qutebrowser/browser/eventfilter.py index 860287dbc..34d2c98e5 100644 --- a/qutebrowser/browser/eventfilter.py +++ b/qutebrowser/browser/eventfilter.py @@ -48,7 +48,7 @@ class ChildEventFilter(QObject): def eventFilter(self, obj, event): """Act on ChildAdded events.""" - if event.type() == QEvent.ChildAdded: + if event.type() == QEvent.Type.ChildAdded: child = event.child() log.misc.debug("{} got new child {}, installing filter" .format(obj, child)) @@ -58,7 +58,7 @@ class ChildEventFilter(QObject): assert obj is self._widget child.installEventFilter(self._filter) - elif event.type() == QEvent.ChildRemoved: + elif event.type() == QEvent.Type.ChildRemoved: child = event.child() log.misc.debug("{}: removed child {}".format(obj, child)) @@ -81,10 +81,10 @@ class TabEventFilter(QObject): super().__init__(parent) self._tab = tab self._handlers = { - QEvent.MouseButtonPress: self._handle_mouse_press, - QEvent.MouseButtonRelease: self._handle_mouse_release, - QEvent.Wheel: self._handle_wheel, - QEvent.KeyRelease: self._handle_key_release, + QEvent.Type.MouseButtonPress: self._handle_mouse_press, + QEvent.Type.MouseButtonRelease: self._handle_mouse_release, + QEvent.Type.Wheel: self._handle_wheel, + QEvent.Type.KeyRelease: self._handle_key_release, } self._ignore_wheel_event = False self._check_insertmode_on_release = False @@ -99,9 +99,9 @@ class TabEventFilter(QObject): True if the event should be filtered, False otherwise. """ is_rocker_gesture = (config.val.input.mouse.rocker_gestures and - e.buttons() == Qt.LeftButton | Qt.RightButton) + e.buttons() == Qt.MouseButton.LeftButton | Qt.MouseButton.RightButton) - if e.button() in [Qt.XButton1, Qt.XButton2] or is_rocker_gesture: + if e.button() in [Qt.MouseButton.XButton1, Qt.MouseButton.XButton2] or is_rocker_gesture: self._mousepress_backforward(e) return True @@ -112,7 +112,7 @@ class TabEventFilter(QObject): log.mouse.warning("Ignoring invalid click at {}".format(pos)) return False - if e.button() != Qt.NoButton: + if e.button() != Qt.MouseButton.NoButton: self._tab.elements.find_at_pos(pos, self._mousepress_insertmode_cb) return False @@ -150,7 +150,7 @@ class TabEventFilter(QObject): if mode == usertypes.KeyMode.hint: return True - elif e.modifiers() & Qt.ControlModifier: + elif e.modifiers() & Qt.KeyboardModifier.ControlModifier: if mode == usertypes.KeyMode.passthrough: return False @@ -240,17 +240,17 @@ class TabEventFilter(QObject): True if the event should be filtered, False otherwise. """ if (not config.val.input.mouse.back_forward_buttons and - e.button() in [Qt.XButton1, Qt.XButton2]): + e.button() in [Qt.MouseButton.XButton1, Qt.MouseButton.XButton2]): # Back and forward on mice are disabled return - if e.button() in [Qt.XButton1, Qt.LeftButton]: + if e.button() in [Qt.MouseButton.XButton1, Qt.MouseButton.LeftButton]: # Back button on mice which have it, or rocker gesture if self._tab.history.can_go_back(): self._tab.history.back() else: message.error("At beginning of history.") - elif e.button() in [Qt.XButton2, Qt.RightButton]: + elif e.button() in [Qt.MouseButton.XButton2, Qt.MouseButton.RightButton]: # Forward button on mice which have it, or rocker gesture if self._tab.history.can_go_forward(): self._tab.history.forward() diff --git a/qutebrowser/browser/greasemonkey.py b/qutebrowser/browser/greasemonkey.py index 7f5763812..7fd3e3914 100644 --- a/qutebrowser/browser/greasemonkey.py +++ b/qutebrowser/browser/greasemonkey.py @@ -238,7 +238,7 @@ class GreasemonkeyMatcher: def __init__(self, url): self._url = url - self._url_string = url.toString(QUrl.FullyEncoded) + self._url_string = url.toString(QUrl.ComponentFormattingOption.FullyEncoded) self.is_greaseable = url.scheme() in self.GREASEABLE_SCHEMES def _match_pattern(self, pattern): diff --git a/qutebrowser/browser/hints.py b/qutebrowser/browser/hints.py index 33aa95eb5..7e1be9662 100644 --- a/qutebrowser/browser/hints.py +++ b/qutebrowser/browser/hints.py @@ -92,12 +92,12 @@ class HintLabel(QLabel): self._context = context self.elem = elem - self.setTextFormat(Qt.RichText) + self.setTextFormat(Qt.TextFormat.RichText) # Make sure we can style the background via a style sheet, and we don't # get any extra text indent from Qt. # The real stylesheet lives in mainwindow.py for performance reasons.. - self.setAttribute(Qt.WA_StyledBackground, True) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) self.setIndent(0) self._context.tab.contents_size_changed.connect(self._move_to_elem) @@ -252,9 +252,9 @@ class HintActions: sel = (context.target == Target.yank_primary and utils.supports_selection()) - flags = QUrl.FullyEncoded | QUrl.RemovePassword + flags = QUrl.ComponentFormattingOption.FullyEncoded | QUrl.UrlFormattingOption.RemovePassword if url.scheme() == 'mailto': - flags |= QUrl.RemoveScheme + flags |= QUrl.UrlFormattingOption.RemoveScheme urlstr = url.toString(flags) # type: ignore[arg-type] new_content = urlstr @@ -276,14 +276,14 @@ class HintActions: def run_cmd(self, url: QUrl, context: HintContext) -> None: """Run the command based on a hint URL.""" - urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + urlstr = url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] args = context.get_args(urlstr) commandrunner = runners.CommandRunner(self._win_id) commandrunner.run_safely(' '.join(args)) def preset_cmd_text(self, url: QUrl, context: HintContext) -> None: """Preset a commandline text based on a hint URL.""" - flags = QUrl.FullyEncoded + flags = QUrl.ComponentFormattingOption.FullyEncoded urlstr = url.toDisplayString(flags) # type: ignore[arg-type] args = context.get_args(urlstr) text = ' '.join(args) @@ -325,7 +325,7 @@ class HintActions: cmd = context.args[0] args = context.args[1:] - flags = QUrl.FullyEncoded + flags = QUrl.ComponentFormattingOption.FullyEncoded env = { 'QUTE_MODE': 'hints', @@ -357,7 +357,7 @@ class HintActions: context: The HintContext to use. """ urlstr = url.toString( - QUrl.FullyEncoded | QUrl.RemovePassword) # type: ignore[arg-type] + QUrl.ComponentFormattingOption.FullyEncoded | QUrl.UrlFormattingOption.RemovePassword) # type: ignore[arg-type] args = context.get_args(urlstr) commandrunner = runners.CommandRunner(self._win_id) commandrunner.run_safely('spawn ' + ' '.join(args)) diff --git a/qutebrowser/browser/history.py b/qutebrowser/browser/history.py index 64ac896b7..c418f3ce4 100644 --- a/qutebrowser/browser/history.py +++ b/qutebrowser/browser/history.py @@ -434,10 +434,10 @@ class WebHistory(sql.SqlTable): }, replace=True) def _format_url(self, url): - return url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + return url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) def _format_completion_url(self, url): - return url.toString(QUrl.RemovePassword) + return url.toString(QUrl.UrlFormattingOption.RemovePassword) @cmdutils.register() diff --git a/qutebrowser/browser/inspector.py b/qutebrowser/browser/inspector.py index 33a30d2ac..8fb35fbb3 100644 --- a/qutebrowser/browser/inspector.py +++ b/qutebrowser/browser/inspector.py @@ -70,7 +70,7 @@ class _EventFilter(QObject): def eventFilter(self, _obj: QObject, event: QEvent) -> bool: """Translate mouse presses to a clicked signal.""" - if event.type() == QEvent.MouseButtonPress: + if event.type() == QEvent.Type.MouseButtonPress: self.clicked.emit() return False diff --git a/qutebrowser/browser/navigate.py b/qutebrowser/browser/navigate.py index 8368a7782..23a0f4437 100644 --- a/qutebrowser/browser/navigate.py +++ b/qutebrowser/browser/navigate.py @@ -42,24 +42,24 @@ class Error(Exception): # of information. (host and path use FullyDecoded by default) _URL_SEGMENTS = [ ('host', - lambda url: url.host(QUrl.FullyEncoded), - lambda url, host: url.setHost(host, QUrl.StrictMode)), + lambda url: url.host(QUrl.ComponentFormattingOption.FullyEncoded), + lambda url, host: url.setHost(host, QUrl.ParsingMode.StrictMode)), ('port', lambda url: str(url.port()) if url.port() > 0 else '', lambda url, x: url.setPort(int(x))), ('path', - lambda url: url.path(QUrl.FullyEncoded), - lambda url, path: url.setPath(path, QUrl.StrictMode)), + lambda url: url.path(QUrl.ComponentFormattingOption.FullyEncoded), + lambda url, path: url.setPath(path, QUrl.ParsingMode.StrictMode)), ('query', - lambda url: url.query(QUrl.FullyEncoded), - lambda url, query: url.setQuery(query, QUrl.StrictMode)), + lambda url: url.query(QUrl.ComponentFormattingOption.FullyEncoded), + lambda url, query: url.setQuery(query, QUrl.ParsingMode.StrictMode)), ('anchor', - lambda url: url.fragment(QUrl.FullyEncoded), - lambda url, fragment: url.setFragment(fragment, QUrl.StrictMode)), + lambda url: url.fragment(QUrl.ComponentFormattingOption.FullyEncoded), + lambda url, fragment: url.setFragment(fragment, QUrl.ParsingMode.StrictMode)), ] @@ -133,14 +133,14 @@ def path_up(url, count): count: The number of levels to go up in the url. """ urlutils.ensure_valid(url) - url = url.adjusted(QUrl.RemoveFragment | QUrl.RemoveQuery) - path = url.path(QUrl.FullyEncoded) + url = url.adjusted(QUrl.UrlFormattingOption.RemoveFragment | QUrl.UrlFormattingOption.RemoveQuery) + path = url.path(QUrl.ComponentFormattingOption.FullyEncoded) if not path or path == '/': raise Error("Can't go up!") for _i in range(0, min(count, path.count('/'))): path = posixpath.join(path, posixpath.pardir) path = posixpath.normpath(path) - url.setPath(path, QUrl.StrictMode) + url.setPath(path, QUrl.ParsingMode.StrictMode) return url @@ -149,7 +149,7 @@ def strip(url, count): if count != 1: raise Error("Count is not supported when stripping URL components") urlutils.ensure_valid(url) - return url.adjusted(QUrl.RemoveFragment | QUrl.RemoveQuery) + return url.adjusted(QUrl.UrlFormattingOption.RemoveFragment | QUrl.UrlFormattingOption.RemoveQuery) def _find_prevnext(prev, elems): diff --git a/qutebrowser/browser/network/pac.py b/qutebrowser/browser/network/pac.py index 7973cff2d..9e0da986f 100644 --- a/qutebrowser/browser/network/pac.py +++ b/qutebrowser/browser/network/pac.py @@ -109,10 +109,10 @@ class _PACContext(QObject): host: hostname to resolve. """ ips = QHostInfo.fromName(host) - if ips.error() != QHostInfo.NoError or not ips.addresses(): + if ips.error() != QHostInfo.HostInfoError.NoError or not ips.addresses(): err_f = "Failed to resolve host during PAC evaluation: {}" log.network.info(err_f.format(host)) - return QJSValue(QJSValue.NullValue) + return QJSValue(QJSValue.SpecialValue.NullValue) else: return ips.addresses()[0].toString() @@ -123,7 +123,7 @@ class _PACContext(QObject): Return the server IP address of the current machine, as a string in the dot-separated integer format. """ - return QHostAddress(QHostAddress.LocalHost).toString() + return QHostAddress(QHostAddress.SpecialAddress.LocalHost).toString() class PACResolver: @@ -150,17 +150,17 @@ class PACResolver: if len(config) != 1: raise ParseProxyError("Invalid number of parameters for " + "DIRECT") - return QNetworkProxy(QNetworkProxy.NoProxy) + return QNetworkProxy(QNetworkProxy.ProxyType.NoProxy) elif config[0] == "PROXY": if len(config) != 2: raise ParseProxyError("Invalid number of parameters for PROXY") host, port = PACResolver._parse_proxy_host(config[1]) - return QNetworkProxy(QNetworkProxy.HttpProxy, host, port) + return QNetworkProxy(QNetworkProxy.ProxyType.HttpProxy, host, port) elif config[0] in ["SOCKS", "SOCKS5"]: if len(config) != 2: raise ParseProxyError("Invalid number of parameters for SOCKS") host, port = PACResolver._parse_proxy_host(config[1]) - return QNetworkProxy(QNetworkProxy.Socks5Proxy, host, port) + return QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, host, port) else: err = "Unknown proxy type: {}" raise ParseProxyError(err.format(config[0])) @@ -184,7 +184,7 @@ class PACResolver: """ self._engine = QJSEngine() - self._engine.installExtensions(QJSEngine.ConsoleExtension) + self._engine.installExtensions(QJSEngine.Extension.ConsoleExtension) self._ctx = _PACContext(self._engine) self._engine.globalObject().setProperty( @@ -215,12 +215,12 @@ class PACResolver: qtutils.ensure_valid(query.url()) if from_file: - string_flags = QUrl.PrettyDecoded + string_flags = QUrl.ComponentFormattingOption.PrettyDecoded else: - string_flags = QUrl.RemoveUserInfo # type: ignore[assignment] + string_flags = QUrl.UrlFormattingOption.RemoveUserInfo # type: ignore[assignment] if query.url().scheme() == 'https': - string_flags |= QUrl.RemovePath # type: ignore[assignment] - string_flags |= QUrl.RemoveQuery # type: ignore[assignment] + string_flags |= QUrl.UrlFormattingOption.RemovePath # type: ignore[assignment] + string_flags |= QUrl.UrlFormattingOption.RemoveQuery # type: ignore[assignment] result = self._resolver.call([query.url().toString(string_flags), query.peerHostName()]) @@ -255,7 +255,7 @@ class PACFetcher(QObject): # WORKAROUND for a hang when messages are printed, see our # NetworkAccessManager subclass for details. self._manager: Optional[QNetworkAccessManager] = QNetworkAccessManager() - self._manager.setProxy(QNetworkProxy(QNetworkProxy.NoProxy)) + self._manager.setProxy(QNetworkProxy(QNetworkProxy.ProxyType.NoProxy)) self._pac = None self._error_message = None self._reply = None @@ -276,7 +276,7 @@ class PACFetcher(QObject): @pyqtSlot() def _finish(self): assert self._reply is not None - if self._reply.error() != QNetworkReply.NoError: + if self._reply.error() != QNetworkReply.NetworkError.NoError: error = "Can't fetch PAC file from URL, error code {}: {}" self._error_message = error.format( self._reply.error(), self._reply.errorString()) @@ -335,4 +335,4 @@ class PACFetcher(QObject): # Later NetworkManager.createRequest will detect this and display # an error message. error_host = "pac-resolve-error.qutebrowser.invalid" - return [QNetworkProxy(QNetworkProxy.HttpProxy, error_host, 9)] + return [QNetworkProxy(QNetworkProxy.ProxyType.HttpProxy, error_host, 9)] diff --git a/qutebrowser/browser/network/proxy.py b/qutebrowser/browser/network/proxy.py index 9f938a35e..e60ed6efd 100644 --- a/qutebrowser/browser/network/proxy.py +++ b/qutebrowser/browser/network/proxy.py @@ -73,11 +73,11 @@ class ProxyFactory(QNetworkProxyFactory): return None def _set_capabilities(self, proxy): - if proxy.type() == QNetworkProxy.NoProxy: + if proxy.type() == QNetworkProxy.ProxyType.NoProxy: return capabilities = proxy.capabilities() - lookup_cap = QNetworkProxy.HostNameLookupCapability + lookup_cap = QNetworkProxy.Capability.HostNameLookupCapability if config.val.content.proxy_dns_requests: capabilities |= lookup_cap else: diff --git a/qutebrowser/browser/pdfjs.py b/qutebrowser/browser/pdfjs.py index d531f71d2..c55ab81d1 100644 --- a/qutebrowser/browser/pdfjs.py +++ b/qutebrowser/browser/pdfjs.py @@ -96,7 +96,7 @@ def _generate_pdfjs_script(filename): url.setQuery(url_query) js_url = javascript.to_js( - url.toString(QUrl.FullyEncoded)) # type: ignore[arg-type] + url.toString(QUrl.ComponentFormattingOption.FullyEncoded)) # type: ignore[arg-type] return jinja.js_environment.from_string(""" document.addEventListener("DOMContentLoaded", function() { @@ -237,7 +237,7 @@ def get_main_url(filename: str, original_url: QUrl) -> QUrl: query = QUrlQuery() query.addQueryItem('filename', filename) # read from our JS query.addQueryItem('file', '') # to avoid pdfjs opening the default PDF - urlstr = original_url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + urlstr = original_url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] query.addQueryItem('source', urlstr) url.setQuery(query) return url diff --git a/qutebrowser/browser/qtnetworkdownloads.py b/qutebrowser/browser/qtnetworkdownloads.py index 2a2a67a69..c6b81c435 100644 --- a/qutebrowser/browser/qtnetworkdownloads.py +++ b/qutebrowser/browser/qtnetworkdownloads.py @@ -161,7 +161,7 @@ class DownloadItem(downloads.AbstractDownloadItem): # We could have got signals before we connected slots to them. # Here no signals are connected to the DownloadItem yet, so we use a # singleShot QTimer to emit them after they are connected. - if reply.error() != QNetworkReply.NoError: + if reply.error() != QNetworkReply.NetworkError.NoError: QTimer.singleShot(0, lambda: self._die(reply.errorString())) def _do_cancel(self): @@ -285,7 +285,7 @@ class DownloadItem(downloads.AbstractDownloadItem): self.fileobj.write(self._reply.readAll()) if self._autoclose: self.fileobj.close() - self.successful = self._reply.error() == QNetworkReply.NoError + self.successful = self._reply.error() == QNetworkReply.NetworkError.NoError self._reply.close() self._reply.deleteLater() self._reply = None @@ -333,7 +333,7 @@ class DownloadItem(downloads.AbstractDownloadItem): @pyqtSlot('QNetworkReply::NetworkError') def _on_reply_error(self, code): """Handle QNetworkReply errors.""" - if code == QNetworkReply.OperationCanceledError: + if code == QNetworkReply.NetworkError.OperationCanceledError: return if self._reply is None: @@ -371,7 +371,7 @@ class DownloadItem(downloads.AbstractDownloadItem): """ assert self._reply is not None redirect = self._reply.attribute( - QNetworkRequest.RedirectionTargetAttribute) + QNetworkRequest.Attribute.RedirectionTargetAttribute) if redirect is None or redirect.isEmpty(): return False new_url = self._reply.url().resolved(redirect) @@ -447,10 +447,10 @@ class DownloadManager(downloads.AbstractDownloadManager): req = QNetworkRequest(url) user_agent = websettings.user_agent(url) - req.setHeader(QNetworkRequest.UserAgentHeader, user_agent) + req.setHeader(QNetworkRequest.KnownHeaders.UserAgentHeader, user_agent) if not cache: - req.setAttribute(QNetworkRequest.CacheSaveControlAttribute, False) + req.setAttribute(QNetworkRequest.Attribute.CacheSaveControlAttribute, False) return self.get_request(req, **kwargs) @@ -509,8 +509,8 @@ class DownloadManager(downloads.AbstractDownloadManager): """ # WORKAROUND for Qt corrupting data loaded from cache: # https://bugreports.qt.io/browse/QTBUG-42757 - request.setAttribute(QNetworkRequest.CacheLoadControlAttribute, - QNetworkRequest.AlwaysNetwork) + request.setAttribute(QNetworkRequest.Attribute.CacheLoadControlAttribute, + QNetworkRequest.CacheLoadControl.AlwaysNetwork) if suggested_fn is None: suggested_fn = self._get_suggested_filename(request) diff --git a/qutebrowser/browser/qutescheme.py b/qutebrowser/browser/qutescheme.py index fdcd6cf39..ed38fdaaf 100644 --- a/qutebrowser/browser/qutescheme.py +++ b/qutebrowser/browser/qutescheme.py @@ -129,8 +129,8 @@ def data_for_url(url: QUrl) -> Tuple[str, bytes]: A (mimetype, data) tuple. """ norm_url = url.adjusted( - QUrl.NormalizePathSegments | # type: ignore[arg-type] - QUrl.StripTrailingSlash) + QUrl.UrlFormattingOption.NormalizePathSegments | # type: ignore[arg-type] + QUrl.UrlFormattingOption.StripTrailingSlash) if norm_url != url: raise Redirect(norm_url) @@ -425,8 +425,8 @@ def qute_help(url: QUrl) -> _HandlerRet: def _qute_settings_set(url: QUrl) -> _HandlerRet: """Handler for qute://settings/set.""" query = QUrlQuery(url) - option = query.queryItemValue('option', QUrl.FullyDecoded) - value = query.queryItemValue('value', QUrl.FullyDecoded) + option = query.queryItemValue('option', QUrl.ComponentFormattingOption.FullyDecoded) + value = query.queryItemValue('value', QUrl.ComponentFormattingOption.FullyDecoded) # https://github.com/qutebrowser/qutebrowser/issues/727 if option == 'content.javascript.enabled' and value == 'false': diff --git a/qutebrowser/browser/shared.py b/qutebrowser/browser/shared.py index b5e0c90cb..0188a653f 100644 --- a/qutebrowser/browser/shared.py +++ b/qutebrowser/browser/shared.py @@ -70,7 +70,7 @@ def authentication_required(url, authenticator, abort_on): else: msg = '<b>{}</b> needs authentication'.format( html.escape(url.toDisplayString())) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) answer = message.ask(title="Authentication required", text=msg, mode=usertypes.PromptMode.user_pwd, abort_on=abort_on, url=urlstr) @@ -93,7 +93,7 @@ def javascript_confirm(url, js_msg, abort_on): msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()), _format_msg(js_msg)) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) ans = message.ask('Javascript confirm', msg, mode=usertypes.PromptMode.yesno, abort_on=abort_on, url=urlstr) @@ -110,7 +110,7 @@ def javascript_prompt(url, js_msg, default, abort_on): msg = '<b>{}</b> asks:<br/>{}'.format(html.escape(url.toDisplayString()), _format_msg(js_msg)) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) answer = message.ask('Javascript prompt', msg, mode=usertypes.PromptMode.text, default=default, @@ -133,7 +133,7 @@ def javascript_alert(url, js_msg, abort_on): msg = 'From <b>{}</b>:<br/>{}'.format(html.escape(url.toDisplayString()), _format_msg(js_msg)) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) message.ask('Javascript alert', msg, mode=usertypes.PromptMode.alert, abort_on=abort_on, url=urlstr) @@ -185,7 +185,7 @@ def ignore_certificate_error( first_party_url.isValid() and not request_url.matches( first_party_url, - QUrl.RemoveScheme)) # type: ignore[arg-type] + QUrl.UrlFormattingOption.RemoveScheme)) # type: ignore[arg-type] if conf == 'ask' or conf == 'ask-block-thirdparty' and not is_resource: err_template = jinja.environment.from_string(""" @@ -216,7 +216,7 @@ def ignore_certificate_error( ) urlstr = request_url.toString( - QUrl.RemovePassword | QUrl.FullyEncoded) # type: ignore[arg-type] + QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] ignore = message.ask(title="Certificate error", text=msg, mode=usertypes.PromptMode.yesno, default=False, abort_on=abort_on, url=urlstr) @@ -258,7 +258,7 @@ def feature_permission(url, option, msg, yes_action, no_action, abort_on, config_val = config.instance.get(option, url=url) if config_val == 'ask': if url.isValid(): - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) text = "Allow the website at <b>{}</b> to {}?".format( html.escape(url.toDisplayString()), msg) else: diff --git a/qutebrowser/browser/urlmarks.py b/qutebrowser/browser/urlmarks.py index dc0d37284..99908f4f8 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -149,7 +149,7 @@ class QuickmarkManager(UrlMarkManager): if not url.isValid(): urlutils.invalid_url_error(url, "save quickmark") return - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) message.ask_async( "Add quickmark:", usertypes.PromptMode.text, functools.partial(self.quickmark_add, urlstr), @@ -196,7 +196,7 @@ class QuickmarkManager(UrlMarkManager): Use a name instead where possible. """ qtutils.ensure_valid(url) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) try: index = list(self.marks.values()).index(urlstr) @@ -268,7 +268,7 @@ class BookmarkManager(UrlMarkManager): errstr = urlutils.get_errstring(url) raise InvalidUrlError(errstr) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) if urlstr in self.marks: if toggle: diff --git a/qutebrowser/browser/webelem.py b/qutebrowser/browser/webelem.py index df534f99c..c9110a58d 100644 --- a/qutebrowser/browser/webelem.py +++ b/qutebrowser/browser/webelem.py @@ -339,7 +339,7 @@ class AbstractWebElement(collections.abc.MutableMapping): # type: ignore[type-a raise NotImplementedError def _click_fake_event(self, click_target: usertypes.ClickTarget, - button: Qt.MouseButton = Qt.LeftButton) -> None: + button: Qt.MouseButton = Qt.MouseButton.LeftButton) -> None: """Send a fake click event to the element.""" pos = self._mouse_pos() @@ -347,22 +347,22 @@ class AbstractWebElement(collections.abc.MutableMapping): # type: ignore[type-a "target {}".format(self, pos, click_target)) target_modifiers = { - usertypes.ClickTarget.normal: Qt.NoModifier, - usertypes.ClickTarget.window: Qt.AltModifier | Qt.ShiftModifier, - usertypes.ClickTarget.tab: Qt.ControlModifier, - usertypes.ClickTarget.tab_bg: Qt.ControlModifier, + usertypes.ClickTarget.normal: Qt.KeyboardModifier.NoModifier, + usertypes.ClickTarget.window: Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier, + usertypes.ClickTarget.tab: Qt.KeyboardModifier.ControlModifier, + usertypes.ClickTarget.tab_bg: Qt.KeyboardModifier.ControlModifier, } if config.val.tabs.background: - target_modifiers[usertypes.ClickTarget.tab] |= Qt.ShiftModifier + target_modifiers[usertypes.ClickTarget.tab] |= Qt.KeyboardModifier.ShiftModifier else: - target_modifiers[usertypes.ClickTarget.tab_bg] |= Qt.ShiftModifier + target_modifiers[usertypes.ClickTarget.tab_bg] |= Qt.KeyboardModifier.ShiftModifier modifiers = cast(Qt.KeyboardModifiers, target_modifiers[click_target]) events = [ - QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton, Qt.NoModifier), - QMouseEvent(QEvent.MouseButtonPress, pos, button, button, modifiers), - QMouseEvent(QEvent.MouseButtonRelease, pos, button, Qt.NoButton, modifiers), + QMouseEvent(QEvent.Type.MouseMove, pos, Qt.MouseButton.NoButton, Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier), + QMouseEvent(QEvent.Type.MouseButtonPress, pos, button, button, modifiers), + QMouseEvent(QEvent.Type.MouseButtonRelease, pos, button, Qt.MouseButton.NoButton, modifiers), ] for evt in events: @@ -446,11 +446,11 @@ class AbstractWebElement(collections.abc.MutableMapping): # type: ignore[type-a def hover(self) -> None: """Simulate a mouse hover over the element.""" pos = self._mouse_pos() - event = QMouseEvent(QEvent.MouseMove, pos, Qt.NoButton, Qt.NoButton, - Qt.NoModifier) + event = QMouseEvent(QEvent.Type.MouseMove, pos, Qt.MouseButton.NoButton, Qt.MouseButton.NoButton, + Qt.KeyboardModifier.NoModifier) self._tab.send_event(event) def right_click(self) -> None: """Simulate a right-click on the element.""" self._click_fake_event(usertypes.ClickTarget.normal, - button=Qt.RightButton) + button=Qt.MouseButton.RightButton) diff --git a/qutebrowser/browser/webengine/interceptor.py b/qutebrowser/browser/webengine/interceptor.py index de7e1ae1f..904baf3c9 100644 --- a/qutebrowser/browser/webengine/interceptor.py +++ b/qutebrowser/browser/webengine/interceptor.py @@ -71,43 +71,43 @@ class RequestInterceptor(QWebEngineUrlRequestInterceptor): # extension ResourceTypes. If a ResourceType is added to Qt, this table # should be updated too. self._resource_types = { - QWebEngineUrlRequestInfo.ResourceTypeMainFrame: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeMainFrame: interceptors.ResourceType.main_frame, - QWebEngineUrlRequestInfo.ResourceTypeSubFrame: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeSubFrame: interceptors.ResourceType.sub_frame, - QWebEngineUrlRequestInfo.ResourceTypeStylesheet: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeStylesheet: interceptors.ResourceType.stylesheet, - QWebEngineUrlRequestInfo.ResourceTypeScript: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeScript: interceptors.ResourceType.script, - QWebEngineUrlRequestInfo.ResourceTypeImage: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeImage: interceptors.ResourceType.image, - QWebEngineUrlRequestInfo.ResourceTypeFontResource: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeFontResource: interceptors.ResourceType.font_resource, - QWebEngineUrlRequestInfo.ResourceTypeSubResource: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeSubResource: interceptors.ResourceType.sub_resource, - QWebEngineUrlRequestInfo.ResourceTypeObject: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeObject: interceptors.ResourceType.object, - QWebEngineUrlRequestInfo.ResourceTypeMedia: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeMedia: interceptors.ResourceType.media, - QWebEngineUrlRequestInfo.ResourceTypeWorker: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeWorker: interceptors.ResourceType.worker, - QWebEngineUrlRequestInfo.ResourceTypeSharedWorker: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeSharedWorker: interceptors.ResourceType.shared_worker, - QWebEngineUrlRequestInfo.ResourceTypePrefetch: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypePrefetch: interceptors.ResourceType.prefetch, - QWebEngineUrlRequestInfo.ResourceTypeFavicon: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeFavicon: interceptors.ResourceType.favicon, - QWebEngineUrlRequestInfo.ResourceTypeXhr: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeXhr: interceptors.ResourceType.xhr, - QWebEngineUrlRequestInfo.ResourceTypePing: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypePing: interceptors.ResourceType.ping, - QWebEngineUrlRequestInfo.ResourceTypeServiceWorker: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeServiceWorker: interceptors.ResourceType.service_worker, - QWebEngineUrlRequestInfo.ResourceTypeCspReport: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeCspReport: interceptors.ResourceType.csp_report, - QWebEngineUrlRequestInfo.ResourceTypePluginResource: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypePluginResource: interceptors.ResourceType.plugin_resource, - QWebEngineUrlRequestInfo.ResourceTypeUnknown: + QWebEngineUrlRequestInfo.ResourceType.ResourceTypeUnknown: interceptors.ResourceType.unknown, } @@ -181,7 +181,7 @@ class RequestInterceptor(QWebEngineUrlRequestInterceptor): info.resourceType()))) resource_type = interceptors.ResourceType.unknown - is_xhr = info.resourceType() == QWebEngineUrlRequestInfo.ResourceTypeXhr + is_xhr = info.resourceType() == QWebEngineUrlRequestInfo.ResourceType.ResourceTypeXhr if ((url.scheme(), url.host(), url.path()) == ('qute', 'settings', '/set')): diff --git a/qutebrowser/browser/webengine/notification.py b/qutebrowser/browser/webengine/notification.py index f7264ecd6..1c06127a6 100644 --- a/qutebrowser/browser/webengine/notification.py +++ b/qutebrowser/browser/webengine/notification.py @@ -459,7 +459,7 @@ class SystrayNotificationAdapter(AbstractNotificationAdapter): """Convert a QImage to a QIcon.""" if image.isNull(): return QIcon() - pixmap = QPixmap.fromImage(image, Qt.NoFormatConversion) + pixmap = QPixmap.fromImage(image, Qt.ImageConversionFlag.NoFormatConversion) assert not pixmap.isNull() icon = QIcon(pixmap) assert not icon.isNull() @@ -610,7 +610,7 @@ class HerbeNotificationAdapter(AbstractNotificationAdapter): signals, we can't do much - emitting self.error would just go use herbe again, so there's no point. """ - if status == QProcess.CrashExit: + if status == QProcess.ExitStatus.CrashExit: return if code == 0: @@ -624,7 +624,7 @@ class HerbeNotificationAdapter(AbstractNotificationAdapter): @pyqtSlot(QProcess.ProcessError) def _on_error(self, error: QProcess.ProcessError) -> None: - if error == QProcess.Crashed: + if error == QProcess.ProcessError.Crashed: return name = debug.qenum_key(QProcess.ProcessError, error) raise Error(f'herbe process error: {name}') @@ -679,7 +679,7 @@ class _ServerCapabilities: def _as_uint32(x: int) -> QVariant: """Convert the given int to an uint32 for DBus.""" variant = QVariant(x) - successful = variant.convert(QVariant.UInt) + successful = variant.convert(QVariant.Type.UInt) assert successful return variant @@ -737,7 +737,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): self._watcher = QDBusServiceWatcher( self.SERVICE, bus, - QDBusServiceWatcher.WatchForUnregistration, + QDBusServiceWatcher.WatchModeFlag.WatchForUnregistration, self, ) self._watcher.serviceUnregistered.connect( # type: ignore[attr-defined] @@ -850,8 +850,8 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): def _get_server_info(self) -> None: """Query notification server information and set quirks.""" - reply = self.interface.call(QDBus.BlockWithGui, "GetServerInformation") - self._verify_message(reply, "ssss", QDBusMessage.ReplyMessage) + reply = self.interface.call(QDBus.CallMode.BlockWithGui, "GetServerInformation") + self._verify_message(reply, "ssss", QDBusMessage.MessageType.ReplyMessage) name, vendor, ver, spec_version = reply.arguments() log.misc.debug( @@ -895,11 +895,11 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): Raises DBusError if the signature doesn't match. """ assert expected_type not in [ - QDBusMessage.ErrorMessage, - QDBusMessage.InvalidMessage, + QDBusMessage.MessageType.ErrorMessage, + QDBusMessage.MessageType.InvalidMessage, ], expected_type - if msg.type() == QDBusMessage.ErrorMessage: + if msg.type() == QDBusMessage.MessageType.ErrorMessage: err = msg.errorName() if err in self._NON_FATAL_ERRORS: self.error.emit(msg.errorMessage()) @@ -934,7 +934,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): actions = [] if self._capabilities.actions: actions = ['default', 'Activate'] # key, name - actions_arg = QDBusArgument(actions, QMetaType.QStringList) + actions_arg = QDBusArgument(actions, QMetaType.Type.QStringList) origin_url_str = qt_notification.origin().toDisplayString() hints: Dict[str, Any] = { @@ -964,7 +964,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): title = html.escape(title, quote=False) reply = self.interface.call( - QDBus.BlockWithGui, + QDBus.CallMode.BlockWithGui, "Notify", "qutebrowser", # application name _as_uint32(replaces_id), # replaces notification id @@ -975,7 +975,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): hints, -1, # timeout; -1 means 'use default' ) - self._verify_message(reply, "u", QDBusMessage.ReplyMessage) + self._verify_message(reply, "u", QDBusMessage.MessageType.ReplyMessage) notification_id = reply.arguments()[0] @@ -999,10 +999,10 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): bits_per_color = 8 has_alpha = qimage.hasAlphaChannel() if has_alpha: - image_format = QImage.Format_RGBA8888 + image_format = QImage.Format.Format_RGBA8888 channel_count = 4 else: - image_format = QImage.Format_RGB888 + image_format = QImage.Format.Format_RGB888 channel_count = 3 qimage.convertTo(image_format) @@ -1067,14 +1067,14 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): @pyqtSlot(QDBusMessage) def _handle_close(self, msg: QDBusMessage) -> None: """Handle NotificationClosed from DBus.""" - self._verify_message(msg, "uu", QDBusMessage.SignalMessage) + self._verify_message(msg, "uu", QDBusMessage.MessageType.SignalMessage) notification_id, _close_reason = msg.arguments() self.close_id.emit(notification_id) @pyqtSlot(QDBusMessage) def _handle_action(self, msg: QDBusMessage) -> None: """Handle ActionInvoked from DBus.""" - self._verify_message(msg, "us", QDBusMessage.SignalMessage) + self._verify_message(msg, "us", QDBusMessage.MessageType.SignalMessage) notification_id, action_key = msg.arguments() if action_key == "default": self.click_id.emit(notification_id) @@ -1083,7 +1083,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): def on_web_closed(self, notification_id: int) -> None: """Send CloseNotification if a notification was closed from JS.""" self.interface.call( - QDBus.NoBlock, + QDBus.CallMode.NoBlock, "CloseNotification", _as_uint32(notification_id), ) @@ -1091,10 +1091,10 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): def _fetch_capabilities(self) -> None: """Fetch capabilities from the notification server.""" reply = self.interface.call( - QDBus.BlockWithGui, + QDBus.CallMode.BlockWithGui, "GetCapabilities", ) - self._verify_message(reply, "as", QDBusMessage.ReplyMessage) + self._verify_message(reply, "as", QDBusMessage.MessageType.ReplyMessage) caplist = reply.arguments()[0] self._capabilities = _ServerCapabilities.from_list(caplist) @@ -1121,7 +1121,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): prefix = None elif self._capabilities.body_markup and self._capabilities.body_hyperlinks: href = html.escape( - origin_url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + origin_url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] ) text = html.escape(urlstr, quote=False) prefix = f'<a href="{href}">{text}</a>' diff --git a/qutebrowser/browser/webengine/tabhistory.py b/qutebrowser/browser/webengine/tabhistory.py index db166647f..b87e41a41 100644 --- a/qutebrowser/browser/webengine/tabhistory.py +++ b/qutebrowser/browser/webengine/tabhistory.py @@ -124,7 +124,7 @@ def serialize(items): segfault! """ data = QByteArray() - stream = QDataStream(data, QIODevice.ReadWrite) + stream = QDataStream(data, QIODevice.OpenModeFlag.ReadWrite) cur_user_data = None current_idx = None diff --git a/qutebrowser/browser/webengine/webenginedownloads.py b/qutebrowser/browser/webengine/webenginedownloads.py index 85d7a4ce5..7dd1dcfab 100644 --- a/qutebrowser/browser/webengine/webenginedownloads.py +++ b/qutebrowser/browser/webengine/webenginedownloads.py @@ -56,7 +56,7 @@ class DownloadItem(downloads.AbstractDownloadItem): def _is_page_download(self): """Check if this item is a page (i.e. mhtml) download.""" return (self._qt_item.savePageFormat() != - QWebEngineDownloadItem.UnknownSaveFormat) + QWebEngineDownloadItem.SavePageFormat.UnknownSaveFormat) @pyqtSlot(QWebEngineDownloadItem.DownloadState) def _on_state_changed(self, state): @@ -64,11 +64,11 @@ class DownloadItem(downloads.AbstractDownloadItem): log.downloads.debug("State for {!r} changed to {}".format( self, state_name)) - if state == QWebEngineDownloadItem.DownloadRequested: + if state == QWebEngineDownloadItem.DownloadState.DownloadRequested: pass - elif state == QWebEngineDownloadItem.DownloadInProgress: + elif state == QWebEngineDownloadItem.DownloadState.DownloadInProgress: pass - elif state == QWebEngineDownloadItem.DownloadCompleted: + elif state == QWebEngineDownloadItem.DownloadState.DownloadCompleted: log.downloads.debug("Download {} finished".format(self.basename)) if self._is_page_download(): # Same logging as QtWebKit mhtml downloads. @@ -77,12 +77,12 @@ class DownloadItem(downloads.AbstractDownloadItem): self.done = True self.finished.emit() self.stats.finish() - elif state == QWebEngineDownloadItem.DownloadCancelled: + elif state == QWebEngineDownloadItem.DownloadState.DownloadCancelled: self.successful = False self.done = True self.cancelled.emit() self.stats.finish() - elif state == QWebEngineDownloadItem.DownloadInterrupted: + elif state == QWebEngineDownloadItem.DownloadState.DownloadInterrupted: self.successful = False reason = self._qt_item.interruptReasonString() self._die(reason) @@ -93,19 +93,19 @@ class DownloadItem(downloads.AbstractDownloadItem): def _do_die(self): progress_signal = self._qt_item.downloadProgress progress_signal.disconnect() # type: ignore[attr-defined] - if self._qt_item.state() != QWebEngineDownloadItem.DownloadInterrupted: + if self._qt_item.state() != QWebEngineDownloadItem.DownloadState.DownloadInterrupted: self._qt_item.cancel() def _do_cancel(self): state = self._qt_item.state() state_name = debug.qenum_key(QWebEngineDownloadItem, state) - assert state not in [QWebEngineDownloadItem.DownloadCompleted, - QWebEngineDownloadItem.DownloadCancelled], state_name + assert state not in [QWebEngineDownloadItem.DownloadState.DownloadCompleted, + QWebEngineDownloadItem.DownloadState.DownloadCancelled], state_name self._qt_item.cancel() def retry(self): state = self._qt_item.state() - if state != QWebEngineDownloadItem.DownloadInterrupted: + if state != QWebEngineDownloadItem.DownloadState.DownloadInterrupted: log.downloads.warning( "Refusing to retry download in state {}".format( debug.qenum_key(QWebEngineDownloadItem, state))) @@ -133,7 +133,7 @@ class DownloadItem(downloads.AbstractDownloadItem): def _ensure_can_set_filename(self, filename): state = self._qt_item.state() - if state != QWebEngineDownloadItem.DownloadRequested: + if state != QWebEngineDownloadItem.DownloadState.DownloadRequested: state_name = debug.qenum_key(QWebEngineDownloadItem, state) raise ValueError("Trying to set filename {} on {!r} which is " "state {} (not in requested state)!".format( @@ -247,7 +247,7 @@ class DownloadManager(downloads.AbstractDownloadManager): def install(self, profile): """Set up the download manager on a QWebEngineProfile.""" profile.downloadRequested.connect(self.handle_download, - Qt.DirectConnection) + Qt.ConnectionType.DirectConnection) @pyqtSlot(QWebEngineDownloadItem) def handle_download(self, qt_item): diff --git a/qutebrowser/browser/webengine/webengineelem.py b/qutebrowser/browser/webengine/webengineelem.py index a992d9d99..ed32ed469 100644 --- a/qutebrowser/browser/webengine/webengineelem.py +++ b/qutebrowser/browser/webengine/webengineelem.py @@ -240,7 +240,7 @@ class WebEngineElement(webelem.AbstractWebElement): view = self._tab._widget assert view is not None # pylint: enable=protected-access - attribute = QWebEngineSettings.JavascriptCanOpenWindows + attribute = QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows could_open_windows = view.settings().testAttribute(attribute) view.settings().setAttribute(attribute, True) @@ -249,8 +249,8 @@ class WebEngineElement(webelem.AbstractWebElement): # This is also used in Qt's tests: # https://github.com/qt/qtwebengine/commit/5e572e88efa7ba7c2b9138ec19e606d3e345ac90 QApplication.processEvents( # type: ignore[call-overload] - QEventLoop.ExcludeSocketNotifiers | - QEventLoop.ExcludeUserInputEvents) + QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers | + QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents) def reset_setting(_arg: Any) -> None: """Set the JavascriptCanOpenWindows setting to its old value.""" diff --git a/qutebrowser/browser/webengine/webengineinspector.py b/qutebrowser/browser/webengine/webengineinspector.py index 7d6a5308c..1c3bf80fd 100644 --- a/qutebrowser/browser/webengine/webengineinspector.py +++ b/qutebrowser/browser/webengine/webengineinspector.py @@ -89,7 +89,7 @@ class WebEngineInspector(inspector.AbstractWebInspector): if dist is None or dist.parsed != version.Distribution.fedora: return - data_path = pathlib.Path(QLibraryInfo.location(QLibraryInfo.DataPath)) + data_path = pathlib.Path(QLibraryInfo.location(QLibraryInfo.LibraryLocation.DataPath)) pak = data_path / 'resources' / 'qtwebengine_devtools_resources.pak' if not pak.exists(): raise inspector.Error("QtWebEngine devtools resources not found, " diff --git a/qutebrowser/browser/webengine/webenginequtescheme.py b/qutebrowser/browser/webengine/webenginequtescheme.py index 100817977..915890968 100644 --- a/qutebrowser/browser/webengine/webenginequtescheme.py +++ b/qutebrowser/browser/webengine/webenginequtescheme.py @@ -67,7 +67,7 @@ class QuteSchemeHandler(QWebEngineUrlSchemeHandler): log.network.warning("Blocking malicious request from {} to {}" .format(initiator.toDisplayString(), request_url.toDisplayString())) - job.fail(QWebEngineUrlRequestJob.RequestDenied) + job.fail(QWebEngineUrlRequestJob.Error.RequestDenied) return False return True @@ -87,7 +87,7 @@ class QuteSchemeHandler(QWebEngineUrlSchemeHandler): return if job.requestMethod() != b'GET': - job.fail(QWebEngineUrlRequestJob.RequestDenied) + job.fail(QWebEngineUrlRequestJob.Error.RequestDenied) return assert url.scheme() == 'qute' @@ -98,15 +98,15 @@ class QuteSchemeHandler(QWebEngineUrlSchemeHandler): except qutescheme.Error as e: errors = { qutescheme.NotFoundError: - QWebEngineUrlRequestJob.UrlNotFound, + QWebEngineUrlRequestJob.Error.UrlNotFound, qutescheme.UrlInvalidError: - QWebEngineUrlRequestJob.UrlInvalid, + QWebEngineUrlRequestJob.Error.UrlInvalid, qutescheme.RequestDeniedError: - QWebEngineUrlRequestJob.RequestDenied, + QWebEngineUrlRequestJob.Error.RequestDenied, qutescheme.SchemeOSError: - QWebEngineUrlRequestJob.UrlNotFound, + QWebEngineUrlRequestJob.Error.UrlNotFound, qutescheme.Error: - QWebEngineUrlRequestJob.RequestFailed, + QWebEngineUrlRequestJob.Error.RequestFailed, } exctype = type(e) log.network.error(f"{exctype.__name__} while handling qute://* URL: {e}") @@ -121,7 +121,7 @@ class QuteSchemeHandler(QWebEngineUrlSchemeHandler): # because that somehow segfaults... # https://www.riverbankcomputing.com/pipermail/pyqt/2016-September/038075.html buf = QBuffer(parent=self) - buf.open(QIODevice.WriteOnly) + buf.open(QIODevice.OpenModeFlag.WriteOnly) buf.write(data) buf.seek(0) buf.close() @@ -138,6 +138,6 @@ def init(): assert not QWebEngineUrlScheme.schemeByName(b'qute').name() scheme = QWebEngineUrlScheme(b'qute') scheme.setFlags( - QWebEngineUrlScheme.LocalScheme | # type: ignore[arg-type] - QWebEngineUrlScheme.LocalAccessAllowed) + QWebEngineUrlScheme.Flag.LocalScheme | # type: ignore[arg-type] + QWebEngineUrlScheme.Flag.LocalAccessAllowed) QWebEngineUrlScheme.registerScheme(scheme) diff --git a/qutebrowser/browser/webengine/webenginesettings.py b/qutebrowser/browser/webengine/webenginesettings.py index 0d0c3b502..e42b94a9f 100644 --- a/qutebrowser/browser/webengine/webenginesettings.py +++ b/qutebrowser/browser/webengine/webenginesettings.py @@ -110,93 +110,93 @@ class WebEngineSettings(websettings.AbstractSettings): _ATTRIBUTES = { 'content.xss_auditing': - Attr(QWebEngineSettings.XSSAuditingEnabled), + Attr(QWebEngineSettings.WebAttribute.XSSAuditingEnabled), 'content.images': - Attr(QWebEngineSettings.AutoLoadImages), + Attr(QWebEngineSettings.WebAttribute.AutoLoadImages), 'content.javascript.enabled': - Attr(QWebEngineSettings.JavascriptEnabled), + Attr(QWebEngineSettings.WebAttribute.JavascriptEnabled), 'content.javascript.can_open_tabs_automatically': - Attr(QWebEngineSettings.JavascriptCanOpenWindows), + Attr(QWebEngineSettings.WebAttribute.JavascriptCanOpenWindows), 'content.javascript.can_access_clipboard': - Attr(QWebEngineSettings.JavascriptCanAccessClipboard), + Attr(QWebEngineSettings.WebAttribute.JavascriptCanAccessClipboard), 'content.plugins': - Attr(QWebEngineSettings.PluginsEnabled), + Attr(QWebEngineSettings.WebAttribute.PluginsEnabled), 'content.hyperlink_auditing': - Attr(QWebEngineSettings.HyperlinkAuditingEnabled), + Attr(QWebEngineSettings.WebAttribute.HyperlinkAuditingEnabled), 'content.local_content_can_access_remote_urls': - Attr(QWebEngineSettings.LocalContentCanAccessRemoteUrls), + Attr(QWebEngineSettings.WebAttribute.LocalContentCanAccessRemoteUrls), 'content.local_content_can_access_file_urls': - Attr(QWebEngineSettings.LocalContentCanAccessFileUrls), + Attr(QWebEngineSettings.WebAttribute.LocalContentCanAccessFileUrls), 'content.webgl': - Attr(QWebEngineSettings.WebGLEnabled), + Attr(QWebEngineSettings.WebAttribute.WebGLEnabled), 'content.local_storage': - Attr(QWebEngineSettings.LocalStorageEnabled), + Attr(QWebEngineSettings.WebAttribute.LocalStorageEnabled), 'content.desktop_capture': - Attr(QWebEngineSettings.ScreenCaptureEnabled, + Attr(QWebEngineSettings.WebAttribute.ScreenCaptureEnabled, converter=lambda val: True if val == 'ask' else val), # 'ask' is handled via the permission system 'input.spatial_navigation': - Attr(QWebEngineSettings.SpatialNavigationEnabled), + Attr(QWebEngineSettings.WebAttribute.SpatialNavigationEnabled), 'input.links_included_in_focus_chain': - Attr(QWebEngineSettings.LinksIncludedInFocusChain), + Attr(QWebEngineSettings.WebAttribute.LinksIncludedInFocusChain), 'scrolling.smooth': - Attr(QWebEngineSettings.ScrollAnimatorEnabled), + Attr(QWebEngineSettings.WebAttribute.ScrollAnimatorEnabled), 'content.print_element_backgrounds': - Attr(QWebEngineSettings.PrintElementBackgrounds), + Attr(QWebEngineSettings.WebAttribute.PrintElementBackgrounds), 'content.autoplay': - Attr(QWebEngineSettings.PlaybackRequiresUserGesture, + Attr(QWebEngineSettings.WebAttribute.PlaybackRequiresUserGesture, converter=operator.not_), 'content.dns_prefetch': - Attr(QWebEngineSettings.DnsPrefetchEnabled), + Attr(QWebEngineSettings.WebAttribute.DnsPrefetchEnabled), 'tabs.favicons.show': - Attr(QWebEngineSettings.AutoLoadIconsForPage, + Attr(QWebEngineSettings.WebAttribute.AutoLoadIconsForPage, converter=lambda val: val != 'never'), } _FONT_SIZES = { 'fonts.web.size.minimum': - QWebEngineSettings.MinimumFontSize, + QWebEngineSettings.FontSize.MinimumFontSize, 'fonts.web.size.minimum_logical': - QWebEngineSettings.MinimumLogicalFontSize, + QWebEngineSettings.FontSize.MinimumLogicalFontSize, 'fonts.web.size.default': - QWebEngineSettings.DefaultFontSize, + QWebEngineSettings.FontSize.DefaultFontSize, 'fonts.web.size.default_fixed': - QWebEngineSettings.DefaultFixedFontSize, + QWebEngineSettings.FontSize.DefaultFixedFontSize, } _FONT_FAMILIES = { - 'fonts.web.family.standard': QWebEngineSettings.StandardFont, - 'fonts.web.family.fixed': QWebEngineSettings.FixedFont, - 'fonts.web.family.serif': QWebEngineSettings.SerifFont, - 'fonts.web.family.sans_serif': QWebEngineSettings.SansSerifFont, - 'fonts.web.family.cursive': QWebEngineSettings.CursiveFont, - 'fonts.web.family.fantasy': QWebEngineSettings.FantasyFont, + 'fonts.web.family.standard': QWebEngineSettings.FontFamily.StandardFont, + 'fonts.web.family.fixed': QWebEngineSettings.FontFamily.FixedFont, + 'fonts.web.family.serif': QWebEngineSettings.FontFamily.SerifFont, + 'fonts.web.family.sans_serif': QWebEngineSettings.FontFamily.SansSerifFont, + 'fonts.web.family.cursive': QWebEngineSettings.FontFamily.CursiveFont, + 'fonts.web.family.fantasy': QWebEngineSettings.FontFamily.FantasyFont, } _UNKNOWN_URL_SCHEME_POLICY = { 'disallow': - QWebEngineSettings.DisallowUnknownUrlSchemes, + QWebEngineSettings.UnknownUrlSchemePolicy.DisallowUnknownUrlSchemes, 'allow-from-user-interaction': - QWebEngineSettings.AllowUnknownUrlSchemesFromUserInteraction, + QWebEngineSettings.UnknownUrlSchemePolicy.AllowUnknownUrlSchemesFromUserInteraction, 'allow-all': - QWebEngineSettings.AllowAllUnknownUrlSchemes, + QWebEngineSettings.UnknownUrlSchemePolicy.AllowAllUnknownUrlSchemes, } # Mapping from WebEngineSettings::initDefaults in # qtwebengine/src/core/web_engine_settings.cpp _FONT_TO_QFONT = { - QWebEngineSettings.StandardFont: QFont.Serif, - QWebEngineSettings.FixedFont: QFont.Monospace, - QWebEngineSettings.SerifFont: QFont.Serif, - QWebEngineSettings.SansSerifFont: QFont.SansSerif, - QWebEngineSettings.CursiveFont: QFont.Cursive, - QWebEngineSettings.FantasyFont: QFont.Fantasy, + QWebEngineSettings.FontFamily.StandardFont: QFont.StyleHint.Serif, + QWebEngineSettings.FontFamily.FixedFont: QFont.StyleHint.Monospace, + QWebEngineSettings.FontFamily.SerifFont: QFont.StyleHint.Serif, + QWebEngineSettings.FontFamily.SansSerifFont: QFont.StyleHint.SansSerif, + QWebEngineSettings.FontFamily.CursiveFont: QFont.StyleHint.Cursive, + QWebEngineSettings.FontFamily.FantasyFont: QFont.StyleHint.Fantasy, } def set_unknown_url_scheme_policy( @@ -265,12 +265,12 @@ class ProfileSetter: settings = self._profile.settings() settings.setAttribute( - QWebEngineSettings.FullScreenSupportEnabled, True) + QWebEngineSettings.WebAttribute.FullScreenSupportEnabled, True) settings.setAttribute( - QWebEngineSettings.FocusOnNavigationEnabled, False) + QWebEngineSettings.WebAttribute.FocusOnNavigationEnabled, False) try: - settings.setAttribute(QWebEngineSettings.PdfViewerEnabled, False) + settings.setAttribute(QWebEngineSettings.WebAttribute.PdfViewerEnabled, False) except AttributeError: # Added in Qt 5.13 pass @@ -305,9 +305,9 @@ class ProfileSetter: if self._profile.isOffTheRecord(): return if config.val.content.cookies.store: - value = QWebEngineProfile.AllowPersistentCookies + value = QWebEngineProfile.PersistentCookiesPolicy.AllowPersistentCookies else: - value = QWebEngineProfile.NoPersistentCookies + value = QWebEngineProfile.PersistentCookiesPolicy.NoPersistentCookies self._profile.setPersistentCookiesPolicy(value) def set_dictionary_language(self): diff --git a/qutebrowser/browser/webengine/webenginetab.py b/qutebrowser/browser/webengine/webenginetab.py index 6cad141f5..f01e902fb 100644 --- a/qutebrowser/browser/webengine/webenginetab.py +++ b/qutebrowser/browser/webengine/webenginetab.py @@ -45,10 +45,10 @@ from qutebrowser.misc import objects, miscwidgets # Mapping worlds from usertypes.JsWorld to QWebEngineScript world IDs. _JS_WORLD_MAP = { - usertypes.JsWorld.main: QWebEngineScript.MainWorld, - usertypes.JsWorld.application: QWebEngineScript.ApplicationWorld, - usertypes.JsWorld.user: QWebEngineScript.UserWorld, - usertypes.JsWorld.jseval: QWebEngineScript.UserWorld + 1, + usertypes.JsWorld.main: QWebEngineScript.ScriptWorldId.MainWorld, + usertypes.JsWorld.application: QWebEngineScript.ScriptWorldId.ApplicationWorld, + usertypes.JsWorld.user: QWebEngineScript.ScriptWorldId.UserWorld, + usertypes.JsWorld.jseval: QWebEngineScript.ScriptWorldId.UserWorld + 1, } @@ -60,18 +60,18 @@ class WebEngineAction(browsertab.AbstractAction): action_base = QWebEnginePage.WebAction def exit_fullscreen(self): - self._widget.triggerPageAction(QWebEnginePage.ExitFullScreen) + self._widget.triggerPageAction(QWebEnginePage.WebAction.ExitFullScreen) def save_page(self): """Save the current page.""" - self._widget.triggerPageAction(QWebEnginePage.SavePage) + self._widget.triggerPageAction(QWebEnginePage.WebAction.SavePage) def show_source(self, pygments=False): if pygments: self._show_source_pygments() return - self._widget.triggerPageAction(QWebEnginePage.ViewSource) + self._widget.triggerPageAction(QWebEnginePage.WebAction.ViewSource) class WebEnginePrinting(browsertab.AbstractPrinting): @@ -254,9 +254,9 @@ class WebEngineSearch(browsertab.AbstractSearch): self._wrap_handler.reset_match_data() self._wrap_handler.flag_wrap = wrap if self._is_case_sensitive(ignore_case): - self._flags |= QWebEnginePage.FindCaseSensitively + self._flags |= QWebEnginePage.FindFlag.FindCaseSensitively if reverse: - self._flags |= QWebEnginePage.FindBackward + self._flags |= QWebEnginePage.FindFlag.FindBackward self._find(text, self._flags, result_cb, 'search') @@ -271,18 +271,18 @@ class WebEngineSearch(browsertab.AbstractSearch): # The int() here makes sure we get a copy of the flags. flags = QWebEnginePage.FindFlags( int(self._flags)) # type: ignore[call-overload] - if flags & QWebEnginePage.FindBackward: + if flags & QWebEnginePage.FindFlag.FindBackward: if self._wrap_handler.prevent_wrapping(going_up=False): return - flags &= ~QWebEnginePage.FindBackward + flags &= ~QWebEnginePage.FindFlag.FindBackward else: if self._wrap_handler.prevent_wrapping(going_up=True): return - flags |= QWebEnginePage.FindBackward + flags |= QWebEnginePage.FindFlag.FindBackward self._find(self.text, flags, result_cb, 'prev_result') def next_result(self, *, result_cb=None): - going_up = self._flags & QWebEnginePage.FindBackward + going_up = self._flags & QWebEnginePage.FindFlag.FindBackward if self._wrap_handler.prevent_wrapping(going_up=going_up): return self._find(self.text, self._flags, result_cb, 'next_result') @@ -498,7 +498,7 @@ class WebEngineScroller(browsertab.AbstractScroller): page = widget.page() page.scrollPositionChanged.connect(self._update_pos) - def _repeated_key_press(self, key, count=1, modifier=Qt.NoModifier): + def _repeated_key_press(self, key, count=1, modifier=Qt.KeyboardModifier.NoModifier): """Send count fake key presses to this scroller's WebEngineTab.""" for _ in range(min(count, 1000)): self._tab.fake_key_press(key, modifier) @@ -577,28 +577,28 @@ class WebEngineScroller(browsertab.AbstractScroller): self._tab.run_js_async(js_code) def up(self, count=1): - self._repeated_key_press(Qt.Key_Up, count) + self._repeated_key_press(Qt.Key.Key_Up, count) def down(self, count=1): - self._repeated_key_press(Qt.Key_Down, count) + self._repeated_key_press(Qt.Key.Key_Down, count) def left(self, count=1): - self._repeated_key_press(Qt.Key_Left, count) + self._repeated_key_press(Qt.Key.Key_Left, count) def right(self, count=1): - self._repeated_key_press(Qt.Key_Right, count) + self._repeated_key_press(Qt.Key.Key_Right, count) def top(self): - self._tab.fake_key_press(Qt.Key_Home) + self._tab.fake_key_press(Qt.Key.Key_Home) def bottom(self): - self._tab.fake_key_press(Qt.Key_End) + self._tab.fake_key_press(Qt.Key.Key_End) def page_up(self, count=1): - self._repeated_key_press(Qt.Key_PageUp, count) + self._repeated_key_press(Qt.Key.Key_PageUp, count) def page_down(self, count=1): - self._repeated_key_press(Qt.Key_PageDown, count) + self._repeated_key_press(Qt.Key.Key_PageDown, count) def at_top(self): return self.pos_px().y() == 0 @@ -844,24 +844,24 @@ class _WebEnginePermissions(QObject): _options = { 0: 'content.notifications.enabled', - QWebEnginePage.Geolocation: 'content.geolocation', - QWebEnginePage.MediaAudioCapture: 'content.media.audio_capture', - QWebEnginePage.MediaVideoCapture: 'content.media.video_capture', - QWebEnginePage.MediaAudioVideoCapture: 'content.media.audio_video_capture', - QWebEnginePage.MouseLock: 'content.mouse_lock', - QWebEnginePage.DesktopVideoCapture: 'content.desktop_capture', - QWebEnginePage.DesktopAudioVideoCapture: 'content.desktop_capture', + QWebEnginePage.Feature.Geolocation: 'content.geolocation', + QWebEnginePage.Feature.MediaAudioCapture: 'content.media.audio_capture', + QWebEnginePage.Feature.MediaVideoCapture: 'content.media.video_capture', + QWebEnginePage.Feature.MediaAudioVideoCapture: 'content.media.audio_video_capture', + QWebEnginePage.Feature.MouseLock: 'content.mouse_lock', + QWebEnginePage.Feature.DesktopVideoCapture: 'content.desktop_capture', + QWebEnginePage.Feature.DesktopAudioVideoCapture: 'content.desktop_capture', } _messages = { 0: 'show notifications', - QWebEnginePage.Geolocation: 'access your location', - QWebEnginePage.MediaAudioCapture: 'record audio', - QWebEnginePage.MediaVideoCapture: 'record video', - QWebEnginePage.MediaAudioVideoCapture: 'record audio/video', - QWebEnginePage.MouseLock: 'hide your mouse pointer', - QWebEnginePage.DesktopVideoCapture: 'capture your desktop', - QWebEnginePage.DesktopAudioVideoCapture: 'capture your desktop and audio', + QWebEnginePage.Feature.Geolocation: 'access your location', + QWebEnginePage.Feature.MediaAudioCapture: 'record audio', + QWebEnginePage.Feature.MediaVideoCapture: 'record video', + QWebEnginePage.Feature.MediaAudioVideoCapture: 'record audio/video', + QWebEnginePage.Feature.MouseLock: 'hide your mouse pointer', + QWebEnginePage.Feature.DesktopVideoCapture: 'capture your desktop', + QWebEnginePage.Feature.DesktopAudioVideoCapture: 'capture your desktop and audio', } def __init__(self, tab, parent=None): @@ -902,10 +902,10 @@ class _WebEnginePermissions(QObject): page = self._widget.page() grant_permission = functools.partial( page.setFeaturePermission, url, feature, - QWebEnginePage.PermissionGrantedByUser) + QWebEnginePage.PermissionPolicy.PermissionGrantedByUser) deny_permission = functools.partial( page.setFeaturePermission, url, feature, - QWebEnginePage.PermissionDeniedByUser) + QWebEnginePage.PermissionPolicy.PermissionDeniedByUser) permission_str = debug.qenum_key(QWebEnginePage, feature) @@ -915,7 +915,7 @@ class _WebEnginePermissions(QObject): compiled=False, exact=True) and self._tab.is_private and - feature == QWebEnginePage.Notifications) + feature == QWebEnginePage.Feature.Notifications) logger = log.webview.debug if is_qtbug else log.webview.warning logger("Ignoring feature permission {} for invalid URL {}".format( permission_str, url)) @@ -929,8 +929,8 @@ class _WebEnginePermissions(QObject): return if ( - feature in [QWebEnginePage.DesktopVideoCapture, - QWebEnginePage.DesktopAudioVideoCapture] and + feature in [QWebEnginePage.Feature.DesktopVideoCapture, + QWebEnginePage.Feature.DesktopAudioVideoCapture] and qtutils.version_check('5.13', compiled=False) and not qtutils.version_check('5.13.2', compiled=False) ): @@ -941,7 +941,7 @@ class _WebEnginePermissions(QObject): return question = shared.feature_permission( - url=url.adjusted(QUrl.RemovePath), + url=url.adjusted(QUrl.UrlFormattingOption.RemovePath), option=self._options[feature], msg=self._messages[feature], yes_action=grant_permission, no_action=deny_permission, abort_on=[self._tab.abort_questions]) @@ -968,7 +968,7 @@ class _WebEnginePermissions(QObject): def _on_quota_requested(self, request): size = utils.format_size(request.requestedSize()) shared.feature_permission( - url=request.origin().adjusted(QUrl.RemovePath), + url=request.origin().adjusted(QUrl.UrlFormattingOption.RemovePath), option='content.persistent_storage', msg='use {} of persistent storage'.format(size), yes_action=request.accept, no_action=request.reject, @@ -977,7 +977,7 @@ class _WebEnginePermissions(QObject): def _on_register_protocol_handler_requested(self, request): shared.feature_permission( - url=request.origin().adjusted(QUrl.RemovePath), + url=request.origin().adjusted(QUrl.UrlFormattingOption.RemovePath), option='content.register_protocol_handler', msg='open all {} links'.format(request.scheme()), yes_action=request.accept, no_action=request.reject, @@ -990,8 +990,8 @@ class _Quirk: filename: str injection_point: QWebEngineScript.InjectionPoint = ( - QWebEngineScript.DocumentCreation) - world: QWebEngineScript.ScriptWorldId = QWebEngineScript.MainWorld + QWebEngineScript.InjectionPoint.DocumentCreation) + world: QWebEngineScript.ScriptWorldId = QWebEngineScript.ScriptWorldId.MainWorld predicate: bool = True name: Optional[str] = None @@ -1030,8 +1030,8 @@ class _WebEngineScripts(QObject): self._tab.run_js_async(code) def _inject_js(self, name, js_code, *, - world=QWebEngineScript.ApplicationWorld, - injection_point=QWebEngineScript.DocumentCreation, + world=QWebEngineScript.ScriptWorldId.ApplicationWorld, + injection_point=QWebEngineScript.InjectionPoint.DocumentCreation, subframes=False): """Inject the given script to run early on a page load.""" script = QWebEngineScript() @@ -1140,13 +1140,13 @@ class _WebEngineScripts(QObject): # Corresponds to "@run-at document-end" which is the default according to # https://wiki.greasespot.net/Metadata_Block#.40run-at - however, - # QtWebEngine uses QWebEngineScript.Deferred (@run-at document-idle) as + # QtWebEngine uses QWebEngineScript.InjectionPoint.Deferred (@run-at document-idle) as # default. # # NOTE that this needs to be done before setSourceCode, so that # QtWebEngine's parsing of GreaseMonkey tags will override it if there is a # @run-at comment. - new_script.setInjectionPoint(QWebEngineScript.DocumentReady) + new_script.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady) new_script.setSourceCode(script.code()) new_script.setName(script.full_name()) @@ -1155,7 +1155,7 @@ class _WebEngineScripts(QObject): if script.needs_document_end_workaround(): log.greasemonkey.debug( f"Forcing @run-at document-end for {script.name}") - new_script.setInjectionPoint(QWebEngineScript.DocumentReady) + new_script.setInjectionPoint(QWebEngineScript.InjectionPoint.DocumentReady) log.greasemonkey.debug(f'adding script: {new_script.name()}') page_scripts.insert(new_script) @@ -1169,8 +1169,8 @@ class _WebEngineScripts(QObject): quirks = [ _Quirk( 'whatsapp_web', - injection_point=QWebEngineScript.DocumentReady, - world=QWebEngineScript.ApplicationWorld, + injection_point=QWebEngineScript.InjectionPoint.DocumentReady, + world=QWebEngineScript.ScriptWorldId.ApplicationWorld, ), _Quirk('discord'), _Quirk( @@ -1330,7 +1330,7 @@ class WebEngineTab(browsertab.AbstractTab): def run_js_async(self, code, callback=None, *, world=None): world_id_type = Union[QWebEngineScript.ScriptWorldId, int] if world is None: - world_id: world_id_type = QWebEngineScript.ApplicationWorld + world_id: world_id_type = QWebEngineScript.ScriptWorldId.ApplicationWorld elif isinstance(world, int): world_id = world if not 0 <= world_id <= qtutils.MAX_WORLD_ID: @@ -1347,9 +1347,9 @@ class WebEngineTab(browsertab.AbstractTab): def reload(self, *, force=False): if force: - action = QWebEnginePage.ReloadAndBypassCache + action = QWebEnginePage.WebAction.ReloadAndBypassCache else: - action = QWebEnginePage.Reload + action = QWebEnginePage.WebAction.Reload self._widget.triggerPageAction(action) def stop(self): @@ -1406,7 +1406,7 @@ class WebEngineTab(browsertab.AbstractTab): title_url = QUrl(url) title_url.setScheme('') title_url_str = title_url.toDisplayString( - QUrl.RemoveScheme) # type: ignore[arg-type] + QUrl.UrlFormattingOption.RemoveScheme) # type: ignore[arg-type] if title == title_url_str.strip('/'): title = "" @@ -1423,7 +1423,7 @@ class WebEngineTab(browsertab.AbstractTab): """Called when a proxy needs authentication.""" msg = "<b>{}</b> requires a username and password.".format( html_utils.escape(proxy_host)) - urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded) + urlstr = url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) answer = message.ask( title="Proxy authentication required", text=msg, mode=usertypes.PromptMode.user_pwd, @@ -1472,19 +1472,19 @@ class WebEngineTab(browsertab.AbstractTab): @pyqtSlot(QWebEnginePage.RenderProcessTerminationStatus, int) def _on_render_process_terminated(self, status, exitcode): """Show an error when the renderer process terminated.""" - if (status == QWebEnginePage.AbnormalTerminationStatus and + if (status == QWebEnginePage.RenderProcessTerminationStatus.AbnormalTerminationStatus and exitcode == 256): # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-58697 - status = QWebEnginePage.CrashedTerminationStatus + status = QWebEnginePage.RenderProcessTerminationStatus.CrashedTerminationStatus status_map = { - QWebEnginePage.NormalTerminationStatus: + QWebEnginePage.RenderProcessTerminationStatus.NormalTerminationStatus: browsertab.TerminationStatus.normal, - QWebEnginePage.AbnormalTerminationStatus: + QWebEnginePage.RenderProcessTerminationStatus.AbnormalTerminationStatus: browsertab.TerminationStatus.abnormal, - QWebEnginePage.CrashedTerminationStatus: + QWebEnginePage.RenderProcessTerminationStatus.CrashedTerminationStatus: browsertab.TerminationStatus.crashed, - QWebEnginePage.KilledTerminationStatus: + QWebEnginePage.RenderProcessTerminationStatus.KilledTerminationStatus: browsertab.TerminationStatus.killed, -1: browsertab.TerminationStatus.unknown, @@ -1584,7 +1584,7 @@ class WebEngineTab(browsertab.AbstractTab): # have happened when loading some resource. is_resource = ( first_party_url.isValid() and - url.matches(first_party_url, QUrl.RemoveScheme)) + url.matches(first_party_url, QUrl.UrlFormattingOption.RemoveScheme)) if show_non_overr_cert_error and is_resource: self._show_error_page(url, str(error)) diff --git a/qutebrowser/browser/webengine/webview.py b/qutebrowser/browser/webengine/webview.py index 6ca96716b..d82dbcff7 100644 --- a/qutebrowser/browser/webengine/webview.py +++ b/qutebrowser/browser/webengine/webview.py @@ -32,8 +32,8 @@ from qutebrowser.utils import log, debug, usertypes _QB_FILESELECTION_MODES = { - QWebEnginePage.FileSelectOpen: shared.FileSelectionMode.single_file, - QWebEnginePage.FileSelectOpenMultiple: shared.FileSelectionMode.multiple_files, + QWebEnginePage.FileSelectionMode.FileSelectOpen: shared.FileSelectionMode.single_file, + QWebEnginePage.FileSelectionMode.FileSelectOpenMultiple: shared.FileSelectionMode.multiple_files, # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-91489 # # QtWebEngine doesn't expose this value from its internal @@ -54,7 +54,7 @@ class WebEngineView(QWebEngineView): self._win_id = win_id self._tabdata = tabdata - theme_color = self.style().standardPalette().color(QPalette.Base) + theme_color = self.style().standardPalette().color(QPalette.ColorRole.Base) if private: assert webenginesettings.private_profile is not None profile = webenginesettings.private_profile @@ -103,21 +103,21 @@ class WebEngineView(QWebEngineView): log.webview.debug("createWindow with type {}, background {}".format( debug_type, background)) - if wintype == QWebEnginePage.WebBrowserWindow: + if wintype == QWebEnginePage.WebWindowType.WebBrowserWindow: # Shift-Alt-Click target = usertypes.ClickTarget.window - elif wintype == QWebEnginePage.WebDialog: + elif wintype == QWebEnginePage.WebWindowType.WebDialog: log.webview.warning("{} requested, but we don't support " "that!".format(debug_type)) target = usertypes.ClickTarget.tab - elif wintype == QWebEnginePage.WebBrowserTab: + elif wintype == QWebEnginePage.WebWindowType.WebBrowserTab: # Middle-click / Ctrl-Click with Shift # FIXME:qtwebengine this also affects target=_blank links... if background: target = usertypes.ClickTarget.tab else: target = usertypes.ClickTarget.tab_bg - elif wintype == QWebEnginePage.WebBrowserBackgroundTab: + elif wintype == QWebEnginePage.WebWindowType.WebBrowserBackgroundTab: # Middle-click / Ctrl-Click if background: target = usertypes.ClickTarget.tab_bg @@ -214,9 +214,9 @@ class WebEnginePage(QWebEnginePage): def javaScriptConsoleMessage(self, level, msg, line, source): """Log javascript messages to qutebrowser's log.""" level_map = { - QWebEnginePage.InfoMessageLevel: usertypes.JsLogLevel.info, - QWebEnginePage.WarningMessageLevel: usertypes.JsLogLevel.warning, - QWebEnginePage.ErrorMessageLevel: usertypes.JsLogLevel.error, + QWebEnginePage.JavaScriptConsoleMessageLevel.InfoMessageLevel: usertypes.JsLogLevel.info, + QWebEnginePage.JavaScriptConsoleMessageLevel.WarningMessageLevel: usertypes.JsLogLevel.warning, + QWebEnginePage.JavaScriptConsoleMessageLevel.ErrorMessageLevel: usertypes.JsLogLevel.error, } shared.javascript_log_message(level_map[level], source, line, msg) @@ -226,21 +226,21 @@ class WebEnginePage(QWebEnginePage): is_main_frame: bool) -> bool: """Override acceptNavigationRequest to forward it to the tab API.""" type_map = { - QWebEnginePage.NavigationTypeLinkClicked: + QWebEnginePage.NavigationType.NavigationTypeLinkClicked: usertypes.NavigationRequest.Type.link_clicked, - QWebEnginePage.NavigationTypeTyped: + QWebEnginePage.NavigationType.NavigationTypeTyped: usertypes.NavigationRequest.Type.typed, - QWebEnginePage.NavigationTypeFormSubmitted: + QWebEnginePage.NavigationType.NavigationTypeFormSubmitted: usertypes.NavigationRequest.Type.form_submitted, - QWebEnginePage.NavigationTypeBackForward: + QWebEnginePage.NavigationType.NavigationTypeBackForward: usertypes.NavigationRequest.Type.back_forward, - QWebEnginePage.NavigationTypeReload: + QWebEnginePage.NavigationType.NavigationTypeReload: usertypes.NavigationRequest.Type.reloaded, - QWebEnginePage.NavigationTypeOther: + QWebEnginePage.NavigationType.NavigationTypeOther: usertypes.NavigationRequest.Type.other, } try: - type_map[QWebEnginePage.NavigationTypeRedirect] = ( + type_map[QWebEnginePage.NavigationType.NavigationTypeRedirect] = ( usertypes.NavigationRequest.Type.redirect) except AttributeError: # Added in Qt 5.14 diff --git a/qutebrowser/browser/webkit/http.py b/qutebrowser/browser/webkit/http.py index 6a6165767..10d98032e 100644 --- a/qutebrowser/browser/webkit/http.py +++ b/qutebrowser/browser/webkit/http.py @@ -180,7 +180,7 @@ def parse_content_type(reply): A [mimetype, rest] list, or [None, None] if unset. Rest can be None. """ - content_type = reply.header(QNetworkRequest.ContentTypeHeader) + content_type = reply.header(QNetworkRequest.KnownHeaders.ContentTypeHeader) if content_type is None: return [None, None] if ';' in content_type: diff --git a/qutebrowser/browser/webkit/network/networkmanager.py b/qutebrowser/browser/webkit/network/networkmanager.py index cf18822c8..b8e87350b 100644 --- a/qutebrowser/browser/webkit/network/networkmanager.py +++ b/qutebrowser/browser/webkit/network/networkmanager.py @@ -79,7 +79,7 @@ def _is_secure_cipher(cipher): return False # OpenSSL should already protect against this in a better way # elif (('CBC3' in tokens or 'CBC' in tokens) and (cipher.protocol() not in - # [QSsl.TlsV1_0, QSsl.TlsV1_1, QSsl.TlsV1_2])): + # [QSsl.SslProtocol.TlsV1_0, QSsl.SslProtocol.TlsV1_1, QSsl.SslProtocol.TlsV1_2])): # # https://en.wikipedia.org/wiki/POODLE # return False ### These things should never happen as those are already filtered out by @@ -238,7 +238,7 @@ class NetworkManager(QNetworkAccessManager): def shutdown(self): """Abort all running requests.""" - self.setNetworkAccessible(QNetworkAccessManager.NotAccessible) + self.setNetworkAccessible(QNetworkAccessManager.NetworkAccessibility.NotAccessible) self.shutting_down.emit() # No @pyqtSlot here, see @@ -405,14 +405,14 @@ class NetworkManager(QNetworkAccessManager): proxy_error = proxymod.application_factory.get_error() if proxy_error is not None: return networkreply.ErrorNetworkReply( - req, proxy_error, QNetworkReply.UnknownProxyError, + req, proxy_error, QNetworkReply.NetworkError.UnknownProxyError, self) if not req.url().isValid(): log.network.debug("Ignoring invalid requested URL: {}".format( req.url().errorString())) return networkreply.ErrorNetworkReply( - req, "Invalid request URL", QNetworkReply.HostNotFoundError, + req, "Invalid request URL", QNetworkReply.NetworkError.HostNotFoundError, self) for header, value in shared.custom_headers(url=req.url()): @@ -432,7 +432,7 @@ class NetworkManager(QNetworkAccessManager): interceptors.run(request) if request.is_blocked: return networkreply.ErrorNetworkReply( - req, HOSTBLOCK_ERROR_STRING, QNetworkReply.ContentAccessDenied, + req, HOSTBLOCK_ERROR_STRING, QNetworkReply.NetworkError.ContentAccessDenied, self) if 'log-requests' in objects.debug_flags: diff --git a/qutebrowser/browser/webkit/network/networkreply.py b/qutebrowser/browser/webkit/network/networkreply.py index 5f762d806..6b8f56a27 100644 --- a/qutebrowser/browser/webkit/network/networkreply.py +++ b/qutebrowser/browser/webkit/network/networkreply.py @@ -49,13 +49,13 @@ class FixedDataNetworkReply(QNetworkReply): self.setRequest(request) self.setUrl(request.url()) - self.setOpenMode(QIODevice.ReadOnly) + self.setOpenMode(QIODevice.OpenModeFlag.ReadOnly) - self.setHeader(QNetworkRequest.ContentTypeHeader, mimeType) - self.setHeader(QNetworkRequest.ContentLengthHeader, + self.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, mimeType) + self.setHeader(QNetworkRequest.KnownHeaders.ContentLengthHeader, QByteArray.number(len(fileData))) - self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200) - self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, 'OK') + self.setAttribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute, 200) + self.setAttribute(QNetworkRequest.Attribute.HttpReasonPhraseAttribute, 'OK') # For some reason, a segfault will be triggered if these lambdas aren't # there. # pylint: disable=unnecessary-lambda @@ -120,7 +120,7 @@ class ErrorNetworkReply(QNetworkReply): self.setUrl(req.url()) # We don't actually want to read anything, but we still need to open # the device to avoid getting a warning. - self.setOpenMode(QIODevice.ReadOnly) + self.setOpenMode(QIODevice.OpenModeFlag.ReadOnly) self.setError(error, errorstring) QTimer.singleShot(0, lambda: self.error.emit(error)) # type: ignore[attr-defined] @@ -151,7 +151,7 @@ class RedirectNetworkReply(QNetworkReply): def __init__(self, new_url, parent=None): super().__init__(parent) - self.setAttribute(QNetworkRequest.RedirectionTargetAttribute, new_url) + self.setAttribute(QNetworkRequest.Attribute.RedirectionTargetAttribute, new_url) QTimer.singleShot(0, lambda: self.finished.emit()) # type: ignore[attr-defined] diff --git a/qutebrowser/browser/webkit/network/webkitqutescheme.py b/qutebrowser/browser/webkit/network/webkitqutescheme.py index 2e6462425..6ddb57feb 100644 --- a/qutebrowser/browser/webkit/network/webkitqutescheme.py +++ b/qutebrowser/browser/webkit/network/webkitqutescheme.py @@ -38,10 +38,10 @@ def handler(request, operation, current_url): Return: A QNetworkReply. """ - if operation != QNetworkAccessManager.GetOperation: + if operation != QNetworkAccessManager.Operation.GetOperation: return networkreply.ErrorNetworkReply( request, "Unsupported request type", - QNetworkReply.ContentOperationNotPermittedError) + QNetworkReply.NetworkError.ContentOperationNotPermittedError) url = request.url() @@ -53,22 +53,22 @@ def handler(request, operation, current_url): url.toDisplayString())) return networkreply.ErrorNetworkReply( request, "Invalid qute://settings request", - QNetworkReply.ContentAccessDenied) + QNetworkReply.NetworkError.ContentAccessDenied) try: mimetype, data = qutescheme.data_for_url(url) except qutescheme.Error as e: errors = { qutescheme.NotFoundError: - QNetworkReply.ContentNotFoundError, + QNetworkReply.NetworkError.ContentNotFoundError, qutescheme.UrlInvalidError: - QNetworkReply.ContentOperationNotPermittedError, + QNetworkReply.NetworkError.ContentOperationNotPermittedError, qutescheme.RequestDeniedError: - QNetworkReply.ContentAccessDenied, + QNetworkReply.NetworkError.ContentAccessDenied, qutescheme.SchemeOSError: - QNetworkReply.ContentNotFoundError, + QNetworkReply.NetworkError.ContentNotFoundError, qutescheme.Error: - QNetworkReply.InternalServerError, + QNetworkReply.NetworkError.InternalServerError, } exctype = type(e) log.misc.error("{} while handling qute://* URL".format( diff --git a/qutebrowser/browser/webkit/tabhistory.py b/qutebrowser/browser/webkit/tabhistory.py index 186ad8a7f..2d8dcf0a2 100644 --- a/qutebrowser/browser/webkit/tabhistory.py +++ b/qutebrowser/browser/webkit/tabhistory.py @@ -50,10 +50,10 @@ def _serialize_items(items, current_idx, stream): def _serialize_item(item): data = { - 'originalURLString': item.original_url.toString(QUrl.FullyEncoded), + 'originalURLString': item.original_url.toString(QUrl.ComponentFormattingOption.FullyEncoded), 'scrollPosition': {'x': 0, 'y': 0}, 'title': item.title, - 'urlString': item.url.toString(QUrl.FullyEncoded), + 'urlString': item.url.toString(QUrl.ComponentFormattingOption.FullyEncoded), } try: data['scrollPosition']['x'] = item.user_data['scroll-pos'].x() @@ -80,7 +80,7 @@ def serialize(items): segfault! """ data = QByteArray() - stream = QDataStream(data, QIODevice.ReadWrite) + stream = QDataStream(data, QIODevice.OpenModeFlag.ReadWrite) user_data: List[Mapping[str, Any]] = [] current_idx = None diff --git a/qutebrowser/browser/webkit/webkitelem.py b/qutebrowser/browser/webkit/webkitelem.py index f70ce0559..aac8209b8 100644 --- a/qutebrowser/browser/webkit/webkitelem.py +++ b/qutebrowser/browser/webkit/webkitelem.py @@ -276,7 +276,7 @@ class WebKitElement(webelem.AbstractWebElement): def _is_hidden_css(self) -> bool: """Check if the given element is hidden via CSS.""" attr_values = { - attr: self._elem.styleProperty(attr, QWebElement.ComputedStyle) + attr: self._elem.styleProperty(attr, QWebElement.StyleResolveStrategy.ComputedStyle) for attr in ['visibility', 'display', 'opacity'] } invisible = attr_values['visibility'] == 'hidden' @@ -362,7 +362,7 @@ class WebKitElement(webelem.AbstractWebElement): def _click_js(self, click_target: usertypes.ClickTarget) -> None: settings = QWebSettings.globalSettings() - attribute = QWebSettings.JavascriptCanOpenWindows + attribute = QWebSettings.WebAttribute.JavascriptCanOpenWindows could_open_windows = settings.testAttribute(attribute) settings.setAttribute(attribute, True) ok = self._elem.evaluateJavaScript('this.click(); true;') @@ -372,7 +372,7 @@ class WebKitElement(webelem.AbstractWebElement): self._click_fake_event(click_target) def _click_fake_event(self, click_target: usertypes.ClickTarget, - button: Qt.MouseButton = Qt.LeftButton) -> None: + button: Qt.MouseButton = Qt.MouseButton.LeftButton) -> None: self._tab.data.override_target = click_target super()._click_fake_event(click_target) diff --git a/qutebrowser/browser/webkit/webkitinspector.py b/qutebrowser/browser/webkit/webkitinspector.py index be26860cc..b00010d8b 100644 --- a/qutebrowser/browser/webkit/webkitinspector.py +++ b/qutebrowser/browser/webkit/webkitinspector.py @@ -40,5 +40,5 @@ class WebKitInspector(inspector.AbstractWebInspector): def inspect(self, page: QWebPage) -> None: # type: ignore[override] settings = QWebSettings.globalSettings() - settings.setAttribute(QWebSettings.DeveloperExtrasEnabled, True) + settings.setAttribute(QWebSettings.WebAttribute.DeveloperExtrasEnabled, True) self._widget.setPage(page) diff --git a/qutebrowser/browser/webkit/webkitsettings.py b/qutebrowser/browser/webkit/webkitsettings.py index cc67c8494..b8a70a46e 100644 --- a/qutebrowser/browser/webkit/webkitsettings.py +++ b/qutebrowser/browser/webkit/webkitsettings.py @@ -50,81 +50,81 @@ class WebKitSettings(websettings.AbstractSettings): _ATTRIBUTES = { 'content.images': - Attr(QWebSettings.AutoLoadImages), + Attr(QWebSettings.WebAttribute.AutoLoadImages), 'content.javascript.enabled': - Attr(QWebSettings.JavascriptEnabled), + Attr(QWebSettings.WebAttribute.JavascriptEnabled), 'content.javascript.can_open_tabs_automatically': - Attr(QWebSettings.JavascriptCanOpenWindows), + Attr(QWebSettings.WebAttribute.JavascriptCanOpenWindows), 'content.javascript.can_close_tabs': - Attr(QWebSettings.JavascriptCanCloseWindows), + Attr(QWebSettings.WebAttribute.JavascriptCanCloseWindows), 'content.javascript.can_access_clipboard': - Attr(QWebSettings.JavascriptCanAccessClipboard), + Attr(QWebSettings.WebAttribute.JavascriptCanAccessClipboard), 'content.plugins': - Attr(QWebSettings.PluginsEnabled), + Attr(QWebSettings.WebAttribute.PluginsEnabled), 'content.webgl': - Attr(QWebSettings.WebGLEnabled), + Attr(QWebSettings.WebAttribute.WebGLEnabled), 'content.hyperlink_auditing': - Attr(QWebSettings.HyperlinkAuditingEnabled), + Attr(QWebSettings.WebAttribute.HyperlinkAuditingEnabled), 'content.local_content_can_access_remote_urls': - Attr(QWebSettings.LocalContentCanAccessRemoteUrls), + Attr(QWebSettings.WebAttribute.LocalContentCanAccessRemoteUrls), 'content.local_content_can_access_file_urls': - Attr(QWebSettings.LocalContentCanAccessFileUrls), + Attr(QWebSettings.WebAttribute.LocalContentCanAccessFileUrls), 'content.dns_prefetch': - Attr(QWebSettings.DnsPrefetchEnabled), + Attr(QWebSettings.WebAttribute.DnsPrefetchEnabled), 'content.frame_flattening': - Attr(QWebSettings.FrameFlatteningEnabled), + Attr(QWebSettings.WebAttribute.FrameFlatteningEnabled), 'content.cache.appcache': - Attr(QWebSettings.OfflineWebApplicationCacheEnabled), + Attr(QWebSettings.WebAttribute.OfflineWebApplicationCacheEnabled), 'content.local_storage': - Attr(QWebSettings.LocalStorageEnabled, - QWebSettings.OfflineStorageDatabaseEnabled), + Attr(QWebSettings.WebAttribute.LocalStorageEnabled, + QWebSettings.WebAttribute.OfflineStorageDatabaseEnabled), 'content.print_element_backgrounds': - Attr(QWebSettings.PrintElementBackgrounds), + Attr(QWebSettings.WebAttribute.PrintElementBackgrounds), 'content.xss_auditing': - Attr(QWebSettings.XSSAuditingEnabled), + Attr(QWebSettings.WebAttribute.XSSAuditingEnabled), 'content.site_specific_quirks.enabled': - Attr(QWebSettings.SiteSpecificQuirksEnabled), + Attr(QWebSettings.WebAttribute.SiteSpecificQuirksEnabled), 'input.spatial_navigation': - Attr(QWebSettings.SpatialNavigationEnabled), + Attr(QWebSettings.WebAttribute.SpatialNavigationEnabled), 'input.links_included_in_focus_chain': - Attr(QWebSettings.LinksIncludedInFocusChain), + Attr(QWebSettings.WebAttribute.LinksIncludedInFocusChain), 'zoom.text_only': - Attr(QWebSettings.ZoomTextOnly), + Attr(QWebSettings.WebAttribute.ZoomTextOnly), 'scrolling.smooth': - Attr(QWebSettings.ScrollAnimatorEnabled), + Attr(QWebSettings.WebAttribute.ScrollAnimatorEnabled), } _FONT_SIZES = { 'fonts.web.size.minimum': - QWebSettings.MinimumFontSize, + QWebSettings.FontSize.MinimumFontSize, 'fonts.web.size.minimum_logical': - QWebSettings.MinimumLogicalFontSize, + QWebSettings.FontSize.MinimumLogicalFontSize, 'fonts.web.size.default': - QWebSettings.DefaultFontSize, + QWebSettings.FontSize.DefaultFontSize, 'fonts.web.size.default_fixed': - QWebSettings.DefaultFixedFontSize, + QWebSettings.FontSize.DefaultFixedFontSize, } _FONT_FAMILIES = { - 'fonts.web.family.standard': QWebSettings.StandardFont, - 'fonts.web.family.fixed': QWebSettings.FixedFont, - 'fonts.web.family.serif': QWebSettings.SerifFont, - 'fonts.web.family.sans_serif': QWebSettings.SansSerifFont, - 'fonts.web.family.cursive': QWebSettings.CursiveFont, - 'fonts.web.family.fantasy': QWebSettings.FantasyFont, + 'fonts.web.family.standard': QWebSettings.FontFamily.StandardFont, + 'fonts.web.family.fixed': QWebSettings.FontFamily.FixedFont, + 'fonts.web.family.serif': QWebSettings.FontFamily.SerifFont, + 'fonts.web.family.sans_serif': QWebSettings.FontFamily.SansSerifFont, + 'fonts.web.family.cursive': QWebSettings.FontFamily.CursiveFont, + 'fonts.web.family.fantasy': QWebSettings.FontFamily.FantasyFont, } # Mapping from QWebSettings::QWebSettings() in # qtwebkit/Source/WebKit/qt/Api/qwebsettings.cpp _FONT_TO_QFONT = { - QWebSettings.StandardFont: QFont.Serif, - QWebSettings.FixedFont: QFont.Monospace, - QWebSettings.SerifFont: QFont.Serif, - QWebSettings.SansSerifFont: QFont.SansSerif, - QWebSettings.CursiveFont: QFont.Cursive, - QWebSettings.FantasyFont: QFont.Fantasy, + QWebSettings.FontFamily.StandardFont: QFont.StyleHint.Serif, + QWebSettings.FontFamily.FixedFont: QFont.StyleHint.Monospace, + QWebSettings.FontFamily.SerifFont: QFont.StyleHint.Serif, + QWebSettings.FontFamily.SansSerifFont: QFont.StyleHint.SansSerif, + QWebSettings.FontFamily.CursiveFont: QFont.StyleHint.Cursive, + QWebSettings.FontFamily.FantasyFont: QFont.StyleHint.Fantasy, } @@ -138,10 +138,10 @@ def _set_user_stylesheet(settings): def _set_cookie_accept_policy(settings): """Update the content.cookies.accept setting.""" mapping = { - 'all': QWebSettings.AlwaysAllowThirdPartyCookies, - 'no-3rdparty': QWebSettings.AlwaysBlockThirdPartyCookies, - 'never': QWebSettings.AlwaysBlockThirdPartyCookies, - 'no-unknown-3rdparty': QWebSettings.AllowThirdPartyWithExistingCookies, + 'all': QWebSettings.ThirdPartyCookiePolicy.AlwaysAllowThirdPartyCookies, + 'no-3rdparty': QWebSettings.ThirdPartyCookiePolicy.AlwaysBlockThirdPartyCookies, + 'never': QWebSettings.ThirdPartyCookiePolicy.AlwaysBlockThirdPartyCookies, + 'no-unknown-3rdparty': QWebSettings.ThirdPartyCookiePolicy.AllowThirdPartyWithExistingCookies, } value = config.val.content.cookies.accept settings.setThirdPartyCookiePolicy(mapping[value]) diff --git a/qutebrowser/browser/webkit/webkittab.py b/qutebrowser/browser/webkit/webkittab.py index 6c2710fb4..f7ba641fa 100644 --- a/qutebrowser/browser/webkit/webkittab.py +++ b/qutebrowser/browser/webkit/webkittab.py @@ -64,9 +64,9 @@ class WebKitAction(browsertab.AbstractAction): """ new_actions = { # https://github.com/qtwebkit/qtwebkit/commit/a96d9ef5d24b02d996ad14ff050d0e485c9ddc97 - 'RequestClose': QWebPage.ToggleVideoFullscreen + 1, + 'RequestClose': QWebPage.WebAction.ToggleVideoFullscreen + 1, # https://github.com/qtwebkit/qtwebkit/commit/96b9ba6269a5be44343635a7aaca4a153ea0366b - 'Unselect': QWebPage.ToggleVideoFullscreen + 2, + 'Unselect': QWebPage.WebAction.ToggleVideoFullscreen + 2, } if name in new_actions: self._widget.triggerPageAction(new_actions[name]) @@ -124,7 +124,7 @@ class WebKitSearch(browsertab.AbstractSearch): # Removing FindWrapsAroundDocument to get the same logging as with # QtWebEngine debug_flags = debug.qflags_key( - QWebPage, flags & ~QWebPage.FindWrapsAroundDocument, + QWebPage, flags & ~QWebPage.FindFlag.FindWrapsAroundDocument, klass=QWebPage.FindFlag) if debug_flags != '0x0000': flag_text = 'with flags {}'.format(debug_flags) @@ -143,7 +143,7 @@ class WebKitSearch(browsertab.AbstractSearch): self.search_displayed = False # We first clear the marked text, then the highlights self._widget.findText('') - self._widget.findText('', QWebPage.HighlightAllOccurrences) + self._widget.findText('', QWebPage.FindFlag.HighlightAllOccurrences) def search(self, text, *, ignore_case=usertypes.IgnoreCase.never, reverse=False, wrap=True, result_cb=None): @@ -160,16 +160,16 @@ class WebKitSearch(browsertab.AbstractSearch): self.search_displayed = True self._flags = self._empty_flags() if self._is_case_sensitive(ignore_case): - self._flags |= QWebPage.FindCaseSensitively + self._flags |= QWebPage.FindFlag.FindCaseSensitively if reverse: - self._flags |= QWebPage.FindBackward + self._flags |= QWebPage.FindFlag.FindBackward if wrap: - self._flags |= QWebPage.FindWrapsAroundDocument + self._flags |= QWebPage.FindFlag.FindWrapsAroundDocument # We actually search *twice* - once to highlight everything, then again # to get a mark so we can navigate. found = self._widget.findText(text, self._flags) self._widget.findText(text, - self._flags | QWebPage.HighlightAllOccurrences) + self._flags | QWebPage.FindFlag.HighlightAllOccurrences) self._call_cb(result_cb, found, text, self._flags, 'search') def next_result(self, *, result_cb=None): @@ -182,10 +182,10 @@ class WebKitSearch(browsertab.AbstractSearch): # The int() here makes sure we get a copy of the flags. flags = QWebPage.FindFlags( int(self._flags)) # type: ignore[call-overload] - if flags & QWebPage.FindBackward: - flags &= ~QWebPage.FindBackward + if flags & QWebPage.FindFlag.FindBackward: + flags &= ~QWebPage.FindFlag.FindBackward else: - flags |= QWebPage.FindBackward + flags |= QWebPage.FindFlag.FindBackward found = self._widget.findText(self.text, flags) self._call_cb(result_cb, found, self.text, flags, 'prev_result') @@ -212,13 +212,13 @@ class WebKitCaret(browsertab.AbstractCaret): self._selection_state = browsertab.SelectionState.none self.selection_toggled.emit(self._selection_state) settings = self._widget.settings() - settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True) + settings.setAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled, True) if self._widget.isVisible(): # Sometimes the caret isn't immediately visible, but unfocusing # and refocusing it fixes that. self._widget.clearFocus() - self._widget.setFocus(Qt.OtherFocusReason) + self._widget.setFocus(Qt.FocusReason.OtherFocusReason) # Move the caret to the first element in the viewport if there # isn't any text which is already selected. @@ -232,19 +232,19 @@ class WebKitCaret(browsertab.AbstractCaret): @pyqtSlot(usertypes.KeyMode) def _on_mode_left(self, _mode): settings = self._widget.settings() - if settings.testAttribute(QWebSettings.CaretBrowsingEnabled): + if settings.testAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled): if (self._selection_state is not browsertab.SelectionState.none and self._widget.hasSelection()): # Remove selection if it exists - self._widget.triggerPageAction(QWebPage.MoveToNextChar) - settings.setAttribute(QWebSettings.CaretBrowsingEnabled, False) + self._widget.triggerPageAction(QWebPage.WebAction.MoveToNextChar) + settings.setAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled, False) self._selection_state = browsertab.SelectionState.none def move_to_next_line(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = QWebPage.SelectNextLine + act = QWebPage.WebAction.SelectNextLine else: - act = QWebPage.MoveToNextLine + act = QWebPage.WebAction.MoveToNextLine for _ in range(count): self._widget.triggerPageAction(act) if self._selection_state is browsertab.SelectionState.line: @@ -252,9 +252,9 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_prev_line(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = QWebPage.SelectPreviousLine + act = QWebPage.WebAction.SelectPreviousLine else: - act = QWebPage.MoveToPreviousLine + act = QWebPage.WebAction.MoveToPreviousLine for _ in range(count): self._widget.triggerPageAction(act) if self._selection_state is browsertab.SelectionState.line: @@ -262,89 +262,89 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_next_char(self, count=1): if self._selection_state is browsertab.SelectionState.normal: - act = QWebPage.SelectNextChar + act = QWebPage.WebAction.SelectNextChar elif self._selection_state is browsertab.SelectionState.line: return else: - act = QWebPage.MoveToNextChar + act = QWebPage.WebAction.MoveToNextChar for _ in range(count): self._widget.triggerPageAction(act) def move_to_prev_char(self, count=1): if self._selection_state is browsertab.SelectionState.normal: - act = QWebPage.SelectPreviousChar + act = QWebPage.WebAction.SelectPreviousChar elif self._selection_state is browsertab.SelectionState.line: return else: - act = QWebPage.MoveToPreviousChar + act = QWebPage.WebAction.MoveToPreviousChar for _ in range(count): self._widget.triggerPageAction(act) def move_to_end_of_word(self, count=1): if self._selection_state is browsertab.SelectionState.normal: - act = [QWebPage.SelectNextWord] + act = [QWebPage.WebAction.SelectNextWord] if utils.is_windows: # pragma: no cover - act.append(QWebPage.SelectPreviousChar) + act.append(QWebPage.WebAction.SelectPreviousChar) elif self._selection_state is browsertab.SelectionState.line: return else: - act = [QWebPage.MoveToNextWord] + act = [QWebPage.WebAction.MoveToNextWord] if utils.is_windows: # pragma: no cover - act.append(QWebPage.MoveToPreviousChar) + act.append(QWebPage.WebAction.MoveToPreviousChar) for _ in range(count): for a in act: self._widget.triggerPageAction(a) def move_to_next_word(self, count=1): if self._selection_state is browsertab.SelectionState.normal: - act = [QWebPage.SelectNextWord] + act = [QWebPage.WebAction.SelectNextWord] if not utils.is_windows: # pragma: no branch - act.append(QWebPage.SelectNextChar) + act.append(QWebPage.WebAction.SelectNextChar) elif self._selection_state is browsertab.SelectionState.line: return else: - act = [QWebPage.MoveToNextWord] + act = [QWebPage.WebAction.MoveToNextWord] if not utils.is_windows: # pragma: no branch - act.append(QWebPage.MoveToNextChar) + act.append(QWebPage.WebAction.MoveToNextChar) for _ in range(count): for a in act: self._widget.triggerPageAction(a) def move_to_prev_word(self, count=1): if self._selection_state is browsertab.SelectionState.normal: - act = QWebPage.SelectPreviousWord + act = QWebPage.WebAction.SelectPreviousWord elif self._selection_state is browsertab.SelectionState.line: return else: - act = QWebPage.MoveToPreviousWord + act = QWebPage.WebAction.MoveToPreviousWord for _ in range(count): self._widget.triggerPageAction(act) def move_to_start_of_line(self): if self._selection_state is browsertab.SelectionState.normal: - act = QWebPage.SelectStartOfLine + act = QWebPage.WebAction.SelectStartOfLine elif self._selection_state is browsertab.SelectionState.line: return else: - act = QWebPage.MoveToStartOfLine + act = QWebPage.WebAction.MoveToStartOfLine self._widget.triggerPageAction(act) def move_to_end_of_line(self): if self._selection_state is browsertab.SelectionState.normal: - act = QWebPage.SelectEndOfLine + act = QWebPage.WebAction.SelectEndOfLine elif self._selection_state is browsertab.SelectionState.line: return else: - act = QWebPage.MoveToEndOfLine + act = QWebPage.WebAction.MoveToEndOfLine self._widget.triggerPageAction(act) def move_to_start_of_next_block(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = [QWebPage.SelectNextLine, - QWebPage.SelectStartOfBlock] + act = [QWebPage.WebAction.SelectNextLine, + QWebPage.WebAction.SelectStartOfBlock] else: - act = [QWebPage.MoveToNextLine, - QWebPage.MoveToStartOfBlock] + act = [QWebPage.WebAction.MoveToNextLine, + QWebPage.WebAction.MoveToStartOfBlock] for _ in range(count): for a in act: self._widget.triggerPageAction(a) @@ -353,11 +353,11 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_start_of_prev_block(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = [QWebPage.SelectPreviousLine, - QWebPage.SelectStartOfBlock] + act = [QWebPage.WebAction.SelectPreviousLine, + QWebPage.WebAction.SelectStartOfBlock] else: - act = [QWebPage.MoveToPreviousLine, - QWebPage.MoveToStartOfBlock] + act = [QWebPage.WebAction.MoveToPreviousLine, + QWebPage.WebAction.MoveToStartOfBlock] for _ in range(count): for a in act: self._widget.triggerPageAction(a) @@ -366,11 +366,11 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_end_of_next_block(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = [QWebPage.SelectNextLine, - QWebPage.SelectEndOfBlock] + act = [QWebPage.WebAction.SelectNextLine, + QWebPage.WebAction.SelectEndOfBlock] else: - act = [QWebPage.MoveToNextLine, - QWebPage.MoveToEndOfBlock] + act = [QWebPage.WebAction.MoveToNextLine, + QWebPage.WebAction.MoveToEndOfBlock] for _ in range(count): for a in act: self._widget.triggerPageAction(a) @@ -379,9 +379,9 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_end_of_prev_block(self, count=1): if self._selection_state is not browsertab.SelectionState.none: - act = [QWebPage.SelectPreviousLine, QWebPage.SelectEndOfBlock] + act = [QWebPage.WebAction.SelectPreviousLine, QWebPage.WebAction.SelectEndOfBlock] else: - act = [QWebPage.MoveToPreviousLine, QWebPage.MoveToEndOfBlock] + act = [QWebPage.WebAction.MoveToPreviousLine, QWebPage.WebAction.MoveToEndOfBlock] for _ in range(count): for a in act: self._widget.triggerPageAction(a) @@ -390,18 +390,18 @@ class WebKitCaret(browsertab.AbstractCaret): def move_to_start_of_document(self): if self._selection_state is not browsertab.SelectionState.none: - act = QWebPage.SelectStartOfDocument + act = QWebPage.WebAction.SelectStartOfDocument else: - act = QWebPage.MoveToStartOfDocument + act = QWebPage.WebAction.MoveToStartOfDocument self._widget.triggerPageAction(act) if self._selection_state is browsertab.SelectionState.line: self._select_line() def move_to_end_of_document(self): if self._selection_state is not browsertab.SelectionState.none: - act = QWebPage.SelectEndOfDocument + act = QWebPage.WebAction.SelectEndOfDocument else: - act = QWebPage.MoveToEndOfDocument + act = QWebPage.WebAction.MoveToEndOfDocument self._widget.triggerPageAction(act) def toggle_selection(self, line=False): @@ -418,7 +418,7 @@ class WebKitCaret(browsertab.AbstractCaret): self.selection_toggled.emit(self._selection_state) def drop_selection(self): - self._widget.triggerPageAction(QWebPage.MoveToNextChar) + self._widget.triggerPageAction(QWebPage.WebAction.MoveToNextChar) def selection(self, callback): callback(self._widget.selectedText()) @@ -433,9 +433,9 @@ class WebKitCaret(browsertab.AbstractCaret): }""") def _select_line(self): - self._widget.triggerPageAction(QWebPage.SelectStartOfLine) + self._widget.triggerPageAction(QWebPage.WebAction.SelectStartOfLine) self.reverse_selection() - self._widget.triggerPageAction(QWebPage.SelectEndOfLine) + self._widget.triggerPageAction(QWebPage.WebAction.SelectEndOfLine) self.reverse_selection() def _select_line_to_end(self): @@ -443,11 +443,11 @@ class WebKitCaret(browsertab.AbstractCaret): # of focus) has to be checked before moving selection # to the end of line if self._js_selection_left_to_right(): - self._widget.triggerPageAction(QWebPage.SelectEndOfLine) + self._widget.triggerPageAction(QWebPage.WebAction.SelectEndOfLine) def _select_line_to_start(self): if not self._js_selection_left_to_right(): - self._widget.triggerPageAction(QWebPage.SelectStartOfLine) + self._widget.triggerPageAction(QWebPage.WebAction.SelectStartOfLine) def _js_selection_left_to_right(self): """Return True iff the selection's direction is left to right.""" @@ -460,7 +460,7 @@ class WebKitCaret(browsertab.AbstractCaret): def _follow_selected(self, *, tab=False): if QWebSettings.globalSettings().testAttribute( - QWebSettings.JavascriptEnabled): + QWebSettings.WebAttribute.JavascriptEnabled): if tab: self._tab.data.override_target = usertypes.ClickTarget.tab self._tab.run_js_async(""" @@ -558,7 +558,7 @@ class WebKitScroller(browsertab.AbstractScroller): elif x is None and y == 100: self.bottom() else: - for val, orientation in [(x, Qt.Horizontal), (y, Qt.Vertical)]: + for val, orientation in [(x, Qt.Orientation.Horizontal), (y, Qt.Orientation.Vertical)]: if val is not None: frame = self._widget.page().mainFrame() maximum = frame.scrollBarMaximum(orientation) @@ -583,36 +583,36 @@ class WebKitScroller(browsertab.AbstractScroller): self._tab.fake_key_press(key) def up(self, count=1): - self._key_press(Qt.Key_Up, count, 'scrollBarMinimum', Qt.Vertical) + self._key_press(Qt.Key.Key_Up, count, 'scrollBarMinimum', Qt.Orientation.Vertical) def down(self, count=1): - self._key_press(Qt.Key_Down, count, 'scrollBarMaximum', Qt.Vertical) + self._key_press(Qt.Key.Key_Down, count, 'scrollBarMaximum', Qt.Orientation.Vertical) def left(self, count=1): - self._key_press(Qt.Key_Left, count, 'scrollBarMinimum', Qt.Horizontal) + self._key_press(Qt.Key.Key_Left, count, 'scrollBarMinimum', Qt.Orientation.Horizontal) def right(self, count=1): - self._key_press(Qt.Key_Right, count, 'scrollBarMaximum', Qt.Horizontal) + self._key_press(Qt.Key.Key_Right, count, 'scrollBarMaximum', Qt.Orientation.Horizontal) def top(self): - self._key_press(Qt.Key_Home) + self._key_press(Qt.Key.Key_Home) def bottom(self): - self._key_press(Qt.Key_End) + self._key_press(Qt.Key.Key_End) def page_up(self, count=1): - self._key_press(Qt.Key_PageUp, count, 'scrollBarMinimum', Qt.Vertical) + self._key_press(Qt.Key.Key_PageUp, count, 'scrollBarMinimum', Qt.Orientation.Vertical) def page_down(self, count=1): - self._key_press(Qt.Key_PageDown, count, 'scrollBarMaximum', - Qt.Vertical) + self._key_press(Qt.Key.Key_PageDown, count, 'scrollBarMaximum', + Qt.Orientation.Vertical) def at_top(self): return self.pos_px().y() == 0 def at_bottom(self): frame = self._widget.page().currentFrame() - return self.pos_px().y() >= frame.scrollBarMaximum(Qt.Vertical) + return self.pos_px().y() >= frame.scrollBarMaximum(Qt.Orientation.Vertical) class WebKitHistoryPrivate(browsertab.AbstractHistoryPrivate): @@ -848,7 +848,7 @@ class WebKitTab(browsertab.AbstractTab): def _make_private(self, widget): settings = widget.settings() - settings.setAttribute(QWebSettings.PrivateBrowsingEnabled, True) + settings.setAttribute(QWebSettings.WebAttribute.PrivateBrowsingEnabled, True) def load_url(self, url): self._load_url_prepare(url) @@ -880,9 +880,9 @@ class WebKitTab(browsertab.AbstractTab): def reload(self, *, force=False): if force: - action = QWebPage.ReloadAndBypassCache + action = QWebPage.WebAction.ReloadAndBypassCache else: - action = QWebPage.Reload + action = QWebPage.WebAction.Reload self._widget.triggerPageAction(action) def stop(self): diff --git a/qutebrowser/browser/webkit/webpage.py b/qutebrowser/browser/webkit/webpage.py index 747b2d382..12b9b837d 100644 --- a/qutebrowser/browser/webkit/webpage.py +++ b/qutebrowser/browser/webkit/webpage.py @@ -68,8 +68,8 @@ class BrowserPage(QWebPage): self._tabdata = tabdata self._is_shutting_down = False self._extension_handlers = { - QWebPage.ErrorPageExtension: self._handle_errorpage, - QWebPage.ChooseMultipleFilesExtension: self._handle_multiple_files, + QWebPage.Extension.ErrorPageExtension: self._handle_errorpage, + QWebPage.Extension.ChooseMultipleFilesExtension: self._handle_multiple_files, } self._ignore_load_started = False self.error_occurred = False @@ -135,16 +135,16 @@ class BrowserPage(QWebPage): False if no error page should be displayed, True otherwise. """ ignored_errors = [ - (QWebPage.QtNetwork, QNetworkReply.OperationCanceledError), + (QWebPage.ErrorDomain.QtNetwork, QNetworkReply.NetworkError.OperationCanceledError), # "Loading is handled by the media engine" - (QWebPage.WebKit, 203), + (QWebPage.ErrorDomain.WebKit, 203), # "Frame load interrupted by policy change" - (QWebPage.WebKit, 102), + (QWebPage.ErrorDomain.WebKit, 102), ] errpage.baseUrl = info.url urlstr = info.url.toDisplayString() - if (info.domain, info.error) == (QWebPage.QtNetwork, - QNetworkReply.ProtocolUnknownError): + if (info.domain, info.error) == (QWebPage.ErrorDomain.QtNetwork, + QNetworkReply.NetworkError.ProtocolUnknownError): # For some reason, we get a segfault when we use # QDesktopServices::openUrl with info.url directly - however it # works when we construct a copy of it. @@ -155,7 +155,7 @@ class BrowserPage(QWebPage): text="URL: <b>{}</b>".format( html.escape(url.toDisplayString())), yes_action=functools.partial(QDesktopServices.openUrl, url), - url=info.url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)) + url=info.url.toString(QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded)) return True elif (info.domain, info.error) in ignored_errors: log.webview.debug("Ignored error on {}: {} (error domain: {}, " @@ -251,7 +251,7 @@ class BrowserPage(QWebPage): def on_print_requested(self, frame): """Handle printing when requested via javascript.""" printdiag = QPrintDialog() - printdiag.setAttribute(Qt.WA_DeleteOnClose) + printdiag.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) printdiag.open(lambda: frame.print(printdiag.printer())) def on_download_requested(self, request): @@ -357,25 +357,25 @@ class BrowserPage(QWebPage): return options = { - QWebPage.Notifications: 'content.notifications.enabled', - QWebPage.Geolocation: 'content.geolocation', + QWebPage.Feature.Notifications: 'content.notifications.enabled', + QWebPage.Feature.Geolocation: 'content.geolocation', } messages = { - QWebPage.Notifications: 'show notifications', - QWebPage.Geolocation: 'access your location', + QWebPage.Feature.Notifications: 'show notifications', + QWebPage.Feature.Geolocation: 'access your location', } yes_action = functools.partial( self.setFeaturePermission, frame, feature, - QWebPage.PermissionGrantedByUser) + QWebPage.PermissionPolicy.PermissionGrantedByUser) no_action = functools.partial( self.setFeaturePermission, frame, feature, - QWebPage.PermissionDeniedByUser) + QWebPage.PermissionPolicy.PermissionDeniedByUser) url = frame.url().adjusted(cast(QUrl.FormattingOptions, - QUrl.RemoveUserInfo | - QUrl.RemovePath | - QUrl.RemoveQuery | - QUrl.RemoveFragment)) + QUrl.UrlFormattingOption.RemoveUserInfo | + QUrl.UrlFormattingOption.RemovePath | + QUrl.UrlFormattingOption.RemoveQuery | + QUrl.UrlFormattingOption.RemoveFragment)) question = shared.feature_permission( url=url, option=options[feature], msg=messages[feature], @@ -508,17 +508,17 @@ class BrowserPage(QWebPage): and then conditionally opens the URL here or in another tab/window. """ type_map = { - QWebPage.NavigationTypeLinkClicked: + QWebPage.NavigationType.NavigationTypeLinkClicked: usertypes.NavigationRequest.Type.link_clicked, - QWebPage.NavigationTypeFormSubmitted: + QWebPage.NavigationType.NavigationTypeFormSubmitted: usertypes.NavigationRequest.Type.form_submitted, - QWebPage.NavigationTypeFormResubmitted: + QWebPage.NavigationType.NavigationTypeFormResubmitted: usertypes.NavigationRequest.Type.form_resubmitted, - QWebPage.NavigationTypeBackOrForward: + QWebPage.NavigationType.NavigationTypeBackOrForward: usertypes.NavigationRequest.Type.back_forward, - QWebPage.NavigationTypeReload: + QWebPage.NavigationType.NavigationTypeReload: usertypes.NavigationRequest.Type.reloaded, - QWebPage.NavigationTypeOther: + QWebPage.NavigationType.NavigationTypeOther: usertypes.NavigationRequest.Type.other, } is_main_frame = frame is self.mainFrame() diff --git a/qutebrowser/browser/webkit/webview.py b/qutebrowser/browser/webkit/webview.py index 2fbbafe0a..747032fa3 100644 --- a/qutebrowser/browser/webkit/webview.py +++ b/qutebrowser/browser/webkit/webview.py @@ -74,15 +74,15 @@ class WebView(QWebView): tabdata=tab.data, private=private, parent=self) page.setVisibilityState( - QWebPage.VisibilityStateVisible if self.isVisible() - else QWebPage.VisibilityStateHidden) + QWebPage.VisibilityState.VisibilityStateVisible if self.isVisible() + else QWebPage.VisibilityState.VisibilityStateHidden) self.setPage(page) stylesheet.set_register(self) def __repr__(self): - flags = QUrl.EncodeUnicode + flags = QUrl.ComponentFormattingOption.EncodeUnicode urlstr = self.url().toDisplayString(flags) # type: ignore[arg-type] url = utils.elide(urlstr, 100) return utils.get_repr(self, tab_id=self._tab_id, url=url) @@ -107,7 +107,7 @@ class WebView(QWebView): # quitting it seems. log.destroy.debug("Shutting down {!r}.".format(self)) settings = self.settings() - settings.setAttribute(QWebSettings.JavascriptEnabled, False) + settings.setAttribute(QWebSettings.WebAttribute.JavascriptEnabled, False) self.stop() self.page().shutdown() @@ -132,7 +132,7 @@ class WebView(QWebView): """ debug_type = debug.qenum_key(QWebPage, wintype) log.webview.debug("createWindow with type {}".format(debug_type)) - if wintype == QWebPage.WebModalDialog: + if wintype == QWebPage.WebWindowType.WebModalDialog: log.webview.warning("WebModalDialog requested, but we don't " "support that!") tabbed_browser = objreg.get('tabbed-browser', scope='window', @@ -157,12 +157,12 @@ class WebView(QWebView): The superclass event return value. """ frame = self.page().mainFrame() - new_pos = (frame.scrollBarValue(Qt.Horizontal), - frame.scrollBarValue(Qt.Vertical)) + new_pos = (frame.scrollBarValue(Qt.Orientation.Horizontal), + frame.scrollBarValue(Qt.Orientation.Vertical)) if self._old_scroll_pos != new_pos: self._old_scroll_pos = new_pos - m = (frame.scrollBarMaximum(Qt.Horizontal), - frame.scrollBarMaximum(Qt.Vertical)) + m = (frame.scrollBarMaximum(Qt.Orientation.Horizontal), + frame.scrollBarMaximum(Qt.Orientation.Vertical)) perc = (round(100 * new_pos[0] / m[0]) if m[0] != 0 else 0, round(100 * new_pos[1] / m[1]) if m[1] != 0 else 0) self.scroll_pos = perc @@ -191,7 +191,7 @@ class WebView(QWebView): The superclass event return value. """ super().showEvent(e) - self.page().setVisibilityState(QWebPage.VisibilityStateVisible) + self.page().setVisibilityState(QWebPage.VisibilityState.VisibilityStateVisible) def hideEvent(self, e): """Extend hideEvent to set the page visibility state to hidden. @@ -203,16 +203,16 @@ class WebView(QWebView): The superclass event return value. """ super().hideEvent(e) - self.page().setVisibilityState(QWebPage.VisibilityStateHidden) + self.page().setVisibilityState(QWebPage.VisibilityState.VisibilityStateHidden) def mousePressEvent(self, e): """Set the tabdata ClickTarget on a mousepress. This is implemented here as we don't need it for QtWebEngine. """ - if e.button() == Qt.MidButton or e.modifiers() & Qt.ControlModifier: + if e.button() == Qt.MouseButton.MidButton or e.modifiers() & Qt.KeyboardModifier.ControlModifier: background = config.val.tabs.background - if e.modifiers() & Qt.ShiftModifier: + if e.modifiers() & Qt.KeyboardModifier.ShiftModifier: background = not background if background: target = usertypes.ClickTarget.tab_bg |