diff options
author | Florian Bruhin <me@the-compiler.org> | 2022-04-10 19:01:01 +0200 |
---|---|---|
committer | Florian Bruhin <me@the-compiler.org> | 2022-08-23 18:31:38 +0200 |
commit | 0877fb0d78635692e481c8bde224fac5ad0dd430 (patch) | |
tree | 4ba23ec5a361bbefa09e8b145bf8125d2e3be2e7 | |
parent | a11f1d34d3784b170fbc3f5a0e04d5c96ab06b74 (diff) | |
download | qutebrowser-0877fb0d78635692e481c8bde224fac5ad0dd430.tar.gz qutebrowser-0877fb0d78635692e481c8bde224fac5ad0dd430.zip |
Run scripts/dev/rewrite_enums.py
133 files changed, 1417 insertions, 1413 deletions
diff --git a/qutebrowser/app.py b/qutebrowser/app.py index 4762253cc..b8e8b3bca 100644 --- a/qutebrowser/app.py +++ b/qutebrowser/app.py @@ -563,7 +563,7 @@ class Application(QApplication): self.launch_time = datetime.datetime.now() self.focusObjectChanged.connect(self.on_focus_object_changed) - self.setAttribute(Qt.AA_UseHighDpiPixmaps, True) + self.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps, True) self.new_window.connect(self._on_new_window) @@ -582,7 +582,7 @@ class Application(QApplication): def event(self, e): """Handle macOS FileOpen events.""" - if e.type() != QEvent.FileOpen: + if e.type() != QEvent.Type.FileOpen: return super().event(e) url = e.url() diff --git a/qutebrowser/browser/browsertab.py b/qutebrowser/browser/browsertab.py index b2d6316cc..724425107 100644 --- a/qutebrowser/browser/browsertab.py +++ b/qutebrowser/browser/browsertab.py @@ -281,7 +281,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) @@ -603,9 +603,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 @@ -1238,10 +1238,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) @@ -1316,7 +1316,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 d408949e7..5b431f8e7 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'!") @@ -706,9 +706,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() @@ -1199,7 +1199,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( @@ -1330,8 +1330,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: @@ -1774,8 +1774,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() @@ -1882,9 +1882,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 5ddc3cf8e..381cace9a 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 16e810421..da0763b76 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 88e3002e3..6c27cb9f6 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 052b79713..62c304bd8 100644 --- a/qutebrowser/browser/greasemonkey.py +++ b/qutebrowser/browser/greasemonkey.py @@ -270,7 +270,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 707e112ec..91534a58b 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 # type: ignore[operator] + flags |= QUrl.UrlFormattingOption.RemoveScheme urlstr = url.toString(flags) 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', @@ -356,7 +356,8 @@ class HintActions: url: The URL to open as a QUrl. context: The HintContext to use. """ - urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword) + urlstr = url.toString( + QUrl.ComponentFormattingOption.FullyEncoded | QUrl.UrlFormattingOption.RemovePassword) 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 0fd612376..312edfc13 100644 --- a/qutebrowser/browser/history.py +++ b/qutebrowser/browser/history.py @@ -435,10 +435,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 2f11899c2..dcf718552 100644 --- a/qutebrowser/browser/inspector.py +++ b/qutebrowser/browser/inspector.py @@ -74,7 +74,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 223691d05..d2783e349 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)), ] @@ -130,14 +130,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 @@ -146,7 +146,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 ef401aebf..be25a2a41 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 @@ -275,7 +275,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()) @@ -334,4 +334,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 ae217885c..4022337c4 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 843786261..4b86b4c27 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 8b77e588c..46d51d930 100644 --- a/qutebrowser/browser/qtnetworkdownloads.py +++ b/qutebrowser/browser/qtnetworkdownloads.py @@ -162,7 +162,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): @@ -286,7 +286,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 @@ -334,7 +334,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: @@ -372,7 +372,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) @@ -448,10 +448,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) @@ -511,8 +511,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 b7f2cef6f..aecb9a11a 100644 --- a/qutebrowser/browser/qutescheme.py +++ b/qutebrowser/browser/qutescheme.py @@ -128,7 +128,9 @@ def data_for_url(url: QUrl) -> Tuple[str, bytes]: Return: A (mimetype, data) tuple. """ - norm_url = url.adjusted(QUrl.NormalizePathSegments | QUrl.StripTrailingSlash) + norm_url = url.adjusted( + QUrl.UrlFormattingOption.NormalizePathSegments | + QUrl.UrlFormattingOption.StripTrailingSlash) if norm_url != url: raise Redirect(norm_url) @@ -423,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 99b5785b7..0f9e0bd8d 100644 --- a/qutebrowser/browser/shared.py +++ b/qutebrowser/browser/shared.py @@ -72,7 +72,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) @@ -95,7 +95,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) @@ -112,7 +112,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, @@ -135,7 +135,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) @@ -234,7 +234,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(""" @@ -265,7 +265,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) @@ -307,7 +307,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 37d900a79..0d30f7973 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -151,7 +151,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), @@ -198,7 +198,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) @@ -270,7 +270,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 ca004106d..805e88542 100644 --- a/qutebrowser/browser/webelem.py +++ b/qutebrowser/browser/webelem.py @@ -338,31 +338,30 @@ 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() log.webelem.debug("Sending fake click to {!r} at position {} with " "target {}".format(self, pos, click_target)) - target_modifiers: Dict[usertypes.ClickTarget, Qt.KeyboardModifiers] = { - usertypes.ClickTarget.normal: cast(Qt.KeyboardModifiers, Qt.NoModifier), - usertypes.ClickTarget.window: Qt.AltModifier | Qt.ShiftModifier, - usertypes.ClickTarget.tab: cast(Qt.KeyboardModifiers, Qt.ControlModifier), - usertypes.ClickTarget.tab_bg: - cast(Qt.KeyboardModifiers, Qt.ControlModifier), + target_modifiers: Dict[usertypes.ClickTarget, Qt.KeyboardModifier] = { + 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 = 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 +445,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 9fb47f8b6..a145efdca 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 ed9db3657..fac8ff1c1 100644 --- a/qutebrowser/browser/webengine/notification.py +++ b/qutebrowser/browser/webengine/notification.py @@ -136,7 +136,7 @@ class DBusError(Error): } def __init__(self, msg: QDBusMessage) -> None: - assert msg.type() == QDBusMessage.ErrorMessage + assert msg.type() == QDBusMessage.MessageType.ErrorMessage self.error = msg.errorName() self.error_message = msg.errorMessage() self.is_fatal = self.error not in self._NON_FATAL_ERRORS @@ -415,7 +415,7 @@ class NotificationBridgePresenter(QObject): for win_id in objreg.window_registry: tabbedbrowser = objreg.get("tabbed-browser", window=win_id, scope="window") for idx, tab in enumerate(tabbedbrowser.widgets()): - if tab.url().matches(notification.origin(), QUrl.RemovePath): + if tab.url().matches(notification.origin(), QUrl.UrlFormattingOption.RemovePath): tabbedbrowser.widget.setCurrentIndex(idx) return log.misc.debug(f"No matching tab found for {notification.origin()}") @@ -510,7 +510,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() @@ -661,7 +661,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: pass elif code == 0: self.click_id.emit(pid) @@ -677,7 +677,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}') @@ -733,7 +733,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 @@ -777,7 +777,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): self._watcher = QDBusServiceWatcher( self.SERVICE, bus, - QDBusServiceWatcher.WatchForUnregistration, + QDBusServiceWatcher.WatchModeFlag.WatchForUnregistration, self, ) self._watcher.serviceUnregistered.connect(self._on_service_unregistered) @@ -896,8 +896,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( @@ -941,11 +941,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: raise DBusError(msg) signature = msg.signature() @@ -993,7 +993,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): actions = [] if self._capabilities.actions: actions = ['default', 'Activate'] # key, name - return QDBusArgument(actions, QMetaType.QStringList) + return QDBusArgument(actions, QMetaType.Type.QStringList) def _get_hints_arg(self, *, origin_url: QUrl, icon: QImage) -> Dict[str, Any]: """Get the hints argument for present().""" @@ -1033,7 +1033,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): ) -> Any: """Wrapper around DBus call to use keyword args.""" return self.interface.call( - QDBus.BlockWithGui, + QDBus.CallMode.BlockWithGui, "Notify", appname, replaces_id, @@ -1073,7 +1073,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): ) try: - self._verify_message(reply, "u", QDBusMessage.ReplyMessage) + self._verify_message(reply, "u", QDBusMessage.MessageType.ReplyMessage) except DBusError as e: if e.is_fatal: raise @@ -1093,10 +1093,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) @@ -1162,11 +1162,11 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): def _handle_close(self, msg: QDBusMessage) -> None: """Handle NotificationClosed from DBus.""" try: - self._verify_message(msg, "uu", QDBusMessage.SignalMessage) + self._verify_message(msg, "uu", QDBusMessage.MessageType.SignalMessage) except Error: if not self._quirks.wrong_closes_type: raise - self._verify_message(msg, "ui", QDBusMessage.SignalMessage) + self._verify_message(msg, "ui", QDBusMessage.MessageType.SignalMessage) notification_id, _close_reason = msg.arguments() self.close_id.emit(notification_id) @@ -1174,7 +1174,7 @@ class DBusNotificationAdapter(AbstractNotificationAdapter): @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) @@ -1183,7 +1183,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), ) @@ -1191,10 +1191,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) @@ -1221,7 +1221,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 c483522c2..6efc6a2aa 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 bdb6444f6..8720469e0 100644 --- a/qutebrowser/browser/webengine/webenginedownloads.py +++ b/qutebrowser/browser/webengine/webenginedownloads.py @@ -54,7 +54,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): @@ -62,11 +62,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. @@ -75,12 +75,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) @@ -91,19 +91,19 @@ class DownloadItem(downloads.AbstractDownloadItem): def _do_die(self): progress_signal = self._qt_item.downloadProgress progress_signal.disconnect() - 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))) @@ -131,7 +131,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( @@ -245,7 +245,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 70fe04cdc..dd28db5c3 100644 --- a/qutebrowser/browser/webengine/webengineelem.py +++ b/qutebrowser/browser/webengine/webengineelem.py @@ -242,7 +242,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) @@ -251,8 +251,8 @@ class WebEngineElement(webelem.AbstractWebElement): # This is also used in Qt's tests: # https://github.com/qt/qtwebengine/commit/5e572e88efa7ba7c2b9138ec19e606d3e345ac90 QApplication.processEvents( - 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 2690cde4c..66cd2b2d6 100644 --- a/qutebrowser/browser/webengine/webengineinspector.py +++ b/qutebrowser/browser/webengine/webengineinspector.py @@ -92,7 +92,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 2126d41c4..6fb809f6d 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 | - QWebEngineUrlScheme.LocalAccessAllowed) + QWebEngineUrlScheme.Flag.LocalScheme | + QWebEngineUrlScheme.Flag.LocalAccessAllowed) QWebEngineUrlScheme.registerScheme(scheme) diff --git a/qutebrowser/browser/webengine/webenginesettings.py b/qutebrowser/browser/webengine/webenginesettings.py index d2f0e40d8..10193ff1b 100644 --- a/qutebrowser/browser/webengine/webenginesettings.py +++ b/qutebrowser/browser/webengine/webenginesettings.py @@ -110,91 +110,91 @@ 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.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, } _JS_CLIPBOARD_SETTINGS = { @@ -286,12 +286,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 @@ -326,9 +326,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 c8c02e5eb..beacfe59a 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, } @@ -62,18 +62,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): @@ -505,7 +505,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) @@ -584,28 +584,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 @@ -885,24 +885,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): @@ -943,10 +943,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) @@ -956,7 +956,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)) @@ -970,8 +970,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) ): @@ -982,7 +982,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]) @@ -1009,7 +1009,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, @@ -1018,7 +1018,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, @@ -1031,8 +1031,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 @@ -1073,8 +1073,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() @@ -1183,13 +1183,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()) @@ -1198,7 +1198,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) @@ -1212,8 +1212,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( @@ -1379,7 +1379,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: @@ -1396,9 +1396,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): @@ -1455,7 +1455,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 = "" @@ -1472,7 +1472,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, @@ -1521,19 +1521,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, @@ -1631,7 +1631,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 84e472c21..397ae3493 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 @@ -106,21 +106,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 @@ -217,9 +217,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) @@ -229,21 +229,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 d888050c3..104abf2d3 100644 --- a/qutebrowser/browser/webkit/http.py +++ b/qutebrowser/browser/webkit/http.py @@ -191,7 +191,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 6f180c683..36918c36b 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 @@ -239,7 +239,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 @@ -406,14 +406,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()): @@ -433,7 +433,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 a0a250d0b..6f7abeaab 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 @@ -114,7 +114,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)) QTimer.singleShot(0, lambda: self.finished.emit()) @@ -143,7 +143,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()) def abort(self): diff --git a/qutebrowser/browser/webkit/network/webkitqutescheme.py b/qutebrowser/browser/webkit/network/webkitqutescheme.py index 356121196..0c4da1a84 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 5b087c361..183ffc7a9 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 ebaa234b3..62236dd7b 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 97dd44870..ceec6187c 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: 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 3b56d4e34..2a5c3f765 100644 --- a/qutebrowser/browser/webkit/webkitsettings.py +++ b/qutebrowser/browser/webkit/webkitsettings.py @@ -50,82 +50,82 @@ 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.clipboard': - Attr(QWebSettings.JavascriptCanAccessClipboard, + Attr(QWebSettings.WebAttribute.JavascriptCanAccessClipboard, converter=lambda val: val != "none"), '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, } @@ -139,10 +139,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 e1c58e984..334edeb56 100644 --- a/qutebrowser/browser/webkit/webkittab.py +++ b/qutebrowser/browser/webkit/webkittab.py @@ -67,9 +67,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]) # type: ignore[arg-type] @@ -118,9 +118,9 @@ class WebKitSearch(browsertab.AbstractSearch): def _args_to_flags(self, reverse, ignore_case): flags = self._empty_flags() if self._is_case_sensitive(ignore_case): - flags |= QWebPage.FindCaseSensitively + flags |= QWebPage.FindFlag.FindCaseSensitively if reverse: - flags |= QWebPage.FindBackward + flags |= QWebPage.FindFlag.FindBackward return flags def _call_cb(self, callback, found, text, flags, caller): @@ -139,7 +139,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) @@ -171,7 +171,7 @@ class WebKitSearch(browsertab.AbstractSearch): # We first clear the marked text, then the highlights self._widget.findText('') self._widget.findText( - '', QWebPage.HighlightAllOccurrences) # type: ignore[arg-type] + '', QWebPage.FindFlag.HighlightAllOccurrences) # type: ignore[arg-type] def search(self, text, *, ignore_case=usertypes.IgnoreCase.never, reverse=False, result_cb=None): @@ -192,7 +192,7 @@ class WebKitSearch(browsertab.AbstractSearch): # 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, *, wrap=False, callback=None): @@ -202,7 +202,7 @@ class WebKitSearch(browsertab.AbstractSearch): int(self._flags)) # type: ignore[call-overload] if wrap: - flags |= QWebPage.FindWrapsAroundDocument + flags |= QWebPage.FindFlag.FindWrapsAroundDocument found = self._widget.findText(self.text, flags) # type: ignore[arg-type] self._call_cb(callback, found, self.text, flags, 'next_result') @@ -213,13 +213,13 @@ class WebKitSearch(browsertab.AbstractSearch): 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 if wrap: - flags |= QWebPage.FindWrapsAroundDocument + flags |= QWebPage.FindFlag.FindWrapsAroundDocument found = self._widget.findText(self.text, flags) # type: ignore[arg-type] self._call_cb(callback, found, self.text, flags, 'prev_result') @@ -249,13 +249,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. @@ -269,19 +269,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: @@ -289,9 +289,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: @@ -299,89 +299,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) @@ -390,11 +390,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) @@ -403,11 +403,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) @@ -416,9 +416,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) @@ -427,18 +427,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): @@ -455,7 +455,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()) @@ -470,9 +470,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): @@ -480,11 +480,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.""" @@ -497,7 +497,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(""" @@ -599,7 +599,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) @@ -624,36 +624,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): @@ -899,7 +899,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) @@ -931,9 +931,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 072eca655..ce83ddcc6 100644 --- a/qutebrowser/browser/webkit/webpage.py +++ b/qutebrowser/browser/webkit/webpage.py @@ -67,8 +67,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 @@ -134,16 +134,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. @@ -154,7 +154,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,24 +357,24 @@ 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(QUrl.RemoveUserInfo | # type: ignore[operator] - QUrl.RemovePath | - QUrl.RemoveQuery | - QUrl.RemoveFragment) + url = frame.url().adjusted(QUrl.UrlFormattingOption.RemoveUserInfo | # type: ignore[operator] + QUrl.UrlFormattingOption.RemovePath | + QUrl.UrlFormattingOption.RemoveQuery | + QUrl.UrlFormattingOption.RemoveFragment) question = shared.feature_permission( url=url, option=options[feature], msg=messages[feature], @@ -507,17 +507,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 b547ef058..32028400e 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() page = self.page() assert isinstance(page, webpage.BrowserPage), page @@ -134,7 +134,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', @@ -156,12 +156,12 @@ class WebView(QWebView): e: The QPaintEvent. """ 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 @@ -187,7 +187,7 @@ class WebView(QWebView): e: The QShowEvent. """ 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. @@ -196,16 +196,16 @@ class WebView(QWebView): e: The QHideEvent. """ 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 diff --git a/qutebrowser/commands/runners.py b/qutebrowser/commands/runners.py index a55bc351e..7cf6ab6fa 100644 --- a/qutebrowser/commands/runners.py +++ b/qutebrowser/commands/runners.py @@ -55,9 +55,9 @@ def _init_variable_replacements() -> Mapping[str, _ReplacementFunction]: """Return a dict from variable replacements to fns processing them.""" replacements: Dict[str, _ReplacementFunction] = { 'url': lambda tb: _url(tb).toString( - QUrl.FullyEncoded | QUrl.RemovePassword), + QUrl.ComponentFormattingOption.FullyEncoded | QUrl.UrlFormattingOption.RemovePassword), 'url:pretty': lambda tb: _url(tb).toString( - QUrl.DecodeReserved | QUrl.RemovePassword), + QUrl.ComponentFormattingOption.DecodeReserved | QUrl.UrlFormattingOption.RemovePassword), 'url:domain': lambda tb: "{}://{}{}".format( _url(tb).scheme(), _url(tb).host(), ":" + str(_url(tb).port()) if _url(tb).port() != -1 else ""), diff --git a/qutebrowser/commands/userscripts.py b/qutebrowser/commands/userscripts.py index 6b353ca3a..17164a23a 100644 --- a/qutebrowser/commands/userscripts.py +++ b/qutebrowser/commands/userscripts.py @@ -62,7 +62,7 @@ class _QtFIFOReader(QObject): # pylint: enable=no-member,useless-suppression self._fifo = os.fdopen(fd, 'r') self._notifier = QSocketNotifier(cast(sip.voidptr, fd), - QSocketNotifier.Read, self) + QSocketNotifier.Type.Read, self) self._notifier.activated.connect(self.read_line) @pyqtSlot() diff --git a/qutebrowser/completion/completiondelegate.py b/qutebrowser/completion/completiondelegate.py index ee9abbde1..e561ecf39 100644 --- a/qutebrowser/completion/completiondelegate.py +++ b/qutebrowser/completion/completiondelegate.py @@ -46,7 +46,7 @@ class _Highlighter(QSyntaxHighlighter): words.sort(key=len, reverse=True) pat = "|".join(re.escape(word) for word in words) self._expression = QRegularExpression( - pat, QRegularExpression.CaseInsensitiveOption + pat, QRegularExpression.PatternOption.CaseInsensitiveOption ) qtutils.ensure_valid(self._expression) @@ -110,12 +110,12 @@ class CompletionItemDelegate(QStyledItemDelegate): # be displayed. return - mode = QIcon.Normal - if not self._opt.state & QStyle.State_Enabled: - mode = QIcon.Disabled - elif self._opt.state & QStyle.State_Selected: - mode = QIcon.Selected - state = QIcon.On if self._opt.state & QStyle.State_Open else QIcon.Off + mode = QIcon.Mode.Normal + if not self._opt.state & QStyle.StateFlag.State_Enabled: + mode = QIcon.Mode.Disabled + elif self._opt.state & QStyle.StateFlag.State_Selected: + mode = QIcon.Mode.Selected + state = QIcon.State.On if self._opt.state & QStyle.StateFlag.State_Open else QIcon.State.Off self._opt.icon.paint(self._painter, icon_rect, self._opt.decorationAlignment, mode, state) @@ -137,7 +137,7 @@ class CompletionItemDelegate(QStyledItemDelegate): text_rect_ = self._style.subElementRect( self._style.SE_ItemViewItemText, self._opt, self._opt.widget) qtutils.ensure_valid(text_rect_) - margin = self._style.pixelMetric(QStyle.PM_FocusFrameHMargin, + margin = self._style.pixelMetric(QStyle.PixelMetric.PM_FocusFrameHMargin, self._opt, self._opt.widget) + 1 # remove width padding text_rect = text_rect_.adjusted(margin, 0, -margin, 0) @@ -149,24 +149,24 @@ class CompletionItemDelegate(QStyledItemDelegate): text_rect.adjust(0, -2, 0, -2) self._painter.save() state = self._opt.state - if state & QStyle.State_Enabled and state & QStyle.State_Active: - cg = QPalette.Normal - elif state & QStyle.State_Enabled: - cg = QPalette.Inactive + if state & QStyle.StateFlag.State_Enabled and state & QStyle.StateFlag.State_Active: + cg = QPalette.ColorGroup.Normal + elif state & QStyle.StateFlag.State_Enabled: + cg = QPalette.ColorGroup.Inactive else: - cg = QPalette.Disabled + cg = QPalette.ColorGroup.Disabled - if state & QStyle.State_Selected: + if state & QStyle.StateFlag.State_Selected: self._painter.setPen(self._opt.palette.color( - cg, QPalette.HighlightedText)) + cg, QPalette.ColorRole.HighlightedText)) # This is a dirty fix for the text jumping by one pixel for # whatever reason. text_rect.adjust(0, -1, 0, 0) else: - self._painter.setPen(self._opt.palette.color(cg, QPalette.Text)) + self._painter.setPen(self._opt.palette.color(cg, QPalette.ColorRole.Text)) - if state & QStyle.State_Editing: - self._painter.setPen(self._opt.palette.color(cg, QPalette.Text)) + if state & QStyle.StateFlag.State_Editing: + self._painter.setPen(self._opt.palette.color(cg, QPalette.ColorRole.Text)) self._painter.drawRect(text_rect_.adjusted(0, 0, -1, -1)) self._painter.translate(text_rect.left(), text_rect.top()) @@ -188,9 +188,9 @@ class CompletionItemDelegate(QStyledItemDelegate): clip = QRectF(0, 0, rect.width(), rect.height()) self._painter.save() - if self._opt.state & QStyle.State_Selected: + if self._opt.state & QStyle.StateFlag.State_Selected: color = config.cache['colors.completion.item.selected.fg'] - elif not self._opt.state & QStyle.State_Enabled: + elif not self._opt.state & QStyle.StateFlag.State_Enabled: color = config.cache['colors.completion.category.fg'] else: colors = config.cache['colors.completion.fg'] @@ -199,7 +199,7 @@ class CompletionItemDelegate(QStyledItemDelegate): self._painter.setPen(color) ctx = QAbstractTextDocumentLayout.PaintContext() - ctx.palette.setColor(QPalette.Text, self._painter.pen().color()) + ctx.palette.setColor(QPalette.ColorRole.Text, self._painter.pen().color()) if clip.isValid(): self._painter.setClipRect(clip) ctx.clip = clip @@ -217,10 +217,10 @@ class CompletionItemDelegate(QStyledItemDelegate): # qcommonstyle.cpp:viewItemDrawText # https://github.com/qutebrowser/qutebrowser/issues/118 text_option = QTextOption() - if self._opt.features & QStyleOptionViewItem.WrapText: - text_option.setWrapMode(QTextOption.WordWrap) + if self._opt.features & QStyleOptionViewItem.ViewItemFeature.WrapText: + text_option.setWrapMode(QTextOption.WrapMode.WordWrap) else: - text_option.setWrapMode(QTextOption.ManualWrap) + text_option.setWrapMode(QTextOption.WrapMode.ManualWrap) text_option.setTextDirection(self._opt.direction) text_option.setAlignment(QStyle.visualAlignment( self._opt.direction, self._opt.displayAlignment)) @@ -238,7 +238,7 @@ class CompletionItemDelegate(QStyledItemDelegate): pattern = view.pattern columns_to_filter = index.model().columns_to_filter(index) if index.column() in columns_to_filter and pattern: - if self._opt.state & QStyle.State_Selected: + if self._opt.state & QStyle.StateFlag.State_Selected: color = config.val.colors.completion.item.selected.match.fg else: color = config.val.colors.completion.match.fg @@ -255,23 +255,23 @@ class CompletionItemDelegate(QStyledItemDelegate): assert self._opt is not None assert self._style is not None state = self._opt.state - if not state & QStyle.State_HasFocus: + if not state & QStyle.StateFlag.State_HasFocus: return o = self._opt o.rect = self._style.subElementRect( self._style.SE_ItemViewItemFocusRect, self._opt, self._opt.widget) - o.state |= int(QStyle.State_KeyboardFocusChange | QStyle.State_Item) + o.state |= int(QStyle.StateFlag.State_KeyboardFocusChange | QStyle.StateFlag.State_Item) qtutils.ensure_valid(o.rect) - if state & QStyle.State_Enabled: - cg = QPalette.Normal + if state & QStyle.StateFlag.State_Enabled: + cg = QPalette.ColorGroup.Normal else: - cg = QPalette.Disabled - if state & QStyle.State_Selected: - role = QPalette.Highlight + cg = QPalette.ColorGroup.Disabled + if state & QStyle.StateFlag.State_Selected: + role = QPalette.ColorRole.Highlight else: - role = QPalette.Window + role = QPalette.ColorRole.Window o.backgroundColor = self._opt.palette.color(cg, role) - self._style.drawPrimitive(QStyle.PE_FrameFocusRect, o, self._painter, + self._style.drawPrimitive(QStyle.PrimitiveElement.PE_FrameFocusRect, o, self._painter, self._opt.widget) def sizeHint(self, option, index): @@ -287,7 +287,7 @@ class CompletionItemDelegate(QStyledItemDelegate): Return: A QSize with the recommended size. """ - value = index.data(Qt.SizeHintRole) + value = index.data(Qt.ItemDataRole.SizeHintRole) if value is not None: return value self._opt = QStyleOptionViewItem(option) @@ -298,7 +298,7 @@ class CompletionItemDelegate(QStyledItemDelegate): assert self._doc is not None docsize = self._doc.size().toSize() - size = self._style.sizeFromContents(QStyle.CT_ItemViewItem, self._opt, + size = self._style.sizeFromContents(QStyle.ContentsType.CT_ItemViewItem, self._opt, docsize, self._opt.widget) qtutils.ensure_valid(size) return size + QSize(10, 3) diff --git a/qutebrowser/completion/completionwidget.py b/qutebrowser/completion/completionwidget.py index 9f6c5191b..a7bd41a8e 100644 --- a/qutebrowser/completion/completionwidget.py +++ b/qutebrowser/completion/completionwidget.py @@ -127,14 +127,14 @@ class CompletionView(QTreeView): self.setItemDelegate(self._delegate) self.setStyle(QStyleFactory.create('Fusion')) stylesheet.set_register(self) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) self.setHeaderHidden(True) self.setAlternatingRowColors(True) self.setIndentation(0) self.setItemsExpandable(False) self.setExpandsOnDoubleClick(False) self.setAnimated(False) - self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) + self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff) # WORKAROUND # This is a workaround for weird race conditions with invalid # item indexes leading to segfaults in Qt. @@ -339,8 +339,8 @@ class CompletionView(QTreeView): selmodel.setCurrentIndex( idx, - QItemSelectionModel.ClearAndSelect | - QItemSelectionModel.Rows) + QItemSelectionModel.SelectionFlag.ClearAndSelect | + QItemSelectionModel.SelectionFlag.Rows) # if the last item is focused, try to fetch more next_idx = self.indexBelow(idx) diff --git a/qutebrowser/completion/models/completionmodel.py b/qutebrowser/completion/models/completionmodel.py index 3d28c6d80..ea491612a 100644 --- a/qutebrowser/completion/models/completionmodel.py +++ b/qutebrowser/completion/models/completionmodel.py @@ -63,7 +63,7 @@ class CompletionModel(QAbstractItemModel): """Add a completion category to the model.""" self._categories.append(cat) - def data(self, index, role=Qt.DisplayRole): + def data(self, index, role=Qt.ItemDataRole.DisplayRole): """Return the item data for index. Override QAbstractItemModel::data. @@ -74,7 +74,7 @@ class CompletionModel(QAbstractItemModel): Return: The item data, or None on an invalid index. """ - if role != Qt.DisplayRole: + if role != Qt.ItemDataRole.DisplayRole: return None cat = self._cat_from_idx(index) if cat: @@ -94,17 +94,17 @@ class CompletionModel(QAbstractItemModel): Override QAbstractItemModel::flags. - Return: The item flags, or Qt.NoItemFlags on error. + Return: The item flags, or Qt.ItemFlag.NoItemFlags on error. """ if not index.isValid(): - return Qt.NoItemFlags + return Qt.ItemFlag.NoItemFlags if index.parent().isValid(): # item - return (Qt.ItemIsEnabled | Qt.ItemIsSelectable | - Qt.ItemNeverHasChildren) + return (Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable | + Qt.ItemFlag.ItemNeverHasChildren) else: # category - return Qt.NoItemFlags + return Qt.ItemFlag.NoItemFlags def index(self, row, col, parent=QModelIndex()): """Get an index into the model. diff --git a/qutebrowser/completion/models/filepathcategory.py b/qutebrowser/completion/models/filepathcategory.py index 22fcd1ec1..3bf241c30 100644 --- a/qutebrowser/completion/models/filepathcategory.py +++ b/qutebrowser/completion/models/filepathcategory.py @@ -100,9 +100,9 @@ class FilePathCategory(QAbstractListModel): paths = self._glob(expanded) self._paths = sorted(self._contract_user(val, path) for path in paths) - def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Optional[str]: + def data(self, index: QModelIndex, role: int = Qt.ItemDataRole.DisplayRole) -> Optional[str]: """Implement abstract method in QAbstractListModel.""" - if role == Qt.DisplayRole and index.column() == 0: + if role == Qt.ItemDataRole.DisplayRole and index.column() == 0: return self._paths[index.row()] return None diff --git a/qutebrowser/completion/models/listcategory.py b/qutebrowser/completion/models/listcategory.py index 76a1d896a..e6756c1a3 100644 --- a/qutebrowser/completion/models/listcategory.py +++ b/qutebrowser/completion/models/listcategory.py @@ -66,7 +66,7 @@ class ListCategory(QSortFilterProxyModel): val = re.sub(r' +', r' ', val) # See #1919 val = re.escape(val) val = val.replace(r'\ ', '.*') - rx = QRegularExpression(val, QRegularExpression.CaseInsensitiveOption) + rx = QRegularExpression(val, QRegularExpression.PatternOption.CaseInsensitiveOption) qtutils.ensure_valid(rx) self.setFilterRegularExpression(rx) self.invalidate() diff --git a/qutebrowser/components/misccommands.py b/qutebrowser/components/misccommands.py index 76e46a540..c31ec5e6c 100644 --- a/qutebrowser/components/misccommands.py +++ b/qutebrowser/components/misccommands.py @@ -81,11 +81,11 @@ def _print_preview(tab: apitypes.Tab) -> None: tab.printing.check_preview_support() diag = QPrintPreviewDialog(tab) - diag.setAttribute(Qt.WA_DeleteOnClose) + diag.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) diag.setWindowFlags( diag.windowFlags() | - Qt.WindowMaximizeButtonHint | - Qt.WindowMinimizeButtonHint) + Qt.WindowType.WindowMaximizeButtonHint | + Qt.WindowType.WindowMinimizeButtonHint) diag.paintRequested.connect(functools.partial( tab.printing.to_printer, callback=print_callback)) diag.exec() diff --git a/qutebrowser/config/configfiles.py b/qutebrowser/config/configfiles.py index a68b59383..2316194aa 100644 --- a/qutebrowser/config/configfiles.py +++ b/qutebrowser/config/configfiles.py @@ -990,5 +990,5 @@ def init() -> None: # https://github.com/qutebrowser/qutebrowser/issues/515 path = os.path.join(standarddir.config(auto=True), 'qsettings') - for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: - QSettings.setPath(fmt, QSettings.UserScope, path) + for fmt in [QSettings.Format.NativeFormat, QSettings.Format.IniFormat]: + QSettings.setPath(fmt, QSettings.Scope.UserScope, path) diff --git a/qutebrowser/config/configinit.py b/qutebrowser/config/configinit.py index a85d389bd..03453dded 100644 --- a/qutebrowser/config/configinit.py +++ b/qutebrowser/config/configinit.py @@ -135,7 +135,7 @@ def late_init(save_manager: savemanager.SaveManager) -> None: errbox = msgbox.msgbox(parent=None, title="Error while reading config", text=_init_errors.to_html(), - icon=QMessageBox.Warning, + icon=QMessageBox.Icon.Warning, plain_text=False) errbox.exec() diff --git a/qutebrowser/config/configtypes.py b/qutebrowser/config/configtypes.py index 3d79a6b54..fc134559b 100644 --- a/qutebrowser/config/configtypes.py +++ b/qutebrowser/config/configtypes.py @@ -1062,9 +1062,9 @@ class ColorSystem(MappingType): """The color system to use for color interpolation.""" MAPPING = { - 'rgb': (QColor.Rgb, "Interpolate in the RGB color system."), - 'hsv': (QColor.Hsv, "Interpolate in the HSV color system."), - 'hsl': (QColor.Hsl, "Interpolate in the HSL color system."), + 'rgb': (QColor.Spec.Rgb, "Interpolate in the RGB color system."), + 'hsv': (QColor.Spec.Hsv, "Interpolate in the HSV color system."), + 'hsl': (QColor.Spec.Hsl, "Interpolate in the HSL color system."), 'none': (None, "Don't show a gradient."), } @@ -1798,10 +1798,10 @@ class Position(MappingType): """The position of the tab bar.""" MAPPING = { - 'top': (QTabWidget.North, None), - 'bottom': (QTabWidget.South, None), - 'left': (QTabWidget.West, None), - 'right': (QTabWidget.East, None), + 'top': (QTabWidget.TabPosition.North, None), + 'bottom': (QTabWidget.TabPosition.South, None), + 'left': (QTabWidget.TabPosition.West, None), + 'right': (QTabWidget.TabPosition.East, None), } @@ -1810,9 +1810,9 @@ class TextAlignment(MappingType): """Alignment of text.""" MAPPING = { - 'left': (Qt.AlignLeft, None), - 'right': (Qt.AlignRight, None), - 'center': (Qt.AlignCenter, None), + 'left': (Qt.AlignmentFlag.AlignLeft, None), + 'right': (Qt.AlignmentFlag.AlignRight, None), + 'center': (Qt.AlignmentFlag.AlignCenter, None), } @@ -1821,10 +1821,10 @@ class ElidePosition(MappingType): """Position of ellipsis in truncated text.""" MAPPING = { - 'left': (Qt.ElideLeft, None), - 'right': (Qt.ElideRight, None), - 'middle': (Qt.ElideMiddle, None), - 'none': (Qt.ElideNone, None), + 'left': (Qt.TextElideMode.ElideLeft, None), + 'right': (Qt.TextElideMode.ElideRight, None), + 'middle': (Qt.TextElideMode.ElideMiddle, None), + 'none': (Qt.TextElideMode.ElideNone, None), } @@ -1880,17 +1880,17 @@ class SelectOnRemove(MappingType): MAPPING = { 'prev': ( - QTabBar.SelectLeftTab, + QTabBar.SelectionBehavior.SelectLeftTab, ("Select the tab which came before the closed one " "(left in horizontal, above in vertical)."), ), 'next': ( - QTabBar.SelectRightTab, + QTabBar.SelectionBehavior.SelectRightTab, ("Select the tab which came after the closed one " "(right in horizontal, below in vertical)."), ), 'last-used': ( - QTabBar.SelectPreviousTab, + QTabBar.SelectionBehavior.SelectPreviousTab, "Select the previously selected tab.", ), } diff --git a/qutebrowser/config/configutils.py b/qutebrowser/config/configutils.py index 298249c11..a8a9ba246 100644 --- a/qutebrowser/config/configutils.py +++ b/qutebrowser/config/configutils.py @@ -294,7 +294,7 @@ class FontFamilies: @classmethod def from_system_default( cls, - font_type: QFontDatabase.SystemFont = QFontDatabase.FixedFont, + font_type: QFontDatabase.SystemFont = QFontDatabase.SystemFont.FixedFont, ) -> 'FontFamilies': """Get a FontFamilies object for the default system font. @@ -305,19 +305,19 @@ class FontFamilies: exist: 1) f = QFont() - f.setStyleHint(QFont.Monospace) + f.setStyleHint(QFont.StyleHint.Monospace) print(f.defaultFamily()) 2) f = QFont() - f.setStyleHint(QFont.TypeWriter) + f.setStyleHint(QFont.StyleHint.TypeWriter) print(f.defaultFamily()) - 3) f = QFontDatabase.systemFont(QFontDatabase.FixedFont) + 3) f = QFontDatabase.systemFont(QFontDatabase.SystemFont.FixedFont) print(f.family()) They yield different results depending on the OS: - QFont.Monospace | QFont.TypeWriter | QFontDatabase + QFont.StyleHint.Monospace | QFont.StyleHint.TypeWriter | QFontDatabase ------------------------------------------------------ Windows: Courier New | Courier New | Courier New Linux: DejaVu Sans Mono | DejaVu Sans Mono | monospace diff --git a/qutebrowser/config/qtargs.py b/qutebrowser/config/qtargs.py index b7bb63bc0..699f53273 100644 --- a/qutebrowser/config/qtargs.py +++ b/qutebrowser/config/qtargs.py @@ -199,7 +199,7 @@ def _webengine_locales_path() -> pathlib.Path: # not QtWebEngine. base = pathlib.Path('/app/translations') else: - base = pathlib.Path(QLibraryInfo.location(QLibraryInfo.TranslationsPath)) + base = pathlib.Path(QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath)) return base / 'qtwebengine_locales' diff --git a/qutebrowser/keyinput/basekeyparser.py b/qutebrowser/keyinput/basekeyparser.py index 714929f12..dbf27e965 100644 --- a/qutebrowser/keyinput/basekeyparser.py +++ b/qutebrowser/keyinput/basekeyparser.py @@ -42,7 +42,7 @@ class MatchResult: sequence: keyutils.KeySequence def __post_init__(self) -> None: - if self.match_type == QKeySequence.ExactMatch: + if self.match_type == QKeySequence.SequenceMatch.ExactMatch: assert self.command is not None else: assert self.command is None @@ -89,7 +89,7 @@ class BindingTrie: node.command = command def __contains__(self, sequence: keyutils.KeySequence) -> bool: - return self.matches(sequence).match_type == QKeySequence.ExactMatch + return self.matches(sequence).match_type == QKeySequence.SequenceMatch.ExactMatch def __repr__(self) -> str: return utils.get_repr(self, children=self.children, @@ -131,20 +131,20 @@ class BindingTrie: try: node = node.children[key] except KeyError: - return MatchResult(match_type=QKeySequence.NoMatch, + return MatchResult(match_type=QKeySequence.SequenceMatch.NoMatch, command=None, sequence=sequence) if node.command is not None: - return MatchResult(match_type=QKeySequence.ExactMatch, + return MatchResult(match_type=QKeySequence.SequenceMatch.ExactMatch, command=node.command, sequence=sequence) elif node.children: - return MatchResult(match_type=QKeySequence.PartialMatch, + return MatchResult(match_type=QKeySequence.SequenceMatch.PartialMatch, command=None, sequence=sequence) else: # This can only happen when there are no bindings at all. - return MatchResult(match_type=QKeySequence.NoMatch, + return MatchResult(match_type=QKeySequence.SequenceMatch.NoMatch, command=None, sequence=sequence) @@ -247,7 +247,7 @@ class BaseKeyParser(QObject): self._debug_log("Mapped {} -> {}".format( sequence, mapped)) return self._match_key(mapped) - return MatchResult(match_type=QKeySequence.NoMatch, + return MatchResult(match_type=QKeySequence.SequenceMatch.NoMatch, command=None, sequence=sequence) @@ -292,44 +292,44 @@ class BaseKeyParser(QObject): if keyutils.is_modifier_key(key): self._debug_log("Ignoring, only modifier") - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch try: sequence = self._sequence.append_event(e) except keyutils.KeyParseError as ex: self._debug_log("{} Aborting keychain.".format(ex)) self.clear_keystring() - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch result = self._match_key(sequence) del sequence # Enforce code below to use the modified result.sequence - if result.match_type == QKeySequence.NoMatch: + if result.match_type == QKeySequence.SequenceMatch.NoMatch: result = self._match_without_modifiers(result.sequence) - if result.match_type == QKeySequence.NoMatch: + if result.match_type == QKeySequence.SequenceMatch.NoMatch: result = self._match_key_mapping(result.sequence) - if result.match_type == QKeySequence.NoMatch: + if result.match_type == QKeySequence.SequenceMatch.NoMatch: was_count = self._match_count(result.sequence, dry_run) if was_count: - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch if dry_run: return result.match_type self._sequence = result.sequence - if result.match_type == QKeySequence.ExactMatch: + if result.match_type == QKeySequence.SequenceMatch.ExactMatch: assert result.command is not None self._debug_log("Definitive match for '{}'.".format( result.sequence)) count = int(self._count) if self._count else None self.clear_keystring() self.execute(result.command, count) - elif result.match_type == QKeySequence.PartialMatch: + elif result.match_type == QKeySequence.SequenceMatch.PartialMatch: self._debug_log("No match for '{}' (added {})".format( result.sequence, txt)) self.keystring_updated.emit(self._count + str(result.sequence)) - elif result.match_type == QKeySequence.NoMatch: + elif result.match_type == QKeySequence.SequenceMatch.NoMatch: self._debug_log("Giving up with '{}', no matches".format( result.sequence)) self.clear_keystring() diff --git a/qutebrowser/keyinput/eventfilter.py b/qutebrowser/keyinput/eventfilter.py index 27668c8de..31ffcc7f9 100644 --- a/qutebrowser/keyinput/eventfilter.py +++ b/qutebrowser/keyinput/eventfilter.py @@ -43,9 +43,9 @@ class EventFilter(QObject): super().__init__(parent) self._activated = True self._handlers = { - QEvent.KeyPress: self._handle_key_event, - QEvent.KeyRelease: self._handle_key_event, - QEvent.ShortcutOverride: self._handle_key_event, + QEvent.Type.KeyPress: self._handle_key_event, + QEvent.Type.KeyRelease: self._handle_key_event, + QEvent.Type.ShortcutOverride: self._handle_key_event, } def install(self) -> None: diff --git a/qutebrowser/keyinput/keyutils.py b/qutebrowser/keyinput/keyutils.py index eb580a5bb..a1ac99f9d 100644 --- a/qutebrowser/keyinput/keyutils.py +++ b/qutebrowser/keyinput/keyutils.py @@ -43,12 +43,12 @@ from qutebrowser.utils import utils # Map Qt::Key values to their Qt::KeyboardModifier value. _MODIFIER_MAP = { - Qt.Key_Shift: Qt.ShiftModifier, - Qt.Key_Control: Qt.ControlModifier, - Qt.Key_Alt: Qt.AltModifier, - Qt.Key_Meta: Qt.MetaModifier, - Qt.Key_AltGr: Qt.GroupSwitchModifier, - Qt.Key_Mode_switch: Qt.GroupSwitchModifier, + Qt.Key.Key_Shift: Qt.KeyboardModifier.ShiftModifier, + Qt.Key.Key_Control: Qt.KeyboardModifier.ControlModifier, + Qt.Key.Key_Alt: Qt.KeyboardModifier.AltModifier, + Qt.Key.Key_Meta: Qt.KeyboardModifier.MetaModifier, + Qt.Key.Key_AltGr: Qt.KeyboardModifier.GroupSwitchModifier, + Qt.Key.Key_Mode_switch: Qt.KeyboardModifier.GroupSwitchModifier, } _NIL_KEY = Qt.Key(0) @@ -63,86 +63,86 @@ _SPECIAL_NAMES = { # For dead/combining keys, we return the corresponding non-combining # key, as that's easier to add to the config. - Qt.Key_Super_L: 'Super L', - Qt.Key_Super_R: 'Super R', - Qt.Key_Hyper_L: 'Hyper L', - Qt.Key_Hyper_R: 'Hyper R', - Qt.Key_Direction_L: 'Direction L', - Qt.Key_Direction_R: 'Direction R', - - Qt.Key_Shift: 'Shift', - Qt.Key_Control: 'Control', - Qt.Key_Meta: 'Meta', - Qt.Key_Alt: 'Alt', - - Qt.Key_AltGr: 'AltGr', - Qt.Key_Multi_key: 'Multi key', - Qt.Key_SingleCandidate: 'Single Candidate', - Qt.Key_Mode_switch: 'Mode switch', - Qt.Key_Dead_Grave: '`', - Qt.Key_Dead_Acute: '´', - Qt.Key_Dead_Circumflex: '^', - Qt.Key_Dead_Tilde: '~', - Qt.Key_Dead_Macron: '¯', - Qt.Key_Dead_Breve: '˘', - Qt.Key_Dead_Abovedot: '˙', - Qt.Key_Dead_Diaeresis: '¨', - Qt.Key_Dead_Abovering: '˚', - Qt.Key_Dead_Doubleacute: '˝', - Qt.Key_Dead_Caron: 'ˇ', - Qt.Key_Dead_Cedilla: '¸', - Qt.Key_Dead_Ogonek: '˛', - Qt.Key_Dead_Iota: 'Iota', - Qt.Key_Dead_Voiced_Sound: 'Voiced Sound', - Qt.Key_Dead_Semivoiced_Sound: 'Semivoiced Sound', - Qt.Key_Dead_Belowdot: 'Belowdot', - Qt.Key_Dead_Hook: 'Hook', - Qt.Key_Dead_Horn: 'Horn', - - Qt.Key_Dead_Stroke: '\u0335', # '̵' - Qt.Key_Dead_Abovecomma: '\u0313', # '̓' - Qt.Key_Dead_Abovereversedcomma: '\u0314', # '̔' - Qt.Key_Dead_Doublegrave: '\u030f', # '̏' - Qt.Key_Dead_Belowring: '\u0325', # '̥' - Qt.Key_Dead_Belowmacron: '\u0331', # '̱' - Qt.Key_Dead_Belowcircumflex: '\u032d', # '̭' - Qt.Key_Dead_Belowtilde: '\u0330', # '̰' - Qt.Key_Dead_Belowbreve: '\u032e', # '̮' - Qt.Key_Dead_Belowdiaeresis: '\u0324', # '̤' - Qt.Key_Dead_Invertedbreve: '\u0311', # '̑' - Qt.Key_Dead_Belowcomma: '\u0326', # '̦' - Qt.Key_Dead_Currency: '¤', - Qt.Key_Dead_a: 'a', - Qt.Key_Dead_A: 'A', - Qt.Key_Dead_e: 'e', - Qt.Key_Dead_E: 'E', - Qt.Key_Dead_i: 'i', - Qt.Key_Dead_I: 'I', - Qt.Key_Dead_o: 'o', - Qt.Key_Dead_O: 'O', - Qt.Key_Dead_u: 'u', - Qt.Key_Dead_U: 'U', - Qt.Key_Dead_Small_Schwa: 'ə', - Qt.Key_Dead_Capital_Schwa: 'Ə', - Qt.Key_Dead_Greek: 'Greek', - Qt.Key_Dead_Lowline: '\u0332', # '̲' - Qt.Key_Dead_Aboveverticalline: '\u030d', # '̍' - Qt.Key_Dead_Belowverticalline: '\u0329', - Qt.Key_Dead_Longsolidusoverlay: '\u0338', # '̸' - - Qt.Key_Memo: 'Memo', - Qt.Key_ToDoList: 'To Do List', - Qt.Key_Calendar: 'Calendar', - Qt.Key_ContrastAdjust: 'Contrast Adjust', - Qt.Key_LaunchG: 'Launch (G)', - Qt.Key_LaunchH: 'Launch (H)', - - Qt.Key_MediaLast: 'Media Last', - - Qt.Key_unknown: 'Unknown', + Qt.Key.Key_Super_L: 'Super L', + Qt.Key.Key_Super_R: 'Super R', + Qt.Key.Key_Hyper_L: 'Hyper L', + Qt.Key.Key_Hyper_R: 'Hyper R', + Qt.Key.Key_Direction_L: 'Direction L', + Qt.Key.Key_Direction_R: 'Direction R', + + Qt.Key.Key_Shift: 'Shift', + Qt.Key.Key_Control: 'Control', + Qt.Key.Key_Meta: 'Meta', + Qt.Key.Key_Alt: 'Alt', + + Qt.Key.Key_AltGr: 'AltGr', + Qt.Key.Key_Multi_key: 'Multi key', + Qt.Key.Key_SingleCandidate: 'Single Candidate', + Qt.Key.Key_Mode_switch: 'Mode switch', + Qt.Key.Key_Dead_Grave: '`', + Qt.Key.Key_Dead_Acute: '´', + Qt.Key.Key_Dead_Circumflex: '^', + Qt.Key.Key_Dead_Tilde: '~', + Qt.Key.Key_Dead_Macron: '¯', + Qt.Key.Key_Dead_Breve: '˘', + Qt.Key.Key_Dead_Abovedot: '˙', + Qt.Key.Key_Dead_Diaeresis: '¨', + Qt.Key.Key_Dead_Abovering: '˚', + Qt.Key.Key_Dead_Doubleacute: '˝', + Qt.Key.Key_Dead_Caron: 'ˇ', + Qt.Key.Key_Dead_Cedilla: '¸', + Qt.Key.Key_Dead_Ogonek: '˛', + Qt.Key.Key_Dead_Iota: 'Iota', + Qt.Key.Key_Dead_Voiced_Sound: 'Voiced Sound', + Qt.Key.Key_Dead_Semivoiced_Sound: 'Semivoiced Sound', + Qt.Key.Key_Dead_Belowdot: 'Belowdot', + Qt.Key.Key_Dead_Hook: 'Hook', + Qt.Key.Key_Dead_Horn: 'Horn', + + Qt.Key.Key_Dead_Stroke: '\u0335', # '̵' + Qt.Key.Key_Dead_Abovecomma: '\u0313', # '̓' + Qt.Key.Key_Dead_Abovereversedcomma: '\u0314', # '̔' + Qt.Key.Key_Dead_Doublegrave: '\u030f', # '̏' + Qt.Key.Key_Dead_Belowring: '\u0325', # '̥' + Qt.Key.Key_Dead_Belowmacron: '\u0331', # '̱' + Qt.Key.Key_Dead_Belowcircumflex: '\u032d', # '̭' + Qt.Key.Key_Dead_Belowtilde: '\u0330', # '̰' + Qt.Key.Key_Dead_Belowbreve: '\u032e', # '̮' + Qt.Key.Key_Dead_Belowdiaeresis: '\u0324', # '̤' + Qt.Key.Key_Dead_Invertedbreve: '\u0311', # '̑' + Qt.Key.Key_Dead_Belowcomma: '\u0326', # '̦' + Qt.Key.Key_Dead_Currency: '¤', + Qt.Key.Key_Dead_a: 'a', + Qt.Key.Key_Dead_A: 'A', + Qt.Key.Key_Dead_e: 'e', + Qt.Key.Key_Dead_E: 'E', + Qt.Key.Key_Dead_i: 'i', + Qt.Key.Key_Dead_I: 'I', + Qt.Key.Key_Dead_o: 'o', + Qt.Key.Key_Dead_O: 'O', + Qt.Key.Key_Dead_u: 'u', + Qt.Key.Key_Dead_U: 'U', + Qt.Key.Key_Dead_Small_Schwa: 'ə', + Qt.Key.Key_Dead_Capital_Schwa: 'Ə', + Qt.Key.Key_Dead_Greek: 'Greek', + Qt.Key.Key_Dead_Lowline: '\u0332', # '̲' + Qt.Key.Key_Dead_Aboveverticalline: '\u030d', # '̍' + Qt.Key.Key_Dead_Belowverticalline: '\u0329', + Qt.Key.Key_Dead_Longsolidusoverlay: '\u0338', # '̸' + + Qt.Key.Key_Memo: 'Memo', + Qt.Key.Key_ToDoList: 'To Do List', + Qt.Key.Key_Calendar: 'Calendar', + Qt.Key.Key_ContrastAdjust: 'Contrast Adjust', + Qt.Key.Key_LaunchG: 'Launch (G)', + Qt.Key.Key_LaunchH: 'Launch (H)', + + Qt.Key.Key_MediaLast: 'Media Last', + + Qt.Key.Key_unknown: 'Unknown', # For some keys, we just want a different name - Qt.Key_Escape: 'Escape', + Qt.Key.Key_Escape: 'Escape', _NIL_KEY: 'nil', } @@ -150,18 +150,18 @@ _SPECIAL_NAMES = { def _assert_plain_key(key: Qt.Key) -> None: """Make sure this is a key without KeyboardModifiers mixed in.""" - assert not key & Qt.KeyboardModifierMask, hex(key) + assert not key & Qt.KeyboardModifier.KeyboardModifierMask, hex(key) def _assert_plain_modifier(key: _ModifierType) -> None: """Make sure this is a modifier without a key mixed in.""" - mask = Qt.KeyboardModifierMask + mask = Qt.KeyboardModifier.KeyboardModifierMask assert not key & ~mask, hex(key) def _is_printable(key: Qt.Key) -> bool: _assert_plain_key(key) - return key <= 0xff and key not in [Qt.Key_Space, _NIL_KEY] + return key <= 0xff and key not in [Qt.Key.Key_Space, _NIL_KEY] def is_special(key: Qt.Key, modifiers: _ModifierType) -> bool: @@ -169,7 +169,7 @@ def is_special(key: Qt.Key, modifiers: _ModifierType) -> bool: _assert_plain_key(key) _assert_plain_modifier(modifiers) return not (_is_printable(key) and - modifiers in [Qt.ShiftModifier, Qt.NoModifier]) + modifiers in [Qt.KeyboardModifier.ShiftModifier, Qt.KeyboardModifier.NoModifier]) def is_modifier_key(key: Qt.Key) -> bool: @@ -250,11 +250,11 @@ def _key_to_string(key: Qt.Key) -> str: def _modifiers_to_string(modifiers: _ModifierType) -> str: """Convert the given Qt::KeyboardModifiers to a string. - Handles Qt.GroupSwitchModifier because Qt doesn't handle that as a + Handles Qt.KeyboardModifier.GroupSwitchModifier because Qt doesn't handle that as a modifier. """ _assert_plain_modifier(modifiers) - altgr = cast(Qt.KeyboardModifiers, Qt.GroupSwitchModifier) + altgr = Qt.KeyboardModifier.GroupSwitchModifier if modifiers & altgr: modifiers &= ~altgr result = 'AltGr+' @@ -382,10 +382,10 @@ class KeyInfo: .format(self.key)) assert len(key_string) == 1, key_string - if self.modifiers == Qt.ShiftModifier: + if self.modifiers == Qt.KeyboardModifier.ShiftModifier: assert not is_special(self.key, self.modifiers) return key_string.upper() - elif self.modifiers == Qt.NoModifier: + elif self.modifiers == Qt.KeyboardModifier.NoModifier: assert not is_special(self.key, self.modifiers) return key_string.lower() else: @@ -402,12 +402,12 @@ class KeyInfo: def text(self) -> str: """Get the text which would be displayed when pressing this key.""" control = { - Qt.Key_Space: ' ', - Qt.Key_Tab: '\t', - Qt.Key_Backspace: '\b', - Qt.Key_Return: '\r', - Qt.Key_Enter: '\r', - Qt.Key_Escape: '\x1b', + Qt.Key.Key_Space: ' ', + Qt.Key.Key_Tab: '\t', + Qt.Key.Key_Backspace: '\b', + Qt.Key.Key_Return: '\r', + Qt.Key.Key_Enter: '\r', + Qt.Key.Key_Escape: '\x1b', } if self.key in control: @@ -416,11 +416,11 @@ class KeyInfo: return '' text = QKeySequence(self.key).toString() - if not self.modifiers & Qt.ShiftModifier: + if not self.modifiers & Qt.KeyboardModifier.ShiftModifier: text = text.lower() return text - def to_event(self, typ: QEvent.Type = QEvent.KeyPress) -> QKeyEvent: + def to_event(self, typ: QEvent.Type = QEvent.Type.KeyPress) -> QKeyEvent: """Get a QKeyEvent from this KeyInfo.""" return QKeyEvent(typ, self.key, self.modifiers, self.text()) @@ -472,9 +472,9 @@ class KeySequence: def __iter__(self) -> Iterator[KeyInfo]: """Iterate over KeyInfo objects.""" for key_and_modifiers in self._iter_keys(): - key = Qt.Key(int(key_and_modifiers) & ~Qt.KeyboardModifierMask) + key = Qt.Key(int(key_and_modifiers) & ~Qt.KeyboardModifier.KeyboardModifierMask) modifiers = Qt.KeyboardModifiers( - int(key_and_modifiers) & Qt.KeyboardModifierMask) + int(key_and_modifiers) & Qt.KeyboardModifier.KeyboardModifierMask) yield KeyInfo(key=key, modifiers=modifiers) def __repr__(self) -> str: @@ -533,7 +533,7 @@ class KeySequence: def _validate(self, keystr: str = None) -> None: for info in self: - if info.key < Qt.Key_Space or info.key >= Qt.Key_unknown: + if info.key < Qt.Key.Key_Space or info.key >= Qt.Key.Key_unknown: raise KeyParseError(keystr, "Got invalid key!") for seq in self._sequences: @@ -552,12 +552,12 @@ class KeySequence: if len(self._sequences) > len(other._sequences): # If we entered more sequences than there are in the config, # there's no way there can be a match. - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch for entered, configured in zip(self._sequences, other._sequences): # If we get NoMatch/PartialMatch in a sequence, we can abort there. match = entered.matches(configured) - if match != QKeySequence.ExactMatch: + if match != QKeySequence.SequenceMatch.ExactMatch: return match # We checked all common sequences and they had an ExactMatch. @@ -569,9 +569,9 @@ class KeySequence: # If there's the same amount of sequences configured and entered, # that's an EqualMatch. if len(self._sequences) == len(other._sequences): - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch elif len(self._sequences) < len(other._sequences): - return QKeySequence.PartialMatch + return QKeySequence.SequenceMatch.PartialMatch else: raise utils.Unreachable("self={!r} other={!r}".format(self, other)) @@ -588,14 +588,14 @@ class KeySequence: if key == _NIL_KEY: raise KeyParseError(None, "Got nil key!") - # We always remove Qt.GroupSwitchModifier because QKeySequence has no + # We always remove Qt.KeyboardModifier.GroupSwitchModifier because QKeySequence has no # way to mention that in a binding anyways... - modifiers &= ~Qt.GroupSwitchModifier + modifiers &= ~Qt.KeyboardModifier.GroupSwitchModifier - # We change Qt.Key_Backtab to Key_Tab here because nobody would + # We change Qt.Key.Key_Backtab to Key_Tab here because nobody would # configure "Shift-Backtab" in their config. - if modifiers & Qt.ShiftModifier and key == Qt.Key_Backtab: - key = Qt.Key_Tab + if modifiers & Qt.KeyboardModifier.ShiftModifier and key == Qt.Key.Key_Backtab: + key = Qt.Key.Key_Tab # We don't care about a shift modifier with symbols (Shift-: should # match a : binding even though we typed it with a shift on an @@ -607,27 +607,26 @@ class KeySequence: # # In addition, Shift also *is* relevant when other modifiers are # involved. Shift-Ctrl-X should not be equivalent to Ctrl-X. - if (modifiers == Qt.ShiftModifier and + if (modifiers == Qt.KeyboardModifier.ShiftModifier and _is_printable(key) and not ev.text().isupper()): modifiers = Qt.KeyboardModifiers() # type: ignore[assignment] # On macOS, swap Ctrl and Meta back # - # We don't use Qt.AA_MacDontSwapCtrlAndMeta because that also affects + # We don't use Qt.ApplicationAttribute.AA_MacDontSwapCtrlAndMeta because that also affects # Qt/QtWebEngine's own shortcuts. However, we do want "Ctrl" and "Meta" # (or "Cmd") in a key binding name to actually represent what's on the # keyboard. if utils.is_mac: - # FIXME:qt6 Reevaluate the type ignores below - if modifiers & Qt.ControlModifier and modifiers & Qt.MetaModifier: + if modifiers & Qt.KeyboardModifier.ControlModifier and modifiers & Qt.KeyboardModifier.MetaModifier: pass - elif modifiers & Qt.ControlModifier: - modifiers &= ~Qt.ControlModifier - modifiers |= Qt.MetaModifier # type: ignore[assignment] - elif modifiers & Qt.MetaModifier: - modifiers &= ~Qt.MetaModifier - modifiers |= Qt.ControlModifier # type: ignore[assignment] + elif modifiers & Qt.KeyboardModifier.ControlModifier: + modifiers &= ~Qt.KeyboardModifier.ControlModifier + modifiers |= Qt.KeyboardModifier.MetaModifier + elif modifiers & Qt.KeyboardModifier.MetaModifier: + modifiers &= ~Qt.KeyboardModifier.MetaModifier + modifiers |= Qt.KeyboardModifier.ControlModifier keys = list(self._iter_keys()) keys.append(key | int(modifiers)) @@ -636,7 +635,7 @@ class KeySequence: def strip_modifiers(self) -> 'KeySequence': """Strip optional modifiers from keys.""" - modifiers = Qt.KeypadModifier + modifiers = Qt.KeyboardModifier.KeypadModifier keys = [key & ~modifiers for key in self._iter_keys()] return self.__class__(*keys) diff --git a/qutebrowser/keyinput/modeman.py b/qutebrowser/keyinput/modeman.py index 130568c92..57e663c12 100644 --- a/qutebrowser/keyinput/modeman.py +++ b/qutebrowser/keyinput/modeman.py @@ -290,8 +290,8 @@ class ModeManager(QObject): match = parser.handle(event, dry_run=dry_run) has_modifier = event.modifiers() not in [ - Qt.NoModifier, - Qt.ShiftModifier, + Qt.KeyboardModifier.NoModifier, + Qt.KeyboardModifier.ShiftModifier, ] # type: ignore[comparison-overlap] is_non_alnum = has_modifier or not event.text().strip() @@ -460,9 +460,9 @@ class ModeManager(QObject): True if event should be filtered, False otherwise. """ handlers: Mapping[QEvent.Type, Callable[[QKeyEvent], bool]] = { - QEvent.KeyPress: self._handle_keypress, - QEvent.KeyRelease: self._handle_keyrelease, - QEvent.ShortcutOverride: + QEvent.Type.KeyPress: self._handle_keypress, + QEvent.Type.KeyRelease: self._handle_keyrelease, + QEvent.Type.ShortcutOverride: functools.partial(self._handle_keypress, dry_run=True), } handler = handlers[event.type()] diff --git a/qutebrowser/keyinput/modeparsers.py b/qutebrowser/keyinput/modeparsers.py index 0b050f76e..db6773602 100644 --- a/qutebrowser/keyinput/modeparsers.py +++ b/qutebrowser/keyinput/modeparsers.py @@ -110,11 +110,11 @@ class NormalKeyParser(CommandKeyParser): if self._inhibited: self._debug_log("Ignoring key '{}', because the normal mode is " "currently inhibited.".format(txt)) - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch match = super().handle(e, dry_run=dry_run) - if match == QKeySequence.PartialMatch and not dry_run: + if match == QKeySequence.SequenceMatch.PartialMatch and not dry_run: timeout = config.val.input.partial_timeout if timeout != 0: self._partial_timer.setInterval(timeout) @@ -178,7 +178,7 @@ class HintKeyParser(basekeyparser.BaseKeyParser): """Handle keys for string filtering.""" log.keyboard.debug("Got filter key 0x{:x} text {}".format( e.key(), e.text())) - if e.key() == Qt.Key_Backspace: + if e.key() == Qt.Key.Key_Backspace: log.keyboard.debug("Got backspace, mode {}, filtertext '{}', " "sequence '{}'".format(self._last_press, self._filtertext, @@ -186,7 +186,7 @@ class HintKeyParser(basekeyparser.BaseKeyParser): if self._last_press != LastPress.keystring and self._filtertext: self._filtertext = self._filtertext[:-1] self._hintmanager.filter_hints(self._filtertext) - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch elif self._last_press == LastPress.keystring and self._sequence: self._sequence = self._sequence[:-1] self.keystring_updated.emit(str(self._sequence)) @@ -195,18 +195,18 @@ class HintKeyParser(basekeyparser.BaseKeyParser): # in numeric mode after the number has been deleted). self._hintmanager.filter_hints(self._filtertext) self._last_press = LastPress.filtertext - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch else: - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch elif self._hintmanager.current_mode() != 'number': - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch elif not e.text(): - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch else: self._filtertext += e.text() self._hintmanager.filter_hints(self._filtertext) self._last_press = LastPress.filtertext - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch def handle(self, e: QKeyEvent, *, dry_run: bool = False) -> QKeySequence.SequenceMatch: @@ -217,18 +217,18 @@ class HintKeyParser(basekeyparser.BaseKeyParser): assert not dry_run if (self._command_parser.handle(e, dry_run=True) != - QKeySequence.NoMatch): + QKeySequence.SequenceMatch.NoMatch): log.keyboard.debug("Handling key via command parser") self.clear_keystring() return self._command_parser.handle(e) match = super().handle(e) - if match == QKeySequence.PartialMatch: + if match == QKeySequence.SequenceMatch.PartialMatch: self._last_press = LastPress.keystring - elif match == QKeySequence.ExactMatch: + elif match == QKeySequence.SequenceMatch.ExactMatch: self._last_press = LastPress.none - elif match == QKeySequence.NoMatch: + elif match == QKeySequence.SequenceMatch.NoMatch: # We couldn't find a keychain so we check if it's a special key. return self._handle_filter_key(e) else: @@ -283,7 +283,7 @@ class RegisterKeyParser(CommandKeyParser): if keyutils.is_special(Qt.Key(e.key()), e.modifiers()): # this is not a proper register key, let it pass and keep going - return QKeySequence.NoMatch + return QKeySequence.SequenceMatch.NoMatch key = e.text() @@ -307,4 +307,4 @@ class RegisterKeyParser(CommandKeyParser): self.request_leave.emit( self._register_mode, "valid register key", True) - return QKeySequence.ExactMatch + return QKeySequence.SequenceMatch.ExactMatch diff --git a/qutebrowser/mainwindow/mainwindow.py b/qutebrowser/mainwindow/mainwindow.py index 5797fd5b1..c3e3cbf78 100644 --- a/qutebrowser/mainwindow/mainwindow.py +++ b/qutebrowser/mainwindow/mainwindow.py @@ -88,12 +88,12 @@ def get_window(*, via_ipc: bool, def raise_window(window, alert=True): """Raise the given MainWindow object.""" - window.setWindowState(window.windowState() & ~Qt.WindowMinimized) - window.setWindowState(window.windowState() | Qt.WindowActive) + window.setWindowState(window.windowState() & ~Qt.WindowState.WindowMinimized) + window.setWindowState(window.windowState() | Qt.WindowState.WindowActive) window.raise_() # WORKAROUND for https://bugreports.qt.io/browse/QTBUG-69568 QCoreApplication.processEvents( - QEventLoop.ExcludeUserInputEvents | QEventLoop.ExcludeSocketNotifiers) + QEventLoop.ProcessEventsFlag.ExcludeUserInputEvents | QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) if not sip.isdeleted(window): # Could be deleted by the events run above @@ -202,10 +202,10 @@ class MainWindow(QWidget): from qutebrowser.mainwindow import tabbedbrowser from qutebrowser.mainwindow.statusbar import bar - self.setAttribute(Qt.WA_DeleteOnClose) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) if config.val.window.transparent: - self.setAttribute(Qt.WA_TranslucentBackground) - self.palette().setColor(QPalette.Window, Qt.transparent) + self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground) + self.palette().setColor(QPalette.ColorRole.Window, Qt.GlobalColor.transparent) self._overlays: MutableSequence[_OverlayInfoType] = [] self.win_id = next(win_id_gen) @@ -305,7 +305,7 @@ class MainWindow(QWidget): if not widget.isVisible(): return - if widget.sizePolicy().horizontalPolicy() == QSizePolicy.Expanding: + if widget.sizePolicy().horizontalPolicy() == QSizePolicy.Policy.Expanding: width = self.width() - 2 * padding if widget.hasHeightForWidth(): height = widget.heightForWidth(width) @@ -564,10 +564,10 @@ class MainWindow(QWidget): def _set_decoration(self, hidden): """Set the visibility of the window decoration via Qt.""" - window_flags = cast(Qt.WindowFlags, Qt.Window) + window_flags = cast(Qt.WindowFlags, Qt.WindowType.Window) refresh_window = self.isVisible() if hidden: - window_flags |= Qt.CustomizeWindowHint | Qt.NoDropShadowWindowHint + window_flags |= Qt.WindowType.CustomizeWindowHint | Qt.WindowType.NoDropShadowWindowHint self.setWindowFlags(window_flags) if utils.is_mac and hidden: @@ -586,7 +586,7 @@ class MainWindow(QWidget): if not config.val.content.fullscreen.window: if on: self.state_before_fullscreen = self.windowState() - self.setWindowState(Qt.WindowFullScreen | self.state_before_fullscreen) + self.setWindowState(Qt.WindowState.WindowFullScreen | self.state_before_fullscreen) elif self.isFullScreen(): self.setWindowState(self.state_before_fullscreen) log.misc.debug('on: {}, state before fullscreen: {}'.format( diff --git a/qutebrowser/mainwindow/messageview.py b/qutebrowser/mainwindow/messageview.py index 8a1f12ee2..d76a8b0e2 100644 --- a/qutebrowser/mainwindow/messageview.py +++ b/qutebrowser/mainwindow/messageview.py @@ -43,7 +43,7 @@ class Message(QLabel): super().__init__(text, parent) self.replace = replace self.level = level - self.setAttribute(Qt.WA_StyledBackground, True) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) self.setWordWrap(True) self.setTextFormat(text_format) qss = """ @@ -114,7 +114,7 @@ class MessageView(QWidget): self._vbox = QVBoxLayout(self) self._vbox.setContentsMargins(0, 0, 0, 0) self._vbox.setSpacing(0) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) self._clear_timer = QTimer() self._clear_timer.timeout.connect(self.clear_messages) @@ -173,5 +173,5 @@ class MessageView(QWidget): def mousePressEvent(self, e): """Clear messages when they are clicked on.""" - if e.button() in [Qt.LeftButton, Qt.MiddleButton, Qt.RightButton]: + if e.button() in [Qt.MouseButton.LeftButton, Qt.MouseButton.MiddleButton, Qt.MouseButton.RightButton]: self.clear_messages() diff --git a/qutebrowser/mainwindow/prompt.py b/qutebrowser/mainwindow/prompt.py index 59fbc8e45..e32206a03 100644 --- a/qutebrowser/mainwindow/prompt.py +++ b/qutebrowser/mainwindow/prompt.py @@ -196,7 +196,7 @@ class PromptQueue(QObject): question.completed.connect(loop.deleteLater) log.prompt.debug("Starting loop.exec() for {}".format(question)) flags = cast(QEventLoop.ProcessEventsFlags, - QEventLoop.ExcludeSocketNotifiers) + QEventLoop.ProcessEventsFlag.ExcludeSocketNotifiers) loop.exec(flags) log.prompt.debug("Ending loop.exec() for {}".format(question)) @@ -293,7 +293,7 @@ class PromptContainer(QWidget): self._prompt: Optional[_BasePrompt] = None self.setObjectName('PromptContainer') - self.setAttribute(Qt.WA_StyledBackground, True) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) stylesheet.set_register(self) message.global_bridge.prompt_done.connect(self._on_prompt_done) @@ -504,11 +504,11 @@ class LineEdit(QLineEdit): background-color: transparent; } """) - self.setAttribute(Qt.WA_MacShowFocusRect, False) + self.setAttribute(Qt.WidgetAttribute.WA_MacShowFocusRect, False) def keyPressEvent(self, e): """Override keyPressEvent to paste primary selection on Shift + Ins.""" - if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier: + if e.key() == Qt.Key.Key_Insert and e.modifiers() == Qt.KeyboardModifier.ShiftModifier: try: text = utils.get_clipboard(selection=True, fallback=True) except utils.ClipboardError: # pragma: no cover @@ -549,7 +549,7 @@ class _BasePrompt(QWidget): # Not doing any HTML escaping here as the text can be formatted text_label = QLabel(question.text) text_label.setWordWrap(True) - text_label.setTextInteractionFlags(Qt.TextSelectableByMouse) + text_label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse) self._vbox.addWidget(text_label) def _init_key_label(self): @@ -584,7 +584,7 @@ class _BasePrompt(QWidget): self._key_grid.addWidget(key_label, i, 0) self._key_grid.addWidget(text_label, i, 1) - spacer = QSpacerItem(0, 0, QSizePolicy.Expanding) + spacer = QSpacerItem(0, 0, QSizePolicy.Policy.Expanding) self._key_grid.addItem(spacer, 0, 2) self._vbox.addLayout(self._key_grid) @@ -666,7 +666,7 @@ class FilenamePrompt(_BasePrompt): self._set_fileview_root(question.default) if config.val.prompt.filebrowser: - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred) self._to_complete = '' self._root_index = QModelIndex() @@ -809,8 +809,8 @@ class FilenamePrompt(_BasePrompt): selmodel.setCurrentIndex( idx, - QItemSelectionModel.ClearAndSelect | - QItemSelectionModel.Rows) + QItemSelectionModel.SelectionFlag.ClearAndSelect | + QItemSelectionModel.SelectionFlag.Rows) self._insert_path(idx, clicked=False) def _do_completion(self, idx, which): @@ -833,7 +833,7 @@ class DownloadFilenamePrompt(FilenamePrompt): def __init__(self, question, parent=None): super().__init__(question, parent) self._file_model.setFilter( - QDir.AllDirs | QDir.Drives | QDir.NoDotAndDotDot) + QDir.Filter.AllDirs | QDir.Filter.Drives | QDir.Filter.NoDotAndDotDot) def accept(self, value=None, save=False): done = super().accept(value, save) @@ -878,7 +878,7 @@ class AuthenticationPrompt(_BasePrompt): password_label = QLabel("Password:", self) self._password_lineedit = LineEdit(self) - self._password_lineedit.setEchoMode(QLineEdit.Password) + self._password_lineedit.setEchoMode(QLineEdit.EchoMode.Password) grid = QGridLayout() grid.addWidget(user_label, 1, 0) @@ -1013,4 +1013,4 @@ def init(): global prompt_queue prompt_queue = PromptQueue() message.global_bridge.ask_question.connect( # type: ignore[call-arg] - prompt_queue.ask_question, Qt.DirectConnection) + prompt_queue.ask_question, Qt.ConnectionType.DirectConnection) diff --git a/qutebrowser/mainwindow/statusbar/bar.py b/qutebrowser/mainwindow/statusbar/bar.py index a19c58ef0..1205b5466 100644 --- a/qutebrowser/mainwindow/statusbar/bar.py +++ b/qutebrowser/mainwindow/statusbar/bar.py @@ -165,10 +165,10 @@ class StatusBar(QWidget): def __init__(self, *, win_id, private, parent=None): super().__init__(parent) self.setObjectName(self.__class__.__name__) - self.setAttribute(Qt.WA_StyledBackground) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground) stylesheet.set_register(self) - self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Ignored, QSizePolicy.Policy.Fixed) self._win_id = win_id self._color_flags = ColorFlags() diff --git a/qutebrowser/mainwindow/statusbar/clock.py b/qutebrowser/mainwindow/statusbar/clock.py index e22e82fef..ebab152b7 100644 --- a/qutebrowser/mainwindow/statusbar/clock.py +++ b/qutebrowser/mainwindow/statusbar/clock.py @@ -32,7 +32,7 @@ class Clock(textbase.TextBase): UPDATE_DELAY = 500 # ms def __init__(self, parent=None): - super().__init__(parent, elidemode=Qt.ElideNone) + super().__init__(parent, elidemode=Qt.TextElideMode.ElideNone) self.format = "" self.timer = QTimer(self) diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py index 893dee42a..df85d0dfa 100644 --- a/qutebrowser/mainwindow/statusbar/command.py +++ b/qutebrowser/mainwindow/statusbar/command.py @@ -70,7 +70,7 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): command_history = objreg.get('command-history') self.history.history = command_history.data self.history.changed.connect(command_history.changed) - self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored) + self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.Ignored) self.cursorPositionChanged.connect(self.update_completion) self.textChanged.connect(self.update_completion) @@ -260,12 +260,12 @@ class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit): without command_accept to be called. """ text = self.text() - if text in modeparsers.STARTCHARS and e.key() == Qt.Key_Backspace: + if text in modeparsers.STARTCHARS and e.key() == Qt.Key.Key_Backspace: e.accept() modeman.leave(self._win_id, usertypes.KeyMode.command, 'prefix deleted') return - if e.key() == Qt.Key_Return: + if e.key() == Qt.Key.Key_Return: e.ignore() return else: diff --git a/qutebrowser/mainwindow/statusbar/percentage.py b/qutebrowser/mainwindow/statusbar/percentage.py index 3bb31971b..6ecdc4659 100644 --- a/qutebrowser/mainwindow/statusbar/percentage.py +++ b/qutebrowser/mainwindow/statusbar/percentage.py @@ -32,7 +32,7 @@ class Percentage(textbase.TextBase): def __init__(self, parent=None): """Constructor. Set percentage to 0%.""" - super().__init__(parent, elidemode=Qt.ElideNone) + super().__init__(parent, elidemode=Qt.TextElideMode.ElideNone) self._strings = self._calc_strings() self._set_text = throttle.Throttle(self.setText, 100, parent=self) self.set_perc(0, 0) diff --git a/qutebrowser/mainwindow/statusbar/progress.py b/qutebrowser/mainwindow/statusbar/progress.py index d5960db37..f76367b38 100644 --- a/qutebrowser/mainwindow/statusbar/progress.py +++ b/qutebrowser/mainwindow/statusbar/progress.py @@ -47,7 +47,7 @@ class Progress(QProgressBar): super().__init__(parent) stylesheet.set_register(self) self.enabled = False - self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed) self.setTextVisible(False) self.hide() diff --git a/qutebrowser/mainwindow/statusbar/textbase.py b/qutebrowser/mainwindow/statusbar/textbase.py index 1a0a5a42e..9ab4b9753 100644 --- a/qutebrowser/mainwindow/statusbar/textbase.py +++ b/qutebrowser/mainwindow/statusbar/textbase.py @@ -40,9 +40,9 @@ class TextBase(QLabel): _elided_text: The current elided text. """ - def __init__(self, parent=None, elidemode=Qt.ElideRight): + def __init__(self, parent=None, elidemode=Qt.TextElideMode.ElideRight): super().__init__(parent) - self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Minimum) self._elidemode = elidemode self._elided_text = '' @@ -57,7 +57,7 @@ class TextBase(QLabel): """ if self.text(): self._elided_text = self.fontMetrics().elidedText( - self.text(), self._elidemode, width, Qt.TextShowMnemonic) + self.text(), self._elidemode, width, Qt.TextFlag.TextShowMnemonic) else: self._elided_text = '' @@ -68,7 +68,7 @@ class TextBase(QLabel): txt: The text to set (string). """ super().setText(txt) - if self._elidemode != Qt.ElideNone: + if self._elidemode != Qt.TextElideMode.ElideNone: self._update_elided_text(self.geometry().width()) def resizeEvent(self, e): @@ -80,7 +80,7 @@ class TextBase(QLabel): def paintEvent(self, e): """Override QLabel::paintEvent to draw elided text.""" - if self._elidemode == Qt.ElideNone: + if self._elidemode == Qt.TextElideMode.ElideNone: super().paintEvent(e) else: e.accept() diff --git a/qutebrowser/mainwindow/tabbedbrowser.py b/qutebrowser/mainwindow/tabbedbrowser.py index 8b8446a23..bce66db2a 100644 --- a/qutebrowser/mainwindow/tabbedbrowser.py +++ b/qutebrowser/mainwindow/tabbedbrowser.py @@ -223,9 +223,9 @@ class TabbedBrowser(QWidget): self.widget.tabCloseRequested.connect(self.on_tab_close_requested) self.widget.new_tab_requested.connect(self.tabopen) self.widget.currentChanged.connect(self._on_current_changed) - self.cur_fullscreen_requested.connect(self.widget.tab_bar().maybe_hide) + self.cur_fullscreen_requested.connect(self.widget.tabBar().maybe_hide) - self.widget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + self.widget.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding) # load_finished instead of load_started as WORKAROUND for # https://bugreports.qt.io/browse/QTBUG-65223 @@ -1051,7 +1051,7 @@ class TabbedBrowser(QWidget): """ # strip the fragment as it may interfere with scrolling try: - url = self.current_url().adjusted(QUrl.RemoveFragment) + url = self.current_url().adjusted(QUrl.UrlFormattingOption.RemoveFragment) except qtutils.QtValueError: # show an error only if the mark is not automatically set if key != "'": @@ -1074,7 +1074,7 @@ class TabbedBrowser(QWidget): """ try: # consider urls that differ only in fragment to be identical - urlkey = self.current_url().adjusted(QUrl.RemoveFragment) + urlkey = self.current_url().adjusted(QUrl.UrlFormattingOption.RemoveFragment) except qtutils.QtValueError: urlkey = None diff --git a/qutebrowser/mainwindow/tabwidget.py b/qutebrowser/mainwindow/tabwidget.py index d410e54df..4af9d2f80 100644 --- a/qutebrowser/mainwindow/tabwidget.py +++ b/qutebrowser/mainwindow/tabwidget.py @@ -65,7 +65,7 @@ class TabWidget(QTabWidget): QTimer.singleShot, 0, self.update_tab_titles)) bar.currentChanged.connect(self._on_current_changed) bar.new_tab_requested.connect(self._on_new_tab_requested) - self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) self.setDocumentMode(True) self.setUsesScrollButtons(True) bar.setDrawBase(False) @@ -83,7 +83,8 @@ class TabWidget(QTabWidget): self.setElideMode(config.val.tabs.title.elide) tabbar = self.tab_bar() - tabbar.vertical = position in [QTabWidget.West, QTabWidget.East] + tabbar.vertical = position in [ + QTabWidget.TabPosition.West, QTabWidget.TabPosition.East] tabbar.setSelectionBehaviorOnRemove(selection_behavior) tabbar.refresh() @@ -366,7 +367,7 @@ class TabWidget(QTabWidget): config.cache['tabs.pinned.shrink'] and not self.tab_bar().vertical and tab is not None and tab.data.pinned): - icon = self.style().standardIcon(QStyle.SP_FileIcon) + icon = self.style().standardIcon(QStyle.StandardPixmap.SP_FileIcon) super().setTabIcon(idx, icon) @@ -554,8 +555,8 @@ class TabBar(QTabBar): Also keep track of if we are currently in a drag.""" self.drag_in_progress = True button = config.val.tabs.close_mouse_button - if (e.button() == Qt.RightButton and button == 'right' or - e.button() == Qt.MiddleButton and button == 'middle'): + if (e.button() == Qt.MouseButton.RightButton and button == 'right' or + e.button() == Qt.MouseButton.MiddleButton and button == 'middle'): e.accept() idx = self.tabAt(e.pos()) if idx == -1: @@ -613,7 +614,7 @@ class TabBar(QTabBar): def _text_to_width(text): # Calculate text width taking into account qt mnemonics - return self.fontMetrics().size(Qt.TextShowMnemonic, text).width() + return self.fontMetrics().size(Qt.TextFlag.TextShowMnemonic, text).width() text_width = min(_text_to_width(text), _text_to_width(tab_text)) padding = config.cache['tabs.padding'] @@ -714,14 +715,14 @@ class TabBar(QTabBar): setting += '.selected' setting += '.odd' if (idx + 1) % 2 else '.even' - tab.palette.setColor(QPalette.Window, + tab.palette.setColor(QPalette.ColorRole.Window, config.cache[setting + '.bg']) - tab.palette.setColor(QPalette.WindowText, + tab.palette.setColor(QPalette.ColorRole.WindowText, config.cache[setting + '.fg']) indicator_color = self.tab_indicator_color(idx) - tab.palette.setColor(QPalette.Base, indicator_color) - p.drawControl(QStyle.CE_TabBarTab, tab) + tab.palette.setColor(QPalette.ColorRole.Base, indicator_color) + p.drawControl(QStyle.ControlElement.CE_TabBarTab, tab) def tabInserted(self, idx): """Update visibility when a tab was inserted.""" @@ -831,12 +832,12 @@ class TabBarStyle(QCommonStyle): p: QPainter """ qtutils.ensure_valid(layouts.icon) - icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled - else QIcon.Disabled) - icon_state = (QIcon.On if opt.state & QStyle.State_Selected - else QIcon.Off) + icon_mode = (QIcon.Mode.Normal if opt.state & QStyle.StateFlag.State_Enabled + else QIcon.Mode.Disabled) + icon_state = (QIcon.State.On if opt.state & QStyle.StateFlag.State_Selected + else QIcon.State.Off) icon = opt.icon.pixmap(opt.iconSize, icon_mode, icon_state) - self._style.drawItemPixmap(p, layouts.icon, Qt.AlignCenter, icon) + self._style.drawItemPixmap(p, layouts.icon, Qt.AlignmentFlag.AlignCenter, icon) def drawControl(self, element, opt, p, widget=None): """Override drawControl to draw odd tabs in a different color. @@ -850,8 +851,8 @@ class TabBarStyle(QCommonStyle): p: QPainter widget: QWidget """ - if element not in [QStyle.CE_TabBarTab, QStyle.CE_TabBarTabShape, - QStyle.CE_TabBarTabLabel]: + if element not in [QStyle.ControlElement.CE_TabBarTab, QStyle.ControlElement.CE_TabBarTabShape, + QStyle.ControlElement.CE_TabBarTabLabel]: # Let the real style draw it. self._style.drawControl(element, opt, p, widget) return @@ -861,28 +862,28 @@ class TabBarStyle(QCommonStyle): log.misc.warning("Could not get layouts for tab!") return - if element == QStyle.CE_TabBarTab: + if element == QStyle.ControlElement.CE_TabBarTab: # We override this so we can control TabBarTabShape/TabBarTabLabel. - self.drawControl(QStyle.CE_TabBarTabShape, opt, p, widget) - self.drawControl(QStyle.CE_TabBarTabLabel, opt, p, widget) - elif element == QStyle.CE_TabBarTabShape: + self.drawControl(QStyle.ControlElement.CE_TabBarTabShape, opt, p, widget) + self.drawControl(QStyle.ControlElement.CE_TabBarTabLabel, opt, p, widget) + elif element == QStyle.ControlElement.CE_TabBarTabShape: p.fillRect(opt.rect, opt.palette.window()) self._draw_indicator(layouts, opt, p) # We use super() rather than self._style here because we don't want # any sophisticated drawing. - super().drawControl(QStyle.CE_TabBarTabShape, opt, p, widget) - elif element == QStyle.CE_TabBarTabLabel: + super().drawControl(QStyle.ControlElement.CE_TabBarTabShape, opt, p, widget) + elif element == QStyle.ControlElement.CE_TabBarTabLabel: if not opt.icon.isNull() and layouts.icon.isValid(): self._draw_icon(layouts, opt, p) alignment = (config.cache['tabs.title.alignment'] | - Qt.AlignVCenter | Qt.TextHideMnemonic) + Qt.AlignmentFlag.AlignVCenter | Qt.TextFlag.TextHideMnemonic) self._style.drawItemText(p, layouts.text, int(alignment), opt.palette, - bool(opt.state & QStyle.State_Enabled), + bool(opt.state & QStyle.StateFlag.State_Enabled), opt.text, - QPalette.WindowText) + QPalette.ColorRole.WindowText) else: raise ValueError("Invalid element {!r}".format(element)) @@ -897,11 +898,11 @@ class TabBarStyle(QCommonStyle): Return: An int. """ - if metric in [QStyle.PM_TabBarTabShiftHorizontal, - QStyle.PM_TabBarTabShiftVertical, - QStyle.PM_TabBarTabHSpace, - QStyle.PM_TabBarTabVSpace, - QStyle.PM_TabBarScrollButtonWidth]: + if metric in [QStyle.PixelMetric.PM_TabBarTabShiftHorizontal, + QStyle.PixelMetric.PM_TabBarTabShiftVertical, + QStyle.PixelMetric.PM_TabBarTabHSpace, + QStyle.PixelMetric.PM_TabBarTabVSpace, + QStyle.PixelMetric.PM_TabBarScrollButtonWidth]: return 0 else: return self._style.pixelMetric(metric, option, widget) @@ -917,14 +918,14 @@ class TabBarStyle(QCommonStyle): Return: A QRect. """ - if sr == QStyle.SE_TabBarTabText: + if sr == QStyle.SubElement.SE_TabBarTabText: layouts = self._tab_layout(opt) if layouts is None: log.misc.warning("Could not get layouts for tab!") return QRect() return layouts.text - elif sr in [QStyle.SE_TabWidgetTabBar, - QStyle.SE_TabBarScrollLeftButton]: + elif sr in [QStyle.SubElement.SE_TabWidgetTabBar, + QStyle.SubElement.SE_TabBarScrollLeftButton]: # Handling SE_TabBarScrollLeftButton so the left scroll button is # aligned properly. Otherwise, empty space will be shown after the # last tab even though the button width is set to 0 @@ -997,15 +998,15 @@ class TabBarStyle(QCommonStyle): """ icon_size = opt.iconSize if not icon_size.isValid(): - icon_extent = self.pixelMetric(QStyle.PM_SmallIconSize) + icon_extent = self.pixelMetric(QStyle.PixelMetric.PM_SmallIconSize) icon_size = QSize(icon_extent, icon_extent) - icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled - else QIcon.Disabled) - icon_state = (QIcon.On if opt.state & QStyle.State_Selected - else QIcon.Off) + icon_mode = (QIcon.Mode.Normal if opt.state & QStyle.StateFlag.State_Enabled + else QIcon.Mode.Disabled) + icon_state = (QIcon.State.On if opt.state & QStyle.StateFlag.State_Selected + else QIcon.State.Off) # reserve space for favicon when tab bar is vertical (issue #1968) position = config.cache['tabs.position'] - if (position in [QTabWidget.East, QTabWidget.West] and + if (position in [QTabWidget.TabPosition.East, QTabWidget.TabPosition.West] and config.cache['tabs.favicons.show'] != 'never'): tab_icon_size = icon_size else: diff --git a/qutebrowser/misc/backendproblem.py b/qutebrowser/misc/backendproblem.py index 7ce8b6f94..93ff4a7bd 100644 --- a/qutebrowser/misc/backendproblem.py +++ b/qutebrowser/misc/backendproblem.py @@ -44,10 +44,10 @@ class _Result(enum.IntEnum): """The result code returned by the backend problem dialog.""" - quit = QDialog.Accepted + 1 - restart = QDialog.Accepted + 2 - restart_webkit = QDialog.Accepted + 3 - restart_webengine = QDialog.Accepted + 4 + quit = QDialog.DialogCode.Accepted + 1 + restart = QDialog.DialogCode.Accepted + 2 + restart_webkit = QDialog.DialogCode.Accepted + 3 + restart_webengine = QDialog.DialogCode.Accepted + 4 @dataclasses.dataclass @@ -111,7 +111,7 @@ class _Dialog(QDialog): label = QLabel(text) label.setWordWrap(True) - label.setTextFormat(Qt.RichText) + label.setTextFormat(Qt.TextFormat.RichText) vbox.addWidget(label) hbox = QHBoxLayout() @@ -181,7 +181,7 @@ class _BackendProblemChecker: status = dialog.exec() self._save_manager.save_all(is_exit=True) - if status in [_Result.quit, QDialog.Rejected]: + if status in [_Result.quit, QDialog.DialogCode.Rejected]: pass elif status == _Result.restart_webkit: quitter.instance.restart(override_args={'backend': 'webkit'}) @@ -312,7 +312,7 @@ class _BackendProblemChecker: errbox = msgbox.msgbox(parent=None, title="SSL error", text="Could not initialize SSL support.", - icon=QMessageBox.Critical, + icon=QMessageBox.Icon.Critical, plain_text=False) errbox.exec() sys.exit(usertypes.Exit.err_init) @@ -338,7 +338,7 @@ class _BackendProblemChecker: errbox = msgbox.msgbox(parent=None, title="No backend library found!", text=text, - icon=QMessageBox.Critical, + icon=QMessageBox.Icon.Critical, plain_text=False) errbox.exec() sys.exit(usertypes.Exit.err_init) diff --git a/qutebrowser/misc/consolewidget.py b/qutebrowser/misc/consolewidget.py index 1f2dc3cfd..b2c2b4571 100644 --- a/qutebrowser/misc/consolewidget.py +++ b/qutebrowser/misc/consolewidget.py @@ -92,13 +92,13 @@ class ConsoleLineEdit(miscwidgets.CommandLineEdit): def keyPressEvent(self, e): """Override keyPressEvent to handle special keypresses.""" - if e.key() == Qt.Key_Up: + if e.key() == Qt.Key.Key_Up: self.history_prev() e.accept() - elif e.key() == Qt.Key_Down: + elif e.key() == Qt.Key.Key_Down: self.history_next() e.accept() - elif e.modifiers() & Qt.ControlModifier and e.key() == Qt.Key_C: + elif e.modifiers() & Qt.KeyboardModifier.ControlModifier and e.key() == Qt.Key.Key_C: self.setText('') e.accept() else: @@ -113,7 +113,7 @@ class ConsoleTextEdit(QTextEdit): super().__init__(parent) self.setAcceptRichText(False) self.setReadOnly(True) - self.setFocusPolicy(Qt.ClickFocus) + self.setFocusPolicy(Qt.FocusPolicy.ClickFocus) def __repr__(self): return utils.get_repr(self) @@ -124,7 +124,7 @@ class ConsoleTextEdit(QTextEdit): We can't use Qt's way to append stuff because that inserts weird newlines. """ - self.moveCursor(QTextCursor.End) + self.moveCursor(QTextCursor.MoveOperation.End) self.insertPlainText(text) scrollbar = self.verticalScrollBar() scrollbar.setValue(scrollbar.maximum()) diff --git a/qutebrowser/misc/crashdialog.py b/qutebrowser/misc/crashdialog.py index b4ff574e7..b3998cf27 100644 --- a/qutebrowser/misc/crashdialog.py +++ b/qutebrowser/misc/crashdialog.py @@ -47,8 +47,8 @@ class Result(enum.IntEnum): """The result code returned by the crash dialog.""" - restore = QDialog.Accepted + 1 - no_restore = QDialog.Accepted + 2 + restore = QDialog.DialogCode.Accepted + 1 + no_restore = QDialog.DialogCode.Accepted + 2 def parse_fatal_stacktrace(text): @@ -149,7 +149,7 @@ class _CrashDialog(QDialog): self._debug_log = QTextEdit() self._debug_log.setTabChangesFocus(True) self._debug_log.setAcceptRichText(False) - self._debug_log.setLineWrapMode(QTextEdit.NoWrap) + self._debug_log.setLineWrapMode(QTextEdit.LineWrapMode.NoWrap) self._debug_log.hide() self._fold = miscwidgets.DetailFold("Show log", self) self._fold.toggled.connect(self._debug_log.setVisible) @@ -165,7 +165,7 @@ class _CrashDialog(QDialog): def keyPressEvent(self, e): """Prevent closing :report dialogs when pressing <Escape>.""" - if config.val.input.escape_quits_reporter or e.key() != Qt.Key_Escape: + if config.val.input.escape_quits_reporter or e.key() != Qt.Key.Key_Escape: super().keyPressEvent(e) def __repr__(self): @@ -201,7 +201,7 @@ class _CrashDialog(QDialog): self._lbl = QLabel() self._lbl.setWordWrap(True) self._lbl.setOpenExternalLinks(True) - self._lbl.setTextInteractionFlags(Qt.LinksAccessibleByMouse) + self._lbl.setTextInteractionFlags(Qt.TextInteractionFlag.LinksAccessibleByMouse) self._vbox.addWidget(self._lbl) def _init_checkboxes(self): @@ -215,12 +215,12 @@ class _CrashDialog(QDialog): self._btn_report = QPushButton("Report") self._btn_report.setDefault(True) self._btn_report.clicked.connect(self.on_report_clicked) - self._btn_box.addButton(self._btn_report, QDialogButtonBox.AcceptRole) + self._btn_box.addButton(self._btn_report, QDialogButtonBox.ButtonRole.AcceptRole) self._btn_cancel = QPushButton("Don't report") self._btn_cancel.setAutoDefault(False) self._btn_cancel.clicked.connect(self.finish) - self._btn_box.addButton(self._btn_cancel, QDialogButtonBox.RejectRole) + self._btn_box.addButton(self._btn_cancel, QDialogButtonBox.ButtonRole.RejectRole) def _init_info_text(self): """Add an info text encouraging the user to report crashes.""" @@ -492,7 +492,7 @@ class FatalCrashDialog(_CrashDialog): def __init__(self, debug, text, parent=None): super().__init__(debug, parent) self._log = text - self.setAttribute(Qt.WA_DeleteOnClose) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) self._set_crash_info() self._type, self._func = parse_fatal_stacktrace(self._log) @@ -557,7 +557,7 @@ class FatalCrashDialog(_CrashDialog): "spend on developing qutebrowser instead.\n\nPlease " "help making qutebrowser better by providing more " "information, or don't report this.", - icon=QMessageBox.Critical) + icon=QMessageBox.Icon.Critical) else: super().on_report_clicked() @@ -574,7 +574,7 @@ class ReportDialog(_CrashDialog): def __init__(self, pages, cmdhist, qobjects, parent=None): super().__init__(False, parent) - self.setAttribute(Qt.WA_DeleteOnClose) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) self._pages = pages self._cmdhist = cmdhist self._qobjects = qobjects diff --git a/qutebrowser/misc/crashsignal.py b/qutebrowser/misc/crashsignal.py index 46c95abf1..a0144e26d 100644 --- a/qutebrowser/misc/crashsignal.py +++ b/qutebrowser/misc/crashsignal.py @@ -135,7 +135,7 @@ class CrashHandler(QObject): for tab in tabbed_browser.widgets(): try: urlstr = tab.url().toString( - QUrl.RemovePassword | QUrl.FullyEncoded) + QUrl.UrlFormattingOption.RemovePassword | QUrl.ComponentFormattingOption.FullyEncoded) if urlstr: win_pages.append(urlstr) except Exception: @@ -359,7 +359,7 @@ class SignalHandler(QObject): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) self._notifier = QSocketNotifier(cast(sip.voidptr, read_fd), - QSocketNotifier.Read, + QSocketNotifier.Type.Read, self) self._notifier.activated.connect(self.handle_signal_wakeup) self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd) diff --git a/qutebrowser/misc/earlyinit.py b/qutebrowser/misc/earlyinit.py index ddbb8f746..16a06896e 100644 --- a/qutebrowser/misc/earlyinit.py +++ b/qutebrowser/misc/earlyinit.py @@ -91,9 +91,9 @@ def _die(message, exception=None): else: if exception is not None: message = message.replace('%ERROR%', str(exception)) - msgbox = QMessageBox(QMessageBox.Critical, "qutebrowser: Fatal error!", + msgbox = QMessageBox(QMessageBox.Icon.Critical, "qutebrowser: Fatal error!", message) - msgbox.setTextFormat(Qt.RichText) + msgbox.setTextFormat(Qt.TextFormat.RichText) msgbox.resize(msgbox.sizeHint()) msgbox.exec() app.quit() diff --git a/qutebrowser/misc/editor.py b/qutebrowser/misc/editor.py index faa1a0323..1c4c6ca03 100644 --- a/qutebrowser/misc/editor.py +++ b/qutebrowser/misc/editor.py @@ -105,7 +105,7 @@ class ExternalEditor(QObject): return log.procs.debug("Editor closed") - if exitstatus != QProcess.NormalExit: + if exitstatus != QProcess.ExitStatus.NormalExit: # No error/cleanup here, since we already handle this in # on_proc_error. return diff --git a/qutebrowser/misc/elf.py b/qutebrowser/misc/elf.py index b3a38a40e..5e63f2380 100644 --- a/qutebrowser/misc/elf.py +++ b/qutebrowser/misc/elf.py @@ -314,7 +314,7 @@ def parse_webenginecore() -> Optional[Versions]: # Flatpak has Qt in /usr/lib/x86_64-linux-gnu, but QtWebEngine in /app/lib. library_path = pathlib.Path("/app/lib") else: - library_path = pathlib.Path(QLibraryInfo.location(QLibraryInfo.LibrariesPath)) + library_path = pathlib.Path(QLibraryInfo.location(QLibraryInfo.LibraryLocation.LibrariesPath)) library_name = sorted(library_path.glob('libQt5WebEngineCore.so*')) if not library_name: diff --git a/qutebrowser/misc/guiprocess.py b/qutebrowser/misc/guiprocess.py index 0f8843f9e..8fcfb2803 100644 --- a/qutebrowser/misc/guiprocess.py +++ b/qutebrowser/misc/guiprocess.py @@ -94,7 +94,7 @@ class ProcessOutcome: """ assert self.status is not None, "Process didn't finish yet" assert self.code is not None - return self.status == QProcess.NormalExit and self.code == 0 + return self.status == QProcess.ExitStatus.NormalExit and self.code == 0 def __str__(self) -> str: if self.running: @@ -105,12 +105,12 @@ class ProcessOutcome: assert self.status is not None assert self.code is not None - if self.status == QProcess.CrashExit: + if self.status == QProcess.ExitStatus.CrashExit: return f"{self.what.capitalize()} crashed." elif self.was_successful(): return f"{self.what.capitalize()} exited successfully." - assert self.status == QProcess.NormalExit + assert self.status == QProcess.ExitStatus.NormalExit # We call this 'status' here as it makes more sense to the user - # it's actually 'code'. return f"{self.what.capitalize()} exited with status {self.code}." @@ -124,7 +124,7 @@ class ProcessOutcome: return 'running' elif self.status is None: return 'not started' - elif self.status == QProcess.CrashExit: + elif self.status == QProcess.ExitStatus.CrashExit: return 'crashed' elif self.was_successful(): return 'successful' @@ -177,7 +177,7 @@ class GUIProcess(QObject): self.stderr: str = "" self._cleanup_timer = usertypes.Timer(self, 'process-cleanup') - self._cleanup_timer.setTimerType(Qt.VeryCoarseTimer) + self._cleanup_timer.setTimerType(Qt.TimerType.VeryCoarseTimer) self._cleanup_timer.setInterval(3600 * 1000) # 1h self._cleanup_timer.timeout.connect(self._on_cleanup_timer) self._cleanup_timer.setSingleShot(True) @@ -254,17 +254,17 @@ class GUIProcess(QObject): @pyqtSlot(QProcess.ProcessError) def _on_error(self, error: QProcess.ProcessError) -> None: """Show a message if there was an error while spawning.""" - if error == QProcess.Crashed and not utils.is_windows: + if error == QProcess.ProcessError.Crashed and not utils.is_windows: # Already handled via ExitStatus in _on_finished return what = f"{self.what} {self.cmd!r}" error_descriptions = { - QProcess.FailedToStart: f"{what.capitalize()} failed to start", - QProcess.Crashed: f"{what.capitalize()} crashed", - QProcess.Timedout: f"{what.capitalize()} timed out", - QProcess.WriteError: f"Write error for {what}", - QProcess.ReadError: f"Read error for {what}", + QProcess.ProcessError.FailedToStart: f"{what.capitalize()} failed to start", + QProcess.ProcessError.Crashed: f"{what.capitalize()} crashed", + QProcess.ProcessError.Timedout: f"{what.capitalize()} timed out", + QProcess.ProcessError.WriteError: f"Write error for {what}", + QProcess.ProcessError.ReadError: f"Read error for {what}", } error_string = self._proc.errorString() msg = ': '.join([error_descriptions[error], error_string]) diff --git a/qutebrowser/misc/httpclient.py b/qutebrowser/misc/httpclient.py index cc61f8de5..da205ae50 100644 --- a/qutebrowser/misc/httpclient.py +++ b/qutebrowser/misc/httpclient.py @@ -35,8 +35,8 @@ class HTTPRequest(QNetworkRequest): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.setAttribute(QNetworkRequest.RedirectPolicyAttribute, - QNetworkRequest.NoLessSafeRedirectPolicy) + self.setAttribute(QNetworkRequest.Attribute.RedirectPolicyAttribute, + QNetworkRequest.RedirectPolicy.NoLessSafeRedirectPolicy) class HTTPClient(QObject): @@ -78,7 +78,7 @@ class HTTPClient(QObject): data = {} encoded_data = urllib.parse.urlencode(data).encode('utf-8') request = HTTPRequest(url) - request.setHeader(QNetworkRequest.ContentTypeHeader, + request.setHeader(QNetworkRequest.KnownHeaders.ContentTypeHeader, 'application/x-www-form-urlencoded;charset=utf-8') reply = self._nam.post(request, encoded_data) self._handle_reply(reply) @@ -118,7 +118,7 @@ class HTTPClient(QObject): if timer is not None: timer.stop() timer.deleteLater() - if reply.error() != QNetworkReply.NoError: + if reply.error() != QNetworkReply.NetworkError.NoError: self.error.emit(reply.errorString()) return try: diff --git a/qutebrowser/misc/ipc.py b/qutebrowser/misc/ipc.py index 4d061244c..d9bbefbbe 100644 --- a/qutebrowser/misc/ipc.py +++ b/qutebrowser/misc/ipc.py @@ -188,7 +188,7 @@ class IPCServer(QObject): self._atime_timer = usertypes.Timer(self, 'ipc-atime') self._atime_timer.setInterval(ATIME_INTERVAL) self._atime_timer.timeout.connect(self.update_atime) - self._atime_timer.setTimerType(Qt.VeryCoarseTimer) + self._atime_timer.setTimerType(Qt.TimerType.VeryCoarseTimer) self._server = QLocalServer(self) self._server.newConnection.connect(self.handle_connection) @@ -204,7 +204,7 @@ class IPCServer(QObject): # Thus, we only do so on Windows, and handle permissions manually in # listen() on Linux. log.ipc.debug("Calling setSocketOptions") - self._server.setSocketOptions(QLocalServer.UserAccessOption) + self._server.setSocketOptions(QLocalServer.SocketOption.UserAccessOption) else: # pragma: no cover log.ipc.debug("Not calling setSocketOptions") @@ -223,7 +223,7 @@ class IPCServer(QObject): self._remove_server() ok = self._server.listen(self._socketname) if not ok: - if self._server.serverError() == QAbstractSocket.AddressInUseError: + if self._server.serverError() == QAbstractSocket.SocketError.AddressInUseError: raise AddressInUseError(self._server) raise ListenError(self._server) @@ -248,7 +248,7 @@ class IPCServer(QObject): log.ipc.debug("Socket 0x{:x}: error {}: {}".format( id(self._socket), self._socket.error(), self._socket.errorString())) - if err != QLocalSocket.PeerClosedError: + if err != QLocalSocket.LocalSocketError.PeerClosedError: raise SocketError("handling IPC connection", self._socket) @pyqtSlot() @@ -275,11 +275,13 @@ class IPCServer(QObject): self.on_ready_read() socket.error.connect(self.on_error) if socket.error() not in [ # type: ignore[operator] - QLocalSocket.UnknownSocketError, QLocalSocket.PeerClosedError]: + QLocalSocket.LocalSocketError.UnknownSocketError, + QLocalSocket.LocalSocketError.PeerClosedError + ]: log.ipc.debug("We got an error immediately.") self.on_error(socket.error()) # type: ignore[operator] socket.disconnected.connect(self.on_disconnected) - if socket.state() == QLocalSocket.UnconnectedState: + if socket.state() == QLocalSocket.LocalSocketState.UnconnectedState: log.ipc.debug("Socket was disconnected immediately.") self.on_disconnected() @@ -490,15 +492,15 @@ def send_to_running_instance(socketname, command, target_arg, *, socket=None): log.ipc.debug("Writing: {!r}".format(data)) socket.writeData(data) socket.waitForBytesWritten(WRITE_TIMEOUT) - if socket.error() != QLocalSocket.UnknownSocketError: + if socket.error() != QLocalSocket.LocalSocketError.UnknownSocketError: raise SocketError("writing to running instance", socket) socket.disconnectFromServer() - if socket.state() != QLocalSocket.UnconnectedState: + if socket.state() != QLocalSocket.LocalSocketState.UnconnectedState: socket.waitForDisconnected(CONNECT_TIMEOUT) return True else: - if socket.error() not in [QLocalSocket.ConnectionRefusedError, - QLocalSocket.ServerNotFoundError]: + if socket.error() not in [QLocalSocket.LocalSocketError.ConnectionRefusedError, + QLocalSocket.LocalSocketError.ServerNotFoundError]: raise SocketError("connecting to running instance", socket) log.ipc.debug("No existing instance present (error {})".format( socket.error())) diff --git a/qutebrowser/misc/keyhintwidget.py b/qutebrowser/misc/keyhintwidget.py index 2f538cc19..beb6816d8 100644 --- a/qutebrowser/misc/keyhintwidget.py +++ b/qutebrowser/misc/keyhintwidget.py @@ -64,9 +64,9 @@ class KeyHintView(QLabel): def __init__(self, win_id, parent=None): super().__init__(parent) - self.setTextFormat(Qt.RichText) + self.setTextFormat(Qt.TextFormat.RichText) self._win_id = win_id - self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Minimum) + self.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum) self.hide() self._show_timer = usertypes.Timer(self, 'keyhint_show') self._show_timer.timeout.connect(self.show) diff --git a/qutebrowser/misc/miscwidgets.py b/qutebrowser/misc/miscwidgets.py index 473271b24..928ab6b18 100644 --- a/qutebrowser/misc/miscwidgets.py +++ b/qutebrowser/misc/miscwidgets.py @@ -49,11 +49,11 @@ class MinimalLineEditMixin: """ ) self.setAttribute( # type: ignore[attr-defined] - Qt.WA_MacShowFocusRect, False) + Qt.WidgetAttribute.WA_MacShowFocusRect, False) def keyPressEvent(self, e): """Override keyPressEvent to paste primary selection on Shift + Ins.""" - if e.key() == Qt.Key_Insert and e.modifiers() == Qt.ShiftModifier: + if e.key() == Qt.Key.Key_Insert and e.modifiers() == Qt.KeyboardModifier.ShiftModifier: try: text = utils.get_clipboard(selection=True, fallback=True) except utils.ClipboardError: @@ -137,9 +137,9 @@ class _CommandValidator(QValidator): A tuple (status, string, pos) as a QValidator should. """ if self.prompt is None or string.startswith(self.prompt): - return (QValidator.Acceptable, string, pos) + return (QValidator.State.Acceptable, string, pos) else: - return (QValidator.Invalid, string, pos) + return (QValidator.State.Invalid, string, pos) class DetailFold(QWidget): @@ -181,7 +181,7 @@ class DetailFold(QWidget): Args: e: The QMouseEvent. """ - if e.button() == Qt.LeftButton: + if e.button() == Qt.MouseButton.LeftButton: e.accept() self.toggle() else: @@ -219,9 +219,9 @@ class _FoldArrow(QWidget): opt.initFrom(self) painter = QPainter(self) if self._folded: - elem = QStyle.PE_IndicatorArrowRight + elem = QStyle.PrimitiveElement.PE_IndicatorArrowRight else: - elem = QStyle.PE_IndicatorArrowDown + elem = QStyle.PrimitiveElement.PE_IndicatorArrowDown self.style().drawPrimitive(elem, opt, painter, self) def minimumSizeHint(self): @@ -387,10 +387,10 @@ class InspectorSplitter(QSplitter): self._inspector_idx = 0 self._main_idx = 1 - self.setOrientation(Qt.Horizontal + self.setOrientation(Qt.Orientation.Horizontal if position in [inspector.Position.left, inspector.Position.right] - else Qt.Vertical) + else Qt.Orientation.Vertical) self.insertWidget(self._inspector_idx, inspector_widget) self._position = position self._load_preferred_size() @@ -405,7 +405,7 @@ class InspectorSplitter(QSplitter): def _load_preferred_size(self) -> None: """Load the preferred size of the inspector widget.""" assert self._position is not None - full = (self.width() if self.orientation() == Qt.Horizontal + full = (self.width() if self.orientation() == Qt.Orientation.Horizontal else self.height()) # If we first open the inspector with a window size of < 300px @@ -489,7 +489,7 @@ class KeyTesterWidget(QWidget): def __init__(self, parent=None): super().__init__(parent) - self.setAttribute(Qt.WA_DeleteOnClose) + self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) self._layout = QHBoxLayout(self) self._label = QLabel(text="Waiting for keypress...") self._layout.addWidget(self._label) diff --git a/qutebrowser/misc/msgbox.py b/qutebrowser/misc/msgbox.py index a0f0170c4..45ad2d44a 100644 --- a/qutebrowser/misc/msgbox.py +++ b/qutebrowser/misc/msgbox.py @@ -34,7 +34,7 @@ class DummyBox: pass -def msgbox(parent, title, text, *, icon, buttons=QMessageBox.Ok, +def msgbox(parent, title, text, *, icon, buttons=QMessageBox.StandardButton.Ok, on_finished=None, plain_text=None): """Display a QMessageBox with the given icon. @@ -56,15 +56,15 @@ def msgbox(parent, title, text, *, icon, buttons=QMessageBox.Ok, return DummyBox() box = QMessageBox(parent) - box.setAttribute(Qt.WA_DeleteOnClose) + box.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose) box.setIcon(icon) box.setStandardButtons(buttons) if on_finished is not None: box.finished.connect(on_finished) if plain_text: - box.setTextFormat(Qt.PlainText) + box.setTextFormat(Qt.TextFormat.PlainText) elif plain_text is not None: - box.setTextFormat(Qt.RichText) + box.setTextFormat(Qt.TextFormat.RichText) box.setWindowTitle(title) box.setText(text) box.show() @@ -81,4 +81,4 @@ def information(*args, **kwargs): Return: A new QMessageBox. """ - return msgbox(*args, icon=QMessageBox.Information, **kwargs) + return msgbox(*args, icon=QMessageBox.Icon.Information, **kwargs) diff --git a/qutebrowser/misc/sessions.py b/qutebrowser/misc/sessions.py index 4547057c9..e33bb23c5 100644 --- a/qutebrowser/misc/sessions.py +++ b/qutebrowser/misc/sessions.py @@ -225,7 +225,7 @@ class SessionManager(QObject): # QtWebEngine user_data = None - data['last_visited'] = item.lastVisited().toString(Qt.ISODate) + data['last_visited'] = item.lastVisited().toString(Qt.DateFormat.ISODate) if tab.history.current_idx() == idx: pos = tab.scroller.pos_px() @@ -450,7 +450,7 @@ class SessionManager(QObject): if histentry.get("last_visited"): last_visited: Optional[QDateTime] = QDateTime.fromString( histentry.get("last_visited"), - Qt.ISODate, + Qt.DateFormat.ISODate, ) else: last_visited = None diff --git a/qutebrowser/utils/debug.py b/qutebrowser/utils/debug.py index 4836bb01b..832bc1e61 100644 --- a/qutebrowser/utils/debug.py +++ b/qutebrowser/utils/debug.py @@ -70,7 +70,7 @@ def log_signals(obj: QObject) -> QObject: for i in range(metaobj.methodCount()): meta_method = metaobj.method(i) qtutils.ensure_valid(meta_method) - if meta_method.methodType() == QMetaMethod.Signal: + if meta_method.methodType() == QMetaMethod.MethodType.Signal: name = meta_method.name().data().decode('ascii') if name != 'destroyed': signal = getattr(obj, name) @@ -149,8 +149,8 @@ def qflags_key(base: Type[_EnumValueType], klass: Type[_EnumValueType] = None) -> str: """Convert a Qt QFlags value to its keys as string. - Note: Passing a combined value (such as Qt.AlignCenter) will get the names - for the individual bits (e.g. Qt.AlignVCenter | Qt.AlignHCenter). FIXME + Note: Passing a combined value (such as Qt.AlignmentFlag.AlignCenter) will get the names + for the individual bits (e.g. Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignHCenter). FIXME https://github.com/qutebrowser/qutebrowser/issues/42 @@ -327,7 +327,7 @@ def _get_pyqt_objects(lines: MutableSequence[str], obj: QObject, depth: int = 0) -> None: """Recursive method for get_all_objects to get Qt objects.""" - for kid in obj.findChildren(QObject, '', Qt.FindDirectChildrenOnly): + for kid in obj.findChildren(QObject, '', Qt.FindChildOption.FindDirectChildrenOnly): lines.append(' ' * depth + repr(kid)) _get_pyqt_objects(lines, kid, depth + 1) diff --git a/qutebrowser/utils/error.py b/qutebrowser/utils/error.py index ffc428858..3a155a4fe 100644 --- a/qutebrowser/utils/error.py +++ b/qutebrowser/utils/error.py @@ -70,5 +70,5 @@ def handle_fatal_exc(exc: BaseException, msg_text = str(exc) if post_text: msg_text += '\n\n{}'.format(post_text) - msgbox = QMessageBox(QMessageBox.Critical, title, msg_text) + msgbox = QMessageBox(QMessageBox.Icon.Critical, title, msg_text) msgbox.exec() diff --git a/qutebrowser/utils/jinja.py b/qutebrowser/utils/jinja.py index 73f548888..5775b317b 100644 --- a/qutebrowser/utils/jinja.py +++ b/qutebrowser/utils/jinja.py @@ -114,7 +114,7 @@ class Environment(jinja2.Environment): url = QUrl('qute://resource') url.setPath('/' + path) urlutils.ensure_valid(url) - urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + urlstr = url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] return urlstr def _data_url(self, path: str) -> str: diff --git a/qutebrowser/utils/message.py b/qutebrowser/utils/message.py index 118c0196f..10183afee 100644 --- a/qutebrowser/utils/message.py +++ b/qutebrowser/utils/message.py @@ -241,7 +241,7 @@ class GlobalMessageBridge(QObject): arg 1: Whether to block (True) or ask async (False). IMPORTANT: Slots need to be connected to this signal via - a Qt.DirectConnection! + a Qt.ConnectionType.DirectConnection! mode_left: Emitted when a keymode was left in any window. """ diff --git a/qutebrowser/utils/qtutils.py b/qutebrowser/utils/qtutils.py index ef0de3425..d93555436 100644 --- a/qutebrowser/utils/qtutils.py +++ b/qutebrowser/utils/qtutils.py @@ -173,14 +173,14 @@ def ensure_valid(obj: Validatable) -> None: def check_qdatastream(stream: QDataStream) -> None: """Check the status of a QDataStream and raise OSError if it's not ok.""" status_to_str = { - QDataStream.Ok: "The data stream is operating normally.", - QDataStream.ReadPastEnd: ("The data stream has read past the end of " + QDataStream.Status.Ok: "The data stream is operating normally.", + QDataStream.Status.ReadPastEnd: ("The data stream has read past the end of " "the data in the underlying device."), - QDataStream.ReadCorruptData: "The data stream has read corrupt data.", - QDataStream.WriteFailed: ("The data stream cannot write to the " + QDataStream.Status.ReadCorruptData: "The data stream has read corrupt data.", + QDataStream.Status.WriteFailed: ("The data stream cannot write to the " "underlying device."), } - if stream.status() != QDataStream.Ok: + if stream.status() != QDataStream.Status.Ok: raise OSError(status_to_str[stream.status()]) @@ -196,14 +196,14 @@ _QtSerializableType = Union[ def serialize(obj: _QtSerializableType) -> QByteArray: """Serialize an object into a QByteArray.""" data = QByteArray() - stream = QDataStream(data, QIODevice.WriteOnly) + stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly) serialize_stream(stream, obj) return data def deserialize(data: QByteArray, obj: _QtSerializableType) -> None: """Deserialize an object from a QByteArray.""" - stream = QDataStream(data, QIODevice.ReadOnly) + stream = QDataStream(data, QIODevice.OpenModeFlag.ReadOnly) deserialize_stream(stream, obj) @@ -233,7 +233,7 @@ def savefile_open( f = QSaveFile(filename) cancelled = False try: - open_ok = f.open(QIODevice.WriteOnly) + open_ok = f.open(QIODevice.OpenModeFlag.WriteOnly) if not open_ok: raise QtOSError(f) @@ -464,7 +464,7 @@ class EventLoop(QEventLoop): def exec( self, flags: QEventLoop.ProcessEventsFlags = - cast(QEventLoop.ProcessEventsFlags, QEventLoop.AllEvents) + cast(QEventLoop.ProcessEventsFlags, QEventLoop.ProcessEventsFlag.AllEvents) ) -> int: """Override exec_ to raise an exception when re-running.""" if self._executing: @@ -503,7 +503,7 @@ def interpolate_color( start: QColor, end: QColor, percent: int, - colorspace: Optional[QColor.Spec] = QColor.Rgb + colorspace: Optional[QColor.Spec] = QColor.Spec.Rgb ) -> QColor: """Get an interpolated color value. @@ -528,17 +528,17 @@ def interpolate_color( return QColor(*start.getRgb()) out = QColor() - if colorspace == QColor.Rgb: + if colorspace == QColor.Spec.Rgb: r1, g1, b1, a1 = start.getRgb() r2, g2, b2, a2 = end.getRgb() components = _get_color_percentage(r1, g1, b1, a1, r2, g2, b2, a2, percent) out.setRgb(*components) - elif colorspace == QColor.Hsv: + elif colorspace == QColor.Spec.Hsv: h1, s1, v1, a1 = start.getHsv() h2, s2, v2, a2 = end.getHsv() components = _get_color_percentage(h1, s1, v1, a1, h2, s2, v2, a2, percent) out.setHsv(*components) - elif colorspace == QColor.Hsl: + elif colorspace == QColor.Spec.Hsl: h1, s1, l1, a1 = start.getHsl() h2, s2, l2, a2 = end.getHsl() components = _get_color_percentage(h1, s1, l1, a1, h2, s2, l2, a2, percent) diff --git a/qutebrowser/utils/standarddir.py b/qutebrowser/utils/standarddir.py index 659396b1c..e63b43548 100644 --- a/qutebrowser/utils/standarddir.py +++ b/qutebrowser/utils/standarddir.py @@ -77,12 +77,12 @@ def _unset_organization() -> Iterator[None]: def _init_config(args: Optional[argparse.Namespace]) -> None: """Initialize the location for configs.""" - typ = QStandardPaths.ConfigLocation + typ = QStandardPaths.StandardLocation.ConfigLocation path = _from_args(typ, args) if path is None: if utils.is_windows: app_data_path = _writable_location( - QStandardPaths.AppDataLocation) + QStandardPaths.StandardLocation.AppDataLocation) path = os.path.join(app_data_path, 'config') else: path = _writable_location(typ) @@ -128,7 +128,7 @@ def config_py() -> str: def _init_data(args: Optional[argparse.Namespace]) -> None: """Initialize the location for data.""" - typ = QStandardPaths.AppDataLocation + typ = QStandardPaths.StandardLocation.AppDataLocation path = _from_args(typ, args) if path is None: if utils.is_windows: @@ -136,7 +136,7 @@ def _init_data(args: Optional[argparse.Namespace]) -> None: path = os.path.join(app_data_path, 'data') elif sys.platform.startswith('haiku'): # HaikuOS returns an empty value for AppDataLocation - config_path = _writable_location(QStandardPaths.ConfigLocation) + config_path = _writable_location(QStandardPaths.StandardLocation.ConfigLocation) path = os.path.join(config_path, 'data') else: path = _writable_location(typ) @@ -169,12 +169,12 @@ def data(system: bool = False) -> str: def _init_cache(args: Optional[argparse.Namespace]) -> None: """Initialize the location for the cache.""" - typ = QStandardPaths.CacheLocation + typ = QStandardPaths.StandardLocation.CacheLocation path = _from_args(typ, args) if path is None: if utils.is_windows: # Local, not Roaming! - data_path = _writable_location(QStandardPaths.AppLocalDataLocation) + data_path = _writable_location(QStandardPaths.StandardLocation.AppLocalDataLocation) path = os.path.join(data_path, 'cache') else: path = _writable_location(typ) @@ -193,7 +193,7 @@ def _init_download(args: Optional[argparse.Namespace]) -> None: Note this is only the default directory as found by Qt. Therefore, we also don't create it. """ - typ = QStandardPaths.DownloadLocation + typ = QStandardPaths.StandardLocation.DownloadLocation path = _from_args(typ, args) if path is None: path = _writable_location(typ) @@ -208,9 +208,9 @@ def _init_runtime(args: Optional[argparse.Namespace]) -> None: """Initialize location for runtime data.""" if utils.is_mac or utils.is_windows: # RuntimeLocation is a weird path on macOS and Windows. - typ = QStandardPaths.TempLocation + typ = QStandardPaths.StandardLocation.TempLocation else: - typ = QStandardPaths.RuntimeLocation + typ = QStandardPaths.StandardLocation.RuntimeLocation path = _from_args(typ, args) if path is None: @@ -218,10 +218,10 @@ def _init_runtime(args: Optional[argparse.Namespace]) -> None: path = _writable_location(typ) except EmptyValueError: # Fall back to TempLocation when RuntimeLocation is misconfigured - if typ == QStandardPaths.TempLocation: + if typ == QStandardPaths.StandardLocation.TempLocation: raise path = _writable_location( # pragma: no cover - QStandardPaths.TempLocation) + QStandardPaths.StandardLocation.TempLocation) # This is generic, but per-user. # _writable_location makes sure we have a qutebrowser-specific subdir. @@ -263,10 +263,10 @@ def _writable_location(typ: QStandardPaths.StandardLocation) -> str: # Types we are sure we handle correctly below. assert typ in [ - QStandardPaths.ConfigLocation, QStandardPaths.AppLocalDataLocation, - QStandardPaths.CacheLocation, QStandardPaths.DownloadLocation, - QStandardPaths.RuntimeLocation, QStandardPaths.TempLocation, - QStandardPaths.AppDataLocation], typ_str + QStandardPaths.StandardLocation.ConfigLocation, QStandardPaths.StandardLocation.AppLocalDataLocation, + QStandardPaths.StandardLocation.CacheLocation, QStandardPaths.StandardLocation.DownloadLocation, + QStandardPaths.StandardLocation.RuntimeLocation, QStandardPaths.StandardLocation.TempLocation, + QStandardPaths.StandardLocation.AppDataLocation], typ_str with _unset_organization(): path = QStandardPaths.writableLocation(typ) @@ -281,7 +281,7 @@ def _writable_location(typ: QStandardPaths.StandardLocation) -> str: # Add the application name to the given path if needed. # This is in order for this to work without a QApplication (and thus # QStandardsPaths not knowing the application name). - if (typ != QStandardPaths.DownloadLocation and + if (typ != QStandardPaths.StandardLocation.DownloadLocation and path.split(os.sep)[-1] != APPNAME): path = os.path.join(path, APPNAME) @@ -298,12 +298,12 @@ def _from_args( The overridden path, or None if there is no override. """ basedir_suffix = { - QStandardPaths.ConfigLocation: 'config', - QStandardPaths.AppDataLocation: 'data', - QStandardPaths.AppLocalDataLocation: 'data', - QStandardPaths.CacheLocation: 'cache', - QStandardPaths.DownloadLocation: 'download', - QStandardPaths.RuntimeLocation: 'runtime', + QStandardPaths.StandardLocation.ConfigLocation: 'config', + QStandardPaths.StandardLocation.AppDataLocation: 'data', + QStandardPaths.StandardLocation.AppLocalDataLocation: 'data', + QStandardPaths.StandardLocation.CacheLocation: 'cache', + QStandardPaths.StandardLocation.DownloadLocation: 'download', + QStandardPaths.StandardLocation.RuntimeLocation: 'runtime', } if getattr(args, 'basedir', None) is None: diff --git a/qutebrowser/utils/urlutils.py b/qutebrowser/utils/urlutils.py index bebdf96df..6fa70dfc9 100644 --- a/qutebrowser/utils/urlutils.py +++ b/qutebrowser/utils/urlutils.py @@ -522,7 +522,7 @@ def file_url(path: str) -> str: path: The absolute path to the local file """ url = QUrl.fromLocalFile(path) - return url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + return url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] def data_url(mimetype: str, data: bytes) -> QUrl: @@ -544,11 +544,11 @@ def safe_display_string(qurl: QUrl) -> str: """ ensure_valid(qurl) - host = qurl.host(QUrl.FullyEncoded) + host = qurl.host(QUrl.ComponentFormattingOption.FullyEncoded) assert '..' not in host, qurl # https://bugreports.qt.io/browse/QTBUG-60364 for part in host.split('.'): - url_host = qurl.host(QUrl.FullyDecoded) + url_host = qurl.host(QUrl.ComponentFormattingOption.FullyDecoded) if part.startswith('xn--') and host != url_host: return '({}) {}'.format(host, qurl.toDisplayString()) @@ -581,10 +581,10 @@ def proxy_from_url(url: QUrl) -> Union[QNetworkProxy, pac.PACFetcher]: return fetcher types = { - 'http': QNetworkProxy.HttpProxy, - 'socks': QNetworkProxy.Socks5Proxy, - 'socks5': QNetworkProxy.Socks5Proxy, - 'direct': QNetworkProxy.NoProxy, + 'http': QNetworkProxy.ProxyType.HttpProxy, + 'socks': QNetworkProxy.ProxyType.Socks5Proxy, + 'socks5': QNetworkProxy.ProxyType.Socks5Proxy, + 'direct': QNetworkProxy.ProxyType.NoProxy, } if scheme not in types: raise InvalidProxyTypeError(scheme) @@ -613,7 +613,7 @@ def parse_javascript_url(url: QUrl) -> str: raise Error("URL contains unexpected components: {}" .format(url.authority())) - urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type] + urlstr = url.toString(QUrl.ComponentFormattingOption.FullyEncoded) # type: ignore[arg-type] urlstr = urllib.parse.unquote(urlstr) code = urlstr[len('javascript:'):] diff --git a/qutebrowser/utils/utils.py b/qutebrowser/utils/utils.py index 404f903f1..ddd82cb76 100644 --- a/qutebrowser/utils/utils.py +++ b/qutebrowser/utils/utils.py @@ -536,7 +536,7 @@ def set_clipboard(data: str, selection: bool = False) -> None: log.misc.debug("Setting fake {}: {}".format(what, json.dumps(data))) fake_clipboard = data else: - mode = QClipboard.Selection if selection else QClipboard.Clipboard + mode = QClipboard.Mode.Selection if selection else QClipboard.Mode.Clipboard QApplication.clipboard().setText(data, mode=mode) @@ -562,7 +562,7 @@ def get_clipboard(selection: bool = False, fallback: bool = False) -> str: data = fake_clipboard fake_clipboard = None else: - mode = QClipboard.Selection if selection else QClipboard.Clipboard + mode = QClipboard.Mode.Selection if selection else QClipboard.Mode.Clipboard data = QApplication.clipboard().text(mode=mode) target = "Primary selection" if selection else "Clipboard" diff --git a/qutebrowser/utils/version.py b/qutebrowser/utils/version.py index 4303d40e8..1a986f9b0 100644 --- a/qutebrowser/utils/version.py +++ b/qutebrowser/utils/version.py @@ -849,8 +849,8 @@ def version_info() -> str: "Imported from {}".format(importpath), "Using Python from {}".format(sys.executable), "Qt library executable path: {}, data path: {}".format( - QLibraryInfo.location(QLibraryInfo.LibraryExecutablesPath), - QLibraryInfo.location(QLibraryInfo.DataPath) + QLibraryInfo.location(QLibraryInfo.LibraryLocation.LibraryExecutablesPath), + QLibraryInfo.location(QLibraryInfo.LibraryLocation.DataPath) ) ] diff --git a/tests/end2end/fixtures/notificationserver.py b/tests/end2end/fixtures/notificationserver.py index ce58d87cd..3cc1be9d8 100644 --- a/tests/end2end/fixtures/notificationserver.py +++ b/tests/end2end/fixtures/notificationserver.py @@ -82,7 +82,7 @@ class TestNotificationServer(QObject): notification.DBusNotificationAdapter.PATH, notification.DBusNotificationAdapter.INTERFACE, self, - QDBusConnection.ExportAllSlots, + QDBusConnection.RegisterOption.ExportAllSlots, ) return True @@ -151,7 +151,7 @@ class TestNotificationServer(QObject): assert channel_count == (4 if has_alpha else 3) assert bytes_per_line >= width * channel_count - qimage_format = QImage.Format_RGBA8888 if has_alpha else QImage.Format_RGB888 + qimage_format = QImage.Format.Format_RGBA8888 if has_alpha else QImage.Format.Format_RGB888 img = QImage(data, width, height, bytes_per_line, qimage_format) assert not img.isNull() assert img.width() == width @@ -196,7 +196,7 @@ class TestNotificationServer(QObject): @pyqtSlot(QDBusMessage, result="uint") def Notify(self, dbus_message: QDBusMessage) -> int: assert dbus_message.signature() == 'susssasa{sv}i' - assert dbus_message.type() == QDBusMessage.MethodCallMessage + assert dbus_message.type() == QDBusMessage.MessageType.MethodCallMessage message = self._parse_notify_args(*dbus_message.arguments()) @@ -213,7 +213,7 @@ class TestNotificationServer(QObject): def GetCapabilities(self, message: QDBusMessage) -> List[str]: assert not message.signature() assert not message.arguments() - assert message.type() == QDBusMessage.MethodCallMessage + assert message.type() == QDBusMessage.MessageType.MethodCallMessage capabilities = ["actions", "x-kde-origin-name"] if self.supports_body_markup: @@ -232,7 +232,7 @@ class TestNotificationServer(QObject): @pyqtSlot(QDBusMessage) def CloseNotification(self, dbus_message: QDBusMessage) -> None: assert dbus_message.signature() == 'u' - assert dbus_message.type() == QDBusMessage.MethodCallMessage + assert dbus_message.type() == QDBusMessage.MessageType.MethodCallMessage message_id = dbus_message.arguments()[0] self.messages[message_id].closed_via_web = True diff --git a/tests/end2end/fixtures/quteprocess.py b/tests/end2end/fixtures/quteprocess.py index da244620b..a0d0b022c 100644 --- a/tests/end2end/fixtures/quteprocess.py +++ b/tests/end2end/fixtures/quteprocess.py @@ -849,7 +849,7 @@ class QuteProc(testprocess.Process): # We really need the same representation that the webview uses in # its __repr__ - url = utils.elide(qurl.toDisplayString(QUrl.EncodeUnicode), 100) + url = utils.elide(qurl.toDisplayString(QUrl.ComponentFormattingOption.EncodeUnicode), 100) assert url pattern = re.compile( diff --git a/tests/end2end/fixtures/test_testprocess.py b/tests/end2end/fixtures/test_testprocess.py index 5ce11f0b2..dd16b8b8f 100644 --- a/tests/end2end/fixtures/test_testprocess.py +++ b/tests/end2end/fixtures/test_testprocess.py @@ -53,7 +53,7 @@ class PythonProcess(testprocess.Process): def __init__(self, request): super().__init__(request) - self.proc.setReadChannel(QProcess.StandardOutput) + self.proc.setReadChannel(QProcess.ProcessChannel.StandardOutput) self.code = None def _parse_line(self, line): diff --git a/tests/end2end/fixtures/testprocess.py b/tests/end2end/fixtures/testprocess.py index dfe2802d2..78c08a4c0 100644 --- a/tests/end2end/fixtures/testprocess.py +++ b/tests/end2end/fixtures/testprocess.py @@ -151,7 +151,7 @@ class Process(QObject): self._invalid = [] self._data = [] self.proc = QProcess() - self.proc.setReadChannel(QProcess.StandardError) + self.proc.setReadChannel(QProcess.ProcessChannel.StandardError) self.exit_expected = None # Not started at all yet def _log(self, line): @@ -325,7 +325,7 @@ class Process(QObject): def is_running(self): """Check if the process is currently running.""" - return self.proc.state() == QProcess.Running + return self.proc.state() == QProcess.ProcessState.Running def _match_data(self, value, expected): """Helper for wait_for to match a given value. diff --git a/tests/end2end/test_invocations.py b/tests/end2end/test_invocations.py index 7169a7bec..cacd39f52 100644 --- a/tests/end2end/test_invocations.py +++ b/tests/end2end/test_invocations.py @@ -262,7 +262,7 @@ def test_version(request): # can't use quteproc_new here because it's confused by # early process termination proc = QProcess() - proc.setProcessChannelMode(QProcess.SeparateChannels) + proc.setProcessChannelMode(QProcess.ProcessChannelMode.SeparateChannels) proc.start(sys.executable, args) ok = proc.waitForStarted(2000) @@ -275,7 +275,7 @@ def test_version(request): print(stderr) assert ok - assert proc.exitStatus() == QProcess.NormalExit + assert proc.exitStatus() == QProcess.ExitStatus.NormalExit match = re.search(r'^qutebrowser\s+v\d+(\.\d+)', stdout, re.MULTILINE) assert match is not None diff --git a/tests/helpers/fixtures.py b/tests/helpers/fixtures.py index fba2bf438..79a003f81 100644 --- a/tests/helpers/fixtures.py +++ b/tests/helpers/fixtures.py @@ -126,7 +126,7 @@ class FakeStatusBar(QWidget): self.hbox = QHBoxLayout(self) self.hbox.addStretch() self.hbox.setContentsMargins(0, 0, 0, 0) - self.setAttribute(Qt.WA_StyledBackground, True) + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) self.setStyleSheet('background-color: red;') def minimumSizeHint(self): @@ -434,7 +434,7 @@ def qnam(qapp): """Session-wide QNetworkAccessManager.""" from qutebrowser.qt.network import QNetworkAccessManager nam = QNetworkAccessManager() - nam.setNetworkAccessible(QNetworkAccessManager.NotAccessible) + nam.setNetworkAccessible(QNetworkAccessManager.NetworkAccessibility.NotAccessible) return nam diff --git a/tests/helpers/stubs.py b/tests/helpers/stubs.py index 0b9c926c4..2963a2c13 100644 --- a/tests/helpers/stubs.py +++ b/tests/helpers/stubs.py @@ -135,7 +135,7 @@ class FakeNetworkReply: """QNetworkReply stub which provides a Content-Disposition header.""" KNOWN_HEADERS = { - QNetworkRequest.ContentTypeHeader: 'Content-Type', + QNetworkRequest.KnownHeaders.ContentTypeHeader: 'Content-Type', } def __init__(self, headers=None, url=None): diff --git a/tests/unit/browser/test_pdfjs.py b/tests/unit/browser/test_pdfjs.py index 6923c9417..e9ca51796 100644 --- a/tests/unit/browser/test_pdfjs.py +++ b/tests/unit/browser/test_pdfjs.py @@ -52,7 +52,7 @@ def test_generate_pdfjs_page(available, snippet, monkeypatch): assert snippet in content -# Note that we got double protection, once because we use QUrl.FullyEncoded and +# Note that we got double protection, once because we use QUrl.ComponentFormattingOption.FullyEncoded and # because we use qutebrowser.utils.javascript.to_js. Characters like " are # already replaced by QUrl. @pytest.mark.parametrize('filename, expected', [ diff --git a/tests/unit/browser/webengine/test_webenginetab.py b/tests/unit/browser/webengine/test_webenginetab.py index 30807bb4e..6f9e4af7a 100644 --- a/tests/unit/browser/webengine/test_webenginetab.py +++ b/tests/unit/browser/webengine/test_webenginetab.py @@ -131,17 +131,17 @@ class TestWebengineScripts: scripts_helper.inject(scripts) script = scripts_helper.get_script() - assert script.injectionPoint() == QWebEngineScript.DocumentReady + assert script.injectionPoint() == QWebEngineScript.InjectionPoint.DocumentReady @pytest.mark.parametrize('run_at, expected', [ # UserScript::DocumentElementCreation - ('document-start', QWebEngineScript.DocumentCreation), + ('document-start', QWebEngineScript.InjectionPoint.DocumentCreation), # UserScript::DocumentLoadFinished - ('document-end', QWebEngineScript.DocumentReady), + ('document-end', QWebEngineScript.InjectionPoint.DocumentReady), # UserScript::AfterLoad - ('document-idle', QWebEngineScript.Deferred), + ('document-idle', QWebEngineScript.InjectionPoint.Deferred), # default according to https://wiki.greasespot.net/Metadata_Block#.40run-at - (None, QWebEngineScript.DocumentReady), + (None, QWebEngineScript.InjectionPoint.DocumentReady), ]) def test_greasemonkey_run_at_values(self, scripts_helper, run_at, expected): if run_at is None: @@ -207,7 +207,7 @@ class TestWebengineScripts: def test_notification_permission_workaround(): """Make sure the value for QWebEnginePage::Notifications is correct.""" try: - notifications = QWebEnginePage.Notifications + notifications = QWebEnginePage.Feature.Notifications except AttributeError: pytest.skip("No Notifications member") diff --git a/tests/unit/browser/webkit/network/test_networkreply.py b/tests/unit/browser/webkit/network/test_networkreply.py index 88facb333..5de31bf0f 100644 --- a/tests/unit/browser/webkit/network/test_networkreply.py +++ b/tests/unit/browser/webkit/network/test_networkreply.py @@ -38,11 +38,11 @@ class TestFixedDataNetworkReply: reply = networkreply.FixedDataNetworkReply(req, b'', 'test/foo') assert reply.request() == req assert reply.url() == req.url() - assert reply.openMode() == QIODevice.ReadOnly - assert reply.header(QNetworkRequest.ContentTypeHeader) == 'test/foo' - http_code = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) + assert reply.openMode() == QIODevice.OpenModeFlag.ReadOnly + assert reply.header(QNetworkRequest.KnownHeaders.ContentTypeHeader) == 'test/foo' + http_code = reply.attribute(QNetworkRequest.Attribute.HttpStatusCodeAttribute) http_reason = reply.attribute( - QNetworkRequest.HttpReasonPhraseAttribute) + QNetworkRequest.Attribute.HttpReasonPhraseAttribute) assert http_code == 200 assert http_reason == 'OK' assert reply.isFinished() @@ -76,7 +76,7 @@ class TestFixedDataNetworkReply: def test_error_network_reply(qtbot, req): reply = networkreply.ErrorNetworkReply( - req, "This is an error", QNetworkReply.UnknownNetworkError) + req, "This is an error", QNetworkReply.NetworkError.UnknownNetworkError) with qtbot.wait_signals([reply.error, reply.finished], order='strict'): pass @@ -84,12 +84,12 @@ def test_error_network_reply(qtbot, req): reply.abort() # shouldn't do anything assert reply.request() == req assert reply.url() == req.url() - assert reply.openMode() == QIODevice.ReadOnly + assert reply.openMode() == QIODevice.OpenModeFlag.ReadOnly assert reply.isFinished() assert not reply.isRunning() assert reply.bytesAvailable() == 0 assert reply.readData(1) == b'' - assert reply.error() == QNetworkReply.UnknownNetworkError + assert reply.error() == QNetworkReply.NetworkError.UnknownNetworkError assert reply.errorString() == "This is an error" @@ -97,5 +97,5 @@ def test_redirect_network_reply(): url = QUrl('https://www.example.com/') reply = networkreply.RedirectNetworkReply(url) assert reply.readData(1) == b'' - assert reply.attribute(QNetworkRequest.RedirectionTargetAttribute) == url + assert reply.attribute(QNetworkRequest.Attribute.RedirectionTargetAttribute) == url reply.abort() # shouldn't do anything diff --git a/tests/unit/browser/webkit/network/test_pac.py b/tests/unit/browser/webkit/network/test_pac.py index 897dd055a..8b9e29912 100644 --- a/tests/unit/browser/webkit/network/test_pac.py +++ b/tests/unit/browser/webkit/network/test_pac.py @@ -44,11 +44,11 @@ def _pac_common_test(test_str): res = pac.PACResolver(fun_str) proxies = res.resolve(QNetworkProxyQuery(QUrl("https://example.com/test"))) assert len(proxies) == 3 - assert proxies[0].type() == QNetworkProxy.NoProxy - assert proxies[1].type() == QNetworkProxy.HttpProxy + assert proxies[0].type() == QNetworkProxy.ProxyType.NoProxy + assert proxies[1].type() == QNetworkProxy.ProxyType.HttpProxy assert proxies[1].hostName() == "127.0.0.1" assert proxies[1].port() == 8080 - assert proxies[2].type() == QNetworkProxy.Socks5Proxy + assert proxies[2].type() == QNetworkProxy.ProxyType.Socks5Proxy assert proxies[2].hostName() == "192.168.1.1" assert proxies[2].port() == 4444 diff --git a/tests/unit/browser/webkit/test_certificateerror.py b/tests/unit/browser/webkit/test_certificateerror.py index 0f2f92fd2..4d497b528 100644 --- a/tests/unit/browser/webkit/test_certificateerror.py +++ b/tests/unit/browser/webkit/test_certificateerror.py @@ -34,13 +34,13 @@ class FakeError: @pytest.mark.parametrize('errors, expected', [ ( - [QSslError(QSslError.UnableToGetIssuerCertificate)], + [QSslError(QSslError.SslError.UnableToGetIssuerCertificate)], ['<p>The issuer certificate could not be found</p>'], ), ( [ - QSslError(QSslError.UnableToGetIssuerCertificate), - QSslError(QSslError.UnableToDecryptCertificateSignature), + QSslError(QSslError.SslError.UnableToGetIssuerCertificate), + QSslError(QSslError.SslError.UnableToDecryptCertificateSignature), ], [ '<ul>', diff --git a/tests/unit/browser/webkit/test_webkitelem.py b/tests/unit/browser/webkit/test_webkitelem.py index da02c5d91..dd63d135b 100644 --- a/tests/unit/browser/webkit/test_webkitelem.py +++ b/tests/unit/browser/webkit/test_webkitelem.py @@ -124,7 +124,7 @@ def get_webelem(geometry=None, frame=None, *, null=False, style=None, def _style_property(name, strategy): """Helper function to act as styleProperty method.""" - if strategy != QWebElement.ComputedStyle: + if strategy != QWebElement.StyleResolveStrategy.ComputedStyle: raise ValueError("styleProperty called with strategy != " "ComputedStyle ({})!".format(strategy)) return style_dict[name] diff --git a/tests/unit/completion/test_completiondelegate.py b/tests/unit/completion/test_completiondelegate.py index 4885d0138..31df6f1ce 100644 --- a/tests/unit/completion/test_completiondelegate.py +++ b/tests/unit/completion/test_completiondelegate.py @@ -51,7 +51,7 @@ from qutebrowser.completion import completiondelegate ]) def test_highlight(pat, txt, segments): doc = QTextDocument(txt) - highlighter = completiondelegate._Highlighter(doc, pat, Qt.red) + highlighter = completiondelegate._Highlighter(doc, pat, Qt.GlobalColor.red) highlighter.setFormat = mock.Mock() highlighter.highlightBlock(txt) highlighter.setFormat.assert_has_calls([ @@ -65,7 +65,7 @@ def test_benchmark_highlight(benchmark): doc = QTextDocument(txt) def bench(): - highlighter = completiondelegate._Highlighter(doc, pat, Qt.red) + highlighter = completiondelegate._Highlighter(doc, pat, Qt.GlobalColor.red) highlighter.highlightBlock(txt) benchmark(bench) @@ -75,7 +75,7 @@ def test_benchmark_highlight(benchmark): def test_pattern_hypothesis(text): """Make sure we can't produce invalid patterns.""" doc = QTextDocument() - completiondelegate._Highlighter(doc, text, Qt.red) + completiondelegate._Highlighter(doc, text, Qt.GlobalColor.red) def test_highlighted(qtbot): @@ -87,7 +87,7 @@ def test_highlighted(qtbot): that is kind of hard, so we just test it in isolation here. """ doc = QTextDocument() - completiondelegate._Highlighter(doc, 'Hello', Qt.red) + completiondelegate._Highlighter(doc, 'Hello', Qt.GlobalColor.red) doc.setPlainText('Hello World') # Needed so the highlighting actually works. diff --git a/tests/unit/completion/test_models.py b/tests/unit/completion/test_models.py index d90551764..07bc30424 100644 --- a/tests/unit/completion/test_models.py +++ b/tests/unit/completion/test_models.py @@ -1490,7 +1490,7 @@ def test_process_completion(monkeypatch, stubs, info): p1.cmd = 'cmd1' p1.args = [] p1.outcome.running = False - p1.outcome.status = QProcess.NormalExit + p1.outcome.status = QProcess.ExitStatus.NormalExit p1.outcome.code = 0 p2.pid = 1002 @@ -1502,7 +1502,7 @@ def test_process_completion(monkeypatch, stubs, info): p3.cmd = 'cmd3' p3.args = [] p3.outcome.running = False - p3.outcome.status = QProcess.NormalExit + p3.outcome.status = QProcess.ExitStatus.NormalExit p3.outcome.code = 1 monkeypatch.setattr(guiprocess, 'all_processes', { diff --git a/tests/unit/components/test_braveadblock.py b/tests/unit/components/test_braveadblock.py index ddb70d4f5..d776e94be 100644 --- a/tests/unit/components/test_braveadblock.py +++ b/tests/unit/components/test_braveadblock.py @@ -327,7 +327,7 @@ def test_whitelist_on_dataset(config_stub, easylist_easyprivacy): assert not blockutils.is_whitelisted_url(url) config_stub.val.content.blocking.whitelist = [] assert not blockutils.is_whitelisted_url(url) - whitelist_url = url.toString(QUrl.RemovePath) + "/*" + whitelist_url = url.toString(QUrl.UrlFormattingOption.RemovePath) + "/*" config_stub.val.content.blocking.whitelist = [whitelist_url] assert blockutils.is_whitelisted_url(url) diff --git a/tests/unit/config/test_config.py b/tests/unit/config/test_config.py index 7ddf3dc6b..3bff794a0 100644 --- a/tests/unit/config/test_config.py +++ b/tests/unit/config/test_config.py @@ -771,7 +771,7 @@ class TestContainer: @pytest.mark.parametrize('configapi, expected', [ (object(), 'rgb'), - (None, QColor.Rgb), + (None, QColor.Spec.Rgb), ]) def test_getattr_option(self, container, configapi, expected): container._configapi = configapi diff --git a/tests/unit/config/test_configtypes.py b/tests/unit/config/test_configtypes.py index 9381af6a0..00d701011 100644 --- a/tests/unit/config/test_configtypes.py +++ b/tests/unit/config/test_configtypes.py @@ -1376,46 +1376,46 @@ class TestFont: TESTS = { # (style, weight, pointsize, pixelsize, family '"Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Normal, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, -1, -1, 'Foobar Neue'), 'inconsolatazi4': - FontDesc(QFont.StyleNormal, QFont.Normal, -1, -1, + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, -1, -1, 'inconsolatazi4'), 'Terminus (TTF)': - FontDesc(QFont.StyleNormal, QFont.Normal, -1, -1, + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, -1, -1, 'Terminus (TTF)'), '10pt "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Normal, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, 10, None, 'Foobar Neue'), '10PT "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Normal, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, 10, None, 'Foobar Neue'), '10px "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Normal, None, 10, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, None, 10, 'Foobar Neue'), '10PX "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Normal, None, 10, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Normal, None, 10, 'Foobar Neue'), 'bold "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Bold, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Bold, -1, -1, 'Foobar Neue'), 'italic "Foobar Neue"': - FontDesc(QFont.StyleItalic, QFont.Normal, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleItalic, QFont.Weight.Normal, -1, -1, 'Foobar Neue'), 'oblique "Foobar Neue"': - FontDesc(QFont.StyleOblique, QFont.Normal, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleOblique, QFont.Weight.Normal, -1, -1, 'Foobar Neue'), 'normal bold "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Bold, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Bold, -1, -1, 'Foobar Neue'), 'bold italic "Foobar Neue"': - FontDesc(QFont.StyleItalic, QFont.Bold, -1, -1, 'Foobar Neue'), + FontDesc(QFont.Style.StyleItalic, QFont.Weight.Bold, -1, -1, 'Foobar Neue'), 'bold 10pt "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Bold, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Bold, 10, None, 'Foobar Neue'), 'italic 10pt "Foobar Neue"': - FontDesc(QFont.StyleItalic, QFont.Normal, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleItalic, QFont.Weight.Normal, 10, None, 'Foobar Neue'), 'oblique 10pt "Foobar Neue"': - FontDesc(QFont.StyleOblique, QFont.Normal, 10, None, + FontDesc(QFont.Style.StyleOblique, QFont.Weight.Normal, 10, None, 'Foobar Neue'), 'normal bold 10pt "Foobar Neue"': - FontDesc(QFont.StyleNormal, QFont.Bold, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, QFont.Weight.Bold, 10, None, 'Foobar Neue'), 'bold italic 10pt "Foobar Neue"': - FontDesc(QFont.StyleItalic, QFont.Bold, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleItalic, QFont.Weight.Bold, 10, None, 'Foobar Neue'), 'normal 300 10pt "Foobar Neue"': - FontDesc(QFont.StyleNormal, 37, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, 37, 10, None, 'Foobar Neue'), 'normal 800 10pt "Foobar Neue"': - FontDesc(QFont.StyleNormal, 99, 10, None, 'Foobar Neue'), + FontDesc(QFont.Style.StyleNormal, 99, 10, None, 'Foobar Neue'), } font_xfail = pytest.mark.xfail(reason='FIXME: #103') @@ -1892,11 +1892,11 @@ class TestProxy: @pytest.mark.parametrize('val, expected', [ ('system', configtypes.SYSTEM_PROXY), - ('none', QNetworkProxy(QNetworkProxy.NoProxy)), + ('none', QNetworkProxy(QNetworkProxy.ProxyType.NoProxy)), ('socks://example.com/', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com')), ('socks5://foo:bar@example.com:2323', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323, + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com', 2323, 'foo', 'bar')), ('pac+http://example.com/proxy.pac', pac.PACFetcher(QUrl('pac+http://example.com/proxy.pac'))), diff --git a/tests/unit/javascript/position_caret/test_position_caret.py b/tests/unit/javascript/position_caret/test_position_caret.py index 70a1df333..ba3a1f2fd 100644 --- a/tests/unit/javascript/position_caret/test_position_caret.py +++ b/tests/unit/javascript/position_caret/test_position_caret.py @@ -29,10 +29,10 @@ QWebPage = pytest.importorskip("PyQt5.QtWebKitWidgets").QWebPage def enable_caret_browsing(qapp): """Fixture to enable caret browsing globally.""" settings = QWebSettings.globalSettings() - old_value = settings.testAttribute(QWebSettings.CaretBrowsingEnabled) - settings.setAttribute(QWebSettings.CaretBrowsingEnabled, True) + old_value = settings.testAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled) + settings.setAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled, True) yield - settings.setAttribute(QWebSettings.CaretBrowsingEnabled, old_value) + settings.setAttribute(QWebSettings.WebAttribute.CaretBrowsingEnabled, old_value) class CaretTester: diff --git a/tests/unit/javascript/test_js_execution.py b/tests/unit/javascript/test_js_execution.py index 4c7b25056..66236a015 100644 --- a/tests/unit/javascript/test_js_execution.py +++ b/tests/unit/javascript/test_js_execution.py @@ -29,7 +29,7 @@ def test_simple_js_webkit(webview, js_enabled, expected): # If we get there (because of the webview fixture) we can be certain # QtWebKit is available from qutebrowser.qt.webkit import QWebSettings - webview.settings().setAttribute(QWebSettings.JavascriptEnabled, js_enabled) + webview.settings().setAttribute(QWebSettings.WebAttribute.JavascriptEnabled, js_enabled) result = webview.page().mainFrame().evaluateJavaScript('1 + 1') assert result == expected @@ -40,7 +40,7 @@ def test_element_js_webkit(webview, js_enabled, expected): # If we get there (because of the webview fixture) we can be certain # QtWebKit is available from qutebrowser.qt.webkit import QWebSettings - webview.settings().setAttribute(QWebSettings.JavascriptEnabled, js_enabled) + webview.settings().setAttribute(QWebSettings.WebAttribute.JavascriptEnabled, js_enabled) elem = webview.page().mainFrame().documentElement() result = elem.evaluateJavaScript('1 + 1') assert result == expected @@ -65,12 +65,12 @@ def test_simple_js_webengine(qtbot, webengineview, qapp, # QtWebEngine is available from qutebrowser.qt.webengineWidgets import QWebEngineSettings, QWebEngineScript - assert world in [QWebEngineScript.MainWorld, - QWebEngineScript.ApplicationWorld, - QWebEngineScript.UserWorld] + assert world in [QWebEngineScript.ScriptWorldId.MainWorld, + QWebEngineScript.ScriptWorldId.ApplicationWorld, + QWebEngineScript.ScriptWorldId.UserWorld] settings = webengineview.settings() - settings.setAttribute(QWebEngineSettings.JavascriptEnabled, js_enabled) + settings.setAttribute(QWebEngineSettings.WebAttribute.JavascriptEnabled, js_enabled) qapp.processEvents() page = webengineview.page() diff --git a/tests/unit/keyinput/key_data.py b/tests/unit/keyinput/key_data.py index 795fa7d5b..f9b31feaf 100644 --- a/tests/unit/keyinput/key_data.py +++ b/tests/unit/keyinput/key_data.py @@ -62,7 +62,7 @@ class Modifier: Attributes: attribute: The name of the Qt::KeyboardModifier attribute - ('Shift' -> Qt.ShiftModifier) + ('Shift' -> Qt.KeyboardModifier.ShiftModifier) name: The name returned by str(KeyInfo) with that modifier. member: The numeric value. """ diff --git a/tests/unit/keyinput/test_basekeyparser.py b/tests/unit/keyinput/test_basekeyparser.py index 419986303..c2592c197 100644 --- a/tests/unit/keyinput/test_basekeyparser.py +++ b/tests/unit/keyinput/test_basekeyparser.py @@ -54,7 +54,7 @@ def handle_text(): """Helper function to handle multiple fake keypresses.""" def func(kp, *args): for key in args: - info = keyutils.KeyInfo(key, Qt.NoModifier) + info = keyutils.KeyInfo(key, Qt.KeyboardModifier.NoModifier) kp.handle(info.to_event()) return func @@ -119,11 +119,11 @@ def test_read_config(keyparser, key_config_stub, changed_mode, expected): class TestHandle: def test_valid_key(self, prompt_keyparser, handle_text): - modifier = Qt.MetaModifier if utils.is_mac else Qt.ControlModifier + modifier = Qt.KeyboardModifier.MetaModifier if utils.is_mac else Qt.KeyboardModifier.ControlModifier infos = [ - keyutils.KeyInfo(Qt.Key_A, modifier), - keyutils.KeyInfo(Qt.Key_X, modifier), + keyutils.KeyInfo(Qt.Key.Key_A, modifier), + keyutils.KeyInfo(Qt.Key.Key_X, modifier), ] for info in infos: prompt_keyparser.handle(info.to_event()) @@ -133,11 +133,11 @@ class TestHandle: assert not prompt_keyparser._sequence def test_valid_key_count(self, prompt_keyparser): - modifier = Qt.MetaModifier if utils.is_mac else Qt.ControlModifier + modifier = Qt.KeyboardModifier.MetaModifier if utils.is_mac else Qt.KeyboardModifier.ControlModifier infos = [ - keyutils.KeyInfo(Qt.Key_5, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_A, modifier), + keyutils.KeyInfo(Qt.Key.Key_5, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_A, modifier), ] for info in infos: prompt_keyparser.handle(info.to_event()) @@ -145,10 +145,10 @@ class TestHandle: 'message-info ctrla', 5) @pytest.mark.parametrize('keys', [ - [(Qt.Key_B, Qt.NoModifier), (Qt.Key_C, Qt.NoModifier)], - [(Qt.Key_A, Qt.ControlModifier | Qt.AltModifier)], + [(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier), (Qt.Key.Key_C, Qt.KeyboardModifier.NoModifier)], + [(Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier)], # Only modifier - [(Qt.Key_Shift, Qt.ShiftModifier)], + [(Qt.Key.Key_Shift, Qt.KeyboardModifier.ShiftModifier)], ]) def test_invalid_keys(self, prompt_keyparser, keys): for key, modifiers in keys: @@ -158,40 +158,40 @@ class TestHandle: assert not prompt_keyparser._sequence def test_dry_run(self, prompt_keyparser): - b_info = keyutils.KeyInfo(Qt.Key_B, Qt.NoModifier) + b_info = keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier) prompt_keyparser.handle(b_info.to_event()) - a_info = keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier) + a_info = keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier) prompt_keyparser.handle(a_info.to_event(), dry_run=True) assert not prompt_keyparser.execute.called assert prompt_keyparser._sequence def test_dry_run_count(self, prompt_keyparser): - info = keyutils.KeyInfo(Qt.Key_9, Qt.NoModifier) + info = keyutils.KeyInfo(Qt.Key.Key_9, Qt.KeyboardModifier.NoModifier) prompt_keyparser.handle(info.to_event(), dry_run=True) assert not prompt_keyparser._count def test_invalid_key(self, prompt_keyparser): - keys = [Qt.Key_B, 0x0] + keys = [Qt.Key.Key_B, 0x0] for key in keys: - info = keyutils.KeyInfo(key, Qt.NoModifier) + info = keyutils.KeyInfo(key, Qt.KeyboardModifier.NoModifier) prompt_keyparser.handle(info.to_event()) assert not prompt_keyparser._sequence def test_valid_keychain(self, handle_text, prompt_keyparser): handle_text(prompt_keyparser, # Press 'x' which is ignored because of no match - Qt.Key_X, + Qt.Key.Key_X, # Then start the real chain - Qt.Key_B, Qt.Key_A) + Qt.Key.Key_B, Qt.Key.Key_A) prompt_keyparser.execute.assert_called_with('message-info ba', None) assert not prompt_keyparser._sequence @pytest.mark.parametrize('key, modifiers, number', [ - (Qt.Key_0, Qt.NoModifier, 0), - (Qt.Key_1, Qt.NoModifier, 1), - (Qt.Key_1, Qt.KeypadModifier, 1), + (Qt.Key.Key_0, Qt.KeyboardModifier.NoModifier, 0), + (Qt.Key.Key_1, Qt.KeyboardModifier.NoModifier, 1), + (Qt.Key.Key_1, Qt.KeyboardModifier.KeypadModifier, 1), ]) def test_number_press(self, prompt_keyparser, key, modifiers, number): @@ -201,8 +201,8 @@ class TestHandle: assert not prompt_keyparser._sequence @pytest.mark.parametrize('modifiers, text', [ - (Qt.NoModifier, '2'), - (Qt.KeypadModifier, 'num-2'), + (Qt.KeyboardModifier.NoModifier, '2'), + (Qt.KeyboardModifier.KeypadModifier, 'num-2'), ]) def test_number_press_keypad(self, keyparser, config_stub, modifiers, text): @@ -210,18 +210,18 @@ class TestHandle: config_stub.val.bindings.commands = {'normal': { '2': 'message-info 2', '<Num+2>': 'message-info num-2'}} - keyparser.handle(keyutils.KeyInfo(Qt.Key_2, modifiers).to_event()) + keyparser.handle(keyutils.KeyInfo(Qt.Key.Key_2, modifiers).to_event()) command = 'message-info {}'.format(text) keyparser.execute.assert_called_once_with(command, None) assert not keyparser._sequence def test_umlauts(self, handle_text, keyparser, config_stub): config_stub.val.bindings.commands = {'normal': {'ü': 'message-info ü'}} - handle_text(keyparser, Qt.Key_Udiaeresis) + handle_text(keyparser, Qt.Key.Key_Udiaeresis) keyparser.execute.assert_called_once_with('message-info ü', None) def test_mapping(self, config_stub, handle_text, prompt_keyparser): - handle_text(prompt_keyparser, Qt.Key_X) + handle_text(prompt_keyparser, Qt.Key.Key_X) prompt_keyparser.execute.assert_called_once_with( 'message-info a', None) @@ -230,27 +230,27 @@ class TestHandle: config_stub.val.bindings.commands = {'normal': {'a': 'nop'}} config_stub.val.bindings.key_mappings = {'1': 'a'} - info = keyutils.KeyInfo(Qt.Key_1, Qt.KeypadModifier) + info = keyutils.KeyInfo(Qt.Key.Key_1, Qt.KeyboardModifier.KeypadModifier) keyparser.handle(info.to_event()) keyparser.execute.assert_called_once_with('nop', None) def test_binding_and_mapping(self, config_stub, handle_text, prompt_keyparser): """with a conflicting binding/mapping, the binding should win.""" - handle_text(prompt_keyparser, Qt.Key_B) + handle_text(prompt_keyparser, Qt.Key.Key_B) assert not prompt_keyparser.execute.called def test_mapping_in_key_chain(self, config_stub, handle_text, keyparser): """A mapping should work even as part of a keychain.""" config_stub.val.bindings.commands = {'normal': {'aa': 'message-info aa'}} - handle_text(keyparser, Qt.Key_A, Qt.Key_X) + handle_text(keyparser, Qt.Key.Key_A, Qt.Key.Key_X) keyparser.execute.assert_called_once_with('message-info aa', None) def test_binding_with_shift(self, prompt_keyparser): """Simulate a binding which involves shift.""" - for key, modifiers in [(Qt.Key_Y, Qt.NoModifier), - (Qt.Key_Shift, Qt.ShiftModifier), - (Qt.Key_Y, Qt.ShiftModifier)]: + for key, modifiers in [(Qt.Key.Key_Y, Qt.KeyboardModifier.NoModifier), + (Qt.Key.Key_Shift, Qt.KeyboardModifier.ShiftModifier), + (Qt.Key.Key_Y, Qt.KeyboardModifier.ShiftModifier)]: info = keyutils.KeyInfo(key, modifiers) prompt_keyparser.handle(info.to_event()) @@ -264,7 +264,7 @@ class TestHandle: 'a': 'message-info foo' } } - info = keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier) + info = keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier) keyparser.handle(info.to_event()) keyparser.execute.assert_called_once_with('message-info foo', None) @@ -275,39 +275,39 @@ class TestCount: def test_no_count(self, handle_text, prompt_keyparser): """Test with no count added.""" - handle_text(prompt_keyparser, Qt.Key_B, Qt.Key_A) + handle_text(prompt_keyparser, Qt.Key.Key_B, Qt.Key.Key_A) prompt_keyparser.execute.assert_called_once_with( 'message-info ba', None) assert not prompt_keyparser._sequence def test_count_0(self, handle_text, prompt_keyparser): - handle_text(prompt_keyparser, Qt.Key_0, Qt.Key_B, Qt.Key_A) + handle_text(prompt_keyparser, Qt.Key.Key_0, Qt.Key.Key_B, Qt.Key.Key_A) calls = [mock.call('message-info 0', None), mock.call('message-info ba', None)] prompt_keyparser.execute.assert_has_calls(calls) assert not prompt_keyparser._sequence def test_count_42(self, handle_text, prompt_keyparser): - handle_text(prompt_keyparser, Qt.Key_4, Qt.Key_2, Qt.Key_B, Qt.Key_A) + handle_text(prompt_keyparser, Qt.Key.Key_4, Qt.Key.Key_2, Qt.Key.Key_B, Qt.Key.Key_A) prompt_keyparser.execute.assert_called_once_with('message-info ba', 42) assert not prompt_keyparser._sequence def test_count_42_invalid(self, handle_text, prompt_keyparser): # Invalid call with ccx gets ignored handle_text(prompt_keyparser, - Qt.Key_4, Qt.Key_2, Qt.Key_C, Qt.Key_C, Qt.Key_X) + Qt.Key.Key_4, Qt.Key.Key_2, Qt.Key.Key_C, Qt.Key.Key_C, Qt.Key.Key_X) assert not prompt_keyparser.execute.called assert not prompt_keyparser._sequence # Valid call with ccc gets the correct count handle_text(prompt_keyparser, - Qt.Key_2, Qt.Key_3, Qt.Key_C, Qt.Key_C, Qt.Key_C) + Qt.Key.Key_2, Qt.Key.Key_3, Qt.Key.Key_C, Qt.Key.Key_C, Qt.Key.Key_C) prompt_keyparser.execute.assert_called_once_with( 'message-info ccc', 23) assert not prompt_keyparser._sequence def test_superscript(self, handle_text, prompt_keyparser): # https://github.com/qutebrowser/qutebrowser/issues/3743 - handle_text(prompt_keyparser, Qt.Key_twosuperior, Qt.Key_B, Qt.Key_A) + handle_text(prompt_keyparser, Qt.Key.Key_twosuperior, Qt.Key.Key_B, Qt.Key.Key_A) def test_count_keystring_update(self, qtbot, handle_text, prompt_keyparser): @@ -315,17 +315,17 @@ class TestCount: with qtbot.wait_signals([ prompt_keyparser.keystring_updated, prompt_keyparser.keystring_updated]) as blocker: - handle_text(prompt_keyparser, Qt.Key_4, Qt.Key_2) + handle_text(prompt_keyparser, Qt.Key.Key_4, Qt.Key.Key_2) sig1, sig2 = blocker.all_signals_and_args assert sig1.args == ('4',) assert sig2.args == ('42',) def test_numpad(self, prompt_keyparser): """Make sure we can enter a count via numpad.""" - for key, modifiers in [(Qt.Key_4, Qt.KeypadModifier), - (Qt.Key_2, Qt.KeypadModifier), - (Qt.Key_B, Qt.NoModifier), - (Qt.Key_A, Qt.NoModifier)]: + for key, modifiers in [(Qt.Key.Key_4, Qt.KeyboardModifier.KeypadModifier), + (Qt.Key.Key_2, Qt.KeyboardModifier.KeypadModifier), + (Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier), + (Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier)]: info = keyutils.KeyInfo(key, modifiers) prompt_keyparser.handle(info.to_event()) prompt_keyparser.execute.assert_called_once_with('message-info ba', 42) @@ -352,7 +352,7 @@ def test_respect_config_when_matching_counts(keyparser, config_stub): """Don't match counts if disabled in the config.""" config_stub.val.input.match_counts = False - info = keyutils.KeyInfo(Qt.Key_1, Qt.NoModifier) + info = keyutils.KeyInfo(Qt.Key.Key_1, Qt.KeyboardModifier.NoModifier) keyparser.handle(info.to_event()) assert not keyparser._sequence diff --git a/tests/unit/keyinput/test_bindingtrie.py b/tests/unit/keyinput/test_bindingtrie.py index 44606e98f..b0844c980 100644 --- a/tests/unit/keyinput/test_bindingtrie.py +++ b/tests/unit/keyinput/test_bindingtrie.py @@ -39,7 +39,7 @@ def test_matches_single(entered, configured, match_type): configured = keyutils.KeySequence.parse(configured) trie = basekeyparser.BindingTrie() trie[configured] = "eeloo" - command = "eeloo" if match_type == QKeySequence.ExactMatch else None + command = "eeloo" if match_type == QKeySequence.SequenceMatch.ExactMatch else None result = basekeyparser.MatchResult(match_type=match_type, command=command, sequence=entered) @@ -82,22 +82,22 @@ def test_str(): @pytest.mark.parametrize('configured, expected', [ ([], # null match - [('a', QKeySequence.NoMatch), - ('', QKeySequence.NoMatch)]), + [('a', QKeySequence.SequenceMatch.NoMatch), + ('', QKeySequence.SequenceMatch.NoMatch)]), (['abcd'], - [('abcd', QKeySequence.ExactMatch), - ('abc', QKeySequence.PartialMatch)]), + [('abcd', QKeySequence.SequenceMatch.ExactMatch), + ('abc', QKeySequence.SequenceMatch.PartialMatch)]), (['aa', 'ab', 'ac', 'ad'], - [('ac', QKeySequence.ExactMatch), - ('a', QKeySequence.PartialMatch), - ('f', QKeySequence.NoMatch), - ('acd', QKeySequence.NoMatch)]), + [('ac', QKeySequence.SequenceMatch.ExactMatch), + ('a', QKeySequence.SequenceMatch.PartialMatch), + ('f', QKeySequence.SequenceMatch.NoMatch), + ('acd', QKeySequence.SequenceMatch.NoMatch)]), (['aaaaaaab', 'aaaaaaac', 'aaaaaaad'], - [('aaaaaaab', QKeySequence.ExactMatch), - ('z', QKeySequence.NoMatch)]), + [('aaaaaaab', QKeySequence.SequenceMatch.ExactMatch), + ('z', QKeySequence.SequenceMatch.NoMatch)]), (string.ascii_letters, - [('a', QKeySequence.ExactMatch), - ('!', QKeySequence.NoMatch)]), + [('a', QKeySequence.SequenceMatch.ExactMatch), + ('!', QKeySequence.SequenceMatch.NoMatch)]), ]) def test_matches_tree(configured, expected, benchmark): trie = basekeyparser.BindingTrie() @@ -107,7 +107,7 @@ def test_matches_tree(configured, expected, benchmark): def run(): for entered, match_type in expected: sequence = keyutils.KeySequence.parse(entered) - command = ("eeloo" if match_type == QKeySequence.ExactMatch + command = ("eeloo" if match_type == QKeySequence.SequenceMatch.ExactMatch else None) result = basekeyparser.MatchResult(match_type=match_type, command=command, diff --git a/tests/unit/keyinput/test_keyutils.py b/tests/unit/keyinput/test_keyutils.py index 22b4816c2..386811fb8 100644 --- a/tests/unit/keyinput/test_keyutils.py +++ b/tests/unit/keyinput/test_keyutils.py @@ -73,7 +73,7 @@ def test_key_data_modifiers(): mod_names = {name[:-len("Modifier")] for name, value in sorted(vars(Qt).items()) if isinstance(value, Qt.KeyboardModifier) and - value not in [Qt.NoModifier, Qt.KeyboardModifierMask]} + value not in [Qt.KeyboardModifier.NoModifier, Qt.KeyboardModifier.KeyboardModifierMask]} mod_data_names = {mod.attribute for mod in sorted(key_data.MODIFIERS)} diff = mod_names - mod_data_names assert not diff @@ -106,7 +106,7 @@ class TestKeyInfoText: See key_data.py for inputs and expected values. """ - modifiers = Qt.ShiftModifier if upper else Qt.KeyboardModifiers() + modifiers = Qt.KeyboardModifier.ShiftModifier if upper else Qt.KeyboardModifiers() info = keyutils.KeyInfo(qt_key.member, modifiers=modifiers) expected = qt_key.uppertext if upper else qt_key.text assert info.text() == expected @@ -143,45 +143,45 @@ class TestKeyToString: monkeypatch.delattr(keyutils.Qt, 'Key_AltGr') # We don't want to test the key which is actually missing - we only # want to know if the mapping still behaves properly. - assert keyutils._key_to_string(Qt.Key_A) == 'A' + assert keyutils._key_to_string(Qt.Key.Key_A) == 'A' @pytest.mark.parametrize('key, modifiers, expected', [ - (Qt.Key_A, Qt.NoModifier, 'a'), - (Qt.Key_A, Qt.ShiftModifier, 'A'), - - (Qt.Key_Space, Qt.NoModifier, '<Space>'), - (Qt.Key_Space, Qt.ShiftModifier, '<Shift+Space>'), - (Qt.Key_Tab, Qt.ShiftModifier, '<Shift+Tab>'), - (Qt.Key_A, Qt.ControlModifier, '<Ctrl+a>'), - (Qt.Key_A, Qt.ControlModifier | Qt.ShiftModifier, '<Ctrl+Shift+a>'), - (Qt.Key_A, - Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier | Qt.ShiftModifier, + (Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier, 'a'), + (Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier, 'A'), + + (Qt.Key.Key_Space, Qt.KeyboardModifier.NoModifier, '<Space>'), + (Qt.Key.Key_Space, Qt.KeyboardModifier.ShiftModifier, '<Shift+Space>'), + (Qt.Key.Key_Tab, Qt.KeyboardModifier.ShiftModifier, '<Shift+Tab>'), + (Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier, '<Ctrl+a>'), + (Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier, '<Ctrl+Shift+a>'), + (Qt.Key.Key_A, + Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.ShiftModifier, '<Meta+Ctrl+Alt+Shift+a>'), - (ord('Œ'), Qt.NoModifier, '<Œ>'), - (ord('Œ'), Qt.ShiftModifier, '<Shift+Œ>'), - (ord('Œ'), Qt.GroupSwitchModifier, '<AltGr+Œ>'), - (ord('Œ'), Qt.GroupSwitchModifier | Qt.ShiftModifier, '<AltGr+Shift+Œ>'), - - (Qt.Key_Shift, Qt.ShiftModifier, '<Shift>'), - (Qt.Key_Shift, Qt.ShiftModifier | Qt.ControlModifier, '<Ctrl+Shift>'), - (Qt.Key_Alt, Qt.AltModifier, '<Alt>'), - (Qt.Key_Shift, Qt.GroupSwitchModifier | Qt.ShiftModifier, '<AltGr+Shift>'), - (Qt.Key_AltGr, Qt.GroupSwitchModifier, '<AltGr>'), + (ord('Œ'), Qt.KeyboardModifier.NoModifier, '<Œ>'), + (ord('Œ'), Qt.KeyboardModifier.ShiftModifier, '<Shift+Œ>'), + (ord('Œ'), Qt.KeyboardModifier.GroupSwitchModifier, '<AltGr+Œ>'), + (ord('Œ'), Qt.KeyboardModifier.GroupSwitchModifier | Qt.KeyboardModifier.ShiftModifier, '<AltGr+Shift+Œ>'), + + (Qt.Key.Key_Shift, Qt.KeyboardModifier.ShiftModifier, '<Shift>'), + (Qt.Key.Key_Shift, Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier, '<Ctrl+Shift>'), + (Qt.Key.Key_Alt, Qt.KeyboardModifier.AltModifier, '<Alt>'), + (Qt.Key.Key_Shift, Qt.KeyboardModifier.GroupSwitchModifier | Qt.KeyboardModifier.ShiftModifier, '<AltGr+Shift>'), + (Qt.Key.Key_AltGr, Qt.KeyboardModifier.GroupSwitchModifier, '<AltGr>'), ]) def test_key_info_str(key, modifiers, expected): assert str(keyutils.KeyInfo(key, modifiers)) == expected @pytest.mark.parametrize('info1, info2, equal', [ - (keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier), + (keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), True), - (keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_B, Qt.NoModifier), + (keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier), False), - (keyutils.KeyInfo(Qt.Key_A, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_B, Qt.ControlModifier), + (keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.ControlModifier), False), ]) def test_hash(info1, info2, equal): @@ -189,9 +189,9 @@ def test_hash(info1, info2, equal): @pytest.mark.parametrize('key, modifiers, text, expected', [ - (0xd83c, Qt.NoModifier, '🏻', '<🏻>'), - (0xd867, Qt.NoModifier, '𩷶', '<𩷶>'), - (0xd867, Qt.ShiftModifier, '𩷶', '<Shift+𩷶>'), + (0xd83c, Qt.KeyboardModifier.NoModifier, '🏻', '<🏻>'), + (0xd867, Qt.KeyboardModifier.NoModifier, '𩷶', '<𩷶>'), + (0xd867, Qt.KeyboardModifier.ShiftModifier, '𩷶', '<Shift+𩷶>'), ]) def test_surrogates(key, modifiers, text, expected): evt = QKeyEvent(QKeyEvent.KeyPress, key, modifiers, text) @@ -201,7 +201,7 @@ def test_surrogates(key, modifiers, text, expected): @pytest.mark.parametrize('keys, expected', [ ([0x1f3fb], '<🏻>'), ([0x29df6], '<𩷶>'), - ([Qt.Key_Shift, 0x29df6], '<Shift><𩷶>'), + ([Qt.Key.Key_Shift, 0x29df6], '<Shift><𩷶>'), ([0x1f468, 0x200d, 0x1f468, 0x200d, 0x1f466], '<👨><><👨><><👦>'), ]) def test_surrogate_sequences(keys, expected): @@ -211,7 +211,7 @@ def test_surrogate_sequences(keys, expected): # This shouldn't happen, but if it does we should handle it well def test_surrogate_error(): - evt = QKeyEvent(QKeyEvent.KeyPress, 0xd83e, Qt.NoModifier, '🤞🏻') + evt = QKeyEvent(QKeyEvent.KeyPress, 0xd83e, Qt.KeyboardModifier.NoModifier, '🤞🏻') with pytest.raises(keyutils.KeyParseError): keyutils.KeyInfo.from_event(evt) @@ -246,8 +246,8 @@ def test_parse_keystr(keystr, parts): class TestKeySequence: def test_init(self): - seq = keyutils.KeySequence(Qt.Key_A, Qt.Key_B, Qt.Key_C, Qt.Key_D, - Qt.Key_E) + seq = keyutils.KeySequence(Qt.Key.Key_A, Qt.Key.Key_B, Qt.Key.Key_C, Qt.Key.Key_D, + Qt.Key.Key_E) assert len(seq._sequences) == 2 assert len(seq._sequences[0]) == 4 assert len(seq._sequences[1]) == 1 @@ -256,7 +256,7 @@ class TestKeySequence: seq = keyutils.KeySequence() assert not seq - @pytest.mark.parametrize('key', [Qt.Key_unknown, -1, 0]) + @pytest.mark.parametrize('key', [Qt.Key.Key_unknown, -1, 0]) def test_init_unknown(self, key): with pytest.raises(keyutils.KeyParseError): keyutils.KeySequence(key) @@ -283,21 +283,21 @@ class TestKeySequence: assert str(keyutils.KeySequence.parse(orig)) == normalized def test_iter(self): - seq = keyutils.KeySequence(Qt.Key_A | Qt.ControlModifier, - Qt.Key_B | Qt.ShiftModifier, - Qt.Key_C, - Qt.Key_D, - Qt.Key_E) - expected = [keyutils.KeyInfo(Qt.Key_A, Qt.ControlModifier), - keyutils.KeyInfo(Qt.Key_B, Qt.ShiftModifier), - keyutils.KeyInfo(Qt.Key_C, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_D, Qt.NoModifier), - keyutils.KeyInfo(Qt.Key_E, Qt.NoModifier)] + seq = keyutils.KeySequence(Qt.Key.Key_A | Qt.KeyboardModifier.ControlModifier, + Qt.Key.Key_B | Qt.KeyboardModifier.ShiftModifier, + Qt.Key.Key_C, + Qt.Key.Key_D, + Qt.Key.Key_E) + expected = [keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier), + keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.ShiftModifier), + keyutils.KeyInfo(Qt.Key.Key_C, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_D, Qt.KeyboardModifier.NoModifier), + keyutils.KeyInfo(Qt.Key.Key_E, Qt.KeyboardModifier.NoModifier)] assert list(seq) == expected def test_repr(self): - seq = keyutils.KeySequence(Qt.Key_A | Qt.ControlModifier, - Qt.Key_B | Qt.ShiftModifier) + seq = keyutils.KeySequence(Qt.Key.Key_A | Qt.KeyboardModifier.ControlModifier, + Qt.Key.Key_B | Qt.KeyboardModifier.ShiftModifier) assert repr(seq) == ("<qutebrowser.keyinput.keyutils.KeySequence " "keys='<Ctrl+a>B'>") @@ -369,7 +369,7 @@ class TestKeySequence: def test_getitem(self): seq = keyutils.KeySequence.parse('ab') - expected = keyutils.KeyInfo(Qt.Key_B, Qt.NoModifier) + expected = keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier) assert seq[1] == expected def test_getitem_slice(self): @@ -382,27 +382,27 @@ class TestKeySequence: MATCH_TESTS = [ # config: abcd - ('abc', 'abcd', QKeySequence.PartialMatch), - ('abcd', 'abcd', QKeySequence.ExactMatch), - ('ax', 'abcd', QKeySequence.NoMatch), - ('abcdef', 'abcd', QKeySequence.NoMatch), + ('abc', 'abcd', QKeySequence.SequenceMatch.PartialMatch), + ('abcd', 'abcd', QKeySequence.SequenceMatch.ExactMatch), + ('ax', 'abcd', QKeySequence.SequenceMatch.NoMatch), + ('abcdef', 'abcd', QKeySequence.SequenceMatch.NoMatch), # config: abcd ef - ('abc', 'abcdef', QKeySequence.PartialMatch), - ('abcde', 'abcdef', QKeySequence.PartialMatch), - ('abcd', 'abcdef', QKeySequence.PartialMatch), - ('abcdx', 'abcdef', QKeySequence.NoMatch), - ('ax', 'abcdef', QKeySequence.NoMatch), - ('abcdefg', 'abcdef', QKeySequence.NoMatch), - ('abcdef', 'abcdef', QKeySequence.ExactMatch), + ('abc', 'abcdef', QKeySequence.SequenceMatch.PartialMatch), + ('abcde', 'abcdef', QKeySequence.SequenceMatch.PartialMatch), + ('abcd', 'abcdef', QKeySequence.SequenceMatch.PartialMatch), + ('abcdx', 'abcdef', QKeySequence.SequenceMatch.NoMatch), + ('ax', 'abcdef', QKeySequence.SequenceMatch.NoMatch), + ('abcdefg', 'abcdef', QKeySequence.SequenceMatch.NoMatch), + ('abcdef', 'abcdef', QKeySequence.SequenceMatch.ExactMatch), # other examples - ('ab', 'a', QKeySequence.NoMatch), + ('ab', 'a', QKeySequence.SequenceMatch.NoMatch), # empty strings - ('', '', QKeySequence.ExactMatch), - ('', 'a', QKeySequence.PartialMatch), - ('a', '', QKeySequence.NoMatch)] + ('', '', QKeySequence.SequenceMatch.ExactMatch), + ('', 'a', QKeySequence.SequenceMatch.PartialMatch), + ('a', '', QKeySequence.SequenceMatch.NoMatch)] @pytest.mark.parametrize('entered, configured, match_type', MATCH_TESTS) def test_matches(self, entered, configured, match_type): @@ -411,33 +411,33 @@ class TestKeySequence: assert entered.matches(configured) == match_type @pytest.mark.parametrize('old, key, modifiers, text, expected', [ - ('a', Qt.Key_B, Qt.NoModifier, 'b', 'ab'), - ('a', Qt.Key_B, Qt.ShiftModifier, 'B', 'aB'), - ('a', Qt.Key_B, Qt.AltModifier | Qt.ShiftModifier, 'B', + ('a', Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier, 'b', 'ab'), + ('a', Qt.Key.Key_B, Qt.KeyboardModifier.ShiftModifier, 'B', 'aB'), + ('a', Qt.Key.Key_B, Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier, 'B', 'a<Alt+Shift+b>'), # Modifier stripping with symbols - ('', Qt.Key_Colon, Qt.NoModifier, ':', ':'), - ('', Qt.Key_Colon, Qt.ShiftModifier, ':', ':'), - ('', Qt.Key_Colon, Qt.AltModifier | Qt.ShiftModifier, ':', + ('', Qt.Key.Key_Colon, Qt.KeyboardModifier.NoModifier, ':', ':'), + ('', Qt.Key.Key_Colon, Qt.KeyboardModifier.ShiftModifier, ':', ':'), + ('', Qt.Key.Key_Colon, Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier, ':', '<Alt+Shift+:>'), # Swapping Control/Meta on macOS - ('', Qt.Key_A, Qt.ControlModifier, '', + ('', Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier, '', '<Meta+A>' if utils.is_mac else '<Ctrl+A>'), - ('', Qt.Key_A, Qt.ControlModifier | Qt.ShiftModifier, '', + ('', Qt.Key.Key_A, Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier, '', '<Meta+Shift+A>' if utils.is_mac else '<Ctrl+Shift+A>'), - ('', Qt.Key_A, Qt.MetaModifier, '', + ('', Qt.Key.Key_A, Qt.KeyboardModifier.MetaModifier, '', '<Ctrl+A>' if utils.is_mac else '<Meta+A>'), # Handling of Backtab - ('', Qt.Key_Backtab, Qt.NoModifier, '', '<Backtab>'), - ('', Qt.Key_Backtab, Qt.ShiftModifier, '', '<Shift+Tab>'), - ('', Qt.Key_Backtab, Qt.AltModifier | Qt.ShiftModifier, '', + ('', Qt.Key.Key_Backtab, Qt.KeyboardModifier.NoModifier, '', '<Backtab>'), + ('', Qt.Key.Key_Backtab, Qt.KeyboardModifier.ShiftModifier, '', '<Shift+Tab>'), + ('', Qt.Key.Key_Backtab, Qt.KeyboardModifier.AltModifier | Qt.KeyboardModifier.ShiftModifier, '', '<Alt+Shift+Tab>'), - # Stripping of Qt.GroupSwitchModifier - ('', Qt.Key_A, Qt.GroupSwitchModifier, 'a', 'a'), + # Stripping of Qt.KeyboardModifier.GroupSwitchModifier + ('', Qt.Key.Key_A, Qt.KeyboardModifier.GroupSwitchModifier, 'a', 'a'), ]) def test_append_event(self, old, key, modifiers, text, expected): seq = keyutils.KeySequence.parse(old) @@ -447,39 +447,39 @@ class TestKeySequence: @pytest.mark.fake_os('mac') @pytest.mark.parametrize('modifiers, expected', [ - (Qt.ControlModifier, - Qt.MetaModifier), - (Qt.MetaModifier, - Qt.ControlModifier), - (Qt.ControlModifier | Qt.MetaModifier, - Qt.ControlModifier | Qt.MetaModifier), - (Qt.ControlModifier | Qt.ShiftModifier, - Qt.MetaModifier | Qt.ShiftModifier), - (Qt.MetaModifier | Qt.ShiftModifier, - Qt.ControlModifier | Qt.ShiftModifier), - (Qt.ShiftModifier, Qt.ShiftModifier), + (Qt.KeyboardModifier.ControlModifier, + Qt.KeyboardModifier.MetaModifier), + (Qt.KeyboardModifier.MetaModifier, + Qt.KeyboardModifier.ControlModifier), + (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.MetaModifier, + Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.MetaModifier), + (Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier, + Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.ShiftModifier), + (Qt.KeyboardModifier.MetaModifier | Qt.KeyboardModifier.ShiftModifier, + Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.ShiftModifier), + (Qt.KeyboardModifier.ShiftModifier, Qt.KeyboardModifier.ShiftModifier), ]) def test_fake_mac(self, modifiers, expected): """Make sure Control/Meta are swapped with a simulated Mac.""" seq = keyutils.KeySequence() - info = keyutils.KeyInfo(key=Qt.Key_A, modifiers=modifiers) + info = keyutils.KeyInfo(key=Qt.Key.Key_A, modifiers=modifiers) new = seq.append_event(info.to_event()) - assert new[0] == keyutils.KeyInfo(Qt.Key_A, expected) + assert new[0] == keyutils.KeyInfo(Qt.Key.Key_A, expected) - @pytest.mark.parametrize('key', [Qt.Key_unknown, 0x0]) + @pytest.mark.parametrize('key', [Qt.Key.Key_unknown, 0x0]) def test_append_event_invalid(self, key): seq = keyutils.KeySequence() - event = QKeyEvent(QKeyEvent.KeyPress, key, Qt.NoModifier, '') + event = QKeyEvent(QKeyEvent.KeyPress, key, Qt.KeyboardModifier.NoModifier, '') with pytest.raises(keyutils.KeyParseError): seq.append_event(event) def test_strip_modifiers(self): - seq = keyutils.KeySequence(Qt.Key_0, - Qt.Key_1 | Qt.KeypadModifier, - Qt.Key_A | Qt.ControlModifier) - expected = keyutils.KeySequence(Qt.Key_0, - Qt.Key_1, - Qt.Key_A | Qt.ControlModifier) + seq = keyutils.KeySequence(Qt.Key.Key_0, + Qt.Key.Key_1 | Qt.KeyboardModifier.KeypadModifier, + Qt.Key.Key_A | Qt.KeyboardModifier.ControlModifier) + expected = keyutils.KeySequence(Qt.Key.Key_0, + Qt.Key.Key_1, + Qt.Key.Key_A | Qt.KeyboardModifier.ControlModifier) assert seq.strip_modifiers() == expected @pytest.mark.parametrize('inp, mappings, expected', [ @@ -497,31 +497,31 @@ class TestKeySequence: @pytest.mark.parametrize('keystr, expected', [ ('<Ctrl-Alt-y>', - keyutils.KeySequence(Qt.ControlModifier | Qt.AltModifier | Qt.Key_Y)), - ('x', keyutils.KeySequence(Qt.Key_X)), - ('X', keyutils.KeySequence(Qt.ShiftModifier | Qt.Key_X)), - ('<Escape>', keyutils.KeySequence(Qt.Key_Escape)), - ('xyz', keyutils.KeySequence(Qt.Key_X, Qt.Key_Y, Qt.Key_Z)), + keyutils.KeySequence(Qt.KeyboardModifier.ControlModifier | Qt.KeyboardModifier.AltModifier | Qt.Key.Key_Y)), + ('x', keyutils.KeySequence(Qt.Key.Key_X)), + ('X', keyutils.KeySequence(Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_X)), + ('<Escape>', keyutils.KeySequence(Qt.Key.Key_Escape)), + ('xyz', keyutils.KeySequence(Qt.Key.Key_X, Qt.Key.Key_Y, Qt.Key.Key_Z)), ('<Control-x><Meta-y>', - keyutils.KeySequence(Qt.ControlModifier | Qt.Key_X, - Qt.MetaModifier | Qt.Key_Y)), - - ('<Shift-x>', keyutils.KeySequence(Qt.ShiftModifier | Qt.Key_X)), - ('<Alt-x>', keyutils.KeySequence(Qt.AltModifier | Qt.Key_X)), - ('<Control-x>', keyutils.KeySequence(Qt.ControlModifier | Qt.Key_X)), - ('<Meta-x>', keyutils.KeySequence(Qt.MetaModifier | Qt.Key_X)), - ('<Num-x>', keyutils.KeySequence(Qt.KeypadModifier | Qt.Key_X)), - - ('>', keyutils.KeySequence(Qt.Key_Greater)), - ('<', keyutils.KeySequence(Qt.Key_Less)), - ('a>', keyutils.KeySequence(Qt.Key_A, Qt.Key_Greater)), - ('a<', keyutils.KeySequence(Qt.Key_A, Qt.Key_Less)), - ('>a', keyutils.KeySequence(Qt.Key_Greater, Qt.Key_A)), - ('<a', keyutils.KeySequence(Qt.Key_Less, Qt.Key_A)), + keyutils.KeySequence(Qt.KeyboardModifier.ControlModifier | Qt.Key.Key_X, + Qt.KeyboardModifier.MetaModifier | Qt.Key.Key_Y)), + + ('<Shift-x>', keyutils.KeySequence(Qt.KeyboardModifier.ShiftModifier | Qt.Key.Key_X)), + ('<Alt-x>', keyutils.KeySequence(Qt.KeyboardModifier.AltModifier | Qt.Key.Key_X)), + ('<Control-x>', keyutils.KeySequence(Qt.KeyboardModifier.ControlModifier | Qt.Key.Key_X)), + ('<Meta-x>', keyutils.KeySequence(Qt.KeyboardModifier.MetaModifier | Qt.Key.Key_X)), + ('<Num-x>', keyutils.KeySequence(Qt.KeyboardModifier.KeypadModifier | Qt.Key.Key_X)), + + ('>', keyutils.KeySequence(Qt.Key.Key_Greater)), + ('<', keyutils.KeySequence(Qt.Key.Key_Less)), + ('a>', keyutils.KeySequence(Qt.Key.Key_A, Qt.Key.Key_Greater)), + ('a<', keyutils.KeySequence(Qt.Key.Key_A, Qt.Key.Key_Less)), + ('>a', keyutils.KeySequence(Qt.Key.Key_Greater, Qt.Key.Key_A)), + ('<a', keyutils.KeySequence(Qt.Key.Key_Less, Qt.Key.Key_A)), ('<alt+greater>', - keyutils.KeySequence(Qt.Key_Greater | Qt.AltModifier)), + keyutils.KeySequence(Qt.Key.Key_Greater | Qt.KeyboardModifier.AltModifier)), ('<alt+less>', - keyutils.KeySequence(Qt.Key_Less | Qt.AltModifier)), + keyutils.KeySequence(Qt.Key.Key_Less | Qt.KeyboardModifier.AltModifier)), ('<alt+<>', keyutils.KeyParseError), ('<alt+>>', keyutils.KeyParseError), @@ -547,66 +547,66 @@ class TestKeySequence: def test_key_info_from_event(): - ev = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.ShiftModifier, 'A') + ev = QKeyEvent(QEvent.Type.KeyPress, Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier, 'A') info = keyutils.KeyInfo.from_event(ev) - assert info.key == Qt.Key_A - assert info.modifiers == Qt.ShiftModifier + assert info.key == Qt.Key.Key_A + assert info.modifiers == Qt.KeyboardModifier.ShiftModifier def test_key_info_to_event(): - info = keyutils.KeyInfo(Qt.Key_A, Qt.ShiftModifier) + info = keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier) ev = info.to_event() - assert ev.key() == Qt.Key_A - assert ev.modifiers() == Qt.ShiftModifier + assert ev.key() == Qt.Key.Key_A + assert ev.modifiers() == Qt.KeyboardModifier.ShiftModifier assert ev.text() == 'A' def test_key_info_to_int(): - info = keyutils.KeyInfo(Qt.Key_A, Qt.ShiftModifier) - assert info.to_int() == Qt.Key_A | Qt.ShiftModifier + info = keyutils.KeyInfo(Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier) + assert info.to_int() == Qt.Key.Key_A | Qt.KeyboardModifier.ShiftModifier @pytest.mark.parametrize('key, printable', [ - (Qt.Key_Control, False), - (Qt.Key_Escape, False), - (Qt.Key_Tab, False), - (Qt.Key_Backtab, False), - (Qt.Key_Backspace, False), - (Qt.Key_Return, False), - (Qt.Key_Enter, False), - (Qt.Key_Space, False), + (Qt.Key.Key_Control, False), + (Qt.Key.Key_Escape, False), + (Qt.Key.Key_Tab, False), + (Qt.Key.Key_Backtab, False), + (Qt.Key.Key_Backspace, False), + (Qt.Key.Key_Return, False), + (Qt.Key.Key_Enter, False), + (Qt.Key.Key_Space, False), (0x0, False), # Used by Qt for unknown keys - (Qt.Key_ydiaeresis, True), - (Qt.Key_X, True), + (Qt.Key.Key_ydiaeresis, True), + (Qt.Key.Key_X, True), ]) def test_is_printable(key, printable): assert keyutils._is_printable(key) == printable - assert keyutils.is_special(key, Qt.NoModifier) != printable + assert keyutils.is_special(key, Qt.KeyboardModifier.NoModifier) != printable @pytest.mark.parametrize('key, modifiers, special', [ - (Qt.Key_Escape, Qt.NoModifier, True), - (Qt.Key_Escape, Qt.ShiftModifier, True), - (Qt.Key_Escape, Qt.ControlModifier, True), - (Qt.Key_X, Qt.ControlModifier, True), - (Qt.Key_X, Qt.NoModifier, False), - (Qt.Key_2, Qt.KeypadModifier, True), - (Qt.Key_2, Qt.NoModifier, False), - (Qt.Key_Shift, Qt.ShiftModifier, True), - (Qt.Key_Control, Qt.ControlModifier, True), - (Qt.Key_Alt, Qt.AltModifier, True), - (Qt.Key_Meta, Qt.MetaModifier, True), - (Qt.Key_Mode_switch, Qt.GroupSwitchModifier, True), + (Qt.Key.Key_Escape, Qt.KeyboardModifier.NoModifier, True), + (Qt.Key.Key_Escape, Qt.KeyboardModifier.ShiftModifier, True), + (Qt.Key.Key_Escape, Qt.KeyboardModifier.ControlModifier, True), + (Qt.Key.Key_X, Qt.KeyboardModifier.ControlModifier, True), + (Qt.Key.Key_X, Qt.KeyboardModifier.NoModifier, False), + (Qt.Key.Key_2, Qt.KeyboardModifier.KeypadModifier, True), + (Qt.Key.Key_2, Qt.KeyboardModifier.NoModifier, False), + (Qt.Key.Key_Shift, Qt.KeyboardModifier.ShiftModifier, True), + (Qt.Key.Key_Control, Qt.KeyboardModifier.ControlModifier, True), + (Qt.Key.Key_Alt, Qt.KeyboardModifier.AltModifier, True), + (Qt.Key.Key_Meta, Qt.KeyboardModifier.MetaModifier, True), + (Qt.Key.Key_Mode_switch, Qt.KeyboardModifier.GroupSwitchModifier, True), ]) def test_is_special(key, modifiers, special): assert keyutils.is_special(key, modifiers) == special @pytest.mark.parametrize('key, ismodifier', [ - (Qt.Key_Control, True), - (Qt.Key_X, False), - (Qt.Key_Super_L, False), # Modifier but not in _MODIFIER_MAP + (Qt.Key.Key_Control, True), + (Qt.Key.Key_X, False), + (Qt.Key.Key_Super_L, False), # Modifier but not in _MODIFIER_MAP ]) def test_is_modifier_key(key, ismodifier): assert keyutils.is_modifier_key(key) == ismodifier @@ -622,4 +622,4 @@ def test_is_modifier_key(key, ismodifier): ]) def test_non_plain(func): with pytest.raises(AssertionError): - func(Qt.Key_X | Qt.ControlModifier) + func(Qt.Key.Key_X | Qt.KeyboardModifier.ControlModifier) diff --git a/tests/unit/keyinput/test_modeman.py b/tests/unit/keyinput/test_modeman.py index 61e2a6a96..ee24098ff 100644 --- a/tests/unit/keyinput/test_modeman.py +++ b/tests/unit/keyinput/test_modeman.py @@ -53,11 +53,11 @@ def set_qapp(monkeypatch, qapp): @pytest.mark.parametrize('key, modifiers, filtered', [ - (Qt.Key_A, Qt.NoModifier, True), - (Qt.Key_Up, Qt.NoModifier, False), + (Qt.Key.Key_A, Qt.KeyboardModifier.NoModifier, True), + (Qt.Key.Key_Up, Qt.KeyboardModifier.NoModifier, False), # https://github.com/qutebrowser/qutebrowser/issues/1207 - (Qt.Key_A, Qt.ShiftModifier, True), - (Qt.Key_A, Qt.ShiftModifier | Qt.ControlModifier, False), + (Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier, True), + (Qt.Key.Key_A, Qt.KeyboardModifier.ShiftModifier | Qt.KeyboardModifier.ControlModifier, False), ]) def test_non_alphanumeric(key, modifiers, filtered, modeman): """Make sure non-alphanumeric keys are passed through correctly.""" diff --git a/tests/unit/keyinput/test_modeparsers.py b/tests/unit/keyinput/test_modeparsers.py index 62d332b9f..fa8918a0b 100644 --- a/tests/unit/keyinput/test_modeparsers.py +++ b/tests/unit/keyinput/test_modeparsers.py @@ -65,7 +65,7 @@ class TestsNormalKeyParser: # Press 'b' for a partial match. # Then we check if the timer has been set up correctly - keyparser.handle(keyutils.KeyInfo(Qt.Key_B, Qt.NoModifier).to_event()) + keyparser.handle(keyutils.KeyInfo(Qt.Key.Key_B, Qt.KeyboardModifier.NoModifier).to_event()) assert timer.isSingleShot() assert timer.interval() == 100 assert timer.isActive() @@ -129,11 +129,11 @@ class TestHintKeyParser: assert len(seq) == 2 match = keyparser.handle(seq[0].to_event()) - assert match == QKeySequence.PartialMatch + assert match == QKeySequence.SequenceMatch.PartialMatch assert hintmanager.keystr == prefix match = keyparser.handle(seq[1].to_event()) - assert match == QKeySequence.ExactMatch + assert match == QKeySequence.SequenceMatch.ExactMatch assert hintmanager.keystr == hint def test_match_key_mappings(self, config_stub, keyparser, hintmanager): @@ -144,11 +144,11 @@ class TestHintKeyParser: assert len(seq) == 2 match = keyparser.handle(seq[0].to_event()) - assert match == QKeySequence.PartialMatch + assert match == QKeySequence.SequenceMatch.PartialMatch assert hintmanager.keystr == 'a' match = keyparser.handle(seq[1].to_event()) - assert match == QKeySequence.ExactMatch + assert match == QKeySequence.SequenceMatch.ExactMatch assert hintmanager.keystr == 'as' def test_command(self, keyparser, config_stub, hintmanager, commandrunner): @@ -159,17 +159,17 @@ class TestHintKeyParser: keyparser.update_bindings(['xabcy']) steps = [ - (Qt.Key_X, QKeySequence.PartialMatch, 'x'), - (Qt.Key_A, QKeySequence.PartialMatch, ''), - (Qt.Key_B, QKeySequence.PartialMatch, ''), - (Qt.Key_C, QKeySequence.ExactMatch, ''), + (Qt.Key.Key_X, QKeySequence.SequenceMatch.PartialMatch, 'x'), + (Qt.Key.Key_A, QKeySequence.SequenceMatch.PartialMatch, ''), + (Qt.Key.Key_B, QKeySequence.SequenceMatch.PartialMatch, ''), + (Qt.Key.Key_C, QKeySequence.SequenceMatch.ExactMatch, ''), ] for key, expected_match, keystr in steps: - info = keyutils.KeyInfo(key, Qt.NoModifier) + info = keyutils.KeyInfo(key, Qt.KeyboardModifier.NoModifier) match = keyparser.handle(info.to_event()) assert match == expected_match assert hintmanager.keystr == keystr - if key != Qt.Key_C: + if key != Qt.Key.Key_C: assert not commandrunner.commands assert commandrunner.commands == [('message-info abc', None)] diff --git a/tests/unit/mainwindow/statusbar/test_textbase.py b/tests/unit/mainwindow/statusbar/test_textbase.py index a3ea6b893..6bceb4bc4 100644 --- a/tests/unit/mainwindow/statusbar/test_textbase.py +++ b/tests/unit/mainwindow/statusbar/test_textbase.py @@ -26,10 +26,10 @@ from qutebrowser.mainwindow.statusbar.textbase import TextBase @pytest.mark.parametrize('elidemode, check', [ - (Qt.ElideRight, lambda s: s.endswith('…') or s.endswith('...')), - (Qt.ElideLeft, lambda s: s.startswith('…') or s.startswith('...')), - (Qt.ElideMiddle, lambda s: '…' in s or '...' in s), - (Qt.ElideNone, lambda s: '…' not in s and '...' not in s), + (Qt.TextElideMode.ElideRight, lambda s: s.endswith('…') or s.endswith('...')), + (Qt.TextElideMode.ElideLeft, lambda s: s.startswith('…') or s.startswith('...')), + (Qt.TextElideMode.ElideMiddle, lambda s: '…' in s or '...' in s), + (Qt.TextElideMode.ElideNone, lambda s: '…' not in s and '...' not in s), ]) def test_elided_text(fake_statusbar, qtbot, elidemode, check): """Ensure that a widget too small to hold the entire label text will elide. diff --git a/tests/unit/mainwindow/test_messageview.py b/tests/unit/mainwindow/test_messageview.py index 06badd0cf..77d1911d0 100644 --- a/tests/unit/mainwindow/test_messageview.py +++ b/tests/unit/mainwindow/test_messageview.py @@ -239,10 +239,10 @@ def test_replacing_geometry(qtbot, view): @pytest.mark.parametrize('button, count', [ - (Qt.LeftButton, 0), - (Qt.MiddleButton, 0), - (Qt.RightButton, 0), - (Qt.BackButton, 2), + (Qt.MouseButton.LeftButton, 0), + (Qt.MouseButton.MiddleButton, 0), + (Qt.MouseButton.RightButton, 0), + (Qt.MouseButton.BackButton, 2), ]) def test_click_messages(qtbot, view, button, count): """Messages should disappear when we click on them.""" diff --git a/tests/unit/mainwindow/test_prompt.py b/tests/unit/mainwindow/test_prompt.py index 31f682de8..4dbe5a41a 100644 --- a/tests/unit/mainwindow/test_prompt.py +++ b/tests/unit/mainwindow/test_prompt.py @@ -79,7 +79,7 @@ class TestFileCompletion: # Deleting /f[oo/] with qtbot.wait_signal(prompt._file_model.directoryLoaded): for _ in range(3): - qtbot.keyPress(prompt._lineedit, Qt.Key_Backspace) + qtbot.keyPress(prompt._lineedit, Qt.Key.Key_Backspace) # For some reason, this isn't always called when using qtbot.keyPress. prompt._set_fileview_root(prompt._lineedit.text()) @@ -90,7 +90,7 @@ class TestFileCompletion: # Deleting /[foo] for _ in range(3): - qtbot.keyPress(prompt._lineedit, Qt.Key_Backspace) + qtbot.keyPress(prompt._lineedit, Qt.Key.Key_Backspace) # We should now show / again, so tabbing twice gives us bar -> foo prompt.item_focus('next') @@ -99,8 +99,8 @@ class TestFileCompletion: @pytest.mark.parametrize("keys, expected", [ ([], ['bar', 'bat', 'foo']), - ([Qt.Key_F], ['foo']), - ([Qt.Key_A], ['bar', 'bat']), + ([Qt.Key.Key_F], ['foo']), + ([Qt.Key.Key_A], ['bar', 'bat']), ]) def test_filtering_path(self, qtbot, tmp_path, get_prompt, keys, expected): testdir = tmp_path / 'test' diff --git a/tests/unit/misc/test_editor.py b/tests/unit/misc/test_editor.py index 5f45a0f3e..628ee8545 100644 --- a/tests/unit/misc/test_editor.py +++ b/tests/unit/misc/test_editor.py @@ -81,7 +81,7 @@ class TestFileHandling: filename = pathlib.Path(editor._filename) assert filename.exists() assert filename.name.startswith('qutebrowser-editor-') - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) assert filename.exists() != config_stub.val.editor.remove_file @pytest.mark.parametrize('touch', [True, False]) @@ -92,7 +92,7 @@ class TestFileHandling: path.touch() editor.edit_file(str(path)) - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) assert path.exists() @@ -103,7 +103,7 @@ class TestFileHandling: assert filename.exists() with caplog.at_level(logging.ERROR): - editor._proc._proc.finished.emit(1, QProcess.NormalExit) + editor._proc._proc.finished.emit(1, QProcess.ExitStatus.NormalExit) assert filename.exists() @@ -115,9 +115,9 @@ class TestFileHandling: filename = pathlib.Path(editor._filename) assert filename.exists() - editor._proc.error.emit(QProcess.Crashed) + editor._proc.error.emit(QProcess.ProcessError.Crashed) with caplog.at_level(logging.ERROR): - editor._proc._proc.finished.emit(0, QProcess.CrashExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.CrashExit) assert filename.exists() filename.unlink() @@ -133,7 +133,7 @@ class TestFileHandling: pytest.skip("File was still readable") with caplog.at_level(logging.ERROR): - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) assert not filename.exists() msg = message_mock.getmsg(usertypes.MessageLevel.error) assert msg.text.startswith("Failed to read back edited file: ") @@ -181,7 +181,7 @@ class TestFileHandling: fname = msg.text[len(prefix):] with qtbot.wait_signal(editor.editing_finished): - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) with open(fname, 'r', encoding='utf-8') as f: assert f.read() == 'bar' @@ -224,7 +224,7 @@ def test_modify(qtbot, editor, initial_text, edited_text): f.write(edited_text) with qtbot.wait_signal(editor.file_updated) as blocker: - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) assert blocker.args == [edited_text] @@ -258,7 +258,7 @@ def test_modify_watch(qtbot): assert blocker.args == ['baz'] with qtbot.assert_not_emitted(editor.file_updated): - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) def test_failing_watch(qtbot, caplog, monkeypatch): @@ -276,7 +276,7 @@ def test_failing_watch(qtbot, caplog, monkeypatch): _update_file(editor._filename, 'bar') with qtbot.wait_signal(editor.file_updated) as blocker: - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) assert blocker.args == ['bar'] message = 'Failed to watch path: {}'.format(editor._filename) @@ -293,7 +293,7 @@ def test_failing_unwatch(qtbot, caplog, monkeypatch): editor.edit('foo') with caplog.at_level(logging.ERROR): - editor._proc._proc.finished.emit(0, QProcess.NormalExit) + editor._proc._proc.finished.emit(0, QProcess.ExitStatus.NormalExit) message = 'Failed to unwatch paths: [{!r}]'.format(editor._filename) assert caplog.messages[-1] == message diff --git a/tests/unit/misc/test_guiprocess.py b/tests/unit/misc/test_guiprocess.py index 1ac3ddebf..702a1dca8 100644 --- a/tests/unit/misc/test_guiprocess.py +++ b/tests/unit/misc/test_guiprocess.py @@ -36,7 +36,7 @@ def proc(qtbot, caplog): """A fixture providing a GUIProcess and cleaning it up after the test.""" p = guiprocess.GUIProcess('testprocess') yield p - if not sip.isdeleted(p._proc) and p._proc.state() != QProcess.NotRunning: + if not sip.isdeleted(p._proc) and p._proc.state() != QProcess.ProcessState.NotRunning: with caplog.at_level(logging.ERROR): with qtbot.wait_signal(p.finished, timeout=10000, raising=False) as blocker: @@ -126,7 +126,7 @@ def test_start(proc, qtbot, message_mock, py_proc): assert not message_mock.messages assert not proc.outcome.running - assert proc.outcome.status == QProcess.NormalExit + assert proc.outcome.status == QProcess.ExitStatus.NormalExit assert proc.outcome.code == 0 assert str(proc.outcome) == 'Testprocess exited successfully.' assert proc.outcome.state_str() == 'successful' @@ -434,7 +434,7 @@ def test_exit_unsuccessful(qtbot, proc, message_mock, py_proc, caplog): assert msg.text == expected assert not proc.outcome.running - assert proc.outcome.status == QProcess.NormalExit + assert proc.outcome.status == QProcess.ExitStatus.NormalExit assert proc.outcome.code == 1 assert str(proc.outcome) == 'Testprocess exited with status 1.' assert proc.outcome.state_str() == 'unsuccessful' @@ -454,7 +454,7 @@ def test_exit_crash(qtbot, proc, message_mock, py_proc, caplog): assert msg.text == "Testprocess crashed. See :process for details." assert not proc.outcome.running - assert proc.outcome.status == QProcess.CrashExit + assert proc.outcome.status == QProcess.ExitStatus.CrashExit assert str(proc.outcome) == 'Testprocess crashed.' assert proc.outcome.state_str() == 'crashed' assert not proc.outcome.was_successful() diff --git a/tests/unit/misc/test_ipc.py b/tests/unit/misc/test_ipc.py index f83d1a94a..82b4bf533 100644 --- a/tests/unit/misc/test_ipc.py +++ b/tests/unit/misc/test_ipc.py @@ -56,7 +56,7 @@ def ipc_server(qapp, qtbot): server = ipc.IPCServer('qute-test') yield server if (server._socket is not None and - server._socket.state() != QLocalSocket.UnconnectedState): + server._socket.state() != QLocalSocket.LocalSocketState.UnconnectedState): with qtbot.wait_signal(server._socket.disconnected, raising=False): server._socket.abort() try: @@ -78,7 +78,7 @@ def qlocalsocket(qapp): socket = QLocalSocket() yield socket socket.disconnectFromServer() - if socket.state() != QLocalSocket.UnconnectedState: + if socket.state() != QLocalSocket.LocalSocketState.UnconnectedState: socket.waitForDisconnected(1000) @@ -103,7 +103,7 @@ class FakeSocket(QObject): readyRead = pyqtSignal() # noqa: N815 disconnected = pyqtSignal() - def __init__(self, *, error=QLocalSocket.UnknownSocketError, state=None, + def __init__(self, *, error=QLocalSocket.LocalSocketError.UnknownSocketError, state=None, data=None, connect_successful=True, parent=None): super().__init__(parent) self._error_val = error @@ -280,9 +280,9 @@ class TestExceptions: raise exc def test_socket_error(self, qlocalserver): - socket = FakeSocket(error=QLocalSocket.ConnectionRefusedError) + socket = FakeSocket(error=QLocalSocket.LocalSocketError.ConnectionRefusedError) exc = ipc.SocketError("testing", socket) - assert exc.code == QLocalSocket.ConnectionRefusedError + assert exc.code == QLocalSocket.LocalSocketError.ConnectionRefusedError assert exc.message == "Error string" assert str(exc) == "Error while testing: Error string (error 0)" @@ -322,7 +322,7 @@ class TestListen: @pytest.mark.windows def test_permissions_windows(self, ipc_server): opts = ipc_server._server.socketOptions() - assert opts == QLocalServer.UserAccessOption + assert opts == QLocalServer.SocketOption.UserAccessOption @pytest.mark.posix def test_permissions_posix(self, ipc_server): @@ -406,21 +406,21 @@ class TestOnError: ipc_server._socket = QLocalSocket() ipc_server._timer.timeout.disconnect() ipc_server._timer.start() - ipc_server.on_error(QLocalSocket.PeerClosedError) + ipc_server.on_error(QLocalSocket.LocalSocketError.PeerClosedError) assert not ipc_server._timer.isActive() def test_other_error(self, ipc_server, monkeypatch): socket = QLocalSocket() ipc_server._socket = socket monkeypatch.setattr(socket, 'error', - lambda: QLocalSocket.ConnectionRefusedError) + lambda: QLocalSocket.LocalSocketError.ConnectionRefusedError) monkeypatch.setattr(socket, 'errorString', lambda: "Connection refused") socket.setErrorString("Connection refused.") with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Connection refused \(error 0\)"): - ipc_server.on_error(QLocalSocket.ConnectionRefusedError) + ipc_server.on_error(QLocalSocket.LocalSocketError.ConnectionRefusedError) class TestHandleConnection: @@ -444,13 +444,13 @@ class TestHandleConnection: assert any(message.startswith(msg) for message in caplog.messages) def test_disconnected_immediately(self, ipc_server, caplog): - socket = FakeSocket(state=QLocalSocket.UnconnectedState) + socket = FakeSocket(state=QLocalSocket.LocalSocketState.UnconnectedState) ipc_server._server = FakeServer(socket) ipc_server.handle_connection() assert "Socket was disconnected immediately." in caplog.messages def test_error_immediately(self, ipc_server, caplog): - socket = FakeSocket(error=QLocalSocket.ConnectionError) + socket = FakeSocket(error=QLocalSocket.LocalSocketError.ConnectionError) ipc_server._server = FakeServer(socket) with pytest.raises(ipc.Error, match=r"Error while handling IPC " @@ -588,7 +588,7 @@ class TestSendToRunningInstance: assert parsed == raw_expected def test_socket_error(self): - socket = FakeSocket(error=QLocalSocket.ConnectionError) + socket = FakeSocket(error=QLocalSocket.LocalSocketError.ConnectionError) with pytest.raises(ipc.Error, match=r"Error while writing to running " r"instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) @@ -598,7 +598,7 @@ class TestSendToRunningInstance: ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_socket_error_no_server(self): - socket = FakeSocket(error=QLocalSocket.ConnectionError, + socket = FakeSocket(error=QLocalSocket.LocalSocketError.ConnectionError, connect_successful=False) with pytest.raises(ipc.Error, match=r"Error while connecting to " r"running instance: Error string \(error 7\)"): @@ -701,14 +701,14 @@ class TestSendOrListen: -> success """ qlocalserver_mock().listen.return_value = False - err = QAbstractSocket.AddressInUseError + err = QAbstractSocket.SocketError.AddressInUseError qlocalserver_mock().serverError.return_value = err qlocalsocket_mock().waitForConnected.side_effect = [False, True] qlocalsocket_mock().error.side_effect = [ - QLocalSocket.ServerNotFoundError, - QLocalSocket.UnknownSocketError, - QLocalSocket.UnknownSocketError, # error() gets called twice + QLocalSocket.LocalSocketError.ServerNotFoundError, + QLocalSocket.LocalSocketError.UnknownSocketError, + QLocalSocket.LocalSocketError.UnknownSocketError, # error() gets called twice ] ret = ipc.send_or_listen(args) @@ -734,17 +734,17 @@ class TestSendOrListen: -> not sent / error """ qlocalserver_mock().listen.return_value = False - err = QAbstractSocket.AddressInUseError + err = QAbstractSocket.SocketError.AddressInUseError qlocalserver_mock().serverError.return_value = err # If the second connection succeeds, we will have an error later. # If it fails, that's the "not sent" case above. qlocalsocket_mock().waitForConnected.side_effect = [False, has_error] qlocalsocket_mock().error.side_effect = [ - QLocalSocket.ServerNotFoundError, - QLocalSocket.ServerNotFoundError, - QLocalSocket.ConnectionRefusedError, - QLocalSocket.ConnectionRefusedError, # error() gets called twice + QLocalSocket.LocalSocketError.ServerNotFoundError, + QLocalSocket.LocalSocketError.ServerNotFoundError, + QLocalSocket.LocalSocketError.ConnectionRefusedError, + QLocalSocket.LocalSocketError.ConnectionRefusedError, # error() gets called twice ] with caplog.at_level(logging.ERROR): @@ -766,7 +766,7 @@ class TestSendOrListen: def test_error_while_listening(self, qlocalserver_mock, caplog, args): """Test an error with the first listen call.""" qlocalserver_mock().listen.return_value = False - err = QAbstractSocket.SocketResourceError + err = QAbstractSocket.SocketError.SocketResourceError qlocalserver_mock().serverError.return_value = err with caplog.at_level(logging.ERROR): @@ -809,7 +809,7 @@ def test_connect_inexistent(qlocalsocket): would not work properly. """ qlocalsocket.connectToServer('qute-test-inexistent') - assert qlocalsocket.error() == QLocalSocket.ServerNotFoundError + assert qlocalsocket.error() == QLocalSocket.LocalSocketError.ServerNotFoundError @pytest.mark.posix @@ -826,7 +826,7 @@ def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir): assert ok s2 = QLocalServer() - s2.setSocketOptions(QLocalServer.UserAccessOption) + s2.setSocketOptions(QLocalServer.SocketOption.UserAccessOption) ok = s2.listen(servername) print(s2.errorString()) # We actually would expect ok == False here - but we want the test to fail diff --git a/tests/unit/misc/test_miscwidgets.py b/tests/unit/misc/test_miscwidgets.py index 9d99d2d48..b6c0873dd 100644 --- a/tests/unit/misc/test_miscwidgets.py +++ b/tests/unit/misc/test_miscwidgets.py @@ -48,9 +48,9 @@ class TestCommandLineEdit: cmd_edit.home(True) assert cmd_edit.cursorPosition() == len(':') - qtbot.keyClick(cmd_edit, Qt.Key_Delete) + qtbot.keyClick(cmd_edit, Qt.Key.Key_Delete) assert cmd_edit.text() == ':' - qtbot.keyClick(cmd_edit, Qt.Key_Backspace) + qtbot.keyClick(cmd_edit, Qt.Key.Key_Backspace) assert cmd_edit.text() == ':' qtbot.keyClicks(cmd_edit, 'hey again') @@ -76,7 +76,7 @@ class TestCommandLineEdit: assert cmd_edit.text() == ':hello' assert cmd_edit.cursorPosition() == len(':hello') for _ in ':hello': - qtbot.keyClick(cmd_edit, Qt.Key_Left, modifier=Qt.ShiftModifier) + qtbot.keyClick(cmd_edit, Qt.Key.Key_Left, modifier=Qt.KeyboardModifier.ShiftModifier) assert cmd_edit.cursorPosition() == len(':') assert cmd_edit.selectionStart() == len(':') @@ -165,10 +165,10 @@ class TestInspectorSplitter: @pytest.mark.parametrize( 'position, orientation, inspector_idx, webview_idx', [ - (inspector.Position.left, Qt.Horizontal, 0, 1), - (inspector.Position.right, Qt.Horizontal, 1, 0), - (inspector.Position.top, Qt.Vertical, 0, 1), - (inspector.Position.bottom, Qt.Vertical, 1, 0), + (inspector.Position.left, Qt.Orientation.Horizontal, 0, 1), + (inspector.Position.right, Qt.Orientation.Horizontal, 1, 0), + (inspector.Position.top, Qt.Orientation.Vertical, 0, 1), + (inspector.Position.bottom, Qt.Orientation.Vertical, 1, 0), ] ) def test_set_inspector(self, position, orientation, @@ -260,7 +260,7 @@ class TestInspectorSplitter: new_window_size, exp_inspector_size, position, splitter, fake_inspector, qtbot): def resize(dim): - size = (QSize(dim, 666) if splitter.orientation() == Qt.Horizontal + size = (QSize(dim, 666) if splitter.orientation() == Qt.Orientation.Horizontal else QSize(666, dim)) splitter.resize(size) if splitter.size() != size: diff --git a/tests/unit/misc/test_msgbox.py b/tests/unit/misc/test_msgbox.py index f7b6d352b..6eee28f32 100644 --- a/tests/unit/misc/test_msgbox.py +++ b/tests/unit/misc/test_msgbox.py @@ -38,8 +38,8 @@ def test_attributes(qtbot): text = 'text' parent = QWidget() qtbot.add_widget(parent) - icon = QMessageBox.Critical - buttons = QMessageBox.Ok | QMessageBox.Cancel + icon = QMessageBox.Icon.Critical + buttons = QMessageBox.StandardButton.Ok | QMessageBox.StandardButton.Cancel box = msgbox.msgbox(parent=parent, title=title, text=text, icon=icon, buttons=buttons) @@ -53,13 +53,13 @@ def test_attributes(qtbot): @pytest.mark.parametrize('plain_text, expected', [ - (True, Qt.PlainText), - (False, Qt.RichText), - (None, Qt.AutoText), + (True, Qt.TextFormat.PlainText), + (False, Qt.TextFormat.RichText), + (None, Qt.TextFormat.AutoText), ]) def test_plain_text(qtbot, plain_text, expected): box = msgbox.msgbox(parent=None, title='foo', text='foo', - icon=QMessageBox.Information, plain_text=plain_text) + icon=QMessageBox.Icon.Information, plain_text=plain_text) qtbot.add_widget(box) assert box.textFormat() == expected @@ -73,7 +73,7 @@ def test_finished_signal(qtbot): signal_triggered = True box = msgbox.msgbox(parent=None, title='foo', text='foo', - icon=QMessageBox.Information, on_finished=on_finished) + icon=QMessageBox.Icon.Information, on_finished=on_finished) qtbot.add_widget(box) @@ -89,7 +89,7 @@ def test_information(qtbot): if not utils.is_mac: assert box.windowTitle() == 'foo' assert box.text() == 'bar' - assert box.icon() == QMessageBox.Information + assert box.icon() == QMessageBox.Icon.Information def test_no_err_windows(fake_args, caplog): diff --git a/tests/unit/misc/test_sql.py b/tests/unit/misc/test_sql.py index f8789c06f..da72c5bb1 100644 --- a/tests/unit/misc/test_sql.py +++ b/tests/unit/misc/test_sql.py @@ -95,13 +95,13 @@ class TestSqlError: (sql.SqliteErrorCode.CONSTRAINT, sql.BugError), ]) def test_known(self, error_code, exception): - sql_err = QSqlError("driver text", "db text", QSqlError.UnknownError, + sql_err = QSqlError("driver text", "db text", QSqlError.ErrorType.UnknownError, error_code) with pytest.raises(exception): sql.raise_sqlite_error("Message", sql_err) def test_logging(self, caplog): - sql_err = QSqlError("driver text", "db text", QSqlError.UnknownError, '23') + sql_err = QSqlError("driver text", "db text", QSqlError.ErrorType.UnknownError, '23') with pytest.raises(sql.BugError): sql.raise_sqlite_error("Message", sql_err) diff --git a/tests/unit/utils/test_debug.py b/tests/unit/utils/test_debug.py index 26f3b58e1..ea4930aa3 100644 --- a/tests/unit/utils/test_debug.py +++ b/tests/unit/utils/test_debug.py @@ -40,7 +40,7 @@ class EventObject(QObject): def test_log_events(qapp, caplog): obj = EventObject() - qapp.sendEvent(obj, QEvent(QEvent.User)) + qapp.sendEvent(obj, QEvent(QEvent.Type.User)) qapp.processEvents() assert caplog.messages == ['Event in test_debug.EventObject: User'] @@ -133,19 +133,19 @@ class TestQEnumKey: assert hasattr(QFrame, 'staticMetaObject') @pytest.mark.parametrize('base, value, klass, expected', [ - (QStyle, QStyle.PE_PanelButtonCommand, None, 'PE_PanelButtonCommand'), - (QFrame, QFrame.Sunken, None, 'Sunken'), + (QStyle, QStyle.PrimitiveElement.PE_PanelButtonCommand, None, 'PE_PanelButtonCommand'), + (QFrame, QFrame.Shadow.Sunken, None, 'Sunken'), (QFrame, 0x0030, QFrame.Shadow, 'Sunken'), (QFrame, 0x1337, QFrame.Shadow, '0x1337'), - (Qt, Qt.AnchorLeft, None, 'AnchorLeft'), + (Qt, Qt.AnchorPoint.AnchorLeft, None, 'AnchorLeft'), ]) def test_qenum_key(self, base, value, klass, expected): key = debug.qenum_key(base, value, klass=klass) assert key == expected def test_add_base(self): - key = debug.qenum_key(QFrame, QFrame.Sunken, add_base=True) - assert key == 'QFrame.Sunken' + key = debug.qenum_key(QFrame, QFrame.Shadow.Sunken, add_base=True) + assert key == 'QFrame.Shadow.Sunken' def test_int_noklass(self): """Test passing an int without explicit klass given.""" @@ -163,10 +163,10 @@ class TestQFlagsKey: fixme = pytest.mark.xfail(reason="See issue #42", raises=AssertionError) @pytest.mark.parametrize('base, value, klass, expected', [ - (Qt, Qt.AlignTop, None, 'AlignTop'), - pytest.param(Qt, Qt.AlignLeft | Qt.AlignTop, None, + (Qt, Qt.AlignmentFlag.AlignTop, None, 'AlignTop'), + pytest.param(Qt, Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignTop, None, 'AlignLeft|AlignTop', marks=fixme), - (Qt, Qt.AlignCenter, None, 'AlignHCenter|AlignVCenter'), + (Qt, Qt.AlignmentFlag.AlignCenter, None, 'AlignHCenter|AlignVCenter'), pytest.param(Qt, 0x0021, Qt.Alignment, 'AlignLeft|AlignTop', marks=fixme), (Qt, 0x1100, Qt.Alignment, '0x0100|0x1000'), @@ -199,8 +199,8 @@ class TestQFlagsKey: def test_add_base(self): """Test with add_base=True.""" - flags = debug.qflags_key(Qt, Qt.AlignTop, add_base=True) - assert flags == 'Qt.AlignTop' + flags = debug.qflags_key(Qt, Qt.AlignmentFlag.AlignTop, add_base=True) + assert flags == 'Qt.AlignmentFlag.AlignTop' def test_int_noklass(self): """Test passing an int without explicit klass given.""" diff --git a/tests/unit/utils/test_error.py b/tests/unit/utils/test_error.py index 53bd46d56..576a048de 100644 --- a/tests/unit/utils/test_error.py +++ b/tests/unit/utils/test_error.py @@ -82,8 +82,8 @@ def test_err_windows(qtbot, qapp, pre_text, post_text, expected, caplog): qtbot.add_widget(w) if not utils.is_mac: assert w.windowTitle() == 'title' - assert w.icon() == QMessageBox.Critical - assert w.standardButtons() == QMessageBox.Ok + assert w.icon() == QMessageBox.Icon.Critical + assert w.standardButtons() == QMessageBox.StandardButton.Ok assert w.text() == expected finally: w.close() diff --git a/tests/unit/utils/test_qtutils.py b/tests/unit/utils/test_qtutils.py index f33838f2a..fe642b007 100644 --- a/tests/unit/utils/test_qtutils.py +++ b/tests/unit/utils/test_qtutils.py @@ -205,12 +205,12 @@ def test_ensure_valid(obj, raising, exc_reason, exc_str): @pytest.mark.parametrize('status, raising, message', [ - (QDataStream.Ok, False, None), - (QDataStream.ReadPastEnd, True, "The data stream has read past the end of " + (QDataStream.Status.Ok, False, None), + (QDataStream.Status.ReadPastEnd, True, "The data stream has read past the end of " "the data in the underlying device."), - (QDataStream.ReadCorruptData, True, "The data stream has read corrupt " + (QDataStream.Status.ReadCorruptData, True, "The data stream has read corrupt " "data."), - (QDataStream.WriteFailed, True, "The data stream cannot write to the " + (QDataStream.Status.WriteFailed, True, "The data stream cannot write to the " "underlying device."), ]) def test_check_qdatastream(status, raising, message): @@ -278,12 +278,12 @@ class TestSerializeStream: def stream_mock(self): """Fixture providing a QDataStream-like mock.""" m = unittest.mock.MagicMock(spec=QDataStream) - m.status.return_value = QDataStream.Ok + m.status.return_value = QDataStream.Status.Ok return m def test_serialize_pre_error_mock(self, stream_mock): """Test serialize_stream with an error already set.""" - stream_mock.status.return_value = QDataStream.ReadCorruptData + stream_mock.status.return_value = QDataStream.Status.ReadCorruptData with pytest.raises(OSError, match="The data stream has read corrupt " "data."): @@ -295,7 +295,7 @@ class TestSerializeStream: """Test serialize_stream with an error while serializing.""" obj = QPoint() stream_mock.__lshift__.side_effect = lambda _other: self._set_status( - stream_mock, QDataStream.ReadCorruptData) + stream_mock, QDataStream.Status.ReadCorruptData) with pytest.raises(OSError, match="The data stream has read corrupt " "data."): @@ -305,7 +305,7 @@ class TestSerializeStream: def test_deserialize_pre_error_mock(self, stream_mock): """Test deserialize_stream with an error already set.""" - stream_mock.status.return_value = QDataStream.ReadCorruptData + stream_mock.status.return_value = QDataStream.Status.ReadCorruptData with pytest.raises(OSError, match="The data stream has read corrupt " "data."): @@ -317,7 +317,7 @@ class TestSerializeStream: """Test deserialize_stream with an error while deserializing.""" obj = QPoint() stream_mock.__rshift__.side_effect = lambda _other: self._set_status( - stream_mock, QDataStream.ReadCorruptData) + stream_mock, QDataStream.Status.ReadCorruptData) with pytest.raises(OSError, match="The data stream has read corrupt " "data."): @@ -331,10 +331,10 @@ class TestSerializeStream: dest_obj = QPoint() data = QByteArray() - write_stream = QDataStream(data, QIODevice.WriteOnly) + write_stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly) qtutils.serialize_stream(write_stream, src_obj) - read_stream = QDataStream(data, QIODevice.ReadOnly) + read_stream = QDataStream(data, QIODevice.OpenModeFlag.ReadOnly) qtutils.deserialize_stream(read_stream, dest_obj) assert src_obj == dest_obj @@ -343,7 +343,7 @@ class TestSerializeStream: def test_serialize_readonly_stream(self): """Test serialize_stream with a read-only stream.""" data = QByteArray() - stream = QDataStream(data, QIODevice.ReadOnly) + stream = QDataStream(data, QIODevice.OpenModeFlag.ReadOnly) with pytest.raises(OSError, match="The data stream cannot write to " "the underlying device."): qtutils.serialize_stream(stream, QPoint()) @@ -353,7 +353,7 @@ class TestSerializeStream: """Test deserialize_stream with a write-only stream.""" data = QByteArray() obj = QPoint() - stream = QDataStream(data, QIODevice.WriteOnly) + stream = QDataStream(data, QIODevice.OpenModeFlag.WriteOnly) with pytest.raises(OSError, match="The data stream has read past the " "end of the data in the underlying device."): qtutils.deserialize_stream(stream, obj) @@ -388,7 +388,7 @@ class TestSavefileOpen: with qtutils.savefile_open('filename'): pass - qsavefile_mock.open.assert_called_once_with(QIODevice.WriteOnly) + qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly) qsavefile_mock.cancelWriting.assert_called_once_with() def test_mock_exception(self, qsavefile_mock): @@ -399,7 +399,7 @@ class TestSavefileOpen: with qtutils.savefile_open('filename'): raise SavefileTestException - qsavefile_mock.open.assert_called_once_with(QIODevice.WriteOnly) + qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly) qsavefile_mock.cancelWriting.assert_called_once_with() def test_mock_commit_failed(self, qsavefile_mock): @@ -411,7 +411,7 @@ class TestSavefileOpen: with qtutils.savefile_open('filename'): pass - qsavefile_mock.open.assert_called_once_with(QIODevice.WriteOnly) + qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly) assert not qsavefile_mock.cancelWriting.called assert not qsavefile_mock.errorString.called @@ -426,7 +426,7 @@ class TestSavefileOpen: with qtutils.savefile_open('filename') as f: f.write("Hello World") - qsavefile_mock.open.assert_called_once_with(QIODevice.WriteOnly) + qsavefile_mock.open.assert_called_once_with(QIODevice.OpenModeFlag.WriteOnly) assert not qsavefile_mock.cancelWriting.called qsavefile_mock.write.assert_called_once_with(b"Hello World") @@ -539,10 +539,10 @@ if test_file is not None: def open(self, _fname, mode): """Open an in-memory PyQIODevice instead of a real file.""" modes = { - 'wb': QIODevice.WriteOnly | QIODevice.Truncate, - 'w': QIODevice.WriteOnly | QIODevice.Text | QIODevice.Truncate, - 'rb': QIODevice.ReadOnly, - 'r': QIODevice.ReadOnly | QIODevice.Text, + 'wb': QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Truncate, + 'w': QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Text | QIODevice.OpenModeFlag.Truncate, + 'rb': QIODevice.OpenModeFlag.ReadOnly, + 'r': QIODevice.OpenModeFlag.ReadOnly | QIODevice.OpenModeFlag.Text, } try: qt_mode = modes[mode] @@ -656,14 +656,14 @@ class TestPyQIODevice: Args: method: The name of the method to call. """ - pyqiodev.open(QIODevice.WriteOnly) + pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) func = getattr(pyqiodev, method) with pytest.raises(OSError, match="Trying to read unreadable file!"): func() def test_unwritable(self, pyqiodev): """Test writing with a read-only device.""" - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) with pytest.raises(OSError, match="Trying to write to unwritable " "file!"): pyqiodev.write(b'') @@ -676,7 +676,7 @@ class TestPyQIODevice: data: The data to write before checking if the length equals len(data). """ - pyqiodev.open(QIODevice.WriteOnly) + pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) pyqiodev.write(data) assert len(pyqiodev) == len(data) @@ -685,8 +685,8 @@ class TestPyQIODevice: qf = QFile(str(tmp_path)) dev = qtutils.PyQIODevice(qf) with pytest.raises(qtutils.QtOSError) as excinfo: - dev.open(QIODevice.WriteOnly) - assert excinfo.value.qt_errno == QFileDevice.OpenError + dev.open(QIODevice.OpenModeFlag.WriteOnly) + assert excinfo.value.qt_errno == QFileDevice.FileError.OpenError assert dev.closed def test_fileno(self, pyqiodev): @@ -715,9 +715,9 @@ class TestPyQIODevice: data: The expected data to read after seeking. raising: Whether seeking should raise OSError. """ - with pyqiodev.open(QIODevice.WriteOnly) as f: + with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f: f.write(b'1234567890') - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) if raising: with pytest.raises(OSError, match="seek failed!"): pyqiodev.seek(offset, whence) @@ -736,7 +736,7 @@ class TestPyQIODevice: # pylint: enable=no-member,useless-suppression else: pytest.skip("Needs os.SEEK_HOLE or os.SEEK_DATA available.") - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) with pytest.raises(io.UnsupportedOperation): pyqiodev.seek(0, whence) @@ -765,7 +765,7 @@ class TestPyQIODevice: def test_closed(self, pyqiodev): """Test the closed attribute.""" assert pyqiodev.closed - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) assert not pyqiodev.closed pyqiodev.close() assert pyqiodev.closed @@ -773,14 +773,14 @@ class TestPyQIODevice: def test_contextmanager(self, pyqiodev): """Make sure using the PyQIODevice as context manager works.""" assert pyqiodev.closed - with pyqiodev.open(QIODevice.ReadOnly) as f: + with pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) as f: assert not f.closed assert f is pyqiodev assert pyqiodev.closed def test_flush(self, pyqiodev): """Make sure flushing doesn't raise an exception.""" - pyqiodev.open(QIODevice.WriteOnly) + pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) pyqiodev.write(b'test') pyqiodev.flush() @@ -795,14 +795,14 @@ class TestPyQIODevice: method: The name of the method to call. ret: The return value we expect. """ - pyqiodev.open(QIODevice.WriteOnly) + pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) func = getattr(pyqiodev, method) assert func() == ret @pytest.mark.parametrize('mode, readable, writable', [ - (QIODevice.ReadOnly, True, False), - (QIODevice.ReadWrite, True, True), - (QIODevice.WriteOnly, False, True), + (QIODevice.OpenModeFlag.ReadOnly, True, False), + (QIODevice.OpenModeFlag.ReadWrite, True, True), + (QIODevice.OpenModeFlag.WriteOnly, False, True), ]) def test_readable_writable(self, mode, readable, writable, pyqiodev): """Test readable() and writable(). @@ -831,19 +831,19 @@ class TestPyQIODevice: size: The size to pass to readline() chunks: A list of expected chunks to read. """ - with pyqiodev.open(QIODevice.WriteOnly) as f: + with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f: f.write(b'one\ntwo\nthree') - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) for i, chunk in enumerate(chunks, start=1): print("Expecting chunk {}: {!r}".format(i, chunk)) assert pyqiodev.readline(size) == chunk def test_write(self, pyqiodev): """Make sure writing and re-reading works.""" - with pyqiodev.open(QIODevice.WriteOnly) as f: + with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f: f.write(b'foo\n') f.write(b'bar\n') - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) assert pyqiodev.read() == b'foo\nbar\n' def test_write_error(self, pyqiodev_failing): @@ -857,7 +857,7 @@ class TestPyQIODevice: def test_write_error_real(self): """Test a real write error with /dev/full on supported systems.""" qf = QFile('/dev/full') - qf.open(QIODevice.WriteOnly | QIODevice.Unbuffered) + qf.open(QIODevice.OpenModeFlag.WriteOnly | QIODevice.OpenModeFlag.Unbuffered) dev = qtutils.PyQIODevice(qf) with pytest.raises(OSError, match='No space left on device'): dev.write(b'foo') @@ -876,9 +876,9 @@ class TestPyQIODevice: size: The size to pass to read() chunks: A list of expected data chunks. """ - with pyqiodev.open(QIODevice.WriteOnly) as f: + with pyqiodev.open(QIODevice.OpenModeFlag.WriteOnly) as f: f.write(b'1234567890') - pyqiodev.open(QIODevice.ReadOnly) + pyqiodev.open(QIODevice.OpenModeFlag.ReadOnly) for i, chunk in enumerate(chunks): print("Expecting chunk {}: {!r}".format(i, chunk)) assert pyqiodev.read(size) == chunk @@ -972,9 +972,9 @@ class TestInterpolateColor: def test_invalid_colorspace(self, colors): """Test an invalid colorspace.""" with pytest.raises(ValueError): - qtutils.interpolate_color(colors.white, colors.black, 10, QColor.Cmyk) + qtutils.interpolate_color(colors.white, colors.black, 10, QColor.Spec.Cmyk) - @pytest.mark.parametrize('colorspace', [QColor.Rgb, QColor.Hsv, QColor.Hsl]) + @pytest.mark.parametrize('colorspace', [QColor.Spec.Rgb, QColor.Spec.Hsv, QColor.Spec.Hsl]) def test_0_100(self, colors, colorspace): """Test 0% and 100% in different colorspaces.""" white = qtutils.interpolate_color(colors.white, colors.black, 0, colorspace) @@ -985,7 +985,7 @@ class TestInterpolateColor: def test_interpolation_rgb(self): """Test an interpolation in the RGB colorspace.""" color = qtutils.interpolate_color( - testutils.Color(0, 40, 100), testutils.Color(0, 20, 200), 50, QColor.Rgb) + testutils.Color(0, 40, 100), testutils.Color(0, 20, 200), 50, QColor.Spec.Rgb) assert testutils.Color(color) == testutils.Color(0, 30, 150) def test_interpolation_hsv(self): @@ -994,7 +994,7 @@ class TestInterpolateColor: stop = testutils.Color() start.setHsv(0, 40, 100) stop.setHsv(0, 20, 200) - color = qtutils.interpolate_color(start, stop, 50, QColor.Hsv) + color = qtutils.interpolate_color(start, stop, 50, QColor.Spec.Hsv) expected = testutils.Color() expected.setHsv(0, 30, 150) assert testutils.Color(color) == expected @@ -1005,12 +1005,12 @@ class TestInterpolateColor: stop = testutils.Color() start.setHsl(0, 40, 100) stop.setHsl(0, 20, 200) - color = qtutils.interpolate_color(start, stop, 50, QColor.Hsl) + color = qtutils.interpolate_color(start, stop, 50, QColor.Spec.Hsl) expected = testutils.Color() expected.setHsl(0, 30, 150) assert testutils.Color(color) == expected - @pytest.mark.parametrize('colorspace', [QColor.Rgb, QColor.Hsv, QColor.Hsl]) + @pytest.mark.parametrize('colorspace', [QColor.Spec.Rgb, QColor.Spec.Hsv, QColor.Spec.Hsl]) def test_interpolation_alpha(self, colorspace): """Test interpolation of colorspace's alpha.""" start = testutils.Color(0, 0, 0, 30) diff --git a/tests/unit/utils/test_standarddir.py b/tests/unit/utils/test_standarddir.py index 81693986a..d4eb14208 100644 --- a/tests/unit/utils/test_standarddir.py +++ b/tests/unit/utils/test_standarddir.py @@ -114,8 +114,8 @@ def test_fake_windows(tmpdir, monkeypatch, what): def test_fake_haiku(tmpdir, monkeypatch): """Test getting data dir on HaikuOS.""" locations = { - QStandardPaths.AppDataLocation: '', - QStandardPaths.ConfigLocation: str(tmpdir / 'config' / APPNAME), + QStandardPaths.StandardLocation.AppDataLocation: '', + QStandardPaths.StandardLocation.ConfigLocation: str(tmpdir / 'config' / APPNAME), } monkeypatch.setattr(standarddir.QStandardPaths, 'writableLocation', locations.get) @@ -135,14 +135,14 @@ class TestWritableLocation: 'qutebrowser.utils.standarddir.QStandardPaths.writableLocation', lambda typ: '') with pytest.raises(standarddir.EmptyValueError): - standarddir._writable_location(QStandardPaths.AppDataLocation) + standarddir._writable_location(QStandardPaths.StandardLocation.AppDataLocation) def test_sep(self, monkeypatch): """Make sure the right kind of separator is used.""" monkeypatch.setattr(standarddir.os, 'sep', '\\') monkeypatch.setattr(standarddir.os.path, 'join', lambda *parts: '\\'.join(parts)) - loc = standarddir._writable_location(QStandardPaths.AppDataLocation) + loc = standarddir._writable_location(QStandardPaths.StandardLocation.AppDataLocation) assert '/' not in loc assert '\\' in loc diff --git a/tests/unit/utils/test_urlutils.py b/tests/unit/utils/test_urlutils.py index f926424b8..776f6d557 100644 --- a/tests/unit/utils/test_urlutils.py +++ b/tests/unit/utils/test_urlutils.py @@ -321,7 +321,7 @@ def test_get_search_url_for_path_search(config_stub, url, host, path, open_base_ config_stub.val.url.open_base_url = open_base_url url = urlutils._get_search_url(url) assert url.host() == host - assert url.path(options=QUrl.PrettyDecoded) == '/' + path + assert url.path(options=QUrl.ComponentFormattingOption.PrettyDecoded) == '/' + path @pytest.mark.parametrize('url, host', [ @@ -703,20 +703,20 @@ class TestProxyFromUrl: @pytest.mark.parametrize('url, expected', [ ('socks://example.com/', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com')), ('socks5://example.com', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com')), + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com')), ('socks5://example.com:2342', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2342)), + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com', 2342)), ('socks5://foo@example.com', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo')), + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com', 0, 'foo')), ('socks5://foo:bar@example.com', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 0, 'foo', + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com', 0, 'foo', 'bar')), ('socks5://foo:bar@example.com:2323', - QNetworkProxy(QNetworkProxy.Socks5Proxy, 'example.com', 2323, + QNetworkProxy(QNetworkProxy.ProxyType.Socks5Proxy, 'example.com', 2323, 'foo', 'bar')), - ('direct://', QNetworkProxy(QNetworkProxy.NoProxy)), + ('direct://', QNetworkProxy(QNetworkProxy.ProxyType.NoProxy)), ]) def test_proxy_from_url_valid(self, url, expected): assert urlutils.proxy_from_url(QUrl(url)) == expected diff --git a/tests/unit/utils/test_utils.py b/tests/unit/utils/test_utils.py index b5b49a7d4..b4d9703ca 100644 --- a/tests/unit/utils/test_utils.py +++ b/tests/unit/utils/test_utils.py @@ -676,7 +676,7 @@ class TestGetSetClipboard: def test_set(self, clipboard_mock, caplog): utils.set_clipboard('Hello World') clipboard_mock.setText.assert_called_with('Hello World', - mode=QClipboard.Clipboard) + mode=QClipboard.Mode.Clipboard) assert not caplog.records def test_set_unsupported_selection(self, clipboard_mock): |