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 "private/nepomuk/resourcewatcher.h"
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 Nepomuk::ResourceWatcher(this);
280 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk::Resource
,Nepomuk::Types::Property
,QVariantList
,QVariantList
)),
281 this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource
)));
282 connect(m_nepomukResourceWatcher
, SIGNAL(propertyRemoved(Nepomuk::Resource
,Nepomuk::Types::Property
,QVariant
)),
283 this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource
)));
284 connect(m_nepomukResourceWatcher
, SIGNAL(propertyAdded(Nepomuk::Resource
,Nepomuk::Types::Property
,QVariant
)),
285 this, SLOT(applyChangedNepomukRoles(Nepomuk::Resource
)));
286 connect(m_nepomukResourceWatcher
, SIGNAL(resourceCreated(Nepomuk::Resource
,QList
<QUrl
>)),
287 this, SLOT(applyChangedNepomukRoles(Nepomuk::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
<Nepomuk::Resource
>());
355 m_nepomukResourceWatcher
->stop();
356 m_nepomukUriItems
.clear();
358 QList
<Nepomuk::Resource
> newResources
;
359 const QList
<Nepomuk::Resource
> oldResources
= m_nepomukResourceWatcher
->resources();
360 foreach (const Nepomuk::Resource
& resource
, oldResources
) {
361 const QUrl uri
= resource
.resourceUri();
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 Nepomuk::Resource
& resource
)
594 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.resourceUri());
595 const KFileItem item
= m_model
->fileItem(itemUrl
);
596 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
598 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
599 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
600 while (it
.hasNext()) {
602 data
.insert(it
.key(), it
.value());
605 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
606 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
607 const int index
= m_model
->index(item
);
608 m_model
->setData(index
, data
);
609 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
610 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
618 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
620 const bool getSizeRole
= m_roles
.contains("size");
621 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
623 if (getSizeRole
|| getIsExpandableRole
) {
624 const int index
= m_model
->index(KUrl(path
));
626 QHash
<QByteArray
, QVariant
> data
;
628 const int count
= subItemsCount(path
);
630 data
.insert("size", count
);
632 if (getIsExpandableRole
) {
633 data
.insert("isExpandable", count
> 0);
636 m_model
->setData(index
, data
);
641 void KFileItemModelRolesUpdater::startUpdating(const KItemRangeList
& itemRanges
)
643 // If no valid index range is given assume that all items are visible.
644 // A cleanup will be done later as soon as the index range has been set.
645 const bool hasValidIndexRange
= (m_lastVisibleIndex
>= 0);
647 if (hasValidIndexRange
) {
648 // Move all current pending visible items that are not visible anymore
649 // to the pending invisible items.
650 QSet
<KFileItem
>::iterator it
= m_pendingVisibleItems
.begin();
651 while (it
!= m_pendingVisibleItems
.end()) {
652 const KFileItem item
= *it
;
653 const int index
= m_model
->index(item
);
654 if (index
< m_firstVisibleIndex
|| index
> m_lastVisibleIndex
) {
655 it
= m_pendingVisibleItems
.erase(it
);
656 m_pendingInvisibleItems
.insert(item
);
665 foreach (const KItemRange
& range
, itemRanges
) {
666 rangesCount
+= range
.count
;
668 // Add the inserted items to the pending visible and invisible items
669 const int lastIndex
= range
.index
+ range
.count
- 1;
670 for (int i
= range
.index
; i
<= lastIndex
; ++i
) {
671 const KFileItem item
= m_model
->fileItem(i
);
672 if (!hasValidIndexRange
|| (i
>= m_firstVisibleIndex
&& i
<= m_lastVisibleIndex
)) {
673 m_pendingVisibleItems
.insert(item
);
675 m_pendingInvisibleItems
.insert(item
);
680 resolvePendingRoles();
683 void KFileItemModelRolesUpdater::startPreviewJob(const KFileItemList
& items
)
685 if (items
.isEmpty() || m_paused
) {
689 // PreviewJob internally caches items always with the size of
690 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
691 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
692 // do a downscaling anyhow because of the frame, so in this case only the provided
693 // cache sizes are requested.
694 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
695 ? QSize(256, 256) : QSize(128, 128);
697 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
698 // worst case) might block the application for several seconds. To prevent such
699 // a blocking the MIME-type of the items will determined until the MaxBlockTimeout
700 // has been reached and only those items will get passed. As soon as the MIME-type
701 // has been resolved once KIO::PreviewJob() can already access the resolved
702 // MIME-type in a fast way.
706 KFileItemList itemSubSet
;
707 const int count
= items
.count();
708 itemSubSet
.reserve(count
);
709 for (int i
= 0; i
< count
; ++i
) {
710 KFileItem item
= items
.at(i
);
711 item
.determineMimeType();
712 itemSubSet
.append(item
);
713 if (timer
.elapsed() > MaxBlockTimeout
) {
714 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
715 kDebug() << "Maximum time of" << MaxBlockTimeout
<< "ms exceeded, creating only previews for"
716 << (i
+ 1) << "items," << (items
.count() - (i
+ 1)) << "will be resolved later";
721 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
722 job
->setIgnoreMaximumSize(items
.first().isLocalFile());
724 job
->ui()->setWindow(qApp
->activeWindow());
727 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
728 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
729 connect(job
, SIGNAL(failed(KFileItem
)),
730 this, SLOT(slotPreviewFailed(KFileItem
)));
731 connect(job
, SIGNAL(finished(KJob
*)),
732 this, SLOT(slotPreviewJobFinished(KJob
*)));
734 m_previewJobs
.append(job
);
738 bool KFileItemModelRolesUpdater::hasPendingRoles() const
740 return !m_pendingVisibleItems
.isEmpty() || !m_pendingInvisibleItems
.isEmpty();
743 void KFileItemModelRolesUpdater::resolvePendingRoles()
745 int resolvedCount
= 0;
747 bool hasSlowRoles
= m_previewShown
;
749 QSetIterator
<QByteArray
> it(m_roles
);
750 while (it
.hasNext()) {
751 if (m_resolvableRoles
.contains(it
.next())) {
758 const ResolveHint resolveHint
= hasSlowRoles
? ResolveFast
: ResolveAll
;
760 // Resolving the MIME type can be expensive. Assure that not more than MaxBlockTimeout ms are
761 // spend for resolving them synchronously. Usually this is more than enough to determine
762 // all visible items, but there are corner cases where this limit gets easily exceeded.
766 // Resolve the MIME type of all visible items
767 QSet
<KFileItem
>::iterator visibleIt
= m_pendingVisibleItems
.begin();
768 while (visibleIt
!= m_pendingVisibleItems
.end()) {
769 const KFileItem item
= *visibleIt
;
771 Q_ASSERT(!m_pendingInvisibleItems
.contains(item
));
772 // All roles will be resolved by applyResolvedRoles()
773 visibleIt
= m_pendingVisibleItems
.erase(visibleIt
);
777 applyResolvedRoles(item
, resolveHint
);
780 if (timer
.elapsed() > MaxBlockTimeout
) {
785 // Resolve the MIME type of the invisible items at least until the timeout
786 // has been exceeded or the maximum number of items has been reached
787 KFileItemList invisibleItems
;
788 if (m_lastVisibleIndex
>= 0) {
789 // The visible range is valid, don't care about the order how the MIME
790 // type of invisible items get resolved
791 invisibleItems
= m_pendingInvisibleItems
.toList();
793 // The visible range is temporary invalid (e.g. happens when loading
794 // a directory) so take care to sort the currently invisible items where
795 // a part will get visible later
796 invisibleItems
= sortedItems(m_pendingInvisibleItems
);
800 while (resolvedCount
< MaxResolveItemsCount
&& index
< invisibleItems
.count() && timer
.elapsed() <= MaxBlockTimeout
) {
801 const KFileItem item
= invisibleItems
.at(index
);
802 applyResolvedRoles(item
, resolveHint
);
805 // All roles have been resolved already by applyResolvedRoles()
806 m_pendingInvisibleItems
.remove(item
);
812 if (m_previewShown
) {
813 KFileItemList items
= sortedItems(m_pendingVisibleItems
);
814 items
+= invisibleItems
;
815 startPreviewJob(items
);
817 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
820 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
821 if (timer
.elapsed() > MaxBlockTimeout
) {
822 kDebug() << "Maximum time of" << MaxBlockTimeout
823 << "ms exceeded, skipping items... Remaining visible:" << m_pendingVisibleItems
.count()
824 << "invisible:" << m_pendingInvisibleItems
.count();
826 kDebug() << "[TIME] Resolved pending roles:" << timer
.elapsed();
829 applySortProgressToModel();
832 void KFileItemModelRolesUpdater::resetPendingRoles()
834 m_pendingVisibleItems
.clear();
835 m_pendingInvisibleItems
.clear();
837 foreach (KJob
* job
, m_previewJobs
) {
840 Q_ASSERT(m_previewJobs
.isEmpty());
843 void KFileItemModelRolesUpdater::sortAndResolveAllRoles()
850 Q_ASSERT(m_pendingVisibleItems
.isEmpty());
851 Q_ASSERT(m_pendingInvisibleItems
.isEmpty());
853 if (m_model
->count() == 0) {
857 // Determine all visible items
858 Q_ASSERT(m_firstVisibleIndex
>= 0);
859 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
860 const KFileItem item
= m_model
->fileItem(i
);
861 if (!item
.isNull()) {
862 m_pendingVisibleItems
.insert(item
);
866 // Determine all invisible items
867 for (int i
= 0; i
< m_firstVisibleIndex
; ++i
) {
868 const KFileItem item
= m_model
->fileItem(i
);
869 if (!item
.isNull()) {
870 m_pendingInvisibleItems
.insert(item
);
873 const int count
= m_model
->count();
874 for (int i
= m_lastVisibleIndex
+ 1; i
< count
; ++i
) {
875 const KFileItem item
= m_model
->fileItem(i
);
876 if (!item
.isNull()) {
877 m_pendingInvisibleItems
.insert(item
);
881 resolvePendingRoles();
884 void KFileItemModelRolesUpdater::sortAndResolvePendingRoles()
887 if (m_model
->count() == 0) {
891 // If no valid index range is given assume that all items are visible.
892 // A cleanup will be done later as soon as the index range has been set.
893 const bool hasValidIndexRange
= (m_lastVisibleIndex
>= 0);
895 // Trigger a preview generation of all pending items. Assure that the visible
896 // pending items get generated first.
898 // Step 1: Check if any items in m_pendingVisibleItems are not visible any more
899 // and move them to m_pendingInvisibleItems.
900 QSet
<KFileItem
>::iterator itVisible
= m_pendingVisibleItems
.begin();
901 while (itVisible
!= m_pendingVisibleItems
.end()) {
902 const KFileItem item
= *itVisible
;
904 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
908 const int index
= m_model
->index(item
);
909 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
912 itVisible
= m_pendingVisibleItems
.erase(itVisible
);
913 m_pendingInvisibleItems
.insert(item
);
917 // Step 2: Check if any items in m_pendingInvisibleItems have become visible
918 // and move them to m_pendingVisibleItems.
919 QSet
<KFileItem
>::iterator itInvisible
= m_pendingInvisibleItems
.begin();
920 while (itInvisible
!= m_pendingInvisibleItems
.end()) {
921 const KFileItem item
= *itInvisible
;
923 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
927 const int index
= m_model
->index(item
);
928 if (!hasValidIndexRange
|| (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
)) {
929 itInvisible
= m_pendingInvisibleItems
.erase(itInvisible
);
930 m_pendingVisibleItems
.insert(item
);
936 resolvePendingRoles();
939 void KFileItemModelRolesUpdater::applySortProgressToModel()
941 if (m_sortingProgress
< 0) {
945 // Inform the model about the progress of the resolved items,
946 // so that it can give an indication when the sorting has been finished.
947 const int resolvedCount
= m_model
->count()
948 - m_pendingVisibleItems
.count()
949 - m_pendingInvisibleItems
.count();
950 if (resolvedCount
> 0) {
951 m_model
->emitSortProgress(resolvedCount
);
952 if (resolvedCount
== m_model
->count()) {
953 m_sortingProgress
= -1;
958 void KFileItemModelRolesUpdater::updateSortProgress()
960 const QByteArray sortRole
= m_model
->sortRole();
962 // Optimization if the sorting is done by type: In case if all MIME-types
963 // are known, the types have been resolved already by KFileItemModel and
964 // no sort-progress feedback is required.
965 const bool showProgress
= (sortRole
== "type")
966 ? hasUnknownMimeTypes()
967 : m_resolvableRoles
.contains(sortRole
);
969 if (m_sortingProgress
>= 0) {
970 // Mark the current sorting as finished
971 m_model
->emitSortProgress(m_model
->count());
973 m_sortingProgress
= showProgress
? 0 : -1;
976 bool KFileItemModelRolesUpdater::hasUnknownMimeTypes() const
978 const int count
= m_model
->count();
979 for (int i
= 0; i
< count
; ++i
) {
980 const KFileItem item
= m_model
->fileItem(i
);
981 if (!item
.isMimeTypeKnown()) {
989 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
995 const bool resolveAll
= (hint
== ResolveAll
);
997 bool mimeTypeChanged
= false;
998 if (!item
.isMimeTypeKnown()) {
999 item
.determineMimeType();
1000 mimeTypeChanged
= true;
1003 if (mimeTypeChanged
|| resolveAll
|| m_clearPreviews
) {
1004 const int index
= m_model
->index(item
);
1009 QHash
<QByteArray
, QVariant
> data
;
1011 data
= rolesData(item
);
1014 data
.insert("iconName", item
.iconName());
1016 if (m_clearPreviews
) {
1017 data
.insert("iconPixmap", QPixmap());
1020 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1021 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1022 m_model
->setData(index
, data
);
1023 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1024 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1031 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1033 QHash
<QByteArray
, QVariant
> data
;
1035 const bool getSizeRole
= m_roles
.contains("size");
1036 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1038 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1039 if (item
.isLocalFile()) {
1040 const QString path
= item
.localPath();
1041 const int count
= subItemsCount(path
);
1043 data
.insert("size", count
);
1045 if (getIsExpandableRole
) {
1046 data
.insert("isExpandable", count
> 0);
1049 if (!m_dirWatcher
->contains(path
)) {
1050 m_dirWatcher
->addDir(path
);
1051 m_watchedDirs
.insert(path
);
1053 } else if (getSizeRole
) {
1054 data
.insert("size", -1); // -1 indicates an unknown number of items
1058 if (m_roles
.contains("type")) {
1059 data
.insert("type", item
.mimeComment());
1062 data
.insert("iconOverlays", item
.overlays());
1065 if (m_nepomukResourceWatcher
) {
1066 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1067 Nepomuk::Resource
resource(item
.nepomukUri());
1068 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1069 while (it
.hasNext()) {
1071 data
.insert(it
.key(), it
.value());
1074 QUrl uri
= resource
.resourceUri();
1075 if (uri
.isEmpty()) {
1076 // TODO: Is there another way to explicitly create a resource?
1077 // We need a resource to be able to track it for changes.
1078 resource
.setRating(0);
1079 uri
= resource
.resourceUri();
1081 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1082 m_nepomukResourceWatcher
->addResource(resource
);
1084 if (m_nepomukUriItems
.isEmpty()) {
1085 m_nepomukResourceWatcher
->start();
1088 m_nepomukUriItems
.insert(uri
, item
.url());
1096 KFileItemList
KFileItemModelRolesUpdater::sortedItems(const QSet
<KFileItem
>& items
) const
1098 KFileItemList itemList
;
1099 if (items
.isEmpty()) {
1103 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1104 QElapsedTimer timer
;
1109 indexes
.reserve(items
.count());
1111 QSetIterator
<KFileItem
> it(items
);
1112 while (it
.hasNext()) {
1113 const KFileItem item
= it
.next();
1114 const int index
= m_model
->index(item
);
1116 indexes
.append(index
);
1121 itemList
.reserve(items
.count());
1122 foreach (int index
, indexes
) {
1123 itemList
.append(m_model
->fileItem(index
));
1126 #ifdef KFILEITEMMODELROLESUPDATER_DEBUG
1127 kDebug() << "[TIME] Sorting of items:" << timer
.elapsed();
1132 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1134 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1135 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1139 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1140 if (countHiddenFiles
) {
1141 filters
|= QDir::Hidden
;
1143 if (showFoldersOnly
) {
1144 filters
|= QDir::Dirs
;
1146 filters
|= QDir::AllEntries
;
1148 return dir
.entryList(filters
).count();
1150 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1151 // Copyright (C) 2006 David Faure <faure@kde.org>
1154 DIR* dir
= ::opendir(QFile::encodeName(path
));
1155 if (dir
) { // krazy:exclude=syscalls
1157 struct dirent
*dirEntry
= 0;
1158 while ((dirEntry
= ::readdir(dir
))) {
1159 if (dirEntry
->d_name
[0] == '.') {
1160 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1161 // Skip "." or hidden files
1164 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1170 // If only directories are counted, consider an unknown file type and links also
1171 // as directory instead of trying to do an expensive stat()
1172 // (see bugs 292642 and 299997).
1173 const bool countEntry
= !showFoldersOnly
||
1174 dirEntry
->d_type
== DT_DIR
||
1175 dirEntry
->d_type
== DT_LNK
||
1176 dirEntry
->d_type
== DT_UNKNOWN
;
1187 void KFileItemModelRolesUpdater::updateAllPreviews()
1190 m_previewChangedDuringPausing
= true;
1192 sortAndResolveAllRoles();
1196 #include "kfileitemmodelrolesupdater.moc"