2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_contentdisplaysettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
15 #include "views/draganddrophelper.h"
19 #include <KIO/ListJob>
20 #include <KLocalizedString>
21 #include <KUrlMimeData>
23 #include <QElapsedTimer>
26 #include <QMimeDatabase>
27 #include <QRecursiveMutex>
30 #include <klazylocalizedstring.h>
32 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
34 // #define KFILEITEMMODEL_DEBUG
36 KFileItemModel::KFileItemModel(QObject
*parent
)
37 : KItemModelBase("text", parent
)
38 , m_dirLister(nullptr)
39 , m_sortDirsFirst(true)
40 , m_sortHiddenLast(false)
41 , m_sortRole(NameRole
)
42 , m_sortingProgressPercent(-1)
49 , m_maximumUpdateIntervalTimer(nullptr)
50 , m_resortAllItemsTimer(nullptr)
51 , m_pendingItemsToInsert()
56 m_collator
.setNumericMode(true);
58 loadSortingSettings();
60 m_dirLister
= new KDirLister(this);
61 m_dirLister
->setAutoErrorHandlingEnabled(false);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
70 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
71 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
72 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
73 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
74 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
75 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
76 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
77 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
78 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
79 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
81 // Apply default roles that should be determined
83 m_requestRole
[NameRole
] = true;
84 m_requestRole
[IsDirRole
] = true;
85 m_requestRole
[IsLinkRole
] = true;
86 m_roles
.insert("text");
87 m_roles
.insert("isDir");
88 m_roles
.insert("isLink");
89 m_roles
.insert("isHidden");
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
, &QTimer::timeout
, this, &KFileItemModel::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(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
104 // and sorting too infrequently which leads to users seeing an outdated sort order.
105 m_resortAllItemsTimer
->setSingleShot(true);
106 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
108 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
110 setShowTrashMime(m_dirLister
->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
116 qDeleteAll(m_filteredItems
);
117 qDeleteAll(m_pendingItemsToInsert
);
120 void KFileItemModel::loadDirectory(const QUrl
&url
)
122 m_dirLister
->openUrl(url
);
125 void KFileItemModel::refreshDirectory(const QUrl
&url
)
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
129 while (expandedDirs
.hasNext()) {
131 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
134 m_dirLister
->openUrl(url
, KDirLister::Reload
);
136 Q_EMIT
directoryRefreshing();
139 QUrl
KFileItemModel::directory() const
141 return m_dirLister
->url();
144 void KFileItemModel::cancelDirectoryLoading()
149 int KFileItemModel::count() const
151 return m_itemData
.count();
154 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
156 if (index
>= 0 && index
< count()) {
157 ItemData
*data
= m_itemData
.at(index
);
158 if (data
->values
.isEmpty()) {
159 data
->values
= retrieveData(data
->item
, data
->parent
);
160 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
161 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
162 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
163 // so this special request of different behavior can be identified here.
164 bool hasExpandedParentsCount
= false;
165 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
167 data
->values
= retrieveData(data
->item
, data
->parent
);
168 data
->values
.insert("isExpanded", true);
169 if (hasExpandedParentsCount
) {
170 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
176 return QHash
<QByteArray
, QVariant
>();
179 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
181 if (index
< 0 || index
>= count()) {
185 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
187 // Determine which roles have been changed
188 QSet
<QByteArray
> changedRoles
;
189 QHashIterator
<QByteArray
, QVariant
> it(values
);
190 while (it
.hasNext()) {
192 const QByteArray role
= sharedValue(it
.key());
193 const QVariant value
= it
.value();
195 if (currentValues
[role
] != value
) {
196 currentValues
[role
] = value
;
197 changedRoles
.insert(role
);
201 if (changedRoles
.isEmpty()) {
205 if (changedRoles
.contains("text")) {
206 QUrl url
= m_itemData
[index
]->item
.url();
208 url
= url
.adjusted(QUrl::RemoveFilename
);
209 url
.setPath(url
.path() + currentValues
["text"].toString());
210 m_itemData
[index
]->item
.setUrl(url
);
211 m_items
.insert(url
, index
);
213 if (!changedRoles
.contains("url")) {
214 changedRoles
.insert("url");
215 currentValues
["url"] = url
;
218 m_itemData
[index
]->values
= currentValues
;
220 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
225 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
227 if (dirsFirst
!= m_sortDirsFirst
) {
228 m_sortDirsFirst
= dirsFirst
;
233 bool KFileItemModel::sortDirectoriesFirst() const
235 return m_sortDirsFirst
;
238 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
240 if (hiddenLast
!= m_sortHiddenLast
) {
241 m_sortHiddenLast
= hiddenLast
;
246 bool KFileItemModel::sortHiddenLast() const
248 return m_sortHiddenLast
;
251 void KFileItemModel::setShowTrashMime(bool showTrashMime
)
253 const auto trashMime
= QStringLiteral("application/x-trash");
254 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
257 excludeFilter
.removeAll(trashMime
);
258 } else if (!excludeFilter
.contains(trashMime
)) {
259 excludeFilter
.append(trashMime
);
262 setExcludeMimeTypeFilter(excludeFilter
);
265 void KFileItemModel::scheduleResortAllItems()
267 if (!m_resortAllItemsTimer
->isActive()) {
268 m_resortAllItemsTimer
->start();
272 void KFileItemModel::setShowHiddenFiles(bool show
)
274 m_dirLister
->setShowHiddenFiles(show
);
275 setShowTrashMime(show
|| !GeneralSettings::hideXTrashFile());
276 m_dirLister
->emitChanges();
278 dispatchPendingItemsToInsert();
282 bool KFileItemModel::showHiddenFiles() const
284 return m_dirLister
->showHiddenFiles();
287 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
289 m_dirLister
->setDirOnlyMode(enabled
);
292 bool KFileItemModel::showDirectoriesOnly() const
294 return m_dirLister
->dirOnlyMode();
297 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
299 QMimeData
*data
= new QMimeData();
301 // The following code has been taken from KDirModel::mimeData()
302 // (kdelibs/kio/kio/kdirmodel.cpp)
303 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
305 QList
<QUrl
> mostLocalUrls
;
306 const ItemData
*lastAddedItem
= nullptr;
308 for (int index
: indexes
) {
309 const ItemData
*itemData
= m_itemData
.at(index
);
310 const ItemData
*parent
= itemData
->parent
;
312 while (parent
&& parent
!= lastAddedItem
) {
313 parent
= parent
->parent
;
316 if (parent
&& parent
== lastAddedItem
) {
317 // A parent of 'itemData' has been added already.
321 lastAddedItem
= itemData
;
322 const KFileItem
&item
= itemData
->item
;
323 if (!item
.isNull()) {
327 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
331 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
335 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
337 startFromIndex
= qMax(0, startFromIndex
);
338 for (int i
= startFromIndex
; i
< count(); ++i
) {
339 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
343 for (int i
= 0; i
< startFromIndex
; ++i
) {
344 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
351 bool KFileItemModel::supportsDropping(int index
) const
357 item
= fileItem(index
);
359 return !item
.isNull() && DragAndDropHelper::supportsDropping(item
);
362 bool KFileItemModel::canEnterOnHover(int index
) const
368 item
= fileItem(index
);
370 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
373 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
375 static QHash
<QByteArray
, QString
> description
;
376 if (description
.isEmpty()) {
378 const RoleInfoMap
*map
= rolesInfoMap(count
);
379 for (int i
= 0; i
< count
; ++i
) {
380 if (map
[i
].roleTranslation
.isEmpty()) {
383 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
387 return description
.value(role
);
390 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
392 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
393 #ifdef KFILEITEMMODEL_DEBUG
397 switch (typeForRole(sortRole())) {
399 m_groups
= nameRoleGroups();
402 m_groups
= sizeRoleGroups();
404 case ModificationTimeRole
:
405 m_groups
= timeRoleGroups([](const ItemData
*item
) {
406 return item
->item
.time(KFileItem::ModificationTime
);
409 case CreationTimeRole
:
410 m_groups
= timeRoleGroups([](const ItemData
*item
) {
411 return item
->item
.time(KFileItem::CreationTime
);
415 m_groups
= timeRoleGroups([](const ItemData
*item
) {
416 return item
->item
.time(KFileItem::AccessTime
);
419 case DeletionTimeRole
:
420 m_groups
= timeRoleGroups([](const ItemData
*item
) {
421 return item
->values
.value("deletiontime").toDateTime();
424 case PermissionsRole
:
425 m_groups
= permissionRoleGroups();
428 m_groups
= ratingRoleGroups();
431 m_groups
= genericStringRoleGroups(sortRole());
435 #ifdef KFILEITEMMODEL_DEBUG
436 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
443 KFileItem
KFileItemModel::fileItem(int index
) const
445 if (index
>= 0 && index
< count()) {
446 return m_itemData
.at(index
)->item
;
452 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
454 const int indexForUrl
= index(url
);
455 if (indexForUrl
>= 0) {
456 return m_itemData
.at(indexForUrl
)->item
;
461 int KFileItemModel::index(const KFileItem
&item
) const
463 return index(item
.url());
466 int KFileItemModel::index(const QUrl
&url
) const
468 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
470 const int itemCount
= m_itemData
.count();
471 int itemsInHash
= m_items
.count();
473 int index
= m_items
.value(urlToFind
, -1);
474 while (index
< 0 && itemsInHash
< itemCount
) {
475 // Not all URLs are stored yet in m_items. We grow m_items until either
476 // urlToFind is found, or all URLs have been stored in m_items.
477 // Note that we do not add the URLs to m_items one by one, but in
478 // larger blocks. After each block, we check if urlToFind is in
479 // m_items. We could in principle compare urlToFind with each URL while
480 // we are going through m_itemData, but comparing two QUrls will,
481 // unlike calling qHash for the URLs, trigger a parsing of the URLs
482 // which costs both CPU cycles and memory.
483 const int blockSize
= 1000;
484 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
485 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
486 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
487 m_items
.insert(nextUrl
, i
);
490 itemsInHash
= currentBlockEnd
;
491 index
= m_items
.value(urlToFind
, -1);
495 // The item could not be found, even though all items from m_itemData
496 // should be in m_items now. We print some diagnostic information which
497 // might help to find the cause of the problem, but only once. This
498 // prevents that obtaining and printing the debugging information
499 // wastes CPU cycles and floods the shell or .xsession-errors.
500 static bool printDebugInfo
= true;
502 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
503 printDebugInfo
= false;
505 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
506 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
507 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
509 // Check if there are multiple items with the same URL.
510 QMultiHash
<QUrl
, int> indexesForUrl
;
511 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
512 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
515 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
516 for (const QUrl
&url
: uniqueKeys
) {
517 if (indexesForUrl
.count(url
) > 1) {
518 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
520 auto it
= indexesForUrl
.find(url
);
521 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
522 const ItemData
*data
= m_itemData
.at(it
.value());
523 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
525 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
537 KFileItem
KFileItemModel::rootItem() const
539 return m_dirLister
->rootItem();
542 void KFileItemModel::clear()
547 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
549 if (m_roles
== roles
) {
553 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
557 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
558 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
559 if (supportedExpanding
&& !willSupportExpanding
) {
560 // No expanding is supported anymore. Take care to delete all items that have an expansion level
561 // that is not 0 (and hence are part of an expanded item).
562 removeExpandedItems();
569 QSetIterator
<QByteArray
> it(roles
);
570 while (it
.hasNext()) {
571 const QByteArray
&role
= it
.next();
572 m_requestRole
[typeForRole(role
)] = true;
576 // Update m_data with the changed requested roles
577 const int maxIndex
= count() - 1;
578 for (int i
= 0; i
<= maxIndex
; ++i
) {
579 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
582 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
585 // Clear the 'values' of all filtered items. They will be re-populated with the
586 // correct roles the next time 'values' will be accessed via data(int).
587 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
588 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
589 while (filteredIt
!= filteredEnd
) {
590 (*filteredIt
)->values
.clear();
595 QSet
<QByteArray
> KFileItemModel::roles() const
600 bool KFileItemModel::setExpanded(int index
, bool expanded
)
602 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
606 QHash
<QByteArray
, QVariant
> values
;
607 values
.insert(sharedValue("isExpanded"), expanded
);
608 if (!setData(index
, values
)) {
612 const KFileItem item
= m_itemData
.at(index
)->item
;
613 const QUrl url
= item
.url();
614 const QUrl targetUrl
= item
.targetUrl();
616 m_expandedDirs
.insert(targetUrl
, url
);
617 m_dirLister
->openUrl(url
, KDirLister::Keep
);
619 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
620 for (const QVariant
&var
: previouslyExpandedChildren
) {
621 m_urlsToExpand
.insert(var
.toUrl());
624 // Note that there might be (indirect) children of the folder which is to be collapsed in
625 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
626 // possibly without a parent, which might result in a crash, we insert all pending items
627 // right now. All new items which would be without a parent will then be removed.
628 dispatchPendingItemsToInsert();
630 // Check if the index of the collapsed folder has changed. If that is the case, then items
631 // were inserted before the collapsed folder, and its index needs to be updated.
632 if (m_itemData
.at(index
)->item
!= item
) {
633 index
= this->index(item
);
636 m_expandedDirs
.remove(targetUrl
);
637 m_dirLister
->stop(url
);
638 m_dirLister
->forgetDirs(url
);
640 const int parentLevel
= expandedParentsCount(index
);
641 const int itemCount
= m_itemData
.count();
642 const int firstChildIndex
= index
+ 1;
644 QVariantList expandedChildren
;
646 int childIndex
= firstChildIndex
;
647 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
648 ItemData
*itemData
= m_itemData
.at(childIndex
);
649 if (itemData
->values
.value("isExpanded").toBool()) {
650 const QUrl targetUrl
= itemData
->item
.targetUrl();
651 const QUrl url
= itemData
->item
.url();
652 m_expandedDirs
.remove(targetUrl
);
653 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
654 m_dirLister
->forgetDirs(url
);
655 expandedChildren
.append(targetUrl
);
659 const int childrenCount
= childIndex
- firstChildIndex
;
661 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
662 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
664 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
670 bool KFileItemModel::isExpanded(int index
) const
672 if (index
>= 0 && index
< count()) {
673 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
678 bool KFileItemModel::isExpandable(int index
) const
680 if (index
>= 0 && index
< count()) {
681 // Call data (instead of accessing m_itemData directly)
682 // to ensure that the value is initialized.
683 return data(index
).value("isExpandable").toBool();
688 int KFileItemModel::expandedParentsCount(int index
) const
690 if (index
>= 0 && index
< count()) {
691 return expandedParentsCount(m_itemData
.at(index
));
696 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
699 const auto dirs
= m_expandedDirs
;
700 for (const auto &dir
: dirs
) {
706 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
708 m_urlsToExpand
= urls
;
711 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
713 // Assure that each sub-path of the URL that should be
714 // expanded is added to m_urlsToExpand. KDirLister
715 // does not care whether the parent-URL has already been
717 QUrl urlToExpand
= m_dirLister
->url();
718 const int pos
= urlToExpand
.path().length();
720 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
721 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
722 // so using QString::SkipEmptyParts
723 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
724 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
725 QString path
= urlToExpand
.path();
726 if (!path
.endsWith(QLatin1Char('/'))) {
727 path
.append(QLatin1Char('/'));
729 urlToExpand
.setPath(path
+ subDirs
.at(i
));
730 m_urlsToExpand
.insert(urlToExpand
);
733 // KDirLister::open() must called at least once to trigger an initial
734 // loading. The pending URLs that must be restored are handled
735 // in slotCompleted().
736 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
737 while (it2
.hasNext()) {
738 const int idx
= index(it2
.next());
739 if (idx
>= 0 && !isExpanded(idx
)) {
740 setExpanded(idx
, true);
746 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
748 if (m_filter
.pattern() != nameFilter
) {
749 dispatchPendingItemsToInsert();
750 m_filter
.setPattern(nameFilter
);
755 QString
KFileItemModel::nameFilter() const
757 return m_filter
.pattern();
760 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
762 if (m_filter
.mimeTypes() != filters
) {
763 dispatchPendingItemsToInsert();
764 m_filter
.setMimeTypes(filters
);
769 QStringList
KFileItemModel::mimeTypeFilters() const
771 return m_filter
.mimeTypes();
774 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
776 if (m_filter
.excludeMimeTypes() != filters
) {
777 dispatchPendingItemsToInsert();
778 m_filter
.setExcludeMimeTypes(filters
);
783 QStringList
KFileItemModel::excludeMimeTypeFilter() const
785 return m_filter
.excludeMimeTypes();
788 void KFileItemModel::applyFilters()
791 // Check which previously shown items from m_itemData must now get
792 // hidden and hence moved from m_itemData into m_filteredItems.
794 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
796 // This pointer will refer to the next confirmed shown item from the point of
797 // view of the current "itemData" in the upcoming "for" loop.
798 ItemData
*itemShownBelow
= nullptr;
800 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
801 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
802 ItemData
*itemData
= m_itemData
.at(index
);
804 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
805 // We could've entered here for two reasons:
806 // 1. This item passes the filter itself
807 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
809 // So this item must remain shown.
810 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
811 itemShownBelow
= itemData
;
813 // We hide this item for now, however, for expanded folders this is not final:
814 // if after the next "for" loop we discover that its children must now be shown with the newly applied fliter, we shall re-insert it
815 newFilteredIndexes
.prepend(index
);
816 m_filteredItems
.insert(itemData
->item
, itemData
);
817 // indexShownBelow doesn't get updated since this item will be hidden
821 // This will remove the newly filtered items from m_itemData
822 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
825 // Check which hidden items from m_filteredItems should
826 // become visible again and hence moved from m_filteredItems back into m_itemData.
828 QList
<ItemData
*> newVisibleItems
;
830 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
832 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
833 while (it
!= m_filteredItems
.end()) {
834 if (m_filter
.matches(it
.key())) {
835 newVisibleItems
.append(it
.value());
837 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
838 // We will go up through its parental chain until we either:
839 // 1 - reach the "root item" of the current view, i.e the currently opened folder on Dolphin. Their children have their ItemData::parent set to
840 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
841 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
842 parent
= parent
->parent
) {
843 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
844 // and it would mess up the iteration. We will mark it to be removed in step 3.
845 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
848 it
= m_filteredItems
.erase(it
);
850 // Item remains filtered for now
851 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
857 // Handles the ancestorsOfNewVisibleItems.
858 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
859 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
860 if (m_filteredItems
.remove(it
.key())) {
861 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
862 newVisibleItems
.append(it
.value());
866 // This will insert the newly discovered unfiltered items into m_itemData
867 insertItems(newVisibleItems
);
870 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
872 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
873 // There are either no filtered items, or it is not possible to expand
874 // folders -> there cannot be any filtered children.
878 QSet
<ItemData
*> parents
;
879 for (const KItemRange
&range
: itemRanges
) {
880 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
881 parents
.insert(m_itemData
.at(index
));
885 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
886 while (it
!= m_filteredItems
.end()) {
887 if (parents
.contains(it
.value()->parent
)) {
889 it
= m_filteredItems
.erase(it
);
896 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
898 static QList
<RoleInfo
> rolesInfo
;
899 if (rolesInfo
.isEmpty()) {
901 const RoleInfoMap
*map
= rolesInfoMap(count
);
902 for (int i
= 0; i
< count
; ++i
) {
903 if (map
[i
].roleType
!= NoRole
) {
905 info
.role
= map
[i
].role
;
906 info
.translation
= map
[i
].roleTranslation
.toString();
907 if (!map
[i
].groupTranslation
.isEmpty()) {
908 info
.group
= map
[i
].groupTranslation
.toString();
910 // For top level roles, groupTranslation is 0. We must make sure that
911 // info.group is an empty string then because the code that generates
912 // menus tries to put the actions into sub menus otherwise.
913 info
.group
= QString();
915 info
.requiresBaloo
= map
[i
].requiresBaloo
;
916 info
.requiresIndexer
= map
[i
].requiresIndexer
;
917 if (!map
[i
].tooltipTranslation
.isEmpty()) {
918 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
920 info
.tooltip
= QString();
922 rolesInfo
.append(info
);
930 void KFileItemModel::onGroupedSortingChanged(bool current
)
936 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
939 m_sortRole
= typeForRole(current
);
941 if (!m_requestRole
[m_sortRole
]) {
942 QSet
<QByteArray
> newRoles
= m_roles
;
952 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
959 void KFileItemModel::loadSortingSettings()
961 using Choice
= GeneralSettings::EnumSortingChoice
;
962 switch (GeneralSettings::sortingChoice()) {
963 case Choice::NaturalSorting
:
964 m_naturalSorting
= true;
965 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
967 case Choice::CaseSensitiveSorting
:
968 m_naturalSorting
= false;
969 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
971 case Choice::CaseInsensitiveSorting
:
972 m_naturalSorting
= false;
973 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
978 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
979 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
980 m_collator
.compare(QString(), QString());
983 void KFileItemModel::resortAllItems()
985 m_resortAllItemsTimer
->stop();
987 const int itemCount
= count();
988 if (itemCount
<= 0) {
992 #ifdef KFILEITEMMODEL_DEBUG
995 qCDebug(DolphinDebug
) << "===========================================================";
996 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
999 // Remember the order of the current URLs so
1000 // that it can be determined which indexes have
1001 // been moved because of the resorting.
1002 QList
<QUrl
> oldUrls
;
1003 oldUrls
.reserve(itemCount
);
1004 for (const ItemData
*itemData
: std::as_const(m_itemData
)) {
1005 oldUrls
.append(itemData
->item
.url());
1009 m_items
.reserve(itemCount
);
1012 sort(m_itemData
.begin(), m_itemData
.end());
1013 for (int i
= 0; i
< itemCount
; ++i
) {
1014 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1017 // Determine the first index that has been moved.
1018 int firstMovedIndex
= 0;
1019 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1023 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1024 if (itemsHaveMoved
) {
1027 int lastMovedIndex
= itemCount
- 1;
1028 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1032 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1034 // Create a list movedToIndexes, which has the property that
1035 // movedToIndexes[i] is the new index of the item with the old index
1036 // firstMovedIndex + i.
1037 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1038 QList
<int> movedToIndexes
;
1039 movedToIndexes
.reserve(movedItemsCount
);
1040 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1041 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1042 movedToIndexes
.append(newIndex
);
1045 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1046 } else if (groupedSorting()) {
1047 // The groups might have changed even if the order of the items has not.
1048 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1050 if (groups() != oldGroups
) {
1051 Q_EMIT
groupsChanged();
1055 #ifdef KFILEITEMMODEL_DEBUG
1056 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1060 void KFileItemModel::slotCompleted()
1062 m_maximumUpdateIntervalTimer
->stop();
1063 dispatchPendingItemsToInsert();
1065 if (!m_urlsToExpand
.isEmpty()) {
1066 // Try to find a URL that can be expanded.
1067 // Note that the parent folder must be expanded before any of its subfolders become visible.
1068 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1069 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1070 // Iterate over a const copy because items are deleted and inserted within the loop
1071 const auto urlsToExpand
= m_urlsToExpand
;
1072 for (const QUrl
&url
: urlsToExpand
) {
1073 const int indexForUrl
= index(url
);
1074 if (indexForUrl
>= 0) {
1075 m_urlsToExpand
.remove(url
);
1076 if (setExpanded(indexForUrl
, true)) {
1077 // The dir lister has been triggered. This slot will be called
1078 // again after the directory has been expanded.
1084 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1085 // if these URLs have been deleted in the meantime.
1086 m_urlsToExpand
.clear();
1089 Q_EMIT
directoryLoadingCompleted();
1092 void KFileItemModel::slotCanceled()
1094 m_maximumUpdateIntervalTimer
->stop();
1095 dispatchPendingItemsToInsert();
1097 Q_EMIT
directoryLoadingCanceled();
1100 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1102 Q_ASSERT(!items
.isEmpty());
1104 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1106 if (m_requestRole
[ExpandedParentsCountRole
]) {
1107 // If the expanding of items is enabled, the call
1108 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1109 // might result in emitting the same items twice due to the Keep-parameter.
1110 // This case happens if an item gets expanded, collapsed and expanded again
1111 // before the items could be loaded for the first expansion.
1112 if (index(items
.first().url()) >= 0) {
1113 // The items are already part of the model.
1117 if (directoryUrl
!= directory()) {
1118 // To be able to compare whether the new items may be inserted as children
1119 // of a parent item the pending items must be added to the model first.
1120 dispatchPendingItemsToInsert();
1123 // KDirLister keeps the children of items that got expanded once even if
1124 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1125 // checked whether the parent for new items is still expanded.
1126 const int parentIndex
= index(parentUrl
);
1127 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1128 // The parent is not expanded.
1133 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1135 if (!m_filter
.hasSetFilters()) {
1136 m_pendingItemsToInsert
.append(itemDataList
);
1138 QSet
<ItemData
*> parentsToEnsureVisible
;
1140 // The name or type filter is active. Hide filtered items
1141 // before inserting them into the model and remember
1142 // the filtered items in m_filteredItems.
1143 for (ItemData
*itemData
: itemDataList
) {
1144 if (m_filter
.matches(itemData
->item
)) {
1145 m_pendingItemsToInsert
.append(itemData
);
1146 if (itemData
->parent
) {
1147 parentsToEnsureVisible
.insert(itemData
->parent
);
1150 m_filteredItems
.insert(itemData
->item
, itemData
);
1154 // Entire parental chains must be shown
1155 for (ItemData
*parent
: parentsToEnsureVisible
) {
1156 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1157 m_pendingItemsToInsert
.append(parent
);
1162 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1163 // Assure that items get dispatched if no completed() or canceled() signal is
1164 // emitted during the maximum update interval.
1165 m_maximumUpdateIntervalTimer
->start();
1168 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1171 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1173 int filteredParentsCount
= 0;
1174 // The childless parents not yet removed will always be right above the start of a removed range.
1175 // We iterate backwards to ensure the deepest folders are processed before their parents
1176 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1177 KItemRange itemRange
= removedItemRanges
.at(i
);
1178 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1179 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1180 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1182 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1183 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1184 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1185 // and this deleted range covers all of its descendents, so none will be left.
1186 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1187 // This range's starting index will be extended to include the parent above:
1190 ++filteredParentsCount
;
1191 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1192 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1193 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1194 previousRange
.count
+= itemRange
.count
;
1195 removedItemRanges
.replace(i
- 1, previousRange
);
1196 removedItemRanges
.removeAt(i
);
1198 removedItemRanges
.replace(i
, itemRange
);
1199 // We must revisit this range in the next iteration since its starting index changed
1204 return filteredParentsCount
;
1207 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1209 dispatchPendingItemsToInsert();
1211 QVector
<int> indexesToRemove
;
1212 indexesToRemove
.reserve(items
.count());
1213 KFileItemList dirsChanged
;
1215 const auto currentDir
= directory();
1217 for (const KFileItem
&item
: items
) {
1218 if (item
.url() == currentDir
) {
1219 Q_EMIT
currentDirectoryRemoved();
1223 const int indexForItem
= index(item
);
1224 if (indexForItem
>= 0) {
1225 indexesToRemove
.append(indexForItem
);
1227 // Probably the item has been filtered.
1228 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1229 if (it
!= m_filteredItems
.end()) {
1231 m_filteredItems
.erase(it
);
1235 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1236 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1237 dirsChanged
<< KFileItem(parentUrl
);
1241 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1243 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1244 // Assure that removing a parent item also results in removing all children
1245 QVector
<int> indexesToRemoveWithChildren
;
1246 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1248 const int itemCount
= m_itemData
.count();
1249 for (int index
: std::as_const(indexesToRemove
)) {
1250 indexesToRemoveWithChildren
.append(index
);
1252 const int parentLevel
= expandedParentsCount(index
);
1253 int childIndex
= index
+ 1;
1254 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1255 indexesToRemoveWithChildren
.append(childIndex
);
1260 indexesToRemove
= indexesToRemoveWithChildren
;
1263 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1264 removeFilteredChildren(itemRanges
);
1266 // This call will update itemRanges to include the childless parents that have been filtered.
1267 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1269 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1270 // mixed with expanded folders that are just being filtered out.
1271 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1272 // so removeItems() will check m_filteredItems to differentiate which is which.
1273 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1275 Q_EMIT
fileItemsChanged(dirsChanged
);
1278 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1280 Q_ASSERT(!items
.isEmpty());
1281 #ifdef KFILEITEMMODEL_DEBUG
1282 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1285 // Get the indexes of all items that have been refreshed
1287 indexes
.reserve(items
.count());
1289 QSet
<QByteArray
> changedRoles
;
1290 KFileItemList changedFiles
;
1292 // Contains the indexes of the currently visible items
1293 // that should get hidden and hence moved to m_filteredItems.
1294 QVector
<int> newFilteredIndexes
;
1296 // Contains currently hidden items that should
1297 // get visible and hence removed from m_filteredItems
1298 QList
<ItemData
*> newVisibleItems
;
1300 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1302 while (it
.hasNext()) {
1303 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1304 const KFileItem
&oldItem
= itemPair
.first
;
1305 const KFileItem
&newItem
= itemPair
.second
;
1306 const int indexForItem
= index(oldItem
);
1307 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1308 if (indexForItem
>= 0) {
1309 m_itemData
[indexForItem
]->item
= newItem
;
1311 // Keep old values as long as possible if they could not retrieved synchronously yet.
1312 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1313 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1314 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1315 while (it
.hasNext()) {
1317 const QByteArray
&role
= it
.key();
1318 if (itemData
->values
.value(role
) != it
.value()) {
1319 itemData
->values
.insert(role
, it
.value());
1320 changedRoles
.insert(role
);
1324 m_items
.remove(oldItem
.url());
1325 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1326 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1327 m_items
.insert(newItem
.url(), indexForItem
);
1328 if (newItemMatchesFilter
1329 || (itemData
->values
.value("isExpanded").toBool()
1330 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1331 // We are lenient with expanded folders that originally had visible children.
1332 // If they become childless now they will be caught by filterChildlessParents()
1333 changedFiles
.append(newItem
);
1334 indexes
.append(indexForItem
);
1336 newFilteredIndexes
.append(indexForItem
);
1337 m_filteredItems
.insert(newItem
, itemData
);
1340 // Check if 'oldItem' is one of the filtered items.
1341 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1342 if (it
!= m_filteredItems
.end()) {
1343 ItemData
*const itemData
= it
.value();
1344 itemData
->item
= newItem
;
1346 // The data stored in 'values' might have changed. Therefore, we clear
1347 // 'values' and re-populate it the next time it is requested via data(int).
1348 // Before clearing, we must remember if it was expanded and the expanded parents count,
1349 // otherwise these states would be lost. The data() method will deal with this special case.
1350 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1351 bool hasExpandedParentsCount
= false;
1352 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1353 itemData
->values
.clear();
1355 itemData
->values
.insert("isExpanded", true);
1356 if (hasExpandedParentsCount
) {
1357 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1361 m_filteredItems
.erase(it
);
1362 if (newItemMatchesFilter
) {
1363 newVisibleItems
.append(itemData
);
1365 m_filteredItems
.insert(newItem
, itemData
);
1371 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1373 // We must keep track of parents of new visible items since they must be shown no matter what
1374 // They will be considered "immune" to filterChildlessParents()
1375 QSet
<ItemData
*> parentsToEnsureVisible
;
1377 for (ItemData
*item
: newVisibleItems
) {
1378 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1379 parentsToEnsureVisible
.insert(parent
);
1382 for (ItemData
*parent
: parentsToEnsureVisible
) {
1383 // We make sure they are all unfiltered.
1384 if (m_filteredItems
.remove(parent
->item
)) {
1385 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1386 newVisibleItems
.append(parent
);
1387 // It could be in newFilteredIndexes, we must remove it if it's there:
1388 const int parentIndex
= index(parent
->item
);
1389 if (parentIndex
>= 0) {
1390 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1391 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1392 newFilteredIndexes
.erase(it
);
1398 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1400 // This call will update itemRanges to include the childless parents that have been filtered.
1401 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1403 removeItems(removedRanges
, KeepItemData
);
1405 // Show previously hidden items that should get visible
1406 insertItems(newVisibleItems
);
1408 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1410 // If the changed items have been created recently, they might not be in m_items yet.
1411 // In that case, the list 'indexes' might be empty.
1412 if (indexes
.isEmpty()) {
1416 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1417 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1419 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1420 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1421 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1422 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1427 std::sort(indexes
.begin(), indexes
.end());
1430 // Extract the item-ranges out of the changed indexes
1431 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1432 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1434 Q_EMIT
fileItemsChanged(changedFiles
);
1437 void KFileItemModel::slotClear()
1439 #ifdef KFILEITEMMODEL_DEBUG
1440 qCDebug(DolphinDebug
) << "Clearing all items";
1443 qDeleteAll(m_filteredItems
);
1444 m_filteredItems
.clear();
1447 m_maximumUpdateIntervalTimer
->stop();
1448 m_resortAllItemsTimer
->stop();
1450 qDeleteAll(m_pendingItemsToInsert
);
1451 m_pendingItemsToInsert
.clear();
1453 const int removedCount
= m_itemData
.count();
1454 if (removedCount
> 0) {
1455 qDeleteAll(m_itemData
);
1458 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1461 m_expandedDirs
.clear();
1464 void KFileItemModel::slotSortingChoiceChanged()
1466 loadSortingSettings();
1470 void KFileItemModel::dispatchPendingItemsToInsert()
1472 if (!m_pendingItemsToInsert
.isEmpty()) {
1473 insertItems(m_pendingItemsToInsert
);
1474 m_pendingItemsToInsert
.clear();
1478 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1480 if (newItems
.isEmpty()) {
1484 #ifdef KFILEITEMMODEL_DEBUG
1485 QElapsedTimer timer
;
1487 qCDebug(DolphinDebug
) << "===========================================================";
1488 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1492 prepareItemsForSorting(newItems
);
1494 // Natural sorting of items can be very slow. However, it becomes much faster
1495 // if the input sequence is already mostly sorted. Therefore, we first sort
1496 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1497 if (m_naturalSorting
) {
1498 if (m_sortRole
== NameRole
) {
1499 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1500 } else if (isRoleValueNatural(m_sortRole
)) {
1501 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1502 const QByteArray role
= roleForType(m_sortRole
);
1503 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1505 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1509 sort(newItems
.begin(), newItems
.end());
1511 #ifdef KFILEITEMMODEL_DEBUG
1512 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1515 KItemRangeList itemRanges
;
1516 const int existingItemCount
= m_itemData
.count();
1517 const int newItemCount
= newItems
.count();
1518 const int totalItemCount
= existingItemCount
+ newItemCount
;
1520 if (existingItemCount
== 0) {
1521 // Optimization for the common special case that there are no
1522 // items in the model yet. Happens, e.g., when entering a folder.
1523 m_itemData
= newItems
;
1524 itemRanges
<< KItemRange(0, newItemCount
);
1526 m_itemData
.reserve(totalItemCount
);
1527 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1528 m_itemData
.append(nullptr);
1531 // We build the new list m_itemData in reverse order to minimize
1532 // the number of moves and guarantee O(N) complexity.
1533 int targetIndex
= totalItemCount
- 1;
1534 int sourceIndexExistingItems
= existingItemCount
- 1;
1535 int sourceIndexNewItems
= newItemCount
- 1;
1539 while (sourceIndexNewItems
>= 0) {
1540 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1541 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1542 // Move an existing item to its new position. If any new items
1543 // are behind it, push the item range to itemRanges.
1544 if (rangeCount
> 0) {
1545 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1549 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1550 --sourceIndexExistingItems
;
1552 // Insert a new item into the list.
1554 m_itemData
[targetIndex
] = newItem
;
1555 --sourceIndexNewItems
;
1560 // Push the final item range to itemRanges.
1561 if (rangeCount
> 0) {
1562 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1565 // Note that itemRanges is still sorted in reverse order.
1566 std::reverse(itemRanges
.begin(), itemRanges
.end());
1569 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1570 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1573 Q_EMIT
itemsInserted(itemRanges
);
1575 #ifdef KFILEITEMMODEL_DEBUG
1576 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1580 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1582 if (itemRanges
.isEmpty()) {
1588 // Step 1: Remove the items from m_itemData, and free the ItemData.
1589 int removedItemsCount
= 0;
1590 for (const KItemRange
&range
: itemRanges
) {
1591 removedItemsCount
+= range
.count
;
1593 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1594 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1595 delete m_itemData
.at(index
);
1598 m_itemData
[index
] = nullptr;
1602 // Step 2: Remove the ItemData pointers from the list m_itemData.
1603 int target
= itemRanges
.at(0).index
;
1604 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1607 const int oldItemDataCount
= m_itemData
.count();
1608 while (source
< oldItemDataCount
) {
1609 m_itemData
[target
] = m_itemData
[source
];
1613 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1614 // Skip the items in the next removed range.
1615 source
+= itemRanges
.at(nextRange
).count
;
1620 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1622 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1623 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1626 Q_EMIT
itemsRemoved(itemRanges
);
1629 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1631 if (m_sortRole
== TypeRole
) {
1632 // Try to resolve the MIME-types synchronously to prevent a reordering of
1633 // the items when sorting by type (per default MIME-types are resolved
1634 // asynchronously by KFileItemModelRolesUpdater).
1635 determineMimeTypes(items
, 200);
1638 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1639 const int parentIndex
= index(parentUrl
);
1640 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1642 QList
<ItemData
*> itemDataList
;
1643 itemDataList
.reserve(items
.count());
1645 for (const KFileItem
&item
: items
) {
1646 ItemData
*itemData
= new ItemData();
1647 itemData
->item
= item
;
1648 itemData
->parent
= parentItem
;
1649 itemDataList
.append(itemData
);
1652 return itemDataList
;
1655 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1657 switch (m_sortRole
) {
1659 case PermissionsRole
:
1662 case DestinationRole
:
1664 case DeletionTimeRole
:
1665 // These roles can be determined with retrieveData, and they have to be stored
1666 // in the QHash "values" for the sorting.
1667 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1668 if (itemData
->values
.isEmpty()) {
1669 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1675 // At least store the data including the file type for items with known MIME type.
1676 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1677 if (itemData
->values
.isEmpty()) {
1678 const KFileItem item
= itemData
->item
;
1679 if (item
.isDir() || item
.isMimeTypeKnown()) {
1680 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1687 // The other roles are either resolved by KFileItemModelRolesUpdater
1688 // (this includes the SizeRole for directories), or they do not need
1689 // to be stored in the QHash "values" for sorting because the data can
1690 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1696 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1698 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1699 // if the corresponding item is expanded, and it is not a top-level item.
1700 const ItemData
*parent
= data
->parent
;
1702 if (parent
->parent
) {
1703 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1704 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1713 void KFileItemModel::removeExpandedItems()
1715 QVector
<int> indexesToRemove
;
1717 const int maxIndex
= m_itemData
.count() - 1;
1718 for (int i
= 0; i
<= maxIndex
; ++i
) {
1719 const ItemData
*itemData
= m_itemData
.at(i
);
1720 if (itemData
->parent
) {
1721 indexesToRemove
.append(i
);
1725 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1726 m_expandedDirs
.clear();
1728 // Also remove all filtered items which have a parent.
1729 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1730 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1733 if (it
.value()->parent
) {
1735 it
= m_filteredItems
.erase(it
);
1742 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1744 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1746 // Trigger a resorting if necessary. Note that this can happen even if the sort
1747 // role has not changed at all because the file name can be used as a fallback.
1748 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))
1749 || (changedRoles
.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1750 for (const KItemRange
&range
: itemRanges
) {
1751 bool needsResorting
= false;
1753 const int first
= range
.index
;
1754 const int last
= range
.index
+ range
.count
- 1;
1756 // Resorting the model is necessary if
1757 // (a) The first item in the range is "lessThan" its predecessor,
1758 // (b) the successor of the last item is "lessThan" the last item, or
1759 // (c) the internal order of the items in the range is incorrect.
1760 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1761 needsResorting
= true;
1762 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1763 needsResorting
= true;
1765 for (int index
= first
; index
< last
; ++index
) {
1766 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1767 needsResorting
= true;
1773 if (needsResorting
) {
1774 scheduleResortAllItems();
1780 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1781 // The position is still correct, but the groups might have changed
1782 // if the changed item is either the first or the last item in a
1784 // In principle, we could try to find out if the item really is the
1785 // first or last one in its group and then update the groups
1786 // (possibly with a delayed timer to make sure that we don't
1787 // re-calculate the groups very often if items are updated one by
1788 // one), but starting m_resortAllItemsTimer is easier.
1789 m_resortAllItemsTimer
->start();
1793 void KFileItemModel::resetRoles()
1795 for (int i
= 0; i
< RolesCount
; ++i
) {
1796 m_requestRole
[i
] = false;
1800 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1802 static QHash
<QByteArray
, RoleType
> roles
;
1803 if (roles
.isEmpty()) {
1804 // Insert user visible roles that can be accessed with
1805 // KFileItemModel::roleInformation()
1807 const RoleInfoMap
*map
= rolesInfoMap(count
);
1808 for (int i
= 0; i
< count
; ++i
) {
1809 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1812 // Insert internal roles (take care to synchronize the implementation
1813 // with KFileItemModel::roleForType() in case if a change is done).
1814 roles
.insert("isDir", IsDirRole
);
1815 roles
.insert("isLink", IsLinkRole
);
1816 roles
.insert("isHidden", IsHiddenRole
);
1817 roles
.insert("isExpanded", IsExpandedRole
);
1818 roles
.insert("isExpandable", IsExpandableRole
);
1819 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1821 Q_ASSERT(roles
.count() == RolesCount
);
1824 return roles
.value(role
, NoRole
);
1827 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1829 static QHash
<RoleType
, QByteArray
> roles
;
1830 if (roles
.isEmpty()) {
1831 // Insert user visible roles that can be accessed with
1832 // KFileItemModel::roleInformation()
1834 const RoleInfoMap
*map
= rolesInfoMap(count
);
1835 for (int i
= 0; i
< count
; ++i
) {
1836 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1839 // Insert internal roles (take care to synchronize the implementation
1840 // with KFileItemModel::typeForRole() in case if a change is done).
1841 roles
.insert(IsDirRole
, "isDir");
1842 roles
.insert(IsLinkRole
, "isLink");
1843 roles
.insert(IsHiddenRole
, "isHidden");
1844 roles
.insert(IsExpandedRole
, "isExpanded");
1845 roles
.insert(IsExpandableRole
, "isExpandable");
1846 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1848 Q_ASSERT(roles
.count() == RolesCount
);
1851 return roles
.value(roleType
);
1854 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1856 // It is important to insert only roles that are fast to retrieve. E.g.
1857 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1858 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1859 QHash
<QByteArray
, QVariant
> data
;
1860 data
.insert(sharedValue("url"), item
.url());
1862 const bool isDir
= item
.isDir();
1863 if (m_requestRole
[IsDirRole
] && isDir
) {
1864 data
.insert(sharedValue("isDir"), true);
1867 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1868 data
.insert(sharedValue("isLink"), true);
1871 if (m_requestRole
[IsHiddenRole
]) {
1872 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1875 if (m_requestRole
[NameRole
]) {
1876 data
.insert(sharedValue("text"), item
.text());
1879 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1880 // TODO KF6 use KFileItem::suffix 464722
1881 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1884 if (m_requestRole
[SizeRole
] && !isDir
) {
1885 data
.insert(sharedValue("size"), item
.size());
1888 if (m_requestRole
[ModificationTimeRole
]) {
1889 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1890 // having several thousands of items. Instead read the raw number from UDSEntry directly
1891 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1892 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1893 data
.insert(sharedValue("modificationtime"), dateTime
);
1896 if (m_requestRole
[CreationTimeRole
]) {
1897 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1898 // having several thousands of items. Instead read the raw number from UDSEntry directly
1899 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1900 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1901 data
.insert(sharedValue("creationtime"), dateTime
);
1904 if (m_requestRole
[AccessTimeRole
]) {
1905 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1906 // having several thousands of items. Instead read the raw number from UDSEntry directly
1907 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1908 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1909 data
.insert(sharedValue("accesstime"), dateTime
);
1912 if (m_requestRole
[PermissionsRole
]) {
1913 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1916 if (m_requestRole
[OwnerRole
]) {
1917 data
.insert(sharedValue("owner"), item
.user());
1920 if (m_requestRole
[GroupRole
]) {
1921 data
.insert(sharedValue("group"), item
.group());
1924 if (m_requestRole
[DestinationRole
]) {
1925 QString destination
= item
.linkDest();
1926 if (destination
.isEmpty()) {
1927 destination
= QLatin1Char('-');
1929 data
.insert(sharedValue("destination"), destination
);
1932 if (m_requestRole
[PathRole
]) {
1934 if (item
.url().scheme() == QLatin1String("trash")) {
1935 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1937 // For performance reasons cache the home-path in a static QString
1938 // (see QDir::homePath() for more details)
1939 static QString homePath
;
1940 if (homePath
.isEmpty()) {
1941 homePath
= QDir::homePath();
1944 path
= item
.localPath();
1945 if (path
.startsWith(homePath
)) {
1946 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1950 const int index
= path
.lastIndexOf(item
.text());
1951 path
= path
.mid(0, index
- 1);
1952 data
.insert(sharedValue("path"), path
);
1955 if (m_requestRole
[DeletionTimeRole
]) {
1956 QDateTime deletionTime
;
1957 if (item
.url().scheme() == QLatin1String("trash")) {
1958 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1960 data
.insert(sharedValue("deletiontime"), deletionTime
);
1963 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1964 data
.insert(sharedValue("isExpandable"), true);
1967 if (m_requestRole
[ExpandedParentsCountRole
]) {
1969 const int level
= expandedParentsCount(parent
) + 1;
1970 data
.insert(sharedValue("expandedParentsCount"), level
);
1974 if (item
.isMimeTypeKnown()) {
1975 QString iconName
= item
.iconName();
1976 if (!QIcon::hasThemeIcon(iconName
)) {
1977 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1978 iconName
= mimeType
.genericIconName();
1981 data
.insert(sharedValue("iconName"), iconName
);
1983 if (m_requestRole
[TypeRole
]) {
1984 data
.insert(sharedValue("type"), item
.mimeComment());
1986 } else if (m_requestRole
[TypeRole
] && isDir
) {
1987 static const QString folderMimeType
= item
.mimeComment();
1988 data
.insert(sharedValue("type"), folderMimeType
);
1994 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1998 if (a
->parent
!= b
->parent
) {
1999 const int expansionLevelA
= expandedParentsCount(a
);
2000 const int expansionLevelB
= expandedParentsCount(b
);
2002 // If b has a higher expansion level than a, check if a is a parent
2003 // of b, and make sure that both expansion levels are equal otherwise.
2004 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
2005 if (b
->parent
== a
) {
2011 // If a has a higher expansion level than a, check if b is a parent
2012 // of a, and make sure that both expansion levels are equal otherwise.
2013 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
2014 if (a
->parent
== b
) {
2020 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2022 // Compare the last parents of a and b which are different.
2023 while (a
->parent
!= b
->parent
) {
2029 // Show hidden files and folders last
2030 if (m_sortHiddenLast
) {
2031 const bool isHiddenA
= a
->item
.isHidden();
2032 const bool isHiddenB
= b
->item
.isHidden();
2033 if (isHiddenA
&& !isHiddenB
) {
2035 } else if (!isHiddenA
&& isHiddenB
) {
2041 || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& m_sortRole
== SizeRole
)) {
2042 const bool isDirA
= a
->item
.isDir();
2043 const bool isDirB
= b
->item
.isDir();
2044 if (isDirA
&& !isDirB
) {
2046 } else if (!isDirA
&& isDirB
) {
2051 result
= sortRoleCompare(a
, b
, collator
);
2053 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2056 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2058 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2059 return lessThan(a
, b
, m_collator
);
2062 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2063 // Sorting by string can be expensive, in particular if natural sorting is
2064 // enabled. Use all CPU cores to speed up the sorting process.
2065 static const int numberOfThreads
= QThread::idealThreadCount();
2066 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2068 // Sorting by other roles is quite fast. Use only one thread to prevent
2069 // problems caused by non-reentrant comparison functions, see
2070 // https://bugs.kde.org/show_bug.cgi?id=312679
2071 mergeSort(begin
, end
, lambdaLessThan
);
2075 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2077 // This function must never return 0, because that would break stable
2078 // sorting, which leads to all kinds of bugs.
2079 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2080 // If two items have equal sort values, let the fallbacks at the bottom of
2081 // the function handle it.
2082 const KFileItem
&itemA
= a
->item
;
2083 const KFileItem
&itemB
= b
->item
;
2087 switch (m_sortRole
) {
2089 // The name role is handled as default fallback after the switch
2093 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& itemA
.isDir()) {
2094 // folders first then
2095 // items A and B are folders thanks to lessThan checks
2096 auto valueA
= a
->values
.value("count");
2097 auto valueB
= b
->values
.value("count");
2098 if (valueA
.isNull()) {
2099 if (!valueB
.isNull()) {
2102 } else if (valueB
.isNull()) {
2105 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2107 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2114 KIO::filesize_t sizeA
= 0;
2115 if (itemA
.isDir()) {
2116 sizeA
= a
->values
.value("size").toULongLong();
2118 sizeA
= itemA
.size();
2120 KIO::filesize_t sizeB
= 0;
2121 if (itemB
.isDir()) {
2122 sizeB
= b
->values
.value("size").toULongLong();
2124 sizeB
= itemB
.size();
2126 if (sizeA
< sizeB
) {
2128 } else if (sizeA
> sizeB
) {
2134 case ModificationTimeRole
: {
2135 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2136 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2137 if (dateTimeA
< dateTimeB
) {
2139 } else if (dateTimeA
> dateTimeB
) {
2145 case AccessTimeRole
: {
2146 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2147 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2148 if (dateTimeA
< dateTimeB
) {
2150 } else if (dateTimeA
> dateTimeB
) {
2156 case CreationTimeRole
: {
2157 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2158 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2159 if (dateTimeA
< dateTimeB
) {
2161 } else if (dateTimeA
> dateTimeB
) {
2167 case DeletionTimeRole
: {
2168 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2169 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2170 if (dateTimeA
< dateTimeB
) {
2172 } else if (dateTimeA
> dateTimeB
) {
2186 case ReleaseYearRole
: {
2187 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2191 case DimensionsRole
: {
2192 const QByteArray role
= roleForType(m_sortRole
);
2193 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2194 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2196 if (dimensionsA
.width() == dimensionsB
.width()) {
2197 result
= dimensionsA
.height() - dimensionsB
.height();
2199 result
= dimensionsA
.width() - dimensionsB
.width();
2205 const QByteArray role
= roleForType(m_sortRole
);
2206 const QString roleValueA
= a
->values
.value(role
).toString();
2207 const QString roleValueB
= b
->values
.value(role
).toString();
2208 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2210 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2212 } else if (isRoleValueNatural(m_sortRole
)) {
2213 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2215 result
= QString::compare(roleValueA
, roleValueB
);
2222 // The current sort role was sufficient to define an order
2226 // Fallback #1: Compare the text of the items
2227 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2232 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2233 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2238 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2239 // equal. In this case a comparison of the URL is done which is unique in all cases
2240 // within KDirLister.
2241 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2244 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2246 QMutexLocker
collatorLock(s_collatorMutex());
2248 if (m_naturalSorting
) {
2249 return collator
.compare(a
, b
);
2252 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2253 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2254 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2255 // comparison, still a deterministic sort order is required. A case sensitive
2256 // comparison is done as fallback.
2260 return QString::compare(a
, b
, Qt::CaseSensitive
);
2263 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2265 Q_ASSERT(!m_itemData
.isEmpty());
2267 const int maxIndex
= count() - 1;
2268 QList
<QPair
<int, QVariant
>> groups
;
2272 for (int i
= 0; i
<= maxIndex
; ++i
) {
2273 if (isChildItem(i
)) {
2277 const QString name
= m_itemData
.at(i
)->item
.text();
2279 // Use the first character of the name as group indication
2280 QChar newFirstChar
= name
.at(0).toUpper();
2281 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2282 newFirstChar
= name
.at(1).toUpper();
2285 if (firstChar
!= newFirstChar
) {
2286 QString newGroupValue
;
2287 if (newFirstChar
.isLetter()) {
2288 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2289 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2291 // Try to find a matching group in the range 'A' to 'Z'.
2292 static std::vector
<QChar
> lettersAtoZ
;
2293 lettersAtoZ
.reserve('Z' - 'A' + 1);
2294 if (lettersAtoZ
.empty()) {
2295 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2296 lettersAtoZ
.push_back(QLatin1Char(c
));
2300 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2301 return m_collator
.compare(c1
, c2
) < 0;
2304 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2305 if (it
!= lettersAtoZ
.end()) {
2306 if (localeAwareLessThan(newFirstChar
, *it
)) {
2307 // newFirstChar belongs to the group preceding *it.
2308 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2311 newGroupValue
= *it
;
2315 // Symbols from non Latin-based scripts
2316 newGroupValue
= newFirstChar
;
2318 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2319 // Apply group '0 - 9' for any name that starts with a digit
2320 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2322 newGroupValue
= i18nc("@title:group", "Others");
2325 if (newGroupValue
!= groupValue
) {
2326 groupValue
= newGroupValue
;
2327 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2330 firstChar
= newFirstChar
;
2336 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2338 Q_ASSERT(!m_itemData
.isEmpty());
2340 const int maxIndex
= count() - 1;
2341 QList
<QPair
<int, QVariant
>> groups
;
2344 for (int i
= 0; i
<= maxIndex
; ++i
) {
2345 if (isChildItem(i
)) {
2349 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2350 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2351 QString newGroupValue
;
2352 if (!item
.isNull() && item
.isDir()) {
2353 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
|| m_sortDirsFirst
) {
2354 newGroupValue
= i18nc("@title:group Size", "Folders");
2356 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2360 if (newGroupValue
.isEmpty()) {
2361 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2362 newGroupValue
= i18nc("@title:group Size", "Small");
2363 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2364 newGroupValue
= i18nc("@title:group Size", "Medium");
2366 newGroupValue
= i18nc("@title:group Size", "Big");
2370 if (newGroupValue
!= groupValue
) {
2371 groupValue
= newGroupValue
;
2372 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2379 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2381 Q_ASSERT(!m_itemData
.isEmpty());
2383 const int maxIndex
= count() - 1;
2384 QList
<QPair
<int, QVariant
>> groups
;
2386 const QDate currentDate
= QDate::currentDate();
2388 QDate previousFileDate
;
2390 for (int i
= 0; i
<= maxIndex
; ++i
) {
2391 if (isChildItem(i
)) {
2395 const QLocale locale
;
2396 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2397 const QDate fileDate
= fileTime
.date();
2398 if (fileDate
== previousFileDate
) {
2399 // The current item is in the same group as the previous item
2402 previousFileDate
= fileDate
;
2404 const int daysDistance
= fileDate
.daysTo(currentDate
);
2406 QString newGroupValue
;
2407 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2408 switch (daysDistance
/ 7) {
2410 switch (daysDistance
) {
2412 newGroupValue
= i18nc("@title:group Date", "Today");
2415 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2418 newGroupValue
= locale
.toString(fileTime
, i18nc("@title:group Date: The week day name: dddd", "dddd"));
2419 newGroupValue
= i18nc(
2420 "Can be used to script translation of \"dddd\""
2421 "with context @title:group Date",
2427 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2430 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2433 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2437 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2443 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2444 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2445 if (daysDistance
== 1) {
2446 const KLocalizedString format
= ki18nc(
2447 "@title:group Date: "
2448 "MMMM is full month name in current locale, and yyyy is "
2449 "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
2450 "part of the text that should not be formatted as a date",
2451 "'Yesterday' (MMMM, yyyy)");
2452 const QString translatedFormat
= format
.toString();
2453 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2454 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2455 newGroupValue
= i18nc(
2456 "Can be used to script translation of "
2457 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2461 qCWarning(DolphinDebug
).nospace()
2462 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2463 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2464 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2466 } else if (daysDistance
<= 7) {
2467 newGroupValue
= locale
.toString(fileTime
,
2468 i18nc("@title:group Date: "
2469 "The week day name: dddd, MMMM is full month name "
2470 "in current locale, and yyyy is full year number.",
2471 "dddd (MMMM, yyyy)"));
2472 newGroupValue
= i18nc(
2473 "Can be used to script translation of "
2474 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2477 } else if (daysDistance
<= 7 * 2) {
2478 const KLocalizedString format
= ki18nc(
2479 "@title:group Date: "
2480 "MMMM is full month name in current locale, and yyyy is "
2481 "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
2482 "part of the text that should not be formatted as a date",
2483 "'One Week Ago' (MMMM, yyyy)");
2484 const QString translatedFormat
= format
.toString();
2485 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2486 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2487 newGroupValue
= i18nc(
2488 "Can be used to script translation of "
2489 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2493 qCWarning(DolphinDebug
).nospace()
2494 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2495 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2496 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2498 } else if (daysDistance
<= 7 * 3) {
2499 const KLocalizedString format
= ki18nc(
2500 "@title:group Date: "
2501 "MMMM is full month name in current locale, and yyyy is "
2502 "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
2503 "part of the text that should not be formatted as a date",
2504 "'Two Weeks Ago' (MMMM, yyyy)");
2505 const QString translatedFormat
= format
.toString();
2506 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2507 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2508 newGroupValue
= i18nc(
2509 "Can be used to script translation of "
2510 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2514 qCWarning(DolphinDebug
).nospace()
2515 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2516 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2517 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2519 } else if (daysDistance
<= 7 * 4) {
2520 const KLocalizedString format
= ki18nc(
2521 "@title:group Date: "
2522 "MMMM is full month name in current locale, and yyyy is "
2523 "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
2524 "part of the text that should not be formatted as a date",
2525 "'Three Weeks Ago' (MMMM, yyyy)");
2526 const QString translatedFormat
= format
.toString();
2527 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2528 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2529 newGroupValue
= i18nc(
2530 "Can be used to script translation of "
2531 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2535 qCWarning(DolphinDebug
).nospace()
2536 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2537 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2538 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2541 const KLocalizedString format
= ki18nc(
2542 "@title:group Date: "
2543 "MMMM is full month name in current locale, and yyyy is "
2544 "full year number. You must keep the ' don't use any fancy \" or « or similar. The ' is not shown to the user, it's there to mark a "
2545 "part of the text that should not be formatted as a date",
2546 "'Earlier on' MMMM, yyyy");
2547 const QString translatedFormat
= format
.toString();
2548 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2549 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2550 newGroupValue
= i18nc(
2551 "Can be used to script translation of "
2552 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2556 qCWarning(DolphinDebug
).nospace()
2557 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2558 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2559 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2563 newGroupValue
= locale
.toString(fileTime
,
2564 i18nc("@title:group "
2565 "The month and year: MMMM is full month name in current locale, "
2566 "and yyyy is full year number",
2568 newGroupValue
= i18nc(
2569 "Can be used to script translation of "
2570 "\"MMMM, yyyy\" with context @title:group Date",
2576 if (newGroupValue
!= groupValue
) {
2577 groupValue
= newGroupValue
;
2578 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2585 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2587 Q_ASSERT(!m_itemData
.isEmpty());
2589 const int maxIndex
= count() - 1;
2590 QList
<QPair
<int, QVariant
>> groups
;
2592 QString permissionsString
;
2594 for (int i
= 0; i
<= maxIndex
; ++i
) {
2595 if (isChildItem(i
)) {
2599 const ItemData
*itemData
= m_itemData
.at(i
);
2600 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2601 if (newPermissionsString
== permissionsString
) {
2604 permissionsString
= newPermissionsString
;
2606 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2610 if (info
.permission(QFile::ReadUser
)) {
2611 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2613 if (info
.permission(QFile::WriteUser
)) {
2614 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2616 if (info
.permission(QFile::ExeUser
)) {
2617 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2619 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2623 if (info
.permission(QFile::ReadGroup
)) {
2624 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2626 if (info
.permission(QFile::WriteGroup
)) {
2627 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2629 if (info
.permission(QFile::ExeGroup
)) {
2630 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2632 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2634 // Set others string
2636 if (info
.permission(QFile::ReadOther
)) {
2637 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2639 if (info
.permission(QFile::WriteOther
)) {
2640 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2642 if (info
.permission(QFile::ExeOther
)) {
2643 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2645 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2647 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2648 if (newGroupValue
!= groupValue
) {
2649 groupValue
= newGroupValue
;
2650 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2657 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2659 Q_ASSERT(!m_itemData
.isEmpty());
2661 const int maxIndex
= count() - 1;
2662 QList
<QPair
<int, QVariant
>> groups
;
2664 int groupValue
= -1;
2665 for (int i
= 0; i
<= maxIndex
; ++i
) {
2666 if (isChildItem(i
)) {
2669 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2670 if (newGroupValue
!= groupValue
) {
2671 groupValue
= newGroupValue
;
2672 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2679 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2681 Q_ASSERT(!m_itemData
.isEmpty());
2683 const int maxIndex
= count() - 1;
2684 QList
<QPair
<int, QVariant
>> groups
;
2686 bool isFirstGroupValue
= true;
2688 for (int i
= 0; i
<= maxIndex
; ++i
) {
2689 if (isChildItem(i
)) {
2692 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2693 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2694 groupValue
= newGroupValue
;
2695 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2696 isFirstGroupValue
= false;
2703 void KFileItemModel::emitSortProgress(int resolvedCount
)
2705 // Be tolerant against a resolvedCount with a wrong range.
2706 // Although there should not be a case where KFileItemModelRolesUpdater
2707 // (= caller) provides a wrong range, it is important to emit
2708 // a useful progress information even if there is an unexpected
2709 // implementation issue.
2711 const int itemCount
= count();
2712 if (resolvedCount
>= itemCount
) {
2713 m_sortingProgressPercent
= -1;
2714 if (m_resortAllItemsTimer
->isActive()) {
2715 m_resortAllItemsTimer
->stop();
2719 Q_EMIT
directorySortingProgress(100);
2720 } else if (itemCount
> 0) {
2721 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2723 const int progress
= resolvedCount
* 100 / itemCount
;
2724 if (m_sortingProgressPercent
!= progress
) {
2725 m_sortingProgressPercent
= progress
;
2726 Q_EMIT
directorySortingProgress(progress
);
2731 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2733 static const RoleInfoMap rolesInfoMap
[] = {
2735 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2736 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2737 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2738 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2739 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2740 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2741 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2742 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2743 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2744 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2745 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2746 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2747 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2748 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2749 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2750 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2751 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2752 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2753 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2754 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2755 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2756 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2757 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2758 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2759 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2760 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2761 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2762 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2763 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2764 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2765 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2766 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2767 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2768 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2769 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2770 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2771 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2772 { "permissions", PermissionsRole
, kli18nc("@label", "Permissions"), kli18nc("@label", "Other"), kli18nc("@tooltip", "The permission format can be changed in settings. Options are Symbolic, Numeric (Octal) or Combined formats"), false, false },
2773 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2774 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2778 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2779 return rolesInfoMap
;
2782 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2784 QElapsedTimer timer
;
2786 for (const KFileItem
&item
: items
) {
2787 // Only determine mime types for files here. For directories,
2788 // KFileItem::determineMimeType() reads the .directory file inside to
2789 // load the icon, but this is not necessary at all if we just need the
2790 // type. Some special code for setting the correct mime type for
2791 // directories is in retrieveData().
2792 if (!item
.isDir()) {
2793 item
.determineMimeType();
2796 if (timer
.elapsed() > timeout
) {
2797 // Don't block the user interface, let the remaining items
2798 // be resolved asynchronously.
2804 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2806 static QSet
<QByteArray
> pool
;
2807 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2809 if (it
!= pool
.constEnd()) {
2817 bool KFileItemModel::isConsistent() const
2819 // m_items may contain less items than m_itemData because m_items
2820 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2821 if (m_items
.count() > m_itemData
.count()) {
2825 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2826 // Check if m_items and m_itemData are consistent.
2827 const KFileItem item
= fileItem(i
);
2828 if (item
.isNull()) {
2829 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2833 const int itemIndex
= index(item
);
2834 if (itemIndex
!= i
) {
2835 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2839 // Check if the items are sorted correctly.
2840 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2841 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2845 // Check if all parent-child relationships are consistent.
2846 const ItemData
*data
= m_itemData
.at(i
);
2847 const ItemData
*parent
= data
->parent
;
2849 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2850 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2854 const int parentIndex
= index(parent
->item
);
2855 if (parentIndex
>= i
) {
2856 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2866 void KFileItemModel::slotListerError(KIO::Job
*job
)
2868 const int jobError
= job
->error();
2869 if (jobError
== KIO::ERR_IS_FILE
) {
2870 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2871 Q_EMIT
urlIsFileError(listJob
->url());
2874 const QString errorString
= job
->errorString();
2875 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."), jobError
);
2879 #include "moc_kfileitemmodel.cpp"