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>
31 #include <QElapsedTimer>
34 // #define KFILEITEMMODELROLESUPDATER_DEBUG
37 // Maximum time in ms that the KFileItemModelRolesUpdater
38 // may perform a blocking operation
39 const int MaxBlockTimeout
= 200;
41 // If the number of items is smaller than ResolveAllItemsLimit,
42 // the roles of all items will be resolved.
43 const int ResolveAllItemsLimit
= 500;
45 // Not only the visible area, but up to ReadAheadPages before and after
46 // this area will be resolved.
47 const int ReadAheadPages
= 5;
50 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
53 m_previewChangedDuringPausing(false),
54 m_iconSizeChangedDuringPausing(false),
55 m_rolesChangedDuringPausing(false),
56 m_previewShown(false),
57 m_enlargeSmallPreviews(true),
58 m_clearPreviews(false),
62 m_firstVisibleIndex(0),
63 m_lastVisibleIndex(-1),
64 m_maximumVisibleItems(50),
68 m_localFileSizePreviewLimit(0),
69 m_pendingSortRoleItems(),
71 m_pendingPreviewItems(),
73 m_recentlyChangedItemsTimer(nullptr),
74 m_recentlyChangedItems(),
76 m_directoryContentsCounter(nullptr)
78 , m_balooFileMonitor(nullptr)
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));
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
);
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
);
105 m_resolvableRoles
.insert("size");
106 m_resolvableRoles
.insert("type");
107 m_resolvableRoles
.insert("isExpandable");
109 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
112 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
113 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
114 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
116 auto plugins
= KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp
);
117 foreach (QObject
*it
, plugins
) {
118 auto plugin
= qobject_cast
<KOverlayIconPlugin
*>(it
);
120 m_overlayIconsPlugin
.append(plugin
);
121 connect(plugin
, &KOverlayIconPlugin::overlaysChanged
, this, &KFileItemModelRolesUpdater::slotOverlaysChanged
);
123 // not our/valid plugin, so delete the created object
129 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
134 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
136 if (size
!= m_iconSize
) {
138 if (m_state
== Paused
) {
139 m_iconSizeChangedDuringPausing
= true;
140 } else if (m_previewShown
) {
141 // An icon size change requires the regenerating of
143 m_finishedItems
.clear();
149 QSize
KFileItemModelRolesUpdater::iconSize() const
154 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
163 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
164 // The range has not been changed
168 m_firstVisibleIndex
= index
;
169 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
174 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
176 m_maximumVisibleItems
= count
;
179 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
181 if (show
== m_previewShown
) {
185 m_previewShown
= show
;
187 m_clearPreviews
= true;
193 bool KFileItemModelRolesUpdater::previewsShown() const
195 return m_previewShown
;
198 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
200 if (enlarge
!= m_enlargeSmallPreviews
) {
201 m_enlargeSmallPreviews
= enlarge
;
202 if (m_previewShown
) {
208 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
210 return m_enlargeSmallPreviews
;
213 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
215 if (m_enabledPlugins
!= list
) {
216 m_enabledPlugins
= list
;
217 if (m_previewShown
) {
223 void KFileItemModelRolesUpdater::setPaused(bool paused
)
225 if (paused
== (m_state
== Paused
)) {
233 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
234 m_previewChangedDuringPausing
;
235 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
237 m_finishedItems
.clear();
240 m_iconSizeChangedDuringPausing
= false;
241 m_previewChangedDuringPausing
= false;
242 m_rolesChangedDuringPausing
= false;
244 if (!m_pendingSortRoleItems
.isEmpty()) {
245 m_state
= ResolvingSortRole
;
246 resolveNextSortRole();
255 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
257 if (m_roles
!= roles
) {
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
)) {
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;
286 if (m_state
== Paused
) {
287 m_rolesChangedDuringPausing
= true;
294 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
299 bool KFileItemModelRolesUpdater::isPaused() const
301 return m_state
== Paused
;
304 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
306 return m_enabledPlugins
;
309 void KFileItemModelRolesUpdater::setLocalFileSizePreviewLimit(const qlonglong size
)
311 m_localFileSizePreviewLimit
= size
;
314 qlonglong
KFileItemModelRolesUpdater::localFileSizePreviewLimit() const
316 return m_localFileSizePreviewLimit
;
319 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
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
) {
333 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
336 insertedCount
+= range
.count
;
339 applySortProgressToModel();
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
) {
346 m_state
= ResolvingSortRole
;
347 resolveNextSortRole();
354 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
358 const bool allItemsRemoved
= (m_model
->count() == 0);
361 if (m_balooFileMonitor
) {
362 // Don't let the FileWatcher watch for removed items
363 if (allItemsRemoved
) {
364 m_balooFileMonitor
->clear();
366 QStringList newFileList
;
367 foreach (const QString
& file
, m_balooFileMonitor
->files()) {
368 if (m_model
->index(QUrl::fromLocalFile(file
)) >= 0) {
369 newFileList
.append(file
);
372 m_balooFileMonitor
->setFiles(newFileList
);
377 if (allItemsRemoved
) {
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();
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
);
401 // The visible items might have changed.
406 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, const QList
<int> &movedToIndexes
)
409 Q_UNUSED(movedToIndexes
)
411 // The visible items might have changed.
415 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
416 const QSet
<QByteArray
>& roles
)
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();
425 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
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
);
436 m_recentlyChangedItemsTimer
->start();
438 if (!itemsChangedRecently
) {
439 updateChangedItems();
443 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
444 const QByteArray
& previous
)
449 if (m_resolvableRoles
.contains(current
)) {
450 m_pendingSortRoleItems
.clear();
451 m_finishedItems
.clear();
453 const int count
= m_model
->count();
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
);
462 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
466 applySortProgressToModel();
468 if (!m_pendingSortRoleItems
.isEmpty()) {
469 // Trigger the asynchronous determination of the sort role.
471 m_state
= ResolvingSortRole
;
472 resolveNextSortRole();
476 m_pendingSortRoleItems
.clear();
477 applySortProgressToModel();
481 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
483 if (m_state
!= PreviewJobRunning
) {
487 m_changedItems
.remove(item
);
489 const int index
= m_model
->index(item
);
494 QPixmap scaledPixmap
= pixmap
;
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
);
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
);
511 QPixmap
largeFrame(frameSize
);
512 largeFrame
.fill(Qt::transparent
);
514 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
516 QPainter
painter(&largeFrame
);
517 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width() / scaledPixmap
.devicePixelRatio()) / 2,
518 (largeFrame
.height() - scaledPixmap
.height() / scaledPixmap
.devicePixelRatio()) / 2,
520 scaledPixmap
= largeFrame
;
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
);
528 KPixmapModifier::scale(scaledPixmap
, m_iconSize
* qApp
->devicePixelRatio());
529 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
532 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
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
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
);
549 data
.insert("iconPixmap", scaledPixmap
);
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
);
557 m_finishedItems
.insert(item
);
560 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
562 if (m_state
!= PreviewJobRunning
) {
566 m_changedItems
.remove(item
);
568 const int index
= m_model
->index(item
);
570 QHash
<QByteArray
, QVariant
> data
;
571 data
.insert("iconPixmap", QPixmap());
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
);
579 applyResolvedRoles(index
, ResolveAll
);
580 m_finishedItems
.insert(item
);
584 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
586 m_previewJob
= nullptr;
588 if (m_state
!= PreviewJobRunning
) {
594 if (!m_pendingPreviewItems
.isEmpty()) {
597 if (!m_changedItems
.isEmpty()) {
598 updateChangedItems();
603 void KFileItemModelRolesUpdater::resolveNextSortRole()
605 if (m_state
!= ResolvingSortRole
) {
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
);
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
);
621 applySortRole(index
);
622 m_pendingSortRoleItems
.erase(it
);
626 if (!m_pendingSortRoleItems
.isEmpty()) {
627 applySortProgressToModel();
628 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
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
);
642 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
644 if (m_state
!= ResolvingAllRoles
) {
648 while (!m_pendingIndexes
.isEmpty()) {
649 const int index
= m_pendingIndexes
.takeFirst();
650 const KFileItem item
= m_model
->fileItem(index
);
652 if (m_finishedItems
.contains(item
)) {
656 applyResolvedRoles(index
, ResolveAll
);
657 m_finishedItems
.insert(item
);
658 m_changedItems
.remove(item
);
662 if (!m_pendingIndexes
.isEmpty()) {
663 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
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());
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
);
680 connect(m_model
, &KFileItemModel::itemsChanged
,
681 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
684 m_clearPreviews
= false;
687 if (!m_changedItems
.isEmpty()) {
688 updateChangedItems();
693 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
695 m_changedItems
+= m_recentlyChangedItems
;
696 m_recentlyChangedItems
.clear();
697 updateChangedItems();
700 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& file
)
703 const KFileItem item
= m_model
->fileItem(QUrl::fromLocalFile(file
));
706 // itemUrl is not in the model anymore, probably because
707 // the corresponding file has been deleted in the meantime.
710 applyChangedBalooRolesForItem(item
);
716 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem
&item
)
719 Baloo::File
file(item
.localPath());
722 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
723 QHash
<QByteArray
, QVariant
> data
;
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.
729 data
.insert(role
, QVariant());
732 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(file
, m_roles
));
733 while (it
.hasNext()) {
735 data
.insert(it
.key(), it
.value());
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
);
751 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString
& path
, int count
, long size
)
753 const bool getSizeRole
= m_roles
.contains("size");
754 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
756 if (getSizeRole
|| getIsExpandableRole
) {
757 const int index
= m_model
->index(QUrl::fromLocalFile(path
));
759 QHash
<QByteArray
, QVariant
> data
;
762 data
.insert("count", count
);
764 data
.insert("size", QVariant::fromValue(size
));
767 if (getIsExpandableRole
) {
768 data
.insert("isExpandable", count
> 0);
771 m_model
->setData(index
, data
);
776 void KFileItemModelRolesUpdater::startUpdating()
778 if (m_state
== Paused
) {
782 if (m_finishedItems
.count() == m_model
->count()) {
783 // All roles have been resolved already.
788 // Terminate all updates that are currently active.
790 m_pendingIndexes
.clear();
795 // Determine the icons for the visible items synchronously.
796 updateVisibleIcons();
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
) {
804 // Start the preview job or the asynchronous resolving of all roles.
805 QList
<int> indexes
= indexesToResolve();
807 if (m_previewShown
) {
808 m_pendingPreviewItems
.clear();
809 m_pendingPreviewItems
.reserve(indexes
.count());
811 foreach (int index
, indexes
) {
812 const KFileItem item
= m_model
->fileItem(index
);
813 if (!m_finishedItems
.contains(item
)) {
814 m_pendingPreviewItems
.append(item
);
820 m_pendingIndexes
= indexes
;
821 // Trigger the asynchronous resolving of all roles.
822 m_state
= ResolvingAllRoles
;
823 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
827 void KFileItemModelRolesUpdater::updateVisibleIcons()
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);
842 // Try to determine the final icons for all visible items.
844 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
845 applyResolvedRoles(index
, ResolveFast
);
848 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
849 // preliminary icons (i.e., without mime type determination) for the
853 void KFileItemModelRolesUpdater::startPreviewJob()
855 m_state
= PreviewJobRunning
;
857 if (m_pendingPreviewItems
.isEmpty()) {
858 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
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);
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
);
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.
883 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
884 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
886 // Determine mime types for MaxBlockTimeout ms, and start a preview
887 // job for the corresponding items.
892 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
893 item
.determineMimeType();
894 itemSubSet
.append(item
);
895 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
898 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
900 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile() && m_localFileSizePreviewLimit
<= 0);
901 if (job
->uiDelegate()) {
902 KJobWidgets::setWindow(job
, qApp
->activeWindow());
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
);
915 void KFileItemModelRolesUpdater::updateChangedItems()
917 if (m_state
== Paused
) {
921 if (m_changedItems
.isEmpty()) {
925 m_finishedItems
-= m_changedItems
;
927 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
928 m_pendingSortRoleItems
+= m_changedItems
;
930 if (m_state
!= ResolvingSortRole
) {
931 // Stop the preview job if necessary, and trigger the
932 // asynchronous determination of the sort role.
934 m_state
= ResolvingSortRole
;
935 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
941 QList
<int> visibleChangedIndexes
;
942 QList
<int> invisibleChangedIndexes
;
944 foreach (const KFileItem
& item
, m_changedItems
) {
945 const int index
= m_model
->index(item
);
948 m_changedItems
.remove(item
);
952 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
953 visibleChangedIndexes
.append(index
);
955 invisibleChangedIndexes
.append(index
);
959 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
961 if (m_previewShown
) {
962 foreach (int index
, visibleChangedIndexes
) {
963 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
966 foreach (int index
, invisibleChangedIndexes
) {
967 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
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
);
984 void KFileItemModelRolesUpdater::applySortRole(int index
)
986 QHash
<QByteArray
, QVariant
> data
;
987 const KFileItem item
= m_model
->fileItem(index
);
989 if (m_model
->sortRole() == "type") {
990 if (!item
.isMimeTypeKnown()) {
991 item
.determineMimeType();
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
);
999 // Probably the sort role is a baloo role - just determine all roles.
1000 data
= rolesData(item
);
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
);
1010 void KFileItemModelRolesUpdater::applySortProgressToModel()
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
);
1018 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index
, ResolveHint hint
)
1020 const KFileItem item
= m_model
->fileItem(index
);
1021 const bool resolveAll
= (hint
== ResolveAll
);
1023 bool iconChanged
= false;
1024 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1025 item
.determineMimeType();
1027 } else if (!m_model
->data(index
).contains("iconName")) {
1031 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1036 QHash
<QByteArray
, QVariant
> data
;
1038 data
= rolesData(item
);
1041 data
.insert("iconName", item
.iconName());
1043 if (m_clearPreviews
) {
1044 data
.insert("iconPixmap", QPixmap());
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
);
1058 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
)
1060 QHash
<QByteArray
, QVariant
> data
;
1062 const bool getSizeRole
= m_roles
.contains("size");
1063 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
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
1076 if (m_roles
.contains("type")) {
1077 data
.insert("type", item
.mimeComment());
1080 QStringList overlays
= item
.overlays();
1081 foreach(KOverlayIconPlugin
*it
, m_overlayIconsPlugin
) {
1082 overlays
.append(it
->getOverlays(item
.url()));
1084 data
.insert("iconOverlays", overlays
);
1087 if (m_balooFileMonitor
) {
1088 m_balooFileMonitor
->addFile(item
.localPath());
1089 applyChangedBalooRolesForItem(item
);
1095 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl
& url
, const QStringList
&)
1097 const KFileItem item
= m_model
->fileItem(url
);
1098 if (item
.isNull()) {
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
));
1107 data
.insert("iconOverlays", overlays
);
1108 m_model
->setData(index
, data
);
1111 void KFileItemModelRolesUpdater::updateAllPreviews()
1113 if (m_state
== Paused
) {
1114 m_previewChangedDuringPausing
= true;
1116 m_finishedItems
.clear();
1121 void KFileItemModelRolesUpdater::killPreviewJob()
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();
1136 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1138 const int count
= m_model
->count();
1141 result
.reserve(ResolveAllItemsLimit
);
1143 // Add visible items.
1144 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
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);
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
) {
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
) {
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
) {
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
) {
1177 // Continue adding items until ResolveAllItemsLimit is reached.
1178 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1180 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1185 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {