Various code style improvements
This commit is contained in:
parent
fd20b46b33
commit
2a343cb3a1
@ -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()
|
||||
|
||||
|
@ -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)
|
||||
|
@ -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)
|
||||
|
@ -611,8 +611,7 @@ class HintManager(QObject):
|
||||
def _find_prevnext(self, frame, prev=False):
|
||||
"""Find a prev/next element in frame."""
|
||||
# First check for <link rel="prev(ious)|next">
|
||||
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."""
|
||||
|
@ -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.
|
||||
|
@ -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.
|
||||
|
@ -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)
|
||||
|
@ -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(
|
||||
'</body>', '</body><script>{}</script>'.format(script)
|
||||
)
|
||||
html_page = viewer.replace('</body>',
|
||||
'</body><script>{}</script>'.format(script))
|
||||
return html_page
|
||||
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -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()
|
||||
|
@ -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:
|
||||
|
@ -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.
|
||||
|
@ -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))
|
||||
|
@ -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)
|
||||
|
||||
|
@ -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):
|
||||
|
@ -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():
|
||||
|
@ -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.
|
||||
|
@ -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):
|
||||
|
@ -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):
|
||||
|
@ -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__()
|
||||
|
@ -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):
|
||||
|
@ -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):
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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
|
||||
|
@ -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():
|
||||
|
@ -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')
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -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])
|
||||
|
||||
|
@ -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:
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
@ -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():
|
||||
|
@ -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)
|
||||
|
||||
|
@ -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()
|
||||
|
@ -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()
|
||||
|
@ -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')
|
||||
|
@ -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
|
||||
|
||||
|
@ -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
|
||||
|
||||
|
@ -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')
|
||||
|
@ -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."""
|
||||
|
@ -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()
|
||||
|
@ -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')
|
||||
|
@ -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")
|
||||
|
@ -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."""
|
||||
|
Loading…
Reference in New Issue
Block a user