Remove qt_ prefix from qtutils functions.

This commit is contained in:
Florian Bruhin 2014-08-26 19:23:06 +02:00
parent d625cde28c
commit e04b31eb90
22 changed files with 67 additions and 67 deletions

View File

@ -244,7 +244,7 @@ instead of using exceptions.
+
If a function gets or returns a Qt object which
has an `.isValid()` method such as `QUrl` or `QModelIndex`, there's a helper
function `qt_ensure_valid` in `qutebrowser.utils.qt` which should get called on
function `ensure_valid` in `qutebrowser.utils.qt` which should get called on
all such objects. It will raise `qutebrowser.utils.qt.QtValueError` if the
value is not valid.
+
@ -372,8 +372,8 @@ displaying it to the user.
* Name a string URL something like `urlstr`, and a `QUrl` something like `url`.
* Mention in the docstring whether your function needs a URL string or a
`QUrl`.
* Call `qt_ensure_valid` from `utils.qt` whenever getting or creating a
`QUrl` and take appropriate action if not.
* Call `ensure_valid` from `utils.qt` whenever getting or creating a `QUrl` and
take appropriate action if not.
Style conventions

View File

@ -86,7 +86,7 @@ class Application(QApplication):
# We don't enable this earlier because some imports trigger
# warnings (which are not our fault).
warnings.simplefilter('default')
qt_args = qtutils.get_qt_args(args)
qt_args = qtutils.get_args(args)
log.init.debug("Qt arguments: {}, based on {}".format(qt_args, args))
super().__init__(qt_args)
self._quit_status = {

View File

@ -347,7 +347,7 @@ class DownloadManager(QObject):
url: The URL to get, as QUrl
page: The QWebPage to get the download from.
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
req = QNetworkRequest(url)
reply = page.networkAccessManager().get(req)
self.fetch(reply)

View File

@ -340,7 +340,7 @@ class HintManager(QObject):
Args:
url: The URL to open as a QURL.
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
sel = self._context.target == Target.yank_primary
mode = QClipboard.Selection if sel else QClipboard.Clipboard
urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword)
@ -354,7 +354,7 @@ class HintManager(QObject):
Args:
url: The URL to open as a QUrl.
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
urlstr = url.toDisplayString(QUrl.FullyEncoded)
args = self._context.get_args(urlstr)
message.set_cmd_text(' '.join(args))
@ -370,19 +370,19 @@ class HintManager(QObject):
message.error("No suitable link found for this element.",
immediately=True)
return
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
self.download_get.emit(url, elem.webFrame().page())
def _call_userscript(self, url):
"""Call an userscript from a hint."""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
cmd = self._context.args[0]
args = self._context.args[1:]
userscripts.run(cmd, *args, url=url)
def _spawn(self, url):
"""Spawn a simple command from a hint."""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
urlstr = url.toString(QUrl.FullyEncoded | QUrl.RemovePassword)
args = self._context.get_args(urlstr)
subprocess.Popen(args)
@ -406,7 +406,7 @@ class HintManager(QObject):
url = QUrl(text)
if url.isRelative():
url = baseurl.resolved(url)
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
return url
def _find_prevnext(self, frame, prev=False):

View File

@ -67,7 +67,7 @@ def prompt_save(url):
Args:
url: The quickmark url as a QUrl.
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
urlstr = url.toString(QUrl.RemovePassword | QUrl.FullyEncoded)
message.ask_async("Add quickmark:", usertypes.PromptMode.text,
functools.partial(quickmark_add, urlstr))

View File

@ -74,7 +74,7 @@ class BaseCompletionModel(QStandardItemModel):
index: A QModelIndex of the item to mark.
needle: The string to mark.
"""
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
haystack = self.data(index)
marks = self._get_marks(needle, haystack)
ok = self.setData(index, marks, Role.marks)
@ -132,7 +132,7 @@ class BaseCompletionModel(QStandardItemModel):
Return:
The item flags, or Qt.NoItemFlags on error.
"""
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
if index.parent().isValid():
# item
return Qt.ItemIsEnabled | Qt.ItemIsSelectable

View File

@ -87,7 +87,7 @@ class SettingOptionCompletionModel(basecompletion.BaseCompletionModel):
return
val = config.get(section, option, raw=True)
idx = item.index()
qtutils.qt_ensure_valid(idx)
qtutils.ensure_valid(idx)
ok = self.setData(idx, val, Qt.DisplayRole)
if not ok:
raise ValueError("Setting data failed! (section: {}, option: {}, "
@ -138,7 +138,7 @@ class SettingValueCompletionModel(basecompletion.BaseCompletionModel):
if not value:
value = '""'
idx = self.cur_item.index()
qtutils.qt_ensure_valid(idx)
qtutils.ensure_valid(idx)
ok = self.setData(idx, value, Qt.DisplayRole)
if not ok:
raise ValueError("Setting data failed! (section: {}, option: {}, "

View File

@ -81,7 +81,7 @@ class CompletionFilterModel(QSortFilterProxyModel):
count = 0
for i in range(self.rowCount()):
cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat)
qtutils.ensure_valid(cat)
count += self.rowCount(cat)
return count
@ -89,10 +89,10 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Return the first item in the model."""
for i in range(self.rowCount()):
cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat)
qtutils.ensure_valid(cat)
if cat.model().hasChildren(cat):
index = self.index(0, 0, cat)
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
return index
return QModelIndex()
@ -100,10 +100,10 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Return the last item in the model."""
for i in range(self.rowCount() - 1, -1, -1):
cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat)
qtutils.ensure_valid(cat)
if cat.model().hasChildren(cat):
index = self.index(self.rowCount(cat) - 1, 0, cat)
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
return index
return QModelIndex()
@ -111,12 +111,12 @@ class CompletionFilterModel(QSortFilterProxyModel):
"""Mark the given text in all visible items."""
for i in range(self.rowCount()):
cat = self.index(i, 0)
qtutils.qt_ensure_valid(cat)
qtutils.ensure_valid(cat)
for k in range(self.rowCount(cat)):
index = self.index(k, 0, cat)
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
index = self.mapToSource(index)
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
self.srcmodel.mark_item(index, text)
def setSourceModel(self, model):
@ -142,7 +142,7 @@ class CompletionFilterModel(QSortFilterProxyModel):
if parent == QModelIndex():
return True
idx = self.srcmodel.index(row, 0, parent)
qtutils.qt_ensure_valid(idx)
qtutils.ensure_valid(idx)
data = self.srcmodel.data(idx)
# TODO more sophisticated filtering
if not self.pattern:
@ -162,8 +162,8 @@ class CompletionFilterModel(QSortFilterProxyModel):
Return:
True if left < right, else False
"""
qtutils.qt_ensure_valid(lindex)
qtutils.qt_ensure_valid(rindex)
qtutils.ensure_valid(lindex)
qtutils.ensure_valid(rindex)
left_sort = self.srcmodel.data(lindex, role=completion.Role.sort)
right_sort = self.srcmodel.data(rindex, role=completion.Role.sort)

View File

@ -57,7 +57,7 @@ class DownloadModel(QAbstractListModel):
def on_data_changed(self, idx):
"""Update view when DownloadManager data changed."""
model_idx = self.index(idx, 0)
qtutils.qt_ensure_valid(model_idx)
qtutils.ensure_valid(model_idx)
self.dataChanged.emit(model_idx, model_idx)
def last_index(self):
@ -79,7 +79,7 @@ class DownloadModel(QAbstractListModel):
def data(self, index, role):
"""Download data from DownloadManager."""
qtutils.qt_ensure_valid(index)
qtutils.ensure_valid(index)
if index.parent().isValid() or index.column() != 0:
return QVariant()

View File

@ -72,7 +72,7 @@ def get_argparser():
action='store_true')
# For the Qt args, we use store_const with const=True rather than
# store_true because we want the default to be None, to make
# utils.qt:get_qt_args easier.
# utils.qt:get_args easier.
debug.add_argument('--qt-style', help="Set the Qt GUI style to use.",
metavar='STYLE')
debug.add_argument('--qt-stylesheet', help="Override the Qt application "

View File

@ -84,7 +84,7 @@ class CheckOverflowTests(unittest.TestCase):
class GetQtArgsTests(unittest.TestCase):
"""Tests for get_qt_args."""
"""Tests for get_args."""
def setUp(self):
self.parser = argparse.ArgumentParser()
@ -109,26 +109,26 @@ class GetQtArgsTests(unittest.TestCase):
def test_no_qt_args(self):
"""Test commandline with no Qt arguments given."""
ns = self._namespace(['--foo'], flags=['--foo'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0]])
self.assertEqual(qt.get_args(ns), [sys.argv[0]])
def test_qt_flag(self):
"""Test commandline with a Qt flag."""
ns = self._namespace(['--foo', '--qt-reverse', '--bar'],
flags=['--foo', '--qt-reverse', '--bar'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0], '-reverse'])
self.assertEqual(qt.get_args(ns), [sys.argv[0], '-reverse'])
def test_qt_arg(self):
"""Test commandline with a Qt argument."""
ns = self._namespace(['--qt-stylesheet', 'foobar'],
args=['--qt-stylesheet'])
self.assertEqual(qt.get_qt_args(ns), [sys.argv[0], '-stylesheet',
'foobar'])
self.assertEqual(qt.get_args(ns), [sys.argv[0], '-stylesheet',
'foobar'])
def test_qt_both(self):
"""Test commandline with a Qt argument and flag."""
ns = self._namespace(['--qt-stylesheet', 'foobar', '--qt-reverse'],
flags=['--qt-reverse'], args=['--qt-stylesheet'])
qt_args = qt.get_qt_args(ns)
qt_args = qt.get_args(ns)
self.assertEqual(qt_args[0], sys.argv[0])
self.assertIn('-reverse', qt_args)
self.assertIn('-stylesheet', qt_args)

View File

@ -204,8 +204,8 @@ def check_qt_version():
"""Check if the Qt version is recent enough."""
import operator
from PyQt5.QtCore import qVersion
from qutebrowser.utils.qt import qt_version_check
if qt_version_check('5.2.0', operator.lt):
from qutebrowser.utils import qt as qtutils
if qtutils.version_check('5.2.0', operator.lt):
text = ("Fatal error: Qt and PyQt >= 5.2.0 are required, but {} is "
"installed.".format(qVersion()))
_die(text, exception=False)

View File

@ -190,7 +190,7 @@ def actute_warning():
return
# Qt >= 5.3 doesn't seem to be affected
try:
if qtutils.qt_version_check('5.3.0'):
if qtutils.version_check('5.3.0'):
return
except ValueError:
pass
@ -247,8 +247,8 @@ def interpolate_color(start, end, percent, colorspace=QColor.Rgb):
Raise:
ValueError if invalid parameters are passed.
"""
qtutils.qt_ensure_valid(start)
qtutils.qt_ensure_valid(end)
qtutils.ensure_valid(start)
qtutils.ensure_valid(end)
out = QColor()
if colorspace == QColor.Rgb:
a_c1, a_c2, a_c3, _alpha = start.getRgb()
@ -271,7 +271,7 @@ def interpolate_color(start, end, percent, colorspace=QColor.Rgb):
else:
raise ValueError("Invalid colorspace!")
out = out.convertTo(start.spec())
qtutils.qt_ensure_valid(out)
qtutils.ensure_valid(out)
return out

View File

@ -46,7 +46,7 @@ MINVALS = {
}
def qt_version_check(version, op=operator.ge):
def version_check(version, op=operator.ge):
"""Check if the Qt runtime version is the version supplied or newer.
Args:
@ -88,7 +88,7 @@ def check_overflow(arg, ctype, fatal=True):
return arg
def get_qt_args(namespace):
def get_args(namespace):
"""Get the Qt QApplication arguments based on an argparse namespace.
Args:
@ -114,10 +114,10 @@ def get_qt_args(namespace):
def check_print_compat():
"""Check if printing should work in the given Qt version."""
return not (os.name == 'nt' and qt_version_check('5.3.0', operator.lt))
return not (os.name == 'nt' and version_check('5.3.0', operator.lt))
def qt_ensure_valid(obj):
def ensure_valid(obj):
"""Ensure a Qt object with an .isValid() method is valid.
Raise:
@ -129,7 +129,7 @@ def qt_ensure_valid(obj):
class QtValueError(ValueError):
"""Exception which gets raised by qt_ensure_valid."""
"""Exception which gets raised by ensure_valid."""
def __init__(self, obj):
try:

View File

@ -65,7 +65,7 @@ def _get_search_url(txt):
if not term:
raise FuzzyUrlError("No search term given")
url = QUrl.fromUserInput(template.format(urllib.parse.quote(term)))
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
return url
@ -143,7 +143,7 @@ def fuzzy_url(urlstr):
url = QUrl.fromUserInput(stripped)
logger.debug("Converting fuzzy term {} to URL -> {}".format(
urlstr, url.toDisplayString()))
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
return url

View File

@ -167,7 +167,7 @@ class CompletionView(QTreeView):
# No completion running at the moment, ignore keypress
return
idx = self._next_idx(prev)
qtutils.qt_ensure_valid(idx)
qtutils.ensure_valid(idx)
self.selectionModel().setCurrentIndex(
idx, QItemSelectionModel.ClearAndSelect |
QItemSelectionModel.Rows)

View File

@ -98,12 +98,12 @@ class CompletionItemDelegate(QStyledItemDelegate):
text_rect_ = self._style.subElementRect(
self._style.SE_ItemViewItemText, self._opt, self._opt.widget)
qtutils.qt_ensure_valid(text_rect_)
qtutils.ensure_valid(text_rect_)
margin = self._style.pixelMetric(QStyle.PM_FocusFrameHMargin,
self._opt, self._opt.widget) + 1
# remove width padding
text_rect = text_rect_.adjusted(margin, 0, -margin, 0)
qtutils.qt_ensure_valid(text_rect)
qtutils.ensure_valid(text_rect)
# move text upwards a bit
if index.parent().isValid():
text_rect.adjust(0, -1, 0, -1)
@ -217,7 +217,7 @@ class CompletionItemDelegate(QStyledItemDelegate):
o.rect = self._style.subElementRect(
self._style.SE_ItemViewItemFocusRect, self._opt, self._opt.widget)
o.state |= QStyle.State_KeyboardFocusChange | QStyle.State_Item
qtutils.qt_ensure_valid(o.rect)
qtutils.ensure_valid(o.rect)
if state & QStyle.State_Enabled:
cg = QPalette.Normal
else:
@ -253,7 +253,7 @@ class CompletionItemDelegate(QStyledItemDelegate):
docsize = self._doc.size().toSize()
size = self._style.sizeFromContents(QStyle.CT_ItemViewItem, self._opt,
docsize, self._opt.widget)
qtutils.qt_ensure_valid(size)
qtutils.ensure_valid(size)
return size + QSize(10, 3)
def paint(self, painter, option, index):

View File

@ -91,5 +91,5 @@ class DownloadView(QListView):
size = QSize(0, height + 2)
else:
size = QSize(0, 0)
qtutils.qt_ensure_valid(size)
qtutils.ensure_valid(size)
return size

View File

@ -79,7 +79,7 @@ class TextBase(QLabel):
"""Extend QLabel::resizeEvent to update the elided text afterwards."""
super().resizeEvent(e)
size = e.size()
qtutils.qt_ensure_valid(size)
qtutils.ensure_valid(size)
self._update_elided_text(size.width())
def paintEvent(self, e):
@ -90,6 +90,6 @@ class TextBase(QLabel):
e.accept()
painter = QPainter(self)
geom = self.geometry()
qtutils.qt_ensure_valid(geom)
qtutils.ensure_valid(geom)
painter.drawText(0, 0, geom.width(), geom.height(),
self.alignment(), self._elided_text)

View File

@ -210,7 +210,7 @@ class TabbedBrowser(tabwidget.TabWidget):
"""
url = self.currentWidget().cur_url
try:
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
except qtutils.QtValueError as e:
msg = "Current URL is invalid"
if e.reason:
@ -266,7 +266,7 @@ class TabbedBrowser(tabwidget.TabWidget):
if tab is self.last_focused:
self.last_focused = None
if not tab.cur_url.isEmpty():
qtutils.qt_ensure_valid(tab.cur_url)
qtutils.ensure_valid(tab.cur_url)
self.url_stack.append(tab.cur_url)
tab.shutdown()
self._tabs.remove(tab)
@ -281,7 +281,7 @@ class TabbedBrowser(tabwidget.TabWidget):
url: The URL to open as QUrl.
newtab: True to open URL in a new tab, False otherwise.
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
if newtab:
self.tabopen(url, background=False)
else:
@ -324,7 +324,7 @@ class TabbedBrowser(tabwidget.TabWidget):
The opened WebView instance.
"""
if url is not None:
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
log.webview.debug("Creating new tab with URL {}".format(url))
tab = webview.WebView(self)
self._connect_tab_signals(tab)

View File

@ -211,7 +211,7 @@ class TabBar(QTabBar):
# If we *do* have enough space, tabs should occupy the whole window
# width.
size = QSize(self.width() / self.count(), height)
qtutils.qt_ensure_valid(size)
qtutils.ensure_valid(size)
return size
def paintEvent(self, _e):
@ -311,7 +311,7 @@ class TabBarStyle(QCommonStyle):
elif element == QStyle.CE_TabBarTabLabel:
text_rect, icon_rect = self._tab_layout(opt)
if not opt.icon.isNull():
qtutils.qt_ensure_valid(icon_rect)
qtutils.ensure_valid(icon_rect)
icon_mode = (QIcon.Normal if opt.state & QStyle.State_Enabled
else QIcon.Disabled)
icon_state = (QIcon.On if opt.state & QStyle.State_Selected
@ -382,7 +382,7 @@ class TabBarStyle(QCommonStyle):
padding = self.pixelMetric(PM_TabBarPadding, opt)
icon_rect = QRect()
text_rect = QRect(opt.rect)
qtutils.qt_ensure_valid(text_rect)
qtutils.ensure_valid(text_rect)
indicator_width = config.get('tabs', 'indicator-width')
text_rect.adjust(padding, 0, 0, 0)
if indicator_width != 0:
@ -419,5 +419,5 @@ class TabBarStyle(QCommonStyle):
text_rect.center().y() - tab_icon_size.height() / 2,
tab_icon_size.width(), tab_icon_size.height())
icon_rect = self._style.visualRect(opt.direction, opt.rect, icon_rect)
qtutils.qt_ensure_valid(icon_rect)
qtutils.ensure_valid(icon_rect)
return icon_rect

View File

@ -301,7 +301,7 @@ class WebView(QWebView):
Emit:
titleChanged
"""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
urlstr = url.toDisplayString()
log.webview.debug("New title: {}".format(urlstr))
self.titleChanged.emit(urlstr)
@ -358,7 +358,7 @@ class WebView(QWebView):
@pyqtSlot('QUrl')
def on_url_changed(self, url):
"""Update cur_url when URL has changed."""
qtutils.qt_ensure_valid(url)
qtutils.ensure_valid(url)
self.cur_url = url
@pyqtSlot(str, str)