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(KJob
* job
)
620 if (m_state
!= PreviewJobRunning
) {
626 if (!m_pendingPreviewItems
.isEmpty()) {
627 startPreviewJob(m_pendingPreviewItems
);
629 if (!m_changedItems
.isEmpty()) {
630 updateChangedItems();
635 void KFileItemModelRolesUpdater::resolveNextSortRole()
637 if (m_state
!= ResolvingSortRole
) {
641 if (m_pendingSortRoleItems
.count() != m_pendingSortRoleIndexes
.count()) {
642 // The indexes with missing sort role have to be updated.
643 m_pendingSortRoleIndexes
.clear();
644 foreach (const KFileItem
& item
, m_pendingSortRoleItems
) {
645 const int index
= m_model
->index(item
);
647 m_pendingSortRoleItems
.remove(item
);
649 m_pendingSortRoleIndexes
.append(index
);
653 std::sort(m_pendingSortRoleIndexes
.begin(), m_pendingSortRoleIndexes
.end());
656 // Try to update an item in the visible range.
657 QList
<int>::iterator it
= std::lower_bound(m_pendingSortRoleIndexes
.begin(),
658 m_pendingSortRoleIndexes
.end(),
659 m_firstVisibleIndex
);
661 // It seems that there is no such item. Start with the first item in the list.
662 if (it
== m_pendingSortRoleIndexes
.end()) {
663 it
= m_pendingSortRoleIndexes
.begin();
666 while (it
!= m_pendingSortRoleIndexes
.end()) {
667 // TODO: Note that removing an index from the list m_pendingSortRoleIndexes
668 // at a random position is O(N). We might need a better solution
669 // to make sure that this does not harm the performance if
670 // many items have to be sorted.
671 const int index
= *it
;
672 const KFileItem item
= m_model
->fileItem(index
);
674 // Continue if the sort role has already been determined for the
675 // item, and the item has not been changed recently.
676 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
677 m_pendingSortRoleItems
.remove(item
);
678 m_pendingSortRoleIndexes
.erase(it
);
680 // Check if we are at the end of the list (note that the list's end has changed).
681 if (it
!= m_pendingSortRoleIndexes
.end()) {
687 applySortRole(index
);
688 m_pendingSortRoleItems
.remove(item
);
689 m_pendingSortRoleIndexes
.erase(it
);
693 if (!m_pendingSortRoleItems
.isEmpty()) {
694 applySortProgressToModel();
695 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
699 // Prevent that we try to update the items twice.
700 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
701 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
702 applySortProgressToModel();
703 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
704 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
709 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
711 if (m_state
!= ResolvingAllRoles
&& m_state
!= PreviewJobRunning
) {
715 while (!m_pendingIndexes
.isEmpty()) {
716 const int index
= m_pendingIndexes
.takeFirst();
717 const KFileItem item
= m_model
->fileItem(index
);
719 if (m_finishedItems
.contains(item
)) {
723 if (m_previewShown
) {
724 // Only determine the icon. The other roles are resolved when the preview is received.
725 applyResolvedRoles(item
, ResolveFast
);
727 applyResolvedRoles(item
, ResolveAll
);
728 m_finishedItems
.insert(item
);
729 m_changedItems
.remove(item
);
735 if (!m_pendingIndexes
.isEmpty()) {
736 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
737 } else if (m_state
!= PreviewJobRunning
) {
740 if (m_clearPreviews
) {
741 // Only go through the list if there are items which might still have previews.
742 if (m_finishedItems
.count() != m_model
->count()) {
743 QHash
<QByteArray
, QVariant
> data
;
744 data
.insert("iconPixmap", QPixmap());
746 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
747 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
748 for (int index
= 0; index
<= m_model
->count(); ++index
) {
749 if (m_model
->data(index
).contains("iconPixmap")) {
750 m_model
->setData(index
, data
);
753 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
754 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
757 m_clearPreviews
= false;
760 if (!m_changedItems
.isEmpty()) {
761 updateChangedItems();
766 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
768 m_changedItems
+= m_recentlyChangedItems
;
769 m_recentlyChangedItems
.clear();
770 updateChangedItems();
773 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource
& resource
)
776 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.uri());
777 const KFileItem item
= m_model
->fileItem(itemUrl
);
780 // itemUrl is not in the model anymore, probably because
781 // the corresponding file has been deleted in the meantime.
785 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
787 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
788 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
789 while (it
.hasNext()) {
791 data
.insert(it
.key(), it
.value());
794 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
795 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
796 const int index
= m_model
->index(item
);
797 m_model
->setData(index
, data
);
798 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
799 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
807 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
809 const bool getSizeRole
= m_roles
.contains("size");
810 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
812 if (getSizeRole
|| getIsExpandableRole
) {
813 const int index
= m_model
->index(KUrl(path
));
815 if (!m_model
->fileItem(index
).isDir()) {
816 // If INotify is used, KDirWatch issues the dirty() signal
817 // also for changed files inside the directory, even if we
818 // don't enable this behavior explicitly (see bug 309740).
822 QHash
<QByteArray
, QVariant
> data
;
824 const int count
= subItemsCount(path
);
826 data
.insert("size", count
);
828 if (getIsExpandableRole
) {
829 data
.insert("isExpandable", count
> 0);
832 // Note that we do not block the itemsChanged signal here.
833 // This ensures that a new preview will be generated.
834 m_model
->setData(index
, data
);
839 void KFileItemModelRolesUpdater::startUpdating()
841 // Updating the items in and near the visible area makes sense only
842 // if sorting is finished.
843 if (m_state
== ResolvingSortRole
|| m_state
== Paused
) {
847 if (m_finishedItems
.count() == m_model
->count()) {
848 // All roles have been resolved already.
853 int lastVisibleIndex
= m_lastVisibleIndex
;
854 if (lastVisibleIndex
<= 0) {
855 // Guess a reasonable value for the last visible index if the view
856 // has not told us about the real value yet.
857 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
858 if (lastVisibleIndex
<= 0) {
859 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
863 // Terminate all updates that are currently active.
865 m_pendingIndexes
.clear();
870 // Determine the icons for the visible items synchronously.
872 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
873 const KFileItem item
= m_model
->fileItem(index
);
874 applyResolvedRoles(item
, ResolveFast
);
876 const int firstIndexWithoutIcon
= index
;
878 // Start the preview job or the asynchronous resolving of all roles.
879 QList
<int> indexes
= indexesToResolve();
881 if (m_previewShown
) {
882 KFileItemList itemsToResolve
;
883 foreach (int index
, indexes
) {
884 const KFileItem item
= m_model
->fileItem(index
);
885 if (!m_finishedItems
.contains(item
)) {
886 itemsToResolve
.append(m_model
->fileItem(index
));
888 // Remember the items which have no icon yet. A fast
889 // asynchronous resolving will be done to make sure
890 // that icons are loaded as quickly as possible, i.e.,
891 // before the previews arrive.
892 if (index
< m_firstVisibleIndex
|| index
>= firstIndexWithoutIcon
) {
893 m_pendingIndexes
.append(index
);
898 startPreviewJob(itemsToResolve
);
900 // Determine the icons asynchronously as fast as possible.
901 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
903 m_pendingIndexes
= indexes
;
904 // Trigger the asynchronous resolving of all roles.
905 m_state
= ResolvingAllRoles
;
906 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
910 void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList items
)
912 m_state
= PreviewJobRunning
;
914 if (items
.isEmpty()) {
915 QMetaObject::invokeMethod(this, "slotPreviewJobFinished", Qt::QueuedConnection
, Q_ARG(KJob
*, 0));
919 // PreviewJob internally caches items always with the size of
920 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
921 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
922 // do a downscaling anyhow because of the frame, so in this case only the provided
923 // cache sizes are requested.
924 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
925 ? QSize(256, 256) : QSize(128, 128);
927 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
928 // worst case) might block the application for several seconds. To prevent such
929 // a blocking, we only pass items with known mime type to the preview job
930 // (if the icon has already been determined for an item in startUpdating()
931 // or resolveNextPendingRoles(), the type is known).
932 // This also prevents that repeated expensive mime type determinations are
933 // triggered here if a huge folder is loaded, and startUpdating() is called
936 // Note that we always pass at least one item to the preview job to prevent
937 // that we get an endless startPreviewJob()/slotPreviewJobFinished() loop
938 // if there are no items with known mime types yet for some reason.
939 const int count
= items
.count();
940 int previewJobItemCount
= 1;
942 // TODO: This will start a job with one item only if this function is
943 // called from slotPreviewJobFinished(), and resolveNextPendingRoles()
944 // has not reached the items yet. This can happen if the previous preview
945 // job has finished very fast because generating previews failed for all
948 // Idea to improve this: if the mime type of the first item is unknown,
949 // determine mime types synchronously for a while.
950 while (previewJobItemCount
< qMin(count
, m_maximumVisibleItems
) &&
951 items
.at(previewJobItemCount
).isMimeTypeKnown()) {
952 ++previewJobItemCount
;
955 KFileItemList itemSubSet
;
956 itemSubSet
.reserve(previewJobItemCount
);
957 m_pendingPreviewItems
.clear();
958 m_pendingPreviewItems
.reserve(count
- previewJobItemCount
);
960 for (int i
= 0; i
< previewJobItemCount
; ++i
) {
961 itemSubSet
.append(items
.at(i
));
964 for (int i
= previewJobItemCount
; i
< count
; ++i
) {
965 m_pendingPreviewItems
.append(items
.at(i
));
968 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
970 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
972 job
->ui()->setWindow(qApp
->activeWindow());
975 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
976 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
977 connect(job
, SIGNAL(failed(KFileItem
)),
978 this, SLOT(slotPreviewFailed(KFileItem
)));
979 connect(job
, SIGNAL(finished(KJob
*)),
980 this, SLOT(slotPreviewJobFinished(KJob
*)));
985 void KFileItemModelRolesUpdater::updateChangedItems()
987 if (m_state
== Paused
) {
991 if (m_changedItems
.isEmpty()) {
995 m_finishedItems
-= m_changedItems
;
997 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
998 m_pendingSortRoleItems
+= m_changedItems
;
1000 if (m_state
!= ResolvingSortRole
) {
1001 // Stop the preview job if necessary, and trigger the
1002 // asynchronous determination of the sort role.
1004 m_state
= ResolvingSortRole
;
1005 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
1011 QList
<int> visibleChangedIndexes
;
1012 QList
<int> invisibleChangedIndexes
;
1014 foreach (const KFileItem
& item
, m_changedItems
) {
1015 const int index
= m_model
->index(item
);
1021 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
1022 visibleChangedIndexes
.append(index
);
1024 invisibleChangedIndexes
.append(index
);
1028 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
1030 if (m_previewShown
) {
1031 KFileItemList visibleChangedItems
;
1032 KFileItemList invisibleChangedItems
;
1034 foreach (int index
, visibleChangedIndexes
) {
1035 visibleChangedItems
.append(m_model
->fileItem(index
));
1038 foreach (int index
, invisibleChangedIndexes
) {
1039 invisibleChangedItems
.append(m_model
->fileItem(index
));
1043 m_pendingPreviewItems
+= visibleChangedItems
+ invisibleChangedItems
;
1045 startPreviewJob(visibleChangedItems
+ invisibleChangedItems
);
1048 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
1049 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
1050 if (!resolvingInProgress
) {
1051 // Trigger the asynchronous resolving of the changed roles.
1052 m_state
= ResolvingAllRoles
;
1053 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
1058 void KFileItemModelRolesUpdater::applySortRole(int index
)
1060 QHash
<QByteArray
, QVariant
> data
;
1061 const KFileItem item
= m_model
->fileItem(index
);
1063 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
1064 // Determine the icon.
1065 applyResolvedRoles(item
, ResolveFast
);
1068 if (m_model
->sortRole() == "type") {
1069 if (!item
.isMimeTypeKnown()) {
1070 item
.determineMimeType();
1073 data
.insert("type", item
.mimeComment());
1074 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1075 const QString path
= item
.localPath();
1076 data
.insert("size", subItemsCount(path
));
1078 // Probably the sort role is a Nepomuk role - just determine all roles.
1079 data
= rolesData(item
);
1082 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1083 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1084 m_model
->setData(index
, data
);
1085 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1086 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1089 void KFileItemModelRolesUpdater::applySortProgressToModel()
1091 // Inform the model about the progress of the resolved items,
1092 // so that it can give an indication when the sorting has been finished.
1093 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1094 m_model
->emitSortProgress(resolvedCount
);
1097 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1099 if (item
.isNull()) {
1103 const bool resolveAll
= (hint
== ResolveAll
);
1105 bool iconChanged
= false;
1106 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1107 item
.determineMimeType();
1109 } else if (m_state
== ResolvingSortRole
|| m_state
== PreviewJobRunning
) {
1110 // We are currently performing a fast determination of all icons
1111 // in the visible area.
1112 const int index
= m_model
->index(item
);
1113 if (!m_model
->data(index
).contains("iconName")) {
1118 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1119 const int index
= m_model
->index(item
);
1124 QHash
<QByteArray
, QVariant
> data
;
1126 data
= rolesData(item
);
1129 data
.insert("iconName", item
.iconName());
1131 if (m_clearPreviews
) {
1132 data
.insert("iconPixmap", QPixmap());
1135 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1136 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1137 m_model
->setData(index
, data
);
1138 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1139 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1146 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1148 QHash
<QByteArray
, QVariant
> data
;
1150 const bool getSizeRole
= m_roles
.contains("size");
1151 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1153 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1154 if (item
.isLocalFile()) {
1155 const QString path
= item
.localPath();
1156 const int count
= subItemsCount(path
);
1158 data
.insert("size", count
);
1160 if (getIsExpandableRole
) {
1161 data
.insert("isExpandable", count
> 0);
1164 if (!m_dirWatcher
->contains(path
)) {
1165 m_dirWatcher
->addDir(path
);
1166 m_watchedDirs
.insert(path
);
1168 } else if (getSizeRole
) {
1169 data
.insert("size", -1); // -1 indicates an unknown number of items
1173 if (m_roles
.contains("type")) {
1174 data
.insert("type", item
.mimeComment());
1177 data
.insert("iconOverlays", item
.overlays());
1180 if (m_nepomukResourceWatcher
) {
1181 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1182 Nepomuk2::Resource
resource(item
.nepomukUri());
1183 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1184 while (it
.hasNext()) {
1186 data
.insert(it
.key(), it
.value());
1189 QUrl uri
= resource
.uri();
1190 if (uri
.isEmpty()) {
1191 // TODO: Is there another way to explicitly create a resource?
1192 // We need a resource to be able to track it for changes.
1193 resource
.setRating(0);
1194 uri
= resource
.uri();
1196 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1197 m_nepomukResourceWatcher
->addResource(resource
);
1199 if (m_nepomukUriItems
.isEmpty()) {
1200 m_nepomukResourceWatcher
->start();
1203 m_nepomukUriItems
.insert(uri
, item
.url());
1211 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1213 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1214 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1218 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1219 if (countHiddenFiles
) {
1220 filters
|= QDir::Hidden
;
1222 if (showFoldersOnly
) {
1223 filters
|= QDir::Dirs
;
1225 filters
|= QDir::AllEntries
;
1227 return dir
.entryList(filters
).count();
1229 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1230 // Copyright (C) 2006 David Faure <faure@kde.org>
1233 DIR* dir
= ::opendir(QFile::encodeName(path
));
1234 if (dir
) { // krazy:exclude=syscalls
1236 struct dirent
*dirEntry
= 0;
1237 while ((dirEntry
= ::readdir(dir
))) {
1238 if (dirEntry
->d_name
[0] == '.') {
1239 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1240 // Skip "." or hidden files
1243 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1249 // If only directories are counted, consider an unknown file type and links also
1250 // as directory instead of trying to do an expensive stat()
1251 // (see bugs 292642 and 299997).
1252 const bool countEntry
= !showFoldersOnly
||
1253 dirEntry
->d_type
== DT_DIR
||
1254 dirEntry
->d_type
== DT_LNK
||
1255 dirEntry
->d_type
== DT_UNKNOWN
;
1266 void KFileItemModelRolesUpdater::updateAllPreviews()
1268 if (m_state
== Paused
) {
1269 m_previewChangedDuringPausing
= true;
1271 m_finishedItems
.clear();
1276 void KFileItemModelRolesUpdater::killPreviewJob()
1279 disconnect(m_previewJob
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
1280 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
1281 disconnect(m_previewJob
, SIGNAL(failed(KFileItem
)),
1282 this, SLOT(slotPreviewFailed(KFileItem
)));
1283 disconnect(m_previewJob
, SIGNAL(finished(KJob
*)),
1284 this, SLOT(slotPreviewJobFinished(KJob
*)));
1285 m_previewJob
->kill();
1287 m_pendingPreviewItems
.clear();
1291 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1293 const int count
= m_model
->count();
1296 result
.reserve(ResolveAllItemsLimit
);
1298 // Add visible items.
1299 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1303 // We need a reasonable upper limit for number of items to resolve after
1304 // and before the visible range. m_maximumVisibleItems can be quite large
1305 // when using Compace View.
1306 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1308 // Add items after the visible range.
1309 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1310 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1314 // Add items before the visible range in reverse order.
1315 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1316 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1320 // Add items on the last page.
1321 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1322 for (int i
= beginLastPage
; i
< count
; ++i
) {
1326 // Add items on the first page.
1327 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1328 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1332 // Continue adding items until ResolveAllItemsLimit is reached.
1333 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1335 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1340 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {
1348 #include "kfileitemmodelrolesupdater.moc"