]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
remember old setting of the uniformItemSizes property and restore it again (thanks...
[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(0)
65 {
66 if (view->inherits("QListView")) {
67 m_view = qobject_cast<QListView*>(view);
68 m_uniformSizes = m_view->uniformItemSizes();
69 m_view->setUniformItemSizes(true);
70 }
71 }
72
73 ~LayoutBlocker()
74 {
75 if (m_view != 0) {
76 m_view->setUniformItemSizes(m_uniformSizes);
77 }
78 }
79
80 private:
81 bool m_uniformSizes;
82 QListView* m_view;
83 };
84
85 IconManager::IconManager(QAbstractItemView* parent, DolphinSortFilterProxyModel* model) :
86 QObject(parent),
87 m_showPreview(false),
88 m_clearItemQueues(true),
89 m_view(parent),
90 m_previewTimer(0),
91 m_scrollAreaTimer(0),
92 m_previewJobs(),
93 m_dolphinModel(0),
94 m_proxyModel(model),
95 m_mimeTypeResolver(0),
96 m_cutItemsCache(),
97 m_previews(),
98 m_pendingItems(),
99 m_dispatchedItems()
100 {
101 Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size
102
103 m_dolphinModel = static_cast<DolphinModel*>(m_proxyModel->sourceModel());
104 connect(m_dolphinModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
105 this, SLOT(generatePreviews(const KFileItemList&)));
106
107 QClipboard* clipboard = QApplication::clipboard();
108 connect(clipboard, SIGNAL(dataChanged()),
109 this, SLOT(updateCutItems()));
110
111 m_previewTimer = new QTimer(this);
112 m_previewTimer->setSingleShot(true);
113 connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
114
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()));
128 }
129
130 IconManager::~IconManager()
131 {
132 killPreviewJobs();
133 m_pendingItems.clear();
134 m_dispatchedItems.clear();
135 if (m_mimeTypeResolver != 0) {
136 m_mimeTypeResolver->deleteLater();
137 m_mimeTypeResolver = 0;
138 }
139 }
140
141
142 void IconManager::setShowPreview(bool show)
143 {
144 if (m_showPreview != show) {
145 m_showPreview = show;
146 m_cutItemsCache.clear();
147 updateCutItems();
148 if (show) {
149 updatePreviews();
150 }
151 }
152
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);
161 }
162 }
163
164 void IconManager::updatePreviews()
165 {
166 if (!m_showPreview) {
167 return;
168 }
169
170 killPreviewJobs();
171 m_cutItemsCache.clear();
172 m_pendingItems.clear();
173 m_dispatchedItems.clear();
174
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);
181 }
182
183 generatePreviews(itemList);
184 updateCutItems();
185 }
186
187 void IconManager::cancelPreviews()
188 {
189 killPreviewJobs();
190 m_cutItemsCache.clear();
191 m_pendingItems.clear();
192 m_dispatchedItems.clear();
193 }
194
195 void IconManager::generatePreviews(const KFileItemList& items)
196 {
197 applyCutItemEffect();
198
199 if (!m_showPreview) {
200 return;
201 }
202
203 KFileItemList orderedItems = items;
204 orderItems(orderedItems);
205
206 foreach (const KFileItem& item, orderedItems) {
207 m_pendingItems.append(item);
208 }
209
210 startPreviewJob(orderedItems);
211 }
212
213 void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
214 {
215 ItemInfo preview;
216 preview.url = item.url();
217 preview.pixmap = pixmap;
218 m_previews.append(preview);
219
220 m_dispatchedItems.append(item);
221 }
222
223 void IconManager::slotPreviewJobFinished(KJob* job)
224 {
225 const int index = m_previewJobs.indexOf(job);
226 m_previewJobs.removeAt(index);
227
228 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
229 m_pendingItems.clear();
230 m_dispatchedItems.clear();
231 }
232 }
233
234 void IconManager::updateCutItems()
235 {
236 // restore the icons of all previously selected items to the
237 // original state...
238 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
239 const QModelIndex index = m_dolphinModel->indexForUrl(cutItem.url);
240 if (index.isValid()) {
241 m_dolphinModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
242 }
243 }
244 m_cutItemsCache.clear();
245
246 // ... and apply an item effect to all currently cut items
247 applyCutItemEffect();
248 }
249
250 void IconManager::dispatchPreviewQueue()
251 {
252 int previewsCount = m_previews.count();
253 if (previewsCount > 0) {
254 // Applying the previews to the model must be done step by step
255 // in larger blocks: Applying a preview immediately when getting the signal
256 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
257 // of the view would be triggered for each single preview.
258
259 int dispatchCount = 30;
260 if (dispatchCount > previewsCount) {
261 dispatchCount = previewsCount;
262 }
263
264 LayoutBlocker blocker(m_view);
265 for (int i = 0; i < dispatchCount; ++i) {
266 const ItemInfo& preview = m_previews.first();
267 replaceIcon(preview.url, preview.pixmap);
268 m_previews.pop_front();
269 }
270
271 previewsCount = m_previews.count();
272 }
273
274 const bool workingPreviewJobs = (m_previewJobs.count() > 0);
275 if (workingPreviewJobs) {
276 // poll for previews as long as not all preview jobs are finished
277 m_previewTimer->start(200);
278 } else if (previewsCount > 0) {
279 // all preview jobs are finished but there are still pending previews
280 // in the queue -> poll more aggressively
281 m_previewTimer->start(10);
282 }
283 }
284
285 void IconManager::pausePreviews()
286 {
287 foreach (KJob* job, m_previewJobs) {
288 Q_ASSERT(job != 0);
289 job->suspend();
290 }
291 m_scrollAreaTimer->start();
292 }
293
294 void IconManager::resumePreviews()
295 {
296 // Before creating new preview jobs the m_pendingItems queue must be
297 // cleaned up by removing the already dispatched items. Implementation
298 // note: The order of the m_dispatchedItems queue and the m_pendingItems
299 // queue is usually equal. So even when having a lot of elements the
300 // nested loop is no performance bottle neck, as the inner loop is only
301 // entered once in most cases.
302 foreach (const KFileItem& item, m_dispatchedItems) {
303 KFileItemList::iterator begin = m_pendingItems.begin();
304 KFileItemList::iterator end = m_pendingItems.end();
305 for (KFileItemList::iterator it = begin; it != end; ++it) {
306 if ((*it).url() == item.url()) {
307 m_pendingItems.erase(it);
308 break;
309 }
310 }
311 }
312 m_dispatchedItems.clear();
313
314 KFileItemList orderedItems = m_pendingItems;
315 orderItems(orderedItems);
316
317 // Kill all suspended preview jobs. Usually when a preview job
318 // has been finished, slotPreviewJobFinished() clears all item queues.
319 // This is not wanted in this case, as a new job is created afterwards
320 // for m_pendingItems.
321 m_clearItemQueues = false;
322 killPreviewJobs();
323 m_clearItemQueues = true;
324
325 startPreviewJob(orderedItems);
326 }
327
328 void IconManager::replaceIcon(const KUrl& url, const QPixmap& pixmap)
329 {
330 Q_ASSERT(url.isValid());
331 if (!m_showPreview) {
332 // the preview has been canceled in the meantime
333 return;
334 }
335
336 // check whether the item is part of the directory lister (it is possible
337 // that a preview from an old directory lister is received)
338 KDirLister* dirLister = m_dolphinModel->dirLister();
339 bool isOldPreview = true;
340 const KUrl::List dirs = dirLister->directories();
341 const QString itemDir = url.directory();
342 foreach (const KUrl& url, dirs) {
343 if (url.path() == itemDir) {
344 isOldPreview = false;
345 break;
346 }
347 }
348 if (isOldPreview) {
349 return;
350 }
351
352 const QModelIndex idx = m_dolphinModel->indexForUrl(url);
353 if (idx.isValid() && (idx.column() == 0)) {
354 QPixmap icon = pixmap;
355
356 const KFileItem item = m_dolphinModel->itemForIndex(idx);
357 const QString mimeType = item.mimetype();
358 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
359 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
360 limitToSize(icon, m_view->iconSize());
361 }
362
363 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
364 if (KonqMimeData::decodeIsCutSelection(mimeData) && isCutItem(item)) {
365 // Remember the current icon in the cache for cut items before
366 // the disabled effect is applied. This makes it possible restoring
367 // the uncut version again when cutting other items.
368 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
369 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
370 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
371 if ((*it).url == item.url()) {
372 (*it).pixmap = icon;
373 break;
374 }
375 }
376
377 // apply the disabled effect to the icon for marking it as "cut item"
378 // and apply the icon to the item
379 KIconEffect iconEffect;
380 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
381 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
382 } else {
383 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
384 }
385 }
386 }
387
388 bool IconManager::isCutItem(const KFileItem& item) const
389 {
390 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
391 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
392
393 const KUrl itemUrl = item.url();
394 foreach (const KUrl& url, cutUrls) {
395 if (url == itemUrl) {
396 return true;
397 }
398 }
399
400 return false;
401 }
402
403 void IconManager::applyCutItemEffect()
404 {
405 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
406 if (!KonqMimeData::decodeIsCutSelection(mimeData)) {
407 return;
408 }
409
410 KFileItemList items;
411 KDirLister* dirLister = m_dolphinModel->dirLister();
412 const KUrl::List dirs = dirLister->directories();
413 foreach (const KUrl& url, dirs) {
414 items << dirLister->itemsForDir(url);
415 }
416
417 foreach (const KFileItem& item, items) {
418 if (isCutItem(item)) {
419 const QModelIndex index = m_dolphinModel->indexForItem(item);
420 const QVariant value = m_dolphinModel->data(index, Qt::DecorationRole);
421 if (value.type() == QVariant::Icon) {
422 const QIcon icon(qvariant_cast<QIcon>(value));
423 const QSize actualSize = icon.actualSize(m_view->iconSize());
424 QPixmap pixmap = icon.pixmap(actualSize);
425
426 // remember current pixmap for the item to be able
427 // to restore it when other items get cut
428 ItemInfo cutItem;
429 cutItem.url = item.url();
430 cutItem.pixmap = pixmap;
431 m_cutItemsCache.append(cutItem);
432
433 // apply icon effect to the cut item
434 KIconEffect iconEffect;
435 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
436 m_dolphinModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
437 }
438 }
439 }
440 }
441
442 bool IconManager::applyImageFrame(QPixmap& icon)
443 {
444 const QSize maxSize = m_view->iconSize();
445 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
446 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
447 ((icon.width() > KIconLoader::SizeLarge) ||
448 (icon.height() > KIconLoader::SizeLarge));
449 if (!applyFrame) {
450 // the maximum size or the image itself is too small for a frame
451 return false;
452 }
453
454 const int frame = 4;
455 const int doubleFrame = frame * 2;
456
457 // resize the icon to the maximum size minus the space required for the frame
458 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
459
460 QPainter painter;
461 const QPalette palette = m_view->palette();
462 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
463 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
464 const int width = framedIcon.width() - 1;
465 const int height = framedIcon.height() - 1;
466
467 painter.begin(&framedIcon);
468 painter.drawPixmap(frame, frame, icon);
469
470 // add a border
471 painter.setPen(palette.color(QPalette::Text));
472 painter.setBrush(Qt::NoBrush);
473 painter.drawRect(0, 0, width, height);
474 painter.drawRect(1, 1, width - 2, height - 2);
475
476 // dim image frame by 12.5 %
477 painter.setPen(QColor(0, 0, 0, 32));
478 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
479 painter.end();
480
481 icon = framedIcon;
482
483 // provide an alpha channel for the border
484 QPixmap alphaChannel(icon.size());
485 alphaChannel.fill();
486
487 QPainter alphaPainter(&alphaChannel);
488 alphaPainter.setBrush(Qt::NoBrush);
489 alphaPainter.setPen(QColor(32, 32, 32));
490 alphaPainter.drawRect(0, 0, width, height);
491 alphaPainter.setPen(QColor(64, 64, 64));
492 alphaPainter.drawRect(1, 1, width - 2, height - 2);
493
494 icon.setAlphaChannel(alphaChannel);
495 return true;
496 }
497
498 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
499 {
500 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
501 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
502 }
503 }
504
505 void IconManager::startPreviewJob(const KFileItemList& items)
506 {
507 if (items.count() == 0) {
508 return;
509 }
510
511 const QSize size = m_view->iconSize();
512 KIO::PreviewJob* job = KIO::filePreview(items, 128, 128);
513 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
514 this, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&)));
515 connect(job, SIGNAL(finished(KJob*)),
516 this, SLOT(slotPreviewJobFinished(KJob*)));
517
518 m_previewJobs.append(job);
519 m_previewTimer->start(200);
520 }
521
522 void IconManager::killPreviewJobs()
523 {
524 foreach (KJob* job, m_previewJobs) {
525 Q_ASSERT(job != 0);
526 job->kill();
527 }
528 m_previewJobs.clear();
529 }
530
531 void IconManager::orderItems(KFileItemList& items)
532 {
533 // Order the items in a way that the preview for the visible items
534 // is generated first, as this improves the feeled performance a lot.
535 //
536 // Implementation note: 2 different algorithms are used for the sorting.
537 // Algorithm 1 is faster when having a lot of items in comparison
538 // to the number of rows in the model. Algorithm 2 is faster
539 // when having quite less items in comparison to the number of rows in
540 // the model. Choosing the right algorithm is important when having directories
541 // with several hundreds or thousands of items.
542
543 const int itemCount = items.count();
544 const int rowCount = m_proxyModel->rowCount();
545 const QRect visibleArea = m_view->viewport()->rect();
546
547 if (itemCount * 10 > rowCount) {
548 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
549 // and check whether the received row is part of the item list.
550 for (int row = 0; row < rowCount; ++row) {
551 const QModelIndex proxyIndex = m_proxyModel->index(row, 0);
552 const QRect itemRect = m_view->visualRect(proxyIndex);
553 const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex);
554
555 KFileItem item = m_dolphinModel->itemForIndex(dirIndex); // O(1)
556 const KUrl url = item.url();
557
558 // check whether the item is part of the item list 'items'
559 int index = -1;
560 for (int i = 0; i < itemCount; ++i) {
561 if (items[i].url() == url) {
562 index = i;
563 break;
564 }
565 }
566
567 if ((index > 0) && itemRect.intersects(visibleArea)) {
568 // The current item is (at least partly) visible. Move it
569 // to the front of the list, so that the preview is
570 // generated earlier.
571 items.removeAt(index);
572 items.insert(0, item);
573 }
574 }
575 } else {
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_dolphinModel->indexForItem(items[i]); // O(n) (n = number of rows)
580 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
581 const QRect itemRect = m_view->visualRect(proxyIndex);
582
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(0, items[i]);
588 items.removeAt(i + 1);
589 }
590 }
591 }
592 }
593
594 #include "iconmanager.moc"