1 /***************************************************************************
2 * Copyright (C) 2008 by Peter Penz <peter.penz@gmx.at> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfilepreviewgenerator.h"
22 #include <kiconeffect.h>
23 #include <kio/previewjob.h>
24 #include <kdirlister.h>
25 #include <kdirmodel.h>
26 #include <kdirsortfilterproxymodel.h>
27 #include <kmimetyperesolver.h>
28 #include <konqmimedata.h>
30 #include <QApplication>
31 #include <QAbstractItemView>
40 * If the passed item view is an instance of QListView, expensive
41 * layout operations are blocked in the constructor and are unblocked
42 * again in the destructor.
44 * This helper class is a workaround for the following huge performance
45 * problem when having directories with several 1000 items:
46 * - each change of an icon emits a dataChanged() signal from the model
47 * - QListView iterates through all items on each dataChanged() signal
48 * and invokes QItemDelegate::sizeHint()
49 * - the sizeHint() implementation of KFileItemDelegate is quite complex,
50 * invoking it 1000 times for each icon change might block the UI
52 * QListView does not invoke QItemDelegate::sizeHint() when the
53 * uniformItemSize property has been set to true, so this property is
54 * set before exchanging a block of icons. It is important to reset
55 * it again before the event loop is entered, otherwise QListView
56 * would not get the correct size hints after dispatching the layoutChanged()
61 LayoutBlocker(QAbstractItemView
* view
) :
62 m_uniformSizes(false),
63 m_view(qobject_cast
<QListView
*>(view
))
66 m_uniformSizes
= m_view
->uniformItemSizes();
67 m_view
->setUniformItemSizes(true);
74 m_view
->setUniformItemSizes(m_uniformSizes
);
83 class KFilePreviewGenerator::Private
86 Private(KFilePreviewGenerator
* parent
,
87 QAbstractItemView
* view
,
88 KDirSortFilterProxyModel
* model
);
92 * Generates previews for the items \a items asynchronously.
94 void generatePreviews(const KFileItemList
& items
);
97 * Adds the preview \a pixmap for the item \a item to the preview
98 * queue and starts a timer which will dispatch the preview queue
101 void addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
);
104 * Is invoked when the preview job has been finished and
105 * removes the job from the m_previewJobs list.
107 void slotPreviewJobFinished(KJob
* job
);
109 /** Synchronizes the item icon with the clipboard of cut items. */
110 void updateCutItems();
113 * Dispatches the preview queue block by block within
116 void dispatchPreviewQueue();
119 * Pauses all preview jobs and invokes KFilePreviewGenerator::resumePreviews()
120 * after a short delay. Is invoked as soon as the user has moved
123 void pausePreviews();
126 * Resumes the previews that have been paused after moving the
127 * scrollbar. The previews for the current visible area are
130 void resumePreviews();
133 * Returns true, if the item \a item has been cut into
136 bool isCutItem(const KFileItem
& item
) const;
138 /** Applies an item effect to all cut items. */
139 void applyCutItemEffect();
142 * Applies a frame around the icon. False is returned if
143 * no frame has been added because the icon is too small.
145 bool applyImageFrame(QPixmap
& icon
);
148 * Resizes the icon to \a maxSize if the icon size does not
149 * fit into the maximum size. The aspect ratio of the icon
152 void limitToSize(QPixmap
& icon
, const QSize
& maxSize
);
155 * Starts a new preview job for the items \a to m_previewJobs
156 * and triggers the preview timer.
158 void startPreviewJob(const KFileItemList
& items
);
160 /** Kills all ongoing preview jobs. */
161 void killPreviewJobs();
164 * Orders the items \a items in a way that the visible items
165 * are moved to the front of the list. When passing this
166 * list to a preview job, the visible items will get generated
169 void orderItems(KFileItemList
& items
);
171 /** Remembers the pixmap for an item specified by an URL. */
181 * True, if m_pendingItems and m_dispatchedItems should be
182 * cleared when the preview jobs have been finished.
184 bool m_clearItemQueues
;
187 * True if a selection has been done which should cut items.
189 bool m_hasCutSelection
;
191 int m_pendingVisiblePreviews
;
193 QAbstractItemView
* m_view
;
194 QTimer
* m_previewTimer
;
195 QTimer
* m_scrollAreaTimer
;
196 QList
<KJob
*> m_previewJobs
;
197 KDirModel
* m_dirModel
;
198 KDirSortFilterProxyModel
* m_proxyModel
;
200 KMimeTypeResolver
* m_mimeTypeResolver
;
202 QList
<ItemInfo
> m_cutItemsCache
;
203 QList
<ItemInfo
> m_previews
;
206 * Contains all items where a preview must be generated, but
207 * where the preview job has not dispatched the items yet.
209 KFileItemList m_pendingItems
;
212 * Contains all items, where a preview has already been
213 * generated by the preview jobs.
215 KFileItemList m_dispatchedItems
;
218 KFilePreviewGenerator
* const q
;
222 KFilePreviewGenerator::Private::Private(KFilePreviewGenerator
* parent
,
223 QAbstractItemView
* view
,
224 KDirSortFilterProxyModel
* model
) :
226 m_clearItemQueues(true),
227 m_hasCutSelection(false),
228 m_pendingVisiblePreviews(0),
231 m_scrollAreaTimer(0),
235 m_mimeTypeResolver(0),
242 if (!m_view
->iconSize().isValid()) {
243 m_showPreview
= false;
246 m_dirModel
= static_cast<KDirModel
*>(m_proxyModel
->sourceModel());
247 connect(m_dirModel
->dirLister(), SIGNAL(newItems(const KFileItemList
&)),
248 q
, SLOT(generatePreviews(const KFileItemList
&)));
250 QClipboard
* clipboard
= QApplication::clipboard();
251 connect(clipboard
, SIGNAL(dataChanged()),
252 q
, SLOT(updateCutItems()));
254 m_previewTimer
= new QTimer(q
);
255 m_previewTimer
->setSingleShot(true);
256 connect(m_previewTimer
, SIGNAL(timeout()), q
, SLOT(dispatchPreviewQueue()));
258 // Whenever the scrollbar values have been changed, the pending previews should
259 // be reordered in a way that the previews for the visible items are generated
260 // first. The reordering is done with a small delay, so that during moving the
261 // scrollbars the CPU load is kept low.
262 m_scrollAreaTimer
= new QTimer(q
);
263 m_scrollAreaTimer
->setSingleShot(true);
264 m_scrollAreaTimer
->setInterval(200);
265 connect(m_scrollAreaTimer
, SIGNAL(timeout()),
266 q
, SLOT(resumePreviews()));
267 connect(m_view
->horizontalScrollBar(), SIGNAL(valueChanged(int)),
268 q
, SLOT(pausePreviews()));
269 connect(m_view
->verticalScrollBar(), SIGNAL(valueChanged(int)),
270 q
, SLOT(pausePreviews()));
273 KFilePreviewGenerator::Private::~Private()
276 m_pendingItems
.clear();
277 m_dispatchedItems
.clear();
278 if (m_mimeTypeResolver
!= 0) {
279 m_mimeTypeResolver
->deleteLater();
280 m_mimeTypeResolver
= 0;
284 void KFilePreviewGenerator::Private::generatePreviews(const KFileItemList
& items
)
286 applyCutItemEffect();
288 if (!m_showPreview
) {
292 KFileItemList orderedItems
= items
;
293 orderItems(orderedItems
);
295 foreach (const KFileItem
& item
, orderedItems
) {
296 m_pendingItems
.append(item
);
299 startPreviewJob(orderedItems
);
302 void KFilePreviewGenerator::Private::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
304 if (!m_showPreview
) {
305 // the preview has been canceled in the meantime
308 const KUrl url
= item
.url();
310 // check whether the item is part of the directory lister (it is possible
311 // that a preview from an old directory lister is received)
312 KDirLister
* dirLister
= m_dirModel
->dirLister();
313 bool isOldPreview
= true;
314 const KUrl::List dirs
= dirLister
->directories();
315 const QString itemDir
= url
.directory();
316 foreach (const KUrl
& url
, dirs
) {
317 if (url
.path() == itemDir
) {
318 isOldPreview
= false;
326 QPixmap icon
= pixmap
;
328 const QString mimeType
= item
.mimetype();
329 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
330 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
331 limitToSize(icon
, m_view
->iconSize());
334 if (m_hasCutSelection
&& isCutItem(item
)) {
335 // Remember the current icon in the cache for cut items before
336 // the disabled effect is applied. This makes it possible restoring
337 // the uncut version again when cutting other items.
338 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
339 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
340 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
341 if ((*it
).url
== item
.url()) {
347 // apply the disabled effect to the icon for marking it as "cut item"
348 // and apply the icon to the item
349 KIconEffect iconEffect
;
350 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
353 // remember the preview and URL, so that it can be applied to the model
354 // in KFilePreviewGenerator::dispatchPreviewQueue()
357 preview
.pixmap
= icon
;
358 m_previews
.append(preview
);
360 m_dispatchedItems
.append(item
);
363 void KFilePreviewGenerator::Private::slotPreviewJobFinished(KJob
* job
)
365 const int index
= m_previewJobs
.indexOf(job
);
366 m_previewJobs
.removeAt(index
);
368 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
369 m_pendingItems
.clear();
370 m_dispatchedItems
.clear();
371 m_pendingVisiblePreviews
= 0;
372 QMetaObject::invokeMethod(q
, "dispatchPreviewQueue", Qt::QueuedConnection
);
376 void KFilePreviewGenerator::Private::updateCutItems()
378 // restore the icons of all previously selected items to the
380 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
381 const QModelIndex index
= m_dirModel
->indexForUrl(cutItem
.url
);
382 if (index
.isValid()) {
383 m_dirModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
386 m_cutItemsCache
.clear();
388 // ... and apply an item effect to all currently cut items
389 applyCutItemEffect();
392 void KFilePreviewGenerator::Private::dispatchPreviewQueue()
394 const int previewsCount
= m_previews
.count();
395 if (previewsCount
> 0) {
396 // Applying the previews to the model must be done step by step
397 // in larger blocks: Applying a preview immediately when getting the signal
398 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
399 // of the view would be triggered for each single preview.
400 LayoutBlocker
blocker(m_view
);
401 for (int i
= 0; i
< previewsCount
; ++i
) {
402 const ItemInfo
& preview
= m_previews
.first();
404 const QModelIndex idx
= m_dirModel
->indexForUrl(preview
.url
);
405 if (idx
.isValid() && (idx
.column() == 0)) {
406 m_dirModel
->setData(idx
, QIcon(preview
.pixmap
), Qt::DecorationRole
);
409 m_previews
.pop_front();
410 if (m_pendingVisiblePreviews
> 0) {
411 --m_pendingVisiblePreviews
;
416 if (m_pendingVisiblePreviews
> 0) {
417 // As long as there are pending previews for visible items, poll
418 // the preview queue each 200 ms. If there are no pending previews,
419 // the queue is dispatched in slotPreviewJobFinished().
420 m_previewTimer
->start(200);
424 void KFilePreviewGenerator::Private::pausePreviews()
426 foreach (KJob
* job
, m_previewJobs
) {
430 m_scrollAreaTimer
->start();
433 void KFilePreviewGenerator::Private::resumePreviews()
435 // Before creating new preview jobs the m_pendingItems queue must be
436 // cleaned up by removing the already dispatched items. Implementation
437 // note: The order of the m_dispatchedItems queue and the m_pendingItems
438 // queue is usually equal. So even when having a lot of elements the
439 // nested loop is no performance bottle neck, as the inner loop is only
440 // entered once in most cases.
441 foreach (const KFileItem
& item
, m_dispatchedItems
) {
442 KFileItemList::iterator begin
= m_pendingItems
.begin();
443 KFileItemList::iterator end
= m_pendingItems
.end();
444 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
445 if ((*it
).url() == item
.url()) {
446 m_pendingItems
.erase(it
);
451 m_dispatchedItems
.clear();
453 m_pendingVisiblePreviews
= 0;
454 dispatchPreviewQueue();
456 KFileItemList orderedItems
= m_pendingItems
;
457 orderItems(orderedItems
);
459 // Kill all suspended preview jobs. Usually when a preview job
460 // has been finished, slotPreviewJobFinished() clears all item queues.
461 // This is not wanted in this case, as a new job is created afterwards
462 // for m_pendingItems.
463 m_clearItemQueues
= false;
465 m_clearItemQueues
= true;
467 startPreviewJob(orderedItems
);
470 bool KFilePreviewGenerator::Private::isCutItem(const KFileItem
& item
) const
472 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
473 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
475 const KUrl itemUrl
= item
.url();
476 foreach (const KUrl
& url
, cutUrls
) {
477 if (url
== itemUrl
) {
485 void KFilePreviewGenerator::Private::applyCutItemEffect()
487 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
488 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
489 if (!m_hasCutSelection
) {
494 KDirLister
* dirLister
= m_dirModel
->dirLister();
495 const KUrl::List dirs
= dirLister
->directories();
496 foreach (const KUrl
& url
, dirs
) {
497 items
<< dirLister
->itemsForDir(url
);
500 foreach (const KFileItem
& item
, items
) {
501 if (isCutItem(item
)) {
502 const QModelIndex index
= m_dirModel
->indexForItem(item
);
503 const QVariant value
= m_dirModel
->data(index
, Qt::DecorationRole
);
504 if (value
.type() == QVariant::Icon
) {
505 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
506 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
507 QPixmap pixmap
= icon
.pixmap(actualSize
);
509 // remember current pixmap for the item to be able
510 // to restore it when other items get cut
512 cutItem
.url
= item
.url();
513 cutItem
.pixmap
= pixmap
;
514 m_cutItemsCache
.append(cutItem
);
516 // apply icon effect to the cut item
517 KIconEffect iconEffect
;
518 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
519 m_dirModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
525 bool KFilePreviewGenerator::Private::applyImageFrame(QPixmap
& icon
)
527 const QSize maxSize
= m_view
->iconSize();
528 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
529 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
530 ((icon
.width() > KIconLoader::SizeLarge
) ||
531 (icon
.height() > KIconLoader::SizeLarge
));
533 // the maximum size or the image itself is too small for a frame
538 const int doubleFrame
= frame
* 2;
540 // resize the icon to the maximum size minus the space required for the frame
541 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
544 const QPalette palette
= m_view
->palette();
545 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
546 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
547 const int width
= framedIcon
.width() - 1;
548 const int height
= framedIcon
.height() - 1;
550 painter
.begin(&framedIcon
);
551 painter
.drawPixmap(frame
, frame
, icon
);
554 painter
.setPen(palette
.color(QPalette::Text
));
555 painter
.drawRect(0, 0, width
, height
);
556 painter
.drawRect(1, 1, width
- 2, height
- 2);
558 painter
.setCompositionMode(QPainter::CompositionMode_Plus
);
559 QColor blendColor
= palette
.color(QPalette::Normal
, QPalette::Base
);
561 blendColor
.setAlpha(255 - 32);
562 painter
.setPen(blendColor
);
563 painter
.drawRect(0, 0, width
, height
);
565 blendColor
.setAlpha(255 - 64);
566 painter
.setPen(blendColor
);
567 painter
.drawRect(1, 1, width
- 2, height
- 2);
575 void KFilePreviewGenerator::Private::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
577 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
578 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::FastTransformation
);
582 void KFilePreviewGenerator::Private::startPreviewJob(const KFileItemList
& items
)
584 if (items
.count() == 0) {
588 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
589 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
591 const QSize size
= m_view
->iconSize();
593 // PreviewJob internally caches items always with the size of
594 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
595 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
596 // do a downscaling anyhow because of the frame, only the provided
597 // cache sizes are requested.
598 const int cacheSize
= (size
.width() > 128) || (size
.height() > 128) ? 256 : 128;
599 KIO::PreviewJob
* job
= KIO::filePreview(items
, cacheSize
, cacheSize
);
600 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
601 q
, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
602 connect(job
, SIGNAL(finished(KJob
*)),
603 q
, SLOT(slotPreviewJobFinished(KJob
*)));
605 m_previewJobs
.append(job
);
606 m_previewTimer
->start(200);
609 void KFilePreviewGenerator::Private::killPreviewJobs()
611 foreach (KJob
* job
, m_previewJobs
) {
615 m_previewJobs
.clear();
618 void KFilePreviewGenerator::Private::orderItems(KFileItemList
& items
)
620 // Order the items in a way that the preview for the visible items
621 // is generated first, as this improves the feeled performance a lot.
623 // Implementation note: 2 different algorithms are used for the sorting.
624 // Algorithm 1 is faster when having a lot of items in comparison
625 // to the number of rows in the model. Algorithm 2 is faster
626 // when having quite less items in comparison to the number of rows in
627 // the model. Choosing the right algorithm is important when having directories
628 // with several hundreds or thousands of items.
630 const int itemCount
= items
.count();
631 const int rowCount
= m_proxyModel
->rowCount();
632 const QRect visibleArea
= m_view
->viewport()->rect();
635 if (itemCount
* 10 > rowCount
) {
636 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
637 // and check whether the received row is part of the item list.
638 for (int row
= 0; row
< rowCount
; ++row
) {
639 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
640 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
641 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
643 KFileItem item
= m_dirModel
->itemForIndex(dirIndex
); // O(1)
644 const KUrl url
= item
.url();
646 // check whether the item is part of the item list 'items'
648 for (int i
= 0; i
< itemCount
; ++i
) {
649 if (items
.at(i
).url() == url
) {
655 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
656 // The current item is (at least partly) visible. Move it
657 // to the front of the list, so that the preview is
658 // generated earlier.
659 items
.removeAt(index
);
660 items
.insert(insertPos
, item
);
662 ++m_pendingVisiblePreviews
;
666 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
667 // all items and receive the corresponding row from the item.
668 for (int i
= 0; i
< itemCount
; ++i
) {
669 const QModelIndex dirIndex
= m_dirModel
->indexForItem(items
.at(i
)); // O(n) (n = number of rows)
670 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
671 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
673 if (itemRect
.intersects(visibleArea
)) {
674 // The current item is (at least partly) visible. Move it
675 // to the front of the list, so that the preview is
676 // generated earlier.
677 items
.insert(insertPos
, items
.at(i
));
678 items
.removeAt(i
+ 1);
680 ++m_pendingVisiblePreviews
;
686 KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView
* parent
, KDirSortFilterProxyModel
* model
) :
688 d(new Private(this, parent
, model
))
692 KFilePreviewGenerator::~KFilePreviewGenerator()
697 void KFilePreviewGenerator::setShowPreview(bool show
)
699 if (show
&& !d
->m_view
->iconSize().isValid()) {
700 // the view must provide an icon size, otherwise the showing
701 // off previews will get ignored
705 if (d
->m_showPreview
!= show
) {
706 d
->m_showPreview
= show
;
707 d
->m_cutItemsCache
.clear();
714 if (show
&& (d
->m_mimeTypeResolver
!= 0)) {
715 // don't resolve the MIME types if the preview is turned on
716 d
->m_mimeTypeResolver
->deleteLater();
717 d
->m_mimeTypeResolver
= 0;
718 } else if (!show
&& (d
->m_mimeTypeResolver
== 0)) {
719 // the preview is turned off: resolve the MIME-types so that
720 // the icons gets updated
721 d
->m_mimeTypeResolver
= new KMimeTypeResolver(d
->m_view
, d
->m_dirModel
);
725 bool KFilePreviewGenerator::showPreview() const
727 return d
->m_showPreview
;
730 void KFilePreviewGenerator::updatePreviews()
732 if (!d
->m_showPreview
) {
736 d
->killPreviewJobs();
737 d
->m_cutItemsCache
.clear();
738 d
->m_pendingItems
.clear();
739 d
->m_dispatchedItems
.clear();
741 KFileItemList itemList
;
742 const int rowCount
= d
->m_dirModel
->rowCount();
743 for (int row
= 0; row
< rowCount
; ++row
) {
744 const QModelIndex index
= d
->m_dirModel
->index(row
, 0);
745 KFileItem item
= d
->m_dirModel
->itemForIndex(index
);
746 itemList
.append(item
);
749 d
->generatePreviews(itemList
);
753 void KFilePreviewGenerator::cancelPreviews()
755 d
->killPreviewJobs();
756 d
->m_cutItemsCache
.clear();
757 d
->m_pendingItems
.clear();
758 d
->m_dispatchedItems
.clear();
761 #include "kfilepreviewgenerator.moc"