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"
25 #include <KConfigGroup>
26 #include <KSharedConfig>
28 #include <KIconLoader>
29 #include <KJobWidgets>
30 #include <KIO/JobUiDelegate>
31 #include <KIO/PreviewJob>
32 #include <KPluginLoader>
33 #include <KOverlayIconPlugin>
35 #include "private/kpixmapmodifier.h"
36 #include "private/kdirectorycontentscounter.h"
38 #include <QApplication>
41 #include <QElapsedTimer>
47 #include "private/kbaloorolesprovider.h"
49 #include <Baloo/FileMonitor>
53 // #define KFILEITEMMODELROLESUPDATER_DEBUG
56 // Maximum time in ms that the KFileItemModelRolesUpdater
57 // may perform a blocking operation
58 const int MaxBlockTimeout
= 200;
60 // If the number of items is smaller than ResolveAllItemsLimit,
61 // the roles of all items will be resolved.
62 const int ResolveAllItemsLimit
= 500;
64 // Not only the visible area, but up to ReadAheadPages before and after
65 // this area will be resolved.
66 const int ReadAheadPages
= 5;
69 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
72 m_previewChangedDuringPausing(false),
73 m_iconSizeChangedDuringPausing(false),
74 m_rolesChangedDuringPausing(false),
75 m_previewShown(false),
76 m_enlargeSmallPreviews(true),
77 m_clearPreviews(false),
81 m_firstVisibleIndex(0),
82 m_lastVisibleIndex(-1),
83 m_maximumVisibleItems(50),
87 m_pendingSortRoleItems(),
89 m_pendingPreviewItems(),
91 m_recentlyChangedItemsTimer(0),
92 m_recentlyChangedItems(),
94 m_directoryContentsCounter(0)
96 , m_balooFileMonitor(0)
101 const KConfigGroup
globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
102 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList());
103 if (m_enabledPlugins
.isEmpty()) {
104 m_enabledPlugins
= KIO::PreviewJob::defaultPlugins();
107 connect(m_model
, &KFileItemModel::itemsInserted
,
108 this, &KFileItemModelRolesUpdater::slotItemsInserted
);
109 connect(m_model
, &KFileItemModel::itemsRemoved
,
110 this, &KFileItemModelRolesUpdater::slotItemsRemoved
);
111 connect(m_model
, &KFileItemModel::itemsChanged
,
112 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
113 connect(m_model
, &KFileItemModel::itemsMoved
,
114 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
115 connect(m_model
, &KFileItemModel::sortRoleChanged
,
116 this, &KFileItemModelRolesUpdater::slotSortRoleChanged
);
118 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
119 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
120 m_recentlyChangedItemsTimer
= new QTimer(this);
121 m_recentlyChangedItemsTimer
->setInterval(1000);
122 m_recentlyChangedItemsTimer
->setSingleShot(true);
123 connect(m_recentlyChangedItemsTimer
, &QTimer::timeout
, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems
);
125 m_resolvableRoles
.insert("size");
126 m_resolvableRoles
.insert("type");
127 m_resolvableRoles
.insert("isExpandable");
129 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
132 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
133 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
134 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
136 auto plugins
= KPluginLoader::instantiatePlugins(QStringLiteral("kf5/overlayicon"), nullptr, qApp
);
137 foreach (QObject
*it
, plugins
) {
138 auto plugin
= qobject_cast
<KOverlayIconPlugin
*>(it
);
140 m_overlayIconsPlugin
.append(plugin
);
141 connect(plugin
, &KOverlayIconPlugin::overlaysChanged
, this, &KFileItemModelRolesUpdater::slotOverlaysChanged
);
143 // not our/valid plugin, so delete the created object
149 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
154 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
156 if (size
!= m_iconSize
) {
158 if (m_state
== Paused
) {
159 m_iconSizeChangedDuringPausing
= true;
160 } else if (m_previewShown
) {
161 // An icon size change requires the regenerating of
163 m_finishedItems
.clear();
169 QSize
KFileItemModelRolesUpdater::iconSize() const
174 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
183 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
184 // The range has not been changed
188 m_firstVisibleIndex
= index
;
189 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
194 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
196 m_maximumVisibleItems
= count
;
199 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
201 if (show
== m_previewShown
) {
205 m_previewShown
= show
;
207 m_clearPreviews
= true;
213 bool KFileItemModelRolesUpdater::previewsShown() const
215 return m_previewShown
;
218 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
220 if (enlarge
!= m_enlargeSmallPreviews
) {
221 m_enlargeSmallPreviews
= enlarge
;
222 if (m_previewShown
) {
228 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
230 return m_enlargeSmallPreviews
;
233 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
235 if (m_enabledPlugins
!= list
) {
236 m_enabledPlugins
= list
;
237 if (m_previewShown
) {
243 void KFileItemModelRolesUpdater::setPaused(bool paused
)
245 if (paused
== (m_state
== Paused
)) {
253 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
254 m_previewChangedDuringPausing
;
255 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
257 m_finishedItems
.clear();
260 m_iconSizeChangedDuringPausing
= false;
261 m_previewChangedDuringPausing
= false;
262 m_rolesChangedDuringPausing
= false;
264 if (!m_pendingSortRoleItems
.isEmpty()) {
265 m_state
= ResolvingSortRole
;
266 resolveNextSortRole();
275 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
277 if (m_roles
!= roles
) {
281 // Check whether there is at least one role that must be resolved
282 // with the help of Baloo. If this is the case, a (quite expensive)
283 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
284 // the role gets watched for changes.
285 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
286 bool hasBalooRole
= false;
287 QSetIterator
<QByteArray
> it(roles
);
288 while (it
.hasNext()) {
289 const QByteArray
& role
= it
.next();
290 if (rolesProvider
.roles().contains(role
)) {
296 if (hasBalooRole
&& m_balooConfig
.fileIndexingEnabled() && !m_balooFileMonitor
) {
297 m_balooFileMonitor
= new Baloo::FileMonitor(this);
298 connect(m_balooFileMonitor
, &Baloo::FileMonitor::fileMetaDataChanged
,
299 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles
);
300 } else if (!hasBalooRole
&& m_balooFileMonitor
) {
301 delete m_balooFileMonitor
;
302 m_balooFileMonitor
= 0;
306 if (m_state
== Paused
) {
307 m_rolesChangedDuringPausing
= true;
314 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
319 bool KFileItemModelRolesUpdater::isPaused() const
321 return m_state
== Paused
;
324 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
326 return m_enabledPlugins
;
329 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
334 // Determine the sort role synchronously for as many items as possible.
335 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
336 int insertedCount
= 0;
337 foreach (const KItemRange
& range
, itemRanges
) {
338 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
339 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
340 if (timer
.elapsed() < MaxBlockTimeout
) {
343 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
346 insertedCount
+= range
.count
;
349 applySortProgressToModel();
351 // If there are still items whose sort role is unknown, check if the
352 // asynchronous determination of the sort role is already in progress,
353 // and start it if that is not the case.
354 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
356 m_state
= ResolvingSortRole
;
357 resolveNextSortRole();
364 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
366 Q_UNUSED(itemRanges
);
368 const bool allItemsRemoved
= (m_model
->count() == 0);
371 if (m_balooFileMonitor
) {
372 // Don't let the FileWatcher watch for removed items
373 if (allItemsRemoved
) {
374 m_balooFileMonitor
->clear();
376 QStringList newFileList
;
377 foreach (const QString
& file
, m_balooFileMonitor
->files()) {
378 if (m_model
->index(QUrl::fromLocalFile(file
)) >= 0) {
379 newFileList
.append(file
);
382 m_balooFileMonitor
->setFiles(newFileList
);
387 if (allItemsRemoved
) {
390 m_finishedItems
.clear();
391 m_pendingSortRoleItems
.clear();
392 m_pendingIndexes
.clear();
393 m_pendingPreviewItems
.clear();
394 m_recentlyChangedItems
.clear();
395 m_recentlyChangedItemsTimer
->stop();
396 m_changedItems
.clear();
400 // Only remove the items from m_finishedItems. They will be removed
401 // from the other sets later on.
402 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
403 while (it
!= m_finishedItems
.end()) {
404 if (m_model
->index(*it
) < 0) {
405 it
= m_finishedItems
.erase(it
);
411 // The visible items might have changed.
416 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
419 Q_UNUSED(movedToIndexes
);
421 // The visible items might have changed.
425 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
426 const QSet
<QByteArray
>& roles
)
430 // Find out if slotItemsChanged() has been done recently. If that is the
431 // case, resolving the roles is postponed until a timer has exceeded
432 // to prevent expensive repeated updates if files are updated frequently.
433 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
435 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
437 foreach (const KItemRange
& itemRange
, itemRanges
) {
438 int index
= itemRange
.index
;
439 for (int count
= itemRange
.count
; count
> 0; --count
) {
440 const KFileItem item
= m_model
->fileItem(index
);
441 targetSet
.insert(item
);
446 m_recentlyChangedItemsTimer
->start();
448 if (!itemsChangedRecently
) {
449 updateChangedItems();
453 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
454 const QByteArray
& previous
)
459 if (m_resolvableRoles
.contains(current
)) {
460 m_pendingSortRoleItems
.clear();
461 m_finishedItems
.clear();
463 const int count
= m_model
->count();
467 // Determine the sort role synchronously for as many items as possible.
468 for (int index
= 0; index
< count
; ++index
) {
469 if (timer
.elapsed() < MaxBlockTimeout
) {
470 applySortRole(index
);
472 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
476 applySortProgressToModel();
478 if (!m_pendingSortRoleItems
.isEmpty()) {
479 // Trigger the asynchronous determination of the sort role.
481 m_state
= ResolvingSortRole
;
482 resolveNextSortRole();
486 m_pendingSortRoleItems
.clear();
487 applySortProgressToModel();
491 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
493 if (m_state
!= PreviewJobRunning
) {
497 m_changedItems
.remove(item
);
499 const int index
= m_model
->index(item
);
504 QPixmap scaledPixmap
= pixmap
;
506 const QString mimeType
= item
.mimetype();
507 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
508 const bool isFontPreview
= mimeType
.right(slashIndex
).contains(QLatin1String("font"));
509 const bool isFolderPreview
= item
.isDir();
510 const bool isWindowsExePreview
= mimeType
== QLatin1String("application/x-ms-dos-executable") ||
511 mimeType
== QLatin1String("application/x-msdownload");
513 if (!isFolderPreview
&& !isFontPreview
&& !isWindowsExePreview
) {
514 if (m_enlargeSmallPreviews
) {
515 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
517 // Assure that small previews don't get enlarged. Instead they
518 // should be shown centered within the frame.
519 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
520 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
521 scaledPixmap
.height() < contentSize
.height();
522 if (enlargingRequired
) {
523 QSize frameSize
= scaledPixmap
.size() / scaledPixmap
.devicePixelRatio();
524 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
526 QPixmap
largeFrame(frameSize
);
527 largeFrame
.fill(Qt::transparent
);
529 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
531 QPainter
painter(&largeFrame
);
532 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width() / scaledPixmap
.devicePixelRatio()) / 2,
533 (largeFrame
.height() - scaledPixmap
.height() / scaledPixmap
.devicePixelRatio()) / 2,
535 scaledPixmap
= largeFrame
;
537 // The image must be shrinked as it is too large to fit into
538 // the available icon size
539 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
543 KPixmapModifier::scale(scaledPixmap
, m_iconSize
);
546 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
548 const QStringList overlays
= data
["iconOverlays"].toStringList();
549 // Strangely KFileItem::overlays() returns empty string-values, so
550 // we need to check first whether an overlay must be drawn at all.
551 // It is more efficient to do it here, as KIconLoader::drawOverlays()
552 // assumes that an overlay will be drawn and has some additional
554 foreach (const QString
& overlay
, overlays
) {
555 if (!overlay
.isEmpty()) {
556 // There is at least one overlay, draw all overlays above m_pixmap
557 // and cancel the check
558 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
563 data
.insert("iconPixmap", scaledPixmap
);
565 disconnect(m_model
, &KFileItemModel::itemsChanged
,
566 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
567 m_model
->setData(index
, data
);
568 connect(m_model
, &KFileItemModel::itemsChanged
,
569 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
571 m_finishedItems
.insert(item
);
574 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
576 if (m_state
!= PreviewJobRunning
) {
580 m_changedItems
.remove(item
);
582 const int index
= m_model
->index(item
);
584 QHash
<QByteArray
, QVariant
> data
;
585 data
.insert("iconPixmap", QPixmap());
587 disconnect(m_model
, &KFileItemModel::itemsChanged
,
588 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
589 m_model
->setData(index
, data
);
590 connect(m_model
, &KFileItemModel::itemsChanged
,
591 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
593 applyResolvedRoles(index
, ResolveAll
);
594 m_finishedItems
.insert(item
);
598 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
602 if (m_state
!= PreviewJobRunning
) {
608 if (!m_pendingPreviewItems
.isEmpty()) {
611 if (!m_changedItems
.isEmpty()) {
612 updateChangedItems();
617 void KFileItemModelRolesUpdater::resolveNextSortRole()
619 if (m_state
!= ResolvingSortRole
) {
623 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
624 while (it
!= m_pendingSortRoleItems
.end()) {
625 const KFileItem item
= *it
;
626 const int index
= m_model
->index(item
);
628 // Continue if the sort role has already been determined for the
629 // item, and the item has not been changed recently.
630 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
631 it
= m_pendingSortRoleItems
.erase(it
);
635 applySortRole(index
);
636 m_pendingSortRoleItems
.erase(it
);
640 if (!m_pendingSortRoleItems
.isEmpty()) {
641 applySortProgressToModel();
642 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextSortRole
);
646 // Prevent that we try to update the items twice.
647 disconnect(m_model
, &KFileItemModel::itemsMoved
,
648 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
649 applySortProgressToModel();
650 connect(m_model
, &KFileItemModel::itemsMoved
,
651 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
656 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
658 if (m_state
!= ResolvingAllRoles
) {
662 while (!m_pendingIndexes
.isEmpty()) {
663 const int index
= m_pendingIndexes
.takeFirst();
664 const KFileItem item
= m_model
->fileItem(index
);
666 if (m_finishedItems
.contains(item
)) {
670 applyResolvedRoles(index
, ResolveAll
);
671 m_finishedItems
.insert(item
);
672 m_changedItems
.remove(item
);
676 if (!m_pendingIndexes
.isEmpty()) {
677 QTimer::singleShot(0, this, &KFileItemModelRolesUpdater::resolveNextPendingRoles
);
681 if (m_clearPreviews
) {
682 // Only go through the list if there are items which might still have previews.
683 if (m_finishedItems
.count() != m_model
->count()) {
684 QHash
<QByteArray
, QVariant
> data
;
685 data
.insert("iconPixmap", QPixmap());
687 disconnect(m_model
, &KFileItemModel::itemsChanged
,
688 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
689 for (int index
= 0; index
<= m_model
->count(); ++index
) {
690 if (m_model
->data(index
).contains("iconPixmap")) {
691 m_model
->setData(index
, data
);
694 connect(m_model
, &KFileItemModel::itemsChanged
,
695 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
698 m_clearPreviews
= false;
701 if (!m_changedItems
.isEmpty()) {
702 updateChangedItems();
707 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
709 m_changedItems
+= m_recentlyChangedItems
;
710 m_recentlyChangedItems
.clear();
711 updateChangedItems();
714 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& file
)
717 const KFileItem item
= m_model
->fileItem(QUrl::fromLocalFile(file
));
720 // itemUrl is not in the model anymore, probably because
721 // the corresponding file has been deleted in the meantime.
724 applyChangedBalooRolesForItem(item
);
728 void KFileItemModelRolesUpdater::applyChangedBalooRolesForItem(const KFileItem
&item
)
731 Baloo::File
file(item
.localPath());
734 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
735 QHash
<QByteArray
, QVariant
> data
;
737 foreach (const QByteArray
& role
, rolesProvider
.roles()) {
738 // Overwrite all the role values with an empty QVariant, because the roles
739 // provider doesn't overwrite it when the property value list is empty.
741 data
.insert(role
, QVariant());
744 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(file
, m_roles
));
745 while (it
.hasNext()) {
747 data
.insert(it
.key(), it
.value());
750 disconnect(m_model
, &KFileItemModel::itemsChanged
,
751 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
752 const int index
= m_model
->index(item
);
753 m_model
->setData(index
, data
);
754 connect(m_model
, &KFileItemModel::itemsChanged
,
755 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
763 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString
& path
, int count
)
765 const bool getSizeRole
= m_roles
.contains("size");
766 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
768 if (getSizeRole
|| getIsExpandableRole
) {
769 const int index
= m_model
->index(QUrl::fromLocalFile(path
));
771 QHash
<QByteArray
, QVariant
> data
;
774 data
.insert("size", count
);
776 if (getIsExpandableRole
) {
777 data
.insert("isExpandable", count
> 0);
780 disconnect(m_model
, &KFileItemModel::itemsChanged
,
781 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
782 m_model
->setData(index
, data
);
783 connect(m_model
, &KFileItemModel::itemsChanged
,
784 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
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());
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 data
.insert("size", m_directoryContentsCounter
->countDirectoryContentsSynchronously(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
->addDirectory(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();
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 Compace 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
) {