From cb39e20cd0aa83a59fc516edc9716ef4ba9c7614 Mon Sep 17 00:00:00 2001 From: Clayton Faria Date: Wed, 18 Nov 2026 23:48:47 +0800 Subject: [PATCH] Show the existing thumbnail while a preview loads --- src/Format.js | 5 ++++ src/PreviewWindow.qml | 56 +++++++++++++++++++++++++++++++++++++++---- src/thumbnails.cpp | 41 ++++++++++++++++++++++++++++--- src/thumbnails.h | 3 +++ tests/folio_tests.cpp | 32 ++++++++++++++++++++++--- 5 files changed, 127 insertions(+), 10 deletions(-) diff --git a/src/Format.js b/src/Format.js index 5cdbded4..594c1b7a 100644 --- a/src/Format.js +++ b/src/Format.js @@ -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 diff --git a/src/PreviewWindow.qml b/src/PreviewWindow.qml index 2b710086..96d1123e 100644 --- a/src/PreviewWindow.qml +++ b/src/PreviewWindow.qml @@ -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 @@ -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 @@ -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 { diff --git a/src/thumbnails.cpp b/src/thumbnails.cpp index c0ae8b78..69c56e1c 100644 --- a/src/thumbnails.cpp +++ b/src/thumbnails.cpp @@ -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()) @@ -464,12 +481,31 @@ class ThumbnailResponse : public QQuickImageResponse, public QRunnable { void work(bool &told) { // id = ///, or // page///// for text. + // cached//// 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()); @@ -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))); diff --git a/src/thumbnails.h b/src/thumbnails.h index 531e9c8d..9c693119 100644 --- a/src/thumbnails.h +++ b/src/thumbnails.h @@ -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 diff --git a/tests/folio_tests.cpp b/tests/folio_tests.cpp index 6a0aeeb4..a3f8b88b 100644 --- a/tests/folio_tests.cpp +++ b/tests/folio_tests.cpp @@ -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)); @@ -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")); @@ -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" @@ -6973,14 +6984,25 @@ private slots: QUrl()); std::unique_ptr 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 root(component.create()); QVERIFY2(root, qPrintable(component.errorString())); - auto *image = root->property("view").value()->property("source").value(); + auto *view = root->property("view").value(); + QVERIFY(view); + auto *image = view->property("source").value(); + auto *thumbnail = view->findChild("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)); @@ -6988,6 +7010,10 @@ private slots: 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()