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 #ifndef QT_NO_ACCESSIBILITY
24 #include <QAccessible>
26 #include <QElapsedTimer>
29 #include <QMimeDatabase>
30 #include <QRecursiveMutex>
33 #include <klazylocalizedstring.h>
35 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
37 // #define KFILEITEMMODEL_DEBUG
39 KFileItemModel::KFileItemModel(QObject
*parent
)
40 : KItemModelBase("text", parent
)
41 , m_dirLister(nullptr)
42 , m_sortDirsFirst(true)
43 , m_sortHiddenLast(false)
44 , m_sortRole(NameRole
)
45 , m_sortingProgressPercent(-1)
52 , m_maximumUpdateIntervalTimer(nullptr)
53 , m_resortAllItemsTimer(nullptr)
54 , m_pendingItemsToInsert()
59 m_collator
.setNumericMode(true);
61 loadSortingSettings();
63 m_dirLister
= new KDirLister(this);
64 m_dirLister
->setAutoErrorHandlingEnabled(false);
65 m_dirLister
->setDelayedMimeTypes(true);
67 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
69 m_dirLister
->setMainWindow(parentWidget
->window());
72 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
73 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
74 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
75 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
76 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
77 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
78 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
79 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
80 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
81 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
82 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
84 // Apply default roles that should be determined
86 m_requestRole
[NameRole
] = true;
87 m_requestRole
[IsDirRole
] = true;
88 m_requestRole
[IsLinkRole
] = true;
89 m_roles
.insert("text");
90 m_roles
.insert("isDir");
91 m_roles
.insert("isLink");
92 m_roles
.insert("isHidden");
94 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
95 // before the completed() or canceled() signal has been emitted.
96 m_maximumUpdateIntervalTimer
= new QTimer(this);
97 m_maximumUpdateIntervalTimer
->setInterval(2000);
98 m_maximumUpdateIntervalTimer
->setSingleShot(true);
99 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
101 // When changing the value of an item which represents the sort-role a resorting must be
102 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
103 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
104 // resorting is postponed until the timer has been exceeded.
105 m_resortAllItemsTimer
= new QTimer(this);
106 m_resortAllItemsTimer
->setInterval(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
107 // and sorting too infrequently which leads to users seeing an outdated sort order.
108 m_resortAllItemsTimer
->setSingleShot(true);
109 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
111 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
113 setShowTrashMime(m_dirLister
->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
116 KFileItemModel::~KFileItemModel()
118 qDeleteAll(m_itemData
);
119 qDeleteAll(m_filteredItems
);
120 qDeleteAll(m_pendingItemsToInsert
);
123 void KFileItemModel::loadDirectory(const QUrl
&url
)
125 m_dirLister
->openUrl(url
);
128 void KFileItemModel::refreshDirectory(const QUrl
&url
)
130 // Refresh all expanded directories first (Bug 295300)
131 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
132 while (expandedDirs
.hasNext()) {
134 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
137 m_dirLister
->openUrl(url
, KDirLister::Reload
);
139 Q_EMIT
directoryRefreshing();
142 QUrl
KFileItemModel::directory() const
144 return m_dirLister
->url();
147 void KFileItemModel::cancelDirectoryLoading()
152 int KFileItemModel::count() const
154 return m_itemData
.count();
157 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
159 if (index
>= 0 && index
< count()) {
160 ItemData
*data
= m_itemData
.at(index
);
161 if (data
->values
.isEmpty()) {
162 data
->values
= retrieveData(data
->item
, data
->parent
);
163 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
164 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
165 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
166 // so this special request of different behavior can be identified here.
167 bool hasExpandedParentsCount
= false;
168 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
170 data
->values
= retrieveData(data
->item
, data
->parent
);
171 data
->values
.insert("isExpanded", true);
172 if (hasExpandedParentsCount
) {
173 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
179 return QHash
<QByteArray
, QVariant
>();
182 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
184 if (index
< 0 || index
>= count()) {
188 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
190 // Determine which roles have been changed
191 QSet
<QByteArray
> changedRoles
;
192 QHashIterator
<QByteArray
, QVariant
> it(values
);
193 while (it
.hasNext()) {
195 const QByteArray role
= sharedValue(it
.key());
196 const QVariant value
= it
.value();
198 if (currentValues
[role
] != value
) {
199 currentValues
[role
] = value
;
200 changedRoles
.insert(role
);
204 if (changedRoles
.isEmpty()) {
208 if (changedRoles
.contains("text")) {
209 QUrl url
= m_itemData
[index
]->item
.url();
211 url
= url
.adjusted(QUrl::RemoveFilename
);
212 url
.setPath(url
.path() + currentValues
["text"].toString());
213 m_itemData
[index
]->item
.setUrl(url
);
214 m_items
.insert(url
, index
);
216 if (!changedRoles
.contains("url")) {
217 changedRoles
.insert("url");
218 currentValues
["url"] = url
;
221 m_itemData
[index
]->values
= currentValues
;
223 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
228 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
230 if (dirsFirst
!= m_sortDirsFirst
) {
231 m_sortDirsFirst
= dirsFirst
;
236 bool KFileItemModel::sortDirectoriesFirst() const
238 return m_sortDirsFirst
;
241 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
243 if (hiddenLast
!= m_sortHiddenLast
) {
244 m_sortHiddenLast
= hiddenLast
;
249 bool KFileItemModel::sortHiddenLast() const
251 return m_sortHiddenLast
;
254 void KFileItemModel::setShowTrashMime(bool showTrashMime
)
256 const auto trashMime
= QStringLiteral("application/x-trash");
257 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
260 excludeFilter
.removeAll(trashMime
);
261 } else if (!excludeFilter
.contains(trashMime
)) {
262 excludeFilter
.append(trashMime
);
265 setExcludeMimeTypeFilter(excludeFilter
);
268 void KFileItemModel::scheduleResortAllItems()
270 if (!m_resortAllItemsTimer
->isActive()) {
271 m_resortAllItemsTimer
->start();
275 void KFileItemModel::setShowHiddenFiles(bool show
)
277 m_dirLister
->setShowHiddenFiles(show
);
278 setShowTrashMime(show
|| !GeneralSettings::hideXTrashFile());
279 m_dirLister
->emitChanges();
281 dispatchPendingItemsToInsert();
285 bool KFileItemModel::showHiddenFiles() const
287 return m_dirLister
->showHiddenFiles();
290 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
292 m_dirLister
->setDirOnlyMode(enabled
);
295 bool KFileItemModel::showDirectoriesOnly() const
297 return m_dirLister
->dirOnlyMode();
300 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
302 QMimeData
*data
= new QMimeData();
304 // The following code has been taken from KDirModel::mimeData()
305 // (kdelibs/kio/kio/kdirmodel.cpp)
306 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
308 QList
<QUrl
> mostLocalUrls
;
309 const ItemData
*lastAddedItem
= nullptr;
311 for (int index
: indexes
) {
312 const ItemData
*itemData
= m_itemData
.at(index
);
313 const ItemData
*parent
= itemData
->parent
;
315 while (parent
&& parent
!= lastAddedItem
) {
316 parent
= parent
->parent
;
319 if (parent
&& parent
== lastAddedItem
) {
320 // A parent of 'itemData' has been added already.
324 lastAddedItem
= itemData
;
325 const KFileItem
&item
= itemData
->item
;
326 if (!item
.isNull()) {
330 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
334 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
340 QString
removeMarks(const QString
&original
)
342 const auto normalized
= original
.normalized(QString::NormalizationForm_D
);
344 for (auto ch
: normalized
) {
353 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
355 const auto noMarkText
= removeMarks(text
);
356 startFromIndex
= qMax(0, startFromIndex
);
357 for (int i
= startFromIndex
; i
< count(); ++i
) {
358 if (removeMarks(fileItem(i
).text()).startsWith(noMarkText
, Qt::CaseInsensitive
)) {
362 for (int i
= 0; i
< startFromIndex
; ++i
) {
363 if (removeMarks(fileItem(i
).text()).startsWith(noMarkText
, Qt::CaseInsensitive
)) {
370 bool KFileItemModel::supportsDropping(int index
) const
376 item
= fileItem(index
);
378 return !item
.isNull() && DragAndDropHelper::supportsDropping(item
);
381 bool KFileItemModel::canEnterOnHover(int index
) const
387 item
= fileItem(index
);
389 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
392 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
394 static QHash
<QByteArray
, QString
> description
;
395 if (description
.isEmpty()) {
397 const RoleInfoMap
*map
= rolesInfoMap(count
);
398 for (int i
= 0; i
< count
; ++i
) {
399 if (map
[i
].roleTranslation
.isEmpty()) {
402 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
406 return description
.value(role
);
409 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
411 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
412 #ifdef KFILEITEMMODEL_DEBUG
416 switch (typeForRole(sortRole())) {
418 m_groups
= nameRoleGroups();
421 m_groups
= sizeRoleGroups();
423 case ModificationTimeRole
:
424 m_groups
= timeRoleGroups([](const ItemData
*item
) {
425 return item
->item
.time(KFileItem::ModificationTime
);
428 case CreationTimeRole
:
429 m_groups
= timeRoleGroups([](const ItemData
*item
) {
430 return item
->item
.time(KFileItem::CreationTime
);
434 m_groups
= timeRoleGroups([](const ItemData
*item
) {
435 return item
->item
.time(KFileItem::AccessTime
);
438 case DeletionTimeRole
:
439 m_groups
= timeRoleGroups([](const ItemData
*item
) {
440 return item
->values
.value("deletiontime").toDateTime();
443 case PermissionsRole
:
444 m_groups
= permissionRoleGroups();
447 m_groups
= ratingRoleGroups();
450 m_groups
= genericStringRoleGroups(sortRole());
454 #ifdef KFILEITEMMODEL_DEBUG
455 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
462 KFileItem
KFileItemModel::fileItem(int index
) const
464 if (index
>= 0 && index
< count()) {
465 return m_itemData
.at(index
)->item
;
471 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
473 const int indexForUrl
= index(url
);
474 if (indexForUrl
>= 0) {
475 return m_itemData
.at(indexForUrl
)->item
;
480 int KFileItemModel::index(const KFileItem
&item
) const
482 return index(item
.url());
485 int KFileItemModel::index(const QUrl
&url
) const
487 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
489 const int itemCount
= m_itemData
.count();
490 int itemsInHash
= m_items
.count();
492 int index
= m_items
.value(urlToFind
, -1);
493 while (index
< 0 && itemsInHash
< itemCount
) {
494 // Not all URLs are stored yet in m_items. We grow m_items until either
495 // urlToFind is found, or all URLs have been stored in m_items.
496 // Note that we do not add the URLs to m_items one by one, but in
497 // larger blocks. After each block, we check if urlToFind is in
498 // m_items. We could in principle compare urlToFind with each URL while
499 // we are going through m_itemData, but comparing two QUrls will,
500 // unlike calling qHash for the URLs, trigger a parsing of the URLs
501 // which costs both CPU cycles and memory.
502 const int blockSize
= 1000;
503 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
504 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
505 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
506 m_items
.insert(nextUrl
, i
);
509 itemsInHash
= currentBlockEnd
;
510 index
= m_items
.value(urlToFind
, -1);
514 // The item could not be found, even though all items from m_itemData
515 // should be in m_items now. We print some diagnostic information which
516 // might help to find the cause of the problem, but only once. This
517 // prevents that obtaining and printing the debugging information
518 // wastes CPU cycles and floods the shell or .xsession-errors.
519 static bool printDebugInfo
= true;
521 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
522 printDebugInfo
= false;
524 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
525 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
526 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
528 // Check if there are multiple items with the same URL.
529 QMultiHash
<QUrl
, int> indexesForUrl
;
530 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
531 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
534 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
535 for (const QUrl
&url
: uniqueKeys
) {
536 if (indexesForUrl
.count(url
) > 1) {
537 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
539 auto it
= indexesForUrl
.find(url
);
540 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
541 const ItemData
*data
= m_itemData
.at(it
.value());
542 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
544 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
556 KFileItem
KFileItemModel::rootItem() const
558 return m_dirLister
->rootItem();
561 void KFileItemModel::clear()
566 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
568 if (m_roles
== roles
) {
572 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
576 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
577 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
578 if (supportedExpanding
&& !willSupportExpanding
) {
579 // No expanding is supported anymore. Take care to delete all items that have an expansion level
580 // that is not 0 (and hence are part of an expanded item).
581 removeExpandedItems();
588 QSetIterator
<QByteArray
> it(roles
);
589 while (it
.hasNext()) {
590 const QByteArray
&role
= it
.next();
591 m_requestRole
[typeForRole(role
)] = true;
595 // Update m_data with the changed requested roles
596 const int maxIndex
= count() - 1;
597 for (int i
= 0; i
<= maxIndex
; ++i
) {
598 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
601 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
604 // Clear the 'values' of all filtered items. They will be re-populated with the
605 // correct roles the next time 'values' will be accessed via data(int).
606 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
607 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
608 while (filteredIt
!= filteredEnd
) {
609 (*filteredIt
)->values
.clear();
614 QSet
<QByteArray
> KFileItemModel::roles() const
619 bool KFileItemModel::setExpanded(int index
, bool expanded
)
621 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
625 QHash
<QByteArray
, QVariant
> values
;
626 values
.insert(sharedValue("isExpanded"), expanded
);
627 if (!setData(index
, values
)) {
631 const KFileItem item
= m_itemData
.at(index
)->item
;
632 const QUrl url
= item
.url();
633 const QUrl targetUrl
= item
.targetUrl();
635 m_expandedDirs
.insert(targetUrl
, url
);
636 m_dirLister
->openUrl(url
, KDirLister::Keep
);
638 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
639 for (const QVariant
&var
: previouslyExpandedChildren
) {
640 m_urlsToExpand
.insert(var
.toUrl());
643 // Note that there might be (indirect) children of the folder which is to be collapsed in
644 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
645 // possibly without a parent, which might result in a crash, we insert all pending items
646 // right now. All new items which would be without a parent will then be removed.
647 dispatchPendingItemsToInsert();
649 // Check if the index of the collapsed folder has changed. If that is the case, then items
650 // were inserted before the collapsed folder, and its index needs to be updated.
651 if (m_itemData
.at(index
)->item
!= item
) {
652 index
= this->index(item
);
655 m_expandedDirs
.remove(targetUrl
);
656 m_dirLister
->stop(url
);
657 m_dirLister
->forgetDirs(url
);
659 const int parentLevel
= expandedParentsCount(index
);
660 const int itemCount
= m_itemData
.count();
661 const int firstChildIndex
= index
+ 1;
663 QVariantList expandedChildren
;
665 int childIndex
= firstChildIndex
;
666 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
667 ItemData
*itemData
= m_itemData
.at(childIndex
);
668 if (itemData
->values
.value("isExpanded").toBool()) {
669 const QUrl targetUrl
= itemData
->item
.targetUrl();
670 const QUrl url
= itemData
->item
.url();
671 m_expandedDirs
.remove(targetUrl
);
672 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
673 m_dirLister
->forgetDirs(url
);
674 expandedChildren
.append(targetUrl
);
678 const int childrenCount
= childIndex
- firstChildIndex
;
680 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
681 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
683 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
689 bool KFileItemModel::isExpanded(int index
) const
691 if (index
>= 0 && index
< count()) {
692 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
697 bool KFileItemModel::isExpandable(int index
) const
699 if (index
>= 0 && index
< count()) {
700 // Call data (instead of accessing m_itemData directly)
701 // to ensure that the value is initialized.
702 return data(index
).value("isExpandable").toBool();
707 int KFileItemModel::expandedParentsCount(int index
) const
709 if (index
>= 0 && index
< count()) {
710 return expandedParentsCount(m_itemData
.at(index
));
715 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
718 const auto dirs
= m_expandedDirs
;
719 for (const auto &dir
: dirs
) {
725 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
727 m_urlsToExpand
= urls
;
730 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
732 // Assure that each sub-path of the URL that should be
733 // expanded is added to m_urlsToExpand. KDirLister
734 // does not care whether the parent-URL has already been
736 QUrl urlToExpand
= m_dirLister
->url();
737 const int pos
= urlToExpand
.path().length();
739 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
740 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
741 // so using QString::SkipEmptyParts
742 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
743 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
744 QString path
= urlToExpand
.path();
745 if (!path
.endsWith(QLatin1Char('/'))) {
746 path
.append(QLatin1Char('/'));
748 urlToExpand
.setPath(path
+ subDirs
.at(i
));
749 m_urlsToExpand
.insert(urlToExpand
);
752 // KDirLister::open() must called at least once to trigger an initial
753 // loading. The pending URLs that must be restored are handled
754 // in slotCompleted().
755 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
756 while (it2
.hasNext()) {
757 const int idx
= index(it2
.next());
758 if (idx
>= 0 && !isExpanded(idx
)) {
759 setExpanded(idx
, true);
765 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
767 if (m_filter
.pattern() != nameFilter
) {
768 dispatchPendingItemsToInsert();
769 m_filter
.setPattern(nameFilter
);
774 QString
KFileItemModel::nameFilter() const
776 return m_filter
.pattern();
779 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
781 if (m_filter
.mimeTypes() != filters
) {
782 dispatchPendingItemsToInsert();
783 m_filter
.setMimeTypes(filters
);
788 QStringList
KFileItemModel::mimeTypeFilters() const
790 return m_filter
.mimeTypes();
793 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
795 if (m_filter
.excludeMimeTypes() != filters
) {
796 dispatchPendingItemsToInsert();
797 m_filter
.setExcludeMimeTypes(filters
);
802 QStringList
KFileItemModel::excludeMimeTypeFilter() const
804 return m_filter
.excludeMimeTypes();
807 void KFileItemModel::applyFilters()
810 // Check which previously shown items from m_itemData must now get
811 // hidden and hence moved from m_itemData into m_filteredItems.
813 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
815 // This pointer will refer to the next confirmed shown item from the point of
816 // view of the current "itemData" in the upcoming "for" loop.
817 ItemData
*itemShownBelow
= nullptr;
819 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
820 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
821 ItemData
*itemData
= m_itemData
.at(index
);
823 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
824 // We could've entered here for two reasons:
825 // 1. This item passes the filter itself
826 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
828 // So this item must remain shown.
829 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
830 itemShownBelow
= itemData
;
832 // We hide this item for now, however, for expanded folders this is not final:
833 // 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
834 newFilteredIndexes
.prepend(index
);
835 m_filteredItems
.insert(itemData
->item
, itemData
);
836 // indexShownBelow doesn't get updated since this item will be hidden
840 // This will remove the newly filtered items from m_itemData
841 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
844 // Check which hidden items from m_filteredItems should
845 // become visible again and hence moved from m_filteredItems back into m_itemData.
847 QList
<ItemData
*> newVisibleItems
;
849 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
851 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
852 while (it
!= m_filteredItems
.end()) {
853 if (m_filter
.matches(it
.key())) {
854 newVisibleItems
.append(it
.value());
856 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
857 // We will go up through its parental chain until we either:
858 // 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
859 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
860 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
861 parent
= parent
->parent
) {
862 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
863 // and it would mess up the iteration. We will mark it to be removed in step 3.
864 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
867 it
= m_filteredItems
.erase(it
);
869 // Item remains filtered for now
870 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
876 // Handles the ancestorsOfNewVisibleItems.
877 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
878 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
879 if (m_filteredItems
.remove(it
.key())) {
880 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
881 newVisibleItems
.append(it
.value());
885 // This will insert the newly discovered unfiltered items into m_itemData
886 insertItems(newVisibleItems
);
889 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
891 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
892 // There are either no filtered items, or it is not possible to expand
893 // folders -> there cannot be any filtered children.
897 QSet
<ItemData
*> parents
;
898 for (const KItemRange
&range
: itemRanges
) {
899 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
900 parents
.insert(m_itemData
.at(index
));
904 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
905 while (it
!= m_filteredItems
.end()) {
906 if (parents
.contains(it
.value()->parent
)) {
908 it
= m_filteredItems
.erase(it
);
915 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
917 static QList
<RoleInfo
> rolesInfo
;
918 if (rolesInfo
.isEmpty()) {
920 const RoleInfoMap
*map
= rolesInfoMap(count
);
921 for (int i
= 0; i
< count
; ++i
) {
922 if (map
[i
].roleType
!= NoRole
) {
924 info
.role
= map
[i
].role
;
925 info
.translation
= map
[i
].roleTranslation
.toString();
926 if (!map
[i
].groupTranslation
.isEmpty()) {
927 info
.group
= map
[i
].groupTranslation
.toString();
929 // For top level roles, groupTranslation is 0. We must make sure that
930 // info.group is an empty string then because the code that generates
931 // menus tries to put the actions into sub menus otherwise.
932 info
.group
= QString();
934 info
.requiresBaloo
= map
[i
].requiresBaloo
;
935 info
.requiresIndexer
= map
[i
].requiresIndexer
;
936 if (!map
[i
].tooltipTranslation
.isEmpty()) {
937 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
939 info
.tooltip
= QString();
941 rolesInfo
.append(info
);
949 void KFileItemModel::onGroupedSortingChanged(bool current
)
955 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
958 m_sortRole
= typeForRole(current
);
960 if (!m_requestRole
[m_sortRole
]) {
961 QSet
<QByteArray
> newRoles
= m_roles
;
971 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
978 void KFileItemModel::loadSortingSettings()
980 using Choice
= GeneralSettings::EnumSortingChoice
;
981 switch (GeneralSettings::sortingChoice()) {
982 case Choice::NaturalSorting
:
983 m_naturalSorting
= true;
984 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
986 case Choice::CaseSensitiveSorting
:
987 m_naturalSorting
= false;
988 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
990 case Choice::CaseInsensitiveSorting
:
991 m_naturalSorting
= false;
992 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
997 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
998 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
999 m_collator
.compare(QString(), QString());
1002 void KFileItemModel::resortAllItems()
1004 m_resortAllItemsTimer
->stop();
1006 const int itemCount
= count();
1007 if (itemCount
<= 0) {
1011 #ifdef KFILEITEMMODEL_DEBUG
1012 QElapsedTimer timer
;
1014 qCDebug(DolphinDebug
) << "===========================================================";
1015 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
1018 // Remember the order of the current URLs so
1019 // that it can be determined which indexes have
1020 // been moved because of the resorting.
1021 QList
<QUrl
> oldUrls
;
1022 oldUrls
.reserve(itemCount
);
1023 for (const ItemData
*itemData
: std::as_const(m_itemData
)) {
1024 oldUrls
.append(itemData
->item
.url());
1028 m_items
.reserve(itemCount
);
1031 sort(m_itemData
.begin(), m_itemData
.end());
1032 for (int i
= 0; i
< itemCount
; ++i
) {
1033 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1036 // Determine the first index that has been moved.
1037 int firstMovedIndex
= 0;
1038 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1042 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1043 if (itemsHaveMoved
) {
1046 int lastMovedIndex
= itemCount
- 1;
1047 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1051 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1053 // Create a list movedToIndexes, which has the property that
1054 // movedToIndexes[i] is the new index of the item with the old index
1055 // firstMovedIndex + i.
1056 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1057 QList
<int> movedToIndexes
;
1058 movedToIndexes
.reserve(movedItemsCount
);
1059 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1060 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1061 movedToIndexes
.append(newIndex
);
1064 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1065 } else if (groupedSorting()) {
1066 // The groups might have changed even if the order of the items has not.
1067 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1069 if (groups() != oldGroups
) {
1070 Q_EMIT
groupsChanged();
1074 #ifdef KFILEITEMMODEL_DEBUG
1075 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1079 void KFileItemModel::slotCompleted()
1081 m_maximumUpdateIntervalTimer
->stop();
1082 dispatchPendingItemsToInsert();
1084 if (!m_urlsToExpand
.isEmpty()) {
1085 // Try to find a URL that can be expanded.
1086 // Note that the parent folder must be expanded before any of its subfolders become visible.
1087 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1088 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1089 // Iterate over a const copy because items are deleted and inserted within the loop
1090 const auto urlsToExpand
= m_urlsToExpand
;
1091 for (const QUrl
&url
: urlsToExpand
) {
1092 const int indexForUrl
= index(url
);
1093 if (indexForUrl
>= 0) {
1094 m_urlsToExpand
.remove(url
);
1095 if (setExpanded(indexForUrl
, true)) {
1096 // The dir lister has been triggered. This slot will be called
1097 // again after the directory has been expanded.
1103 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1104 // if these URLs have been deleted in the meantime.
1105 m_urlsToExpand
.clear();
1108 Q_EMIT
directoryLoadingCompleted();
1111 void KFileItemModel::slotCanceled()
1113 m_maximumUpdateIntervalTimer
->stop();
1114 dispatchPendingItemsToInsert();
1116 Q_EMIT
directoryLoadingCanceled();
1119 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1121 Q_ASSERT(!items
.isEmpty());
1123 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1125 if (m_requestRole
[ExpandedParentsCountRole
]) {
1126 // If the expanding of items is enabled, the call
1127 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1128 // might result in emitting the same items twice due to the Keep-parameter.
1129 // This case happens if an item gets expanded, collapsed and expanded again
1130 // before the items could be loaded for the first expansion.
1131 if (index(items
.first().url()) >= 0) {
1132 // The items are already part of the model.
1136 if (directoryUrl
!= directory()) {
1137 // To be able to compare whether the new items may be inserted as children
1138 // of a parent item the pending items must be added to the model first.
1139 dispatchPendingItemsToInsert();
1142 // KDirLister keeps the children of items that got expanded once even if
1143 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1144 // checked whether the parent for new items is still expanded.
1145 const int parentIndex
= index(parentUrl
);
1146 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1147 // The parent is not expanded.
1152 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1154 if (!m_filter
.hasSetFilters()) {
1155 m_pendingItemsToInsert
.append(itemDataList
);
1157 QSet
<ItemData
*> parentsToEnsureVisible
;
1159 // The name or type filter is active. Hide filtered items
1160 // before inserting them into the model and remember
1161 // the filtered items in m_filteredItems.
1162 for (ItemData
*itemData
: itemDataList
) {
1163 if (m_filter
.matches(itemData
->item
)) {
1164 m_pendingItemsToInsert
.append(itemData
);
1165 if (itemData
->parent
) {
1166 parentsToEnsureVisible
.insert(itemData
->parent
);
1169 m_filteredItems
.insert(itemData
->item
, itemData
);
1173 // Entire parental chains must be shown
1174 for (ItemData
*parent
: parentsToEnsureVisible
) {
1175 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1176 m_pendingItemsToInsert
.append(parent
);
1181 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1182 // Assure that items get dispatched if no completed() or canceled() signal is
1183 // emitted during the maximum update interval.
1184 m_maximumUpdateIntervalTimer
->start();
1187 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1190 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1192 int filteredParentsCount
= 0;
1193 // The childless parents not yet removed will always be right above the start of a removed range.
1194 // We iterate backwards to ensure the deepest folders are processed before their parents
1195 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1196 KItemRange itemRange
= removedItemRanges
.at(i
);
1197 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1198 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1199 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1201 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1202 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1203 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1204 // and this deleted range covers all of its descendents, so none will be left.
1205 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1206 // This range's starting index will be extended to include the parent above:
1209 ++filteredParentsCount
;
1210 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1211 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1212 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1213 previousRange
.count
+= itemRange
.count
;
1214 removedItemRanges
.replace(i
- 1, previousRange
);
1215 removedItemRanges
.removeAt(i
);
1217 removedItemRanges
.replace(i
, itemRange
);
1218 // We must revisit this range in the next iteration since its starting index changed
1223 return filteredParentsCount
;
1226 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1228 dispatchPendingItemsToInsert();
1230 QVector
<int> indexesToRemove
;
1231 indexesToRemove
.reserve(items
.count());
1232 KFileItemList dirsChanged
;
1234 const auto currentDir
= directory();
1236 for (const KFileItem
&item
: items
) {
1237 if (item
.url() == currentDir
) {
1238 Q_EMIT
currentDirectoryRemoved();
1242 const int indexForItem
= index(item
);
1243 if (indexForItem
>= 0) {
1244 indexesToRemove
.append(indexForItem
);
1246 // Probably the item has been filtered.
1247 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1248 if (it
!= m_filteredItems
.end()) {
1250 m_filteredItems
.erase(it
);
1254 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1255 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1256 dirsChanged
<< KFileItem(parentUrl
);
1260 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1262 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1263 // Assure that removing a parent item also results in removing all children
1264 QVector
<int> indexesToRemoveWithChildren
;
1265 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1267 const int itemCount
= m_itemData
.count();
1268 for (int index
: std::as_const(indexesToRemove
)) {
1269 indexesToRemoveWithChildren
.append(index
);
1271 const int parentLevel
= expandedParentsCount(index
);
1272 int childIndex
= index
+ 1;
1273 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1274 indexesToRemoveWithChildren
.append(childIndex
);
1279 indexesToRemove
= indexesToRemoveWithChildren
;
1282 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1283 removeFilteredChildren(itemRanges
);
1285 // This call will update itemRanges to include the childless parents that have been filtered.
1286 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1288 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1289 // mixed with expanded folders that are just being filtered out.
1290 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1291 // so removeItems() will check m_filteredItems to differentiate which is which.
1292 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1294 Q_EMIT
fileItemsChanged(dirsChanged
);
1297 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1299 Q_ASSERT(!items
.isEmpty());
1300 #ifdef KFILEITEMMODEL_DEBUG
1301 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1304 // Get the indexes of all items that have been refreshed
1306 indexes
.reserve(items
.count());
1308 QSet
<QByteArray
> changedRoles
;
1309 KFileItemList changedFiles
;
1311 // Contains the indexes of the currently visible items
1312 // that should get hidden and hence moved to m_filteredItems.
1313 QVector
<int> newFilteredIndexes
;
1315 // Contains currently hidden items that should
1316 // get visible and hence removed from m_filteredItems
1317 QList
<ItemData
*> newVisibleItems
;
1319 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1321 while (it
.hasNext()) {
1322 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1323 const KFileItem
&oldItem
= itemPair
.first
;
1324 const KFileItem
&newItem
= itemPair
.second
;
1325 const int indexForItem
= index(oldItem
);
1326 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1327 if (indexForItem
>= 0) {
1328 m_itemData
[indexForItem
]->item
= newItem
;
1330 // Keep old values as long as possible if they could not retrieved synchronously yet.
1331 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1332 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1333 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1334 while (it
.hasNext()) {
1336 const QByteArray
&role
= it
.key();
1337 if (itemData
->values
.value(role
) != it
.value()) {
1338 itemData
->values
.insert(role
, it
.value());
1339 changedRoles
.insert(role
);
1343 m_items
.remove(oldItem
.url());
1344 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1345 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1346 m_items
.insert(newItem
.url(), indexForItem
);
1347 if (newItemMatchesFilter
1348 || (itemData
->values
.value("isExpanded").toBool()
1349 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1350 // We are lenient with expanded folders that originally had visible children.
1351 // If they become childless now they will be caught by filterChildlessParents()
1352 changedFiles
.append(newItem
);
1353 indexes
.append(indexForItem
);
1355 newFilteredIndexes
.append(indexForItem
);
1356 m_filteredItems
.insert(newItem
, itemData
);
1359 // Check if 'oldItem' is one of the filtered items.
1360 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1361 if (it
!= m_filteredItems
.end()) {
1362 ItemData
*const itemData
= it
.value();
1363 itemData
->item
= newItem
;
1365 // The data stored in 'values' might have changed. Therefore, we clear
1366 // 'values' and re-populate it the next time it is requested via data(int).
1367 // Before clearing, we must remember if it was expanded and the expanded parents count,
1368 // otherwise these states would be lost. The data() method will deal with this special case.
1369 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1370 bool hasExpandedParentsCount
= false;
1371 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1372 itemData
->values
.clear();
1374 itemData
->values
.insert("isExpanded", true);
1375 if (hasExpandedParentsCount
) {
1376 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1380 m_filteredItems
.erase(it
);
1381 if (newItemMatchesFilter
) {
1382 newVisibleItems
.append(itemData
);
1384 m_filteredItems
.insert(newItem
, itemData
);
1390 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1392 // We must keep track of parents of new visible items since they must be shown no matter what
1393 // They will be considered "immune" to filterChildlessParents()
1394 QSet
<ItemData
*> parentsToEnsureVisible
;
1396 for (ItemData
*item
: newVisibleItems
) {
1397 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1398 parentsToEnsureVisible
.insert(parent
);
1401 for (ItemData
*parent
: parentsToEnsureVisible
) {
1402 // We make sure they are all unfiltered.
1403 if (m_filteredItems
.remove(parent
->item
)) {
1404 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1405 newVisibleItems
.append(parent
);
1406 // It could be in newFilteredIndexes, we must remove it if it's there:
1407 const int parentIndex
= index(parent
->item
);
1408 if (parentIndex
>= 0) {
1409 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1410 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1411 newFilteredIndexes
.erase(it
);
1417 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1419 // This call will update itemRanges to include the childless parents that have been filtered.
1420 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1422 removeItems(removedRanges
, KeepItemData
);
1424 // Show previously hidden items that should get visible
1425 insertItems(newVisibleItems
);
1427 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1429 // If the changed items have been created recently, they might not be in m_items yet.
1430 // In that case, the list 'indexes' might be empty.
1431 if (indexes
.isEmpty()) {
1435 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1436 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1438 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1439 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1440 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1441 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1446 std::sort(indexes
.begin(), indexes
.end());
1449 // Extract the item-ranges out of the changed indexes
1450 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1451 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1453 Q_EMIT
fileItemsChanged(changedFiles
);
1456 void KFileItemModel::slotClear()
1458 #ifdef KFILEITEMMODEL_DEBUG
1459 qCDebug(DolphinDebug
) << "Clearing all items";
1462 qDeleteAll(m_filteredItems
);
1463 m_filteredItems
.clear();
1466 m_maximumUpdateIntervalTimer
->stop();
1467 m_resortAllItemsTimer
->stop();
1469 qDeleteAll(m_pendingItemsToInsert
);
1470 m_pendingItemsToInsert
.clear();
1472 const int removedCount
= m_itemData
.count();
1473 if (removedCount
> 0) {
1474 qDeleteAll(m_itemData
);
1477 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1480 m_expandedDirs
.clear();
1483 void KFileItemModel::slotSortingChoiceChanged()
1485 loadSortingSettings();
1489 void KFileItemModel::dispatchPendingItemsToInsert()
1491 if (!m_pendingItemsToInsert
.isEmpty()) {
1492 insertItems(m_pendingItemsToInsert
);
1493 m_pendingItemsToInsert
.clear();
1497 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1499 if (newItems
.isEmpty()) {
1503 #ifdef KFILEITEMMODEL_DEBUG
1504 QElapsedTimer timer
;
1506 qCDebug(DolphinDebug
) << "===========================================================";
1507 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1511 prepareItemsForSorting(newItems
);
1513 // Natural sorting of items can be very slow. However, it becomes much faster
1514 // if the input sequence is already mostly sorted. Therefore, we first sort
1515 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1516 if (m_naturalSorting
) {
1517 if (m_sortRole
== NameRole
) {
1518 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1519 } else if (isRoleValueNatural(m_sortRole
)) {
1520 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1521 const QByteArray role
= roleForType(m_sortRole
);
1522 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1524 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1528 sort(newItems
.begin(), newItems
.end());
1530 #ifdef KFILEITEMMODEL_DEBUG
1531 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1534 KItemRangeList itemRanges
;
1535 const int existingItemCount
= m_itemData
.count();
1536 const int newItemCount
= newItems
.count();
1537 const int totalItemCount
= existingItemCount
+ newItemCount
;
1539 if (existingItemCount
== 0) {
1540 // Optimization for the common special case that there are no
1541 // items in the model yet. Happens, e.g., when entering a folder.
1542 m_itemData
= newItems
;
1543 itemRanges
<< KItemRange(0, newItemCount
);
1545 m_itemData
.reserve(totalItemCount
);
1546 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1547 m_itemData
.append(nullptr);
1550 // We build the new list m_itemData in reverse order to minimize
1551 // the number of moves and guarantee O(N) complexity.
1552 int targetIndex
= totalItemCount
- 1;
1553 int sourceIndexExistingItems
= existingItemCount
- 1;
1554 int sourceIndexNewItems
= newItemCount
- 1;
1558 while (sourceIndexNewItems
>= 0) {
1559 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1560 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1561 // Move an existing item to its new position. If any new items
1562 // are behind it, push the item range to itemRanges.
1563 if (rangeCount
> 0) {
1564 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1568 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1569 --sourceIndexExistingItems
;
1571 // Insert a new item into the list.
1573 m_itemData
[targetIndex
] = newItem
;
1574 --sourceIndexNewItems
;
1579 // Push the final item range to itemRanges.
1580 if (rangeCount
> 0) {
1581 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1584 // Note that itemRanges is still sorted in reverse order.
1585 std::reverse(itemRanges
.begin(), itemRanges
.end());
1588 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1589 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1592 Q_EMIT
itemsInserted(itemRanges
);
1594 #ifdef KFILEITEMMODEL_DEBUG
1595 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1599 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1601 if (itemRanges
.isEmpty()) {
1607 // Step 1: Remove the items from m_itemData, and free the ItemData.
1608 int removedItemsCount
= 0;
1609 for (const KItemRange
&range
: itemRanges
) {
1610 removedItemsCount
+= range
.count
;
1612 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1613 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1614 delete m_itemData
.at(index
);
1617 m_itemData
[index
] = nullptr;
1621 // Step 2: Remove the ItemData pointers from the list m_itemData.
1622 int target
= itemRanges
.at(0).index
;
1623 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1626 const int oldItemDataCount
= m_itemData
.count();
1627 while (source
< oldItemDataCount
) {
1628 m_itemData
[target
] = m_itemData
[source
];
1632 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1633 // Skip the items in the next removed range.
1634 source
+= itemRanges
.at(nextRange
).count
;
1639 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1641 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1642 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1645 Q_EMIT
itemsRemoved(itemRanges
);
1648 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1650 if (m_sortRole
== TypeRole
) {
1651 // Try to resolve the MIME-types synchronously to prevent a reordering of
1652 // the items when sorting by type (per default MIME-types are resolved
1653 // asynchronously by KFileItemModelRolesUpdater).
1654 determineMimeTypes(items
, 200);
1657 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1658 const int parentIndex
= index(parentUrl
);
1659 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1661 QList
<ItemData
*> itemDataList
;
1662 itemDataList
.reserve(items
.count());
1664 for (const KFileItem
&item
: items
) {
1665 ItemData
*itemData
= new ItemData();
1666 itemData
->item
= item
;
1667 itemData
->parent
= parentItem
;
1668 itemDataList
.append(itemData
);
1671 return itemDataList
;
1674 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1676 switch (m_sortRole
) {
1678 case PermissionsRole
:
1681 case DestinationRole
:
1683 case DeletionTimeRole
:
1684 // These roles can be determined with retrieveData, and they have to be stored
1685 // in the QHash "values" for the sorting.
1686 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1687 if (itemData
->values
.isEmpty()) {
1688 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1694 // At least store the data including the file type for items with known MIME type.
1695 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1696 if (itemData
->values
.isEmpty()) {
1697 const KFileItem item
= itemData
->item
;
1698 if (item
.isDir() || item
.isMimeTypeKnown()) {
1699 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1706 // The other roles are either resolved by KFileItemModelRolesUpdater
1707 // (this includes the SizeRole for directories), or they do not need
1708 // to be stored in the QHash "values" for sorting because the data can
1709 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1715 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1717 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1718 // if the corresponding item is expanded, and it is not a top-level item.
1719 const ItemData
*parent
= data
->parent
;
1721 if (parent
->parent
) {
1722 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1723 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1732 void KFileItemModel::removeExpandedItems()
1734 QVector
<int> indexesToRemove
;
1736 const int maxIndex
= m_itemData
.count() - 1;
1737 for (int i
= 0; i
<= maxIndex
; ++i
) {
1738 const ItemData
*itemData
= m_itemData
.at(i
);
1739 if (itemData
->parent
) {
1740 indexesToRemove
.append(i
);
1744 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1745 m_expandedDirs
.clear();
1747 // Also remove all filtered items which have a parent.
1748 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1749 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1752 if (it
.value()->parent
) {
1754 it
= m_filteredItems
.erase(it
);
1761 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1763 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1765 // Trigger a resorting if necessary. Note that this can happen even if the sort
1766 // role has not changed at all because the file name can be used as a fallback.
1767 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))
1768 || (changedRoles
.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1769 for (const KItemRange
&range
: itemRanges
) {
1770 bool needsResorting
= false;
1772 const int first
= range
.index
;
1773 const int last
= range
.index
+ range
.count
- 1;
1775 // Resorting the model is necessary if
1776 // (a) The first item in the range is "lessThan" its predecessor,
1777 // (b) the successor of the last item is "lessThan" the last item, or
1778 // (c) the internal order of the items in the range is incorrect.
1779 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1780 needsResorting
= true;
1781 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1782 needsResorting
= true;
1784 for (int index
= first
; index
< last
; ++index
) {
1785 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1786 needsResorting
= true;
1792 if (needsResorting
) {
1793 scheduleResortAllItems();
1799 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1800 // The position is still correct, but the groups might have changed
1801 // if the changed item is either the first or the last item in a
1803 // In principle, we could try to find out if the item really is the
1804 // first or last one in its group and then update the groups
1805 // (possibly with a delayed timer to make sure that we don't
1806 // re-calculate the groups very often if items are updated one by
1807 // one), but starting m_resortAllItemsTimer is easier.
1808 m_resortAllItemsTimer
->start();
1812 void KFileItemModel::resetRoles()
1814 for (int i
= 0; i
< RolesCount
; ++i
) {
1815 m_requestRole
[i
] = false;
1819 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1821 static QHash
<QByteArray
, RoleType
> roles
;
1822 if (roles
.isEmpty()) {
1823 // Insert user visible roles that can be accessed with
1824 // KFileItemModel::roleInformation()
1826 const RoleInfoMap
*map
= rolesInfoMap(count
);
1827 for (int i
= 0; i
< count
; ++i
) {
1828 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1831 // Insert internal roles (take care to synchronize the implementation
1832 // with KFileItemModel::roleForType() in case if a change is done).
1833 roles
.insert("isDir", IsDirRole
);
1834 roles
.insert("isLink", IsLinkRole
);
1835 roles
.insert("isHidden", IsHiddenRole
);
1836 roles
.insert("isExpanded", IsExpandedRole
);
1837 roles
.insert("isExpandable", IsExpandableRole
);
1838 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1840 Q_ASSERT(roles
.count() == RolesCount
);
1843 return roles
.value(role
, NoRole
);
1846 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1848 static QHash
<RoleType
, QByteArray
> roles
;
1849 if (roles
.isEmpty()) {
1850 // Insert user visible roles that can be accessed with
1851 // KFileItemModel::roleInformation()
1853 const RoleInfoMap
*map
= rolesInfoMap(count
);
1854 for (int i
= 0; i
< count
; ++i
) {
1855 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1858 // Insert internal roles (take care to synchronize the implementation
1859 // with KFileItemModel::typeForRole() in case if a change is done).
1860 roles
.insert(IsDirRole
, "isDir");
1861 roles
.insert(IsLinkRole
, "isLink");
1862 roles
.insert(IsHiddenRole
, "isHidden");
1863 roles
.insert(IsExpandedRole
, "isExpanded");
1864 roles
.insert(IsExpandableRole
, "isExpandable");
1865 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1867 Q_ASSERT(roles
.count() == RolesCount
);
1870 return roles
.value(roleType
);
1873 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1875 // It is important to insert only roles that are fast to retrieve. E.g.
1876 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1877 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1878 QHash
<QByteArray
, QVariant
> data
;
1879 data
.insert(sharedValue("url"), item
.url());
1881 const bool isDir
= item
.isDir();
1882 if (m_requestRole
[IsDirRole
] && isDir
) {
1883 data
.insert(sharedValue("isDir"), true);
1886 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1887 data
.insert(sharedValue("isLink"), true);
1890 if (m_requestRole
[IsHiddenRole
]) {
1891 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1894 if (m_requestRole
[NameRole
]) {
1895 data
.insert(sharedValue("text"), item
.text());
1898 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1899 // TODO KF6 use KFileItem::suffix 464722
1900 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1903 if (m_requestRole
[SizeRole
] && !isDir
) {
1904 data
.insert(sharedValue("size"), item
.size());
1907 if (m_requestRole
[ModificationTimeRole
]) {
1908 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1909 // having several thousands of items. Instead read the raw number from UDSEntry directly
1910 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1911 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1912 data
.insert(sharedValue("modificationtime"), dateTime
);
1915 if (m_requestRole
[CreationTimeRole
]) {
1916 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1917 // having several thousands of items. Instead read the raw number from UDSEntry directly
1918 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1919 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1920 data
.insert(sharedValue("creationtime"), dateTime
);
1923 if (m_requestRole
[AccessTimeRole
]) {
1924 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1925 // having several thousands of items. Instead read the raw number from UDSEntry directly
1926 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1927 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1928 data
.insert(sharedValue("accesstime"), dateTime
);
1931 if (m_requestRole
[PermissionsRole
]) {
1932 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1935 if (m_requestRole
[OwnerRole
]) {
1936 data
.insert(sharedValue("owner"), item
.user());
1939 if (m_requestRole
[GroupRole
]) {
1940 data
.insert(sharedValue("group"), item
.group());
1943 if (m_requestRole
[DestinationRole
]) {
1944 QString destination
= item
.linkDest();
1945 if (destination
.isEmpty()) {
1946 destination
= QLatin1Char('-');
1948 data
.insert(sharedValue("destination"), destination
);
1951 if (m_requestRole
[PathRole
]) {
1953 if (item
.url().scheme() == QLatin1String("trash")) {
1954 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1956 // For performance reasons cache the home-path in a static QString
1957 // (see QDir::homePath() for more details)
1958 static QString homePath
;
1959 if (homePath
.isEmpty()) {
1960 homePath
= QDir::homePath();
1963 path
= item
.localPath();
1964 if (path
.startsWith(homePath
)) {
1965 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1969 const int index
= path
.lastIndexOf(item
.text());
1970 path
= path
.mid(0, index
- 1);
1971 data
.insert(sharedValue("path"), path
);
1974 if (m_requestRole
[DeletionTimeRole
]) {
1975 QDateTime deletionTime
;
1976 if (item
.url().scheme() == QLatin1String("trash")) {
1977 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1979 data
.insert(sharedValue("deletiontime"), deletionTime
);
1982 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1983 data
.insert(sharedValue("isExpandable"), true);
1986 if (m_requestRole
[ExpandedParentsCountRole
]) {
1988 const int level
= expandedParentsCount(parent
) + 1;
1989 data
.insert(sharedValue("expandedParentsCount"), level
);
1993 if (item
.isMimeTypeKnown()) {
1994 QString iconName
= item
.iconName();
1995 if (!QIcon::hasThemeIcon(iconName
)) {
1996 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1997 iconName
= mimeType
.genericIconName();
2000 data
.insert(sharedValue("iconName"), iconName
);
2002 if (m_requestRole
[TypeRole
]) {
2003 data
.insert(sharedValue("type"), item
.mimeComment());
2005 } else if (m_requestRole
[TypeRole
] && isDir
) {
2006 static const QString folderMimeType
= item
.mimeComment();
2007 data
.insert(sharedValue("type"), folderMimeType
);
2013 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2017 if (a
->parent
!= b
->parent
) {
2018 const int expansionLevelA
= expandedParentsCount(a
);
2019 const int expansionLevelB
= expandedParentsCount(b
);
2021 // If b has a higher expansion level than a, check if a is a parent
2022 // of b, and make sure that both expansion levels are equal otherwise.
2023 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
2024 if (b
->parent
== a
) {
2030 // If a has a higher expansion level than a, check if b is a parent
2031 // of a, and make sure that both expansion levels are equal otherwise.
2032 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
2033 if (a
->parent
== b
) {
2039 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2041 // Compare the last parents of a and b which are different.
2042 while (a
->parent
!= b
->parent
) {
2048 // Show hidden files and folders last
2049 if (m_sortHiddenLast
) {
2050 const bool isHiddenA
= a
->item
.isHidden();
2051 const bool isHiddenB
= b
->item
.isHidden();
2052 if (isHiddenA
&& !isHiddenB
) {
2054 } else if (!isHiddenA
&& isHiddenB
) {
2060 || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& m_sortRole
== SizeRole
)) {
2061 const bool isDirA
= a
->item
.isDir();
2062 const bool isDirB
= b
->item
.isDir();
2063 if (isDirA
&& !isDirB
) {
2065 } else if (!isDirA
&& isDirB
) {
2070 result
= sortRoleCompare(a
, b
, collator
);
2072 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2075 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2077 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2078 return lessThan(a
, b
, m_collator
);
2081 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2082 // Sorting by string can be expensive, in particular if natural sorting is
2083 // enabled. Use all CPU cores to speed up the sorting process.
2084 static const int numberOfThreads
= QThread::idealThreadCount();
2085 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2087 // Sorting by other roles is quite fast. Use only one thread to prevent
2088 // problems caused by non-reentrant comparison functions, see
2089 // https://bugs.kde.org/show_bug.cgi?id=312679
2090 mergeSort(begin
, end
, lambdaLessThan
);
2094 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2096 // This function must never return 0, because that would break stable
2097 // sorting, which leads to all kinds of bugs.
2098 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2099 // If two items have equal sort values, let the fallbacks at the bottom of
2100 // the function handle it.
2101 const KFileItem
&itemA
= a
->item
;
2102 const KFileItem
&itemB
= b
->item
;
2106 switch (m_sortRole
) {
2108 // The name role is handled as default fallback after the switch
2112 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& itemA
.isDir()) {
2113 // folders first then
2114 // items A and B are folders thanks to lessThan checks
2115 auto valueA
= a
->values
.value("count");
2116 auto valueB
= b
->values
.value("count");
2117 if (valueA
.isNull()) {
2118 if (!valueB
.isNull()) {
2121 } else if (valueB
.isNull()) {
2124 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2126 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2133 KIO::filesize_t sizeA
= 0;
2134 if (itemA
.isDir()) {
2135 sizeA
= a
->values
.value("size").toULongLong();
2137 sizeA
= itemA
.size();
2139 KIO::filesize_t sizeB
= 0;
2140 if (itemB
.isDir()) {
2141 sizeB
= b
->values
.value("size").toULongLong();
2143 sizeB
= itemB
.size();
2145 if (sizeA
< sizeB
) {
2147 } else if (sizeA
> sizeB
) {
2153 case ModificationTimeRole
: {
2154 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2155 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2156 if (dateTimeA
< dateTimeB
) {
2158 } else if (dateTimeA
> dateTimeB
) {
2164 case AccessTimeRole
: {
2165 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2166 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2167 if (dateTimeA
< dateTimeB
) {
2169 } else if (dateTimeA
> dateTimeB
) {
2175 case CreationTimeRole
: {
2176 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2177 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2178 if (dateTimeA
< dateTimeB
) {
2180 } else if (dateTimeA
> dateTimeB
) {
2186 case DeletionTimeRole
: {
2187 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2188 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2189 if (dateTimeA
< dateTimeB
) {
2191 } else if (dateTimeA
> dateTimeB
) {
2205 case ReleaseYearRole
: {
2206 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2210 case DimensionsRole
: {
2211 const QByteArray role
= roleForType(m_sortRole
);
2212 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2213 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2215 if (dimensionsA
.width() == dimensionsB
.width()) {
2216 result
= dimensionsA
.height() - dimensionsB
.height();
2218 result
= dimensionsA
.width() - dimensionsB
.width();
2224 const QByteArray role
= roleForType(m_sortRole
);
2225 const QString roleValueA
= a
->values
.value(role
).toString();
2226 const QString roleValueB
= b
->values
.value(role
).toString();
2227 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2229 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2231 } else if (isRoleValueNatural(m_sortRole
)) {
2232 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2234 result
= QString::compare(roleValueA
, roleValueB
);
2241 // The current sort role was sufficient to define an order
2245 // Fallback #1: Compare the text of the items
2246 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2251 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2252 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2257 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2258 // equal. In this case a comparison of the URL is done which is unique in all cases
2259 // within KDirLister.
2260 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2263 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2265 QMutexLocker
collatorLock(s_collatorMutex());
2267 if (m_naturalSorting
) {
2268 // Split extension, taking into account it can be empty
2269 constexpr QString::SectionFlags flags
= QString::SectionSkipEmpty
| QString::SectionIncludeLeadingSep
;
2271 // Sort by baseName first
2272 const QString aBaseName
= a
.section('.', 0, 0, flags
);
2273 const QString bBaseName
= b
.section('.', 0, 0, flags
);
2275 const int res
= collator
.compare(aBaseName
, bBaseName
);
2276 if (res
!= 0 || (aBaseName
.length() == a
.length() && bBaseName
.length() == b
.length())) {
2280 // sliced() has undefined behavior when pos < 0 or pos > size().
2281 Q_ASSERT(aBaseName
.length() <= a
.length() && aBaseName
.length() >= 0);
2282 Q_ASSERT(bBaseName
.length() <= b
.length() && bBaseName
.length() >= 0);
2284 // baseNames were equal, sort by extension
2285 return collator
.compare(a
.sliced(aBaseName
.length()), b
.sliced(bBaseName
.length()));
2288 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2289 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2290 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2291 // comparison, still a deterministic sort order is required. A case sensitive
2292 // comparison is done as fallback.
2296 return QString::compare(a
, b
, Qt::CaseSensitive
);
2299 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2301 Q_ASSERT(!m_itemData
.isEmpty());
2303 const int maxIndex
= count() - 1;
2304 QList
<QPair
<int, QVariant
>> groups
;
2308 for (int i
= 0; i
<= maxIndex
; ++i
) {
2309 if (isChildItem(i
)) {
2313 const QString name
= m_itemData
.at(i
)->item
.text();
2315 // Use the first character of the name as group indication
2316 QChar newFirstChar
= name
.at(0).toUpper();
2317 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2318 newFirstChar
= name
.at(1).toUpper();
2321 if (firstChar
!= newFirstChar
) {
2322 QString newGroupValue
;
2323 if (newFirstChar
.isLetter()) {
2324 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2325 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2327 // Try to find a matching group in the range 'A' to 'Z'.
2328 static std::vector
<QChar
> lettersAtoZ
;
2329 lettersAtoZ
.reserve('Z' - 'A' + 1);
2330 if (lettersAtoZ
.empty()) {
2331 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2332 lettersAtoZ
.push_back(QLatin1Char(c
));
2336 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2337 return m_collator
.compare(c1
, c2
) < 0;
2340 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2341 if (it
!= lettersAtoZ
.end()) {
2342 if (localeAwareLessThan(newFirstChar
, *it
)) {
2343 // newFirstChar belongs to the group preceding *it.
2344 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2347 newGroupValue
= *it
;
2351 // Symbols from non Latin-based scripts
2352 newGroupValue
= newFirstChar
;
2354 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2355 // Apply group '0 - 9' for any name that starts with a digit
2356 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2358 newGroupValue
= i18nc("@title:group", "Others");
2361 if (newGroupValue
!= groupValue
) {
2362 groupValue
= newGroupValue
;
2363 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2366 firstChar
= newFirstChar
;
2372 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2374 Q_ASSERT(!m_itemData
.isEmpty());
2376 const int maxIndex
= count() - 1;
2377 QList
<QPair
<int, QVariant
>> groups
;
2380 for (int i
= 0; i
<= maxIndex
; ++i
) {
2381 if (isChildItem(i
)) {
2385 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2386 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2387 QString newGroupValue
;
2388 if (!item
.isNull() && item
.isDir()) {
2389 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
|| m_sortDirsFirst
) {
2390 newGroupValue
= i18nc("@title:group Size", "Folders");
2392 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2396 if (newGroupValue
.isEmpty()) {
2397 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2398 newGroupValue
= i18nc("@title:group Size", "Small");
2399 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2400 newGroupValue
= i18nc("@title:group Size", "Medium");
2402 newGroupValue
= i18nc("@title:group Size", "Big");
2406 if (newGroupValue
!= groupValue
) {
2407 groupValue
= newGroupValue
;
2408 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2415 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2417 Q_ASSERT(!m_itemData
.isEmpty());
2419 const int maxIndex
= count() - 1;
2420 QList
<QPair
<int, QVariant
>> groups
;
2422 const QDate currentDate
= QDate::currentDate();
2424 QDate previousFileDate
;
2426 for (int i
= 0; i
<= maxIndex
; ++i
) {
2427 if (isChildItem(i
)) {
2431 const QLocale locale
;
2432 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2433 const QDate fileDate
= fileTime
.date();
2434 if (fileDate
== previousFileDate
) {
2435 // The current item is in the same group as the previous item
2438 previousFileDate
= fileDate
;
2440 const int daysDistance
= fileDate
.daysTo(currentDate
);
2442 QString newGroupValue
;
2443 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2444 switch (daysDistance
/ 7) {
2446 switch (daysDistance
) {
2448 newGroupValue
= i18nc("@title:group Date", "Today");
2451 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2454 newGroupValue
= locale
.toString(fileTime
, i18nc("@title:group Date: The week day name: dddd", "dddd"));
2455 newGroupValue
= i18nc(
2456 "Can be used to script translation of \"dddd\""
2457 "with context @title:group Date",
2463 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2466 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2469 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2473 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2479 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2480 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2481 if (daysDistance
== 1) {
2482 const KLocalizedString format
= ki18nc(
2483 "@title:group Date: "
2484 "MMMM is full month name in current locale, and yyyy is "
2485 "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 "
2486 "part of the text that should not be formatted as a date",
2487 "'Yesterday' (MMMM, yyyy)");
2488 const QString translatedFormat
= format
.toString();
2489 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2490 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2491 newGroupValue
= i18nc(
2492 "Can be used to script translation of "
2493 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2497 qCWarning(DolphinDebug
).nospace()
2498 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2499 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2500 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2502 } else if (daysDistance
<= 7) {
2503 newGroupValue
= locale
.toString(fileTime
,
2504 i18nc("@title:group Date: "
2505 "The week day name: dddd, MMMM is full month name "
2506 "in current locale, and yyyy is full year number.",
2507 "dddd (MMMM, yyyy)"));
2508 newGroupValue
= i18nc(
2509 "Can be used to script translation of "
2510 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2513 } else if (daysDistance
<= 7 * 2) {
2514 const KLocalizedString format
= ki18nc(
2515 "@title:group Date: "
2516 "MMMM is full month name in current locale, and yyyy is "
2517 "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 "
2518 "part of the text that should not be formatted as a date",
2519 "'One Week Ago' (MMMM, yyyy)");
2520 const QString translatedFormat
= format
.toString();
2521 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2522 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2523 newGroupValue
= i18nc(
2524 "Can be used to script translation of "
2525 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2529 qCWarning(DolphinDebug
).nospace()
2530 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2531 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2532 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2534 } else if (daysDistance
<= 7 * 3) {
2535 const KLocalizedString format
= ki18nc(
2536 "@title:group Date: "
2537 "MMMM is full month name in current locale, and yyyy is "
2538 "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 "
2539 "part of the text that should not be formatted as a date",
2540 "'Two Weeks Ago' (MMMM, yyyy)");
2541 const QString translatedFormat
= format
.toString();
2542 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2543 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2544 newGroupValue
= i18nc(
2545 "Can be used to script translation of "
2546 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2550 qCWarning(DolphinDebug
).nospace()
2551 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2552 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2553 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2555 } else if (daysDistance
<= 7 * 4) {
2556 const KLocalizedString format
= ki18nc(
2557 "@title:group Date: "
2558 "MMMM is full month name in current locale, and yyyy is "
2559 "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 "
2560 "part of the text that should not be formatted as a date",
2561 "'Three Weeks Ago' (MMMM, yyyy)");
2562 const QString translatedFormat
= format
.toString();
2563 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2564 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2565 newGroupValue
= i18nc(
2566 "Can be used to script translation of "
2567 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2571 qCWarning(DolphinDebug
).nospace()
2572 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2573 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2574 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2577 const KLocalizedString format
= ki18nc(
2578 "@title:group Date: "
2579 "MMMM is full month name in current locale, and yyyy is "
2580 "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 "
2581 "part of the text that should not be formatted as a date",
2582 "'Earlier on' MMMM, yyyy");
2583 const QString translatedFormat
= format
.toString();
2584 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2585 newGroupValue
= locale
.toString(fileTime
, translatedFormat
);
2586 newGroupValue
= i18nc(
2587 "Can be used to script translation of "
2588 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2592 qCWarning(DolphinDebug
).nospace()
2593 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2594 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2595 newGroupValue
= locale
.toString(fileTime
, untranslatedFormat
);
2599 newGroupValue
= locale
.toString(fileTime
,
2600 i18nc("@title:group "
2601 "The month and year: MMMM is full month name in current locale, "
2602 "and yyyy is full year number",
2604 newGroupValue
= i18nc(
2605 "Can be used to script translation of "
2606 "\"MMMM, yyyy\" with context @title:group Date",
2612 if (newGroupValue
!= groupValue
) {
2613 groupValue
= newGroupValue
;
2614 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2621 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2623 Q_ASSERT(!m_itemData
.isEmpty());
2625 const int maxIndex
= count() - 1;
2626 QList
<QPair
<int, QVariant
>> groups
;
2628 QString permissionsString
;
2630 for (int i
= 0; i
<= maxIndex
; ++i
) {
2631 if (isChildItem(i
)) {
2635 const ItemData
*itemData
= m_itemData
.at(i
);
2636 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2637 if (newPermissionsString
== permissionsString
) {
2640 permissionsString
= newPermissionsString
;
2642 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2646 if (info
.permission(QFile::ReadUser
)) {
2647 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2649 if (info
.permission(QFile::WriteUser
)) {
2650 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2652 if (info
.permission(QFile::ExeUser
)) {
2653 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2655 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2659 if (info
.permission(QFile::ReadGroup
)) {
2660 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2662 if (info
.permission(QFile::WriteGroup
)) {
2663 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2665 if (info
.permission(QFile::ExeGroup
)) {
2666 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2668 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2670 // Set others string
2672 if (info
.permission(QFile::ReadOther
)) {
2673 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2675 if (info
.permission(QFile::WriteOther
)) {
2676 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2678 if (info
.permission(QFile::ExeOther
)) {
2679 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2681 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2683 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2684 if (newGroupValue
!= groupValue
) {
2685 groupValue
= newGroupValue
;
2686 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2693 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2695 Q_ASSERT(!m_itemData
.isEmpty());
2697 const int maxIndex
= count() - 1;
2698 QList
<QPair
<int, QVariant
>> groups
;
2700 int groupValue
= -1;
2701 for (int i
= 0; i
<= maxIndex
; ++i
) {
2702 if (isChildItem(i
)) {
2705 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2706 if (newGroupValue
!= groupValue
) {
2707 groupValue
= newGroupValue
;
2708 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2715 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2717 Q_ASSERT(!m_itemData
.isEmpty());
2719 const int maxIndex
= count() - 1;
2720 QList
<QPair
<int, QVariant
>> groups
;
2722 bool isFirstGroupValue
= true;
2724 for (int i
= 0; i
<= maxIndex
; ++i
) {
2725 if (isChildItem(i
)) {
2728 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2729 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2730 groupValue
= newGroupValue
;
2731 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2732 isFirstGroupValue
= false;
2739 void KFileItemModel::emitSortProgress(int resolvedCount
)
2741 // Be tolerant against a resolvedCount with a wrong range.
2742 // Although there should not be a case where KFileItemModelRolesUpdater
2743 // (= caller) provides a wrong range, it is important to emit
2744 // a useful progress information even if there is an unexpected
2745 // implementation issue.
2747 const int itemCount
= count();
2748 if (resolvedCount
>= itemCount
) {
2749 m_sortingProgressPercent
= -1;
2750 if (m_resortAllItemsTimer
->isActive()) {
2751 m_resortAllItemsTimer
->stop();
2755 Q_EMIT
directorySortingProgress(100);
2756 } else if (itemCount
> 0) {
2757 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2759 const int progress
= resolvedCount
* 100 / itemCount
;
2760 if (m_sortingProgressPercent
!= progress
) {
2761 m_sortingProgressPercent
= progress
;
2762 Q_EMIT
directorySortingProgress(progress
);
2767 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2769 static const RoleInfoMap rolesInfoMap
[] = {
2771 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2772 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2773 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2774 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2775 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2776 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2777 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2778 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2779 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2780 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2781 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2782 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2783 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2784 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2785 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2786 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2787 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2788 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2789 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2790 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2791 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2792 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2793 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2794 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2795 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2796 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2797 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2798 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2799 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2800 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2801 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2802 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2803 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2804 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2805 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2806 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2807 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2808 { "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 },
2809 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2810 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2814 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2815 return rolesInfoMap
;
2818 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2820 QElapsedTimer timer
;
2822 for (const KFileItem
&item
: items
) {
2823 // Only determine mime types for files here. For directories,
2824 // KFileItem::determineMimeType() reads the .directory file inside to
2825 // load the icon, but this is not necessary at all if we just need the
2826 // type. Some special code for setting the correct mime type for
2827 // directories is in retrieveData().
2828 if (!item
.isDir()) {
2829 item
.determineMimeType();
2832 if (timer
.elapsed() > timeout
) {
2833 // Don't block the user interface, let the remaining items
2834 // be resolved asynchronously.
2840 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2842 static QSet
<QByteArray
> pool
;
2843 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2845 if (it
!= pool
.constEnd()) {
2853 bool KFileItemModel::isConsistent() const
2855 // m_items may contain less items than m_itemData because m_items
2856 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2857 if (m_items
.count() > m_itemData
.count()) {
2861 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2862 // Check if m_items and m_itemData are consistent.
2863 const KFileItem item
= fileItem(i
);
2864 if (item
.isNull()) {
2865 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2869 const int itemIndex
= index(item
);
2870 if (itemIndex
!= i
) {
2871 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2875 // Check if the items are sorted correctly.
2876 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2877 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2881 // Check if all parent-child relationships are consistent.
2882 const ItemData
*data
= m_itemData
.at(i
);
2883 const ItemData
*parent
= data
->parent
;
2885 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2886 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2890 const int parentIndex
= index(parent
->item
);
2891 if (parentIndex
>= i
) {
2892 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2902 void KFileItemModel::slotListerError(KIO::Job
*job
)
2904 const int jobError
= job
->error();
2905 if (jobError
== KIO::ERR_IS_FILE
) {
2906 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2907 Q_EMIT
urlIsFileError(listJob
->url());
2910 const QString errorString
= job
->errorString();
2911 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."), jobError
);
2915 #include "moc_kfileitemmodel.cpp"