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