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 KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView
* parent
, KDirSortFilterProxyModel
* model
) :
86 m_clearItemQueues(true),
87 m_hasCutSelection(false),
88 m_pendingVisiblePreviews(0),
95 m_mimeTypeResolver(0),
101 if (!m_view
->iconSize().isValid()) {
102 m_showPreview
= false;
105 m_dirModel
= static_cast<KDirModel
*>(m_proxyModel
->sourceModel());
106 connect(m_dirModel
->dirLister(), SIGNAL(newItems(const KFileItemList
&)),
107 this, SLOT(generatePreviews(const KFileItemList
&)));
109 QClipboard
* clipboard
= QApplication::clipboard();
110 connect(clipboard
, SIGNAL(dataChanged()),
111 this, SLOT(updateCutItems()));
113 m_previewTimer
= new QTimer(this);
114 m_previewTimer
->setSingleShot(true);
115 connect(m_previewTimer
, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
117 // Whenever the scrollbar values have been changed, the pending previews should
118 // be reordered in a way that the previews for the visible items are generated
119 // first. The reordering is done with a small delay, so that during moving the
120 // scrollbars the CPU load is kept low.
121 m_scrollAreaTimer
= new QTimer(this);
122 m_scrollAreaTimer
->setSingleShot(true);
123 m_scrollAreaTimer
->setInterval(200);
124 connect(m_scrollAreaTimer
, SIGNAL(timeout()),
125 this, SLOT(resumePreviews()));
126 connect(m_view
->horizontalScrollBar(), SIGNAL(valueChanged(int)),
127 this, SLOT(pausePreviews()));
128 connect(m_view
->verticalScrollBar(), SIGNAL(valueChanged(int)),
129 this, SLOT(pausePreviews()));
132 KFilePreviewGenerator::~KFilePreviewGenerator()
135 m_pendingItems
.clear();
136 m_dispatchedItems
.clear();
137 if (m_mimeTypeResolver
!= 0) {
138 m_mimeTypeResolver
->deleteLater();
139 m_mimeTypeResolver
= 0;
143 void KFilePreviewGenerator::setShowPreview(bool show
)
145 if (show
&& !m_view
->iconSize().isValid()) {
146 // the view must provide an icon size, otherwise the showing
147 // off previews will get ignored
151 if (m_showPreview
!= show
) {
152 m_showPreview
= show
;
153 m_cutItemsCache
.clear();
160 if (show
&& (m_mimeTypeResolver
!= 0)) {
161 // don't resolve the MIME types if the preview is turned on
162 m_mimeTypeResolver
->deleteLater();
163 m_mimeTypeResolver
= 0;
164 } else if (!show
&& (m_mimeTypeResolver
== 0)) {
165 // the preview is turned off: resolve the MIME-types so that
166 // the icons gets updated
167 m_mimeTypeResolver
= new KMimeTypeResolver(m_view
, m_dirModel
);
171 void KFilePreviewGenerator::updatePreviews()
173 if (!m_showPreview
) {
178 m_cutItemsCache
.clear();
179 m_pendingItems
.clear();
180 m_dispatchedItems
.clear();
182 KFileItemList itemList
;
183 const int rowCount
= m_dirModel
->rowCount();
184 for (int row
= 0; row
< rowCount
; ++row
) {
185 const QModelIndex index
= m_dirModel
->index(row
, 0);
186 KFileItem item
= m_dirModel
->itemForIndex(index
);
187 itemList
.append(item
);
190 generatePreviews(itemList
);
194 void KFilePreviewGenerator::cancelPreviews()
197 m_cutItemsCache
.clear();
198 m_pendingItems
.clear();
199 m_dispatchedItems
.clear();
202 void KFilePreviewGenerator::generatePreviews(const KFileItemList
& items
)
204 applyCutItemEffect();
206 if (!m_showPreview
) {
210 KFileItemList orderedItems
= items
;
211 orderItems(orderedItems
);
213 foreach (const KFileItem
& item
, orderedItems
) {
214 m_pendingItems
.append(item
);
217 startPreviewJob(orderedItems
);
220 void KFilePreviewGenerator::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
222 if (!m_showPreview
) {
223 // the preview has been canceled in the meantime
226 const KUrl url
= item
.url();
228 // check whether the item is part of the directory lister (it is possible
229 // that a preview from an old directory lister is received)
230 KDirLister
* dirLister
= m_dirModel
->dirLister();
231 bool isOldPreview
= true;
232 const KUrl::List dirs
= dirLister
->directories();
233 const QString itemDir
= url
.directory();
234 foreach (const KUrl
& url
, dirs
) {
235 if (url
.path() == itemDir
) {
236 isOldPreview
= false;
244 QPixmap icon
= pixmap
;
246 const QString mimeType
= item
.mimetype();
247 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
248 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
249 limitToSize(icon
, m_view
->iconSize());
252 if (m_hasCutSelection
&& isCutItem(item
)) {
253 // Remember the current icon in the cache for cut items before
254 // the disabled effect is applied. This makes it possible restoring
255 // the uncut version again when cutting other items.
256 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
257 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
258 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
259 if ((*it
).url
== item
.url()) {
265 // apply the disabled effect to the icon for marking it as "cut item"
266 // and apply the icon to the item
267 KIconEffect iconEffect
;
268 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
271 // remember the preview and URL, so that it can be applied to the model
272 // in KFilePreviewGenerator::dispatchPreviewQueue()
275 preview
.pixmap
= icon
;
276 m_previews
.append(preview
);
278 m_dispatchedItems
.append(item
);
281 void KFilePreviewGenerator::slotPreviewJobFinished(KJob
* job
)
283 const int index
= m_previewJobs
.indexOf(job
);
284 m_previewJobs
.removeAt(index
);
286 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
287 m_pendingItems
.clear();
288 m_dispatchedItems
.clear();
289 m_pendingVisiblePreviews
= 0;
290 QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection
);
294 void KFilePreviewGenerator::updateCutItems()
296 // restore the icons of all previously selected items to the
298 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
299 const QModelIndex index
= m_dirModel
->indexForUrl(cutItem
.url
);
300 if (index
.isValid()) {
301 m_dirModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
304 m_cutItemsCache
.clear();
306 // ... and apply an item effect to all currently cut items
307 applyCutItemEffect();
310 void KFilePreviewGenerator::dispatchPreviewQueue()
312 const int previewsCount
= m_previews
.count();
313 if (previewsCount
> 0) {
314 // Applying the previews to the model must be done step by step
315 // in larger blocks: Applying a preview immediately when getting the signal
316 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
317 // of the view would be triggered for each single preview.
318 LayoutBlocker
blocker(m_view
);
319 for (int i
= 0; i
< previewsCount
; ++i
) {
320 const ItemInfo
& preview
= m_previews
.first();
322 const QModelIndex idx
= m_dirModel
->indexForUrl(preview
.url
);
323 if (idx
.isValid() && (idx
.column() == 0)) {
324 m_dirModel
->setData(idx
, QIcon(preview
.pixmap
), Qt::DecorationRole
);
327 m_previews
.pop_front();
328 if (m_pendingVisiblePreviews
> 0) {
329 --m_pendingVisiblePreviews
;
334 if (m_pendingVisiblePreviews
> 0) {
335 // As long as there are pending previews for visible items, poll
336 // the preview queue each 200 ms. If there are no pending previews,
337 // the queue is dispatched in slotPreviewJobFinished().
338 m_previewTimer
->start(200);
342 void KFilePreviewGenerator::pausePreviews()
344 foreach (KJob
* job
, m_previewJobs
) {
348 m_scrollAreaTimer
->start();
351 void KFilePreviewGenerator::resumePreviews()
353 // Before creating new preview jobs the m_pendingItems queue must be
354 // cleaned up by removing the already dispatched items. Implementation
355 // note: The order of the m_dispatchedItems queue and the m_pendingItems
356 // queue is usually equal. So even when having a lot of elements the
357 // nested loop is no performance bottle neck, as the inner loop is only
358 // entered once in most cases.
359 foreach (const KFileItem
& item
, m_dispatchedItems
) {
360 KFileItemList::iterator begin
= m_pendingItems
.begin();
361 KFileItemList::iterator end
= m_pendingItems
.end();
362 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
363 if ((*it
).url() == item
.url()) {
364 m_pendingItems
.erase(it
);
369 m_dispatchedItems
.clear();
371 m_pendingVisiblePreviews
= 0;
372 dispatchPreviewQueue();
374 KFileItemList orderedItems
= m_pendingItems
;
375 orderItems(orderedItems
);
377 // Kill all suspended preview jobs. Usually when a preview job
378 // has been finished, slotPreviewJobFinished() clears all item queues.
379 // This is not wanted in this case, as a new job is created afterwards
380 // for m_pendingItems.
381 m_clearItemQueues
= false;
383 m_clearItemQueues
= true;
385 startPreviewJob(orderedItems
);
388 bool KFilePreviewGenerator::isCutItem(const KFileItem
& item
) const
390 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
391 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
393 const KUrl itemUrl
= item
.url();
394 foreach (const KUrl
& url
, cutUrls
) {
395 if (url
== itemUrl
) {
403 void KFilePreviewGenerator::applyCutItemEffect()
405 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
406 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
407 if (!m_hasCutSelection
) {
412 KDirLister
* dirLister
= m_dirModel
->dirLister();
413 const KUrl::List dirs
= dirLister
->directories();
414 foreach (const KUrl
& url
, dirs
) {
415 items
<< dirLister
->itemsForDir(url
);
418 foreach (const KFileItem
& item
, items
) {
419 if (isCutItem(item
)) {
420 const QModelIndex index
= m_dirModel
->indexForItem(item
);
421 const QVariant value
= m_dirModel
->data(index
, Qt::DecorationRole
);
422 if (value
.type() == QVariant::Icon
) {
423 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
424 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
425 QPixmap pixmap
= icon
.pixmap(actualSize
);
427 // remember current pixmap for the item to be able
428 // to restore it when other items get cut
430 cutItem
.url
= item
.url();
431 cutItem
.pixmap
= pixmap
;
432 m_cutItemsCache
.append(cutItem
);
434 // apply icon effect to the cut item
435 KIconEffect iconEffect
;
436 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
437 m_dirModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
443 bool KFilePreviewGenerator::applyImageFrame(QPixmap
& icon
)
445 const QSize maxSize
= m_view
->iconSize();
446 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
447 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
448 ((icon
.width() > KIconLoader::SizeLarge
) ||
449 (icon
.height() > KIconLoader::SizeLarge
));
451 // the maximum size or the image itself is too small for a frame
456 const int doubleFrame
= frame
* 2;
458 // resize the icon to the maximum size minus the space required for the frame
459 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
462 const QPalette palette
= m_view
->palette();
463 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
464 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
465 const int width
= framedIcon
.width() - 1;
466 const int height
= framedIcon
.height() - 1;
468 painter
.begin(&framedIcon
);
469 painter
.drawPixmap(frame
, frame
, icon
);
472 painter
.setPen(palette
.color(QPalette::Text
));
473 painter
.drawRect(0, 0, width
, height
);
474 painter
.drawRect(1, 1, width
- 2, height
- 2);
476 painter
.setCompositionMode(QPainter::CompositionMode_Plus
);
477 QColor blendColor
= palette
.color(QPalette::Normal
, QPalette::Base
);
479 blendColor
.setAlpha(255 - 32);
480 painter
.setPen(blendColor
);
481 painter
.drawRect(0, 0, width
, height
);
483 blendColor
.setAlpha(255 - 64);
484 painter
.setPen(blendColor
);
485 painter
.drawRect(1, 1, width
- 2, height
- 2);
493 void KFilePreviewGenerator::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
495 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
496 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::FastTransformation
);
500 void KFilePreviewGenerator::startPreviewJob(const KFileItemList
& items
)
502 if (items
.count() == 0) {
506 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
507 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
509 const QSize size
= m_view
->iconSize();
511 // PreviewJob internally caches items always with the size of
512 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
513 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
514 // do a downscaling anyhow because of the frame, only the provided
515 // cache sizes are requested.
516 const int cacheSize
= (size
.width() > 128) || (size
.height() > 128) ? 256 : 128;
517 KIO::PreviewJob
* job
= KIO::filePreview(items
, cacheSize
, cacheSize
);
518 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
519 this, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
520 connect(job
, SIGNAL(finished(KJob
*)),
521 this, SLOT(slotPreviewJobFinished(KJob
*)));
523 m_previewJobs
.append(job
);
524 m_previewTimer
->start(200);
527 void KFilePreviewGenerator::killPreviewJobs()
529 foreach (KJob
* job
, m_previewJobs
) {
533 m_previewJobs
.clear();
536 void KFilePreviewGenerator::orderItems(KFileItemList
& items
)
538 // Order the items in a way that the preview for the visible items
539 // is generated first, as this improves the feeled performance a lot.
541 // Implementation note: 2 different algorithms are used for the sorting.
542 // Algorithm 1 is faster when having a lot of items in comparison
543 // to the number of rows in the model. Algorithm 2 is faster
544 // when having quite less items in comparison to the number of rows in
545 // the model. Choosing the right algorithm is important when having directories
546 // with several hundreds or thousands of items.
548 const int itemCount
= items
.count();
549 const int rowCount
= m_proxyModel
->rowCount();
550 const QRect visibleArea
= m_view
->viewport()->rect();
553 if (itemCount
* 10 > rowCount
) {
554 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
555 // and check whether the received row is part of the item list.
556 for (int row
= 0; row
< rowCount
; ++row
) {
557 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
558 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
559 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
561 KFileItem item
= m_dirModel
->itemForIndex(dirIndex
); // O(1)
562 const KUrl url
= item
.url();
564 // check whether the item is part of the item list 'items'
566 for (int i
= 0; i
< itemCount
; ++i
) {
567 if (items
.at(i
).url() == url
) {
573 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
574 // The current item is (at least partly) visible. Move it
575 // to the front of the list, so that the preview is
576 // generated earlier.
577 items
.removeAt(index
);
578 items
.insert(insertPos
, item
);
580 ++m_pendingVisiblePreviews
;
584 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
585 // all items and receive the corresponding row from the item.
586 for (int i
= 0; i
< itemCount
; ++i
) {
587 const QModelIndex dirIndex
= m_dirModel
->indexForItem(items
.at(i
)); // O(n) (n = number of rows)
588 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
589 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
591 if (itemRect
.intersects(visibleArea
)) {
592 // The current item is (at least partly) visible. Move it
593 // to the front of the list, so that the preview is
594 // generated earlier.
595 items
.insert(insertPos
, items
.at(i
));
596 items
.removeAt(i
+ 1);
598 ++m_pendingVisiblePreviews
;
604 #include "kfilepreviewgenerator.moc"