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>
41 // #define KFILEITEMMODEL_DEBUG
43 KFileItemModel::KFileItemModel(QObject
* parent
) :
44 KItemModelBase("text", parent
),
46 m_naturalSorting(KGlobalSettings::naturalSorting()),
47 m_sortDirsFirst(true),
49 m_sortingProgressPercent(-1),
51 m_caseSensitivity(Qt::CaseInsensitive
),
57 m_maximumUpdateIntervalTimer(0),
58 m_resortAllItemsTimer(0),
59 m_pendingItemsToInsert(),
64 m_dirLister
= new KFileItemModelDirLister(this);
65 m_dirLister
->setDelayedMimeTypes(true);
67 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
69 m_dirLister
->setMainWindow(parentWidget
->window());
72 connect(m_dirLister
, SIGNAL(started(KUrl
)), this, SIGNAL(directoryLoadingStarted()));
73 connect(m_dirLister
, SIGNAL(canceled()), this, SLOT(slotCanceled()));
74 connect(m_dirLister
, SIGNAL(completed(KUrl
)), this, SLOT(slotCompleted()));
75 connect(m_dirLister
, SIGNAL(itemsAdded(KUrl
,KFileItemList
)), this, SLOT(slotItemsAdded(KUrl
,KFileItemList
)));
76 connect(m_dirLister
, SIGNAL(itemsDeleted(KFileItemList
)), this, SLOT(slotItemsDeleted(KFileItemList
)));
77 connect(m_dirLister
, SIGNAL(refreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)), this, SLOT(slotRefreshItems(QList
<QPair
<KFileItem
,KFileItem
> >)));
78 connect(m_dirLister
, SIGNAL(clear()), this, SLOT(slotClear()));
79 connect(m_dirLister
, SIGNAL(clear(KUrl
)), this, SLOT(slotClear(KUrl
)));
80 connect(m_dirLister
, SIGNAL(infoMessage(QString
)), this, SIGNAL(infoMessage(QString
)));
81 connect(m_dirLister
, SIGNAL(errorMessage(QString
)), this, SIGNAL(errorMessage(QString
)));
82 connect(m_dirLister
, SIGNAL(redirection(KUrl
,KUrl
)), this, SIGNAL(directoryRedirection(KUrl
,KUrl
)));
83 connect(m_dirLister
, SIGNAL(urlIsFileError(KUrl
)), this, SIGNAL(urlIsFileError(KUrl
)));
85 // Apply default roles that should be determined
87 m_requestRole
[NameRole
] = true;
88 m_requestRole
[IsDirRole
] = true;
89 m_requestRole
[IsLinkRole
] = true;
90 m_roles
.insert("text");
91 m_roles
.insert("isDir");
92 m_roles
.insert("isLink");
94 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
95 // before the completed() or canceled() signal has been emitted.
96 m_maximumUpdateIntervalTimer
= new QTimer(this);
97 m_maximumUpdateIntervalTimer
->setInterval(2000);
98 m_maximumUpdateIntervalTimer
->setSingleShot(true);
99 connect(m_maximumUpdateIntervalTimer
, SIGNAL(timeout()), this, SLOT(dispatchPendingItemsToInsert()));
101 // When changing the value of an item which represents the sort-role a resorting must be
102 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
103 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
104 // resorting is postponed until the timer has been exceeded.
105 m_resortAllItemsTimer
= new QTimer(this);
106 m_resortAllItemsTimer
->setInterval(500);
107 m_resortAllItemsTimer
->setSingleShot(true);
108 connect(m_resortAllItemsTimer
, SIGNAL(timeout()), this, SLOT(resortAllItems()));
110 connect(KGlobalSettings::self(), SIGNAL(naturalSortingChanged()), this, SLOT(slotNaturalSortingChanged()));
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
116 qDeleteAll(m_filteredItems
.values());
117 qDeleteAll(m_pendingItemsToInsert
);
120 void KFileItemModel::loadDirectory(const KUrl
& url
)
122 m_dirLister
->openUrl(url
);
125 void KFileItemModel::refreshDirectory(const KUrl
& url
)
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator
<KUrl
, KUrl
> expandedDirs(m_expandedDirs
);
129 while (expandedDirs
.hasNext()) {
131 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
134 m_dirLister
->openUrl(url
, KDirLister::Reload
);
137 KUrl
KFileItemModel::directory() const
139 return m_dirLister
->url();
142 void KFileItemModel::cancelDirectoryLoading()
147 int KFileItemModel::count() const
149 return m_itemData
.count();
152 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
154 if (index
>= 0 && index
< count()) {
155 ItemData
* data
= m_itemData
.at(index
);
156 if (data
->values
.isEmpty()) {
157 data
->values
= retrieveData(data
->item
, data
->parent
);
162 return QHash
<QByteArray
, QVariant
>();
165 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
167 if (index
< 0 || index
>= count()) {
171 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
173 // Determine which roles have been changed
174 QSet
<QByteArray
> changedRoles
;
175 QHashIterator
<QByteArray
, QVariant
> it(values
);
176 while (it
.hasNext()) {
178 const QByteArray role
= sharedValue(it
.key());
179 const QVariant value
= it
.value();
181 if (currentValues
[role
] != value
) {
182 currentValues
[role
] = value
;
183 changedRoles
.insert(role
);
187 if (changedRoles
.isEmpty()) {
191 m_itemData
[index
]->values
= currentValues
;
192 if (changedRoles
.contains("text")) {
193 KUrl url
= m_itemData
[index
]->item
.url();
194 url
.setFileName(currentValues
["text"].toString());
195 m_itemData
[index
]->item
.setUrl(url
);
198 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
203 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
205 if (dirsFirst
!= m_sortDirsFirst
) {
206 m_sortDirsFirst
= dirsFirst
;
211 bool KFileItemModel::sortDirectoriesFirst() const
213 return m_sortDirsFirst
;
216 void KFileItemModel::setShowHiddenFiles(bool show
)
218 m_dirLister
->setShowingDotFiles(show
);
219 m_dirLister
->emitChanges();
225 bool KFileItemModel::showHiddenFiles() const
227 return m_dirLister
->showingDotFiles();
230 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
232 m_dirLister
->setDirOnlyMode(enabled
);
235 bool KFileItemModel::showDirectoriesOnly() const
237 return m_dirLister
->dirOnlyMode();
240 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
242 QMimeData
* data
= new QMimeData();
244 // The following code has been taken from KDirModel::mimeData()
245 // (kdelibs/kio/kio/kdirmodel.cpp)
246 // Copyright (C) 2006 David Faure <faure@kde.org>
248 KUrl::List mostLocalUrls
;
249 bool canUseMostLocalUrls
= true;
251 foreach (int index
, indexes
) {
252 const KFileItem item
= fileItem(index
);
253 if (!item
.isNull()) {
254 urls
<< item
.targetUrl();
257 mostLocalUrls
<< item
.mostLocalUrl(isLocal
);
259 canUseMostLocalUrls
= false;
264 const bool different
= canUseMostLocalUrls
&& mostLocalUrls
!= urls
;
265 urls
= KDirModel::simplifiedUrlList(urls
); // TODO: Check if we still need KDirModel for this in KDE 5.0
267 mostLocalUrls
= KDirModel::simplifiedUrlList(mostLocalUrls
);
268 urls
.populateMimeData(mostLocalUrls
, data
);
270 urls
.populateMimeData(data
);
276 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
278 startFromIndex
= qMax(0, startFromIndex
);
279 for (int i
= startFromIndex
; i
< count(); ++i
) {
280 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
284 for (int i
= 0; i
< startFromIndex
; ++i
) {
285 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
292 bool KFileItemModel::supportsDropping(int index
) const
294 const KFileItem item
= fileItem(index
);
295 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
298 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
300 static QHash
<QByteArray
, QString
> description
;
301 if (description
.isEmpty()) {
303 const RoleInfoMap
* map
= rolesInfoMap(count
);
304 for (int i
= 0; i
< count
; ++i
) {
305 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
309 return description
.value(role
);
312 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
314 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
315 #ifdef KFILEITEMMODEL_DEBUG
319 switch (typeForRole(sortRole())) {
320 case NameRole
: m_groups
= nameRoleGroups(); break;
321 case SizeRole
: m_groups
= sizeRoleGroups(); break;
322 case DateRole
: m_groups
= dateRoleGroups(); break;
323 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
324 case RatingRole
: m_groups
= ratingRoleGroups(); break;
325 default: m_groups
= genericStringRoleGroups(sortRole()); break;
328 #ifdef KFILEITEMMODEL_DEBUG
329 kDebug() << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
336 KFileItem
KFileItemModel::fileItem(int index
) const
338 if (index
>= 0 && index
< count()) {
339 return m_itemData
.at(index
)->item
;
345 KFileItem
KFileItemModel::fileItem(const KUrl
& url
) const
347 const int index
= m_items
.value(url
, -1);
349 return m_itemData
.at(index
)->item
;
354 int KFileItemModel::index(const KFileItem
& item
) const
360 return m_items
.value(item
.url(), -1);
363 int KFileItemModel::index(const KUrl
& url
) const
365 KUrl urlToFind
= url
;
366 urlToFind
.adjustPath(KUrl::RemoveTrailingSlash
);
367 return m_items
.value(urlToFind
, -1);
370 KFileItem
KFileItemModel::rootItem() const
372 return m_dirLister
->rootItem();
375 void KFileItemModel::clear()
380 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
382 if (m_roles
== roles
) {
388 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
389 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
390 if (supportedExpanding
&& !willSupportExpanding
) {
391 // No expanding is supported anymore. Take care to delete all items that have an expansion level
392 // that is not 0 (and hence are part of an expanded item).
393 removeExpandedItems();
400 QSetIterator
<QByteArray
> it(roles
);
401 while (it
.hasNext()) {
402 const QByteArray
& role
= it
.next();
403 m_requestRole
[typeForRole(role
)] = true;
407 // Update m_data with the changed requested roles
408 const int maxIndex
= count() - 1;
409 for (int i
= 0; i
<= maxIndex
; ++i
) {
410 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
413 kWarning() << "TODO: Emitting itemsChanged() with no information what has changed!";
414 emit
itemsChanged(KItemRangeList() << KItemRange(0, count()), QSet
<QByteArray
>());
418 QSet
<QByteArray
> KFileItemModel::roles() const
423 bool KFileItemModel::setExpanded(int index
, bool expanded
)
425 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
429 QHash
<QByteArray
, QVariant
> values
;
430 values
.insert(sharedValue("isExpanded"), expanded
);
431 if (!setData(index
, values
)) {
435 const KFileItem item
= m_itemData
.at(index
)->item
;
436 const KUrl url
= item
.url();
437 const KUrl targetUrl
= item
.targetUrl();
439 m_expandedDirs
.insert(targetUrl
, url
);
440 m_dirLister
->openUrl(url
, KDirLister::Keep
);
442 const KUrl::List previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<KUrl::List
>();
443 foreach (const KUrl
& url
, previouslyExpandedChildren
) {
444 m_urlsToExpand
.insert(url
);
447 m_expandedDirs
.remove(targetUrl
);
448 m_dirLister
->stop(url
);
450 const int parentLevel
= expandedParentsCount(index
);
451 const int itemCount
= m_itemData
.count();
452 const int firstChildIndex
= index
+ 1;
454 KUrl::List expandedChildren
;
456 int childIndex
= firstChildIndex
;
457 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
458 ItemData
* itemData
= m_itemData
.at(childIndex
);
459 if (itemData
->values
.value("isExpanded").toBool()) {
460 const KUrl targetUrl
= itemData
->item
.targetUrl();
461 m_expandedDirs
.remove(targetUrl
);
462 expandedChildren
.append(targetUrl
);
466 const int childrenCount
= childIndex
- firstChildIndex
;
468 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
469 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
471 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
477 bool KFileItemModel::isExpanded(int index
) const
479 if (index
>= 0 && index
< count()) {
480 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
485 bool KFileItemModel::isExpandable(int index
) const
487 if (index
>= 0 && index
< count()) {
488 // Call data (instead of accessing m_itemData directly)
489 // to ensure that the value is initialized.
490 return data(index
).value("isExpandable").toBool();
495 int KFileItemModel::expandedParentsCount(int index
) const
497 if (index
>= 0 && index
< count()) {
498 return expandedParentsCount(m_itemData
.at(index
));
503 QSet
<KUrl
> KFileItemModel::expandedDirectories() const
505 return m_expandedDirs
.values().toSet();
508 void KFileItemModel::restoreExpandedDirectories(const QSet
<KUrl
>& urls
)
510 m_urlsToExpand
= urls
;
513 void KFileItemModel::expandParentDirectories(const KUrl
& url
)
515 const int pos
= m_dirLister
->url().path().length();
517 // Assure that each sub-path of the URL that should be
518 // expanded is added to m_urlsToExpand. KDirLister
519 // does not care whether the parent-URL has already been
521 KUrl urlToExpand
= m_dirLister
->url();
522 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator());
523 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
524 urlToExpand
.addPath(subDirs
.at(i
));
525 m_urlsToExpand
.insert(urlToExpand
);
528 // KDirLister::open() must called at least once to trigger an initial
529 // loading. The pending URLs that must be restored are handled
530 // in slotCompleted().
531 QSetIterator
<KUrl
> it2(m_urlsToExpand
);
532 while (it2
.hasNext()) {
533 const int idx
= index(it2
.next());
534 if (idx
>= 0 && !isExpanded(idx
)) {
535 setExpanded(idx
, true);
541 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
543 if (m_filter
.pattern() != nameFilter
) {
544 dispatchPendingItemsToInsert();
545 m_filter
.setPattern(nameFilter
);
550 QString
KFileItemModel::nameFilter() const
552 return m_filter
.pattern();
555 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
557 if (m_filter
.mimeTypes() != filters
) {
558 dispatchPendingItemsToInsert();
559 m_filter
.setMimeTypes(filters
);
564 QStringList
KFileItemModel::mimeTypeFilters() const
566 return m_filter
.mimeTypes();
570 void KFileItemModel::applyFilters()
572 // Check which shown items from m_itemData must get
573 // hidden and hence moved to m_filteredItems.
574 QVector
<int> newFilteredIndexes
;
576 const int itemCount
= m_itemData
.count();
577 for (int index
= 0; index
< itemCount
; ++index
) {
578 ItemData
* itemData
= m_itemData
.at(index
);
580 // Only filter non-expanded items as child items may never
581 // exist without a parent item
582 if (!itemData
->values
.value("isExpanded").toBool()) {
583 const KFileItem item
= itemData
->item
;
584 if (!m_filter
.matches(item
)) {
585 newFilteredIndexes
.append(index
);
586 m_filteredItems
.insert(item
, itemData
);
591 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
592 removeItems(removedRanges
, KeepItemData
);
594 // Check which hidden items from m_filteredItems should
595 // get visible again and hence removed from m_filteredItems.
596 QList
<ItemData
*> newVisibleItems
;
598 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
599 while (it
!= m_filteredItems
.end()) {
600 if (m_filter
.matches(it
.key())) {
601 newVisibleItems
.append(it
.value());
602 it
= m_filteredItems
.erase(it
);
608 insertItems(newVisibleItems
);
611 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
613 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
614 // There are either no filtered items, or it is not possible to expand
615 // folders -> there cannot be any filtered children.
619 QSet
<ItemData
*> parents
;
620 foreach (const KItemRange
& range
, itemRanges
) {
621 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
622 parents
.insert(m_itemData
.at(index
));
626 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
627 while (it
!= m_filteredItems
.end()) {
628 if (parents
.contains(it
.value()->parent
)) {
630 it
= m_filteredItems
.erase(it
);
637 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
639 static QList
<RoleInfo
> rolesInfo
;
640 if (rolesInfo
.isEmpty()) {
642 const RoleInfoMap
* map
= rolesInfoMap(count
);
643 for (int i
= 0; i
< count
; ++i
) {
644 if (map
[i
].roleType
!= NoRole
) {
646 info
.role
= map
[i
].role
;
647 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
648 if (map
[i
].groupTranslation
) {
649 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
651 // For top level roles, groupTranslation is 0. We must make sure that
652 // info.group is an empty string then because the code that generates
653 // menus tries to put the actions into sub menus otherwise.
654 info
.group
= QString();
656 info
.requiresNepomuk
= map
[i
].requiresNepomuk
;
657 info
.requiresIndexer
= map
[i
].requiresIndexer
;
658 rolesInfo
.append(info
);
666 void KFileItemModel::onGroupedSortingChanged(bool current
)
672 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
)
675 m_sortRole
= typeForRole(current
);
677 if (!m_requestRole
[m_sortRole
]) {
678 QSet
<QByteArray
> newRoles
= m_roles
;
686 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
693 void KFileItemModel::resortAllItems()
695 m_resortAllItemsTimer
->stop();
697 const int itemCount
= count();
698 if (itemCount
<= 0) {
702 #ifdef KFILEITEMMODEL_DEBUG
705 kDebug() << "===========================================================";
706 kDebug() << "Resorting" << itemCount
<< "items";
709 // Remember the order of the current URLs so
710 // that it can be determined which indexes have
711 // been moved because of the resorting.
713 oldUrls
.reserve(itemCount
);
714 foreach (const ItemData
* itemData
, m_itemData
) {
715 oldUrls
.append(itemData
->item
.url());
721 sort(m_itemData
.begin(), m_itemData
.end());
722 for (int i
= 0; i
< itemCount
; ++i
) {
723 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
726 // Determine the first index that has been moved.
727 int firstMovedIndex
= 0;
728 while (firstMovedIndex
< itemCount
729 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
733 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
734 if (itemsHaveMoved
) {
737 int lastMovedIndex
= itemCount
- 1;
738 while (lastMovedIndex
> firstMovedIndex
739 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
743 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
745 // Create a list movedToIndexes, which has the property that
746 // movedToIndexes[i] is the new index of the item with the old index
747 // firstMovedIndex + i.
748 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
749 QList
<int> movedToIndexes
;
750 movedToIndexes
.reserve(movedItemsCount
);
751 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
752 const int newIndex
= m_items
.value(oldUrls
.at(i
));
753 movedToIndexes
.append(newIndex
);
756 emit
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
757 } else if (groupedSorting()) {
758 // The groups might have changed even if the order of the items has not.
759 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
761 if (groups() != oldGroups
) {
762 emit
groupsChanged();
766 #ifdef KFILEITEMMODEL_DEBUG
767 kDebug() << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
771 void KFileItemModel::slotCompleted()
773 dispatchPendingItemsToInsert();
775 if (!m_urlsToExpand
.isEmpty()) {
776 // Try to find a URL that can be expanded.
777 // Note that the parent folder must be expanded before any of its subfolders become visible.
778 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
779 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
780 foreach (const KUrl
& url
, m_urlsToExpand
) {
781 const int index
= m_items
.value(url
, -1);
783 m_urlsToExpand
.remove(url
);
784 if (setExpanded(index
, true)) {
785 // The dir lister has been triggered. This slot will be called
786 // again after the directory has been expanded.
792 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
793 // if these URLs have been deleted in the meantime.
794 m_urlsToExpand
.clear();
797 emit
directoryLoadingCompleted();
800 void KFileItemModel::slotCanceled()
802 m_maximumUpdateIntervalTimer
->stop();
803 dispatchPendingItemsToInsert();
805 emit
directoryLoadingCanceled();
808 void KFileItemModel::slotItemsAdded(const KUrl
& directoryUrl
, const KFileItemList
& items
)
810 Q_ASSERT(!items
.isEmpty());
813 if (m_expandedDirs
.contains(directoryUrl
)) {
814 parentUrl
= m_expandedDirs
.value(directoryUrl
);
816 parentUrl
= directoryUrl
;
817 parentUrl
.adjustPath(KUrl::RemoveTrailingSlash
);
820 if (m_requestRole
[ExpandedParentsCountRole
]) {
821 KFileItem item
= items
.first();
823 // If the expanding of items is enabled, the call
824 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
825 // might result in emitting the same items twice due to the Keep-parameter.
826 // This case happens if an item gets expanded, collapsed and expanded again
827 // before the items could be loaded for the first expansion.
828 const int index
= m_items
.value(item
.url(), -1);
830 // The items are already part of the model.
834 if (directoryUrl
!= directory()) {
835 // To be able to compare whether the new items may be inserted as children
836 // of a parent item the pending items must be added to the model first.
837 dispatchPendingItemsToInsert();
840 // KDirLister keeps the children of items that got expanded once even if
841 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
842 // checked whether the parent for new items is still expanded.
843 const int parentIndex
= m_items
.value(parentUrl
, -1);
844 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
845 // The parent is not expanded.
850 QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
852 if (!m_filter
.hasSetFilters()) {
853 m_pendingItemsToInsert
.append(itemDataList
);
855 // The name or type filter is active. Hide filtered items
856 // before inserting them into the model and remember
857 // the filtered items in m_filteredItems.
858 foreach (ItemData
* itemData
, itemDataList
) {
859 if (m_filter
.matches(itemData
->item
)) {
860 m_pendingItemsToInsert
.append(itemData
);
862 m_filteredItems
.insert(itemData
->item
, itemData
);
867 if (useMaximumUpdateInterval() && !m_maximumUpdateIntervalTimer
->isActive()) {
868 // Assure that items get dispatched if no completed() or canceled() signal is
869 // emitted during the maximum update interval.
870 m_maximumUpdateIntervalTimer
->start();
874 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
876 dispatchPendingItemsToInsert();
878 QVector
<int> indexesToRemove
;
879 indexesToRemove
.reserve(items
.count());
881 foreach (const KFileItem
& item
, items
) {
882 const KUrl url
= item
.url();
883 const int index
= m_items
.value(url
, -1);
885 indexesToRemove
.append(index
);
887 // Probably the item has been filtered.
888 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
889 if (it
!= m_filteredItems
.end()) {
891 m_filteredItems
.erase(it
);
896 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
898 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
899 // Assure that removing a parent item also results in removing all children
900 QVector
<int> indexesToRemoveWithChildren
;
901 indexesToRemoveWithChildren
.reserve(m_items
.count());
903 const int itemCount
= m_itemData
.count();
904 foreach (int index
, indexesToRemove
) {
905 indexesToRemoveWithChildren
.append(index
);
907 const int parentLevel
= expandedParentsCount(index
);
908 int childIndex
= index
+ 1;
909 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
910 indexesToRemoveWithChildren
.append(childIndex
);
915 indexesToRemove
= indexesToRemoveWithChildren
;
918 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
919 removeFilteredChildren(itemRanges
);
920 removeItems(itemRanges
, DeleteItemData
);
923 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
925 Q_ASSERT(!items
.isEmpty());
926 #ifdef KFILEITEMMODEL_DEBUG
927 kDebug() << "Refreshing" << items
.count() << "items";
930 // Get the indexes of all items that have been refreshed
932 indexes
.reserve(items
.count());
934 QSet
<QByteArray
> changedRoles
;
936 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
937 while (it
.hasNext()) {
938 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
939 const KFileItem
& oldItem
= itemPair
.first
;
940 const KFileItem
& newItem
= itemPair
.second
;
941 const int index
= m_items
.value(oldItem
.url(), -1);
943 m_itemData
[index
]->item
= newItem
;
945 // Keep old values as long as possible if they could not retrieved synchronously yet.
946 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
947 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(index
)->parent
));
948 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[index
]->values
;
949 while (it
.hasNext()) {
951 const QByteArray
& role
= it
.key();
952 if (values
.value(role
) != it
.value()) {
953 values
.insert(role
, it
.value());
954 changedRoles
.insert(role
);
958 m_items
.remove(oldItem
.url());
959 m_items
.insert(newItem
.url(), index
);
960 indexes
.append(index
);
964 // If the changed items have been created recently, they might not be in m_items yet.
965 // In that case, the list 'indexes' might be empty.
966 if (indexes
.isEmpty()) {
970 // Extract the item-ranges out of the changed indexes
972 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
973 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
976 void KFileItemModel::slotClear()
978 #ifdef KFILEITEMMODEL_DEBUG
979 kDebug() << "Clearing all items";
982 qDeleteAll(m_filteredItems
.values());
983 m_filteredItems
.clear();
986 m_maximumUpdateIntervalTimer
->stop();
987 m_resortAllItemsTimer
->stop();
989 qDeleteAll(m_pendingItemsToInsert
);
990 m_pendingItemsToInsert
.clear();
992 const int removedCount
= m_itemData
.count();
993 if (removedCount
> 0) {
994 qDeleteAll(m_itemData
);
997 emit
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1000 m_expandedDirs
.clear();
1003 void KFileItemModel::slotClear(const KUrl
& url
)
1008 void KFileItemModel::slotNaturalSortingChanged()
1010 m_naturalSorting
= KGlobalSettings::naturalSorting();
1014 void KFileItemModel::dispatchPendingItemsToInsert()
1016 if (!m_pendingItemsToInsert
.isEmpty()) {
1017 insertItems(m_pendingItemsToInsert
);
1018 m_pendingItemsToInsert
.clear();
1022 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1024 if (newItems
.isEmpty()) {
1028 #ifdef KFILEITEMMODEL_DEBUG
1029 QElapsedTimer timer
;
1031 kDebug() << "===========================================================";
1032 kDebug() << "Inserting" << newItems
.count() << "items";
1037 if (m_sortRole
== NameRole
&& m_naturalSorting
) {
1038 // Natural sorting of items can be very slow. However, it becomes much
1039 // faster if the input sequence is already mostly sorted. Therefore, we
1040 // first sort 'newItems' according to the QStrings returned by
1041 // KFileItem::text() using QString::operator<(), which is quite fast.
1042 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1045 sort(newItems
.begin(), newItems
.end());
1047 #ifdef KFILEITEMMODEL_DEBUG
1048 kDebug() << "[TIME] Sorting:" << timer
.elapsed();
1051 KItemRangeList itemRanges
;
1052 const int existingItemCount
= m_itemData
.count();
1053 const int newItemCount
= newItems
.count();
1054 const int totalItemCount
= existingItemCount
+ newItemCount
;
1056 if (existingItemCount
== 0) {
1057 // Optimization for the common special case that there are no
1058 // items in the model yet. Happens, e.g., when entering a folder.
1059 m_itemData
= newItems
;
1060 itemRanges
<< KItemRange(0, newItemCount
);
1062 m_itemData
.reserve(totalItemCount
);
1063 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1064 m_itemData
.append(0);
1067 // We build the new list m_items in reverse order to minimize
1068 // the number of moves and guarantee O(N) complexity.
1069 int targetIndex
= totalItemCount
- 1;
1070 int sourceIndexExistingItems
= existingItemCount
- 1;
1071 int sourceIndexNewItems
= newItemCount
- 1;
1075 while (sourceIndexNewItems
>= 0) {
1076 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1077 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
))) {
1078 // Move an existing item to its new position. If any new items
1079 // are behind it, push the item range to itemRanges.
1080 if (rangeCount
> 0) {
1081 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1085 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1086 --sourceIndexExistingItems
;
1088 // Insert a new item into the list.
1090 m_itemData
[targetIndex
] = newItem
;
1091 --sourceIndexNewItems
;
1096 // Push the final item range to itemRanges.
1097 if (rangeCount
> 0) {
1098 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1101 // Note that itemRanges is still sorted in reverse order.
1102 std::reverse(itemRanges
.begin(), itemRanges
.end());
1105 // The indexes starting from the first inserted item must be adjusted.
1106 m_items
.reserve(totalItemCount
);
1107 for (int i
= itemRanges
.front().index
; i
< totalItemCount
; ++i
) {
1108 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1111 emit
itemsInserted(itemRanges
);
1113 #ifdef KFILEITEMMODEL_DEBUG
1114 kDebug() << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1118 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1120 if (itemRanges
.isEmpty()) {
1126 // Step 1: Remove the items from the hash m_items, and free the ItemData.
1127 int removedItemsCount
= 0;
1128 foreach (const KItemRange
& range
, itemRanges
) {
1129 removedItemsCount
+= range
.count
;
1131 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1132 const KUrl url
= m_itemData
.at(index
)->item
.url();
1134 // Prevent repeated expensive rehashing by using QHash::erase(),
1135 // rather than QHash::remove().
1136 QHash
<KUrl
, int>::iterator it
= m_items
.find(url
);
1139 if (behavior
== DeleteItemData
) {
1140 delete m_itemData
.at(index
);
1143 m_itemData
[index
] = 0;
1147 // Step 2: Remove the ItemData pointers from the list m_itemData.
1148 int target
= itemRanges
.at(0).index
;
1149 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1152 const int oldItemDataCount
= m_itemData
.count();
1153 while (source
< oldItemDataCount
) {
1154 m_itemData
[target
] = m_itemData
[source
];
1158 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1159 // Skip the items in the next removed range.
1160 source
+= itemRanges
.at(nextRange
).count
;
1165 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1167 // Step 3: Adjust indexes in the hash m_items, starting from the
1168 // index of the first removed item.
1169 const int newItemDataCount
= m_itemData
.count();
1170 for (int i
= itemRanges
.front().index
; i
< newItemDataCount
; ++i
) {
1171 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1174 emit
itemsRemoved(itemRanges
);
1177 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const KUrl
& parentUrl
, const KFileItemList
& items
) const
1179 if (m_sortRole
== TypeRole
) {
1180 // Try to resolve the MIME-types synchronously to prevent a reordering of
1181 // the items when sorting by type (per default MIME-types are resolved
1182 // asynchronously by KFileItemModelRolesUpdater).
1183 determineMimeTypes(items
, 200);
1186 const int parentIndex
= m_items
.value(parentUrl
, -1);
1187 ItemData
* parentItem
= parentIndex
< 0 ? 0 : m_itemData
.at(parentIndex
);
1189 QList
<ItemData
*> itemDataList
;
1190 itemDataList
.reserve(items
.count());
1192 foreach (const KFileItem
& item
, items
) {
1193 ItemData
* itemData
= new ItemData();
1194 itemData
->item
= item
;
1195 itemData
->parent
= parentItem
;
1196 itemDataList
.append(itemData
);
1199 switch (m_sortRole
) {
1200 case PermissionsRole
:
1203 case DestinationRole
:
1205 // These roles can be determined with retrieveData, and they have to be stored
1206 // in the QHash "values" for the sorting.
1207 foreach (ItemData
* itemData
, itemDataList
) {
1208 itemData
->values
= retrieveData(itemData
->item
, parentItem
);
1213 // At least store the data including the file type for items with known MIME type.
1214 foreach (ItemData
* itemData
, itemDataList
) {
1215 const KFileItem item
= itemData
->item
;
1216 if (item
.isDir() || item
.isMimeTypeKnown()) {
1217 itemData
->values
= retrieveData(itemData
->item
, parentItem
);
1223 // The other roles are either resolved by KFileItemModelRolesUpdater
1224 // (this includes the SizeRole for directories), or they do not need
1225 // to be stored in the QHash "values" for sorting because the data can
1226 // be retrieved directly from the KFileItem (NameRole, SiezRole for files,
1231 return itemDataList
;
1234 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1236 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1237 // if the corresponding item is expanded, and it is not a top-level item.
1238 const ItemData
* parent
= data
->parent
;
1240 if (parent
->parent
) {
1241 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1242 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1251 void KFileItemModel::removeExpandedItems()
1253 QVector
<int> indexesToRemove
;
1255 const int maxIndex
= m_itemData
.count() - 1;
1256 for (int i
= 0; i
<= maxIndex
; ++i
) {
1257 const ItemData
* itemData
= m_itemData
.at(i
);
1258 if (itemData
->parent
) {
1259 indexesToRemove
.append(i
);
1263 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1264 m_expandedDirs
.clear();
1266 // Also remove all filtered items which have a parent.
1267 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1268 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1271 if (it
.value()->parent
) {
1273 it
= m_filteredItems
.erase(it
);
1280 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1282 emit
itemsChanged(itemRanges
, changedRoles
);
1284 // Trigger a resorting if necessary. Note that this can happen even if the sort
1285 // role has not changed at all because the file name can be used as a fallback.
1286 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1287 foreach (const KItemRange
& range
, itemRanges
) {
1288 bool needsResorting
= false;
1290 const int first
= range
.index
;
1291 const int last
= range
.index
+ range
.count
- 1;
1293 // Resorting the model is necessary if
1294 // (a) The first item in the range is "lessThan" its predecessor,
1295 // (b) the successor of the last item is "lessThan" the last item, or
1296 // (c) the internal order of the items in the range is incorrect.
1298 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1))) {
1299 needsResorting
= true;
1300 } else if (last
< count() - 1
1301 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
))) {
1302 needsResorting
= true;
1304 for (int index
= first
; index
< last
; ++index
) {
1305 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
))) {
1306 needsResorting
= true;
1312 if (needsResorting
) {
1313 m_resortAllItemsTimer
->start();
1319 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1320 // The position is still correct, but the groups might have changed
1321 // if the changed item is either the first or the last item in a
1323 // In principle, we could try to find out if the item really is the
1324 // first or last one in its group and then update the groups
1325 // (possibly with a delayed timer to make sure that we don't
1326 // re-calculate the groups very often if items are updated one by
1327 // one), but starting m_resortAllItemsTimer is easier.
1328 m_resortAllItemsTimer
->start();
1332 void KFileItemModel::resetRoles()
1334 for (int i
= 0; i
< RolesCount
; ++i
) {
1335 m_requestRole
[i
] = false;
1339 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1341 static QHash
<QByteArray
, RoleType
> roles
;
1342 if (roles
.isEmpty()) {
1343 // Insert user visible roles that can be accessed with
1344 // KFileItemModel::roleInformation()
1346 const RoleInfoMap
* map
= rolesInfoMap(count
);
1347 for (int i
= 0; i
< count
; ++i
) {
1348 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1351 // Insert internal roles (take care to synchronize the implementation
1352 // with KFileItemModel::roleForType() in case if a change is done).
1353 roles
.insert("isDir", IsDirRole
);
1354 roles
.insert("isLink", IsLinkRole
);
1355 roles
.insert("isExpanded", IsExpandedRole
);
1356 roles
.insert("isExpandable", IsExpandableRole
);
1357 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1359 Q_ASSERT(roles
.count() == RolesCount
);
1362 return roles
.value(role
, NoRole
);
1365 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1367 static QHash
<RoleType
, QByteArray
> roles
;
1368 if (roles
.isEmpty()) {
1369 // Insert user visible roles that can be accessed with
1370 // KFileItemModel::roleInformation()
1372 const RoleInfoMap
* map
= rolesInfoMap(count
);
1373 for (int i
= 0; i
< count
; ++i
) {
1374 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1377 // Insert internal roles (take care to synchronize the implementation
1378 // with KFileItemModel::typeForRole() in case if a change is done).
1379 roles
.insert(IsDirRole
, "isDir");
1380 roles
.insert(IsLinkRole
, "isLink");
1381 roles
.insert(IsExpandedRole
, "isExpanded");
1382 roles
.insert(IsExpandableRole
, "isExpandable");
1383 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1385 Q_ASSERT(roles
.count() == RolesCount
);
1388 return roles
.value(roleType
);
1391 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1393 // It is important to insert only roles that are fast to retrieve. E.g.
1394 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1395 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1396 QHash
<QByteArray
, QVariant
> data
;
1397 data
.insert(sharedValue("url"), item
.url());
1399 const bool isDir
= item
.isDir();
1400 if (m_requestRole
[IsDirRole
] && isDir
) {
1401 data
.insert(sharedValue("isDir"), true);
1404 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1405 data
.insert(sharedValue("isLink"), true);
1408 if (m_requestRole
[NameRole
]) {
1409 data
.insert(sharedValue("text"), item
.text());
1412 if (m_requestRole
[SizeRole
] && !isDir
) {
1413 data
.insert(sharedValue("size"), item
.size());
1416 if (m_requestRole
[DateRole
]) {
1417 // Don't use KFileItem::timeString() as this is too expensive when
1418 // having several thousands of items. Instead the formatting of the
1419 // date-time will be done on-demand by the view when the date will be shown.
1420 const KDateTime dateTime
= item
.time(KFileItem::ModificationTime
);
1421 data
.insert(sharedValue("date"), dateTime
.dateTime());
1424 if (m_requestRole
[PermissionsRole
]) {
1425 data
.insert(sharedValue("permissions"), item
.permissionsString());
1428 if (m_requestRole
[OwnerRole
]) {
1429 data
.insert(sharedValue("owner"), item
.user());
1432 if (m_requestRole
[GroupRole
]) {
1433 data
.insert(sharedValue("group"), item
.group());
1436 if (m_requestRole
[DestinationRole
]) {
1437 QString destination
= item
.linkDest();
1438 if (destination
.isEmpty()) {
1439 destination
= QLatin1String("-");
1441 data
.insert(sharedValue("destination"), destination
);
1444 if (m_requestRole
[PathRole
]) {
1446 if (item
.url().protocol() == QLatin1String("trash")) {
1447 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1449 // For performance reasons cache the home-path in a static QString
1450 // (see QDir::homePath() for more details)
1451 static QString homePath
;
1452 if (homePath
.isEmpty()) {
1453 homePath
= QDir::homePath();
1456 path
= item
.localPath();
1457 if (path
.startsWith(homePath
)) {
1458 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1462 const int index
= path
.lastIndexOf(item
.text());
1463 path
= path
.mid(0, index
- 1);
1464 data
.insert(sharedValue("path"), path
);
1467 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1468 data
.insert(sharedValue("isExpandable"), true);
1471 if (m_requestRole
[ExpandedParentsCountRole
]) {
1473 const int level
= expandedParentsCount(parent
) + 1;
1474 data
.insert(sharedValue("expandedParentsCount"), level
);
1478 if (item
.isMimeTypeKnown()) {
1479 data
.insert(sharedValue("iconName"), item
.iconName());
1481 if (m_requestRole
[TypeRole
]) {
1482 data
.insert(sharedValue("type"), item
.mimeComment());
1484 } else if (m_requestRole
[TypeRole
] && isDir
) {
1485 static const QString folderMimeType
= item
.mimeComment();
1486 data
.insert(sharedValue("type"), folderMimeType
);
1492 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
) const
1496 if (a
->parent
!= b
->parent
) {
1497 const int expansionLevelA
= expandedParentsCount(a
);
1498 const int expansionLevelB
= expandedParentsCount(b
);
1500 // If b has a higher expansion level than a, check if a is a parent
1501 // of b, and make sure that both expansion levels are equal otherwise.
1502 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1503 if (b
->parent
== a
) {
1509 // If a has a higher expansion level than a, check if b is a parent
1510 // of a, and make sure that both expansion levels are equal otherwise.
1511 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1512 if (a
->parent
== b
) {
1518 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1520 // Compare the last parents of a and b which are different.
1521 while (a
->parent
!= b
->parent
) {
1527 if (m_sortDirsFirst
|| m_sortRole
== SizeRole
) {
1528 const bool isDirA
= a
->item
.isDir();
1529 const bool isDirB
= b
->item
.isDir();
1530 if (isDirA
&& !isDirB
) {
1532 } else if (!isDirA
&& isDirB
) {
1537 result
= sortRoleCompare(a
, b
);
1539 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1543 * Helper class for KFileItemModel::sort().
1545 class KFileItemModelLessThan
1548 KFileItemModelLessThan(const KFileItemModel
* model
) :
1553 bool operator()(const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
) const
1555 return m_model
->lessThan(a
, b
);
1559 const KFileItemModel
* m_model
;
1562 void KFileItemModel::sort(QList
<KFileItemModel::ItemData
*>::iterator begin
,
1563 QList
<KFileItemModel::ItemData
*>::iterator end
) const
1565 KFileItemModelLessThan
lessThan(this);
1567 if (m_sortRole
== NameRole
) {
1568 // Sorting by name can be expensive, in particular if natural sorting is
1569 // enabled. Use all CPU cores to speed up the sorting process.
1570 static const int numberOfThreads
= QThread::idealThreadCount();
1571 parallelMergeSort(begin
, end
, lessThan
, numberOfThreads
);
1573 // Sorting by other roles is quite fast. Use only one thread to prevent
1574 // problems caused by non-reentrant comparison functions, see
1575 // https://bugs.kde.org/show_bug.cgi?id=312679
1576 mergeSort(begin
, end
, lessThan
);
1580 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
) const
1582 const KFileItem
& itemA
= a
->item
;
1583 const KFileItem
& itemB
= b
->item
;
1587 switch (m_sortRole
) {
1589 // The name role is handled as default fallback after the switch
1593 if (itemA
.isDir()) {
1594 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1595 Q_ASSERT(itemB
.isDir());
1597 const QVariant valueA
= a
->values
.value("size");
1598 const QVariant valueB
= b
->values
.value("size");
1599 if (valueA
.isNull() && valueB
.isNull()) {
1601 } else if (valueA
.isNull()) {
1603 } else if (valueB
.isNull()) {
1606 result
= valueA
.toInt() - valueB
.toInt();
1609 // See "if (m_sortFoldersFirst || m_sortRole == SizeRole)" in KFileItemModel::lessThan():
1610 Q_ASSERT(!itemB
.isDir());
1611 const KIO::filesize_t sizeA
= itemA
.size();
1612 const KIO::filesize_t sizeB
= itemB
.size();
1613 if (sizeA
> sizeB
) {
1615 } else if (sizeA
< sizeB
) {
1625 const KDateTime dateTimeA
= itemA
.time(KFileItem::ModificationTime
);
1626 const KDateTime dateTimeB
= itemB
.time(KFileItem::ModificationTime
);
1627 if (dateTimeA
< dateTimeB
) {
1629 } else if (dateTimeA
> dateTimeB
) {
1636 result
= a
->values
.value("rating").toInt() - b
->values
.value("rating").toInt();
1640 case ImageSizeRole
: {
1641 // Alway use a natural comparing to interpret the numbers of a string like
1642 // "1600 x 1200" for having a correct sorting.
1643 result
= KStringHandler::naturalCompare(a
->values
.value("imageSize").toString(),
1644 b
->values
.value("imageSize").toString(),
1650 const QByteArray role
= roleForType(m_sortRole
);
1651 result
= QString::compare(a
->values
.value(role
).toString(),
1652 b
->values
.value(role
).toString());
1659 // The current sort role was sufficient to define an order
1663 // Fallback #1: Compare the text of the items
1664 result
= stringCompare(itemA
.text(), itemB
.text());
1669 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1670 result
= stringCompare(itemA
.name(m_caseSensitivity
== Qt::CaseInsensitive
),
1671 itemB
.name(m_caseSensitivity
== Qt::CaseInsensitive
));
1676 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1677 // equal. In this case a comparison of the URL is done which is unique in all cases
1678 // within KDirLister.
1679 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1682 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
) const
1684 // Taken from KDirSortFilterProxyModel (kdelibs/kfile/kdirsortfilterproxymodel.*)
1685 // Copyright (C) 2006 by Peter Penz <peter.penz@gmx.at>
1686 // Copyright (C) 2006 by Dominic Battre <dominic@battre.de>
1687 // Copyright (C) 2006 by Martin Pool <mbp@canonical.com>
1689 if (m_caseSensitivity
== Qt::CaseInsensitive
) {
1690 const int result
= m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseInsensitive
)
1691 : QString::compare(a
, b
, Qt::CaseInsensitive
);
1693 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1694 // comparison, still a deterministic sort order is required. A case sensitive
1695 // comparison is done as fallback.
1700 return m_naturalSorting
? KStringHandler::naturalCompare(a
, b
, Qt::CaseSensitive
)
1701 : QString::compare(a
, b
, Qt::CaseSensitive
);
1704 bool KFileItemModel::useMaximumUpdateInterval() const
1706 return !m_dirLister
->url().isLocalFile();
1709 static bool localeAwareLessThan(const QChar
& c1
, const QChar
& c2
)
1711 return QString::localeAwareCompare(c1
, c2
) < 0;
1714 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1716 Q_ASSERT(!m_itemData
.isEmpty());
1718 const int maxIndex
= count() - 1;
1719 QList
<QPair
<int, QVariant
> > groups
;
1723 for (int i
= 0; i
<= maxIndex
; ++i
) {
1724 if (isChildItem(i
)) {
1728 const QString name
= m_itemData
.at(i
)->item
.text();
1730 // Use the first character of the name as group indication
1731 QChar newFirstChar
= name
.at(0).toUpper();
1732 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1733 newFirstChar
= name
.at(1).toUpper();
1736 if (firstChar
!= newFirstChar
) {
1737 QString newGroupValue
;
1738 if (newFirstChar
.isLetter()) {
1739 // Try to find a matching group in the range 'A' to 'Z'.
1740 static std::vector
<QChar
> lettersAtoZ
;
1741 if (lettersAtoZ
.empty()) {
1742 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1743 lettersAtoZ
.push_back(QLatin1Char(c
));
1747 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1748 if (it
!= lettersAtoZ
.end()) {
1749 if (localeAwareLessThan(newFirstChar
, *it
) && it
!= lettersAtoZ
.begin()) {
1750 // newFirstChar belongs to the group preceding *it.
1751 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1754 newGroupValue
= *it
;
1756 newGroupValue
= newFirstChar
;
1758 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1759 // Apply group '0 - 9' for any name that starts with a digit
1760 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1762 newGroupValue
= i18nc("@title:group", "Others");
1765 if (newGroupValue
!= groupValue
) {
1766 groupValue
= newGroupValue
;
1767 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1770 firstChar
= newFirstChar
;
1776 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1778 Q_ASSERT(!m_itemData
.isEmpty());
1780 const int maxIndex
= count() - 1;
1781 QList
<QPair
<int, QVariant
> > groups
;
1784 for (int i
= 0; i
<= maxIndex
; ++i
) {
1785 if (isChildItem(i
)) {
1789 const KFileItem
& item
= m_itemData
.at(i
)->item
;
1790 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
1791 QString newGroupValue
;
1792 if (!item
.isNull() && item
.isDir()) {
1793 newGroupValue
= i18nc("@title:group Size", "Folders");
1794 } else if (fileSize
< 5 * 1024 * 1024) {
1795 newGroupValue
= i18nc("@title:group Size", "Small");
1796 } else if (fileSize
< 10 * 1024 * 1024) {
1797 newGroupValue
= i18nc("@title:group Size", "Medium");
1799 newGroupValue
= i18nc("@title:group Size", "Big");
1802 if (newGroupValue
!= groupValue
) {
1803 groupValue
= newGroupValue
;
1804 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1811 QList
<QPair
<int, QVariant
> > KFileItemModel::dateRoleGroups() const
1813 Q_ASSERT(!m_itemData
.isEmpty());
1815 const int maxIndex
= count() - 1;
1816 QList
<QPair
<int, QVariant
> > groups
;
1818 const QDate currentDate
= KDateTime::currentLocalDateTime().date();
1820 QDate previousModifiedDate
;
1822 for (int i
= 0; i
<= maxIndex
; ++i
) {
1823 if (isChildItem(i
)) {
1827 const KDateTime modifiedTime
= m_itemData
.at(i
)->item
.time(KFileItem::ModificationTime
);
1828 const QDate modifiedDate
= modifiedTime
.date();
1829 if (modifiedDate
== previousModifiedDate
) {
1830 // The current item is in the same group as the previous item
1833 previousModifiedDate
= modifiedDate
;
1835 const int daysDistance
= modifiedDate
.daysTo(currentDate
);
1837 QString newGroupValue
;
1838 if (currentDate
.year() == modifiedDate
.year() && currentDate
.month() == modifiedDate
.month()) {
1839 switch (daysDistance
/ 7) {
1841 switch (daysDistance
) {
1842 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
1843 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
1844 default: newGroupValue
= modifiedTime
.toString(i18nc("@title:group The week day name: %A", "%A"));
1848 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
1851 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
1854 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
1858 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
1864 const QDate lastMonthDate
= currentDate
.addMonths(-1);
1865 if (lastMonthDate
.year() == modifiedDate
.year() && lastMonthDate
.month() == modifiedDate
.month()) {
1866 if (daysDistance
== 1) {
1867 newGroupValue
= modifiedTime
.toString(i18nc("@title:group Date: %B is full month name in current locale, and %Y is full year number", "Yesterday (%B, %Y)"));
1868 } else if (daysDistance
<= 7) {
1869 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)"));
1870 } else if (daysDistance
<= 7 * 2) {
1871 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)"));
1872 } else if (daysDistance
<= 7 * 3) {
1873 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)"));
1874 } else if (daysDistance
<= 7 * 4) {
1875 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)"));
1877 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"));
1880 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"));
1884 if (newGroupValue
!= groupValue
) {
1885 groupValue
= newGroupValue
;
1886 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1893 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
1895 Q_ASSERT(!m_itemData
.isEmpty());
1897 const int maxIndex
= count() - 1;
1898 QList
<QPair
<int, QVariant
> > groups
;
1900 QString permissionsString
;
1902 for (int i
= 0; i
<= maxIndex
; ++i
) {
1903 if (isChildItem(i
)) {
1907 const ItemData
* itemData
= m_itemData
.at(i
);
1908 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
1909 if (newPermissionsString
== permissionsString
) {
1912 permissionsString
= newPermissionsString
;
1914 const QFileInfo
info(itemData
->item
.url().pathOrUrl());
1918 if (info
.permission(QFile::ReadUser
)) {
1919 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1921 if (info
.permission(QFile::WriteUser
)) {
1922 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1924 if (info
.permission(QFile::ExeUser
)) {
1925 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1927 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
1931 if (info
.permission(QFile::ReadGroup
)) {
1932 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1934 if (info
.permission(QFile::WriteGroup
)) {
1935 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1937 if (info
.permission(QFile::ExeGroup
)) {
1938 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1940 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
1942 // Set others string
1944 if (info
.permission(QFile::ReadOther
)) {
1945 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
1947 if (info
.permission(QFile::WriteOther
)) {
1948 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
1950 if (info
.permission(QFile::ExeOther
)) {
1951 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
1953 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
1955 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
1956 if (newGroupValue
!= groupValue
) {
1957 groupValue
= newGroupValue
;
1958 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1965 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
1967 Q_ASSERT(!m_itemData
.isEmpty());
1969 const int maxIndex
= count() - 1;
1970 QList
<QPair
<int, QVariant
> > groups
;
1972 int groupValue
= -1;
1973 for (int i
= 0; i
<= maxIndex
; ++i
) {
1974 if (isChildItem(i
)) {
1977 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
1978 if (newGroupValue
!= groupValue
) {
1979 groupValue
= newGroupValue
;
1980 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1987 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
1989 Q_ASSERT(!m_itemData
.isEmpty());
1991 const int maxIndex
= count() - 1;
1992 QList
<QPair
<int, QVariant
> > groups
;
1994 bool isFirstGroupValue
= true;
1996 for (int i
= 0; i
<= maxIndex
; ++i
) {
1997 if (isChildItem(i
)) {
2000 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2001 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2002 groupValue
= newGroupValue
;
2003 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2004 isFirstGroupValue
= false;
2011 void KFileItemModel::emitSortProgress(int resolvedCount
)
2013 // Be tolerant against a resolvedCount with a wrong range.
2014 // Although there should not be a case where KFileItemModelRolesUpdater
2015 // (= caller) provides a wrong range, it is important to emit
2016 // a useful progress information even if there is an unexpected
2017 // implementation issue.
2019 const int itemCount
= count();
2020 if (resolvedCount
>= itemCount
) {
2021 m_sortingProgressPercent
= -1;
2022 if (m_resortAllItemsTimer
->isActive()) {
2023 m_resortAllItemsTimer
->stop();
2027 emit
directorySortingProgress(100);
2028 } else if (itemCount
> 0) {
2029 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2031 const int progress
= resolvedCount
* 100 / itemCount
;
2032 if (m_sortingProgressPercent
!= progress
) {
2033 m_sortingProgressPercent
= progress
;
2034 emit
directorySortingProgress(progress
);
2039 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2041 static const RoleInfoMap rolesInfoMap
[] = {
2042 // | role | roleType | role translation | group translation | requires Nepomuk | requires indexer
2043 { 0, NoRole
, 0, 0, 0, 0, false, false },
2044 { "text", NameRole
, I18N_NOOP2_NOSTRIP("@label", "Name"), 0, 0, false, false },
2045 { "size", SizeRole
, I18N_NOOP2_NOSTRIP("@label", "Size"), 0, 0, false, false },
2046 { "date", DateRole
, I18N_NOOP2_NOSTRIP("@label", "Date"), 0, 0, false, false },
2047 { "type", TypeRole
, I18N_NOOP2_NOSTRIP("@label", "Type"), 0, 0, false, false },
2048 { "rating", RatingRole
, I18N_NOOP2_NOSTRIP("@label", "Rating"), 0, 0, true, false },
2049 { "tags", TagsRole
, I18N_NOOP2_NOSTRIP("@label", "Tags"), 0, 0, true, false },
2050 { "comment", CommentRole
, I18N_NOOP2_NOSTRIP("@label", "Comment"), 0, 0, true, false },
2051 { "wordCount", WordCountRole
, I18N_NOOP2_NOSTRIP("@label", "Word Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2052 { "lineCount", LineCountRole
, I18N_NOOP2_NOSTRIP("@label", "Line Count"), I18N_NOOP2_NOSTRIP("@label", "Document"), true, true },
2053 { "imageSize", ImageSizeRole
, I18N_NOOP2_NOSTRIP("@label", "Image Size"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2054 { "orientation", OrientationRole
, I18N_NOOP2_NOSTRIP("@label", "Orientation"), I18N_NOOP2_NOSTRIP("@label", "Image"), true, true },
2055 { "artist", ArtistRole
, I18N_NOOP2_NOSTRIP("@label", "Artist"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2056 { "album", AlbumRole
, I18N_NOOP2_NOSTRIP("@label", "Album"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2057 { "duration", DurationRole
, I18N_NOOP2_NOSTRIP("@label", "Duration"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2058 { "track", TrackRole
, I18N_NOOP2_NOSTRIP("@label", "Track"), I18N_NOOP2_NOSTRIP("@label", "Audio"), true, true },
2059 { "path", PathRole
, I18N_NOOP2_NOSTRIP("@label", "Path"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2060 { "destination", DestinationRole
, I18N_NOOP2_NOSTRIP("@label", "Link Destination"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2061 { "copiedFrom", CopiedFromRole
, I18N_NOOP2_NOSTRIP("@label", "Copied From"), I18N_NOOP2_NOSTRIP("@label", "Other"), true, false },
2062 { "permissions", PermissionsRole
, I18N_NOOP2_NOSTRIP("@label", "Permissions"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2063 { "owner", OwnerRole
, I18N_NOOP2_NOSTRIP("@label", "Owner"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2064 { "group", GroupRole
, I18N_NOOP2_NOSTRIP("@label", "User Group"), I18N_NOOP2_NOSTRIP("@label", "Other"), false, false },
2067 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2068 return rolesInfoMap
;
2071 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2073 QElapsedTimer timer
;
2075 foreach (const KFileItem
& item
, items
) { // krazy:exclude=foreach
2076 // Only determine mime types for files here. For directories,
2077 // KFileItem::determineMimeType() reads the .directory file inside to
2078 // load the icon, but this is not necessary at all if we just need the
2079 // type. Some special code for setting the correct mime type for
2080 // directories is in retrieveData().
2081 if (!item
.isDir()) {
2082 item
.determineMimeType();
2085 if (timer
.elapsed() > timeout
) {
2086 // Don't block the user interface, let the remaining items
2087 // be resolved asynchronously.
2093 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2095 static QSet
<QByteArray
> pool
;
2096 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2098 if (it
!= pool
.constEnd()) {
2106 bool KFileItemModel::isConsistent() const
2108 if (m_items
.count() != m_itemData
.count()) {
2112 for (int i
= 0; i
< count(); ++i
) {
2113 // Check if m_items and m_itemData are consistent.
2114 const KFileItem item
= fileItem(i
);
2115 if (item
.isNull()) {
2116 qWarning() << "Item" << i
<< "is null";
2120 const int itemIndex
= index(item
);
2121 if (itemIndex
!= i
) {
2122 qWarning() << "Item" << i
<< "has a wrong index:" << itemIndex
;
2126 // Check if the items are sorted correctly.
2127 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
))) {
2128 qWarning() << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2129 << fileItem(i
- 1) << fileItem(i
);
2133 // Check if all parent-child relationships are consistent.
2134 const ItemData
* data
= m_itemData
.at(i
);
2135 const ItemData
* parent
= data
->parent
;
2137 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2138 qWarning() << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2142 const int parentIndex
= index(parent
->item
);
2143 if (parentIndex
>= i
) {
2144 qWarning() << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2153 #include "kfileitemmodel.moc"