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"
18 #include <KLocalizedString>
19 #include <KUrlMimeData>
21 #include <QElapsedTimer>
24 #include <QMimeDatabase>
25 #include <QRecursiveMutex>
29 #include <klazylocalizedstring.h>
31 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(QObject
*parent
)
36 : KItemModelBase("text", parent
)
37 , m_dirLister(nullptr)
38 , m_sortDirsFirst(true)
39 , m_sortHiddenLast(false)
40 , m_sortRole(NameRole
)
41 , m_sortingProgressPercent(-1)
48 , m_maximumUpdateIntervalTimer(nullptr)
49 , m_resortAllItemsTimer(nullptr)
50 , m_pendingItemsToInsert()
55 m_collator
.setNumericMode(true);
57 loadSortingSettings();
59 m_dirLister
= new KDirLister(this);
60 m_dirLister
->setAutoErrorHandlingEnabled(false);
61 m_dirLister
->setDelayedMimeTypes(true);
63 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
65 m_dirLister
->setMainWindow(parentWidget
->window());
68 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
69 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
70 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
71 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
72 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
73 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
74 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
75 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
76 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
77 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
78 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
80 // Apply default roles that should be determined
82 m_requestRole
[NameRole
] = true;
83 m_requestRole
[IsDirRole
] = true;
84 m_requestRole
[IsLinkRole
] = true;
85 m_roles
.insert("text");
86 m_roles
.insert("isDir");
87 m_roles
.insert("isLink");
88 m_roles
.insert("isHidden");
90 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
91 // before the completed() or canceled() signal has been emitted.
92 m_maximumUpdateIntervalTimer
= new QTimer(this);
93 m_maximumUpdateIntervalTimer
->setInterval(2000);
94 m_maximumUpdateIntervalTimer
->setSingleShot(true);
95 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
97 // When changing the value of an item which represents the sort-role a resorting must be
98 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
99 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
100 // resorting is postponed until the timer has been exceeded.
101 m_resortAllItemsTimer
= new QTimer(this);
102 m_resortAllItemsTimer
->setInterval(500);
103 m_resortAllItemsTimer
->setSingleShot(true);
104 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
106 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
108 setShowTrashMime(m_dirLister
->showHiddenFiles());
111 KFileItemModel::~KFileItemModel()
113 qDeleteAll(m_itemData
);
114 qDeleteAll(m_filteredItems
);
115 qDeleteAll(m_pendingItemsToInsert
);
118 void KFileItemModel::loadDirectory(const QUrl
&url
)
120 m_dirLister
->openUrl(url
);
123 void KFileItemModel::refreshDirectory(const QUrl
&url
)
125 // Refresh all expanded directories first (Bug 295300)
126 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
127 while (expandedDirs
.hasNext()) {
129 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
132 m_dirLister
->openUrl(url
, KDirLister::Reload
);
134 Q_EMIT
directoryRefreshing();
137 QUrl
KFileItemModel::directory() const
139 return m_dirLister
->url();
142 void KFileItemModel::cancelDirectoryLoading()
147 int KFileItemModel::count() const
149 return m_itemData
.count();
152 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
154 if (index
>= 0 && index
< count()) {
155 ItemData
*data
= m_itemData
.at(index
);
156 if (data
->values
.isEmpty()) {
157 data
->values
= retrieveData(data
->item
, data
->parent
);
158 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
159 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
160 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
161 // so this special request of different behavior can be identified here.
162 bool hasExpandedParentsCount
= false;
163 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
165 data
->values
= retrieveData(data
->item
, data
->parent
);
166 data
->values
.insert("isExpanded", true);
167 if (hasExpandedParentsCount
) {
168 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
174 return QHash
<QByteArray
, QVariant
>();
177 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
179 if (index
< 0 || index
>= count()) {
183 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
185 // Determine which roles have been changed
186 QSet
<QByteArray
> changedRoles
;
187 QHashIterator
<QByteArray
, QVariant
> it(values
);
188 while (it
.hasNext()) {
190 const QByteArray role
= sharedValue(it
.key());
191 const QVariant value
= it
.value();
193 if (currentValues
[role
] != value
) {
194 currentValues
[role
] = value
;
195 changedRoles
.insert(role
);
199 if (changedRoles
.isEmpty()) {
203 m_itemData
[index
]->values
= currentValues
;
204 if (changedRoles
.contains("text")) {
205 QUrl url
= m_itemData
[index
]->item
.url();
206 url
= url
.adjusted(QUrl::RemoveFilename
);
207 url
.setPath(url
.path() + currentValues
["text"].toString());
208 m_itemData
[index
]->item
.setUrl(url
);
211 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
216 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
218 if (dirsFirst
!= m_sortDirsFirst
) {
219 m_sortDirsFirst
= dirsFirst
;
224 bool KFileItemModel::sortDirectoriesFirst() const
226 return m_sortDirsFirst
;
229 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
231 if (hiddenLast
!= m_sortHiddenLast
) {
232 m_sortHiddenLast
= hiddenLast
;
237 bool KFileItemModel::sortHiddenLast() const
239 return m_sortHiddenLast
;
242 void KFileItemModel::setShowTrashMime(bool show
)
244 const auto trashMime
= QStringLiteral("application/x-trash");
245 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
246 bool wasShown
= !excludeFilter
.contains(trashMime
);
250 excludeFilter
.removeAll(trashMime
);
254 excludeFilter
.append(trashMime
);
258 if (wasShown
!= show
) {
259 setExcludeMimeTypeFilter(excludeFilter
);
263 void KFileItemModel::setShowHiddenFiles(bool show
)
265 m_dirLister
->setShowHiddenFiles(show
);
266 setShowTrashMime(show
);
267 m_dirLister
->emitChanges();
269 dispatchPendingItemsToInsert();
273 bool KFileItemModel::showHiddenFiles() const
275 return m_dirLister
->showHiddenFiles();
278 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
280 m_dirLister
->setDirOnlyMode(enabled
);
283 bool KFileItemModel::showDirectoriesOnly() const
285 return m_dirLister
->dirOnlyMode();
288 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
290 QMimeData
*data
= new QMimeData();
292 // The following code has been taken from KDirModel::mimeData()
293 // (kdelibs/kio/kio/kdirmodel.cpp)
294 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
296 QList
<QUrl
> mostLocalUrls
;
297 const ItemData
*lastAddedItem
= nullptr;
299 for (int index
: indexes
) {
300 const ItemData
*itemData
= m_itemData
.at(index
);
301 const ItemData
*parent
= itemData
->parent
;
303 while (parent
&& parent
!= lastAddedItem
) {
304 parent
= parent
->parent
;
307 if (parent
&& parent
== lastAddedItem
) {
308 // A parent of 'itemData' has been added already.
312 lastAddedItem
= itemData
;
313 const KFileItem
&item
= itemData
->item
;
314 if (!item
.isNull()) {
318 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
322 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
326 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
328 startFromIndex
= qMax(0, startFromIndex
);
329 for (int i
= startFromIndex
; i
< count(); ++i
) {
330 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
334 for (int i
= 0; i
< startFromIndex
; ++i
) {
335 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
342 bool KFileItemModel::supportsDropping(int index
) const
348 item
= fileItem(index
);
350 return !item
.isNull() && ((item
.isDir() && item
.isWritable()) || item
.isDesktopFile());
353 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
355 static QHash
<QByteArray
, QString
> description
;
356 if (description
.isEmpty()) {
358 const RoleInfoMap
*map
= rolesInfoMap(count
);
359 for (int i
= 0; i
< count
; ++i
) {
360 if (map
[i
].roleTranslation
.isEmpty()) {
363 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
367 return description
.value(role
);
370 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
372 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
373 #ifdef KFILEITEMMODEL_DEBUG
377 switch (typeForRole(sortRole())) {
379 m_groups
= nameRoleGroups();
382 m_groups
= sizeRoleGroups();
384 case ModificationTimeRole
:
385 m_groups
= timeRoleGroups([](const ItemData
*item
) {
386 return item
->item
.time(KFileItem::ModificationTime
);
389 case CreationTimeRole
:
390 m_groups
= timeRoleGroups([](const ItemData
*item
) {
391 return item
->item
.time(KFileItem::CreationTime
);
395 m_groups
= timeRoleGroups([](const ItemData
*item
) {
396 return item
->item
.time(KFileItem::AccessTime
);
399 case DeletionTimeRole
:
400 m_groups
= timeRoleGroups([](const ItemData
*item
) {
401 return item
->values
.value("deletiontime").toDateTime();
404 case PermissionsRole
:
405 m_groups
= permissionRoleGroups();
408 m_groups
= ratingRoleGroups();
411 m_groups
= genericStringRoleGroups(sortRole());
415 #ifdef KFILEITEMMODEL_DEBUG
416 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
423 KFileItem
KFileItemModel::fileItem(int index
) const
425 if (index
>= 0 && index
< count()) {
426 return m_itemData
.at(index
)->item
;
432 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
434 const int indexForUrl
= index(url
);
435 if (indexForUrl
>= 0) {
436 return m_itemData
.at(indexForUrl
)->item
;
441 int KFileItemModel::index(const KFileItem
&item
) const
443 return index(item
.url());
446 int KFileItemModel::index(const QUrl
&url
) const
448 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
450 const int itemCount
= m_itemData
.count();
451 int itemsInHash
= m_items
.count();
453 int index
= m_items
.value(urlToFind
, -1);
454 while (index
< 0 && itemsInHash
< itemCount
) {
455 // Not all URLs are stored yet in m_items. We grow m_items until either
456 // urlToFind is found, or all URLs have been stored in m_items.
457 // Note that we do not add the URLs to m_items one by one, but in
458 // larger blocks. After each block, we check if urlToFind is in
459 // m_items. We could in principle compare urlToFind with each URL while
460 // we are going through m_itemData, but comparing two QUrls will,
461 // unlike calling qHash for the URLs, trigger a parsing of the URLs
462 // which costs both CPU cycles and memory.
463 const int blockSize
= 1000;
464 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
465 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
466 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
467 m_items
.insert(nextUrl
, i
);
470 itemsInHash
= currentBlockEnd
;
471 index
= m_items
.value(urlToFind
, -1);
475 // The item could not be found, even though all items from m_itemData
476 // should be in m_items now. We print some diagnostic information which
477 // might help to find the cause of the problem, but only once. This
478 // prevents that obtaining and printing the debugging information
479 // wastes CPU cycles and floods the shell or .xsession-errors.
480 static bool printDebugInfo
= true;
482 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
483 printDebugInfo
= false;
485 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
486 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
487 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
489 // Check if there are multiple items with the same URL.
490 QMultiHash
<QUrl
, int> indexesForUrl
;
491 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
492 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
495 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
496 for (const QUrl
&url
: uniqueKeys
) {
497 if (indexesForUrl
.count(url
) > 1) {
498 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
500 auto it
= indexesForUrl
.find(url
);
501 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
502 const ItemData
*data
= m_itemData
.at(it
.value());
503 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
505 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
517 KFileItem
KFileItemModel::rootItem() const
519 return m_dirLister
->rootItem();
522 void KFileItemModel::clear()
527 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
529 if (m_roles
== roles
) {
533 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
537 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
538 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
539 if (supportedExpanding
&& !willSupportExpanding
) {
540 // No expanding is supported anymore. Take care to delete all items that have an expansion level
541 // that is not 0 (and hence are part of an expanded item).
542 removeExpandedItems();
549 QSetIterator
<QByteArray
> it(roles
);
550 while (it
.hasNext()) {
551 const QByteArray
&role
= it
.next();
552 m_requestRole
[typeForRole(role
)] = true;
556 // Update m_data with the changed requested roles
557 const int maxIndex
= count() - 1;
558 for (int i
= 0; i
<= maxIndex
; ++i
) {
559 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
562 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
565 // Clear the 'values' of all filtered items. They will be re-populated with the
566 // correct roles the next time 'values' will be accessed via data(int).
567 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
568 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
569 while (filteredIt
!= filteredEnd
) {
570 (*filteredIt
)->values
.clear();
575 QSet
<QByteArray
> KFileItemModel::roles() const
580 bool KFileItemModel::setExpanded(int index
, bool expanded
)
582 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
586 QHash
<QByteArray
, QVariant
> values
;
587 values
.insert(sharedValue("isExpanded"), expanded
);
588 if (!setData(index
, values
)) {
592 const KFileItem item
= m_itemData
.at(index
)->item
;
593 const QUrl url
= item
.url();
594 const QUrl targetUrl
= item
.targetUrl();
596 m_expandedDirs
.insert(targetUrl
, url
);
597 m_dirLister
->openUrl(url
, KDirLister::Keep
);
599 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
600 for (const QVariant
&var
: previouslyExpandedChildren
) {
601 m_urlsToExpand
.insert(var
.toUrl());
604 // Note that there might be (indirect) children of the folder which is to be collapsed in
605 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
606 // possibly without a parent, which might result in a crash, we insert all pending items
607 // right now. All new items which would be without a parent will then be removed.
608 dispatchPendingItemsToInsert();
610 // Check if the index of the collapsed folder has changed. If that is the case, then items
611 // were inserted before the collapsed folder, and its index needs to be updated.
612 if (m_itemData
.at(index
)->item
!= item
) {
613 index
= this->index(item
);
616 m_expandedDirs
.remove(targetUrl
);
617 m_dirLister
->stop(url
);
618 m_dirLister
->forgetDirs(url
);
620 const int parentLevel
= expandedParentsCount(index
);
621 const int itemCount
= m_itemData
.count();
622 const int firstChildIndex
= index
+ 1;
624 QVariantList expandedChildren
;
626 int childIndex
= firstChildIndex
;
627 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
628 ItemData
*itemData
= m_itemData
.at(childIndex
);
629 if (itemData
->values
.value("isExpanded").toBool()) {
630 const QUrl targetUrl
= itemData
->item
.targetUrl();
631 const QUrl url
= itemData
->item
.url();
632 m_expandedDirs
.remove(targetUrl
);
633 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
634 m_dirLister
->forgetDirs(url
);
635 expandedChildren
.append(targetUrl
);
639 const int childrenCount
= childIndex
- firstChildIndex
;
641 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
642 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
644 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
650 bool KFileItemModel::isExpanded(int index
) const
652 if (index
>= 0 && index
< count()) {
653 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
658 bool KFileItemModel::isExpandable(int index
) const
660 if (index
>= 0 && index
< count()) {
661 // Call data (instead of accessing m_itemData directly)
662 // to ensure that the value is initialized.
663 return data(index
).value("isExpandable").toBool();
668 int KFileItemModel::expandedParentsCount(int index
) const
670 if (index
>= 0 && index
< count()) {
671 return expandedParentsCount(m_itemData
.at(index
));
676 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
679 const auto dirs
= m_expandedDirs
;
680 for (const auto &dir
: dirs
) {
686 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
688 m_urlsToExpand
= urls
;
691 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
693 // Assure that each sub-path of the URL that should be
694 // expanded is added to m_urlsToExpand. KDirLister
695 // does not care whether the parent-URL has already been
697 QUrl urlToExpand
= m_dirLister
->url();
698 const int pos
= urlToExpand
.path().length();
700 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
701 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
702 // so using QString::SkipEmptyParts
703 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
704 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
705 QString path
= urlToExpand
.path();
706 if (!path
.endsWith(QLatin1Char('/'))) {
707 path
.append(QLatin1Char('/'));
709 urlToExpand
.setPath(path
+ subDirs
.at(i
));
710 m_urlsToExpand
.insert(urlToExpand
);
713 // KDirLister::open() must called at least once to trigger an initial
714 // loading. The pending URLs that must be restored are handled
715 // in slotCompleted().
716 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
717 while (it2
.hasNext()) {
718 const int idx
= index(it2
.next());
719 if (idx
>= 0 && !isExpanded(idx
)) {
720 setExpanded(idx
, true);
726 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
728 if (m_filter
.pattern() != nameFilter
) {
729 dispatchPendingItemsToInsert();
730 m_filter
.setPattern(nameFilter
);
735 QString
KFileItemModel::nameFilter() const
737 return m_filter
.pattern();
740 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
742 if (m_filter
.mimeTypes() != filters
) {
743 dispatchPendingItemsToInsert();
744 m_filter
.setMimeTypes(filters
);
749 QStringList
KFileItemModel::mimeTypeFilters() const
751 return m_filter
.mimeTypes();
754 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
756 if (m_filter
.excludeMimeTypes() != filters
) {
757 dispatchPendingItemsToInsert();
758 m_filter
.setExcludeMimeTypes(filters
);
763 QStringList
KFileItemModel::excludeMimeTypeFilter() const
765 return m_filter
.excludeMimeTypes();
768 void KFileItemModel::applyFilters()
771 // Check which previously shown items from m_itemData must now get
772 // hidden and hence moved from m_itemData into m_filteredItems.
774 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
776 // This pointer will refer to the next confirmed shown item from the point of
777 // view of the current "itemData" in the upcoming "for" loop.
778 ItemData
*itemShownBelow
= nullptr;
780 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
781 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
782 ItemData
*itemData
= m_itemData
.at(index
);
784 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
785 // We could've entered here for two reasons:
786 // 1. This item passes the filter itself
787 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
789 // So this item must remain shown.
790 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
791 itemShownBelow
= itemData
;
793 // We hide this item for now, however, for expanded folders this is not final:
794 // 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
795 newFilteredIndexes
.prepend(index
);
796 m_filteredItems
.insert(itemData
->item
, itemData
);
797 // indexShownBelow doesn't get updated since this item will be hidden
801 // This will remove the newly filtered items from m_itemData
802 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
805 // Check which hidden items from m_filteredItems should
806 // become visible again and hence moved from m_filteredItems back into m_itemData.
808 QList
<ItemData
*> newVisibleItems
;
810 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
812 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
813 while (it
!= m_filteredItems
.end()) {
814 if (m_filter
.matches(it
.key())) {
815 newVisibleItems
.append(it
.value());
817 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
818 // We will go up through its parental chain until we either:
819 // 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
820 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
821 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
822 parent
= parent
->parent
) {
823 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
824 // and it would mess up the iteration. We will mark it to be removed in step 3.
825 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
828 it
= m_filteredItems
.erase(it
);
830 // Item remains filtered for now
831 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
837 // Handles the ancestorsOfNewVisibleItems.
838 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
839 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
840 if (m_filteredItems
.remove(it
.key())) {
841 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
842 newVisibleItems
.append(it
.value());
846 // This will insert the newly discovered unfiltered items into m_itemData
847 insertItems(newVisibleItems
);
850 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
852 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
853 // There are either no filtered items, or it is not possible to expand
854 // folders -> there cannot be any filtered children.
858 QSet
<ItemData
*> parents
;
859 for (const KItemRange
&range
: itemRanges
) {
860 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
861 parents
.insert(m_itemData
.at(index
));
865 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
866 while (it
!= m_filteredItems
.end()) {
867 if (parents
.contains(it
.value()->parent
)) {
869 it
= m_filteredItems
.erase(it
);
876 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
878 static QList
<RoleInfo
> rolesInfo
;
879 if (rolesInfo
.isEmpty()) {
881 const RoleInfoMap
*map
= rolesInfoMap(count
);
882 for (int i
= 0; i
< count
; ++i
) {
883 if (map
[i
].roleType
!= NoRole
) {
885 info
.role
= map
[i
].role
;
886 info
.translation
= map
[i
].roleTranslation
.toString();
887 if (!map
[i
].groupTranslation
.isEmpty()) {
888 info
.group
= map
[i
].groupTranslation
.toString();
890 // For top level roles, groupTranslation is 0. We must make sure that
891 // info.group is an empty string then because the code that generates
892 // menus tries to put the actions into sub menus otherwise.
893 info
.group
= QString();
895 info
.requiresBaloo
= map
[i
].requiresBaloo
;
896 info
.requiresIndexer
= map
[i
].requiresIndexer
;
897 if (!map
[i
].tooltipTranslation
.isEmpty()) {
898 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
900 info
.tooltip
= QString();
902 rolesInfo
.append(info
);
910 void KFileItemModel::onGroupedSortingChanged(bool current
)
916 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
919 m_sortRole
= typeForRole(current
);
921 if (!m_requestRole
[m_sortRole
]) {
922 QSet
<QByteArray
> newRoles
= m_roles
;
932 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
939 void KFileItemModel::loadSortingSettings()
941 using Choice
= GeneralSettings::EnumSortingChoice
;
942 switch (GeneralSettings::sortingChoice()) {
943 case Choice::NaturalSorting
:
944 m_naturalSorting
= true;
945 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
947 case Choice::CaseSensitiveSorting
:
948 m_naturalSorting
= false;
949 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
951 case Choice::CaseInsensitiveSorting
:
952 m_naturalSorting
= false;
953 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
958 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
959 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
960 m_collator
.compare(QString(), QString());
963 void KFileItemModel::resortAllItems()
965 m_resortAllItemsTimer
->stop();
967 const int itemCount
= count();
968 if (itemCount
<= 0) {
972 #ifdef KFILEITEMMODEL_DEBUG
975 qCDebug(DolphinDebug
) << "===========================================================";
976 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
979 // Remember the order of the current URLs so
980 // that it can be determined which indexes have
981 // been moved because of the resorting.
983 oldUrls
.reserve(itemCount
);
984 for (const ItemData
*itemData
: qAsConst(m_itemData
)) {
985 oldUrls
.append(itemData
->item
.url());
989 m_items
.reserve(itemCount
);
992 sort(m_itemData
.begin(), m_itemData
.end());
993 for (int i
= 0; i
< itemCount
; ++i
) {
994 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
997 // Determine the first index that has been moved.
998 int firstMovedIndex
= 0;
999 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1003 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1004 if (itemsHaveMoved
) {
1007 int lastMovedIndex
= itemCount
- 1;
1008 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1012 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1014 // Create a list movedToIndexes, which has the property that
1015 // movedToIndexes[i] is the new index of the item with the old index
1016 // firstMovedIndex + i.
1017 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1018 QList
<int> movedToIndexes
;
1019 movedToIndexes
.reserve(movedItemsCount
);
1020 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1021 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1022 movedToIndexes
.append(newIndex
);
1025 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1026 } else if (groupedSorting()) {
1027 // The groups might have changed even if the order of the items has not.
1028 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1030 if (groups() != oldGroups
) {
1031 Q_EMIT
groupsChanged();
1035 #ifdef KFILEITEMMODEL_DEBUG
1036 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1040 void KFileItemModel::slotCompleted()
1042 m_maximumUpdateIntervalTimer
->stop();
1043 dispatchPendingItemsToInsert();
1045 if (!m_urlsToExpand
.isEmpty()) {
1046 // Try to find a URL that can be expanded.
1047 // Note that the parent folder must be expanded before any of its subfolders become visible.
1048 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1049 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1050 // Iterate over a const copy because items are deleted and inserted within the loop
1051 const auto urlsToExpand
= m_urlsToExpand
;
1052 for (const QUrl
&url
: urlsToExpand
) {
1053 const int indexForUrl
= index(url
);
1054 if (indexForUrl
>= 0) {
1055 m_urlsToExpand
.remove(url
);
1056 if (setExpanded(indexForUrl
, true)) {
1057 // The dir lister has been triggered. This slot will be called
1058 // again after the directory has been expanded.
1064 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1065 // if these URLs have been deleted in the meantime.
1066 m_urlsToExpand
.clear();
1069 Q_EMIT
directoryLoadingCompleted();
1072 void KFileItemModel::slotCanceled()
1074 m_maximumUpdateIntervalTimer
->stop();
1075 dispatchPendingItemsToInsert();
1077 Q_EMIT
directoryLoadingCanceled();
1080 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1082 Q_ASSERT(!items
.isEmpty());
1084 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1086 if (m_requestRole
[ExpandedParentsCountRole
]) {
1087 // If the expanding of items is enabled, the call
1088 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1089 // might result in emitting the same items twice due to the Keep-parameter.
1090 // This case happens if an item gets expanded, collapsed and expanded again
1091 // before the items could be loaded for the first expansion.
1092 if (index(items
.first().url()) >= 0) {
1093 // The items are already part of the model.
1097 if (directoryUrl
!= directory()) {
1098 // To be able to compare whether the new items may be inserted as children
1099 // of a parent item the pending items must be added to the model first.
1100 dispatchPendingItemsToInsert();
1103 // KDirLister keeps the children of items that got expanded once even if
1104 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1105 // checked whether the parent for new items is still expanded.
1106 const int parentIndex
= index(parentUrl
);
1107 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1108 // The parent is not expanded.
1113 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1115 if (!m_filter
.hasSetFilters()) {
1116 m_pendingItemsToInsert
.append(itemDataList
);
1118 QSet
<ItemData
*> parentsToEnsureVisible
;
1120 // The name or type filter is active. Hide filtered items
1121 // before inserting them into the model and remember
1122 // the filtered items in m_filteredItems.
1123 for (ItemData
*itemData
: itemDataList
) {
1124 if (m_filter
.matches(itemData
->item
)) {
1125 m_pendingItemsToInsert
.append(itemData
);
1126 if (itemData
->parent
) {
1127 parentsToEnsureVisible
.insert(itemData
->parent
);
1130 m_filteredItems
.insert(itemData
->item
, itemData
);
1134 // Entire parental chains must be shown
1135 for (ItemData
*parent
: parentsToEnsureVisible
) {
1136 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1137 m_pendingItemsToInsert
.append(parent
);
1142 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1143 // Assure that items get dispatched if no completed() or canceled() signal is
1144 // emitted during the maximum update interval.
1145 m_maximumUpdateIntervalTimer
->start();
1148 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1151 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1153 int filteredParentsCount
= 0;
1154 // The childless parents not yet removed will always be right above the start of a removed range.
1155 // We iterate backwards to ensure the deepest folders are processed before their parents
1156 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1157 KItemRange itemRange
= removedItemRanges
.at(i
);
1158 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1159 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1160 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1162 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1163 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1164 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1165 // and this deleted range covers all of its descendents, so none will be left.
1166 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1167 // This range's starting index will be extended to include the parent above:
1170 ++filteredParentsCount
;
1171 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1172 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1173 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1174 previousRange
.count
+= itemRange
.count
;
1175 removedItemRanges
.replace(i
- 1, previousRange
);
1176 removedItemRanges
.removeAt(i
);
1178 removedItemRanges
.replace(i
, itemRange
);
1179 // We must revisit this range in the next iteration since its starting index changed
1184 return filteredParentsCount
;
1187 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1189 dispatchPendingItemsToInsert();
1191 QVector
<int> indexesToRemove
;
1192 indexesToRemove
.reserve(items
.count());
1193 KFileItemList dirsChanged
;
1195 const auto currentDir
= directory();
1197 for (const KFileItem
&item
: items
) {
1198 if (item
.url() == currentDir
) {
1199 Q_EMIT
currentDirectoryRemoved();
1203 const int indexForItem
= index(item
);
1204 if (indexForItem
>= 0) {
1205 indexesToRemove
.append(indexForItem
);
1207 // Probably the item has been filtered.
1208 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1209 if (it
!= m_filteredItems
.end()) {
1211 m_filteredItems
.erase(it
);
1215 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1216 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1217 dirsChanged
<< KFileItem(parentUrl
);
1221 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1223 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1224 // Assure that removing a parent item also results in removing all children
1225 QVector
<int> indexesToRemoveWithChildren
;
1226 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1228 const int itemCount
= m_itemData
.count();
1229 for (int index
: qAsConst(indexesToRemove
)) {
1230 indexesToRemoveWithChildren
.append(index
);
1232 const int parentLevel
= expandedParentsCount(index
);
1233 int childIndex
= index
+ 1;
1234 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1235 indexesToRemoveWithChildren
.append(childIndex
);
1240 indexesToRemove
= indexesToRemoveWithChildren
;
1243 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1244 removeFilteredChildren(itemRanges
);
1246 // This call will update itemRanges to include the childless parents that have been filtered.
1247 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1249 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1250 // mixed with expanded folders that are just being filtered out.
1251 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1252 // so removeItems() will check m_filteredItems to differentiate which is which.
1253 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1255 Q_EMIT
fileItemsChanged(dirsChanged
);
1258 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1260 Q_ASSERT(!items
.isEmpty());
1261 #ifdef KFILEITEMMODEL_DEBUG
1262 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1265 // Get the indexes of all items that have been refreshed
1267 indexes
.reserve(items
.count());
1269 QSet
<QByteArray
> changedRoles
;
1270 KFileItemList changedFiles
;
1272 // Contains the indexes of the currently visible items
1273 // that should get hidden and hence moved to m_filteredItems.
1274 QVector
<int> newFilteredIndexes
;
1276 // Contains currently hidden items that should
1277 // get visible and hence removed from m_filteredItems
1278 QList
<ItemData
*> newVisibleItems
;
1280 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1282 while (it
.hasNext()) {
1283 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1284 const KFileItem
&oldItem
= itemPair
.first
;
1285 const KFileItem
&newItem
= itemPair
.second
;
1286 const int indexForItem
= index(oldItem
);
1287 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1288 if (indexForItem
>= 0) {
1289 m_itemData
[indexForItem
]->item
= newItem
;
1291 // Keep old values as long as possible if they could not retrieved synchronously yet.
1292 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1293 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1294 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1295 while (it
.hasNext()) {
1297 const QByteArray
&role
= it
.key();
1298 if (itemData
->values
.value(role
) != it
.value()) {
1299 itemData
->values
.insert(role
, it
.value());
1300 changedRoles
.insert(role
);
1304 m_items
.remove(oldItem
.url());
1305 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1306 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1307 m_items
.insert(newItem
.url(), indexForItem
);
1308 if (newItemMatchesFilter
1309 || (itemData
->values
.value("isExpanded").toBool()
1310 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1311 // We are lenient with expanded folders that originally had visible children.
1312 // If they become childless now they will be caught by filterChildlessParents()
1313 changedFiles
.append(newItem
);
1314 indexes
.append(indexForItem
);
1316 newFilteredIndexes
.append(indexForItem
);
1317 m_filteredItems
.insert(newItem
, itemData
);
1320 // Check if 'oldItem' is one of the filtered items.
1321 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1322 if (it
!= m_filteredItems
.end()) {
1323 ItemData
*const itemData
= it
.value();
1324 itemData
->item
= newItem
;
1326 // The data stored in 'values' might have changed. Therefore, we clear
1327 // 'values' and re-populate it the next time it is requested via data(int).
1328 // Before clearing, we must remember if it was expanded and the expanded parents count,
1329 // otherwise these states would be lost. The data() method will deal with this special case.
1330 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1331 bool hasExpandedParentsCount
= false;
1332 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1333 itemData
->values
.clear();
1335 itemData
->values
.insert("isExpanded", true);
1336 if (hasExpandedParentsCount
) {
1337 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1341 m_filteredItems
.erase(it
);
1342 if (newItemMatchesFilter
) {
1343 newVisibleItems
.append(itemData
);
1345 m_filteredItems
.insert(newItem
, itemData
);
1351 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1353 // We must keep track of parents of new visible items since they must be shown no matter what
1354 // They will be considered "immune" to filterChildlessParents()
1355 QSet
<ItemData
*> parentsToEnsureVisible
;
1357 for (ItemData
*item
: newVisibleItems
) {
1358 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1359 parentsToEnsureVisible
.insert(parent
);
1362 for (ItemData
*parent
: parentsToEnsureVisible
) {
1363 // We make sure they are all unfiltered.
1364 if (m_filteredItems
.remove(parent
->item
)) {
1365 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1366 newVisibleItems
.append(parent
);
1367 // It could be in newFilteredIndexes, we must remove it if it's there:
1368 const int parentIndex
= index(parent
->item
);
1369 if (parentIndex
>= 0) {
1370 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1371 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1372 newFilteredIndexes
.erase(it
);
1378 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1380 // This call will update itemRanges to include the childless parents that have been filtered.
1381 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1383 removeItems(removedRanges
, KeepItemData
);
1385 // Show previously hidden items that should get visible
1386 insertItems(newVisibleItems
);
1388 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1390 // If the changed items have been created recently, they might not be in m_items yet.
1391 // In that case, the list 'indexes' might be empty.
1392 if (indexes
.isEmpty()) {
1396 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1397 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1399 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1400 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1401 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1402 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1407 std::sort(indexes
.begin(), indexes
.end());
1410 // Extract the item-ranges out of the changed indexes
1411 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1412 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1414 Q_EMIT
fileItemsChanged(changedFiles
);
1417 void KFileItemModel::slotClear()
1419 #ifdef KFILEITEMMODEL_DEBUG
1420 qCDebug(DolphinDebug
) << "Clearing all items";
1423 qDeleteAll(m_filteredItems
);
1424 m_filteredItems
.clear();
1427 m_maximumUpdateIntervalTimer
->stop();
1428 m_resortAllItemsTimer
->stop();
1430 qDeleteAll(m_pendingItemsToInsert
);
1431 m_pendingItemsToInsert
.clear();
1433 const int removedCount
= m_itemData
.count();
1434 if (removedCount
> 0) {
1435 qDeleteAll(m_itemData
);
1438 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1441 m_expandedDirs
.clear();
1444 void KFileItemModel::slotSortingChoiceChanged()
1446 loadSortingSettings();
1450 void KFileItemModel::dispatchPendingItemsToInsert()
1452 if (!m_pendingItemsToInsert
.isEmpty()) {
1453 insertItems(m_pendingItemsToInsert
);
1454 m_pendingItemsToInsert
.clear();
1458 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1460 if (newItems
.isEmpty()) {
1464 #ifdef KFILEITEMMODEL_DEBUG
1465 QElapsedTimer timer
;
1467 qCDebug(DolphinDebug
) << "===========================================================";
1468 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1472 prepareItemsForSorting(newItems
);
1474 // Natural sorting of items can be very slow. However, it becomes much faster
1475 // if the input sequence is already mostly sorted. Therefore, we first sort
1476 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1477 if (m_naturalSorting
) {
1478 if (m_sortRole
== NameRole
) {
1479 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1480 } else if (isRoleValueNatural(m_sortRole
)) {
1481 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1482 const QByteArray role
= roleForType(m_sortRole
);
1483 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1485 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1489 sort(newItems
.begin(), newItems
.end());
1491 #ifdef KFILEITEMMODEL_DEBUG
1492 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1495 KItemRangeList itemRanges
;
1496 const int existingItemCount
= m_itemData
.count();
1497 const int newItemCount
= newItems
.count();
1498 const int totalItemCount
= existingItemCount
+ newItemCount
;
1500 if (existingItemCount
== 0) {
1501 // Optimization for the common special case that there are no
1502 // items in the model yet. Happens, e.g., when entering a folder.
1503 m_itemData
= newItems
;
1504 itemRanges
<< KItemRange(0, newItemCount
);
1506 m_itemData
.reserve(totalItemCount
);
1507 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1508 m_itemData
.append(nullptr);
1511 // We build the new list m_itemData in reverse order to minimize
1512 // the number of moves and guarantee O(N) complexity.
1513 int targetIndex
= totalItemCount
- 1;
1514 int sourceIndexExistingItems
= existingItemCount
- 1;
1515 int sourceIndexNewItems
= newItemCount
- 1;
1519 while (sourceIndexNewItems
>= 0) {
1520 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1521 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1522 // Move an existing item to its new position. If any new items
1523 // are behind it, push the item range to itemRanges.
1524 if (rangeCount
> 0) {
1525 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1529 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1530 --sourceIndexExistingItems
;
1532 // Insert a new item into the list.
1534 m_itemData
[targetIndex
] = newItem
;
1535 --sourceIndexNewItems
;
1540 // Push the final item range to itemRanges.
1541 if (rangeCount
> 0) {
1542 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1545 // Note that itemRanges is still sorted in reverse order.
1546 std::reverse(itemRanges
.begin(), itemRanges
.end());
1549 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1550 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1553 Q_EMIT
itemsInserted(itemRanges
);
1555 #ifdef KFILEITEMMODEL_DEBUG
1556 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1560 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1562 if (itemRanges
.isEmpty()) {
1568 // Step 1: Remove the items from m_itemData, and free the ItemData.
1569 int removedItemsCount
= 0;
1570 for (const KItemRange
&range
: itemRanges
) {
1571 removedItemsCount
+= range
.count
;
1573 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1574 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1575 delete m_itemData
.at(index
);
1578 m_itemData
[index
] = nullptr;
1582 // Step 2: Remove the ItemData pointers from the list m_itemData.
1583 int target
= itemRanges
.at(0).index
;
1584 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1587 const int oldItemDataCount
= m_itemData
.count();
1588 while (source
< oldItemDataCount
) {
1589 m_itemData
[target
] = m_itemData
[source
];
1593 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1594 // Skip the items in the next removed range.
1595 source
+= itemRanges
.at(nextRange
).count
;
1600 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1602 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1603 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1606 Q_EMIT
itemsRemoved(itemRanges
);
1609 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1611 if (m_sortRole
== TypeRole
) {
1612 // Try to resolve the MIME-types synchronously to prevent a reordering of
1613 // the items when sorting by type (per default MIME-types are resolved
1614 // asynchronously by KFileItemModelRolesUpdater).
1615 determineMimeTypes(items
, 200);
1618 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1619 const int parentIndex
= index(parentUrl
);
1620 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1622 QList
<ItemData
*> itemDataList
;
1623 itemDataList
.reserve(items
.count());
1625 for (const KFileItem
&item
: items
) {
1626 ItemData
*itemData
= new ItemData();
1627 itemData
->item
= item
;
1628 itemData
->parent
= parentItem
;
1629 itemDataList
.append(itemData
);
1632 return itemDataList
;
1635 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1637 switch (m_sortRole
) {
1639 case PermissionsRole
:
1642 case DestinationRole
:
1644 case DeletionTimeRole
:
1645 // These roles can be determined with retrieveData, and they have to be stored
1646 // in the QHash "values" for the sorting.
1647 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1648 if (itemData
->values
.isEmpty()) {
1649 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1655 // At least store the data including the file type for items with known MIME type.
1656 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1657 if (itemData
->values
.isEmpty()) {
1658 const KFileItem item
= itemData
->item
;
1659 if (item
.isDir() || item
.isMimeTypeKnown()) {
1660 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1667 // The other roles are either resolved by KFileItemModelRolesUpdater
1668 // (this includes the SizeRole for directories), or they do not need
1669 // to be stored in the QHash "values" for sorting because the data can
1670 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1676 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1678 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1679 // if the corresponding item is expanded, and it is not a top-level item.
1680 const ItemData
*parent
= data
->parent
;
1682 if (parent
->parent
) {
1683 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1684 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1693 void KFileItemModel::removeExpandedItems()
1695 QVector
<int> indexesToRemove
;
1697 const int maxIndex
= m_itemData
.count() - 1;
1698 for (int i
= 0; i
<= maxIndex
; ++i
) {
1699 const ItemData
*itemData
= m_itemData
.at(i
);
1700 if (itemData
->parent
) {
1701 indexesToRemove
.append(i
);
1705 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1706 m_expandedDirs
.clear();
1708 // Also remove all filtered items which have a parent.
1709 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1710 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1713 if (it
.value()->parent
) {
1715 it
= m_filteredItems
.erase(it
);
1722 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1724 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1726 // Trigger a resorting if necessary. Note that this can happen even if the sort
1727 // role has not changed at all because the file name can be used as a fallback.
1728 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1729 for (const KItemRange
&range
: itemRanges
) {
1730 bool needsResorting
= false;
1732 const int first
= range
.index
;
1733 const int last
= range
.index
+ range
.count
- 1;
1735 // Resorting the model is necessary if
1736 // (a) The first item in the range is "lessThan" its predecessor,
1737 // (b) the successor of the last item is "lessThan" the last item, or
1738 // (c) the internal order of the items in the range is incorrect.
1739 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1740 needsResorting
= true;
1741 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1742 needsResorting
= true;
1744 for (int index
= first
; index
< last
; ++index
) {
1745 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1746 needsResorting
= true;
1752 if (needsResorting
) {
1753 m_resortAllItemsTimer
->start();
1759 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1760 // The position is still correct, but the groups might have changed
1761 // if the changed item is either the first or the last item in a
1763 // In principle, we could try to find out if the item really is the
1764 // first or last one in its group and then update the groups
1765 // (possibly with a delayed timer to make sure that we don't
1766 // re-calculate the groups very often if items are updated one by
1767 // one), but starting m_resortAllItemsTimer is easier.
1768 m_resortAllItemsTimer
->start();
1772 void KFileItemModel::resetRoles()
1774 for (int i
= 0; i
< RolesCount
; ++i
) {
1775 m_requestRole
[i
] = false;
1779 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1781 static QHash
<QByteArray
, RoleType
> roles
;
1782 if (roles
.isEmpty()) {
1783 // Insert user visible roles that can be accessed with
1784 // KFileItemModel::roleInformation()
1786 const RoleInfoMap
*map
= rolesInfoMap(count
);
1787 for (int i
= 0; i
< count
; ++i
) {
1788 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1791 // Insert internal roles (take care to synchronize the implementation
1792 // with KFileItemModel::roleForType() in case if a change is done).
1793 roles
.insert("isDir", IsDirRole
);
1794 roles
.insert("isLink", IsLinkRole
);
1795 roles
.insert("isHidden", IsHiddenRole
);
1796 roles
.insert("isExpanded", IsExpandedRole
);
1797 roles
.insert("isExpandable", IsExpandableRole
);
1798 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1800 Q_ASSERT(roles
.count() == RolesCount
);
1803 return roles
.value(role
, NoRole
);
1806 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1808 static QHash
<RoleType
, QByteArray
> roles
;
1809 if (roles
.isEmpty()) {
1810 // Insert user visible roles that can be accessed with
1811 // KFileItemModel::roleInformation()
1813 const RoleInfoMap
*map
= rolesInfoMap(count
);
1814 for (int i
= 0; i
< count
; ++i
) {
1815 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1818 // Insert internal roles (take care to synchronize the implementation
1819 // with KFileItemModel::typeForRole() in case if a change is done).
1820 roles
.insert(IsDirRole
, "isDir");
1821 roles
.insert(IsLinkRole
, "isLink");
1822 roles
.insert(IsHiddenRole
, "isHidden");
1823 roles
.insert(IsExpandedRole
, "isExpanded");
1824 roles
.insert(IsExpandableRole
, "isExpandable");
1825 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1827 Q_ASSERT(roles
.count() == RolesCount
);
1830 return roles
.value(roleType
);
1833 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1835 // It is important to insert only roles that are fast to retrieve. E.g.
1836 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1837 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1838 QHash
<QByteArray
, QVariant
> data
;
1839 data
.insert(sharedValue("url"), item
.url());
1841 const bool isDir
= item
.isDir();
1842 if (m_requestRole
[IsDirRole
] && isDir
) {
1843 data
.insert(sharedValue("isDir"), true);
1846 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1847 data
.insert(sharedValue("isLink"), true);
1850 if (m_requestRole
[IsHiddenRole
]) {
1851 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1854 if (m_requestRole
[NameRole
]) {
1855 data
.insert(sharedValue("text"), item
.text());
1858 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1859 // TODO KF6 use KFileItem::suffix 464722
1860 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1863 if (m_requestRole
[SizeRole
] && !isDir
) {
1864 data
.insert(sharedValue("size"), item
.size());
1867 if (m_requestRole
[ModificationTimeRole
]) {
1868 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1869 // having several thousands of items. Instead read the raw number from UDSEntry directly
1870 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1871 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1872 data
.insert(sharedValue("modificationtime"), dateTime
);
1875 if (m_requestRole
[CreationTimeRole
]) {
1876 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1877 // having several thousands of items. Instead read the raw number from UDSEntry directly
1878 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1879 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1880 data
.insert(sharedValue("creationtime"), dateTime
);
1883 if (m_requestRole
[AccessTimeRole
]) {
1884 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1885 // having several thousands of items. Instead read the raw number from UDSEntry directly
1886 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1887 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1888 data
.insert(sharedValue("accesstime"), dateTime
);
1891 if (m_requestRole
[PermissionsRole
]) {
1892 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1895 if (m_requestRole
[OwnerRole
]) {
1896 data
.insert(sharedValue("owner"), item
.user());
1899 if (m_requestRole
[GroupRole
]) {
1900 data
.insert(sharedValue("group"), item
.group());
1903 if (m_requestRole
[DestinationRole
]) {
1904 QString destination
= item
.linkDest();
1905 if (destination
.isEmpty()) {
1906 destination
= QLatin1Char('-');
1908 data
.insert(sharedValue("destination"), destination
);
1911 if (m_requestRole
[PathRole
]) {
1913 if (item
.url().scheme() == QLatin1String("trash")) {
1914 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1916 // For performance reasons cache the home-path in a static QString
1917 // (see QDir::homePath() for more details)
1918 static QString homePath
;
1919 if (homePath
.isEmpty()) {
1920 homePath
= QDir::homePath();
1923 path
= item
.localPath();
1924 if (path
.startsWith(homePath
)) {
1925 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1929 const int index
= path
.lastIndexOf(item
.text());
1930 path
= path
.mid(0, index
- 1);
1931 data
.insert(sharedValue("path"), path
);
1934 if (m_requestRole
[DeletionTimeRole
]) {
1935 QDateTime deletionTime
;
1936 if (item
.url().scheme() == QLatin1String("trash")) {
1937 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1939 data
.insert(sharedValue("deletiontime"), deletionTime
);
1942 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1943 data
.insert(sharedValue("isExpandable"), true);
1946 if (m_requestRole
[ExpandedParentsCountRole
]) {
1948 const int level
= expandedParentsCount(parent
) + 1;
1949 data
.insert(sharedValue("expandedParentsCount"), level
);
1953 if (item
.isMimeTypeKnown()) {
1954 QString iconName
= item
.iconName();
1955 if (!QIcon::hasThemeIcon(iconName
)) {
1956 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1957 iconName
= mimeType
.genericIconName();
1960 data
.insert(sharedValue("iconName"), iconName
);
1962 if (m_requestRole
[TypeRole
]) {
1963 data
.insert(sharedValue("type"), item
.mimeComment());
1965 } else if (m_requestRole
[TypeRole
] && isDir
) {
1966 static const QString folderMimeType
= item
.mimeComment();
1967 data
.insert(sharedValue("type"), folderMimeType
);
1973 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1977 if (a
->parent
!= b
->parent
) {
1978 const int expansionLevelA
= expandedParentsCount(a
);
1979 const int expansionLevelB
= expandedParentsCount(b
);
1981 // If b has a higher expansion level than a, check if a is a parent
1982 // of b, and make sure that both expansion levels are equal otherwise.
1983 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1984 if (b
->parent
== a
) {
1990 // If a has a higher expansion level than a, check if b is a parent
1991 // of a, and make sure that both expansion levels are equal otherwise.
1992 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1993 if (a
->parent
== b
) {
1999 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2001 // Compare the last parents of a and b which are different.
2002 while (a
->parent
!= b
->parent
) {
2008 // Show hidden files and folders last
2009 if (m_sortHiddenLast
) {
2010 const bool isHiddenA
= a
->item
.isHidden();
2011 const bool isHiddenB
= b
->item
.isHidden();
2012 if (isHiddenA
&& !isHiddenB
) {
2014 } else if (!isHiddenA
&& isHiddenB
) {
2019 if (m_sortDirsFirst
|| (ContentDisplaySettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
2020 const bool isDirA
= a
->item
.isDir();
2021 const bool isDirB
= b
->item
.isDir();
2022 if (isDirA
&& !isDirB
) {
2024 } else if (!isDirA
&& isDirB
) {
2029 result
= sortRoleCompare(a
, b
, collator
);
2031 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2034 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2036 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2037 return lessThan(a
, b
, m_collator
);
2040 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2041 // Sorting by string can be expensive, in particular if natural sorting is
2042 // enabled. Use all CPU cores to speed up the sorting process.
2043 static const int numberOfThreads
= QThread::idealThreadCount();
2044 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2046 // Sorting by other roles is quite fast. Use only one thread to prevent
2047 // problems caused by non-reentrant comparison functions, see
2048 // https://bugs.kde.org/show_bug.cgi?id=312679
2049 mergeSort(begin
, end
, lambdaLessThan
);
2053 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2055 // This function must never return 0, because that would break stable
2056 // sorting, which leads to all kinds of bugs.
2057 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2058 // If two items have equal sort values, let the fallbacks at the bottom of
2059 // the function handle it.
2060 const KFileItem
&itemA
= a
->item
;
2061 const KFileItem
&itemB
= b
->item
;
2065 switch (m_sortRole
) {
2067 // The name role is handled as default fallback after the switch
2071 if (ContentDisplaySettings::directorySizeCount() && itemA
.isDir()) {
2072 // folders first then
2073 // items A and B are folders thanks to lessThan checks
2074 auto valueA
= a
->values
.value("count");
2075 auto valueB
= b
->values
.value("count");
2076 if (valueA
.isNull()) {
2077 if (!valueB
.isNull()) {
2080 } else if (valueB
.isNull()) {
2083 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2085 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2092 KIO::filesize_t sizeA
= 0;
2093 if (itemA
.isDir()) {
2094 sizeA
= a
->values
.value("size").toULongLong();
2096 sizeA
= itemA
.size();
2098 KIO::filesize_t sizeB
= 0;
2099 if (itemB
.isDir()) {
2100 sizeB
= b
->values
.value("size").toULongLong();
2102 sizeB
= itemB
.size();
2104 if (sizeA
< sizeB
) {
2106 } else if (sizeA
> sizeB
) {
2112 case ModificationTimeRole
: {
2113 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2114 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2115 if (dateTimeA
< dateTimeB
) {
2117 } else if (dateTimeA
> dateTimeB
) {
2123 case AccessTimeRole
: {
2124 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2125 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2126 if (dateTimeA
< dateTimeB
) {
2128 } else if (dateTimeA
> dateTimeB
) {
2134 case CreationTimeRole
: {
2135 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2136 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2137 if (dateTimeA
< dateTimeB
) {
2139 } else if (dateTimeA
> dateTimeB
) {
2145 case DeletionTimeRole
: {
2146 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2147 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2148 if (dateTimeA
< dateTimeB
) {
2150 } else if (dateTimeA
> dateTimeB
) {
2164 case ReleaseYearRole
: {
2165 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2169 case DimensionsRole
: {
2170 const QByteArray role
= roleForType(m_sortRole
);
2171 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2172 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2174 if (dimensionsA
.width() == dimensionsB
.width()) {
2175 result
= dimensionsA
.height() - dimensionsB
.height();
2177 result
= dimensionsA
.width() - dimensionsB
.width();
2183 const QByteArray role
= roleForType(m_sortRole
);
2184 const QString roleValueA
= a
->values
.value(role
).toString();
2185 const QString roleValueB
= b
->values
.value(role
).toString();
2186 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2188 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2190 } else if (isRoleValueNatural(m_sortRole
)) {
2191 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2193 result
= QString::compare(roleValueA
, roleValueB
);
2200 // The current sort role was sufficient to define an order
2204 // Fallback #1: Compare the text of the items
2205 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2210 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2211 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2216 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2217 // equal. In this case a comparison of the URL is done which is unique in all cases
2218 // within KDirLister.
2219 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2222 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2224 QMutexLocker
collatorLock(s_collatorMutex());
2226 if (m_naturalSorting
) {
2227 return collator
.compare(a
, b
);
2230 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2231 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2232 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2233 // comparison, still a deterministic sort order is required. A case sensitive
2234 // comparison is done as fallback.
2238 return QString::compare(a
, b
, Qt::CaseSensitive
);
2241 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2243 Q_ASSERT(!m_itemData
.isEmpty());
2245 const int maxIndex
= count() - 1;
2246 QList
<QPair
<int, QVariant
>> groups
;
2250 for (int i
= 0; i
<= maxIndex
; ++i
) {
2251 if (isChildItem(i
)) {
2255 const QString name
= m_itemData
.at(i
)->item
.text();
2257 // Use the first character of the name as group indication
2258 QChar newFirstChar
= name
.at(0).toUpper();
2259 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2260 newFirstChar
= name
.at(1).toUpper();
2263 if (firstChar
!= newFirstChar
) {
2264 QString newGroupValue
;
2265 if (newFirstChar
.isLetter()) {
2266 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2267 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2269 // Try to find a matching group in the range 'A' to 'Z'.
2270 static std::vector
<QChar
> lettersAtoZ
;
2271 lettersAtoZ
.reserve('Z' - 'A' + 1);
2272 if (lettersAtoZ
.empty()) {
2273 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2274 lettersAtoZ
.push_back(QLatin1Char(c
));
2278 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2279 return m_collator
.compare(c1
, c2
) < 0;
2282 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2283 if (it
!= lettersAtoZ
.end()) {
2284 if (localeAwareLessThan(newFirstChar
, *it
)) {
2285 // newFirstChar belongs to the group preceding *it.
2286 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2289 newGroupValue
= *it
;
2293 // Symbols from non Latin-based scripts
2294 newGroupValue
= newFirstChar
;
2296 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2297 // Apply group '0 - 9' for any name that starts with a digit
2298 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2300 newGroupValue
= i18nc("@title:group", "Others");
2303 if (newGroupValue
!= groupValue
) {
2304 groupValue
= newGroupValue
;
2305 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2308 firstChar
= newFirstChar
;
2314 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2316 Q_ASSERT(!m_itemData
.isEmpty());
2318 const int maxIndex
= count() - 1;
2319 QList
<QPair
<int, QVariant
>> groups
;
2322 for (int i
= 0; i
<= maxIndex
; ++i
) {
2323 if (isChildItem(i
)) {
2327 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2328 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2329 QString newGroupValue
;
2330 if (!item
.isNull() && item
.isDir()) {
2331 if (ContentDisplaySettings::directorySizeCount() || m_sortDirsFirst
) {
2332 newGroupValue
= i18nc("@title:group Size", "Folders");
2334 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2338 if (newGroupValue
.isEmpty()) {
2339 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2340 newGroupValue
= i18nc("@title:group Size", "Small");
2341 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2342 newGroupValue
= i18nc("@title:group Size", "Medium");
2344 newGroupValue
= i18nc("@title:group Size", "Big");
2348 if (newGroupValue
!= groupValue
) {
2349 groupValue
= newGroupValue
;
2350 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2357 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2359 Q_ASSERT(!m_itemData
.isEmpty());
2361 const int maxIndex
= count() - 1;
2362 QList
<QPair
<int, QVariant
>> groups
;
2364 const QDate currentDate
= QDate::currentDate();
2366 QDate previousFileDate
;
2368 for (int i
= 0; i
<= maxIndex
; ++i
) {
2369 if (isChildItem(i
)) {
2373 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2374 const QDate fileDate
= fileTime
.date();
2375 if (fileDate
== previousFileDate
) {
2376 // The current item is in the same group as the previous item
2379 previousFileDate
= fileDate
;
2381 const int daysDistance
= fileDate
.daysTo(currentDate
);
2383 QString newGroupValue
;
2384 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2385 switch (daysDistance
/ 7) {
2387 switch (daysDistance
) {
2389 newGroupValue
= i18nc("@title:group Date", "Today");
2392 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2395 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2396 newGroupValue
= i18nc(
2397 "Can be used to script translation of \"dddd\""
2398 "with context @title:group Date",
2404 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2407 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2410 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2414 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2420 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2421 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2422 if (daysDistance
== 1) {
2423 const KLocalizedString format
= ki18nc(
2424 "@title:group Date: "
2425 "MMMM is full month name in current locale, and yyyy is "
2426 "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 "
2427 "part of the text that should not be formatted as a date",
2428 "'Yesterday' (MMMM, yyyy)");
2429 const QString translatedFormat
= format
.toString();
2430 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2431 newGroupValue
= fileTime
.toString(translatedFormat
);
2432 newGroupValue
= i18nc(
2433 "Can be used to script translation of "
2434 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2438 qCWarning(DolphinDebug
).nospace()
2439 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2440 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2441 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2443 } else if (daysDistance
<= 7) {
2445 fileTime
.toString(i18nc("@title:group Date: "
2446 "The week day name: dddd, MMMM is full month name "
2447 "in current locale, and yyyy is full year number.",
2448 "dddd (MMMM, yyyy)"));
2449 newGroupValue
= i18nc(
2450 "Can be used to script translation of "
2451 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2454 } else if (daysDistance
<= 7 * 2) {
2455 const KLocalizedString format
= ki18nc(
2456 "@title:group Date: "
2457 "MMMM is full month name in current locale, and yyyy is "
2458 "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 "
2459 "part of the text that should not be formatted as a date",
2460 "'One Week Ago' (MMMM, yyyy)");
2461 const QString translatedFormat
= format
.toString();
2462 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2463 newGroupValue
= fileTime
.toString(translatedFormat
);
2464 newGroupValue
= i18nc(
2465 "Can be used to script translation of "
2466 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2470 qCWarning(DolphinDebug
).nospace()
2471 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2472 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2473 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2475 } else if (daysDistance
<= 7 * 3) {
2476 const KLocalizedString format
= ki18nc(
2477 "@title:group Date: "
2478 "MMMM is full month name in current locale, and yyyy is "
2479 "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 "
2480 "part of the text that should not be formatted as a date",
2481 "'Two Weeks Ago' (MMMM, yyyy)");
2482 const QString translatedFormat
= format
.toString();
2483 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2484 newGroupValue
= fileTime
.toString(translatedFormat
);
2485 newGroupValue
= i18nc(
2486 "Can be used to script translation of "
2487 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2491 qCWarning(DolphinDebug
).nospace()
2492 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2493 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2494 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2496 } else if (daysDistance
<= 7 * 4) {
2497 const KLocalizedString format
= ki18nc(
2498 "@title:group Date: "
2499 "MMMM is full month name in current locale, and yyyy is "
2500 "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 "
2501 "part of the text that should not be formatted as a date",
2502 "'Three Weeks Ago' (MMMM, yyyy)");
2503 const QString translatedFormat
= format
.toString();
2504 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2505 newGroupValue
= fileTime
.toString(translatedFormat
);
2506 newGroupValue
= i18nc(
2507 "Can be used to script translation of "
2508 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2512 qCWarning(DolphinDebug
).nospace()
2513 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2514 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2515 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2518 const KLocalizedString format
= ki18nc(
2519 "@title:group Date: "
2520 "MMMM is full month name in current locale, and yyyy is "
2521 "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 "
2522 "part of the text that should not be formatted as a date",
2523 "'Earlier on' MMMM, yyyy");
2524 const QString translatedFormat
= format
.toString();
2525 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2526 newGroupValue
= fileTime
.toString(translatedFormat
);
2527 newGroupValue
= i18nc(
2528 "Can be used to script translation of "
2529 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2533 qCWarning(DolphinDebug
).nospace()
2534 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2535 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2536 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2541 fileTime
.toString(i18nc("@title:group "
2542 "The month and year: MMMM is full month name in current locale, "
2543 "and yyyy is full year number",
2545 newGroupValue
= i18nc(
2546 "Can be used to script translation of "
2547 "\"MMMM, yyyy\" with context @title:group Date",
2553 if (newGroupValue
!= groupValue
) {
2554 groupValue
= newGroupValue
;
2555 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2562 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2564 Q_ASSERT(!m_itemData
.isEmpty());
2566 const int maxIndex
= count() - 1;
2567 QList
<QPair
<int, QVariant
>> groups
;
2569 QString permissionsString
;
2571 for (int i
= 0; i
<= maxIndex
; ++i
) {
2572 if (isChildItem(i
)) {
2576 const ItemData
*itemData
= m_itemData
.at(i
);
2577 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2578 if (newPermissionsString
== permissionsString
) {
2581 permissionsString
= newPermissionsString
;
2583 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2587 if (info
.permission(QFile::ReadUser
)) {
2588 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2590 if (info
.permission(QFile::WriteUser
)) {
2591 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2593 if (info
.permission(QFile::ExeUser
)) {
2594 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2596 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2600 if (info
.permission(QFile::ReadGroup
)) {
2601 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2603 if (info
.permission(QFile::WriteGroup
)) {
2604 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2606 if (info
.permission(QFile::ExeGroup
)) {
2607 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2609 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2611 // Set others string
2613 if (info
.permission(QFile::ReadOther
)) {
2614 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2616 if (info
.permission(QFile::WriteOther
)) {
2617 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2619 if (info
.permission(QFile::ExeOther
)) {
2620 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2622 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2624 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2625 if (newGroupValue
!= groupValue
) {
2626 groupValue
= newGroupValue
;
2627 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2634 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2636 Q_ASSERT(!m_itemData
.isEmpty());
2638 const int maxIndex
= count() - 1;
2639 QList
<QPair
<int, QVariant
>> groups
;
2641 int groupValue
= -1;
2642 for (int i
= 0; i
<= maxIndex
; ++i
) {
2643 if (isChildItem(i
)) {
2646 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2647 if (newGroupValue
!= groupValue
) {
2648 groupValue
= newGroupValue
;
2649 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2656 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2658 Q_ASSERT(!m_itemData
.isEmpty());
2660 const int maxIndex
= count() - 1;
2661 QList
<QPair
<int, QVariant
>> groups
;
2663 bool isFirstGroupValue
= true;
2665 for (int i
= 0; i
<= maxIndex
; ++i
) {
2666 if (isChildItem(i
)) {
2669 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2670 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2671 groupValue
= newGroupValue
;
2672 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2673 isFirstGroupValue
= false;
2680 void KFileItemModel::emitSortProgress(int resolvedCount
)
2682 // Be tolerant against a resolvedCount with a wrong range.
2683 // Although there should not be a case where KFileItemModelRolesUpdater
2684 // (= caller) provides a wrong range, it is important to emit
2685 // a useful progress information even if there is an unexpected
2686 // implementation issue.
2688 const int itemCount
= count();
2689 if (resolvedCount
>= itemCount
) {
2690 m_sortingProgressPercent
= -1;
2691 if (m_resortAllItemsTimer
->isActive()) {
2692 m_resortAllItemsTimer
->stop();
2696 Q_EMIT
directorySortingProgress(100);
2697 } else if (itemCount
> 0) {
2698 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2700 const int progress
= resolvedCount
* 100 / itemCount
;
2701 if (m_sortingProgressPercent
!= progress
) {
2702 m_sortingProgressPercent
= progress
;
2703 Q_EMIT
directorySortingProgress(progress
);
2708 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2710 static const RoleInfoMap rolesInfoMap
[] = {
2712 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2713 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2714 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2715 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2716 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2717 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2718 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2719 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2720 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2721 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2722 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2723 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2724 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2725 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2726 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2727 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2728 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2729 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2730 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2731 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2732 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2733 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2734 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2735 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2736 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2737 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2738 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2739 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2740 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2741 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2742 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2743 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2744 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2745 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2746 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2747 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2748 { "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 },
2749 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2750 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2754 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2755 return rolesInfoMap
;
2758 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2760 QElapsedTimer timer
;
2762 for (const KFileItem
&item
: items
) {
2763 // Only determine mime types for files here. For directories,
2764 // KFileItem::determineMimeType() reads the .directory file inside to
2765 // load the icon, but this is not necessary at all if we just need the
2766 // type. Some special code for setting the correct mime type for
2767 // directories is in retrieveData().
2768 if (!item
.isDir()) {
2769 item
.determineMimeType();
2772 if (timer
.elapsed() > timeout
) {
2773 // Don't block the user interface, let the remaining items
2774 // be resolved asynchronously.
2780 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2782 static QSet
<QByteArray
> pool
;
2783 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2785 if (it
!= pool
.constEnd()) {
2793 bool KFileItemModel::isConsistent() const
2795 // m_items may contain less items than m_itemData because m_items
2796 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2797 if (m_items
.count() > m_itemData
.count()) {
2801 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2802 // Check if m_items and m_itemData are consistent.
2803 const KFileItem item
= fileItem(i
);
2804 if (item
.isNull()) {
2805 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2809 const int itemIndex
= index(item
);
2810 if (itemIndex
!= i
) {
2811 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2815 // Check if the items are sorted correctly.
2816 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2817 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2821 // Check if all parent-child relationships are consistent.
2822 const ItemData
*data
= m_itemData
.at(i
);
2823 const ItemData
*parent
= data
->parent
;
2825 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2826 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2830 const int parentIndex
= index(parent
->item
);
2831 if (parentIndex
>= i
) {
2832 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2842 void KFileItemModel::slotListerError(KIO::Job
*job
)
2844 if (job
->error() == KIO::ERR_IS_FILE
) {
2845 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2846 Q_EMIT
urlIsFileError(listJob
->url());
2849 const QString errorString
= job
->errorString();
2850 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));
2854 #include "moc_kfileitemmodel.cpp"