fix tricky regression noticed by Vyacheslav Tokarev on Google Reader.
[kdelibs.git] / kfile / kfilepreviewgenerator.cpp
blob58529c2b08ae5f75cf55d125b9b9e753108278df
1 /*******************************************************************************
2 * Copyright (C) 2008-2009 by Peter Penz <peter.penz@gmx.at> *
3 * *
4 * This library is free software; you can redistribute it and/or *
5 * modify it under the terms of the GNU Library General Public *
6 * License as published by the Free Software Foundation; either *
7 * version 2 of the License, or (at your option) any later version. *
8 * *
9 * This library 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 GNU *
12 * Library General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU Library General Public License *
15 * along with this library; see the file COPYING.LIB. If not, write to *
16 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, *
17 * Boston, MA 02110-1301, USA. *
18 *******************************************************************************/
19 #include <config.h> // for HAVE_XRENDER
21 #include "kfilepreviewgenerator.h"
23 #include "../kio/kio/defaultviewadapter_p.h"
24 #include "../kio/kio/imagefilter_p.h"
25 #include <kfileitem.h>
26 #include <kiconeffect.h>
27 #include <kio/previewjob.h>
28 #include <kdirlister.h>
29 #include <kdirmodel.h>
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>
43 #if defined(Q_WS_X11) && defined(HAVE_XRENDER)
44 # include <QX11Info>
45 # include <X11/Xlib.h>
46 # include <X11/extensions/Xrender.h>
47 #endif
49 /**
50 * If the passed item view is an instance of QListView, expensive
51 * layout operations are blocked in the constructor and are unblocked
52 * again in the destructor.
54 * This helper class is a workaround for the following huge performance
55 * problem when having directories with several 1000 items:
56 * - each change of an icon emits a dataChanged() signal from the model
57 * - QListView iterates through all items on each dataChanged() signal
58 * and invokes QItemDelegate::sizeHint()
59 * - the sizeHint() implementation of KFileItemDelegate is quite complex,
60 * invoking it 1000 times for each icon change might block the UI
62 * QListView does not invoke QItemDelegate::sizeHint() when the
63 * uniformItemSize property has been set to true, so this property is
64 * set before exchanging a block of icons. It is important to reset
65 * it again before the event loop is entered, otherwise QListView
66 * would not get the correct size hints after dispatching the layoutChanged()
67 * signal.
69 class LayoutBlocker {
70 public:
71 LayoutBlocker(QAbstractItemView* view) :
72 m_uniformSizes(false),
73 m_view(qobject_cast<QListView*>(view))
75 if (m_view != 0) {
76 m_uniformSizes = m_view->uniformItemSizes();
77 m_view->setUniformItemSizes(true);
81 ~LayoutBlocker()
83 if (m_view != 0) {
84 m_view->setUniformItemSizes(m_uniformSizes);
88 private:
89 bool m_uniformSizes;
90 QListView* m_view;
93 /** Helper class for drawing frames for image previews. */
94 class TileSet
96 public:
97 enum Tile { TopLeftCorner = 0, TopSide, TopRightCorner, LeftSide, Center,
98 RightSide, BottomLeftCorner, BottomSide, BottomRightCorner,
99 NumTiles };
101 TileSet()
103 QImage image(8 * 3, 8 * 3, QImage::Format_ARGB32_Premultiplied);
105 QPainter p(&image);
106 p.setCompositionMode(QPainter::CompositionMode_Source);
107 p.fillRect(image.rect(), Qt::transparent);
108 p.fillRect(image.rect().adjusted(3, 3, -3, -3), Qt::black);
109 p.end();
111 KIO::ImageFilter::shadowBlur(image, 3, Qt::black);
113 QPixmap pixmap = QPixmap::fromImage(image);
114 m_tiles[TopLeftCorner] = pixmap.copy(0, 0, 8, 8);
115 m_tiles[TopSide] = pixmap.copy(8, 0, 8, 8);
116 m_tiles[TopRightCorner] = pixmap.copy(16, 0, 8, 8);
117 m_tiles[LeftSide] = pixmap.copy(0, 8, 8, 8);
118 m_tiles[Center] = pixmap.copy(8, 8, 8, 8);
119 m_tiles[RightSide] = pixmap.copy(16, 8, 8, 8);
120 m_tiles[BottomLeftCorner] = pixmap.copy(0, 16, 8, 8);
121 m_tiles[BottomSide] = pixmap.copy(8, 16, 8, 8);
122 m_tiles[BottomRightCorner] = pixmap.copy(16, 16, 8, 8);
125 void paint(QPainter* p, const QRect& r)
127 p->drawPixmap(r.topLeft(), m_tiles[TopLeftCorner]);
128 if (r.width() - 16 > 0) {
129 p->drawTiledPixmap(r.x() + 8, r.y(), r.width() - 16, 8, m_tiles[TopSide]);
131 p->drawPixmap(r.right() - 8 + 1, r.y(), m_tiles[TopRightCorner]);
132 if (r.height() - 16 > 0) {
133 p->drawTiledPixmap(r.x(), r.y() + 8, 8, r.height() - 16, m_tiles[LeftSide]);
134 if (r.width() - 16 > 0) {
135 p->drawTiledPixmap(r.x() + 8, r.y() + 8, r.width() - 16, r.height() - 16, m_tiles[Center]);
137 p->drawTiledPixmap(r.right() - 8 + 1, r.y() + 8, 8, r.height() - 16, m_tiles[RightSide]);
139 p->drawPixmap(r.x(), r.bottom() - 8 + 1, m_tiles[BottomLeftCorner]);
140 if (r.width() - 16 > 0) {
141 p->drawTiledPixmap(r.x() + 8, r.bottom() - 8 + 1, r.width() - 16, 8, m_tiles[BottomSide]);
143 p->drawPixmap(r.right() - 8 + 1, r.bottom() - 8 + 1, m_tiles[BottomRightCorner]);
146 private:
147 QPixmap m_tiles[NumTiles];
150 class KFilePreviewGenerator::Private
152 public:
153 Private(KFilePreviewGenerator* parent,
154 KAbstractViewAdapter* viewAdapter,
155 QAbstractItemModel* model);
156 ~Private();
159 * Generates previews for the items \a items asynchronously.
161 void updateIcons(const KFileItemList& items);
164 * Generates previews for the indices within \a topLeft
165 * and \a bottomRight asynchronously.
167 void updateIcons(const QModelIndex& topLeft, const QModelIndex& bottomRight);
170 * Adds the preview \a pixmap for the item \a item to the preview
171 * queue and starts a timer which will dispatch the preview queue
172 * later.
174 void addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap);
177 * Is invoked when the preview job has been finished and
178 * removes the job from the m_previewJobs list.
180 void slotPreviewJobFinished(KJob* job);
182 /** Synchronizes the item icon with the clipboard of cut items. */
183 void updateCutItems();
186 * Dispatches the preview queue block by block within
187 * time slices.
189 void dispatchIconUpdateQueue();
192 * Pauses all icon updates and invokes KFilePreviewGenerator::resumeIconUpdates()
193 * after a short delay. Is invoked as soon as the user has moved
194 * a scrollbar.
196 void pauseIconUpdates();
199 * Resumes the icons updates that have been paused after moving the
200 * scrollbar. The previews for the current visible area are
201 * generated first.
203 void resumeIconUpdates();
206 * Starts the resolving of the MIME types from
207 * the m_pendingItems queue.
209 void startMimeTypeResolving();
212 * Resolves the MIME type for exactly one item of the
213 * m_pendingItems queue.
215 void resolveMimeType();
218 * Returns true, if the item \a item has been cut into
219 * the clipboard.
221 bool isCutItem(const KFileItem& item) const;
223 /** Applies an item effect to all cut items. */
224 void applyCutItemEffect();
227 * Applies a frame around the icon. False is returned if
228 * no frame has been added because the icon is too small.
230 bool applyImageFrame(QPixmap& icon);
233 * Resizes the icon to \a maxSize if the icon size does not
234 * fit into the maximum size. The aspect ratio of the icon
235 * is kept.
237 void limitToSize(QPixmap& icon, const QSize& maxSize);
240 * Starts a new preview job for the items \a to m_previewJobs
241 * and triggers the preview timer.
243 void startPreviewJob(const KFileItemList& items);
245 /** Kills all ongoing preview jobs. */
246 void killPreviewJobs();
249 * Orders the items \a items in a way that the visible items
250 * are moved to the front of the list. When passing this
251 * list to a preview job, the visible items will get generated
252 * first.
254 void orderItems(KFileItemList& items);
257 * Returns true, if \a mimeData represents a selection that has
258 * been cut.
260 bool decodeIsCutSelection(const QMimeData* mimeData);
262 /** Remembers the pixmap for an item specified by an URL. */
263 struct ItemInfo
265 KUrl url;
266 QPixmap pixmap;
270 * During the lifetime of a DataChangeObtainer instance changing
271 * the data of the model won't trigger generating a preview.
273 class DataChangeObtainer
275 public:
276 DataChangeObtainer(KFilePreviewGenerator::Private* generator) :
277 m_gen(generator) { ++m_gen->m_internalDataChange; }
278 ~DataChangeObtainer() { --m_gen->m_internalDataChange; }
279 private:
280 KFilePreviewGenerator::Private* m_gen;
283 bool m_previewShown;
286 * True, if m_pendingItems and m_dispatchedItems should be
287 * cleared when the preview jobs have been finished.
289 bool m_clearItemQueues;
292 * True if a selection has been done which should cut items.
294 bool m_hasCutSelection;
297 * True if the updates of icons has been paused by pauseIconUpdates().
298 * The value is reset by resumeIconUpdates().
300 bool m_iconUpdatesPaused;
303 * If the value is 0, the slot
304 * updateIcons(const QModelIndex&, const QModelIndex&) has
305 * been triggered by an external data change.
307 int m_internalDataChange;
309 int m_pendingVisibleIconUpdates;
311 KAbstractViewAdapter* m_viewAdapter;
312 QAbstractItemView* m_itemView;
313 QTimer* m_iconUpdateTimer;
314 QTimer* m_scrollAreaTimer;
315 QList<KJob*> m_previewJobs;
316 KDirModel* m_dirModel;
317 QAbstractProxyModel* m_proxyModel;
319 QList<ItemInfo> m_cutItemsCache;
320 QList<ItemInfo> m_previews;
323 * Contains all items where a preview must be generated, but
324 * where the preview job has not dispatched the items yet.
326 KFileItemList m_pendingItems;
329 * Contains all items, where a preview has already been
330 * generated by the preview jobs.
332 KFileItemList m_dispatchedItems;
334 KFileItemList m_resolvedMimeTypes;
336 QStringList m_enabledPlugins;
338 TileSet* m_tileSet;
340 private:
341 KFilePreviewGenerator* const q;
345 KFilePreviewGenerator::Private::Private(KFilePreviewGenerator* parent,
346 KAbstractViewAdapter* viewAdapter,
347 QAbstractItemModel* model) :
348 m_previewShown(true),
349 m_clearItemQueues(true),
350 m_hasCutSelection(false),
351 m_iconUpdatesPaused(false),
352 m_internalDataChange(0),
353 m_pendingVisibleIconUpdates(0),
354 m_viewAdapter(viewAdapter),
355 m_itemView(0),
356 m_iconUpdateTimer(0),
357 m_scrollAreaTimer(0),
358 m_previewJobs(),
359 m_dirModel(0),
360 m_proxyModel(0),
361 m_cutItemsCache(),
362 m_previews(),
363 m_pendingItems(),
364 m_dispatchedItems(),
365 m_resolvedMimeTypes(),
366 m_tileSet(0),
367 q(parent)
369 if (!m_viewAdapter->iconSize().isValid()) {
370 m_previewShown = false;
373 m_proxyModel = qobject_cast<QAbstractProxyModel*>(model);
374 m_dirModel = (m_proxyModel == 0) ?
375 qobject_cast<KDirModel*>(model) :
376 qobject_cast<KDirModel*>(m_proxyModel->sourceModel());
377 if (m_dirModel == 0) {
378 // previews can only get generated for directory models
379 m_previewShown = false;
380 } else {
381 connect(m_dirModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
382 q, SLOT(updateIcons(const KFileItemList&)));
383 connect(m_dirModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)),
384 q, SLOT(updateIcons(const QModelIndex&, const QModelIndex&)));
387 QClipboard* clipboard = QApplication::clipboard();
388 connect(clipboard, SIGNAL(dataChanged()),
389 q, SLOT(updateCutItems()));
391 m_iconUpdateTimer = new QTimer(q);
392 m_iconUpdateTimer->setSingleShot(true);
393 connect(m_iconUpdateTimer, SIGNAL(timeout()), q, SLOT(dispatchIconUpdateQueue()));
395 // Whenever the scrollbar values have been changed, the pending previews should
396 // be reordered in a way that the previews for the visible items are generated
397 // first. The reordering is done with a small delay, so that during moving the
398 // scrollbars the CPU load is kept low.
399 m_scrollAreaTimer = new QTimer(q);
400 m_scrollAreaTimer->setSingleShot(true);
401 m_scrollAreaTimer->setInterval(200);
402 connect(m_scrollAreaTimer, SIGNAL(timeout()),
403 q, SLOT(resumeIconUpdates()));
404 m_viewAdapter->connect(KAbstractViewAdapter::ScrollBarValueChanged,
405 q, SLOT(pauseIconUpdates()));
408 KFilePreviewGenerator::Private::~Private()
410 killPreviewJobs();
411 m_pendingItems.clear();
412 m_dispatchedItems.clear();
413 delete m_tileSet;
416 void KFilePreviewGenerator::Private::updateIcons(const KFileItemList& items)
418 applyCutItemEffect();
420 KFileItemList orderedItems = items;
421 orderItems(orderedItems);
423 foreach (const KFileItem& item, orderedItems) {
424 m_pendingItems.append(item);
427 if (m_previewShown) {
428 startPreviewJob(orderedItems);
429 } else {
430 startMimeTypeResolving();
434 void KFilePreviewGenerator::Private::updateIcons(const QModelIndex& topLeft,
435 const QModelIndex& bottomRight)
437 if (m_internalDataChange > 0) {
438 // QAbstractItemModel::setData() has been invoked internally by the KFilePreviewGenerator.
439 // The signal dataChanged() is connected with this method, but previews only need
440 // to be generated when an external data change has occured.
441 return;
444 KFileItemList itemList;
445 for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
446 const QModelIndex index = m_dirModel->index(row, 0);
447 const KFileItem item = m_dirModel->itemForIndex(index);
448 itemList.append(item);
450 updateIcons(itemList);
453 void KFilePreviewGenerator::Private::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
455 if (!m_previewShown) {
456 // the preview has been canceled in the meantime
457 return;
459 const KUrl url = item.url();
461 // check whether the item is part of the directory lister (it is possible
462 // that a preview from an old directory lister is received)
463 KDirLister* dirLister = m_dirModel->dirLister();
464 bool isOldPreview = true;
465 const KUrl::List dirs = dirLister->directories();
466 const QString itemDir = url.directory();
467 foreach (const KUrl& url, dirs) {
468 if (url.path() == itemDir) {
469 isOldPreview = false;
470 break;
473 if (isOldPreview) {
474 return;
477 QPixmap icon = pixmap;
479 const QString mimeType = item.mimetype();
480 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
481 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
482 limitToSize(icon, m_viewAdapter->iconSize());
485 if (m_hasCutSelection && isCutItem(item)) {
486 // Remember the current icon in the cache for cut items before
487 // the disabled effect is applied. This makes it possible restoring
488 // the uncut version again when cutting other items.
489 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
490 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
491 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
492 if ((*it).url == item.url()) {
493 (*it).pixmap = icon;
494 break;
498 // apply the disabled effect to the icon for marking it as "cut item"
499 // and apply the icon to the item
500 KIconEffect iconEffect;
501 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
504 // remember the preview and URL, so that it can be applied to the model
505 // in KFilePreviewGenerator::dispatchIconUpdateQueue()
506 ItemInfo preview;
507 preview.url = url;
508 preview.pixmap = icon;
509 m_previews.append(preview);
511 m_dispatchedItems.append(item);
514 void KFilePreviewGenerator::Private::slotPreviewJobFinished(KJob* job)
516 const int index = m_previewJobs.indexOf(job);
517 m_previewJobs.removeAt(index);
519 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
520 m_pendingItems.clear();
521 m_dispatchedItems.clear();
522 m_pendingVisibleIconUpdates = 0;
523 QMetaObject::invokeMethod(q, "dispatchIconUpdateQueue", Qt::QueuedConnection);
527 void KFilePreviewGenerator::Private::updateCutItems()
529 DataChangeObtainer obt(this);
531 // restore the icons of all previously selected items to the
532 // original state...
533 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
534 const QModelIndex index = m_dirModel->indexForUrl(cutItem.url);
535 if (index.isValid()) {
536 m_dirModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
539 m_cutItemsCache.clear();
541 // ... and apply an item effect to all currently cut items
542 applyCutItemEffect();
545 void KFilePreviewGenerator::Private::dispatchIconUpdateQueue()
547 const int count = m_previewShown ? m_previews.count()
548 : m_resolvedMimeTypes.count();
549 if (count > 0) {
550 LayoutBlocker blocker(m_itemView);
551 DataChangeObtainer obt(this);
553 if (m_previewShown) {
554 // dispatch preview queue
555 foreach (const ItemInfo& preview, m_previews) {
556 const QModelIndex idx = m_dirModel->indexForUrl(preview.url);
557 if (idx.isValid() && (idx.column() == 0)) {
558 m_dirModel->setData(idx, QIcon(preview.pixmap), Qt::DecorationRole);
561 m_previews.clear();
562 } else {
563 // dispatch mime type queue
564 foreach (const KFileItem& item, m_resolvedMimeTypes) {
565 const QModelIndex idx = m_dirModel->indexForItem(item);
566 m_dirModel->itemChanged(idx);
568 m_resolvedMimeTypes.clear();
571 m_pendingVisibleIconUpdates -= count;
572 if (m_pendingVisibleIconUpdates < 0) {
573 m_pendingVisibleIconUpdates = 0;
577 if (m_pendingVisibleIconUpdates > 0) {
578 // As long as there are pending previews for visible items, poll
579 // the preview queue each 200 ms. If there are no pending previews,
580 // the queue is dispatched in slotPreviewJobFinished().
581 m_iconUpdateTimer->start(200);
585 void KFilePreviewGenerator::Private::pauseIconUpdates()
587 m_iconUpdatesPaused = true;
588 foreach (KJob* job, m_previewJobs) {
589 Q_ASSERT(job != 0);
590 job->suspend();
592 m_scrollAreaTimer->start();
595 void KFilePreviewGenerator::Private::resumeIconUpdates()
597 m_iconUpdatesPaused = false;
599 // Before creating new preview jobs the m_pendingItems queue must be
600 // cleaned up by removing the already dispatched items. Implementation
601 // note: The order of the m_dispatchedItems queue and the m_pendingItems
602 // queue is usually equal. So even when having a lot of elements the
603 // nested loop is no performance bottle neck, as the inner loop is only
604 // entered once in most cases.
605 foreach (const KFileItem& item, m_dispatchedItems) {
606 KFileItemList::iterator begin = m_pendingItems.begin();
607 KFileItemList::iterator end = m_pendingItems.end();
608 for (KFileItemList::iterator it = begin; it != end; ++it) {
609 if ((*it).url() == item.url()) {
610 m_pendingItems.erase(it);
611 break;
615 m_dispatchedItems.clear();
617 m_pendingVisibleIconUpdates = 0;
618 dispatchIconUpdateQueue();
621 if (m_previewShown) {
622 KFileItemList orderedItems = m_pendingItems;
623 orderItems(orderedItems);
625 // Kill all suspended preview jobs. Usually when a preview job
626 // has been finished, slotPreviewJobFinished() clears all item queues.
627 // This is not wanted in this case, as a new job is created afterwards
628 // for m_pendingItems.
629 m_clearItemQueues = false;
630 killPreviewJobs();
631 m_clearItemQueues = true;
633 startPreviewJob(orderedItems);
634 } else {
635 orderItems(m_pendingItems);
636 startMimeTypeResolving();
640 void KFilePreviewGenerator::Private::startMimeTypeResolving()
642 resolveMimeType();
643 m_iconUpdateTimer->start(200);
646 void KFilePreviewGenerator::Private::resolveMimeType()
648 if (m_pendingItems.isEmpty()) {
649 return;
652 // resolve at least one MIME type
653 bool resolved = false;
654 do {
655 KFileItem item = m_pendingItems.takeFirst();
656 if (item.isMimeTypeKnown()) {
657 if (m_pendingVisibleIconUpdates > 0) {
658 // The item is visible and the MIME type already known.
659 // Decrease the update counter for dispatchIconUpdateQueue():
660 --m_pendingVisibleIconUpdates;
662 } else {
663 // The MIME type is unknown and must get resolved. The
664 // directory model is not informed yet, as a single update
665 // would be very expensive. Instead the item is remembered in
666 // m_resolvedMimeTypes and will be dispatched later
667 // by dispatchIconUpdateQueue().
668 item.determineMimeType();
669 m_resolvedMimeTypes.append(item);
670 resolved = true;
672 } while (!resolved && !m_pendingItems.isEmpty());
674 if (m_pendingItems.isEmpty()) {
675 // All MIME types have been resolved now. Assure
676 // that the directory model gets informed about
677 // this, so that an update of the icons is done.
678 dispatchIconUpdateQueue();
679 } else if (!m_iconUpdatesPaused) {
680 // assure that the MIME type of the next
681 // item will be resolved asynchronously
682 QMetaObject::invokeMethod(q, "resolveMimeType", Qt::QueuedConnection);
686 bool KFilePreviewGenerator::Private::isCutItem(const KFileItem& item) const
688 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
689 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
691 const KUrl itemUrl = item.url();
692 foreach (const KUrl& url, cutUrls) {
693 if (url == itemUrl) {
694 return true;
698 return false;
701 void KFilePreviewGenerator::Private::applyCutItemEffect()
703 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
704 m_hasCutSelection = decodeIsCutSelection(mimeData);
705 if (!m_hasCutSelection) {
706 return;
709 KFileItemList items;
710 KDirLister* dirLister = m_dirModel->dirLister();
711 const KUrl::List dirs = dirLister->directories();
712 foreach (const KUrl& url, dirs) {
713 items << dirLister->itemsForDir(url);
716 DataChangeObtainer obt(this);
717 foreach (const KFileItem& item, items) {
718 if (isCutItem(item)) {
719 const QModelIndex index = m_dirModel->indexForItem(item);
720 const QVariant value = m_dirModel->data(index, Qt::DecorationRole);
721 if (value.type() == QVariant::Icon) {
722 const QIcon icon(qvariant_cast<QIcon>(value));
723 const QSize actualSize = icon.actualSize(m_viewAdapter->iconSize());
724 QPixmap pixmap = icon.pixmap(actualSize);
726 // remember current pixmap for the item to be able
727 // to restore it when other items get cut
728 ItemInfo cutItem;
729 cutItem.url = item.url();
730 cutItem.pixmap = pixmap;
731 m_cutItemsCache.append(cutItem);
733 // apply icon effect to the cut item
734 KIconEffect iconEffect;
735 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
736 m_dirModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
742 bool KFilePreviewGenerator::Private::applyImageFrame(QPixmap& icon)
744 const QSize maxSize = m_viewAdapter->iconSize();
745 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
746 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
747 ((icon.width() > KIconLoader::SizeLarge) ||
748 (icon.height() > KIconLoader::SizeLarge));
749 if (!applyFrame) {
750 // the maximum size or the image itself is too small for a frame
751 return false;
754 const int tloffset = 2;
755 const int broffset = 4;
756 const int doubleFrame = tloffset + broffset;
758 // resize the icon to the maximum size minus the space required for the frame
759 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
761 if (!m_tileSet) {
762 m_tileSet = new TileSet;
765 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
766 framedIcon.fill(Qt::transparent);
768 QPainter painter;
769 painter.begin(&framedIcon);
770 painter.setCompositionMode(QPainter::CompositionMode_Source);
771 m_tileSet->paint(&painter, framedIcon.rect());
772 painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
773 painter.drawPixmap(tloffset, tloffset, icon);
774 painter.end();
776 icon = framedIcon;
777 return true;
780 void KFilePreviewGenerator::Private::limitToSize(QPixmap& icon, const QSize& maxSize)
782 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
783 #if defined(Q_WS_X11) && defined(HAVE_XRENDER)
784 // Assume that the texture size limit is 2048x2048
785 if ((icon.width() <= 2048) && (icon.height() <= 2048) && icon.x11PictureHandle()) {
786 QSize size = icon.size();
787 size.scale(maxSize, Qt::KeepAspectRatio);
789 const qreal factor = size.width() / qreal(icon.width());
791 XTransform xform = {{
792 { XDoubleToFixed(1 / factor), 0, 0 },
793 { 0, XDoubleToFixed(1 / factor), 0 },
794 { 0, 0, XDoubleToFixed(1) }
797 QPixmap pixmap(size);
798 pixmap.fill(Qt::transparent);
800 Display* dpy = QX11Info::display();
801 XRenderSetPictureFilter(dpy, icon.x11PictureHandle(), FilterBilinear, 0, 0);
802 XRenderSetPictureTransform(dpy, icon.x11PictureHandle(), &xform);
803 XRenderComposite(dpy, PictOpOver, icon.x11PictureHandle(), None, pixmap.x11PictureHandle(),
804 0, 0, 0, 0, 0, 0, pixmap.width(), pixmap.height());
805 icon = pixmap;
806 } else {
807 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
809 #else
810 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::FastTransformation);
811 #endif
815 void KFilePreviewGenerator::Private::startPreviewJob(const KFileItemList& items)
817 if (items.count() == 0) {
818 return;
821 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
822 m_hasCutSelection = decodeIsCutSelection(mimeData);
824 const QSize size = m_viewAdapter->iconSize();
826 // PreviewJob internally caches items always with the size of
827 // 128 x 128 pixels or 256 x 256 pixels. A downscaling is done
828 // by PreviewJob if a smaller size is requested. As the KFilePreviewGenerator must
829 // do a downscaling anyhow because of the frame, only the provided
830 // cache sizes are requested.
831 const int cacheSize = (size.width() > 128) || (size.height() > 128) ? 256 : 128;
832 KIO::PreviewJob* job = KIO::filePreview(items, cacheSize, cacheSize, 0, 70, true, true, &m_enabledPlugins);
833 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
834 q, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&)));
835 connect(job, SIGNAL(finished(KJob*)),
836 q, SLOT(slotPreviewJobFinished(KJob*)));
838 m_previewJobs.append(job);
839 m_iconUpdateTimer->start(200);
842 void KFilePreviewGenerator::Private::killPreviewJobs()
844 foreach (KJob* job, m_previewJobs) {
845 Q_ASSERT(job != 0);
846 job->kill();
848 m_previewJobs.clear();
851 void KFilePreviewGenerator::Private::orderItems(KFileItemList& items)
853 // Order the items in a way that the preview for the visible items
854 // is generated first, as this improves the feeled performance a lot.
856 // Implementation note: 2 different algorithms are used for the sorting.
857 // Algorithm 1 is faster when having a lot of items in comparison
858 // to the number of rows in the model. Algorithm 2 is faster
859 // when having quite less items in comparison to the number of rows in
860 // the model. Choosing the right algorithm is important when having directories
861 // with several hundreds or thousands of items.
863 const bool hasProxy = (m_proxyModel != 0);
864 const int itemCount = items.count();
865 const int rowCount = hasProxy ? m_proxyModel->rowCount() : m_dirModel->rowCount();
866 const QRect visibleArea = m_viewAdapter->visibleArea();
868 QModelIndex dirIndex;
869 QRect itemRect;
870 int insertPos = 0;
871 if (itemCount * 10 > rowCount) {
872 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
873 // and check whether the received row is part of the item list.
874 for (int row = 0; row < rowCount; ++row) {
875 if (hasProxy) {
876 const QModelIndex proxyIndex = m_proxyModel->index(row, 0);
877 itemRect = m_viewAdapter->visualRect(proxyIndex);
878 dirIndex = m_proxyModel->mapToSource(proxyIndex);
879 } else {
880 dirIndex = m_dirModel->index(row, 0);
881 itemRect = m_viewAdapter->visualRect(dirIndex);
884 KFileItem item = m_dirModel->itemForIndex(dirIndex); // O(1)
885 const KUrl url = item.url();
887 // check whether the item is part of the item list 'items'
888 int index = -1;
889 for (int i = 0; i < itemCount; ++i) {
890 if (items.at(i).url() == url) {
891 index = i;
892 break;
896 if ((index > 0) && itemRect.intersects(visibleArea)) {
897 // The current item is (at least partly) visible. Move it
898 // to the front of the list, so that the preview is
899 // generated earlier.
900 items.removeAt(index);
901 items.insert(insertPos, item);
902 ++insertPos;
903 ++m_pendingVisibleIconUpdates;
906 } else {
907 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
908 // all items and receive the corresponding row from the item.
909 for (int i = 0; i < itemCount; ++i) {
910 dirIndex = m_dirModel->indexForItem(items.at(i)); // O(n) (n = number of rows)
911 if (hasProxy) {
912 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
913 itemRect = m_viewAdapter->visualRect(proxyIndex);
914 } else {
915 itemRect = m_viewAdapter->visualRect(dirIndex);
918 if (itemRect.intersects(visibleArea)) {
919 // The current item is (at least partly) visible. Move it
920 // to the front of the list, so that the preview is
921 // generated earlier.
922 items.insert(insertPos, items.at(i));
923 items.removeAt(i + 1);
924 ++insertPos;
925 ++m_pendingVisibleIconUpdates;
931 bool KFilePreviewGenerator::Private::decodeIsCutSelection(const QMimeData* mimeData)
933 const QByteArray data = mimeData->data("application/x-kde-cutselection");
934 if (data.isEmpty()) {
935 return false;
936 } else {
937 return data.at(0) == '1';
941 KFilePreviewGenerator::KFilePreviewGenerator(QAbstractItemView* parent) :
942 QObject(parent),
943 d(new Private(this, new KIO::DefaultViewAdapter(parent, this), parent->model()))
945 d->m_itemView = parent;
948 KFilePreviewGenerator::KFilePreviewGenerator(KAbstractViewAdapter* parent, QAbstractProxyModel* model) :
949 QObject(parent),
950 d(new Private(this, parent, model))
954 KFilePreviewGenerator::~KFilePreviewGenerator()
956 delete d;
959 void KFilePreviewGenerator::setPreviewShown(bool show)
961 if (show && (!d->m_viewAdapter->iconSize().isValid() || (d->m_dirModel == 0))) {
962 // the view must provide an icon size and a directory model,
963 // otherwise the showing the previews will get ignored
964 return;
967 if (d->m_previewShown != show) {
968 d->m_previewShown = show;
969 d->m_cutItemsCache.clear();
970 d->updateCutItems();
971 if (show) {
972 updatePreviews();
977 bool KFilePreviewGenerator::isPreviewShown() const
979 return d->m_previewShown;
982 void KFilePreviewGenerator::updatePreviews()
984 if (!d->m_previewShown) {
985 return;
988 d->killPreviewJobs();
989 d->m_cutItemsCache.clear();
990 d->m_pendingItems.clear();
991 d->m_dispatchedItems.clear();
993 KFileItemList itemList;
994 const int rowCount = d->m_dirModel->rowCount();
995 for (int row = 0; row < rowCount; ++row) {
996 const QModelIndex index = d->m_dirModel->index(row, 0);
997 KFileItem item = d->m_dirModel->itemForIndex(index);
998 itemList.append(item);
1001 d->updateIcons(itemList);
1002 d->updateCutItems();
1005 void KFilePreviewGenerator::cancelPreviews()
1007 d->killPreviewJobs();
1008 d->m_cutItemsCache.clear();
1009 d->m_pendingItems.clear();
1010 d->m_dispatchedItems.clear();
1013 void KFilePreviewGenerator::setEnabledPlugins(const QStringList& plugins)
1015 d->m_enabledPlugins = plugins;
1018 QStringList KFilePreviewGenerator::enabledPlugins() const
1020 return d->m_enabledPlugins;
1023 #include "kfilepreviewgenerator.moc"