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