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