thumbnailview.cpp 34.4 KB
Newer Older
1
2
/*
Gwenview: an image viewer
Aurélien Gâteau's avatar
Aurélien Gâteau committed
3
Copyright 2007 Aurélien Gâteau <agateau@kde.org>
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
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 this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

*/
David Edmundson's avatar
David Edmundson committed
20
#include "thumbnailview.h"
21

22
23
// STL
#include <cmath>
24
25

// Qt
26
#include <QApplication>
27
28
#include <QDragEnterEvent>
#include <QDropEvent>
29
#include <QPainter>
30
#include <QPointer>
31
#include <QQueue>
32
#include <QScrollBar>
33
#include <QTimeLine>
34
#include <QTimer>
David Edmundson's avatar
David Edmundson committed
35
#include <QDrag>
David Edmundson's avatar
David Edmundson committed
36
#include <QMimeData>
Lukáš Tinkl's avatar
Lukáš Tinkl committed
37
#include <QDateTime>
Steffen Hartleib's avatar
Steffen Hartleib committed
38
39
#include <QGestureEvent>
#include <QScroller>
40

41
// KF
Aurélien Gâteau's avatar
Aurélien Gâteau committed
42
43
44
#include <KDirModel>
#include <KIconLoader>
#include <KPixmapSequence>
45
#include <KUrlMimeData>
46
47

// Local
48
#include "gwenview_lib_debug.h"
49
#include "abstractdocumentinfoprovider.h"
50
#include "abstractthumbnailviewhelper.h"
51
#include "archiveutils.h"
Aurélien Gâteau's avatar
Aurélien Gâteau committed
52
#include "dragpixmapgenerator.h"
53
#include "gwenviewconfig.h"
54
#include "mimetypeutils.h"
55
#include "urlutils.h"
56
#include <lib/gvdebug.h>
57
#include <lib/thumbnailprovider/thumbnailprovider.h>
Steffen Hartleib's avatar
Steffen Hartleib committed
58
59
#include <lib/scrollerutils.h>
#include <lib/touch/touch.h>
60

61
62
namespace Gwenview
{
Aurélien Gâteau's avatar
Aurélien Gâteau committed
63

64
65
66
67
#undef ENABLE_LOG
#undef LOG
//#define ENABLE_LOG
#ifdef ENABLE_LOG
Laurent Montel's avatar
Laurent Montel committed
68
#define LOG(x) //qCDebug(GWENVIEW_LIB_LOG) << x
69
70
71
72
#else
#define LOG(x) ;
#endif

Aurélien Gâteau's avatar
Aurélien Gâteau committed
73
74
/** How many msec to wait before starting to smooth thumbnails */
const int SMOOTH_DELAY = 500;
75

76
77
const int WHEEL_ZOOM_MULTIPLIER = 4;

78
79
80
81
82
83
84
85
static KFileItem fileItemForIndex(const QModelIndex& index)
{
    if (!index.isValid()) {
        LOG("Invalid index");
        return KFileItem();
    }
    QVariant data = index.data(KDirModel::FileItemRole);
    return qvariant_cast<KFileItem>(data);
86
87
}

David Edmundson's avatar
David Edmundson committed
88
static QUrl urlForIndex(const QModelIndex& index)
89
90
{
    KFileItem item = fileItemForIndex(index);
David Edmundson's avatar
David Edmundson committed
91
    return item.isNull() ? QUrl() : item.url();
92
93
}

Aurélien Gâteau's avatar
Aurélien Gâteau committed
94
95
struct Thumbnail
{
David Edmundson's avatar
David Edmundson committed
96
    Thumbnail(const QPersistentModelIndex& index_, const QDateTime& mtime)
97
98
        : mIndex(index_)
        , mModificationTime(mtime)
Benjamin Löwe's avatar
Benjamin Löwe committed
99
        , mFileSize(0)
100
101
102
103
        , mRough(true)
        , mWaitingForThumbnail(true) {}

    Thumbnail()
Benjamin Löwe's avatar
Benjamin Löwe committed
104
105
        : mFileSize(0)
        , mRough(true)
106
107
108
109
110
111
112
113
114
115
116
117
        , mWaitingForThumbnail(true) {}

    /**
     * Init the thumbnail based on a icon
     */
    void initAsIcon(const QPixmap& pix)
    {
        mGroupPix = pix;
        int largeGroupSize = ThumbnailGroup::pixelSize(ThumbnailGroup::Large);
        mFullSize = QSize(largeGroupSize, largeGroupSize);
    }

Aurélien Gâteau's avatar
Aurélien Gâteau committed
118
119
    bool isGroupPixAdaptedForSize(int size) const
    {
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
        if (mWaitingForThumbnail) {
            return false;
        }
        if (mGroupPix.isNull()) {
            return false;
        }
        const int groupSize = qMax(mGroupPix.width(), mGroupPix.height());
        if (groupSize >= size) {
            return true;
        }

        // groupSize is less than size, but this may be because the full image
        // is the same size as groupSize
        return groupSize == qMax(mFullSize.width(), mFullSize.height());
    }

David Edmundson's avatar
David Edmundson committed
136
    void prepareForRefresh(const QDateTime& mtime)
137
138
    {
        mModificationTime = mtime;
Benjamin Löwe's avatar
Benjamin Löwe committed
139
        mFileSize = 0;
140
141
142
143
144
145
146
147
148
        mGroupPix = QPixmap();
        mAdjustedPix = QPixmap();
        mFullSize = QSize();
        mRealFullSize = QSize();
        mRough = true;
        mWaitingForThumbnail = true;
    }

    QPersistentModelIndex mIndex;
David Edmundson's avatar
David Edmundson committed
149
    QDateTime mModificationTime;
150
151
152
153
154
155
156
157
158
    /// The pix loaded from .thumbnails/{large,normal}
    QPixmap mGroupPix;
    /// Scaled version of mGroupPix, adjusted to ThumbnailView::thumbnailSize
    QPixmap mAdjustedPix;
    /// Size of the full image
    QSize mFullSize;
    /// Real size of the full image, invalid unless the thumbnail
    /// represents a raster image (not an icon)
    QSize mRealFullSize;
Benjamin Löwe's avatar
Benjamin Löwe committed
159
160
    /// File size of the full image
    KIO::filesize_t mFileSize;
161
    /// Whether mAdjustedPix represents has been scaled using fast or smooth
Benjamin Löwe's avatar
Benjamin Löwe committed
162
    /// transformation
163
164
165
    bool mRough;
    /// Set to true if mGroupPix should be replaced with a real thumbnail
    bool mWaitingForThumbnail;
166
167
};

Aurélien Gâteau's avatar
Aurélien Gâteau committed
168
typedef QHash<QUrl, Thumbnail> ThumbnailForUrl;
David Edmundson's avatar
David Edmundson committed
169
typedef QQueue<QUrl> UrlQueue;
170
typedef QSet<QPersistentModelIndex> PersistentModelIndexSet;
171

Aurélien Gâteau's avatar
Aurélien Gâteau committed
172
173
struct ThumbnailViewPrivate
{
174
    ThumbnailView* q;
175
    ThumbnailView::ThumbnailScaleMode mScaleMode;
176
177
    QSize mThumbnailSize;
    qreal mThumbnailAspectRatio;
178
179
180
181
182
183
184
185
186
    AbstractDocumentInfoProvider* mDocumentInfoProvider;
    AbstractThumbnailViewHelper* mThumbnailViewHelper;
    ThumbnailForUrl mThumbnailForUrl;
    QTimer mScheduledThumbnailGenerationTimer;

    UrlQueue mSmoothThumbnailQueue;
    QTimer mSmoothThumbnailTimer;

    QPixmap mWaitingThumbnail;
187
    QPointer<ThumbnailProvider> mThumbnailProvider;
188
189
190
191
192

    PersistentModelIndexSet mBusyIndexSet;
    KPixmapSequence mBusySequence;
    QTimeLine* mBusyAnimationTimeLine;

193
194
    bool mCreateThumbnailsForRemoteUrls;

Steffen Hartleib's avatar
Steffen Hartleib committed
195
196
197
    QScroller* mScroller;
    Touch* mTouch;

198
199
    void setupBusyAnimation()
    {
200
        mBusySequence = KIconLoader::global()->loadPixmapSequence(QStringLiteral("process-working"), 22);
201
        mBusyAnimationTimeLine = new QTimeLine(100 * mBusySequence.frameCount(), q);
202
        mBusyAnimationTimeLine->setEasingCurve(QEasingCurve::Linear);
203
204
        mBusyAnimationTimeLine->setEndFrame(mBusySequence.frameCount() - 1);
        mBusyAnimationTimeLine->setLoopCount(0);
Laurent Montel's avatar
Laurent Montel committed
205
        QObject::connect(mBusyAnimationTimeLine, &QTimeLine::frameChanged, q, &ThumbnailView::updateBusyIndexes);
206
207
    }

208
    void scheduleThumbnailGeneration()
209
    {
210
211
        if (mThumbnailProvider) {
            mThumbnailProvider->removePendingItems();
212
213
        }
        mSmoothThumbnailQueue.clear();
214
215
216
        if (!mScheduledThumbnailGenerationTimer.isActive()) {
            mScheduledThumbnailGenerationTimer.start();
        }
217
218
219
220
221
222
    }

    void updateThumbnailForModifiedDocument(const QModelIndex& index)
    {
        Q_ASSERT(mDocumentInfoProvider);
        KFileItem item = fileItemForIndex(index);
David Edmundson's avatar
David Edmundson committed
223
        QUrl url = item.url();
224
        ThumbnailGroup::Enum group = ThumbnailGroup::fromPixelSize(mThumbnailSize.width());
225
226
227
        QPixmap pix;
        QSize fullSize;
        mDocumentInfoProvider->thumbnailForDocument(url, group, &pix, &fullSize);
David Edmundson's avatar
David Edmundson committed
228
        mThumbnailForUrl[url] = Thumbnail(QPersistentModelIndex(index), QDateTime::currentDateTime());
Benjamin Löwe's avatar
Benjamin Löwe committed
229
        q->setThumbnail(item, pix, fullSize, 0);
230
231
    }

232
    void appendItemsToThumbnailProvider(const KFileItemList& list)
233
    {
234
        if (mThumbnailProvider) {
235
            ThumbnailGroup::Enum group = ThumbnailGroup::fromPixelSize(mThumbnailSize.width());
236
237
            mThumbnailProvider->setThumbnailGroup(group);
            mThumbnailProvider->appendItems(list);
238
239
240
241
242
243
244
245
        }
    }

    void roughAdjustThumbnail(Thumbnail* thumbnail)
    {
        const QPixmap& mGroupPix = thumbnail->mGroupPix;
        const int groupSize = qMax(mGroupPix.width(), mGroupPix.height());
        const int fullSize = qMax(thumbnail->mFullSize.width(), thumbnail->mFullSize.height());
246
        if (fullSize == groupSize && mGroupPix.height() <= mThumbnailSize.height() && mGroupPix.width() <= mThumbnailSize.width()) {
247
248
249
            thumbnail->mAdjustedPix = mGroupPix;
            thumbnail->mRough = false;
        } else {
250
            thumbnail->mAdjustedPix = scale(mGroupPix, Qt::FastTransformation);
251
252
253
254
            thumbnail->mRough = true;
        }
    }

Aurélien Gâteau's avatar
Aurélien Gâteau committed
255
    void initDragPixmap(QDrag* drag, const QModelIndexList& indexes)
256
    {
257
        const int thumbCount = qMin(indexes.count(), int(DragPixmapGenerator::MaxCount));
Aurélien Gâteau's avatar
Aurélien Gâteau committed
258
        QList<QPixmap> lst;
259
        for (int row = 0; row < thumbCount; ++row) {
David Edmundson's avatar
David Edmundson committed
260
            const QUrl url = urlForIndex(indexes[row]);
Aurélien Gâteau's avatar
Aurélien Gâteau committed
261
            lst << mThumbnailForUrl.value(url).mAdjustedPix;
262
        }
263
        DragPixmapGenerator::DragPixmap dragPixmap = DragPixmapGenerator::generate(lst, indexes.count());
Aurélien Gâteau's avatar
Aurélien Gâteau committed
264
265
        drag->setPixmap(dragPixmap.pix);
        drag->setHotSpot(dragPixmap.hotSpot);
266
    }
267
268
269
270
271

    QPixmap scale(const QPixmap& pix, Qt::TransformationMode transformationMode)
    {
        switch (mScaleMode) {
        case ThumbnailView::ScaleToFit:
272
            return pix.scaled(mThumbnailSize.width(), mThumbnailSize.height(), Qt::KeepAspectRatio, transformationMode);
273
        case ThumbnailView::ScaleToSquare: {
274
275
            int minSize = qMin(pix.width(), pix.height());
            QPixmap pix2 = pix.copy((pix.width() - minSize) / 2, (pix.height() - minSize) / 2, minSize, minSize);
276
            return pix2.scaled(mThumbnailSize.width(), mThumbnailSize.height(), Qt::KeepAspectRatio, transformationMode);
277
        }
278
        case ThumbnailView::ScaleToHeight:
279
            return pix.scaledToHeight(mThumbnailSize.height(), transformationMode);
280
        case ThumbnailView::ScaleToWidth:
281
            return pix.scaledToWidth(mThumbnailSize.width(), transformationMode);
282
283
284
285
286
        }
        // Keep compiler happy
        Q_ASSERT(0);
        return QPixmap();
    }
287
288
289
290
};

ThumbnailView::ThumbnailView(QWidget* parent)
: QListView(parent)
291
292
, d(new ThumbnailViewPrivate)
{
293
    d->q = this;
294
    d->mScaleMode = ScaleToFit;
295
296
297
    d->mThumbnailViewHelper = nullptr;
    d->mDocumentInfoProvider = nullptr;
    d->mThumbnailProvider = nullptr;
298
299
300
    // Init to some stupid value so that the first call to setThumbnailSize()
    // is not ignored (do not use 0 in case someone try to divide by
    // mThumbnailSize...)
301
302
    d->mThumbnailSize = QSize(1, 1);
    d->mThumbnailAspectRatio = 1;
303
    d->mCreateThumbnailsForRemoteUrls = true;
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

    setFrameShape(QFrame::NoFrame);
    setViewMode(QListView::IconMode);
    setResizeMode(QListView::Adjust);
    setDragEnabled(true);
    setAcceptDrops(true);
    setDropIndicatorShown(true);
    setUniformItemSizes(true);
    setEditTriggers(QAbstractItemView::EditKeyPressed);

    d->setupBusyAnimation();

    setVerticalScrollMode(ScrollPerPixel);
    setHorizontalScrollMode(ScrollPerPixel);

    d->mScheduledThumbnailGenerationTimer.setSingleShot(true);
    d->mScheduledThumbnailGenerationTimer.setInterval(500);
Laurent Montel's avatar
Laurent Montel committed
321
    connect(&d->mScheduledThumbnailGenerationTimer, &QTimer::timeout, this, &ThumbnailView::generateThumbnailsForItems);
322
323

    d->mSmoothThumbnailTimer.setSingleShot(true);
Laurent Montel's avatar
Laurent Montel committed
324
    connect(&d->mSmoothThumbnailTimer, &QTimer::timeout, this, &ThumbnailView::smoothNextThumbnail);
325
326

    setContextMenuPolicy(Qt::CustomContextMenu);
Laurent Montel's avatar
Laurent Montel committed
327
    connect(this, &ThumbnailView::customContextMenuRequested, this, &ThumbnailView::showContextMenu);
328

329
    connect(this, &ThumbnailView::activated, this, &ThumbnailView::emitIndexActivatedIfNoModifiers);
Steffen Hartleib's avatar
Steffen Hartleib committed
330
331
332
333
334
335
336
337

    d->mScroller = ScrollerUtils::setQScroller(this->viewport());
    d->mTouch = new Touch(viewport());
    connect(d->mTouch, &Touch::twoFingerTapTriggered, this, &ThumbnailView::showContextMenu);
    connect(d->mTouch, &Touch::pinchZoomTriggered, this, &ThumbnailView::zoomGesture);
    connect(d->mTouch, &Touch::pinchGestureStarted, this, &ThumbnailView::setZoomParameter);
    connect(d->mTouch, &Touch::tapTriggered, this, &ThumbnailView::tapGesture);
    connect(d->mTouch, &Touch::tapHoldAndMovingTriggered, this, &ThumbnailView::startDragFromTouch);
338
339
340
341
342
343

    const QFontMetrics metrics(viewport()->font());
    const int singleStep = metrics.height() * QApplication::wheelScrollLines();

    verticalScrollBar()->setSingleStep(singleStep);
    horizontalScrollBar()->setSingleStep(singleStep);
344
345
346
347
}

ThumbnailView::~ThumbnailView()
{
Steffen Hartleib's avatar
Steffen Hartleib committed
348
    delete d->mTouch;
349
350
351
    delete d;
}

352
353
354
355
356
ThumbnailView::ThumbnailScaleMode ThumbnailView::thumbnailScaleMode() const
{
    return d->mScaleMode;
}

357
358
359
void ThumbnailView::setThumbnailScaleMode(ThumbnailScaleMode mode)
{
    d->mScaleMode = mode;
360
    setUniformItemSizes(mode == ScaleToFit || mode == ScaleToSquare);
361
362
}

363
364
365
void ThumbnailView::setModel(QAbstractItemModel* newModel)
{
    if (model()) {
366
        disconnect(model(), nullptr, this, nullptr);
367
368
    }
    QListView::setModel(newModel);
369
370
371
372
373
374
375

    connect(model(), &QAbstractItemModel::rowsRemoved, this, [=](const QModelIndex &index, int first, int last) {
        // Avoid the delegate doing a ton of work if we're not visible
        if (isVisible()) {
            emit rowsRemovedSignal(index, first, last);
        }
    });
376
377
}

378
void ThumbnailView::setThumbnailProvider(ThumbnailProvider* thumbnailProvider)
Benjamin Löwe's avatar
Benjamin Löwe committed
379
{
380
381
    GV_RETURN_IF_FAIL(d->mThumbnailProvider != thumbnailProvider);
    if (thumbnailProvider) {
Laurent Montel's avatar
Laurent Montel committed
382
383
384
385
        connect(thumbnailProvider, &ThumbnailProvider::thumbnailLoaded,
                         this, &ThumbnailView::setThumbnail);
        connect(thumbnailProvider, &ThumbnailProvider::thumbnailLoadingFailed,
                         this, &ThumbnailView::setBrokenThumbnail);
Benjamin Löwe's avatar
Benjamin Löwe committed
386
    } else {
387
        disconnect(d->mThumbnailProvider, nullptr , this, nullptr);
Benjamin Löwe's avatar
Benjamin Löwe committed
388
    }
389
    d->mThumbnailProvider = thumbnailProvider;
Benjamin Löwe's avatar
Benjamin Löwe committed
390
391
}

392
void ThumbnailView::updateThumbnailSize()
393
{
394
    QSize value = d->mThumbnailSize;
395
    // mWaitingThumbnail
396
    const auto dpr = devicePixelRatioF();
397
    int waitingThumbnailSize;
398
399
    if (value.width() > 64 * dpr) {
        waitingThumbnailSize = qRound(48 * dpr);
400
    } else {
401
        waitingThumbnailSize = qRound(32 * dpr);
402
    }
403
    QPixmap icon = QIcon::fromTheme(QStringLiteral("chronometer")).pixmap(waitingThumbnailSize);
404
    QPixmap pix(value);
405
406
407
    pix.fill(Qt::transparent);
    QPainter painter(&pix);
    painter.setOpacity(0.5);
408
    painter.drawPixmap((value.width() - icon.width()) / 2, (value.height() - icon.height()) / 2, icon);
409
410
    painter.end();
    d->mWaitingThumbnail = pix;
411
    d->mWaitingThumbnail.setDevicePixelRatio(dpr);
412
413
414
415
416
417
418
419
420
421
422
423
424

    // Stop smoothing
    d->mSmoothThumbnailTimer.stop();
    d->mSmoothThumbnailQueue.clear();

    // Clear adjustedPixes
    ThumbnailForUrl::iterator
    it = d->mThumbnailForUrl.begin(),
    end = d->mThumbnailForUrl.end();
    for (; it != end; ++it) {
        it.value().mAdjustedPix = QPixmap();
    }

425
426
    emit thumbnailSizeChanged(value / dpr);
    emit thumbnailWidthChanged(qRound(value.width() / dpr));
427
428
429
    if (d->mScaleMode != ScaleToFit) {
        scheduleDelayedItemsLayout();
    }
430
    d->scheduleThumbnailGeneration();
431
432
}

433
434
void ThumbnailView::setThumbnailWidth(int width)
{
435
436
437
438
    const auto dpr = devicePixelRatioF();
    const qreal newWidthF = width * dpr;
    const int newWidth = qRound(newWidthF);
    if(d->mThumbnailSize.width() == newWidth) {
439
440
        return;
    }
441
442
    int height = qRound(newWidthF / d->mThumbnailAspectRatio);
    d->mThumbnailSize = QSize(newWidth, height);
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
    updateThumbnailSize();
}

void ThumbnailView::setThumbnailAspectRatio(qreal ratio)
{
    if(d->mThumbnailAspectRatio == ratio) {
        return;
    }
    d->mThumbnailAspectRatio = ratio;
    int width = d->mThumbnailSize.width();
    int height = round((qreal)width / d->mThumbnailAspectRatio);
    d->mThumbnailSize = QSize(width, height);
    updateThumbnailSize();
}

qreal ThumbnailView::thumbnailAspectRatio() const
{
    return d->mThumbnailAspectRatio;
}

QSize ThumbnailView::thumbnailSize() const
464
{
465
    return d->mThumbnailSize / devicePixelRatioF();
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
}

void ThumbnailView::setThumbnailViewHelper(AbstractThumbnailViewHelper* helper)
{
    d->mThumbnailViewHelper = helper;
}

AbstractThumbnailViewHelper* ThumbnailView::thumbnailViewHelper() const
{
    return d->mThumbnailViewHelper;
}

void ThumbnailView::setDocumentInfoProvider(AbstractDocumentInfoProvider* provider)
{
    d->mDocumentInfoProvider = provider;
    if (provider) {
482
483
484
485
        connect(provider, &AbstractDocumentInfoProvider::busyStateChanged,
                this, &ThumbnailView::updateThumbnailBusyState);
        connect(provider, &AbstractDocumentInfoProvider::documentChanged,
                this, &ThumbnailView::updateThumbnail);
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
    }
}

AbstractDocumentInfoProvider* ThumbnailView::documentInfoProvider() const
{
    return d->mDocumentInfoProvider;
}

void ThumbnailView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end)
{
    QListView::rowsAboutToBeRemoved(parent, start, end);

    // Remove references to removed items
    KFileItemList itemList;
    for (int pos = start; pos <= end; ++pos) {
        QModelIndex index = model()->index(pos, 0, parent);
        KFileItem item = fileItemForIndex(index);
        if (item.isNull()) {
Laurent Montel's avatar
Laurent Montel committed
504
            //qCDebug(GWENVIEW_LIB_LOG) << "Skipping invalid item!" << index.data().toString();
505
506
507
508
509
510
511
512
513
514
            continue;
        }

        QUrl url = item.url();
        d->mThumbnailForUrl.remove(url);
        d->mSmoothThumbnailQueue.removeAll(url);

        itemList.append(item);
    }

515
516
    if (d->mThumbnailProvider) {
        d->mThumbnailProvider->removeItems(itemList);
517
518
519
520
    }

    // Removing rows might make new images visible, make sure their thumbnail
    // is generated
521
522
523
    if (!d->mScheduledThumbnailGenerationTimer.isActive()) {
        d->mScheduledThumbnailGenerationTimer.start();
    }
524
525
526
527
528
}

void ThumbnailView::rowsInserted(const QModelIndex& parent, int start, int end)
{
    QListView::rowsInserted(parent, start, end);
529
530
531
532

    if (!d->mScheduledThumbnailGenerationTimer.isActive()) {
        d->mScheduledThumbnailGenerationTimer.start();
    }
533
534
535
536

    if (isVisible()) {
        emit rowsInsertedSignal(parent, start, end);
    }
537
538
}

Lukáš Tinkl's avatar
Lukáš Tinkl committed
539
void ThumbnailView::dataChanged(const QModelIndex& topLeft, const QModelIndex& bottomRight, const QVector<int> &roles)
540
{
Lukáš Tinkl's avatar
Lukáš Tinkl committed
541
    QListView::dataChanged(topLeft, bottomRight, roles);
542
543
544
545
546
    bool thumbnailsNeedRefresh = false;
    for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
        QModelIndex index = model()->index(row, 0);
        KFileItem item = fileItemForIndex(index);
        if (item.isNull()) {
Laurent Montel's avatar
Laurent Montel committed
547
            qCWarning(GWENVIEW_LIB_LOG) << "Invalid item for index" << index << ". This should not happen!";
548
            GV_FATAL_FAILS;
549
550
551
552
553
554
555
556
557
558
            continue;
        }

        ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(item.url());
        if (it != d->mThumbnailForUrl.end()) {
            // All thumbnail views are connected to the model, so
            // ThumbnailView::dataChanged() is called for all of them. As a
            // result this method will also be called for views which are not
            // currently visible, and do not yet have a thumbnail for the
            // modified url.
559
            QDateTime mtime = item.time(KFileItem::ModificationTime);
Benjamin Löwe's avatar
Benjamin Löwe committed
560
            if (it->mModificationTime != mtime || it->mFileSize != item.size()) {
561
562
563
564
565
566
567
568
569
                // dataChanged() is called when the file changes but also when
                // the model fetched additional data such as semantic info. To
                // avoid needless refreshes, we only trigger a refresh if the
                // modification time changes.
                thumbnailsNeedRefresh = true;
                it->prepareForRefresh(mtime);
            }
        }
    }
570
    if (thumbnailsNeedRefresh && !d->mScheduledThumbnailGenerationTimer.isActive()) {
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
        d->mScheduledThumbnailGenerationTimer.start();
    }
}

void ThumbnailView::showContextMenu()
{
    d->mThumbnailViewHelper->showContextMenu(this);
}

void ThumbnailView::emitIndexActivatedIfNoModifiers(const QModelIndex& index)
{
    if (QApplication::keyboardModifiers() == Qt::NoModifier) {
        emit indexActivated(index);
    }
}

587
void ThumbnailView::setThumbnail(const KFileItem& item, const QPixmap& pixmap, const QSize& size, qulonglong fileSize)
588
589
590
591
592
593
594
595
{
    ThumbnailForUrl::iterator it = d->mThumbnailForUrl.find(item.url());
    if (it == d->mThumbnailForUrl.end()) {
        return;
    }
    Thumbnail& thumbnail = it.value();
    thumbnail.mGroupPix = pixmap;
    thumbnail.mAdjustedPix = QPixmap();
596
    int largeGroupSize = ThumbnailGroup::pixelSize(ThumbnailGroup::Large2x);
597
598
599
    thumbnail.mFullSize = size.isValid() ? size : QSize(largeGroupSize, largeGroupSize);
    thumbnail.mRealFullSize = size;
    thumbnail.mWaitingForThumbnail = false;
Benjamin Löwe's avatar
Benjamin Löwe committed
600
    thumbnail.mFileSize = fileSize;
601
602

    update(thumbnail.mIndex);
603
604
605
    if (d->mScaleMode != ScaleToFit) {
        scheduleDelayedItemsLayout();
    }
606
607
608
609
610
611
612
613
614
615
616
617
618
619
}

void ThumbnailView::setBrokenThumbnail(const KFileItem& item)
{
    ThumbnailForUrl::iterator it = d->mThumbnailForUrl.find(item.url());
    if (it == d->mThumbnailForUrl.end()) {
        return;
    }
    Thumbnail& thumbnail = it.value();
    MimeTypeUtils::Kind kind = MimeTypeUtils::fileItemKind(item);
    if (kind == MimeTypeUtils::KIND_VIDEO) {
        // Special case for videos because our kde install may come without
        // support for video thumbnails so we show the mimetype icon instead of
        // a broken image icon
620
        const QPixmap pix = KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, d->mThumbnailSize.height());
621
622
        thumbnail.initAsIcon(pix);
    } else if (kind == MimeTypeUtils::KIND_DIR) {
623
        // Special case for folders because ThumbnailProvider does not return a
624
625
626
627
        // thumbnail if there is no images
        thumbnail.mWaitingForThumbnail = false;
        return;
    } else {
628
        thumbnail.initAsIcon(QIcon::fromTheme(QStringLiteral("image-missing")).pixmap(48));
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
        thumbnail.mFullSize = thumbnail.mGroupPix.size();
    }
    update(thumbnail.mIndex);
}

QPixmap ThumbnailView::thumbnailForIndex(const QModelIndex& index, QSize* fullSize)
{
    KFileItem item = fileItemForIndex(index);
    if (item.isNull()) {
        LOG("Invalid item");
        if (fullSize) {
            *fullSize = QSize();
        }
        return QPixmap();
    }
David Edmundson's avatar
David Edmundson committed
644
    QUrl url = item.url();
645
646
647
648
649
650
651
652
653
654
655
656

    // Find or create Thumbnail instance
    ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(url);
    if (it == d->mThumbnailForUrl.end()) {
        Thumbnail thumbnail = Thumbnail(QPersistentModelIndex(index), item.time(KFileItem::ModificationTime));
        it = d->mThumbnailForUrl.insert(url, thumbnail);
    }
    Thumbnail& thumbnail = it.value();

    // If dir or archive, generate a thumbnail from fileitem pixmap
    MimeTypeUtils::Kind kind = MimeTypeUtils::fileItemKind(item);
    if (kind == MimeTypeUtils::KIND_ARCHIVE || kind == MimeTypeUtils::KIND_DIR) {
657
658
        int groupSize = ThumbnailGroup::pixelSize(ThumbnailGroup::fromPixelSize(d->mThumbnailSize.height()));
        if (thumbnail.mGroupPix.isNull() || thumbnail.mGroupPix.height() < groupSize) {
659
            const QPixmap pix = KIconLoader::global()->loadIcon(item.iconName(), KIconLoader::Desktop, d->mThumbnailSize.height());
David Edmundson's avatar
David Edmundson committed
660

661
662
663
664
            thumbnail.initAsIcon(pix);
            if (kind == MimeTypeUtils::KIND_ARCHIVE) {
                // No thumbnails for archives
                thumbnail.mWaitingForThumbnail = false;
665
666
667
668
669
            } else if (!d->mCreateThumbnailsForRemoteUrls && !UrlUtils::urlIsFastLocalFile(url)) {
                // If we don't want thumbnails for remote urls, use
                // "folder-remote" icon for remote folders, so that they do
                // not look like regular folders
                thumbnail.mWaitingForThumbnail = false;
670
                thumbnail.initAsIcon(QIcon::fromTheme(QStringLiteral("folder-remote")).pixmap(groupSize));
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
            } else {
                // set mWaitingForThumbnail to true (necessary in the case
                // 'thumbnail' already existed before, but with a too small
                // mGroupPix)
                thumbnail.mWaitingForThumbnail = true;
            }
        }
    }

    if (thumbnail.mGroupPix.isNull()) {
        if (fullSize) {
            *fullSize = QSize();
        }
        return d->mWaitingThumbnail;
    }

    // Adjust thumbnail
    if (thumbnail.mAdjustedPix.isNull()) {
        d->roughAdjustThumbnail(&thumbnail);
    }
691
    if (GwenviewConfig::lowResourceUsageMode() && thumbnail.mRough && !d->mSmoothThumbnailQueue.contains(url)) {
692
693
694
695
696
697
698
699
        d->mSmoothThumbnailQueue.enqueue(url);
        if (!d->mSmoothThumbnailTimer.isActive()) {
            d->mSmoothThumbnailTimer.start(SMOOTH_DELAY);
        }
    }
    if (fullSize) {
        *fullSize = thumbnail.mRealFullSize;
    }
700
    thumbnail.mAdjustedPix.setDevicePixelRatio(devicePixelRatioF());
701
702
703
704
705
706
707
708
    return thumbnail.mAdjustedPix;
}

bool ThumbnailView::isModified(const QModelIndex& index) const
{
    if (!d->mDocumentInfoProvider) {
        return false;
    }
David Edmundson's avatar
David Edmundson committed
709
    QUrl url = urlForIndex(index);
710
711
712
713
714
715
716
717
    return d->mDocumentInfoProvider->isModified(url);
}

bool ThumbnailView::isBusy(const QModelIndex& index) const
{
    if (!d->mDocumentInfoProvider) {
        return false;
    }
David Edmundson's avatar
David Edmundson committed
718
    QUrl url = urlForIndex(index);
719
720
721
    return d->mDocumentInfoProvider->isBusy(url);
}

722
void ThumbnailView::startDrag(Qt::DropActions)
723
{
724
    const QModelIndexList indexes = selectionModel()->selectedIndexes();
725
726
727
    if (indexes.isEmpty()) {
        return;
    }
728
729

    KFileItemList selectedFiles;
730
    for (const auto &index : indexes) {
731
732
733
        selectedFiles << fileItemForIndex(index);
    }

734
    QDrag* drag = new QDrag(this);
735
    drag->setMimeData(MimeTypeUtils::selectionMimeData(selectedFiles, MimeTypeUtils::DropTarget));
Aurélien Gâteau's avatar
Aurélien Gâteau committed
736
    d->initDragPixmap(drag, indexes);
737
    drag->exec(Qt::MoveAction | Qt::CopyAction | Qt::LinkAction, Qt::CopyAction);
738
739
}

Steffen Hartleib's avatar
Steffen Hartleib committed
740
741
742
void ThumbnailView::setZoomParameter()
{
    const qreal sensitivityModifier = 0.25;
743
    d->mTouch->setZoomParameter(sensitivityModifier, thumbnailSize().width());
Steffen Hartleib's avatar
Steffen Hartleib committed
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
}

void ThumbnailView::zoomGesture(qreal newZoom, const QPoint&)
{
    if (newZoom >= 0.0) {
        int width = qBound (int(MinThumbnailSize), static_cast<int>(newZoom), int(MaxThumbnailSize));
        setThumbnailWidth(width);
    }
}

void ThumbnailView::tapGesture(const QPoint& pos)
{
    const QRect rect = QRect(pos, QSize(1, 1));
    setSelection(rect, QItemSelectionModel::ClearAndSelect);
    emit activated(indexAt(pos));
}

void ThumbnailView::startDragFromTouch(const QPoint& pos)
{
    QModelIndex index = indexAt(pos);
    if (index.isValid()) {
        setCurrentIndex(index);
        d->mScroller->stop();
        startDrag(Qt::CopyAction);
    }
}

771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
void ThumbnailView::dragEnterEvent(QDragEnterEvent* event)
{
    QAbstractItemView::dragEnterEvent(event);
    if (event->mimeData()->hasUrls()) {
        event->acceptProposedAction();
    }
}

void ThumbnailView::dragMoveEvent(QDragMoveEvent* event)
{
    // Necessary, otherwise we don't reach dropEvent()
    QAbstractItemView::dragMoveEvent(event);
    event->acceptProposedAction();
}

void ThumbnailView::dropEvent(QDropEvent* event)
{
788
    const QList<QUrl> urlList = KUrlMimeData::urlsFromMimeData(event->mimeData());
789
790
791
792
793
794
795
796
    if (urlList.isEmpty()) {
        return;
    }

    QModelIndex destIndex = indexAt(event->pos());
    if (destIndex.isValid()) {
        KFileItem item = fileItemForIndex(destIndex);
        if (item.isDir()) {
David Edmundson's avatar
David Edmundson committed
797
            QUrl destUrl = item.url();
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
            d->mThumbnailViewHelper->showMenuForUrlDroppedOnDir(this, urlList, destUrl);
            return;
        }
    }

    d->mThumbnailViewHelper->showMenuForUrlDroppedOnViewport(this, urlList);

    event->acceptProposedAction();
}

void ThumbnailView::keyPressEvent(QKeyEvent* event)
{
    QListView::keyPressEvent(event);
    if (event->key() == Qt::Key_Return) {
        const QModelIndex index = selectionModel()->currentIndex();
        if (index.isValid() && selectionModel()->selectedIndexes().count() == 1) {
            emit indexActivated(index);
        }
    }
}

void ThumbnailView::resizeEvent(QResizeEvent* event)
{
    QListView::resizeEvent(event);
822
    d->scheduleThumbnailGeneration();
823
824
825
826
827
}

void ThumbnailView::showEvent(QShowEvent* event)
{
    QListView::showEvent(event);
828
    d->scheduleThumbnailGeneration();
Laurent Montel's avatar
Laurent Montel committed
829
    QTimer::singleShot(0, this, &ThumbnailView::scrollToSelectedIndex);
830
831
832
833
834
835
836
837
838
839
840
}

void ThumbnailView::wheelEvent(QWheelEvent* event)
{
    // If we don't adjust the single step, the wheel scroll exactly one item up
    // and down, giving the impression that the items do not move but only
    // their label changes.
    // For some reason it is necessary to set the step here: setting it in
    // setThumbnailSize() does not work
    //verticalScrollBar()->setSingleStep(d->mThumbnailSize / 5);
    if (event->modifiers() == Qt::ControlModifier) {
Laurent Montel's avatar
Laurent Montel committed
841
        int width = thumbnailSize().width() + (event->angleDelta().y() > 0 ? 1 : -1) * WHEEL_ZOOM_MULTIPLIER;
842
843
        width = qMax(int(MinThumbnailSize), qMin(width, int(MaxThumbnailSize)));
        setThumbnailWidth(width);
844
845
846
847
848
    } else {
        QListView::wheelEvent(event);
    }
}

849
850
851
852
853
854
855
856
857
858
859
void ThumbnailView::mousePressEvent(QMouseEvent* event)
{
    switch (event->button()) {
    case Qt::ForwardButton:
    case Qt::BackButton:
        return;
    default:
        QListView::mousePressEvent(event);
    }
}

860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
void ThumbnailView::scrollToSelectedIndex()
{
    QModelIndexList list = selectedIndexes();
    if (list.count() >= 1) {
        scrollTo(list.first(), PositionAtCenter);
    }
}

void ThumbnailView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected)
{
    QListView::selectionChanged(selected, deselected);
    emit selectionChangedSignal(selected, deselected);
}

void ThumbnailView::scrollContentsBy(int dx, int dy)
{
    QListView::scrollContentsBy(dx, dy);
877
    d->scheduleThumbnailGeneration();
878
879
}

880
void ThumbnailView::generateThumbnailsForItems()
881
882
883
884
{
    if (!isVisible() || !model()) {
        return;
    }
885
886
887
888
889
    const QRect visibleRect = viewport()->rect();
    const int visibleSurface = visibleRect.width() * visibleRect.height();
    const QPoint origin = visibleRect.center();

    // distance => item
890
    QMultiMap<int, KFileItem> itemMap;
891
892
893
894
895
896

    for (int row = 0; row < model()->rowCount(); ++row) {
        QModelIndex index = model()->index(row, 0);
        KFileItem item = fileItemForIndex(index);
        QUrl url = item.url();

897
898
899
900
901
        // Filter out remote items if necessary
        if (!d->mCreateThumbnailsForRemoteUrls && !url.isLocalFile()) {
            continue;
        }

902
903
904
905
906
907
908
909
910
911
912
913
914
915
        // Filter out archives
        MimeTypeUtils::Kind kind = MimeTypeUtils::fileItemKind(item);
        if (kind == MimeTypeUtils::KIND_ARCHIVE) {
            continue;
        }

        // Immediately update modified items
        if (d->mDocumentInfoProvider && d->mDocumentInfoProvider->isModified(url)) {
            d->updateThumbnailForModifiedDocument(index);
            continue;
        }

        // Filter out items which already have a thumbnail
        ThumbnailForUrl::ConstIterator it = d->mThumbnailForUrl.constFind(url);
916
        if (it != d->mThumbnailForUrl.constEnd() && it.value().isGroupPixAdaptedForSize(d->mThumbnailSize.height())) {
917
918
919
            continue;
        }

920
921
        // Compute distance
        int distance;
922
        const QRect itemRect = visualRect(index);
923
        if (itemRect.isValid()) {
924
925
926
            // Item is visible, order thumbnails from left to right, top to bottom
            // Distance is computed so that it is between 0 and visibleSurface
            distance = itemRect.top() * visibleRect.width() + itemRect.left();
927
928
929
930
931
            // Make sure directory thumbnails are generated after image thumbnails:
            // Distance is between visibleSurface and 2 * visibleSurface
            if (kind == MimeTypeUtils::KIND_DIR) {
                distance = distance + visibleSurface;
            }
932
933
        } else {
            // Item is not visible, order thumbnails according to distance
934
            // Start at 2 * visibleSurface to ensure invisible thumbnails are
935
            // generated *after* visible thumbnails
936
            distance = 2 * visibleSurface + (itemRect.center() - origin).manhattanLength();
937
938
939
940
        }

        // Add the item to our map
        itemMap.insert(distance, item);
941
942
943
944
945
946
947
948
949

        // Insert the thumbnail in mThumbnailForUrl, so that
        // setThumbnail() can find the item to update
        if (it == d->mThumbnailForUrl.constEnd()) {
            Thumbnail thumbnail = Thumbnail(QPersistentModelIndex(index), item.time(KFileItem::ModificationTime));
            d->mThumbnailForUrl.insert(url, thumbnail);
        }
    }

950
    if (!itemMap.isEmpty()) {
951
        d->appendItemsToThumbnailProvider(itemMap.values());
952
953
954
    }
}

955
void ThumbnailView::updateThumbnail(const QUrl& url)
956
{
957
958
959
960
961
    const ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(url);
    if (it == d->mThumbnailForUrl.end()) {
        return;
    }

962
    if (d->mDocumentInfoProvider) {
963
        d->updateThumbnailForModifiedDocument(it->mIndex);
964
    } else {
965
966
        const KFileItem item = fileItemForIndex(it->mIndex);
        d->appendItemsToThumbnailProvider(KFileItemList({ item }));
967
968
969
    }
}

970
void ThumbnailView::updateThumbnailBusyState(const QUrl& url, bool busy)
971
{
972
973
974
975
976
977
    const ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(url);
    if (it == d->mThumbnailForUrl.end()) {
        return;
    }

    QPersistentModelIndex index(it->mIndex);
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
    if (busy && !d->mBusyIndexSet.contains(index)) {
        d->mBusyIndexSet << index;
        update(index);
        if (d->mBusyAnimationTimeLine->state() != QTimeLine::Running) {
            d->mBusyAnimationTimeLine->start();
        }
    } else if (!busy && d->mBusyIndexSet.remove(index)) {
        update(index);
        if (d->mBusyIndexSet.isEmpty()) {
            d->mBusyAnimationTimeLine->stop();
        }
    }
}

void ThumbnailView::updateBusyIndexes()
{
994
    for (const QPersistentModelIndex & index : qAsConst(d->mBusyIndexSet)) {
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
        update(index);
    }
}

QPixmap ThumbnailView::busySequenceCurrentPixmap() const
{
    return d->mBusySequence.frameAt(d->mBusyAnimationTimeLine->currentFrame());
}

void ThumbnailView::smoothNextThumbnail()
{
    if (d->mSmoothThumbnailQueue.isEmpty()) {
        return;
    }

1010
1011
    if (d->mThumbnailProvider && d->mThumbnailProvider->isRunning()) {
        // give mThumbnailProvider priority over smoothing
1012
1013
1014
1015
        d->mSmoothThumbnailTimer.start(SMOOTH_DELAY);
        return;
    }

David Edmundson's avatar
David Edmundson committed
1016
    QUrl url = d->mSmoothThumbnailQueue.dequeue();
1017
    ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(url);
1018
    GV_RETURN_IF_FAIL2(it != d->mThumbnailForUrl.end(), url << "not in mThumbnailForUrl.");
1019
1020

    Thumbnail& thumbnail = it.value();
1021
    thumbnail.mAdjustedPix = d->scale(thumbnail.mGroupPix, Qt::SmoothTransformation);
1022
1023
    thumbnail.mRough = false;

1024
1025
    GV_RETURN_IF_FAIL2(thumbnail.mIndex.isValid(), "index for" << url << "is invalid.");
    update(thumbnail.mIndex);
1026
1027
1028
1029
1030
1031
1032
1033

    if (!d->mSmoothThumbnailQueue.isEmpty()) {
        d->mSmoothThumbnailTimer.start(0);
    }
}

void ThumbnailView::reloadThumbnail(const QModelIndex& index)
{
David Edmundson's avatar
David Edmundson committed
1034
    QUrl url = urlForIndex(index);
1035
    if (!url.isValid()) {
Laurent Montel's avatar
Laurent Montel committed
1036
        qCWarning(GWENVIEW_LIB_LOG) << "Invalid url for index" << index;
1037
1038
        return;
    }
1039
    ThumbnailProvider::deleteImageThumbnail(url);
1040
1041
1042
1043
1044
    ThumbnailForUrl::Iterator it = d->mThumbnailForUrl.find(url);
    if (it == d->mThumbnailForUrl.end()) {
        return;
    }
    d->mThumbnailForUrl.erase(it);
1045
    generateThumbnailsForItems();
1046
1047
}

1048
1049
1050
1051
1052
void ThumbnailView::setCreateThumbnailsForRemoteUrls(bool createRemoteThumbs)
{
    d->mCreateThumbnailsForRemoteUrls = createRemoteThumbs;
}

Aurélien Gâteau's avatar
Aurélien Gâteau committed
1053
} // namespace