]> cloud.milkyroute.net Git - dolphin.git/blob - src/kfilepreviewgenerator.cpp
renamed IconManager to KFilePreviewGenerator
[dolphin.git] / src / kfilepreviewgenerator.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 "kfilepreviewgenerator.h"
21
22 #include <kiconeffect.h>
23 #include <kio/previewjob.h>
24 #include <kdirlister.h>
25 #include <kdirmodel.h>
26 #include <kdirsortfilterproxymodel.h>
27 #include <kmimetyperesolver.h>
28 #include <konqmimedata.h>
29
30 #include <QApplication>
31 #include <QAbstractItemView>
32 #include <QClipboard>
33 #include <QColor>
34 #include <QListView>
35 #include <QPainter>
36 #include <QScrollBar>
37 #include <QIcon>
38
39 /**
40 * If the passed item view is an instance of QListView, expensive
41 * layout operations are blocked in the constructor and are unblocked
42 * again in the destructor.
43 *
44 * This helper class is a workaround for the following huge performance
45 * problem when having directories with several 1000 items:
46 * - each change of an icon emits a dataChanged() signal from the model
47 * - QListView iterates through all items on each dataChanged() signal
48 * and invokes QItemDelegate::sizeHint()
49 * - the sizeHint() implementation of KFileItemDelegate is quite complex,
50 * invoking it 1000 times for each icon change might block the UI
51 *
52 * QListView does not invoke QItemDelegate::sizeHint() when the
53 * uniformItemSize property has been set to true, so this property is
54 * set before exchanging a block of icons. It is important to reset
55 * it again before the event loop is entered, otherwise QListView
56 * would not get the correct size hints after dispatching the layoutChanged()
57 * signal.
58 */
59 class LayoutBlocker {
60 public:
61 LayoutBlocker(QAbstractItemView* view) :
62 m_uniformSizes(false),
63 m_view(qobject_cast<QListView*>(view))
64 {
65 if (m_view != 0) {
66 m_uniformSizes = m_view->uniformItemSizes();
67 m_view->setUniformItemSizes(true);
68 }
69 }
70
71 ~LayoutBlocker()
72 {
73 if (m_view != 0) {
74 m_view->setUniformItemSizes(m_uniformSizes);
75 }
76 }
77
78 private:
79 bool m_uniformSizes;
80 QListView* m_view;
81 };
82
83 KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView* parent, KDirSortFilterProxyModel* model) :
84 QObject(parent),
85 m_showPreview(false),
86 m_clearItemQueues(true),
87 m_hasCutSelection(false),
88 m_pendingVisiblePreviews(0),
89 m_view(parent),
90 m_previewTimer(0),
91 m_scrollAreaTimer(0),
92 m_previewJobs(),
93 m_dirModel(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_dirModel = static_cast<KDirModel*>(m_proxyModel->sourceModel());
104 connect(m_dirModel->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 KFilePreviewGenerator::~KFilePreviewGenerator()
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 void KFilePreviewGenerator::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_dirModel);
160 }
161 }
162
163 void KFilePreviewGenerator::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_dirModel->rowCount();
176 for (int row = 0; row < rowCount; ++row) {
177 const QModelIndex index = m_dirModel->index(row, 0);
178 KFileItem item = m_dirModel->itemForIndex(index);
179 itemList.append(item);
180 }
181
182 generatePreviews(itemList);
183 updateCutItems();
184 }
185
186 void KFilePreviewGenerator::cancelPreviews()
187 {
188 killPreviewJobs();
189 m_cutItemsCache.clear();
190 m_pendingItems.clear();
191 m_dispatchedItems.clear();
192 }
193
194 void KFilePreviewGenerator::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 KFilePreviewGenerator::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
213 {
214 if (!m_showPreview) {
215 // the preview has been canceled in the meantime
216 return;
217 }
218 const KUrl url = item.url();
219
220 // check whether the item is part of the directory lister (it is possible
221 // that a preview from an old directory lister is received)
222 KDirLister* dirLister = m_dirModel->dirLister();
223 bool isOldPreview = true;
224 const KUrl::List dirs = dirLister->directories();
225 const QString itemDir = url.directory();
226 foreach (const KUrl& url, dirs) {
227 if (url.path() == itemDir) {
228 isOldPreview = false;
229 break;
230 }
231 }
232 if (isOldPreview) {
233 return;
234 }
235
236 QPixmap icon = pixmap;
237
238 const QString mimeType = item.mimetype();
239 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
240 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
241 limitToSize(icon, m_view->iconSize());
242 }
243
244 if (m_hasCutSelection && isCutItem(item)) {
245 // Remember the current icon in the cache for cut items before
246 // the disabled effect is applied. This makes it possible restoring
247 // the uncut version again when cutting other items.
248 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
249 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
250 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
251 if ((*it).url == item.url()) {
252 (*it).pixmap = icon;
253 break;
254 }
255 }
256
257 // apply the disabled effect to the icon for marking it as "cut item"
258 // and apply the icon to the item
259 KIconEffect iconEffect;
260 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
261 }
262
263 // remember the preview and URL, so that it can be applied to the model
264 // in KFilePreviewGenerator::dispatchPreviewQueue()
265 ItemInfo preview;
266 preview.url = url;
267 preview.pixmap = icon;
268 m_previews.append(preview);
269
270 m_dispatchedItems.append(item);
271 }
272
273 void KFilePreviewGenerator::slotPreviewJobFinished(KJob* job)
274 {
275 const int index = m_previewJobs.indexOf(job);
276 m_previewJobs.removeAt(index);
277
278 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
279 m_pendingItems.clear();
280 m_dispatchedItems.clear();
281 m_pendingVisiblePreviews = 0;
282 QMetaObject::invokeMethod(this, "dispatchPreviewQueue", Qt::QueuedConnection);
283 }
284 }
285
286 void KFilePreviewGenerator::updateCutItems()
287 {
288 // restore the icons of all previously selected items to the
289 // original state...
290 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
291 const QModelIndex index = m_dirModel->indexForUrl(cutItem.url);
292 if (index.isValid()) {
293 m_dirModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
294 }
295 }
296 m_cutItemsCache.clear();
297
298 // ... and apply an item effect to all currently cut items
299 applyCutItemEffect();
300 }
301
302 void KFilePreviewGenerator::dispatchPreviewQueue()
303 {
304 const int previewsCount = m_previews.count();
305 if (previewsCount > 0) {
306 // Applying the previews to the model must be done step by step
307 // in larger blocks: Applying a preview immediately when getting the signal
308 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
309 // of the view would be triggered for each single preview.
310 LayoutBlocker blocker(m_view);
311 for (int i = 0; i < previewsCount; ++i) {
312 const ItemInfo& preview = m_previews.first();
313
314 const QModelIndex idx = m_dirModel->indexForUrl(preview.url);
315 if (idx.isValid() && (idx.column() == 0)) {
316 m_dirModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole);
317 }
318
319 m_previews.pop_front();
320 if (m_pendingVisiblePreviews > 0) {
321 --m_pendingVisiblePreviews;
322 }
323 }
324 }
325
326 if (m_pendingVisiblePreviews > 0) {
327 // As long as there are pending previews for visible items, poll
328 // the preview queue each 200 ms. If there are no pending previews,
329 // the queue is dispatched in slotPreviewJobFinished().
330 m_previewTimer->start(200);
331 }
332 }
333
334 void KFilePreviewGenerator::pausePreviews()
335 {
336 foreach (KJob* job, m_previewJobs) {
337 Q_ASSERT(job != 0);
338 job->suspend();
339 }
340 m_scrollAreaTimer->start();
341 }
342
343 void KFilePreviewGenerator::resumePreviews()
344 {
345 // Before creating new preview jobs the m_pendingItems queue must be
346 // cleaned up by removing the already dispatched items. Implementation
347 // note: The order of the m_dispatchedItems queue and the m_pendingItems
348 // queue is usually equal. So even when having a lot of elements the
349 // nested loop is no performance bottle neck, as the inner loop is only
350 // entered once in most cases.
351 foreach (const KFileItem& item, m_dispatchedItems) {
352 KFileItemList::iterator begin = m_pendingItems.begin();
353 KFileItemList::iterator end = m_pendingItems.end();
354 for (KFileItemList::iterator it = begin; it != end; ++it) {
355 if ((*it).url() == item.url()) {
356 m_pendingItems.erase(it);
357 break;
358 }
359 }
360 }
361 m_dispatchedItems.clear();
362
363 m_pendingVisiblePreviews = 0;
364 dispatchPreviewQueue();
365
366 KFileItemList orderedItems = m_pendingItems;
367 orderItems(orderedItems);
368
369 // Kill all suspended preview jobs. Usually when a preview job
370 // has been finished, slotPreviewJobFinished() clears all item queues.
371 // This is not wanted in this case, as a new job is created afterwards
372 // for m_pendingItems.
373 m_clearItemQueues = false;
374 killPreviewJobs();
375 m_clearItemQueues = true;
376
377 startPreviewJob(orderedItems);
378 }
379
380 bool KFilePreviewGenerator::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 KFilePreviewGenerator::applyCutItemEffect()
396 {
397 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
398 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
399 if (!m_hasCutSelection) {
400 return;
401 }
402
403 KFileItemList items;
404 KDirLister* dirLister = m_dirModel->dirLister();
405 const KUrl::List dirs = dirLister->directories();
406 foreach (const KUrl& url, dirs) {
407 items << dirLister->itemsForDir(url);
408 }
409
410 foreach (const KFileItem& item, items) {
411 if (isCutItem(item)) {
412 const QModelIndex index = m_dirModel->indexForItem(item);
413 const QVariant value = m_dirModel->data(index, Qt::DecorationRole);
414 if (value.type() == QVariant::Icon) {
415 const QIcon icon(qvariant_cast<QIcon>(value));
416 const QSize actualSize = icon.actualSize(m_view->iconSize());
417 QPixmap pixmap = icon.pixmap(actualSize);
418
419 // remember current pixmap for the item to be able
420 // to restore it when other items get cut
421 ItemInfo cutItem;
422 cutItem.url = item.url();
423 cutItem.pixmap = pixmap;
424 m_cutItemsCache.append(cutItem);
425
426 // apply icon effect to the cut item
427 KIconEffect iconEffect;
428 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
429 m_dirModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
430 }
431 }
432 }
433 }
434
435 bool KFilePreviewGenerator::applyImageFrame(QPixmap& icon)
436 {
437 const QSize maxSize = m_view->iconSize();
438 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
439 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
440 ((icon.width() > KIconLoader::SizeLarge) ||
441 (icon.height() > KIconLoader::SizeLarge));
442 if (!applyFrame) {
443 // the maximum size or the image itself is too small for a frame
444 return false;
445 }
446
447 const int frame = 4;
448 const int doubleFrame = frame * 2;
449
450 // resize the icon to the maximum size minus the space required for the frame
451 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
452
453 QPainter painter;
454 const QPalette palette = m_view->palette();
455 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
456 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
457 const int width = framedIcon.width() - 1;
458 const int height = framedIcon.height() - 1;
459
460 painter.begin(&framedIcon);
461 painter.drawPixmap(frame, frame, icon);
462
463 // add a border
464 painter.setPen(palette.color(QPalette::Text));
465 painter.drawRect(0, 0, width, height);
466 painter.drawRect(1, 1, width - 2, height - 2);
467
468 painter.setCompositionMode(QPainter::CompositionMode_Plus);
469 QColor blendColor = palette.color(QPalette::Normal, QPalette::Base);
470
471 blendColor.setAlpha(255 - 32);
472 painter.setPen(blendColor);
473 painter.drawRect(0, 0, width, height);
474
475 blendColor.setAlpha(255 - 64);
476 painter.setPen(blendColor);
477 painter.drawRect(1, 1, width - 2, height - 2);
478 painter.end();
479
480 icon = framedIcon;
481
482 return true;
483 }
484
485 void KFilePreviewGenerator::limitToSize(QPixmap& icon, const QSize& maxSize)
486 {
487 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
488 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
489 }
490 }
491
492 void KFilePreviewGenerator::startPreviewJob(const KFileItemList& items)
493 {
494 if (items.count() == 0) {
495 return;
496 }
497
498 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
499 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
500
501 const QSize size = m_view->iconSize();
502
503 // PreviewJob internally caches items always with the size of
504 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
505 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
506 // do a downscaling anyhow because of the frame, only the provided
507 // cache sizes are requested.
508 const int cacheSize = (size.width() > 128) || (size.height() > 128) ? 256 : 128;
509 KIO::PreviewJob* job = KIO::filePreview(items, cacheSize, cacheSize);
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 KFilePreviewGenerator::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 KFilePreviewGenerator::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_dirModel->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.at(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_dirModel->indexForItem(items.at(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.at(i));
588 items.removeAt(i + 1);
589 ++insertPos;
590 ++m_pendingVisiblePreviews;
591 }
592 }
593 }
594 }
595
596 #include "kfilepreviewgenerator.moc"