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