How to use the qutebrowser.utils.qtutils function in qutebrowser

To help you get started, we’ve selected a few qutebrowser examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github qutebrowser / qutebrowser / tests / helpers / utils.py View on Github external
"""Partial comparison of dicts/lists."""


import re
import pprint
import os.path
import contextlib

import pytest

from qutebrowser.utils import qtutils


qt58 = pytest.mark.skipif(
    qtutils.version_check('5.9'), reason="Needs Qt 5.8 or earlier")
qt59 = pytest.mark.skipif(
    not qtutils.version_check('5.9'), reason="Needs Qt 5.9 or newer")
qt510 = pytest.mark.skipif(
    not qtutils.version_check('5.10'), reason="Needs Qt 5.10 or newer")
skip_qt511 = pytest.mark.skipif(
    qtutils.version_check('5.11'), reason="Needs Qt 5.10 or earlier")


class PartialCompareOutcome:

    """Storage for a partial_compare error.

    Evaluates to False if an error was found.

    Attributes:
        error: A string describing an error or None.
github qutebrowser / qutebrowser / tests / unit / utils / test_qtutils.py View on Github external
def test_version_check(monkeypatch, qversion, compiled, pyqt, version, exact,
                       expected):
    """Test for version_check().

    Args:
        monkeypatch: The pytest monkeypatch fixture.
        qversion: The version to set as fake qVersion().
        compiled: The value for QT_VERSION_STR (set compiled=False)
        pyqt: The value for PYQT_VERSION_STR (set compiled=False)
        version: The version to compare with.
        exact: Use exact comparing (==)
        expected: The expected result.
    """
    monkeypatch.setattr(qtutils, 'qVersion', lambda: qversion)
    if compiled is not None:
        monkeypatch.setattr(qtutils, 'QT_VERSION_STR', compiled)
        monkeypatch.setattr(qtutils, 'PYQT_VERSION_STR', pyqt)
        compiled_arg = True
    else:
        compiled_arg = False

    actual = qtutils.version_check(version, exact, compiled=compiled_arg)
    assert actual == expected
github qutebrowser / qutebrowser / tests / unit / utils / test_utils.py View on Github external
def test_invalid_start(self, colors):
        """Test an invalid start color."""
        with pytest.raises(qtutils.QtValueError):
            utils.interpolate_color(Color(), colors.white, 0)
github qutebrowser / qutebrowser / tests / unit / config / test_configtypes.py View on Github external
def test_special_bounds(self, klass):
        """Test passing strings as bounds."""
        numeric = klass(minval='maxint', maxval='maxint64')
        assert numeric.minval == qtutils.MAXVALS['int']
        assert numeric.maxval == qtutils.MAXVALS['int64']
github qutebrowser / qutebrowser / tests / end2end / fixtures / quteprocess.py View on Github external
__tracebackhide__ = (lambda e: e.errisinstance(
            testprocess.WaitForTimeout))

        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000

        qurl = QUrl(url)
        if not qurl.isValid():
            raise ValueError("Invalid URL {}: {}".format(url,
                                                         qurl.errorString()))

        if (qurl == QUrl('about:blank') and
                not qtutils.version_check('5.10', compiled=False)):
            # For some reason, we don't get a LoadStatus.success for
            # about:blank sometimes.
            # However, if we do this for Qt 5.10, we get general testsuite
            # instability as site loads get reported with about:blank...
            pattern = "Changing title for idx * to 'about:blank'"
        else:
            # We really need the same representation that the webview uses in
            # its __repr__
            url = utils.elide(qurl.toDisplayString(QUrl.EncodeUnicode), 100)
            assert url

            pattern = re.compile(
                r"(load status for : LoadStatus\.{load_status}|fetch: "
                r"PyQt5\.QtCore\.QUrl\('{url}'\) -> .*)".format(
                    load_status=re.escape(load_status), url=re.escape(url)))
github qutebrowser / qutebrowser / tests / unit / browser / webkit / test_cache.py View on Github external
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser.  If not, see .

import pytest
from PyQt5.QtCore import QUrl, QDateTime
from PyQt5.QtNetwork import QNetworkDiskCache, QNetworkCacheMetaData

from qutebrowser.browser.webkit import cache
from qutebrowser.utils import qtutils


pytestmark = pytest.mark.skipif(
    qtutils.version_check('5.7.1', compiled=False) and
    not qtutils.version_check('5.9', compiled=False),
    reason="QNetworkDiskCache is broken on Qt 5.7.1 and 5.8")


@pytest.fixture
def disk_cache(tmpdir, config_stub):
    return cache.DiskCache(str(tmpdir))


def preload_cache(cache, url='http://www.example.com/', content=b'foobar'):
    metadata = QNetworkCacheMetaData()
    metadata.setUrl(QUrl(url))
    assert metadata.isValid()
    device = cache.prepare(metadata)
    assert device is not None
    device.write(content)
github qutebrowser / qutebrowser / qutebrowser / mainwindow / tabbedbrowser.py View on Github external
    @pyqtSlot('QUrl', bool)
    def openurl(self, url, newtab):
        """Open a URL, used as a slot.

        Args:
            url: The URL to open as QUrl.
            newtab: True to open URL in a new tab, False otherwise.
        """
        qtutils.ensure_valid(url)
        if newtab or self.widget.currentWidget() is None:
            self.tabopen(url, background=False)
        else:
            self.widget.currentWidget().openurl(url)
github qutebrowser / qutebrowser / qutebrowser / browser / commands.py View on Github external
'QUTE_SELECTED_TEXT': selection,
        }

        if count is not None:
            env['QUTE_COUNT'] = str(count)

        idx = self._current_index()
        if idx != -1:
            env['QUTE_TITLE'] = self._tabbed_browser.widget.page_title(idx)

        # FIXME:qtwebengine: If tab is None, run_async will fail!
        tab = self._tabbed_browser.widget.currentWidget()

        try:
            url = self._tabbed_browser.current_url()
        except qtutils.QtValueError:
            pass
        else:
            env['QUTE_URL'] = url.toString(QUrl.FullyEncoded)

        try:
            runner = userscripts.run_async(
                tab, cmd, *args, win_id=self._win_id, env=env, verbose=verbose)
        except userscripts.Error as e:
            raise cmdutils.CommandError(e)
        return runner
github qutebrowser / qutebrowser / qutebrowser / utils / utils.py View on Github external
elif colorspace == QColor.Hsv:
        a_c1, a_c2, a_c3, _alpha = start.getHsv()
        b_c1, b_c2, b_c3, _alpha = end.getHsv()
        components = _get_color_percentage(a_c1, a_c2, a_c3, b_c1, b_c2, b_c3,
                                           percent)
        out.setHsv(*components)
    elif colorspace == QColor.Hsl:
        a_c1, a_c2, a_c3, _alpha = start.getHsl()
        b_c1, b_c2, b_c3, _alpha = end.getHsl()
        components = _get_color_percentage(a_c1, a_c2, a_c3, b_c1, b_c2, b_c3,
                                           percent)
        out.setHsl(*components)
    else:
        raise ValueError("Invalid colorspace!")
    out = out.convertTo(start.spec())
    qtutils.ensure_valid(out)
    return out
github qutebrowser / qutebrowser / qutebrowser / browser / downloadview.py View on Github external
def sizeHint(self):
        """Return sizeHint based on the view contents."""
        idx = self.model().last_index()
        bottom = self.visualRect(idx).bottom()
        if bottom != -1:
            margins = self.contentsMargins()
            height = (bottom + margins.top() + margins.bottom() +
                      2 * self.spacing())
            size = QSize(0, height)
        else:
            size = QSize(0, 0)
        qtutils.ensure_valid(size)
        return size