1 /***************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, write to the *
16 * Free Software Foundation, Inc., *
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
18 ***************************************************************************/
20 #include "kfileitemmodelrolesupdater.h"
22 #include "kfileitemmodel.h"
25 #include <KConfigGroup>
30 #include <KIO/JobUiDelegate>
31 #include <KIO/PreviewJob>
33 #include "private/kpixmapmodifier.h"
35 #include <QApplication>
38 #include <QElapsedTimer>
44 #include "private/knepomukrolesprovider.h"
45 #include <Nepomuk2/ResourceWatcher>
46 #include <Nepomuk2/ResourceManager>
49 // Required includes for subItemsCount():
57 // #define KFILEITEMMODELROLESUPDATER_DEBUG
60 // Maximum time in ms that the KFileItemModelRolesUpdater
61 // may perform a blocking operation
62 const int MaxBlockTimeout
= 200;
64 // If the number of items is smaller than ResolveAllItemsLimit,
65 // the roles of all items will be resolved.
66 const int ResolveAllItemsLimit
= 500;
68 // Not only the visible area, but up to ReadAheadPages before and after
69 // this area will be resolved.
70 const int ReadAheadPages
= 5;
73 KFileItemModelRolesUpdater::KFileItemModelRolesUpdater(KFileItemModel
* model
, QObject
* parent
) :
76 m_previewChangedDuringPausing(false),
77 m_iconSizeChangedDuringPausing(false),
78 m_rolesChangedDuringPausing(false),
79 m_previewShown(false),
80 m_enlargeSmallPreviews(true),
81 m_clearPreviews(false),
85 m_firstVisibleIndex(0),
86 m_lastVisibleIndex(-1),
87 m_maximumVisibleItems(50),
91 m_pendingSortRoleItems(),
93 m_pendingPreviewItems(),
95 m_recentlyChangedItemsTimer(0),
96 m_recentlyChangedItems(),
101 , m_nepomukResourceWatcher(0),
107 const KConfigGroup
globalConfig(KGlobal::config(), "PreviewSettings");
108 m_enabledPlugins
= globalConfig
.readEntry("Plugins", QStringList()
109 << "directorythumbnail"
113 connect(m_model
, SIGNAL(itemsInserted(KItemRangeList
)),
114 this, SLOT(slotItemsInserted(KItemRangeList
)));
115 connect(m_model
, SIGNAL(itemsRemoved(KItemRangeList
)),
116 this, SLOT(slotItemsRemoved(KItemRangeList
)));
117 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
118 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
119 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
120 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
121 connect(m_model
, SIGNAL(sortRoleChanged(QByteArray
,QByteArray
)),
122 this, SLOT(slotSortRoleChanged(QByteArray
,QByteArray
)));
124 // Use a timer to prevent that each call of slotItemsChanged() results in a synchronous
125 // resolving of the roles. Postpone the resolving until no update has been done for 1 second.
126 m_recentlyChangedItemsTimer
= new QTimer(this);
127 m_recentlyChangedItemsTimer
->setInterval(1000);
128 m_recentlyChangedItemsTimer
->setSingleShot(true);
129 connect(m_recentlyChangedItemsTimer
, SIGNAL(timeout()), this, SLOT(resolveRecentlyChangedItems()));
131 m_resolvableRoles
.insert("size");
132 m_resolvableRoles
.insert("type");
133 m_resolvableRoles
.insert("isExpandable");
135 m_resolvableRoles
+= KNepomukRolesProvider::instance().roles();
138 // When folders are expandable or the item-count is shown for folders, it is necessary
139 // to watch the number of items of the sub-folder to be able to react on changes.
140 m_dirWatcher
= new KDirWatch(this);
141 connect(m_dirWatcher
, SIGNAL(dirty(QString
)), this, SLOT(slotDirWatchDirty(QString
)));
144 KFileItemModelRolesUpdater::~KFileItemModelRolesUpdater()
149 void KFileItemModelRolesUpdater::setIconSize(const QSize
& size
)
151 if (size
!= m_iconSize
) {
153 if (m_state
== Paused
) {
154 m_iconSizeChangedDuringPausing
= true;
155 } else if (m_previewShown
) {
156 // An icon size change requires the regenerating of
158 m_finishedItems
.clear();
164 QSize
KFileItemModelRolesUpdater::iconSize() const
169 void KFileItemModelRolesUpdater::setVisibleIndexRange(int index
, int count
)
178 if (index
== m_firstVisibleIndex
&& count
== m_lastVisibleIndex
- m_firstVisibleIndex
+ 1) {
179 // The range has not been changed
183 m_firstVisibleIndex
= index
;
184 m_lastVisibleIndex
= qMin(index
+ count
- 1, m_model
->count() - 1);
189 void KFileItemModelRolesUpdater::setMaximumVisibleItems(int count
)
191 m_maximumVisibleItems
= count
;
194 void KFileItemModelRolesUpdater::setPreviewsShown(bool show
)
196 if (show
== m_previewShown
) {
200 m_previewShown
= show
;
202 m_clearPreviews
= true;
208 bool KFileItemModelRolesUpdater::previewsShown() const
210 return m_previewShown
;
213 void KFileItemModelRolesUpdater::setEnlargeSmallPreviews(bool enlarge
)
215 if (enlarge
!= m_enlargeSmallPreviews
) {
216 m_enlargeSmallPreviews
= enlarge
;
217 if (m_previewShown
) {
223 bool KFileItemModelRolesUpdater::enlargeSmallPreviews() const
225 return m_enlargeSmallPreviews
;
228 void KFileItemModelRolesUpdater::setEnabledPlugins(const QStringList
& list
)
230 if (m_enabledPlugins
!= list
) {
231 m_enabledPlugins
= list
;
232 if (m_previewShown
) {
238 void KFileItemModelRolesUpdater::setPaused(bool paused
)
240 if (paused
== (m_state
== Paused
)) {
248 const bool updatePreviews
= (m_iconSizeChangedDuringPausing
&& m_previewShown
) ||
249 m_previewChangedDuringPausing
;
250 const bool resolveAll
= updatePreviews
|| m_rolesChangedDuringPausing
;
252 m_finishedItems
.clear();
255 m_iconSizeChangedDuringPausing
= false;
256 m_previewChangedDuringPausing
= false;
257 m_rolesChangedDuringPausing
= false;
259 if (!m_pendingSortRoleItems
.isEmpty()) {
260 m_state
= ResolvingSortRole
;
261 resolveNextSortRole();
270 void KFileItemModelRolesUpdater::setRoles(const QSet
<QByteArray
>& roles
)
272 if (m_roles
!= roles
) {
276 if (Nepomuk2::ResourceManager::instance()->initialized()) {
277 // Check whether there is at least one role that must be resolved
278 // with the help of Nepomuk. If this is the case, a (quite expensive)
279 // resolving will be done in KFileItemModelRolesUpdater::rolesData() and
280 // the role gets watched for changes.
281 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
282 bool hasNepomukRole
= false;
283 QSetIterator
<QByteArray
> it(roles
);
284 while (it
.hasNext()) {
285 const QByteArray
& role
= it
.next();
286 if (rolesProvider
.roles().contains(role
)) {
287 hasNepomukRole
= true;
292 if (hasNepomukRole
&& !m_nepomukResourceWatcher
) {
293 Q_ASSERT(m_nepomukUriItems
.isEmpty());
295 m_nepomukResourceWatcher
= new Nepomuk2::ResourceWatcher(this);
296 connect(m_nepomukResourceWatcher
, SIGNAL(propertyChanged(Nepomuk2::Resource
,Nepomuk2::Types::Property
,QVariantList
,QVariantList
)),
297 this, SLOT(applyChangedNepomukRoles(Nepomuk2::Resource
,Nepomuk2::Types::Property
)));
298 } else if (!hasNepomukRole
&& m_nepomukResourceWatcher
) {
299 delete m_nepomukResourceWatcher
;
300 m_nepomukResourceWatcher
= 0;
301 m_nepomukUriItems
.clear();
306 if (m_state
== Paused
) {
307 m_rolesChangedDuringPausing
= true;
314 QSet
<QByteArray
> KFileItemModelRolesUpdater::roles() const
319 bool KFileItemModelRolesUpdater::isPaused() const
321 return m_state
== Paused
;
324 QStringList
KFileItemModelRolesUpdater::enabledPlugins() const
326 return m_enabledPlugins
;
329 void KFileItemModelRolesUpdater::slotItemsInserted(const KItemRangeList
& itemRanges
)
334 // Determine the sort role synchronously for as many items as possible.
335 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
336 int insertedCount
= 0;
337 foreach (const KItemRange
& range
, itemRanges
) {
338 const int lastIndex
= insertedCount
+ range
.index
+ range
.count
- 1;
339 for (int i
= insertedCount
+ range
.index
; i
<= lastIndex
; ++i
) {
340 if (timer
.elapsed() < MaxBlockTimeout
) {
343 m_pendingSortRoleItems
.insert(m_model
->fileItem(i
));
346 insertedCount
+= range
.count
;
349 applySortProgressToModel();
351 // If there are still items whose sort role is unknown, check if the
352 // asynchronous determination of the sort role is already in progress,
353 // and start it if that is not the case.
354 if (!m_pendingSortRoleItems
.isEmpty() && m_state
!= ResolvingSortRole
) {
356 m_state
= ResolvingSortRole
;
357 resolveNextSortRole();
364 void KFileItemModelRolesUpdater::slotItemsRemoved(const KItemRangeList
& itemRanges
)
366 Q_UNUSED(itemRanges
);
368 const bool allItemsRemoved
= (m_model
->count() == 0);
370 if (!m_watchedDirs
.isEmpty()) {
371 // Don't let KDirWatch watch for removed items
372 if (allItemsRemoved
) {
373 foreach (const QString
& path
, m_watchedDirs
) {
374 m_dirWatcher
->removeDir(path
);
376 m_watchedDirs
.clear();
378 QMutableSetIterator
<QString
> it(m_watchedDirs
);
379 while (it
.hasNext()) {
380 const QString
& path
= it
.next();
381 if (m_model
->index(KUrl(path
)) < 0) {
382 m_dirWatcher
->removeDir(path
);
390 if (m_nepomukResourceWatcher
) {
391 // Don't let the ResourceWatcher watch for removed items
392 if (allItemsRemoved
) {
393 m_nepomukResourceWatcher
->setResources(QList
<Nepomuk2::Resource
>());
394 m_nepomukResourceWatcher
->stop();
395 m_nepomukUriItems
.clear();
397 QList
<Nepomuk2::Resource
> newResources
;
398 const QList
<Nepomuk2::Resource
> oldResources
= m_nepomukResourceWatcher
->resources();
399 foreach (const Nepomuk2::Resource
& resource
, oldResources
) {
400 const QUrl uri
= resource
.uri();
401 const KUrl itemUrl
= m_nepomukUriItems
.value(uri
);
402 if (m_model
->index(itemUrl
) >= 0) {
403 newResources
.append(resource
);
405 m_nepomukUriItems
.remove(uri
);
408 m_nepomukResourceWatcher
->setResources(newResources
);
409 if (newResources
.isEmpty()) {
410 Q_ASSERT(m_nepomukUriItems
.isEmpty());
411 m_nepomukResourceWatcher
->stop();
417 if (allItemsRemoved
) {
420 m_finishedItems
.clear();
421 m_pendingSortRoleItems
.clear();
422 m_pendingIndexes
.clear();
423 m_pendingPreviewItems
.clear();
424 m_recentlyChangedItems
.clear();
425 m_recentlyChangedItemsTimer
->stop();
426 m_changedItems
.clear();
430 // Only remove the items from m_finishedItems. They will be removed
431 // from the other sets later on.
432 QSet
<KFileItem
>::iterator it
= m_finishedItems
.begin();
433 while (it
!= m_finishedItems
.end()) {
434 if (m_model
->index(*it
) < 0) {
435 it
= m_finishedItems
.erase(it
);
441 // The visible items might have changed.
446 void KFileItemModelRolesUpdater::slotItemsMoved(const KItemRange
& itemRange
, QList
<int> movedToIndexes
)
449 Q_UNUSED(movedToIndexes
);
451 // The visible items might have changed.
455 void KFileItemModelRolesUpdater::slotItemsChanged(const KItemRangeList
& itemRanges
,
456 const QSet
<QByteArray
>& roles
)
460 // Find out if slotItemsChanged() has been done recently. If that is the
461 // case, resolving the roles is postponed until a timer has exceeded
462 // to prevent expensive repeated updates if files are updated frequently.
463 const bool itemsChangedRecently
= m_recentlyChangedItemsTimer
->isActive();
465 QSet
<KFileItem
>& targetSet
= itemsChangedRecently
? m_recentlyChangedItems
: m_changedItems
;
467 foreach (const KItemRange
& itemRange
, itemRanges
) {
468 int index
= itemRange
.index
;
469 for (int count
= itemRange
.count
; count
> 0; --count
) {
470 const KFileItem item
= m_model
->fileItem(index
);
471 targetSet
.insert(item
);
476 m_recentlyChangedItemsTimer
->start();
478 if (!itemsChangedRecently
) {
479 updateChangedItems();
483 void KFileItemModelRolesUpdater::slotSortRoleChanged(const QByteArray
& current
,
484 const QByteArray
& previous
)
489 if (m_resolvableRoles
.contains(current
)) {
490 m_pendingSortRoleItems
.clear();
491 m_finishedItems
.clear();
493 const int count
= m_model
->count();
497 // Determine the sort role synchronously for as many items as possible.
498 for (int index
= 0; index
< count
; ++index
) {
499 if (timer
.elapsed() < MaxBlockTimeout
) {
500 applySortRole(index
);
502 m_pendingSortRoleItems
.insert(m_model
->fileItem(index
));
506 applySortProgressToModel();
508 if (!m_pendingSortRoleItems
.isEmpty()) {
509 // Trigger the asynchronous determination of the sort role.
511 m_state
= ResolvingSortRole
;
512 resolveNextSortRole();
516 m_pendingSortRoleItems
.clear();
517 applySortProgressToModel();
521 void KFileItemModelRolesUpdater::slotGotPreview(const KFileItem
& item
, const QPixmap
& pixmap
)
523 if (m_state
!= PreviewJobRunning
) {
527 m_changedItems
.remove(item
);
529 const int index
= m_model
->index(item
);
534 QPixmap scaledPixmap
= pixmap
;
536 const QString mimeType
= item
.mimetype();
537 const int slashIndex
= mimeType
.indexOf(QLatin1Char('/'));
538 const QString mimeTypeGroup
= mimeType
.left(slashIndex
);
539 if (mimeTypeGroup
== QLatin1String("image")) {
540 if (m_enlargeSmallPreviews
) {
541 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
543 // Assure that small previews don't get enlarged. Instead they
544 // should be shown centered within the frame.
545 const QSize contentSize
= KPixmapModifier::sizeInsideFrame(m_iconSize
);
546 const bool enlargingRequired
= scaledPixmap
.width() < contentSize
.width() &&
547 scaledPixmap
.height() < contentSize
.height();
548 if (enlargingRequired
) {
549 QSize frameSize
= scaledPixmap
.size();
550 frameSize
.scale(m_iconSize
, Qt::KeepAspectRatio
);
552 QPixmap
largeFrame(frameSize
);
553 largeFrame
.fill(Qt::transparent
);
555 KPixmapModifier::applyFrame(largeFrame
, frameSize
);
557 QPainter
painter(&largeFrame
);
558 painter
.drawPixmap((largeFrame
.width() - scaledPixmap
.width()) / 2,
559 (largeFrame
.height() - scaledPixmap
.height()) / 2,
561 scaledPixmap
= largeFrame
;
563 // The image must be shrinked as it is too large to fit into
564 // the available icon size
565 KPixmapModifier::applyFrame(scaledPixmap
, m_iconSize
);
569 KPixmapModifier::scale(scaledPixmap
, m_iconSize
);
572 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
574 const QStringList overlays
= data
["iconOverlays"].toStringList();
575 // Strangely KFileItem::overlays() returns empty string-values, so
576 // we need to check first whether an overlay must be drawn at all.
577 // It is more efficient to do it here, as KIconLoader::drawOverlays()
578 // assumes that an overlay will be drawn and has some additional
580 foreach (const QString
& overlay
, overlays
) {
581 if (!overlay
.isEmpty()) {
582 // There is at least one overlay, draw all overlays above m_pixmap
583 // and cancel the check
584 KIconLoader::global()->drawOverlays(overlays
, scaledPixmap
, KIconLoader::Desktop
);
589 data
.insert("iconPixmap", scaledPixmap
);
591 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
592 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
593 m_model
->setData(index
, data
);
594 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
595 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
597 m_finishedItems
.insert(item
);
600 void KFileItemModelRolesUpdater::slotPreviewFailed(const KFileItem
& item
)
602 if (m_state
!= PreviewJobRunning
) {
606 m_changedItems
.remove(item
);
608 const int index
= m_model
->index(item
);
610 QHash
<QByteArray
, QVariant
> data
;
611 data
.insert("iconPixmap", QPixmap());
613 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
614 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
615 m_model
->setData(index
, data
);
616 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
617 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
619 applyResolvedRoles(item
, ResolveAll
);
620 m_finishedItems
.insert(item
);
624 void KFileItemModelRolesUpdater::slotPreviewJobFinished()
628 if (m_state
!= PreviewJobRunning
) {
634 if (!m_pendingPreviewItems
.isEmpty()) {
637 if (!m_changedItems
.isEmpty()) {
638 updateChangedItems();
643 void KFileItemModelRolesUpdater::resolveNextSortRole()
645 if (m_state
!= ResolvingSortRole
) {
649 QSet
<KFileItem
>::iterator it
= m_pendingSortRoleItems
.begin();
650 while (it
!= m_pendingSortRoleItems
.end()) {
651 const KFileItem item
= *it
;
652 const int index
= m_model
->index(item
);
654 // Continue if the sort role has already been determined for the
655 // item, and the item has not been changed recently.
656 if (!m_changedItems
.contains(item
) && m_model
->data(index
).contains(m_model
->sortRole())) {
657 it
= m_pendingSortRoleItems
.erase(it
);
661 applySortRole(index
);
662 m_pendingSortRoleItems
.erase(it
);
666 if (!m_pendingSortRoleItems
.isEmpty()) {
667 applySortProgressToModel();
668 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
672 // Prevent that we try to update the items twice.
673 disconnect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
674 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
675 applySortProgressToModel();
676 connect(m_model
, SIGNAL(itemsMoved(KItemRange
,QList
<int>)),
677 this, SLOT(slotItemsMoved(KItemRange
,QList
<int>)));
682 void KFileItemModelRolesUpdater::resolveNextPendingRoles()
684 if (m_state
!= ResolvingAllRoles
) {
688 while (!m_pendingIndexes
.isEmpty()) {
689 const int index
= m_pendingIndexes
.takeFirst();
690 const KFileItem item
= m_model
->fileItem(index
);
692 if (m_finishedItems
.contains(item
)) {
696 applyResolvedRoles(item
, ResolveAll
);
697 m_finishedItems
.insert(item
);
698 m_changedItems
.remove(item
);
702 if (!m_pendingIndexes
.isEmpty()) {
703 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
707 if (m_clearPreviews
) {
708 // Only go through the list if there are items which might still have previews.
709 if (m_finishedItems
.count() != m_model
->count()) {
710 QHash
<QByteArray
, QVariant
> data
;
711 data
.insert("iconPixmap", QPixmap());
713 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
714 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
715 for (int index
= 0; index
<= m_model
->count(); ++index
) {
716 if (m_model
->data(index
).contains("iconPixmap")) {
717 m_model
->setData(index
, data
);
720 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
721 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
724 m_clearPreviews
= false;
727 if (!m_changedItems
.isEmpty()) {
728 updateChangedItems();
733 void KFileItemModelRolesUpdater::resolveRecentlyChangedItems()
735 m_changedItems
+= m_recentlyChangedItems
;
736 m_recentlyChangedItems
.clear();
737 updateChangedItems();
740 void KFileItemModelRolesUpdater::applyChangedNepomukRoles(const Nepomuk2::Resource
& resource
, const Nepomuk2::Types::Property
& property
)
743 if (!Nepomuk2::ResourceManager::instance()->initialized()) {
747 const KUrl itemUrl
= m_nepomukUriItems
.value(resource
.uri());
748 const KFileItem item
= m_model
->fileItem(itemUrl
);
751 // itemUrl is not in the model anymore, probably because
752 // the corresponding file has been deleted in the meantime.
756 QHash
<QByteArray
, QVariant
> data
= rolesData(item
);
758 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
759 const QByteArray role
= rolesProvider
.roleForPropertyUri(property
.uri());
760 if (!role
.isEmpty() && m_roles
.contains(role
)) {
761 // Overwrite the changed role value with an empty QVariant, because the roles
762 // provider doesn't overwrite it when the property value list is empty.
764 data
.insert(role
, QVariant());
767 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
768 while (it
.hasNext()) {
770 data
.insert(it
.key(), it
.value());
773 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
774 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
775 const int index
= m_model
->index(item
);
776 m_model
->setData(index
, data
);
777 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
778 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
786 void KFileItemModelRolesUpdater::slotDirWatchDirty(const QString
& path
)
788 const bool getSizeRole
= m_roles
.contains("size");
789 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
791 if (getSizeRole
|| getIsExpandableRole
) {
792 const int index
= m_model
->index(KUrl(path
));
794 if (!m_model
->fileItem(index
).isDir()) {
795 // If INotify is used, KDirWatch issues the dirty() signal
796 // also for changed files inside the directory, even if we
797 // don't enable this behavior explicitly (see bug 309740).
801 QHash
<QByteArray
, QVariant
> data
;
803 const int count
= subItemsCount(path
);
805 data
.insert("size", count
);
807 if (getIsExpandableRole
) {
808 data
.insert("isExpandable", count
> 0);
811 // Note that we do not block the itemsChanged signal here.
812 // This ensures that a new preview will be generated.
813 m_model
->setData(index
, data
);
818 void KFileItemModelRolesUpdater::startUpdating()
820 if (m_state
== Paused
) {
824 if (m_finishedItems
.count() == m_model
->count()) {
825 // All roles have been resolved already.
830 // Terminate all updates that are currently active.
832 m_pendingIndexes
.clear();
837 // Determine the icons for the visible items synchronously.
838 updateVisibleIcons();
840 // A detailed update of the items in and near the visible area
841 // only makes sense if sorting is finished.
842 if (m_state
== ResolvingSortRole
) {
846 // Start the preview job or the asynchronous resolving of all roles.
847 QList
<int> indexes
= indexesToResolve();
849 if (m_previewShown
) {
850 m_pendingPreviewItems
.clear();
851 m_pendingPreviewItems
.reserve(indexes
.count());
853 foreach (int index
, indexes
) {
854 const KFileItem item
= m_model
->fileItem(index
);
855 if (!m_finishedItems
.contains(item
)) {
856 m_pendingPreviewItems
.append(item
);
862 m_pendingIndexes
= indexes
;
863 // Trigger the asynchronous resolving of all roles.
864 m_state
= ResolvingAllRoles
;
865 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
869 void KFileItemModelRolesUpdater::updateVisibleIcons()
871 int lastVisibleIndex
= m_lastVisibleIndex
;
872 if (lastVisibleIndex
<= 0) {
873 // Guess a reasonable value for the last visible index if the view
874 // has not told us about the real value yet.
875 lastVisibleIndex
= qMin(m_firstVisibleIndex
+ m_maximumVisibleItems
, m_model
->count() - 1);
876 if (lastVisibleIndex
<= 0) {
877 lastVisibleIndex
= qMin(200, m_model
->count() - 1);
884 // Try to determine the final icons for all visible items.
886 for (index
= m_firstVisibleIndex
; index
<= lastVisibleIndex
&& timer
.elapsed() < MaxBlockTimeout
; ++index
) {
887 const KFileItem item
= m_model
->fileItem(index
);
888 applyResolvedRoles(item
, ResolveFast
);
891 // KFileItemListView::initializeItemListWidget(KItemListWidget*) will load
892 // preliminary icons (i.e., without mime type determination) for the
896 void KFileItemModelRolesUpdater::startPreviewJob()
898 m_state
= PreviewJobRunning
;
900 if (m_pendingPreviewItems
.isEmpty()) {
901 QTimer::singleShot(0, this, SLOT(slotPreviewJobFinished()));
905 // PreviewJob internally caches items always with the size of
906 // 128 x 128 pixels or 256 x 256 pixels. A (slow) downscaling is done
907 // by PreviewJob if a smaller size is requested. For images KFileItemModelRolesUpdater must
908 // do a downscaling anyhow because of the frame, so in this case only the provided
909 // cache sizes are requested.
910 const QSize cacheSize
= (m_iconSize
.width() > 128) || (m_iconSize
.height() > 128)
911 ? QSize(256, 256) : QSize(128, 128);
913 // KIO::filePreview() will request the MIME-type of all passed items, which (in the
914 // worst case) might block the application for several seconds. To prevent such
915 // a blocking, we only pass items with known mime type to the preview job.
916 const int count
= m_pendingPreviewItems
.count();
917 KFileItemList itemSubSet
;
918 itemSubSet
.reserve(count
);
920 if (m_pendingPreviewItems
.first().isMimeTypeKnown()) {
921 // Some mime types are known already, probably because they were
922 // determined when loading the icons for the visible items. Start
923 // a preview job for all items at the beginning of the list which
924 // have a known mime type.
926 itemSubSet
.append(m_pendingPreviewItems
.takeFirst());
927 } while (!m_pendingPreviewItems
.isEmpty() && m_pendingPreviewItems
.first().isMimeTypeKnown());
929 // Determine mime types for MaxBlockTimeout ms, and start a preview
930 // job for the corresponding items.
935 const KFileItem item
= m_pendingPreviewItems
.takeFirst();
936 item
.determineMimeType();
937 itemSubSet
.append(item
);
938 } while (!m_pendingPreviewItems
.isEmpty() && timer
.elapsed() < MaxBlockTimeout
);
941 KIO::PreviewJob
* job
= new KIO::PreviewJob(itemSubSet
, cacheSize
, &m_enabledPlugins
);
943 job
->setIgnoreMaximumSize(itemSubSet
.first().isLocalFile());
945 job
->ui()->setWindow(qApp
->activeWindow());
948 connect(job
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
949 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
950 connect(job
, SIGNAL(failed(KFileItem
)),
951 this, SLOT(slotPreviewFailed(KFileItem
)));
952 connect(job
, SIGNAL(finished(KJob
*)),
953 this, SLOT(slotPreviewJobFinished()));
958 void KFileItemModelRolesUpdater::updateChangedItems()
960 if (m_state
== Paused
) {
964 if (m_changedItems
.isEmpty()) {
968 m_finishedItems
-= m_changedItems
;
970 if (m_resolvableRoles
.contains(m_model
->sortRole())) {
971 m_pendingSortRoleItems
+= m_changedItems
;
973 if (m_state
!= ResolvingSortRole
) {
974 // Stop the preview job if necessary, and trigger the
975 // asynchronous determination of the sort role.
977 m_state
= ResolvingSortRole
;
978 QTimer::singleShot(0, this, SLOT(resolveNextSortRole()));
984 QList
<int> visibleChangedIndexes
;
985 QList
<int> invisibleChangedIndexes
;
987 foreach (const KFileItem
& item
, m_changedItems
) {
988 const int index
= m_model
->index(item
);
991 m_changedItems
.remove(item
);
995 if (index
>= m_firstVisibleIndex
&& index
<= m_lastVisibleIndex
) {
996 visibleChangedIndexes
.append(index
);
998 invisibleChangedIndexes
.append(index
);
1002 std::sort(visibleChangedIndexes
.begin(), visibleChangedIndexes
.end());
1004 if (m_previewShown
) {
1005 foreach (int index
, visibleChangedIndexes
) {
1006 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
1009 foreach (int index
, invisibleChangedIndexes
) {
1010 m_pendingPreviewItems
.append(m_model
->fileItem(index
));
1013 if (!m_previewJob
) {
1017 const bool resolvingInProgress
= !m_pendingIndexes
.isEmpty();
1018 m_pendingIndexes
= visibleChangedIndexes
+ m_pendingIndexes
+ invisibleChangedIndexes
;
1019 if (!resolvingInProgress
) {
1020 // Trigger the asynchronous resolving of the changed roles.
1021 m_state
= ResolvingAllRoles
;
1022 QTimer::singleShot(0, this, SLOT(resolveNextPendingRoles()));
1027 void KFileItemModelRolesUpdater::applySortRole(int index
)
1029 QHash
<QByteArray
, QVariant
> data
;
1030 const KFileItem item
= m_model
->fileItem(index
);
1032 if (m_model
->sortRole() == "type") {
1033 if (!item
.isMimeTypeKnown()) {
1034 item
.determineMimeType();
1037 data
.insert("type", item
.mimeComment());
1038 } else if (m_model
->sortRole() == "size" && item
.isLocalFile() && item
.isDir()) {
1039 const QString path
= item
.localPath();
1040 data
.insert("size", subItemsCount(path
));
1042 // Probably the sort role is a Nepomuk role - just determine all roles.
1043 data
= rolesData(item
);
1046 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1047 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1048 m_model
->setData(index
, data
);
1049 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1050 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1053 void KFileItemModelRolesUpdater::applySortProgressToModel()
1055 // Inform the model about the progress of the resolved items,
1056 // so that it can give an indication when the sorting has been finished.
1057 const int resolvedCount
= m_model
->count() - m_pendingSortRoleItems
.count();
1058 m_model
->emitSortProgress(resolvedCount
);
1061 bool KFileItemModelRolesUpdater::applyResolvedRoles(const KFileItem
& item
, ResolveHint hint
)
1063 if (item
.isNull()) {
1067 const bool resolveAll
= (hint
== ResolveAll
);
1069 bool iconChanged
= false;
1070 if (!item
.isMimeTypeKnown() || !item
.isFinalIconKnown()) {
1071 item
.determineMimeType();
1074 const int index
= m_model
->index(item
);
1075 if (!m_model
->data(index
).contains("iconName")) {
1080 if (iconChanged
|| resolveAll
|| m_clearPreviews
) {
1081 const int index
= m_model
->index(item
);
1086 QHash
<QByteArray
, QVariant
> data
;
1088 data
= rolesData(item
);
1091 data
.insert("iconName", item
.iconName());
1093 if (m_clearPreviews
) {
1094 data
.insert("iconPixmap", QPixmap());
1097 disconnect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1098 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1099 m_model
->setData(index
, data
);
1100 connect(m_model
, SIGNAL(itemsChanged(KItemRangeList
,QSet
<QByteArray
>)),
1101 this, SLOT(slotItemsChanged(KItemRangeList
,QSet
<QByteArray
>)));
1108 QHash
<QByteArray
, QVariant
> KFileItemModelRolesUpdater::rolesData(const KFileItem
& item
) const
1110 QHash
<QByteArray
, QVariant
> data
;
1112 const bool getSizeRole
= m_roles
.contains("size");
1113 const bool getIsExpandableRole
= m_roles
.contains("isExpandable");
1115 if ((getSizeRole
|| getIsExpandableRole
) && item
.isDir()) {
1116 if (item
.isLocalFile()) {
1117 const QString path
= item
.localPath();
1118 const int count
= subItemsCount(path
);
1120 data
.insert("size", count
);
1122 if (getIsExpandableRole
) {
1123 data
.insert("isExpandable", count
> 0);
1126 if (!m_dirWatcher
->contains(path
)) {
1127 m_dirWatcher
->addDir(path
);
1128 m_watchedDirs
.insert(path
);
1130 } else if (getSizeRole
) {
1131 data
.insert("size", -1); // -1 indicates an unknown number of items
1135 if (m_roles
.contains("type")) {
1136 data
.insert("type", item
.mimeComment());
1139 data
.insert("iconOverlays", item
.overlays());
1142 if (m_nepomukResourceWatcher
) {
1143 const KNepomukRolesProvider
& rolesProvider
= KNepomukRolesProvider::instance();
1144 Nepomuk2::Resource
resource(item
.nepomukUri());
1145 QHashIterator
<QByteArray
, QVariant
> it(rolesProvider
.roleValues(resource
, m_roles
));
1146 while (it
.hasNext()) {
1148 data
.insert(it
.key(), it
.value());
1151 QUrl uri
= resource
.uri();
1152 if (uri
.isEmpty()) {
1153 // TODO: Is there another way to explicitly create a resource?
1154 // We need a resource to be able to track it for changes.
1155 resource
.setRating(0);
1156 uri
= resource
.uri();
1158 if (!uri
.isEmpty() && !m_nepomukUriItems
.contains(uri
)) {
1159 m_nepomukResourceWatcher
->addResource(resource
);
1161 if (m_nepomukUriItems
.isEmpty()) {
1162 m_nepomukResourceWatcher
->start();
1165 m_nepomukUriItems
.insert(uri
, item
.url());
1173 int KFileItemModelRolesUpdater::subItemsCount(const QString
& path
) const
1175 const bool countHiddenFiles
= m_model
->showHiddenFiles();
1176 const bool showFoldersOnly
= m_model
->showDirectoriesOnly();
1180 QDir::Filters filters
= QDir::NoDotAndDotDot
| QDir::System
;
1181 if (countHiddenFiles
) {
1182 filters
|= QDir::Hidden
;
1184 if (showFoldersOnly
) {
1185 filters
|= QDir::Dirs
;
1187 filters
|= QDir::AllEntries
;
1189 return dir
.entryList(filters
).count();
1191 // Taken from kdelibs/kio/kio/kdirmodel.cpp
1192 // Copyright (C) 2006 David Faure <faure@kde.org>
1195 DIR* dir
= ::opendir(QFile::encodeName(path
));
1196 if (dir
) { // krazy:exclude=syscalls
1198 struct dirent
*dirEntry
= 0;
1199 while ((dirEntry
= ::readdir(dir
))) {
1200 if (dirEntry
->d_name
[0] == '.') {
1201 if (dirEntry
->d_name
[1] == '\0' || !countHiddenFiles
) {
1202 // Skip "." or hidden files
1205 if (dirEntry
->d_name
[1] == '.' && dirEntry
->d_name
[2] == '\0') {
1211 // If only directories are counted, consider an unknown file type and links also
1212 // as directory instead of trying to do an expensive stat()
1213 // (see bugs 292642 and 299997).
1214 const bool countEntry
= !showFoldersOnly
||
1215 dirEntry
->d_type
== DT_DIR
||
1216 dirEntry
->d_type
== DT_LNK
||
1217 dirEntry
->d_type
== DT_UNKNOWN
;
1228 void KFileItemModelRolesUpdater::updateAllPreviews()
1230 if (m_state
== Paused
) {
1231 m_previewChangedDuringPausing
= true;
1233 m_finishedItems
.clear();
1238 void KFileItemModelRolesUpdater::killPreviewJob()
1241 disconnect(m_previewJob
, SIGNAL(gotPreview(KFileItem
,QPixmap
)),
1242 this, SLOT(slotGotPreview(KFileItem
,QPixmap
)));
1243 disconnect(m_previewJob
, SIGNAL(failed(KFileItem
)),
1244 this, SLOT(slotPreviewFailed(KFileItem
)));
1245 disconnect(m_previewJob
, SIGNAL(finished(KJob
*)),
1246 this, SLOT(slotPreviewJobFinished()));
1247 m_previewJob
->kill();
1249 m_pendingPreviewItems
.clear();
1253 QList
<int> KFileItemModelRolesUpdater::indexesToResolve() const
1255 const int count
= m_model
->count();
1258 result
.reserve(ResolveAllItemsLimit
);
1260 // Add visible items.
1261 for (int i
= m_firstVisibleIndex
; i
<= m_lastVisibleIndex
; ++i
) {
1265 // We need a reasonable upper limit for number of items to resolve after
1266 // and before the visible range. m_maximumVisibleItems can be quite large
1267 // when using Compace View.
1268 const int readAheadItems
= qMin(ReadAheadPages
* m_maximumVisibleItems
, ResolveAllItemsLimit
/ 2);
1270 // Add items after the visible range.
1271 const int endExtendedVisibleRange
= qMin(m_lastVisibleIndex
+ readAheadItems
, count
- 1);
1272 for (int i
= m_lastVisibleIndex
+ 1; i
<= endExtendedVisibleRange
; ++i
) {
1276 // Add items before the visible range in reverse order.
1277 const int beginExtendedVisibleRange
= qMax(0, m_firstVisibleIndex
- readAheadItems
);
1278 for (int i
= m_firstVisibleIndex
- 1; i
>= beginExtendedVisibleRange
; --i
) {
1282 // Add items on the last page.
1283 const int beginLastPage
= qMax(qMin(endExtendedVisibleRange
+ 1, count
- 1), count
- m_maximumVisibleItems
);
1284 for (int i
= beginLastPage
; i
< count
; ++i
) {
1288 // Add items on the first page.
1289 const int endFirstPage
= qMin(qMax(beginExtendedVisibleRange
- 1, 0), m_maximumVisibleItems
);
1290 for (int i
= 0; i
<= endFirstPage
; ++i
) {
1294 // Continue adding items until ResolveAllItemsLimit is reached.
1295 int remainingItems
= ResolveAllItemsLimit
- result
.count();
1297 for (int i
= endExtendedVisibleRange
+ 1; i
< beginLastPage
&& remainingItems
> 0; ++i
) {
1302 for (int i
= beginExtendedVisibleRange
- 1; i
> endFirstPage
&& remainingItems
> 0; --i
) {
1310 #include "kfileitemmodelrolesupdater.moc"