diff --git a/qutebrowser/browser/cache.py b/qutebrowser/browser/cache.py index b34fa232b..33848d9e1 100644 --- a/qutebrowser/browser/cache.py +++ b/qutebrowser/browser/cache.py @@ -65,7 +65,7 @@ class DiskCache(QNetworkDiskCache): """Update cache size/activated if the config was changed.""" if (section, option) == ('storage', 'cache-size'): self.setMaximumCacheSize(config.get('storage', 'cache-size')) - elif (section, option) == ('general', # pragma: no branch + elif (section, option) == ('general', # pragma: no branch 'private-browsing'): self._maybe_activate() diff --git a/qutebrowser/browser/commands.py b/qutebrowser/browser/commands.py index b37987866..2faa63e6f 100644 --- a/qutebrowser/browser/commands.py +++ b/qutebrowser/browser/commands.py @@ -842,8 +842,8 @@ class CommandDispatcher: log.misc.debug("{} contained: {!r}".format(target, text)) text_urls = [u for u in text.split('\n') if u.strip()] if (len(text_urls) > 1 and not urlutils.is_url(text_urls[0]) and - urlutils.get_path_if_valid( - text_urls[0], check_exists=True) is None): + urlutils.get_path_if_valid(text_urls[0], + check_exists=True) is None): text_urls = [text] for i, text_url in enumerate(text_urls): if not window and i > 0: @@ -1202,9 +1202,9 @@ class CommandDispatcher: mhtml_: Download the current page and all assets as mhtml file. """ if dest_old is not None: - message.warning( - self._win_id, ":download [url] [dest] is deprecated - use" - " download --dest [dest] [url]") + message.warning(self._win_id, + ":download [url] [dest] is deprecated - use" + " download --dest [dest] [url]") if dest is not None: raise cmdexc.CommandError("Can't give two destinations for the" " download.") @@ -1260,8 +1260,8 @@ class CommandDispatcher: frame = widget.page().currentFrame() html = frame.toHtml() lexer = pygments.lexers.HtmlLexer() - formatter = pygments.formatters.HtmlFormatter( - full=True, linenos='table') + formatter = pygments.formatters.HtmlFormatter(full=True, + linenos='table') highlighted = pygments.highlight(html, lexer, formatter) current_url = self._current_url() tab = self._tabbed_browser.tabopen(explicit=True) diff --git a/qutebrowser/browser/downloads.py b/qutebrowser/browser/downloads.py index aa7d99427..85c957fb9 100644 --- a/qutebrowser/browser/downloads.py +++ b/qutebrowser/browser/downloads.py @@ -49,10 +49,7 @@ ModelRole = usertypes.enum('ModelRole', ['item'], start=Qt.UserRole, RetryInfo = collections.namedtuple('RetryInfo', ['request', 'manager']) - -DownloadPath = collections.namedtuple('DownloadPath', ['filename', - 'question']) - +DownloadPath = collections.namedtuple('DownloadPath', ['filename', 'question']) # Remember the last used directory last_used_directory = None @@ -148,8 +145,7 @@ def ask_for_filename(suggested_filename, win_id, *, parent=None, return DownloadPath(filename=download_dir(), question=None) encoding = sys.getfilesystemencoding() - suggested_filename = utils.force_encoding(suggested_filename, - encoding) + suggested_filename = utils.force_encoding(suggested_filename, encoding) q = usertypes.Question(parent) q.text = "Save file to:" @@ -461,8 +457,8 @@ class DownloadItem(QObject): elif self.stats.percentage() is None: return start else: - return utils.interpolate_color( - start, stop, self.stats.percentage(), system) + return utils.interpolate_color(start, stop, + self.stats.percentage(), system) @pyqtSlot() def cancel(self, remove_data=True): @@ -562,8 +558,8 @@ class DownloadItem(QObject): txt = self._filename + " already exists. Overwrite?" self._ask_confirm_question(txt) # FIFO, device node, etc. Make sure we want to do this - elif (os.path.exists(self._filename) and not - os.path.isdir(self._filename)): + elif (os.path.exists(self._filename) and + not os.path.isdir(self._filename)): txt = (self._filename + " already exists and is a special file. " "Write to this?") self._ask_confirm_question(txt) diff --git a/qutebrowser/browser/hints.py b/qutebrowser/browser/hints.py index 9ec14388f..d32e340b7 100644 --- a/qutebrowser/browser/hints.py +++ b/qutebrowser/browser/hints.py @@ -611,8 +611,7 @@ class HintManager(QObject): def _find_prevnext(self, frame, prev=False): """Find a prev/next element in frame.""" # First check for - elems = frame.findAllElements( - webelem.SELECTORS[webelem.Group.links]) + elems = frame.findAllElements(webelem.SELECTORS[webelem.Group.links]) rel_values = ('prev', 'previous') if prev else ('next') for e in elems: e = webelem.WebElementWrapper(e) @@ -924,19 +923,20 @@ class HintManager(QObject): } elem = self._context.elems[keystr].elem if elem.webFrame() is None: - message.error(self._win_id, "This element has no webframe.", + message.error(self._win_id, + "This element has no webframe.", immediately=True) return if self._context.target in elem_handlers: - handler = functools.partial( - elem_handlers[self._context.target], elem, self._context) + handler = functools.partial(elem_handlers[self._context.target], + elem, self._context) elif self._context.target in url_handlers: url = self._resolve_url(elem, self._context.baseurl) if url is None: self._show_url_error() return - handler = functools.partial( - url_handlers[self._context.target], url, self._context) + handler = functools.partial(url_handlers[self._context.target], + url, self._context) else: raise ValueError("No suitable handler found!") if not self._context.rapid: @@ -1041,13 +1041,11 @@ class WordHinter: "text": str, } - extractable_attrs = collections.defaultdict( - list, { - "IMG": ["alt", "title", "src"], - "A": ["title", "href", "text"], - "INPUT": ["name"] - } - ) + extractable_attrs = collections.defaultdict(list, { + "IMG": ["alt", "title", "src"], + "A": ["title", "href", "text"], + "INPUT": ["name"] + }) return (attr_extractors[attr](elem) for attr in extractable_attrs[elem.tagName()] @@ -1065,8 +1063,7 @@ class WordHinter: yield candidate[match.start():match.end()].lower() def any_prefix(self, hint, existing): - return any(hint.startswith(e) or e.startswith(hint) - for e in existing) + return any(hint.startswith(e) or e.startswith(hint) for e in existing) def new_hint_for(self, elem, existing): """Return a hint for elem, not conflicting with the existing.""" diff --git a/qutebrowser/browser/mhtml.py b/qutebrowser/browser/mhtml.py index d43a60292..20d8b071d 100644 --- a/qutebrowser/browser/mhtml.py +++ b/qutebrowser/browser/mhtml.py @@ -343,12 +343,9 @@ class _Downloader: item = download_manager.get(url, fileobj=_NoCloseBytesIO(), auto_remove=True) self.pending_downloads.add((url, item)) - item.finished.connect( - functools.partial(self._finished, url, item)) - item.error.connect( - functools.partial(self._error, url, item)) - item.cancelled.connect( - functools.partial(self._error, url, item)) + item.finished.connect(functools.partial(self._finished, url, item)) + item.error.connect(functools.partial(self._error, url, item)) + item.cancelled.connect(functools.partial(self._error, url, item)) def _finished(self, url, item): """Callback when a single asset is downloaded. diff --git a/qutebrowser/browser/network/networkmanager.py b/qutebrowser/browser/network/networkmanager.py index 1974a0d6b..19c04c1b7 100644 --- a/qutebrowser/browser/network/networkmanager.py +++ b/qutebrowser/browser/network/networkmanager.py @@ -276,10 +276,9 @@ class NetworkManager(QNetworkAccessManager): if user is None: # netrc check failed - answer = self._ask( - "Username ({}):".format(authenticator.realm()), - mode=usertypes.PromptMode.user_pwd, - owner=reply) + answer = self._ask("Username ({}):".format(authenticator.realm()), + mode=usertypes.PromptMode.user_pwd, + owner=reply) if answer is not None: user, password = answer.user, answer.password if user is not None: @@ -295,8 +294,9 @@ class NetworkManager(QNetworkAccessManager): authenticator.setUser(user) authenticator.setPassword(password) else: - answer = self._ask("Proxy username ({}):".format( - authenticator.realm()), mode=usertypes.PromptMode.user_pwd) + answer = self._ask( + "Proxy username ({}):".format(authenticator.realm()), + mode=usertypes.PromptMode.user_pwd) if answer is not None: authenticator.setUser(answer.user) authenticator.setPassword(answer.password) @@ -345,7 +345,7 @@ class NetworkManager(QNetworkAccessManager): # instead of no header at all req.setRawHeader('Referer'.encode('ascii'), QByteArray()) elif (referer_header_conf == 'same-domain' and - not urlutils.same_domain(req.url(), current_url)): + not urlutils.same_domain(req.url(), current_url)): req.setRawHeader('Referer'.encode('ascii'), QByteArray()) # If refer_header_conf is set to 'always', we leave the header # alone as QtWebKit did set it. diff --git a/qutebrowser/browser/network/qutescheme.py b/qutebrowser/browser/network/qutescheme.py index 0790db24f..a608dd304 100644 --- a/qutebrowser/browser/network/qutescheme.py +++ b/qutebrowser/browser/network/qutescheme.py @@ -109,13 +109,13 @@ class QuteSchemeHandler(schemehandler.SchemeHandler): request, str(e), QNetworkReply.ContentNotFoundError, self.parent()) except QuteSchemeError as e: - return networkreply.ErrorNetworkReply( - request, e.errorstring, e.error, self.parent()) + return networkreply.ErrorNetworkReply(request, e.errorstring, + e.error, self.parent()) mimetype, _encoding = mimetypes.guess_type(request.url().fileName()) if mimetype is None: mimetype = 'text/html' - return networkreply.FixedDataNetworkReply( - request, data, mimetype, self.parent()) + return networkreply.FixedDataNetworkReply(request, data, mimetype, + self.parent()) class JSBridge(QObject): @@ -240,4 +240,4 @@ def qute_pdfjs(_win_id, request): log.misc.warning( "pdfjs resource requested but not found: {}".format(e.path)) raise QuteSchemeError("Can't find pdfjs resource '{}'".format(e.path), - QNetworkReply.ContentNotFoundError) + QNetworkReply.ContentNotFoundError) diff --git a/qutebrowser/browser/pdfjs.py b/qutebrowser/browser/pdfjs.py index c12146d0b..8110d337b 100644 --- a/qutebrowser/browser/pdfjs.py +++ b/qutebrowser/browser/pdfjs.py @@ -51,9 +51,8 @@ def generate_pdfjs_page(url): """ viewer = get_pdfjs_res('web/viewer.html').decode('utf-8') script = _generate_pdfjs_script(url) - html_page = viewer.replace( - '', ''.format(script) - ) + html_page = viewer.replace('', + ''.format(script)) return html_page diff --git a/qutebrowser/browser/urlmarks.py b/qutebrowser/browser/urlmarks.py index 17e944073..01aa5d23c 100644 --- a/qutebrowser/browser/urlmarks.py +++ b/qutebrowser/browser/urlmarks.py @@ -154,8 +154,7 @@ class QuickmarkManager(UrlMarkManager): try: key, url = line.rsplit(maxsplit=1) except ValueError: - message.error('current', "Invalid quickmark '{}'".format( - line)) + message.error('current', "Invalid quickmark '{}'".format(line)) else: self.marks[key] = url diff --git a/qutebrowser/browser/webelem.py b/qutebrowser/browser/webelem.py index df481b98c..e47a67235 100644 --- a/qutebrowser/browser/webelem.py +++ b/qutebrowser/browser/webelem.py @@ -157,8 +157,7 @@ class WebElementWrapper(collections.abc.MutableMapping): def _check_vanished(self): """Raise an exception if the element vanished (is null).""" if self._elem.isNull(): - raise IsNullError('Element {} vanished!'.format( - self._elem)) + raise IsNullError('Element {} vanished!'.format(self._elem)) def is_visible(self, mainframe): """Check whether the element is currently visible on the screen. @@ -421,8 +420,7 @@ def is_visible(elem, mainframe): else: # We got an invalid rectangle (width/height 0/0 probably), but this # can still be a valid link. - visible_on_screen = mainframe_geometry.contains( - elem_rect.topLeft()) + visible_on_screen = mainframe_geometry.contains(elem_rect.topLeft()) # Then check if it's visible in its frame if it's not in the main # frame. elem_frame = elem.webFrame() diff --git a/qutebrowser/commands/userscripts.py b/qutebrowser/commands/userscripts.py index f95818eb1..798467664 100644 --- a/qutebrowser/commands/userscripts.py +++ b/qutebrowser/commands/userscripts.py @@ -184,8 +184,8 @@ class _POSIXUserscriptRunner(_BaseUserscriptRunner): # pylint: disable=no-member,useless-suppression os.mkfifo(self._filepath) except OSError as e: - message.error(self._win_id, "Error while creating FIFO: {}".format( - e)) + message.error(self._win_id, + "Error while creating FIFO: {}".format(e)) return self._reader = _QtFIFOReader(self._filepath) @@ -338,8 +338,8 @@ def run(cmd, *args, win_id, env, verbose=False): commandrunner = runners.CommandRunner(win_id, tabbed_browser) runner = UserscriptRunner(win_id, tabbed_browser) runner.got_cmd.connect( - lambda cmd: log.commands.debug("Got userscript command: {}".format( - cmd))) + lambda cmd: + log.commands.debug("Got userscript command: {}".format(cmd))) runner.got_cmd.connect(commandrunner.run_safely) user_agent = config.get('network', 'user-agent') if user_agent is not None: diff --git a/qutebrowser/completion/completionwidget.py b/qutebrowser/completion/completionwidget.py index 96e4be20a..8c2b8c1fd 100644 --- a/qutebrowser/completion/completionwidget.py +++ b/qutebrowser/completion/completionwidget.py @@ -201,8 +201,7 @@ class CompletionView(QTreeView): idx = self._next_idx(prev) qtutils.ensure_valid(idx) self.selectionModel().setCurrentIndex( - idx, QItemSelectionModel.ClearAndSelect | - QItemSelectionModel.Rows) + idx, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) def set_model(self, model): """Switch completion to a new model. diff --git a/qutebrowser/completion/models/miscmodels.py b/qutebrowser/completion/models/miscmodels.py index 7b86b762f..a0cc5bdc8 100644 --- a/qutebrowser/completion/models/miscmodels.py +++ b/qutebrowser/completion/models/miscmodels.py @@ -167,7 +167,7 @@ class TabCompletionModel(base.BaseCompletionModel): for win_id in objreg.window_registry: tabbed_browser = objreg.get('tabbed-browser', scope='window', - window=win_id) + window=win_id) for i in range(tabbed_browser.count()): tab = tabbed_browser.widget(i) tab.url_text_changed.connect(self.rebuild) @@ -210,6 +210,6 @@ class TabCompletionModel(base.BaseCompletionModel): c = self.new_category("{}".format(win_id)) for i in range(tabbed_browser.count()): tab = tabbed_browser.widget(i) - self.new_item(c, "{}/{}".format(win_id, i+1), + self.new_item(c, "{}/{}".format(win_id, i + 1), tab.url().toDisplayString(), tabbed_browser.page_title(i)) diff --git a/qutebrowser/completion/models/urlmodel.py b/qutebrowser/completion/models/urlmodel.py index 244bb1395..466dea65c 100644 --- a/qutebrowser/completion/models/urlmodel.py +++ b/qutebrowser/completion/models/urlmodel.py @@ -75,8 +75,7 @@ class UrlCompletionModel(base.BaseCompletionModel): history = utils.newest_slice(self._history, self._max_history) for entry in history: self._add_history_entry(entry) - self._history.add_completion_item.connect( - self.on_history_item_added) + self._history.add_completion_item.connect(self.on_history_item_added) objreg.get('config').changed.connect(self.reformat_timestamps) diff --git a/qutebrowser/config/configtypes.py b/qutebrowser/config/configtypes.py index da4ecf8d5..dcc0c96de 100644 --- a/qutebrowser/config/configtypes.py +++ b/qutebrowser/config/configtypes.py @@ -173,8 +173,8 @@ class BaseType: if self.valid_values is not None: if value not in self.valid_values: raise configexc.ValidationError( - value, "valid values: {}".format(', '.join( - self.valid_values))) + value, + "valid values: {}".format(', '.join(self.valid_values))) else: raise NotImplementedError("{} does not implement validate.".format( self.__class__.__name__)) @@ -263,8 +263,8 @@ class String(BaseType): if self.valid_values is not None: if value not in self.valid_values: raise configexc.ValidationError( - value, "valid values: {}".format(', '.join( - self.valid_values))) + value, + "valid values: {}".format(', '.join(self.valid_values))) if self.forbidden is not None and any(c in value for c in self.forbidden): @@ -1147,8 +1147,8 @@ class Proxy(BaseType): return url = QUrl(value) if not url.isValid(): - raise configexc.ValidationError(value, "invalid url, {}".format( - url.errorString())) + raise configexc.ValidationError( + value, "invalid url, {}".format(url.errorString())) elif url.scheme() not in self.PROXY_TYPES: raise configexc.ValidationError(value, "must be a proxy URL " "(http://... or socks://...) or " @@ -1211,8 +1211,8 @@ class SearchEngineUrl(BaseType): url = QUrl(value.replace('{}', 'foobar')) if not url.isValid(): - raise configexc.ValidationError(value, "invalid url, {}".format( - url.errorString())) + raise configexc.ValidationError( + value, "invalid url, {}".format(url.errorString())) class FuzzyUrl(BaseType): diff --git a/qutebrowser/config/sections.py b/qutebrowser/config/sections.py index 9b244d166..15b6a096e 100644 --- a/qutebrowser/config/sections.py +++ b/qutebrowser/config/sections.py @@ -208,8 +208,8 @@ class ValueList(Section): def dump_userconfig(self): changed = [] - mapping = collections.ChainMap( - self.layers['temp'], self.layers['conf']) + mapping = collections.ChainMap(self.layers['temp'], + self.layers['conf']) for k, v in mapping.items(): try: if v.value() != self.layers['default'][k].value(): diff --git a/qutebrowser/keyinput/basekeyparser.py b/qutebrowser/keyinput/basekeyparser.py index f2b87eea6..4accafcb6 100644 --- a/qutebrowser/keyinput/basekeyparser.py +++ b/qutebrowser/keyinput/basekeyparser.py @@ -341,10 +341,9 @@ class BaseKeyParser(QObject): elif self._supports_chains: self.bindings[key] = cmd elif self._warn_on_keychains: - log.keyboard.warning( - "Ignoring keychain '{}' in mode '{}' because " - "keychains are not supported there." - .format(key, modename)) + log.keyboard.warning("Ignoring keychain '{}' in mode '{}' because " + "keychains are not supported there." + .format(key, modename)) def execute(self, cmdstr, keytype, count=None): """Handle a completed keychain. diff --git a/qutebrowser/keyinput/modeman.py b/qutebrowser/keyinput/modeman.py index c5642a207..1cccd3d80 100644 --- a/qutebrowser/keyinput/modeman.py +++ b/qutebrowser/keyinput/modeman.py @@ -175,9 +175,8 @@ class ModeManager(QObject): if handled: filter_this = True - elif (parser.passthrough or - self._forward_unbound_keys == 'all' or - (self._forward_unbound_keys == 'auto' and is_non_alnum)): + elif (parser.passthrough or self._forward_unbound_keys == 'all' or + (self._forward_unbound_keys == 'auto' and is_non_alnum)): filter_this = False else: filter_this = True @@ -191,8 +190,8 @@ class ModeManager(QObject): "passthrough: {}, is_non_alnum: {} --> " "filter: {} (focused: {!r})".format( handled, self._forward_unbound_keys, - parser.passthrough, is_non_alnum, - filter_this, focus_widget)) + parser.passthrough, is_non_alnum, filter_this, + focus_widget)) return filter_this def _eventFilter_keyrelease(self, event): diff --git a/qutebrowser/mainwindow/mainwindow.py b/qutebrowser/mainwindow/mainwindow.py index f7fe0b706..d93e672b4 100644 --- a/qutebrowser/mainwindow/mainwindow.py +++ b/qutebrowser/mainwindow/mainwindow.py @@ -183,10 +183,6 @@ class MainWindow(QWidget): if config.get('ui', 'hide-mouse-cursor'): self.setCursor(Qt.BlankCursor) - #self.retranslateUi(MainWindow) - #self.tabWidget.setCurrentIndex(0) - #QtCore.QMetaObject.connectSlotsByName(MainWindow) - objreg.get("app").new_window.emit(self) def __repr__(self): diff --git a/qutebrowser/mainwindow/tabwidget.py b/qutebrowser/mainwindow/tabwidget.py index 90f493a37..3d0a418a1 100644 --- a/qutebrowser/mainwindow/tabwidget.py +++ b/qutebrowser/mainwindow/tabwidget.py @@ -515,9 +515,9 @@ class TabBarStyle(QCommonStyle): self._style = style for method in ('drawComplexControl', 'drawItemPixmap', 'generatedIconPixmap', 'hitTestComplexControl', - 'itemPixmapRect', 'itemTextRect', - 'polish', 'styleHint', 'subControlRect', 'unpolish', - 'drawItemText', 'sizeFromContents', 'drawPrimitive'): + 'itemPixmapRect', 'itemTextRect', 'polish', 'styleHint', + 'subControlRect', 'unpolish', 'drawItemText', + 'sizeFromContents', 'drawPrimitive'): target = getattr(self._style, method) setattr(self, method, functools.partial(target)) super().__init__() diff --git a/qutebrowser/misc/crashdialog.py b/qutebrowser/misc/crashdialog.py index 57447069a..1d23ff839 100644 --- a/qutebrowser/misc/crashdialog.py +++ b/qutebrowser/misc/crashdialog.py @@ -255,8 +255,7 @@ class _CrashDialog(QDialog): except Exception: self._crash_info.append(("Config", traceback.format_exc())) try: - self._crash_info.append( - ("Environment", _get_environment_vars())) + self._crash_info.append(("Environment", _get_environment_vars())) except Exception: self._crash_info.append(("Environment", traceback.format_exc())) @@ -283,8 +282,8 @@ class _CrashDialog(QDialog): def _get_paste_title(self): """Get a title for the paste.""" desc = self._get_paste_title_desc() - title = "qute {} {}".format( - qutebrowser.__version__, self._get_error_type()) + title = "qute {} {}".format(qutebrowser.__version__, + self._get_error_type()) if desc: title += ' {}'.format(desc) return title @@ -466,8 +465,7 @@ class ExceptionCrashDialog(_CrashDialog): self._crash_info.append( ("Debug log", log.ram_handler.dump_log())) except Exception: - self._crash_info.append( - ("Debug log", traceback.format_exc())) + self._crash_info.append(("Debug log", traceback.format_exc())) @pyqtSlot() def finish(self): diff --git a/qutebrowser/misc/crashsignal.py b/qutebrowser/misc/crashsignal.py index 8d78b1e9a..9ceb49a22 100644 --- a/qutebrowser/misc/crashsignal.py +++ b/qutebrowser/misc/crashsignal.py @@ -314,8 +314,8 @@ class SignalHandler(QObject): for fd in (read_fd, write_fd): flags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK) - self._notifier = QSocketNotifier( - read_fd, QSocketNotifier.Read, self) + self._notifier = QSocketNotifier(read_fd, QSocketNotifier.Read, + self) self._notifier.activated.connect(self.handle_signal_wakeup) self._orig_wakeup_fd = signal.set_wakeup_fd(write_fd) else: @@ -369,9 +369,8 @@ class SignalHandler(QObject): signal.signal(signal.SIGINT, self.interrupt_forcefully) signal.signal(signal.SIGTERM, self.interrupt_forcefully) # Signals can arrive anywhere, so we do this in the main thread - self._log_later( - "SIGINT/SIGTERM received, shutting down!", - "Do the same again to forcefully quit.") + self._log_later("SIGINT/SIGTERM received, shutting down!", + "Do the same again to forcefully quit.") QTimer.singleShot(0, functools.partial( self._quitter.shutdown, 128 + signum)) @@ -385,9 +384,8 @@ class SignalHandler(QObject): signal.signal(signal.SIGINT, self.interrupt_really_forcefully) signal.signal(signal.SIGTERM, self.interrupt_really_forcefully) # Signals can arrive anywhere, so we do this in the main thread - self._log_later( - "Forceful quit requested, goodbye cruel world!", - "Do the same again to quit with even more force.") + self._log_later("Forceful quit requested, goodbye cruel world!", + "Do the same again to quit with even more force.") QTimer.singleShot(0, functools.partial(self._app.exit, 128 + signum)) def interrupt_really_forcefully(self, signum, _frame): diff --git a/qutebrowser/misc/ipc.py b/qutebrowser/misc/ipc.py index 1e3bcc4c1..6042a829f 100644 --- a/qutebrowser/misc/ipc.py +++ b/qutebrowser/misc/ipc.py @@ -293,8 +293,7 @@ class IPCServer(QObject): try: decoded = data.decode('utf-8') except UnicodeDecodeError: - log.ipc.error("invalid utf-8: {}".format( - binascii.hexlify(data))) + log.ipc.error("invalid utf-8: {}".format(binascii.hexlify(data))) self._handle_invalid_data() return @@ -455,8 +454,7 @@ def send_to_running_instance(socketname, command, target_arg, *, if socket is None: socket = QLocalSocket() - if (legacy_name is not None and - _has_legacy_server(legacy_name)): + if legacy_name is not None and _has_legacy_server(legacy_name): name_to_use = legacy_name else: name_to_use = socketname diff --git a/qutebrowser/misc/split.py b/qutebrowser/misc/split.py index 0fd4f96c3..cb7a38d81 100644 --- a/qutebrowser/misc/split.py +++ b/qutebrowser/misc/split.py @@ -82,7 +82,7 @@ class ShellLexer: self.token += nextchar self.state = 'a' elif (nextchar in self.escape and - self.state in self.escapedquotes): + self.state in self.escapedquotes): if self.keep: self.token += nextchar self.escapedstate = self.state diff --git a/qutebrowser/utils/debug.py b/qutebrowser/utils/debug.py index 09aa314e5..194540f34 100644 --- a/qutebrowser/utils/debug.py +++ b/qutebrowser/utils/debug.py @@ -252,8 +252,8 @@ class log_time: # pylint: disable=invalid-name assert self._started is not None finished = datetime.datetime.now() delta = (finished - self._started).total_seconds() - self._logger.debug( - "{} took {} seconds.".format(self._action.capitalize(), delta)) + self._logger.debug("{} took {} seconds.".format( + self._action.capitalize(), delta)) def __call__(self, func): @functools.wraps(func) @@ -293,8 +293,7 @@ def get_all_objects(start_obj=None): pyqt_lines = [] _get_pyqt_objects(pyqt_lines, start_obj) pyqt_lines = [' ' + e for e in pyqt_lines] - pyqt_lines.insert(0, 'Qt objects - {} objects:'.format( - len(pyqt_lines))) + pyqt_lines.insert(0, 'Qt objects - {} objects:'.format(len(pyqt_lines))) output += [''] output += pyqt_lines diff --git a/qutebrowser/utils/utils.py b/qutebrowser/utils/utils.py index f2209f711..bfd6bbf5c 100644 --- a/qutebrowser/utils/utils.py +++ b/qutebrowser/utils/utils.py @@ -387,9 +387,8 @@ def keyevent_to_string(e): (Qt.ShiftModifier, 'Shift'), ]) modifiers = (Qt.Key_Control, Qt.Key_Alt, Qt.Key_Shift, Qt.Key_Meta, - Qt.Key_AltGr, Qt.Key_Super_L, Qt.Key_Super_R, - Qt.Key_Hyper_L, Qt.Key_Hyper_R, Qt.Key_Direction_L, - Qt.Key_Direction_R) + Qt.Key_AltGr, Qt.Key_Super_L, Qt.Key_Super_R, Qt.Key_Hyper_L, + Qt.Key_Hyper_R, Qt.Key_Direction_L, Qt.Key_Direction_R) if e.key() in modifiers: # Only modifier pressed return None diff --git a/scripts/dev/build_release.py b/scripts/dev/build_release.py index 57fa1d724..2e487efad 100755 --- a/scripts/dev/build_release.py +++ b/scripts/dev/build_release.py @@ -31,7 +31,7 @@ import tarfile import collections sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) import qutebrowser from scripts import utils @@ -85,7 +85,7 @@ def _maybe_remove(path): def smoke_test(executable): """Try starting the given qutebrowser executable.""" subprocess.check_call([executable, '--no-err-windows', '--nowindow', - '--temp-basedir', 'about:blank', ':later 500 quit']) + '--temp-basedir', 'about:blank', ':later 500 quit']) def build_windows(): diff --git a/scripts/dev/check_coverage.py b/scripts/dev/check_coverage.py index 40f7ebc4a..e82229545 100644 --- a/scripts/dev/check_coverage.py +++ b/scripts/dev/check_coverage.py @@ -210,7 +210,7 @@ def check(fileobj, perfect_files): filename, line_cov, branch_cov) messages.append(Message(MsgType.insufficent_coverage, text)) elif (filename not in perfect_src_files and not is_bad and - filename not in WHITELISTED_FILES): + filename not in WHITELISTED_FILES): text = ("{} has 100% coverage but is not in " "perfect_files!".format(filename)) messages.append(Message(MsgType.perfect_file, text)) @@ -257,9 +257,9 @@ def main_check_all(): for test_file, src_file in PERFECT_FILES: if test_file is None: continue - subprocess.check_call([sys.executable, '-m', 'py.test', '--cov', - 'qutebrowser', '--cov-report', 'xml', - test_file]) + subprocess.check_call( + [sys.executable, '-m', 'py.test', '--cov', 'qutebrowser', + '--cov-report', 'xml', test_file]) with open('coverage.xml', encoding='utf-8') as f: messages = check(f, [(test_file, src_file)]) os.remove('coverage.xml') diff --git a/scripts/dev/cleanup.py b/scripts/dev/cleanup.py index 2f2613842..f08292017 100755 --- a/scripts/dev/cleanup.py +++ b/scripts/dev/cleanup.py @@ -28,7 +28,7 @@ import shutil import fnmatch sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import utils diff --git a/scripts/dev/freeze.py b/scripts/dev/freeze.py index 295cbf737..0ea958eaa 100755 --- a/scripts/dev/freeze.py +++ b/scripts/dev/freeze.py @@ -33,7 +33,7 @@ import cx_Freeze as cx # pylint: disable=import-error,useless-suppression # cx_Freeze is hard to install (needs C extensions) so we don't check for it. sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import setupcommon diff --git a/scripts/dev/freeze_tests.py b/scripts/dev/freeze_tests.py index 580033aae..36f1a6c71 100755 --- a/scripts/dev/freeze_tests.py +++ b/scripts/dev/freeze_tests.py @@ -33,7 +33,7 @@ import pytest import httpbin sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import setupcommon from scripts.dev import freeze diff --git a/scripts/dev/get_coredumpctl_traces.py b/scripts/dev/get_coredumpctl_traces.py index 257cc3ac3..76936e319 100644 --- a/scripts/dev/get_coredumpctl_traces.py +++ b/scripts/dev/get_coredumpctl_traces.py @@ -29,7 +29,7 @@ import os.path import tempfile sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import utils diff --git a/scripts/dev/misc_checks.py b/scripts/dev/misc_checks.py index 05c672325..842215b0d 100644 --- a/scripts/dev/misc_checks.py +++ b/scripts/dev/misc_checks.py @@ -31,7 +31,7 @@ import traceback import collections sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import utils diff --git a/scripts/dev/run_profile.py b/scripts/dev/run_profile.py index 57d527b07..6d8ec5bb1 100755 --- a/scripts/dev/run_profile.py +++ b/scripts/dev/run_profile.py @@ -31,7 +31,7 @@ import argparse import shlex sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) import qutebrowser.qutebrowser @@ -77,7 +77,7 @@ def main(): elif args.profile_tool == 'kcachegrind': callgraphfile = os.path.join(tempdir, 'callgraph') subprocess.call(['pyprof2calltree', '-k', '-i', profilefile, - '-o', callgraphfile]) + '-o', callgraphfile]) elif args.profile_tool == 'snakeviz': subprocess.call(['snakeviz', profilefile]) diff --git a/scripts/dev/run_vulture.py b/scripts/dev/run_vulture.py index 98892eb1f..fb6aef0b3 100755 --- a/scripts/dev/run_vulture.py +++ b/scripts/dev/run_vulture.py @@ -105,8 +105,7 @@ def whitelist_generator(): yield 'scripts.dev.pylint_checkers.modeline.process_module' for attr in ('_get_default_metavar_for_optional', - '_get_default_metavar_for_positional', - '_metavar_formatter'): + '_get_default_metavar_for_positional', '_metavar_formatter'): yield 'scripts.dev.src2asciidoc.UsageFormatter.' + attr @@ -169,8 +168,7 @@ def run(files): def main(): parser = argparse.ArgumentParser() - parser.add_argument('files', nargs='*', - default=['qutebrowser', 'scripts']) + parser.add_argument('files', nargs='*', default=['qutebrowser', 'scripts']) args = parser.parse_args() out = run(args.files) for line in out: diff --git a/scripts/dev/segfault_test.py b/scripts/dev/segfault_test.py index adf29783c..cac8c6a14 100755 --- a/scripts/dev/segfault_test.py +++ b/scripts/dev/segfault_test.py @@ -27,7 +27,7 @@ import subprocess import os.path sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) from scripts import utils diff --git a/scripts/dev/src2asciidoc.py b/scripts/dev/src2asciidoc.py index e70276109..a38cc44c8 100755 --- a/scripts/dev/src2asciidoc.py +++ b/scripts/dev/src2asciidoc.py @@ -32,7 +32,7 @@ import tempfile import argparse sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.pardir, - os.pardir)) + os.pardir)) # We import qutebrowser.app so all @cmdutils-register decorators are run. import qutebrowser.app diff --git a/scripts/dev/ua_fetch.py b/scripts/dev/ua_fetch.py index 37865e2c3..788267eda 100644 --- a/scripts/dev/ua_fetch.py +++ b/scripts/dev/ua_fetch.py @@ -27,7 +27,7 @@ script is formatted to be pasted into configtypes.py. """ import requests -from lxml import html # pylint: disable=import-error +from lxml import html # pylint: disable=import-error def fetch(): diff --git a/scripts/link_pyqt.py b/scripts/link_pyqt.py index 249255404..92fbb84c9 100644 --- a/scripts/link_pyqt.py +++ b/scripts/link_pyqt.py @@ -86,9 +86,8 @@ def needs_update(source, dest): diffs = filecmp.dircmp(source, dest) ignored = get_ignored_files(source, diffs.left_only) has_new_files = set(ignored) != set(diffs.left_only) - return (has_new_files or diffs.right_only or - diffs.common_funny or diffs.diff_files or - diffs.funny_files) + return (has_new_files or diffs.right_only or diffs.common_funny or + diffs.diff_files or diffs.funny_files) else: return not filecmp.cmp(source, dest) diff --git a/tests/helpers/utils.py b/tests/helpers/utils.py index fb4bca176..eba5fc0f5 100644 --- a/tests/helpers/utils.py +++ b/tests/helpers/utils.py @@ -64,7 +64,7 @@ def _partial_compare_dict(val1, val2, *, indent): "Key {!r} is in second dict but not in first!".format(key)) print_i(outcome.error, indent, error=True) return outcome - outcome = partial_compare(val1[key], val2[key], indent=indent+1) + outcome = partial_compare(val1[key], val2[key], indent=indent + 1) if not outcome: return outcome return PartialCompareOutcome() @@ -77,7 +77,7 @@ def _partial_compare_list(val1, val2, *, indent): print_i(outcome.error, indent, error=True) return outcome for item1, item2 in zip(val1, val2): - outcome = partial_compare(item1, item2, indent=indent+1) + outcome = partial_compare(item1, item2, indent=indent + 1) if not outcome: return outcome return PartialCompareOutcome() diff --git a/tests/integration/quteprocess.py b/tests/integration/quteprocess.py index c7fa66732..f3f3d0087 100644 --- a/tests/integration/quteprocess.py +++ b/tests/integration/quteprocess.py @@ -195,15 +195,15 @@ class QuteProc(testprocess.Process): log_line.message.startswith("Listening as ")): self._ipc_socket = log_line.message.split(' ', maxsplit=2)[2] elif (log_line.category == 'webview' and - log_line.message == start_okay_message_load): + log_line.message == start_okay_message_load): self._is_ready('load') elif (log_line.category == 'misc' and - log_line.message == start_okay_message_focus): + log_line.message == start_okay_message_focus): self._is_ready('focus') elif (log_line.category == 'init' and - log_line.module == 'standarddir' and - log_line.function == 'init' and - log_line.message.startswith('Base directory:')): + log_line.module == 'standarddir' and + log_line.function == 'init' and + log_line.message.startswith('Base directory:')): self.basedir = log_line.message.split(':', maxsplit=1)[1].strip() elif self._is_error_logline(log_line): self.got_error.emit() diff --git a/tests/integration/test_dirbrowser.py b/tests/integration/test_dirbrowser.py index 452dfbb4b..86b70eaea 100644 --- a/tests/integration/test_dirbrowser.py +++ b/tests/integration/test_dirbrowser.py @@ -135,8 +135,7 @@ def parse(quteproc): list_.append(Item(path=item_path, link=li.a['href'], text=str(li.a.string))) - return Parsed(path=path, parent=parent, folders=folders, - files=files) + return Parsed(path=path, parent=parent, folders=folders, files=files) @pytest.fixture(scope='module') diff --git a/tests/integration/testprocess.py b/tests/integration/testprocess.py index 1898a24ba..e67817917 100644 --- a/tests/integration/testprocess.py +++ b/tests/integration/testprocess.py @@ -195,8 +195,8 @@ class Process(QObject): Should be used in a contextmanager. """ - blocker = pytestqt.plugin.SignalBlocker( - timeout=timeout, raising=raising) + blocker = pytestqt.plugin.SignalBlocker(timeout=timeout, + raising=raising) blocker.connect(signal) return blocker diff --git a/tests/integration/webserver.py b/tests/integration/webserver.py index 0cae0c603..fc06a49b3 100644 --- a/tests/integration/webserver.py +++ b/tests/integration/webserver.py @@ -93,8 +93,7 @@ class ExpectedRequest: def __eq__(self, other): if isinstance(other, (Request, ExpectedRequest)): - return (self.verb == other.verb and - self.path == other.path) + return self.verb == other.verb and self.path == other.path else: return NotImplemented diff --git a/tests/unit/browser/network/test_filescheme.py b/tests/unit/browser/network/test_filescheme.py index 1321a649c..859957dac 100644 --- a/tests/unit/browser/network/test_filescheme.py +++ b/tests/unit/browser/network/test_filescheme.py @@ -156,9 +156,8 @@ class TestDirbrowserHtml: def test_icons(self, monkeypatch): """Make sure icon paths are correct file:// URLs.""" - monkeypatch.setattr( - 'qutebrowser.utils.jinja.utils.resource_filename', - lambda name: '/test path/foo.svg') + monkeypatch.setattr('qutebrowser.utils.jinja.utils.resource_filename', + lambda name: '/test path/foo.svg') html = filescheme.dirbrowser_html(os.getcwd()) soup = bs4.BeautifulSoup(html, 'html.parser') diff --git a/tests/unit/browser/network/test_qutescheme.py b/tests/unit/browser/network/test_qutescheme.py index 1d9cfa5d5..1dede5d72 100644 --- a/tests/unit/browser/network/test_qutescheme.py +++ b/tests/unit/browser/network/test_qutescheme.py @@ -35,19 +35,17 @@ def handler(): class TestPDFJSHandler: - """Test the qute://pdfjs endpoint.""" @pytest.fixture(autouse=True) def fake_pdfjs(self, monkeypatch): - def get_pdfjs_res(path): if path == '/existing/file': return b'foobar' raise pdfjs.PDFJSNotFound(path) monkeypatch.setattr('qutebrowser.browser.pdfjs.get_pdfjs_res', - get_pdfjs_res) + get_pdfjs_res) def test_existing_resource(self, handler): """Test with a resource that exists.""" diff --git a/tests/unit/browser/test_cookies.py b/tests/unit/browser/test_cookies.py index ba5fbe810..f92a4f2ca 100644 --- a/tests/unit/browser/test_cookies.py +++ b/tests/unit/browser/test_cookies.py @@ -130,8 +130,7 @@ def test_purge_old_cookies(config_stub, fake_save_manager): def test_save(config_stub, fake_save_manager, monkeypatch, qapp): """Test that expired and session cookies are not saved.""" - monkeypatch.setattr(lineparser, - 'LineParser', LineparserSaveStub) + monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() jar._lineparser.data = [COOKIE1, COOKIE2, SESSION_COOKIE, EXPIRED_COOKIE] @@ -147,24 +146,19 @@ def test_cookies_changed_emit(config_stub, fake_save_manager, monkeypatch, qtbot): """Test that self.changed is emitted.""" config_stub.data = CONFIG_COOKIES_ENABLED - monkeypatch.setattr(lineparser, - 'LineParser', LineparserSaveStub) + monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() with qtbot.waitSignal(jar.changed): config_stub.set('content', 'cookies-store', False) -@pytest.mark.parametrize('store_cookies,empty', [ - (True, False), - (False, True) -]) -def test_cookies_changed(config_stub, fake_save_manager, monkeypatch, - qtbot, store_cookies, empty): +@pytest.mark.parametrize('store_cookies,empty', [(True, False), (False, True)]) +def test_cookies_changed(config_stub, fake_save_manager, monkeypatch, qtbot, + store_cookies, empty): """Test that cookies are saved correctly.""" config_stub.data = CONFIG_COOKIES_ENABLED - monkeypatch.setattr(lineparser, - 'LineParser', LineparserSaveStub) + monkeypatch.setattr(lineparser, 'LineParser', LineparserSaveStub) jar = cookies.CookieJar() jar._lineparser.data = [COOKIE1, COOKIE2] jar.parse_cookies() diff --git a/tests/unit/config/test_config.py b/tests/unit/config/test_config.py index 5d831e15e..fecb45fd4 100644 --- a/tests/unit/config/test_config.py +++ b/tests/unit/config/test_config.py @@ -112,12 +112,10 @@ class TestConfigParser: def test_interpolation_cross_section(self, objects): """Test setting an interpolated value from another section.""" - objects.cp.read_dict( - { - 'general': {'ignore-case': '${network:do-not-track}'}, - 'network': {'do-not-track': 'false'}, - } - ) + objects.cp.read_dict({ + 'general': {'ignore-case': '${network:do-not-track}'}, + 'network': {'do-not-track': 'false'}, + }) objects.cfg._from_cp(objects.cp) assert not objects.cfg.get('general', 'ignore-case') assert not objects.cfg.get('network', 'do-not-track') diff --git a/tests/unit/misc/test_checkpyver.py b/tests/unit/misc/test_checkpyver.py index aacd576f4..92d44dc22 100644 --- a/tests/unit/misc/test_checkpyver.py +++ b/tests/unit/misc/test_checkpyver.py @@ -36,10 +36,10 @@ TEXT = (r"At least Python 3.4 is required to run qutebrowser, but " def test_python2(): """Run checkpyver with python 2.""" try: - proc = subprocess.Popen(['python2', checkpyver.__file__, - '--no-err-windows'], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE) + proc = subprocess.Popen( + ['python2', checkpyver.__file__, '--no-err-windows'], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) stdout, stderr = proc.communicate() except FileNotFoundError: pytest.skip("python2 not found") diff --git a/tests/unit/utils/test_utils.py b/tests/unit/utils/test_utils.py index b38e1ca3b..0c2ed5cec 100644 --- a/tests/unit/utils/test_utils.py +++ b/tests/unit/utils/test_utils.py @@ -150,8 +150,8 @@ class Patcher: def patch_version(self, version='5.2.0'): """Patch Qt version.""" - self.monkeypatch.setattr( - 'qutebrowser.utils.utils.qtutils.qVersion', lambda: version) + self.monkeypatch.setattr('qutebrowser.utils.utils.qtutils.qVersion', + lambda: version) def patch_file(self, data): """Patch open() to return the given data."""