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