2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_contentdisplaysettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
15 #include "views/draganddrophelper.h"
19 #include <KIO/ListJob>
20 #include <KLocalizedString>
21 #include <KUrlMimeData>
23 #include <QElapsedTimer>
26 #include <QMimeDatabase>
27 #include <QRecursiveMutex>
30 #include <klazylocalizedstring.h>
32 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
34 // #define KFILEITEMMODEL_DEBUG
36 KFileItemModel::KFileItemModel(QObject
*parent
)
37 : KItemModelBase("text", "text", parent
)
38 , m_dirLister(nullptr)
39 , m_sortDirsFirst(true)
40 , m_sortHiddenLast(false)
41 , m_sortRole(NameRole
)
42 , m_sortingProgressPercent(-1)
49 , m_maximumUpdateIntervalTimer(nullptr)
50 , m_resortAllItemsTimer(nullptr)
51 , m_pendingItemsToInsert()
56 m_collator
.setNumericMode(true);
58 loadSortingSettings();
60 m_dirLister
= new KDirLister(this);
61 m_dirLister
->setAutoErrorHandlingEnabled(false);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
70 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
71 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
72 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
73 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
74 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
75 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
76 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
77 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
78 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
79 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
81 // Apply default roles that should be determined
83 m_requestRole
[NameRole
] = true;
84 m_requestRole
[IsDirRole
] = true;
85 m_requestRole
[IsLinkRole
] = true;
86 m_roles
.insert("text");
87 m_roles
.insert("isDir");
88 m_roles
.insert("isLink");
89 m_roles
.insert("isHidden");
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer
= new QTimer(this);
94 m_maximumUpdateIntervalTimer
->setInterval(2000);
95 m_maximumUpdateIntervalTimer
->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer
= new QTimer(this);
103 m_resortAllItemsTimer
->setInterval(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
104 // and sorting too infrequently which leads to users seeing an outdated sort order.
105 m_resortAllItemsTimer
->setSingleShot(true);
106 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
108 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
110 setShowTrashMime(m_dirLister
->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
113 KFileItemModel::~KFileItemModel()
115 qDeleteAll(m_itemData
);
116 qDeleteAll(m_filteredItems
);
117 qDeleteAll(m_pendingItemsToInsert
);
120 void KFileItemModel::loadDirectory(const QUrl
&url
)
122 m_dirLister
->openUrl(url
);
125 void KFileItemModel::refreshDirectory(const QUrl
&url
)
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
129 while (expandedDirs
.hasNext()) {
131 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
134 m_dirLister
->openUrl(url
, KDirLister::Reload
);
136 Q_EMIT
directoryRefreshing();
139 QUrl
KFileItemModel::directory() const
141 return m_dirLister
->url();
144 void KFileItemModel::cancelDirectoryLoading()
149 int KFileItemModel::count() const
151 return m_itemData
.count();
154 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
156 if (index
>= 0 && index
< count()) {
157 ItemData
*data
= m_itemData
.at(index
);
158 if (data
->values
.isEmpty()) {
159 data
->values
= retrieveData(data
->item
, data
->parent
);
160 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
161 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
162 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
163 // so this special request of different behavior can be identified here.
164 bool hasExpandedParentsCount
= false;
165 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
167 data
->values
= retrieveData(data
->item
, data
->parent
);
168 data
->values
.insert("isExpanded", true);
169 if (hasExpandedParentsCount
) {
170 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
176 return QHash
<QByteArray
, QVariant
>();
179 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
181 if (index
< 0 || index
>= count()) {
185 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
187 // Determine which roles have been changed
188 QSet
<QByteArray
> changedRoles
;
189 QHashIterator
<QByteArray
, QVariant
> it(values
);
190 while (it
.hasNext()) {
192 const QByteArray role
= sharedValue(it
.key());
193 const QVariant value
= it
.value();
195 if (currentValues
[role
] != value
) {
196 currentValues
[role
] = value
;
197 changedRoles
.insert(role
);
201 if (changedRoles
.isEmpty()) {
205 m_itemData
[index
]->values
= currentValues
;
206 if (changedRoles
.contains("text")) {
207 QUrl url
= m_itemData
[index
]->item
.url();
208 url
= url
.adjusted(QUrl::RemoveFilename
);
209 url
.setPath(url
.path() + currentValues
["text"].toString());
210 m_itemData
[index
]->item
.setUrl(url
);
213 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
218 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
220 if (dirsFirst
!= m_sortDirsFirst
) {
221 m_sortDirsFirst
= dirsFirst
;
226 bool KFileItemModel::sortDirectoriesFirst() const
228 return m_sortDirsFirst
;
231 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
233 if (hiddenLast
!= m_sortHiddenLast
) {
234 m_sortHiddenLast
= hiddenLast
;
239 bool KFileItemModel::sortHiddenLast() const
241 return m_sortHiddenLast
;
244 void KFileItemModel::setShowTrashMime(bool showTrashMime
)
246 const auto trashMime
= QStringLiteral("application/x-trash");
247 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
250 excludeFilter
.removeAll(trashMime
);
251 } else if (!excludeFilter
.contains(trashMime
)) {
252 excludeFilter
.append(trashMime
);
255 setExcludeMimeTypeFilter(excludeFilter
);
258 void KFileItemModel::scheduleResortAllItems()
260 if (!m_resortAllItemsTimer
->isActive()) {
261 m_resortAllItemsTimer
->start();
265 void KFileItemModel::setShowHiddenFiles(bool show
)
267 m_dirLister
->setShowHiddenFiles(show
);
268 setShowTrashMime(show
|| !GeneralSettings::hideXTrashFile());
269 m_dirLister
->emitChanges();
271 dispatchPendingItemsToInsert();
275 bool KFileItemModel::showHiddenFiles() const
277 return m_dirLister
->showHiddenFiles();
280 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
282 m_dirLister
->setDirOnlyMode(enabled
);
285 bool KFileItemModel::showDirectoriesOnly() const
287 return m_dirLister
->dirOnlyMode();
290 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
292 QMimeData
*data
= new QMimeData();
294 // The following code has been taken from KDirModel::mimeData()
295 // (kdelibs/kio/kio/kdirmodel.cpp)
296 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
298 QList
<QUrl
> mostLocalUrls
;
299 const ItemData
*lastAddedItem
= nullptr;
301 for (int index
: indexes
) {
302 const ItemData
*itemData
= m_itemData
.at(index
);
303 const ItemData
*parent
= itemData
->parent
;
305 while (parent
&& parent
!= lastAddedItem
) {
306 parent
= parent
->parent
;
309 if (parent
&& parent
== lastAddedItem
) {
310 // A parent of 'itemData' has been added already.
314 lastAddedItem
= itemData
;
315 const KFileItem
&item
= itemData
->item
;
316 if (!item
.isNull()) {
320 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
324 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
328 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
330 startFromIndex
= qMax(0, startFromIndex
);
331 for (int i
= startFromIndex
; i
< count(); ++i
) {
332 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
336 for (int i
= 0; i
< startFromIndex
; ++i
) {
337 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
344 bool KFileItemModel::supportsDropping(int index
) const
350 item
= fileItem(index
);
352 return !item
.isNull() && DragAndDropHelper::supportsDropping(item
);
355 bool KFileItemModel::canEnterOnHover(int index
) const
361 item
= fileItem(index
);
363 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
366 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
368 static QHash
<QByteArray
, QString
> description
;
369 if (description
.isEmpty()) {
371 const RoleInfoMap
*map
= rolesInfoMap(count
);
372 for (int i
= 0; i
< count
; ++i
) {
373 if (map
[i
].roleTranslation
.isEmpty()) {
376 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
380 return description
.value(role
);
383 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
385 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
386 #ifdef KFILEITEMMODEL_DEBUG
390 switch (typeForRole(groupRole())) {
395 m_groups
= nameRoleGroups();
398 m_groups
= sizeRoleGroups();
400 case ModificationTimeRole
:
401 m_groups
= timeRoleGroups([](const ItemData
*item
) {
402 return item
->item
.time(KFileItem::ModificationTime
);
405 case CreationTimeRole
:
406 m_groups
= timeRoleGroups([](const ItemData
*item
) {
407 return item
->item
.time(KFileItem::CreationTime
);
411 m_groups
= timeRoleGroups([](const ItemData
*item
) {
412 return item
->item
.time(KFileItem::AccessTime
);
415 case DeletionTimeRole
:
416 m_groups
= timeRoleGroups([](const ItemData
*item
) {
417 return item
->values
.value("deletiontime").toDateTime();
420 case PermissionsRole
:
421 m_groups
= permissionRoleGroups();
424 m_groups
= ratingRoleGroups();
427 m_groups
= genericStringRoleGroups(groupRole());
431 #ifdef KFILEITEMMODEL_DEBUG
432 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
439 KFileItem
KFileItemModel::fileItem(int index
) const
441 if (index
>= 0 && index
< count()) {
442 return m_itemData
.at(index
)->item
;
448 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
450 const int indexForUrl
= index(url
);
451 if (indexForUrl
>= 0) {
452 return m_itemData
.at(indexForUrl
)->item
;
457 int KFileItemModel::index(const KFileItem
&item
) const
459 return index(item
.url());
462 int KFileItemModel::index(const QUrl
&url
) const
464 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
466 const int itemCount
= m_itemData
.count();
467 int itemsInHash
= m_items
.count();
469 int index
= m_items
.value(urlToFind
, -1);
470 while (index
< 0 && itemsInHash
< itemCount
) {
471 // Not all URLs are stored yet in m_items. We grow m_items until either
472 // urlToFind is found, or all URLs have been stored in m_items.
473 // Note that we do not add the URLs to m_items one by one, but in
474 // larger blocks. After each block, we check if urlToFind is in
475 // m_items. We could in principle compare urlToFind with each URL while
476 // we are going through m_itemData, but comparing two QUrls will,
477 // unlike calling qHash for the URLs, trigger a parsing of the URLs
478 // which costs both CPU cycles and memory.
479 const int blockSize
= 1000;
480 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
481 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
482 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
483 m_items
.insert(nextUrl
, i
);
486 itemsInHash
= currentBlockEnd
;
487 index
= m_items
.value(urlToFind
, -1);
491 // The item could not be found, even though all items from m_itemData
492 // should be in m_items now. We print some diagnostic information which
493 // might help to find the cause of the problem, but only once. This
494 // prevents that obtaining and printing the debugging information
495 // wastes CPU cycles and floods the shell or .xsession-errors.
496 static bool printDebugInfo
= true;
498 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
499 printDebugInfo
= false;
501 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
502 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
503 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
505 // Check if there are multiple items with the same URL.
506 QMultiHash
<QUrl
, int> indexesForUrl
;
507 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
508 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
511 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
512 for (const QUrl
&url
: uniqueKeys
) {
513 if (indexesForUrl
.count(url
) > 1) {
514 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
516 auto it
= indexesForUrl
.find(url
);
517 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
518 const ItemData
*data
= m_itemData
.at(it
.value());
519 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
521 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
533 KFileItem
KFileItemModel::rootItem() const
535 return m_dirLister
->rootItem();
538 void KFileItemModel::clear()
543 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
545 if (m_roles
== roles
) {
549 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
553 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
554 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
555 if (supportedExpanding
&& !willSupportExpanding
) {
556 // No expanding is supported anymore. Take care to delete all items that have an expansion level
557 // that is not 0 (and hence are part of an expanded item).
558 removeExpandedItems();
565 QSetIterator
<QByteArray
> it(roles
);
566 while (it
.hasNext()) {
567 const QByteArray
&role
= it
.next();
568 m_requestRole
[typeForRole(role
)] = true;
572 // Update m_data with the changed requested roles
573 const int maxIndex
= count() - 1;
574 for (int i
= 0; i
<= maxIndex
; ++i
) {
575 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
578 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
581 // Clear the 'values' of all filtered items. They will be re-populated with the
582 // correct roles the next time 'values' will be accessed via data(int).
583 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
584 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
585 while (filteredIt
!= filteredEnd
) {
586 (*filteredIt
)->values
.clear();
591 QSet
<QByteArray
> KFileItemModel::roles() const
596 bool KFileItemModel::setExpanded(int index
, bool expanded
)
598 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
602 QHash
<QByteArray
, QVariant
> values
;
603 values
.insert(sharedValue("isExpanded"), expanded
);
604 if (!setData(index
, values
)) {
608 const KFileItem item
= m_itemData
.at(index
)->item
;
609 const QUrl url
= item
.url();
610 const QUrl targetUrl
= item
.targetUrl();
612 m_expandedDirs
.insert(targetUrl
, url
);
613 m_dirLister
->openUrl(url
, KDirLister::Keep
);
615 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
616 for (const QVariant
&var
: previouslyExpandedChildren
) {
617 m_urlsToExpand
.insert(var
.toUrl());
620 // Note that there might be (indirect) children of the folder which is to be collapsed in
621 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
622 // possibly without a parent, which might result in a crash, we insert all pending items
623 // right now. All new items which would be without a parent will then be removed.
624 dispatchPendingItemsToInsert();
626 // Check if the index of the collapsed folder has changed. If that is the case, then items
627 // were inserted before the collapsed folder, and its index needs to be updated.
628 if (m_itemData
.at(index
)->item
!= item
) {
629 index
= this->index(item
);
632 m_expandedDirs
.remove(targetUrl
);
633 m_dirLister
->stop(url
);
634 m_dirLister
->forgetDirs(url
);
636 const int parentLevel
= expandedParentsCount(index
);
637 const int itemCount
= m_itemData
.count();
638 const int firstChildIndex
= index
+ 1;
640 QVariantList expandedChildren
;
642 int childIndex
= firstChildIndex
;
643 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
644 ItemData
*itemData
= m_itemData
.at(childIndex
);
645 if (itemData
->values
.value("isExpanded").toBool()) {
646 const QUrl targetUrl
= itemData
->item
.targetUrl();
647 const QUrl url
= itemData
->item
.url();
648 m_expandedDirs
.remove(targetUrl
);
649 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
650 m_dirLister
->forgetDirs(url
);
651 expandedChildren
.append(targetUrl
);
655 const int childrenCount
= childIndex
- firstChildIndex
;
657 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
658 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
660 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
666 bool KFileItemModel::isExpanded(int index
) const
668 if (index
>= 0 && index
< count()) {
669 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
674 bool KFileItemModel::isExpandable(int index
) const
676 if (index
>= 0 && index
< count()) {
677 // Call data (instead of accessing m_itemData directly)
678 // to ensure that the value is initialized.
679 return data(index
).value("isExpandable").toBool();
684 int KFileItemModel::expandedParentsCount(int index
) const
686 if (index
>= 0 && index
< count()) {
687 return expandedParentsCount(m_itemData
.at(index
));
692 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
695 const auto dirs
= m_expandedDirs
;
696 for (const auto &dir
: dirs
) {
702 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
704 m_urlsToExpand
= urls
;
707 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
709 // Assure that each sub-path of the URL that should be
710 // expanded is added to m_urlsToExpand. KDirLister
711 // does not care whether the parent-URL has already been
713 QUrl urlToExpand
= m_dirLister
->url();
714 const int pos
= urlToExpand
.path().length();
716 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
717 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
718 // so using QString::SkipEmptyParts
719 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
720 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
721 QString path
= urlToExpand
.path();
722 if (!path
.endsWith(QLatin1Char('/'))) {
723 path
.append(QLatin1Char('/'));
725 urlToExpand
.setPath(path
+ subDirs
.at(i
));
726 m_urlsToExpand
.insert(urlToExpand
);
729 // KDirLister::open() must called at least once to trigger an initial
730 // loading. The pending URLs that must be restored are handled
731 // in slotCompleted().
732 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
733 while (it2
.hasNext()) {
734 const int idx
= index(it2
.next());
735 if (idx
>= 0 && !isExpanded(idx
)) {
736 setExpanded(idx
, true);
742 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
744 if (m_filter
.pattern() != nameFilter
) {
745 dispatchPendingItemsToInsert();
746 m_filter
.setPattern(nameFilter
);
751 QString
KFileItemModel::nameFilter() const
753 return m_filter
.pattern();
756 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
758 if (m_filter
.mimeTypes() != filters
) {
759 dispatchPendingItemsToInsert();
760 m_filter
.setMimeTypes(filters
);
765 QStringList
KFileItemModel::mimeTypeFilters() const
767 return m_filter
.mimeTypes();
770 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
772 if (m_filter
.excludeMimeTypes() != filters
) {
773 dispatchPendingItemsToInsert();
774 m_filter
.setExcludeMimeTypes(filters
);
779 QStringList
KFileItemModel::excludeMimeTypeFilter() const
781 return m_filter
.excludeMimeTypes();
784 void KFileItemModel::applyFilters()
787 // Check which previously shown items from m_itemData must now get
788 // hidden and hence moved from m_itemData into m_filteredItems.
790 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
792 // This pointer will refer to the next confirmed shown item from the point of
793 // view of the current "itemData" in the upcoming "for" loop.
794 ItemData
*itemShownBelow
= nullptr;
796 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
797 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
798 ItemData
*itemData
= m_itemData
.at(index
);
800 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
801 // We could've entered here for two reasons:
802 // 1. This item passes the filter itself
803 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
805 // So this item must remain shown.
806 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
807 itemShownBelow
= itemData
;
809 // We hide this item for now, however, for expanded folders this is not final:
810 // 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
811 newFilteredIndexes
.prepend(index
);
812 m_filteredItems
.insert(itemData
->item
, itemData
);
813 // indexShownBelow doesn't get updated since this item will be hidden
817 // This will remove the newly filtered items from m_itemData
818 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
821 // Check which hidden items from m_filteredItems should
822 // become visible again and hence moved from m_filteredItems back into m_itemData.
824 QList
<ItemData
*> newVisibleItems
;
826 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
828 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
829 while (it
!= m_filteredItems
.end()) {
830 if (m_filter
.matches(it
.key())) {
831 newVisibleItems
.append(it
.value());
833 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
834 // We will go up through its parental chain until we either:
835 // 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
836 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
837 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
838 parent
= parent
->parent
) {
839 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
840 // and it would mess up the iteration. We will mark it to be removed in step 3.
841 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
844 it
= m_filteredItems
.erase(it
);
846 // Item remains filtered for now
847 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
853 // Handles the ancestorsOfNewVisibleItems.
854 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
855 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
856 if (m_filteredItems
.remove(it
.key())) {
857 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
858 newVisibleItems
.append(it
.value());
862 // This will insert the newly discovered unfiltered items into m_itemData
863 insertItems(newVisibleItems
);
866 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
868 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
869 // There are either no filtered items, or it is not possible to expand
870 // folders -> there cannot be any filtered children.
874 QSet
<ItemData
*> parents
;
875 for (const KItemRange
&range
: itemRanges
) {
876 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
877 parents
.insert(m_itemData
.at(index
));
881 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
882 while (it
!= m_filteredItems
.end()) {
883 if (parents
.contains(it
.value()->parent
)) {
885 it
= m_filteredItems
.erase(it
);
892 KFileItemModel::RoleInfo
KFileItemModel::roleInformation(const QByteArray
&role
)
894 static QHash
<QByteArray
, RoleInfo
> information
;
895 if (information
.isEmpty()) {
897 const RoleInfoMap
*map
= rolesInfoMap(count
);
898 for (int i
= 0; i
< count
; ++i
) {
900 info
.role
= map
[i
].role
;
901 info
.translation
= map
[i
].roleTranslation
.toString();
902 if (!map
[i
].groupTranslation
.isEmpty()) {
903 info
.group
= map
[i
].groupTranslation
.toString();
905 // For top level roles, groupTranslation is 0. We must make sure that
906 // info.group is an empty string then because the code that generates
907 // menus tries to put the actions into sub menus otherwise.
908 info
.group
= QString();
910 info
.requiresBaloo
= map
[i
].requiresBaloo
;
911 info
.requiresIndexer
= map
[i
].requiresIndexer
;
912 if (!map
[i
].tooltipTranslation
.isEmpty()) {
913 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
915 info
.tooltip
= QString();
918 information
.insert(map
[i
].role
, info
);
922 return information
.value(role
);
925 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
927 static QList
<RoleInfo
> rolesInfo
;
928 if (rolesInfo
.isEmpty()) {
930 const RoleInfoMap
*map
= rolesInfoMap(count
);
931 for (int i
= 0; i
< count
; ++i
) {
932 if (map
[i
].roleType
!= NoRole
) {
933 RoleInfo info
= roleInformation(map
[i
].role
);
934 rolesInfo
.append(info
);
942 void KFileItemModel::onGroupedSortingChanged(bool current
)
948 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
951 m_sortRole
= typeForRole(current
);
953 if (!m_requestRole
[m_sortRole
]) {
954 QSet
<QByteArray
> newRoles
= m_roles
;
964 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
, bool resortItems
)
974 void KFileItemModel::onGroupRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
977 m_groupRole
= typeForRole(current
);
979 if (!m_requestRole
[m_sortRole
]) {
980 QSet
<QByteArray
> newRoles
= m_roles
;
990 void KFileItemModel::onGroupOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
, bool resortItems
)
1000 void KFileItemModel::loadSortingSettings()
1002 using Choice
= GeneralSettings::EnumSortingChoice
;
1003 switch (GeneralSettings::sortingChoice()) {
1004 case Choice::NaturalSorting
:
1005 m_naturalSorting
= true;
1006 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
1008 case Choice::CaseSensitiveSorting
:
1009 m_naturalSorting
= false;
1010 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
1012 case Choice::CaseInsensitiveSorting
:
1013 m_naturalSorting
= false;
1014 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
1019 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
1020 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
1021 m_collator
.compare(QString(), QString());
1024 void KFileItemModel::resortAllItems()
1026 m_resortAllItemsTimer
->stop();
1028 const int itemCount
= count();
1029 if (itemCount
<= 0) {
1033 #ifdef KFILEITEMMODEL_DEBUG
1034 QElapsedTimer timer
;
1036 qCDebug(DolphinDebug
) << "===========================================================";
1037 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
1040 // Remember the order of the current URLs so
1041 // that it can be determined which indexes have
1042 // been moved because of the resorting.
1043 QList
<QUrl
> oldUrls
;
1044 oldUrls
.reserve(itemCount
);
1045 for (const ItemData
*itemData
: std::as_const(m_itemData
)) {
1046 oldUrls
.append(itemData
->item
.url());
1050 m_items
.reserve(itemCount
);
1053 sort(m_itemData
.begin(), m_itemData
.end());
1054 for (int i
= 0; i
< itemCount
; ++i
) {
1055 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
1058 // Determine the first index that has been moved.
1059 int firstMovedIndex
= 0;
1060 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1064 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1065 if (itemsHaveMoved
) {
1068 int lastMovedIndex
= itemCount
- 1;
1069 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1073 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1075 // Create a list movedToIndexes, which has the property that
1076 // movedToIndexes[i] is the new index of the item with the old index
1077 // firstMovedIndex + i.
1078 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1079 QList
<int> movedToIndexes
;
1080 movedToIndexes
.reserve(movedItemsCount
);
1081 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1082 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1083 movedToIndexes
.append(newIndex
);
1086 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1087 } else if (groupedSorting()) {
1088 // The groups might have changed even if the order of the items has not.
1089 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1091 if (groups() != oldGroups
) {
1092 Q_EMIT
groupsChanged();
1096 #ifdef KFILEITEMMODEL_DEBUG
1097 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1101 void KFileItemModel::slotCompleted()
1103 m_maximumUpdateIntervalTimer
->stop();
1104 dispatchPendingItemsToInsert();
1106 if (!m_urlsToExpand
.isEmpty()) {
1107 // Try to find a URL that can be expanded.
1108 // Note that the parent folder must be expanded before any of its subfolders become visible.
1109 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1110 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1111 // Iterate over a const copy because items are deleted and inserted within the loop
1112 const auto urlsToExpand
= m_urlsToExpand
;
1113 for (const QUrl
&url
: urlsToExpand
) {
1114 const int indexForUrl
= index(url
);
1115 if (indexForUrl
>= 0) {
1116 m_urlsToExpand
.remove(url
);
1117 if (setExpanded(indexForUrl
, true)) {
1118 // The dir lister has been triggered. This slot will be called
1119 // again after the directory has been expanded.
1125 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1126 // if these URLs have been deleted in the meantime.
1127 m_urlsToExpand
.clear();
1130 Q_EMIT
directoryLoadingCompleted();
1133 void KFileItemModel::slotCanceled()
1135 m_maximumUpdateIntervalTimer
->stop();
1136 dispatchPendingItemsToInsert();
1138 Q_EMIT
directoryLoadingCanceled();
1141 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1143 Q_ASSERT(!items
.isEmpty());
1145 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1147 if (m_requestRole
[ExpandedParentsCountRole
]) {
1148 // If the expanding of items is enabled, the call
1149 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1150 // might result in emitting the same items twice due to the Keep-parameter.
1151 // This case happens if an item gets expanded, collapsed and expanded again
1152 // before the items could be loaded for the first expansion.
1153 if (index(items
.first().url()) >= 0) {
1154 // The items are already part of the model.
1158 if (directoryUrl
!= directory()) {
1159 // To be able to compare whether the new items may be inserted as children
1160 // of a parent item the pending items must be added to the model first.
1161 dispatchPendingItemsToInsert();
1164 // KDirLister keeps the children of items that got expanded once even if
1165 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1166 // checked whether the parent for new items is still expanded.
1167 const int parentIndex
= index(parentUrl
);
1168 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1169 // The parent is not expanded.
1174 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1176 if (!m_filter
.hasSetFilters()) {
1177 m_pendingItemsToInsert
.append(itemDataList
);
1179 QSet
<ItemData
*> parentsToEnsureVisible
;
1181 // The name or type filter is active. Hide filtered items
1182 // before inserting them into the model and remember
1183 // the filtered items in m_filteredItems.
1184 for (ItemData
*itemData
: itemDataList
) {
1185 if (m_filter
.matches(itemData
->item
)) {
1186 m_pendingItemsToInsert
.append(itemData
);
1187 if (itemData
->parent
) {
1188 parentsToEnsureVisible
.insert(itemData
->parent
);
1191 m_filteredItems
.insert(itemData
->item
, itemData
);
1195 // Entire parental chains must be shown
1196 for (ItemData
*parent
: parentsToEnsureVisible
) {
1197 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1198 m_pendingItemsToInsert
.append(parent
);
1203 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1204 // Assure that items get dispatched if no completed() or canceled() signal is
1205 // emitted during the maximum update interval.
1206 m_maximumUpdateIntervalTimer
->start();
1209 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1212 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1214 int filteredParentsCount
= 0;
1215 // The childless parents not yet removed will always be right above the start of a removed range.
1216 // We iterate backwards to ensure the deepest folders are processed before their parents
1217 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1218 KItemRange itemRange
= removedItemRanges
.at(i
);
1219 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1220 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1221 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1223 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1224 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1225 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1226 // and this deleted range covers all of its descendents, so none will be left.
1227 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1228 // This range's starting index will be extended to include the parent above:
1231 ++filteredParentsCount
;
1232 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1233 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1234 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1235 previousRange
.count
+= itemRange
.count
;
1236 removedItemRanges
.replace(i
- 1, previousRange
);
1237 removedItemRanges
.removeAt(i
);
1239 removedItemRanges
.replace(i
, itemRange
);
1240 // We must revisit this range in the next iteration since its starting index changed
1245 return filteredParentsCount
;
1248 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1250 dispatchPendingItemsToInsert();
1252 QVector
<int> indexesToRemove
;
1253 indexesToRemove
.reserve(items
.count());
1254 KFileItemList dirsChanged
;
1256 const auto currentDir
= directory();
1258 for (const KFileItem
&item
: items
) {
1259 if (item
.url() == currentDir
) {
1260 Q_EMIT
currentDirectoryRemoved();
1264 const int indexForItem
= index(item
);
1265 if (indexForItem
>= 0) {
1266 indexesToRemove
.append(indexForItem
);
1268 // Probably the item has been filtered.
1269 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1270 if (it
!= m_filteredItems
.end()) {
1272 m_filteredItems
.erase(it
);
1276 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1277 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1278 dirsChanged
<< KFileItem(parentUrl
);
1282 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1284 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1285 // Assure that removing a parent item also results in removing all children
1286 QVector
<int> indexesToRemoveWithChildren
;
1287 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1289 const int itemCount
= m_itemData
.count();
1290 for (int index
: std::as_const(indexesToRemove
)) {
1291 indexesToRemoveWithChildren
.append(index
);
1293 const int parentLevel
= expandedParentsCount(index
);
1294 int childIndex
= index
+ 1;
1295 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1296 indexesToRemoveWithChildren
.append(childIndex
);
1301 indexesToRemove
= indexesToRemoveWithChildren
;
1304 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1305 removeFilteredChildren(itemRanges
);
1307 // This call will update itemRanges to include the childless parents that have been filtered.
1308 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1310 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1311 // mixed with expanded folders that are just being filtered out.
1312 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1313 // so removeItems() will check m_filteredItems to differentiate which is which.
1314 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1316 Q_EMIT
fileItemsChanged(dirsChanged
);
1319 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1321 Q_ASSERT(!items
.isEmpty());
1322 #ifdef KFILEITEMMODEL_DEBUG
1323 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1326 // Get the indexes of all items that have been refreshed
1328 indexes
.reserve(items
.count());
1330 QSet
<QByteArray
> changedRoles
;
1331 KFileItemList changedFiles
;
1333 // Contains the indexes of the currently visible items
1334 // that should get hidden and hence moved to m_filteredItems.
1335 QVector
<int> newFilteredIndexes
;
1337 // Contains currently hidden items that should
1338 // get visible and hence removed from m_filteredItems
1339 QList
<ItemData
*> newVisibleItems
;
1341 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1343 while (it
.hasNext()) {
1344 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1345 const KFileItem
&oldItem
= itemPair
.first
;
1346 const KFileItem
&newItem
= itemPair
.second
;
1347 const int indexForItem
= index(oldItem
);
1348 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1349 if (indexForItem
>= 0) {
1350 m_itemData
[indexForItem
]->item
= newItem
;
1352 // Keep old values as long as possible if they could not retrieved synchronously yet.
1353 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1354 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1355 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1356 while (it
.hasNext()) {
1358 const QByteArray
&role
= it
.key();
1359 if (itemData
->values
.value(role
) != it
.value()) {
1360 itemData
->values
.insert(role
, it
.value());
1361 changedRoles
.insert(role
);
1365 m_items
.remove(oldItem
.url());
1366 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1367 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1368 m_items
.insert(newItem
.url(), indexForItem
);
1369 if (newItemMatchesFilter
1370 || (itemData
->values
.value("isExpanded").toBool()
1371 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1372 // We are lenient with expanded folders that originally had visible children.
1373 // If they become childless now they will be caught by filterChildlessParents()
1374 changedFiles
.append(newItem
);
1375 indexes
.append(indexForItem
);
1377 newFilteredIndexes
.append(indexForItem
);
1378 m_filteredItems
.insert(newItem
, itemData
);
1381 // Check if 'oldItem' is one of the filtered items.
1382 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1383 if (it
!= m_filteredItems
.end()) {
1384 ItemData
*const itemData
= it
.value();
1385 itemData
->item
= newItem
;
1387 // The data stored in 'values' might have changed. Therefore, we clear
1388 // 'values' and re-populate it the next time it is requested via data(int).
1389 // Before clearing, we must remember if it was expanded and the expanded parents count,
1390 // otherwise these states would be lost. The data() method will deal with this special case.
1391 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1392 bool hasExpandedParentsCount
= false;
1393 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1394 itemData
->values
.clear();
1396 itemData
->values
.insert("isExpanded", true);
1397 if (hasExpandedParentsCount
) {
1398 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1402 m_filteredItems
.erase(it
);
1403 if (newItemMatchesFilter
) {
1404 newVisibleItems
.append(itemData
);
1406 m_filteredItems
.insert(newItem
, itemData
);
1412 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1414 // We must keep track of parents of new visible items since they must be shown no matter what
1415 // They will be considered "immune" to filterChildlessParents()
1416 QSet
<ItemData
*> parentsToEnsureVisible
;
1418 for (ItemData
*item
: newVisibleItems
) {
1419 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1420 parentsToEnsureVisible
.insert(parent
);
1423 for (ItemData
*parent
: parentsToEnsureVisible
) {
1424 // We make sure they are all unfiltered.
1425 if (m_filteredItems
.remove(parent
->item
)) {
1426 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1427 newVisibleItems
.append(parent
);
1428 // It could be in newFilteredIndexes, we must remove it if it's there:
1429 const int parentIndex
= index(parent
->item
);
1430 if (parentIndex
>= 0) {
1431 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1432 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1433 newFilteredIndexes
.erase(it
);
1439 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1441 // This call will update itemRanges to include the childless parents that have been filtered.
1442 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1444 removeItems(removedRanges
, KeepItemData
);
1446 // Show previously hidden items that should get visible
1447 insertItems(newVisibleItems
);
1449 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1451 // If the changed items have been created recently, they might not be in m_items yet.
1452 // In that case, the list 'indexes' might be empty.
1453 if (indexes
.isEmpty()) {
1457 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1458 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1460 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1461 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1462 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1463 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1468 std::sort(indexes
.begin(), indexes
.end());
1471 // Extract the item-ranges out of the changed indexes
1472 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1473 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1475 Q_EMIT
fileItemsChanged(changedFiles
);
1478 void KFileItemModel::slotClear()
1480 #ifdef KFILEITEMMODEL_DEBUG
1481 qCDebug(DolphinDebug
) << "Clearing all items";
1484 qDeleteAll(m_filteredItems
);
1485 m_filteredItems
.clear();
1488 m_maximumUpdateIntervalTimer
->stop();
1489 m_resortAllItemsTimer
->stop();
1491 qDeleteAll(m_pendingItemsToInsert
);
1492 m_pendingItemsToInsert
.clear();
1494 const int removedCount
= m_itemData
.count();
1495 if (removedCount
> 0) {
1496 qDeleteAll(m_itemData
);
1499 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1502 m_expandedDirs
.clear();
1505 void KFileItemModel::slotSortingChoiceChanged()
1507 loadSortingSettings();
1511 void KFileItemModel::dispatchPendingItemsToInsert()
1513 if (!m_pendingItemsToInsert
.isEmpty()) {
1514 insertItems(m_pendingItemsToInsert
);
1515 m_pendingItemsToInsert
.clear();
1519 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1521 if (newItems
.isEmpty()) {
1525 #ifdef KFILEITEMMODEL_DEBUG
1526 QElapsedTimer timer
;
1528 qCDebug(DolphinDebug
) << "===========================================================";
1529 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1533 prepareItemsForSorting(newItems
);
1535 // Natural sorting of items can be very slow. However, it becomes much faster
1536 // if the input sequence is already mostly sorted. Therefore, we first sort
1537 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1538 if (m_naturalSorting
) {
1539 if (m_sortRole
== NameRole
) {
1540 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1541 } else if (isRoleValueNatural(m_sortRole
)) {
1542 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1543 const QByteArray role
= roleForType(m_sortRole
);
1544 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1546 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1550 sort(newItems
.begin(), newItems
.end());
1552 #ifdef KFILEITEMMODEL_DEBUG
1553 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1556 KItemRangeList itemRanges
;
1557 const int existingItemCount
= m_itemData
.count();
1558 const int newItemCount
= newItems
.count();
1559 const int totalItemCount
= existingItemCount
+ newItemCount
;
1561 if (existingItemCount
== 0) {
1562 // Optimization for the common special case that there are no
1563 // items in the model yet. Happens, e.g., when entering a folder.
1564 m_itemData
= newItems
;
1565 itemRanges
<< KItemRange(0, newItemCount
);
1567 m_itemData
.reserve(totalItemCount
);
1568 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1569 m_itemData
.append(nullptr);
1572 // We build the new list m_itemData in reverse order to minimize
1573 // the number of moves and guarantee O(N) complexity.
1574 int targetIndex
= totalItemCount
- 1;
1575 int sourceIndexExistingItems
= existingItemCount
- 1;
1576 int sourceIndexNewItems
= newItemCount
- 1;
1580 while (sourceIndexNewItems
>= 0) {
1581 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1582 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1583 // Move an existing item to its new position. If any new items
1584 // are behind it, push the item range to itemRanges.
1585 if (rangeCount
> 0) {
1586 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1590 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1591 --sourceIndexExistingItems
;
1593 // Insert a new item into the list.
1595 m_itemData
[targetIndex
] = newItem
;
1596 --sourceIndexNewItems
;
1601 // Push the final item range to itemRanges.
1602 if (rangeCount
> 0) {
1603 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1606 // Note that itemRanges is still sorted in reverse order.
1607 std::reverse(itemRanges
.begin(), itemRanges
.end());
1610 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1611 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1614 Q_EMIT
itemsInserted(itemRanges
);
1616 #ifdef KFILEITEMMODEL_DEBUG
1617 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1621 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1623 if (itemRanges
.isEmpty()) {
1629 // Step 1: Remove the items from m_itemData, and free the ItemData.
1630 int removedItemsCount
= 0;
1631 for (const KItemRange
&range
: itemRanges
) {
1632 removedItemsCount
+= range
.count
;
1634 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1635 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1636 delete m_itemData
.at(index
);
1639 m_itemData
[index
] = nullptr;
1643 // Step 2: Remove the ItemData pointers from the list m_itemData.
1644 int target
= itemRanges
.at(0).index
;
1645 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1648 const int oldItemDataCount
= m_itemData
.count();
1649 while (source
< oldItemDataCount
) {
1650 m_itemData
[target
] = m_itemData
[source
];
1654 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1655 // Skip the items in the next removed range.
1656 source
+= itemRanges
.at(nextRange
).count
;
1661 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1663 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1664 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1667 Q_EMIT
itemsRemoved(itemRanges
);
1670 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1672 if (m_sortRole
== TypeRole
) {
1673 // Try to resolve the MIME-types synchronously to prevent a reordering of
1674 // the items when sorting by type (per default MIME-types are resolved
1675 // asynchronously by KFileItemModelRolesUpdater).
1676 determineMimeTypes(items
, 200);
1679 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1680 const int parentIndex
= index(parentUrl
);
1681 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1683 QList
<ItemData
*> itemDataList
;
1684 itemDataList
.reserve(items
.count());
1686 for (const KFileItem
&item
: items
) {
1687 ItemData
*itemData
= new ItemData();
1688 itemData
->item
= item
;
1689 itemData
->parent
= parentItem
;
1690 itemDataList
.append(itemData
);
1693 return itemDataList
;
1696 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1698 switch (m_sortRole
) {
1700 case PermissionsRole
:
1703 case DestinationRole
:
1705 case DeletionTimeRole
:
1706 // These roles can be determined with retrieveData, and they have to be stored
1707 // in the QHash "values" for the sorting.
1708 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1709 if (itemData
->values
.isEmpty()) {
1710 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1716 // At least store the data including the file type for items with known MIME type.
1717 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1718 if (itemData
->values
.isEmpty()) {
1719 const KFileItem item
= itemData
->item
;
1720 if (item
.isDir() || item
.isMimeTypeKnown()) {
1721 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1728 // The other roles are either resolved by KFileItemModelRolesUpdater
1729 // (this includes the SizeRole for directories), or they do not need
1730 // to be stored in the QHash "values" for sorting because the data can
1731 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1737 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1739 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1740 // if the corresponding item is expanded, and it is not a top-level item.
1741 const ItemData
*parent
= data
->parent
;
1743 if (parent
->parent
) {
1744 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1745 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1754 void KFileItemModel::removeExpandedItems()
1756 QVector
<int> indexesToRemove
;
1758 const int maxIndex
= m_itemData
.count() - 1;
1759 for (int i
= 0; i
<= maxIndex
; ++i
) {
1760 const ItemData
*itemData
= m_itemData
.at(i
);
1761 if (itemData
->parent
) {
1762 indexesToRemove
.append(i
);
1766 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1767 m_expandedDirs
.clear();
1769 // Also remove all filtered items which have a parent.
1770 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1771 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1774 if (it
.value()->parent
) {
1776 it
= m_filteredItems
.erase(it
);
1783 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1785 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1787 // Trigger a resorting if necessary. Note that this can happen even if the sort
1788 // role has not changed at all because the file name can be used as a fallback.
1789 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))
1790 || (changedRoles
.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1791 for (const KItemRange
&range
: itemRanges
) {
1792 bool needsResorting
= false;
1794 const int first
= range
.index
;
1795 const int last
= range
.index
+ range
.count
- 1;
1797 // Resorting the model is necessary if
1798 // (a) The first item in the range is "lessThan" its predecessor,
1799 // (b) the successor of the last item is "lessThan" the last item, or
1800 // (c) the internal order of the items in the range is incorrect.
1801 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1802 needsResorting
= true;
1803 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1804 needsResorting
= true;
1806 for (int index
= first
; index
< last
; ++index
) {
1807 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1808 needsResorting
= true;
1814 if (needsResorting
) {
1815 scheduleResortAllItems();
1821 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1822 // The position is still correct, but the groups might have changed
1823 // if the changed item is either the first or the last item in a
1825 // In principle, we could try to find out if the item really is the
1826 // first or last one in its group and then update the groups
1827 // (possibly with a delayed timer to make sure that we don't
1828 // re-calculate the groups very often if items are updated one by
1829 // one), but starting m_resortAllItemsTimer is easier.
1830 m_resortAllItemsTimer
->start();
1834 void KFileItemModel::resetRoles()
1836 for (int i
= 0; i
< RolesCount
; ++i
) {
1837 m_requestRole
[i
] = false;
1841 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1843 static QHash
<QByteArray
, RoleType
> roles
;
1844 if (roles
.isEmpty()) {
1845 // Insert user visible roles that can be accessed with
1846 // KFileItemModel::roleInformation()
1848 const RoleInfoMap
*map
= rolesInfoMap(count
);
1849 for (int i
= 0; i
< count
; ++i
) {
1850 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1853 // Insert internal roles (take care to synchronize the implementation
1854 // with KFileItemModel::roleForType() in case if a change is done).
1855 roles
.insert("isDir", IsDirRole
);
1856 roles
.insert("isLink", IsLinkRole
);
1857 roles
.insert("isHidden", IsHiddenRole
);
1858 roles
.insert("isExpanded", IsExpandedRole
);
1859 roles
.insert("isExpandable", IsExpandableRole
);
1860 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1862 Q_ASSERT(roles
.count() == RolesCount
);
1865 return roles
.value(role
, NoRole
);
1868 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1870 static QHash
<RoleType
, QByteArray
> roles
;
1871 if (roles
.isEmpty()) {
1872 // Insert user visible roles that can be accessed with
1873 // KFileItemModel::roleInformation()
1875 const RoleInfoMap
*map
= rolesInfoMap(count
);
1876 for (int i
= 0; i
< count
; ++i
) {
1877 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1880 // Insert internal roles (take care to synchronize the implementation
1881 // with KFileItemModel::typeForRole() in case if a change is done).
1882 roles
.insert(IsDirRole
, "isDir");
1883 roles
.insert(IsLinkRole
, "isLink");
1884 roles
.insert(IsHiddenRole
, "isHidden");
1885 roles
.insert(IsExpandedRole
, "isExpanded");
1886 roles
.insert(IsExpandableRole
, "isExpandable");
1887 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1889 Q_ASSERT(roles
.count() == RolesCount
);
1892 return roles
.value(roleType
);
1895 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1897 // It is important to insert only roles that are fast to retrieve. E.g.
1898 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1899 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1900 QHash
<QByteArray
, QVariant
> data
;
1901 data
.insert(sharedValue("url"), item
.url());
1903 const bool isDir
= item
.isDir();
1904 if (m_requestRole
[IsDirRole
] && isDir
) {
1905 data
.insert(sharedValue("isDir"), true);
1908 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1909 data
.insert(sharedValue("isLink"), true);
1912 if (m_requestRole
[IsHiddenRole
]) {
1913 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1916 if (m_requestRole
[NameRole
]) {
1917 data
.insert(sharedValue("text"), item
.text());
1920 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1921 // TODO KF6 use KFileItem::suffix 464722
1922 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1925 if (m_requestRole
[SizeRole
] && !isDir
) {
1926 data
.insert(sharedValue("size"), item
.size());
1929 if (m_requestRole
[ModificationTimeRole
]) {
1930 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1931 // having several thousands of items. Instead read the raw number from UDSEntry directly
1932 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1933 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1934 data
.insert(sharedValue("modificationtime"), dateTime
);
1937 if (m_requestRole
[CreationTimeRole
]) {
1938 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1939 // having several thousands of items. Instead read the raw number from UDSEntry directly
1940 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1941 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1942 data
.insert(sharedValue("creationtime"), dateTime
);
1945 if (m_requestRole
[AccessTimeRole
]) {
1946 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1947 // having several thousands of items. Instead read the raw number from UDSEntry directly
1948 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1949 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1950 data
.insert(sharedValue("accesstime"), dateTime
);
1953 if (m_requestRole
[PermissionsRole
]) {
1954 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1957 if (m_requestRole
[OwnerRole
]) {
1958 data
.insert(sharedValue("owner"), item
.user());
1961 if (m_requestRole
[GroupRole
]) {
1962 data
.insert(sharedValue("group"), item
.group());
1965 if (m_requestRole
[DestinationRole
]) {
1966 QString destination
= item
.linkDest();
1967 if (destination
.isEmpty()) {
1968 destination
= QLatin1Char('-');
1970 data
.insert(sharedValue("destination"), destination
);
1973 if (m_requestRole
[PathRole
]) {
1975 if (item
.url().scheme() == QLatin1String("trash")) {
1976 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1978 // For performance reasons cache the home-path in a static QString
1979 // (see QDir::homePath() for more details)
1980 static QString homePath
;
1981 if (homePath
.isEmpty()) {
1982 homePath
= QDir::homePath();
1985 path
= item
.localPath();
1986 if (path
.startsWith(homePath
)) {
1987 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1991 const int index
= path
.lastIndexOf(item
.text());
1992 path
= path
.mid(0, index
- 1);
1993 data
.insert(sharedValue("path"), path
);
1996 if (m_requestRole
[DeletionTimeRole
]) {
1997 QDateTime deletionTime
;
1998 if (item
.url().scheme() == QLatin1String("trash")) {
1999 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
2001 data
.insert(sharedValue("deletiontime"), deletionTime
);
2004 if (m_requestRole
[IsExpandableRole
] && isDir
) {
2005 data
.insert(sharedValue("isExpandable"), true);
2008 if (m_requestRole
[ExpandedParentsCountRole
]) {
2010 const int level
= expandedParentsCount(parent
) + 1;
2011 data
.insert(sharedValue("expandedParentsCount"), level
);
2015 if (item
.isMimeTypeKnown()) {
2016 QString iconName
= item
.iconName();
2017 if (!QIcon::hasThemeIcon(iconName
)) {
2018 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
2019 iconName
= mimeType
.genericIconName();
2022 data
.insert(sharedValue("iconName"), iconName
);
2024 if (m_requestRole
[TypeRole
]) {
2025 data
.insert(sharedValue("type"), item
.mimeComment());
2027 } else if (m_requestRole
[TypeRole
] && isDir
) {
2028 static const QString folderMimeType
= item
.mimeComment();
2029 data
.insert(sharedValue("type"), folderMimeType
);
2035 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2039 if (a
->parent
!= b
->parent
) {
2040 const int expansionLevelA
= expandedParentsCount(a
);
2041 const int expansionLevelB
= expandedParentsCount(b
);
2043 // If b has a higher expansion level than a, check if a is a parent
2044 // of b, and make sure that both expansion levels are equal otherwise.
2045 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
2046 if (b
->parent
== a
) {
2052 // If a has a higher expansion level than a, check if b is a parent
2053 // of a, and make sure that both expansion levels are equal otherwise.
2054 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
2055 if (a
->parent
== b
) {
2061 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2063 // Compare the last parents of a and b which are different.
2064 while (a
->parent
!= b
->parent
) {
2070 result
= groupRoleCompare(a
, b
, collator
);
2072 // Show hidden files and folders last
2073 if (m_sortHiddenLast
) {
2074 const bool isHiddenA
= a
->item
.isHidden();
2075 const bool isHiddenB
= b
->item
.isHidden();
2076 if (isHiddenA
&& !isHiddenB
) {
2078 } else if (!isHiddenA
&& isHiddenB
) {
2083 || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& m_sortRole
== SizeRole
)) {
2084 const bool isDirA
= a
->item
.isDir();
2085 const bool isDirB
= b
->item
.isDir();
2086 if (isDirA
&& !isDirB
) {
2088 } else if (!isDirA
&& isDirB
) {
2092 result
= sortRoleCompare(a
, b
, collator
);
2093 result
= (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2095 result
= (groupOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2100 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2102 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2103 return lessThan(a
, b
, m_collator
);
2106 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2107 // Sorting by string can be expensive, in particular if natural sorting is
2108 // enabled. Use all CPU cores to speed up the sorting process.
2109 static const int numberOfThreads
= QThread::idealThreadCount();
2110 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2112 // Sorting by other roles is quite fast. Use only one thread to prevent
2113 // problems caused by non-reentrant comparison functions, see
2114 // https://bugs.kde.org/show_bug.cgi?id=312679
2115 mergeSort(begin
, end
, lambdaLessThan
);
2119 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2121 // This function must never return 0, because that would break stable
2122 // sorting, which leads to all kinds of bugs.
2123 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2124 // If two items have equal sort values, let the fallbacks at the bottom of
2125 // the function handle it.
2126 const KFileItem
&itemA
= a
->item
;
2127 const KFileItem
&itemB
= b
->item
;
2131 switch (m_sortRole
) {
2133 // The name role is handled as default fallback after the switch
2137 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
&& itemA
.isDir()) {
2138 // folders first then
2139 // items A and B are folders thanks to lessThan checks
2140 auto valueA
= a
->values
.value("count");
2141 auto valueB
= b
->values
.value("count");
2142 if (valueA
.isNull()) {
2143 if (!valueB
.isNull()) {
2146 } else if (valueB
.isNull()) {
2149 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2151 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2158 KIO::filesize_t sizeA
= 0;
2159 if (itemA
.isDir()) {
2160 sizeA
= a
->values
.value("size").toULongLong();
2162 sizeA
= itemA
.size();
2164 KIO::filesize_t sizeB
= 0;
2165 if (itemB
.isDir()) {
2166 sizeB
= b
->values
.value("size").toULongLong();
2168 sizeB
= itemB
.size();
2170 if (sizeA
< sizeB
) {
2172 } else if (sizeA
> sizeB
) {
2178 case ModificationTimeRole
: {
2179 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2180 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2181 if (dateTimeA
< dateTimeB
) {
2183 } else if (dateTimeA
> dateTimeB
) {
2189 case AccessTimeRole
: {
2190 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2191 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2192 if (dateTimeA
< dateTimeB
) {
2194 } else if (dateTimeA
> dateTimeB
) {
2200 case CreationTimeRole
: {
2201 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2202 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2203 if (dateTimeA
< dateTimeB
) {
2205 } else if (dateTimeA
> dateTimeB
) {
2211 case DeletionTimeRole
: {
2212 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2213 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2214 if (dateTimeA
< dateTimeB
) {
2216 } else if (dateTimeA
> dateTimeB
) {
2230 case ReleaseYearRole
: {
2231 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2235 case DimensionsRole
: {
2236 const QByteArray role
= roleForType(m_sortRole
);
2237 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2238 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2240 if (dimensionsA
.width() == dimensionsB
.width()) {
2241 result
= dimensionsA
.height() - dimensionsB
.height();
2243 result
= dimensionsA
.width() - dimensionsB
.width();
2249 const QByteArray role
= roleForType(m_sortRole
);
2250 const QString roleValueA
= a
->values
.value(role
).toString();
2251 const QString roleValueB
= b
->values
.value(role
).toString();
2252 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2254 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2256 } else if (isRoleValueNatural(m_sortRole
)) {
2257 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2259 result
= QString::compare(roleValueA
, roleValueB
);
2266 // The current sort role was sufficient to define an order
2270 // Fallback #1: Compare the text of the items
2271 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2276 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2277 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2282 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2283 // equal. In this case a comparison of the URL is done which is unique in all cases
2284 // within KDirLister.
2285 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2288 int KFileItemModel::groupRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2290 // Unlike sortRoleCompare, this function can and often will return 0.
2294 switch (m_groupRole
) {
2298 groupA
= nameRoleGroup(a
, false).comparable
;
2299 groupB
= nameRoleGroup(b
, false).comparable
;
2302 groupA
= sizeRoleGroup(a
, false).comparable
;
2303 groupB
= sizeRoleGroup(b
, false).comparable
;
2305 case ModificationTimeRole
:
2306 groupA
= timeRoleGroup(
2307 [](const ItemData
*item
) {
2308 return item
->item
.time(KFileItem::ModificationTime
);
2313 groupB
= timeRoleGroup(
2314 [](const ItemData
*item
) {
2315 return item
->item
.time(KFileItem::ModificationTime
);
2321 case CreationTimeRole
:
2322 groupA
= timeRoleGroup(
2323 [](const ItemData
*item
) {
2324 return item
->item
.time(KFileItem::CreationTime
);
2329 groupB
= timeRoleGroup(
2330 [](const ItemData
*item
) {
2331 return item
->item
.time(KFileItem::CreationTime
);
2337 case AccessTimeRole
:
2338 groupA
= timeRoleGroup(
2339 [](const ItemData
*item
) {
2340 return item
->item
.time(KFileItem::AccessTime
);
2345 groupB
= timeRoleGroup(
2346 [](const ItemData
*item
) {
2347 return item
->item
.time(KFileItem::AccessTime
);
2353 case DeletionTimeRole
:
2354 groupA
= timeRoleGroup(
2355 [](const ItemData
*item
) {
2356 return item
->values
.value("deletiontime").toDateTime();
2361 groupB
= timeRoleGroup(
2362 [](const ItemData
*item
) {
2363 return item
->values
.value("deletiontime").toDateTime();
2369 case PermissionsRole
:
2370 groupA
= permissionRoleGroup(a
, false).comparable
;
2371 groupB
= permissionRoleGroup(b
, false).comparable
;
2374 groupA
= ratingRoleGroup(a
, false).comparable
;
2375 groupB
= ratingRoleGroup(b
, false).comparable
;
2378 QString strGroupA
= genericStringRoleGroup(groupRole(), a
);
2379 QString strGroupB
= genericStringRoleGroup(groupRole(), b
);
2380 result
= stringCompare(strGroupA
, strGroupB
, collator
);
2385 if (groupA
< groupB
) {
2387 } else if (groupA
> groupB
) {
2394 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2396 QMutexLocker
collatorLock(s_collatorMutex());
2398 if (m_naturalSorting
) {
2399 return collator
.compare(a
, b
);
2402 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2403 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2404 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2405 // comparison, still a deterministic sort order is required. A case sensitive
2406 // comparison is done as fallback.
2410 return QString::compare(a
, b
, Qt::CaseSensitive
);
2413 KFileItemModel::ItemGroupInfo
KFileItemModel::nameRoleGroup(const ItemData
*itemData
, bool withString
) const
2415 static ItemGroupInfo oldGroupInfo
;
2416 static QChar oldFirstChar
;
2417 ItemGroupInfo groupInfo
;
2420 const QString name
= itemData
->item
.text();
2422 // Use the first character of the name as group indication
2423 firstChar
= name
.at(0).toUpper();
2425 if (firstChar
== oldFirstChar
) {
2426 return oldGroupInfo
;
2428 if (firstChar
== QLatin1Char('~') && name
.length() > 1) {
2429 firstChar
= name
.at(1).toUpper();
2431 if (firstChar
.isLetter()) {
2432 if (m_collator
.compare(firstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(firstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2433 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2435 // Try to find a matching group in the range 'A' to 'Z'.
2436 static std::vector
<QChar
> lettersAtoZ
;
2437 lettersAtoZ
.reserve('Z' - 'A' + 1);
2438 if (lettersAtoZ
.empty()) {
2439 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2440 lettersAtoZ
.push_back(QLatin1Char(c
));
2444 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2445 return m_collator
.compare(c1
, c2
) < 0;
2448 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), firstChar
, localeAwareLessThan
);
2449 if (it
!= lettersAtoZ
.end()) {
2450 if (localeAwareLessThan(firstChar
, *it
)) {
2451 // newFirstChar belongs to the group preceding *it.
2452 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2456 groupInfo
.text
= *it
;
2458 groupInfo
.comparable
= (*it
).unicode();
2462 // Symbols from non Latin-based scripts
2464 groupInfo
.text
= firstChar
;
2466 groupInfo
.comparable
= firstChar
.unicode();
2468 } else if (firstChar
>= QLatin1Char('0') && firstChar
<= QLatin1Char('9')) {
2469 // Apply group '0 - 9' for any name that starts with a digit
2471 groupInfo
.text
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2473 groupInfo
.comparable
= (int)'0';
2476 groupInfo
.text
= i18nc("@title:group", "Others");
2478 groupInfo
.comparable
= (int)'.';
2480 oldFirstChar
= firstChar
;
2481 oldGroupInfo
= groupInfo
;
2485 KFileItemModel::ItemGroupInfo
KFileItemModel::sizeRoleGroup(const ItemData
*itemData
, bool withString
) const
2487 static ItemGroupInfo oldGroupInfo
;
2488 static KIO::filesize_t oldFileSize
;
2489 ItemGroupInfo groupInfo
;
2490 KIO::filesize_t fileSize
;
2492 const KFileItem item
= itemData
->item
;
2493 fileSize
= !item
.isNull() ? item
.size() : ~0U;
2495 groupInfo
.comparable
= -1; // None
2496 if (!item
.isNull() && item
.isDir()) {
2497 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount
|| m_sortDirsFirst
) {
2498 groupInfo
.comparable
= 0; // Folders
2500 fileSize
= itemData
->values
.value("size").toULongLong();
2503 if (fileSize
== oldFileSize
) {
2504 return oldGroupInfo
;
2506 if (groupInfo
.comparable
< 0) {
2507 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2508 groupInfo
.comparable
= 1; // Small
2509 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2510 groupInfo
.comparable
= 2; // Medium
2512 groupInfo
.comparable
= 3; // Big
2517 char const *groupNames
[] = {"Folders", "Small", "Medium", "Big"};
2518 groupInfo
.text
= i18nc("@title:group Size", groupNames
[groupInfo
.comparable
]);
2520 oldFileSize
= fileSize
;
2521 oldGroupInfo
= groupInfo
;
2525 KFileItemModel::ItemGroupInfo
2526 KFileItemModel::timeRoleGroup(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
, const ItemData
*itemData
, bool withString
) const
2528 static ItemGroupInfo oldGroupInfo
;
2529 static QDate oldFileDate
;
2530 ItemGroupInfo groupInfo
;
2532 const QDate currentDate
= QDate::currentDate();
2533 const QDateTime fileTime
= fileTimeCb(itemData
);
2534 const QDate fileDate
= fileTime
.date();
2535 const int daysDistance
= fileDate
.daysTo(currentDate
);
2537 // Simplified grouping algorithm, preserving dates
2538 // but not taking "pretty printing" into account
2539 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2540 if (daysDistance
< 7) {
2541 groupInfo
.comparable
= daysDistance
; // Today, Yesterday and week days
2542 } else if (daysDistance
< 14) {
2543 groupInfo
.comparable
= 10; // One Week Ago
2544 } else if (daysDistance
< 21) {
2545 groupInfo
.comparable
= 20; // Two Weeks Ago
2546 } else if (daysDistance
< 28) {
2547 groupInfo
.comparable
= 30; // Three Weeks Ago
2549 groupInfo
.comparable
= 40; // Earlier This Month
2552 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2553 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2554 if (daysDistance
< 7) {
2555 groupInfo
.comparable
= daysDistance
; // Today, Yesterday and week days (Month, Year)
2556 } else if (daysDistance
< 14) {
2557 groupInfo
.comparable
= 11; // One Week Ago (Month, Year)
2558 } else if (daysDistance
< 21) {
2559 groupInfo
.comparable
= 21; // Two Weeks Ago (Month, Year)
2560 } else if (daysDistance
< 28) {
2561 groupInfo
.comparable
= 31; // Three Weeks Ago (Month, Year)
2563 groupInfo
.comparable
= 41; // Earlier on Month, Year
2566 // The trick will fail for dates past April, 178956967 or before 1 AD.
2567 groupInfo
.comparable
= 2147483647 - (fileDate
.year() * 12 + fileDate
.month() - 1); // Month, Year; newer < older
2571 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2572 switch (daysDistance
/ 7) {
2574 switch (daysDistance
) {
2576 groupInfo
.text
= i18nc("@title:group Date", "Today");
2579 groupInfo
.text
= i18nc("@title:group Date", "Yesterday");
2582 groupInfo
.text
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2583 groupInfo
.text
= i18nc(
2584 "Can be used to script translation of \"dddd\""
2585 "with context @title:group Date",
2591 groupInfo
.text
= i18nc("@title:group Date", "One Week Ago");
2594 groupInfo
.text
= i18nc("@title:group Date", "Two Weeks Ago");
2597 groupInfo
.text
= i18nc("@title:group Date", "Three Weeks Ago");
2601 groupInfo
.text
= i18nc("@title:group Date", "Earlier this Month");
2607 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2608 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2609 if (daysDistance
== 1) {
2610 const KLocalizedString format
= ki18nc(
2611 "@title:group Date: "
2612 "MMMM is full month name in current locale, and yyyy is "
2613 "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 "
2614 "part of the text that should not be formatted as a date",
2615 "'Yesterday' (MMMM, yyyy)");
2616 const QString translatedFormat
= format
.toString();
2617 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2618 groupInfo
.text
= fileTime
.toString(translatedFormat
);
2619 groupInfo
.text
= i18nc(
2620 "Can be used to script translation of "
2621 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2625 qCWarning(DolphinDebug
).nospace()
2626 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2627 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2628 groupInfo
.text
= fileTime
.toString(untranslatedFormat
);
2630 } else if (daysDistance
< 7) {
2632 fileTime
.toString(i18nc("@title:group Date: "
2633 "The week day name: dddd, MMMM is full month name "
2634 "in current locale, and yyyy is full year number.",
2635 "dddd (MMMM, yyyy)"));
2636 groupInfo
.text
= i18nc(
2637 "Can be used to script translation of "
2638 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2641 } else if (daysDistance
< 7 * 2) {
2642 const KLocalizedString format
= ki18nc(
2643 "@title:group Date: "
2644 "MMMM is full month name in current locale, and yyyy is "
2645 "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 "
2646 "part of the text that should not be formatted as a date",
2647 "'One Week Ago' (MMMM, yyyy)");
2648 const QString translatedFormat
= format
.toString();
2649 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2650 groupInfo
.text
= fileTime
.toString(translatedFormat
);
2651 groupInfo
.text
= i18nc(
2652 "Can be used to script translation of "
2653 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2657 qCWarning(DolphinDebug
).nospace()
2658 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2659 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2660 groupInfo
.text
= fileTime
.toString(untranslatedFormat
);
2662 } else if (daysDistance
< 7 * 3) {
2663 const KLocalizedString format
= ki18nc(
2664 "@title:group Date: "
2665 "MMMM is full month name in current locale, and yyyy is "
2666 "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 "
2667 "part of the text that should not be formatted as a date",
2668 "'Two Weeks Ago' (MMMM, yyyy)");
2669 const QString translatedFormat
= format
.toString();
2670 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2671 groupInfo
.text
= fileTime
.toString(translatedFormat
);
2672 groupInfo
.text
= i18nc(
2673 "Can be used to script translation of "
2674 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2678 qCWarning(DolphinDebug
).nospace()
2679 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2680 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2681 groupInfo
.text
= fileTime
.toString(untranslatedFormat
);
2683 } else if (daysDistance
< 7 * 4) {
2684 const KLocalizedString format
= ki18nc(
2685 "@title:group Date: "
2686 "MMMM is full month name in current locale, and yyyy is "
2687 "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 "
2688 "part of the text that should not be formatted as a date",
2689 "'Three Weeks Ago' (MMMM, yyyy)");
2690 const QString translatedFormat
= format
.toString();
2691 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2692 groupInfo
.text
= fileTime
.toString(translatedFormat
);
2693 groupInfo
.text
= i18nc(
2694 "Can be used to script translation of "
2695 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2699 qCWarning(DolphinDebug
).nospace()
2700 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2701 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2702 groupInfo
.text
= fileTime
.toString(untranslatedFormat
);
2705 const KLocalizedString format
= ki18nc(
2706 "@title:group Date: "
2707 "MMMM is full month name in current locale, and yyyy is "
2708 "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 "
2709 "part of the text that should not be formatted as a date",
2710 "'Earlier on' MMMM, yyyy");
2711 const QString translatedFormat
= format
.toString();
2712 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2713 groupInfo
.text
= fileTime
.toString(translatedFormat
);
2714 groupInfo
.text
= i18nc(
2715 "Can be used to script translation of "
2716 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2720 qCWarning(DolphinDebug
).nospace()
2721 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2722 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2723 groupInfo
.text
= fileTime
.toString(untranslatedFormat
);
2728 fileTime
.toString(i18nc("@title:group "
2729 "The month and year: MMMM is full month name in current locale, "
2730 "and yyyy is full year number",
2732 groupInfo
.text
= i18nc(
2733 "Can be used to script translation of "
2734 "\"MMMM, yyyy\" with context @title:group Date",
2740 oldFileDate
= fileDate
;
2741 oldGroupInfo
= groupInfo
;
2745 KFileItemModel::ItemGroupInfo
KFileItemModel::permissionRoleGroup(const ItemData
*itemData
, bool withString
) const
2747 static ItemGroupInfo oldGroupInfo
;
2748 static QFileDevice::Permissions oldPermissions
;
2749 ItemGroupInfo groupInfo
;
2751 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2752 const QFileDevice::Permissions permissions
= info
.permissions();
2753 if (permissions
== oldPermissions
) {
2754 return oldGroupInfo
;
2756 groupInfo
.comparable
= (int)permissions
;
2761 if (permissions
& QFile::ReadUser
) {
2762 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2764 if (permissions
& QFile::WriteUser
) {
2765 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2767 if (permissions
& QFile::ExeUser
) {
2768 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2770 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2774 if (permissions
& QFile::ReadGroup
) {
2775 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2777 if (permissions
& QFile::WriteGroup
) {
2778 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2780 if (permissions
& QFile::ExeGroup
) {
2781 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2783 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2785 // Set others string
2787 if (permissions
& QFile::ReadOther
) {
2788 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2790 if (permissions
& QFile::WriteOther
) {
2791 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2793 if (permissions
& QFile::ExeOther
) {
2794 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2796 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2797 groupInfo
.text
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2799 oldPermissions
= permissions
;
2800 oldGroupInfo
= groupInfo
;
2804 KFileItemModel::ItemGroupInfo
KFileItemModel::ratingRoleGroup(const ItemData
*itemData
, bool withString
) const
2806 ItemGroupInfo groupInfo
;
2807 groupInfo
.comparable
= itemData
->values
.value("rating", 0).toInt();
2809 // Dolphin does not currently use string representation of star rating
2810 // as stars are rendered as graphics in group headers.
2811 groupInfo
.text
= i18nc("@item:intext Rated N (stars)", "Rated ") + QString::number(groupInfo
.comparable
);
2816 QString
KFileItemModel::genericStringRoleGroup(const QByteArray
&role
, const ItemData
*itemData
) const
2818 return itemData
->values
.value(role
).toString();
2821 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2823 Q_ASSERT(!m_itemData
.isEmpty());
2825 const int maxIndex
= count() - 1;
2826 QList
<QPair
<int, QVariant
>> groups
;
2828 ItemGroupInfo groupInfo
;
2829 for (int i
= 0; i
<= maxIndex
; ++i
) {
2830 if (isChildItem(i
)) {
2834 ItemGroupInfo newGroupInfo
= nameRoleGroup(m_itemData
.at(i
));
2836 if (newGroupInfo
!= groupInfo
) {
2837 groupInfo
= newGroupInfo
;
2838 groups
.append(QPair
<int, QVariant
>(i
, newGroupInfo
.text
));
2844 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2846 Q_ASSERT(!m_itemData
.isEmpty());
2848 const int maxIndex
= count() - 1;
2849 QList
<QPair
<int, QVariant
>> groups
;
2851 ItemGroupInfo groupInfo
;
2852 for (int i
= 0; i
<= maxIndex
; ++i
) {
2853 if (isChildItem(i
)) {
2857 ItemGroupInfo newGroupInfo
= sizeRoleGroup(m_itemData
.at(i
));
2859 if (newGroupInfo
!= groupInfo
) {
2860 groupInfo
= newGroupInfo
;
2861 groups
.append(QPair
<int, QVariant
>(i
, newGroupInfo
.text
));
2867 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2869 Q_ASSERT(!m_itemData
.isEmpty());
2871 const int maxIndex
= count() - 1;
2872 QList
<QPair
<int, QVariant
>> groups
;
2874 ItemGroupInfo groupInfo
;
2875 for (int i
= 0; i
<= maxIndex
; ++i
) {
2876 if (isChildItem(i
)) {
2880 ItemGroupInfo newGroupInfo
= timeRoleGroup(fileTimeCb
, m_itemData
.at(i
));
2882 if (newGroupInfo
!= groupInfo
) {
2883 groupInfo
= newGroupInfo
;
2884 groups
.append(QPair
<int, QVariant
>(i
, newGroupInfo
.text
));
2890 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2892 Q_ASSERT(!m_itemData
.isEmpty());
2894 const int maxIndex
= count() - 1;
2895 QList
<QPair
<int, QVariant
>> groups
;
2897 ItemGroupInfo groupInfo
;
2898 for (int i
= 0; i
<= maxIndex
; ++i
) {
2899 if (isChildItem(i
)) {
2903 ItemGroupInfo newGroupInfo
= permissionRoleGroup(m_itemData
.at(i
));
2905 if (newGroupInfo
!= groupInfo
) {
2906 groupInfo
= newGroupInfo
;
2907 groups
.append(QPair
<int, QVariant
>(i
, newGroupInfo
.text
));
2913 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2915 Q_ASSERT(!m_itemData
.isEmpty());
2917 const int maxIndex
= count() - 1;
2918 QList
<QPair
<int, QVariant
>> groups
;
2920 ItemGroupInfo groupInfo
;
2921 for (int i
= 0; i
<= maxIndex
; ++i
) {
2922 if (isChildItem(i
)) {
2926 ItemGroupInfo newGroupInfo
= ratingRoleGroup(m_itemData
.at(i
));
2928 if (newGroupInfo
!= groupInfo
) {
2929 groupInfo
= newGroupInfo
;
2930 // Using the numeric representation because Dolphin has a special
2931 // case for drawing stars.
2932 groups
.append(QPair
<int, QVariant
>(i
, newGroupInfo
.comparable
));
2938 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2940 Q_ASSERT(!m_itemData
.isEmpty());
2942 const int maxIndex
= count() - 1;
2943 QList
<QPair
<int, QVariant
>> groups
;
2946 for (int i
= 0; i
<= maxIndex
; ++i
) {
2947 if (isChildItem(i
)) {
2951 QString newGroupText
= genericStringRoleGroup(role
, m_itemData
.at(i
));
2953 if (newGroupText
!= groupText
) {
2954 groupText
= newGroupText
;
2955 groups
.append(QPair
<int, QVariant
>(i
, newGroupText
));
2961 void KFileItemModel::emitSortProgress(int resolvedCount
)
2963 // Be tolerant against a resolvedCount with a wrong range.
2964 // Although there should not be a case where KFileItemModelRolesUpdater
2965 // (= caller) provides a wrong range, it is important to emit
2966 // a useful progress information even if there is an unexpected
2967 // implementation issue.
2969 const int itemCount
= count();
2970 if (resolvedCount
>= itemCount
) {
2971 m_sortingProgressPercent
= -1;
2972 if (m_resortAllItemsTimer
->isActive()) {
2973 m_resortAllItemsTimer
->stop();
2977 Q_EMIT
directorySortingProgress(100);
2978 } else if (itemCount
> 0) {
2979 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2981 const int progress
= resolvedCount
* 100 / itemCount
;
2982 if (m_sortingProgressPercent
!= progress
) {
2983 m_sortingProgressPercent
= progress
;
2984 Q_EMIT
directorySortingProgress(progress
);
2989 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2991 static const RoleInfoMap rolesInfoMap
[] = {
2993 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2994 { nullptr, NoRole
, kli18nc("@label", "None"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2995 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2996 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2997 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2998 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2999 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
3000 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
3001 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3002 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3003 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3004 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3005 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3006 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3007 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3008 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3009 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3010 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3011 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3012 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3013 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3014 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3015 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3016 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3017 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3018 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3019 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3020 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3021 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3022 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
3023 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
3024 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3025 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3026 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3027 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3028 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
3029 { "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 },
3030 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3031 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3035 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
3036 return rolesInfoMap
;
3039 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
3041 QElapsedTimer timer
;
3043 for (const KFileItem
&item
: items
) {
3044 // Only determine mime types for files here. For directories,
3045 // KFileItem::determineMimeType() reads the .directory file inside to
3046 // load the icon, but this is not necessary at all if we just need the
3047 // type. Some special code for setting the correct mime type for
3048 // directories is in retrieveData().
3049 if (!item
.isDir()) {
3050 item
.determineMimeType();
3053 if (timer
.elapsed() > timeout
) {
3054 // Don't block the user interface, let the remaining items
3055 // be resolved asynchronously.
3061 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
3063 static QSet
<QByteArray
> pool
;
3064 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
3066 if (it
!= pool
.constEnd()) {
3074 bool KFileItemModel::isConsistent() const
3076 // m_items may contain less items than m_itemData because m_items
3077 // is populated lazily, see KFileItemModel::index(const QUrl& url).
3078 if (m_items
.count() > m_itemData
.count()) {
3082 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
3083 // Check if m_items and m_itemData are consistent.
3084 const KFileItem item
= fileItem(i
);
3085 if (item
.isNull()) {
3086 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
3090 const int itemIndex
= index(item
);
3091 if (itemIndex
!= i
) {
3092 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
3096 // Check if the items are sorted correctly.
3097 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
3098 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
3102 // Check if all parent-child relationships are consistent.
3103 const ItemData
*data
= m_itemData
.at(i
);
3104 const ItemData
*parent
= data
->parent
;
3106 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
3107 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
3111 const int parentIndex
= index(parent
->item
);
3112 if (parentIndex
>= i
) {
3113 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
3123 void KFileItemModel::slotListerError(KIO::Job
*job
)
3125 if (job
->error() == KIO::ERR_IS_FILE
) {
3126 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
3127 Q_EMIT
urlIsFileError(listJob
->url());
3130 const QString errorString
= job
->errorString();
3131 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));
3135 #include "moc_kfileitemmodel.cpp"