]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
only resolve the MIME-types asynchronously, if no preview is generated
[dolphin.git] / src / iconmanager.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 "iconmanager.h"
21
22 #include "dolphinmodel.h"
23 #include "dolphinsortfilterproxymodel.h"
24
25 #include <kiconeffect.h>
26 #include <kio/previewjob.h>
27 #include <kdirlister.h>
28 #include <kmimetyperesolver.h>
29 #include <konqmimedata.h>
30
31 #include <QApplication>
32 #include <QAbstractItemView>
33 #include <QClipboard>
34 #include <QColor>
35 #include <QPainter>
36 #include <QScrollBar>
37 #include <QIcon>
38
39 IconManager::IconManager(QAbstractItemView* parent, DolphinSortFilterProxyModel* model) :
40 QObject(parent),
41 m_showPreview(false),
42 m_clearItemQueues(true),
43 m_view(parent),
44 m_previewTimer(0),
45 m_scrollAreaTimer(0),
46 m_previewJobs(),
47 m_dolphinModel(0),
48 m_proxyModel(model),
49 m_mimeTypeResolver(0),
50 m_cutItemsCache(),
51 m_previews(),
52 m_pendingItems(),
53 m_dispatchedItems()
54 {
55 Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size
56
57 m_dolphinModel = static_cast<DolphinModel*>(m_proxyModel->sourceModel());
58 connect(m_dolphinModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
59 this, SLOT(generatePreviews(const KFileItemList&)));
60
61 QClipboard* clipboard = QApplication::clipboard();
62 connect(clipboard, SIGNAL(dataChanged()),
63 this, SLOT(updateCutItems()));
64
65 m_previewTimer = new QTimer(this);
66 m_previewTimer->setSingleShot(true);
67 connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
68
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()));
82 }
83
84 IconManager::~IconManager()
85 {
86 killPreviewJobs();
87 m_pendingItems.clear();
88 m_dispatchedItems.clear();
89 }
90
91
92 void IconManager::setShowPreview(bool show)
93 {
94 if (m_showPreview != show) {
95 m_showPreview = show;
96 m_cutItemsCache.clear();
97 updateCutItems();
98 if (show) {
99 updatePreviews();
100 }
101 }
102
103 if (show && (m_mimeTypeResolver != 0)) {
104 // don't resolve the MIME types if the preview is turned on
105 m_mimeTypeResolver->deleteLater();
106 m_mimeTypeResolver = 0;
107 } else if (!show && (m_mimeTypeResolver == 0)) {
108 // the preview is turned off: resolve the MIME-types so that
109 // the icons gets updated
110 m_mimeTypeResolver = new KMimeTypeResolver(m_view, m_dolphinModel);
111 }
112 }
113
114 void IconManager::updatePreviews()
115 {
116 if (!m_showPreview) {
117 return;
118 }
119
120 killPreviewJobs();
121 m_cutItemsCache.clear();
122 m_pendingItems.clear();
123 m_dispatchedItems.clear();
124
125 KFileItemList itemList;
126 const int rowCount = m_dolphinModel->rowCount();
127 for (int row = 0; row < rowCount; ++row) {
128 const QModelIndex index = m_dolphinModel->index(row, 0);
129 KFileItem item = m_dolphinModel->itemForIndex(index);
130 itemList.append(item);
131 }
132
133 generatePreviews(itemList);
134 updateCutItems();
135 }
136
137 void IconManager::generatePreviews(const KFileItemList& items)
138 {
139 applyCutItemEffect();
140
141 if (!m_showPreview) {
142 return;
143 }
144
145 // Order the items in a way that the preview for the visible items
146 // is generated first, as this improves the feeled performance a lot.
147 const QRect visibleArea = m_view->viewport()->rect();
148 KFileItemList orderedItems;
149 foreach (const KFileItem& item, items) {
150 const QModelIndex dirIndex = m_dolphinModel->indexForItem(item);
151 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
152 const QRect itemRect = m_view->visualRect(proxyIndex);
153 if (itemRect.intersects(visibleArea)) {
154 orderedItems.insert(0, item);
155 m_pendingItems.insert(0, item.url());
156 } else {
157 orderedItems.append(item);
158 m_pendingItems.append(item.url());
159 }
160 }
161
162 startPreviewJob(orderedItems);
163 }
164
165 void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
166 {
167 ItemInfo preview;
168 preview.url = item.url();
169 preview.pixmap = pixmap;
170 m_previews.append(preview);
171
172 m_dispatchedItems.append(item.url());
173 }
174
175 void IconManager::slotPreviewJobFinished(KJob* job)
176 {
177 const int index = m_previewJobs.indexOf(job);
178 m_previewJobs.removeAt(index);
179
180 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
181 m_pendingItems.clear();
182 m_dispatchedItems.clear();
183 }
184 }
185
186 void IconManager::updateCutItems()
187 {
188 // restore the icons of all previously selected items to the
189 // original state...
190 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
191 const QModelIndex index = m_dolphinModel->indexForUrl(cutItem.url);
192 if (index.isValid()) {
193 m_dolphinModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
194 }
195 }
196 m_cutItemsCache.clear();
197
198 // ... and apply an item effect to all currently cut items
199 applyCutItemEffect();
200 }
201
202 void IconManager::dispatchPreviewQueue()
203 {
204 int previewsCount = m_previews.count();
205 if (previewsCount > 0) {
206 // Applying the previews to the model must be done step by step
207 // in larger blocks: Applying a preview immediately when getting the signal
208 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
209 // of the view would be triggered for each single preview.
210
211 int dispatchCount = 30;
212 if (dispatchCount > previewsCount) {
213 dispatchCount = previewsCount;
214 }
215
216 for (int i = 0; i < dispatchCount; ++i) {
217 const ItemInfo& preview = m_previews.first();
218 replaceIcon(preview.url, preview.pixmap);
219 m_previews.pop_front();
220 }
221
222 previewsCount = m_previews.count();
223 }
224
225 const bool workingPreviewJobs = (m_previewJobs.count() > 0);
226 if (workingPreviewJobs) {
227 // poll for previews as long as not all preview jobs are finished
228 m_previewTimer->start(200);
229 } else if (previewsCount > 0) {
230 // all preview jobs are finished but there are still pending previews
231 // in the queue -> poll more aggressively
232 m_previewTimer->start(10);
233 }
234 }
235
236 void IconManager::pausePreviews()
237 {
238 foreach (KJob* job, m_previewJobs) {
239 Q_ASSERT(job != 0);
240 job->suspend();
241 }
242 m_scrollAreaTimer->start();
243 }
244
245 void IconManager::resumePreviews()
246 {
247 // Before creating new preview jobs the m_pendingItems queue must be
248 // cleaned up by removing the already dispatched items. Implementation
249 // note: The order of the m_dispatchedItems queue and the m_pendingItems
250 // queue is usually equal. So even when having a lot of elements the
251 // nested loop is no performance bottle neck, as the inner loop is only
252 // entered once in most cases.
253 foreach (const KUrl& url, m_dispatchedItems) {
254 QList<KUrl>::iterator begin = m_pendingItems.begin();
255 QList<KUrl>::iterator end = m_pendingItems.end();
256 for (QList<KUrl>::iterator it = begin; it != end; ++it) {
257 if ((*it) == url) {
258 m_pendingItems.erase(it);
259 break;
260 }
261 }
262 }
263 m_dispatchedItems.clear();
264
265 // Create a new preview job for the remaining items.
266 // Order the items in a way that the preview for the visible items
267 // is generated first, as this improves the feeled performance a lot.
268 const QRect visibleArea = m_view->viewport()->rect();
269 KFileItemList orderedItems;
270 foreach (const KUrl& url, m_pendingItems) {
271 const QModelIndex dirIndex = m_dolphinModel->indexForUrl(url);
272 const KFileItem item = m_dolphinModel->itemForIndex(dirIndex);
273 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
274 const QRect itemRect = m_view->visualRect(proxyIndex);
275 if (itemRect.intersects(visibleArea)) {
276 orderedItems.insert(0, item);
277 } else {
278 orderedItems.append(item);
279 }
280 }
281
282 // Kill all suspended preview jobs. Usually when a preview job
283 // has been finished, slotPreviewJobFinished() clears all item queues.
284 // This is not wanted in this case, as a new job is created afterwards
285 // for m_pendingItems.
286 m_clearItemQueues = false;
287 killPreviewJobs();
288 m_clearItemQueues = true;
289
290 startPreviewJob(orderedItems);
291 }
292
293 void IconManager::replaceIcon(const KUrl& url, const QPixmap& pixmap)
294 {
295 Q_ASSERT(url.isValid());
296 if (!m_showPreview) {
297 // the preview has been canceled in the meantime
298 return;
299 }
300
301 // check whether the item is part of the directory lister (it is possible
302 // that a preview from an old directory lister is received)
303 KDirLister* dirLister = m_dolphinModel->dirLister();
304 bool isOldPreview = true;
305 const KUrl::List dirs = dirLister->directories();
306 const QString itemDir = url.directory();
307 foreach (const KUrl& url, dirs) {
308 if (url.path() == itemDir) {
309 isOldPreview = false;
310 break;
311 }
312 }
313 if (isOldPreview) {
314 return;
315 }
316
317 const QModelIndex idx = m_dolphinModel->indexForUrl(url);
318 if (idx.isValid() && (idx.column() == 0)) {
319 QPixmap icon = pixmap;
320
321 const KFileItem item = m_dolphinModel->itemForIndex(idx);
322 const QString mimeType = item.mimetype();
323 const QString mimeTypeGroup = mimeType.left(mimeType.indexOf('/'));
324 if ((mimeTypeGroup != "image") || !applyImageFrame(icon)) {
325 limitToSize(icon, m_view->iconSize());
326 }
327
328 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
329 if (KonqMimeData::decodeIsCutSelection(mimeData) && isCutItem(item)) {
330 // Remember the current icon in the cache for cut items before
331 // the disabled effect is applied. This makes it possible restoring
332 // the uncut version again when cutting other items.
333 QList<ItemInfo>::iterator begin = m_cutItemsCache.begin();
334 QList<ItemInfo>::iterator end = m_cutItemsCache.end();
335 for (QList<ItemInfo>::iterator it = begin; it != end; ++it) {
336 if ((*it).url == item.url()) {
337 (*it).pixmap = icon;
338 break;
339 }
340 }
341
342 // apply the disabled effect to the icon for marking it as "cut item"
343 // and apply the icon to the item
344 KIconEffect iconEffect;
345 icon = iconEffect.apply(icon, KIconLoader::Desktop, KIconLoader::DisabledState);
346 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
347 } else {
348 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
349 }
350 }
351 }
352
353 bool IconManager::isCutItem(const KFileItem& item) const
354 {
355 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
356 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
357
358 const KUrl itemUrl = item.url();
359 foreach (const KUrl& url, cutUrls) {
360 if (url == itemUrl) {
361 return true;
362 }
363 }
364
365 return false;
366 }
367
368 void IconManager::applyCutItemEffect()
369 {
370 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
371 if (!KonqMimeData::decodeIsCutSelection(mimeData)) {
372 return;
373 }
374
375 KFileItemList items;
376 KDirLister* dirLister = m_dolphinModel->dirLister();
377 const KUrl::List dirs = dirLister->directories();
378 foreach (const KUrl& url, dirs) {
379 items << dirLister->itemsForDir(url);
380 }
381
382 foreach (const KFileItem& item, items) {
383 if (isCutItem(item)) {
384 const QModelIndex index = m_dolphinModel->indexForItem(item);
385 const QVariant value = m_dolphinModel->data(index, Qt::DecorationRole);
386 if (value.type() == QVariant::Icon) {
387 const QIcon icon(qvariant_cast<QIcon>(value));
388 const QSize actualSize = icon.actualSize(m_view->iconSize());
389 QPixmap pixmap = icon.pixmap(actualSize);
390
391 // remember current pixmap for the item to be able
392 // to restore it when other items get cut
393 ItemInfo cutItem;
394 cutItem.url = item.url();
395 cutItem.pixmap = pixmap;
396 m_cutItemsCache.append(cutItem);
397
398 // apply icon effect to the cut item
399 KIconEffect iconEffect;
400 pixmap = iconEffect.apply(pixmap, KIconLoader::Desktop, KIconLoader::DisabledState);
401 m_dolphinModel->setData(index, QIcon(pixmap), Qt::DecorationRole);
402 }
403 }
404 }
405 }
406
407 bool IconManager::applyImageFrame(QPixmap& icon)
408 {
409 const QSize maxSize = m_view->iconSize();
410 const bool applyFrame = (maxSize.width() > KIconLoader::SizeSmallMedium) &&
411 (maxSize.height() > KIconLoader::SizeSmallMedium) &&
412 ((icon.width() > KIconLoader::SizeLarge) ||
413 (icon.height() > KIconLoader::SizeLarge));
414 if (!applyFrame) {
415 // the maximum size or the image itself is too small for a frame
416 return false;
417 }
418
419 const int frame = 4;
420 const int doubleFrame = frame * 2;
421
422 // resize the icon to the maximum size minus the space required for the frame
423 limitToSize(icon, QSize(maxSize.width() - doubleFrame, maxSize.height() - doubleFrame));
424
425 QPainter painter;
426 const QPalette palette = m_view->palette();
427 QPixmap framedIcon(icon.size().width() + doubleFrame, icon.size().height() + doubleFrame);
428 framedIcon.fill(palette.color(QPalette::Normal, QPalette::Base));
429 const int width = framedIcon.width() - 1;
430 const int height = framedIcon.height() - 1;
431
432 painter.begin(&framedIcon);
433 painter.drawPixmap(frame, frame, icon);
434
435 // add a border
436 painter.setPen(palette.color(QPalette::Text));
437 painter.setBrush(Qt::NoBrush);
438 painter.drawRect(0, 0, width, height);
439 painter.drawRect(1, 1, width - 2, height - 2);
440
441 // dim image frame by 12.5 %
442 painter.setPen(QColor(0, 0, 0, 32));
443 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
444 painter.end();
445
446 icon = framedIcon;
447
448 // provide an alpha channel for the border
449 QPixmap alphaChannel(icon.size());
450 alphaChannel.fill();
451
452 QPainter alphaPainter(&alphaChannel);
453 alphaPainter.setBrush(Qt::NoBrush);
454 alphaPainter.setPen(QColor(32, 32, 32));
455 alphaPainter.drawRect(0, 0, width, height);
456 alphaPainter.setPen(QColor(64, 64, 64));
457 alphaPainter.drawRect(1, 1, width - 2, height - 2);
458
459 icon.setAlphaChannel(alphaChannel);
460 return true;
461 }
462
463 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
464 {
465 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
466 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
467 }
468 }
469
470 void IconManager::startPreviewJob(const KFileItemList& items)
471 {
472 if (items.count() == 0) {
473 return;
474 }
475
476 const QSize size = m_view->iconSize();
477 KIO::PreviewJob* job = KIO::filePreview(items, 128, 128);
478 connect(job, SIGNAL(gotPreview(const KFileItem&, const QPixmap&)),
479 this, SLOT(addToPreviewQueue(const KFileItem&, const QPixmap&)));
480 connect(job, SIGNAL(finished(KJob*)),
481 this, SLOT(slotPreviewJobFinished(KJob*)));
482
483 m_previewJobs.append(job);
484 m_previewTimer->start(200);
485 }
486
487 void IconManager::killPreviewJobs()
488 {
489 foreach (KJob* job, m_previewJobs) {
490 Q_ASSERT(job != 0);
491 job->kill();
492 }
493 m_previewJobs.clear();
494 }
495
496 #include "iconmanager.moc"