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>
48 // Required includes for subItemsCount():
56 // #define KFILEITEMMODELROLESUPDATER_DEBUG
59 // Maximum time in ms that the KFileItemModelRolesUpdater
60 // may perform a blocking operation
61 const int MaxBlockTimeout
= 200;
63 // If the number of items is smaller than ResolveAllItemsLimit,
64 // the roles of all items will be resolved.
65 const int ResolveAllItemsLimit
= 500;
67 // Not only the visible area, but up to ReadAheadPages before and after
68 // this area will be resolved.
69 const int ReadAheadPages
= 5;
72 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
75 m_previewChangedDuringPausing(false),
76 m_iconSizeChangedDuringPausing(false),
77 m_rolesChangedDuringPausing(false),
78 m_previewShown(false),
79 m_enlargeSmallPreviews(true),
80 m_clearPreviews(false),
84 m_firstVisibleIndex(0),
85 m_lastVisibleIndex(-1),
86 m_maximumVisibleItems(50),
90 m_pendingSortRoleItems(),
91 m_pendingSortRoleIndexes(),
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();
269 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
271 if (m_roles
!= roles
) {
275 // Check whether there is at least one role that must be resolved
276 // with the help of Nepomuk. If this is the case, a (quite expensive)
277 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
278 // the role gets watched for changes.
279 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
280 bool hasNepomukRole
= false;
281 QSetIterator
<QByteArray
> it(roles
);
282 while (it
.hasNext()) {
283 const QByteArray
& role
= it
.next();
284 if (rolesProvider
.roles().contains(role
)) {
285 hasNepomukRole
= true;
290 if (hasNepomukRole
&& !m_nepomukResourceWatcher
) {
291 Q_ASSERT(m_nepomukUriItems
.isEmpty());
293 m_nepomukResourceWatcher
= new Nepomuk2::ResourceWatcher(this);
294 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariantList
,QVariantList
)),
295 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
)));
296 } else if (!hasNepomukRole
&& m_nepomukResourceWatcher
) {
297 delete m_nepomukResourceWatcher
;
298 m_nepomukResourceWatcher
= 0;
299 m_nepomukUriItems
.clear();
303 if (m_state
== Paused
) {
304 m_rolesChangedDuringPausing
= true;
311 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
316 bool KFileItemModelRolesUpdater::isPaused() const
318 return m_state
== Paused
;
321 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
323 return m_enabledPlugins
;
326 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
331 // Determine the sort role synchronously for as many items as possible.
332 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
333 int insertedCount
= 0;
334 foreach (const KItemRange
& range
, itemRanges
) {
335 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
336 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
337 if (timer
.elapsed() < MaxBlockTimeout
) {
340 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
343 insertedCount
+= range
.count
;
346 applySortProgressToModel();
348 // If there are still items whose sort role is unknown, return
349 // and handle them asynchronously.
350 if (!m_pendingSortRoleItems
.isEmpty()) {
351 if (m_state
!= ResolvingSortRole
) {
352 // Trigger the asynchronous determination of the sort role.
354 m_state
= ResolvingSortRole
;
355 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_pendingSortRoleIndexes
.clear();
423 m_pendingIndexes
.clear();
424 m_pendingPreviewItems
.clear();
425 m_recentlyChangedItems
.clear();
426 m_recentlyChangedItemsTimer
->stop();
427 m_changedItems
.clear();
431 // Only remove the items from m_finishedItems. They will be removed
432 // from the other sets later on.
433 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
434 while (it
!= m_finishedItems
.end()) {
435 if (m_model
->index(*it
) < 0) {
436 it
= m_finishedItems
.erase(it
);
442 // The visible items might have changed.
447 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
450 Q_UNUSED(movedToIndexes
);
452 // The indexes of the items with missing sort role are not valid any more.
453 m_pendingSortRoleIndexes
.clear();
455 // The visible items might have changed.
459 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
460 const QSet
<QByteArray
>& roles
)
464 // Find out if slotItemsChanged() has been done recently. If that is the
465 // case, resolving the roles is postponed until a timer has exceeded
466 // to prevent expensive repeated updates if files are updated frequently.
467 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
469 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
471 foreach (const KItemRange
& itemRange
, itemRanges
) {
472 int index
= itemRange
.index
;
473 for (int count
= itemRange
.count
; count
> 0; --count
) {
474 const KFileItem item
= m_model
->fileItem(index
);
475 targetSet
.insert(item
);
480 m_recentlyChangedItemsTimer
->start();
482 if (!itemsChangedRecently
) {
483 updateChangedItems();
487 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
488 const QByteArray
& previous
)
493 if (m_resolvableRoles
.contains(current
)) {
494 m_pendingSortRoleItems
.clear();
495 m_pendingSortRoleIndexes
.clear();
496 m_finishedItems
.clear();
498 const int count
= m_model
->count();
502 // Determine the sort role synchronously for as many items as possible.
503 for (int index
= 0; index
< count
; ++index
) {
504 if (timer
.elapsed() < MaxBlockTimeout
) {
505 applySortRole(index
);
507 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
511 applySortProgressToModel();
513 if (!m_pendingSortRoleItems
.isEmpty()) {
514 // Trigger the asynchronous determination of the sort role.
516 m_state
= ResolvingSortRole
;
517 resolveNextSortRole();
521 m_pendingSortRoleItems
.clear();
522 m_pendingSortRoleIndexes
.clear();
523 applySortProgressToModel();
527 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
529 if (m_state
!= PreviewJobRunning
) {
533 m_changedItems
.remove(item
);
535 const int index
= m_model
->index(item
);
540 QPixmap scaledPixmap
= pixmap
;
542 const QString mimeType
= item
.mimetype();
543 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
544 const QString mimeTypeGroup
= mimeType
.left(slashIndex
);
545 if (mimeTypeGroup
== QLatin1String("image")) {
546 if (m_enlargeSmallPreviews
) {
547 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
549 // Assure that small previews don't get enlarged. Instead they
550 // should be shown centered within the frame.
551 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
552 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
553 scaledPixmap
.height() < contentSize
.height();
554 if (enlargingRequired
) {
555 QSize frameSize
= scaledPixmap
.size();
556 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
558 QPixmap
largeFrame(frameSize
);
559 largeFrame
.fill(Qt::transparent
);
561 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
563 QPainter
painter(&largeFrame
);
564 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width()) / 2,
565 (largeFrame
.height() - scaledPixmap
.height()) / 2,
567 scaledPixmap
= largeFrame
;
569 // The image must be shrinked as it is too large to fit into
570 // the available icon size
571 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
575 KPixmapModifier::scale(scaledPixmap
, m_iconSize
);
578 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
579 data
.insert("iconPixmap", scaledPixmap
);
581 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
582 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
583 m_model
->setData(index
, data
);
584 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
585 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
587 m_finishedItems
.insert(item
);
590 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
592 if (m_state
!= PreviewJobRunning
) {
596 m_changedItems
.remove(item
);
598 const int index
= m_model
->index(item
);
600 QHash
<QByteArray
, QVariant
> data
;
601 data
.insert("iconPixmap", QPixmap());
603 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
604 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
605 m_model
->setData(index
, data
);
606 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
607 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
609 applyResolvedRoles(item
, ResolveAll
);
610 m_finishedItems
.insert(item
);
614 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
618 if (m_state
!= PreviewJobRunning
) {
624 if (!m_pendingPreviewItems
.isEmpty()) {
625 startPreviewJob(m_pendingPreviewItems
);
627 if (!m_changedItems
.isEmpty()) {
628 updateChangedItems();
633 void KFileItemModelRolesUpdater::resolveNextSortRole()
635 if (m_state
!= ResolvingSortRole
) {
639 if (m_pendingSortRoleItems
.count() != m_pendingSortRoleIndexes
.count()) {
640 // The indexes with missing sort role have to be updated.
641 m_pendingSortRoleIndexes
.clear();
642 foreach (const KFileItem
& item
, m_pendingSortRoleItems
) {
643 const int index
= m_model
->index(item
);
645 m_pendingSortRoleItems
.remove(item
);
647 m_pendingSortRoleIndexes
.append(index
);
651 std::sort(m_pendingSortRoleIndexes
.begin(), m_pendingSortRoleIndexes
.end());
654 // Try to update an item in the visible range.
655 QList
<int>::iterator it
= std::lower_bound(m_pendingSortRoleIndexes
.begin(),
656 m_pendingSortRoleIndexes
.end(),
657 m_firstVisibleIndex
);
659 // It seems that there is no such item. Start with the first item in the list.
660 if (it
== m_pendingSortRoleIndexes
.end()) {
661 it
= m_pendingSortRoleIndexes
.begin();
664 while (it
!= m_pendingSortRoleIndexes
.end()) {
665 // TODO: Note that removing an index from the list m_pendingSortRoleIndexes
666 // at a random position is O(N). We might need a better solution
667 // to make sure that this does not harm the performance if
668 // many items have to be sorted.
669 const int index
= *it
;
670 const KFileItem item
= m_model
->fileItem(index
);
672 // Continue if the sort role has already been determined for the
673 // item, and the item has not been changed recently.
674 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
675 m_pendingSortRoleItems
.remove(item
);
676 m_pendingSortRoleIndexes
.erase(it
);
678 // Check if we are at the end of the list (note that the list's end has changed).
679 if (it
!= m_pendingSortRoleIndexes
.end()) {
685 applySortRole(index
);
686 m_pendingSortRoleItems
.remove(item
);
687 m_pendingSortRoleIndexes
.erase(it
);
691 if (!m_pendingSortRoleItems
.isEmpty()) {
692 applySortProgressToModel();
693 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
697 // Prevent that we try to update the items twice.
698 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
699 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
700 applySortProgressToModel();
701 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
702 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
707 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
709 if (m_state
!= ResolvingAllRoles
&& m_state
!= PreviewJobRunning
) {
713 while (!m_pendingIndexes
.isEmpty()) {
714 const int index
= m_pendingIndexes
.takeFirst();
715 const KFileItem item
= m_model
->fileItem(index
);
717 if (m_finishedItems
.contains(item
)) {
721 if (m_previewShown
) {
722 // Only determine the icon. The other roles are resolved when the preview is received.
723 applyResolvedRoles(item
, ResolveFast
);
725 applyResolvedRoles(item
, ResolveAll
);
726 m_finishedItems
.insert(item
);
727 m_changedItems
.remove(item
);
733 if (!m_pendingIndexes
.isEmpty()) {
734 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
735 } else if (m_state
!= PreviewJobRunning
) {
738 if (m_clearPreviews
) {
739 // Only go through the list if there are items which might still have previews.
740 if (m_finishedItems
.count() != m_model
->count()) {
741 QHash
<QByteArray
, QVariant
> data
;
742 data
.insert("iconPixmap", QPixmap());
744 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
745 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
746 for (int index
= 0; index
<= m_model
->count(); ++index
) {
747 if (m_model
->data(index
).contains("iconPixmap")) {
748 m_model
->setData(index
, data
);
751 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
752 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
755 m_clearPreviews
= false;
758 if (!m_changedItems
.isEmpty()) {
759 updateChangedItems();
764 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
766 m_changedItems
+= m_recentlyChangedItems
;
767 m_recentlyChangedItems
.clear();
768 updateChangedItems();
771 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource
& resource
)
774 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.uri());
775 const KFileItem item
= m_model
->fileItem(itemUrl
);
778 // itemUrl is not in the model anymore, probably because
779 // the corresponding file has been deleted in the meantime.
783 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
785 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
786 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
787 while (it
.hasNext()) {
789 data
.insert(it
.key(), it
.value());
792 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
793 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
794 const int index
= m_model
->index(item
);
795 m_model
->setData(index
, data
);
796 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
797 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
805 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
807 const bool getSizeRole
= m_roles
.contains("size");
808 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
810 if (getSizeRole
|| getIsExpandableRole
) {
811 const int index
= m_model
->index(KUrl(path
));
813 if (!m_model
->fileItem(index
).isDir()) {
814 // If INotify is used, KDirWatch issues the dirty() signal
815 // also for changed files inside the directory, even if we
816 // don't enable this behavior explicitly (see bug 309740).
820 QHash
<QByteArray
, QVariant
> data
;
822 const int count
= subItemsCount(path
);
824 data
.insert("size", count
);
826 if (getIsExpandableRole
) {
827 data
.insert("isExpandable", count
> 0);
830 // Note that we do not block the itemsChanged signal here.
831 // This ensures that a new preview will be generated.
832 m_model
->setData(index
, data
);
837 void KFileItemModelRolesUpdater::startUpdating()
839 // Updating the items in and near the visible area makes sense only
840 // if sorting is finished.
841 if (m_state
== ResolvingSortRole
|| m_state
== Paused
) {
845 if (m_finishedItems
.count() == m_model
->count()) {
846 // All roles have been resolved already.
851 int lastVisibleIndex
= m_lastVisibleIndex
;
852 if (lastVisibleIndex
<= 0) {
853 // Guess a reasonable value for the last visible index if the view
854 // has not told us about the real value yet.
855 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
856 if (lastVisibleIndex
<= 0) {
857 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
861 // Terminate all updates that are currently active.
863 m_pendingIndexes
.clear();
868 // Determine the icons for the visible items synchronously.
870 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
871 const KFileItem item
= m_model
->fileItem(index
);
872 applyResolvedRoles(item
, ResolveFast
);
874 const int firstIndexWithoutIcon
= index
;
876 // Start the preview job or the asynchronous resolving of all roles.
877 QList
<int> indexes
= indexesToResolve();
879 if (m_previewShown
) {
880 KFileItemList itemsToResolve
;
881 foreach (int index
, indexes
) {
882 const KFileItem item
= m_model
->fileItem(index
);
883 if (!m_finishedItems
.contains(item
)) {
884 itemsToResolve
.append(m_model
->fileItem(index
));
886 // Remember the items which have no icon yet. A fast
887 // asynchronous resolving will be done to make sure
888 // that icons are loaded as quickly as possible, i.e.,
889 // before the previews arrive.
890 if (index
< m_firstVisibleIndex
|| index
>= firstIndexWithoutIcon
) {
891 m_pendingIndexes
.append(index
);
896 startPreviewJob(itemsToResolve
);
898 // Determine the icons asynchronously as fast as possible.
899 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
901 m_pendingIndexes
= indexes
;
902 // Trigger the asynchronous resolving of all roles.
903 m_state
= ResolvingAllRoles
;
904 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
908 void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList items
)
910 m_state
= PreviewJobRunning
;
912 if (items
.isEmpty()) {
913 QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
917 // PreviewJob internally caches items always with the size of
918 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
919 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
920 // do a downscaling anyhow because of the frame, so in this case only the provided
921 // cache sizes are requested.
922 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
923 ? QSize(256, 256) : QSize(128, 128);
925 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
926 // worst case) might block the application for several seconds. To prevent such
927 // a blocking, we only pass items with known mime type to the preview job
928 // (if the icon has already been determined for an item in startUpdating()
929 // or resolveNextPendingRoles(), the type is known).
930 // This also prevents that repeated expensive mime type determinations are
931 // triggered here if a huge folder is loaded, and startUpdating() is called
934 // Note that we always pass at least one item to the preview job to prevent
935 // that we get an endless startPreviewJob()/slotPreviewJobFinished() loop
936 // if there are no items with known mime types yet for some reason.
937 const int count
= items
.count();
938 int previewJobItemCount
= 1;
940 // TODO: This will start a job with one item only if this function is
941 // called from slotPreviewJobFinished(), and resolveNextPendingRoles()
942 // has not reached the items yet. This can happen if the previous preview
943 // job has finished very fast because generating previews failed for all
946 // Idea to improve this: if the mime type of the first item is unknown,
947 // determine mime types synchronously for a while.
948 while (previewJobItemCount
< qMin(count
, m_maximumVisibleItems
) &&
949 items
.at(previewJobItemCount
).isMimeTypeKnown()) {
950 ++previewJobItemCount
;
953 KFileItemList itemSubSet
;
954 itemSubSet
.reserve(previewJobItemCount
);
955 m_pendingPreviewItems
.clear();
956 m_pendingPreviewItems
.reserve(count
- previewJobItemCount
);
958 for (int i
= 0; i
< previewJobItemCount
; ++i
) {
959 itemSubSet
.append(items
.at(i
));
962 for (int i
= previewJobItemCount
; i
< count
; ++i
) {
963 m_pendingPreviewItems
.append(items
.at(i
));
966 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
968 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
970 job
->ui()->setWindow(qApp
->activeWindow());
973 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
974 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
975 connect(job
, SIGNAL(failed(KFileItem
)),
976 this, SLOT(slotPreviewFailed(KFileItem
)));
977 connect(job
, SIGNAL(finished(KJob
*)),
978 this, SLOT(slotPreviewJobFinished()));
983 void KFileItemModelRolesUpdater::updateChangedItems()
985 if (m_state
== Paused
) {
989 if (m_changedItems
.isEmpty()) {
993 m_finishedItems
-= m_changedItems
;
995 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
996 m_pendingSortRoleItems
+= m_changedItems
;
998 if (m_state
!= ResolvingSortRole
) {
999 // Stop the preview job if necessary, and trigger the
1000 // asynchronous determination of the sort role.
1002 m_state
= ResolvingSortRole
;
1003 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
1009 QList
<int> visibleChangedIndexes
;
1010 QList
<int> invisibleChangedIndexes
;
1012 foreach (const KFileItem
& item
, m_changedItems
) {
1013 const int index
= m_model
->index(item
);
1016 m_changedItems
.remove(item
);
1020 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
1021 visibleChangedIndexes
.append(index
);
1023 invisibleChangedIndexes
.append(index
);
1027 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
1029 if (m_previewShown
) {
1030 KFileItemList visibleChangedItems
;
1031 KFileItemList invisibleChangedItems
;
1033 foreach (int index
, visibleChangedIndexes
) {
1034 visibleChangedItems
.append(m_model
->fileItem(index
));
1037 foreach (int index
, invisibleChangedIndexes
) {
1038 invisibleChangedItems
.append(m_model
->fileItem(index
));
1042 m_pendingPreviewItems
+= visibleChangedItems
+ invisibleChangedItems
;
1044 startPreviewJob(visibleChangedItems
+ invisibleChangedItems
);
1047 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
1048 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
1049 if (!resolvingInProgress
) {
1050 // Trigger the asynchronous resolving of the changed roles.
1051 m_state
= ResolvingAllRoles
;
1052 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
1057 void KFileItemModelRolesUpdater::applySortRole(int index
)
1059 QHash
<QByteArray
, QVariant
> data
;
1060 const KFileItem item
= m_model
->fileItem(index
);
1062 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
1063 // Determine the icon.
1064 applyResolvedRoles(item
, ResolveFast
);
1067 if (m_model
->sortRole() == "type") {
1068 if (!item
.isMimeTypeKnown()) {
1069 item
.determineMimeType();
1072 data
.insert("type", item
.mimeComment());
1073 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1074 const QString path
= item
.localPath();
1075 data
.insert("size", subItemsCount(path
));
1077 // Probably the sort role is a Nepomuk role - just determine all roles.
1078 data
= rolesData(item
);
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
>)));
1088 void KFileItemModelRolesUpdater::applySortProgressToModel()
1090 // Inform the model about the progress of the resolved items,
1091 // so that it can give an indication when the sorting has been finished.
1092 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1093 m_model
->emitSortProgress(resolvedCount
);
1096 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1098 if (item
.isNull()) {
1102 const bool resolveAll
= (hint
== ResolveAll
);
1104 bool iconChanged
= false;
1105 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1106 item
.determineMimeType();
1108 } else if (m_state
== ResolvingSortRole
|| m_state
== PreviewJobRunning
) {
1109 // We are currently performing a fast determination of all icons
1110 // in the visible area.
1111 const int index
= m_model
->index(item
);
1112 if (!m_model
->data(index
).contains("iconName")) {
1117 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1118 const int index
= m_model
->index(item
);
1123 QHash
<QByteArray
, QVariant
> data
;
1125 data
= rolesData(item
);
1128 data
.insert("iconName", item
.iconName());
1130 if (m_clearPreviews
) {
1131 data
.insert("iconPixmap", QPixmap());
1134 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1135 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1136 m_model
->setData(index
, data
);
1137 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1138 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1145 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1147 QHash
<QByteArray
, QVariant
> data
;
1149 const bool getSizeRole
= m_roles
.contains("size");
1150 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1152 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1153 if (item
.isLocalFile()) {
1154 const QString path
= item
.localPath();
1155 const int count
= subItemsCount(path
);
1157 data
.insert("size", count
);
1159 if (getIsExpandableRole
) {
1160 data
.insert("isExpandable", count
> 0);
1163 if (!m_dirWatcher
->contains(path
)) {
1164 m_dirWatcher
->addDir(path
);
1165 m_watchedDirs
.insert(path
);
1167 } else if (getSizeRole
) {
1168 data
.insert("size", -1); // -1 indicates an unknown number of items
1172 if (m_roles
.contains("type")) {
1173 data
.insert("type", item
.mimeComment());
1176 data
.insert("iconOverlays", item
.overlays());
1179 if (m_nepomukResourceWatcher
) {
1180 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1181 Nepomuk2::Resource
resource(item
.nepomukUri());
1182 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1183 while (it
.hasNext()) {
1185 data
.insert(it
.key(), it
.value());
1188 QUrl uri
= resource
.uri();
1189 if (uri
.isEmpty()) {
1190 // TODO: Is there another way to explicitly create a resource?
1191 // We need a resource to be able to track it for changes.
1192 resource
.setRating(0);
1193 uri
= resource
.uri();
1195 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1196 m_nepomukResourceWatcher
->addResource(resource
);
1198 if (m_nepomukUriItems
.isEmpty()) {
1199 m_nepomukResourceWatcher
->start();
1202 m_nepomukUriItems
.insert(uri
, item
.url());
1210 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1212 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1213 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1217 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1218 if (countHiddenFiles
) {
1219 filters
|= QDir::Hidden
;
1221 if (showFoldersOnly
) {
1222 filters
|= QDir::Dirs
;
1224 filters
|= QDir::AllEntries
;
1226 return dir
.entryList(filters
).count();
1228 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1229 // Copyright (C) 2006 David Faure <faure@kde.org>
1232 DIR* dir
= ::opendir(QFile::encodeName(path
));
1233 if (dir
) { // krazy:exclude=syscalls
1235 struct dirent
*dirEntry
= 0;
1236 while ((dirEntry
= ::readdir(dir
))) {
1237 if (dirEntry
->d_name
[0] == '.') {
1238 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1239 // Skip "." or hidden files
1242 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1248 // If only directories are counted, consider an unknown file type and links also
1249 // as directory instead of trying to do an expensive stat()
1250 // (see bugs 292642 and 299997).
1251 const bool countEntry
= !showFoldersOnly
||
1252 dirEntry
->d_type
== DT_DIR
||
1253 dirEntry
->d_type
== DT_LNK
||
1254 dirEntry
->d_type
== DT_UNKNOWN
;
1265 void KFileItemModelRolesUpdater::updateAllPreviews()
1267 if (m_state
== Paused
) {
1268 m_previewChangedDuringPausing
= true;
1270 m_finishedItems
.clear();
1275 void KFileItemModelRolesUpdater::killPreviewJob()
1278 disconnect(m_previewJob
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
1279 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
1280 disconnect(m_previewJob
, SIGNAL(failed(KFileItem
)),
1281 this, SLOT(slotPreviewFailed(KFileItem
)));
1282 disconnect(m_previewJob
, SIGNAL(finished(KJob
*)),
1283 this, SLOT(slotPreviewJobFinished()));
1284 m_previewJob
->kill();
1286 m_pendingPreviewItems
.clear();
1290 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1292 const int count
= m_model
->count();
1295 result
.reserve(ResolveAllItemsLimit
);
1297 // Add visible items.
1298 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1302 // We need a reasonable upper limit for number of items to resolve after
1303 // and before the visible range. m_maximumVisibleItems can be quite large
1304 // when using Compace View.
1305 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1307 // Add items after the visible range.
1308 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1309 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1313 // Add items before the visible range in reverse order.
1314 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1315 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1319 // Add items on the last page.
1320 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1321 for (int i
= beginLastPage
; i
< count
; ++i
) {
1325 // Add items on the first page.
1326 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1327 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1331 // Continue adding items until ResolveAllItemsLimit is reached.
1332 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1334 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1339 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {
1347 #include "kfileitemmodelrolesupdater.moc"