]> cloud.milkyroute.net Git - dolphin.git/blob - src/iconmanager.cpp
jump to the URL of the clipboard content if a middle click on an empty area inside...
[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 <konqmimedata.h>
29
30 #include <QApplication>
31 #include <QAbstractItemView>
32 #include <QClipboard>
33 #include <QColor>
34 #include <QPainter>
35 #include <QScrollBar>
36 #include <QIcon>
37
38 IconManager::IconManager(QAbstractItemView* parent, DolphinSortFilterProxyModel* model) :
39 QObject(parent),
40 m_showPreview(false),
41 m_clearItemQueues(true),
42 m_view(parent),
43 m_previewTimer(0),
44 m_scrollAreaTimer(0),
45 m_previewJobs(),
46 m_dolphinModel(0),
47 m_proxyModel(model),
48 m_cutItemsCache(),
49 m_previews(),
50 m_pendingItems(),
51 m_dispatchedItems()
52 {
53 Q_ASSERT(m_view->iconSize().isValid()); // each view must provide its current icon size
54
55 m_dolphinModel = static_cast<DolphinModel*>(m_proxyModel->sourceModel());
56 connect(m_dolphinModel->dirLister(), SIGNAL(newItems(const KFileItemList&)),
57 this, SLOT(generatePreviews(const KFileItemList&)));
58
59 QClipboard* clipboard = QApplication::clipboard();
60 connect(clipboard, SIGNAL(dataChanged()),
61 this, SLOT(updateCutItems()));
62
63 m_previewTimer = new QTimer(this);
64 m_previewTimer->setSingleShot(true);
65 connect(m_previewTimer, SIGNAL(timeout()), this, SLOT(dispatchPreviewQueue()));
66
67 // Whenever the scrollbar values have been changed, the pending previews should
68 // be reordered in a way that the previews for the visible items are generated
69 // first. The reordering is done with a small delay, so that during moving the
70 // scrollbars the CPU load is kept low.
71 m_scrollAreaTimer = new QTimer(this);
72 m_scrollAreaTimer->setSingleShot(true);
73 m_scrollAreaTimer->setInterval(200);
74 connect(m_scrollAreaTimer, SIGNAL(timeout()),
75 this, SLOT(resumePreviews()));
76 connect(m_view->horizontalScrollBar(), SIGNAL(valueChanged(int)),
77 this, SLOT(pausePreviews()));
78 connect(m_view->verticalScrollBar(), SIGNAL(valueChanged(int)),
79 this, SLOT(pausePreviews()));
80 }
81
82 IconManager::~IconManager()
83 {
84 killPreviewJobs();
85 m_pendingItems.clear();
86 m_dispatchedItems.clear();
87 }
88
89
90 void IconManager::setShowPreview(bool show)
91 {
92 if (m_showPreview != show) {
93 m_showPreview = show;
94 m_cutItemsCache.clear();
95 updateCutItems();
96 if (show) {
97 updatePreviews();
98 }
99 }
100 }
101
102 void IconManager::updatePreviews()
103 {
104 if (!m_showPreview) {
105 return;
106 }
107
108 killPreviewJobs();
109 m_cutItemsCache.clear();
110 m_pendingItems.clear();
111 m_dispatchedItems.clear();
112
113 KFileItemList itemList;
114 const int rowCount = m_dolphinModel->rowCount();
115 for (int row = 0; row < rowCount; ++row) {
116 const QModelIndex index = m_dolphinModel->index(row, 0);
117 KFileItem item = m_dolphinModel->itemForIndex(index);
118 itemList.append(item);
119 }
120
121 generatePreviews(itemList);
122 updateCutItems();
123 }
124
125 void IconManager::generatePreviews(const KFileItemList& items)
126 {
127 applyCutItemEffect();
128
129 if (!m_showPreview) {
130 return;
131 }
132
133 // Order the items in a way that the preview for the visible items
134 // is generated first, as this improves the feeled performance a lot.
135 const QRect visibleArea = m_view->viewport()->rect();
136 KFileItemList orderedItems;
137 foreach (const KFileItem& item, items) {
138 const QModelIndex dirIndex = m_dolphinModel->indexForItem(item);
139 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
140 const QRect itemRect = m_view->visualRect(proxyIndex);
141 if (itemRect.intersects(visibleArea)) {
142 orderedItems.insert(0, item);
143 m_pendingItems.insert(0, item.url());
144 } else {
145 orderedItems.append(item);
146 m_pendingItems.append(item.url());
147 }
148 }
149
150 startPreviewJob(orderedItems);
151 }
152
153 void IconManager::addToPreviewQueue(const KFileItem& item, const QPixmap& pixmap)
154 {
155 ItemInfo preview;
156 preview.url = item.url();
157 preview.pixmap = pixmap;
158 m_previews.append(preview);
159
160 m_dispatchedItems.append(item.url());
161 }
162
163 void IconManager::slotPreviewJobFinished(KJob* job)
164 {
165 const int index = m_previewJobs.indexOf(job);
166 m_previewJobs.removeAt(index);
167
168 if ((m_previewJobs.count() == 0) && m_clearItemQueues) {
169 m_pendingItems.clear();
170 m_dispatchedItems.clear();
171 }
172 }
173
174 void IconManager::updateCutItems()
175 {
176 // restore the icons of all previously selected items to the
177 // original state...
178 foreach (const ItemInfo& cutItem, m_cutItemsCache) {
179 const QModelIndex index = m_dolphinModel->indexForUrl(cutItem.url);
180 if (index.isValid()) {
181 m_dolphinModel->setData(index, QIcon(cutItem.pixmap), Qt::DecorationRole);
182 }
183 }
184 m_cutItemsCache.clear();
185
186 // ... and apply an item effect to all currently cut items
187 applyCutItemEffect();
188 }
189
190 void IconManager::dispatchPreviewQueue()
191 {
192 int previewsCount = m_previews.count();
193 if (previewsCount > 0) {
194 // Applying the previews to the model must be done step by step
195 // in larger blocks: Applying a preview immediately when getting the signal
196 // 'gotPreview()' from the PreviewJob is too expensive, as a relayout
197 // of the view would be triggered for each single preview.
198
199 int dispatchCount = 30;
200 if (dispatchCount > previewsCount) {
201 dispatchCount = previewsCount;
202 }
203
204 for (int i = 0; i < dispatchCount; ++i) {
205 const ItemInfo& preview = m_previews.first();
206 replaceIcon(preview.url, preview.pixmap);
207 m_previews.pop_front();
208 }
209
210 previewsCount = m_previews.count();
211 }
212
213 const bool workingPreviewJobs = (m_previewJobs.count() > 0);
214 if (workingPreviewJobs) {
215 // poll for previews as long as not all preview jobs are finished
216 m_previewTimer->start(200);
217 } else if (previewsCount > 0) {
218 // all preview jobs are finished but there are still pending previews
219 // in the queue -> poll more aggressively
220 m_previewTimer->start(10);
221 }
222 }
223
224 void IconManager::pausePreviews()
225 {
226 foreach (KJob* job, m_previewJobs) {
227 Q_ASSERT(job != 0);
228 job->suspend();
229 }
230 m_scrollAreaTimer->start();
231 }
232
233 void IconManager::resumePreviews()
234 {
235 // Before creating new preview jobs the m_pendingItems queue must be
236 // cleaned up by removing the already dispatched items. Implementation
237 // note: The order of the m_dispatchedItems queue and the m_pendingItems
238 // queue is usually equal. So even when having a lot of elements the
239 // nested loop is no performance bottle neck, as the inner loop is only
240 // entered once in most cases.
241 foreach (const KUrl& url, m_dispatchedItems) {
242 QList<KUrl>::iterator begin = m_pendingItems.begin();
243 QList<KUrl>::iterator end = m_pendingItems.end();
244 for (QList<KUrl>::iterator it = begin; it != end; ++it) {
245 if ((*it) == url) {
246 m_pendingItems.erase(it);
247 break;
248 }
249 }
250 }
251 m_dispatchedItems.clear();
252
253 // Create a new preview job for the remaining items.
254 // Order the items in a way that the preview for the visible items
255 // is generated first, as this improves the feeled performance a lot.
256 const QRect visibleArea = m_view->viewport()->rect();
257 KFileItemList orderedItems;
258 foreach (const KUrl& url, m_pendingItems) {
259 const QModelIndex dirIndex = m_dolphinModel->indexForUrl(url);
260 const KFileItem item = m_dolphinModel->itemForIndex(dirIndex);
261 const QModelIndex proxyIndex = m_proxyModel->mapFromSource(dirIndex);
262 const QRect itemRect = m_view->visualRect(proxyIndex);
263 if (itemRect.intersects(visibleArea)) {
264 orderedItems.insert(0, item);
265 } else {
266 orderedItems.append(item);
267 }
268 }
269
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;
275 killPreviewJobs();
276 m_clearItemQueues = true;
277
278 startPreviewJob(orderedItems);
279 }
280
281 void IconManager::replaceIcon(const KUrl& url, const QPixmap& pixmap)
282 {
283 Q_ASSERT(url.isValid());
284 if (!m_showPreview) {
285 // the preview has been canceled in the meantime
286 return;
287 }
288
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;
298 break;
299 }
300 }
301 if (isOldPreview) {
302 return;
303 }
304
305 const QModelIndex idx = m_dolphinModel->indexForUrl(url);
306 if (idx.isValid() && (idx.column() == 0)) {
307 QPixmap icon = pixmap;
308
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());
314 }
315
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()) {
325 (*it).pixmap = icon;
326 break;
327 }
328 }
329
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);
335 } else {
336 m_dolphinModel->setData(idx, QIcon(icon), Qt::DecorationRole);
337 }
338 }
339 }
340
341 bool IconManager::isCutItem(const KFileItem& item) const
342 {
343 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
344 const KUrl::List cutUrls = KUrl::List::fromMimeData(mimeData);
345
346 const KUrl itemUrl = item.url();
347 foreach (const KUrl& url, cutUrls) {
348 if (url == itemUrl) {
349 return true;
350 }
351 }
352
353 return false;
354 }
355
356 void IconManager::applyCutItemEffect()
357 {
358 const QMimeData* mimeData = QApplication::clipboard()->mimeData();
359 if (!KonqMimeData::decodeIsCutSelection(mimeData)) {
360 return;
361 }
362
363 KFileItemList items;
364 KDirLister* dirLister = m_dolphinModel->dirLister();
365 const KUrl::List dirs = dirLister->directories();
366 foreach (const KUrl& url, dirs) {
367 items << dirLister->itemsForDir(url);
368 }
369
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);
378
379 // remember current pixmap for the item to be able
380 // to restore it when other items get cut
381 ItemInfo cutItem;
382 cutItem.url = item.url();
383 cutItem.pixmap = pixmap;
384 m_cutItemsCache.append(cutItem);
385
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);
390 }
391 }
392 }
393 }
394
395 bool IconManager::applyImageFrame(QPixmap& icon)
396 {
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));
402 if (!applyFrame) {
403 // the maximum size or the image itself is too small for a frame
404 return false;
405 }
406
407 const int frame = 4;
408 const int doubleFrame = frame * 2;
409
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));
412
413 QPainter painter;
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;
419
420 painter.begin(&framedIcon);
421 painter.drawPixmap(frame, frame, icon);
422
423 // add a border
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);
428
429 // dim image frame by 12.5 %
430 painter.setPen(QColor(0, 0, 0, 32));
431 painter.drawRect(frame, frame, width - doubleFrame, height - doubleFrame);
432 painter.end();
433
434 icon = framedIcon;
435
436 // provide an alpha channel for the border
437 QPixmap alphaChannel(icon.size());
438 alphaChannel.fill();
439
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);
446
447 icon.setAlphaChannel(alphaChannel);
448 return true;
449 }
450
451 void IconManager::limitToSize(QPixmap& icon, const QSize& maxSize)
452 {
453 if ((icon.width() > maxSize.width()) || (icon.height() > maxSize.height())) {
454 icon = icon.scaled(maxSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
455 }
456 }
457
458 void IconManager::startPreviewJob(const KFileItemList& items)
459 {
460 if (items.count() == 0) {
461 return;
462 }
463
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*)));
470
471 m_previewJobs.append(job);
472 m_previewTimer->start(200);
473 }
474
475 void IconManager::killPreviewJobs()
476 {
477 foreach (KJob* job, m_previewJobs) {
478 Q_ASSERT(job != 0);
479 job->kill();
480 }
481 m_previewJobs.clear();
482 }
483
484 #include "iconmanager.moc"