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 "iconmanager.h"
22 #include "dolphinmodel.h"
23 #include "dolphinsortfilterproxymodel.h"
25 #include <kiconeffect.h>
26 #include <kio/previewjob.h>
27 #include <kdirlister.h>
28 #include <kmimetyperesolver.h>
29 #include <konqmimedata.h>
31 #include <QApplication>
32 #include <QAbstractItemView>
41 * If the passed item view is an instance of QListView, expensive
42 * layout operations are blocked in the constructor and are unblocked
43 * again in the destructor.
45 * This helper class is a workaround for the following huge performance
46 * problem when having directories with several 1000 items:
47 * - each change of an icon emits a dataChanged() signal from the model
48 * - QListView iterates through all items on each dataChanged() signal
49 * and invokes QItemDelegate::sizeHint()
50 * - the sizeHint() implementation of KFileItemDelegate is quite complex,
51 * invoking it 1000 times for each icon change might block the UI
53 * QListView does not invoke QItemDelegate::sizeHint() when the
54 * uniformItemSize property has been set to true, so this property is
55 * set before exchanging a block of icons. It is important to reset
56 * it again before the event loop is entered, otherwise QListView
57 * would not get the correct size hints after dispatching the layoutChanged()
62 LayoutBlocker(QAbstractItemView
* view
) :
63 m_uniformSizes(false),
64 m_view(qobject_cast
<QListView
*>(view
))
67 m_uniformSizes
= m_view
->uniformItemSizes();
68 m_view
->setUniformItemSizes(true);
75 m_view
->setUniformItemSizes(m_uniformSizes
);
84 IconManager::IconManager(QAbstractItemView
* parent
, DolphinSortFilterProxyModel
* model
) :
87 m_clearItemQueues(true),
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_dolphinModel
= static_cast<DolphinModel
*>(m_proxyModel
->sourceModel());
104 connect(m_dolphinModel
->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 IconManager::~IconManager()
133 m_pendingItems
.clear();
134 m_dispatchedItems
.clear();
135 if (m_mimeTypeResolver
!= 0) {
136 m_mimeTypeResolver
->deleteLater();
137 m_mimeTypeResolver
= 0;
142 void IconManager::setShowPreview(bool show
)
144 if (m_showPreview
!= show
) {
145 m_showPreview
= show
;
146 m_cutItemsCache
.clear();
153 if (show
&& (m_mimeTypeResolver
!= 0)) {
154 // don't resolve the MIME types if the preview is turned on
155 m_mimeTypeResolver
->deleteLater();
156 m_mimeTypeResolver
= 0;
157 } else if (!show
&& (m_mimeTypeResolver
== 0)) {
158 // the preview is turned off: resolve the MIME-types so that
159 // the icons gets updated
160 m_mimeTypeResolver
= new KMimeTypeResolver(m_view
, m_dolphinModel
);
164 void IconManager::updatePreviews()
166 if (!m_showPreview
) {
171 m_cutItemsCache
.clear();
172 m_pendingItems
.clear();
173 m_dispatchedItems
.clear();
175 KFileItemList itemList
;
176 const int rowCount
= m_dolphinModel
->rowCount();
177 for (int row
= 0; row
< rowCount
; ++row
) {
178 const QModelIndex index
= m_dolphinModel
->index(row
, 0);
179 KFileItem item
= m_dolphinModel
->itemForIndex(index
);
180 itemList
.append(item
);
183 generatePreviews(itemList
);
187 void IconManager::cancelPreviews()
190 m_cutItemsCache
.clear();
191 m_pendingItems
.clear();
192 m_dispatchedItems
.clear();
195 void IconManager::generatePreviews(const KFileItemList
& items
)
197 applyCutItemEffect();
199 if (!m_showPreview
) {
203 KFileItemList orderedItems
= items
;
204 orderItems(orderedItems
);
206 foreach (const KFileItem
& item
, orderedItems
) {
207 m_pendingItems
.append(item
);
210 startPreviewJob(orderedItems
);
213 void IconManager::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
215 if (!m_showPreview
) {
216 // the preview has been canceled in the meantime
219 const KUrl url
= item
.url();
221 // check whether the item is part of the directory lister (it is possible
222 // that a preview from an old directory lister is received)
223 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
224 bool isOldPreview
= true;
225 const KUrl::List dirs
= dirLister
->directories();
226 const QString itemDir
= url
.directory();
227 foreach (const KUrl
& url
, dirs
) {
228 if (url
.path() == itemDir
) {
229 isOldPreview
= false;
237 QPixmap icon
= pixmap
;
239 const QString mimeType
= item
.mimetype();
240 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
241 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
242 limitToSize(icon
, m_view
->iconSize());
245 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
246 if (KonqMimeData::decodeIsCutSelection(mimeData
) && isCutItem(item
)) {
247 // Remember the current icon in the cache for cut items before
248 // the disabled effect is applied. This makes it possible restoring
249 // the uncut version again when cutting other items.
250 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
251 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
252 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
253 if ((*it
).url
== item
.url()) {
259 // apply the disabled effect to the icon for marking it as "cut item"
260 // and apply the icon to the item
261 KIconEffect iconEffect
;
262 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
265 // remember the preview and URL, so that it can be applied to the model
266 // in IconManager::dispatchPreviewQueue()
269 preview
.pixmap
= icon
;
270 m_previews
.append(preview
);
272 m_dispatchedItems
.append(item
);
275 void IconManager::slotPreviewJobFinished(KJob
* job
)
277 const int index
= m_previewJobs
.indexOf(job
);
278 m_previewJobs
.removeAt(index
);
280 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
281 m_pendingItems
.clear();
282 m_dispatchedItems
.clear();
283 m_pendingVisiblePreviews
= 0;
284 QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection
);
288 void IconManager::updateCutItems()
290 // restore the icons of all previously selected items to the
292 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
293 const QModelIndex index
= m_dolphinModel
->indexForUrl(cutItem
.url
);
294 if (index
.isValid()) {
295 m_dolphinModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
298 m_cutItemsCache
.clear();
300 // ... and apply an item effect to all currently cut items
301 applyCutItemEffect();
304 void IconManager::dispatchPreviewQueue()
306 const int previewsCount
= m_previews
.count();
307 if (previewsCount
> 0) {
308 // Applying the previews to the model must be done step by step
309 // in larger blocks: Applying a preview immediately when getting the signal
310 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
311 // of the view would be triggered for each single preview.
312 LayoutBlocker
blocker(m_view
);
313 for (int i
= 0; i
< previewsCount
; ++i
) {
314 const ItemInfo
& preview
= m_previews
.first();
316 const QModelIndex idx
= m_dolphinModel
->indexForUrl(preview
.url
);
317 if (idx
.isValid() && (idx
.column() == 0)) {
318 m_dolphinModel
->setData(idx
, QIcon(preview
.pixmap
), Qt::DecorationRole
);
321 m_previews
.pop_front();
322 if (m_pendingVisiblePreviews
> 0) {
323 --m_pendingVisiblePreviews
;
328 if (m_pendingVisiblePreviews
> 0) {
329 // As long as there are pending previews for visible items, poll
330 // the preview queue each 200 ms. If there are no pending previews,
331 // the queue is dispatched in slotPreviewJobFinished().
332 m_previewTimer
->start(200);
336 void IconManager::pausePreviews()
338 foreach (KJob
* job
, m_previewJobs
) {
342 m_scrollAreaTimer
->start();
345 void IconManager::resumePreviews()
347 // Before creating new preview jobs the m_pendingItems queue must be
348 // cleaned up by removing the already dispatched items. Implementation
349 // note: The order of the m_dispatchedItems queue and the m_pendingItems
350 // queue is usually equal. So even when having a lot of elements the
351 // nested loop is no performance bottle neck, as the inner loop is only
352 // entered once in most cases.
353 foreach (const KFileItem
& item
, m_dispatchedItems
) {
354 KFileItemList::iterator begin
= m_pendingItems
.begin();
355 KFileItemList::iterator end
= m_pendingItems
.end();
356 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
357 if ((*it
).url() == item
.url()) {
358 m_pendingItems
.erase(it
);
363 m_dispatchedItems
.clear();
365 KFileItemList orderedItems
= m_pendingItems
;
366 orderItems(orderedItems
);
368 // Kill all suspended preview jobs. Usually when a preview job
369 // has been finished, slotPreviewJobFinished() clears all item queues.
370 // This is not wanted in this case, as a new job is created afterwards
371 // for m_pendingItems.
372 m_clearItemQueues
= false;
374 m_clearItemQueues
= true;
376 startPreviewJob(orderedItems
);
379 bool IconManager::isCutItem(const KFileItem
& item
) const
381 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
382 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
384 const KUrl itemUrl
= item
.url();
385 foreach (const KUrl
& url
, cutUrls
) {
386 if (url
== itemUrl
) {
394 void IconManager::applyCutItemEffect()
396 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
397 if (!KonqMimeData::decodeIsCutSelection(mimeData
)) {
402 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
403 const KUrl::List dirs
= dirLister
->directories();
404 foreach (const KUrl
& url
, dirs
) {
405 items
<< dirLister
->itemsForDir(url
);
408 foreach (const KFileItem
& item
, items
) {
409 if (isCutItem(item
)) {
410 const QModelIndex index
= m_dolphinModel
->indexForItem(item
);
411 const QVariant value
= m_dolphinModel
->data(index
, Qt::DecorationRole
);
412 if (value
.type() == QVariant::Icon
) {
413 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
414 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
415 QPixmap pixmap
= icon
.pixmap(actualSize
);
417 // remember current pixmap for the item to be able
418 // to restore it when other items get cut
420 cutItem
.url
= item
.url();
421 cutItem
.pixmap
= pixmap
;
422 m_cutItemsCache
.append(cutItem
);
424 // apply icon effect to the cut item
425 KIconEffect iconEffect
;
426 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
427 m_dolphinModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
433 bool IconManager::applyImageFrame(QPixmap
& icon
)
435 const QSize maxSize
= m_view
->iconSize();
436 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
437 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
438 ((icon
.width() > KIconLoader::SizeLarge
) ||
439 (icon
.height() > KIconLoader::SizeLarge
));
441 // the maximum size or the image itself is too small for a frame
446 const int doubleFrame
= frame
* 2;
448 // resize the icon to the maximum size minus the space required for the frame
449 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
452 const QPalette palette
= m_view
->palette();
453 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
454 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
455 const int width
= framedIcon
.width() - 1;
456 const int height
= framedIcon
.height() - 1;
458 painter
.begin(&framedIcon
);
459 painter
.drawPixmap(frame
, frame
, icon
);
462 painter
.setPen(palette
.color(QPalette::Text
));
463 painter
.setBrush(Qt::NoBrush
);
464 painter
.drawRect(0, 0, width
, height
);
465 painter
.drawRect(1, 1, width
- 2, height
- 2);
467 // dim image frame by 12.5 %
468 painter
.setPen(QColor(0, 0, 0, 32));
469 painter
.drawRect(frame
, frame
, width
- doubleFrame
, height
- doubleFrame
);
474 // provide an alpha channel for the border
475 QPixmap
alphaChannel(icon
.size());
478 QPainter
alphaPainter(&alphaChannel
);
479 alphaPainter
.setBrush(Qt::NoBrush
);
480 alphaPainter
.setPen(QColor(32, 32, 32));
481 alphaPainter
.drawRect(0, 0, width
, height
);
482 alphaPainter
.setPen(QColor(64, 64, 64));
483 alphaPainter
.drawRect(1, 1, width
- 2, height
- 2);
485 icon
.setAlphaChannel(alphaChannel
);
489 void IconManager::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
491 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
492 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::SmoothTransformation
);
496 void IconManager::startPreviewJob(const KFileItemList
& items
)
498 if (items
.count() == 0) {
502 const QSize size
= m_view
->iconSize();
503 KIO::PreviewJob
* job
= KIO::filePreview(items
, 128, 128);
504 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
505 this, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
506 connect(job
, SIGNAL(finished(KJob
*)),
507 this, SLOT(slotPreviewJobFinished(KJob
*)));
509 m_previewJobs
.append(job
);
510 m_previewTimer
->start(200);
513 void IconManager::killPreviewJobs()
515 foreach (KJob
* job
, m_previewJobs
) {
519 m_previewJobs
.clear();
522 void IconManager::orderItems(KFileItemList
& items
)
524 // Order the items in a way that the preview for the visible items
525 // is generated first, as this improves the feeled performance a lot.
527 // Implementation note: 2 different algorithms are used for the sorting.
528 // Algorithm 1 is faster when having a lot of items in comparison
529 // to the number of rows in the model. Algorithm 2 is faster
530 // when having quite less items in comparison to the number of rows in
531 // the model. Choosing the right algorithm is important when having directories
532 // with several hundreds or thousands of items.
534 const int itemCount
= items
.count();
535 const int rowCount
= m_proxyModel
->rowCount();
536 const QRect visibleArea
= m_view
->viewport()->rect();
538 if (itemCount
* 10 > rowCount
) {
539 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
540 // and check whether the received row is part of the item list.
541 for (int row
= 0; row
< rowCount
; ++row
) {
542 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
543 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
544 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
546 KFileItem item
= m_dolphinModel
->itemForIndex(dirIndex
); // O(1)
547 const KUrl url
= item
.url();
549 // check whether the item is part of the item list 'items'
551 for (int i
= 0; i
< itemCount
; ++i
) {
552 if (items
[i
].url() == url
) {
558 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
559 // The current item is (at least partly) visible. Move it
560 // to the front of the list, so that the preview is
561 // generated earlier.
562 items
.removeAt(index
);
563 items
.insert(0, item
);
564 ++m_pendingVisiblePreviews
;
568 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
569 // all items and receive the corresponding row from the item.
570 for (int i
= 0; i
< itemCount
; ++i
) {
571 const QModelIndex dirIndex
= m_dolphinModel
->indexForItem(items
[i
]); // O(n) (n = number of rows)
572 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
573 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
575 if (itemRect
.intersects(visibleArea
)) {
576 // The current item is (at least partly) visible. Move it
577 // to the front of the list, so that the preview is
578 // generated earlier.
579 items
.insert(0, items
[i
]);
580 items
.removeAt(i
+ 1);
581 ++m_pendingVisiblePreviews
;
587 #include "iconmanager.moc"