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>
48 // #define KFILEITEMMODELROLESUPDATER_DEBUG
51 // Maximum time in ms that the KFileItemModelRolesUpdater
52 // may perform a blocking operation
53 const int MaxBlockTimeout
= 200;
55 // If the number of items is smaller than ResolveAllItemsLimit,
56 // the roles of all items will be resolved.
57 const int ResolveAllItemsLimit
= 500;
59 // Not only the visible area, but up to ReadAheadPages before and after
60 // this area will be resolved.
61 const int ReadAheadPages
= 5;
64 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
67 m_previewChangedDuringPausing(false),
68 m_iconSizeChangedDuringPausing(false),
69 m_rolesChangedDuringPausing(false),
70 m_previewShown(false),
71 m_enlargeSmallPreviews(true),
72 m_clearPreviews(false),
76 m_firstVisibleIndex(0),
77 m_lastVisibleIndex(-1),
78 m_maximumVisibleItems(50),
82 m_pendingSortRoleItems(),
84 m_pendingPreviewItems(),
86 m_recentlyChangedItemsTimer(nullptr),
87 m_recentlyChangedItems(),
89 m_directoryContentsCounter(nullptr)
91 , m_balooFileMonitor(nullptr)
96 const KConfigGroup
globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
97 m_enabledPlugins
= globalConfig
.readEntry("Plugins", KIO::PreviewJob::defaultPlugins());
99 connect(m_model
, &KFileItemModel::itemsInserted
,
100 this, &KFileItemModelRolesUpdater::slotItemsInserted
);
101 connect(m_model
, &KFileItemModel::itemsRemoved
,
102 this, &KFileItemModelRolesUpdater::slotItemsRemoved
);
103 connect(m_model
, &KFileItemModel::itemsChanged
,
104 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
105 connect(m_model
, &KFileItemModel::itemsMoved
,
106 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
107 connect(m_model
, &KFileItemModel::sortRoleChanged
,
108 this, &KFileItemModelRolesUpdater::slotSortRoleChanged
);
110 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
111 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
112 m_recentlyChangedItemsTimer
= new QTimer(this);
113 m_recentlyChangedItemsTimer
->setInterval(1000);
114 m_recentlyChangedItemsTimer
->setSingleShot(true);
115 connect(m_recentlyChangedItemsTimer
, &QTimer::timeout
, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems
);
117 m_resolvableRoles
.insert("size");
118 m_resolvableRoles
.insert("type");
119 m_resolvableRoles
.insert("isExpandable");
121 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
124 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
125 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
126 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
128 auto plugins
= KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp
);
129 foreach (QObject
*it
, plugins
) {
130 auto plugin
= qobject_cast
<KOverlayIconPlugin
*>(it
);
132 m_overlayIconsPlugin
.append(plugin
);
133 connect(plugin
, &KOverlayIconPlugin::overlaysChanged
, this, &KFileItemModelRolesUpdater::slotOverlaysChanged
);
135 // not our/valid plugin, so delete the created object
141 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
146 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
148 if (size
!= m_iconSize
) {
150 if (m_state
== Paused
) {
151 m_iconSizeChangedDuringPausing
= true;
152 } else if (m_previewShown
) {
153 // An icon size change requires the regenerating of
155 m_finishedItems
.clear();
161 QSize
KFileItemModelRolesUpdater::iconSize() const
166 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
175 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
176 // The range has not been changed
180 m_firstVisibleIndex
= index
;
181 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
186 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
188 m_maximumVisibleItems
= count
;
191 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
193 if (show
== m_previewShown
) {
197 m_previewShown
= show
;
199 m_clearPreviews
= true;
205 bool KFileItemModelRolesUpdater::previewsShown() const
207 return m_previewShown
;
210 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
212 if (enlarge
!= m_enlargeSmallPreviews
) {
213 m_enlargeSmallPreviews
= enlarge
;
214 if (m_previewShown
) {
220 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
222 return m_enlargeSmallPreviews
;
225 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
227 if (m_enabledPlugins
!= list
) {
228 m_enabledPlugins
= list
;
229 if (m_previewShown
) {
235 void KFileItemModelRolesUpdater::setPaused(bool paused
)
237 if (paused
== (m_state
== Paused
)) {
245 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
246 m_previewChangedDuringPausing
;
247 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
249 m_finishedItems
.clear();
252 m_iconSizeChangedDuringPausing
= false;
253 m_previewChangedDuringPausing
= false;
254 m_rolesChangedDuringPausing
= false;
256 if (!m_pendingSortRoleItems
.isEmpty()) {
257 m_state
= ResolvingSortRole
;
258 resolveNextSortRole();
267 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
269 if (m_roles
!= roles
) {
273 // Check whether there is at least one role that must be resolved
274 // with the help of Baloo. If this is the case, a (quite expensive)
275 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
276 // the role gets watched for changes.
277 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
278 bool hasBalooRole
= false;
279 QSetIterator
<QByteArray
> it(roles
);
280 while (it
.hasNext()) {
281 const QByteArray
& role
= it
.next();
282 if (rolesProvider
.roles().contains(role
)) {
288 if (hasBalooRole
&& m_balooConfig
.fileIndexingEnabled() && !m_balooFileMonitor
) {
289 m_balooFileMonitor
= new Baloo::FileMonitor(this);
290 connect(m_balooFileMonitor
, &Baloo::FileMonitor::fileMetaDataChanged
,
291 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles
);
292 } else if (!hasBalooRole
&& m_balooFileMonitor
) {
293 delete m_balooFileMonitor
;
294 m_balooFileMonitor
= nullptr;
298 if (m_state
== Paused
) {
299 m_rolesChangedDuringPausing
= true;
306 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
311 bool KFileItemModelRolesUpdater::isPaused() const
313 return m_state
== Paused
;
316 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
318 return m_enabledPlugins
;
321 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
326 // Determine the sort role synchronously for as many items as possible.
327 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
328 int insertedCount
= 0;
329 foreach (const KItemRange
& range
, itemRanges
) {
330 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
331 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
332 if (timer
.elapsed() < MaxBlockTimeout
) {
335 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
338 insertedCount
+= range
.count
;
341 applySortProgressToModel();
343 // If there are still items whose sort role is unknown, check if the
344 // asynchronous determination of the sort role is already in progress,
345 // and start it if that is not the case.
346 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
348 m_state
= ResolvingSortRole
;
349 resolveNextSortRole();
356 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
358 Q_UNUSED(itemRanges
);
360 const bool allItemsRemoved
= (m_model
->count() == 0);
363 if (m_balooFileMonitor
) {
364 // Don't let the FileWatcher watch for removed items
365 if (allItemsRemoved
) {
366 m_balooFileMonitor
->clear();
368 QStringList newFileList
;
369 foreach (const QString
& file
, m_balooFileMonitor
->files()) {
370 if (m_model
->index(QUrl::fromLocalFile(file
)) >= 0) {
371 newFileList
.append(file
);
374 m_balooFileMonitor
->setFiles(newFileList
);
379 if (allItemsRemoved
) {
382 m_finishedItems
.clear();
383 m_pendingSortRoleItems
.clear();
384 m_pendingIndexes
.clear();
385 m_pendingPreviewItems
.clear();
386 m_recentlyChangedItems
.clear();
387 m_recentlyChangedItemsTimer
->stop();
388 m_changedItems
.clear();
392 // Only remove the items from m_finishedItems. They will be removed
393 // from the other sets later on.
394 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
395 while (it
!= m_finishedItems
.end()) {
396 if (m_model
->index(*it
) < 0) {
397 it
= m_finishedItems
.erase(it
);
403 // The visible items might have changed.
408 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
411 Q_UNUSED(movedToIndexes
);
413 // The visible items might have changed.
417 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
418 const QSet
<QByteArray
>& roles
)
422 // Find out if slotItemsChanged() has been done recently. If that is the
423 // case, resolving the roles is postponed until a timer has exceeded
424 // to prevent expensive repeated updates if files are updated frequently.
425 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
427 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
429 foreach (const KItemRange
& itemRange
, itemRanges
) {
430 int index
= itemRange
.index
;
431 for (int count
= itemRange
.count
; count
> 0; --count
) {
432 const KFileItem item
= m_model
->fileItem(index
);
433 targetSet
.insert(item
);
438 m_recentlyChangedItemsTimer
->start();
440 if (!itemsChangedRecently
) {
441 updateChangedItems();
445 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
446 const QByteArray
& previous
)
451 if (m_resolvableRoles
.contains(current
)) {
452 m_pendingSortRoleItems
.clear();
453 m_finishedItems
.clear();
455 const int count
= m_model
->count();
459 // Determine the sort role synchronously for as many items as possible.
460 for (int index
= 0; index
< count
; ++index
) {
461 if (timer
.elapsed() < MaxBlockTimeout
) {
462 applySortRole(index
);
464 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
468 applySortProgressToModel();
470 if (!m_pendingSortRoleItems
.isEmpty()) {
471 // Trigger the asynchronous determination of the sort role.
473 m_state
= ResolvingSortRole
;
474 resolveNextSortRole();
478 m_pendingSortRoleItems
.clear();
479 applySortProgressToModel();
483 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
485 if (m_state
!= PreviewJobRunning
) {
489 m_changedItems
.remove(item
);
491 const int index
= m_model
->index(item
);
496 QPixmap scaledPixmap
= pixmap
;
498 if (!pixmap
.hasAlpha()
499 && m_iconSize
.width() > KIconLoader::SizeSmallMedium
500 && m_iconSize
.height() > KIconLoader::SizeSmallMedium
) {
501 if (m_enlargeSmallPreviews
) {
502 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
504 // Assure that small previews don't get enlarged. Instead they
505 // should be shown centered within the frame.
506 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
507 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
508 scaledPixmap
.height() < contentSize
.height();
509 if (enlargingRequired
) {
510 QSize frameSize
= scaledPixmap
.size() / scaledPixmap
.devicePixelRatio();
511 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
513 QPixmap
largeFrame(frameSize
);
514 largeFrame
.fill(Qt::transparent
);
516 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
518 QPainter
painter(&largeFrame
);
519 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width() / scaledPixmap
.devicePixelRatio()) / 2,
520 (largeFrame
.height() - scaledPixmap
.height() / scaledPixmap
.devicePixelRatio()) / 2,
522 scaledPixmap
= largeFrame
;
524 // The image must be shrinked as it is too large to fit into
525 // the available icon size
526 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
530 KPixmapModifier::scale(scaledPixmap
, m_iconSize
* qApp
->devicePixelRatio());
531 scaledPixmap
.setDevicePixelRatio(qApp
->devicePixelRatio());
534 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
536 const QStringList overlays
= data
["iconOverlays"].toStringList();
537 // Strangely KFileItem::overlays() returns empty string-values, so
538 // we need to check first whether an overlay must be drawn at all.
539 // It is more efficient to do it here, as KIconLoader::drawOverlays()
540 // assumes that an overlay will be drawn and has some additional
542 foreach (const QString
& overlay
, overlays
) {
543 if (!overlay
.isEmpty()) {
544 // There is at least one overlay, draw all overlays above m_pixmap
545 // and cancel the check
546 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
551 data
.insert("iconPixmap", scaledPixmap
);
553 disconnect(m_model
, &KFileItemModel::itemsChanged
,
554 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
555 m_model
->setData(index
, data
);
556 connect(m_model
, &KFileItemModel::itemsChanged
,
557 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
559 m_finishedItems
.insert(item
);
562 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
564 if (m_state
!= PreviewJobRunning
) {
568 m_changedItems
.remove(item
);
570 const int index
= m_model
->index(item
);
572 QHash
<QByteArray
, QVariant
> data
;
573 data
.insert("iconPixmap", QPixmap());
575 disconnect(m_model
, &KFileItemModel::itemsChanged
,
576 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
577 m_model
->setData(index
, data
);
578 connect(m_model
, &KFileItemModel::itemsChanged
,
579 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
581 applyResolvedRoles(index
, ResolveAll
);
582 m_finishedItems
.insert(item
);
586 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
588 m_previewJob
= nullptr;
590 if (m_state
!= PreviewJobRunning
) {
596 if (!m_pendingPreviewItems
.isEmpty()) {
599 if (!m_changedItems
.isEmpty()) {
600 updateChangedItems();
605 void KFileItemModelRolesUpdater::resolveNextSortRole()
607 if (m_state
!= ResolvingSortRole
) {
611 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
612 while (it
!= m_pendingSortRoleItems
.end()) {
613 const KFileItem item
= *it
;
614 const int index
= m_model
->index(item
);
616 // Continue if the sort role has already been determined for the
617 // item, and the item has not been changed recently.
618 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
619 it
= m_pendingSortRoleItems
.erase(it
);
623 applySortRole(index
);
624 m_pendingSortRoleItems
.erase(it
);
628 if (!m_pendingSortRoleItems
.isEmpty()) {
629 applySortProgressToModel();
630 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
634 // Prevent that we try to update the items twice.
635 disconnect(m_model
, &KFileItemModel::itemsMoved
,
636 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
637 applySortProgressToModel();
638 connect(m_model
, &KFileItemModel::itemsMoved
,
639 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
644 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
646 if (m_state
!= ResolvingAllRoles
) {
650 while (!m_pendingIndexes
.isEmpty()) {
651 const int index
= m_pendingIndexes
.takeFirst();
652 const KFileItem item
= m_model
->fileItem(index
);
654 if (m_finishedItems
.contains(item
)) {
658 applyResolvedRoles(index
, ResolveAll
);
659 m_finishedItems
.insert(item
);
660 m_changedItems
.remove(item
);
664 if (!m_pendingIndexes
.isEmpty()) {
665 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
669 if (m_clearPreviews
) {
670 // Only go through the list if there are items which might still have previews.
671 if (m_finishedItems
.count() != m_model
->count()) {
672 QHash
<QByteArray
, QVariant
> data
;
673 data
.insert("iconPixmap", QPixmap());
675 disconnect(m_model
, &KFileItemModel::itemsChanged
,
676 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
677 for (int index
= 0; index
<= m_model
->count(); ++index
) {
678 if (m_model
->data(index
).contains("iconPixmap")) {
679 m_model
->setData(index
, data
);
682 connect(m_model
, &KFileItemModel::itemsChanged
,
683 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
686 m_clearPreviews
= false;
689 if (!m_changedItems
.isEmpty()) {
690 updateChangedItems();
695 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
697 m_changedItems
+= m_recentlyChangedItems
;
698 m_recentlyChangedItems
.clear();
699 updateChangedItems();
702 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& file
)
705 const KFileItem item
= m_model
->fileItem(QUrl::fromLocalFile(file
));
708 // itemUrl is not in the model anymore, probably because
709 // the corresponding file has been deleted in the meantime.
712 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
)
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("size", count
);
764 if (getIsExpandableRole
) {
765 data
.insert("isExpandable", count
> 0);
768 disconnect(m_model
, &KFileItemModel::itemsChanged
,
769 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
770 m_model
->setData(index
, data
);
771 connect(m_model
, &KFileItemModel::itemsChanged
,
772 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
777 void KFileItemModelRolesUpdater::startUpdating()
779 if (m_state
== Paused
) {
783 if (m_finishedItems
.count() == m_model
->count()) {
784 // All roles have been resolved already.
789 // Terminate all updates that are currently active.
791 m_pendingIndexes
.clear();
796 // Determine the icons for the visible items synchronously.
797 updateVisibleIcons();
799 // A detailed update of the items in and near the visible area
800 // only makes sense if sorting is finished.
801 if (m_state
== ResolvingSortRole
) {
805 // Start the preview job or the asynchronous resolving of all roles.
806 QList
<int> indexes
= indexesToResolve();
808 if (m_previewShown
) {
809 m_pendingPreviewItems
.clear();
810 m_pendingPreviewItems
.reserve(indexes
.count());
812 foreach (int index
, indexes
) {
813 const KFileItem item
= m_model
->fileItem(index
);
814 if (!m_finishedItems
.contains(item
)) {
815 m_pendingPreviewItems
.append(item
);
821 m_pendingIndexes
= indexes
;
822 // Trigger the asynchronous resolving of all roles.
823 m_state
= ResolvingAllRoles
;
824 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
828 void KFileItemModelRolesUpdater::updateVisibleIcons()
830 int lastVisibleIndex
= m_lastVisibleIndex
;
831 if (lastVisibleIndex
<= 0) {
832 // Guess a reasonable value for the last visible index if the view
833 // has not told us about the real value yet.
834 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
835 if (lastVisibleIndex
<= 0) {
836 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
843 // Try to determine the final icons for all visible items.
845 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
846 applyResolvedRoles(index
, ResolveFast
);
849 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
850 // preliminary icons (i.e., without mime type determination) for the
854 void KFileItemModelRolesUpdater::startPreviewJob()
856 m_state
= PreviewJobRunning
;
858 if (m_pendingPreviewItems
.isEmpty()) {
859 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
863 // PreviewJob internally caches items always with the size of
864 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
865 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
866 // do a downscaling anyhow because of the frame, so in this case only the provided
867 // cache sizes are requested.
868 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
869 ? QSize(256, 256) : QSize(128, 128);
871 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
872 // worst case) might block the application for several seconds. To prevent such
873 // a blocking, we only pass items with known mime type to the preview job.
874 const int count
= m_pendingPreviewItems
.count();
875 KFileItemList itemSubSet
;
876 itemSubSet
.reserve(count
);
878 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
879 // Some mime types are known already, probably because they were
880 // determined when loading the icons for the visible items. Start
881 // a preview job for all items at the beginning of the list which
882 // have a known mime type.
884 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
885 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
887 // Determine mime types for MaxBlockTimeout ms, and start a preview
888 // job for the corresponding items.
893 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
894 item
.determineMimeType();
895 itemSubSet
.append(item
);
896 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
899 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
901 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
902 if (job
->uiDelegate()) {
903 KJobWidgets::setWindow(job
, qApp
->activeWindow());
906 connect(job
, &KIO::PreviewJob::gotPreview
,
907 this, &KFileItemModelRolesUpdater::slotGotPreview
);
908 connect(job
, &KIO::PreviewJob::failed
,
909 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
910 connect(job
, &KIO::PreviewJob::finished
,
911 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
916 void KFileItemModelRolesUpdater::updateChangedItems()
918 if (m_state
== Paused
) {
922 if (m_changedItems
.isEmpty()) {
926 m_finishedItems
-= m_changedItems
;
928 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
929 m_pendingSortRoleItems
+= m_changedItems
;
931 if (m_state
!= ResolvingSortRole
) {
932 // Stop the preview job if necessary, and trigger the
933 // asynchronous determination of the sort role.
935 m_state
= ResolvingSortRole
;
936 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
942 QList
<int> visibleChangedIndexes
;
943 QList
<int> invisibleChangedIndexes
;
945 foreach (const KFileItem
& item
, m_changedItems
) {
946 const int index
= m_model
->index(item
);
949 m_changedItems
.remove(item
);
953 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
954 visibleChangedIndexes
.append(index
);
956 invisibleChangedIndexes
.append(index
);
960 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
962 if (m_previewShown
) {
963 foreach (int index
, visibleChangedIndexes
) {
964 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
967 foreach (int index
, invisibleChangedIndexes
) {
968 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
975 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
976 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
977 if (!resolvingInProgress
) {
978 // Trigger the asynchronous resolving of the changed roles.
979 m_state
= ResolvingAllRoles
;
980 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
985 void KFileItemModelRolesUpdater::applySortRole(int index
)
987 QHash
<QByteArray
, QVariant
> data
;
988 const KFileItem item
= m_model
->fileItem(index
);
990 if (m_model
->sortRole() == "type") {
991 if (!item
.isMimeTypeKnown()) {
992 item
.determineMimeType();
995 data
.insert("type", item
.mimeComment());
996 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
997 const QString path
= item
.localPath();
998 data
.insert("size", m_directoryContentsCounter
->countDirectoryContentsSynchronously(path
));
1000 // Probably the sort role is a baloo role - just determine all roles.
1001 data
= rolesData(item
);
1004 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1005 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1006 m_model
->setData(index
, data
);
1007 connect(m_model
, &KFileItemModel::itemsChanged
,
1008 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1011 void KFileItemModelRolesUpdater::applySortProgressToModel()
1013 // Inform the model about the progress of the resolved items,
1014 // so that it can give an indication when the sorting has been finished.
1015 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1016 m_model
->emitSortProgress(resolvedCount
);
1019 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index
, ResolveHint hint
)
1021 const KFileItem item
= m_model
->fileItem(index
);
1022 const bool resolveAll
= (hint
== ResolveAll
);
1024 bool iconChanged
= false;
1025 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1026 item
.determineMimeType();
1028 } else if (!m_model
->data(index
).contains("iconName")) {
1032 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1037 QHash
<QByteArray
, QVariant
> data
;
1039 data
= rolesData(item
);
1042 data
.insert("iconName", item
.iconName());
1044 if (m_clearPreviews
) {
1045 data
.insert("iconPixmap", QPixmap());
1048 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1049 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1050 m_model
->setData(index
, data
);
1051 connect(m_model
, &KFileItemModel::itemsChanged
,
1052 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1059 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
)
1061 QHash
<QByteArray
, QVariant
> data
;
1063 const bool getSizeRole
= m_roles
.contains("size");
1064 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1066 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1067 if (item
.isLocalFile()) {
1068 // Tell m_directoryContentsCounter that we want to count the items
1069 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1070 const QString path
= item
.localPath();
1071 m_directoryContentsCounter
->addDirectory(path
);
1072 } else if (getSizeRole
) {
1073 data
.insert("size", -1); // -1 indicates an unknown number of items
1077 if (m_roles
.contains("type")) {
1078 data
.insert("type", item
.mimeComment());
1081 QStringList overlays
= item
.overlays();
1082 foreach(KOverlayIconPlugin
*it
, m_overlayIconsPlugin
) {
1083 overlays
.append(it
->getOverlays(item
.url()));
1085 data
.insert("iconOverlays", overlays
);
1088 if (m_balooFileMonitor
) {
1089 m_balooFileMonitor
->addFile(item
.localPath());
1090 applyChangedBalooRolesForItem(item
);
1096 void KFileItemModelRolesUpdater::slotOverlaysChanged(const QUrl
& url
, const QStringList
&)
1098 const KFileItem item
= m_model
->fileItem(url
);
1099 if (item
.isNull()) {
1102 const int index
= m_model
->index(item
);
1103 QHash
<QByteArray
, QVariant
> data
= m_model
->data(index
);
1104 QStringList overlays
= item
.overlays();
1105 foreach (KOverlayIconPlugin
*it
, m_overlayIconsPlugin
) {
1106 overlays
.append(it
->getOverlays(url
));
1108 data
.insert("iconOverlays", overlays
);
1109 m_model
->setData(index
, data
);
1112 void KFileItemModelRolesUpdater::updateAllPreviews()
1114 if (m_state
== Paused
) {
1115 m_previewChangedDuringPausing
= true;
1117 m_finishedItems
.clear();
1122 void KFileItemModelRolesUpdater::killPreviewJob()
1125 disconnect(m_previewJob
, &KIO::PreviewJob::gotPreview
,
1126 this, &KFileItemModelRolesUpdater::slotGotPreview
);
1127 disconnect(m_previewJob
, &KIO::PreviewJob::failed
,
1128 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
1129 disconnect(m_previewJob
, &KIO::PreviewJob::finished
,
1130 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
1131 m_previewJob
->kill();
1132 m_previewJob
= nullptr;
1133 m_pendingPreviewItems
.clear();
1137 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1139 const int count
= m_model
->count();
1142 result
.reserve(ResolveAllItemsLimit
);
1144 // Add visible items.
1145 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1149 // We need a reasonable upper limit for number of items to resolve after
1150 // and before the visible range. m_maximumVisibleItems can be quite large
1151 // when using Compace View.
1152 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1154 // Add items after the visible range.
1155 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1156 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1160 // Add items before the visible range in reverse order.
1161 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1162 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1166 // Add items on the last page.
1167 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1168 for (int i
= beginLastPage
; i
< count
; ++i
) {
1172 // Add items on the first page.
1173 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1174 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1178 // Continue adding items until ResolveAllItemsLimit is reached.
1179 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1181 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1186 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {