]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
increase version number
[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_hasCutSelection(false),
89 m_pendingVisiblePreviews(0),
90 m_view(parent),
91 m_previewTimer(0),
92 m_scrollAreaTimer(0),
93 m_previewJobs(),
94 m_dolphinModel(0),
95 m_proxyModel(model),
96 m_mimeTypeResolver(0),
97 m_cutItemsCache(),
98 m_previews(),
99 m_pendingItems(),
100 m_dispatchedItems()
101 {
102 Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size
103
104 m_dolphinModel = static_cast<DolphinModel*>(m_proxyModel->sourceModel());
105 connect(m_dolphinModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
106 this, SLOT(generatePreviews(const KFileItemList&)));
107
108 QClipboard* clipboard = QApplication::clipboard();
109 connect(clipboard, SIGNAL(dataChanged()),
110 this, SLOT(updateCutItems()));
111
112 m_previewTimer = new QTimer(this);
113 m_previewTimer->setSingleShot(true);
114 connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
115
116 // Whenever the scrollbar values have been changed, the pending previews should
117 // be reordered in a way that the previews for the visible items are generated
118 // first. The reordering is done with a small delay, so that during moving the
119 // scrollbars the CPU load is kept low.
120 m_scrollAreaTimer = new QTimer(this);
121 m_scrollAreaTimer->setSingleShot(true);
122 m_scrollAreaTimer->setInterval(200);
123 connect(m_scrollAreaTimer, SIGNAL(timeout()),
124 this, SLOT(resumePreviews()));
125 connect(m_view->horizontalScrollBar(), SIGNAL(valueChanged(int)),
126 this, SLOT(pausePreviews()));
127 connect(m_view->verticalScrollBar(), SIGNAL(valueChanged(int)),
128 this, SLOT(pausePreviews()));
129 }
130
131 IconManager::~IconManager()
132 {
133 killPreviewJobs();
134 m_pendingItems.clear();
135 m_dispatchedItems.clear();
136 if (m_mimeTypeResolver != 0) {
137 m_mimeTypeResolver->deleteLater();
138 m_mimeTypeResolver = 0;
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 if (!m_showPreview) {
216 // the preview has been canceled in the meantime
217 return;
218 }
219 const KUrl url = item.url();
220
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;
230 break;
231 }
232 }
233 if (isOldPreview) {
234 return;
235 }
236
237 QPixmap icon = pixmap;
238
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());
243 }
244
245 if (m_hasCutSelection && isCutItem(item)) {
246 // Remember the current icon in the cache for cut items before
247 // the disabled effect is applied. This makes it possible restoring
248 // the uncut version again when cutting other items.
249 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
250 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
251 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
252 if ((*it).url == item.url()) {
253 (*it).pixmap = icon;
254 break;
255 }
256 }
257
258 // apply the disabled effect to the icon for marking it as "cut item"
259 // and apply the icon to the item
260 KIconEffect iconEffect;
261 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
262 }
263
264 // remember the preview and URL, so that it can be applied to the model
265 // in IconManager::dispatchPreviewQueue()
266 ItemInfo preview;
267 preview.url = url;
268 preview.pixmap = icon;
269 m_previews.append(preview);
270
271 m_dispatchedItems.append(item);
272 }
273
274 void IconManager::slotPreviewJobFinished(KJob* job)
275 {
276 const int index = m_previewJobs.indexOf(job);
277 m_previewJobs.removeAt(index);
278
279 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
280 m_pendingItems.clear();
281 m_dispatchedItems.clear();
282 m_pendingVisiblePreviews = 0;
283 QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection);
284 }
285 }
286
287 void IconManager::updateCutItems()
288 {
289 // restore the icons of all previously selected items to the
290 // original state...
291 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
292 const QModelIndex index = m_dolphinModel->indexForUrl(cutItem.url);
293 if (index.isValid()) {
294 m_dolphinModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
295 }
296 }
297 m_cutItemsCache.clear();
298
299 // ... and apply an item effect to all currently cut items
300 applyCutItemEffect();
301 }
302
303 void IconManager::dispatchPreviewQueue()
304 {
305 const int previewsCount = m_previews.count();
306 if (previewsCount > 0) {
307 // Applying the previews to the model must be done step by step
308 // in larger blocks: Applying a preview immediately when getting the signal
309 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
310 // of the view would be triggered for each single preview.
311 LayoutBlocker blocker(m_view);
312 for (int i = 0; i < previewsCount; ++i) {
313 const ItemInfo& preview = m_previews.first();
314
315 const QModelIndex idx = m_dolphinModel->indexForUrl(preview.url);
316 if (idx.isValid() && (idx.column() == 0)) {
317 m_dolphinModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole);
318 }
319
320 m_previews.pop_front();
321 if (m_pendingVisiblePreviews > 0) {
322 --m_pendingVisiblePreviews;
323 }
324 }
325 }
326
327 if (m_pendingVisiblePreviews > 0) {
328 // As long as there are pending previews for visible items, poll
329 // the preview queue each 200 ms. If there are no pending previews,
330 // the queue is dispatched in slotPreviewJobFinished().
331 m_previewTimer->start(200);
332 }
333 }
334
335 void IconManager::pausePreviews()
336 {
337 foreach (KJob* job, m_previewJobs) {
338 Q_ASSERT(job != 0);
339 job->suspend();
340 }
341 m_scrollAreaTimer->start();
342 }
343
344 void IconManager::resumePreviews()
345 {
346 // Before creating new preview jobs the m_pendingItems queue must be
347 // cleaned up by removing the already dispatched items. Implementation
348 // note: The order of the m_dispatchedItems queue and the m_pendingItems
349 // queue is usually equal. So even when having a lot of elements the
350 // nested loop is no performance bottle neck, as the inner loop is only
351 // entered once in most cases.
352 foreach (const KFileItem& item, m_dispatchedItems) {
353 KFileItemList::iterator begin = m_pendingItems.begin();
354 KFileItemList::iterator end = m_pendingItems.end();
355 for (KFileItemList::iterator it = begin; it != end; ++it) {
356 if ((*it).url() == item.url()) {
357 m_pendingItems.erase(it);
358 break;
359 }
360 }
361 }
362 m_dispatchedItems.clear();
363
364 m_pendingVisiblePreviews = 0;
365 dispatchPreviewQueue();
366
367 KFileItemList orderedItems = m_pendingItems;
368 orderItems(orderedItems);
369
370 // Kill all suspended preview jobs. Usually when a preview job
371 // has been finished, slotPreviewJobFinished() clears all item queues.
372 // This is not wanted in this case, as a new job is created afterwards
373 // for m_pendingItems.
374 m_clearItemQueues = false;
375 killPreviewJobs();
376 m_clearItemQueues = true;
377
378 startPreviewJob(orderedItems);
379 }
380
381 bool IconManager::isCutItem(const KFileItem& item) const
382 {
383 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
384 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
385
386 const KUrl itemUrl = item.url();
387 foreach (const KUrl& url, cutUrls) {
388 if (url == itemUrl) {
389 return true;
390 }
391 }
392
393 return false;
394 }
395
396 void IconManager::applyCutItemEffect()
397 {
398 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
399 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
400 if (!m_hasCutSelection) {
401 return;
402 }
403
404 KFileItemList items;
405 KDirLister* dirLister = m_dolphinModel->dirLister();
406 const KUrl::List dirs = dirLister->directories();
407 foreach (const KUrl& url, dirs) {
408 items << dirLister->itemsForDir(url);
409 }
410
411 foreach (const KFileItem& item, items) {
412 if (isCutItem(item)) {
413 const QModelIndex index = m_dolphinModel->indexForItem(item);
414 const QVariant value = m_dolphinModel->data(index, Qt::DecorationRole);
415 if (value.type() == QVariant::Icon) {
416 const QIcon icon(qvariant_cast<QIcon>(value));
417 const QSize actualSize = icon.actualSize(m_view->iconSize());
418 QPixmap pixmap = icon.pixmap(actualSize);
419
420 // remember current pixmap for the item to be able
421 // to restore it when other items get cut
422 ItemInfo cutItem;
423 cutItem.url = item.url();
424 cutItem.pixmap = pixmap;
425 m_cutItemsCache.append(cutItem);
426
427 // apply icon effect to the cut item
428 KIconEffect iconEffect;
429 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
430 m_dolphinModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
431 }
432 }
433 }
434 }
435
436 bool IconManager::applyImageFrame(QPixmap& icon)
437 {
438 const QSize maxSize = m_view->iconSize();
439 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
440 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
441 ((icon.width() > KIconLoader::SizeLarge) ||
442 (icon.height() > KIconLoader::SizeLarge));
443 if (!applyFrame) {
444 // the maximum size or the image itself is too small for a frame
445 return false;
446 }
447
448 const int frame = 4;
449 const int doubleFrame = frame * 2;
450
451 // resize the icon to the maximum size minus the space required for the frame
452 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
453
454 QPainter painter;
455 const QPalette palette = m_view->palette();
456 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
457 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
458 const int width = framedIcon.width() - 1;
459 const int height = framedIcon.height() - 1;
460
461 painter.begin(&framedIcon);
462 painter.drawPixmap(frame, frame, icon);
463
464 // add a border
465 painter.setPen(palette.color(QPalette::Text));
466 painter.setBrush(Qt::NoBrush);
467 painter.drawRect(0, 0, width, height);
468 painter.drawRect(1, 1, width - 2, height - 2);
469
470 // dim image frame by 12.5 %
471 painter.setPen(QColor(0, 0, 0, 32));
472 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
473 painter.end();
474
475 icon = framedIcon;
476
477 // provide an alpha channel for the border
478 QPixmap alphaChannel(icon.size());
479 alphaChannel.fill();
480
481 QPainter alphaPainter(&alphaChannel);
482 alphaPainter.setBrush(Qt::NoBrush);
483 alphaPainter.setPen(QColor(32, 32, 32));
484 alphaPainter.drawRect(0, 0, width, height);
485 alphaPainter.setPen(QColor(64, 64, 64));
486 alphaPainter.drawRect(1, 1, width - 2, height - 2);
487
488 icon.setAlphaChannel(alphaChannel);
489 return true;
490 }
491
492 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
493 {
494 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
495 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
496 }
497 }
498
499 void IconManager::startPreviewJob(const KFileItemList& items)
500 {
501 if (items.count() == 0) {
502 return;
503 }
504
505 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
506 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
507
508 const QSize size = m_view->iconSize();
509 KIO::PreviewJob* job = KIO::filePreview(items, 128, 128);
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*)));
514
515 m_previewJobs.append(job);
516 m_previewTimer->start(200);
517 }
518
519 void IconManager::killPreviewJobs()
520 {
521 foreach (KJob* job, m_previewJobs) {
522 Q_ASSERT(job != 0);
523 job->kill();
524 }
525 m_previewJobs.clear();
526 }
527
528 void IconManager::orderItems(KFileItemList& items)
529 {
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.
532 //
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.
539
540 const int itemCount = items.count();
541 const int rowCount = m_proxyModel->rowCount();
542 const QRect visibleArea = m_view->viewport()->rect();
543
544 int insertPos = 0;
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);
552
553 KFileItem item = m_dolphinModel->itemForIndex(dirIndex); // O(1)
554 const KUrl url = item.url();
555
556 // check whether the item is part of the item list 'items'
557 int index = -1;
558 for (int i = 0; i < itemCount; ++i) {
559 if (items[i].url() == url) {
560 index = i;
561 break;
562 }
563 }
564
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);
571 ++insertPos;
572 ++m_pendingVisiblePreviews;
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(insertPos, items[i]);
588 items.removeAt(i + 1);
589 ++insertPos;
590 ++m_pendingVisiblePreviews;
591 }
592 }
593 }
594 }
595
596 #include "iconmanager.moc"