]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
Improve the performance of the code part which checks which items are visible. Althou...
[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 // Order the items in a way that the preview for the visible items
158 // is generated first, as this improves the feeled performance a lot.
159 // Implementation note: using KDirModel::itemForUrl() would lead to a more
160 // readable code, but it is a lot slower in comparison to itemListContains().
161 const QRect visibleArea = m_view->viewport()->rect();
162 KFileItemList orderedItems;
163 const int rowCount = m_proxyModel->rowCount();
164 for (int row = 0; row < rowCount; ++row) {
165 const QModelIndex proxyIndex = m_proxyModel->index(row, 0);
166 const QRect itemRect = m_view->visualRect(proxyIndex);
167 const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex);
168 KFileItem item = m_dolphinModel->itemForIndex(dirIndex);
169 const KUrl url = item.url();
170 if (itemListContains(items, url)) {
171 if (itemRect.intersects(visibleArea)) {
172 orderedItems.insert(0, item);
173 m_pendingItems.insert(0, url);
174 } else {
175 orderedItems.append(item);
176 m_pendingItems.append(url);
177 }
178 }
179 }
180
181 startPreviewJob(orderedItems);
182 }
183
184 void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
185 {
186 ItemInfo preview;
187 preview.url = item.url();
188 preview.pixmap = pixmap;
189 m_previews.append(preview);
190
191 m_dispatchedItems.append(item.url());
192 }
193
194 void IconManager::slotPreviewJobFinished(KJob* job)
195 {
196 const int index = m_previewJobs.indexOf(job);
197 m_previewJobs.removeAt(index);
198
199 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
200 m_pendingItems.clear();
201 m_dispatchedItems.clear();
202 }
203 }
204
205 void IconManager::updateCutItems()
206 {
207 // restore the icons of all previously selected items to the
208 // original state...
209 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
210 const QModelIndex index = m_dolphinModel->indexForUrl(cutItem.url);
211 if (index.isValid()) {
212 m_dolphinModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
213 }
214 }
215 m_cutItemsCache.clear();
216
217 // ... and apply an item effect to all currently cut items
218 applyCutItemEffect();
219 }
220
221 void IconManager::dispatchPreviewQueue()
222 {
223 int previewsCount = m_previews.count();
224 if (previewsCount > 0) {
225 // Applying the previews to the model must be done step by step
226 // in larger blocks: Applying a preview immediately when getting the signal
227 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
228 // of the view would be triggered for each single preview.
229
230 int dispatchCount = 30;
231 if (dispatchCount > previewsCount) {
232 dispatchCount = previewsCount;
233 }
234
235 for (int i = 0; i < dispatchCount; ++i) {
236 const ItemInfo& preview = m_previews.first();
237 replaceIcon(preview.url, preview.pixmap);
238 m_previews.pop_front();
239 }
240
241 previewsCount = m_previews.count();
242 }
243
244 const bool workingPreviewJobs = (m_previewJobs.count() > 0);
245 if (workingPreviewJobs) {
246 // poll for previews as long as not all preview jobs are finished
247 m_previewTimer->start(200);
248 } else if (previewsCount > 0) {
249 // all preview jobs are finished but there are still pending previews
250 // in the queue -> poll more aggressively
251 m_previewTimer->start(10);
252 }
253 }
254
255 void IconManager::pausePreviews()
256 {
257 foreach (KJob* job, m_previewJobs) {
258 Q_ASSERT(job != 0);
259 job->suspend();
260 }
261 m_scrollAreaTimer->start();
262 }
263
264 void IconManager::resumePreviews()
265 {
266 // Before creating new preview jobs the m_pendingItems queue must be
267 // cleaned up by removing the already dispatched items. Implementation
268 // note: The order of the m_dispatchedItems queue and the m_pendingItems
269 // queue is usually equal. So even when having a lot of elements the
270 // nested loop is no performance bottle neck, as the inner loop is only
271 // entered once in most cases.
272 foreach (const KUrl& url, m_dispatchedItems) {
273 QList<KUrl>::iterator begin = m_pendingItems.begin();
274 QList<KUrl>::iterator end = m_pendingItems.end();
275 for (QList<KUrl>::iterator it = begin; it != end; ++it) {
276 if ((*it) == url) {
277 m_pendingItems.erase(it);
278 break;
279 }
280 }
281 }
282 m_dispatchedItems.clear();
283
284 // Create a new preview job for the remaining items.
285 // Order the items in a way that the preview for the visible items
286 // is generated first, as this improves the feeled performance a lot.
287 // Implementation note: using KDirModel::itemForUrl() would lead to a more
288 // readable code, but it is a lot slower in comparison
289 // to m_pendingItems.contains().
290 const QRect visibleArea = m_view->viewport()->rect();
291 KFileItemList orderedItems;
292
293 const int rowCount = m_proxyModel->rowCount();
294 for (int row = 0; row < rowCount; ++row) {
295 const QModelIndex proxyIndex = m_proxyModel->index(row, 0);
296 const QRect itemRect = m_view->visualRect(proxyIndex);
297 const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex);
298 KFileItem item = m_dolphinModel->itemForIndex(dirIndex);
299 const KUrl url = item.url();
300 if (m_pendingItems.contains(url)) {
301 if (itemRect.intersects(visibleArea)) {
302 orderedItems.insert(0, item);
303 } else {
304 orderedItems.append(item);
305 }
306 }
307 }
308
309 // Kill all suspended preview jobs. Usually when a preview job
310 // has been finished, slotPreviewJobFinished() clears all item queues.
311 // This is not wanted in this case, as a new job is created afterwards
312 // for m_pendingItems.
313 m_clearItemQueues = false;
314 killPreviewJobs();
315 m_clearItemQueues = true;
316
317 startPreviewJob(orderedItems);
318 }
319
320 void IconManager::replaceIcon(const KUrl& url, const QPixmap& pixmap)
321 {
322 Q_ASSERT(url.isValid());
323 if (!m_showPreview) {
324 // the preview has been canceled in the meantime
325 return;
326 }
327
328 // check whether the item is part of the directory lister (it is possible
329 // that a preview from an old directory lister is received)
330 KDirLister* dirLister = m_dolphinModel->dirLister();
331 bool isOldPreview = true;
332 const KUrl::List dirs = dirLister->directories();
333 const QString itemDir = url.directory();
334 foreach (const KUrl& url, dirs) {
335 if (url.path() == itemDir) {
336 isOldPreview = false;
337 break;
338 }
339 }
340 if (isOldPreview) {
341 return;
342 }
343
344 const QModelIndex idx = m_dolphinModel->indexForUrl(url);
345 if (idx.isValid() && (idx.column() == 0)) {
346 QPixmap icon = pixmap;
347
348 const KFileItem item = m_dolphinModel->itemForIndex(idx);
349 const QString mimeType = item.mimetype();
350 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
351 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
352 limitToSize(icon, m_view->iconSize());
353 }
354
355 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
356 if (KonqMimeData::decodeIsCutSelection(mimeData) && isCutItem(item)) {
357 // Remember the current icon in the cache for cut items before
358 // the disabled effect is applied. This makes it possible restoring
359 // the uncut version again when cutting other items.
360 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
361 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
362 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
363 if ((*it).url == item.url()) {
364 (*it).pixmap = icon;
365 break;
366 }
367 }
368
369 // apply the disabled effect to the icon for marking it as "cut item"
370 // and apply the icon to the item
371 KIconEffect iconEffect;
372 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
373 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
374 } else {
375 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
376 }
377 }
378 }
379
380 bool IconManager::isCutItem(const KFileItem& item) const
381 {
382 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
383 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
384
385 const KUrl itemUrl = item.url();
386 foreach (const KUrl& url, cutUrls) {
387 if (url == itemUrl) {
388 return true;
389 }
390 }
391
392 return false;
393 }
394
395 void IconManager::applyCutItemEffect()
396 {
397 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
398 if (!KonqMimeData::decodeIsCutSelection(mimeData)) {
399 return;
400 }
401
402 KFileItemList items;
403 KDirLister* dirLister = m_dolphinModel->dirLister();
404 const KUrl::List dirs = dirLister->directories();
405 foreach (const KUrl& url, dirs) {
406 items << dirLister->itemsForDir(url);
407 }
408
409 foreach (const KFileItem& item, items) {
410 if (isCutItem(item)) {
411 const QModelIndex index = m_dolphinModel->indexForItem(item);
412 const QVariant value = m_dolphinModel->data(index, Qt::DecorationRole);
413 if (value.type() == QVariant::Icon) {
414 const QIcon icon(qvariant_cast<QIcon>(value));
415 const QSize actualSize = icon.actualSize(m_view->iconSize());
416 QPixmap pixmap = icon.pixmap(actualSize);
417
418 // remember current pixmap for the item to be able
419 // to restore it when other items get cut
420 ItemInfo cutItem;
421 cutItem.url = item.url();
422 cutItem.pixmap = pixmap;
423 m_cutItemsCache.append(cutItem);
424
425 // apply icon effect to the cut item
426 KIconEffect iconEffect;
427 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
428 m_dolphinModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
429 }
430 }
431 }
432 }
433
434 bool IconManager::applyImageFrame(QPixmap& icon)
435 {
436 const QSize maxSize = m_view->iconSize();
437 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
438 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
439 ((icon.width() > KIconLoader::SizeLarge) ||
440 (icon.height() > KIconLoader::SizeLarge));
441 if (!applyFrame) {
442 // the maximum size or the image itself is too small for a frame
443 return false;
444 }
445
446 const int frame = 4;
447 const int doubleFrame = frame * 2;
448
449 // resize the icon to the maximum size minus the space required for the frame
450 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
451
452 QPainter painter;
453 const QPalette palette = m_view->palette();
454 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
455 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
456 const int width = framedIcon.width() - 1;
457 const int height = framedIcon.height() - 1;
458
459 painter.begin(&framedIcon);
460 painter.drawPixmap(frame, frame, icon);
461
462 // add a border
463 painter.setPen(palette.color(QPalette::Text));
464 painter.setBrush(Qt::NoBrush);
465 painter.drawRect(0, 0, width, height);
466 painter.drawRect(1, 1, width - 2, height - 2);
467
468 // dim image frame by 12.5 %
469 painter.setPen(QColor(0, 0, 0, 32));
470 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
471 painter.end();
472
473 icon = framedIcon;
474
475 // provide an alpha channel for the border
476 QPixmap alphaChannel(icon.size());
477 alphaChannel.fill();
478
479 QPainter alphaPainter(&alphaChannel);
480 alphaPainter.setBrush(Qt::NoBrush);
481 alphaPainter.setPen(QColor(32, 32, 32));
482 alphaPainter.drawRect(0, 0, width, height);
483 alphaPainter.setPen(QColor(64, 64, 64));
484 alphaPainter.drawRect(1, 1, width - 2, height - 2);
485
486 icon.setAlphaChannel(alphaChannel);
487 return true;
488 }
489
490 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
491 {
492 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
493 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
494 }
495 }
496
497 void IconManager::startPreviewJob(const KFileItemList& items)
498 {
499 if (items.count() == 0) {
500 return;
501 }
502
503 const QSize size = m_view->iconSize();
504 KIO::PreviewJob* job = KIO::filePreview(items, 128, 128);
505 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
506 this, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&)));
507 connect(job, SIGNAL(finished(KJob*)),
508 this, SLOT(slotPreviewJobFinished(KJob*)));
509
510 m_previewJobs.append(job);
511 m_previewTimer->start(200);
512 }
513
514 void IconManager::killPreviewJobs()
515 {
516 foreach (KJob* job, m_previewJobs) {
517 Q_ASSERT(job != 0);
518 job->kill();
519 }
520 m_previewJobs.clear();
521 }
522
523 bool IconManager::itemListContains(const KFileItemList& items, const KUrl& url) const
524 {
525 foreach (const KFileItem& item, items) {
526 if (url == item.url()) {
527 return true;
528 }
529 }
530 return false;
531 }
532
533 #include "iconmanager.moc"