Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Format.js
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,11 @@ function thumb(path, mime, px, modified) {
return "image://thumb/" + px + "/" + changed + "/" + encodeURIComponent(mime) + "/" + encodeURIComponent(path)
}

function cachedPreview(path, modified, width, height) {
const changed = modified ? modified.getTime() : 0
return "image://thumb/cached/" + Math.floor(width) + "/" + Math.floor(height) + "/" + changed + "/" + encodeURIComponent(path)
}

// A picture as sharp as `px` pixels on its longest side, for the details.
function sharp(path, mime, px, modified) {
const changed = modified ? modified.getTime() : 0
Expand Down
56 changes: 52 additions & 4 deletions src/PreviewWindow.qml
Original file line number Diff line number Diff line change
Expand Up @@ -213,25 +213,72 @@ ApplicationWindow {

readonly property bool animated: win.viewer === "animated"
readonly property var source: animated ? moving : still
readonly property size natural: source.status === Image.Ready ? Qt.size(source.implicitWidth, source.implicitHeight) : Qt.size(1, 1)
readonly property bool canZoom: animated || still.status === Image.Ready
readonly property size natural: source.status === Image.Ready ? Qt.size(source.implicitWidth, source.implicitHeight)
: quick.visible ? Qt.size(quick.implicitWidth, quick.implicitHeight) : Qt.size(1, 1)
readonly property real fitScale: Math.min(1, (width - 48) / natural.width, (height - 48) / natural.height)
property real zoom: fitScale

onFitScaleChanged: if (!zoomed) zoom = fitScale
property bool zoomed: false

function zoomBy(factor) { zoomed = true; zoom = Math.max(0.05, Math.min(16, zoom * factor)) }
function zoomBy(factor) {
if (!canZoom)
return
zoomed = true
zoom = Math.max(0.05, Math.min(16, zoom * factor))
}
function fit() { zoomed = false; zoom = fitScale }
function scroll(direction) { contentY = Math.max(0, Math.min(contentHeight - height, contentY + direction * 80)) }
function loadStill() {
headStart.stop()
still.source = ""
const item = previewer.item
quick.source = previewer.viewer === "image" && item.path && !item.mime.startsWith("image/svg")
&& !/@[2-9]x\.[^.]+$/.test(item.path)
? Format.cachedPreview(item.path, item.modified, win.width, win.height) : ""
if (quick.status === Image.Loading)
headStart.start()
else
showStill()
}
function showStill() {
headStart.stop()
if (previewer.viewer === "image")
still.source = previewer.url
}

contentWidth: Math.max(width, natural.width * zoom)
contentHeight: Math.max(height, natural.height * zoom)

Component.onCompleted: loadStill()
Connections {
target: previewer
function onChanged() { flick.fit() }
function onChanged() {
flick.loadStill()
flick.fit()
}
}

// Qt delivers both images on one reader thread. Give a warm thumb
// a chance to arrive before the full decode occupies that thread.
Timer {
id: headStart
interval: 50
onTriggered: flick.showStill()
}

Image {
id: quick
objectName: "previewThumbnail"
anchors.fill: still
asynchronous: true
cache: false
fillMode: Image.PreserveAspectFit
visible: !flick.animated && status === Image.Ready
&& still.status !== Image.Ready && still.status !== Image.Error
onStatusChanged: if (headStart.running && (status === Image.Ready || status === Image.Error)) flick.showStill()
}
Image {
id: still
// Share the in-flight decode across scale reloads. The hidden
Expand All @@ -252,7 +299,7 @@ ApplicationWindow {
autoTransform: true
smooth: true
mipmap: true
source: flick.animated ? "" : previewer.url
onStatusChanged: if (status === Image.Ready || status === Image.Error) quick.source = ""
}
AnimatedImage {
id: moving
Expand All @@ -266,6 +313,7 @@ ApplicationWindow {
}

TapHandler {
enabled: flick.canZoom
onDoubleTapped: flick.zoomed && Math.abs(flick.zoom - 1) < 0.01 ? flick.fit() : (flick.zoomed = true, flick.zoom = 1)
}
WheelHandler {
Expand Down
41 changes: 38 additions & 3 deletions src/thumbnails.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,23 @@ void Thumbnails::keep(const QImage &image, const QString &path, int pixels, cons
}
}

QImage Thumbnails::cached(const QString &path) const {
const QFileInfo info(path);
if (!info.isFile())
return {};

for (const int size : {128, 256, 512, 1024}) {
QImageReader reader(cachePath(path, size), "png");
const QSize pixels = reader.size();
if (!pixels.isValid() || pixels.width() > size || pixels.height() > size)
continue;
const QImage image = reader.read();
if (madeFor(image, info.lastModified()) && image.text("Thumb::URI") == fileUri(path))
return image;
}
return {};
}

QImage Thumbnails::load(const QString &path, const QString &mime, int size) const {
const QFileInfo info(path);
if (!info.isFile())
Expand Down Expand Up @@ -464,12 +481,31 @@ class ThumbnailResponse : public QQuickImageResponse, public QRunnable {
void work(bool &told) {
// id = <size>/<modified>/<url-encoded mime>/<url-encoded path>, or
// page/<size>/<modified>/<paper>/<ink>/<url-encoded path> for text.
// cached/<width>/<height>/<modified>/<url-encoded path> fits a cached preview.
// The time is only there to tell Qt's own cache apart; load() checks
// the file's.
const QStringList parts = m_id.split('/');
// A tile scrolled away before its turn came shouldn't keep the pool
// from the ones on screen.
if (!m_cancelled && parts.size() >= 5 && parts.at(0) == "sharp") {
if (!m_cancelled && parts.size() >= 5 && parts.at(0) == "cached") {
const QString path = QUrl::fromPercentEncoding(parts.mid(4).join('/').toUtf8());
const QImage thumbnail = m_thumbnails->cached(path);
if (!thumbnail.isNull()) {
// Read the header for geometry. The full Image still decodes the pixels.
QImageReader reader(path);
QSize original = reader.size();
if (reader.transformation().testFlag(QImageIOHandler::TransformationRotate90))
original.transpose();
const QSize viewport(qBound(1, parts.at(1).toInt(), 2048),
qBound(1, parts.at(2).toInt(), 2048));
if (!original.isEmpty()) {
if (original.width() > viewport.width() || original.height() > viewport.height())
original.scale(viewport, Qt::KeepAspectRatio);
m_image = thumbnail.scaled(original.expandedTo(QSize(1, 1)), Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
}
}
} else if (!m_cancelled && parts.size() >= 5 && parts.at(0) == "sharp") {
const int pixels = qBound(256, parts.at(1).toInt(), 8192);
const QString mime = QUrl::fromPercentEncoding(parts.at(3).toUtf8());
const QString path = QUrl::fromPercentEncoding(parts.mid(4).join('/').toUtf8());
Expand All @@ -488,8 +524,7 @@ class ThumbnailResponse : public QQuickImageResponse, public QRunnable {
if (!made.isNull())
thumbnails->keep(made, path, pixels, modified);
return;
}
if (!m_cancelled && parts.size() >= 6 && parts.at(0) == "page") {
} else if (!m_cancelled && parts.size() >= 6 && parts.at(0) == "page") {
const QString path = QUrl::fromPercentEncoding(parts.mid(5).join('/').toUtf8());
m_image = Thumbnails::textPage(path, qBound(64, parts.at(1).toInt(), 1024),
QColor::fromString("#" + parts.at(3)), QColor::fromString("#" + parts.at(4)));
Expand Down
3 changes: 3 additions & 0 deletions src/thumbnails.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ class Thumbnails {
// cache when it is fresh, or a null image when none can be made.
QImage load(const QString &path, const QString &mime, int size) const;

// Read a fresh thumbnail from any standard bucket, smallest first.
QImage cached(const QString &path) const;

// A picture at `pixels` on its longest side, as sharp as the details
// column draws it: read from the file when it's that small already,
// otherwise from Folio's own cache (~/.cache/folio/sharp) when one's been
Expand Down
32 changes: 29 additions & 3 deletions tests/folio_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6443,6 +6443,8 @@ private slots:
QVERIFY(picture.save(file));

Thumbnails thumbnails(dir.filePath("cache"), {dir.filePath("none")});
QVERIFY(thumbnails.cached(file).isNull());
QVERIFY(!QFile::exists(dir.filePath("cache")));
const QImage thumb = thumbnails.load(file, "image/png", 256);
QCOMPARE(thumb.size(), QSize(256, 128));

Expand All @@ -6458,6 +6460,7 @@ private slots:
QImage marked = stored;
marked.fill(Qt::blue);
QVERIFY(marked.save(cached));
QCOMPARE(thumbnails.cached(file).pixelColor(0, 0), QColor(Qt::blue));
QCOMPARE(thumbnails.load(file, "image/png", 256).pixelColor(0, 0), QColor(Qt::blue));
QCOMPARE(Thumbnails::bucketFor(128), QString("normal"));
QCOMPARE(Thumbnails::bucketFor(512), QString("x-large"));
Expand Down Expand Up @@ -6946,23 +6949,31 @@ private slots:
{
if (reads.fetch_add(1) == 0)
release.acquire();
QImage image(1600, 900, QImage::Format_RGB32);
QImage image(200, 100, QImage::Format_RGB32);
image.fill(Qt::darkCyan);
*size = image.size();
return image;
}
};
QTemporaryDir home;
const QString path = home.filePath("picture.png");
QImage picture(200, 100, QImage::Format_RGB32);
picture.fill(Qt::red);
QVERIFY(picture.save(path));
Thumbnails thumbnails(home.filePath("cache"), {home.filePath("none")});
QCOMPARE(thumbnails.load(path, "image/png", 256).size(), QSize(256, 128));
Theme theme(home.filePath("theme"));
QQmlEngine engine;
auto *images = new GatedImages;
engine.addImageProvider("gated", images);
engine.addImageProvider("thumb", new ThumbnailProvider(&thumbnails));
const auto unblock = qScopeGuard([&] { images->release.release(); });
QQmlComponent stand(&engine);
stand.setData("import QtQml\n"
"QtObject {\n"
" signal changed\n"
" property var item: ({ name: 'Picture', path: '/picture.png', mime: 'image/png', size: 1 })\n"
" signal opened\n"
" property var item\n"
" property string viewer: 'image'\n"
" property string url: 'image://gated/picture'\n"
" property int count: 1\n"
Expand All @@ -6973,21 +6984,36 @@ private slots:
QUrl());
std::unique_ptr<QObject> preview(stand.create());
QVERIFY2(preview, qPrintable(stand.errorString()));
QVERIFY(preview->setProperty("item", QVariantMap{
{"name", "Picture"}, {"path", path}, {"mime", "image/png"},
{"size", QFileInfo(path).size()}, {"modified", QFileInfo(path).lastModified()}
}));
engine.rootContext()->setContextProperty("theme", &theme);
engine.rootContext()->setContextProperty("previewer", preview.get());
QQmlComponent component(&engine, QUrl("qrc:/PreviewWindow.qml"));
std::unique_ptr<QObject> root(component.create());
QVERIFY2(root, qPrintable(component.errorString()));
auto *image = root->property("view").value<QQuickItem *>()->property("source").value<QObject *>();
auto *view = root->property("view").value<QQuickItem *>();
QVERIFY(view);
auto *image = view->property("source").value<QObject *>();
auto *thumbnail = view->findChild<QQuickItem *>("previewThumbnail");
QVERIFY(image);
QVERIFY(thumbnail);
QTRY_COMPARE(images->reads.load(), 1);
QTRY_VERIFY(thumbnail->isVisible());
QCOMPARE(view->property("natural").toSize(), picture.size());
QCOMPARE(thumbnail->size(), QSizeF(picture.size()));
// Turning the cache off and on drops and re-requests the image as a
// scale change does, while leaving its source alone.
QVERIFY(image->setProperty("cache", false));
QVERIFY(image->setProperty("cache", true));
images->release.release();
QTRY_COMPARE(image->property("status").toInt(), 1);
QCOMPARE(images->reads.load(), 1);
QVERIFY(!thumbnail->isVisible());
QVERIFY(thumbnail->property("source").toUrl().isEmpty());
QCOMPARE(view->property("natural").toSize(), picture.size());
QVERIFY(!QFile::exists(home.filePath("cache/normal/" + Thumbnails::cacheKey(path))));
}

void previewerStepsThroughTheFolder()
Expand Down
Loading