]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
faster + nicer (thanks to André Wöbbeking for the hint)
[dolphin.git] / src / iconmanager.cpp
1 /***************************************************************************
2 * Copyright (C) 2008 by Peter Penz <peter.penz@gmx.at> *
3 * *
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. *
8 * *
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. *
13 * *
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 ***************************************************************************/
19
20 #include "iconmanager.h"
21
22 #include "dolphinmodel.h"
23 #include "dolphinsortfilterproxymodel.h"
24
25 #include <kiconeffect.h>
26 #include <kio/previewjob.h>
27 #include <kdirlister.h>
28 #include <kmimetyperesolver.h>
29 #include <konqmimedata.h>
30
31 #include <QApplication>
32 #include <QAbstractItemView>
33 #include <QClipboard>
34 #include <QColor>
35 #include <QListView>
36 #include <QPainter>
37 #include <QScrollBar>
38 #include <QIcon>
39
40 /**
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.
44 *
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
52 *
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()
58 * signal.
59 */
60 class LayoutBlocker {
61 public:
62 LayoutBlocker(QAbstractItemView* view) :
63 m_uniformSizes(false),
64 m_view(qobject_cast<QListView*>(view))
65 {
66 if (m_view != 0) {
67 m_uniformSizes = m_view->uniformItemSizes();
68 m_view->setUniformItemSizes(true);
69 }
70 }
71
72 ~LayoutBlocker()
73 {
74 if (m_view != 0) {
75 m_view->setUniformItemSizes(m_uniformSizes);
76 }
77 }
78
79 private:
80 bool m_uniformSizes;
81 QListView* m_view;
82 };
83
84 IconManager::IconManager(QAbstractItemView* parent, DolphinSortFilterProxyModel* model) :
85 QObject(parent),
86 m_showPreview(false),
87 m_clearItemQueues(true),
88 m_view(parent),
89 m_previewTimer(0),
90 m_scrollAreaTimer(0),
91 m_previewJobs(),
92 m_dolphinModel(0),
93 m_proxyModel(model),
94 m_mimeTypeResolver(0),
95 m_cutItemsCache(),
96 m_previews(),
97 m_pendingItems(),
98 m_dispatchedItems()
99 {
100 Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size
101
102 m_dolphinModel = static_cast<DolphinModel*>(m_proxyModel->sourceModel());
103 connect(m_dolphinModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
104 this, SLOT(generatePreviews(const KFileItemList&)));
105
106 QClipboard* clipboard = QApplication::clipboard();
107 connect(clipboard, SIGNAL(dataChanged()),
108 this, SLOT(updateCutItems()));
109
110 m_previewTimer = new QTimer(this);
111 m_previewTimer->setSingleShot(true);
112 connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
113
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()));
127 }
128
129 IconManager::~IconManager()
130 {
131 killPreviewJobs();
132 m_pendingItems.clear();
133 m_dispatchedItems.clear();
134 if (m_mimeTypeResolver != 0) {
135 m_mimeTypeResolver->deleteLater();
136 m_mimeTypeResolver = 0;
137 }
138 }
139
140
141 void IconManager::setShowPreview(bool show)
142 {
143 if (m_showPreview != show) {
144 m_showPreview = show;
145 m_cutItemsCache.clear();
146 updateCutItems();
147 if (show) {
148 updatePreviews();
149 }
150 }
151
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);
160 }
161 }
162
163 void IconManager::updatePreviews()
164 {
165 if (!m_showPreview) {
166 return;
167 }
168
169 killPreviewJobs();
170 m_cutItemsCache.clear();
171 m_pendingItems.clear();
172 m_dispatchedItems.clear();
173
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);
180 }
181
182 generatePreviews(itemList);
183 updateCutItems();
184 }
185
186 void IconManager::cancelPreviews()
187 {
188 killPreviewJobs();
189 m_cutItemsCache.clear();
190 m_pendingItems.clear();
191 m_dispatchedItems.clear();
192 }
193
194 void IconManager::generatePreviews(const KFileItemList& items)
195 {
196 applyCutItemEffect();
197
198 if (!m_showPreview) {
199 return;
200 }
201
202 KFileItemList orderedItems = items;
203 orderItems(orderedItems);
204
205 foreach (const KFileItem& item, orderedItems) {
206 m_pendingItems.append(item);
207 }
208
209 startPreviewJob(orderedItems);
210 }
211
212 void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
213 {
214 ItemInfo preview;
215 preview.url = item.url();
216 preview.pixmap = pixmap;
217 m_previews.append(preview);
218
219 m_dispatchedItems.append(item);
220 }
221
222 void IconManager::slotPreviewJobFinished(KJob* job)
223 {
224 const int index = m_previewJobs.indexOf(job);
225 m_previewJobs.removeAt(index);
226
227 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
228 m_pendingItems.clear();
229 m_dispatchedItems.clear();
230 }
231 }
232
233 void IconManager::updateCutItems()
234 {
235 // restore the icons of all previously selected items to the
236 // original state...
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);
241 }
242 }
243 m_cutItemsCache.clear();
244
245 // ... and apply an item effect to all currently cut items
246 applyCutItemEffect();
247 }
248
249 void IconManager::dispatchPreviewQueue()
250 {
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.
257
258 int dispatchCount = 30;
259 if (dispatchCount > previewsCount) {
260 dispatchCount = previewsCount;
261 }
262
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();
268 }
269
270 previewsCount = m_previews.count();
271 }
272
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);
281 }
282 }
283
284 void IconManager::pausePreviews()
285 {
286 foreach (KJob* job, m_previewJobs) {
287 Q_ASSERT(job != 0);
288 job->suspend();
289 }
290 m_scrollAreaTimer->start();
291 }
292
293 void IconManager::resumePreviews()
294 {
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);
307 break;
308 }
309 }
310 }
311 m_dispatchedItems.clear();
312
313 KFileItemList orderedItems = m_pendingItems;
314 orderItems(orderedItems);
315
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;
321 killPreviewJobs();
322 m_clearItemQueues = true;
323
324 startPreviewJob(orderedItems);
325 }
326
327 void IconManager::replaceIcon(const KUrl& url, const QPixmap& pixmap)
328 {
329 Q_ASSERT(url.isValid());
330 if (!m_showPreview) {
331 // the preview has been canceled in the meantime
332 return;
333 }
334
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;
344 break;
345 }
346 }
347 if (isOldPreview) {
348 return;
349 }
350
351 const QModelIndex idx = m_dolphinModel->indexForUrl(url);
352 if (idx.isValid() && (idx.column() == 0)) {
353 QPixmap icon = pixmap;
354
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());
360 }
361
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()) {
371 (*it).pixmap = icon;
372 break;
373 }
374 }
375
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);
381 } else {
382 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
383 }
384 }
385 }
386
387 bool IconManager::isCutItem(const KFileItem& item) const
388 {
389 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
390 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
391
392 const KUrl itemUrl = item.url();
393 foreach (const KUrl& url, cutUrls) {
394 if (url == itemUrl) {
395 return true;
396 }
397 }
398
399 return false;
400 }
401
402 void IconManager::applyCutItemEffect()
403 {
404 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
405 if (!KonqMimeData::decodeIsCutSelection(mimeData)) {
406 return;
407 }
408
409 KFileItemList items;
410 KDirLister* dirLister = m_dolphinModel->dirLister();
411 const KUrl::List dirs = dirLister->directories();
412 foreach (const KUrl& url, dirs) {
413 items << dirLister->itemsForDir(url);
414 }
415
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);
424
425 // remember current pixmap for the item to be able
426 // to restore it when other items get cut
427 ItemInfo cutItem;
428 cutItem.url = item.url();
429 cutItem.pixmap = pixmap;
430 m_cutItemsCache.append(cutItem);
431
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);
436 }
437 }
438 }
439 }
440
441 bool IconManager::applyImageFrame(QPixmap& icon)
442 {
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));
448 if (!applyFrame) {
449 // the maximum size or the image itself is too small for a frame
450 return false;
451 }
452
453 const int frame = 4;
454 const int doubleFrame = frame * 2;
455
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));
458
459 QPainter painter;
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;
465
466 painter.begin(&framedIcon);
467 painter.drawPixmap(frame, frame, icon);
468
469 // add a border
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);
474
475 // dim image frame by 12.5 %
476 painter.setPen(QColor(0, 0, 0, 32));
477 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
478 painter.end();
479
480 icon = framedIcon;
481
482 // provide an alpha channel for the border
483 QPixmap alphaChannel(icon.size());
484 alphaChannel.fill();
485
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);
492
493 icon.setAlphaChannel(alphaChannel);
494 return true;
495 }
496
497 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
498 {
499 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
500 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
501 }
502 }
503
504 void IconManager::startPreviewJob(const KFileItemList& items)
505 {
506 if (items.count() == 0) {
507 return;
508 }
509
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*)));
516
517 m_previewJobs.append(job);
518 m_previewTimer->start(200);
519 }
520
521 void IconManager::killPreviewJobs()
522 {
523 foreach (KJob* job, m_previewJobs) {
524 Q_ASSERT(job != 0);
525 job->kill();
526 }
527 m_previewJobs.clear();
528 }
529
530 void IconManager::orderItems(KFileItemList& items)
531 {
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.
534 //
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.
541
542 const int itemCount = items.count();
543 const int rowCount = m_proxyModel->rowCount();
544 const QRect visibleArea = m_view->viewport()->rect();
545
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);
553
554 KFileItem item = m_dolphinModel->itemForIndex(dirIndex); // O(1)
555 const KUrl url = item.url();
556
557 // check whether the item is part of the item list 'items'
558 int index = -1;
559 for (int i = 0; i < itemCount; ++i) {
560 if (items[i].url() == url) {
561 index = i;
562 break;
563 }
564 }
565
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);
572 }
573 }
574 } else {
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);
581
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);
588 }
589 }
590 }
591 }
592
593 #include "iconmanager.moc"