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 Q_ASSERT(m_view
->iconSize().isValid()); // each view must provide its current icon size
103 m_dirModel
= static_cast<KDirModel
*>(m_proxyModel
->sourceModel());
104 connect(m_dirModel
->dirLister(), SIGNAL(newItems(const KFileItemList
&)),
105 this, SLOT(generatePreviews(const KFileItemList
&)));
107 QClipboard
* clipboard
= QApplication::clipboard();
108 connect(clipboard
, SIGNAL(dataChanged()),
109 this, SLOT(updateCutItems()));
111 m_previewTimer
= new QTimer(this);
112 m_previewTimer
->setSingleShot(true);
113 connect(m_previewTimer
, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
115 // Whenever the scrollbar values have been changed, the pending previews should
116 // be reordered in a way that the previews for the visible items are generated
117 // first. The reordering is done with a small delay, so that during moving the
118 // scrollbars the CPU load is kept low.
119 m_scrollAreaTimer
= new QTimer(this);
120 m_scrollAreaTimer
->setSingleShot(true);
121 m_scrollAreaTimer
->setInterval(200);
122 connect(m_scrollAreaTimer
, SIGNAL(timeout()),
123 this, SLOT(resumePreviews()));
124 connect(m_view
->horizontalScrollBar(), SIGNAL(valueChanged(int)),
125 this, SLOT(pausePreviews()));
126 connect(m_view
->verticalScrollBar(), SIGNAL(valueChanged(int)),
127 this, SLOT(pausePreviews()));
130 KFilePreviewGenerator::~KFilePreviewGenerator()
133 m_pendingItems
.clear();
134 m_dispatchedItems
.clear();
135 if (m_mimeTypeResolver
!= 0) {
136 m_mimeTypeResolver
->deleteLater();
137 m_mimeTypeResolver
= 0;
141 void KFilePreviewGenerator::setShowPreview(bool show
)
143 if (m_showPreview
!= show
) {
144 m_showPreview
= show
;
145 m_cutItemsCache
.clear();
152 if (show
&& (m_mimeTypeResolver
!= 0)) {
153 // don't resolve the MIME types if the preview is turned on
154 m_mimeTypeResolver
->deleteLater();
155 m_mimeTypeResolver
= 0;
156 } else if (!show
&& (m_mimeTypeResolver
== 0)) {
157 // the preview is turned off: resolve the MIME-types so that
158 // the icons gets updated
159 m_mimeTypeResolver
= new KMimeTypeResolver(m_view
, m_dirModel
);
163 void KFilePreviewGenerator::updatePreviews()
165 if (!m_showPreview
) {
170 m_cutItemsCache
.clear();
171 m_pendingItems
.clear();
172 m_dispatchedItems
.clear();
174 KFileItemList itemList
;
175 const int rowCount
= m_dirModel
->rowCount();
176 for (int row
= 0; row
< rowCount
; ++row
) {
177 const QModelIndex index
= m_dirModel
->index(row
, 0);
178 KFileItem item
= m_dirModel
->itemForIndex(index
);
179 itemList
.append(item
);
182 generatePreviews(itemList
);
186 void KFilePreviewGenerator::cancelPreviews()
189 m_cutItemsCache
.clear();
190 m_pendingItems
.clear();
191 m_dispatchedItems
.clear();
194 void KFilePreviewGenerator::generatePreviews(const KFileItemList
& items
)
196 applyCutItemEffect();
198 if (!m_showPreview
) {
202 KFileItemList orderedItems
= items
;
203 orderItems(orderedItems
);
205 foreach (const KFileItem
& item
, orderedItems
) {
206 m_pendingItems
.append(item
);
209 startPreviewJob(orderedItems
);
212 void KFilePreviewGenerator::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
214 if (!m_showPreview
) {
215 // the preview has been canceled in the meantime
218 const KUrl url
= item
.url();
220 // check whether the item is part of the directory lister (it is possible
221 // that a preview from an old directory lister is received)
222 KDirLister
* dirLister
= m_dirModel
->dirLister();
223 bool isOldPreview
= true;
224 const KUrl::List dirs
= dirLister
->directories();
225 const QString itemDir
= url
.directory();
226 foreach (const KUrl
& url
, dirs
) {
227 if (url
.path() == itemDir
) {
228 isOldPreview
= false;
236 QPixmap icon
= pixmap
;
238 const QString mimeType
= item
.mimetype();
239 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
240 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
241 limitToSize(icon
, m_view
->iconSize());
244 if (m_hasCutSelection
&& isCutItem(item
)) {
245 // Remember the current icon in the cache for cut items before
246 // the disabled effect is applied. This makes it possible restoring
247 // the uncut version again when cutting other items.
248 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
249 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
250 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
251 if ((*it
).url
== item
.url()) {
257 // apply the disabled effect to the icon for marking it as "cut item"
258 // and apply the icon to the item
259 KIconEffect iconEffect
;
260 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
263 // remember the preview and URL, so that it can be applied to the model
264 // in KFilePreviewGenerator::dispatchPreviewQueue()
267 preview
.pixmap
= icon
;
268 m_previews
.append(preview
);
270 m_dispatchedItems
.append(item
);
273 void KFilePreviewGenerator::slotPreviewJobFinished(KJob
* job
)
275 const int index
= m_previewJobs
.indexOf(job
);
276 m_previewJobs
.removeAt(index
);
278 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
279 m_pendingItems
.clear();
280 m_dispatchedItems
.clear();
281 m_pendingVisiblePreviews
= 0;
282 QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection
);
286 void KFilePreviewGenerator::updateCutItems()
288 // restore the icons of all previously selected items to the
290 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
291 const QModelIndex index
= m_dirModel
->indexForUrl(cutItem
.url
);
292 if (index
.isValid()) {
293 m_dirModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
296 m_cutItemsCache
.clear();
298 // ... and apply an item effect to all currently cut items
299 applyCutItemEffect();
302 void KFilePreviewGenerator::dispatchPreviewQueue()
304 const int previewsCount
= m_previews
.count();
305 if (previewsCount
> 0) {
306 // Applying the previews to the model must be done step by step
307 // in larger blocks: Applying a preview immediately when getting the signal
308 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
309 // of the view would be triggered for each single preview.
310 LayoutBlocker
blocker(m_view
);
311 for (int i
= 0; i
< previewsCount
; ++i
) {
312 const ItemInfo
& preview
= m_previews
.first();
314 const QModelIndex idx
= m_dirModel
->indexForUrl(preview
.url
);
315 if (idx
.isValid() && (idx
.column() == 0)) {
316 m_dirModel
->setData(idx
, QIcon(preview
.pixmap
), Qt::DecorationRole
);
319 m_previews
.pop_front();
320 if (m_pendingVisiblePreviews
> 0) {
321 --m_pendingVisiblePreviews
;
326 if (m_pendingVisiblePreviews
> 0) {
327 // As long as there are pending previews for visible items, poll
328 // the preview queue each 200 ms. If there are no pending previews,
329 // the queue is dispatched in slotPreviewJobFinished().
330 m_previewTimer
->start(200);
334 void KFilePreviewGenerator::pausePreviews()
336 foreach (KJob
* job
, m_previewJobs
) {
340 m_scrollAreaTimer
->start();
343 void KFilePreviewGenerator::resumePreviews()
345 // Before creating new preview jobs the m_pendingItems queue must be
346 // cleaned up by removing the already dispatched items. Implementation
347 // note: The order of the m_dispatchedItems queue and the m_pendingItems
348 // queue is usually equal. So even when having a lot of elements the
349 // nested loop is no performance bottle neck, as the inner loop is only
350 // entered once in most cases.
351 foreach (const KFileItem
& item
, m_dispatchedItems
) {
352 KFileItemList::iterator begin
= m_pendingItems
.begin();
353 KFileItemList::iterator end
= m_pendingItems
.end();
354 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
355 if ((*it
).url() == item
.url()) {
356 m_pendingItems
.erase(it
);
361 m_dispatchedItems
.clear();
363 m_pendingVisiblePreviews
= 0;
364 dispatchPreviewQueue();
366 KFileItemList orderedItems
= m_pendingItems
;
367 orderItems(orderedItems
);
369 // Kill all suspended preview jobs. Usually when a preview job
370 // has been finished, slotPreviewJobFinished() clears all item queues.
371 // This is not wanted in this case, as a new job is created afterwards
372 // for m_pendingItems.
373 m_clearItemQueues
= false;
375 m_clearItemQueues
= true;
377 startPreviewJob(orderedItems
);
380 bool KFilePreviewGenerator::isCutItem(const KFileItem
& item
) const
382 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
383 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
385 const KUrl itemUrl
= item
.url();
386 foreach (const KUrl
& url
, cutUrls
) {
387 if (url
== itemUrl
) {
395 void KFilePreviewGenerator::applyCutItemEffect()
397 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
398 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
399 if (!m_hasCutSelection
) {
404 KDirLister
* dirLister
= m_dirModel
->dirLister();
405 const KUrl::List dirs
= dirLister
->directories();
406 foreach (const KUrl
& url
, dirs
) {
407 items
<< dirLister
->itemsForDir(url
);
410 foreach (const KFileItem
& item
, items
) {
411 if (isCutItem(item
)) {
412 const QModelIndex index
= m_dirModel
->indexForItem(item
);
413 const QVariant value
= m_dirModel
->data(index
, Qt::DecorationRole
);
414 if (value
.type() == QVariant::Icon
) {
415 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
416 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
417 QPixmap pixmap
= icon
.pixmap(actualSize
);
419 // remember current pixmap for the item to be able
420 // to restore it when other items get cut
422 cutItem
.url
= item
.url();
423 cutItem
.pixmap
= pixmap
;
424 m_cutItemsCache
.append(cutItem
);
426 // apply icon effect to the cut item
427 KIconEffect iconEffect
;
428 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
429 m_dirModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
435 bool KFilePreviewGenerator::applyImageFrame(QPixmap
& icon
)
437 const QSize maxSize
= m_view
->iconSize();
438 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
439 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
440 ((icon
.width() > KIconLoader::SizeLarge
) ||
441 (icon
.height() > KIconLoader::SizeLarge
));
443 // the maximum size or the image itself is too small for a frame
448 const int doubleFrame
= frame
* 2;
450 // resize the icon to the maximum size minus the space required for the frame
451 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
454 const QPalette palette
= m_view
->palette();
455 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
456 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
457 const int width
= framedIcon
.width() - 1;
458 const int height
= framedIcon
.height() - 1;
460 painter
.begin(&framedIcon
);
461 painter
.drawPixmap(frame
, frame
, icon
);
464 painter
.setPen(palette
.color(QPalette::Text
));
465 painter
.drawRect(0, 0, width
, height
);
466 painter
.drawRect(1, 1, width
- 2, height
- 2);
468 painter
.setCompositionMode(QPainter::CompositionMode_Plus
);
469 QColor blendColor
= palette
.color(QPalette::Normal
, QPalette::Base
);
471 blendColor
.setAlpha(255 - 32);
472 painter
.setPen(blendColor
);
473 painter
.drawRect(0, 0, width
, height
);
475 blendColor
.setAlpha(255 - 64);
476 painter
.setPen(blendColor
);
477 painter
.drawRect(1, 1, width
- 2, height
- 2);
485 void KFilePreviewGenerator::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
487 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
488 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::FastTransformation
);
492 void KFilePreviewGenerator::startPreviewJob(const KFileItemList
& items
)
494 if (items
.count() == 0) {
498 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
499 m_hasCutSelection
= KonqMimeData::decodeIsCutSelection(mimeData
);
501 const QSize size
= m_view
->iconSize();
503 // PreviewJob internally caches items always with the size of
504 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
505 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
506 // do a downscaling anyhow because of the frame, only the provided
507 // cache sizes are requested.
508 const int cacheSize
= (size
.width() > 128) || (size
.height() > 128) ? 256 : 128;
509 KIO::PreviewJob
* job
= KIO::filePreview(items
, cacheSize
, cacheSize
);
510 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
511 this, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
512 connect(job
, SIGNAL(finished(KJob
*)),
513 this, SLOT(slotPreviewJobFinished(KJob
*)));
515 m_previewJobs
.append(job
);
516 m_previewTimer
->start(200);
519 void KFilePreviewGenerator::killPreviewJobs()
521 foreach (KJob
* job
, m_previewJobs
) {
525 m_previewJobs
.clear();
528 void KFilePreviewGenerator::orderItems(KFileItemList
& items
)
530 // Order the items in a way that the preview for the visible items
531 // is generated first, as this improves the feeled performance a lot.
533 // Implementation note: 2 different algorithms are used for the sorting.
534 // Algorithm 1 is faster when having a lot of items in comparison
535 // to the number of rows in the model. Algorithm 2 is faster
536 // when having quite less items in comparison to the number of rows in
537 // the model. Choosing the right algorithm is important when having directories
538 // with several hundreds or thousands of items.
540 const int itemCount
= items
.count();
541 const int rowCount
= m_proxyModel
->rowCount();
542 const QRect visibleArea
= m_view
->viewport()->rect();
545 if (itemCount
* 10 > rowCount
) {
546 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
547 // and check whether the received row is part of the item list.
548 for (int row
= 0; row
< rowCount
; ++row
) {
549 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
550 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
551 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
553 KFileItem item
= m_dirModel
->itemForIndex(dirIndex
); // O(1)
554 const KUrl url
= item
.url();
556 // check whether the item is part of the item list 'items'
558 for (int i
= 0; i
< itemCount
; ++i
) {
559 if (items
.at(i
).url() == url
) {
565 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
566 // The current item is (at least partly) visible. Move it
567 // to the front of the list, so that the preview is
568 // generated earlier.
569 items
.removeAt(index
);
570 items
.insert(insertPos
, item
);
572 ++m_pendingVisiblePreviews
;
576 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
577 // all items and receive the corresponding row from the item.
578 for (int i
= 0; i
< itemCount
; ++i
) {
579 const QModelIndex dirIndex
= m_dirModel
->indexForItem(items
.at(i
)); // O(n) (n = number of rows)
580 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
581 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
583 if (itemRect
.intersects(visibleArea
)) {
584 // The current item is (at least partly) visible. Move it
585 // to the front of the list, so that the preview is
586 // generated earlier.
587 items
.insert(insertPos
, items
.at(i
));
588 items
.removeAt(i
+ 1);
590 ++m_pendingVisiblePreviews
;
596 #include "kfilepreviewgenerator.moc"