2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_contentdisplaysettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
15 #include "views/draganddrophelper.h"
19 #include <KIO/ListJob>
20 #include <KLocalizedString>
21 #include <KUrlMimeData>
23 #include <QElapsedTimer>
26 #include <QMimeDatabase>
27 #include <QRecursiveMutex>
30 #include <klazylocalizedstring.h>
32 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
34 // #define KFILEITEMMODEL_DEBUG
36 KFileItemModel::KFileItemModel(QObject
*parent
)
37 : KItemModelBase("text", parent
)
38 , m_dirLister(nullptr)
39 , m_sortDirsFirst(true)
40 , m_sortHiddenLast(false)
41 , m_sortRole(NameRole
)
42 , m_sortingProgressPercent(-1)
49 , m_maximumUpdateIntervalTimer(nullptr)
50 , m_resortAllItemsTimer(nullptr)
51 , m_pendingItemsToInsert()
56 m_collator
.setNumericMode(true);
58 loadSortingSettings();
60 m_dirLister
= new KDirLister(this);
61 m_dirLister
->setAutoErrorHandlingEnabled(false);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
70 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
71 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
72 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
73 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
74 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
75 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
76 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
77 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
78 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
79 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
81 // Apply default roles that should be determined
83 m_requestRole
[NameRole
] = true;
84 m_requestRole
[IsDirRole
] = true;
85 m_requestRole
[IsLinkRole
] = true;
86 m_roles
.insert("text");
87 m_roles
.insert("isDir");
88 m_roles
.insert("isLink");
89 m_roles
.insert("isHidden");
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer
= new QTimer(this);
94 m_maximumUpdateIntervalTimer
->setInterval(2000);
95 m_maximumUpdateIntervalTimer
->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer
= new QTimer(this);
103 m_resortAllItemsTimer
->setInterval(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
104 // and sorting too infrequently which leads to users seeing an outdated sort order.
105 m_resortAllItemsTimer
->setSingleShot(true);
106 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
108 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
110 setShowTrashMime(m_dirLister
->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
116 qDeleteAll(m_filteredItems
);
117 qDeleteAll(m_pendingItemsToInsert
);
120 void KFileItemModel::loadDirectory(const QUrl
&url
)
122 m_dirLister
->openUrl(url
);
125 void KFileItemModel::refreshDirectory(const QUrl
&url
)
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
129 while (expandedDirs
.hasNext()) {
131 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
134 m_dirLister
->openUrl(url
, KDirLister::Reload
);
136 Q_EMIT
directoryRefreshing();
139 QUrl
KFileItemModel::directory() const
141 return m_dirLister
->url();
144 void KFileItemModel::cancelDirectoryLoading()
149 int KFileItemModel::count() const
151 return m_itemData
.count();
154 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
156 if (index
>= 0 && index
< count()) {
157 ItemData
*data
= m_itemData
.at(index
);
158 if (data
->values
.isEmpty()) {
159 data
->values
= retrieveData(data
->item
, data
->parent
);
160 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
161 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
162 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
163 // so this special request of different behavior can be identified here.
164 bool hasExpandedParentsCount
= false;
165 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
167 data
->values
= retrieveData(data
->item
, data
->parent
);
168 data
->values
.insert("isExpanded", true);
169 if (hasExpandedParentsCount
) {
170 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
176 return QHash
<QByteArray
, QVariant
>();
179 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
181 if (index
< 0 || index
>= count()) {
185 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
187 // Determine which roles have been changed
188 QSet
<QByteArray
> changedRoles
;
189 QHashIterator
<QByteArray
, QVariant
> it(values
);
190 while (it
.hasNext()) {
192 const QByteArray role
= sharedValue(it
.key());
193 const QVariant value
= it
.value();
195 if (currentValues
[role
] != value
) {
196 currentValues
[role
] = value
;
197 changedRoles
.insert(role
);
201 if (changedRoles
.isEmpty()) {
205 m_itemData
[index
]->values
= currentValues
;
206 if (changedRoles
.contains("text")) {
207 QUrl url
= m_itemData
[index
]->item
.url();
208 url
= url
.adjusted(QUrl::RemoveFilename
);
209 url
.setPath(url
.path() + currentValues
["text"].toString());
210 m_itemData
[index
]->item
.setUrl(url
);
213 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
218 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
220 if (dirsFirst
!= m_sortDirsFirst
) {
221 m_sortDirsFirst
= dirsFirst
;
226 bool KFileItemModel::sortDirectoriesFirst() const
228 return m_sortDirsFirst
;
231 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
233 if (hiddenLast
!= m_sortHiddenLast
) {
234 m_sortHiddenLast
= hiddenLast
;
239 bool KFileItemModel::sortHiddenLast() const
241 return m_sortHiddenLast
;
244 void KFileItemModel::setShowTrashMime(bool showTrashMime
)
246 const auto trashMime
= QStringLiteral("application/x-trash");
247 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
250 excludeFilter
.removeAll(trashMime
);
251 } else if (!excludeFilter
.contains(trashMime
)) {
252 excludeFilter
.append(trashMime
);
255 setExcludeMimeTypeFilter(excludeFilter
);
258 void KFileItemModel::scheduleResortAllItems()
260 if (!m_resortAllItemsTimer
->isActive()) {
261 m_resortAllItemsTimer
->start();
265 void KFileItemModel::setShowHiddenFiles(bool show
)
267 m_dirLister
->setShowHiddenFiles(show
);
268 setShowTrashMime(show
|| !GeneralSettings::hideXTrashFile());
269 m_dirLister
->emitChanges();
271 dispatchPendingItemsToInsert();
275 bool KFileItemModel::showHiddenFiles() const
277 return m_dirLister
->showHiddenFiles();
280 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
282 m_dirLister
->setDirOnlyMode(enabled
);
285 bool KFileItemModel::showDirectoriesOnly() const
287 return m_dirLister
->dirOnlyMode();
290 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
292 QMimeData
*data
= new QMimeData();
294 // The following code has been taken from KDirModel::mimeData()
295 // (kdelibs/kio/kio/kdirmodel.cpp)
296 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
298 QList
<QUrl
> mostLocalUrls
;
299 const ItemData
*lastAddedItem
= nullptr;
301 for (int index
: indexes
) {
302 const ItemData
*itemData
= m_itemData
.at(index
);
303 const ItemData
*parent
= itemData
->parent
;
305 while (parent
&& parent
!= lastAddedItem
) {
306 parent
= parent
->parent
;
309 if (parent
&& parent
== lastAddedItem
) {
310 // A parent of 'itemData' has been added already.
314 lastAddedItem
= itemData
;
315 const KFileItem
&item
= itemData
->item
;
316 if (!item
.isNull()) {
320 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
324 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
328 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
330 startFromIndex
= qMax(0, startFromIndex
);
331 for (int i
= startFromIndex
; i
< count(); ++i
) {
332 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
336 for (int i
= 0; i
< startFromIndex
; ++i
) {
337 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
344 bool KFileItemModel::supportsDropping(int index
) const
350 item
= fileItem(index
);
352 return !item
.isNull() && DragAndDropHelper::supportsDropping(item
);
355 bool KFileItemModel::canEnterOnHover(int index
) const
361 item
= fileItem(index
);
363 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
366 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
368 static QHash
<QByteArray
, QString
> description
;
369 if (description
.isEmpty()) {
371 const RoleInfoMap
*map
= rolesInfoMap(count
);
372 for (int i
= 0; i
< count
; ++i
) {
373 if (map
[i
].roleTranslation
.isEmpty()) {
376 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
380 return description
.value(role
);
383 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
385 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
386 #ifdef KFILEITEMMODEL_DEBUG
390 switch (typeForRole(sortRole())) {
392 m_groups
= nameRoleGroups();
395 m_groups
= sizeRoleGroups();
397 case ModificationTimeRole
:
398 m_groups
= timeRoleGroups([](const ItemData
*item
) {
399 return item
->item
.time(KFileItem::ModificationTime
);
402 case CreationTimeRole
:
403 m_groups
= timeRoleGroups([](const ItemData
*item
) {
404 return item
->item
.time(KFileItem::CreationTime
);
408 m_groups
= timeRoleGroups([](const ItemData
*item
) {
409 return item
->item
.time(KFileItem::AccessTime
);
412 case DeletionTimeRole
:
413 m_groups
= timeRoleGroups([](const ItemData
*item
) {
414 return item
->values
.value("deletiontime").toDateTime();
417 case PermissionsRole
:
418 m_groups
= permissionRoleGroups();
421 m_groups
= ratingRoleGroups();
424 m_groups
= genericStringRoleGroups(sortRole());
428 #ifdef KFILEITEMMODEL_DEBUG
429 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
436 KFileItem
KFileItemModel::fileItem(int index
) const
438 if (index
>= 0 && index
< count()) {
439 return m_itemData
.at(index
)->item
;
445 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
447 const int indexForUrl
= index(url
);
448 if (indexForUrl
>= 0) {
449 return m_itemData
.at(indexForUrl
)->item
;
454 int KFileItemModel::index(const KFileItem
&item
) const
456 return index(item
.url());
459 int KFileItemModel::index(const QUrl
&url
) const
461 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
463 const int itemCount
= m_itemData
.count();
464 int itemsInHash
= m_items
.count();
466 int index
= m_items
.value(urlToFind
, -1);
467 while (index
< 0 && itemsInHash
< itemCount
) {
468 // Not all URLs are stored yet in m_items. We grow m_items until either
469 // urlToFind is found, or all URLs have been stored in m_items.
470 // Note that we do not add the URLs to m_items one by one, but in
471 // larger blocks. After each block, we check if urlToFind is in
472 // m_items. We could in principle compare urlToFind with each URL while
473 // we are going through m_itemData, but comparing two QUrls will,
474 // unlike calling qHash for the URLs, trigger a parsing of the URLs
475 // which costs both CPU cycles and memory.
476 const int blockSize
= 1000;
477 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
478 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
479 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
480 m_items
.insert(nextUrl
, i
);
483 itemsInHash
= currentBlockEnd
;
484 index
= m_items
.value(urlToFind
, -1);
488 // The item could not be found, even though all items from m_itemData
489 // should be in m_items now. We print some diagnostic information which
490 // might help to find the cause of the problem, but only once. This
491 // prevents that obtaining and printing the debugging information
492 // wastes CPU cycles and floods the shell or .xsession-errors.
493 static bool printDebugInfo
= true;
495 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
496 printDebugInfo
= false;
498 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
499 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
500 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
502 // Check if there are multiple items with the same URL.
503 QMultiHash
<QUrl
, int> indexesForUrl
;
504 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
505 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
508 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
509 for (const QUrl
&url
: uniqueKeys
) {
510 if (indexesForUrl
.count(url
) > 1) {
511 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
513 auto it
= indexesForUrl
.find(url
);
514 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
515 const ItemData
*data
= m_itemData
.at(it
.value());
516 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
518 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
530 KFileItem
KFileItemModel::rootItem() const
532 return m_dirLister
->rootItem();
535 void KFileItemModel::clear()
540 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
542 if (m_roles
== roles
) {
546 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
550 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
551 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
552 if (supportedExpanding
&& !willSupportExpanding
) {
553 // No expanding is supported anymore. Take care to delete all items that have an expansion level
554 // that is not 0 (and hence are part of an expanded item).
555 removeExpandedItems();
562 QSetIterator
<QByteArray
> it(roles
);
563 while (it
.hasNext()) {
564 const QByteArray
&role
= it
.next();
565 m_requestRole
[typeForRole(role
)] = true;
569 // Update m_data with the changed requested roles
570 const int maxIndex
= count() - 1;
571 for (int i
= 0; i
<= maxIndex
; ++i
) {
572 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
575 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
578 // Clear the 'values' of all filtered items. They will be re-populated with the
579 // correct roles the next time 'values' will be accessed via data(int).
580 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
581 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
582 while (filteredIt
!= filteredEnd
) {
583 (*filteredIt
)->values
.clear();
588 QSet
<QByteArray
> KFileItemModel::roles() const
593 bool KFileItemModel::setExpanded(int index
, bool expanded
)
595 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
599 QHash
<QByteArray
, QVariant
> values
;
600 values
.insert(sharedValue("isExpanded"), expanded
);
601 if (!setData(index
, values
)) {
605 const KFileItem item
= m_itemData
.at(index
)->item
;
606 const QUrl url
= item
.url();
607 const QUrl targetUrl
= item
.targetUrl();
609 m_expandedDirs
.insert(targetUrl
, url
);
610 m_dirLister
->openUrl(url
, KDirLister::Keep
);
612 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
613 for (const QVariant
&var
: previouslyExpandedChildren
) {
614 m_urlsToExpand
.insert(var
.toUrl());
617 // Note that there might be (indirect) children of the folder which is to be collapsed in
618 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
619 // possibly without a parent, which might result in a crash, we insert all pending items
620 // right now. All new items which would be without a parent will then be removed.
621 dispatchPendingItemsToInsert();
623 // Check if the index of the collapsed folder has changed. If that is the case, then items
624 // were inserted before the collapsed folder, and its index needs to be updated.
625 if (m_itemData
.at(index
)->item
!= item
) {
626 index
= this->index(item
);
629 m_expandedDirs
.remove(targetUrl
);
630 m_dirLister
->stop(url
);
631 m_dirLister
->forgetDirs(url
);
633 const int parentLevel
= expandedParentsCount(index
);
634 const int itemCount
= m_itemData
.count();
635 const int firstChildIndex
= index
+ 1;
637 QVariantList expandedChildren
;
639 int childIndex
= firstChildIndex
;
640 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
641 ItemData
*itemData
= m_itemData
.at(childIndex
);
642 if (itemData
->values
.value("isExpanded").toBool()) {
643 const QUrl targetUrl
= itemData
->item
.targetUrl();
644 const QUrl url
= itemData
->item
.url();
645 m_expandedDirs
.remove(targetUrl
);
646 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
647 m_dirLister
->forgetDirs(url
);
648 expandedChildren
.append(targetUrl
);
652 const int childrenCount
= childIndex
- firstChildIndex
;
654 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
655 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
657 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
663 bool KFileItemModel::isExpanded(int index
) const
665 if (index
>= 0 && index
< count()) {
666 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
671 bool KFileItemModel::isExpandable(int index
) const
673 if (index
>= 0 && index
< count()) {
674 // Call data (instead of accessing m_itemData directly)
675 // to ensure that the value is initialized.
676 return data(index
).value("isExpandable").toBool();
681 int KFileItemModel::expandedParentsCount(int index
) const
683 if (index
>= 0 && index
< count()) {
684 return expandedParentsCount(m_itemData
.at(index
));
689 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
692 const auto dirs
= m_expandedDirs
;
693 for (const auto &dir
: dirs
) {
699 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
701 m_urlsToExpand
= urls
;
704 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
706 // Assure that each sub-path of the URL that should be
707 // expanded is added to m_urlsToExpand. KDirLister
708 // does not care whether the parent-URL has already been
710 QUrl urlToExpand
= m_dirLister
->url();
711 const int pos
= urlToExpand
.path().length();
713 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
714 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
715 // so using QString::SkipEmptyParts
716 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
717 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
718 QString path
= urlToExpand
.path();
719 if (!path
.endsWith(QLatin1Char('/'))) {
720 path
.append(QLatin1Char('/'));
722 urlToExpand
.setPath(path
+ subDirs
.at(i
));
723 m_urlsToExpand
.insert(urlToExpand
);
726 // KDirLister::open() must called at least once to trigger an initial
727 // loading. The pending URLs that must be restored are handled
728 // in slotCompleted().
729 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
730 while (it2
.hasNext()) {
731 const int idx
= index(it2
.next());
732 if (idx
>= 0 && !isExpanded(idx
)) {
733 setExpanded(idx
, true);
739 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
741 if (m_filter
.pattern() != nameFilter
) {
742 dispatchPendingItemsToInsert();
743 m_filter
.setPattern(nameFilter
);
748 QString
KFileItemModel::nameFilter() const
750 return m_filter
.pattern();
753 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
755 if (m_filter
.mimeTypes() != filters
) {
756 dispatchPendingItemsToInsert();
757 m_filter
.setMimeTypes(filters
);
762 QStringList
KFileItemModel::mimeTypeFilters() const
764 return m_filter
.mimeTypes();
767 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
769 if (m_filter
.excludeMimeTypes() != filters
) {
770 dispatchPendingItemsToInsert();
771 m_filter
.setExcludeMimeTypes(filters
);
776 QStringList
KFileItemModel::excludeMimeTypeFilter() const
778 return m_filter
.excludeMimeTypes();
781 void KFileItemModel::applyFilters()
784 // Check which previously shown items from m_itemData must now get
785 // hidden and hence moved from m_itemData into m_filteredItems.
787 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
789 // This pointer will refer to the next confirmed shown item from the point of
790 // view of the current "itemData" in the upcoming "for" loop.
791 ItemData
*itemShownBelow
= nullptr;
793 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
794 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
795 ItemData
*itemData
= m_itemData
.at(index
);
797 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
798 // We could've entered here for two reasons:
799 // 1. This item passes the filter itself
800 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
802 // So this item must remain shown.
803 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
804 itemShownBelow
= itemData
;
806 // We hide this item for now, however, for expanded folders this is not final:
807 // 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
808 newFilteredIndexes
.prepend(index
);
809 m_filteredItems
.insert(itemData
->item
, itemData
);
810 // indexShownBelow doesn't get updated since this item will be hidden
814 // This will remove the newly filtered items from m_itemData
815 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
818 // Check which hidden items from m_filteredItems should
819 // become visible again and hence moved from m_filteredItems back into m_itemData.
821 QList
<ItemData
*> newVisibleItems
;
823 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
825 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
826 while (it
!= m_filteredItems
.end()) {
827 if (m_filter
.matches(it
.key())) {
828 newVisibleItems
.append(it
.value());
830 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
831 // We will go up through its parental chain until we either:
832 // 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
833 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
834 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
835 parent
= parent
->parent
) {
836 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
837 // and it would mess up the iteration. We will mark it to be removed in step 3.
838 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
841 it
= m_filteredItems
.erase(it
);
843 // Item remains filtered for now
844 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
850 // Handles the ancestorsOfNewVisibleItems.
851 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
852 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
853 if (m_filteredItems
.remove(it
.key())) {
854 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
855 newVisibleItems
.append(it
.value());
859 // This will insert the newly discovered unfiltered items into m_itemData
860 insertItems(newVisibleItems
);
863 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
865 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
866 // There are either no filtered items, or it is not possible to expand
867 // folders -> there cannot be any filtered children.
871 QSet
<ItemData
*> parents
;
872 for (const KItemRange
&range
: itemRanges
) {
873 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
874 parents
.insert(m_itemData
.at(index
));
878 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
879 while (it
!= m_filteredItems
.end()) {
880 if (parents
.contains(it
.value()->parent
)) {
882 it
= m_filteredItems
.erase(it
);
889 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
891 static QList
<RoleInfo
> rolesInfo
;
892 if (rolesInfo
.isEmpty()) {
894 const RoleInfoMap
*map
= rolesInfoMap(count
);
895 for (int i
= 0; i
< count
; ++i
) {
896 if (map
[i
].roleType
!= NoRole
) {
898 info
.role
= map
[i
].role
;
899 info
.translation
= map
[i
].roleTranslation
.toString();
900 if (!map
[i
].groupTranslation
.isEmpty()) {
901 info
.group
= map
[i
].groupTranslation
.toString();
903 // For top level roles, groupTranslation is 0. We must make sure that
904 // info.group is an empty string then because the code that generates
905 // menus tries to put the actions into sub menus otherwise.
906 info
.group
= QString();
908 info
.requiresBaloo
= map
[i
].requiresBaloo
;
909 info
.requiresIndexer
= map
[i
].requiresIndexer
;
910 if (!map
[i
].tooltipTranslation
.isEmpty()) {
911 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
913 info
.tooltip
= QString();
915 rolesInfo
.append(info
);
923 void KFileItemModel::onGroupedSortingChanged(bool current
)
929 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
932 m_sortRole
= typeForRole(current
);
934 if (!m_requestRole
[m_sortRole
]) {
935 QSet
<QByteArray
> newRoles
= m_roles
;
945 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
952 void KFileItemModel::loadSortingSettings()
954 using Choice
= GeneralSettings::EnumSortingChoice
;
955 switch (GeneralSettings::sortingChoice()) {
956 case Choice::NaturalSorting
:
957 m_naturalSorting
= true;
958 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
960 case Choice::CaseSensitiveSorting
:
961 m_naturalSorting
= false;
962 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
964 case Choice::CaseInsensitiveSorting
:
965 m_naturalSorting
= false;
966 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
971 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
972 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
973 m_collator
.compare(QString(), QString());
976 void KFileItemModel::resortAllItems()
978 m_resortAllItemsTimer
->stop();
980 const int itemCount
= count();
981 if (itemCount
<= 0) {
985 #ifdef KFILEITEMMODEL_DEBUG
988 qCDebug(DolphinDebug
) << "===========================================================";
989 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
992 // Remember the order of the current URLs so
993 // that it can be determined which indexes have
994 // been moved because of the resorting.
996 oldUrls
.reserve(itemCount
);
997 for (const ItemData
*itemData
: std::as_const(m_itemData
)) {
998 oldUrls
.append(itemData
->item
.url());
1002 m_items
.reserve(itemCount
);
1005 sort(m_itemData
.begin(), m_itemData
.end());
1006 for (int i
= 0; i
< itemCount
; ++i
) {
1007 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1010 // Determine the first index that has been moved.
1011 int firstMovedIndex
= 0;
1012 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1016 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1017 if (itemsHaveMoved
) {
1020 int lastMovedIndex
= itemCount
- 1;
1021 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1025 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1027 // Create a list movedToIndexes, which has the property that
1028 // movedToIndexes[i] is the new index of the item with the old index
1029 // firstMovedIndex + i.
1030 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1031 QList
<int> movedToIndexes
;
1032 movedToIndexes
.reserve(movedItemsCount
);
1033 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1034 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1035 movedToIndexes
.append(newIndex
);
1038 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1039 } else if (groupedSorting()) {
1040 // The groups might have changed even if the order of the items has not.
1041 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1043 if (groups() != oldGroups
) {
1044 Q_EMIT
groupsChanged();
1048 #ifdef KFILEITEMMODEL_DEBUG
1049 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1053 void KFileItemModel::slotCompleted()
1055 m_maximumUpdateIntervalTimer
->stop();
1056 dispatchPendingItemsToInsert();
1058 if (!m_urlsToExpand
.isEmpty()) {
1059 // Try to find a URL that can be expanded.
1060 // Note that the parent folder must be expanded before any of its subfolders become visible.
1061 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1062 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1063 // Iterate over a const copy because items are deleted and inserted within the loop
1064 const auto urlsToExpand
= m_urlsToExpand
;
1065 for (const QUrl
&url
: urlsToExpand
) {
1066 const int indexForUrl
= index(url
);
1067 if (indexForUrl
>= 0) {
1068 m_urlsToExpand
.remove(url
);
1069 if (setExpanded(indexForUrl
, true)) {
1070 // The dir lister has been triggered. This slot will be called
1071 // again after the directory has been expanded.
1077 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1078 // if these URLs have been deleted in the meantime.
1079 m_urlsToExpand
.clear();
1082 Q_EMIT
directoryLoadingCompleted();
1085 void KFileItemModel::slotCanceled()
1087 m_maximumUpdateIntervalTimer
->stop();
1088 dispatchPendingItemsToInsert();
1090 Q_EMIT
directoryLoadingCanceled();
1093 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1095 Q_ASSERT(!items
.isEmpty());
1097 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1099 if (m_requestRole
[ExpandedParentsCountRole
]) {
1100 // If the expanding of items is enabled, the call
1101 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1102 // might result in emitting the same items twice due to the Keep-parameter.
1103 // This case happens if an item gets expanded, collapsed and expanded again
1104 // before the items could be loaded for the first expansion.
1105 if (index(items
.first().url()) >= 0) {
1106 // The items are already part of the model.
1110 if (directoryUrl
!= directory()) {
1111 // To be able to compare whether the new items may be inserted as children
1112 // of a parent item the pending items must be added to the model first.
1113 dispatchPendingItemsToInsert();
1116 // KDirLister keeps the children of items that got expanded once even if
1117 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1118 // checked whether the parent for new items is still expanded.
1119 const int parentIndex
= index(parentUrl
);
1120 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1121 // The parent is not expanded.
1126 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1128 if (!m_filter
.hasSetFilters()) {
1129 m_pendingItemsToInsert
.append(itemDataList
);
1131 QSet
<ItemData
*> parentsToEnsureVisible
;
1133 // The name or type filter is active. Hide filtered items
1134 // before inserting them into the model and remember
1135 // the filtered items in m_filteredItems.
1136 for (ItemData
*itemData
: itemDataList
) {
1137 if (m_filter
.matches(itemData
->item
)) {
1138 m_pendingItemsToInsert
.append(itemData
);
1139 if (itemData
->parent
) {
1140 parentsToEnsureVisible
.insert(itemData
->parent
);
1143 m_filteredItems
.insert(itemData
->item
, itemData
);
1147 // Entire parental chains must be shown
1148 for (ItemData
*parent
: parentsToEnsureVisible
) {
1149 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1150 m_pendingItemsToInsert
.append(parent
);
1155 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1156 // Assure that items get dispatched if no completed() or canceled() signal is
1157 // emitted during the maximum update interval.
1158 m_maximumUpdateIntervalTimer
->start();
1161 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1164 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1166 int filteredParentsCount
= 0;
1167 // The childless parents not yet removed will always be right above the start of a removed range.
1168 // We iterate backwards to ensure the deepest folders are processed before their parents
1169 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1170 KItemRange itemRange
= removedItemRanges
.at(i
);
1171 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1172 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1173 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1175 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1176 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1177 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1178 // and this deleted range covers all of its descendents, so none will be left.
1179 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1180 // This range's starting index will be extended to include the parent above:
1183 ++filteredParentsCount
;
1184 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1185 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1186 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1187 previousRange
.count
+= itemRange
.count
;
1188 removedItemRanges
.replace(i
- 1, previousRange
);
1189 removedItemRanges
.removeAt(i
);
1191 removedItemRanges
.replace(i
, itemRange
);
1192 // We must revisit this range in the next iteration since its starting index changed
1197 return filteredParentsCount
;
1200 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1202 dispatchPendingItemsToInsert();
1204 QVector
<int> indexesToRemove
;
1205 indexesToRemove
.reserve(items
.count());
1206 KFileItemList dirsChanged
;
1208 const auto currentDir
= directory();
1210 for (const KFileItem
&item
: items
) {
1211 if (item
.url() == currentDir
) {
1212 Q_EMIT
currentDirectoryRemoved();
1216 const int indexForItem
= index(item
);
1217 if (indexForItem
>= 0) {
1218 indexesToRemove
.append(indexForItem
);
1220 // Probably the item has been filtered.
1221 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1222 if (it
!= m_filteredItems
.end()) {
1224 m_filteredItems
.erase(it
);
1228 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1229 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1230 dirsChanged
<< KFileItem(parentUrl
);
1234 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1236 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1237 // Assure that removing a parent item also results in removing all children
1238 QVector
<int> indexesToRemoveWithChildren
;
1239 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1241 const int itemCount
= m_itemData
.count();
1242 for (int index
: std::as_const(indexesToRemove
)) {
1243 indexesToRemoveWithChildren
.append(index
);
1245 const int parentLevel
= expandedParentsCount(index
);
1246 int childIndex
= index
+ 1;
1247 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1248 indexesToRemoveWithChildren
.append(childIndex
);
1253 indexesToRemove
= indexesToRemoveWithChildren
;
1256 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1257 removeFilteredChildren(itemRanges
);
1259 // This call will update itemRanges to include the childless parents that have been filtered.
1260 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1262 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1263 // mixed with expanded folders that are just being filtered out.
1264 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1265 // so removeItems() will check m_filteredItems to differentiate which is which.
1266 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1268 Q_EMIT
fileItemsChanged(dirsChanged
);
1271 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1273 Q_ASSERT(!items
.isEmpty());
1274 #ifdef KFILEITEMMODEL_DEBUG
1275 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1278 // Get the indexes of all items that have been refreshed
1280 indexes
.reserve(items
.count());
1282 QSet
<QByteArray
> changedRoles
;
1283 KFileItemList changedFiles
;
1285 // Contains the indexes of the currently visible items
1286 // that should get hidden and hence moved to m_filteredItems.
1287 QVector
<int> newFilteredIndexes
;
1289 // Contains currently hidden items that should
1290 // get visible and hence removed from m_filteredItems
1291 QList
<ItemData
*> newVisibleItems
;
1293 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1295 while (it
.hasNext()) {
1296 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1297 const KFileItem
&oldItem
= itemPair
.first
;
1298 const KFileItem
&newItem
= itemPair
.second
;
1299 const int indexForItem
= index(oldItem
);
1300 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1301 if (indexForItem
>= 0) {
1302 m_itemData
[indexForItem
]->item
= newItem
;
1304 // Keep old values as long as possible if they could not retrieved synchronously yet.
1305 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1306 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1307 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1308 while (it
.hasNext()) {
1310 const QByteArray
&role
= it
.key();
1311 if (itemData
->values
.value(role
) != it
.value()) {
1312 itemData
->values
.insert(role
, it
.value());
1313 changedRoles
.insert(role
);
1317 m_items
.remove(oldItem
.url());
1318 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1319 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1320 m_items
.insert(newItem
.url(), indexForItem
);
1321 if (newItemMatchesFilter
1322 || (itemData
->values
.value("isExpanded").toBool()
1323 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1324 // We are lenient with expanded folders that originally had visible children.
1325 // If they become childless now they will be caught by filterChildlessParents()
1326 changedFiles
.append(newItem
);
1327 indexes
.append(indexForItem
);
1329 newFilteredIndexes
.append(indexForItem
);
1330 m_filteredItems
.insert(newItem
, itemData
);
1333 // Check if 'oldItem' is one of the filtered items.
1334 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1335 if (it
!= m_filteredItems
.end()) {
1336 ItemData
*const itemData
= it
.value();
1337 itemData
->item
= newItem
;
1339 // The data stored in 'values' might have changed. Therefore, we clear
1340 // 'values' and re-populate it the next time it is requested via data(int).
1341 // Before clearing, we must remember if it was expanded and the expanded parents count,
1342 // otherwise these states would be lost. The data() method will deal with this special case.
1343 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1344 bool hasExpandedParentsCount
= false;
1345 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1346 itemData
->values
.clear();
1348 itemData
->values
.insert("isExpanded", true);
1349 if (hasExpandedParentsCount
) {
1350 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1354 m_filteredItems
.erase(it
);
1355 if (newItemMatchesFilter
) {
1356 newVisibleItems
.append(itemData
);
1358 m_filteredItems
.insert(newItem
, itemData
);
1364 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1366 // We must keep track of parents of new visible items since they must be shown no matter what
1367 // They will be considered "immune" to filterChildlessParents()
1368 QSet
<ItemData
*> parentsToEnsureVisible
;
1370 for (ItemData
*item
: newVisibleItems
) {
1371 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1372 parentsToEnsureVisible
.insert(parent
);
1375 for (ItemData
*parent
: parentsToEnsureVisible
) {
1376 // We make sure they are all unfiltered.
1377 if (m_filteredItems
.remove(parent
->item
)) {
1378 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1379 newVisibleItems
.append(parent
);
1380 // It could be in newFilteredIndexes, we must remove it if it's there:
1381 const int parentIndex
= index(parent
->item
);
1382 if (parentIndex
>= 0) {
1383 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1384 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1385 newFilteredIndexes
.erase(it
);
1391 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1393 // This call will update itemRanges to include the childless parents that have been filtered.
1394 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1396 removeItems(removedRanges
, KeepItemData
);
1398 // Show previously hidden items that should get visible
1399 insertItems(newVisibleItems
);
1401 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1403 // If the changed items have been created recently, they might not be in m_items yet.
1404 // In that case, the list 'indexes' might be empty.
1405 if (indexes
.isEmpty()) {
1409 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1410 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1412 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1413 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1414 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1415 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1420 std::sort(indexes
.begin(), indexes
.end());
1423 // Extract the item-ranges out of the changed indexes
1424 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1425 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1427 Q_EMIT
fileItemsChanged(changedFiles
);
1430 void KFileItemModel::slotClear()
1432 #ifdef KFILEITEMMODEL_DEBUG
1433 qCDebug(DolphinDebug
) << "Clearing all items";
1436 qDeleteAll(m_filteredItems
);
1437 m_filteredItems
.clear();
1440 m_maximumUpdateIntervalTimer
->stop();
1441 m_resortAllItemsTimer
->stop();
1443 qDeleteAll(m_pendingItemsToInsert
);
1444 m_pendingItemsToInsert
.clear();
1446 const int removedCount
= m_itemData
.count();
1447 if (removedCount
> 0) {
1448 qDeleteAll(m_itemData
);
1451 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1454 m_expandedDirs
.clear();
1457 void KFileItemModel::slotSortingChoiceChanged()
1459 loadSortingSettings();
1463 void KFileItemModel::dispatchPendingItemsToInsert()
1465 if (!m_pendingItemsToInsert
.isEmpty()) {
1466 insertItems(m_pendingItemsToInsert
);
1467 m_pendingItemsToInsert
.clear();
1471 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1473 if (newItems
.isEmpty()) {
1477 #ifdef KFILEITEMMODEL_DEBUG
1478 QElapsedTimer timer
;
1480 qCDebug(DolphinDebug
) << "===========================================================";
1481 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1485 prepareItemsForSorting(newItems
);
1487 // Natural sorting of items can be very slow. However, it becomes much faster
1488 // if the input sequence is already mostly sorted. Therefore, we first sort
1489 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1490 if (m_naturalSorting
) {
1491 if (m_sortRole
== NameRole
) {
1492 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1493 } else if (isRoleValueNatural(m_sortRole
)) {
1494 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1495 const QByteArray role
= roleForType(m_sortRole
);
1496 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1498 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1502 sort(newItems
.begin(), newItems
.end());
1504 #ifdef KFILEITEMMODEL_DEBUG
1505 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1508 KItemRangeList itemRanges
;
1509 const int existingItemCount
= m_itemData
.count();
1510 const int newItemCount
= newItems
.count();
1511 const int totalItemCount
= existingItemCount
+ newItemCount
;
1513 if (existingItemCount
== 0) {
1514 // Optimization for the common special case that there are no
1515 // items in the model yet. Happens, e.g., when entering a folder.
1516 m_itemData
= newItems
;
1517 itemRanges
<< KItemRange(0, newItemCount
);
1519 m_itemData
.reserve(totalItemCount
);
1520 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1521 m_itemData
.append(nullptr);
1524 // We build the new list m_itemData in reverse order to minimize
1525 // the number of moves and guarantee O(N) complexity.
1526 int targetIndex
= totalItemCount
- 1;
1527 int sourceIndexExistingItems
= existingItemCount
- 1;
1528 int sourceIndexNewItems
= newItemCount
- 1;
1532 while (sourceIndexNewItems
>= 0) {
1533 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1534 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1535 // Move an existing item to its new position. If any new items
1536 // are behind it, push the item range to itemRanges.
1537 if (rangeCount
> 0) {
1538 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1542 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1543 --sourceIndexExistingItems
;
1545 // Insert a new item into the list.
1547 m_itemData
[targetIndex
] = newItem
;
1548 --sourceIndexNewItems
;
1553 // Push the final item range to itemRanges.
1554 if (rangeCount
> 0) {
1555 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1558 // Note that itemRanges is still sorted in reverse order.
1559 std::reverse(itemRanges
.begin(), itemRanges
.end());
1562 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1563 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1566 Q_EMIT
itemsInserted(itemRanges
);
1568 #ifdef KFILEITEMMODEL_DEBUG
1569 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1573 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1575 if (itemRanges
.isEmpty()) {
1581 // Step 1: Remove the items from m_itemData, and free the ItemData.
1582 int removedItemsCount
= 0;
1583 for (const KItemRange
&range
: itemRanges
) {
1584 removedItemsCount
+= range
.count
;
1586 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1587 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1588 delete m_itemData
.at(index
);
1591 m_itemData
[index
] = nullptr;
1595 // Step 2: Remove the ItemData pointers from the list m_itemData.
1596 int target
= itemRanges
.at(0).index
;
1597 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1600 const int oldItemDataCount
= m_itemData
.count();
1601 while (source
< oldItemDataCount
) {
1602 m_itemData
[target
] = m_itemData
[source
];
1606 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1607 // Skip the items in the next removed range.
1608 source
+= itemRanges
.at(nextRange
).count
;
1613 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1615 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1616 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1619 Q_EMIT
itemsRemoved(itemRanges
);
1622 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1624 if (m_sortRole
== TypeRole
) {
1625 // Try to resolve the MIME-types synchronously to prevent a reordering of
1626 // the items when sorting by type (per default MIME-types are resolved
1627 // asynchronously by KFileItemModelRolesUpdater).
1628 determineMimeTypes(items
, 200);
1631 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1632 const int parentIndex
= index(parentUrl
);
1633 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1635 QList
<ItemData
*> itemDataList
;
1636 itemDataList
.reserve(items
.count());
1638 for (const KFileItem
&item
: items
) {
1639 ItemData
*itemData
= new ItemData();
1640 itemData
->item
= item
;
1641 itemData
->parent
= parentItem
;
1642 itemDataList
.append(itemData
);
1645 return itemDataList
;
1648 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1650 switch (m_sortRole
) {
1652 case PermissionsRole
:
1655 case DestinationRole
:
1657 case DeletionTimeRole
:
1658 // These roles can be determined with retrieveData, and they have to be stored
1659 // in the QHash "values" for the sorting.
1660 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1661 if (itemData
->values
.isEmpty()) {
1662 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1668 // At least store the data including the file type for items with known MIME type.
1669 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1670 if (itemData
->values
.isEmpty()) {
1671 const KFileItem item
= itemData
->item
;
1672 if (item
.isDir() || item
.isMimeTypeKnown()) {
1673 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1680 // The other roles are either resolved by KFileItemModelRolesUpdater
1681 // (this includes the SizeRole for directories), or they do not need
1682 // to be stored in the QHash "values" for sorting because the data can
1683 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1689 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1691 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1692 // if the corresponding item is expanded, and it is not a top-level item.
1693 const ItemData
*parent
= data
->parent
;
1695 if (parent
->parent
) {
1696 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1697 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1706 void KFileItemModel::removeExpandedItems()
1708 QVector
<int> indexesToRemove
;
1710 const int maxIndex
= m_itemData
.count() - 1;
1711 for (int i
= 0; i
<= maxIndex
; ++i
) {
1712 const ItemData
*itemData
= m_itemData
.at(i
);
1713 if (itemData
->parent
) {
1714 indexesToRemove
.append(i
);
1718 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1719 m_expandedDirs
.clear();
1721 // Also remove all filtered items which have a parent.
1722 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1723 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1726 if (it
.value()->parent
) {
1728 it
= m_filteredItems
.erase(it
);
1735 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1737 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1739 // Trigger a resorting if necessary. Note that this can happen even if the sort
1740 // role has not changed at all because the file name can be used as a fallback.
1741 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))
1742 || (changedRoles
.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1743 for (const KItemRange
&range
: itemRanges
) {
1744 bool needsResorting
= false;
1746 const int first
= range
.index
;
1747 const int last
= range
.index
+ range
.count
- 1;
1749 // Resorting the model is necessary if
1750 // (a) The first item in the range is "lessThan" its predecessor,
1751 // (b) the successor of the last item is "lessThan" the last item, or
1752 // (c) the internal order of the items in the range is incorrect.
1753 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1754 needsResorting
= true;
1755 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1756 needsResorting
= true;
1758 for (int index
= first
; index
< last
; ++index
) {
1759 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1760 needsResorting
= true;
1766 if (needsResorting
) {
1767 scheduleResortAllItems();
1773 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1774 // The position is still correct, but the groups might have changed
1775 // if the changed item is either the first or the last item in a
1777 // In principle, we could try to find out if the item really is the
1778 // first or last one in its group and then update the groups
1779 // (possibly with a delayed timer to make sure that we don't
1780 // re-calculate the groups very often if items are updated one by
1781 // one), but starting m_resortAllItemsTimer is easier.
1782 m_resortAllItemsTimer
->start();
1786 void KFileItemModel::resetRoles()
1788 for (int i
= 0; i
< RolesCount
; ++i
) {
1789 m_requestRole
[i
] = false;
1793 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1795 static QHash
<QByteArray
, RoleType
> roles
;
1796 if (roles
.isEmpty()) {
1797 // Insert user visible roles that can be accessed with
1798 // KFileItemModel::roleInformation()
1800 const RoleInfoMap
*map
= rolesInfoMap(count
);
1801 for (int i
= 0; i
< count
; ++i
) {
1802 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1805 // Insert internal roles (take care to synchronize the implementation
1806 // with KFileItemModel::roleForType() in case if a change is done).
1807 roles
.insert("isDir", IsDirRole
);
1808 roles
.insert("isLink", IsLinkRole
);
1809 roles
.insert("isHidden", IsHiddenRole
);
1810 roles
.insert("isExpanded", IsExpandedRole
);
1811 roles
.insert("isExpandable", IsExpandableRole
);
1812 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1814 Q_ASSERT(roles
.count() == RolesCount
);
1817 return roles
.value(role
, NoRole
);
1820 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1822 static QHash
<RoleType
, QByteArray
> roles
;
1823 if (roles
.isEmpty()) {
1824 // Insert user visible roles that can be accessed with
1825 // KFileItemModel::roleInformation()
1827 const RoleInfoMap
*map
= rolesInfoMap(count
);
1828 for (int i
= 0; i
< count
; ++i
) {
1829 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1832 // Insert internal roles (take care to synchronize the implementation
1833 // with KFileItemModel::typeForRole() in case if a change is done).
1834 roles
.insert(IsDirRole
, "isDir");
1835 roles
.insert(IsLinkRole
, "isLink");
1836 roles
.insert(IsHiddenRole
, "isHidden");
1837 roles
.insert(IsExpandedRole
, "isExpanded");
1838 roles
.insert(IsExpandableRole
, "isExpandable");
1839 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1841 Q_ASSERT(roles
.count() == RolesCount
);
1844 return roles
.value(roleType
);
1847 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1849 // It is important to insert only roles that are fast to retrieve. E.g.
1850 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1851 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1852 QHash
<QByteArray
, QVariant
> data
;
1853 data
.insert(sharedValue("url"), item
.url());
1855 const bool isDir
= item
.isDir();
1856 if (m_requestRole
[IsDirRole
] && isDir
) {
1857 data
.insert(sharedValue("isDir"), true);
1860 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1861 data
.insert(sharedValue("isLink"), true);
1864 if (m_requestRole
[IsHiddenRole
]) {
1865 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1868 if (m_requestRole
[NameRole
]) {
1869 data
.insert(sharedValue("text"), item
.text());
1872 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1873 // TODO KF6 use KFileItem::suffix 464722
1874 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1877 if (m_requestRole
[SizeRole
] && !isDir
) {
1878 data
.insert(sharedValue("size"), item
.size());
1881 if (m_requestRole
[ModificationTimeRole
]) {
1882 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1883 // having several thousands of items. Instead read the raw number from UDSEntry directly
1884 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1885 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1886 data
.insert(sharedValue("modificationtime"), dateTime
);
1889 if (m_requestRole
[CreationTimeRole
]) {
1890 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1891 // having several thousands of items. Instead read the raw number from UDSEntry directly
1892 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1893 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1894 data
.insert(sharedValue("creationtime"), dateTime
);
1897 if (m_requestRole
[AccessTimeRole
]) {
1898 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1899 // having several thousands of items. Instead read the raw number from UDSEntry directly
1900 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1901 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1902 data
.insert(sharedValue("accesstime"), dateTime
);
1905 if (m_requestRole
[PermissionsRole
]) {
1906 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1909 if (m_requestRole
[OwnerRole
]) {
1910 data
.insert(sharedValue("owner"), item
.user());
1913 if (m_requestRole
[GroupRole
]) {
1914 data
.insert(sharedValue("group"), item
.group());
1917 if (m_requestRole
[DestinationRole
]) {
1918 QString destination
= item
.linkDest();
1919 if (destination
.isEmpty()) {
1920 destination
= QLatin1Char('-');
1922 data
.insert(sharedValue("destination"), destination
);
1925 if (m_requestRole
[PathRole
]) {
1927 if (item
.url().scheme() == QLatin1String("trash")) {
1928 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1930 // For performance reasons cache the home-path in a static QString
1931 // (see QDir::homePath() for more details)
1932 static QString homePath
;
1933 if (homePath
.isEmpty()) {
1934 homePath
= QDir::homePath();
1937 path
= item
.localPath();
1938 if (path
.startsWith(homePath
)) {
1939 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1943 const int index
= path
.lastIndexOf(item
.text());
1944 path
= path
.mid(0, index
- 1);
1945 data
.insert(sharedValue("path"), path
);
1948 if (m_requestRole
[DeletionTimeRole
]) {
1949 QDateTime deletionTime
;
1950 if (item
.url().scheme() == QLatin1String("trash")) {
1951 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1953 data
.insert(sharedValue("deletiontime"), deletionTime
);
1956 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1957 data
.insert(sharedValue("isExpandable"), true);
1960 if (m_requestRole
[ExpandedParentsCountRole
]) {
1962 const int level
= expandedParentsCount(parent
) + 1;
1963 data
.insert(sharedValue("expandedParentsCount"), level
);
1967 if (item
.isMimeTypeKnown()) {
1968 QString iconName
= item
.iconName();
1969 if (!QIcon::hasThemeIcon(iconName
)) {
1970 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1971 iconName
= mimeType
.genericIconName();
1974 data
.insert(sharedValue("iconName"), iconName
);
1976 if (m_requestRole
[TypeRole
]) {
1977 data
.insert(sharedValue("type"), item
.mimeComment());
1979 } else if (m_requestRole
[TypeRole
] && isDir
) {
1980 static const QString folderMimeType
= item
.mimeComment();
1981 data
.insert(sharedValue("type"), folderMimeType
);
1987 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1991 if (a
->parent
!= b
->parent
) {
1992 const int expansionLevelA
= expandedParentsCount(a
);
1993 const int expansionLevelB
= expandedParentsCount(b
);
1995 // If b has a higher expansion level than a, check if a is a parent
1996 // of b, and make sure that both expansion levels are equal otherwise.
1997 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1998 if (b
->parent
== a
) {
2004 // If a has a higher expansion level than a, check if b is a parent
2005 // of a, and make sure that both expansion levels are equal otherwise.
2006 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
2007 if (a
->parent
== b
) {
2013 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2015 // Compare the last parents of a and b which are different.
2016 while (a
->parent
!= b
->parent
) {
2022 // Show hidden files and folders last
2023 if (m_sortHiddenLast
) {
2024 const bool isHiddenA
= a
->item
.isHidden();
2025 const bool isHiddenB
= b
->item
.isHidden();
2026 if (isHiddenA
&& !isHiddenB
) {
2028 } else if (!isHiddenA
&& isHiddenB
) {
2034 || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& m_sortRole
== SizeRole
)) {
2035 const bool isDirA
= a
->item
.isDir();
2036 const bool isDirB
= b
->item
.isDir();
2037 if (isDirA
&& !isDirB
) {
2039 } else if (!isDirA
&& isDirB
) {
2044 result
= sortRoleCompare(a
, b
, collator
);
2046 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2049 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2051 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2052 return lessThan(a
, b
, m_collator
);
2055 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2056 // Sorting by string can be expensive, in particular if natural sorting is
2057 // enabled. Use all CPU cores to speed up the sorting process.
2058 static const int numberOfThreads
= QThread::idealThreadCount();
2059 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2061 // Sorting by other roles is quite fast. Use only one thread to prevent
2062 // problems caused by non-reentrant comparison functions, see
2063 // https://bugs.kde.org/show_bug.cgi?id=312679
2064 mergeSort(begin
, end
, lambdaLessThan
);
2068 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2070 // This function must never return 0, because that would break stable
2071 // sorting, which leads to all kinds of bugs.
2072 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2073 // If two items have equal sort values, let the fallbacks at the bottom of
2074 // the function handle it.
2075 const KFileItem
&itemA
= a
->item
;
2076 const KFileItem
&itemB
= b
->item
;
2080 switch (m_sortRole
) {
2082 // The name role is handled as default fallback after the switch
2086 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& itemA
.isDir()) {
2087 // folders first then
2088 // items A and B are folders thanks to lessThan checks
2089 auto valueA
= a
->values
.value("count");
2090 auto valueB
= b
->values
.value("count");
2091 if (valueA
.isNull()) {
2092 if (!valueB
.isNull()) {
2095 } else if (valueB
.isNull()) {
2098 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2100 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2107 KIO::filesize_t sizeA
= 0;
2108 if (itemA
.isDir()) {
2109 sizeA
= a
->values
.value("size").toULongLong();
2111 sizeA
= itemA
.size();
2113 KIO::filesize_t sizeB
= 0;
2114 if (itemB
.isDir()) {
2115 sizeB
= b
->values
.value("size").toULongLong();
2117 sizeB
= itemB
.size();
2119 if (sizeA
< sizeB
) {
2121 } else if (sizeA
> sizeB
) {
2127 case ModificationTimeRole
: {
2128 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2129 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2130 if (dateTimeA
< dateTimeB
) {
2132 } else if (dateTimeA
> dateTimeB
) {
2138 case AccessTimeRole
: {
2139 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2140 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2141 if (dateTimeA
< dateTimeB
) {
2143 } else if (dateTimeA
> dateTimeB
) {
2149 case CreationTimeRole
: {
2150 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2151 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2152 if (dateTimeA
< dateTimeB
) {
2154 } else if (dateTimeA
> dateTimeB
) {
2160 case DeletionTimeRole
: {
2161 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2162 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2163 if (dateTimeA
< dateTimeB
) {
2165 } else if (dateTimeA
> dateTimeB
) {
2179 case ReleaseYearRole
: {
2180 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2184 case DimensionsRole
: {
2185 const QByteArray role
= roleForType(m_sortRole
);
2186 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2187 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2189 if (dimensionsA
.width() == dimensionsB
.width()) {
2190 result
= dimensionsA
.height() - dimensionsB
.height();
2192 result
= dimensionsA
.width() - dimensionsB
.width();
2198 const QByteArray role
= roleForType(m_sortRole
);
2199 const QString roleValueA
= a
->values
.value(role
).toString();
2200 const QString roleValueB
= b
->values
.value(role
).toString();
2201 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2203 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2205 } else if (isRoleValueNatural(m_sortRole
)) {
2206 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2208 result
= QString::compare(roleValueA
, roleValueB
);
2215 // The current sort role was sufficient to define an order
2219 // Fallback #1: Compare the text of the items
2220 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2225 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2226 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2231 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2232 // equal. In this case a comparison of the URL is done which is unique in all cases
2233 // within KDirLister.
2234 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2237 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2239 QMutexLocker
collatorLock(s_collatorMutex());
2241 if (m_naturalSorting
) {
2242 return collator
.compare(a
, b
);
2245 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2246 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2247 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2248 // comparison, still a deterministic sort order is required. A case sensitive
2249 // comparison is done as fallback.
2253 return QString::compare(a
, b
, Qt::CaseSensitive
);
2256 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2258 Q_ASSERT(!m_itemData
.isEmpty());
2260 const int maxIndex
= count() - 1;
2261 QList
<QPair
<int, QVariant
>> groups
;
2265 for (int i
= 0; i
<= maxIndex
; ++i
) {
2266 if (isChildItem(i
)) {
2270 const QString name
= m_itemData
.at(i
)->item
.text();
2272 // Use the first character of the name as group indication
2273 QChar newFirstChar
= name
.at(0).toUpper();
2274 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2275 newFirstChar
= name
.at(1).toUpper();
2278 if (firstChar
!= newFirstChar
) {
2279 QString newGroupValue
;
2280 if (newFirstChar
.isLetter()) {
2281 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2282 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2284 // Try to find a matching group in the range 'A' to 'Z'.
2285 static std::vector
<QChar
> lettersAtoZ
;
2286 lettersAtoZ
.reserve('Z' - 'A' + 1);
2287 if (lettersAtoZ
.empty()) {
2288 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2289 lettersAtoZ
.push_back(QLatin1Char(c
));
2293 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2294 return m_collator
.compare(c1
, c2
) < 0;
2297 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2298 if (it
!= lettersAtoZ
.end()) {
2299 if (localeAwareLessThan(newFirstChar
, *it
)) {
2300 // newFirstChar belongs to the group preceding *it.
2301 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2304 newGroupValue
= *it
;
2308 // Symbols from non Latin-based scripts
2309 newGroupValue
= newFirstChar
;
2311 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2312 // Apply group '0 - 9' for any name that starts with a digit
2313 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2315 newGroupValue
= i18nc("@title:group", "Others");
2318 if (newGroupValue
!= groupValue
) {
2319 groupValue
= newGroupValue
;
2320 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2323 firstChar
= newFirstChar
;
2329 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2331 Q_ASSERT(!m_itemData
.isEmpty());
2333 const int maxIndex
= count() - 1;
2334 QList
<QPair
<int, QVariant
>> groups
;
2337 for (int i
= 0; i
<= maxIndex
; ++i
) {
2338 if (isChildItem(i
)) {
2342 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2343 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2344 QString newGroupValue
;
2345 if (!item
.isNull() && item
.isDir()) {
2346 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
|| m_sortDirsFirst
) {
2347 newGroupValue
= i18nc("@title:group Size", "Folders");
2349 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2353 if (newGroupValue
.isEmpty()) {
2354 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2355 newGroupValue
= i18nc("@title:group Size", "Small");
2356 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2357 newGroupValue
= i18nc("@title:group Size", "Medium");
2359 newGroupValue
= i18nc("@title:group Size", "Big");
2363 if (newGroupValue
!= groupValue
) {
2364 groupValue
= newGroupValue
;
2365 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2372 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2374 Q_ASSERT(!m_itemData
.isEmpty());
2376 const int maxIndex
= count() - 1;
2377 QList
<QPair
<int, QVariant
>> groups
;
2379 const QDate currentDate
= QDate::currentDate();
2381 QDate previousFileDate
;
2383 for (int i
= 0; i
<= maxIndex
; ++i
) {
2384 if (isChildItem(i
)) {
2388 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2389 const QDate fileDate
= fileTime
.date();
2390 if (fileDate
== previousFileDate
) {
2391 // The current item is in the same group as the previous item
2394 previousFileDate
= fileDate
;
2396 const int daysDistance
= fileDate
.daysTo(currentDate
);
2398 QString newGroupValue
;
2399 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2400 switch (daysDistance
/ 7) {
2402 switch (daysDistance
) {
2404 newGroupValue
= i18nc("@title:group Date", "Today");
2407 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2410 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2411 newGroupValue
= i18nc(
2412 "Can be used to script translation of \"dddd\""
2413 "with context @title:group Date",
2419 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2422 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2425 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2429 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2435 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2436 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2437 if (daysDistance
== 1) {
2438 const KLocalizedString format
= ki18nc(
2439 "@title:group Date: "
2440 "MMMM is full month name in current locale, and yyyy is "
2441 "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 "
2442 "part of the text that should not be formatted as a date",
2443 "'Yesterday' (MMMM, yyyy)");
2444 const QString translatedFormat
= format
.toString();
2445 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2446 newGroupValue
= fileTime
.toString(translatedFormat
);
2447 newGroupValue
= i18nc(
2448 "Can be used to script translation of "
2449 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2453 qCWarning(DolphinDebug
).nospace()
2454 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2455 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2456 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2458 } else if (daysDistance
<= 7) {
2460 fileTime
.toString(i18nc("@title:group Date: "
2461 "The week day name: dddd, MMMM is full month name "
2462 "in current locale, and yyyy is full year number.",
2463 "dddd (MMMM, yyyy)"));
2464 newGroupValue
= i18nc(
2465 "Can be used to script translation of "
2466 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2469 } else if (daysDistance
<= 7 * 2) {
2470 const KLocalizedString format
= ki18nc(
2471 "@title:group Date: "
2472 "MMMM is full month name in current locale, and yyyy is "
2473 "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 "
2474 "part of the text that should not be formatted as a date",
2475 "'One Week Ago' (MMMM, yyyy)");
2476 const QString translatedFormat
= format
.toString();
2477 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2478 newGroupValue
= fileTime
.toString(translatedFormat
);
2479 newGroupValue
= i18nc(
2480 "Can be used to script translation of "
2481 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2485 qCWarning(DolphinDebug
).nospace()
2486 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2487 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2488 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2490 } else if (daysDistance
<= 7 * 3) {
2491 const KLocalizedString format
= ki18nc(
2492 "@title:group Date: "
2493 "MMMM is full month name in current locale, and yyyy is "
2494 "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 "
2495 "part of the text that should not be formatted as a date",
2496 "'Two Weeks Ago' (MMMM, yyyy)");
2497 const QString translatedFormat
= format
.toString();
2498 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2499 newGroupValue
= fileTime
.toString(translatedFormat
);
2500 newGroupValue
= i18nc(
2501 "Can be used to script translation of "
2502 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2506 qCWarning(DolphinDebug
).nospace()
2507 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2508 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2509 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2511 } else if (daysDistance
<= 7 * 4) {
2512 const KLocalizedString format
= ki18nc(
2513 "@title:group Date: "
2514 "MMMM is full month name in current locale, and yyyy is "
2515 "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 "
2516 "part of the text that should not be formatted as a date",
2517 "'Three Weeks Ago' (MMMM, yyyy)");
2518 const QString translatedFormat
= format
.toString();
2519 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2520 newGroupValue
= fileTime
.toString(translatedFormat
);
2521 newGroupValue
= i18nc(
2522 "Can be used to script translation of "
2523 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2527 qCWarning(DolphinDebug
).nospace()
2528 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2529 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2530 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2533 const KLocalizedString format
= ki18nc(
2534 "@title:group Date: "
2535 "MMMM is full month name in current locale, and yyyy is "
2536 "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 "
2537 "part of the text that should not be formatted as a date",
2538 "'Earlier on' MMMM, yyyy");
2539 const QString translatedFormat
= format
.toString();
2540 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2541 newGroupValue
= fileTime
.toString(translatedFormat
);
2542 newGroupValue
= i18nc(
2543 "Can be used to script translation of "
2544 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2548 qCWarning(DolphinDebug
).nospace()
2549 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2550 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2551 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2556 fileTime
.toString(i18nc("@title:group "
2557 "The month and year: MMMM is full month name in current locale, "
2558 "and yyyy is full year number",
2560 newGroupValue
= i18nc(
2561 "Can be used to script translation of "
2562 "\"MMMM, yyyy\" with context @title:group Date",
2568 if (newGroupValue
!= groupValue
) {
2569 groupValue
= newGroupValue
;
2570 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2577 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2579 Q_ASSERT(!m_itemData
.isEmpty());
2581 const int maxIndex
= count() - 1;
2582 QList
<QPair
<int, QVariant
>> groups
;
2584 QString permissionsString
;
2586 for (int i
= 0; i
<= maxIndex
; ++i
) {
2587 if (isChildItem(i
)) {
2591 const ItemData
*itemData
= m_itemData
.at(i
);
2592 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2593 if (newPermissionsString
== permissionsString
) {
2596 permissionsString
= newPermissionsString
;
2598 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2602 if (info
.permission(QFile::ReadUser
)) {
2603 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2605 if (info
.permission(QFile::WriteUser
)) {
2606 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2608 if (info
.permission(QFile::ExeUser
)) {
2609 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2611 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2615 if (info
.permission(QFile::ReadGroup
)) {
2616 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2618 if (info
.permission(QFile::WriteGroup
)) {
2619 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2621 if (info
.permission(QFile::ExeGroup
)) {
2622 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2624 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2626 // Set others string
2628 if (info
.permission(QFile::ReadOther
)) {
2629 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2631 if (info
.permission(QFile::WriteOther
)) {
2632 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2634 if (info
.permission(QFile::ExeOther
)) {
2635 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2637 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2639 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2640 if (newGroupValue
!= groupValue
) {
2641 groupValue
= newGroupValue
;
2642 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2649 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2651 Q_ASSERT(!m_itemData
.isEmpty());
2653 const int maxIndex
= count() - 1;
2654 QList
<QPair
<int, QVariant
>> groups
;
2656 int groupValue
= -1;
2657 for (int i
= 0; i
<= maxIndex
; ++i
) {
2658 if (isChildItem(i
)) {
2661 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2662 if (newGroupValue
!= groupValue
) {
2663 groupValue
= newGroupValue
;
2664 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2671 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2673 Q_ASSERT(!m_itemData
.isEmpty());
2675 const int maxIndex
= count() - 1;
2676 QList
<QPair
<int, QVariant
>> groups
;
2678 bool isFirstGroupValue
= true;
2680 for (int i
= 0; i
<= maxIndex
; ++i
) {
2681 if (isChildItem(i
)) {
2684 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2685 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2686 groupValue
= newGroupValue
;
2687 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2688 isFirstGroupValue
= false;
2695 void KFileItemModel::emitSortProgress(int resolvedCount
)
2697 // Be tolerant against a resolvedCount with a wrong range.
2698 // Although there should not be a case where KFileItemModelRolesUpdater
2699 // (= caller) provides a wrong range, it is important to emit
2700 // a useful progress information even if there is an unexpected
2701 // implementation issue.
2703 const int itemCount
= count();
2704 if (resolvedCount
>= itemCount
) {
2705 m_sortingProgressPercent
= -1;
2706 if (m_resortAllItemsTimer
->isActive()) {
2707 m_resortAllItemsTimer
->stop();
2711 Q_EMIT
directorySortingProgress(100);
2712 } else if (itemCount
> 0) {
2713 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2715 const int progress
= resolvedCount
* 100 / itemCount
;
2716 if (m_sortingProgressPercent
!= progress
) {
2717 m_sortingProgressPercent
= progress
;
2718 Q_EMIT
directorySortingProgress(progress
);
2723 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2725 static const RoleInfoMap rolesInfoMap
[] = {
2727 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2728 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2729 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2730 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2731 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2732 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2733 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2734 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2735 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2736 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2737 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2738 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2739 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2740 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2741 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2742 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2743 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2744 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2745 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2746 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2747 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2748 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2749 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2750 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2751 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2752 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2753 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2754 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2755 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2756 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2757 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2758 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2759 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2760 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2761 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2762 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2763 { "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 },
2764 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2765 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2769 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2770 return rolesInfoMap
;
2773 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2775 QElapsedTimer timer
;
2777 for (const KFileItem
&item
: items
) {
2778 // Only determine mime types for files here. For directories,
2779 // KFileItem::determineMimeType() reads the .directory file inside to
2780 // load the icon, but this is not necessary at all if we just need the
2781 // type. Some special code for setting the correct mime type for
2782 // directories is in retrieveData().
2783 if (!item
.isDir()) {
2784 item
.determineMimeType();
2787 if (timer
.elapsed() > timeout
) {
2788 // Don't block the user interface, let the remaining items
2789 // be resolved asynchronously.
2795 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2797 static QSet
<QByteArray
> pool
;
2798 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2800 if (it
!= pool
.constEnd()) {
2808 bool KFileItemModel::isConsistent() const
2810 // m_items may contain less items than m_itemData because m_items
2811 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2812 if (m_items
.count() > m_itemData
.count()) {
2816 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2817 // Check if m_items and m_itemData are consistent.
2818 const KFileItem item
= fileItem(i
);
2819 if (item
.isNull()) {
2820 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2824 const int itemIndex
= index(item
);
2825 if (itemIndex
!= i
) {
2826 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2830 // Check if the items are sorted correctly.
2831 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2832 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2836 // Check if all parent-child relationships are consistent.
2837 const ItemData
*data
= m_itemData
.at(i
);
2838 const ItemData
*parent
= data
->parent
;
2840 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2841 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2845 const int parentIndex
= index(parent
->item
);
2846 if (parentIndex
>= i
) {
2847 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2857 void KFileItemModel::slotListerError(KIO::Job
*job
)
2859 const int jobError
= job
->error();
2860 if (jobError
== KIO::ERR_IS_FILE
) {
2861 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2862 Q_EMIT
urlIsFileError(listJob
->url());
2865 const QString errorString
= job
->errorString();
2866 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."), jobError
);
2870 #include "moc_kfileitemmodel.cpp"