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),
84 m_pendingVisibleItems(),
85 m_pendingInvisibleItems(),
87 m_changedItemsTimer(0),
92 , m_nepomukResourceWatcher(0),
98 const KConfigGroup
globalConfig(KGlobal::config(), "PreviewSettings");
99 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList()
100 << "directorythumbnail"
104 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
105 this, SLOT(slotItemsInserted(KItemRangeList
)));
106 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
107 this, SLOT(slotItemsRemoved(KItemRangeList
)));
108 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
109 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
110 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
111 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
113 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
114 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
115 m_changedItemsTimer
= new QTimer(this);
116 m_changedItemsTimer
->setInterval(1000);
117 m_changedItemsTimer
->setSingleShot(true);
118 connect(m_changedItemsTimer
, SIGNAL(timeout()), this, SLOT(resolveChangedItems()));
120 m_resolvableRoles
.insert("size");
121 m_resolvableRoles
.insert("type");
122 m_resolvableRoles
.insert("isExpandable");
124 m_resolvableRoles
+= KNepomukRolesProvider::instance().roles();
127 // When folders are expandable or the item-count is shown for folders, it is necessary
128 // to watch the number of items of the sub-folder to be able to react on changes.
129 m_dirWatcher
= new KDirWatch(this);
130 connect(m_dirWatcher
, SIGNAL(dirty(QString
)), this, SLOT(slotDirWatchDirty(QString
)));
133 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
138 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
140 if (size
!= m_iconSize
) {
143 m_iconSizeChangedDuringPausing
= true;
144 } else if (m_previewShown
) {
145 // An icon size change requires the regenerating of
147 sortAndResolveAllRoles();
149 sortAndResolvePendingRoles();
154 QSize
KFileItemModelRolesUpdater::iconSize() const
159 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
168 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
169 // The range has not been changed
173 m_firstVisibleIndex
= index
;
174 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
176 if (hasPendingRoles() && !m_paused
) {
177 sortAndResolvePendingRoles();
181 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
183 if (show
== m_previewShown
) {
187 m_previewShown
= show
;
189 m_clearPreviews
= true;
195 bool KFileItemModelRolesUpdater::previewsShown() const
197 return m_previewShown
;
200 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
202 if (enlarge
!= m_enlargeSmallPreviews
) {
203 m_enlargeSmallPreviews
= enlarge
;
204 if (m_previewShown
) {
210 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
212 return m_enlargeSmallPreviews
;
215 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
217 if (m_enabledPlugins
!= list
) {
218 m_enabledPlugins
= list
;
219 if (m_previewShown
) {
225 void KFileItemModelRolesUpdater::setPaused(bool paused
)
227 if (paused
== m_paused
) {
233 if (hasPendingRoles()) {
234 foreach (KJob
* job
, m_previewJobs
) {
237 Q_ASSERT(m_previewJobs
.isEmpty());
240 const bool resolveAll
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
241 m_previewChangedDuringPausing
||
242 m_rolesChangedDuringPausing
;
244 sortAndResolveAllRoles();
246 sortAndResolvePendingRoles();
249 m_iconSizeChangedDuringPausing
= false;
250 m_previewChangedDuringPausing
= false;
251 m_rolesChangedDuringPausing
= false;
255 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
257 if (m_roles
!= roles
) {
261 // Check whether there is at least one role that must be resolved
262 // with the help of Nepomuk. If this is the case, a (quite expensive)
263 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
264 // the role gets watched for changes.
265 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
266 bool hasNepomukRole
= false;
267 QSetIterator
<QByteArray
> it(roles
);
268 while (it
.hasNext()) {
269 const QByteArray
& role
= it
.next();
270 if (rolesProvider
.roles().contains(role
)) {
271 hasNepomukRole
= true;
276 if (hasNepomukRole
&& !m_nepomukResourceWatcher
) {
277 Q_ASSERT(m_nepomukUriItems
.isEmpty());
279 m_nepomukResourceWatcher
= new Nepomuk2::ResourceWatcher(this);
280 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariantList
,QVariantList
)),
281 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
)));
282 connect(m_nepomukResourceWatcher
, SIGNAL(propertyRemoved(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariant
)),
283 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
)));
284 connect(m_nepomukResourceWatcher
, SIGNAL(propertyAdded(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariant
)),
285 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
)));
286 connect(m_nepomukResourceWatcher
, SIGNAL(resourceCreated(Nepomuk2::Resource
,QList
<QUrl
>)),
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
);
679 if (!hasValidIndexRange
|| (i
>= m_firstVisibleIndex
&& i
<= m_lastVisibleIndex
)) {
680 m_pendingVisibleItems
.insert(item
);
682 m_pendingInvisibleItems
.insert(item
);
687 resolvePendingRoles();
690 void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList
& items
)
692 if (items
.isEmpty() || m_paused
) {
696 // PreviewJob internally caches items always with the size of
697 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
698 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
699 // do a downscaling anyhow because of the frame, so in this case only the provided
700 // cache sizes are requested.
701 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
702 ? QSize(256, 256) : QSize(128, 128);
704 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
705 // worst case) might block the application for several seconds. To prevent such
706 // a blocking the MIME-type of the items will determined until the MaxBlockTimeout
707 // has been reached and only those items will get passed. As soon as the MIME-type
708 // has been resolved once KIO::PreviewJob() can already access the resolved
709 // MIME-type in a fast way.
713 KFileItemList itemSubSet
;
714 const int count
= items
.count();
715 itemSubSet
.reserve(count
);
716 for (int i
= 0; i
< count
; ++i
) {
717 KFileItem item
= items
.at(i
);
718 item
.determineMimeType();
719 itemSubSet
.append(item
);
720 if (timer
.elapsed() > MaxBlockTimeout
) {
721 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
722 kDebug() << "Maximum time of" << MaxBlockTimeout
<< "ms exceeded, creating only previews for"
723 << (i
+ 1) << "items," << (items
.count() - (i
+ 1)) << "will be resolved later";
728 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
729 job
->setIgnoreMaximumSize(items
.first().isLocalFile());
731 job
->ui()->setWindow(qApp
->activeWindow());
734 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
735 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
736 connect(job
, SIGNAL(failed(KFileItem
)),
737 this, SLOT(slotPreviewFailed(KFileItem
)));
738 connect(job
, SIGNAL(finished(KJob
*)),
739 this, SLOT(slotPreviewJobFinished(KJob
*)));
741 m_previewJobs
.append(job
);
745 bool KFileItemModelRolesUpdater::hasPendingRoles() const
747 return !m_pendingVisibleItems
.isEmpty() || !m_pendingInvisibleItems
.isEmpty();
750 void KFileItemModelRolesUpdater::resolvePendingRoles()
752 int resolvedCount
= 0;
754 bool hasSlowRoles
= m_previewShown
;
756 QSetIterator
<QByteArray
> it(m_roles
);
757 while (it
.hasNext()) {
758 if (m_resolvableRoles
.contains(it
.next())) {
765 const ResolveHint resolveHint
= hasSlowRoles
? ResolveFast
: ResolveAll
;
767 // Resolving the MIME type can be expensive. Assure that not more than MaxBlockTimeout ms are
768 // spend for resolving them synchronously. Usually this is more than enough to determine
769 // all visible items, but there are corner cases where this limit gets easily exceeded.
773 // Resolve the MIME type of all visible items
774 QSet
<KFileItem
>::iterator visibleIt
= m_pendingVisibleItems
.begin();
775 while (visibleIt
!= m_pendingVisibleItems
.end()) {
776 const KFileItem item
= *visibleIt
;
778 Q_ASSERT(!m_pendingInvisibleItems
.contains(item
));
779 // All roles will be resolved by applyResolvedRoles()
780 visibleIt
= m_pendingVisibleItems
.erase(visibleIt
);
784 applyResolvedRoles(item
, resolveHint
);
787 if (timer
.elapsed() > MaxBlockTimeout
) {
792 // Resolve the MIME type of the invisible items at least until the timeout
793 // has been exceeded or the maximum number of items has been reached
794 KFileItemList invisibleItems
;
795 if (m_lastVisibleIndex
>= 0) {
796 // The visible range is valid, don't care about the order how the MIME
797 // type of invisible items get resolved
798 invisibleItems
= m_pendingInvisibleItems
.toList();
800 // The visible range is temporary invalid (e.g. happens when loading
801 // a directory) so take care to sort the currently invisible items where
802 // a part will get visible later
803 invisibleItems
= sortedItems(m_pendingInvisibleItems
);
807 while (resolvedCount
< MaxResolveItemsCount
&& index
< invisibleItems
.count() && timer
.elapsed() <= MaxBlockTimeout
) {
808 const KFileItem item
= invisibleItems
.at(index
);
809 applyResolvedRoles(item
, resolveHint
);
812 // All roles have been resolved already by applyResolvedRoles()
813 m_pendingInvisibleItems
.remove(item
);
819 if (m_previewShown
) {
820 KFileItemList items
= sortedItems(m_pendingVisibleItems
);
821 items
+= invisibleItems
;
822 startPreviewJob(items
);
824 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
827 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
828 if (timer
.elapsed() > MaxBlockTimeout
) {
829 kDebug() << "Maximum time of" << MaxBlockTimeout
830 << "ms exceeded, skipping items... Remaining visible:" << m_pendingVisibleItems
.count()
831 << "invisible:" << m_pendingInvisibleItems
.count();
833 kDebug() << "[TIME] Resolved pending roles:" << timer
.elapsed();
836 applySortProgressToModel();
839 void KFileItemModelRolesUpdater::resetPendingRoles()
841 m_pendingVisibleItems
.clear();
842 m_pendingInvisibleItems
.clear();
844 foreach (KJob
* job
, m_previewJobs
) {
847 Q_ASSERT(m_previewJobs
.isEmpty());
850 void KFileItemModelRolesUpdater::sortAndResolveAllRoles()
857 Q_ASSERT(m_pendingVisibleItems
.isEmpty());
858 Q_ASSERT(m_pendingInvisibleItems
.isEmpty());
860 if (m_model
->count() == 0) {
864 // Determine all visible items
865 Q_ASSERT(m_firstVisibleIndex
>= 0);
866 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
867 const KFileItem item
= m_model
->fileItem(i
);
868 if (!item
.isNull()) {
869 m_pendingVisibleItems
.insert(item
);
873 // Determine all invisible items
874 for (int i
= 0; i
< m_firstVisibleIndex
; ++i
) {
875 const KFileItem item
= m_model
->fileItem(i
);
876 if (!item
.isNull()) {
877 m_pendingInvisibleItems
.insert(item
);
880 const int count
= m_model
->count();
881 for (int i
= m_lastVisibleIndex
+ 1; i
< count
; ++i
) {
882 const KFileItem item
= m_model
->fileItem(i
);
883 if (!item
.isNull()) {
884 m_pendingInvisibleItems
.insert(item
);
888 resolvePendingRoles();
891 void KFileItemModelRolesUpdater::sortAndResolvePendingRoles()
894 if (m_model
->count() == 0) {
898 // If no valid index range is given assume that all items are visible.
899 // A cleanup will be done later as soon as the index range has been set.
900 const bool hasValidIndexRange
= (m_lastVisibleIndex
>= 0);
902 // Trigger a preview generation of all pending items. Assure that the visible
903 // pending items get generated first.
905 // Step 1: Check if any items in m_pendingVisibleItems are not visible any more
906 // and move them to m_pendingInvisibleItems.
907 QSet
<KFileItem
>::iterator itVisible
= m_pendingVisibleItems
.begin();
908 while (itVisible
!= m_pendingVisibleItems
.end()) {
909 const KFileItem item
= *itVisible
;
911 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
915 const int index
= m_model
->index(item
);
916 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
919 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
920 m_pendingInvisibleItems
.insert(item
);
924 // Step 2: Check if any items in m_pendingInvisibleItems have become visible
925 // and move them to m_pendingVisibleItems.
926 QSet
<KFileItem
>::iterator itInvisible
= m_pendingInvisibleItems
.begin();
927 while (itInvisible
!= m_pendingInvisibleItems
.end()) {
928 const KFileItem item
= *itInvisible
;
930 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
934 const int index
= m_model
->index(item
);
935 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
936 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
937 m_pendingVisibleItems
.insert(item
);
943 resolvePendingRoles();
946 void KFileItemModelRolesUpdater::applySortProgressToModel()
948 if (m_sortingProgress
< 0) {
952 // Inform the model about the progress of the resolved items,
953 // so that it can give an indication when the sorting has been finished.
954 const int resolvedCount
= m_model
->count()
955 - m_pendingVisibleItems
.count()
956 - m_pendingInvisibleItems
.count();
957 if (resolvedCount
> 0) {
958 m_model
->emitSortProgress(resolvedCount
);
959 if (resolvedCount
== m_model
->count()) {
960 m_sortingProgress
= -1;
965 void KFileItemModelRolesUpdater::updateSortProgress()
967 const QByteArray sortRole
= m_model
->sortRole();
969 // Optimization if the sorting is done by type: In case if all MIME-types
970 // are known, the types have been resolved already by KFileItemModel and
971 // no sort-progress feedback is required.
972 const bool showProgress
= (sortRole
== "type")
973 ? hasUnknownMimeTypes()
974 : m_resolvableRoles
.contains(sortRole
);
976 if (m_sortingProgress
>= 0) {
977 // Mark the current sorting as finished
978 m_model
->emitSortProgress(m_model
->count());
980 m_sortingProgress
= showProgress
? 0 : -1;
983 bool KFileItemModelRolesUpdater::hasUnknownMimeTypes() const
985 const int count
= m_model
->count();
986 for (int i
= 0; i
< count
; ++i
) {
987 const KFileItem item
= m_model
->fileItem(i
);
988 if (!item
.isMimeTypeKnown()) {
996 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1002 const bool resolveAll
= (hint
== ResolveAll
);
1004 bool mimeTypeChanged
= false;
1005 if (!item
.isMimeTypeKnown()) {
1006 item
.determineMimeType();
1007 mimeTypeChanged
= true;
1010 if (mimeTypeChanged
|| resolveAll
|| m_clearPreviews
) {
1011 const int index
= m_model
->index(item
);
1016 QHash
<QByteArray
, QVariant
> data
;
1018 data
= rolesData(item
);
1021 data
.insert("iconName", item
.iconName());
1023 if (m_clearPreviews
) {
1024 data
.insert("iconPixmap", QPixmap());
1027 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1028 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1029 m_model
->setData(index
, data
);
1030 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1031 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1038 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1040 QHash
<QByteArray
, QVariant
> data
;
1042 const bool getSizeRole
= m_roles
.contains("size");
1043 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1045 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1046 if (item
.isLocalFile()) {
1047 const QString path
= item
.localPath();
1048 const int count
= subItemsCount(path
);
1050 data
.insert("size", count
);
1052 if (getIsExpandableRole
) {
1053 data
.insert("isExpandable", count
> 0);
1056 if (!m_dirWatcher
->contains(path
)) {
1057 m_dirWatcher
->addDir(path
);
1058 m_watchedDirs
.insert(path
);
1060 } else if (getSizeRole
) {
1061 data
.insert("size", -1); // -1 indicates an unknown number of items
1065 if (m_roles
.contains("type")) {
1066 data
.insert("type", item
.mimeComment());
1069 data
.insert("iconOverlays", item
.overlays());
1072 if (m_nepomukResourceWatcher
) {
1073 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1074 Nepomuk2::Resource
resource(item
.nepomukUri());
1075 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1076 while (it
.hasNext()) {
1078 data
.insert(it
.key(), it
.value());
1081 QUrl uri
= resource
.uri();
1082 if (uri
.isEmpty()) {
1083 // TODO: Is there another way to explicitly create a resource?
1084 // We need a resource to be able to track it for changes.
1085 resource
.setRating(0);
1086 uri
= resource
.uri();
1088 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1089 m_nepomukResourceWatcher
->addResource(resource
);
1091 if (m_nepomukUriItems
.isEmpty()) {
1092 m_nepomukResourceWatcher
->start();
1095 m_nepomukUriItems
.insert(uri
, item
.url());
1103 KFileItemList
KFileItemModelRolesUpdater::sortedItems(const QSet
<KFileItem
>& items
) const
1105 KFileItemList itemList
;
1106 if (items
.isEmpty()) {
1110 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1111 QElapsedTimer timer
;
1116 indexes
.reserve(items
.count());
1118 QSetIterator
<KFileItem
> it(items
);
1119 while (it
.hasNext()) {
1120 const KFileItem item
= it
.next();
1121 const int index
= m_model
->index(item
);
1123 indexes
.append(index
);
1128 itemList
.reserve(items
.count());
1129 foreach (int index
, indexes
) {
1130 itemList
.append(m_model
->fileItem(index
));
1133 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1134 kDebug() << "[TIME] Sorting of items:" << timer
.elapsed();
1139 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1141 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1142 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1146 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1147 if (countHiddenFiles
) {
1148 filters
|= QDir::Hidden
;
1150 if (showFoldersOnly
) {
1151 filters
|= QDir::Dirs
;
1153 filters
|= QDir::AllEntries
;
1155 return dir
.entryList(filters
).count();
1157 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1158 // Copyright (C) 2006 David Faure <faure@kde.org>
1161 DIR* dir
= ::opendir(QFile::encodeName(path
));
1162 if (dir
) { // krazy:exclude=syscalls
1164 struct dirent
*dirEntry
= 0;
1165 while ((dirEntry
= ::readdir(dir
))) {
1166 if (dirEntry
->d_name
[0] == '.') {
1167 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1168 // Skip "." or hidden files
1171 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1177 // If only directories are counted, consider an unknown file type and links also
1178 // as directory instead of trying to do an expensive stat()
1179 // (see bugs 292642 and 299997).
1180 const bool countEntry
= !showFoldersOnly
||
1181 dirEntry
->d_type
== DT_DIR
||
1182 dirEntry
->d_type
== DT_LNK
||
1183 dirEntry
->d_type
== DT_UNKNOWN
;
1194 void KFileItemModelRolesUpdater::updateAllPreviews()
1197 m_previewChangedDuringPausing
= true;
1199 sortAndResolveAllRoles();
1203 #include "kfileitemmodelrolesupdater.moc"