1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfileitemmodelrolesupdater.h"
22 #include "kfileitemmodel.h"
23 #include "private/kdirectorycontentscounter.h"
24 #include "private/kpixmapmodifier.h"
27 #include <KConfigGroup>
28 #include <KIO/JobUiDelegate>
29 #include <KIO/PreviewJob>
30 #include <KIconLoader>
31 #include <KJobWidgets>
32 #include <KOverlayIconPlugin>
33 #include <KPluginLoader>
34 #include <KSharedConfig>
37 #include "private/kbaloorolesprovider.h"
39 #include <Baloo/FileMonitor>
42 #include <QApplication>
44 #include <QElapsedTimer>
47 // #define KFILEITEMMODELROLESUPDATER_DEBUG
50 // Maximum time in ms that the KFileItemModelRolesUpdater
51 // may perform a blocking operation
52 const int MaxBlockTimeout
= 200;
54 // If the number of items is smaller than ResolveAllItemsLimit,
55 // the roles of all items will be resolved.
56 const int ResolveAllItemsLimit
= 500;
58 // Not only the visible area, but up to ReadAheadPages before and after
59 // this area will be resolved.
60 const int ReadAheadPages
= 5;
63 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
66 m_previewChangedDuringPausing(false),
67 m_iconSizeChangedDuringPausing(false),
68 m_rolesChangedDuringPausing(false),
69 m_previewShown(false),
70 m_enlargeSmallPreviews(true),
71 m_clearPreviews(false),
75 m_firstVisibleIndex(0),
76 m_lastVisibleIndex(-1),
77 m_maximumVisibleItems(50),
81 m_pendingSortRoleItems(),
83 m_pendingPreviewItems(),
85 m_recentlyChangedItemsTimer(nullptr),
86 m_recentlyChangedItems(),
88 m_directoryContentsCounter(nullptr),
89 m_localFileSizePreviewLimit(0)
91 , m_balooFileMonitor(nullptr)
96 const KConfigGroup
globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
97 m_enabledPlugins
= globalConfig
.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
98 m_localFileSizePreviewLimit
= static_cast<qulonglong
>(globalConfig
.readEntry("MaximumSize", 0));
100 connect(m_model
, &KFileItemModel::itemsInserted
,
101 this, &KFileItemModelRolesUpdater::slotItemsInserted
);
102 connect(m_model
, &KFileItemModel::itemsRemoved
,
103 this, &KFileItemModelRolesUpdater::slotItemsRemoved
);
104 connect(m_model
, &KFileItemModel::itemsChanged
,
105 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
106 connect(m_model
, &KFileItemModel::itemsMoved
,
107 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
108 connect(m_model
, &KFileItemModel::sortRoleChanged
,
109 this, &KFileItemModelRolesUpdater::slotSortRoleChanged
);
111 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
112 // resolving of the roles. Postpone the resolving until no update has been done for 100 ms.
113 m_recentlyChangedItemsTimer
= new QTimer(this);
114 m_recentlyChangedItemsTimer
->setInterval(100);
115 m_recentlyChangedItemsTimer
->setSingleShot(true);
116 connect(m_recentlyChangedItemsTimer
, &QTimer::timeout
, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems
);
118 m_resolvableRoles
.insert("size");
119 m_resolvableRoles
.insert("type");
120 m_resolvableRoles
.insert("isExpandable");
122 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
125 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
126 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
127 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
129 auto plugins
= KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp
);
130 foreach (QObject
*it
, plugins
) {
131 auto plugin
= qobject_cast
<KOverlayIconPlugin
*>(it
);
133 m_overlayIconsPlugin
.append(plugin
);
134 connect(plugin
, &KOverlayIconPlugin::overlaysChanged
, this, &KFileItemModelRolesUpdater::slotOverlaysChanged
);
136 // not our/valid plugin, so delete the created object
142 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
147 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
149 if (size
!= m_iconSize
) {
151 if (m_state
== Paused
) {
152 m_iconSizeChangedDuringPausing
= true;
153 } else if (m_previewShown
) {
154 // An icon size change requires the regenerating of
156 m_finishedItems
.clear();
162 QSize
KFileItemModelRolesUpdater::iconSize() const
167 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
176 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
177 // The range has not been changed
181 m_firstVisibleIndex
= index
;
182 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
187 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
189 m_maximumVisibleItems
= count
;
192 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
194 if (show
== m_previewShown
) {
198 m_previewShown
= show
;
200 m_clearPreviews
= true;
206 bool KFileItemModelRolesUpdater::previewsShown() const
208 return m_previewShown
;
211 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
213 if (enlarge
!= m_enlargeSmallPreviews
) {
214 m_enlargeSmallPreviews
= enlarge
;
215 if (m_previewShown
) {
221 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
223 return m_enlargeSmallPreviews
;
226 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
228 if (m_enabledPlugins
!= list
) {
229 m_enabledPlugins
= list
;
230 if (m_previewShown
) {
236 void KFileItemModelRolesUpdater::setPaused(bool paused
)
238 if (paused
== (m_state
== Paused
)) {
246 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
247 m_previewChangedDuringPausing
;
248 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
250 m_finishedItems
.clear();
253 m_iconSizeChangedDuringPausing
= false;
254 m_previewChangedDuringPausing
= false;
255 m_rolesChangedDuringPausing
= false;
257 if (!m_pendingSortRoleItems
.isEmpty()) {
258 m_state
= ResolvingSortRole
;
259 resolveNextSortRole();
268 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
270 if (m_roles
!= roles
) {
274 // Check whether there is at least one role that must be resolved
275 // with the help of Baloo. If this is the case, a (quite expensive)
276 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
277 // the role gets watched for changes.
278 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
279 bool hasBalooRole
= false;
280 QSetIterator
<QByteArray
> it(roles
);
281 while (it
.hasNext()) {
282 const QByteArray
& role
= it
.next();
283 if (rolesProvider
.roles().contains(role
)) {
289 if (hasBalooRole
&& m_balooConfig
.fileIndexingEnabled() && !m_balooFileMonitor
) {
290 m_balooFileMonitor
= new Baloo::FileMonitor(this);
291 connect(m_balooFileMonitor
, &Baloo::FileMonitor::fileMetaDataChanged
,
292 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles
);
293 } else if (!hasBalooRole
&& m_balooFileMonitor
) {
294 delete m_balooFileMonitor
;
295 m_balooFileMonitor
= nullptr;
299 if (m_state
== Paused
) {
300 m_rolesChangedDuringPausing
= true;
307 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
312 bool KFileItemModelRolesUpdater::isPaused() const
314 return m_state
== Paused
;
317 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
319 return m_enabledPlugins
;
322 void KFileItemModelRolesUpdater::setLocalFileSizePreviewLimit(const qlonglong size
)
324 m_localFileSizePreviewLimit
= size
;
327 qlonglong
KFileItemModelRolesUpdater::localFileSizePreviewLimit() const
329 return m_localFileSizePreviewLimit
;
332 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
337 // Determine the sort role synchronously for as many items as possible.
338 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
339 int insertedCount
= 0;
340 foreach (const KItemRange
& range
, itemRanges
) {
341 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
342 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
343 if (timer
.elapsed() < MaxBlockTimeout
) {
346 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
349 insertedCount
+= range
.count
;
352 applySortProgressToModel();
354 // If there are still items whose sort role is unknown, check if the
355 // asynchronous determination of the sort role is already in progress,
356 // and start it if that is not the case.
357 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
359 m_state
= ResolvingSortRole
;
360 resolveNextSortRole();
367 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
371 const bool allItemsRemoved
= (m_model
->count() == 0);
374 if (m_balooFileMonitor
) {
375 // Don't let the FileWatcher watch for removed items
376 if (allItemsRemoved
) {
377 m_balooFileMonitor
->clear();
379 QStringList newFileList
;
380 foreach (const QString
& file
, m_balooFileMonitor
->files()) {
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 foreach (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()
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
);
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 foreach (const QString
& overlay
, overlays
) {
554 if (!overlay
.isEmpty()) {
555 // There is at least one overlay, draw all overlays above m_pixmap
556 // and cancel the check
557 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
562 data
.insert("iconPixmap", scaledPixmap
);
564 disconnect(m_model
, &KFileItemModel::itemsChanged
,
565 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
566 m_model
->setData(index
, data
);
567 connect(m_model
, &KFileItemModel::itemsChanged
,
568 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
570 m_finishedItems
.insert(item
);
573 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
575 if (m_state
!= PreviewJobRunning
) {
579 m_changedItems
.remove(item
);
581 const int index
= m_model
->index(item
);
583 QHash
<QByteArray
, QVariant
> data
;
584 data
.insert("iconPixmap", QPixmap());
586 disconnect(m_model
, &KFileItemModel::itemsChanged
,
587 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
588 m_model
->setData(index
, data
);
589 connect(m_model
, &KFileItemModel::itemsChanged
,
590 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
592 applyResolvedRoles(index
, ResolveAll
);
593 m_finishedItems
.insert(item
);
597 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
599 m_previewJob
= nullptr;
601 if (m_state
!= PreviewJobRunning
) {
607 if (!m_pendingPreviewItems
.isEmpty()) {
610 if (!m_changedItems
.isEmpty()) {
611 updateChangedItems();
616 void KFileItemModelRolesUpdater::resolveNextSortRole()
618 if (m_state
!= ResolvingSortRole
) {
622 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
623 while (it
!= m_pendingSortRoleItems
.end()) {
624 const KFileItem item
= *it
;
625 const int index
= m_model
->index(item
);
627 // Continue if the sort role has already been determined for the
628 // item, and the item has not been changed recently.
629 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
630 it
= m_pendingSortRoleItems
.erase(it
);
634 applySortRole(index
);
635 m_pendingSortRoleItems
.erase(it
);
639 if (!m_pendingSortRoleItems
.isEmpty()) {
640 applySortProgressToModel();
641 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
645 // Prevent that we try to update the items twice.
646 disconnect(m_model
, &KFileItemModel::itemsMoved
,
647 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
648 applySortProgressToModel();
649 connect(m_model
, &KFileItemModel::itemsMoved
,
650 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
655 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
657 if (m_state
!= ResolvingAllRoles
) {
661 while (!m_pendingIndexes
.isEmpty()) {
662 const int index
= m_pendingIndexes
.takeFirst();
663 const KFileItem item
= m_model
->fileItem(index
);
665 if (m_finishedItems
.contains(item
)) {
669 applyResolvedRoles(index
, ResolveAll
);
670 m_finishedItems
.insert(item
);
671 m_changedItems
.remove(item
);
675 if (!m_pendingIndexes
.isEmpty()) {
676 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
680 if (m_clearPreviews
) {
681 // Only go through the list if there are items which might still have previews.
682 if (m_finishedItems
.count() != m_model
->count()) {
683 QHash
<QByteArray
, QVariant
> data
;
684 data
.insert("iconPixmap", QPixmap());
686 disconnect(m_model
, &KFileItemModel::itemsChanged
,
687 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
688 for (int index
= 0; index
<= m_model
->count(); ++index
) {
689 if (m_model
->data(index
).contains("iconPixmap")) {
690 m_model
->setData(index
, data
);
693 connect(m_model
, &KFileItemModel::itemsChanged
,
694 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
697 m_clearPreviews
= false;
700 if (!m_changedItems
.isEmpty()) {
701 updateChangedItems();
706 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
708 m_changedItems
+= m_recentlyChangedItems
;
709 m_recentlyChangedItems
.clear();
710 updateChangedItems();
713 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& file
)
716 const KFileItem item
= m_model
->fileItem(QUrl::fromLocalFile(file
));
719 // itemUrl is not in the model anymore, probably because
720 // the corresponding file has been deleted in the meantime.
723 applyChangedBalooRolesForItem(item
);
729 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem
&item
)
732 Baloo::File
file(item
.localPath());
735 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
736 QHash
<QByteArray
, QVariant
> data
;
738 foreach (const QByteArray
& role
, rolesProvider
.roles()) {
739 // Overwrite all the role values with an empty QVariant, because the roles
740 // provider doesn't overwrite it when the property value list is empty.
742 data
.insert(role
, QVariant());
745 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(file
, m_roles
));
746 while (it
.hasNext()) {
748 data
.insert(it
.key(), it
.value());
751 disconnect(m_model
, &KFileItemModel::itemsChanged
,
752 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
753 const int index
= m_model
->index(item
);
754 m_model
->setData(index
, data
);
755 connect(m_model
, &KFileItemModel::itemsChanged
,
756 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
764 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString
& path
, int count
, long size
)
766 const bool getSizeRole
= m_roles
.contains("size");
767 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
769 if (getSizeRole
|| getIsExpandableRole
) {
770 const int index
= m_model
->index(QUrl::fromLocalFile(path
));
772 QHash
<QByteArray
, QVariant
> data
;
775 data
.insert("count", count
);
777 data
.insert("size", QVariant::fromValue(size
));
780 if (getIsExpandableRole
) {
781 data
.insert("isExpandable", count
> 0);
784 m_model
->setData(index
, data
);
789 void KFileItemModelRolesUpdater::startUpdating()
791 if (m_state
== Paused
) {
795 if (m_finishedItems
.count() == m_model
->count()) {
796 // All roles have been resolved already.
801 // Terminate all updates that are currently active.
803 m_pendingIndexes
.clear();
808 // Determine the icons for the visible items synchronously.
809 updateVisibleIcons();
811 // A detailed update of the items in and near the visible area
812 // only makes sense if sorting is finished.
813 if (m_state
== ResolvingSortRole
) {
817 // Start the preview job or the asynchronous resolving of all roles.
818 QList
<int> indexes
= indexesToResolve();
820 if (m_previewShown
) {
821 m_pendingPreviewItems
.clear();
822 m_pendingPreviewItems
.reserve(indexes
.count());
824 foreach (int index
, indexes
) {
825 const KFileItem item
= m_model
->fileItem(index
);
826 if (!m_finishedItems
.contains(item
)) {
827 m_pendingPreviewItems
.append(item
);
833 m_pendingIndexes
= indexes
;
834 // Trigger the asynchronous resolving of all roles.
835 m_state
= ResolvingAllRoles
;
836 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
840 void KFileItemModelRolesUpdater::updateVisibleIcons()
842 int lastVisibleIndex
= m_lastVisibleIndex
;
843 if (lastVisibleIndex
<= 0) {
844 // Guess a reasonable value for the last visible index if the view
845 // has not told us about the real value yet.
846 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
847 if (lastVisibleIndex
<= 0) {
848 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
855 // Try to determine the final icons for all visible items.
857 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
858 applyResolvedRoles(index
, ResolveFast
);
861 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
862 // preliminary icons (i.e., without mime type determination) for the
866 void KFileItemModelRolesUpdater::startPreviewJob()
868 m_state
= PreviewJobRunning
;
870 if (m_pendingPreviewItems
.isEmpty()) {
871 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
875 // PreviewJob internally caches items always with the size of
876 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
877 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
878 // do a downscaling anyhow because of the frame, so in this case only the provided
879 // cache sizes are requested.
880 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
881 ? QSize(256, 256) : QSize(128, 128);
883 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
884 // worst case) might block the application for several seconds. To prevent such
885 // a blocking, we only pass items with known mime type to the preview job.
886 const int count
= m_pendingPreviewItems
.count();
887 KFileItemList itemSubSet
;
888 itemSubSet
.reserve(count
);
890 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
891 // Some mime types are known already, probably because they were
892 // determined when loading the icons for the visible items. Start
893 // a preview job for all items at the beginning of the list which
894 // have a known mime type.
896 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
897 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
899 // Determine mime types for MaxBlockTimeout ms, and start a preview
900 // job for the corresponding items.
905 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
906 item
.determineMimeType();
907 itemSubSet
.append(item
);
908 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
911 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
913 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile() && m_localFileSizePreviewLimit
<= 0);
914 if (job
->uiDelegate()) {
915 KJobWidgets::setWindow(job
, qApp
->activeWindow());
918 connect(job
, &KIO::PreviewJob::gotPreview
,
919 this, &KFileItemModelRolesUpdater::slotGotPreview
);
920 connect(job
, &KIO::PreviewJob::failed
,
921 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
922 connect(job
, &KIO::PreviewJob::finished
,
923 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
928 void KFileItemModelRolesUpdater::updateChangedItems()
930 if (m_state
== Paused
) {
934 if (m_changedItems
.isEmpty()) {
938 m_finishedItems
-= m_changedItems
;
940 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
941 m_pendingSortRoleItems
+= m_changedItems
;
943 if (m_state
!= ResolvingSortRole
) {
944 // Stop the preview job if necessary, and trigger the
945 // asynchronous determination of the sort role.
947 m_state
= ResolvingSortRole
;
948 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
954 QList
<int> visibleChangedIndexes
;
955 QList
<int> invisibleChangedIndexes
;
957 foreach (const KFileItem
& item
, m_changedItems
) {
958 const int index
= m_model
->index(item
);
961 m_changedItems
.remove(item
);
965 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
966 visibleChangedIndexes
.append(index
);
968 invisibleChangedIndexes
.append(index
);
972 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
974 if (m_previewShown
) {
975 foreach (int index
, visibleChangedIndexes
) {
976 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
979 foreach (int index
, invisibleChangedIndexes
) {
980 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
987 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
988 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
989 if (!resolvingInProgress
) {
990 // Trigger the asynchronous resolving of the changed roles.
991 m_state
= ResolvingAllRoles
;
992 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
997 void KFileItemModelRolesUpdater::applySortRole(int index
)
999 QHash
<QByteArray
, QVariant
> data
;
1000 const KFileItem item
= m_model
->fileItem(index
);
1002 if (m_model
->sortRole() == "type") {
1003 if (!item
.isMimeTypeKnown()) {
1004 item
.determineMimeType();
1007 data
.insert("type", item
.mimeComment());
1008 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1009 const QString path
= item
.localPath();
1010 m_directoryContentsCounter
->scanDirectory(path
);
1012 // Probably the sort role is a baloo role - just determine all roles.
1013 data
= rolesData(item
);
1016 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1017 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1018 m_model
->setData(index
, data
);
1019 connect(m_model
, &KFileItemModel::itemsChanged
,
1020 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1023 void KFileItemModelRolesUpdater::applySortProgressToModel()
1025 // Inform the model about the progress of the resolved items,
1026 // so that it can give an indication when the sorting has been finished.
1027 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1028 m_model
->emitSortProgress(resolvedCount
);
1031 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index
, ResolveHint hint
)
1033 const KFileItem item
= m_model
->fileItem(index
);
1034 const bool resolveAll
= (hint
== ResolveAll
);
1036 bool iconChanged
= false;
1037 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1038 item
.determineMimeType();
1040 } else if (!m_model
->data(index
).contains("iconName")) {
1044 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1049 QHash
<QByteArray
, QVariant
> data
;
1051 data
= rolesData(item
);
1054 data
.insert("iconName", item
.iconName());
1056 if (m_clearPreviews
) {
1057 data
.insert("iconPixmap", QPixmap());
1060 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1061 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1062 m_model
->setData(index
, data
);
1063 connect(m_model
, &KFileItemModel::itemsChanged
,
1064 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1071 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
)
1073 QHash
<QByteArray
, QVariant
> data
;
1075 const bool getSizeRole
= m_roles
.contains("size");
1076 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1078 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1079 if (item
.isLocalFile()) {
1080 // Tell m_directoryContentsCounter that we want to count the items
1081 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1082 const QString path
= item
.localPath();
1083 m_directoryContentsCounter
->scanDirectory(path
);
1084 } else if (getSizeRole
) {
1085 data
.insert("size", -1); // -1 indicates an unknown number of items
1089 if (m_roles
.contains("type")) {
1090 data
.insert("type", item
.mimeComment());
1093 QStringList overlays
= item
.overlays();
1094 foreach(KOverlayIconPlugin
*it
, m_overlayIconsPlugin
) {
1095 overlays
.append(it
->getOverlays(item
.url()));
1097 data
.insert("iconOverlays", overlays
);
1100 if (m_balooFileMonitor
) {
1101 m_balooFileMonitor
->addFile(item
.localPath());
1102 applyChangedBalooRolesForItem(item
);
1108 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl
& url
, const QStringList
&)
1110 const KFileItem item
= m_model
->fileItem(url
);
1111 if (item
.isNull()) {
1114 const int index
= m_model
->index(item
);
1115 QHash
<QByteArray
, QVariant
> data
= m_model
->data(index
);
1116 QStringList overlays
= item
.overlays();
1117 foreach (KOverlayIconPlugin
*it
, m_overlayIconsPlugin
) {
1118 overlays
.append(it
->getOverlays(url
));
1120 data
.insert("iconOverlays", overlays
);
1121 m_model
->setData(index
, data
);
1124 void KFileItemModelRolesUpdater::updateAllPreviews()
1126 if (m_state
== Paused
) {
1127 m_previewChangedDuringPausing
= true;
1129 m_finishedItems
.clear();
1134 void KFileItemModelRolesUpdater::killPreviewJob()
1137 disconnect(m_previewJob
, &KIO::PreviewJob::gotPreview
,
1138 this, &KFileItemModelRolesUpdater::slotGotPreview
);
1139 disconnect(m_previewJob
, &KIO::PreviewJob::failed
,
1140 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
1141 disconnect(m_previewJob
, &KIO::PreviewJob::finished
,
1142 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
1143 m_previewJob
->kill();
1144 m_previewJob
= nullptr;
1145 m_pendingPreviewItems
.clear();
1149 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1151 const int count
= m_model
->count();
1154 result
.reserve(ResolveAllItemsLimit
);
1156 // Add visible items.
1157 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1161 // We need a reasonable upper limit for number of items to resolve after
1162 // and before the visible range. m_maximumVisibleItems can be quite large
1163 // when using Compact View.
1164 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1166 // Add items after the visible range.
1167 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1168 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1172 // Add items before the visible range in reverse order.
1173 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1174 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1178 // Add items on the last page.
1179 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1180 for (int i
= beginLastPage
; i
< count
; ++i
) {
1184 // Add items on the first page.
1185 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1186 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1190 // Continue adding items until ResolveAllItemsLimit is reached.
1191 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1193 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1198 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {