]> cloud.milkyroute.net Git - dolphin.git/blob - src/kfilepreviewgenerator.cpp
Experimental patch provided by Fredrik Höglund: Use Xrender to scale the preview...
[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 #ifdef Q_WS_X11
40 # include <QX11Info>
41 # include <X11/Xlib.h>
42 # include <X11/extensions/Xrender.h>
43 #endif
44
45 /**
46 * If the passed item view is an instance of QListView, expensive
47 * layout operations are blocked in the constructor and are unblocked
48 * again in the destructor.
49 *
50 * This helper class is a workaround for the following huge performance
51 * problem when having directories with several 1000 items:
52 * - each change of an icon emits a dataChanged() signal from the model
53 * - QListView iterates through all items on each dataChanged() signal
54 * and invokes QItemDelegate::sizeHint()
55 * - the sizeHint() implementation of KFileItemDelegate is quite complex,
56 * invoking it 1000 times for each icon change might block the UI
57 *
58 * QListView does not invoke QItemDelegate::sizeHint() when the
59 * uniformItemSize property has been set to true, so this property is
60 * set before exchanging a block of icons. It is important to reset
61 * it again before the event loop is entered, otherwise QListView
62 * would not get the correct size hints after dispatching the layoutChanged()
63 * signal.
64 */
65 class LayoutBlocker {
66 public:
67 LayoutBlocker(QAbstractItemView* view) :
68 m_uniformSizes(false),
69 m_view(qobject_cast<QListView*>(view))
70 {
71 if (m_view != 0) {
72 m_uniformSizes = m_view->uniformItemSizes();
73 m_view->setUniformItemSizes(true);
74 }
75 }
76
77 ~LayoutBlocker()
78 {
79 if (m_view != 0) {
80 m_view->setUniformItemSizes(m_uniformSizes);
81 }
82 }
83
84 private:
85 bool m_uniformSizes;
86 QListView* m_view;
87 };
88
89 class KFilePreviewGenerator::Private
90 {
91 public:
92 Private(KFilePreviewGenerator* parent,
93 QAbstractItemView* view,
94 KDirSortFilterProxyModel* model);
95 ~Private();
96
97 /**
98 * Generates previews for the items \a items asynchronously.
99 */
100 void generatePreviews(const KFileItemList& items);
101
102 /**
103 * Adds the preview \a pixmap for the item \a item to the preview
104 * queue and starts a timer which will dispatch the preview queue
105 * later.
106 */
107 void addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap);
108
109 /**
110 * Is invoked when the preview job has been finished and
111 * removes the job from the m_previewJobs list.
112 */
113 void slotPreviewJobFinished(KJob* job);
114
115 /** Synchronizes the item icon with the clipboard of cut items. */
116 void updateCutItems();
117
118 /**
119 * Dispatches the preview queue block by block within
120 * time slices.
121 */
122 void dispatchPreviewQueue();
123
124 /**
125 * Pauses all preview jobs and invokes KFilePreviewGenerator::resumePreviews()
126 * after a short delay. Is invoked as soon as the user has moved
127 * a scrollbar.
128 */
129 void pausePreviews();
130
131 /**
132 * Resumes the previews that have been paused after moving the
133 * scrollbar. The previews for the current visible area are
134 * generated first.
135 */
136 void resumePreviews();
137
138 /**
139 * Returns true, if the item \a item has been cut into
140 * the clipboard.
141 */
142 bool isCutItem(const KFileItem& item) const;
143
144 /** Applies an item effect to all cut items. */
145 void applyCutItemEffect();
146
147 /**
148 * Applies a frame around the icon. False is returned if
149 * no frame has been added because the icon is too small.
150 */
151 bool applyImageFrame(QPixmap& icon);
152
153 /**
154 * Resizes the icon to \a maxSize if the icon size does not
155 * fit into the maximum size. The aspect ratio of the icon
156 * is kept.
157 */
158 void limitToSize(QPixmap& icon, const QSize& maxSize);
159
160 /**
161 * Starts a new preview job for the items \a to m_previewJobs
162 * and triggers the preview timer.
163 */
164 void startPreviewJob(const KFileItemList& items);
165
166 /** Kills all ongoing preview jobs. */
167 void killPreviewJobs();
168
169 /**
170 * Orders the items \a items in a way that the visible items
171 * are moved to the front of the list. When passing this
172 * list to a preview job, the visible items will get generated
173 * first.
174 */
175 void orderItems(KFileItemList& items);
176
177 /** Remembers the pixmap for an item specified by an URL. */
178 struct ItemInfo
179 {
180 KUrl url;
181 QPixmap pixmap;
182 };
183
184 bool m_showPreview;
185
186 /**
187 * True, if m_pendingItems and m_dispatchedItems should be
188 * cleared when the preview jobs have been finished.
189 */
190 bool m_clearItemQueues;
191
192 /**
193 * True if a selection has been done which should cut items.
194 */
195 bool m_hasCutSelection;
196
197 int m_pendingVisiblePreviews;
198
199 QAbstractItemView* m_view;
200 QTimer* m_previewTimer;
201 QTimer* m_scrollAreaTimer;
202 QList<KJob*> m_previewJobs;
203 KDirModel* m_dirModel;
204 KDirSortFilterProxyModel* m_proxyModel;
205
206 KMimeTypeResolver* m_mimeTypeResolver;
207
208 QList<ItemInfo> m_cutItemsCache;
209 QList<ItemInfo> m_previews;
210
211 /**
212 * Contains all items where a preview must be generated, but
213 * where the preview job has not dispatched the items yet.
214 */
215 KFileItemList m_pendingItems;
216
217 /**
218 * Contains all items, where a preview has already been
219 * generated by the preview jobs.
220 */
221 KFileItemList m_dispatchedItems;
222
223 private:
224 KFilePreviewGenerator* const q;
225
226 };
227
228 KFilePreviewGenerator::Private::Private(KFilePreviewGenerator* parent,
229 QAbstractItemView* view,
230 KDirSortFilterProxyModel* model) :
231 m_showPreview(true),
232 m_clearItemQueues(true),
233 m_hasCutSelection(false),
234 m_pendingVisiblePreviews(0),
235 m_view(view),
236 m_previewTimer(0),
237 m_scrollAreaTimer(0),
238 m_previewJobs(),
239 m_dirModel(0),
240 m_proxyModel(model),
241 m_mimeTypeResolver(0),
242 m_cutItemsCache(),
243 m_previews(),
244 m_pendingItems(),
245 m_dispatchedItems(),
246 q(parent)
247 {
248 if (!m_view->iconSize().isValid()) {
249 m_showPreview = false;
250 }
251
252 m_dirModel = static_cast<KDirModel*>(m_proxyModel->sourceModel());
253 connect(m_dirModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
254 q, SLOT(generatePreviews(const KFileItemList&)));
255
256 QClipboard* clipboard = QApplication::clipboard();
257 connect(clipboard, SIGNAL(dataChanged()),
258 q, SLOT(updateCutItems()));
259
260 m_previewTimer = new QTimer(q);
261 m_previewTimer->setSingleShot(true);
262 connect(m_previewTimer, SIGNAL(timeout()), q, SLOT(dispatchPreviewQueue()));
263
264 // Whenever the scrollbar values have been changed, the pending previews should
265 // be reordered in a way that the previews for the visible items are generated
266 // first. The reordering is done with a small delay, so that during moving the
267 // scrollbars the CPU load is kept low.
268 m_scrollAreaTimer = new QTimer(q);
269 m_scrollAreaTimer->setSingleShot(true);
270 m_scrollAreaTimer->setInterval(200);
271 connect(m_scrollAreaTimer, SIGNAL(timeout()),
272 q, SLOT(resumePreviews()));
273 connect(m_view->horizontalScrollBar(), SIGNAL(valueChanged(int)),
274 q, SLOT(pausePreviews()));
275 connect(m_view->verticalScrollBar(), SIGNAL(valueChanged(int)),
276 q, SLOT(pausePreviews()));
277 }
278
279 KFilePreviewGenerator::Private::~Private()
280 {
281 killPreviewJobs();
282 m_pendingItems.clear();
283 m_dispatchedItems.clear();
284 if (m_mimeTypeResolver != 0) {
285 m_mimeTypeResolver->deleteLater();
286 m_mimeTypeResolver = 0;
287 }
288 }
289
290 void KFilePreviewGenerator::Private::generatePreviews(const KFileItemList& items)
291 {
292 applyCutItemEffect();
293
294 if (!m_showPreview) {
295 return;
296 }
297
298 KFileItemList orderedItems = items;
299 orderItems(orderedItems);
300
301 foreach (const KFileItem& item, orderedItems) {
302 m_pendingItems.append(item);
303 }
304
305 startPreviewJob(orderedItems);
306 }
307
308 void KFilePreviewGenerator::Private::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
309 {
310 if (!m_showPreview) {
311 // the preview has been canceled in the meantime
312 return;
313 }
314 const KUrl url = item.url();
315
316 // check whether the item is part of the directory lister (it is possible
317 // that a preview from an old directory lister is received)
318 KDirLister* dirLister = m_dirModel->dirLister();
319 bool isOldPreview = true;
320 const KUrl::List dirs = dirLister->directories();
321 const QString itemDir = url.directory();
322 foreach (const KUrl& url, dirs) {
323 if (url.path() == itemDir) {
324 isOldPreview = false;
325 break;
326 }
327 }
328 if (isOldPreview) {
329 return;
330 }
331
332 QPixmap icon = pixmap;
333
334 const QString mimeType = item.mimetype();
335 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
336 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
337 limitToSize(icon, m_view->iconSize());
338 }
339
340 if (m_hasCutSelection && isCutItem(item)) {
341 // Remember the current icon in the cache for cut items before
342 // the disabled effect is applied. This makes it possible restoring
343 // the uncut version again when cutting other items.
344 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
345 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
346 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
347 if ((*it).url == item.url()) {
348 (*it).pixmap = icon;
349 break;
350 }
351 }
352
353 // apply the disabled effect to the icon for marking it as "cut item"
354 // and apply the icon to the item
355 KIconEffect iconEffect;
356 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
357 }
358
359 // remember the preview and URL, so that it can be applied to the model
360 // in KFilePreviewGenerator::dispatchPreviewQueue()
361 ItemInfo preview;
362 preview.url = url;
363 preview.pixmap = icon;
364 m_previews.append(preview);
365
366 m_dispatchedItems.append(item);
367 }
368
369 void KFilePreviewGenerator::Private::slotPreviewJobFinished(KJob* job)
370 {
371 const int index = m_previewJobs.indexOf(job);
372 m_previewJobs.removeAt(index);
373
374 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
375 m_pendingItems.clear();
376 m_dispatchedItems.clear();
377 m_pendingVisiblePreviews = 0;
378 QMetaObject::invokeMethod(q, "dispatchPreviewQueue", Qt::QueuedConnection);
379 }
380 }
381
382 void KFilePreviewGenerator::Private::updateCutItems()
383 {
384 // restore the icons of all previously selected items to the
385 // original state...
386 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
387 const QModelIndex index = m_dirModel->indexForUrl(cutItem.url);
388 if (index.isValid()) {
389 m_dirModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
390 }
391 }
392 m_cutItemsCache.clear();
393
394 // ... and apply an item effect to all currently cut items
395 applyCutItemEffect();
396 }
397
398 void KFilePreviewGenerator::Private::dispatchPreviewQueue()
399 {
400 const int previewsCount = m_previews.count();
401 if (previewsCount > 0) {
402 // Applying the previews to the model must be done step by step
403 // in larger blocks: Applying a preview immediately when getting the signal
404 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
405 // of the view would be triggered for each single preview.
406 LayoutBlocker blocker(m_view);
407 for (int i = 0; i < previewsCount; ++i) {
408 const ItemInfo& preview = m_previews.first();
409
410 const QModelIndex idx = m_dirModel->indexForUrl(preview.url);
411 if (idx.isValid() && (idx.column() == 0)) {
412 m_dirModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole);
413 }
414
415 m_previews.pop_front();
416 if (m_pendingVisiblePreviews > 0) {
417 --m_pendingVisiblePreviews;
418 }
419 }
420 }
421
422 if (m_pendingVisiblePreviews > 0) {
423 // As long as there are pending previews for visible items, poll
424 // the preview queue each 200 ms. If there are no pending previews,
425 // the queue is dispatched in slotPreviewJobFinished().
426 m_previewTimer->start(200);
427 }
428 }
429
430 void KFilePreviewGenerator::Private::pausePreviews()
431 {
432 foreach (KJob* job, m_previewJobs) {
433 Q_ASSERT(job != 0);
434 job->suspend();
435 }
436 m_scrollAreaTimer->start();
437 }
438
439 void KFilePreviewGenerator::Private::resumePreviews()
440 {
441 // Before creating new preview jobs the m_pendingItems queue must be
442 // cleaned up by removing the already dispatched items. Implementation
443 // note: The order of the m_dispatchedItems queue and the m_pendingItems
444 // queue is usually equal. So even when having a lot of elements the
445 // nested loop is no performance bottle neck, as the inner loop is only
446 // entered once in most cases.
447 foreach (const KFileItem& item, m_dispatchedItems) {
448 KFileItemList::iterator begin = m_pendingItems.begin();
449 KFileItemList::iterator end = m_pendingItems.end();
450 for (KFileItemList::iterator it = begin; it != end; ++it) {
451 if ((*it).url() == item.url()) {
452 m_pendingItems.erase(it);
453 break;
454 }
455 }
456 }
457 m_dispatchedItems.clear();
458
459 m_pendingVisiblePreviews = 0;
460 dispatchPreviewQueue();
461
462 KFileItemList orderedItems = m_pendingItems;
463 orderItems(orderedItems);
464
465 // Kill all suspended preview jobs. Usually when a preview job
466 // has been finished, slotPreviewJobFinished() clears all item queues.
467 // This is not wanted in this case, as a new job is created afterwards
468 // for m_pendingItems.
469 m_clearItemQueues = false;
470 killPreviewJobs();
471 m_clearItemQueues = true;
472
473 startPreviewJob(orderedItems);
474 }
475
476 bool KFilePreviewGenerator::Private::isCutItem(const KFileItem& item) const
477 {
478 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
479 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
480
481 const KUrl itemUrl = item.url();
482 foreach (const KUrl& url, cutUrls) {
483 if (url == itemUrl) {
484 return true;
485 }
486 }
487
488 return false;
489 }
490
491 void KFilePreviewGenerator::Private::applyCutItemEffect()
492 {
493 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
494 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
495 if (!m_hasCutSelection) {
496 return;
497 }
498
499 KFileItemList items;
500 KDirLister* dirLister = m_dirModel->dirLister();
501 const KUrl::List dirs = dirLister->directories();
502 foreach (const KUrl& url, dirs) {
503 items << dirLister->itemsForDir(url);
504 }
505
506 foreach (const KFileItem& item, items) {
507 if (isCutItem(item)) {
508 const QModelIndex index = m_dirModel->indexForItem(item);
509 const QVariant value = m_dirModel->data(index, Qt::DecorationRole);
510 if (value.type() == QVariant::Icon) {
511 const QIcon icon(qvariant_cast<QIcon>(value));
512 const QSize actualSize = icon.actualSize(m_view->iconSize());
513 QPixmap pixmap = icon.pixmap(actualSize);
514
515 // remember current pixmap for the item to be able
516 // to restore it when other items get cut
517 ItemInfo cutItem;
518 cutItem.url = item.url();
519 cutItem.pixmap = pixmap;
520 m_cutItemsCache.append(cutItem);
521
522 // apply icon effect to the cut item
523 KIconEffect iconEffect;
524 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
525 m_dirModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
526 }
527 }
528 }
529 }
530
531 bool KFilePreviewGenerator::Private::applyImageFrame(QPixmap& icon)
532 {
533 const QSize maxSize = m_view->iconSize();
534 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
535 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
536 ((icon.width() > KIconLoader::SizeLarge) ||
537 (icon.height() > KIconLoader::SizeLarge));
538 if (!applyFrame) {
539 // the maximum size or the image itself is too small for a frame
540 return false;
541 }
542
543 const int frame = 4;
544 const int doubleFrame = frame * 2;
545
546 // resize the icon to the maximum size minus the space required for the frame
547 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
548
549 QPainter painter;
550 const QPalette palette = m_view->palette();
551 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
552 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
553 const int width = framedIcon.width() - 1;
554 const int height = framedIcon.height() - 1;
555
556 painter.begin(&framedIcon);
557 painter.drawPixmap(frame, frame, icon);
558
559 // add a border
560 painter.setPen(palette.color(QPalette::Text));
561 painter.drawRect(0, 0, width, height);
562 painter.drawRect(1, 1, width - 2, height - 2);
563
564 painter.setCompositionMode(QPainter::CompositionMode_Plus);
565 QColor blendColor = palette.color(QPalette::Normal, QPalette::Base);
566
567 blendColor.setAlpha(255 - 32);
568 painter.setPen(blendColor);
569 painter.drawRect(0, 0, width, height);
570
571 blendColor.setAlpha(255 - 64);
572 painter.setPen(blendColor);
573 painter.drawRect(1, 1, width - 2, height - 2);
574 painter.end();
575
576 icon = framedIcon;
577
578 return true;
579 }
580
581 void KFilePreviewGenerator::Private::limitToSize(QPixmap& icon, const QSize& maxSize)
582 {
583 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
584 #ifdef Q_WS_X11
585 // Assume that the texture size limit is 2048x2048
586 if ((icon.width() <= 2048) && (icon.height() <= 2048)) {
587 QSize size = icon.size();
588 size.scale(maxSize, Qt::KeepAspectRatio);
589
590 const qreal factor = size.width() / qreal(icon.width());
591
592 XTransform xform = {{
593 { XDoubleToFixed(1 / factor), 0, 0 },
594 { 0, XDoubleToFixed(1 / factor), 0 },
595 { 0, 0, XDoubleToFixed(1) }
596 }};
597
598 QPixmap pixmap(size);
599 pixmap.fill(Qt::transparent);
600
601 Display *dpy = QX11Info::display();
602 XRenderSetPictureFilter(dpy, icon.x11PictureHandle(), FilterBilinear, 0, 0);
603 XRenderSetPictureTransform(dpy, icon.x11PictureHandle(), &xform);
604 XRenderComposite(dpy, PictOpOver, icon.x11PictureHandle(), None, pixmap.x11PictureHandle(),
605 0, 0, 0, 0, 0, 0, pixmap.width(), pixmap.height());
606 icon = pixmap;
607 } else {
608 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
609 }
610 #else
611 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
612 #endif
613 }
614 }
615
616 void KFilePreviewGenerator::Private::startPreviewJob(const KFileItemList& items)
617 {
618 if (items.count() == 0) {
619 return;
620 }
621
622 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
623 m_hasCutSelection = KonqMimeData::decodeIsCutSelection(mimeData);
624
625 const QSize size = m_view->iconSize();
626
627 // PreviewJob internally caches items always with the size of
628 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
629 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
630 // do a downscaling anyhow because of the frame, only the provided
631 // cache sizes are requested.
632 const int cacheSize = (size.width() > 128) || (size.height() > 128) ? 256 : 128;
633 KIO::PreviewJob* job = KIO::filePreview(items, cacheSize, cacheSize);
634 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
635 q, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&)));
636 connect(job, SIGNAL(finished(KJob*)),
637 q, SLOT(slotPreviewJobFinished(KJob*)));
638
639 m_previewJobs.append(job);
640 m_previewTimer->start(200);
641 }
642
643 void KFilePreviewGenerator::Private::killPreviewJobs()
644 {
645 foreach (KJob* job, m_previewJobs) {
646 Q_ASSERT(job != 0);
647 job->kill();
648 }
649 m_previewJobs.clear();
650 }
651
652 void KFilePreviewGenerator::Private::orderItems(KFileItemList& items)
653 {
654 // Order the items in a way that the preview for the visible items
655 // is generated first, as this improves the feeled performance a lot.
656 //
657 // Implementation note: 2 different algorithms are used for the sorting.
658 // Algorithm 1 is faster when having a lot of items in comparison
659 // to the number of rows in the model. Algorithm 2 is faster
660 // when having quite less items in comparison to the number of rows in
661 // the model. Choosing the right algorithm is important when having directories
662 // with several hundreds or thousands of items.
663
664 const int itemCount = items.count();
665 const int rowCount = m_proxyModel->rowCount();
666 const QRect visibleArea = m_view->viewport()->rect();
667
668 int insertPos = 0;
669 if (itemCount * 10 > rowCount) {
670 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
671 // and check whether the received row is part of the item list.
672 for (int row = 0; row < rowCount; ++row) {
673 const QModelIndex proxyIndex = m_proxyModel->index(row, 0);
674 const QRect itemRect = m_view->visualRect(proxyIndex);
675 const QModelIndex dirIndex = m_proxyModel->mapToSource(proxyIndex);
676
677 KFileItem item = m_dirModel->itemForIndex(dirIndex); // O(1)
678 const KUrl url = item.url();
679
680 // check whether the item is part of the item list 'items'
681 int index = -1;
682 for (int i = 0; i < itemCount; ++i) {
683 if (items.at(i).url() == url) {
684 index = i;
685 break;
686 }
687 }
688
689 if ((index > 0) && itemRect.intersects(visibleArea)) {
690 // The current item is (at least partly) visible. Move it
691 // to the front of the list, so that the preview is
692 // generated earlier.
693 items.removeAt(index);
694 items.insert(insertPos, item);
695 ++insertPos;
696 ++m_pendingVisiblePreviews;
697 }
698 }
699 } else {
700 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
701 // all items and receive the corresponding row from the item.
702 for (int i = 0; i < itemCount; ++i) {
703 const QModelIndex dirIndex = m_dirModel->indexForItem(items.at(i)); // O(n) (n = number of rows)
704 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
705 const QRect itemRect = m_view->visualRect(proxyIndex);
706
707 if (itemRect.intersects(visibleArea)) {
708 // The current item is (at least partly) visible. Move it
709 // to the front of the list, so that the preview is
710 // generated earlier.
711 items.insert(insertPos, items.at(i));
712 items.removeAt(i + 1);
713 ++insertPos;
714 ++m_pendingVisiblePreviews;
715 }
716 }
717 }
718 }
719
720 KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView* parent, KDirSortFilterProxyModel* model) :
721 QObject(parent),
722 d(new Private(this, parent, model))
723 {
724 }
725
726 KFilePreviewGenerator::~KFilePreviewGenerator()
727 {
728 delete d;
729 }
730
731 void KFilePreviewGenerator::setShowPreview(bool show)
732 {
733 if (show && !d->m_view->iconSize().isValid()) {
734 // the view must provide an icon size, otherwise the showing
735 // off previews will get ignored
736 return;
737 }
738
739 if (d->m_showPreview != show) {
740 d->m_showPreview = show;
741 d->m_cutItemsCache.clear();
742 d->updateCutItems();
743 if (show) {
744 updatePreviews();
745 }
746 }
747
748 if (show && (d->m_mimeTypeResolver != 0)) {
749 // don't resolve the MIME types if the preview is turned on
750 d->m_mimeTypeResolver->deleteLater();
751 d->m_mimeTypeResolver = 0;
752 } else if (!show && (d->m_mimeTypeResolver == 0)) {
753 // the preview is turned off: resolve the MIME-types so that
754 // the icons gets updated
755 d->m_mimeTypeResolver = new KMimeTypeResolver(d->m_view, d->m_dirModel);
756 }
757 }
758
759 bool KFilePreviewGenerator::showPreview() const
760 {
761 return d->m_showPreview;
762 }
763
764 void KFilePreviewGenerator::updatePreviews()
765 {
766 if (!d->m_showPreview) {
767 return;
768 }
769
770 d->killPreviewJobs();
771 d->m_cutItemsCache.clear();
772 d->m_pendingItems.clear();
773 d->m_dispatchedItems.clear();
774
775 KFileItemList itemList;
776 const int rowCount = d->m_dirModel->rowCount();
777 for (int row = 0; row < rowCount; ++row) {
778 const QModelIndex index = d->m_dirModel->index(row, 0);
779 KFileItem item = d->m_dirModel->itemForIndex(index);
780 itemList.append(item);
781 }
782
783 d->generatePreviews(itemList);
784 d->updateCutItems();
785 }
786
787 void KFilePreviewGenerator::cancelPreviews()
788 {
789 d->killPreviewJobs();
790 d->m_cutItemsCache.clear();
791 d->m_pendingItems.clear();
792 d->m_dispatchedItems.clear();
793 }
794
795 #include "kfilepreviewgenerator.moc"