1 /*****************************************************************************
2 * Copyright (C) 2011 by Peter Penz <peter.penz19@gmail.com> *
3 * Copyright (C) 2013 by Frank Reininghaus <frank78ac@googlemail.com> *
4 * Copyright (C) 2013 by Emmanuel Pescosta <emmanuelpescosta099@gmail.com> *
6 * This program is free software; you can redistribute it and/or modify *
7 * it under the terms of the GNU General Public License as published by *
8 * the Free Software Foundation; either version 2 of the License, or *
9 * (at your option) any later version. *
11 * This program is distributed in the hope that it will be useful, *
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
14 * GNU General Public License for more details. *
16 * You should have received a copy of the GNU General Public License *
17 * along with this program; if not, write to the *
18 * Free Software Foundation, Inc., *
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
20 *****************************************************************************/
22 #include "kfileitemmodel.h"
25 #include <KGlobalSettings>
27 #include <KStringHandler>
30 #include "private/kfileitemmodelsortalgorithm.h"
31 #include "private/kfileitemmodeldirlister.h"
33 #include <QApplication>
38 // #define KFILEITEMMODEL_DEBUG
40 KFileItemModel::KFileItemModel(QObject
* parent
) :
41 KItemModelBase("text", parent
),
43 m_naturalSorting(KGlobalSettings::naturalSorting()),
44 m_sortDirsFirst(true),
46 m_sortingProgressPercent(-1),
48 m_caseSensitivity(Qt::CaseInsensitive
),
54 m_maximumUpdateIntervalTimer(0),
55 m_resortAllItemsTimer(0),
56 m_pendingItemsToInsert(),
61 m_dirLister
= new KFileItemModelDirLister(this);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
70 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
71 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
72 connect(m_dirLister
, SIGNAL(itemsAdded(KUrl
,KFileItemList
)), this, SLOT(slotItemsAdded(KUrl
,KFileItemList
)));
73 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
74 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
75 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
76 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
77 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
78 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
79 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
80 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
82 // Apply default roles that should be determined
84 m_requestRole
[NameRole
] = true;
85 m_requestRole
[IsDirRole
] = true;
86 m_requestRole
[IsLinkRole
] = true;
87 m_roles
.insert("text");
88 m_roles
.insert("isDir");
89 m_roles
.insert("isLink");
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer
= new QTimer(this);
94 m_maximumUpdateIntervalTimer
->setInterval(2000);
95 m_maximumUpdateIntervalTimer
->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer
= new QTimer(this);
103 m_resortAllItemsTimer
->setInterval(500);
104 m_resortAllItemsTimer
->setSingleShot(true);
105 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
107 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
110 KFileItemModel::~KFileItemModel()
112 qDeleteAll(m_itemData
);
113 qDeleteAll(m_filteredItems
.values());
116 void KFileItemModel::loadDirectory(const KUrl
& url
)
118 m_dirLister
->openUrl(url
);
121 void KFileItemModel::refreshDirectory(const KUrl
& url
)
123 m_dirLister
->openUrl(url
, KDirLister::Reload
);
126 KUrl
KFileItemModel::directory() const
128 return m_dirLister
->url();
131 void KFileItemModel::cancelDirectoryLoading()
136 int KFileItemModel::count() const
138 return m_itemData
.count();
141 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
143 if (index
>= 0 && index
< count()) {
144 return m_itemData
.at(index
)->values
;
146 return QHash
<QByteArray
, QVariant
>();
149 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
151 if (index
< 0 || index
>= count()) {
155 QHash
<QByteArray
, QVariant
> currentValues
= m_itemData
.at(index
)->values
;
157 // Determine which roles have been changed
158 QSet
<QByteArray
> changedRoles
;
159 QHashIterator
<QByteArray
, QVariant
> it(values
);
160 while (it
.hasNext()) {
162 const QByteArray role
= it
.key();
163 const QVariant value
= it
.value();
165 if (currentValues
[role
] != value
) {
166 currentValues
[role
] = value
;
167 changedRoles
.insert(role
);
171 if (changedRoles
.isEmpty()) {
175 m_itemData
[index
]->values
= currentValues
;
176 if (changedRoles
.contains("text")) {
177 KUrl url
= m_itemData
[index
]->item
.url();
178 url
.setFileName(currentValues
["text"].toString());
179 m_itemData
[index
]->item
.setUrl(url
);
182 emit
itemsChanged(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
184 if (changedRoles
.contains(sortRole())) {
185 m_resortAllItemsTimer
->start();
191 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
193 if (dirsFirst
!= m_sortDirsFirst
) {
194 m_sortDirsFirst
= dirsFirst
;
199 bool KFileItemModel::sortDirectoriesFirst() const
201 return m_sortDirsFirst
;
204 void KFileItemModel::setShowHiddenFiles(bool show
)
206 m_dirLister
->setShowingDotFiles(show
);
207 m_dirLister
->emitChanges();
213 bool KFileItemModel::showHiddenFiles() const
215 return m_dirLister
->showingDotFiles();
218 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
220 m_dirLister
->setDirOnlyMode(enabled
);
223 bool KFileItemModel::showDirectoriesOnly() const
225 return m_dirLister
->dirOnlyMode();
228 QMimeData
* KFileItemModel::createMimeData(const QSet
<int>& indexes
) const
230 QMimeData
* data
= new QMimeData();
232 // The following code has been taken from KDirModel::mimeData()
233 // (kdelibs/kio/kio/kdirmodel.cpp)
234 // Copyright (C) 2006 David Faure <faure@kde.org>
236 KUrl::List mostLocalUrls
;
237 bool canUseMostLocalUrls
= true;
239 QSetIterator
<int> it(indexes
);
240 while (it
.hasNext()) {
241 const int index
= it
.next();
242 const KFileItem item
= fileItem(index
);
243 if (!item
.isNull()) {
247 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
249 canUseMostLocalUrls
= false;
254 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
255 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
257 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
258 urls
.populateMimeData(mostLocalUrls
, data
);
260 urls
.populateMimeData(data
);
266 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
268 startFromIndex
= qMax(0, startFromIndex
);
269 for (int i
= startFromIndex
; i
< count(); ++i
) {
270 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
274 for (int i
= 0; i
< startFromIndex
; ++i
) {
275 if (data(i
)["text"].toString().startsWith(text
, Qt::CaseInsensitive
)) {
282 bool KFileItemModel::supportsDropping(int index
) const
284 const KFileItem item
= fileItem(index
);
285 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
288 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
290 static QHash
<QByteArray
, QString
> description
;
291 if (description
.isEmpty()) {
293 const RoleInfoMap
* map
= rolesInfoMap(count
);
294 for (int i
= 0; i
< count
; ++i
) {
295 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
299 return description
.value(role
);
302 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
304 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
305 #ifdef KFILEITEMMODEL_DEBUG
309 switch (typeForRole(sortRole())) {
310 case NameRole
: m_groups
= nameRoleGroups(); break;
311 case SizeRole
: m_groups
= sizeRoleGroups(); break;
312 case DateRole
: m_groups
= dateRoleGroups(); break;
313 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
314 case RatingRole
: m_groups
= ratingRoleGroups(); break;
315 default: m_groups
= genericStringRoleGroups(sortRole()); break;
318 #ifdef KFILEITEMMODEL_DEBUG
319 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
326 KFileItem
KFileItemModel::fileItem(int index
) const
328 if (index
>= 0 && index
< count()) {
329 return m_itemData
.at(index
)->item
;
335 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
337 const int index
= m_items
.value(url
, -1);
339 return m_itemData
.at(index
)->item
;
344 int KFileItemModel::index(const KFileItem
& item
) const
350 return m_items
.value(item
.url(), -1);
353 int KFileItemModel::index(const KUrl
& url
) const
355 KUrl urlToFind
= url
;
356 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
357 return m_items
.value(urlToFind
, -1);
360 KFileItem
KFileItemModel::rootItem() const
362 return m_dirLister
->rootItem();
365 void KFileItemModel::clear()
370 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
372 if (m_roles
== roles
) {
378 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
379 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
380 if (supportedExpanding
&& !willSupportExpanding
) {
381 // No expanding is supported anymore. Take care to delete all items that have an expansion level
382 // that is not 0 (and hence are part of an expanded item).
383 removeExpandedItems();
390 QSetIterator
<QByteArray
> it(roles
);
391 while (it
.hasNext()) {
392 const QByteArray
& role
= it
.next();
393 m_requestRole
[typeForRole(role
)] = true;
397 // Update m_data with the changed requested roles
398 const int maxIndex
= count() - 1;
399 for (int i
= 0; i
<= maxIndex
; ++i
) {
400 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
403 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
404 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
408 QSet
<QByteArray
> KFileItemModel::roles() const
413 bool KFileItemModel::setExpanded(int index
, bool expanded
)
415 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
419 QHash
<QByteArray
, QVariant
> values
;
420 values
.insert("isExpanded", expanded
);
421 if (!setData(index
, values
)) {
425 const KFileItem item
= m_itemData
.at(index
)->item
;
426 const KUrl url
= item
.url();
428 m_expandedDirs
.insert(url
);
429 m_dirLister
->openUrl(url
, KDirLister::Keep
);
431 m_expandedDirs
.remove(url
);
432 m_dirLister
->stop(url
);
434 removeFilteredChildren(KFileItemList() << item
);
436 const KFileItemList itemsToRemove
= childItems(item
);
437 removeFilteredChildren(itemsToRemove
);
438 removeItems(itemsToRemove
, DeleteItemData
);
444 bool KFileItemModel::isExpanded(int index
) const
446 if (index
>= 0 && index
< count()) {
447 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
452 bool KFileItemModel::isExpandable(int index
) const
454 if (index
>= 0 && index
< count()) {
455 return m_itemData
.at(index
)->values
.value("isExpandable").toBool();
460 int KFileItemModel::expandedParentsCount(int index
) const
462 if (index
>= 0 && index
< count()) {
463 const int parentsCount
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
464 if (parentsCount
> 0) {
471 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
473 return m_expandedDirs
;
476 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
478 m_urlsToExpand
= urls
;
481 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
483 const int pos
= m_dirLister
->url().path().length();
485 // Assure that each sub-path of the URL that should be
486 // expanded is added to m_urlsToExpand. KDirLister
487 // does not care whether the parent-URL has already been
489 KUrl urlToExpand
= m_dirLister
->url();
490 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
491 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
492 urlToExpand
.addPath(subDirs
.at(i
));
493 m_urlsToExpand
.insert(urlToExpand
);
496 // KDirLister::open() must called at least once to trigger an initial
497 // loading. The pending URLs that must be restored are handled
498 // in slotCompleted().
499 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
500 while (it2
.hasNext()) {
501 const int idx
= index(it2
.next());
502 if (idx
>= 0 && !isExpanded(idx
)) {
503 setExpanded(idx
, true);
509 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
511 if (m_filter
.pattern() != nameFilter
) {
512 dispatchPendingItemsToInsert();
513 m_filter
.setPattern(nameFilter
);
518 QString
KFileItemModel::nameFilter() const
520 return m_filter
.pattern();
523 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
525 if (m_filter
.mimeTypes() != filters
) {
526 dispatchPendingItemsToInsert();
527 m_filter
.setMimeTypes(filters
);
532 QStringList
KFileItemModel::mimeTypeFilters() const
534 return m_filter
.mimeTypes();
538 void KFileItemModel::applyFilters()
540 // Check which shown items from m_itemData must get
541 // hidden and hence moved to m_filteredItems.
542 KFileItemList newFilteredItems
;
544 foreach (ItemData
* itemData
, m_itemData
) {
545 // Only filter non-expanded items as child items may never
546 // exist without a parent item
547 if (!itemData
->values
.value("isExpanded").toBool()) {
548 const KFileItem item
= itemData
->item
;
549 if (!m_filter
.matches(item
)) {
550 newFilteredItems
.append(item
);
551 m_filteredItems
.insert(item
, itemData
);
556 removeItems(newFilteredItems
, KeepItemData
);
558 // Check which hidden items from m_filteredItems should
559 // get visible again and hence removed from m_filteredItems.
560 QList
<ItemData
*> newVisibleItems
;
562 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
563 while (it
!= m_filteredItems
.end()) {
564 if (m_filter
.matches(it
.key())) {
565 newVisibleItems
.append(it
.value());
566 it
= m_filteredItems
.erase(it
);
572 insertItems(newVisibleItems
);
575 void KFileItemModel::removeFilteredChildren(const KFileItemList
& parentsList
)
577 if (m_filteredItems
.isEmpty()) {
581 // First, we put the parent items into a set to provide fast lookup
582 // while iterating over m_filteredItems and prevent quadratic
583 // complexity if there are N parents and N filtered items.
584 const QSet
<KFileItem
> parents
= parentsList
.toSet();
586 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
587 while (it
!= m_filteredItems
.end()) {
588 const ItemData
* parent
= it
.value()->parent
;
590 if (parent
&& parents
.contains(parent
->item
)) {
592 it
= m_filteredItems
.erase(it
);
599 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
601 static QList
<RoleInfo
> rolesInfo
;
602 if (rolesInfo
.isEmpty()) {
604 const RoleInfoMap
* map
= rolesInfoMap(count
);
605 for (int i
= 0; i
< count
; ++i
) {
606 if (map
[i
].roleType
!= NoRole
) {
608 info
.role
= map
[i
].role
;
609 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
610 if (map
[i
].groupTranslation
) {
611 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
613 // For top level roles, groupTranslation is 0. We must make sure that
614 // info.group is an empty string then because the code that generates
615 // menus tries to put the actions into sub menus otherwise.
616 info
.group
= QString();
618 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
619 info
.requiresIndexer
= map
[i
].requiresIndexer
;
620 rolesInfo
.append(info
);
628 void KFileItemModel::onGroupedSortingChanged(bool current
)
634 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
637 m_sortRole
= typeForRole(current
);
639 #ifdef KFILEITEMMODEL_DEBUG
640 if (!m_requestRole
[m_sortRole
]) {
641 kWarning() << "The sort-role has been changed to a role that has not been received yet";
648 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
655 void KFileItemModel::resortAllItems()
657 m_resortAllItemsTimer
->stop();
659 const int itemCount
= count();
660 if (itemCount
<= 0) {
664 #ifdef KFILEITEMMODEL_DEBUG
667 kDebug() << "===========================================================";
668 kDebug() << "Resorting" << itemCount
<< "items";
671 // Remember the order of the current URLs so
672 // that it can be determined which indexes have
673 // been moved because of the resorting.
675 oldUrls
.reserve(itemCount
);
676 foreach (const ItemData
* itemData
, m_itemData
) {
677 oldUrls
.append(itemData
->item
.url());
684 sort(m_itemData
.begin(), m_itemData
.end());
685 for (int i
= 0; i
< itemCount
; ++i
) {
686 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
689 // Determine the indexes that have been moved
690 QList
<int> movedToIndexes
;
691 movedToIndexes
.reserve(itemCount
);
692 for (int i
= 0; i
< itemCount
; i
++) {
693 const int newIndex
= m_items
.value(oldUrls
.at(i
).url());
694 movedToIndexes
.append(newIndex
);
697 // Don't check whether items have really been moved and always emit a
698 // itemsMoved() signal after resorting: In case of grouped items
699 // the groups might change even if the items themselves don't change their
700 // position. Let the receiver of the signal decide whether a check for moved
701 // items makes sense.
702 emit
itemsMoved(KItemRange(0, itemCount
), movedToIndexes
);
704 #ifdef KFILEITEMMODEL_DEBUG
705 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
709 void KFileItemModel::slotCompleted()
711 dispatchPendingItemsToInsert();
713 if (!m_urlsToExpand
.isEmpty()) {
714 // Try to find a URL that can be expanded.
715 // Note that the parent folder must be expanded before any of its subfolders become visible.
716 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
717 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
718 foreach (const KUrl
& url
, m_urlsToExpand
) {
719 const int index
= m_items
.value(url
, -1);
721 m_urlsToExpand
.remove(url
);
722 if (setExpanded(index
, true)) {
723 // The dir lister has been triggered. This slot will be called
724 // again after the directory has been expanded.
730 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
731 // if these URLs have been deleted in the meantime.
732 m_urlsToExpand
.clear();
735 emit
directoryLoadingCompleted();
738 void KFileItemModel::slotCanceled()
740 m_maximumUpdateIntervalTimer
->stop();
741 dispatchPendingItemsToInsert();
743 emit
directoryLoadingCanceled();
746 void KFileItemModel::slotItemsAdded(const KUrl
& directoryUrl
, const KFileItemList
& items
)
748 Q_ASSERT(!items
.isEmpty());
750 KUrl parentUrl
= directoryUrl
;
751 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
753 if (m_requestRole
[ExpandedParentsCountRole
]) {
754 // To be able to compare whether the new items may be inserted as children
755 // of a parent item the pending items must be added to the model first.
756 dispatchPendingItemsToInsert();
758 KFileItem item
= items
.first();
760 // If the expanding of items is enabled, the call
761 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
762 // might result in emitting the same items twice due to the Keep-parameter.
763 // This case happens if an item gets expanded, collapsed and expanded again
764 // before the items could be loaded for the first expansion.
765 const int index
= m_items
.value(item
.url(), -1);
767 // The items are already part of the model.
771 // KDirLister keeps the children of items that got expanded once even if
772 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
773 // checked whether the parent for new items is still expanded.
774 const int parentIndex
= m_items
.value(parentUrl
, -1);
775 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
776 // The parent is not expanded.
781 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
783 if (!m_filter
.hasSetFilters()) {
784 m_pendingItemsToInsert
.append(itemDataList
);
786 // The name or type filter is active. Hide filtered items
787 // before inserting them into the model and remember
788 // the filtered items in m_filteredItems.
789 foreach (ItemData
* itemData
, itemDataList
) {
790 if (m_filter
.matches(itemData
->item
)) {
791 m_pendingItemsToInsert
.append(itemData
);
793 m_filteredItems
.insert(itemData
->item
, itemData
);
798 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
799 // Assure that items get dispatched if no completed() or canceled() signal is
800 // emitted during the maximum update interval.
801 m_maximumUpdateIntervalTimer
->start();
805 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
807 dispatchPendingItemsToInsert();
809 KFileItemList itemsToRemove
= items
;
810 if (m_requestRole
[ExpandedParentsCountRole
]) {
811 // Assure that removing a parent item also results in removing all children
812 foreach (const KFileItem
& item
, items
) {
813 itemsToRemove
.append(childItems(item
));
817 if (!m_filteredItems
.isEmpty()) {
818 foreach (const KFileItem
& item
, itemsToRemove
) {
819 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
820 if (it
!= m_filteredItems
.end()) {
822 m_filteredItems
.erase(it
);
826 if (m_requestRole
[ExpandedParentsCountRole
]) {
827 removeFilteredChildren(itemsToRemove
);
831 removeItems(itemsToRemove
, DeleteItemData
);
834 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
836 Q_ASSERT(!items
.isEmpty());
837 #ifdef KFILEITEMMODEL_DEBUG
838 kDebug() << "Refreshing" << items
.count() << "items";
843 // Get the indexes of all items that have been refreshed
845 indexes
.reserve(items
.count());
847 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
848 while (it
.hasNext()) {
849 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
850 const KFileItem
& oldItem
= itemPair
.first
;
851 const KFileItem
& newItem
= itemPair
.second
;
852 const int index
= m_items
.value(oldItem
.url(), -1);
854 m_itemData
[index
]->item
= newItem
;
856 // Keep old values as long as possible if they could not retrieved synchronously yet.
857 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
858 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(index
)->parent
));
859 while (it
.hasNext()) {
861 m_itemData
[index
]->values
.insert(it
.key(), it
.value());
864 m_items
.remove(oldItem
.url());
865 m_items
.insert(newItem
.url(), index
);
866 indexes
.append(index
);
870 // If the changed items have been created recently, they might not be in m_items yet.
871 // In that case, the list 'indexes' might be empty.
872 if (indexes
.isEmpty()) {
876 // Extract the item-ranges out of the changed indexes
879 KItemRangeList itemRangeList
;
880 int previousIndex
= indexes
.at(0);
881 int rangeIndex
= previousIndex
;
884 const int maxIndex
= indexes
.count() - 1;
885 for (int i
= 1; i
<= maxIndex
; ++i
) {
886 const int currentIndex
= indexes
.at(i
);
887 if (currentIndex
== previousIndex
+ 1) {
890 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
892 rangeIndex
= currentIndex
;
895 previousIndex
= currentIndex
;
898 if (rangeCount
> 0) {
899 itemRangeList
.append(KItemRange(rangeIndex
, rangeCount
));
902 emit
itemsChanged(itemRangeList
, m_roles
);
907 void KFileItemModel::slotClear()
909 #ifdef KFILEITEMMODEL_DEBUG
910 kDebug() << "Clearing all items";
913 qDeleteAll(m_filteredItems
.values());
914 m_filteredItems
.clear();
917 m_maximumUpdateIntervalTimer
->stop();
918 m_resortAllItemsTimer
->stop();
919 m_pendingItemsToInsert
.clear();
921 const int removedCount
= m_itemData
.count();
922 if (removedCount
> 0) {
923 qDeleteAll(m_itemData
);
926 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
929 m_expandedDirs
.clear();
932 void KFileItemModel::slotClear(const KUrl
& url
)
937 void KFileItemModel::slotNaturalSortingChanged()
939 m_naturalSorting
= KGlobalSettings::naturalSorting();
943 void KFileItemModel::dispatchPendingItemsToInsert()
945 if (!m_pendingItemsToInsert
.isEmpty()) {
946 insertItems(m_pendingItemsToInsert
);
947 m_pendingItemsToInsert
.clear();
951 void KFileItemModel::insertItems(QList
<ItemData
*>& items
)
953 if (items
.isEmpty()) {
957 #ifdef KFILEITEMMODEL_DEBUG
960 kDebug() << "===========================================================";
961 kDebug() << "Inserting" << items
.count() << "items";
966 sort(items
.begin(), items
.end());
968 #ifdef KFILEITEMMODEL_DEBUG
969 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
972 KItemRangeList itemRanges
;
975 int insertedAtIndex
= -1; // Index for the current item-range
976 int insertedCount
= 0; // Count for the current item-range
977 int previouslyInsertedCount
= 0; // Sum of previously inserted items for all ranges
978 while (sourceIndex
< items
.count()) {
979 // Find target index from m_items to insert the current item
981 const int previousTargetIndex
= targetIndex
;
982 while (targetIndex
< m_itemData
.count()) {
983 if (!lessThan(m_itemData
.at(targetIndex
), items
.at(sourceIndex
))) {
989 if (targetIndex
- previousTargetIndex
> 0 && insertedAtIndex
>= 0) {
990 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
991 previouslyInsertedCount
+= insertedCount
;
992 insertedAtIndex
= targetIndex
- previouslyInsertedCount
;
996 // Insert item at the position targetIndex by transferring
997 // the ownership of the item-data from 'items' to m_itemData.
998 // m_items will be inserted after the loop (see comment below)
999 m_itemData
.insert(targetIndex
, items
.at(sourceIndex
));
1002 if (insertedAtIndex
< 0) {
1003 insertedAtIndex
= targetIndex
;
1004 Q_ASSERT(previouslyInsertedCount
== 0);
1010 // The indexes of all m_items must be adjusted, not only the index
1012 const int itemDataCount
= m_itemData
.count();
1013 m_items
.reserve(itemDataCount
);
1014 for (int i
= 0; i
< itemDataCount
; ++i
) {
1015 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1018 itemRanges
<< KItemRange(insertedAtIndex
, insertedCount
);
1019 emit
itemsInserted(itemRanges
);
1021 #ifdef KFILEITEMMODEL_DEBUG
1022 kDebug() << "[TIME] Inserting of" << items
.count() << "items:" << timer
.elapsed();
1026 static KItemRangeList
sortedIndexesToKItemRangeList(const QList
<int>& sortedNumbers
)
1028 if (sortedNumbers
.empty()) {
1029 return KItemRangeList();
1032 KItemRangeList result
;
1034 QList
<int>::const_iterator it
= sortedNumbers
.begin();
1040 QList
<int>::const_iterator end
= sortedNumbers
.end();
1042 if (*it
== index
+ count
) {
1045 result
<< KItemRange(index
, count
);
1052 result
<< KItemRange(index
, count
);
1056 void KFileItemModel::removeItems(const KFileItemList
& items
, RemoveItemsBehavior behavior
)
1058 #ifdef KFILEITEMMODEL_DEBUG
1059 kDebug() << "Removing " << items
.count() << "items";
1064 // Step 1: Determine the indexes of the removed items, remove them from
1065 // the hash m_items, and free the ItemData.
1066 QList
<int> indexesToRemove
;
1067 indexesToRemove
.reserve(items
.count());
1068 foreach (const KFileItem
& item
, items
) {
1069 const KUrl url
= item
.url();
1070 const int index
= m_items
.value(url
, -1);
1072 indexesToRemove
.append(index
);
1074 // Prevent repeated expensive rehashing by using QHash::erase(),
1075 // rather than QHash::remove().
1076 QHash
<KUrl
, int>::iterator it
= m_items
.find(url
);
1079 if (behavior
== DeleteItemData
) {
1080 delete m_itemData
.at(index
);
1083 m_itemData
[index
] = 0;
1087 if (indexesToRemove
.isEmpty()) {
1091 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1093 // Step 2: Remove the ItemData pointers from the list m_itemData.
1094 const KItemRangeList itemRanges
= sortedIndexesToKItemRangeList(indexesToRemove
);
1095 int target
= itemRanges
.at(0).index
;
1096 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1099 const int oldItemDataCount
= m_itemData
.count();
1100 while (source
< oldItemDataCount
) {
1101 m_itemData
[target
] = m_itemData
[source
];
1105 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1106 // Skip the items in the next removed range.
1107 source
+= itemRanges
.at(nextRange
).count
;
1112 m_itemData
.erase(m_itemData
.end() - indexesToRemove
.count(), m_itemData
.end());
1114 // Step 3: Adjust indexes in the hash m_items. Note that all indexes
1115 // might have been changed by the removal of the items.
1116 const int newItemDataCount
= m_itemData
.count();
1117 for (int i
= 0; i
< newItemDataCount
; ++i
) {
1118 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1121 emit
itemsRemoved(itemRanges
);
1124 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KUrl
& parentUrl
, const KFileItemList
& items
) const
1126 if (m_sortRole
== TypeRole
) {
1127 // Try to resolve the MIME-types synchronously to prevent a reordering of
1128 // the items when sorting by type (per default MIME-types are resolved
1129 // asynchronously by KFileItemModelRolesUpdater).
1130 determineMimeTypes(items
, 200);
1133 const int parentIndex
= m_items
.value(parentUrl
, -1);
1134 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1136 QList
<ItemData
*> itemDataList
;
1137 itemDataList
.reserve(items
.count());
1139 foreach (const KFileItem
& item
, items
) {
1140 ItemData
* itemData
= new ItemData();
1141 itemData
->item
= item
;
1142 itemData
->values
= retrieveData(item
, parentItem
);
1143 itemData
->parent
= parentItem
;
1144 itemDataList
.append(itemData
);
1147 return itemDataList
;
1150 void KFileItemModel::removeExpandedItems()
1152 KFileItemList expandedItems
;
1154 const int maxIndex
= m_itemData
.count() - 1;
1155 for (int i
= 0; i
<= maxIndex
; ++i
) {
1156 const ItemData
* itemData
= m_itemData
.at(i
);
1157 if (itemData
->values
.value("expandedParentsCount").toInt() > 0) {
1158 expandedItems
.append(itemData
->item
);
1162 // The m_expandedParentsCountRoot may not get reset before all items with
1163 // a bigger count have been removed.
1164 removeItems(expandedItems
, DeleteItemData
);
1166 m_expandedDirs
.clear();
1169 void KFileItemModel::resetRoles()
1171 for (int i
= 0; i
< RolesCount
; ++i
) {
1172 m_requestRole
[i
] = false;
1176 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1178 static QHash
<QByteArray
, RoleType
> roles
;
1179 if (roles
.isEmpty()) {
1180 // Insert user visible roles that can be accessed with
1181 // KFileItemModel::roleInformation()
1183 const RoleInfoMap
* map
= rolesInfoMap(count
);
1184 for (int i
= 0; i
< count
; ++i
) {
1185 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1188 // Insert internal roles (take care to synchronize the implementation
1189 // with KFileItemModel::roleForType() in case if a change is done).
1190 roles
.insert("isDir", IsDirRole
);
1191 roles
.insert("isLink", IsLinkRole
);
1192 roles
.insert("isExpanded", IsExpandedRole
);
1193 roles
.insert("isExpandable", IsExpandableRole
);
1194 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1196 Q_ASSERT(roles
.count() == RolesCount
);
1199 return roles
.value(role
, NoRole
);
1202 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1204 static QHash
<RoleType
, QByteArray
> roles
;
1205 if (roles
.isEmpty()) {
1206 // Insert user visible roles that can be accessed with
1207 // KFileItemModel::roleInformation()
1209 const RoleInfoMap
* map
= rolesInfoMap(count
);
1210 for (int i
= 0; i
< count
; ++i
) {
1211 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1214 // Insert internal roles (take care to synchronize the implementation
1215 // with KFileItemModel::typeForRole() in case if a change is done).
1216 roles
.insert(IsDirRole
, "isDir");
1217 roles
.insert(IsLinkRole
, "isLink");
1218 roles
.insert(IsExpandedRole
, "isExpanded");
1219 roles
.insert(IsExpandableRole
, "isExpandable");
1220 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1222 Q_ASSERT(roles
.count() == RolesCount
);
1225 return roles
.value(roleType
);
1228 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1230 // It is important to insert only roles that are fast to retrieve. E.g.
1231 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1232 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1233 QHash
<QByteArray
, QVariant
> data
;
1234 data
.insert("url", item
.url());
1236 const bool isDir
= item
.isDir();
1237 if (m_requestRole
[IsDirRole
]) {
1238 data
.insert("isDir", isDir
);
1241 if (m_requestRole
[IsLinkRole
]) {
1242 const bool isLink
= item
.isLink();
1243 data
.insert("isLink", isLink
);
1246 if (m_requestRole
[NameRole
]) {
1247 data
.insert("text", item
.text());
1250 if (m_requestRole
[SizeRole
]) {
1252 data
.insert("size", QVariant());
1254 data
.insert("size", item
.size());
1258 if (m_requestRole
[DateRole
]) {
1259 // Don't use KFileItem::timeString() as this is too expensive when
1260 // having several thousands of items. Instead the formatting of the
1261 // date-time will be done on-demand by the view when the date will be shown.
1262 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1263 data
.insert("date", dateTime
.dateTime());
1266 if (m_requestRole
[PermissionsRole
]) {
1267 data
.insert("permissions", item
.permissionsString());
1270 if (m_requestRole
[OwnerRole
]) {
1271 data
.insert("owner", item
.user());
1274 if (m_requestRole
[GroupRole
]) {
1275 data
.insert("group", item
.group());
1278 if (m_requestRole
[DestinationRole
]) {
1279 QString destination
= item
.linkDest();
1280 if (destination
.isEmpty()) {
1281 destination
= QLatin1String("-");
1283 data
.insert("destination", destination
);
1286 if (m_requestRole
[PathRole
]) {
1288 if (item
.url().protocol() == QLatin1String("trash")) {
1289 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1291 // For performance reasons cache the home-path in a static QString
1292 // (see QDir::homePath() for more details)
1293 static QString homePath
;
1294 if (homePath
.isEmpty()) {
1295 homePath
= QDir::homePath();
1298 path
= item
.localPath();
1299 if (path
.startsWith(homePath
)) {
1300 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1304 const int index
= path
.lastIndexOf(item
.text());
1305 path
= path
.mid(0, index
- 1);
1306 data
.insert("path", path
);
1309 if (m_requestRole
[IsExpandedRole
]) {
1310 data
.insert("isExpanded", false);
1313 if (m_requestRole
[IsExpandableRole
]) {
1314 data
.insert("isExpandable", item
.isDir() && item
.url() == item
.targetUrl());
1317 if (m_requestRole
[ExpandedParentsCountRole
]) {
1320 level
= parent
->values
["expandedParentsCount"].toInt() + 1;
1323 data
.insert("expandedParentsCount", level
);
1326 if (item
.isMimeTypeKnown()) {
1327 data
.insert("iconName", item
.iconName());
1329 if (m_requestRole
[TypeRole
]) {
1330 data
.insert("type", item
.mimeComment());
1337 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1341 if (a
->parent
!= b
->parent
) {
1342 const int expansionLevelA
= a
->values
.value("expandedParentsCount").toInt();
1343 const int expansionLevelB
= b
->values
.value("expandedParentsCount").toInt();
1345 // If b has a higher expansion level than a, check if a is a parent
1346 // of b, and make sure that both expansion levels are equal otherwise.
1347 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1348 if (b
->parent
== a
) {
1354 // If a has a higher expansion level than a, check if b is a parent
1355 // of a, and make sure that both expansion levels are equal otherwise.
1356 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1357 if (a
->parent
== b
) {
1363 Q_ASSERT(a
->values
.value("expandedParentsCount").toInt() == b
->values
.value("expandedParentsCount").toInt());
1365 // Compare the last parents of a and b which are different.
1366 while (a
->parent
!= b
->parent
) {
1372 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1373 const bool isDirA
= a
->item
.isDir();
1374 const bool isDirB
= b
->item
.isDir();
1375 if (isDirA
&& !isDirB
) {
1377 } else if (!isDirA
&& isDirB
) {
1382 result
= sortRoleCompare(a
, b
);
1384 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1388 * Helper class for KFileItemModel::sort().
1390 class KFileItemModelLessThan
1393 KFileItemModelLessThan(const KFileItemModel
* model
) :
1398 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1400 return m_model
->lessThan(a
, b
);
1404 const KFileItemModel
* m_model
;
1407 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1408 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1410 KFileItemModelLessThan
lessThan(this);
1412 if (m_sortRole
== NameRole
) {
1413 // Sorting by name can be expensive, in particular if natural sorting is
1414 // enabled. Use all CPU cores to speed up the sorting process.
1415 static const int numberOfThreads
= QThread::idealThreadCount();
1416 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1418 // Sorting by other roles is quite fast. Use only one thread to prevent
1419 // problems caused by non-reentrant comparison functions, see
1420 // https://bugs.kde.org/show_bug.cgi?id=312679
1421 mergeSort(begin
, end
, lessThan
);
1425 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1427 const KFileItem
& itemA
= a
->item
;
1428 const KFileItem
& itemB
= b
->item
;
1432 switch (m_sortRole
) {
1434 // The name role is handled as default fallback after the switch
1438 if (itemA
.isDir()) {
1439 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1440 Q_ASSERT(itemB
.isDir());
1442 const QVariant valueA
= a
->values
.value("size");
1443 const QVariant valueB
= b
->values
.value("size");
1444 if (valueA
.isNull() && valueB
.isNull()) {
1446 } else if (valueA
.isNull()) {
1448 } else if (valueB
.isNull()) {
1451 result
= valueA
.toInt() - valueB
.toInt();
1454 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1455 Q_ASSERT(!itemB
.isDir());
1456 const KIO::filesize_t sizeA
= itemA
.size();
1457 const KIO::filesize_t sizeB
= itemB
.size();
1458 if (sizeA
> sizeB
) {
1460 } else if (sizeA
< sizeB
) {
1470 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1471 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1472 if (dateTimeA
< dateTimeB
) {
1474 } else if (dateTimeA
> dateTimeB
) {
1481 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1485 case ImageSizeRole
: {
1486 // Alway use a natural comparing to interpret the numbers of a string like
1487 // "1600 x 1200" for having a correct sorting.
1488 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1489 b
->values
.value("imageSize").toString(),
1495 const QByteArray role
= roleForType(m_sortRole
);
1496 result
= QString::compare(a
->values
.value(role
).toString(),
1497 b
->values
.value(role
).toString());
1504 // The current sort role was sufficient to define an order
1508 // Fallback #1: Compare the text of the items
1509 result
= stringCompare(itemA
.text(), itemB
.text());
1514 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1515 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1516 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1521 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1522 // equal. In this case a comparison of the URL is done which is unique in all cases
1523 // within KDirLister.
1524 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1527 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1529 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1530 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1531 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1532 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1534 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1535 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1536 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1538 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1539 // comparison, still a deterministic sort order is required. A case sensitive
1540 // comparison is done as fallback.
1545 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1546 : QString::compare(a
, b
, Qt::CaseSensitive
);
1549 bool KFileItemModel::useMaximumUpdateInterval() const
1551 return !m_dirLister
->url().isLocalFile();
1554 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1556 Q_ASSERT(!m_itemData
.isEmpty());
1558 const int maxIndex
= count() - 1;
1559 QList
<QPair
<int, QVariant
> > groups
;
1563 bool isLetter
= false;
1564 for (int i
= 0; i
<= maxIndex
; ++i
) {
1565 if (isChildItem(i
)) {
1569 const QString name
= m_itemData
.at(i
)->values
.value("text").toString();
1571 // Use the first character of the name as group indication
1572 QChar newFirstChar
= name
.at(0).toUpper();
1573 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1574 newFirstChar
= name
.at(1).toUpper();
1577 if (firstChar
!= newFirstChar
) {
1578 QString newGroupValue
;
1579 if (newFirstChar
>= QLatin1Char('A') && newFirstChar
<= QLatin1Char('Z')) {
1580 // Apply group 'A' - 'Z'
1581 newGroupValue
= newFirstChar
;
1583 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1584 // Apply group '0 - 9' for any name that starts with a digit
1585 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1589 // If the current group is 'A' - 'Z' check whether a locale character
1590 // fits into the existing group.
1591 // TODO: This does not work in the case if e.g. the group 'O' starts with
1592 // an umlaut 'O' -> provide unit-test to document this known issue
1593 const QChar
prevChar(firstChar
.unicode() - ushort(1));
1594 const QChar
nextChar(firstChar
.unicode() + ushort(1));
1595 const QString
currChar(newFirstChar
);
1596 const bool partOfCurrentGroup
= currChar
.localeAwareCompare(prevChar
) > 0 &&
1597 currChar
.localeAwareCompare(nextChar
) < 0;
1598 if (partOfCurrentGroup
) {
1602 newGroupValue
= i18nc("@title:group", "Others");
1606 if (newGroupValue
!= groupValue
) {
1607 groupValue
= newGroupValue
;
1608 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1611 firstChar
= newFirstChar
;
1617 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1619 Q_ASSERT(!m_itemData
.isEmpty());
1621 const int maxIndex
= count() - 1;
1622 QList
<QPair
<int, QVariant
> > groups
;
1625 for (int i
= 0; i
<= maxIndex
; ++i
) {
1626 if (isChildItem(i
)) {
1630 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1631 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1632 QString newGroupValue
;
1633 if (!item
.isNull() && item
.isDir()) {
1634 newGroupValue
= i18nc("@title:group Size", "Folders");
1635 } else if (fileSize
< 5 * 1024 * 1024) {
1636 newGroupValue
= i18nc("@title:group Size", "Small");
1637 } else if (fileSize
< 10 * 1024 * 1024) {
1638 newGroupValue
= i18nc("@title:group Size", "Medium");
1640 newGroupValue
= i18nc("@title:group Size", "Big");
1643 if (newGroupValue
!= groupValue
) {
1644 groupValue
= newGroupValue
;
1645 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1652 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1654 Q_ASSERT(!m_itemData
.isEmpty());
1656 const int maxIndex
= count() - 1;
1657 QList
<QPair
<int, QVariant
> > groups
;
1659 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1661 QDate previousModifiedDate
;
1663 for (int i
= 0; i
<= maxIndex
; ++i
) {
1664 if (isChildItem(i
)) {
1668 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1669 const QDate modifiedDate
= modifiedTime
.date();
1670 if (modifiedDate
== previousModifiedDate
) {
1671 // The current item is in the same group as the previous item
1674 previousModifiedDate
= modifiedDate
;
1676 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1678 QString newGroupValue
;
1679 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1680 switch (daysDistance
/ 7) {
1682 switch (daysDistance
) {
1683 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1684 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1685 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1689 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
1692 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1695 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1699 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1705 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1706 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1707 if (daysDistance
== 1) {
1708 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1709 } else if (daysDistance
<= 7) {
1710 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A, %B is full month name in current locale, and %Y is full year number", "%A (%B, %Y)"));
1711 } else if (daysDistance
<= 7 * 2) {
1712 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "One Week Ago (%B, %Y)"));
1713 } else if (daysDistance
<= 7 * 3) {
1714 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Two Weeks Ago (%B, %Y)"));
1715 } else if (daysDistance
<= 7 * 4) {
1716 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Three Weeks Ago (%B, %Y)"));
1718 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Earlier on %B, %Y"));
1721 newGroupValue
= modifiedTime
.toString(i18nc("@title:group The month and year: %B is full month name in current locale, and %Y is full year number", "%B, %Y"));
1725 if (newGroupValue
!= groupValue
) {
1726 groupValue
= newGroupValue
;
1727 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1734 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1736 Q_ASSERT(!m_itemData
.isEmpty());
1738 const int maxIndex
= count() - 1;
1739 QList
<QPair
<int, QVariant
> > groups
;
1741 QString permissionsString
;
1743 for (int i
= 0; i
<= maxIndex
; ++i
) {
1744 if (isChildItem(i
)) {
1748 const ItemData
* itemData
= m_itemData
.at(i
);
1749 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1750 if (newPermissionsString
== permissionsString
) {
1753 permissionsString
= newPermissionsString
;
1755 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1759 if (info
.permission(QFile::ReadUser
)) {
1760 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1762 if (info
.permission(QFile::WriteUser
)) {
1763 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1765 if (info
.permission(QFile::ExeUser
)) {
1766 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1768 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1772 if (info
.permission(QFile::ReadGroup
)) {
1773 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1775 if (info
.permission(QFile::WriteGroup
)) {
1776 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1778 if (info
.permission(QFile::ExeGroup
)) {
1779 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1781 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1783 // Set others string
1785 if (info
.permission(QFile::ReadOther
)) {
1786 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1788 if (info
.permission(QFile::WriteOther
)) {
1789 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1791 if (info
.permission(QFile::ExeOther
)) {
1792 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1794 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1796 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1797 if (newGroupValue
!= groupValue
) {
1798 groupValue
= newGroupValue
;
1799 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1806 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1808 Q_ASSERT(!m_itemData
.isEmpty());
1810 const int maxIndex
= count() - 1;
1811 QList
<QPair
<int, QVariant
> > groups
;
1813 int groupValue
= -1;
1814 for (int i
= 0; i
<= maxIndex
; ++i
) {
1815 if (isChildItem(i
)) {
1818 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1819 if (newGroupValue
!= groupValue
) {
1820 groupValue
= newGroupValue
;
1821 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1828 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1830 Q_ASSERT(!m_itemData
.isEmpty());
1832 const int maxIndex
= count() - 1;
1833 QList
<QPair
<int, QVariant
> > groups
;
1835 bool isFirstGroupValue
= true;
1837 for (int i
= 0; i
<= maxIndex
; ++i
) {
1838 if (isChildItem(i
)) {
1841 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
1842 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
1843 groupValue
= newGroupValue
;
1844 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1845 isFirstGroupValue
= false;
1852 KFileItemList
KFileItemModel::childItems(const KFileItem
& item
) const
1854 KFileItemList items
;
1856 int index
= m_items
.value(item
.url(), -1);
1858 const int parentLevel
= m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt();
1860 while (index
< m_itemData
.count() && m_itemData
.at(index
)->values
.value("expandedParentsCount").toInt() > parentLevel
) {
1861 items
.append(m_itemData
.at(index
)->item
);
1869 void KFileItemModel::emitSortProgress(int resolvedCount
)
1871 // Be tolerant against a resolvedCount with a wrong range.
1872 // Although there should not be a case where KFileItemModelRolesUpdater
1873 // (= caller) provides a wrong range, it is important to emit
1874 // a useful progress information even if there is an unexpected
1875 // implementation issue.
1877 const int itemCount
= count();
1878 if (resolvedCount
>= itemCount
) {
1879 m_sortingProgressPercent
= -1;
1880 if (m_resortAllItemsTimer
->isActive()) {
1881 m_resortAllItemsTimer
->stop();
1885 emit
directorySortingProgress(100);
1886 } else if (itemCount
> 0) {
1887 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
1889 const int progress
= resolvedCount
* 100 / itemCount
;
1890 if (m_sortingProgressPercent
!= progress
) {
1891 m_sortingProgressPercent
= progress
;
1892 emit
directorySortingProgress(progress
);
1897 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
1899 static const RoleInfoMap rolesInfoMap
[] = {
1900 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
1901 { 0, NoRole
, 0, 0, 0, 0, false, false },
1902 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
1903 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
1904 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
1905 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
1906 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
1907 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
1908 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
1909 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1910 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
1911 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1912 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
1913 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1914 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1915 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1916 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
1917 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1918 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1919 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
1920 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1921 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1922 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
1925 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
1926 return rolesInfoMap
;
1929 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
1931 QElapsedTimer timer
;
1933 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
1934 item
.determineMimeType();
1935 if (timer
.elapsed() > timeout
) {
1936 // Don't block the user interface, let the remaining items
1937 // be resolved asynchronously.
1943 bool KFileItemModel::isConsistent() const
1945 if (m_items
.count() != m_itemData
.count()) {
1949 for (int i
= 0; i
< count(); ++i
) {
1950 // Check if m_items and m_itemData are consistent.
1951 const KFileItem item
= fileItem(i
);
1952 if (item
.isNull()) {
1953 qWarning() << "Item" << i
<< "is null";
1957 const int itemIndex
= index(item
);
1958 if (itemIndex
!= i
) {
1959 qWarning() << "Item" << i
<< "has a wrong index:" << itemIndex
;
1963 // Check if the items are sorted correctly.
1964 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
))) {
1965 qWarning() << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
1966 << fileItem(i
- 1) << fileItem(i
);
1970 // Check if all parent-child relationships are consistent.
1971 const ItemData
* data
= m_itemData
.at(i
);
1972 const ItemData
* parent
= data
->parent
;
1974 if (data
->values
.value("expandedParentsCount").toInt() != parent
->values
.value("expandedParentsCount").toInt() + 1) {
1975 qWarning() << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
1979 const int parentIndex
= index(parent
->item
);
1980 if (parentIndex
>= i
) {
1981 qWarning() << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
1990 #include "kfileitemmodel.moc"