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>
33 #include "private/kpixmapmodifier.h"
34 #include "private/kdirectorycontentscounter.h"
36 #include <QApplication>
39 #include <QElapsedTimer>
45 #include "private/kbaloorolesprovider.h"
47 #include <Baloo/FileMonitor>
50 // #define KFILEITEMMODELROLESUPDATER_DEBUG
53 // Maximum time in ms that the KFileItemModelRolesUpdater
54 // may perform a blocking operation
55 const int MaxBlockTimeout
= 200;
57 // If the number of items is smaller than ResolveAllItemsLimit,
58 // the roles of all items will be resolved.
59 const int ResolveAllItemsLimit
= 500;
61 // Not only the visible area, but up to ReadAheadPages before and after
62 // this area will be resolved.
63 const int ReadAheadPages
= 5;
66 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
69 m_previewChangedDuringPausing(false),
70 m_iconSizeChangedDuringPausing(false),
71 m_rolesChangedDuringPausing(false),
72 m_previewShown(false),
73 m_enlargeSmallPreviews(true),
74 m_clearPreviews(false),
78 m_firstVisibleIndex(0),
79 m_lastVisibleIndex(-1),
80 m_maximumVisibleItems(50),
84 m_pendingSortRoleItems(),
86 m_pendingPreviewItems(),
88 m_recentlyChangedItemsTimer(0),
89 m_recentlyChangedItems(),
91 m_directoryContentsCounter(0)
93 , m_balooFileMonitor(0)
98 const KConfigGroup
globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
99 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList()
100 << "directorythumbnail"
104 connect(m_model
, &KFileItemModel::itemsInserted
,
105 this, &KFileItemModelRolesUpdater::slotItemsInserted
);
106 connect(m_model
, &KFileItemModel::itemsRemoved
,
107 this, &KFileItemModelRolesUpdater::slotItemsRemoved
);
108 connect(m_model
, &KFileItemModel::itemsChanged
,
109 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
110 connect(m_model
, &KFileItemModel::itemsMoved
,
111 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
112 connect(m_model
, &KFileItemModel::sortRoleChanged
,
113 this, &KFileItemModelRolesUpdater::slotSortRoleChanged
);
115 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
116 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
117 m_recentlyChangedItemsTimer
= new QTimer(this);
118 m_recentlyChangedItemsTimer
->setInterval(1000);
119 m_recentlyChangedItemsTimer
->setSingleShot(true);
120 connect(m_recentlyChangedItemsTimer
, &QTimer::timeout
, this, &KFileItemModelRolesUpdater::resolveRecentlyChangedItems
);
122 m_resolvableRoles
.insert("size");
123 m_resolvableRoles
.insert("type");
124 m_resolvableRoles
.insert("isExpandable");
126 m_resolvableRoles
+= KBalooRolesProvider::instance().roles();
129 m_directoryContentsCounter
= new KDirectoryContentsCounter(m_model
, this);
130 connect(m_directoryContentsCounter
, &KDirectoryContentsCounter::result
,
131 this, &KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived
);
134 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
139 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
141 if (size
!= m_iconSize
) {
143 if (m_state
== Paused
) {
144 m_iconSizeChangedDuringPausing
= true;
145 } else if (m_previewShown
) {
146 // An icon size change requires the regenerating of
148 m_finishedItems
.clear();
154 QSize
KFileItemModelRolesUpdater::iconSize() const
159 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
168 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
169 // The range has not been changed
173 m_firstVisibleIndex
= index
;
174 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
179 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
181 m_maximumVisibleItems
= count
;
184 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
186 if (show
== m_previewShown
) {
190 m_previewShown
= show
;
192 m_clearPreviews
= true;
198 bool KFileItemModelRolesUpdater::previewsShown() const
200 return m_previewShown
;
203 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
205 if (enlarge
!= m_enlargeSmallPreviews
) {
206 m_enlargeSmallPreviews
= enlarge
;
207 if (m_previewShown
) {
213 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
215 return m_enlargeSmallPreviews
;
218 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
220 if (m_enabledPlugins
!= list
) {
221 m_enabledPlugins
= list
;
222 if (m_previewShown
) {
228 void KFileItemModelRolesUpdater::setPaused(bool paused
)
230 if (paused
== (m_state
== Paused
)) {
238 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
239 m_previewChangedDuringPausing
;
240 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
242 m_finishedItems
.clear();
245 m_iconSizeChangedDuringPausing
= false;
246 m_previewChangedDuringPausing
= false;
247 m_rolesChangedDuringPausing
= false;
249 if (!m_pendingSortRoleItems
.isEmpty()) {
250 m_state
= ResolvingSortRole
;
251 resolveNextSortRole();
260 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
262 if (m_roles
!= roles
) {
266 // Check whether there is at least one role that must be resolved
267 // with the help of Baloo. If this is the case, a (quite expensive)
268 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
269 // the role gets watched for changes.
270 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
271 bool hasBalooRole
= false;
272 QSetIterator
<QByteArray
> it(roles
);
273 while (it
.hasNext()) {
274 const QByteArray
& role
= it
.next();
275 if (rolesProvider
.roles().contains(role
)) {
281 if (hasBalooRole
&& !m_balooFileMonitor
) {
282 m_balooFileMonitor
= new Baloo::FileMonitor(this);
283 connect(m_balooFileMonitor
, &Baloo::FileMonitor::fileMetaDataChanged
,
284 this, &KFileItemModelRolesUpdater::applyChangedBalooRoles
);
285 } else if (!hasBalooRole
&& m_balooFileMonitor
) {
286 delete m_balooFileMonitor
;
287 m_balooFileMonitor
= 0;
291 if (m_state
== Paused
) {
292 m_rolesChangedDuringPausing
= true;
299 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
304 bool KFileItemModelRolesUpdater::isPaused() const
306 return m_state
== Paused
;
309 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
311 return m_enabledPlugins
;
314 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
319 // Determine the sort role synchronously for as many items as possible.
320 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
321 int insertedCount
= 0;
322 foreach (const KItemRange
& range
, itemRanges
) {
323 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
324 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
325 if (timer
.elapsed() < MaxBlockTimeout
) {
328 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
331 insertedCount
+= range
.count
;
334 applySortProgressToModel();
336 // If there are still items whose sort role is unknown, check if the
337 // asynchronous determination of the sort role is already in progress,
338 // and start it if that is not the case.
339 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
341 m_state
= ResolvingSortRole
;
342 resolveNextSortRole();
349 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
351 Q_UNUSED(itemRanges
);
353 const bool allItemsRemoved
= (m_model
->count() == 0);
356 if (m_balooFileMonitor
) {
357 // Don't let the FileWatcher watch for removed items
358 if (allItemsRemoved
) {
359 m_balooFileMonitor
->clear();
361 QStringList newFileList
;
362 foreach (const QString
& itemUrl
, m_balooFileMonitor
->files()) {
363 if (m_model
->index(itemUrl
) >= 0) {
364 newFileList
.append(itemUrl
);
367 m_balooFileMonitor
->setFiles(newFileList
);
372 if (allItemsRemoved
) {
375 m_finishedItems
.clear();
376 m_pendingSortRoleItems
.clear();
377 m_pendingIndexes
.clear();
378 m_pendingPreviewItems
.clear();
379 m_recentlyChangedItems
.clear();
380 m_recentlyChangedItemsTimer
->stop();
381 m_changedItems
.clear();
385 // Only remove the items from m_finishedItems. They will be removed
386 // from the other sets later on.
387 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
388 while (it
!= m_finishedItems
.end()) {
389 if (m_model
->index(*it
) < 0) {
390 it
= m_finishedItems
.erase(it
);
396 // The visible items might have changed.
401 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
404 Q_UNUSED(movedToIndexes
);
406 // The visible items might have changed.
410 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
411 const QSet
<QByteArray
>& roles
)
415 // Find out if slotItemsChanged() has been done recently. If that is the
416 // case, resolving the roles is postponed until a timer has exceeded
417 // to prevent expensive repeated updates if files are updated frequently.
418 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
420 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
422 foreach (const KItemRange
& itemRange
, itemRanges
) {
423 int index
= itemRange
.index
;
424 for (int count
= itemRange
.count
; count
> 0; --count
) {
425 const KFileItem item
= m_model
->fileItem(index
);
426 targetSet
.insert(item
);
431 m_recentlyChangedItemsTimer
->start();
433 if (!itemsChangedRecently
) {
434 updateChangedItems();
438 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
439 const QByteArray
& previous
)
444 if (m_resolvableRoles
.contains(current
)) {
445 m_pendingSortRoleItems
.clear();
446 m_finishedItems
.clear();
448 const int count
= m_model
->count();
452 // Determine the sort role synchronously for as many items as possible.
453 for (int index
= 0; index
< count
; ++index
) {
454 if (timer
.elapsed() < MaxBlockTimeout
) {
455 applySortRole(index
);
457 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
461 applySortProgressToModel();
463 if (!m_pendingSortRoleItems
.isEmpty()) {
464 // Trigger the asynchronous determination of the sort role.
466 m_state
= ResolvingSortRole
;
467 resolveNextSortRole();
471 m_pendingSortRoleItems
.clear();
472 applySortProgressToModel();
476 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
478 if (m_state
!= PreviewJobRunning
) {
482 m_changedItems
.remove(item
);
484 const int index
= m_model
->index(item
);
489 QPixmap scaledPixmap
= pixmap
;
491 const QString mimeType
= item
.mimetype();
492 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
493 const QString mimeTypeGroup
= mimeType
.left(slashIndex
);
494 if (mimeTypeGroup
== QLatin1String("image")) {
495 if (m_enlargeSmallPreviews
) {
496 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
* scaledPixmap
.devicePixelRatio());
498 // Assure that small previews don't get enlarged. Instead they
499 // should be shown centered within the frame.
500 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
501 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
502 scaledPixmap
.height() < contentSize
.height();
503 if (enlargingRequired
) {
504 QSize frameSize
= scaledPixmap
.size();
505 frameSize
.scale(m_iconSize
* scaledPixmap
.devicePixelRatio(), Qt::KeepAspectRatio
);
507 QPixmap
largeFrame(frameSize
);
508 largeFrame
.fill(Qt::transparent
);
510 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
512 QPainter
painter(&largeFrame
);
513 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width() / scaledPixmap
.devicePixelRatio()) / 2,
514 (largeFrame
.height() - scaledPixmap
.height() / scaledPixmap
.devicePixelRatio()) / 2,
516 scaledPixmap
= largeFrame
;
518 // The image must be shrinked as it is too large to fit into
519 // the available icon size
520 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
* scaledPixmap
.devicePixelRatio());
524 KPixmapModifier::scale(scaledPixmap
, m_iconSize
* scaledPixmap
.devicePixelRatio());
527 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
529 const QStringList overlays
= data
["iconOverlays"].toStringList();
530 // Strangely KFileItem::overlays() returns empty string-values, so
531 // we need to check first whether an overlay must be drawn at all.
532 // It is more efficient to do it here, as KIconLoader::drawOverlays()
533 // assumes that an overlay will be drawn and has some additional
535 foreach (const QString
& overlay
, overlays
) {
536 if (!overlay
.isEmpty()) {
537 // There is at least one overlay, draw all overlays above m_pixmap
538 // and cancel the check
539 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
544 data
.insert("iconPixmap", scaledPixmap
);
546 disconnect(m_model
, &KFileItemModel::itemsChanged
,
547 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
548 m_model
->setData(index
, data
);
549 connect(m_model
, &KFileItemModel::itemsChanged
,
550 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
552 m_finishedItems
.insert(item
);
555 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
557 if (m_state
!= PreviewJobRunning
) {
561 m_changedItems
.remove(item
);
563 const int index
= m_model
->index(item
);
565 QHash
<QByteArray
, QVariant
> data
;
566 data
.insert("iconPixmap", QPixmap());
568 disconnect(m_model
, &KFileItemModel::itemsChanged
,
569 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
570 m_model
->setData(index
, data
);
571 connect(m_model
, &KFileItemModel::itemsChanged
,
572 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
574 applyResolvedRoles(index
, ResolveAll
);
575 m_finishedItems
.insert(item
);
579 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
583 if (m_state
!= PreviewJobRunning
) {
589 if (!m_pendingPreviewItems
.isEmpty()) {
592 if (!m_changedItems
.isEmpty()) {
593 updateChangedItems();
598 void KFileItemModelRolesUpdater::resolveNextSortRole()
600 if (m_state
!= ResolvingSortRole
) {
604 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
605 while (it
!= m_pendingSortRoleItems
.end()) {
606 const KFileItem item
= *it
;
607 const int index
= m_model
->index(item
);
609 // Continue if the sort role has already been determined for the
610 // item, and the item has not been changed recently.
611 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
612 it
= m_pendingSortRoleItems
.erase(it
);
616 applySortRole(index
);
617 m_pendingSortRoleItems
.erase(it
);
621 if (!m_pendingSortRoleItems
.isEmpty()) {
622 applySortProgressToModel();
623 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
627 // Prevent that we try to update the items twice.
628 disconnect(m_model
, &KFileItemModel::itemsMoved
,
629 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
630 applySortProgressToModel();
631 connect(m_model
, &KFileItemModel::itemsMoved
,
632 this, &KFileItemModelRolesUpdater::slotItemsMoved
);
637 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
639 if (m_state
!= ResolvingAllRoles
) {
643 while (!m_pendingIndexes
.isEmpty()) {
644 const int index
= m_pendingIndexes
.takeFirst();
645 const KFileItem item
= m_model
->fileItem(index
);
647 if (m_finishedItems
.contains(item
)) {
651 applyResolvedRoles(index
, ResolveAll
);
652 m_finishedItems
.insert(item
);
653 m_changedItems
.remove(item
);
657 if (!m_pendingIndexes
.isEmpty()) {
658 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
662 if (m_clearPreviews
) {
663 // Only go through the list if there are items which might still have previews.
664 if (m_finishedItems
.count() != m_model
->count()) {
665 QHash
<QByteArray
, QVariant
> data
;
666 data
.insert("iconPixmap", QPixmap());
668 disconnect(m_model
, &KFileItemModel::itemsChanged
,
669 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
670 for (int index
= 0; index
<= m_model
->count(); ++index
) {
671 if (m_model
->data(index
).contains("iconPixmap")) {
672 m_model
->setData(index
, data
);
675 connect(m_model
, &KFileItemModel::itemsChanged
,
676 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
679 m_clearPreviews
= false;
682 if (!m_changedItems
.isEmpty()) {
683 updateChangedItems();
688 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
690 m_changedItems
+= m_recentlyChangedItems
;
691 m_recentlyChangedItems
.clear();
692 updateChangedItems();
695 void KFileItemModelRolesUpdater::applyChangedBalooRoles(const QString
& itemUrl
)
698 const KFileItem item
= m_model
->fileItem(itemUrl
);
701 // itemUrl is not in the model anymore, probably because
702 // the corresponding file has been deleted in the meantime.
706 Baloo::File
file(item
.localPath());
709 const KBalooRolesProvider
& rolesProvider
= KBalooRolesProvider::instance();
710 QHash
<QByteArray
, QVariant
> data
;
712 foreach (const QByteArray
& role
, rolesProvider
.roles()) {
713 // Overwrite all the role values with an empty QVariant, because the roles
714 // provider doesn't overwrite it when the property value list is empty.
716 data
.insert(role
, QVariant());
719 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(file
, m_roles
));
720 while (it
.hasNext()) {
722 data
.insert(it
.key(), it
.value());
725 disconnect(m_model
, &KFileItemModel::itemsChanged
,
726 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
727 const int index
= m_model
->index(item
);
728 m_model
->setData(index
, data
);
729 connect(m_model
, &KFileItemModel::itemsChanged
,
730 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
738 void KFileItemModelRolesUpdater::slotDirectoryContentsCountReceived(const QString
& path
, int count
)
740 const bool getSizeRole
= m_roles
.contains("size");
741 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
743 if (getSizeRole
|| getIsExpandableRole
) {
744 const int index
= m_model
->index(QUrl::fromLocalFile(path
));
746 QHash
<QByteArray
, QVariant
> data
;
749 data
.insert("size", count
);
751 if (getIsExpandableRole
) {
752 data
.insert("isExpandable", count
> 0);
755 disconnect(m_model
, &KFileItemModel::itemsChanged
,
756 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
757 m_model
->setData(index
, data
);
758 connect(m_model
, &KFileItemModel::itemsChanged
,
759 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
764 void KFileItemModelRolesUpdater::startUpdating()
766 if (m_state
== Paused
) {
770 if (m_finishedItems
.count() == m_model
->count()) {
771 // All roles have been resolved already.
776 // Terminate all updates that are currently active.
778 m_pendingIndexes
.clear();
783 // Determine the icons for the visible items synchronously.
784 updateVisibleIcons();
786 // A detailed update of the items in and near the visible area
787 // only makes sense if sorting is finished.
788 if (m_state
== ResolvingSortRole
) {
792 // Start the preview job or the asynchronous resolving of all roles.
793 QList
<int> indexes
= indexesToResolve();
795 if (m_previewShown
) {
796 m_pendingPreviewItems
.clear();
797 m_pendingPreviewItems
.reserve(indexes
.count());
799 foreach (int index
, indexes
) {
800 const KFileItem item
= m_model
->fileItem(index
);
801 if (!m_finishedItems
.contains(item
)) {
802 m_pendingPreviewItems
.append(item
);
808 m_pendingIndexes
= indexes
;
809 // Trigger the asynchronous resolving of all roles.
810 m_state
= ResolvingAllRoles
;
811 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
815 void KFileItemModelRolesUpdater::updateVisibleIcons()
817 int lastVisibleIndex
= m_lastVisibleIndex
;
818 if (lastVisibleIndex
<= 0) {
819 // Guess a reasonable value for the last visible index if the view
820 // has not told us about the real value yet.
821 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
822 if (lastVisibleIndex
<= 0) {
823 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
830 // Try to determine the final icons for all visible items.
832 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
833 applyResolvedRoles(index
, ResolveFast
);
836 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
837 // preliminary icons (i.e., without mime type determination) for the
841 void KFileItemModelRolesUpdater::startPreviewJob()
843 m_state
= PreviewJobRunning
;
845 if (m_pendingPreviewItems
.isEmpty()) {
846 QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
850 // PreviewJob internally caches items always with the size of
851 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
852 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
853 // do a downscaling anyhow because of the frame, so in this case only the provided
854 // cache sizes are requested.
855 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
856 ? QSize(256, 256) : QSize(128, 128);
858 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
859 // worst case) might block the application for several seconds. To prevent such
860 // a blocking, we only pass items with known mime type to the preview job.
861 const int count
= m_pendingPreviewItems
.count();
862 KFileItemList itemSubSet
;
863 itemSubSet
.reserve(count
);
865 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
866 // Some mime types are known already, probably because they were
867 // determined when loading the icons for the visible items. Start
868 // a preview job for all items at the beginning of the list which
869 // have a known mime type.
871 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
872 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
874 // Determine mime types for MaxBlockTimeout ms, and start a preview
875 // job for the corresponding items.
880 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
881 item
.determineMimeType();
882 itemSubSet
.append(item
);
883 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
886 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
888 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
890 KJobWidgets::setWindow(job
, qApp
->activeWindow());
893 connect(job
, &KIO::PreviewJob::gotPreview
,
894 this, &KFileItemModelRolesUpdater::slotGotPreview
);
895 connect(job
, &KIO::PreviewJob::failed
,
896 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
897 connect(job
, &KIO::PreviewJob::finished
,
898 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
903 void KFileItemModelRolesUpdater::updateChangedItems()
905 if (m_state
== Paused
) {
909 if (m_changedItems
.isEmpty()) {
913 m_finishedItems
-= m_changedItems
;
915 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
916 m_pendingSortRoleItems
+= m_changedItems
;
918 if (m_state
!= ResolvingSortRole
) {
919 // Stop the preview job if necessary, and trigger the
920 // asynchronous determination of the sort role.
922 m_state
= ResolvingSortRole
;
923 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
929 QList
<int> visibleChangedIndexes
;
930 QList
<int> invisibleChangedIndexes
;
932 foreach (const KFileItem
& item
, m_changedItems
) {
933 const int index
= m_model
->index(item
);
936 m_changedItems
.remove(item
);
940 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
941 visibleChangedIndexes
.append(index
);
943 invisibleChangedIndexes
.append(index
);
947 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
949 if (m_previewShown
) {
950 foreach (int index
, visibleChangedIndexes
) {
951 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
954 foreach (int index
, invisibleChangedIndexes
) {
955 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
962 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
963 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
964 if (!resolvingInProgress
) {
965 // Trigger the asynchronous resolving of the changed roles.
966 m_state
= ResolvingAllRoles
;
967 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
972 void KFileItemModelRolesUpdater::applySortRole(int index
)
974 QHash
<QByteArray
, QVariant
> data
;
975 const KFileItem item
= m_model
->fileItem(index
);
977 if (m_model
->sortRole() == "type") {
978 if (!item
.isMimeTypeKnown()) {
979 item
.determineMimeType();
982 data
.insert("type", item
.mimeComment());
983 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
984 const QString path
= item
.localPath();
985 data
.insert("size", m_directoryContentsCounter
->countDirectoryContentsSynchronously(path
));
987 // Probably the sort role is a baloo role - just determine all roles.
988 data
= rolesData(item
);
991 disconnect(m_model
, &KFileItemModel::itemsChanged
,
992 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
993 m_model
->setData(index
, data
);
994 connect(m_model
, &KFileItemModel::itemsChanged
,
995 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
998 void KFileItemModelRolesUpdater::applySortProgressToModel()
1000 // Inform the model about the progress of the resolved items,
1001 // so that it can give an indication when the sorting has been finished.
1002 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1003 m_model
->emitSortProgress(resolvedCount
);
1006 bool KFileItemModelRolesUpdater::applyResolvedRoles(int index
, ResolveHint hint
)
1008 const KFileItem item
= m_model
->fileItem(index
);
1009 const bool resolveAll
= (hint
== ResolveAll
);
1011 bool iconChanged
= false;
1012 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1013 item
.determineMimeType();
1015 } else if (!m_model
->data(index
).contains("iconName")) {
1019 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1024 QHash
<QByteArray
, QVariant
> data
;
1026 data
= rolesData(item
);
1029 data
.insert("iconName", item
.iconName());
1031 if (m_clearPreviews
) {
1032 data
.insert("iconPixmap", QPixmap());
1035 disconnect(m_model
, &KFileItemModel::itemsChanged
,
1036 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1037 m_model
->setData(index
, data
);
1038 connect(m_model
, &KFileItemModel::itemsChanged
,
1039 this, &KFileItemModelRolesUpdater::slotItemsChanged
);
1046 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
)
1048 QHash
<QByteArray
, QVariant
> data
;
1050 const bool getSizeRole
= m_roles
.contains("size");
1051 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1053 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1054 if (item
.isLocalFile()) {
1055 // Tell m_directoryContentsCounter that we want to count the items
1056 // inside the directory. The result will be received in slotDirectoryContentsCountReceived.
1057 const QString path
= item
.localPath();
1058 m_directoryContentsCounter
->addDirectory(path
);
1059 } else if (getSizeRole
) {
1060 data
.insert("size", -1); // -1 indicates an unknown number of items
1064 if (m_roles
.contains("type")) {
1065 data
.insert("type", item
.mimeComment());
1068 data
.insert("iconOverlays", item
.overlays());
1071 if (m_balooFileMonitor
) {
1072 m_balooFileMonitor
->addFile(item
.localPath());
1073 applyChangedBalooRoles(item
.localPath());
1079 void KFileItemModelRolesUpdater::updateAllPreviews()
1081 if (m_state
== Paused
) {
1082 m_previewChangedDuringPausing
= true;
1084 m_finishedItems
.clear();
1089 void KFileItemModelRolesUpdater::killPreviewJob()
1092 disconnect(m_previewJob
, &KIO::PreviewJob::gotPreview
,
1093 this, &KFileItemModelRolesUpdater::slotGotPreview
);
1094 disconnect(m_previewJob
, &KIO::PreviewJob::failed
,
1095 this, &KFileItemModelRolesUpdater::slotPreviewFailed
);
1096 disconnect(m_previewJob
, &KIO::PreviewJob::finished
,
1097 this, &KFileItemModelRolesUpdater::slotPreviewJobFinished
);
1098 m_previewJob
->kill();
1100 m_pendingPreviewItems
.clear();
1104 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1106 const int count
= m_model
->count();
1109 result
.reserve(ResolveAllItemsLimit
);
1111 // Add visible items.
1112 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1116 // We need a reasonable upper limit for number of items to resolve after
1117 // and before the visible range. m_maximumVisibleItems can be quite large
1118 // when using Compace View.
1119 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1121 // Add items after the visible range.
1122 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1123 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1127 // Add items before the visible range in reverse order.
1128 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1129 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1133 // Add items on the last page.
1134 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1135 for (int i
= beginLastPage
; i
< count
; ++i
) {
1139 // Add items on the first page.
1140 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1141 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1145 // Continue adding items until ResolveAllItemsLimit is reached.
1146 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1148 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1153 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {