]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodelrolesupdater.cpp
Don't filter out duplicated entries from places panel
[dolphin.git] / src / kitemviews / kfileitemmodelrolesupdater.cpp
1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
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 "kfileitemmodelrolesupdater.h"
21
22 #include "kfileitemmodel.h"
23 #include "private/kdirectorycontentscounter.h"
24 #include "private/kpixmapmodifier.h"
25
26 #include <KConfig>
27 #include <KConfigGroup>
28 #include <KIO/JobUiDelegate>
29 #include <KIO/PreviewJob>
30 #include <KIconLoader>
31 #include <KJobWidgets>
32 #include <KOverlayIconPlugin>
33 #include <KPluginLoader>
34 #include <KSharedConfig>
35
36 #ifdef HAVE_BALOO
37 #include "private/kbaloorolesprovider.h"
38 #include <Baloo/File>
39 #include <Baloo/FileMonitor>
40 #endif
41
42 #include <QApplication>
43 #include <QPainter>
44 #include <QElapsedTimer>
45 #include <QTimer>
46
47
48 // #define KFILEITEMMODELROLESUPDATER_DEBUG
49
50 namespace {
51 // Maximum time in ms that the KFileItemModelRolesUpdater
52 // may perform a blocking operation
53 const int MaxBlockTimeout = 200;
54
55 // If the number of items is smaller than ResolveAllItemsLimit,
56 // the roles of all items will be resolved.
57 const int ResolveAllItemsLimit = 500;
58
59 // Not only the visible area, but up to ReadAheadPages before and after
60 // this area will be resolved.
61 const int ReadAheadPages = 5;
62 }
63
64 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel* model, QObject* parent) :
65 QObject(parent),
66 m_state(Idle),
67 m_previewChangedDuringPausing(false),
68 m_iconSizeChangedDuringPausing(false),
69 m_rolesChangedDuringPausing(false),
70 m_previewShown(false),
71 m_enlargeSmallPreviews(true),
72 m_clearPreviews(false),
73 m_finishedItems(),
74 m_model(model),
75 m_iconSize(),
76 m_firstVisibleIndex(0),
77 m_lastVisibleIndex(-1),
78 m_maximumVisibleItems(50),
79 m_roles(),
80 m_resolvableRoles(),
81 m_enabledPlugins(),
82 m_pendingSortRoleItems(),
83 m_pendingIndexes(),
84 m_pendingPreviewItems(),
85 m_previewJob(),
86 m_recentlyChangedItemsTimer(nullptr),
87 m_recentlyChangedItems(),
88 m_changedItems(),
89 m_directoryContentsCounter(nullptr)
90 #ifdef HAVE_BALOO
91 , m_balooFileMonitor(nullptr)
92 #endif
93 {
94 Q_ASSERT(model);
95
96 const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
97 m_enabledPlugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
98
99 connect(m_model, &KFileItemModel::itemsInserted,
100 this, &KFileItemModelRolesUpdater::slotItemsInserted);
101 connect(m_model, &KFileItemModel::itemsRemoved,
102 this, &KFileItemModelRolesUpdater::slotItemsRemoved);
103 connect(m_model, &KFileItemModel::itemsChanged,
104 this, &KFileItemModelRolesUpdater::slotItemsChanged);
105 connect(m_model, &KFileItemModel::itemsMoved,
106 this, &KFileItemModelRolesUpdater::slotItemsMoved);
107 connect(m_model, &KFileItemModel::sortRoleChanged,
108 this, &KFileItemModelRolesUpdater::slotSortRoleChanged);
109
110 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
111 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
112 m_recentlyChangedItemsTimer = new QTimer(this);
113 m_recentlyChangedItemsTimer->setInterval(1000);
114 m_recentlyChangedItemsTimer->setSingleShot(true);
115 connect(m_recentlyChangedItemsTimer, &QTimer::timeout, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems);
116
117 m_resolvableRoles.insert("size");
118 m_resolvableRoles.insert("type");
119 m_resolvableRoles.insert("isExpandable");
120 #ifdef HAVE_BALOO
121 m_resolvableRoles += KBalooRolesProvider::instance().roles();
122 #endif
123
124 m_directoryContentsCounter = new KDirectoryContentsCounter(m_model, this);
125 connect(m_directoryContentsCounter, &KDirectoryContentsCounter::result,
126 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived);
127
128 auto plugins = KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp);
129 foreach (QObject *it, plugins) {
130 auto plugin = qobject_cast<KOverlayIconPlugin*>(it);
131 if (plugin) {
132 m_overlayIconsPlugin.append(plugin);
133 connect(plugin, &KOverlayIconPlugin::overlaysChanged, this, &KFileItemModelRolesUpdater::slotOverlaysChanged);
134 } else {
135 // not our/valid plugin, so delete the created object
136 it->deleteLater();
137 }
138 }
139 }
140
141 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
142 {
143 killPreviewJob();
144 }
145
146 void KFileItemModelRolesUpdater::setIconSize(const QSize& size)
147 {
148 if (size != m_iconSize) {
149 m_iconSize = size;
150 if (m_state == Paused) {
151 m_iconSizeChangedDuringPausing = true;
152 } else if (m_previewShown) {
153 // An icon size change requires the regenerating of
154 // all previews
155 m_finishedItems.clear();
156 startUpdating();
157 }
158 }
159 }
160
161 QSize KFileItemModelRolesUpdater::iconSize() const
162 {
163 return m_iconSize;
164 }
165
166 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index, int count)
167 {
168 if (index < 0) {
169 index = 0;
170 }
171 if (count < 0) {
172 count = 0;
173 }
174
175 if (index == m_firstVisibleIndex && count == m_lastVisibleIndex - m_firstVisibleIndex + 1) {
176 // The range has not been changed
177 return;
178 }
179
180 m_firstVisibleIndex = index;
181 m_lastVisibleIndex = qMin(index + count - 1, m_model->count() - 1);
182
183 startUpdating();
184 }
185
186 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count)
187 {
188 m_maximumVisibleItems = count;
189 }
190
191 void KFileItemModelRolesUpdater::setPreviewsShown(bool show)
192 {
193 if (show == m_previewShown) {
194 return;
195 }
196
197 m_previewShown = show;
198 if (!show) {
199 m_clearPreviews = true;
200 }
201
202 updateAllPreviews();
203 }
204
205 bool KFileItemModelRolesUpdater::previewsShown() const
206 {
207 return m_previewShown;
208 }
209
210 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge)
211 {
212 if (enlarge != m_enlargeSmallPreviews) {
213 m_enlargeSmallPreviews = enlarge;
214 if (m_previewShown) {
215 updateAllPreviews();
216 }
217 }
218 }
219
220 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
221 {
222 return m_enlargeSmallPreviews;
223 }
224
225 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList& list)
226 {
227 if (m_enabledPlugins != list) {
228 m_enabledPlugins = list;
229 if (m_previewShown) {
230 updateAllPreviews();
231 }
232 }
233 }
234
235 void KFileItemModelRolesUpdater::setPaused(bool paused)
236 {
237 if (paused == (m_state == Paused)) {
238 return;
239 }
240
241 if (paused) {
242 m_state = Paused;
243 killPreviewJob();
244 } else {
245 const bool updatePreviews = (m_iconSizeChangedDuringPausing && m_previewShown) ||
246 m_previewChangedDuringPausing;
247 const bool resolveAll = updatePreviews || m_rolesChangedDuringPausing;
248 if (resolveAll) {
249 m_finishedItems.clear();
250 }
251
252 m_iconSizeChangedDuringPausing = false;
253 m_previewChangedDuringPausing = false;
254 m_rolesChangedDuringPausing = false;
255
256 if (!m_pendingSortRoleItems.isEmpty()) {
257 m_state = ResolvingSortRole;
258 resolveNextSortRole();
259 } else {
260 m_state = Idle;
261 }
262
263 startUpdating();
264 }
265 }
266
267 void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray>& roles)
268 {
269 if (m_roles != roles) {
270 m_roles = roles;
271
272 #ifdef HAVE_BALOO
273 // Check whether there is at least one role that must be resolved
274 // with the help of Baloo. If this is the case, a (quite expensive)
275 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
276 // the role gets watched for changes.
277 const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance();
278 bool hasBalooRole = false;
279 QSetIterator<QByteArray> it(roles);
280 while (it.hasNext()) {
281 const QByteArray& role = it.next();
282 if (rolesProvider.roles().contains(role)) {
283 hasBalooRole = true;
284 break;
285 }
286 }
287
288 if (hasBalooRole && m_balooConfig.fileIndexingEnabled() && !m_balooFileMonitor) {
289 m_balooFileMonitor = new Baloo::FileMonitor(this);
290 connect(m_balooFileMonitor, &Baloo::FileMonitor::fileMetaDataChanged,
291 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles);
292 } else if (!hasBalooRole && m_balooFileMonitor) {
293 delete m_balooFileMonitor;
294 m_balooFileMonitor = nullptr;
295 }
296 #endif
297
298 if (m_state == Paused) {
299 m_rolesChangedDuringPausing = true;
300 } else {
301 startUpdating();
302 }
303 }
304 }
305
306 QSet<QByteArray> KFileItemModelRolesUpdater::roles() const
307 {
308 return m_roles;
309 }
310
311 bool KFileItemModelRolesUpdater::isPaused() const
312 {
313 return m_state == Paused;
314 }
315
316 QStringList KFileItemModelRolesUpdater::enabledPlugins() const
317 {
318 return m_enabledPlugins;
319 }
320
321 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList& itemRanges)
322 {
323 QElapsedTimer timer;
324 timer.start();
325
326 // Determine the sort role synchronously for as many items as possible.
327 if (m_resolvableRoles.contains(m_model->sortRole())) {
328 int insertedCount = 0;
329 foreach (const KItemRange& range, itemRanges) {
330 const int lastIndex = insertedCount + range.index + range.count - 1;
331 for (int i = insertedCount + range.index; i <= lastIndex; ++i) {
332 if (timer.elapsed() < MaxBlockTimeout) {
333 applySortRole(i);
334 } else {
335 m_pendingSortRoleItems.insert(m_model->fileItem(i));
336 }
337 }
338 insertedCount += range.count;
339 }
340
341 applySortProgressToModel();
342
343 // If there are still items whose sort role is unknown, check if the
344 // asynchronous determination of the sort role is already in progress,
345 // and start it if that is not the case.
346 if (!m_pendingSortRoleItems.isEmpty() && m_state != ResolvingSortRole) {
347 killPreviewJob();
348 m_state = ResolvingSortRole;
349 resolveNextSortRole();
350 }
351 }
352
353 startUpdating();
354 }
355
356 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList& itemRanges)
357 {
358 Q_UNUSED(itemRanges);
359
360 const bool allItemsRemoved = (m_model->count() == 0);
361
362 #ifdef HAVE_BALOO
363 if (m_balooFileMonitor) {
364 // Don't let the FileWatcher watch for removed items
365 if (allItemsRemoved) {
366 m_balooFileMonitor->clear();
367 } else {
368 QStringList newFileList;
369 foreach (const QString& file, m_balooFileMonitor->files()) {
370 if (m_model->index(QUrl::fromLocalFile(file)) >= 0) {
371 newFileList.append(file);
372 }
373 }
374 m_balooFileMonitor->setFiles(newFileList);
375 }
376 }
377 #endif
378
379 if (allItemsRemoved) {
380 m_state = Idle;
381
382 m_finishedItems.clear();
383 m_pendingSortRoleItems.clear();
384 m_pendingIndexes.clear();
385 m_pendingPreviewItems.clear();
386 m_recentlyChangedItems.clear();
387 m_recentlyChangedItemsTimer->stop();
388 m_changedItems.clear();
389
390 killPreviewJob();
391 } else {
392 // Only remove the items from m_finishedItems. They will be removed
393 // from the other sets later on.
394 QSet<KFileItem>::iterator it = m_finishedItems.begin();
395 while (it != m_finishedItems.end()) {
396 if (m_model->index(*it) < 0) {
397 it = m_finishedItems.erase(it);
398 } else {
399 ++it;
400 }
401 }
402
403 // The visible items might have changed.
404 startUpdating();
405 }
406 }
407
408 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange& itemRange, QList<int> movedToIndexes)
409 {
410 Q_UNUSED(itemRange);
411 Q_UNUSED(movedToIndexes);
412
413 // The visible items might have changed.
414 startUpdating();
415 }
416
417 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList& itemRanges,
418 const QSet<QByteArray>& roles)
419 {
420 Q_UNUSED(roles);
421
422 // Find out if slotItemsChanged() has been done recently. If that is the
423 // case, resolving the roles is postponed until a timer has exceeded
424 // to prevent expensive repeated updates if files are updated frequently.
425 const bool itemsChangedRecently = m_recentlyChangedItemsTimer->isActive();
426
427 QSet<KFileItem>& targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems;
428
429 foreach (const KItemRange& itemRange, itemRanges) {
430 int index = itemRange.index;
431 for (int count = itemRange.count; count > 0; --count) {
432 const KFileItem item = m_model->fileItem(index);
433 targetSet.insert(item);
434 ++index;
435 }
436 }
437
438 m_recentlyChangedItemsTimer->start();
439
440 if (!itemsChangedRecently) {
441 updateChangedItems();
442 }
443 }
444
445 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray& current,
446 const QByteArray& previous)
447 {
448 Q_UNUSED(current);
449 Q_UNUSED(previous);
450
451 if (m_resolvableRoles.contains(current)) {
452 m_pendingSortRoleItems.clear();
453 m_finishedItems.clear();
454
455 const int count = m_model->count();
456 QElapsedTimer timer;
457 timer.start();
458
459 // Determine the sort role synchronously for as many items as possible.
460 for (int index = 0; index < count; ++index) {
461 if (timer.elapsed() < MaxBlockTimeout) {
462 applySortRole(index);
463 } else {
464 m_pendingSortRoleItems.insert(m_model->fileItem(index));
465 }
466 }
467
468 applySortProgressToModel();
469
470 if (!m_pendingSortRoleItems.isEmpty()) {
471 // Trigger the asynchronous determination of the sort role.
472 killPreviewJob();
473 m_state = ResolvingSortRole;
474 resolveNextSortRole();
475 }
476 } else {
477 m_state = Idle;
478 m_pendingSortRoleItems.clear();
479 applySortProgressToModel();
480 }
481 }
482
483 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem& item, const QPixmap& pixmap)
484 {
485 if (m_state != PreviewJobRunning) {
486 return;
487 }
488
489 m_changedItems.remove(item);
490
491 const int index = m_model->index(item);
492 if (index < 0) {
493 return;
494 }
495
496 QPixmap scaledPixmap = pixmap;
497
498 const QString mimeType = item.mimetype();
499 const int slashIndex = mimeType.indexOf(QLatin1Char('/'));
500 const bool isFontPreview = mimeType.right(slashIndex).contains(QLatin1String("font"));
501 const bool isFolderPreview = item.isDir();
502 const bool isWindowsExePreview = mimeType == QLatin1String("application/x-ms-dos-executable") ||
503 mimeType == QLatin1String("application/x-msdownload");
504
505 if (!isFolderPreview && !isFontPreview && !isWindowsExePreview) {
506 if (m_enlargeSmallPreviews) {
507 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
508 } else {
509 // Assure that small previews don't get enlarged. Instead they
510 // should be shown centered within the frame.
511 const QSize contentSize = KPixmapModifier::sizeInsideFrame(m_iconSize);
512 const bool enlargingRequired = scaledPixmap.width() < contentSize.width() &&
513 scaledPixmap.height() < contentSize.height();
514 if (enlargingRequired) {
515 QSize frameSize = scaledPixmap.size() / scaledPixmap.devicePixelRatio();
516 frameSize.scale(m_iconSize, Qt::KeepAspectRatio);
517
518 QPixmap largeFrame(frameSize);
519 largeFrame.fill(Qt::transparent);
520
521 KPixmapModifier::applyFrame(largeFrame, frameSize);
522
523 QPainter painter(&largeFrame);
524 painter.drawPixmap((largeFrame.width() - scaledPixmap.width() / scaledPixmap.devicePixelRatio()) / 2,
525 (largeFrame.height() - scaledPixmap.height() / scaledPixmap.devicePixelRatio()) / 2,
526 scaledPixmap);
527 scaledPixmap = largeFrame;
528 } else {
529 // The image must be shrinked as it is too large to fit into
530 // the available icon size
531 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
532 }
533 }
534 } else {
535 KPixmapModifier::scale(scaledPixmap, m_iconSize);
536 }
537
538 QHash<QByteArray, QVariant> data = rolesData(item);
539
540 const QStringList overlays = data["iconOverlays"].toStringList();
541 // Strangely KFileItem::overlays() returns empty string-values, so
542 // we need to check first whether an overlay must be drawn at all.
543 // It is more efficient to do it here, as KIconLoader::drawOverlays()
544 // assumes that an overlay will be drawn and has some additional
545 // setup time.
546 foreach (const QString& overlay, overlays) {
547 if (!overlay.isEmpty()) {
548 // There is at least one overlay, draw all overlays above m_pixmap
549 // and cancel the check
550 KIconLoader::global()->drawOverlays(overlays, scaledPixmap, KIconLoader::Desktop);
551 break;
552 }
553 }
554
555 data.insert("iconPixmap", scaledPixmap);
556
557 disconnect(m_model, &KFileItemModel::itemsChanged,
558 this, &KFileItemModelRolesUpdater::slotItemsChanged);
559 m_model->setData(index, data);
560 connect(m_model, &KFileItemModel::itemsChanged,
561 this, &KFileItemModelRolesUpdater::slotItemsChanged);
562
563 m_finishedItems.insert(item);
564 }
565
566 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem& item)
567 {
568 if (m_state != PreviewJobRunning) {
569 return;
570 }
571
572 m_changedItems.remove(item);
573
574 const int index = m_model->index(item);
575 if (index >= 0) {
576 QHash<QByteArray, QVariant> data;
577 data.insert("iconPixmap", QPixmap());
578
579 disconnect(m_model, &KFileItemModel::itemsChanged,
580 this, &KFileItemModelRolesUpdater::slotItemsChanged);
581 m_model->setData(index, data);
582 connect(m_model, &KFileItemModel::itemsChanged,
583 this, &KFileItemModelRolesUpdater::slotItemsChanged);
584
585 applyResolvedRoles(index, ResolveAll);
586 m_finishedItems.insert(item);
587 }
588 }
589
590 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
591 {
592 m_previewJob = nullptr;
593
594 if (m_state != PreviewJobRunning) {
595 return;
596 }
597
598 m_state = Idle;
599
600 if (!m_pendingPreviewItems.isEmpty()) {
601 startPreviewJob();
602 } else {
603 if (!m_changedItems.isEmpty()) {
604 updateChangedItems();
605 }
606 }
607 }
608
609 void KFileItemModelRolesUpdater::resolveNextSortRole()
610 {
611 if (m_state != ResolvingSortRole) {
612 return;
613 }
614
615 QSet<KFileItem>::iterator it = m_pendingSortRoleItems.begin();
616 while (it != m_pendingSortRoleItems.end()) {
617 const KFileItem item = *it;
618 const int index = m_model->index(item);
619
620 // Continue if the sort role has already been determined for the
621 // item, and the item has not been changed recently.
622 if (!m_changedItems.contains(item) && m_model->data(index).contains(m_model->sortRole())) {
623 it = m_pendingSortRoleItems.erase(it);
624 continue;
625 }
626
627 applySortRole(index);
628 m_pendingSortRoleItems.erase(it);
629 break;
630 }
631
632 if (!m_pendingSortRoleItems.isEmpty()) {
633 applySortProgressToModel();
634 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
635 } else {
636 m_state = Idle;
637
638 // Prevent that we try to update the items twice.
639 disconnect(m_model, &KFileItemModel::itemsMoved,
640 this, &KFileItemModelRolesUpdater::slotItemsMoved);
641 applySortProgressToModel();
642 connect(m_model, &KFileItemModel::itemsMoved,
643 this, &KFileItemModelRolesUpdater::slotItemsMoved);
644 startUpdating();
645 }
646 }
647
648 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
649 {
650 if (m_state != ResolvingAllRoles) {
651 return;
652 }
653
654 while (!m_pendingIndexes.isEmpty()) {
655 const int index = m_pendingIndexes.takeFirst();
656 const KFileItem item = m_model->fileItem(index);
657
658 if (m_finishedItems.contains(item)) {
659 continue;
660 }
661
662 applyResolvedRoles(index, ResolveAll);
663 m_finishedItems.insert(item);
664 m_changedItems.remove(item);
665 break;
666 }
667
668 if (!m_pendingIndexes.isEmpty()) {
669 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
670 } else {
671 m_state = Idle;
672
673 if (m_clearPreviews) {
674 // Only go through the list if there are items which might still have previews.
675 if (m_finishedItems.count() != m_model->count()) {
676 QHash<QByteArray, QVariant> data;
677 data.insert("iconPixmap", QPixmap());
678
679 disconnect(m_model, &KFileItemModel::itemsChanged,
680 this, &KFileItemModelRolesUpdater::slotItemsChanged);
681 for (int index = 0; index <= m_model->count(); ++index) {
682 if (m_model->data(index).contains("iconPixmap")) {
683 m_model->setData(index, data);
684 }
685 }
686 connect(m_model, &KFileItemModel::itemsChanged,
687 this, &KFileItemModelRolesUpdater::slotItemsChanged);
688
689 }
690 m_clearPreviews = false;
691 }
692
693 if (!m_changedItems.isEmpty()) {
694 updateChangedItems();
695 }
696 }
697 }
698
699 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
700 {
701 m_changedItems += m_recentlyChangedItems;
702 m_recentlyChangedItems.clear();
703 updateChangedItems();
704 }
705
706 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString& file)
707 {
708 #ifdef HAVE_BALOO
709 const KFileItem item = m_model->fileItem(QUrl::fromLocalFile(file));
710
711 if (item.isNull()) {
712 // itemUrl is not in the model anymore, probably because
713 // the corresponding file has been deleted in the meantime.
714 return;
715 }
716 applyChangedBalooRolesForItem(item);
717 #endif
718 }
719
720 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem &item)
721 {
722 #ifdef HAVE_BALOO
723 Baloo::File file(item.localPath());
724 file.load();
725
726 const KBalooRolesProvider& rolesProvider = KBalooRolesProvider::instance();
727 QHash<QByteArray, QVariant> data;
728
729 foreach (const QByteArray& role, rolesProvider.roles()) {
730 // Overwrite all the role values with an empty QVariant, because the roles
731 // provider doesn't overwrite it when the property value list is empty.
732 // See bug 322348
733 data.insert(role, QVariant());
734 }
735
736 QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(file, m_roles));
737 while (it.hasNext()) {
738 it.next();
739 data.insert(it.key(), it.value());
740 }
741
742 disconnect(m_model, &KFileItemModel::itemsChanged,
743 this, &KFileItemModelRolesUpdater::slotItemsChanged);
744 const int index = m_model->index(item);
745 m_model->setData(index, data);
746 connect(m_model, &KFileItemModel::itemsChanged,
747 this, &KFileItemModelRolesUpdater::slotItemsChanged);
748 #else
749 #ifndef Q_CC_MSVC
750 Q_UNUSED(item);
751 #endif
752 #endif
753 }
754
755 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString& path, int count)
756 {
757 const bool getSizeRole = m_roles.contains("size");
758 const bool getIsExpandableRole = m_roles.contains("isExpandable");
759
760 if (getSizeRole || getIsExpandableRole) {
761 const int index = m_model->index(QUrl::fromLocalFile(path));
762 if (index >= 0) {
763 QHash<QByteArray, QVariant> data;
764
765 if (getSizeRole) {
766 data.insert("size", count);
767 }
768 if (getIsExpandableRole) {
769 data.insert("isExpandable", count > 0);
770 }
771
772 disconnect(m_model, &KFileItemModel::itemsChanged,
773 this, &KFileItemModelRolesUpdater::slotItemsChanged);
774 m_model->setData(index, data);
775 connect(m_model, &KFileItemModel::itemsChanged,
776 this, &KFileItemModelRolesUpdater::slotItemsChanged);
777 }
778 }
779 }
780
781 void KFileItemModelRolesUpdater::startUpdating()
782 {
783 if (m_state == Paused) {
784 return;
785 }
786
787 if (m_finishedItems.count() == m_model->count()) {
788 // All roles have been resolved already.
789 m_state = Idle;
790 return;
791 }
792
793 // Terminate all updates that are currently active.
794 killPreviewJob();
795 m_pendingIndexes.clear();
796
797 QElapsedTimer timer;
798 timer.start();
799
800 // Determine the icons for the visible items synchronously.
801 updateVisibleIcons();
802
803 // A detailed update of the items in and near the visible area
804 // only makes sense if sorting is finished.
805 if (m_state == ResolvingSortRole) {
806 return;
807 }
808
809 // Start the preview job or the asynchronous resolving of all roles.
810 QList<int> indexes = indexesToResolve();
811
812 if (m_previewShown) {
813 m_pendingPreviewItems.clear();
814 m_pendingPreviewItems.reserve(indexes.count());
815
816 foreach (int index, indexes) {
817 const KFileItem item = m_model->fileItem(index);
818 if (!m_finishedItems.contains(item)) {
819 m_pendingPreviewItems.append(item);
820 }
821 }
822
823 startPreviewJob();
824 } else {
825 m_pendingIndexes = indexes;
826 // Trigger the asynchronous resolving of all roles.
827 m_state = ResolvingAllRoles;
828 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
829 }
830 }
831
832 void KFileItemModelRolesUpdater::updateVisibleIcons()
833 {
834 int lastVisibleIndex = m_lastVisibleIndex;
835 if (lastVisibleIndex <= 0) {
836 // Guess a reasonable value for the last visible index if the view
837 // has not told us about the real value yet.
838 lastVisibleIndex = qMin(m_firstVisibleIndex + m_maximumVisibleItems, m_model->count() - 1);
839 if (lastVisibleIndex <= 0) {
840 lastVisibleIndex = qMin(200, m_model->count() - 1);
841 }
842 }
843
844 QElapsedTimer timer;
845 timer.start();
846
847 // Try to determine the final icons for all visible items.
848 int index;
849 for (index = m_firstVisibleIndex; index <= lastVisibleIndex && timer.elapsed() < MaxBlockTimeout; ++index) {
850 applyResolvedRoles(index, ResolveFast);
851 }
852
853 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
854 // preliminary icons (i.e., without mime type determination) for the
855 // remaining items.
856 }
857
858 void KFileItemModelRolesUpdater::startPreviewJob()
859 {
860 m_state = PreviewJobRunning;
861
862 if (m_pendingPreviewItems.isEmpty()) {
863 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
864 return;
865 }
866
867 // PreviewJob internally caches items always with the size of
868 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
869 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
870 // do a downscaling anyhow because of the frame, so in this case only the provided
871 // cache sizes are requested.
872 const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128)
873 ? QSize(256, 256) : QSize(128, 128);
874
875 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
876 // worst case) might block the application for several seconds. To prevent such
877 // a blocking, we only pass items with known mime type to the preview job.
878 const int count = m_pendingPreviewItems.count();
879 KFileItemList itemSubSet;
880 itemSubSet.reserve(count);
881
882 if (m_pendingPreviewItems.first().isMimeTypeKnown()) {
883 // Some mime types are known already, probably because they were
884 // determined when loading the icons for the visible items. Start
885 // a preview job for all items at the beginning of the list which
886 // have a known mime type.
887 do {
888 itemSubSet.append(m_pendingPreviewItems.takeFirst());
889 } while (!m_pendingPreviewItems.isEmpty() && m_pendingPreviewItems.first().isMimeTypeKnown());
890 } else {
891 // Determine mime types for MaxBlockTimeout ms, and start a preview
892 // job for the corresponding items.
893 QElapsedTimer timer;
894 timer.start();
895
896 do {
897 const KFileItem item = m_pendingPreviewItems.takeFirst();
898 item.determineMimeType();
899 itemSubSet.append(item);
900 } while (!m_pendingPreviewItems.isEmpty() && timer.elapsed() < MaxBlockTimeout);
901 }
902
903 KIO::PreviewJob* job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins);
904
905 job->setIgnoreMaximumSize(itemSubSet.first().isLocalFile());
906 if (job->uiDelegate()) {
907 KJobWidgets::setWindow(job, qApp->activeWindow());
908 }
909
910 connect(job, &KIO::PreviewJob::gotPreview,
911 this, &KFileItemModelRolesUpdater::slotGotPreview);
912 connect(job, &KIO::PreviewJob::failed,
913 this, &KFileItemModelRolesUpdater::slotPreviewFailed);
914 connect(job, &KIO::PreviewJob::finished,
915 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
916
917 m_previewJob = job;
918 }
919
920 void KFileItemModelRolesUpdater::updateChangedItems()
921 {
922 if (m_state == Paused) {
923 return;
924 }
925
926 if (m_changedItems.isEmpty()) {
927 return;
928 }
929
930 m_finishedItems -= m_changedItems;
931
932 if (m_resolvableRoles.contains(m_model->sortRole())) {
933 m_pendingSortRoleItems += m_changedItems;
934
935 if (m_state != ResolvingSortRole) {
936 // Stop the preview job if necessary, and trigger the
937 // asynchronous determination of the sort role.
938 killPreviewJob();
939 m_state = ResolvingSortRole;
940 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
941 }
942
943 return;
944 }
945
946 QList<int> visibleChangedIndexes;
947 QList<int> invisibleChangedIndexes;
948
949 foreach (const KFileItem& item, m_changedItems) {
950 const int index = m_model->index(item);
951
952 if (index < 0) {
953 m_changedItems.remove(item);
954 continue;
955 }
956
957 if (index >= m_firstVisibleIndex && index <= m_lastVisibleIndex) {
958 visibleChangedIndexes.append(index);
959 } else {
960 invisibleChangedIndexes.append(index);
961 }
962 }
963
964 std::sort(visibleChangedIndexes.begin(), visibleChangedIndexes.end());
965
966 if (m_previewShown) {
967 foreach (int index, visibleChangedIndexes) {
968 m_pendingPreviewItems.append(m_model->fileItem(index));
969 }
970
971 foreach (int index, invisibleChangedIndexes) {
972 m_pendingPreviewItems.append(m_model->fileItem(index));
973 }
974
975 if (!m_previewJob) {
976 startPreviewJob();
977 }
978 } else {
979 const bool resolvingInProgress = !m_pendingIndexes.isEmpty();
980 m_pendingIndexes = visibleChangedIndexes + m_pendingIndexes + invisibleChangedIndexes;
981 if (!resolvingInProgress) {
982 // Trigger the asynchronous resolving of the changed roles.
983 m_state = ResolvingAllRoles;
984 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
985 }
986 }
987 }
988
989 void KFileItemModelRolesUpdater::applySortRole(int index)
990 {
991 QHash<QByteArray, QVariant> data;
992 const KFileItem item = m_model->fileItem(index);
993
994 if (m_model->sortRole() == "type") {
995 if (!item.isMimeTypeKnown()) {
996 item.determineMimeType();
997 }
998
999 data.insert("type", item.mimeComment());
1000 } else if (m_model->sortRole() == "size" && item.isLocalFile() && item.isDir()) {
1001 const QString path = item.localPath();
1002 data.insert("size", m_directoryContentsCounter->countDirectoryContentsSynchronously(path));
1003 } else {
1004 // Probably the sort role is a baloo role - just determine all roles.
1005 data = rolesData(item);
1006 }
1007
1008 disconnect(m_model, &KFileItemModel::itemsChanged,
1009 this, &KFileItemModelRolesUpdater::slotItemsChanged);
1010 m_model->setData(index, data);
1011 connect(m_model, &KFileItemModel::itemsChanged,
1012 this, &KFileItemModelRolesUpdater::slotItemsChanged);
1013 }
1014
1015 void KFileItemModelRolesUpdater::applySortProgressToModel()
1016 {
1017 // Inform the model about the progress of the resolved items,
1018 // so that it can give an indication when the sorting has been finished.
1019 const int resolvedCount = m_model->count() - m_pendingSortRoleItems.count();
1020 m_model->emitSortProgress(resolvedCount);
1021 }
1022
1023 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index, ResolveHint hint)
1024 {
1025 const KFileItem item = m_model->fileItem(index);
1026 const bool resolveAll = (hint == ResolveAll);
1027
1028 bool iconChanged = false;
1029 if (!item.isMimeTypeKnown() || !item.isFinalIconKnown()) {
1030 item.determineMimeType();
1031 iconChanged = true;
1032 } else if (!m_model->data(index).contains("iconName")) {
1033 iconChanged = true;
1034 }
1035
1036 if (iconChanged || resolveAll || m_clearPreviews) {
1037 if (index < 0) {
1038 return false;
1039 }
1040
1041 QHash<QByteArray, QVariant> data;
1042 if (resolveAll) {
1043 data = rolesData(item);
1044 }
1045
1046 data.insert("iconName", item.iconName());
1047
1048 if (m_clearPreviews) {
1049 data.insert("iconPixmap", QPixmap());
1050 }
1051
1052 disconnect(m_model, &KFileItemModel::itemsChanged,
1053 this, &KFileItemModelRolesUpdater::slotItemsChanged);
1054 m_model->setData(index, data);
1055 connect(m_model, &KFileItemModel::itemsChanged,
1056 this, &KFileItemModelRolesUpdater::slotItemsChanged);
1057 return true;
1058 }
1059
1060 return false;
1061 }
1062
1063 QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem& item)
1064 {
1065 QHash<QByteArray, QVariant> data;
1066
1067 const bool getSizeRole = m_roles.contains("size");
1068 const bool getIsExpandableRole = m_roles.contains("isExpandable");
1069
1070 if ((getSizeRole || getIsExpandableRole) && item.isDir()) {
1071 if (item.isLocalFile()) {
1072 // Tell m_directoryContentsCounter that we want to count the items
1073 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1074 const QString path = item.localPath();
1075 m_directoryContentsCounter->addDirectory(path);
1076 } else if (getSizeRole) {
1077 data.insert("size", -1); // -1 indicates an unknown number of items
1078 }
1079 }
1080
1081 if (m_roles.contains("type")) {
1082 data.insert("type", item.mimeComment());
1083 }
1084
1085 QStringList overlays = item.overlays();
1086 foreach(KOverlayIconPlugin *it, m_overlayIconsPlugin) {
1087 overlays.append(it->getOverlays(item.url()));
1088 }
1089 data.insert("iconOverlays", overlays);
1090
1091 #ifdef HAVE_BALOO
1092 if (m_balooFileMonitor) {
1093 m_balooFileMonitor->addFile(item.localPath());
1094 applyChangedBalooRolesForItem(item);
1095 }
1096 #endif
1097 return data;
1098 }
1099
1100 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl& url, const QStringList &)
1101 {
1102 const KFileItem item = m_model->fileItem(url);
1103 if (item.isNull()) {
1104 return;
1105 }
1106 const int index = m_model->index(item);
1107 QHash<QByteArray, QVariant> data = m_model->data(index);
1108 QStringList overlays = item.overlays();
1109 foreach (KOverlayIconPlugin *it, m_overlayIconsPlugin) {
1110 overlays.append(it->getOverlays(url));
1111 }
1112 data.insert("iconOverlays", overlays);
1113 m_model->setData(index, data);
1114 }
1115
1116 void KFileItemModelRolesUpdater::updateAllPreviews()
1117 {
1118 if (m_state == Paused) {
1119 m_previewChangedDuringPausing = true;
1120 } else {
1121 m_finishedItems.clear();
1122 startUpdating();
1123 }
1124 }
1125
1126 void KFileItemModelRolesUpdater::killPreviewJob()
1127 {
1128 if (m_previewJob) {
1129 disconnect(m_previewJob, &KIO::PreviewJob::gotPreview,
1130 this, &KFileItemModelRolesUpdater::slotGotPreview);
1131 disconnect(m_previewJob, &KIO::PreviewJob::failed,
1132 this, &KFileItemModelRolesUpdater::slotPreviewFailed);
1133 disconnect(m_previewJob, &KIO::PreviewJob::finished,
1134 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
1135 m_previewJob->kill();
1136 m_previewJob = nullptr;
1137 m_pendingPreviewItems.clear();
1138 }
1139 }
1140
1141 QList<int> KFileItemModelRolesUpdater::indexesToResolve() const
1142 {
1143 const int count = m_model->count();
1144
1145 QList<int> result;
1146 result.reserve(ResolveAllItemsLimit);
1147
1148 // Add visible items.
1149 for (int i = m_firstVisibleIndex; i <= m_lastVisibleIndex; ++i) {
1150 result.append(i);
1151 }
1152
1153 // We need a reasonable upper limit for number of items to resolve after
1154 // and before the visible range. m_maximumVisibleItems can be quite large
1155 // when using Compace View.
1156 const int readAheadItems = qMin(ReadAheadPages * m_maximumVisibleItems, ResolveAllItemsLimit / 2);
1157
1158 // Add items after the visible range.
1159 const int endExtendedVisibleRange = qMin(m_lastVisibleIndex + readAheadItems, count - 1);
1160 for (int i = m_lastVisibleIndex + 1; i <= endExtendedVisibleRange; ++i) {
1161 result.append(i);
1162 }
1163
1164 // Add items before the visible range in reverse order.
1165 const int beginExtendedVisibleRange = qMax(0, m_firstVisibleIndex - readAheadItems);
1166 for (int i = m_firstVisibleIndex - 1; i >= beginExtendedVisibleRange; --i) {
1167 result.append(i);
1168 }
1169
1170 // Add items on the last page.
1171 const int beginLastPage = qMax(qMin(endExtendedVisibleRange + 1, count - 1), count - m_maximumVisibleItems);
1172 for (int i = beginLastPage; i < count; ++i) {
1173 result.append(i);
1174 }
1175
1176 // Add items on the first page.
1177 const int endFirstPage = qMin(qMax(beginExtendedVisibleRange - 1, 0), m_maximumVisibleItems);
1178 for (int i = 0; i <= endFirstPage; ++i) {
1179 result.append(i);
1180 }
1181
1182 // Continue adding items until ResolveAllItemsLimit is reached.
1183 int remainingItems = ResolveAllItemsLimit - result.count();
1184
1185 for (int i = endExtendedVisibleRange + 1; i < beginLastPage && remainingItems > 0; ++i) {
1186 result.append(i);
1187 --remainingItems;
1188 }
1189
1190 for (int i = beginExtendedVisibleRange - 1; i > endFirstPage && remainingItems > 0; --i) {
1191 result.append(i);
1192 --remainingItems;
1193 }
1194
1195 return result;
1196 }
1197