]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodelrolesupdater.cpp
2a3a8eeb35c48f58ca501238a7604702b8948fa6
[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 "dolphindebug.h"
10 #include "kfileitemmodel.h"
11 #include "private/kdirectorycontentscounter.h"
12 #include "private/kpixmapmodifier.h"
13
14 #include <KConfig>
15 #include <KConfigGroup>
16 #include <KIO/ListJob>
17 #include <KIO/PreviewJob>
18 #include <KIconLoader>
19 #include <KJobWidgets>
20 #include <KOverlayIconPlugin>
21 #include <KPluginMetaData>
22 #include <KSharedConfig>
23
24 #include "dolphin_contentdisplaysettings.h"
25
26 #if HAVE_BALOO
27 #include "private/kbaloorolesprovider.h"
28 #include <Baloo/File>
29 #include <Baloo/FileMonitor>
30 #endif
31
32 #include <QApplication>
33 #include <QElapsedTimer>
34 #include <QFileInfo>
35 #include <QPainter>
36 #include <QPluginLoader>
37 #include <QTimer>
38 #include <chrono>
39
40 using namespace std::chrono_literals;
41
42 // #define KFILEITEMMODELROLESUPDATER_DEBUG
43
44 namespace
45 {
46 // Maximum time in ms that the KFileItemModelRolesUpdater
47 // may perform a blocking operation
48 const int MaxBlockTimeout = 200;
49
50 // If the number of items is smaller than ResolveAllItemsLimit,
51 // the roles of all items will be resolved.
52 const int ResolveAllItemsLimit = 500;
53
54 // Not only the visible area, but up to ReadAheadPages before and after
55 // this area will be resolved.
56 const int ReadAheadPages = 5;
57 }
58
59 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel *model, QObject *parent)
60 : QObject(parent)
61 , m_state(Idle)
62 , m_previewChangedDuringPausing(false)
63 , m_iconSizeChangedDuringPausing(false)
64 , m_rolesChangedDuringPausing(false)
65 , m_previewShown(false)
66 , m_enlargeSmallPreviews(true)
67 , m_clearPreviews(false)
68 , m_finishedItems()
69 , m_model(model)
70 , m_iconSize()
71 , m_devicePixelRatio(1.0)
72 , m_firstVisibleIndex(0)
73 , m_lastVisibleIndex(-1)
74 , m_maximumVisibleItems(50)
75 , m_roles()
76 , m_resolvableRoles()
77 , m_enabledPlugins()
78 , m_localFileSizePreviewLimit(0)
79 , m_pendingSortRoleItems()
80 , m_pendingIndexes()
81 , m_pendingPreviewItems()
82 , m_previewJob()
83 , m_hoverSequenceItem()
84 , m_hoverSequenceIndex(0)
85 , m_hoverSequencePreviewJob(nullptr)
86 , m_hoverSequenceNumSuccessiveFailures(0)
87 , m_recentlyChangedItemsTimer(nullptr)
88 , m_recentlyChangedItems()
89 , m_changedItems()
90 , m_directoryContentsCounter(nullptr)
91 #if HAVE_BALOO
92 , m_balooFileMonitor(nullptr)
93 #endif
94 {
95 Q_ASSERT(model);
96
97 const KConfigGroup globalConfig(KSharedConfig::openConfig(), QStringLiteral("PreviewSettings"));
98 m_enabledPlugins = globalConfig.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
99 m_localFileSizePreviewLimit = static_cast<qulonglong>(globalConfig.readEntry("MaximumSize", 0));
100
101 connect(m_model, &KFileItemModel::itemsInserted, this, &KFileItemModelRolesUpdater::slotItemsInserted);
102 connect(m_model, &KFileItemModel::itemsRemoved, this, &KFileItemModelRolesUpdater::slotItemsRemoved);
103 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
104 connect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved);
105 connect(m_model, &KFileItemModel::sortRoleChanged, this, &KFileItemModelRolesUpdater::slotSortRoleChanged);
106
107 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
108 // resolving of the roles. Postpone the resolving until no update has been done for 100 ms.
109 m_recentlyChangedItemsTimer = new QTimer(this);
110 m_recentlyChangedItemsTimer->setInterval(100ms);
111 m_recentlyChangedItemsTimer->setSingleShot(true);
112 connect(m_recentlyChangedItemsTimer, &QTimer::timeout, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems);
113
114 m_resolvableRoles.insert("size");
115 m_resolvableRoles.insert("type");
116 m_resolvableRoles.insert("isExpandable");
117 #if HAVE_BALOO
118 m_resolvableRoles += KBalooRolesProvider::instance().roles();
119 #endif
120
121 m_directoryContentsCounter = new KDirectoryContentsCounter(m_model, this);
122 connect(m_directoryContentsCounter, &KDirectoryContentsCounter::result, this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived);
123
124 const auto plugins = KPluginMetaData::findPlugins(QStringLiteral("kf6/overlayicon"), {}, KPluginMetaData::AllowEmptyMetaData);
125 for (const KPluginMetaData &data : plugins) {
126 auto instance = QPluginLoader(data.fileName()).instance();
127 auto plugin = qobject_cast<KOverlayIconPlugin *>(instance);
128 if (plugin) {
129 m_overlayIconsPlugin.append(plugin);
130 connect(plugin, &KOverlayIconPlugin::overlaysChanged, this, &KFileItemModelRolesUpdater::slotOverlaysChanged);
131 } else {
132 // not our/valid plugin, so delete the created object
133 delete instance;
134 }
135 }
136 }
137
138 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
139 {
140 killPreviewJob();
141 }
142
143 void KFileItemModelRolesUpdater::setIconSize(const QSize &size)
144 {
145 if (size != m_iconSize) {
146 m_iconSize = size;
147 if (m_state == Paused) {
148 m_iconSizeChangedDuringPausing = true;
149 } else if (m_previewShown) {
150 // An icon size change requires the regenerating of
151 // all previews
152 m_finishedItems.clear();
153 startUpdating();
154 }
155 }
156 }
157
158 QSize KFileItemModelRolesUpdater::iconSize() const
159 {
160 return m_iconSize;
161 }
162
163 void KFileItemModelRolesUpdater::setDevicePixelRatio(qreal devicePixelRatio)
164 {
165 if (m_devicePixelRatio != devicePixelRatio) {
166 m_devicePixelRatio = devicePixelRatio;
167 if (m_state == Paused) {
168 m_iconSizeChangedDuringPausing = true;
169 } else if (m_previewShown) {
170 // A dpr change requires the regenerating of all previews.
171 m_finishedItems.clear();
172 startUpdating();
173 }
174 }
175 }
176
177 qreal KFileItemModelRolesUpdater::devicePixelRatio() const
178 {
179 return m_devicePixelRatio;
180 }
181
182 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index, int count)
183 {
184 if (index < 0) {
185 index = 0;
186 }
187 if (count < 0) {
188 count = 0;
189 }
190
191 if (index == m_firstVisibleIndex && count == m_lastVisibleIndex - m_firstVisibleIndex + 1) {
192 // The range has not been changed
193 return;
194 }
195
196 m_firstVisibleIndex = index;
197 m_lastVisibleIndex = qMin(index + count - 1, m_model->count() - 1);
198
199 startUpdating();
200 }
201
202 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count)
203 {
204 m_maximumVisibleItems = count;
205 }
206
207 void KFileItemModelRolesUpdater::setPreviewsShown(bool show)
208 {
209 if (show == m_previewShown) {
210 return;
211 }
212
213 m_previewShown = show;
214 if (!show) {
215 m_clearPreviews = true;
216 }
217
218 updateAllPreviews();
219 }
220
221 bool KFileItemModelRolesUpdater::previewsShown() const
222 {
223 return m_previewShown;
224 }
225
226 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge)
227 {
228 if (enlarge != m_enlargeSmallPreviews) {
229 m_enlargeSmallPreviews = enlarge;
230 if (m_previewShown) {
231 updateAllPreviews();
232 }
233 }
234 }
235
236 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
237 {
238 return m_enlargeSmallPreviews;
239 }
240
241 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList &list)
242 {
243 if (m_enabledPlugins != list) {
244 m_enabledPlugins = list;
245 if (m_previewShown) {
246 updateAllPreviews();
247 }
248 }
249 }
250
251 void KFileItemModelRolesUpdater::setPaused(bool paused)
252 {
253 if (paused == (m_state == Paused)) {
254 return;
255 }
256
257 if (paused) {
258 m_state = Paused;
259 killPreviewJob();
260 } else {
261 const bool updatePreviews = (m_iconSizeChangedDuringPausing && m_previewShown) || m_previewChangedDuringPausing;
262 const bool resolveAll = updatePreviews || m_rolesChangedDuringPausing;
263 if (resolveAll) {
264 m_finishedItems.clear();
265 }
266
267 m_iconSizeChangedDuringPausing = false;
268 m_previewChangedDuringPausing = false;
269 m_rolesChangedDuringPausing = false;
270
271 if (!m_pendingSortRoleItems.isEmpty()) {
272 m_state = ResolvingSortRole;
273 resolveNextSortRole();
274 } else {
275 m_state = Idle;
276 }
277
278 startUpdating();
279 }
280 }
281
282 void KFileItemModelRolesUpdater::setRoles(const QSet<QByteArray> &roles)
283 {
284 if (m_roles != roles) {
285 m_roles = roles;
286
287 #if HAVE_BALOO
288 // Check whether there is at least one role that must be resolved
289 // with the help of Baloo. If this is the case, a (quite expensive)
290 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
291 // the role gets watched for changes.
292 const KBalooRolesProvider &rolesProvider = KBalooRolesProvider::instance();
293 bool hasBalooRole = false;
294 QSetIterator<QByteArray> it(roles);
295 while (it.hasNext()) {
296 const QByteArray &role = it.next();
297 if (rolesProvider.roles().contains(role)) {
298 hasBalooRole = true;
299 break;
300 }
301 }
302
303 if (hasBalooRole && m_balooConfig.fileIndexingEnabled() && !m_balooFileMonitor) {
304 m_balooFileMonitor = new Baloo::FileMonitor(this);
305 connect(m_balooFileMonitor, &Baloo::FileMonitor::fileMetaDataChanged, this, &KFileItemModelRolesUpdater::applyChangedBalooRoles);
306 } else if (!hasBalooRole && m_balooFileMonitor) {
307 delete m_balooFileMonitor;
308 m_balooFileMonitor = nullptr;
309 }
310 #endif
311
312 if (m_state == Paused) {
313 m_rolesChangedDuringPausing = true;
314 } else {
315 startUpdating();
316 }
317 }
318 }
319
320 QSet<QByteArray> KFileItemModelRolesUpdater::roles() const
321 {
322 return m_roles;
323 }
324
325 bool KFileItemModelRolesUpdater::isPaused() const
326 {
327 return m_state == Paused;
328 }
329
330 QStringList KFileItemModelRolesUpdater::enabledPlugins() const
331 {
332 return m_enabledPlugins;
333 }
334
335 void KFileItemModelRolesUpdater::setLocalFileSizePreviewLimit(const qlonglong size)
336 {
337 m_localFileSizePreviewLimit = size;
338 }
339
340 qlonglong KFileItemModelRolesUpdater::localFileSizePreviewLimit() const
341 {
342 return m_localFileSizePreviewLimit;
343 }
344
345 void KFileItemModelRolesUpdater::setHoverSequenceState(const QUrl &itemUrl, int seqIdx)
346 {
347 const KFileItem item = m_model->fileItem(itemUrl);
348
349 if (item != m_hoverSequenceItem) {
350 killHoverSequencePreviewJob();
351 }
352
353 m_hoverSequenceItem = item;
354 m_hoverSequenceIndex = seqIdx;
355
356 if (!m_previewShown) {
357 return;
358 }
359
360 m_hoverSequenceNumSuccessiveFailures = 0;
361
362 loadNextHoverSequencePreview();
363 }
364
365 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList &itemRanges)
366 {
367 QElapsedTimer timer;
368 timer.start();
369
370 // Determine the sort role synchronously for as many items as possible.
371 if (m_resolvableRoles.contains(m_model->sortRole())) {
372 int insertedCount = 0;
373 for (const KItemRange &range : itemRanges) {
374 const int lastIndex = insertedCount + range.index + range.count - 1;
375 for (int i = insertedCount + range.index; i <= lastIndex; ++i) {
376 if (timer.elapsed() < MaxBlockTimeout) {
377 applySortRole(i);
378 } else {
379 m_pendingSortRoleItems.insert(m_model->fileItem(i));
380 }
381 }
382 insertedCount += range.count;
383 }
384
385 applySortProgressToModel();
386
387 // If there are still items whose sort role is unknown, check if the
388 // asynchronous determination of the sort role is already in progress,
389 // and start it if that is not the case.
390 if (!m_pendingSortRoleItems.isEmpty() && m_state != ResolvingSortRole) {
391 killPreviewJob();
392 m_state = ResolvingSortRole;
393 resolveNextSortRole();
394 }
395 }
396
397 startUpdating();
398 }
399
400 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList &itemRanges)
401 {
402 Q_UNUSED(itemRanges)
403
404 const bool allItemsRemoved = (m_model->count() == 0);
405
406 #if HAVE_BALOO
407 if (m_balooFileMonitor) {
408 // Don't let the FileWatcher watch for removed items
409 if (allItemsRemoved) {
410 m_balooFileMonitor->clear();
411 } else {
412 QStringList newFileList;
413 const QStringList oldFileList = m_balooFileMonitor->files();
414 for (const QString &file : oldFileList) {
415 if (m_model->index(QUrl::fromLocalFile(file)) >= 0) {
416 newFileList.append(file);
417 }
418 }
419 m_balooFileMonitor->setFiles(newFileList);
420 }
421 }
422 #endif
423
424 if (allItemsRemoved) {
425 m_state = Idle;
426
427 m_finishedItems.clear();
428 m_pendingSortRoleItems.clear();
429 m_pendingIndexes.clear();
430 m_pendingPreviewItems.clear();
431 m_recentlyChangedItems.clear();
432 m_recentlyChangedItemsTimer->stop();
433 m_changedItems.clear();
434 m_hoverSequenceLoadedItems.clear();
435
436 killPreviewJob();
437 if (!m_model->showDirectoriesOnly()) {
438 m_directoryContentsCounter->stopWorker();
439 }
440 } else {
441 // Only remove the items from m_finishedItems. They will be removed
442 // from the other sets later on.
443 QSet<KFileItem>::iterator it = m_finishedItems.begin();
444 while (it != m_finishedItems.end()) {
445 if (m_model->index(*it) < 0) {
446 it = m_finishedItems.erase(it);
447 } else {
448 ++it;
449 }
450 }
451
452 // Removed items won't have hover previews loaded anymore.
453 for (const KItemRange &itemRange : itemRanges) {
454 int index = itemRange.index;
455 for (int count = itemRange.count; count > 0; --count) {
456 const KFileItem item = m_model->fileItem(index);
457 m_hoverSequenceLoadedItems.remove(item);
458 ++index;
459 }
460 }
461
462 // The visible items might have changed.
463 startUpdating();
464 }
465 }
466
467 void KFileItemModelRolesUpdater::slotItemsMoved(KItemRange itemRange, const QList<int> &movedToIndexes)
468 {
469 Q_UNUSED(itemRange)
470 Q_UNUSED(movedToIndexes)
471
472 // The visible items might have changed.
473 startUpdating();
474 }
475
476 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList &itemRanges, const QSet<QByteArray> &roles)
477 {
478 Q_UNUSED(roles)
479
480 // Find out if slotItemsChanged() has been done recently. If that is the
481 // case, resolving the roles is postponed until a timer has exceeded
482 // to prevent expensive repeated updates if files are updated frequently.
483 const bool itemsChangedRecently = m_recentlyChangedItemsTimer->isActive();
484
485 QSet<KFileItem> &targetSet = itemsChangedRecently ? m_recentlyChangedItems : m_changedItems;
486
487 for (const KItemRange &itemRange : itemRanges) {
488 int index = itemRange.index;
489 for (int count = itemRange.count; count > 0; --count) {
490 const KFileItem item = m_model->fileItem(index);
491 targetSet.insert(item);
492 ++index;
493 }
494 }
495
496 m_recentlyChangedItemsTimer->start();
497
498 if (!itemsChangedRecently) {
499 updateChangedItems();
500 }
501 }
502
503 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray &current, const QByteArray &previous)
504 {
505 Q_UNUSED(current)
506 Q_UNUSED(previous)
507
508 if (m_resolvableRoles.contains(current)) {
509 m_pendingSortRoleItems.clear();
510 m_finishedItems.clear();
511
512 const int count = m_model->count();
513 QElapsedTimer timer;
514 timer.start();
515
516 // Determine the sort role synchronously for as many items as possible.
517 for (int index = 0; index < count; ++index) {
518 if (timer.elapsed() < MaxBlockTimeout) {
519 applySortRole(index);
520 } else {
521 m_pendingSortRoleItems.insert(m_model->fileItem(index));
522 }
523 }
524
525 applySortProgressToModel();
526
527 if (!m_pendingSortRoleItems.isEmpty()) {
528 // Trigger the asynchronous determination of the sort role.
529 killPreviewJob();
530 m_state = ResolvingSortRole;
531 resolveNextSortRole();
532 }
533 } else {
534 m_state = Idle;
535 m_pendingSortRoleItems.clear();
536 applySortProgressToModel();
537 }
538 }
539
540 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem &item, const QPixmap &pixmap)
541 {
542 if (m_state != PreviewJobRunning) {
543 return;
544 }
545
546 m_changedItems.remove(item);
547
548 const int index = m_model->index(item);
549 if (index < 0) {
550 return;
551 }
552
553 QPixmap scaledPixmap = transformPreviewPixmap(pixmap);
554
555 QHash<QByteArray, QVariant> data = rolesData(item, index);
556
557 const QStringList overlays = data["iconOverlays"].toStringList();
558 // Strangely KFileItem::overlays() returns empty string-values, so
559 // we need to check first whether an overlay must be drawn at all.
560 // It is more efficient to do it here, as KIconLoader::drawOverlays()
561 // assumes that an overlay will be drawn and has some additional
562 // setup time.
563 if (!scaledPixmap.isNull()) {
564 for (const QString &overlay : overlays) {
565 if (!overlay.isEmpty()) {
566 // There is at least one overlay, draw all overlays above m_pixmap
567 // and cancel the check
568 KIconLoader::global()->drawOverlays(overlays, scaledPixmap, KIconLoader::Desktop);
569 break;
570 }
571 }
572 }
573
574 data.insert("iconPixmap", scaledPixmap);
575
576 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
577 m_model->setData(index, data);
578 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
579
580 m_finishedItems.insert(item);
581 }
582
583 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem &item)
584 {
585 if (m_state != PreviewJobRunning) {
586 return;
587 }
588
589 m_changedItems.remove(item);
590
591 const int index = m_model->index(item);
592 if (index >= 0) {
593 QHash<QByteArray, QVariant> data;
594 data.insert("iconPixmap", QPixmap());
595
596 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
597 m_model->setData(index, data);
598 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
599
600 applyResolvedRoles(index, ResolveAll);
601 m_finishedItems.insert(item);
602 }
603 }
604
605 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
606 {
607 m_previewJob = nullptr;
608
609 if (m_state != PreviewJobRunning) {
610 return;
611 }
612
613 m_state = Idle;
614
615 if (!m_pendingPreviewItems.isEmpty()) {
616 startPreviewJob();
617 } else {
618 if (!m_changedItems.isEmpty()) {
619 updateChangedItems();
620 }
621 }
622 }
623
624 void KFileItemModelRolesUpdater::slotHoverSequenceGotPreview(const KFileItem &item, const QPixmap &pixmap)
625 {
626 const int index = m_model->index(item);
627 if (index < 0) {
628 return;
629 }
630
631 QHash<QByteArray, QVariant> data = m_model->data(index);
632 QVector<QPixmap> pixmaps = data["hoverSequencePixmaps"].value<QVector<QPixmap>>();
633 const int loadedIndex = pixmaps.size();
634
635 float wap = m_hoverSequencePreviewJob->sequenceIndexWraparoundPoint();
636 if (!m_hoverSequencePreviewJob->handlesSequences()) {
637 wap = 1.0f;
638 }
639 if (wap >= 0.0f) {
640 data["hoverSequenceWraparoundPoint"] = wap;
641 m_model->setData(index, data);
642 }
643
644 // For hover sequence previews we never load index 0, because that's just the regular preview
645 // in "iconPixmap". But that means we'll load index 1 even for thumbnailers that don't support
646 // sequences, in which case we can just throw away the preview because it's the same as for
647 // index 0. Unfortunately we can't find it out earlier :(
648 if (wap < 0.0f || loadedIndex < static_cast<int>(wap)) {
649 // Add the preview to the model data
650
651 const QPixmap scaledPixmap = transformPreviewPixmap(pixmap);
652
653 pixmaps.append(scaledPixmap);
654 data["hoverSequencePixmaps"] = QVariant::fromValue(pixmaps);
655
656 m_model->setData(index, data);
657
658 const auto loadedIt = std::find(m_hoverSequenceLoadedItems.begin(), m_hoverSequenceLoadedItems.end(), item);
659 if (loadedIt == m_hoverSequenceLoadedItems.end()) {
660 m_hoverSequenceLoadedItems.push_back(item);
661 trimHoverSequenceLoadedItems();
662 }
663 }
664
665 m_hoverSequenceNumSuccessiveFailures = 0;
666 }
667
668 void KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed(const KFileItem &item)
669 {
670 const int index = m_model->index(item);
671 if (index < 0) {
672 return;
673 }
674
675 static const int numRetries = 2;
676
677 QHash<QByteArray, QVariant> data = m_model->data(index);
678 QVector<QPixmap> pixmaps = data["hoverSequencePixmaps"].value<QVector<QPixmap>>();
679
680 qCDebug(DolphinDebug).nospace() << "Failed to generate hover sequence preview #" << pixmaps.size() << " for file " << item.url().toString() << " (attempt "
681 << (m_hoverSequenceNumSuccessiveFailures + 1) << "/" << (numRetries + 1) << ")";
682
683 if (m_hoverSequenceNumSuccessiveFailures >= numRetries) {
684 // Give up and simply duplicate the previous sequence image (if any)
685
686 pixmaps.append(pixmaps.empty() ? QPixmap() : pixmaps.last());
687 data["hoverSequencePixmaps"] = QVariant::fromValue(pixmaps);
688
689 if (!data.contains("hoverSequenceWraparoundPoint")) {
690 // hoverSequenceWraparoundPoint is only available when PreviewJob succeeds, so unless
691 // it has previously succeeded, it's best to assume that it just doesn't handle
692 // sequences instead of trying to load the next image indefinitely.
693 data["hoverSequenceWraparoundPoint"] = 1.0f;
694 }
695
696 m_model->setData(index, data);
697
698 m_hoverSequenceNumSuccessiveFailures = 0;
699 } else {
700 // Retry
701
702 m_hoverSequenceNumSuccessiveFailures++;
703 }
704
705 // Next image in the sequence (or same one if the retry limit wasn't reached yet) will be
706 // loaded automatically, because slotHoverSequencePreviewJobFinished() will be triggered
707 // even when PreviewJob fails.
708 }
709
710 void KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished()
711 {
712 const int index = m_model->index(m_hoverSequenceItem);
713 if (index < 0) {
714 m_hoverSequencePreviewJob = nullptr;
715 return;
716 }
717
718 // Since a PreviewJob can only have one associated sequence index, we can only generate
719 // one sequence image per job, so we have to start another one for the next index.
720
721 // Load the next image in the sequence
722 m_hoverSequencePreviewJob = nullptr;
723 loadNextHoverSequencePreview();
724 }
725
726 void KFileItemModelRolesUpdater::resolveNextSortRole()
727 {
728 if (m_state != ResolvingSortRole) {
729 return;
730 }
731
732 QSet<KFileItem>::iterator it = m_pendingSortRoleItems.begin();
733 while (it != m_pendingSortRoleItems.end()) {
734 const KFileItem item = *it;
735 const int index = m_model->index(item);
736
737 // Continue if the sort role has already been determined for the
738 // item, and the item has not been changed recently.
739 if (!m_changedItems.contains(item) && m_model->data(index).contains(m_model->sortRole())) {
740 it = m_pendingSortRoleItems.erase(it);
741 continue;
742 }
743
744 applySortRole(index);
745 m_pendingSortRoleItems.erase(it);
746 break;
747 }
748
749 if (!m_pendingSortRoleItems.isEmpty()) {
750 applySortProgressToModel();
751 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
752 } else {
753 m_state = Idle;
754
755 // Prevent that we try to update the items twice.
756 disconnect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved);
757 applySortProgressToModel();
758 connect(m_model, &KFileItemModel::itemsMoved, this, &KFileItemModelRolesUpdater::slotItemsMoved);
759 startUpdating();
760 }
761 }
762
763 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
764 {
765 if (m_state != ResolvingAllRoles) {
766 return;
767 }
768
769 while (!m_pendingIndexes.isEmpty()) {
770 const int index = m_pendingIndexes.takeFirst();
771 const KFileItem item = m_model->fileItem(index);
772
773 if (m_finishedItems.contains(item)) {
774 continue;
775 }
776
777 applyResolvedRoles(index, ResolveAll);
778 m_finishedItems.insert(item);
779 m_changedItems.remove(item);
780 break;
781 }
782
783 if (!m_pendingIndexes.isEmpty()) {
784 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
785 } else {
786 m_state = Idle;
787
788 if (m_clearPreviews) {
789 // Only go through the list if there are items which might still have previews.
790 if (m_finishedItems.count() != m_model->count()) {
791 QHash<QByteArray, QVariant> data;
792 data.insert("iconPixmap", QPixmap());
793 data.insert("hoverSequencePixmaps", QVariant::fromValue(QVector<QPixmap>()));
794
795 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
796 for (int index = 0; index <= m_model->count(); ++index) {
797 if (m_model->data(index).contains("iconPixmap") || m_model->data(index).contains("hoverSequencePixmaps")) {
798 m_model->setData(index, data);
799 }
800 }
801 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
802 }
803 m_clearPreviews = false;
804 }
805
806 if (!m_changedItems.isEmpty()) {
807 updateChangedItems();
808 }
809 }
810 }
811
812 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
813 {
814 m_changedItems += m_recentlyChangedItems;
815 m_recentlyChangedItems.clear();
816 updateChangedItems();
817 }
818
819 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString &file)
820 {
821 #if HAVE_BALOO
822 const KFileItem item = m_model->fileItem(QUrl::fromLocalFile(file));
823
824 if (item.isNull()) {
825 // itemUrl is not in the model anymore, probably because
826 // the corresponding file has been deleted in the meantime.
827 return;
828 }
829 applyChangedBalooRolesForItem(item);
830 #else
831 Q_UNUSED(file)
832 #endif
833 }
834
835 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem &item)
836 {
837 #if HAVE_BALOO
838 Baloo::File file(item.localPath());
839 file.load();
840
841 const KBalooRolesProvider &rolesProvider = KBalooRolesProvider::instance();
842 QHash<QByteArray, QVariant> data;
843
844 const auto roles = rolesProvider.roles();
845 for (const QByteArray &role : roles) {
846 // Overwrite all the role values with an empty QVariant, because the roles
847 // provider doesn't overwrite it when the property value list is empty.
848 // See bug 322348
849 data.insert(role, QVariant());
850 }
851
852 QHashIterator<QByteArray, QVariant> it(rolesProvider.roleValues(file, m_roles));
853 while (it.hasNext()) {
854 it.next();
855 data.insert(it.key(), it.value());
856 }
857
858 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
859 const int index = m_model->index(item);
860 m_model->setData(index, data);
861 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
862 #else
863 #ifndef Q_CC_MSVC
864 Q_UNUSED(item)
865 #endif
866 #endif
867 }
868
869 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString &path, int count, long long size)
870 {
871 const bool getIsExpandableRole = m_roles.contains("isExpandable");
872 const bool getSizeRole = m_roles.contains("size");
873
874 if (getSizeRole || getIsExpandableRole) {
875 const int index = m_model->index(QUrl::fromLocalFile(path));
876 if (index >= 0) {
877 QHash<QByteArray, QVariant> data;
878
879 if (getSizeRole) {
880 data.insert("count", count);
881 data.insert("size", QVariant::fromValue(size));
882 }
883 if (getIsExpandableRole) {
884 data.insert("isExpandable", count > 0);
885 }
886
887 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
888 m_model->setData(index, data);
889 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
890 }
891 }
892 }
893
894 void KFileItemModelRolesUpdater::startUpdating()
895 {
896 if (m_state == Paused) {
897 return;
898 }
899
900 if (m_finishedItems.count() == m_model->count()) {
901 // All roles have been resolved already.
902 m_state = Idle;
903 return;
904 }
905
906 // Terminate all updates that are currently active.
907 killPreviewJob();
908 m_pendingIndexes.clear();
909
910 QElapsedTimer timer;
911 timer.start();
912
913 // Determine the icons for the visible items synchronously.
914 updateVisibleIcons();
915
916 // A detailed update of the items in and near the visible area
917 // only makes sense if sorting is finished.
918 if (m_state == ResolvingSortRole) {
919 return;
920 }
921
922 // Start the preview job or the asynchronous resolving of all roles.
923 QList<int> indexes = indexesToResolve();
924
925 if (m_previewShown) {
926 m_pendingPreviewItems.clear();
927 m_pendingPreviewItems.reserve(indexes.count());
928
929 for (int index : std::as_const(indexes)) {
930 const KFileItem item = m_model->fileItem(index);
931 if (!m_finishedItems.contains(item)) {
932 m_pendingPreviewItems.append(item);
933 }
934 }
935
936 startPreviewJob();
937 } else {
938 m_pendingIndexes = indexes;
939 // Trigger the asynchronous resolving of all roles.
940 m_state = ResolvingAllRoles;
941 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
942 }
943 }
944
945 void KFileItemModelRolesUpdater::updateVisibleIcons()
946 {
947 int lastVisibleIndex = m_lastVisibleIndex;
948 if (lastVisibleIndex <= 0) {
949 // Guess a reasonable value for the last visible index if the view
950 // has not told us about the real value yet.
951 lastVisibleIndex = qMin(m_firstVisibleIndex + m_maximumVisibleItems, m_model->count() - 1);
952 if (lastVisibleIndex <= 0) {
953 lastVisibleIndex = qMin(200, m_model->count() - 1);
954 }
955 }
956
957 QElapsedTimer timer;
958 timer.start();
959
960 // Try to determine the final icons for all visible items.
961 int index;
962 for (index = m_firstVisibleIndex; index <= lastVisibleIndex && timer.elapsed() < MaxBlockTimeout; ++index) {
963 applyResolvedRoles(index, ResolveFast);
964 }
965
966 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
967 // preliminary icons (i.e., without mime type determination) for the
968 // remaining items.
969 }
970
971 void KFileItemModelRolesUpdater::startPreviewJob()
972 {
973 m_state = PreviewJobRunning;
974
975 if (m_pendingPreviewItems.isEmpty()) {
976 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
977 return;
978 }
979
980 // PreviewJob internally caches items always with the size of
981 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
982 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
983 // do a downscaling anyhow because of the frame, so in this case only the provided
984 // cache sizes are requested.
985 const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) ? QSize(256, 256) : QSize(128, 128);
986
987 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
988 // worst case) might block the application for several seconds. To prevent such
989 // a blocking, we only pass items with known mime type to the preview job.
990 const int count = m_pendingPreviewItems.count();
991 KFileItemList itemSubSet;
992 itemSubSet.reserve(count);
993
994 if (m_pendingPreviewItems.first().isMimeTypeKnown()) {
995 // Some mime types are known already, probably because they were
996 // determined when loading the icons for the visible items. Start
997 // a preview job for all items at the beginning of the list which
998 // have a known mime type.
999 do {
1000 itemSubSet.append(m_pendingPreviewItems.takeFirst());
1001 } while (!m_pendingPreviewItems.isEmpty() && m_pendingPreviewItems.first().isMimeTypeKnown());
1002 } else {
1003 // Determine mime types for MaxBlockTimeout ms, and start a preview
1004 // job for the corresponding items.
1005 QElapsedTimer timer;
1006 timer.start();
1007
1008 do {
1009 const KFileItem item = m_pendingPreviewItems.takeFirst();
1010 item.determineMimeType();
1011 itemSubSet.append(item);
1012 } while (!m_pendingPreviewItems.isEmpty() && timer.elapsed() < MaxBlockTimeout);
1013 }
1014
1015 KIO::PreviewJob *job = new KIO::PreviewJob(itemSubSet, cacheSize, &m_enabledPlugins);
1016 job->setDevicePixelRatio(m_devicePixelRatio);
1017 job->setIgnoreMaximumSize(itemSubSet.first().isLocalFile() && !itemSubSet.first().isSlow() && m_localFileSizePreviewLimit <= 0);
1018 if (job->uiDelegate()) {
1019 KJobWidgets::setWindow(job, qApp->activeWindow());
1020 }
1021
1022 connect(job, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotGotPreview);
1023 connect(job, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotPreviewFailed);
1024 connect(job, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
1025
1026 m_previewJob = job;
1027 }
1028
1029 QPixmap KFileItemModelRolesUpdater::transformPreviewPixmap(const QPixmap &pixmap)
1030 {
1031 QPixmap scaledPixmap = pixmap;
1032
1033 if (!pixmap.hasAlpha() && !pixmap.isNull() && m_iconSize.width() > KIconLoader::SizeSmallMedium && m_iconSize.height() > KIconLoader::SizeSmallMedium) {
1034 if (m_enlargeSmallPreviews) {
1035 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
1036 } else {
1037 // Assure that small previews don't get enlarged. Instead they
1038 // should be shown centered within the frame.
1039 const QSize contentSize = KPixmapModifier::sizeInsideFrame(m_iconSize);
1040 const bool enlargingRequired = scaledPixmap.width() < contentSize.width() && scaledPixmap.height() < contentSize.height();
1041 if (enlargingRequired) {
1042 QSize frameSize = scaledPixmap.size() / scaledPixmap.devicePixelRatio();
1043 frameSize.scale(m_iconSize, Qt::KeepAspectRatio);
1044
1045 QPixmap largeFrame(frameSize);
1046 largeFrame.fill(Qt::transparent);
1047
1048 KPixmapModifier::applyFrame(largeFrame, frameSize);
1049
1050 QPainter painter(&largeFrame);
1051 painter.drawPixmap((largeFrame.width() - scaledPixmap.width() / scaledPixmap.devicePixelRatio()) / 2,
1052 (largeFrame.height() - scaledPixmap.height() / scaledPixmap.devicePixelRatio()) / 2,
1053 scaledPixmap);
1054 scaledPixmap = largeFrame;
1055 } else {
1056 // The image must be shrunk as it is too large to fit into
1057 // the available icon size
1058 KPixmapModifier::applyFrame(scaledPixmap, m_iconSize);
1059 }
1060 }
1061 } else if (!pixmap.isNull()) {
1062 KPixmapModifier::scale(scaledPixmap, m_iconSize * m_devicePixelRatio);
1063 scaledPixmap.setDevicePixelRatio(m_devicePixelRatio);
1064 }
1065
1066 return scaledPixmap;
1067 }
1068
1069 void KFileItemModelRolesUpdater::loadNextHoverSequencePreview()
1070 {
1071 if (m_hoverSequenceItem.isNull() || m_hoverSequencePreviewJob) {
1072 return;
1073 }
1074
1075 const int index = m_model->index(m_hoverSequenceItem);
1076 if (index < 0) {
1077 return;
1078 }
1079
1080 // We generate the next few sequence indices in advance (buffering)
1081 const int maxSeqIdx = m_hoverSequenceIndex + 5;
1082
1083 QHash<QByteArray, QVariant> data = m_model->data(index);
1084
1085 if (!data.contains("hoverSequencePixmaps")) {
1086 // The pixmap at index 0 isn't used ("iconPixmap" will be used instead)
1087 data.insert("hoverSequencePixmaps", QVariant::fromValue(QVector<QPixmap>() << QPixmap()));
1088 m_model->setData(index, data);
1089 }
1090
1091 const QVector<QPixmap> pixmaps = data["hoverSequencePixmaps"].value<QVector<QPixmap>>();
1092
1093 const int loadSeqIdx = pixmaps.size();
1094
1095 float wap = -1.0f;
1096 if (data.contains("hoverSequenceWraparoundPoint")) {
1097 wap = data["hoverSequenceWraparoundPoint"].toFloat();
1098 }
1099 if (wap >= 1.0f && loadSeqIdx >= static_cast<int>(wap)) {
1100 // Reached the wraparound point -> no more previews to load.
1101 return;
1102 }
1103
1104 if (loadSeqIdx > maxSeqIdx) {
1105 // Wait until setHoverSequenceState() is called with a higher sequence index.
1106 return;
1107 }
1108
1109 // PreviewJob internally caches items always with the size of
1110 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
1111 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
1112 // do a downscaling anyhow because of the frame, so in this case only the provided
1113 // cache sizes are requested.
1114 const QSize cacheSize = (m_iconSize.width() > 128) || (m_iconSize.height() > 128) ? QSize(256, 256) : QSize(128, 128);
1115
1116 KIO::PreviewJob *job = new KIO::PreviewJob({m_hoverSequenceItem}, cacheSize, &m_enabledPlugins);
1117
1118 job->setSequenceIndex(loadSeqIdx);
1119 job->setIgnoreMaximumSize(m_hoverSequenceItem.isLocalFile() && !m_hoverSequenceItem.isSlow() && m_localFileSizePreviewLimit <= 0);
1120 if (job->uiDelegate()) {
1121 KJobWidgets::setWindow(job, qApp->activeWindow());
1122 }
1123
1124 connect(job, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview);
1125 connect(job, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed);
1126 connect(job, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished);
1127
1128 m_hoverSequencePreviewJob = job;
1129 }
1130
1131 void KFileItemModelRolesUpdater::killHoverSequencePreviewJob()
1132 {
1133 if (m_hoverSequencePreviewJob) {
1134 disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotHoverSequenceGotPreview);
1135 disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewFailed);
1136 disconnect(m_hoverSequencePreviewJob, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotHoverSequencePreviewJobFinished);
1137 m_hoverSequencePreviewJob->kill();
1138 m_hoverSequencePreviewJob = nullptr;
1139 }
1140 }
1141
1142 void KFileItemModelRolesUpdater::updateChangedItems()
1143 {
1144 if (m_state == Paused) {
1145 return;
1146 }
1147
1148 if (m_changedItems.isEmpty()) {
1149 return;
1150 }
1151
1152 m_finishedItems -= m_changedItems;
1153
1154 if (m_resolvableRoles.contains(m_model->sortRole())) {
1155 m_pendingSortRoleItems += m_changedItems;
1156
1157 if (m_state != ResolvingSortRole) {
1158 // Stop the preview job if necessary, and trigger the
1159 // asynchronous determination of the sort role.
1160 killPreviewJob();
1161 m_state = ResolvingSortRole;
1162 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole);
1163 }
1164
1165 return;
1166 }
1167
1168 QList<int> visibleChangedIndexes;
1169 QList<int> invisibleChangedIndexes;
1170 visibleChangedIndexes.reserve(m_changedItems.size());
1171 invisibleChangedIndexes.reserve(m_changedItems.size());
1172
1173 auto changedItemsIt = m_changedItems.begin();
1174 while (changedItemsIt != m_changedItems.end()) {
1175 const auto &item = *changedItemsIt;
1176 const int index = m_model->index(item);
1177
1178 if (index < 0) {
1179 changedItemsIt = m_changedItems.erase(changedItemsIt);
1180 continue;
1181 }
1182 ++changedItemsIt;
1183
1184 if (index >= m_firstVisibleIndex && index <= m_lastVisibleIndex) {
1185 visibleChangedIndexes.append(index);
1186 } else {
1187 invisibleChangedIndexes.append(index);
1188 }
1189 }
1190
1191 std::sort(visibleChangedIndexes.begin(), visibleChangedIndexes.end());
1192
1193 if (m_previewShown) {
1194 for (int index : std::as_const(visibleChangedIndexes)) {
1195 m_pendingPreviewItems.append(m_model->fileItem(index));
1196 }
1197
1198 for (int index : std::as_const(invisibleChangedIndexes)) {
1199 m_pendingPreviewItems.append(m_model->fileItem(index));
1200 }
1201
1202 if (!m_previewJob) {
1203 startPreviewJob();
1204 }
1205 } else {
1206 const bool resolvingInProgress = !m_pendingIndexes.isEmpty();
1207 m_pendingIndexes = visibleChangedIndexes + m_pendingIndexes + invisibleChangedIndexes;
1208 if (!resolvingInProgress) {
1209 // Trigger the asynchronous resolving of the changed roles.
1210 m_state = ResolvingAllRoles;
1211 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles);
1212 }
1213 }
1214 }
1215
1216 void KFileItemModelRolesUpdater::applySortRole(int index)
1217 {
1218 QHash<QByteArray, QVariant> data;
1219 const KFileItem item = m_model->fileItem(index);
1220
1221 if (m_model->sortRole() == "type") {
1222 if (!item.isMimeTypeKnown()) {
1223 item.determineMimeType();
1224 }
1225
1226 data.insert("type", item.mimeComment());
1227 } else if (m_model->sortRole() == "size" && item.isLocalFile() && item.isDir()) {
1228 startDirectorySizeCounting(item, index);
1229 return;
1230 } else {
1231 // Probably the sort role is a baloo role - just determine all roles.
1232 data = rolesData(item, index);
1233 }
1234
1235 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1236 m_model->setData(index, data);
1237 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1238 }
1239
1240 void KFileItemModelRolesUpdater::applySortProgressToModel()
1241 {
1242 // Inform the model about the progress of the resolved items,
1243 // so that it can give an indication when the sorting has been finished.
1244 const int resolvedCount = m_model->count() - m_pendingSortRoleItems.count();
1245 m_model->emitSortProgress(resolvedCount);
1246 }
1247
1248 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index, ResolveHint hint)
1249 {
1250 const KFileItem item = m_model->fileItem(index);
1251 const bool resolveAll = (hint == ResolveAll);
1252
1253 bool iconChanged = false;
1254 if (!item.isMimeTypeKnown() || !item.isFinalIconKnown()) {
1255 item.determineMimeType();
1256 iconChanged = true;
1257 } else if (!m_model->data(index).contains("iconName")) {
1258 iconChanged = true;
1259 }
1260
1261 if (iconChanged || resolveAll || m_clearPreviews) {
1262 if (index < 0) {
1263 return false;
1264 }
1265
1266 QHash<QByteArray, QVariant> data;
1267 if (resolveAll) {
1268 data = rolesData(item, index);
1269 }
1270
1271 if (!item.iconName().isEmpty()) {
1272 data.insert("iconName", item.iconName());
1273 }
1274
1275 if (m_clearPreviews) {
1276 data.insert("iconPixmap", QPixmap());
1277 data.insert("hoverSequencePixmaps", QVariant::fromValue(QVector<QPixmap>()));
1278 }
1279
1280 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1281 m_model->setData(index, data);
1282 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1283 return true;
1284 }
1285
1286 return false;
1287 }
1288
1289 void KFileItemModelRolesUpdater::startDirectorySizeCounting(const KFileItem &item, int index)
1290 {
1291 if (!item.isLocalFile()) {
1292 return;
1293 }
1294
1295 if (ContentDisplaySettings::directorySizeCount() || item.isSlow()) {
1296 // fastpath no recursion necessary
1297
1298 auto data = m_model->data(index);
1299 if (data.value("size") == -2) {
1300 // means job already started
1301 return;
1302 }
1303
1304 auto url = item.url();
1305 if (!item.localPath().isEmpty()) {
1306 // optimization for desktop:/, trash:/
1307 url = QUrl::fromLocalFile(item.localPath());
1308 }
1309
1310 data.insert("size", -2); // invalid size, -1 means size unknown
1311
1312 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1313 m_model->setData(index, data);
1314 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1315
1316 auto listJob = KIO::listDir(url, KIO::HideProgressInfo);
1317 QObject::connect(listJob, &KIO::ListJob::entries, this, [this, item](const KJob * /*job*/, const KIO::UDSEntryList &list) {
1318 int index = m_model->index(item);
1319 if (index < 0) {
1320 return;
1321 }
1322 auto data = m_model->data(index);
1323 int origCount = data.value("count").toInt();
1324 int entryCount = origCount;
1325
1326 for (const KIO::UDSEntry &entry : list) {
1327 const auto name = entry.stringValue(KIO::UDSEntry::UDS_NAME);
1328
1329 if (name == QStringLiteral("..") || name == QStringLiteral(".")) {
1330 continue;
1331 }
1332 if (!m_model->showHiddenFiles() && name.startsWith(QLatin1Char('.'))) {
1333 continue;
1334 }
1335 if (m_model->showDirectoriesOnly() && !entry.isDir()) {
1336 continue;
1337 }
1338 ++entryCount;
1339 }
1340
1341 QHash<QByteArray, QVariant> newData;
1342 QVariant expandable = data.value("isExpandable");
1343 if (expandable.isNull() || expandable.toBool() != (entryCount > 0)) {
1344 // if expandable has changed
1345 newData.insert("isExpandable", entryCount > 0);
1346 }
1347
1348 if (origCount != entryCount) {
1349 // count has changed
1350 newData.insert("count", entryCount);
1351 }
1352
1353 if (!newData.isEmpty()) {
1354 disconnect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1355 m_model->setData(index, newData);
1356 connect(m_model, &KFileItemModel::itemsChanged, this, &KFileItemModelRolesUpdater::slotItemsChanged);
1357 }
1358 });
1359 return;
1360 }
1361
1362 // Tell m_directoryContentsCounter that we want to count the items
1363 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1364 const QString path = item.localPath();
1365 const auto priority = index >= m_firstVisibleIndex && index <= m_lastVisibleIndex ? KDirectoryContentsCounter::PathCountPriority::High
1366 : KDirectoryContentsCounter::PathCountPriority::Normal;
1367
1368 m_directoryContentsCounter->scanDirectory(path, priority);
1369 }
1370
1371 QHash<QByteArray, QVariant> KFileItemModelRolesUpdater::rolesData(const KFileItem &item, int index)
1372 {
1373 QHash<QByteArray, QVariant> data;
1374
1375 const bool getSizeRole = m_roles.contains("size");
1376 const bool getIsExpandableRole = m_roles.contains("isExpandable");
1377
1378 if ((getSizeRole || getIsExpandableRole) && item.isDir()) {
1379 startDirectorySizeCounting(item, index);
1380 }
1381
1382 if (m_roles.contains("extension")) {
1383 // TODO KF6 use KFileItem::suffix 464722
1384 data.insert("extension", QFileInfo(item.name()).suffix());
1385 }
1386
1387 if (m_roles.contains("type")) {
1388 data.insert("type", item.mimeComment());
1389 }
1390
1391 QStringList overlays = item.overlays();
1392 for (KOverlayIconPlugin *it : std::as_const(m_overlayIconsPlugin)) {
1393 overlays.append(it->getOverlays(item.url()));
1394 }
1395 if (!overlays.isEmpty()) {
1396 data.insert("iconOverlays", overlays);
1397 }
1398
1399 #if HAVE_BALOO
1400 if (m_balooFileMonitor) {
1401 m_balooFileMonitor->addFile(item.localPath());
1402 applyChangedBalooRolesForItem(item);
1403 }
1404 #endif
1405 return data;
1406 }
1407
1408 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl &url, const QStringList &)
1409 {
1410 const KFileItem item = m_model->fileItem(url);
1411 if (item.isNull()) {
1412 return;
1413 }
1414 const int index = m_model->index(item);
1415 QHash<QByteArray, QVariant> data = m_model->data(index);
1416 QStringList overlays = item.overlays();
1417 for (KOverlayIconPlugin *it : std::as_const(m_overlayIconsPlugin)) {
1418 overlays.append(it->getOverlays(url));
1419 }
1420 data.insert("iconOverlays", overlays);
1421 m_model->setData(index, data);
1422 }
1423
1424 void KFileItemModelRolesUpdater::updateAllPreviews()
1425 {
1426 if (m_state == Paused) {
1427 m_previewChangedDuringPausing = true;
1428 } else {
1429 m_finishedItems.clear();
1430 startUpdating();
1431 }
1432 }
1433
1434 void KFileItemModelRolesUpdater::killPreviewJob()
1435 {
1436 if (m_previewJob) {
1437 disconnect(m_previewJob, &KIO::PreviewJob::gotPreview, this, &KFileItemModelRolesUpdater::slotGotPreview);
1438 disconnect(m_previewJob, &KIO::PreviewJob::failed, this, &KFileItemModelRolesUpdater::slotPreviewFailed);
1439 disconnect(m_previewJob, &KIO::PreviewJob::finished, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished);
1440 m_previewJob->kill();
1441 m_previewJob = nullptr;
1442 m_pendingPreviewItems.clear();
1443 }
1444 }
1445
1446 QList<int> KFileItemModelRolesUpdater::indexesToResolve() const
1447 {
1448 const int count = m_model->count();
1449
1450 QList<int> result;
1451 result.reserve(qMin(count, (m_lastVisibleIndex - m_firstVisibleIndex + 1) + ResolveAllItemsLimit + (2 * m_maximumVisibleItems)));
1452
1453 // Add visible items.
1454 // Resolve files first, their previews are quicker.
1455 QList<int> visibleDirs;
1456 for (int i = m_firstVisibleIndex; i <= m_lastVisibleIndex; ++i) {
1457 const KFileItem item = m_model->fileItem(i);
1458 if (item.isDir()) {
1459 visibleDirs.append(i);
1460 } else {
1461 result.append(i);
1462 }
1463 }
1464
1465 result.append(visibleDirs);
1466
1467 // We need a reasonable upper limit for number of items to resolve after
1468 // and before the visible range. m_maximumVisibleItems can be quite large
1469 // when using Compact View.
1470 const int readAheadItems = qMin(ReadAheadPages * m_maximumVisibleItems, ResolveAllItemsLimit / 2);
1471
1472 // Add items after the visible range.
1473 const int endExtendedVisibleRange = qMin(m_lastVisibleIndex + readAheadItems, count - 1);
1474 for (int i = m_lastVisibleIndex + 1; i <= endExtendedVisibleRange; ++i) {
1475 result.append(i);
1476 }
1477
1478 // Add items before the visible range in reverse order.
1479 const int beginExtendedVisibleRange = qMax(0, m_firstVisibleIndex - readAheadItems);
1480 for (int i = m_firstVisibleIndex - 1; i >= beginExtendedVisibleRange; --i) {
1481 result.append(i);
1482 }
1483
1484 // Add items on the last page.
1485 const int beginLastPage = qMax(endExtendedVisibleRange + 1, count - m_maximumVisibleItems);
1486 for (int i = beginLastPage; i < count; ++i) {
1487 result.append(i);
1488 }
1489
1490 // Add items on the first page.
1491 const int endFirstPage = qMin(beginExtendedVisibleRange, m_maximumVisibleItems);
1492 for (int i = 0; i < endFirstPage; ++i) {
1493 result.append(i);
1494 }
1495
1496 // Continue adding items until ResolveAllItemsLimit is reached.
1497 int remainingItems = ResolveAllItemsLimit - result.count();
1498
1499 for (int i = endExtendedVisibleRange + 1; i < beginLastPage && remainingItems > 0; ++i) {
1500 result.append(i);
1501 --remainingItems;
1502 }
1503
1504 for (int i = beginExtendedVisibleRange - 1; i >= endFirstPage && remainingItems > 0; --i) {
1505 result.append(i);
1506 --remainingItems;
1507 }
1508
1509 return result;
1510 }
1511
1512 void KFileItemModelRolesUpdater::trimHoverSequenceLoadedItems()
1513 {
1514 static const size_t maxLoadedItems = 20;
1515
1516 size_t loadedItems = m_hoverSequenceLoadedItems.size();
1517 while (loadedItems > maxLoadedItems) {
1518 const KFileItem item = m_hoverSequenceLoadedItems.front();
1519
1520 m_hoverSequenceLoadedItems.pop_front();
1521 loadedItems--;
1522
1523 const int index = m_model->index(item);
1524 if (index >= 0) {
1525 QHash<QByteArray, QVariant> data = m_model->data(index);
1526 data["hoverSequencePixmaps"] = QVariant::fromValue(QVector<QPixmap>() << QPixmap());
1527 m_model->setData(index, data);
1528 }
1529 }
1530 }
1531
1532 #include "moc_kfileitemmodelrolesupdater.cpp"