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