1 /***************************************************************************
2 * Copyright (C) 2008 by Peter Penz <peter.penz@gmx.at> *
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. *
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. *
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 ***************************************************************************/
20 #include "iconmanager.h"
22 #include "dolphinmodel.h"
23 #include "dolphinsortfilterproxymodel.h"
25 #include <kiconeffect.h>
26 #include <kio/previewjob.h>
27 #include <kdirlister.h>
28 #include <kmimetyperesolver.h>
29 #include <konqmimedata.h>
31 #include <QApplication>
32 #include <QAbstractItemView>
39 IconManager::IconManager(QAbstractItemView
* parent
, DolphinSortFilterProxyModel
* model
) :
42 m_clearItemQueues(true),
49 m_mimeTypeResolver(0),
55 Q_ASSERT(m_view
->iconSize().isValid()); // each view must provide its current icon size
57 m_dolphinModel
= static_cast<DolphinModel
*>(m_proxyModel
->sourceModel());
58 connect(m_dolphinModel
->dirLister(), SIGNAL(newItems(const KFileItemList
&)),
59 this, SLOT(generatePreviews(const KFileItemList
&)));
61 QClipboard
* clipboard
= QApplication::clipboard();
62 connect(clipboard
, SIGNAL(dataChanged()),
63 this, SLOT(updateCutItems()));
65 m_previewTimer
= new QTimer(this);
66 m_previewTimer
->setSingleShot(true);
67 connect(m_previewTimer
, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
69 // Whenever the scrollbar values have been changed, the pending previews should
70 // be reordered in a way that the previews for the visible items are generated
71 // first. The reordering is done with a small delay, so that during moving the
72 // scrollbars the CPU load is kept low.
73 m_scrollAreaTimer
= new QTimer(this);
74 m_scrollAreaTimer
->setSingleShot(true);
75 m_scrollAreaTimer
->setInterval(200);
76 connect(m_scrollAreaTimer
, SIGNAL(timeout()),
77 this, SLOT(resumePreviews()));
78 connect(m_view
->horizontalScrollBar(), SIGNAL(valueChanged(int)),
79 this, SLOT(pausePreviews()));
80 connect(m_view
->verticalScrollBar(), SIGNAL(valueChanged(int)),
81 this, SLOT(pausePreviews()));
84 IconManager::~IconManager()
87 m_pendingItems
.clear();
88 m_dispatchedItems
.clear();
89 if (m_mimeTypeResolver
!= 0) {
90 m_mimeTypeResolver
->deleteLater();
91 m_mimeTypeResolver
= 0;
96 void IconManager::setShowPreview(bool show
)
98 if (m_showPreview
!= show
) {
100 m_cutItemsCache
.clear();
107 if (show
&& (m_mimeTypeResolver
!= 0)) {
108 // don't resolve the MIME types if the preview is turned on
109 m_mimeTypeResolver
->deleteLater();
110 m_mimeTypeResolver
= 0;
111 } else if (!show
&& (m_mimeTypeResolver
== 0)) {
112 // the preview is turned off: resolve the MIME-types so that
113 // the icons gets updated
114 m_mimeTypeResolver
= new KMimeTypeResolver(m_view
, m_dolphinModel
);
118 void IconManager::updatePreviews()
120 if (!m_showPreview
) {
125 m_cutItemsCache
.clear();
126 m_pendingItems
.clear();
127 m_dispatchedItems
.clear();
129 KFileItemList itemList
;
130 const int rowCount
= m_dolphinModel
->rowCount();
131 for (int row
= 0; row
< rowCount
; ++row
) {
132 const QModelIndex index
= m_dolphinModel
->index(row
, 0);
133 KFileItem item
= m_dolphinModel
->itemForIndex(index
);
134 itemList
.append(item
);
137 generatePreviews(itemList
);
141 void IconManager::cancelPreviews()
144 m_cutItemsCache
.clear();
145 m_pendingItems
.clear();
146 m_dispatchedItems
.clear();
149 void IconManager::generatePreviews(const KFileItemList
& items
)
151 applyCutItemEffect();
153 if (!m_showPreview
) {
157 KFileItemList orderedItems
= items
;
158 orderItems(orderedItems
);
160 foreach (const KFileItem
& item
, orderedItems
) {
161 m_pendingItems
.append(item
);
164 startPreviewJob(orderedItems
);
167 void IconManager::addToPreviewQueue(const KFileItem
& item
, const QPixmap
& pixmap
)
170 preview
.url
= item
.url();
171 preview
.pixmap
= pixmap
;
172 m_previews
.append(preview
);
174 m_dispatchedItems
.append(item
);
177 void IconManager::slotPreviewJobFinished(KJob
* job
)
179 const int index
= m_previewJobs
.indexOf(job
);
180 m_previewJobs
.removeAt(index
);
182 if ((m_previewJobs
.count() == 0) && m_clearItemQueues
) {
183 m_pendingItems
.clear();
184 m_dispatchedItems
.clear();
188 void IconManager::updateCutItems()
190 // restore the icons of all previously selected items to the
192 foreach (const ItemInfo
& cutItem
, m_cutItemsCache
) {
193 const QModelIndex index
= m_dolphinModel
->indexForUrl(cutItem
.url
);
194 if (index
.isValid()) {
195 m_dolphinModel
->setData(index
, QIcon(cutItem
.pixmap
), Qt::DecorationRole
);
198 m_cutItemsCache
.clear();
200 // ... and apply an item effect to all currently cut items
201 applyCutItemEffect();
204 void IconManager::dispatchPreviewQueue()
206 int previewsCount
= m_previews
.count();
207 if (previewsCount
> 0) {
208 // Applying the previews to the model must be done step by step
209 // in larger blocks: Applying a preview immediately when getting the signal
210 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
211 // of the view would be triggered for each single preview.
213 int dispatchCount
= 30;
214 if (dispatchCount
> previewsCount
) {
215 dispatchCount
= previewsCount
;
218 for (int i
= 0; i
< dispatchCount
; ++i
) {
219 const ItemInfo
& preview
= m_previews
.first();
220 replaceIcon(preview
.url
, preview
.pixmap
);
221 m_previews
.pop_front();
224 previewsCount
= m_previews
.count();
227 const bool workingPreviewJobs
= (m_previewJobs
.count() > 0);
228 if (workingPreviewJobs
) {
229 // poll for previews as long as not all preview jobs are finished
230 m_previewTimer
->start(200);
231 } else if (previewsCount
> 0) {
232 // all preview jobs are finished but there are still pending previews
233 // in the queue -> poll more aggressively
234 m_previewTimer
->start(10);
238 void IconManager::pausePreviews()
240 foreach (KJob
* job
, m_previewJobs
) {
244 m_scrollAreaTimer
->start();
247 void IconManager::resumePreviews()
249 // Before creating new preview jobs the m_pendingItems queue must be
250 // cleaned up by removing the already dispatched items. Implementation
251 // note: The order of the m_dispatchedItems queue and the m_pendingItems
252 // queue is usually equal. So even when having a lot of elements the
253 // nested loop is no performance bottle neck, as the inner loop is only
254 // entered once in most cases.
255 foreach (const KFileItem
& item
, m_dispatchedItems
) {
256 KFileItemList::iterator begin
= m_pendingItems
.begin();
257 KFileItemList::iterator end
= m_pendingItems
.end();
258 for (KFileItemList::iterator it
= begin
; it
!= end
; ++it
) {
259 if ((*it
).url() == item
.url()) {
260 m_pendingItems
.erase(it
);
265 m_dispatchedItems
.clear();
267 KFileItemList orderedItems
= m_pendingItems
;
268 orderItems(orderedItems
);
270 // Kill all suspended preview jobs. Usually when a preview job
271 // has been finished, slotPreviewJobFinished() clears all item queues.
272 // This is not wanted in this case, as a new job is created afterwards
273 // for m_pendingItems.
274 m_clearItemQueues
= false;
276 m_clearItemQueues
= true;
278 startPreviewJob(orderedItems
);
281 void IconManager::replaceIcon(const KUrl
& url
, const QPixmap
& pixmap
)
283 Q_ASSERT(url
.isValid());
284 if (!m_showPreview
) {
285 // the preview has been canceled in the meantime
289 // check whether the item is part of the directory lister (it is possible
290 // that a preview from an old directory lister is received)
291 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
292 bool isOldPreview
= true;
293 const KUrl::List dirs
= dirLister
->directories();
294 const QString itemDir
= url
.directory();
295 foreach (const KUrl
& url
, dirs
) {
296 if (url
.path() == itemDir
) {
297 isOldPreview
= false;
305 const QModelIndex idx
= m_dolphinModel
->indexForUrl(url
);
306 if (idx
.isValid() && (idx
.column() == 0)) {
307 QPixmap icon
= pixmap
;
309 const KFileItem item
= m_dolphinModel
->itemForIndex(idx
);
310 const QString mimeType
= item
.mimetype();
311 const QString mimeTypeGroup
= mimeType
.left(mimeType
.indexOf('/'));
312 if ((mimeTypeGroup
!= "image") || !applyImageFrame(icon
)) {
313 limitToSize(icon
, m_view
->iconSize());
316 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
317 if (KonqMimeData::decodeIsCutSelection(mimeData
) && isCutItem(item
)) {
318 // Remember the current icon in the cache for cut items before
319 // the disabled effect is applied. This makes it possible restoring
320 // the uncut version again when cutting other items.
321 QList
<ItemInfo
>::iterator begin
= m_cutItemsCache
.begin();
322 QList
<ItemInfo
>::iterator end
= m_cutItemsCache
.end();
323 for (QList
<ItemInfo
>::iterator it
= begin
; it
!= end
; ++it
) {
324 if ((*it
).url
== item
.url()) {
330 // apply the disabled effect to the icon for marking it as "cut item"
331 // and apply the icon to the item
332 KIconEffect iconEffect
;
333 icon
= iconEffect
.apply(icon
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
334 m_dolphinModel
->setData(idx
, QIcon(icon
), Qt::DecorationRole
);
336 m_dolphinModel
->setData(idx
, QIcon(icon
), Qt::DecorationRole
);
341 bool IconManager::isCutItem(const KFileItem
& item
) const
343 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
344 const KUrl::List cutUrls
= KUrl::List::fromMimeData(mimeData
);
346 const KUrl itemUrl
= item
.url();
347 foreach (const KUrl
& url
, cutUrls
) {
348 if (url
== itemUrl
) {
356 void IconManager::applyCutItemEffect()
358 const QMimeData
* mimeData
= QApplication::clipboard()->mimeData();
359 if (!KonqMimeData::decodeIsCutSelection(mimeData
)) {
364 KDirLister
* dirLister
= m_dolphinModel
->dirLister();
365 const KUrl::List dirs
= dirLister
->directories();
366 foreach (const KUrl
& url
, dirs
) {
367 items
<< dirLister
->itemsForDir(url
);
370 foreach (const KFileItem
& item
, items
) {
371 if (isCutItem(item
)) {
372 const QModelIndex index
= m_dolphinModel
->indexForItem(item
);
373 const QVariant value
= m_dolphinModel
->data(index
, Qt::DecorationRole
);
374 if (value
.type() == QVariant::Icon
) {
375 const QIcon
icon(qvariant_cast
<QIcon
>(value
));
376 const QSize actualSize
= icon
.actualSize(m_view
->iconSize());
377 QPixmap pixmap
= icon
.pixmap(actualSize
);
379 // remember current pixmap for the item to be able
380 // to restore it when other items get cut
382 cutItem
.url
= item
.url();
383 cutItem
.pixmap
= pixmap
;
384 m_cutItemsCache
.append(cutItem
);
386 // apply icon effect to the cut item
387 KIconEffect iconEffect
;
388 pixmap
= iconEffect
.apply(pixmap
, KIconLoader::Desktop
, KIconLoader::DisabledState
);
389 m_dolphinModel
->setData(index
, QIcon(pixmap
), Qt::DecorationRole
);
395 bool IconManager::applyImageFrame(QPixmap
& icon
)
397 const QSize maxSize
= m_view
->iconSize();
398 const bool applyFrame
= (maxSize
.width() > KIconLoader::SizeSmallMedium
) &&
399 (maxSize
.height() > KIconLoader::SizeSmallMedium
) &&
400 ((icon
.width() > KIconLoader::SizeLarge
) ||
401 (icon
.height() > KIconLoader::SizeLarge
));
403 // the maximum size or the image itself is too small for a frame
408 const int doubleFrame
= frame
* 2;
410 // resize the icon to the maximum size minus the space required for the frame
411 limitToSize(icon
, QSize(maxSize
.width() - doubleFrame
, maxSize
.height() - doubleFrame
));
414 const QPalette palette
= m_view
->palette();
415 QPixmap
framedIcon(icon
.size().width() + doubleFrame
, icon
.size().height() + doubleFrame
);
416 framedIcon
.fill(palette
.color(QPalette::Normal
, QPalette::Base
));
417 const int width
= framedIcon
.width() - 1;
418 const int height
= framedIcon
.height() - 1;
420 painter
.begin(&framedIcon
);
421 painter
.drawPixmap(frame
, frame
, icon
);
424 painter
.setPen(palette
.color(QPalette::Text
));
425 painter
.setBrush(Qt::NoBrush
);
426 painter
.drawRect(0, 0, width
, height
);
427 painter
.drawRect(1, 1, width
- 2, height
- 2);
429 // dim image frame by 12.5 %
430 painter
.setPen(QColor(0, 0, 0, 32));
431 painter
.drawRect(frame
, frame
, width
- doubleFrame
, height
- doubleFrame
);
436 // provide an alpha channel for the border
437 QPixmap
alphaChannel(icon
.size());
440 QPainter
alphaPainter(&alphaChannel
);
441 alphaPainter
.setBrush(Qt::NoBrush
);
442 alphaPainter
.setPen(QColor(32, 32, 32));
443 alphaPainter
.drawRect(0, 0, width
, height
);
444 alphaPainter
.setPen(QColor(64, 64, 64));
445 alphaPainter
.drawRect(1, 1, width
- 2, height
- 2);
447 icon
.setAlphaChannel(alphaChannel
);
451 void IconManager::limitToSize(QPixmap
& icon
, const QSize
& maxSize
)
453 if ((icon
.width() > maxSize
.width()) || (icon
.height() > maxSize
.height())) {
454 icon
= icon
.scaled(maxSize
, Qt::KeepAspectRatio
, Qt::SmoothTransformation
);
458 void IconManager::startPreviewJob(const KFileItemList
& items
)
460 if (items
.count() == 0) {
464 const QSize size
= m_view
->iconSize();
465 KIO::PreviewJob
* job
= KIO::filePreview(items
, 128, 128);
466 connect(job
, SIGNAL(gotPreview(const KFileItem
&, const QPixmap
&)),
467 this, SLOT(addToPreviewQueue(const KFileItem
&, const QPixmap
&)));
468 connect(job
, SIGNAL(finished(KJob
*)),
469 this, SLOT(slotPreviewJobFinished(KJob
*)));
471 m_previewJobs
.append(job
);
472 m_previewTimer
->start(200);
475 void IconManager::killPreviewJobs()
477 foreach (KJob
* job
, m_previewJobs
) {
481 m_previewJobs
.clear();
484 void IconManager::orderItems(KFileItemList
& items
)
486 // Order the items in a way that the preview for the visible items
487 // is generated first, as this improves the feeled performance a lot.
489 // Implementation note: 2 different algorithms are used for the sorting.
490 // Algorithm 1 is faster when having a lot of items in comparison
491 // to the number of rows in the model. Algorithm 2 is faster
492 // when having quite less items in comparison to the number of rows in
493 // the model. Choosing the right algorithm is important when having directories
494 // with several hundreds or thousands of items.
496 const int itemCount
= items
.count();
497 const int rowCount
= m_proxyModel
->rowCount();
498 const QRect visibleArea
= m_view
->viewport()->rect();
500 if (itemCount
* 10 > rowCount
) {
501 // Algorithm 1: The number of items is > 10 % of the row count. Parse all rows
502 // and check whether the received row is part of the item list.
503 for (int row
= 0; row
< rowCount
; ++row
) {
504 const QModelIndex proxyIndex
= m_proxyModel
->index(row
, 0);
505 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
506 const QModelIndex dirIndex
= m_proxyModel
->mapToSource(proxyIndex
);
508 KFileItem item
= m_dolphinModel
->itemForIndex(dirIndex
); // O(1)
509 const KUrl url
= item
.url();
511 // check whether the item is part of the item list 'items'
513 for (int i
= 0; i
< itemCount
; ++i
) {
514 if (items
[i
].url() == url
) {
520 if ((index
> 0) && itemRect
.intersects(visibleArea
)) {
521 // The current item is (at least partly) visible. Move it
522 // to the front of the list, so that the preview is
523 // generated earlier.
524 items
.removeAt(index
);
525 items
.insert(0, item
);
529 // Algorithm 2: The number of items is <= 10 % of the row count. In this case iterate
530 // all items and receive the corresponding row from the item.
531 for (int i
= 0; i
< itemCount
; ++i
) {
532 const QModelIndex dirIndex
= m_dolphinModel
->indexForItem(items
[i
]); // O(n) (n = number of rows)
533 const QModelIndex proxyIndex
= m_proxyModel
->mapFromSource(dirIndex
);
534 const QRect itemRect
= m_view
->visualRect(proxyIndex
);
536 if (itemRect
.intersects(visibleArea
)) {
537 // The current item is (at least partly) visible. Move it
538 // to the front of the list, so that the preview is
539 // generated earlier.
540 items
.insert(0, items
[i
]);
541 items
.removeAt(i
+ 1);
547 #include "iconmanager.moc"