2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_contentdisplaysettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
18 #include <KIO/ListJob>
19 #include <KLocalizedString>
20 #include <KUrlMimeData>
22 #include <QElapsedTimer>
25 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
29 #include <klazylocalizedstring.h>
31 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(QObject
*parent
)
36 : KItemModelBase("text", parent
)
37 , m_dirLister(nullptr)
38 , m_sortDirsFirst(true)
39 , m_sortHiddenLast(false)
40 , m_sortRole(NameRole
)
41 , m_sortingProgressPercent(-1)
48 , m_maximumUpdateIntervalTimer(nullptr)
49 , m_resortAllItemsTimer(nullptr)
50 , m_pendingItemsToInsert()
55 m_collator
.setNumericMode(true);
57 loadSortingSettings();
59 m_dirLister
= new KDirLister(this);
60 m_dirLister
->setAutoErrorHandlingEnabled(false);
61 m_dirLister
->setDelayedMimeTypes(true);
63 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
65 m_dirLister
->setMainWindow(parentWidget
->window());
68 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
69 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
70 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
71 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
72 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
73 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
74 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
75 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
76 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
77 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
78 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
80 // Apply default roles that should be determined
82 m_requestRole
[NameRole
] = true;
83 m_requestRole
[IsDirRole
] = true;
84 m_requestRole
[IsLinkRole
] = true;
85 m_roles
.insert("text");
86 m_roles
.insert("isDir");
87 m_roles
.insert("isLink");
88 m_roles
.insert("isHidden");
90 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
91 // before the completed() or canceled() signal has been emitted.
92 m_maximumUpdateIntervalTimer
= new QTimer(this);
93 m_maximumUpdateIntervalTimer
->setInterval(2000);
94 m_maximumUpdateIntervalTimer
->setSingleShot(true);
95 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
97 // When changing the value of an item which represents the sort-role a resorting must be
98 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
99 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
100 // resorting is postponed until the timer has been exceeded.
101 m_resortAllItemsTimer
= new QTimer(this);
102 m_resortAllItemsTimer
->setInterval(50);
103 m_resortAllItemsTimer
->setSingleShot(true);
104 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
106 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
108 setShowTrashMime(m_dirLister
->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
111 KFileItemModel::~KFileItemModel()
113 qDeleteAll(m_itemData
);
114 qDeleteAll(m_filteredItems
);
115 qDeleteAll(m_pendingItemsToInsert
);
118 void KFileItemModel::loadDirectory(const QUrl
&url
)
120 m_dirLister
->openUrl(url
);
123 void KFileItemModel::refreshDirectory(const QUrl
&url
)
125 // Refresh all expanded directories first (Bug 295300)
126 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
127 while (expandedDirs
.hasNext()) {
129 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
132 m_dirLister
->openUrl(url
, KDirLister::Reload
);
134 Q_EMIT
directoryRefreshing();
137 QUrl
KFileItemModel::directory() const
139 return m_dirLister
->url();
142 void KFileItemModel::cancelDirectoryLoading()
147 int KFileItemModel::count() const
149 return m_itemData
.count();
152 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
154 if (index
>= 0 && index
< count()) {
155 ItemData
*data
= m_itemData
.at(index
);
156 if (data
->values
.isEmpty()) {
157 data
->values
= retrieveData(data
->item
, data
->parent
);
158 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
159 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
160 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
161 // so this special request of different behavior can be identified here.
162 bool hasExpandedParentsCount
= false;
163 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
165 data
->values
= retrieveData(data
->item
, data
->parent
);
166 data
->values
.insert("isExpanded", true);
167 if (hasExpandedParentsCount
) {
168 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
174 return QHash
<QByteArray
, QVariant
>();
177 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
179 if (index
< 0 || index
>= count()) {
183 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
185 // Determine which roles have been changed
186 QSet
<QByteArray
> changedRoles
;
187 QHashIterator
<QByteArray
, QVariant
> it(values
);
188 while (it
.hasNext()) {
190 const QByteArray role
= sharedValue(it
.key());
191 const QVariant value
= it
.value();
193 if (currentValues
[role
] != value
) {
194 currentValues
[role
] = value
;
195 changedRoles
.insert(role
);
199 if (changedRoles
.isEmpty()) {
203 m_itemData
[index
]->values
= currentValues
;
204 if (changedRoles
.contains("text")) {
205 QUrl url
= m_itemData
[index
]->item
.url();
206 url
= url
.adjusted(QUrl::RemoveFilename
);
207 url
.setPath(url
.path() + currentValues
["text"].toString());
208 m_itemData
[index
]->item
.setUrl(url
);
211 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
216 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
218 if (dirsFirst
!= m_sortDirsFirst
) {
219 m_sortDirsFirst
= dirsFirst
;
224 bool KFileItemModel::sortDirectoriesFirst() const
226 return m_sortDirsFirst
;
229 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
231 if (hiddenLast
!= m_sortHiddenLast
) {
232 m_sortHiddenLast
= hiddenLast
;
237 bool KFileItemModel::sortHiddenLast() const
239 return m_sortHiddenLast
;
242 void KFileItemModel::setShowTrashMime(bool showTrashMime
)
244 const auto trashMime
= QStringLiteral("application/x-trash");
245 QStringList excludeFilter
= m_filter
.excludeMimeTypes();
248 excludeFilter
.removeAll(trashMime
);
249 } else if (!excludeFilter
.contains(trashMime
)) {
250 excludeFilter
.append(trashMime
);
253 setExcludeMimeTypeFilter(excludeFilter
);
256 void KFileItemModel::scheduleResortAllItems()
258 if (!m_resortAllItemsTimer
->isActive()) {
259 m_resortAllItemsTimer
->start();
263 void KFileItemModel::setShowHiddenFiles(bool show
)
265 m_dirLister
->setShowHiddenFiles(show
);
266 setShowTrashMime(show
|| !GeneralSettings::hideXTrashFile());
267 m_dirLister
->emitChanges();
269 dispatchPendingItemsToInsert();
273 bool KFileItemModel::showHiddenFiles() const
275 return m_dirLister
->showHiddenFiles();
278 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
280 m_dirLister
->setDirOnlyMode(enabled
);
283 bool KFileItemModel::showDirectoriesOnly() const
285 return m_dirLister
->dirOnlyMode();
288 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
290 QMimeData
*data
= new QMimeData();
292 // The following code has been taken from KDirModel::mimeData()
293 // (kdelibs/kio/kio/kdirmodel.cpp)
294 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
296 QList
<QUrl
> mostLocalUrls
;
297 const ItemData
*lastAddedItem
= nullptr;
299 for (int index
: indexes
) {
300 const ItemData
*itemData
= m_itemData
.at(index
);
301 const ItemData
*parent
= itemData
->parent
;
303 while (parent
&& parent
!= lastAddedItem
) {
304 parent
= parent
->parent
;
307 if (parent
&& parent
== lastAddedItem
) {
308 // A parent of 'itemData' has been added already.
312 lastAddedItem
= itemData
;
313 const KFileItem
&item
= itemData
->item
;
314 if (!item
.isNull()) {
318 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
322 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
326 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
328 startFromIndex
= qMax(0, startFromIndex
);
329 for (int i
= startFromIndex
; i
< count(); ++i
) {
330 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
334 for (int i
= 0; i
< startFromIndex
; ++i
) {
335 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
342 bool KFileItemModel::supportsDropping(int index
) const
348 item
= fileItem(index
);
350 return !item
.isNull() && ((item
.isDir() && item
.isWritable()) || item
.isDesktopFile());
353 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
355 static QHash
<QByteArray
, QString
> description
;
356 if (description
.isEmpty()) {
358 const RoleInfoMap
*map
= rolesInfoMap(count
);
359 for (int i
= 0; i
< count
; ++i
) {
360 if (map
[i
].roleTranslation
.isEmpty()) {
363 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
367 return description
.value(role
);
370 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
372 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
373 #ifdef KFILEITEMMODEL_DEBUG
377 switch (typeForRole(sortRole())) {
379 m_groups
= nameRoleGroups();
382 m_groups
= sizeRoleGroups();
384 case ModificationTimeRole
:
385 m_groups
= timeRoleGroups([](const ItemData
*item
) {
386 return item
->item
.time(KFileItem::ModificationTime
);
389 case CreationTimeRole
:
390 m_groups
= timeRoleGroups([](const ItemData
*item
) {
391 return item
->item
.time(KFileItem::CreationTime
);
395 m_groups
= timeRoleGroups([](const ItemData
*item
) {
396 return item
->item
.time(KFileItem::AccessTime
);
399 case DeletionTimeRole
:
400 m_groups
= timeRoleGroups([](const ItemData
*item
) {
401 return item
->values
.value("deletiontime").toDateTime();
404 case PermissionsRole
:
405 m_groups
= permissionRoleGroups();
408 m_groups
= ratingRoleGroups();
411 m_groups
= genericStringRoleGroups(sortRole());
415 #ifdef KFILEITEMMODEL_DEBUG
416 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
423 KFileItem
KFileItemModel::fileItem(int index
) const
425 if (index
>= 0 && index
< count()) {
426 return m_itemData
.at(index
)->item
;
432 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
434 const int indexForUrl
= index(url
);
435 if (indexForUrl
>= 0) {
436 return m_itemData
.at(indexForUrl
)->item
;
441 int KFileItemModel::index(const KFileItem
&item
) const
443 return index(item
.url());
446 int KFileItemModel::index(const QUrl
&url
) const
448 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
450 const int itemCount
= m_itemData
.count();
451 int itemsInHash
= m_items
.count();
453 int index
= m_items
.value(urlToFind
, -1);
454 while (index
< 0 && itemsInHash
< itemCount
) {
455 // Not all URLs are stored yet in m_items. We grow m_items until either
456 // urlToFind is found, or all URLs have been stored in m_items.
457 // Note that we do not add the URLs to m_items one by one, but in
458 // larger blocks. After each block, we check if urlToFind is in
459 // m_items. We could in principle compare urlToFind with each URL while
460 // we are going through m_itemData, but comparing two QUrls will,
461 // unlike calling qHash for the URLs, trigger a parsing of the URLs
462 // which costs both CPU cycles and memory.
463 const int blockSize
= 1000;
464 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
465 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
466 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
467 m_items
.insert(nextUrl
, i
);
470 itemsInHash
= currentBlockEnd
;
471 index
= m_items
.value(urlToFind
, -1);
475 // The item could not be found, even though all items from m_itemData
476 // should be in m_items now. We print some diagnostic information which
477 // might help to find the cause of the problem, but only once. This
478 // prevents that obtaining and printing the debugging information
479 // wastes CPU cycles and floods the shell or .xsession-errors.
480 static bool printDebugInfo
= true;
482 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
483 printDebugInfo
= false;
485 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
486 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
487 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
489 // Check if there are multiple items with the same URL.
490 QMultiHash
<QUrl
, int> indexesForUrl
;
491 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
492 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
495 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
496 for (const QUrl
&url
: uniqueKeys
) {
497 if (indexesForUrl
.count(url
) > 1) {
498 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
500 auto it
= indexesForUrl
.find(url
);
501 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
502 const ItemData
*data
= m_itemData
.at(it
.value());
503 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
505 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
517 KFileItem
KFileItemModel::rootItem() const
519 return m_dirLister
->rootItem();
522 void KFileItemModel::clear()
527 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
529 if (m_roles
== roles
) {
533 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
537 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
538 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
539 if (supportedExpanding
&& !willSupportExpanding
) {
540 // No expanding is supported anymore. Take care to delete all items that have an expansion level
541 // that is not 0 (and hence are part of an expanded item).
542 removeExpandedItems();
549 QSetIterator
<QByteArray
> it(roles
);
550 while (it
.hasNext()) {
551 const QByteArray
&role
= it
.next();
552 m_requestRole
[typeForRole(role
)] = true;
556 // Update m_data with the changed requested roles
557 const int maxIndex
= count() - 1;
558 for (int i
= 0; i
<= maxIndex
; ++i
) {
559 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
562 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
565 // Clear the 'values' of all filtered items. They will be re-populated with the
566 // correct roles the next time 'values' will be accessed via data(int).
567 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
568 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
569 while (filteredIt
!= filteredEnd
) {
570 (*filteredIt
)->values
.clear();
575 QSet
<QByteArray
> KFileItemModel::roles() const
580 bool KFileItemModel::setExpanded(int index
, bool expanded
)
582 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
586 QHash
<QByteArray
, QVariant
> values
;
587 values
.insert(sharedValue("isExpanded"), expanded
);
588 if (!setData(index
, values
)) {
592 const KFileItem item
= m_itemData
.at(index
)->item
;
593 const QUrl url
= item
.url();
594 const QUrl targetUrl
= item
.targetUrl();
596 m_expandedDirs
.insert(targetUrl
, url
);
597 m_dirLister
->openUrl(url
, KDirLister::Keep
);
599 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
600 for (const QVariant
&var
: previouslyExpandedChildren
) {
601 m_urlsToExpand
.insert(var
.toUrl());
604 // Note that there might be (indirect) children of the folder which is to be collapsed in
605 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
606 // possibly without a parent, which might result in a crash, we insert all pending items
607 // right now. All new items which would be without a parent will then be removed.
608 dispatchPendingItemsToInsert();
610 // Check if the index of the collapsed folder has changed. If that is the case, then items
611 // were inserted before the collapsed folder, and its index needs to be updated.
612 if (m_itemData
.at(index
)->item
!= item
) {
613 index
= this->index(item
);
616 m_expandedDirs
.remove(targetUrl
);
617 m_dirLister
->stop(url
);
618 m_dirLister
->forgetDirs(url
);
620 const int parentLevel
= expandedParentsCount(index
);
621 const int itemCount
= m_itemData
.count();
622 const int firstChildIndex
= index
+ 1;
624 QVariantList expandedChildren
;
626 int childIndex
= firstChildIndex
;
627 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
628 ItemData
*itemData
= m_itemData
.at(childIndex
);
629 if (itemData
->values
.value("isExpanded").toBool()) {
630 const QUrl targetUrl
= itemData
->item
.targetUrl();
631 const QUrl url
= itemData
->item
.url();
632 m_expandedDirs
.remove(targetUrl
);
633 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
634 m_dirLister
->forgetDirs(url
);
635 expandedChildren
.append(targetUrl
);
639 const int childrenCount
= childIndex
- firstChildIndex
;
641 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
642 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
644 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
650 bool KFileItemModel::isExpanded(int index
) const
652 if (index
>= 0 && index
< count()) {
653 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
658 bool KFileItemModel::isExpandable(int index
) const
660 if (index
>= 0 && index
< count()) {
661 // Call data (instead of accessing m_itemData directly)
662 // to ensure that the value is initialized.
663 return data(index
).value("isExpandable").toBool();
668 int KFileItemModel::expandedParentsCount(int index
) const
670 if (index
>= 0 && index
< count()) {
671 return expandedParentsCount(m_itemData
.at(index
));
676 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
679 const auto dirs
= m_expandedDirs
;
680 for (const auto &dir
: dirs
) {
686 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
688 m_urlsToExpand
= urls
;
691 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
693 // Assure that each sub-path of the URL that should be
694 // expanded is added to m_urlsToExpand. KDirLister
695 // does not care whether the parent-URL has already been
697 QUrl urlToExpand
= m_dirLister
->url();
698 const int pos
= urlToExpand
.path().length();
700 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
701 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
702 // so using QString::SkipEmptyParts
703 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
704 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
705 QString path
= urlToExpand
.path();
706 if (!path
.endsWith(QLatin1Char('/'))) {
707 path
.append(QLatin1Char('/'));
709 urlToExpand
.setPath(path
+ subDirs
.at(i
));
710 m_urlsToExpand
.insert(urlToExpand
);
713 // KDirLister::open() must called at least once to trigger an initial
714 // loading. The pending URLs that must be restored are handled
715 // in slotCompleted().
716 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
717 while (it2
.hasNext()) {
718 const int idx
= index(it2
.next());
719 if (idx
>= 0 && !isExpanded(idx
)) {
720 setExpanded(idx
, true);
726 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
728 if (m_filter
.pattern() != nameFilter
) {
729 dispatchPendingItemsToInsert();
730 m_filter
.setPattern(nameFilter
);
735 QString
KFileItemModel::nameFilter() const
737 return m_filter
.pattern();
740 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
742 if (m_filter
.mimeTypes() != filters
) {
743 dispatchPendingItemsToInsert();
744 m_filter
.setMimeTypes(filters
);
749 QStringList
KFileItemModel::mimeTypeFilters() const
751 return m_filter
.mimeTypes();
754 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList
&filters
)
756 if (m_filter
.excludeMimeTypes() != filters
) {
757 dispatchPendingItemsToInsert();
758 m_filter
.setExcludeMimeTypes(filters
);
763 QStringList
KFileItemModel::excludeMimeTypeFilter() const
765 return m_filter
.excludeMimeTypes();
768 void KFileItemModel::applyFilters()
771 // Check which previously shown items from m_itemData must now get
772 // hidden and hence moved from m_itemData into m_filteredItems.
774 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
776 // This pointer will refer to the next confirmed shown item from the point of
777 // view of the current "itemData" in the upcoming "for" loop.
778 ItemData
*itemShownBelow
= nullptr;
780 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
781 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
782 ItemData
*itemData
= m_itemData
.at(index
);
784 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
785 // We could've entered here for two reasons:
786 // 1. This item passes the filter itself
787 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
789 // So this item must remain shown.
790 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
791 itemShownBelow
= itemData
;
793 // We hide this item for now, however, for expanded folders this is not final:
794 // if after the next "for" loop we discover that its children must now be shown with the newly applied fliter, we shall re-insert it
795 newFilteredIndexes
.prepend(index
);
796 m_filteredItems
.insert(itemData
->item
, itemData
);
797 // indexShownBelow doesn't get updated since this item will be hidden
801 // This will remove the newly filtered items from m_itemData
802 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
805 // Check which hidden items from m_filteredItems should
806 // become visible again and hence moved from m_filteredItems back into m_itemData.
808 QList
<ItemData
*> newVisibleItems
;
810 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
812 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
813 while (it
!= m_filteredItems
.end()) {
814 if (m_filter
.matches(it
.key())) {
815 newVisibleItems
.append(it
.value());
817 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
818 // We will go up through its parental chain until we either:
819 // 1 - reach the "root item" of the current view, i.e the currently opened folder on Dolphin. Their children have their ItemData::parent set to
820 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
821 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
822 parent
= parent
->parent
) {
823 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
824 // and it would mess up the iteration. We will mark it to be removed in step 3.
825 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
828 it
= m_filteredItems
.erase(it
);
830 // Item remains filtered for now
831 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
837 // Handles the ancestorsOfNewVisibleItems.
838 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
839 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
840 if (m_filteredItems
.remove(it
.key())) {
841 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
842 newVisibleItems
.append(it
.value());
846 // This will insert the newly discovered unfiltered items into m_itemData
847 insertItems(newVisibleItems
);
850 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
852 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
853 // There are either no filtered items, or it is not possible to expand
854 // folders -> there cannot be any filtered children.
858 QSet
<ItemData
*> parents
;
859 for (const KItemRange
&range
: itemRanges
) {
860 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
861 parents
.insert(m_itemData
.at(index
));
865 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
866 while (it
!= m_filteredItems
.end()) {
867 if (parents
.contains(it
.value()->parent
)) {
869 it
= m_filteredItems
.erase(it
);
876 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
878 static QList
<RoleInfo
> rolesInfo
;
879 if (rolesInfo
.isEmpty()) {
881 const RoleInfoMap
*map
= rolesInfoMap(count
);
882 for (int i
= 0; i
< count
; ++i
) {
883 if (map
[i
].roleType
!= NoRole
) {
885 info
.role
= map
[i
].role
;
886 info
.translation
= map
[i
].roleTranslation
.toString();
887 if (!map
[i
].groupTranslation
.isEmpty()) {
888 info
.group
= map
[i
].groupTranslation
.toString();
890 // For top level roles, groupTranslation is 0. We must make sure that
891 // info.group is an empty string then because the code that generates
892 // menus tries to put the actions into sub menus otherwise.
893 info
.group
= QString();
895 info
.requiresBaloo
= map
[i
].requiresBaloo
;
896 info
.requiresIndexer
= map
[i
].requiresIndexer
;
897 if (!map
[i
].tooltipTranslation
.isEmpty()) {
898 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
900 info
.tooltip
= QString();
902 rolesInfo
.append(info
);
910 void KFileItemModel::onGroupedSortingChanged(bool current
)
916 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
919 m_sortRole
= typeForRole(current
);
921 if (!m_requestRole
[m_sortRole
]) {
922 QSet
<QByteArray
> newRoles
= m_roles
;
932 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
939 void KFileItemModel::loadSortingSettings()
941 using Choice
= GeneralSettings::EnumSortingChoice
;
942 switch (GeneralSettings::sortingChoice()) {
943 case Choice::NaturalSorting
:
944 m_naturalSorting
= true;
945 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
947 case Choice::CaseSensitiveSorting
:
948 m_naturalSorting
= false;
949 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
951 case Choice::CaseInsensitiveSorting
:
952 m_naturalSorting
= false;
953 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
958 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
959 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
960 m_collator
.compare(QString(), QString());
963 void KFileItemModel::resortAllItems()
965 m_resortAllItemsTimer
->stop();
967 const int itemCount
= count();
968 if (itemCount
<= 0) {
972 #ifdef KFILEITEMMODEL_DEBUG
975 qCDebug(DolphinDebug
) << "===========================================================";
976 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
979 // Remember the order of the current URLs so
980 // that it can be determined which indexes have
981 // been moved because of the resorting.
983 oldUrls
.reserve(itemCount
);
984 for (const ItemData
*itemData
: std::as_const(m_itemData
)) {
985 oldUrls
.append(itemData
->item
.url());
989 m_items
.reserve(itemCount
);
992 sort(m_itemData
.begin(), m_itemData
.end());
993 for (int i
= 0; i
< itemCount
; ++i
) {
994 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
997 // Determine the first index that has been moved.
998 int firstMovedIndex
= 0;
999 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
1003 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
1004 if (itemsHaveMoved
) {
1007 int lastMovedIndex
= itemCount
- 1;
1008 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
1012 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
1014 // Create a list movedToIndexes, which has the property that
1015 // movedToIndexes[i] is the new index of the item with the old index
1016 // firstMovedIndex + i.
1017 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
1018 QList
<int> movedToIndexes
;
1019 movedToIndexes
.reserve(movedItemsCount
);
1020 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
1021 const int newIndex
= m_items
.value(oldUrls
.at(i
));
1022 movedToIndexes
.append(newIndex
);
1025 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
1026 } else if (groupedSorting()) {
1027 // The groups might have changed even if the order of the items has not.
1028 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
1030 if (groups() != oldGroups
) {
1031 Q_EMIT
groupsChanged();
1035 #ifdef KFILEITEMMODEL_DEBUG
1036 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1040 void KFileItemModel::slotCompleted()
1042 m_maximumUpdateIntervalTimer
->stop();
1043 dispatchPendingItemsToInsert();
1045 if (!m_urlsToExpand
.isEmpty()) {
1046 // Try to find a URL that can be expanded.
1047 // Note that the parent folder must be expanded before any of its subfolders become visible.
1048 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1049 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1050 // Iterate over a const copy because items are deleted and inserted within the loop
1051 const auto urlsToExpand
= m_urlsToExpand
;
1052 for (const QUrl
&url
: urlsToExpand
) {
1053 const int indexForUrl
= index(url
);
1054 if (indexForUrl
>= 0) {
1055 m_urlsToExpand
.remove(url
);
1056 if (setExpanded(indexForUrl
, true)) {
1057 // The dir lister has been triggered. This slot will be called
1058 // again after the directory has been expanded.
1064 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1065 // if these URLs have been deleted in the meantime.
1066 m_urlsToExpand
.clear();
1069 Q_EMIT
directoryLoadingCompleted();
1072 void KFileItemModel::slotCanceled()
1074 m_maximumUpdateIntervalTimer
->stop();
1075 dispatchPendingItemsToInsert();
1077 Q_EMIT
directoryLoadingCanceled();
1080 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1082 Q_ASSERT(!items
.isEmpty());
1084 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1086 if (m_requestRole
[ExpandedParentsCountRole
]) {
1087 // If the expanding of items is enabled, the call
1088 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1089 // might result in emitting the same items twice due to the Keep-parameter.
1090 // This case happens if an item gets expanded, collapsed and expanded again
1091 // before the items could be loaded for the first expansion.
1092 if (index(items
.first().url()) >= 0) {
1093 // The items are already part of the model.
1097 if (directoryUrl
!= directory()) {
1098 // To be able to compare whether the new items may be inserted as children
1099 // of a parent item the pending items must be added to the model first.
1100 dispatchPendingItemsToInsert();
1103 // KDirLister keeps the children of items that got expanded once even if
1104 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1105 // checked whether the parent for new items is still expanded.
1106 const int parentIndex
= index(parentUrl
);
1107 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1108 // The parent is not expanded.
1113 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1115 if (!m_filter
.hasSetFilters()) {
1116 m_pendingItemsToInsert
.append(itemDataList
);
1118 QSet
<ItemData
*> parentsToEnsureVisible
;
1120 // The name or type filter is active. Hide filtered items
1121 // before inserting them into the model and remember
1122 // the filtered items in m_filteredItems.
1123 for (ItemData
*itemData
: itemDataList
) {
1124 if (m_filter
.matches(itemData
->item
)) {
1125 m_pendingItemsToInsert
.append(itemData
);
1126 if (itemData
->parent
) {
1127 parentsToEnsureVisible
.insert(itemData
->parent
);
1130 m_filteredItems
.insert(itemData
->item
, itemData
);
1134 // Entire parental chains must be shown
1135 for (ItemData
*parent
: parentsToEnsureVisible
) {
1136 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1137 m_pendingItemsToInsert
.append(parent
);
1142 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1143 // Assure that items get dispatched if no completed() or canceled() signal is
1144 // emitted during the maximum update interval.
1145 m_maximumUpdateIntervalTimer
->start();
1148 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1151 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1153 int filteredParentsCount
= 0;
1154 // The childless parents not yet removed will always be right above the start of a removed range.
1155 // We iterate backwards to ensure the deepest folders are processed before their parents
1156 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1157 KItemRange itemRange
= removedItemRanges
.at(i
);
1158 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1159 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1160 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1162 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1163 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1164 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1165 // and this deleted range covers all of its descendents, so none will be left.
1166 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1167 // This range's starting index will be extended to include the parent above:
1170 ++filteredParentsCount
;
1171 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1172 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1173 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1174 previousRange
.count
+= itemRange
.count
;
1175 removedItemRanges
.replace(i
- 1, previousRange
);
1176 removedItemRanges
.removeAt(i
);
1178 removedItemRanges
.replace(i
, itemRange
);
1179 // We must revisit this range in the next iteration since its starting index changed
1184 return filteredParentsCount
;
1187 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1189 dispatchPendingItemsToInsert();
1191 QVector
<int> indexesToRemove
;
1192 indexesToRemove
.reserve(items
.count());
1193 KFileItemList dirsChanged
;
1195 const auto currentDir
= directory();
1197 for (const KFileItem
&item
: items
) {
1198 if (item
.url() == currentDir
) {
1199 // #473377: Delay emitting currentDirectoryRemoved() to avoid modifying KCoreDirLister
1200 // before KCoreDirListerCache::deleteDir() returns.
1201 QTimer::singleShot(0, this, [this] {
1202 Q_EMIT
currentDirectoryRemoved();
1208 const int indexForItem
= index(item
);
1209 if (indexForItem
>= 0) {
1210 indexesToRemove
.append(indexForItem
);
1212 // Probably the item has been filtered.
1213 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1214 if (it
!= m_filteredItems
.end()) {
1216 m_filteredItems
.erase(it
);
1220 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1221 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1222 dirsChanged
<< KFileItem(parentUrl
);
1226 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1228 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1229 // Assure that removing a parent item also results in removing all children
1230 QVector
<int> indexesToRemoveWithChildren
;
1231 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1233 const int itemCount
= m_itemData
.count();
1234 for (int index
: std::as_const(indexesToRemove
)) {
1235 indexesToRemoveWithChildren
.append(index
);
1237 const int parentLevel
= expandedParentsCount(index
);
1238 int childIndex
= index
+ 1;
1239 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1240 indexesToRemoveWithChildren
.append(childIndex
);
1245 indexesToRemove
= indexesToRemoveWithChildren
;
1248 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1249 removeFilteredChildren(itemRanges
);
1251 // This call will update itemRanges to include the childless parents that have been filtered.
1252 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1254 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1255 // mixed with expanded folders that are just being filtered out.
1256 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1257 // so removeItems() will check m_filteredItems to differentiate which is which.
1258 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1260 Q_EMIT
fileItemsChanged(dirsChanged
);
1263 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1265 Q_ASSERT(!items
.isEmpty());
1266 #ifdef KFILEITEMMODEL_DEBUG
1267 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1270 // Get the indexes of all items that have been refreshed
1272 indexes
.reserve(items
.count());
1274 QSet
<QByteArray
> changedRoles
;
1275 KFileItemList changedFiles
;
1277 // Contains the indexes of the currently visible items
1278 // that should get hidden and hence moved to m_filteredItems.
1279 QVector
<int> newFilteredIndexes
;
1281 // Contains currently hidden items that should
1282 // get visible and hence removed from m_filteredItems
1283 QList
<ItemData
*> newVisibleItems
;
1285 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1287 while (it
.hasNext()) {
1288 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1289 const KFileItem
&oldItem
= itemPair
.first
;
1290 const KFileItem
&newItem
= itemPair
.second
;
1291 const int indexForItem
= index(oldItem
);
1292 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1293 if (indexForItem
>= 0) {
1294 m_itemData
[indexForItem
]->item
= newItem
;
1296 // Keep old values as long as possible if they could not retrieved synchronously yet.
1297 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1298 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1299 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1300 while (it
.hasNext()) {
1302 const QByteArray
&role
= it
.key();
1303 if (itemData
->values
.value(role
) != it
.value()) {
1304 itemData
->values
.insert(role
, it
.value());
1305 changedRoles
.insert(role
);
1309 m_items
.remove(oldItem
.url());
1310 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1311 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1312 m_items
.insert(newItem
.url(), indexForItem
);
1313 if (newItemMatchesFilter
1314 || (itemData
->values
.value("isExpanded").toBool()
1315 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1316 // We are lenient with expanded folders that originally had visible children.
1317 // If they become childless now they will be caught by filterChildlessParents()
1318 changedFiles
.append(newItem
);
1319 indexes
.append(indexForItem
);
1321 newFilteredIndexes
.append(indexForItem
);
1322 m_filteredItems
.insert(newItem
, itemData
);
1325 // Check if 'oldItem' is one of the filtered items.
1326 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1327 if (it
!= m_filteredItems
.end()) {
1328 ItemData
*const itemData
= it
.value();
1329 itemData
->item
= newItem
;
1331 // The data stored in 'values' might have changed. Therefore, we clear
1332 // 'values' and re-populate it the next time it is requested via data(int).
1333 // Before clearing, we must remember if it was expanded and the expanded parents count,
1334 // otherwise these states would be lost. The data() method will deal with this special case.
1335 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1336 bool hasExpandedParentsCount
= false;
1337 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1338 itemData
->values
.clear();
1340 itemData
->values
.insert("isExpanded", true);
1341 if (hasExpandedParentsCount
) {
1342 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1346 m_filteredItems
.erase(it
);
1347 if (newItemMatchesFilter
) {
1348 newVisibleItems
.append(itemData
);
1350 m_filteredItems
.insert(newItem
, itemData
);
1356 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1358 // We must keep track of parents of new visible items since they must be shown no matter what
1359 // They will be considered "immune" to filterChildlessParents()
1360 QSet
<ItemData
*> parentsToEnsureVisible
;
1362 for (ItemData
*item
: newVisibleItems
) {
1363 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1364 parentsToEnsureVisible
.insert(parent
);
1367 for (ItemData
*parent
: parentsToEnsureVisible
) {
1368 // We make sure they are all unfiltered.
1369 if (m_filteredItems
.remove(parent
->item
)) {
1370 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1371 newVisibleItems
.append(parent
);
1372 // It could be in newFilteredIndexes, we must remove it if it's there:
1373 const int parentIndex
= index(parent
->item
);
1374 if (parentIndex
>= 0) {
1375 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1376 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1377 newFilteredIndexes
.erase(it
);
1383 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1385 // This call will update itemRanges to include the childless parents that have been filtered.
1386 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1388 removeItems(removedRanges
, KeepItemData
);
1390 // Show previously hidden items that should get visible
1391 insertItems(newVisibleItems
);
1393 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1395 // If the changed items have been created recently, they might not be in m_items yet.
1396 // In that case, the list 'indexes' might be empty.
1397 if (indexes
.isEmpty()) {
1401 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1402 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1404 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1405 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1406 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1407 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1412 std::sort(indexes
.begin(), indexes
.end());
1415 // Extract the item-ranges out of the changed indexes
1416 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1417 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1419 Q_EMIT
fileItemsChanged(changedFiles
);
1422 void KFileItemModel::slotClear()
1424 #ifdef KFILEITEMMODEL_DEBUG
1425 qCDebug(DolphinDebug
) << "Clearing all items";
1428 qDeleteAll(m_filteredItems
);
1429 m_filteredItems
.clear();
1432 m_maximumUpdateIntervalTimer
->stop();
1433 m_resortAllItemsTimer
->stop();
1435 qDeleteAll(m_pendingItemsToInsert
);
1436 m_pendingItemsToInsert
.clear();
1438 const int removedCount
= m_itemData
.count();
1439 if (removedCount
> 0) {
1440 qDeleteAll(m_itemData
);
1443 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1446 m_expandedDirs
.clear();
1449 void KFileItemModel::slotSortingChoiceChanged()
1451 loadSortingSettings();
1455 void KFileItemModel::dispatchPendingItemsToInsert()
1457 if (!m_pendingItemsToInsert
.isEmpty()) {
1458 insertItems(m_pendingItemsToInsert
);
1459 m_pendingItemsToInsert
.clear();
1463 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1465 if (newItems
.isEmpty()) {
1469 #ifdef KFILEITEMMODEL_DEBUG
1470 QElapsedTimer timer
;
1472 qCDebug(DolphinDebug
) << "===========================================================";
1473 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1477 prepareItemsForSorting(newItems
);
1479 // Natural sorting of items can be very slow. However, it becomes much faster
1480 // if the input sequence is already mostly sorted. Therefore, we first sort
1481 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1482 if (m_naturalSorting
) {
1483 if (m_sortRole
== NameRole
) {
1484 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1485 } else if (isRoleValueNatural(m_sortRole
)) {
1486 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1487 const QByteArray role
= roleForType(m_sortRole
);
1488 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1490 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1494 sort(newItems
.begin(), newItems
.end());
1496 #ifdef KFILEITEMMODEL_DEBUG
1497 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1500 KItemRangeList itemRanges
;
1501 const int existingItemCount
= m_itemData
.count();
1502 const int newItemCount
= newItems
.count();
1503 const int totalItemCount
= existingItemCount
+ newItemCount
;
1505 if (existingItemCount
== 0) {
1506 // Optimization for the common special case that there are no
1507 // items in the model yet. Happens, e.g., when entering a folder.
1508 m_itemData
= newItems
;
1509 itemRanges
<< KItemRange(0, newItemCount
);
1511 m_itemData
.reserve(totalItemCount
);
1512 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1513 m_itemData
.append(nullptr);
1516 // We build the new list m_itemData in reverse order to minimize
1517 // the number of moves and guarantee O(N) complexity.
1518 int targetIndex
= totalItemCount
- 1;
1519 int sourceIndexExistingItems
= existingItemCount
- 1;
1520 int sourceIndexNewItems
= newItemCount
- 1;
1524 while (sourceIndexNewItems
>= 0) {
1525 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1526 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1527 // Move an existing item to its new position. If any new items
1528 // are behind it, push the item range to itemRanges.
1529 if (rangeCount
> 0) {
1530 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1534 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1535 --sourceIndexExistingItems
;
1537 // Insert a new item into the list.
1539 m_itemData
[targetIndex
] = newItem
;
1540 --sourceIndexNewItems
;
1545 // Push the final item range to itemRanges.
1546 if (rangeCount
> 0) {
1547 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1550 // Note that itemRanges is still sorted in reverse order.
1551 std::reverse(itemRanges
.begin(), itemRanges
.end());
1554 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1555 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1558 Q_EMIT
itemsInserted(itemRanges
);
1560 #ifdef KFILEITEMMODEL_DEBUG
1561 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1565 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1567 if (itemRanges
.isEmpty()) {
1573 // Step 1: Remove the items from m_itemData, and free the ItemData.
1574 int removedItemsCount
= 0;
1575 for (const KItemRange
&range
: itemRanges
) {
1576 removedItemsCount
+= range
.count
;
1578 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1579 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1580 delete m_itemData
.at(index
);
1583 m_itemData
[index
] = nullptr;
1587 // Step 2: Remove the ItemData pointers from the list m_itemData.
1588 int target
= itemRanges
.at(0).index
;
1589 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1592 const int oldItemDataCount
= m_itemData
.count();
1593 while (source
< oldItemDataCount
) {
1594 m_itemData
[target
] = m_itemData
[source
];
1598 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1599 // Skip the items in the next removed range.
1600 source
+= itemRanges
.at(nextRange
).count
;
1605 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1607 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1608 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1611 Q_EMIT
itemsRemoved(itemRanges
);
1614 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1616 if (m_sortRole
== TypeRole
) {
1617 // Try to resolve the MIME-types synchronously to prevent a reordering of
1618 // the items when sorting by type (per default MIME-types are resolved
1619 // asynchronously by KFileItemModelRolesUpdater).
1620 determineMimeTypes(items
, 200);
1623 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1624 const int parentIndex
= index(parentUrl
);
1625 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1627 QList
<ItemData
*> itemDataList
;
1628 itemDataList
.reserve(items
.count());
1630 for (const KFileItem
&item
: items
) {
1631 ItemData
*itemData
= new ItemData();
1632 itemData
->item
= item
;
1633 itemData
->parent
= parentItem
;
1634 itemDataList
.append(itemData
);
1637 return itemDataList
;
1640 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1642 switch (m_sortRole
) {
1644 case PermissionsRole
:
1647 case DestinationRole
:
1649 case DeletionTimeRole
:
1650 // These roles can be determined with retrieveData, and they have to be stored
1651 // in the QHash "values" for the sorting.
1652 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1653 if (itemData
->values
.isEmpty()) {
1654 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1660 // At least store the data including the file type for items with known MIME type.
1661 for (ItemData
*itemData
: std::as_const(itemDataList
)) {
1662 if (itemData
->values
.isEmpty()) {
1663 const KFileItem item
= itemData
->item
;
1664 if (item
.isDir() || item
.isMimeTypeKnown()) {
1665 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1672 // The other roles are either resolved by KFileItemModelRolesUpdater
1673 // (this includes the SizeRole for directories), or they do not need
1674 // to be stored in the QHash "values" for sorting because the data can
1675 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1681 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1683 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1684 // if the corresponding item is expanded, and it is not a top-level item.
1685 const ItemData
*parent
= data
->parent
;
1687 if (parent
->parent
) {
1688 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1689 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1698 void KFileItemModel::removeExpandedItems()
1700 QVector
<int> indexesToRemove
;
1702 const int maxIndex
= m_itemData
.count() - 1;
1703 for (int i
= 0; i
<= maxIndex
; ++i
) {
1704 const ItemData
*itemData
= m_itemData
.at(i
);
1705 if (itemData
->parent
) {
1706 indexesToRemove
.append(i
);
1710 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1711 m_expandedDirs
.clear();
1713 // Also remove all filtered items which have a parent.
1714 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1715 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1718 if (it
.value()->parent
) {
1720 it
= m_filteredItems
.erase(it
);
1727 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1729 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1731 // Trigger a resorting if necessary. Note that this can happen even if the sort
1732 // role has not changed at all because the file name can be used as a fallback.
1733 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1734 for (const KItemRange
&range
: itemRanges
) {
1735 bool needsResorting
= false;
1737 const int first
= range
.index
;
1738 const int last
= range
.index
+ range
.count
- 1;
1740 // Resorting the model is necessary if
1741 // (a) The first item in the range is "lessThan" its predecessor,
1742 // (b) the successor of the last item is "lessThan" the last item, or
1743 // (c) the internal order of the items in the range is incorrect.
1744 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1745 needsResorting
= true;
1746 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1747 needsResorting
= true;
1749 for (int index
= first
; index
< last
; ++index
) {
1750 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1751 needsResorting
= true;
1757 if (needsResorting
) {
1758 m_resortAllItemsTimer
->start();
1764 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1765 // The position is still correct, but the groups might have changed
1766 // if the changed item is either the first or the last item in a
1768 // In principle, we could try to find out if the item really is the
1769 // first or last one in its group and then update the groups
1770 // (possibly with a delayed timer to make sure that we don't
1771 // re-calculate the groups very often if items are updated one by
1772 // one), but starting m_resortAllItemsTimer is easier.
1773 m_resortAllItemsTimer
->start();
1777 void KFileItemModel::resetRoles()
1779 for (int i
= 0; i
< RolesCount
; ++i
) {
1780 m_requestRole
[i
] = false;
1784 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1786 static QHash
<QByteArray
, RoleType
> roles
;
1787 if (roles
.isEmpty()) {
1788 // Insert user visible roles that can be accessed with
1789 // KFileItemModel::roleInformation()
1791 const RoleInfoMap
*map
= rolesInfoMap(count
);
1792 for (int i
= 0; i
< count
; ++i
) {
1793 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1796 // Insert internal roles (take care to synchronize the implementation
1797 // with KFileItemModel::roleForType() in case if a change is done).
1798 roles
.insert("isDir", IsDirRole
);
1799 roles
.insert("isLink", IsLinkRole
);
1800 roles
.insert("isHidden", IsHiddenRole
);
1801 roles
.insert("isExpanded", IsExpandedRole
);
1802 roles
.insert("isExpandable", IsExpandableRole
);
1803 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1805 Q_ASSERT(roles
.count() == RolesCount
);
1808 return roles
.value(role
, NoRole
);
1811 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1813 static QHash
<RoleType
, QByteArray
> roles
;
1814 if (roles
.isEmpty()) {
1815 // Insert user visible roles that can be accessed with
1816 // KFileItemModel::roleInformation()
1818 const RoleInfoMap
*map
= rolesInfoMap(count
);
1819 for (int i
= 0; i
< count
; ++i
) {
1820 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1823 // Insert internal roles (take care to synchronize the implementation
1824 // with KFileItemModel::typeForRole() in case if a change is done).
1825 roles
.insert(IsDirRole
, "isDir");
1826 roles
.insert(IsLinkRole
, "isLink");
1827 roles
.insert(IsHiddenRole
, "isHidden");
1828 roles
.insert(IsExpandedRole
, "isExpanded");
1829 roles
.insert(IsExpandableRole
, "isExpandable");
1830 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1832 Q_ASSERT(roles
.count() == RolesCount
);
1835 return roles
.value(roleType
);
1838 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1840 // It is important to insert only roles that are fast to retrieve. E.g.
1841 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1842 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1843 QHash
<QByteArray
, QVariant
> data
;
1844 data
.insert(sharedValue("url"), item
.url());
1846 const bool isDir
= item
.isDir();
1847 if (m_requestRole
[IsDirRole
] && isDir
) {
1848 data
.insert(sharedValue("isDir"), true);
1851 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1852 data
.insert(sharedValue("isLink"), true);
1855 if (m_requestRole
[IsHiddenRole
]) {
1856 data
.insert(sharedValue("isHidden"), item
.isHidden() || item
.mimetype() == QStringLiteral("application/x-trash"));
1859 if (m_requestRole
[NameRole
]) {
1860 data
.insert(sharedValue("text"), item
.text());
1863 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1864 // TODO KF6 use KFileItem::suffix 464722
1865 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1868 if (m_requestRole
[SizeRole
] && !isDir
) {
1869 data
.insert(sharedValue("size"), item
.size());
1872 if (m_requestRole
[ModificationTimeRole
]) {
1873 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1874 // having several thousands of items. Instead read the raw number from UDSEntry directly
1875 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1876 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1877 data
.insert(sharedValue("modificationtime"), dateTime
);
1880 if (m_requestRole
[CreationTimeRole
]) {
1881 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1882 // having several thousands of items. Instead read the raw number from UDSEntry directly
1883 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1884 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1885 data
.insert(sharedValue("creationtime"), dateTime
);
1888 if (m_requestRole
[AccessTimeRole
]) {
1889 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1890 // having several thousands of items. Instead read the raw number from UDSEntry directly
1891 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1892 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1893 data
.insert(sharedValue("accesstime"), dateTime
);
1896 if (m_requestRole
[PermissionsRole
]) {
1897 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1900 if (m_requestRole
[OwnerRole
]) {
1901 data
.insert(sharedValue("owner"), item
.user());
1904 if (m_requestRole
[GroupRole
]) {
1905 data
.insert(sharedValue("group"), item
.group());
1908 if (m_requestRole
[DestinationRole
]) {
1909 QString destination
= item
.linkDest();
1910 if (destination
.isEmpty()) {
1911 destination
= QLatin1Char('-');
1913 data
.insert(sharedValue("destination"), destination
);
1916 if (m_requestRole
[PathRole
]) {
1918 if (item
.url().scheme() == QLatin1String("trash")) {
1919 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1921 // For performance reasons cache the home-path in a static QString
1922 // (see QDir::homePath() for more details)
1923 static QString homePath
;
1924 if (homePath
.isEmpty()) {
1925 homePath
= QDir::homePath();
1928 path
= item
.localPath();
1929 if (path
.startsWith(homePath
)) {
1930 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1934 const int index
= path
.lastIndexOf(item
.text());
1935 path
= path
.mid(0, index
- 1);
1936 data
.insert(sharedValue("path"), path
);
1939 if (m_requestRole
[DeletionTimeRole
]) {
1940 QDateTime deletionTime
;
1941 if (item
.url().scheme() == QLatin1String("trash")) {
1942 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1944 data
.insert(sharedValue("deletiontime"), deletionTime
);
1947 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1948 data
.insert(sharedValue("isExpandable"), true);
1951 if (m_requestRole
[ExpandedParentsCountRole
]) {
1953 const int level
= expandedParentsCount(parent
) + 1;
1954 data
.insert(sharedValue("expandedParentsCount"), level
);
1958 if (item
.isMimeTypeKnown()) {
1959 QString iconName
= item
.iconName();
1960 if (!QIcon::hasThemeIcon(iconName
)) {
1961 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1962 iconName
= mimeType
.genericIconName();
1965 data
.insert(sharedValue("iconName"), iconName
);
1967 if (m_requestRole
[TypeRole
]) {
1968 data
.insert(sharedValue("type"), item
.mimeComment());
1970 } else if (m_requestRole
[TypeRole
] && isDir
) {
1971 static const QString folderMimeType
= item
.mimeComment();
1972 data
.insert(sharedValue("type"), folderMimeType
);
1978 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1982 if (a
->parent
!= b
->parent
) {
1983 const int expansionLevelA
= expandedParentsCount(a
);
1984 const int expansionLevelB
= expandedParentsCount(b
);
1986 // If b has a higher expansion level than a, check if a is a parent
1987 // of b, and make sure that both expansion levels are equal otherwise.
1988 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1989 if (b
->parent
== a
) {
1995 // If a has a higher expansion level than a, check if b is a parent
1996 // of a, and make sure that both expansion levels are equal otherwise.
1997 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1998 if (a
->parent
== b
) {
2004 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
2006 // Compare the last parents of a and b which are different.
2007 while (a
->parent
!= b
->parent
) {
2013 // Show hidden files and folders last
2014 if (m_sortHiddenLast
) {
2015 const bool isHiddenA
= a
->item
.isHidden();
2016 const bool isHiddenB
= b
->item
.isHidden();
2017 if (isHiddenA
&& !isHiddenB
) {
2019 } else if (!isHiddenA
&& isHiddenB
) {
2024 if (m_sortDirsFirst
|| (ContentDisplaySettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
2025 const bool isDirA
= a
->item
.isDir();
2026 const bool isDirB
= b
->item
.isDir();
2027 if (isDirA
&& !isDirB
) {
2029 } else if (!isDirA
&& isDirB
) {
2034 result
= sortRoleCompare(a
, b
, collator
);
2036 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2039 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2041 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2042 return lessThan(a
, b
, m_collator
);
2045 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2046 // Sorting by string can be expensive, in particular if natural sorting is
2047 // enabled. Use all CPU cores to speed up the sorting process.
2048 static const int numberOfThreads
= QThread::idealThreadCount();
2049 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2051 // Sorting by other roles is quite fast. Use only one thread to prevent
2052 // problems caused by non-reentrant comparison functions, see
2053 // https://bugs.kde.org/show_bug.cgi?id=312679
2054 mergeSort(begin
, end
, lambdaLessThan
);
2058 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2060 // This function must never return 0, because that would break stable
2061 // sorting, which leads to all kinds of bugs.
2062 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2063 // If two items have equal sort values, let the fallbacks at the bottom of
2064 // the function handle it.
2065 const KFileItem
&itemA
= a
->item
;
2066 const KFileItem
&itemB
= b
->item
;
2070 switch (m_sortRole
) {
2072 // The name role is handled as default fallback after the switch
2076 if (ContentDisplaySettings::directorySizeCount() && itemA
.isDir()) {
2077 // folders first then
2078 // items A and B are folders thanks to lessThan checks
2079 auto valueA
= a
->values
.value("count");
2080 auto valueB
= b
->values
.value("count");
2081 if (valueA
.isNull()) {
2082 if (!valueB
.isNull()) {
2085 } else if (valueB
.isNull()) {
2088 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2090 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2097 KIO::filesize_t sizeA
= 0;
2098 if (itemA
.isDir()) {
2099 sizeA
= a
->values
.value("size").toULongLong();
2101 sizeA
= itemA
.size();
2103 KIO::filesize_t sizeB
= 0;
2104 if (itemB
.isDir()) {
2105 sizeB
= b
->values
.value("size").toULongLong();
2107 sizeB
= itemB
.size();
2109 if (sizeA
< sizeB
) {
2111 } else if (sizeA
> sizeB
) {
2117 case ModificationTimeRole
: {
2118 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2119 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2120 if (dateTimeA
< dateTimeB
) {
2122 } else if (dateTimeA
> dateTimeB
) {
2128 case AccessTimeRole
: {
2129 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2130 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2131 if (dateTimeA
< dateTimeB
) {
2133 } else if (dateTimeA
> dateTimeB
) {
2139 case CreationTimeRole
: {
2140 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2141 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2142 if (dateTimeA
< dateTimeB
) {
2144 } else if (dateTimeA
> dateTimeB
) {
2150 case DeletionTimeRole
: {
2151 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2152 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2153 if (dateTimeA
< dateTimeB
) {
2155 } else if (dateTimeA
> dateTimeB
) {
2169 case ReleaseYearRole
: {
2170 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2174 case DimensionsRole
: {
2175 const QByteArray role
= roleForType(m_sortRole
);
2176 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2177 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2179 if (dimensionsA
.width() == dimensionsB
.width()) {
2180 result
= dimensionsA
.height() - dimensionsB
.height();
2182 result
= dimensionsA
.width() - dimensionsB
.width();
2188 const QByteArray role
= roleForType(m_sortRole
);
2189 const QString roleValueA
= a
->values
.value(role
).toString();
2190 const QString roleValueB
= b
->values
.value(role
).toString();
2191 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2193 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2195 } else if (isRoleValueNatural(m_sortRole
)) {
2196 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2198 result
= QString::compare(roleValueA
, roleValueB
);
2205 // The current sort role was sufficient to define an order
2209 // Fallback #1: Compare the text of the items
2210 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2215 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2216 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2221 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2222 // equal. In this case a comparison of the URL is done which is unique in all cases
2223 // within KDirLister.
2224 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2227 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2229 QMutexLocker
collatorLock(s_collatorMutex());
2231 if (m_naturalSorting
) {
2232 return collator
.compare(a
, b
);
2235 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2236 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2237 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2238 // comparison, still a deterministic sort order is required. A case sensitive
2239 // comparison is done as fallback.
2243 return QString::compare(a
, b
, Qt::CaseSensitive
);
2246 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2248 Q_ASSERT(!m_itemData
.isEmpty());
2250 const int maxIndex
= count() - 1;
2251 QList
<QPair
<int, QVariant
>> groups
;
2255 for (int i
= 0; i
<= maxIndex
; ++i
) {
2256 if (isChildItem(i
)) {
2260 const QString name
= m_itemData
.at(i
)->item
.text();
2262 // Use the first character of the name as group indication
2263 QChar newFirstChar
= name
.at(0).toUpper();
2264 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2265 newFirstChar
= name
.at(1).toUpper();
2268 if (firstChar
!= newFirstChar
) {
2269 QString newGroupValue
;
2270 if (newFirstChar
.isLetter()) {
2271 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2272 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2274 // Try to find a matching group in the range 'A' to 'Z'.
2275 static std::vector
<QChar
> lettersAtoZ
;
2276 lettersAtoZ
.reserve('Z' - 'A' + 1);
2277 if (lettersAtoZ
.empty()) {
2278 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2279 lettersAtoZ
.push_back(QLatin1Char(c
));
2283 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2284 return m_collator
.compare(c1
, c2
) < 0;
2287 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2288 if (it
!= lettersAtoZ
.end()) {
2289 if (localeAwareLessThan(newFirstChar
, *it
)) {
2290 // newFirstChar belongs to the group preceding *it.
2291 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2294 newGroupValue
= *it
;
2298 // Symbols from non Latin-based scripts
2299 newGroupValue
= newFirstChar
;
2301 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2302 // Apply group '0 - 9' for any name that starts with a digit
2303 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2305 newGroupValue
= i18nc("@title:group", "Others");
2308 if (newGroupValue
!= groupValue
) {
2309 groupValue
= newGroupValue
;
2310 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2313 firstChar
= newFirstChar
;
2319 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2321 Q_ASSERT(!m_itemData
.isEmpty());
2323 const int maxIndex
= count() - 1;
2324 QList
<QPair
<int, QVariant
>> groups
;
2327 for (int i
= 0; i
<= maxIndex
; ++i
) {
2328 if (isChildItem(i
)) {
2332 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2333 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2334 QString newGroupValue
;
2335 if (!item
.isNull() && item
.isDir()) {
2336 if (ContentDisplaySettings::directorySizeCount() || m_sortDirsFirst
) {
2337 newGroupValue
= i18nc("@title:group Size", "Folders");
2339 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2343 if (newGroupValue
.isEmpty()) {
2344 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2345 newGroupValue
= i18nc("@title:group Size", "Small");
2346 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2347 newGroupValue
= i18nc("@title:group Size", "Medium");
2349 newGroupValue
= i18nc("@title:group Size", "Big");
2353 if (newGroupValue
!= groupValue
) {
2354 groupValue
= newGroupValue
;
2355 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2362 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2364 Q_ASSERT(!m_itemData
.isEmpty());
2366 const int maxIndex
= count() - 1;
2367 QList
<QPair
<int, QVariant
>> groups
;
2369 const QDate currentDate
= QDate::currentDate();
2371 QDate previousFileDate
;
2373 for (int i
= 0; i
<= maxIndex
; ++i
) {
2374 if (isChildItem(i
)) {
2378 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2379 const QDate fileDate
= fileTime
.date();
2380 if (fileDate
== previousFileDate
) {
2381 // The current item is in the same group as the previous item
2384 previousFileDate
= fileDate
;
2386 const int daysDistance
= fileDate
.daysTo(currentDate
);
2388 QString newGroupValue
;
2389 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2390 switch (daysDistance
/ 7) {
2392 switch (daysDistance
) {
2394 newGroupValue
= i18nc("@title:group Date", "Today");
2397 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2400 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2401 newGroupValue
= i18nc(
2402 "Can be used to script translation of \"dddd\""
2403 "with context @title:group Date",
2409 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2412 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2415 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2419 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2425 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2426 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2427 if (daysDistance
== 1) {
2428 const KLocalizedString format
= ki18nc(
2429 "@title:group Date: "
2430 "MMMM is full month name in current locale, and yyyy is "
2431 "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 "
2432 "part of the text that should not be formatted as a date",
2433 "'Yesterday' (MMMM, yyyy)");
2434 const QString translatedFormat
= format
.toString();
2435 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2436 newGroupValue
= fileTime
.toString(translatedFormat
);
2437 newGroupValue
= i18nc(
2438 "Can be used to script translation of "
2439 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2443 qCWarning(DolphinDebug
).nospace()
2444 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2445 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2446 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2448 } else if (daysDistance
<= 7) {
2450 fileTime
.toString(i18nc("@title:group Date: "
2451 "The week day name: dddd, MMMM is full month name "
2452 "in current locale, and yyyy is full year number.",
2453 "dddd (MMMM, yyyy)"));
2454 newGroupValue
= i18nc(
2455 "Can be used to script translation of "
2456 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2459 } else if (daysDistance
<= 7 * 2) {
2460 const KLocalizedString format
= ki18nc(
2461 "@title:group Date: "
2462 "MMMM is full month name in current locale, and yyyy is "
2463 "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 "
2464 "part of the text that should not be formatted as a date",
2465 "'One Week Ago' (MMMM, yyyy)");
2466 const QString translatedFormat
= format
.toString();
2467 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2468 newGroupValue
= fileTime
.toString(translatedFormat
);
2469 newGroupValue
= i18nc(
2470 "Can be used to script translation of "
2471 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2475 qCWarning(DolphinDebug
).nospace()
2476 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2477 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2478 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2480 } else if (daysDistance
<= 7 * 3) {
2481 const KLocalizedString format
= ki18nc(
2482 "@title:group Date: "
2483 "MMMM is full month name in current locale, and yyyy is "
2484 "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 "
2485 "part of the text that should not be formatted as a date",
2486 "'Two Weeks Ago' (MMMM, yyyy)");
2487 const QString translatedFormat
= format
.toString();
2488 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2489 newGroupValue
= fileTime
.toString(translatedFormat
);
2490 newGroupValue
= i18nc(
2491 "Can be used to script translation of "
2492 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2496 qCWarning(DolphinDebug
).nospace()
2497 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2498 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2499 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2501 } else if (daysDistance
<= 7 * 4) {
2502 const KLocalizedString format
= ki18nc(
2503 "@title:group Date: "
2504 "MMMM is full month name in current locale, and yyyy is "
2505 "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 "
2506 "part of the text that should not be formatted as a date",
2507 "'Three Weeks Ago' (MMMM, yyyy)");
2508 const QString translatedFormat
= format
.toString();
2509 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2510 newGroupValue
= fileTime
.toString(translatedFormat
);
2511 newGroupValue
= i18nc(
2512 "Can be used to script translation of "
2513 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2517 qCWarning(DolphinDebug
).nospace()
2518 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2519 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2520 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2523 const KLocalizedString format
= ki18nc(
2524 "@title:group Date: "
2525 "MMMM is full month name in current locale, and yyyy is "
2526 "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 "
2527 "part of the text that should not be formatted as a date",
2528 "'Earlier on' MMMM, yyyy");
2529 const QString translatedFormat
= format
.toString();
2530 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2531 newGroupValue
= fileTime
.toString(translatedFormat
);
2532 newGroupValue
= i18nc(
2533 "Can be used to script translation of "
2534 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2538 qCWarning(DolphinDebug
).nospace()
2539 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2540 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2541 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2546 fileTime
.toString(i18nc("@title:group "
2547 "The month and year: MMMM is full month name in current locale, "
2548 "and yyyy is full year number",
2550 newGroupValue
= i18nc(
2551 "Can be used to script translation of "
2552 "\"MMMM, yyyy\" with context @title:group Date",
2558 if (newGroupValue
!= groupValue
) {
2559 groupValue
= newGroupValue
;
2560 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2567 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2569 Q_ASSERT(!m_itemData
.isEmpty());
2571 const int maxIndex
= count() - 1;
2572 QList
<QPair
<int, QVariant
>> groups
;
2574 QString permissionsString
;
2576 for (int i
= 0; i
<= maxIndex
; ++i
) {
2577 if (isChildItem(i
)) {
2581 const ItemData
*itemData
= m_itemData
.at(i
);
2582 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2583 if (newPermissionsString
== permissionsString
) {
2586 permissionsString
= newPermissionsString
;
2588 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2592 if (info
.permission(QFile::ReadUser
)) {
2593 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2595 if (info
.permission(QFile::WriteUser
)) {
2596 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2598 if (info
.permission(QFile::ExeUser
)) {
2599 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2601 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2605 if (info
.permission(QFile::ReadGroup
)) {
2606 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2608 if (info
.permission(QFile::WriteGroup
)) {
2609 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2611 if (info
.permission(QFile::ExeGroup
)) {
2612 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2614 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2616 // Set others string
2618 if (info
.permission(QFile::ReadOther
)) {
2619 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2621 if (info
.permission(QFile::WriteOther
)) {
2622 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2624 if (info
.permission(QFile::ExeOther
)) {
2625 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2627 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2629 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2630 if (newGroupValue
!= groupValue
) {
2631 groupValue
= newGroupValue
;
2632 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2639 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2641 Q_ASSERT(!m_itemData
.isEmpty());
2643 const int maxIndex
= count() - 1;
2644 QList
<QPair
<int, QVariant
>> groups
;
2646 int groupValue
= -1;
2647 for (int i
= 0; i
<= maxIndex
; ++i
) {
2648 if (isChildItem(i
)) {
2651 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2652 if (newGroupValue
!= groupValue
) {
2653 groupValue
= newGroupValue
;
2654 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2661 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2663 Q_ASSERT(!m_itemData
.isEmpty());
2665 const int maxIndex
= count() - 1;
2666 QList
<QPair
<int, QVariant
>> groups
;
2668 bool isFirstGroupValue
= true;
2670 for (int i
= 0; i
<= maxIndex
; ++i
) {
2671 if (isChildItem(i
)) {
2674 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2675 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2676 groupValue
= newGroupValue
;
2677 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2678 isFirstGroupValue
= false;
2685 void KFileItemModel::emitSortProgress(int resolvedCount
)
2687 // Be tolerant against a resolvedCount with a wrong range.
2688 // Although there should not be a case where KFileItemModelRolesUpdater
2689 // (= caller) provides a wrong range, it is important to emit
2690 // a useful progress information even if there is an unexpected
2691 // implementation issue.
2693 const int itemCount
= count();
2694 if (resolvedCount
>= itemCount
) {
2695 m_sortingProgressPercent
= -1;
2696 if (m_resortAllItemsTimer
->isActive()) {
2697 m_resortAllItemsTimer
->stop();
2701 Q_EMIT
directorySortingProgress(100);
2702 } else if (itemCount
> 0) {
2703 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2705 const int progress
= resolvedCount
* 100 / itemCount
;
2706 if (m_sortingProgressPercent
!= progress
) {
2707 m_sortingProgressPercent
= progress
;
2708 Q_EMIT
directorySortingProgress(progress
);
2713 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2715 static const RoleInfoMap rolesInfoMap
[] = {
2717 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2718 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2719 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2720 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2721 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2722 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2723 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2724 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2725 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2726 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2727 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2728 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2729 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2730 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2731 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2732 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2733 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2734 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2735 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2736 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2737 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2738 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2739 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2740 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2741 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2742 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2743 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2744 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2745 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2746 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2747 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2748 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2749 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2750 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2751 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2752 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2753 { "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 },
2754 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2755 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2759 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2760 return rolesInfoMap
;
2763 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2765 QElapsedTimer timer
;
2767 for (const KFileItem
&item
: items
) {
2768 // Only determine mime types for files here. For directories,
2769 // KFileItem::determineMimeType() reads the .directory file inside to
2770 // load the icon, but this is not necessary at all if we just need the
2771 // type. Some special code for setting the correct mime type for
2772 // directories is in retrieveData().
2773 if (!item
.isDir()) {
2774 item
.determineMimeType();
2777 if (timer
.elapsed() > timeout
) {
2778 // Don't block the user interface, let the remaining items
2779 // be resolved asynchronously.
2785 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2787 static QSet
<QByteArray
> pool
;
2788 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2790 if (it
!= pool
.constEnd()) {
2798 bool KFileItemModel::isConsistent() const
2800 // m_items may contain less items than m_itemData because m_items
2801 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2802 if (m_items
.count() > m_itemData
.count()) {
2806 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2807 // Check if m_items and m_itemData are consistent.
2808 const KFileItem item
= fileItem(i
);
2809 if (item
.isNull()) {
2810 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2814 const int itemIndex
= index(item
);
2815 if (itemIndex
!= i
) {
2816 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2820 // Check if the items are sorted correctly.
2821 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2822 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2826 // Check if all parent-child relationships are consistent.
2827 const ItemData
*data
= m_itemData
.at(i
);
2828 const ItemData
*parent
= data
->parent
;
2830 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2831 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2835 const int parentIndex
= index(parent
->item
);
2836 if (parentIndex
>= i
) {
2837 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2847 void KFileItemModel::slotListerError(KIO::Job
*job
)
2849 if (job
->error() == KIO::ERR_IS_FILE
) {
2850 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2851 Q_EMIT
urlIsFileError(listJob
->url());
2854 const QString errorString
= job
->errorString();
2855 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));
2859 #include "moc_kfileitemmodel.cpp"