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>
30 #include <KIO/JobUiDelegate>
31 #include <KIO/PreviewJob>
33 #include "private/kpixmapmodifier.h"
35 #include <QApplication>
38 #include <QElapsedTimer>
44 #include "private/knepomukrolesprovider.h"
45 #include <Nepomuk2/ResourceWatcher>
46 #include <Nepomuk2/ResourceManager>
49 // Required includes for subItemsCount():
57 // #define KFILEITEMMODELROLESUPDATER_DEBUG
60 // Maximum time in ms that the KFileItemModelRolesUpdater
61 // may perform a blocking operation
62 const int MaxBlockTimeout
= 200;
64 // If the number of items is smaller than ResolveAllItemsLimit,
65 // the roles of all items will be resolved.
66 const int ResolveAllItemsLimit
= 500;
68 // Not only the visible area, but up to ReadAheadPages before and after
69 // this area will be resolved.
70 const int ReadAheadPages
= 5;
73 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
76 m_previewChangedDuringPausing(false),
77 m_iconSizeChangedDuringPausing(false),
78 m_rolesChangedDuringPausing(false),
79 m_previewShown(false),
80 m_enlargeSmallPreviews(true),
81 m_clearPreviews(false),
85 m_firstVisibleIndex(0),
86 m_lastVisibleIndex(-1),
87 m_maximumVisibleItems(50),
91 m_pendingSortRoleItems(),
93 m_pendingPreviewItems(),
95 m_recentlyChangedItemsTimer(0),
96 m_recentlyChangedItems(),
101 , m_nepomukResourceWatcher(0),
107 const KConfigGroup
globalConfig(KGlobal::config(), "PreviewSettings");
108 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList()
109 << "directorythumbnail"
113 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
114 this, SLOT(slotItemsInserted(KItemRangeList
)));
115 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
116 this, SLOT(slotItemsRemoved(KItemRangeList
)));
117 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
118 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
119 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
120 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
121 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
122 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
124 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
125 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
126 m_recentlyChangedItemsTimer
= new QTimer(this);
127 m_recentlyChangedItemsTimer
->setInterval(1000);
128 m_recentlyChangedItemsTimer
->setSingleShot(true);
129 connect(m_recentlyChangedItemsTimer
, SIGNAL(timeout()), this, SLOT(resolveRecentlyChangedItems()));
131 m_resolvableRoles
.insert("size");
132 m_resolvableRoles
.insert("type");
133 m_resolvableRoles
.insert("isExpandable");
135 m_resolvableRoles
+= KNepomukRolesProvider::instance().roles();
138 // When folders are expandable or the item-count is shown for folders, it is necessary
139 // to watch the number of items of the sub-folder to be able to react on changes.
140 m_dirWatcher
= new KDirWatch(this);
141 connect(m_dirWatcher
, SIGNAL(dirty(QString
)), this, SLOT(slotDirWatchDirty(QString
)));
144 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
149 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
151 if (size
!= m_iconSize
) {
153 if (m_state
== Paused
) {
154 m_iconSizeChangedDuringPausing
= true;
155 } else if (m_previewShown
) {
156 // An icon size change requires the regenerating of
158 m_finishedItems
.clear();
164 QSize
KFileItemModelRolesUpdater::iconSize() const
169 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
178 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
179 // The range has not been changed
183 m_firstVisibleIndex
= index
;
184 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
189 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
191 m_maximumVisibleItems
= count
;
194 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
196 if (show
== m_previewShown
) {
200 m_previewShown
= show
;
202 m_clearPreviews
= true;
208 bool KFileItemModelRolesUpdater::previewsShown() const
210 return m_previewShown
;
213 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
215 if (enlarge
!= m_enlargeSmallPreviews
) {
216 m_enlargeSmallPreviews
= enlarge
;
217 if (m_previewShown
) {
223 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
225 return m_enlargeSmallPreviews
;
228 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
230 if (m_enabledPlugins
!= list
) {
231 m_enabledPlugins
= list
;
232 if (m_previewShown
) {
238 void KFileItemModelRolesUpdater::setPaused(bool paused
)
240 if (paused
== (m_state
== Paused
)) {
248 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
249 m_previewChangedDuringPausing
;
250 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
252 m_finishedItems
.clear();
255 m_iconSizeChangedDuringPausing
= false;
256 m_previewChangedDuringPausing
= false;
257 m_rolesChangedDuringPausing
= false;
259 if (!m_pendingSortRoleItems
.isEmpty()) {
260 m_state
= ResolvingSortRole
;
261 resolveNextSortRole();
270 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
272 if (m_roles
!= roles
) {
276 if (Nepomuk2::ResourceManager::instance()->initialized()) {
277 // Check whether there is at least one role that must be resolved
278 // with the help of Nepomuk. If this is the case, a (quite expensive)
279 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
280 // the role gets watched for changes.
281 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
282 bool hasNepomukRole
= false;
283 QSetIterator
<QByteArray
> it(roles
);
284 while (it
.hasNext()) {
285 const QByteArray
& role
= it
.next();
286 if (rolesProvider
.roles().contains(role
)) {
287 hasNepomukRole
= true;
292 if (hasNepomukRole
&& !m_nepomukResourceWatcher
) {
293 Q_ASSERT(m_nepomukUriItems
.isEmpty());
295 m_nepomukResourceWatcher
= new Nepomuk2::ResourceWatcher(this);
296 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariantList
,QVariantList
)),
297 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
,Nepomuk2::Types::Property
)));
298 } else if (!hasNepomukRole
&& m_nepomukResourceWatcher
) {
299 delete m_nepomukResourceWatcher
;
300 m_nepomukResourceWatcher
= 0;
301 m_nepomukUriItems
.clear();
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);
370 if (!m_watchedDirs
.isEmpty()) {
371 // Don't let KDirWatch watch for removed items
372 if (allItemsRemoved
) {
373 foreach (const QString
& path
, m_watchedDirs
) {
374 m_dirWatcher
->removeDir(path
);
376 m_watchedDirs
.clear();
378 QMutableSetIterator
<QString
> it(m_watchedDirs
);
379 while (it
.hasNext()) {
380 const QString
& path
= it
.next();
381 if (m_model
->index(KUrl(path
)) < 0) {
382 m_dirWatcher
->removeDir(path
);
390 if (m_nepomukResourceWatcher
) {
391 // Don't let the ResourceWatcher watch for removed items
392 if (allItemsRemoved
) {
393 m_nepomukResourceWatcher
->setResources(QList
<Nepomuk2::Resource
>());
394 m_nepomukResourceWatcher
->stop();
395 m_nepomukUriItems
.clear();
397 QList
<Nepomuk2::Resource
> newResources
;
398 const QList
<Nepomuk2::Resource
> oldResources
= m_nepomukResourceWatcher
->resources();
399 foreach (const Nepomuk2::Resource
& resource
, oldResources
) {
400 const QUrl uri
= resource
.uri();
401 const KUrl itemUrl
= m_nepomukUriItems
.value(uri
);
402 if (m_model
->index(itemUrl
) >= 0) {
403 newResources
.append(resource
);
405 m_nepomukUriItems
.remove(uri
);
408 m_nepomukResourceWatcher
->setResources(newResources
);
409 if (newResources
.isEmpty()) {
410 Q_ASSERT(m_nepomukUriItems
.isEmpty());
411 m_nepomukResourceWatcher
->stop();
417 if (allItemsRemoved
) {
420 m_finishedItems
.clear();
421 m_pendingSortRoleItems
.clear();
422 m_pendingIndexes
.clear();
423 m_pendingPreviewItems
.clear();
424 m_recentlyChangedItems
.clear();
425 m_recentlyChangedItemsTimer
->stop();
426 m_changedItems
.clear();
430 // Only remove the items from m_finishedItems. They will be removed
431 // from the other sets later on.
432 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
433 while (it
!= m_finishedItems
.end()) {
434 if (m_model
->index(*it
) < 0) {
435 it
= m_finishedItems
.erase(it
);
441 // The visible items might have changed.
446 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
449 Q_UNUSED(movedToIndexes
);
451 // The visible items might have changed.
455 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
456 const QSet
<QByteArray
>& roles
)
460 // Find out if slotItemsChanged() has been done recently. If that is the
461 // case, resolving the roles is postponed until a timer has exceeded
462 // to prevent expensive repeated updates if files are updated frequently.
463 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
465 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
467 foreach (const KItemRange
& itemRange
, itemRanges
) {
468 int index
= itemRange
.index
;
469 for (int count
= itemRange
.count
; count
> 0; --count
) {
470 const KFileItem item
= m_model
->fileItem(index
);
471 targetSet
.insert(item
);
476 m_recentlyChangedItemsTimer
->start();
478 if (!itemsChangedRecently
) {
479 updateChangedItems();
483 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
484 const QByteArray
& previous
)
489 if (m_resolvableRoles
.contains(current
)) {
490 m_pendingSortRoleItems
.clear();
491 m_finishedItems
.clear();
493 const int count
= m_model
->count();
497 // Determine the sort role synchronously for as many items as possible.
498 for (int index
= 0; index
< count
; ++index
) {
499 if (timer
.elapsed() < MaxBlockTimeout
) {
500 applySortRole(index
);
502 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
506 applySortProgressToModel();
508 if (!m_pendingSortRoleItems
.isEmpty()) {
509 // Trigger the asynchronous determination of the sort role.
511 m_state
= ResolvingSortRole
;
512 resolveNextSortRole();
516 m_pendingSortRoleItems
.clear();
517 applySortProgressToModel();
521 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
523 if (m_state
!= PreviewJobRunning
) {
527 m_changedItems
.remove(item
);
529 const int index
= m_model
->index(item
);
534 QPixmap scaledPixmap
= pixmap
;
536 const QString mimeType
= item
.mimetype();
537 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
538 const QString mimeTypeGroup
= mimeType
.left(slashIndex
);
539 if (mimeTypeGroup
== QLatin1String("image")) {
540 if (m_enlargeSmallPreviews
) {
541 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
543 // Assure that small previews don't get enlarged. Instead they
544 // should be shown centered within the frame.
545 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
546 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
547 scaledPixmap
.height() < contentSize
.height();
548 if (enlargingRequired
) {
549 QSize frameSize
= scaledPixmap
.size();
550 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
552 QPixmap
largeFrame(frameSize
);
553 largeFrame
.fill(Qt::transparent
);
555 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
557 QPainter
painter(&largeFrame
);
558 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width()) / 2,
559 (largeFrame
.height() - scaledPixmap
.height()) / 2,
561 scaledPixmap
= largeFrame
;
563 // The image must be shrinked as it is too large to fit into
564 // the available icon size
565 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
569 KPixmapModifier::scale(scaledPixmap
, m_iconSize
);
572 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
573 data
.insert("iconPixmap", scaledPixmap
);
575 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
576 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
577 m_model
->setData(index
, data
);
578 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
579 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
581 m_finishedItems
.insert(item
);
584 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
586 if (m_state
!= PreviewJobRunning
) {
590 m_changedItems
.remove(item
);
592 const int index
= m_model
->index(item
);
594 QHash
<QByteArray
, QVariant
> data
;
595 data
.insert("iconPixmap", QPixmap());
597 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
598 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
599 m_model
->setData(index
, data
);
600 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
601 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
603 applyResolvedRoles(item
, ResolveAll
);
604 m_finishedItems
.insert(item
);
608 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
612 if (m_state
!= PreviewJobRunning
) {
618 if (!m_pendingPreviewItems
.isEmpty()) {
621 if (!m_changedItems
.isEmpty()) {
622 updateChangedItems();
627 void KFileItemModelRolesUpdater::resolveNextSortRole()
629 if (m_state
!= ResolvingSortRole
) {
633 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
634 while (it
!= m_pendingSortRoleItems
.end()) {
635 const KFileItem item
= *it
;
636 const int index
= m_model
->index(item
);
638 // Continue if the sort role has already been determined for the
639 // item, and the item has not been changed recently.
640 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
641 it
= m_pendingSortRoleItems
.erase(it
);
645 applySortRole(index
);
646 m_pendingSortRoleItems
.erase(it
);
650 if (!m_pendingSortRoleItems
.isEmpty()) {
651 applySortProgressToModel();
652 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
656 // Prevent that we try to update the items twice.
657 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
658 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
659 applySortProgressToModel();
660 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
661 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
666 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
668 if (m_state
!= ResolvingAllRoles
) {
672 while (!m_pendingIndexes
.isEmpty()) {
673 const int index
= m_pendingIndexes
.takeFirst();
674 const KFileItem item
= m_model
->fileItem(index
);
676 if (m_finishedItems
.contains(item
)) {
680 applyResolvedRoles(item
, ResolveAll
);
681 m_finishedItems
.insert(item
);
682 m_changedItems
.remove(item
);
686 if (!m_pendingIndexes
.isEmpty()) {
687 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
691 if (m_clearPreviews
) {
692 // Only go through the list if there are items which might still have previews.
693 if (m_finishedItems
.count() != m_model
->count()) {
694 QHash
<QByteArray
, QVariant
> data
;
695 data
.insert("iconPixmap", QPixmap());
697 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
698 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
699 for (int index
= 0; index
<= m_model
->count(); ++index
) {
700 if (m_model
->data(index
).contains("iconPixmap")) {
701 m_model
->setData(index
, data
);
704 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
705 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
708 m_clearPreviews
= false;
711 if (!m_changedItems
.isEmpty()) {
712 updateChangedItems();
717 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
719 m_changedItems
+= m_recentlyChangedItems
;
720 m_recentlyChangedItems
.clear();
721 updateChangedItems();
724 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource
& resource
, const Nepomuk2::Types::Property
& property
)
727 if (!Nepomuk2::ResourceManager::instance()->initialized()) {
731 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.uri());
732 const KFileItem item
= m_model
->fileItem(itemUrl
);
735 // itemUrl is not in the model anymore, probably because
736 // the corresponding file has been deleted in the meantime.
740 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
742 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
743 const QByteArray role
= rolesProvider
.roleForPropertyUri(property
.uri());
744 if (!role
.isEmpty() && m_roles
.contains(role
)) {
745 // Overwrite the changed role value with an empty QVariant, because the roles
746 // provider doesn't overwrite it when the property value list is empty.
748 data
.insert(role
, QVariant());
751 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
752 while (it
.hasNext()) {
754 data
.insert(it
.key(), it
.value());
757 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
758 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
759 const int index
= m_model
->index(item
);
760 m_model
->setData(index
, data
);
761 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
762 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
770 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
772 const bool getSizeRole
= m_roles
.contains("size");
773 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
775 if (getSizeRole
|| getIsExpandableRole
) {
776 const int index
= m_model
->index(KUrl(path
));
778 if (!m_model
->fileItem(index
).isDir()) {
779 // If INotify is used, KDirWatch issues the dirty() signal
780 // also for changed files inside the directory, even if we
781 // don't enable this behavior explicitly (see bug 309740).
785 QHash
<QByteArray
, QVariant
> data
;
787 const int count
= subItemsCount(path
);
789 data
.insert("size", count
);
791 if (getIsExpandableRole
) {
792 data
.insert("isExpandable", count
> 0);
795 // Note that we do not block the itemsChanged signal here.
796 // This ensures that a new preview will be generated.
797 m_model
->setData(index
, data
);
802 void KFileItemModelRolesUpdater::startUpdating()
804 if (m_state
== Paused
) {
808 if (m_finishedItems
.count() == m_model
->count()) {
809 // All roles have been resolved already.
814 // Terminate all updates that are currently active.
816 m_pendingIndexes
.clear();
821 // Determine the icons for the visible items synchronously.
822 updateVisibleIcons();
824 // A detailed update of the items in and near the visible area
825 // only makes sense if sorting is finished.
826 if (m_state
== ResolvingSortRole
) {
830 // Start the preview job or the asynchronous resolving of all roles.
831 QList
<int> indexes
= indexesToResolve();
833 if (m_previewShown
) {
834 m_pendingPreviewItems
.clear();
835 m_pendingPreviewItems
.reserve(indexes
.count());
837 foreach (int index
, indexes
) {
838 const KFileItem item
= m_model
->fileItem(index
);
839 if (!m_finishedItems
.contains(item
)) {
840 m_pendingPreviewItems
.append(item
);
846 m_pendingIndexes
= indexes
;
847 // Trigger the asynchronous resolving of all roles.
848 m_state
= ResolvingAllRoles
;
849 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
853 void KFileItemModelRolesUpdater::updateVisibleIcons()
855 int lastVisibleIndex
= m_lastVisibleIndex
;
856 if (lastVisibleIndex
<= 0) {
857 // Guess a reasonable value for the last visible index if the view
858 // has not told us about the real value yet.
859 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
860 if (lastVisibleIndex
<= 0) {
861 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
868 // Try to determine the final icons for all visible items.
870 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
871 const KFileItem item
= m_model
->fileItem(index
);
872 applyResolvedRoles(item
, ResolveFast
);
875 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
876 // preliminary icons (i.e., without mime type determination) for the
880 void KFileItemModelRolesUpdater::startPreviewJob()
882 m_state
= PreviewJobRunning
;
884 if (m_pendingPreviewItems
.isEmpty()) {
885 QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
889 // PreviewJob internally caches items always with the size of
890 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
891 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
892 // do a downscaling anyhow because of the frame, so in this case only the provided
893 // cache sizes are requested.
894 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
895 ? QSize(256, 256) : QSize(128, 128);
897 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
898 // worst case) might block the application for several seconds. To prevent such
899 // a blocking, we only pass items with known mime type to the preview job.
900 const int count
= m_pendingPreviewItems
.count();
901 KFileItemList itemSubSet
;
902 itemSubSet
.reserve(count
);
904 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
905 // Some mime types are known already, probably because they were
906 // determined when loading the icons for the visible items. Start
907 // a preview job for all items at the beginning of the list which
908 // have a known mime type.
910 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
911 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
913 // Determine mime types for MaxBlockTimeout ms, and start a preview
914 // job for the corresponding items.
919 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
920 item
.determineMimeType();
921 itemSubSet
.append(item
);
922 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
925 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
927 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
929 job
->ui()->setWindow(qApp
->activeWindow());
932 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
933 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
934 connect(job
, SIGNAL(failed(KFileItem
)),
935 this, SLOT(slotPreviewFailed(KFileItem
)));
936 connect(job
, SIGNAL(finished(KJob
*)),
937 this, SLOT(slotPreviewJobFinished()));
942 void KFileItemModelRolesUpdater::updateChangedItems()
944 if (m_state
== Paused
) {
948 if (m_changedItems
.isEmpty()) {
952 m_finishedItems
-= m_changedItems
;
954 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
955 m_pendingSortRoleItems
+= m_changedItems
;
957 if (m_state
!= ResolvingSortRole
) {
958 // Stop the preview job if necessary, and trigger the
959 // asynchronous determination of the sort role.
961 m_state
= ResolvingSortRole
;
962 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
968 QList
<int> visibleChangedIndexes
;
969 QList
<int> invisibleChangedIndexes
;
971 foreach (const KFileItem
& item
, m_changedItems
) {
972 const int index
= m_model
->index(item
);
975 m_changedItems
.remove(item
);
979 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
980 visibleChangedIndexes
.append(index
);
982 invisibleChangedIndexes
.append(index
);
986 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
988 if (m_previewShown
) {
989 foreach (int index
, visibleChangedIndexes
) {
990 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
993 foreach (int index
, invisibleChangedIndexes
) {
994 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
1001 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
1002 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
1003 if (!resolvingInProgress
) {
1004 // Trigger the asynchronous resolving of the changed roles.
1005 m_state
= ResolvingAllRoles
;
1006 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
1011 void KFileItemModelRolesUpdater::applySortRole(int index
)
1013 QHash
<QByteArray
, QVariant
> data
;
1014 const KFileItem item
= m_model
->fileItem(index
);
1016 if (m_model
->sortRole() == "type") {
1017 if (!item
.isMimeTypeKnown()) {
1018 item
.determineMimeType();
1021 data
.insert("type", item
.mimeComment());
1022 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1023 const QString path
= item
.localPath();
1024 data
.insert("size", subItemsCount(path
));
1026 // Probably the sort role is a Nepomuk role - just determine all roles.
1027 data
= rolesData(item
);
1030 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1031 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1032 m_model
->setData(index
, data
);
1033 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1034 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1037 void KFileItemModelRolesUpdater::applySortProgressToModel()
1039 // Inform the model about the progress of the resolved items,
1040 // so that it can give an indication when the sorting has been finished.
1041 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1042 m_model
->emitSortProgress(resolvedCount
);
1045 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1047 if (item
.isNull()) {
1051 const bool resolveAll
= (hint
== ResolveAll
);
1053 bool iconChanged
= false;
1054 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1055 item
.determineMimeType();
1058 const int index
= m_model
->index(item
);
1059 if (!m_model
->data(index
).contains("iconName")) {
1064 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1065 const int index
= m_model
->index(item
);
1070 QHash
<QByteArray
, QVariant
> data
;
1072 data
= rolesData(item
);
1075 data
.insert("iconName", item
.iconName());
1077 if (m_clearPreviews
) {
1078 data
.insert("iconPixmap", QPixmap());
1081 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1082 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1083 m_model
->setData(index
, data
);
1084 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1085 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1092 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1094 QHash
<QByteArray
, QVariant
> data
;
1096 const bool getSizeRole
= m_roles
.contains("size");
1097 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1099 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1100 if (item
.isLocalFile()) {
1101 const QString path
= item
.localPath();
1102 const int count
= subItemsCount(path
);
1104 data
.insert("size", count
);
1106 if (getIsExpandableRole
) {
1107 data
.insert("isExpandable", count
> 0);
1110 if (!m_dirWatcher
->contains(path
)) {
1111 m_dirWatcher
->addDir(path
);
1112 m_watchedDirs
.insert(path
);
1114 } else if (getSizeRole
) {
1115 data
.insert("size", -1); // -1 indicates an unknown number of items
1119 if (m_roles
.contains("type")) {
1120 data
.insert("type", item
.mimeComment());
1123 data
.insert("iconOverlays", item
.overlays());
1126 if (m_nepomukResourceWatcher
) {
1127 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1128 Nepomuk2::Resource
resource(item
.nepomukUri());
1129 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1130 while (it
.hasNext()) {
1132 data
.insert(it
.key(), it
.value());
1135 QUrl uri
= resource
.uri();
1136 if (uri
.isEmpty()) {
1137 // TODO: Is there another way to explicitly create a resource?
1138 // We need a resource to be able to track it for changes.
1139 resource
.setRating(0);
1140 uri
= resource
.uri();
1142 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1143 m_nepomukResourceWatcher
->addResource(resource
);
1145 if (m_nepomukUriItems
.isEmpty()) {
1146 m_nepomukResourceWatcher
->start();
1149 m_nepomukUriItems
.insert(uri
, item
.url());
1157 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1159 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1160 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1164 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1165 if (countHiddenFiles
) {
1166 filters
|= QDir::Hidden
;
1168 if (showFoldersOnly
) {
1169 filters
|= QDir::Dirs
;
1171 filters
|= QDir::AllEntries
;
1173 return dir
.entryList(filters
).count();
1175 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1176 // Copyright (C) 2006 David Faure <faure@kde.org>
1179 DIR* dir
= ::opendir(QFile::encodeName(path
));
1180 if (dir
) { // krazy:exclude=syscalls
1182 struct dirent
*dirEntry
= 0;
1183 while ((dirEntry
= ::readdir(dir
))) {
1184 if (dirEntry
->d_name
[0] == '.') {
1185 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1186 // Skip "." or hidden files
1189 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1195 // If only directories are counted, consider an unknown file type and links also
1196 // as directory instead of trying to do an expensive stat()
1197 // (see bugs 292642 and 299997).
1198 const bool countEntry
= !showFoldersOnly
||
1199 dirEntry
->d_type
== DT_DIR
||
1200 dirEntry
->d_type
== DT_LNK
||
1201 dirEntry
->d_type
== DT_UNKNOWN
;
1212 void KFileItemModelRolesUpdater::updateAllPreviews()
1214 if (m_state
== Paused
) {
1215 m_previewChangedDuringPausing
= true;
1217 m_finishedItems
.clear();
1222 void KFileItemModelRolesUpdater::killPreviewJob()
1225 disconnect(m_previewJob
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
1226 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
1227 disconnect(m_previewJob
, SIGNAL(failed(KFileItem
)),
1228 this, SLOT(slotPreviewFailed(KFileItem
)));
1229 disconnect(m_previewJob
, SIGNAL(finished(KJob
*)),
1230 this, SLOT(slotPreviewJobFinished()));
1231 m_previewJob
->kill();
1233 m_pendingPreviewItems
.clear();
1237 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1239 const int count
= m_model
->count();
1242 result
.reserve(ResolveAllItemsLimit
);
1244 // Add visible items.
1245 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1249 // We need a reasonable upper limit for number of items to resolve after
1250 // and before the visible range. m_maximumVisibleItems can be quite large
1251 // when using Compace View.
1252 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1254 // Add items after the visible range.
1255 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1256 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1260 // Add items before the visible range in reverse order.
1261 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1262 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1266 // Add items on the last page.
1267 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1268 for (int i
= beginLastPage
; i
< count
; ++i
) {
1272 // Add items on the first page.
1273 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1274 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1278 // Continue adding items until ResolveAllItemsLimit is reached.
1279 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1281 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1286 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {
1294 #include "kfileitemmodelrolesupdater.moc"