Serve resource files from qute://resource

See #4467, #5832
This commit is contained in:
Florian Bruhin 2021-01-26 16:49:40 +01:00
parent 6d07d2cbf8
commit 3abe6b3445
4 changed files with 22 additions and 30 deletions

View File

@ -566,3 +566,15 @@ def qute_warning(url: QUrl) -> _HandlerRet:
else:
raise NotFoundError("Invalid warning page {}".format(path))
return 'text/html', src
@add_handler('resource')
def qute_resource(url: QUrl) -> _HandlerRet:
"""Handler for qute://resource."""
path = url.path().lstrip('/')
mimetype = utils.guess_mimetype(path, fallback=True)
try:
data = utils.read_file(path, binary=True)
except FileNotFoundError as e:
raise NotFoundError(str(e))
return mimetype, data

View File

@ -105,13 +105,16 @@ class Environment(jinja2.Environment):
self._autoescape = True
def _resource_url(self, path: str) -> str:
"""Load images from a relative path (to qutebrowser).
"""Load qutebrowser resource files.
Arguments:
path: The relative path to the image
path: The relative path to the resource.
"""
image = utils.resource_filename(path)
url = QUrl.fromLocalFile(image)
if not os.path.isabs(path):
path = '/' + path
url = QUrl('qute://resource')
url.setPath(path)
urlutils.ensure_valid(url)
urlstr = url.toString(QUrl.FullyEncoded) # type: ignore[arg-type]
return urlstr

View File

@ -173,9 +173,6 @@ class TestDirbrowserHtml:
def test_icons(self, monkeypatch):
"""Make sure icon paths are correct file:// URLs."""
monkeypatch.setattr(filescheme.jinja.utils, 'resource_filename',
lambda name: '/test path/foo.svg')
html = filescheme.dirbrowser_html(os.getcwd()).decode('utf-8')
soup = bs4.BeautifulSoup(html, 'html.parser')
@ -183,7 +180,7 @@ class TestDirbrowserHtml:
print(soup.prettify())
css = soup.html.head.style.string
assert "background-image: url('file:///test%20path/foo.svg');" in css
assert "background-image: url('qute://resource/img/folder.svg');" in css
def test_empty(self, tmpdir, parser):
parsed = parser(str(tmpdir))

View File

@ -27,15 +27,13 @@ import jinja2.exceptions
import pytest
from PyQt5.QtCore import QUrl
from qutebrowser.utils import utils, jinja
from qutebrowser.utils import jinja
from qutebrowser.config import configexc
@pytest.fixture(autouse=True)
def patch_read_file(monkeypatch):
"""pytest fixture to patch utils.read_file."""
real_resource_filename = utils.resource_filename
def _read_file(path, binary=False):
"""A read_file which returns a simple template if the path is right."""
if path == os.path.join('html', 'test.html'):
@ -59,16 +57,7 @@ def patch_read_file(monkeypatch):
else:
raise IOError("Invalid path {}!".format(path))
def _resource_filename(path):
if path == 'utils/testfile':
return real_resource_filename(path)
elif path == 'testfile.txt':
return path
else:
raise IOError("Invalid path {}!".format(path))
monkeypatch.setattr(jinja.utils, 'read_file', _read_file)
monkeypatch.setattr(jinja.utils, 'resource_filename', _resource_filename)
def test_simple_template():
@ -83,16 +72,7 @@ def test_resource_url():
print(data)
url = QUrl(data)
assert url.isValid()
assert url.scheme() == 'file'
path = url.path()
if utils.is_windows:
path = path.lstrip('/')
path = path.replace('/', os.sep)
with open(path, 'r', encoding='utf-8') as f:
assert f.read().splitlines()[0] == "Hello World!"
assert url.toDisplayString() == 'qute://resource/utils/testfile'
def test_data_url():