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),
94 m_mimeTypeResolver(0),
100 Q_ASSERT(m_view
->iconSize().isValid()); // each view must provide its current icon size
102 m_dolphinModel
= static_cast<DolphinModel
*>(m_proxyModel
->sourceModel());
103 connect(m_dolphinModel
->dirLister(), SIGNAL(newItems(const KFileItemList
&)),
104 this, SLOT(generatePreviews(const KFileItemList
&)));
106 QClipboard
* clipboard
= QApplication::clipboard();
107 connect(clipboard
, SIGNAL(dataChanged()),
108 this, SLOT(updateCutItems()));
110 m_previewTimer
= new QTimer(this);
111 m_previewTimer
->setSingleShot(true);
112 connect(m_previewTimer
, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
114 // Whenever the scrollbar values have been changed, the pending previews should
115 // be reordered in a way that the previews for the visible items are generated
116 // first. The reordering is done with a small delay, so that during moving the
117 // scrollbars the CPU load is kept low.
118 m_scrollAreaTimer
= new QTimer(this);
119 m_scrollAreaTimer
->setSingleShot(true);
120 m_scrollAreaTimer
->setInterval(200);
121 connect(m_scrollAreaTimer
, SIGNAL(timeout()),
122 this, SLOT(resumePreviews()));
123 connect(m_view
->horizontalScrollBar(), SIGNAL(valueChanged(int)),
124 this, SLOT(pausePreviews()));
125 connect(m_view
->verticalScrollBar(), SIGNAL(valueChanged(int)),
126 this, SLOT(pausePreviews()));
129 IconManager::~IconManager()
132 m_pendingItems
.clear();
133 m_dispatchedItems
.clear();
134 if (m_mimeTypeResolver
!= 0) {
135 m_mimeTypeResolver
->deleteLater();
136 m_mimeTypeResolver
= 0;
141 void IconManager::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_dolphinModel
);
163 void IconManager::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_dolphinModel
->rowCount();
176 for (int row
= 0; row
< rowCount
; ++row
) {
177 const QModelIndex index
= m_dolphinModel
->index(row
, 0);
178 KFileItem item
= m_dolphinModel
->itemForIndex(index
);
179 itemList
.append(item
);
182 generatePreviews(itemList
);
186 void IconManager::cancelPreviews()
189 m_cutItemsCache
.clear();
190 m_pendingItems
.clear();
191 m_dispatchedItems
.clear();
194 void IconManager::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 IconManager::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
215 preview
.url
= item
.url();
216 preview
.pixmap
= pixmap
;
217 m_previews
.append(preview
);
219 m_dispatchedItems
.append(item
);
222 void IconManager::slotPreviewJobFinished(KJob
* job
)
224 const int index
= m_previewJobs
.indexOf(job
);
225 m_previewJobs
.removeAt(index
);
227 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
228 m_pendingItems
.clear();
229 m_dispatchedItems
.clear();
233 void IconManager::updateCutItems()
235 // restore the icons of all previously selected items to the
237 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
238 const QModelIndex index
= m_dolphinModel
->indexForUrl(cutItem
.url
);
239 if (index
.isValid()) {
240 m_dolphinModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
243 m_cutItemsCache
.clear();
245 // ... and apply an item effect to all currently cut items
246 applyCutItemEffect();
249 void IconManager::dispatchPreviewQueue()
251 int previewsCount
= m_previews
.count();
252 if (previewsCount
> 0) {
253 // Applying the previews to the model must be done step by step
254 // in larger blocks: Applying a preview immediately when getting the signal
255 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
256 // of the view would be triggered for each single preview.
258 int dispatchCount
= 30;
259 if (dispatchCount
> previewsCount
) {
260 dispatchCount
= previewsCount
;
263 LayoutBlocker
blocker(m_view
);
264 for (int i
= 0; i
< dispatchCount
; ++i
) {
265 const ItemInfo
& preview
= m_previews
.first();
266 replaceIcon(preview
.url
, preview
.pixmap
);
267 m_previews
.pop_front();
270 previewsCount
= m_previews
.count();
273 const bool workingPreviewJobs
= (m_previewJobs
.count() > 0);
274 if (workingPreviewJobs
) {
275 // poll for previews as long as not all preview jobs are finished
276 m_previewTimer
->start(200);
277 } else if (previewsCount
> 0) {
278 // all preview jobs are finished but there are still pending previews
279 // in the queue -> poll more aggressively
280 m_previewTimer
->start(10);
284 void IconManager::pausePreviews()
286 foreach (KJob
* job
, m_previewJobs
) {
290 m_scrollAreaTimer
->start();
293 void IconManager::resumePreviews()
295 // Before creating new preview jobs the m_pendingItems queue must be
296 // cleaned up by removing the already dispatched items. Implementation
297 // note: The order of the m_dispatchedItems queue and the m_pendingItems
298 // queue is usually equal. So even when having a lot of elements the
299 // nested loop is no performance bottle neck, as the inner loop is only
300 // entered once in most cases.
301 foreach (const KFileItem
& item
, m_dispatchedItems
) {
302 KFileItemList::iterator begin
= m_pendingItems
.begin();
303 KFileItemList::iterator end
= m_pendingItems
.end();
304 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
305 if ((*it
).url() == item
.url()) {
306 m_pendingItems
.erase(it
);
311 m_dispatchedItems
.clear();
313 KFileItemList orderedItems
= m_pendingItems
;
314 orderItems(orderedItems
);
316 // Kill all suspended preview jobs. Usually when a preview job
317 // has been finished, slotPreviewJobFinished() clears all item queues.
318 // This is not wanted in this case, as a new job is created afterwards
319 // for m_pendingItems.
320 m_clearItemQueues
= false;
322 m_clearItemQueues
= true;
324 startPreviewJob(orderedItems
);
327 void IconManager::replaceIcon(const KUrl
& url
, const QPixmap
& pixmap
)
329 Q_ASSERT(url
.isValid());
330 if (!m_showPreview
) {
331 // the preview has been canceled in the meantime
335 // check whether the item is part of the directory lister (it is possible
336 // that a preview from an old directory lister is received)
337 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
338 bool isOldPreview
= true;
339 const KUrl::List dirs
= dirLister
->directories();
340 const QString itemDir
= url
.directory();
341 foreach (const KUrl
& url
, dirs
) {
342 if (url
.path() == itemDir
) {
343 isOldPreview
= false;
351 const QModelIndex idx
= m_dolphinModel
->indexForUrl(url
);
352 if (idx
.isValid() && (idx
.column() == 0)) {
353 QPixmap icon
= pixmap
;
355 const KFileItem item
= m_dolphinModel
->itemForIndex(idx
);
356 const QString mimeType
= item
.mimetype();
357 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
358 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
359 limitToSize(icon
, m_view
->iconSize());
362 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
363 if (KonqMimeData::decodeIsCutSelection(mimeData
) && isCutItem(item
)) {
364 // Remember the current icon in the cache for cut items before
365 // the disabled effect is applied. This makes it possible restoring
366 // the uncut version again when cutting other items.
367 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
368 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
369 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
370 if ((*it
).url
== item
.url()) {
376 // apply the disabled effect to the icon for marking it as "cut item"
377 // and apply the icon to the item
378 KIconEffect iconEffect
;
379 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
380 m_dolphinModel
->setData(idx
, QIcon(icon
), Qt::DecorationRole
);
382 m_dolphinModel
->setData(idx
, QIcon(icon
), Qt::DecorationRole
);
387 bool IconManager::isCutItem(const KFileItem
& item
) const
389 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
390 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
392 const KUrl itemUrl
= item
.url();
393 foreach (const KUrl
& url
, cutUrls
) {
394 if (url
== itemUrl
) {
402 void IconManager::applyCutItemEffect()
404 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
405 if (!KonqMimeData::decodeIsCutSelection(mimeData
)) {
410 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
411 const KUrl::List dirs
= dirLister
->directories();
412 foreach (const KUrl
& url
, dirs
) {
413 items
<< dirLister
->itemsForDir(url
);
416 foreach (const KFileItem
& item
, items
) {
417 if (isCutItem(item
)) {
418 const QModelIndex index
= m_dolphinModel
->indexForItem(item
);
419 const QVariant value
= m_dolphinModel
->data(index
, Qt::DecorationRole
);
420 if (value
.type() == QVariant::Icon
) {
421 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
422 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
423 QPixmap pixmap
= icon
.pixmap(actualSize
);
425 // remember current pixmap for the item to be able
426 // to restore it when other items get cut
428 cutItem
.url
= item
.url();
429 cutItem
.pixmap
= pixmap
;
430 m_cutItemsCache
.append(cutItem
);
432 // apply icon effect to the cut item
433 KIconEffect iconEffect
;
434 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
435 m_dolphinModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
441 bool IconManager::applyImageFrame(QPixmap
& icon
)
443 const QSize maxSize
= m_view
->iconSize();
444 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
445 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
446 ((icon
.width() > KIconLoader::SizeLarge
) ||
447 (icon
.height() > KIconLoader::SizeLarge
));
449 // the maximum size or the image itself is too small for a frame
454 const int doubleFrame
= frame
* 2;
456 // resize the icon to the maximum size minus the space required for the frame
457 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
460 const QPalette palette
= m_view
->palette();
461 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
462 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
463 const int width
= framedIcon
.width() - 1;
464 const int height
= framedIcon
.height() - 1;
466 painter
.begin(&framedIcon
);
467 painter
.drawPixmap(frame
, frame
, icon
);
470 painter
.setPen(palette
.color(QPalette::Text
));
471 painter
.setBrush(Qt::NoBrush
);
472 painter
.drawRect(0, 0, width
, height
);
473 painter
.drawRect(1, 1, width
- 2, height
- 2);
475 // dim image frame by 12.5 %
476 painter
.setPen(QColor(0, 0, 0, 32));
477 painter
.drawRect(frame
, frame
, width
- doubleFrame
, height
- doubleFrame
);
482 // provide an alpha channel for the border
483 QPixmap
alphaChannel(icon
.size());
486 QPainter
alphaPainter(&alphaChannel
);
487 alphaPainter
.setBrush(Qt::NoBrush
);
488 alphaPainter
.setPen(QColor(32, 32, 32));
489 alphaPainter
.drawRect(0, 0, width
, height
);
490 alphaPainter
.setPen(QColor(64, 64, 64));
491 alphaPainter
.drawRect(1, 1, width
- 2, height
- 2);
493 icon
.setAlphaChannel(alphaChannel
);
497 void IconManager::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
499 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
500 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::SmoothTransformation
);
504 void IconManager::startPreviewJob(const KFileItemList
& items
)
506 if (items
.count() == 0) {
510 const QSize size
= m_view
->iconSize();
511 KIO::PreviewJob
* job
= KIO::filePreview(items
, 128, 128);
512 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
513 this, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
514 connect(job
, SIGNAL(finished(KJob
*)),
515 this, SLOT(slotPreviewJobFinished(KJob
*)));
517 m_previewJobs
.append(job
);
518 m_previewTimer
->start(200);
521 void IconManager::killPreviewJobs()
523 foreach (KJob
* job
, m_previewJobs
) {
527 m_previewJobs
.clear();
530 void IconManager::orderItems(KFileItemList
& items
)
532 // Order the items in a way that the preview for the visible items
533 // is generated first, as this improves the feeled performance a lot.
535 // Implementation note: 2 different algorithms are used for the sorting.
536 // Algorithm 1 is faster when having a lot of items in comparison
537 // to the number of rows in the model. Algorithm 2 is faster
538 // when having quite less items in comparison to the number of rows in
539 // the model. Choosing the right algorithm is important when having directories
540 // with several hundreds or thousands of items.
542 const int itemCount
= items
.count();
543 const int rowCount
= m_proxyModel
->rowCount();
544 const QRect visibleArea
= m_view
->viewport()->rect();
546 if (itemCount
* 10 > rowCount
) {
547 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
548 // and check whether the received row is part of the item list.
549 for (int row
= 0; row
< rowCount
; ++row
) {
550 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
551 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
552 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
554 KFileItem item
= m_dolphinModel
->itemForIndex(dirIndex
); // O(1)
555 const KUrl url
= item
.url();
557 // check whether the item is part of the item list 'items'
559 for (int i
= 0; i
< itemCount
; ++i
) {
560 if (items
[i
].url() == url
) {
566 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
567 // The current item is (at least partly) visible. Move it
568 // to the front of the list, so that the preview is
569 // generated earlier.
570 items
.removeAt(index
);
571 items
.insert(0, item
);
575 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
576 // all items and receive the corresponding row from the item.
577 for (int i
= 0; i
< itemCount
; ++i
) {
578 const QModelIndex dirIndex
= m_dolphinModel
->indexForItem(items
[i
]); // O(n) (n = number of rows)
579 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
580 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
582 if (itemRect
.intersects(visibleArea
)) {
583 // The current item is (at least partly) visible. Move it
584 // to the front of the list, so that the preview is
585 // generated earlier.
586 items
.insert(0, items
[i
]);
587 items
.removeAt(i
+ 1);
593 #include "iconmanager.moc"