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