Skip to content
Open
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
12 changes: 9 additions & 3 deletions src/FileRow.qml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import QtQuick
import Folio 1.0
import QtQuick.Layouts
import QtQuick.Effects
import "Format.js" as Format
Expand Down Expand Up @@ -187,11 +188,16 @@ Item {
}
}

HoverHandler {
id: hover
DragPicture {
id: dragPicture
// Cleared first: Qt (6.12) reloads a new picture at the size of the
// one before, which for a grab only warns ("Ignoring sourceSize").
onHoveredChanged: if (hovered) row.grabToImage(result => { row.Drag.imageSource = ""; row.Drag.imageSource = result.url })
onReady: { row.Drag.imageSource = ""; row.Drag.imageSource = url }
}

HoverHandler {
id: hover
onHoveredChanged: if (hovered) dragPicture.capture(row)
}
TapHandler {
id: tap
Expand Down
12 changes: 9 additions & 3 deletions src/FileTile.qml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import QtQuick
import Folio 1.0
import QtQuick.Shapes
import QtQuick.Effects
import "Format.js" as Format
Expand Down Expand Up @@ -119,13 +120,18 @@ Item {
onDropped: (drop) => { fileOps.dropInto(drop.urls, tile.path); drop.accept(Qt.MoveAction) }
}

DragPicture {
id: dragPicture
// Cleared first: Qt (6.12) reloads a new picture at the size of the
// one before, which for a grab only warns ("Ignoring sourceSize").
onReady: { tile.Drag.imageSource = ""; tile.Drag.imageSource = url }
}

HoverHandler {
id: hover
// The picture that follows the pointer while dragging; taken ahead
// of time because a drag can't wait for it.
// Cleared first: Qt (6.12) reloads a new picture at the size of the
// one before, which for a grab only warns ("Ignoring sourceSize").
onHoveredChanged: if (hovered) art.grabToImage(result => { tile.Drag.imageSource = ""; tile.Drag.imageSource = result.url })
onHoveredChanged: if (hovered) dragPicture.capture(art)
}

// Dragging hands the file to whatever it lands on as a URI list: the
Expand Down
29 changes: 29 additions & 0 deletions src/dragpicture.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include "dragpicture.h"

#include <QQuickItem>
#include <QQuickWindow>

bool DragPicture::capture(QQuickItem *item) {
if (!item)
return false;
auto grab = item->grabToImage();
if (!grab)
return false;
// A replaced or discarded delegate can let go between Qt's setup and
// render callbacks. Keep that frame's work alive until it has completed;
// queue the release after ready returns. The window also releases it on
// teardown, after its render thread has stopped.
connect(grab.data(), &QQuickItemGrabResult::ready, item->window(), [grab] {},
Qt::ConnectionType(Qt::QueuedConnection | Qt::SingleShotConnection));
m_source = item;
m_grab = grab;
connect(grab.data(), &QQuickItemGrabResult::ready, this, [this, request = grab.data()] {
if (m_grab.data() == request && m_source)
emit ready();
});
return true;
}

QUrl DragPicture::url() const {
return m_grab ? m_grab->url() : QUrl();
}
28 changes: 28 additions & 0 deletions src/dragpicture.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

#include <QObject>
#include <QPointer>
#include <QQuickItemGrabResult>
#include <QSharedPointer>
#include <QUrl>

class QQuickItem;

// A drag's picture, taken ahead of time. The C++ grab API keeps a render
// callback's result alive even if its item disappears while it is running.
class DragPicture : public QObject {
Q_OBJECT
Q_PROPERTY(QUrl url READ url NOTIFY ready)

public:
explicit DragPicture(QObject *parent = nullptr) : QObject(parent) {}
Q_INVOKABLE bool capture(QQuickItem *item);
QUrl url() const;

signals:
void ready();

private:
QPointer<QQuickItem> m_source;
QSharedPointer<QQuickItemGrabResult> m_grab;
};
2 changes: 2 additions & 0 deletions src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
#include <cstdio>

#include "chooser.h"
#include "dragpicture.h"
#include "filemanager1.h"
#include "foldermodel.h"
#include "places.h"
Expand Down Expand Up @@ -146,6 +147,7 @@ int main(int argc, char *argv[]) {
engine.addImageProvider("plugin-icon", new PluginIconProvider);
// Creatable too: the column view lists each folder on the way here.
qmlRegisterType<FolderModel>("Folio", 1, 0, "FolderModel");
qmlRegisterType<DragPicture>("Folio", 1, 0, "DragPicture");
engine.rootContext()->setContextProperty("translator", &translator);
engine.rootContext()->setContextProperty("theme", &theme);
engine.rootContext()->setContextProperty("places", &places);
Expand Down
158 changes: 158 additions & 0 deletions tests/folio_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
#include "backend.h"
#include "chooser.h"
#include "disks.h"
#include "dragpicture.h"
#include "fileops.h"
#include "foldermodel.h"
#include "mounter.h"
Expand Down Expand Up @@ -549,11 +550,168 @@ class FolioTests : public QObject {
private slots:
void initTestCase()
{
qmlRegisterType<DragPicture>("Folio", 1, 0, "DragPicture");
// No test ever reaches the real udisks, which would change real disks.
fakeDisks({});
Backend::setSettingsFile(settings.filePath("folio.conf"));
}

void dragPicturesKeepTheLatestImage()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData(R"(
import QtQuick
import Folio 1.0
Window {
width: 160; height: 64; visible: true
DragPicture { id: picture; objectName: "picture" }
Rectangle { objectName: "red"; width: 24; height: 24; color: "red" }
Rectangle { objectName: "green"; x: 32; width: 24; height: 24; color: "lime" }
Image { objectName: "preview"; x: 96; width: 24; height: 24; source: picture.url }
Image { objectName: "later"; x: 128; width: 24; height: 24 }
}
)", QUrl("file:///DragPictureTest.qml"));
std::unique_ptr<QObject> root(component.create());
QVERIFY2(root, qPrintable(component.errorString()));
auto *window = qobject_cast<QQuickWindow *>(root.get());
QVERIFY(QTest::qWaitForWindowExposed(window));
auto *picture = root->findChild<DragPicture *>("picture");
auto *red = root->findChild<QQuickItem *>("red");
auto *green = root->findChild<QQuickItem *>("green");
auto *preview = root->findChild<QQuickItem *>("preview");
auto *later = root->findChild<QQuickItem *>("later");
QVERIFY(picture && red && green && preview && later);
QSignalSpy ready(picture, &DragPicture::ready);
const auto shown = [&](QQuickItem *image) {
// grabWindow returns physical pixels, including at high DPI.
const auto frame = window->grabWindow();
const QPointF at = image->mapToScene(QPointF(12, 12)) * window->devicePixelRatio();
return frame.isNull() ? QColor() : frame.pixelColor(at.toPoint());
};
QVERIFY(picture->capture(red));
QTRY_COMPARE(ready.count(), 1);
const QUrl first = picture->url();
QVERIFY(!first.isEmpty());
QTRY_COMPARE(shown(preview), QColor(Qt::red));
// The URL must stay usable after QML's garbage collection, until
// another capture replaces it, rather than referring to freed data.
// Release the first consumer's pixels before collecting, then load
// the saved URL in an initially empty Image.
QVERIFY(preview->setProperty("source", QUrl()));
engine.collectGarbage();
QVERIFY(later->setProperty("source", first));
QTRY_COMPARE(shown(later), QColor(Qt::red));
QVERIFY(later->setProperty("source", QUrl()));
ready.clear();
QVERIFY(picture->capture(red));
QVERIFY(picture->capture(green));
QTRY_COMPARE(ready.count(), 1);
QVERIFY(picture->url() != first);
QTRY_COMPARE(shown(preview), QColor(Qt::green));
QVERIFY(!picture->capture(nullptr));
QCOMPARE(ready.count(), 1);
QTRY_COMPARE(shown(preview), QColor(Qt::green));
}

void dragPicturesAllowPendingItemsAndWindowsToDisappear()
{
QQmlEngine engine;
QQmlComponent component(&engine);
component.setData(R"(
import QtQuick
import Folio 1.0
Window {
width: 64; height: 64; visible: true
DragPicture { objectName: "picture" }
Rectangle { objectName: "source"; width: 24; height: 24; color: "red" }
}
)", QUrl("file:///PendingDragPictureTest.qml"));
// Destroy a source while its snapshot is queued, then the whole
// window with one queued. No reply may reach a discarded delegate.
for (int i = 0; i < 12; ++i) {
std::unique_ptr<QObject> root(component.create());
QVERIFY2(root, qPrintable(component.errorString()));
auto *window = qobject_cast<QQuickWindow *>(root.get());
QVERIFY(QTest::qWaitForWindowExposed(window));
auto *picture = root->findChild<DragPicture *>("picture");
auto *source = root->findChild<QQuickItem *>("source");
QVERIFY(picture && source);
QSignalSpy ready(picture, &DragPicture::ready);
QVERIFY(picture->capture(source));
if (i % 2 == 0) {
delete source;
// A rendered frame is the boundary for the pending grab.
QSignalSpy frame(window, &QQuickWindow::frameSwapped);
window->update();
QTRY_VERIFY(!frame.isEmpty());
QCOMPARE(ready.count(), 0);
Comment on lines +641 to +648

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Delegate destruction goes untested. The source-deletion branch leaves picture alive, so its m_grab still holds the pending capture. The other branch deletes the whole window. Neither covers scrolling a delegate away, where both the source and DragPicture disappear while the window keeps rendering—the case that needs the new window-held reference.

Add a branch that deletes both objects after capture(), leaves the window open, and waits for another frame. This would cover the ownership path this fix adds.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

} else {
QPointer<DragPicture> closing(picture);
root.reset();
QVERIFY(closing.isNull());
QCoreApplication::processEvents();
}
}
}

void fileDelegatesPrepareDragPictures_data()
{
QTest::addColumn<QString>("delegate");
QTest::newRow("list-and-columns") << QString("FileRow");
QTest::newRow("grid") << QString("FileTile");
}

void fileDelegatesPrepareDragPictures()
{
QFETCH(QString, delegate);
QTemporaryDir home;
Backend backend(home.path());
Theme theme(home.filePath("theme"));
FileOps fileOps;
Translator translator(home.filePath("language"), sourceFolder() + "/i18n");
Thumbnails thumbnails(home.filePath("cache"), {home.filePath("none")});
QQmlEngine engine;
engine.rootContext()->setContextProperty("backend", &backend);
engine.rootContext()->setContextProperty("theme", &theme);
engine.rootContext()->setContextProperty("fileOps", &fileOps);
engine.rootContext()->setContextProperty("translator", &translator);
engine.addImageProvider("thumb", new ThumbnailProvider(&thumbnails));
QQmlComponent component(&engine);
component.setData(QString(R"(
import QtQuick
Window {
width: 640; height: 240; visible: true
%1 {
id: entry; objectName: "entry"; width: 300; y: 20; height: %3
index: 0; name: "notes.txt"; path: "/notes.txt"; isDir: false
kind: "text"; mime: "text/plain"; extension: "TXT"
size: 1; modified: new Date(0); itemCount: -1; icon: ""; selected: false
%2
}
function pictureUrl() { return String(entry.Drag.imageSource) }
}
)").arg(delegate, delegate == "FileRow" ? "depth: 0; expanded: false" : "",
delegate == "FileRow" ? "32" : "160").toUtf8(),
QUrl::fromLocalFile(sourceFolder() + "/DelegateDragPictureTest.qml"));
std::unique_ptr<QObject> root(component.create());
QVERIFY2(root, qPrintable(component.errorString()));
auto *window = qobject_cast<QQuickWindow *>(root.get());
QVERIFY(QTest::qWaitForWindowExposed(window));
auto *entry = root->findChild<QQuickItem *>("entry");
QVERIFY(entry);
// Move out and back in: the real hover handler must precompute the
// picture and hand its still-live URL to Qt's drag machinery.
QTest::mouseMove(window, QPoint(600, 220));
QTest::mouseMove(window, entry->mapToScene(QPointF(100, 16)).toPoint());
QVariant url;
QTRY_VERIFY((QMetaObject::invokeMethod(root.get(), "pictureUrl", Q_RETURN_ARG(QVariant, url)),
!url.toString().isEmpty()));
auto *picture = entry->findChild<DragPicture *>();
QVERIFY(picture);
QCOMPARE(QUrl(url.toString()), picture->url());
}

void foldersRememberTheirOrderAndPassItDown()
{
QTemporaryDir home;
Expand Down
Loading