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>
42 #include "private/knepomukrolesprovider.h"
43 #include <Nepomuk2/ResourceWatcher>
46 // Required includes for subItemsCount():
54 // #define KFILEITEMMODELROLESUPDATER_DEBUG
57 // Maximum time in ms that the KFileItemModelRolesUpdater
58 // may perform a blocking operation
59 const int MaxBlockTimeout
= 200;
61 // Maximum number of items that will get resolved synchronously.
62 // The value should roughly represent the number of maximum visible
63 // items, as it does not make sense to resolve more items synchronously
64 // and probably reach the MaxBlockTimeout because of invisible items.
65 const int MaxResolveItemsCount
= 100;
68 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
71 m_previewChangedDuringPausing(false),
72 m_iconSizeChangedDuringPausing(false),
73 m_rolesChangedDuringPausing(false),
74 m_previewShown(false),
75 m_enlargeSmallPreviews(true),
76 m_clearPreviews(false),
77 m_sortingProgress(-1),
80 m_firstVisibleIndex(0),
81 m_lastVisibleIndex(-1),
82 m_maximumVisibleItems(100),
85 m_pendingVisibleItems(),
86 m_pendingInvisibleItems(),
88 m_changedItemsTimer(0),
93 , m_nepomukResourceWatcher(0),
99 const KConfigGroup
globalConfig(KGlobal::config(), "PreviewSettings");
100 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList()
101 << "directorythumbnail"
105 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
106 this, SLOT(slotItemsInserted(KItemRangeList
)));
107 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
108 this, SLOT(slotItemsRemoved(KItemRangeList
)));
109 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
110 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
111 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
112 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
114 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
115 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
116 m_changedItemsTimer
= new QTimer(this);
117 m_changedItemsTimer
->setInterval(1000);
118 m_changedItemsTimer
->setSingleShot(true);
119 connect(m_changedItemsTimer
, SIGNAL(timeout()), this, SLOT(resolveChangedItems()));
121 m_resolvableRoles
.insert("size");
122 m_resolvableRoles
.insert("type");
123 m_resolvableRoles
.insert("isExpandable");
125 m_resolvableRoles
+= KNepomukRolesProvider::instance().roles();
128 // When folders are expandable or the item-count is shown for folders, it is necessary
129 // to watch the number of items of the sub-folder to be able to react on changes.
130 m_dirWatcher
= new KDirWatch(this);
131 connect(m_dirWatcher
, SIGNAL(dirty(QString
)), this, SLOT(slotDirWatchDirty(QString
)));
134 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
139 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
141 if (size
!= m_iconSize
) {
144 m_iconSizeChangedDuringPausing
= true;
145 } else if (m_previewShown
) {
146 // An icon size change requires the regenerating of
148 sortAndResolveAllRoles();
150 sortAndResolvePendingRoles();
155 QSize
KFileItemModelRolesUpdater::iconSize() const
160 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
169 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
170 // The range has not been changed
174 m_firstVisibleIndex
= index
;
175 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
177 if (hasPendingRoles() && !m_paused
) {
178 sortAndResolvePendingRoles();
182 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
184 m_maximumVisibleItems
= count
;
187 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
189 if (show
== m_previewShown
) {
193 m_previewShown
= show
;
195 m_clearPreviews
= true;
201 bool KFileItemModelRolesUpdater::previewsShown() const
203 return m_previewShown
;
206 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
208 if (enlarge
!= m_enlargeSmallPreviews
) {
209 m_enlargeSmallPreviews
= enlarge
;
210 if (m_previewShown
) {
216 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
218 return m_enlargeSmallPreviews
;
221 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
223 if (m_enabledPlugins
!= list
) {
224 m_enabledPlugins
= list
;
225 if (m_previewShown
) {
231 void KFileItemModelRolesUpdater::setPaused(bool paused
)
233 if (paused
== m_paused
) {
239 if (hasPendingRoles()) {
240 foreach (KJob
* job
, m_previewJobs
) {
243 Q_ASSERT(m_previewJobs
.isEmpty());
246 const bool resolveAll
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
247 m_previewChangedDuringPausing
||
248 m_rolesChangedDuringPausing
;
250 sortAndResolveAllRoles();
252 sortAndResolvePendingRoles();
255 m_iconSizeChangedDuringPausing
= false;
256 m_previewChangedDuringPausing
= false;
257 m_rolesChangedDuringPausing
= false;
261 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
263 if (m_roles
!= roles
) {
267 // Check whether there is at least one role that must be resolved
268 // with the help of Nepomuk. If this is the case, a (quite expensive)
269 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
270 // the role gets watched for changes.
271 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
272 bool hasNepomukRole
= false;
273 QSetIterator
<QByteArray
> it(roles
);
274 while (it
.hasNext()) {
275 const QByteArray
& role
= it
.next();
276 if (rolesProvider
.roles().contains(role
)) {
277 hasNepomukRole
= true;
282 if (hasNepomukRole
&& !m_nepomukResourceWatcher
) {
283 Q_ASSERT(m_nepomukUriItems
.isEmpty());
285 m_nepomukResourceWatcher
= new Nepomuk2::ResourceWatcher(this);
286 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariantList
,QVariantList
)),
287 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
)));
288 } else if (!hasNepomukRole
&& m_nepomukResourceWatcher
) {
289 delete m_nepomukResourceWatcher
;
290 m_nepomukResourceWatcher
= 0;
291 m_nepomukUriItems
.clear();
295 updateSortProgress();
298 m_rolesChangedDuringPausing
= true;
300 sortAndResolveAllRoles();
305 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
310 bool KFileItemModelRolesUpdater::isPaused() const
315 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
317 return m_enabledPlugins
;
320 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
322 startUpdating(itemRanges
);
325 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
327 Q_UNUSED(itemRanges
);
329 const bool allItemsRemoved
= (m_model
->count() == 0);
331 if (!m_watchedDirs
.isEmpty()) {
332 // Don't let KDirWatch watch for removed items
333 if (allItemsRemoved
) {
334 foreach (const QString
& path
, m_watchedDirs
) {
335 m_dirWatcher
->removeDir(path
);
337 m_watchedDirs
.clear();
339 QMutableSetIterator
<QString
> it(m_watchedDirs
);
340 while (it
.hasNext()) {
341 const QString
& path
= it
.next();
342 if (m_model
->index(KUrl(path
)) < 0) {
343 m_dirWatcher
->removeDir(path
);
351 if (m_nepomukResourceWatcher
) {
352 // Don't let the ResourceWatcher watch for removed items
353 if (allItemsRemoved
) {
354 m_nepomukResourceWatcher
->setResources(QList
<Nepomuk2::Resource
>());
355 m_nepomukResourceWatcher
->stop();
356 m_nepomukUriItems
.clear();
358 QList
<Nepomuk2::Resource
> newResources
;
359 const QList
<Nepomuk2::Resource
> oldResources
= m_nepomukResourceWatcher
->resources();
360 foreach (const Nepomuk2::Resource
& resource
, oldResources
) {
361 const QUrl uri
= resource
.uri();
362 const KUrl itemUrl
= m_nepomukUriItems
.value(uri
);
363 if (m_model
->index(itemUrl
) >= 0) {
364 newResources
.append(resource
);
366 m_nepomukUriItems
.remove(uri
);
369 m_nepomukResourceWatcher
->setResources(newResources
);
370 if (newResources
.isEmpty()) {
371 Q_ASSERT(m_nepomukUriItems
.isEmpty());
372 m_nepomukResourceWatcher
->stop();
378 m_firstVisibleIndex
= 0;
379 m_lastVisibleIndex
= -1;
380 if (!hasPendingRoles()) {
384 if (allItemsRemoved
) {
385 // Most probably a directory change is done. Clear all pending items
386 // and also kill all ongoing preview-jobs.
389 m_changedItems
.clear();
390 m_changedItemsTimer
->stop();
392 // Remove all items from m_pendingVisibleItems and m_pendingInvisibleItems
393 // that are not part of the model anymore. The items from m_changedItems
394 // don't need to be handled here, removed items are just skipped in
395 // resolveChangedItems().
396 for (int i
= 0; i
<= 1; ++i
) {
397 QSet
<KFileItem
>& pendingItems
= (i
== 0) ? m_pendingVisibleItems
: m_pendingInvisibleItems
;
398 QMutableSetIterator
<KFileItem
> it(pendingItems
);
399 while (it
.hasNext()) {
400 const KFileItem item
= it
.next();
401 if (m_model
->index(item
) < 0) {
402 pendingItems
.remove(item
);
409 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
410 const QSet
<QByteArray
>& roles
)
414 if (m_changedItemsTimer
->isActive()) {
415 // A call of slotItemsChanged() has been done recently. Postpone the resolving
416 // of the roles until the timer has exceeded.
417 foreach (const KItemRange
& itemRange
, itemRanges
) {
418 int index
= itemRange
.index
;
419 for (int count
= itemRange
.count
; count
> 0; --count
) {
420 m_changedItems
.insert(m_model
->fileItem(index
));
425 // No call of slotItemsChanged() has been done recently, resolve the roles now.
426 startUpdating(itemRanges
);
428 m_changedItemsTimer
->start();
431 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
432 const QByteArray
& previous
)
436 updateSortProgress();
439 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
441 m_pendingVisibleItems
.remove(item
);
442 m_pendingInvisibleItems
.remove(item
);
444 const int index
= m_model
->index(item
);
449 QPixmap scaledPixmap
= pixmap
;
451 const QString mimeType
= item
.mimetype();
452 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
453 const QString mimeTypeGroup
= mimeType
.left(slashIndex
);
454 if (mimeTypeGroup
== QLatin1String("image")) {
455 if (m_enlargeSmallPreviews
) {
456 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
458 // Assure that small previews don't get enlarged. Instead they
459 // should be shown centered within the frame.
460 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
461 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
462 scaledPixmap
.height() < contentSize
.height();
463 if (enlargingRequired
) {
464 QSize frameSize
= scaledPixmap
.size();
465 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
467 QPixmap
largeFrame(frameSize
);
468 largeFrame
.fill(Qt::transparent
);
470 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
472 QPainter
painter(&largeFrame
);
473 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width()) / 2,
474 (largeFrame
.height() - scaledPixmap
.height()) / 2,
476 scaledPixmap
= largeFrame
;
478 // The image must be shrinked as it is too large to fit into
479 // the available icon size
480 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
484 KPixmapModifier::scale(scaledPixmap
, m_iconSize
);
487 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
488 data
.insert("iconPixmap", scaledPixmap
);
490 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
491 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
492 m_model
->setData(index
, data
);
493 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
494 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
496 applySortProgressToModel();
499 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
501 m_pendingVisibleItems
.remove(item
);
502 m_pendingInvisibleItems
.remove(item
);
504 const bool clearPreviews
= m_clearPreviews
;
505 m_clearPreviews
= true;
506 applyResolvedRoles(item
, ResolveAll
);
507 m_clearPreviews
= clearPreviews
;
509 applySortProgressToModel();
512 void KFileItemModelRolesUpdater::slotPreviewJobFinished(KJob
* job
)
514 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
515 kDebug() << "Preview job finished. Pending visible:" << m_pendingVisibleItems
.count() << "invisible:" << m_pendingInvisibleItems
.count();
518 m_previewJobs
.removeOne(job
);
519 if (!m_previewJobs
.isEmpty() || !hasPendingRoles()) {
523 const KFileItemList visibleItems
= sortedItems(m_pendingVisibleItems
);
524 startPreviewJob(visibleItems
+ m_pendingInvisibleItems
.toList());
527 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
533 if (m_previewShown
) {
534 // The preview has been turned on since the last run. Skip
535 // resolving further pending roles as this is done as soon
536 // as a preview has been received.
540 int resolvedCount
= 0;
541 bool changed
= false;
542 for (int i
= 0; i
<= 1; ++i
) {
543 QSet
<KFileItem
>& pendingItems
= (i
== 0) ? m_pendingVisibleItems
: m_pendingInvisibleItems
;
544 QSet
<KFileItem
>::iterator it
= pendingItems
.begin();
545 while (it
!= pendingItems
.end() && !changed
&& resolvedCount
< MaxResolveItemsCount
) {
546 changed
= applyResolvedRoles(*it
, ResolveAll
);
547 it
= pendingItems
.erase(it
);
552 if (hasPendingRoles()) {
553 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
555 m_clearPreviews
= false;
558 applySortProgressToModel();
560 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
561 static int callCount
= 0;
563 if (callCount
% 100 == 0) {
564 kDebug() << "Remaining visible roles to resolve:" << m_pendingVisibleItems
.count()
565 << "invisible:" << m_pendingInvisibleItems
.count();
570 void KFileItemModelRolesUpdater::resolveChangedItems()
572 if (m_changedItems
.isEmpty()) {
576 KItemRangeList itemRanges
;
578 QSetIterator
<KFileItem
> it(m_changedItems
);
579 while (it
.hasNext()) {
580 const KFileItem
& item
= it
.next();
581 const int index
= m_model
->index(item
);
583 itemRanges
.append(KItemRange(index
, 1));
586 m_changedItems
.clear();
588 startUpdating(itemRanges
);
591 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource
& resource
)
594 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.uri());
595 const KFileItem item
= m_model
->fileItem(itemUrl
);
598 // itemUrl is not in the model anymore, probably because
599 // the corresponding file has been deleted in the meantime.
603 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
605 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
606 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
607 while (it
.hasNext()) {
609 data
.insert(it
.key(), it
.value());
612 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
613 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
614 const int index
= m_model
->index(item
);
615 m_model
->setData(index
, data
);
616 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
617 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
625 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
627 const bool getSizeRole
= m_roles
.contains("size");
628 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
630 if (getSizeRole
|| getIsExpandableRole
) {
631 const int index
= m_model
->index(KUrl(path
));
633 QHash
<QByteArray
, QVariant
> data
;
635 const int count
= subItemsCount(path
);
637 data
.insert("size", count
);
639 if (getIsExpandableRole
) {
640 data
.insert("isExpandable", count
> 0);
643 m_model
->setData(index
, data
);
648 void KFileItemModelRolesUpdater::startUpdating(const KItemRangeList
& itemRanges
)
650 // If no valid index range is given assume that all items are visible.
651 // A cleanup will be done later as soon as the index range has been set.
652 const bool hasValidIndexRange
= (m_lastVisibleIndex
>= 0);
654 if (hasValidIndexRange
) {
655 // Move all current pending visible items that are not visible anymore
656 // to the pending invisible items.
657 QSet
<KFileItem
>::iterator it
= m_pendingVisibleItems
.begin();
658 while (it
!= m_pendingVisibleItems
.end()) {
659 const KFileItem item
= *it
;
660 const int index
= m_model
->index(item
);
661 if (index
< m_firstVisibleIndex
|| index
> m_lastVisibleIndex
) {
662 it
= m_pendingVisibleItems
.erase(it
);
663 m_pendingInvisibleItems
.insert(item
);
672 foreach (const KItemRange
& range
, itemRanges
) {
673 rangesCount
+= range
.count
;
675 // Add the inserted items to the pending visible and invisible items
676 const int lastIndex
= range
.index
+ range
.count
- 1;
677 for (int i
= range
.index
; i
<= lastIndex
; ++i
) {
678 const KFileItem item
= m_model
->fileItem(i
);
680 if (hasValidIndexRange
) {
681 visible
= (i
>= m_firstVisibleIndex
&& i
<= m_lastVisibleIndex
);
683 // If the view has not informed us about the visible range yet,
684 // just assume that the first items are visible.
685 visible
= (i
< m_maximumVisibleItems
);
689 m_pendingVisibleItems
.insert(item
);
691 m_pendingInvisibleItems
.insert(item
);
696 resolvePendingRoles();
699 void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList
& items
)
701 if (items
.isEmpty() || m_paused
) {
705 // PreviewJob internally caches items always with the size of
706 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
707 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
708 // do a downscaling anyhow because of the frame, so in this case only the provided
709 // cache sizes are requested.
710 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
711 ? QSize(256, 256) : QSize(128, 128);
713 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
714 // worst case) might block the application for several seconds. To prevent such
715 // a blocking the MIME-type of the items will determined until the MaxBlockTimeout
716 // has been reached and only those items will get passed. As soon as the MIME-type
717 // has been resolved once KIO::PreviewJob() can already access the resolved
718 // MIME-type in a fast way.
722 KFileItemList itemSubSet
;
723 const int count
= items
.count();
724 itemSubSet
.reserve(count
);
725 for (int i
= 0; i
< count
; ++i
) {
726 KFileItem item
= items
.at(i
);
727 item
.determineMimeType();
728 itemSubSet
.append(item
);
729 if (timer
.elapsed() > MaxBlockTimeout
) {
730 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
731 kDebug() << "Maximum time of" << MaxBlockTimeout
<< "ms exceeded, creating only previews for"
732 << (i
+ 1) << "items," << (items
.count() - (i
+ 1)) << "will be resolved later";
737 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
738 job
->setIgnoreMaximumSize(items
.first().isLocalFile());
740 job
->ui()->setWindow(qApp
->activeWindow());
743 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
744 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
745 connect(job
, SIGNAL(failed(KFileItem
)),
746 this, SLOT(slotPreviewFailed(KFileItem
)));
747 connect(job
, SIGNAL(finished(KJob
*)),
748 this, SLOT(slotPreviewJobFinished(KJob
*)));
750 m_previewJobs
.append(job
);
754 bool KFileItemModelRolesUpdater::hasPendingRoles() const
756 return !m_pendingVisibleItems
.isEmpty() || !m_pendingInvisibleItems
.isEmpty();
759 void KFileItemModelRolesUpdater::resolvePendingRoles()
761 int resolvedCount
= 0;
763 bool hasSlowRoles
= m_previewShown
;
765 QSetIterator
<QByteArray
> it(m_roles
);
766 while (it
.hasNext()) {
767 if (m_resolvableRoles
.contains(it
.next())) {
774 const ResolveHint resolveHint
= hasSlowRoles
? ResolveFast
: ResolveAll
;
776 // Resolving the MIME type can be expensive. Assure that not more than MaxBlockTimeout ms are
777 // spend for resolving them synchronously. Usually this is more than enough to determine
778 // all visible items, but there are corner cases where this limit gets easily exceeded.
782 // Resolve the MIME type of all visible items
783 QSet
<KFileItem
>::iterator visibleIt
= m_pendingVisibleItems
.begin();
784 while (visibleIt
!= m_pendingVisibleItems
.end()) {
785 const KFileItem item
= *visibleIt
;
787 Q_ASSERT(!m_pendingInvisibleItems
.contains(item
));
788 // All roles will be resolved by applyResolvedRoles()
789 visibleIt
= m_pendingVisibleItems
.erase(visibleIt
);
793 applyResolvedRoles(item
, resolveHint
);
796 if (timer
.elapsed() > MaxBlockTimeout
) {
801 // Resolve the MIME type of the invisible items at least until the timeout
802 // has been exceeded or the maximum number of items has been reached
803 KFileItemList invisibleItems
;
804 if (m_lastVisibleIndex
>= 0) {
805 // The visible range is valid, don't care about the order how the MIME
806 // type of invisible items get resolved
807 invisibleItems
= m_pendingInvisibleItems
.toList();
809 // The visible range is temporary invalid (e.g. happens when loading
810 // a directory) so take care to sort the currently invisible items where
811 // a part will get visible later
812 invisibleItems
= sortedItems(m_pendingInvisibleItems
);
816 while (resolvedCount
< MaxResolveItemsCount
&& index
< invisibleItems
.count() && timer
.elapsed() <= MaxBlockTimeout
) {
817 const KFileItem item
= invisibleItems
.at(index
);
818 applyResolvedRoles(item
, resolveHint
);
821 // All roles have been resolved already by applyResolvedRoles()
822 m_pendingInvisibleItems
.remove(item
);
828 if (m_previewShown
) {
829 KFileItemList items
= sortedItems(m_pendingVisibleItems
);
830 items
+= invisibleItems
;
831 startPreviewJob(items
);
833 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
836 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
837 if (timer
.elapsed() > MaxBlockTimeout
) {
838 kDebug() << "Maximum time of" << MaxBlockTimeout
839 << "ms exceeded, skipping items... Remaining visible:" << m_pendingVisibleItems
.count()
840 << "invisible:" << m_pendingInvisibleItems
.count();
842 kDebug() << "[TIME] Resolved pending roles:" << timer
.elapsed();
845 applySortProgressToModel();
848 void KFileItemModelRolesUpdater::resetPendingRoles()
850 m_pendingVisibleItems
.clear();
851 m_pendingInvisibleItems
.clear();
853 foreach (KJob
* job
, m_previewJobs
) {
856 Q_ASSERT(m_previewJobs
.isEmpty());
859 void KFileItemModelRolesUpdater::sortAndResolveAllRoles()
866 Q_ASSERT(m_pendingVisibleItems
.isEmpty());
867 Q_ASSERT(m_pendingInvisibleItems
.isEmpty());
869 if (m_model
->count() == 0) {
873 // Determine all visible items
874 Q_ASSERT(m_firstVisibleIndex
>= 0);
875 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
876 const KFileItem item
= m_model
->fileItem(i
);
877 if (!item
.isNull()) {
878 m_pendingVisibleItems
.insert(item
);
882 // Determine all invisible items
883 for (int i
= 0; i
< m_firstVisibleIndex
; ++i
) {
884 const KFileItem item
= m_model
->fileItem(i
);
885 if (!item
.isNull()) {
886 m_pendingInvisibleItems
.insert(item
);
889 const int count
= m_model
->count();
890 for (int i
= m_lastVisibleIndex
+ 1; i
< count
; ++i
) {
891 const KFileItem item
= m_model
->fileItem(i
);
892 if (!item
.isNull()) {
893 m_pendingInvisibleItems
.insert(item
);
897 resolvePendingRoles();
900 void KFileItemModelRolesUpdater::sortAndResolvePendingRoles()
903 if (m_model
->count() == 0) {
907 // If no valid index range is given assume that all items are visible.
908 // A cleanup will be done later as soon as the index range has been set.
909 const bool hasValidIndexRange
= (m_lastVisibleIndex
>= 0);
911 // Trigger a preview generation of all pending items. Assure that the visible
912 // pending items get generated first.
914 // Step 1: Check if any items in m_pendingVisibleItems are not visible any more
915 // and move them to m_pendingInvisibleItems.
916 QSet
<KFileItem
>::iterator itVisible
= m_pendingVisibleItems
.begin();
917 while (itVisible
!= m_pendingVisibleItems
.end()) {
918 const KFileItem item
= *itVisible
;
920 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
924 const int index
= m_model
->index(item
);
925 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
928 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
929 m_pendingInvisibleItems
.insert(item
);
933 // Step 2: Check if any items in m_pendingInvisibleItems have become visible
934 // and move them to m_pendingVisibleItems.
935 QSet
<KFileItem
>::iterator itInvisible
= m_pendingInvisibleItems
.begin();
936 while (itInvisible
!= m_pendingInvisibleItems
.end()) {
937 const KFileItem item
= *itInvisible
;
939 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
943 const int index
= m_model
->index(item
);
944 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
945 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
946 m_pendingVisibleItems
.insert(item
);
952 resolvePendingRoles();
955 void KFileItemModelRolesUpdater::applySortProgressToModel()
957 if (m_sortingProgress
< 0) {
961 // Inform the model about the progress of the resolved items,
962 // so that it can give an indication when the sorting has been finished.
963 const int resolvedCount
= m_model
->count()
964 - m_pendingVisibleItems
.count()
965 - m_pendingInvisibleItems
.count();
966 if (resolvedCount
> 0) {
967 m_model
->emitSortProgress(resolvedCount
);
968 if (resolvedCount
== m_model
->count()) {
969 m_sortingProgress
= -1;
974 void KFileItemModelRolesUpdater::updateSortProgress()
976 const QByteArray sortRole
= m_model
->sortRole();
978 // Optimization if the sorting is done by type: In case if all MIME-types
979 // are known, the types have been resolved already by KFileItemModel and
980 // no sort-progress feedback is required.
981 const bool showProgress
= (sortRole
== "type")
982 ? hasUnknownMimeTypes()
983 : m_resolvableRoles
.contains(sortRole
);
985 if (m_sortingProgress
>= 0) {
986 // Mark the current sorting as finished
987 m_model
->emitSortProgress(m_model
->count());
989 m_sortingProgress
= showProgress
? 0 : -1;
992 bool KFileItemModelRolesUpdater::hasUnknownMimeTypes() const
994 const int count
= m_model
->count();
995 for (int i
= 0; i
< count
; ++i
) {
996 const KFileItem item
= m_model
->fileItem(i
);
997 if (!item
.isMimeTypeKnown()) {
1005 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1007 if (item
.isNull()) {
1011 const bool resolveAll
= (hint
== ResolveAll
);
1013 bool mimeTypeChanged
= false;
1014 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1015 item
.determineMimeType();
1016 mimeTypeChanged
= true;
1019 if (mimeTypeChanged
|| resolveAll
|| m_clearPreviews
) {
1020 const int index
= m_model
->index(item
);
1025 QHash
<QByteArray
, QVariant
> data
;
1027 data
= rolesData(item
);
1030 data
.insert("iconName", item
.iconName());
1032 if (m_clearPreviews
) {
1033 data
.insert("iconPixmap", QPixmap());
1036 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1037 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1038 m_model
->setData(index
, data
);
1039 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1040 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1047 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1049 QHash
<QByteArray
, QVariant
> data
;
1051 const bool getSizeRole
= m_roles
.contains("size");
1052 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1054 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1055 if (item
.isLocalFile()) {
1056 const QString path
= item
.localPath();
1057 const int count
= subItemsCount(path
);
1059 data
.insert("size", count
);
1061 if (getIsExpandableRole
) {
1062 data
.insert("isExpandable", count
> 0);
1065 if (!m_dirWatcher
->contains(path
)) {
1066 m_dirWatcher
->addDir(path
);
1067 m_watchedDirs
.insert(path
);
1069 } else if (getSizeRole
) {
1070 data
.insert("size", -1); // -1 indicates an unknown number of items
1074 if (m_roles
.contains("type")) {
1075 data
.insert("type", item
.mimeComment());
1078 data
.insert("iconOverlays", item
.overlays());
1081 if (m_nepomukResourceWatcher
) {
1082 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1083 Nepomuk2::Resource
resource(item
.nepomukUri());
1084 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1085 while (it
.hasNext()) {
1087 data
.insert(it
.key(), it
.value());
1090 QUrl uri
= resource
.uri();
1091 if (uri
.isEmpty()) {
1092 // TODO: Is there another way to explicitly create a resource?
1093 // We need a resource to be able to track it for changes.
1094 resource
.setRating(0);
1095 uri
= resource
.uri();
1097 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1098 m_nepomukResourceWatcher
->addResource(resource
);
1100 if (m_nepomukUriItems
.isEmpty()) {
1101 m_nepomukResourceWatcher
->start();
1104 m_nepomukUriItems
.insert(uri
, item
.url());
1112 KFileItemList
KFileItemModelRolesUpdater::sortedItems(const QSet
<KFileItem
>& items
) const
1114 KFileItemList itemList
;
1115 if (items
.isEmpty()) {
1119 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1120 QElapsedTimer timer
;
1125 indexes
.reserve(items
.count());
1127 QSetIterator
<KFileItem
> it(items
);
1128 while (it
.hasNext()) {
1129 const KFileItem item
= it
.next();
1130 const int index
= m_model
->index(item
);
1132 indexes
.append(index
);
1137 itemList
.reserve(items
.count());
1138 foreach (int index
, indexes
) {
1139 itemList
.append(m_model
->fileItem(index
));
1142 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1143 kDebug() << "[TIME] Sorting of items:" << timer
.elapsed();
1148 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1150 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1151 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1155 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1156 if (countHiddenFiles
) {
1157 filters
|= QDir::Hidden
;
1159 if (showFoldersOnly
) {
1160 filters
|= QDir::Dirs
;
1162 filters
|= QDir::AllEntries
;
1164 return dir
.entryList(filters
).count();
1166 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1167 // Copyright (C) 2006 David Faure <faure@kde.org>
1170 DIR* dir
= ::opendir(QFile::encodeName(path
));
1171 if (dir
) { // krazy:exclude=syscalls
1173 struct dirent
*dirEntry
= 0;
1174 while ((dirEntry
= ::readdir(dir
))) {
1175 if (dirEntry
->d_name
[0] == '.') {
1176 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1177 // Skip "." or hidden files
1180 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1186 // If only directories are counted, consider an unknown file type and links also
1187 // as directory instead of trying to do an expensive stat()
1188 // (see bugs 292642 and 299997).
1189 const bool countEntry
= !showFoldersOnly
||
1190 dirEntry
->d_type
== DT_DIR
||
1191 dirEntry
->d_type
== DT_LNK
||
1192 dirEntry
->d_type
== DT_UNKNOWN
;
1203 void KFileItemModelRolesUpdater::updateAllPreviews()
1206 m_previewChangedDuringPausing
= true;
1208 sortAndResolveAllRoles();
1212 #include "kfileitemmodelrolesupdater.moc"