2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
4 * SPDX-License-Identifier: GPL-2.0-or-later
7 #include "kfileitemmodelrolesupdater.h"
9 #include "kfileitemmodel.h"
10 #include "private/kdirectorycontentscounter.h"
11 #include "private/kpixmapmodifier.h"
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>
24 #include "private/kbaloorolesprovider.h"
26 #include <Baloo/FileMonitor>
29 #include <QApplication>
32 #include <QElapsedTimer>
35 // #define KFILEITEMMODELROLESUPDATER_DEBUG
38 // Maximum time in ms that the KFileItemModelRolesUpdater
39 // may perform a blocking operation
40 const int MaxBlockTimeout
= 200;
42 // If the number of items is smaller than ResolveAllItemsLimit,
43 // the roles of all items will be resolved.
44 const int ResolveAllItemsLimit
= 500;
46 // Not only the visible area, but up to ReadAheadPages before and after
47 // this area will be resolved.
48 const int ReadAheadPages
= 5;
51 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
54 m_previewChangedDuringPausing(false),
55 m_iconSizeChangedDuringPausing(false),
56 m_rolesChangedDuringPausing(false),
57 m_previewShown(false),
58 m_enlargeSmallPreviews(true),
59 m_clearPreviews(false),
63 m_firstVisibleIndex(0),
64 m_lastVisibleIndex(-1),
65 m_maximumVisibleItems(50),
69 m_localFileSizePreviewLimit(0),
70 m_scanDirectories(true),
71 m_pendingSortRoleItems(),
73 m_pendingPreviewItems(),
75 m_recentlyChangedItemsTimer(nullptr),
76 m_recentlyChangedItems(),
78 m_directoryContentsCounter(nullptr)
80 , m_balooFileMonitor(nullptr)
85 const KConfigGroup
globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
86 m_enabledPlugins
= globalConfig
.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
87 m_localFileSizePreviewLimit
= static_cast<qulonglong
>(globalConfig
.readEntry("MaximumSize", 0));
89 connect(m_model
, &KFileItemModel::itemsInserted
,
90 this, &KFileItemModelRolesUpdater::slotItemsInserted
);
91 connect(m_model
, &KFileItemModel::itemsRemoved
,
92 this, &KFileItemModelRolesUpdater::slotItemsRemoved
);
93 connect(m_model
, &KFileItemModel::itemsChanged
,
94 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
95 connect(m_model
, &KFileItemModel::itemsMoved
,
96 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
97 connect(m_model
, &KFileItemModel::sortRoleChanged
,
98 this, &KFileItemModelRolesUpdater::slotSortRoleChanged
);
100 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
101 // resolving of the roles. Postpone the resolving until no update has been done for 100 ms.
102 m_recentlyChangedItemsTimer
= new QTimer(this);
103 m_recentlyChangedItemsTimer
->setInterval(100);
104 m_recentlyChangedItemsTimer
->setSingleShot(true);
105 connect(m_recentlyChangedItemsTimer
, &QTimer::timeout
, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems
);
107 m_resolvableRoles
.insert("size");
108 m_resolvableRoles
.insert("type");
109 m_resolvableRoles
.insert("isExpandable");
111 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
114 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
115 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
116 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
118 const auto plugins
= KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp
);
119 for (QObject
*it
: plugins
) {
120 auto plugin
= qobject_cast
<KOverlayIconPlugin
*>(it
);
122 m_overlayIconsPlugin
.append(plugin
);
123 connect(plugin
, &KOverlayIconPlugin::overlaysChanged
, this, &KFileItemModelRolesUpdater::slotOverlaysChanged
);
125 // not our/valid plugin, so delete the created object
131 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
136 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
138 if (size
!= m_iconSize
) {
140 if (m_state
== Paused
) {
141 m_iconSizeChangedDuringPausing
= true;
142 } else if (m_previewShown
) {
143 // An icon size change requires the regenerating of
145 m_finishedItems
.clear();
151 QSize
KFileItemModelRolesUpdater::iconSize() const
156 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
165 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
166 // The range has not been changed
170 m_firstVisibleIndex
= index
;
171 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
176 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
178 m_maximumVisibleItems
= count
;
181 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
183 if (show
== m_previewShown
) {
187 m_previewShown
= show
;
189 m_clearPreviews
= true;
195 bool KFileItemModelRolesUpdater::previewsShown() const
197 return m_previewShown
;
200 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
202 if (enlarge
!= m_enlargeSmallPreviews
) {
203 m_enlargeSmallPreviews
= enlarge
;
204 if (m_previewShown
) {
210 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
212 return m_enlargeSmallPreviews
;
215 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
217 if (m_enabledPlugins
!= list
) {
218 m_enabledPlugins
= list
;
219 if (m_previewShown
) {
225 void KFileItemModelRolesUpdater::setPaused(bool paused
)
227 if (paused
== (m_state
== Paused
)) {
235 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
236 m_previewChangedDuringPausing
;
237 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
239 m_finishedItems
.clear();
242 m_iconSizeChangedDuringPausing
= false;
243 m_previewChangedDuringPausing
= false;
244 m_rolesChangedDuringPausing
= false;
246 if (!m_pendingSortRoleItems
.isEmpty()) {
247 m_state
= ResolvingSortRole
;
248 resolveNextSortRole();
257 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
259 if (m_roles
!= roles
) {
263 // Check whether there is at least one role that must be resolved
264 // with the help of Baloo. If this is the case, a (quite expensive)
265 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
266 // the role gets watched for changes.
267 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
268 bool hasBalooRole
= false;
269 QSetIterator
<QByteArray
> it(roles
);
270 while (it
.hasNext()) {
271 const QByteArray
& role
= it
.next();
272 if (rolesProvider
.roles().contains(role
)) {
278 if (hasBalooRole
&& m_balooConfig
.fileIndexingEnabled() && !m_balooFileMonitor
) {
279 m_balooFileMonitor
= new Baloo::FileMonitor(this);
280 connect(m_balooFileMonitor
, &Baloo::FileMonitor::fileMetaDataChanged
,
281 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles
);
282 } else if (!hasBalooRole
&& m_balooFileMonitor
) {
283 delete m_balooFileMonitor
;
284 m_balooFileMonitor
= nullptr;
288 if (m_state
== Paused
) {
289 m_rolesChangedDuringPausing
= true;
296 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
301 bool KFileItemModelRolesUpdater::isPaused() const
303 return m_state
== Paused
;
306 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
308 return m_enabledPlugins
;
311 void KFileItemModelRolesUpdater::setLocalFileSizePreviewLimit(const qlonglong size
)
313 m_localFileSizePreviewLimit
= size
;
316 qlonglong
KFileItemModelRolesUpdater::localFileSizePreviewLimit() const
318 return m_localFileSizePreviewLimit
;
321 void KFileItemModelRolesUpdater::setScanDirectories(bool enabled
)
323 m_scanDirectories
= enabled
;
326 bool KFileItemModelRolesUpdater::scanDirectories() const
328 return m_scanDirectories
;
331 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
336 // Determine the sort role synchronously for as many items as possible.
337 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
338 int insertedCount
= 0;
339 for (const KItemRange
& range
: itemRanges
) {
340 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
341 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
342 if (timer
.elapsed() < MaxBlockTimeout
) {
345 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
348 insertedCount
+= range
.count
;
351 applySortProgressToModel();
353 // If there are still items whose sort role is unknown, check if the
354 // asynchronous determination of the sort role is already in progress,
355 // and start it if that is not the case.
356 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
358 m_state
= ResolvingSortRole
;
359 resolveNextSortRole();
366 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
370 const bool allItemsRemoved
= (m_model
->count() == 0);
373 if (m_balooFileMonitor
) {
374 // Don't let the FileWatcher watch for removed items
375 if (allItemsRemoved
) {
376 m_balooFileMonitor
->clear();
378 QStringList newFileList
;
379 const QStringList oldFileList
= m_balooFileMonitor
->files();
380 for (const QString
& file
: oldFileList
) {
381 if (m_model
->index(QUrl::fromLocalFile(file
)) >= 0) {
382 newFileList
.append(file
);
385 m_balooFileMonitor
->setFiles(newFileList
);
390 if (allItemsRemoved
) {
393 m_finishedItems
.clear();
394 m_pendingSortRoleItems
.clear();
395 m_pendingIndexes
.clear();
396 m_pendingPreviewItems
.clear();
397 m_recentlyChangedItems
.clear();
398 m_recentlyChangedItemsTimer
->stop();
399 m_changedItems
.clear();
403 // Only remove the items from m_finishedItems. They will be removed
404 // from the other sets later on.
405 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
406 while (it
!= m_finishedItems
.end()) {
407 if (m_model
->index(*it
) < 0) {
408 it
= m_finishedItems
.erase(it
);
414 // The visible items might have changed.
419 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int> &movedToIndexes
)
422 Q_UNUSED(movedToIndexes
)
424 // The visible items might have changed.
428 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
429 const QSet
<QByteArray
>& roles
)
433 // Find out if slotItemsChanged() has been done recently. If that is the
434 // case, resolving the roles is postponed until a timer has exceeded
435 // to prevent expensive repeated updates if files are updated frequently.
436 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
438 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
440 for (const KItemRange
& itemRange
: itemRanges
) {
441 int index
= itemRange
.index
;
442 for (int count
= itemRange
.count
; count
> 0; --count
) {
443 const KFileItem item
= m_model
->fileItem(index
);
444 targetSet
.insert(item
);
449 m_recentlyChangedItemsTimer
->start();
451 if (!itemsChangedRecently
) {
452 updateChangedItems();
456 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
457 const QByteArray
& previous
)
462 if (m_resolvableRoles
.contains(current
)) {
463 m_pendingSortRoleItems
.clear();
464 m_finishedItems
.clear();
466 const int count
= m_model
->count();
470 // Determine the sort role synchronously for as many items as possible.
471 for (int index
= 0; index
< count
; ++index
) {
472 if (timer
.elapsed() < MaxBlockTimeout
) {
473 applySortRole(index
);
475 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
479 applySortProgressToModel();
481 if (!m_pendingSortRoleItems
.isEmpty()) {
482 // Trigger the asynchronous determination of the sort role.
484 m_state
= ResolvingSortRole
;
485 resolveNextSortRole();
489 m_pendingSortRoleItems
.clear();
490 applySortProgressToModel();
494 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
496 if (m_state
!= PreviewJobRunning
) {
500 m_changedItems
.remove(item
);
502 const int index
= m_model
->index(item
);
507 QPixmap scaledPixmap
= pixmap
;
509 if (!pixmap
.hasAlpha() && !pixmap
.isNull()
510 && m_iconSize
.width() > KIconLoader::SizeSmallMedium
511 && m_iconSize
.height() > KIconLoader::SizeSmallMedium
) {
512 if (m_enlargeSmallPreviews
) {
513 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
515 // Assure that small previews don't get enlarged. Instead they
516 // should be shown centered within the frame.
517 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
518 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
519 scaledPixmap
.height() < contentSize
.height();
520 if (enlargingRequired
) {
521 QSize frameSize
= scaledPixmap
.size() / scaledPixmap
.devicePixelRatio();
522 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
524 QPixmap
largeFrame(frameSize
);
525 largeFrame
.fill(Qt::transparent
);
527 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
529 QPainter
painter(&largeFrame
);
530 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width() / scaledPixmap
.devicePixelRatio()) / 2,
531 (largeFrame
.height() - scaledPixmap
.height() / scaledPixmap
.devicePixelRatio()) / 2,
533 scaledPixmap
= largeFrame
;
535 // The image must be shrunk as it is too large to fit into
536 // the available icon size
537 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
540 } else if (!pixmap
.isNull()) {
541 KPixmapModifier::scale(scaledPixmap
, m_iconSize
* qApp
->devicePixelRatio());
542 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
545 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
547 const QStringList overlays
= data
["iconOverlays"].toStringList();
548 // Strangely KFileItem::overlays() returns empty string-values, so
549 // we need to check first whether an overlay must be drawn at all.
550 // It is more efficient to do it here, as KIconLoader::drawOverlays()
551 // assumes that an overlay will be drawn and has some additional
553 if (!scaledPixmap
.isNull()) {
554 for (const QString
& overlay
: overlays
) {
555 if (!overlay
.isEmpty()) {
556 // There is at least one overlay, draw all overlays above m_pixmap
557 // and cancel the check
558 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
564 data
.insert("iconPixmap", scaledPixmap
);
566 disconnect(m_model
, &KFileItemModel::itemsChanged
,
567 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
568 m_model
->setData(index
, data
);
569 connect(m_model
, &KFileItemModel::itemsChanged
,
570 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
572 m_finishedItems
.insert(item
);
575 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
577 if (m_state
!= PreviewJobRunning
) {
581 m_changedItems
.remove(item
);
583 const int index
= m_model
->index(item
);
585 QHash
<QByteArray
, QVariant
> data
;
586 data
.insert("iconPixmap", QPixmap());
588 disconnect(m_model
, &KFileItemModel::itemsChanged
,
589 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
590 m_model
->setData(index
, data
);
591 connect(m_model
, &KFileItemModel::itemsChanged
,
592 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
594 applyResolvedRoles(index
, ResolveAll
);
595 m_finishedItems
.insert(item
);
599 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
601 m_previewJob
= nullptr;
603 if (m_state
!= PreviewJobRunning
) {
609 if (!m_pendingPreviewItems
.isEmpty()) {
612 if (!m_changedItems
.isEmpty()) {
613 updateChangedItems();
618 void KFileItemModelRolesUpdater::resolveNextSortRole()
620 if (m_state
!= ResolvingSortRole
) {
624 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
625 while (it
!= m_pendingSortRoleItems
.end()) {
626 const KFileItem item
= *it
;
627 const int index
= m_model
->index(item
);
629 // Continue if the sort role has already been determined for the
630 // item, and the item has not been changed recently.
631 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
632 it
= m_pendingSortRoleItems
.erase(it
);
636 applySortRole(index
);
637 m_pendingSortRoleItems
.erase(it
);
641 if (!m_pendingSortRoleItems
.isEmpty()) {
642 applySortProgressToModel();
643 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
647 // Prevent that we try to update the items twice.
648 disconnect(m_model
, &KFileItemModel::itemsMoved
,
649 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
650 applySortProgressToModel();
651 connect(m_model
, &KFileItemModel::itemsMoved
,
652 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
657 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
659 if (m_state
!= ResolvingAllRoles
) {
663 while (!m_pendingIndexes
.isEmpty()) {
664 const int index
= m_pendingIndexes
.takeFirst();
665 const KFileItem item
= m_model
->fileItem(index
);
667 if (m_finishedItems
.contains(item
)) {
671 applyResolvedRoles(index
, ResolveAll
);
672 m_finishedItems
.insert(item
);
673 m_changedItems
.remove(item
);
677 if (!m_pendingIndexes
.isEmpty()) {
678 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
682 if (m_clearPreviews
) {
683 // Only go through the list if there are items which might still have previews.
684 if (m_finishedItems
.count() != m_model
->count()) {
685 QHash
<QByteArray
, QVariant
> data
;
686 data
.insert("iconPixmap", QPixmap());
688 disconnect(m_model
, &KFileItemModel::itemsChanged
,
689 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
690 for (int index
= 0; index
<= m_model
->count(); ++index
) {
691 if (m_model
->data(index
).contains("iconPixmap")) {
692 m_model
->setData(index
, data
);
695 connect(m_model
, &KFileItemModel::itemsChanged
,
696 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
699 m_clearPreviews
= false;
702 if (!m_changedItems
.isEmpty()) {
703 updateChangedItems();
708 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
710 m_changedItems
+= m_recentlyChangedItems
;
711 m_recentlyChangedItems
.clear();
712 updateChangedItems();
715 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& file
)
718 const KFileItem item
= m_model
->fileItem(QUrl::fromLocalFile(file
));
721 // itemUrl is not in the model anymore, probably because
722 // the corresponding file has been deleted in the meantime.
725 applyChangedBalooRolesForItem(item
);
731 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem
&item
)
734 Baloo::File
file(item
.localPath());
737 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
738 QHash
<QByteArray
, QVariant
> data
;
740 const auto roles
= rolesProvider
.roles();
741 for (const QByteArray
& role
: roles
) {
742 // Overwrite all the role values with an empty QVariant, because the roles
743 // provider doesn't overwrite it when the property value list is empty.
745 data
.insert(role
, QVariant());
748 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(file
, m_roles
));
749 while (it
.hasNext()) {
751 data
.insert(it
.key(), it
.value());
754 disconnect(m_model
, &KFileItemModel::itemsChanged
,
755 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
756 const int index
= m_model
->index(item
);
757 m_model
->setData(index
, data
);
758 connect(m_model
, &KFileItemModel::itemsChanged
,
759 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
767 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString
& path
, int count
, long size
)
769 const bool getSizeRole
= m_roles
.contains("size");
770 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
772 if (getSizeRole
|| getIsExpandableRole
) {
773 const int index
= m_model
->index(QUrl::fromLocalFile(path
));
775 QHash
<QByteArray
, QVariant
> data
;
778 data
.insert("count", count
);
780 data
.insert("size", QVariant::fromValue(size
));
783 if (getIsExpandableRole
) {
784 data
.insert("isExpandable", count
> 0);
787 m_model
->setData(index
, data
);
792 void KFileItemModelRolesUpdater::startUpdating()
794 if (m_state
== Paused
) {
798 if (m_finishedItems
.count() == m_model
->count()) {
799 // All roles have been resolved already.
804 // Terminate all updates that are currently active.
806 m_pendingIndexes
.clear();
811 // Determine the icons for the visible items synchronously.
812 updateVisibleIcons();
814 // A detailed update of the items in and near the visible area
815 // only makes sense if sorting is finished.
816 if (m_state
== ResolvingSortRole
) {
820 // Start the preview job or the asynchronous resolving of all roles.
821 QList
<int> indexes
= indexesToResolve();
823 if (m_previewShown
) {
824 m_pendingPreviewItems
.clear();
825 m_pendingPreviewItems
.reserve(indexes
.count());
827 for (int index
: qAsConst(indexes
)) {
828 const KFileItem item
= m_model
->fileItem(index
);
829 if (!m_finishedItems
.contains(item
)) {
830 m_pendingPreviewItems
.append(item
);
836 m_pendingIndexes
= indexes
;
837 // Trigger the asynchronous resolving of all roles.
838 m_state
= ResolvingAllRoles
;
839 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
843 void KFileItemModelRolesUpdater::updateVisibleIcons()
845 int lastVisibleIndex
= m_lastVisibleIndex
;
846 if (lastVisibleIndex
<= 0) {
847 // Guess a reasonable value for the last visible index if the view
848 // has not told us about the real value yet.
849 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
850 if (lastVisibleIndex
<= 0) {
851 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
858 // Try to determine the final icons for all visible items.
860 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
861 applyResolvedRoles(index
, ResolveFast
);
864 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
865 // preliminary icons (i.e., without mime type determination) for the
869 void KFileItemModelRolesUpdater::startPreviewJob()
871 m_state
= PreviewJobRunning
;
873 if (m_pendingPreviewItems
.isEmpty()) {
874 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
878 // PreviewJob internally caches items always with the size of
879 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
880 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
881 // do a downscaling anyhow because of the frame, so in this case only the provided
882 // cache sizes are requested.
883 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
884 ? QSize(256, 256) : QSize(128, 128);
886 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
887 // worst case) might block the application for several seconds. To prevent such
888 // a blocking, we only pass items with known mime type to the preview job.
889 const int count
= m_pendingPreviewItems
.count();
890 KFileItemList itemSubSet
;
891 itemSubSet
.reserve(count
);
893 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
894 // Some mime types are known already, probably because they were
895 // determined when loading the icons for the visible items. Start
896 // a preview job for all items at the beginning of the list which
897 // have a known mime type.
899 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
900 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
902 // Determine mime types for MaxBlockTimeout ms, and start a preview
903 // job for the corresponding items.
908 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
909 item
.determineMimeType();
910 itemSubSet
.append(item
);
911 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
914 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
916 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile() && m_localFileSizePreviewLimit
<= 0);
917 if (job
->uiDelegate()) {
918 KJobWidgets::setWindow(job
, qApp
->activeWindow());
921 connect(job
, &KIO::PreviewJob::gotPreview
,
922 this, &KFileItemModelRolesUpdater::slotGotPreview
);
923 connect(job
, &KIO::PreviewJob::failed
,
924 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
925 connect(job
, &KIO::PreviewJob::finished
,
926 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
931 void KFileItemModelRolesUpdater::updateChangedItems()
933 if (m_state
== Paused
) {
937 if (m_changedItems
.isEmpty()) {
941 m_finishedItems
-= m_changedItems
;
943 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
944 m_pendingSortRoleItems
+= m_changedItems
;
946 if (m_state
!= ResolvingSortRole
) {
947 // Stop the preview job if necessary, and trigger the
948 // asynchronous determination of the sort role.
950 m_state
= ResolvingSortRole
;
951 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
957 QList
<int> visibleChangedIndexes
;
958 QList
<int> invisibleChangedIndexes
;
960 // Iterate over a const copy because items are deleted within the loop
961 const auto changedItems
= m_changedItems
;
962 for (const KFileItem item
: changedItems
) {
963 const int index
= m_model
->index(item
);
966 m_changedItems
.remove(item
);
970 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
971 visibleChangedIndexes
.append(index
);
973 invisibleChangedIndexes
.append(index
);
977 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
979 if (m_previewShown
) {
980 for (int index
: qAsConst(visibleChangedIndexes
)) {
981 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
984 for (int index
: qAsConst(invisibleChangedIndexes
)) {
985 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
992 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
993 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
994 if (!resolvingInProgress
) {
995 // Trigger the asynchronous resolving of the changed roles.
996 m_state
= ResolvingAllRoles
;
997 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
1002 void KFileItemModelRolesUpdater::applySortRole(int index
)
1004 QHash
<QByteArray
, QVariant
> data
;
1005 const KFileItem item
= m_model
->fileItem(index
);
1007 if (m_model
->sortRole() == "type") {
1008 if (!item
.isMimeTypeKnown()) {
1009 item
.determineMimeType();
1012 data
.insert("type", item
.mimeComment());
1013 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1014 const QString path
= item
.localPath();
1015 if (m_scanDirectories
) {
1016 m_directoryContentsCounter
->scanDirectory(path
);
1019 // Probably the sort role is a baloo role - just determine all roles.
1020 data
= rolesData(item
);
1023 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1024 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1025 m_model
->setData(index
, data
);
1026 connect(m_model
, &KFileItemModel::itemsChanged
,
1027 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1030 void KFileItemModelRolesUpdater::applySortProgressToModel()
1032 // Inform the model about the progress of the resolved items,
1033 // so that it can give an indication when the sorting has been finished.
1034 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1035 m_model
->emitSortProgress(resolvedCount
);
1038 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index
, ResolveHint hint
)
1040 const KFileItem item
= m_model
->fileItem(index
);
1041 const bool resolveAll
= (hint
== ResolveAll
);
1043 bool iconChanged
= false;
1044 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1045 item
.determineMimeType();
1047 } else if (!m_model
->data(index
).contains("iconName")) {
1051 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1056 QHash
<QByteArray
, QVariant
> data
;
1058 data
= rolesData(item
);
1061 if (QIcon::hasThemeIcon(item
.iconName())) {
1062 data
.insert("iconName", item
.iconName());
1065 if (m_clearPreviews
) {
1066 data
.insert("iconPixmap", QPixmap());
1069 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1070 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1071 m_model
->setData(index
, data
);
1072 connect(m_model
, &KFileItemModel::itemsChanged
,
1073 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1080 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
)
1082 QHash
<QByteArray
, QVariant
> data
;
1084 const bool getSizeRole
= m_roles
.contains("size");
1085 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1087 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1088 if (item
.isLocalFile() && !item
.isSlow()) {
1089 // Tell m_directoryContentsCounter that we want to count the items
1090 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1091 if (m_scanDirectories
) {
1092 const QString path
= item
.localPath();
1093 m_directoryContentsCounter
->scanDirectory(path
);
1095 } else if (getSizeRole
) {
1096 data
.insert("size", -1); // -1 indicates an unknown number of items
1100 if (m_roles
.contains("type")) {
1101 data
.insert("type", item
.mimeComment());
1104 QStringList overlays
= item
.overlays();
1105 for (KOverlayIconPlugin
*it
: qAsConst(m_overlayIconsPlugin
)) {
1106 overlays
.append(it
->getOverlays(item
.url()));
1108 data
.insert("iconOverlays", overlays
);
1111 if (m_balooFileMonitor
) {
1112 m_balooFileMonitor
->addFile(item
.localPath());
1113 applyChangedBalooRolesForItem(item
);
1119 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl
& url
, const QStringList
&)
1121 const KFileItem item
= m_model
->fileItem(url
);
1122 if (item
.isNull()) {
1125 const int index
= m_model
->index(item
);
1126 QHash
<QByteArray
, QVariant
> data
= m_model
->data(index
);
1127 QStringList overlays
= item
.overlays();
1128 for (KOverlayIconPlugin
*it
: qAsConst(m_overlayIconsPlugin
)) {
1129 overlays
.append(it
->getOverlays(url
));
1131 data
.insert("iconOverlays", overlays
);
1132 m_model
->setData(index
, data
);
1135 void KFileItemModelRolesUpdater::updateAllPreviews()
1137 if (m_state
== Paused
) {
1138 m_previewChangedDuringPausing
= true;
1140 m_finishedItems
.clear();
1145 void KFileItemModelRolesUpdater::killPreviewJob()
1148 disconnect(m_previewJob
, &KIO::PreviewJob::gotPreview
,
1149 this, &KFileItemModelRolesUpdater::slotGotPreview
);
1150 disconnect(m_previewJob
, &KIO::PreviewJob::failed
,
1151 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
1152 disconnect(m_previewJob
, &KIO::PreviewJob::finished
,
1153 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
1154 m_previewJob
->kill();
1155 m_previewJob
= nullptr;
1156 m_pendingPreviewItems
.clear();
1160 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1162 const int count
= m_model
->count();
1165 result
.reserve(ResolveAllItemsLimit
);
1167 // Add visible items.
1168 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1172 // We need a reasonable upper limit for number of items to resolve after
1173 // and before the visible range. m_maximumVisibleItems can be quite large
1174 // when using Compact View.
1175 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1177 // Add items after the visible range.
1178 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1179 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1183 // Add items before the visible range in reverse order.
1184 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1185 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1189 // Add items on the last page.
1190 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1191 for (int i
= beginLastPage
; i
< count
; ++i
) {
1195 // Add items on the first page.
1196 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1197 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1201 // Continue adding items until ResolveAllItemsLimit is reached.
1202 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1204 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1209 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {