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_detailsmodesettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
18 #include <KLocalizedString>
19 #include <KUrlMimeData>
20 #include <kio_version.h>
22 #include <QElapsedTimer>
25 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
30 #include <klazylocalizedstring.h>
32 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
34 // #define KFILEITEMMODEL_DEBUG
36 KFileItemModel::KFileItemModel(QObject
*parent
)
37 : KItemModelBase("text", parent
)
38 , m_dirLister(nullptr)
39 , m_sortDirsFirst(true)
40 , m_sortHiddenLast(false)
41 , m_sortRole(NameRole
)
42 , m_sortingProgressPercent(-1)
49 , m_maximumUpdateIntervalTimer(nullptr)
50 , m_resortAllItemsTimer(nullptr)
51 , m_pendingItemsToInsert()
56 m_collator
.setNumericMode(true);
58 loadSortingSettings();
60 m_dirLister
= new KDirLister(this);
61 m_dirLister
->setAutoErrorHandlingEnabled(false);
62 m_dirLister
->setDelayedMimeTypes(true);
64 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
66 m_dirLister
->setMainWindow(parentWidget
->window());
69 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
70 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
71 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
72 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
73 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
74 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
75 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
76 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
77 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
78 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
79 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
81 // Apply default roles that should be determined
83 m_requestRole
[NameRole
] = true;
84 m_requestRole
[IsDirRole
] = true;
85 m_requestRole
[IsLinkRole
] = true;
86 m_roles
.insert("text");
87 m_roles
.insert("isDir");
88 m_roles
.insert("isLink");
89 m_roles
.insert("isHidden");
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer
= new QTimer(this);
94 m_maximumUpdateIntervalTimer
->setInterval(2000);
95 m_maximumUpdateIntervalTimer
->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer
= new QTimer(this);
103 m_resortAllItemsTimer
->setInterval(500);
104 m_resortAllItemsTimer
->setSingleShot(true);
105 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
107 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
110 KFileItemModel::~KFileItemModel()
112 qDeleteAll(m_itemData
);
113 qDeleteAll(m_filteredItems
);
114 qDeleteAll(m_pendingItemsToInsert
);
117 void KFileItemModel::loadDirectory(const QUrl
&url
)
119 m_dirLister
->openUrl(url
);
122 void KFileItemModel::refreshDirectory(const QUrl
&url
)
124 // Refresh all expanded directories first (Bug 295300)
125 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
126 while (expandedDirs
.hasNext()) {
128 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
131 m_dirLister
->openUrl(url
, KDirLister::Reload
);
134 QUrl
KFileItemModel::directory() const
136 return m_dirLister
->url();
139 void KFileItemModel::cancelDirectoryLoading()
144 int KFileItemModel::count() const
146 return m_itemData
.count();
149 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
151 if (index
>= 0 && index
< count()) {
152 ItemData
*data
= m_itemData
.at(index
);
153 if (data
->values
.isEmpty()) {
154 data
->values
= retrieveData(data
->item
, data
->parent
);
155 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
156 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
157 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
158 // so this special request of different behavior can be identified here.
159 bool hasExpandedParentsCount
= false;
160 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
162 data
->values
= retrieveData(data
->item
, data
->parent
);
163 data
->values
.insert("isExpanded", true);
164 if (hasExpandedParentsCount
) {
165 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
171 return QHash
<QByteArray
, QVariant
>();
174 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
176 if (index
< 0 || index
>= count()) {
180 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
182 // Determine which roles have been changed
183 QSet
<QByteArray
> changedRoles
;
184 QHashIterator
<QByteArray
, QVariant
> it(values
);
185 while (it
.hasNext()) {
187 const QByteArray role
= sharedValue(it
.key());
188 const QVariant value
= it
.value();
190 if (currentValues
[role
] != value
) {
191 currentValues
[role
] = value
;
192 changedRoles
.insert(role
);
196 if (changedRoles
.isEmpty()) {
200 m_itemData
[index
]->values
= currentValues
;
201 if (changedRoles
.contains("text")) {
202 QUrl url
= m_itemData
[index
]->item
.url();
203 url
= url
.adjusted(QUrl::RemoveFilename
);
204 url
.setPath(url
.path() + currentValues
["text"].toString());
205 m_itemData
[index
]->item
.setUrl(url
);
208 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
213 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
215 if (dirsFirst
!= m_sortDirsFirst
) {
216 m_sortDirsFirst
= dirsFirst
;
221 bool KFileItemModel::sortDirectoriesFirst() const
223 return m_sortDirsFirst
;
226 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
228 if (hiddenLast
!= m_sortHiddenLast
) {
229 m_sortHiddenLast
= hiddenLast
;
234 bool KFileItemModel::sortHiddenLast() const
236 return m_sortHiddenLast
;
239 void KFileItemModel::setShowHiddenFiles(bool show
)
241 #if KIO_VERSION < QT_VERSION_CHECK(5, 100, 0)
242 m_dirLister
->setShowingDotFiles(show
);
244 m_dirLister
->setShowHiddenFiles(show
);
246 m_dirLister
->emitChanges();
248 dispatchPendingItemsToInsert();
252 bool KFileItemModel::showHiddenFiles() const
254 #if KIO_VERSION < QT_VERSION_CHECK(5, 100, 0)
255 return m_dirLister
->showingDotFiles();
257 return m_dirLister
->showHiddenFiles();
261 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
263 m_dirLister
->setDirOnlyMode(enabled
);
266 bool KFileItemModel::showDirectoriesOnly() const
268 return m_dirLister
->dirOnlyMode();
271 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
273 QMimeData
*data
= new QMimeData();
275 // The following code has been taken from KDirModel::mimeData()
276 // (kdelibs/kio/kio/kdirmodel.cpp)
277 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
279 QList
<QUrl
> mostLocalUrls
;
280 const ItemData
*lastAddedItem
= nullptr;
282 for (int index
: indexes
) {
283 const ItemData
*itemData
= m_itemData
.at(index
);
284 const ItemData
*parent
= itemData
->parent
;
286 while (parent
&& parent
!= lastAddedItem
) {
287 parent
= parent
->parent
;
290 if (parent
&& parent
== lastAddedItem
) {
291 // A parent of 'itemData' has been added already.
295 lastAddedItem
= itemData
;
296 const KFileItem
&item
= itemData
->item
;
297 if (!item
.isNull()) {
301 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
305 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
309 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
311 startFromIndex
= qMax(0, startFromIndex
);
312 for (int i
= startFromIndex
; i
< count(); ++i
) {
313 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
317 for (int i
= 0; i
< startFromIndex
; ++i
) {
318 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
325 bool KFileItemModel::supportsDropping(int index
) const
327 const KFileItem item
= fileItem(index
);
328 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
331 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
333 static QHash
<QByteArray
, QString
> description
;
334 if (description
.isEmpty()) {
336 const RoleInfoMap
*map
= rolesInfoMap(count
);
337 for (int i
= 0; i
< count
; ++i
) {
338 if (map
[i
].roleTranslation
.isEmpty()) {
341 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
345 return description
.value(role
);
348 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
350 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
351 #ifdef KFILEITEMMODEL_DEBUG
355 switch (typeForRole(sortRole())) {
357 m_groups
= nameRoleGroups();
360 m_groups
= sizeRoleGroups();
362 case ModificationTimeRole
:
363 m_groups
= timeRoleGroups([](const ItemData
*item
) {
364 return item
->item
.time(KFileItem::ModificationTime
);
367 case CreationTimeRole
:
368 m_groups
= timeRoleGroups([](const ItemData
*item
) {
369 return item
->item
.time(KFileItem::CreationTime
);
373 m_groups
= timeRoleGroups([](const ItemData
*item
) {
374 return item
->item
.time(KFileItem::AccessTime
);
377 case DeletionTimeRole
:
378 m_groups
= timeRoleGroups([](const ItemData
*item
) {
379 return item
->values
.value("deletiontime").toDateTime();
382 case PermissionsRole
:
383 m_groups
= permissionRoleGroups();
386 m_groups
= ratingRoleGroups();
389 m_groups
= genericStringRoleGroups(sortRole());
393 #ifdef KFILEITEMMODEL_DEBUG
394 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
401 KFileItem
KFileItemModel::fileItem(int index
) const
403 if (index
>= 0 && index
< count()) {
404 return m_itemData
.at(index
)->item
;
410 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
412 const int indexForUrl
= index(url
);
413 if (indexForUrl
>= 0) {
414 return m_itemData
.at(indexForUrl
)->item
;
419 int KFileItemModel::index(const KFileItem
&item
) const
421 return index(item
.url());
424 int KFileItemModel::index(const QUrl
&url
) const
426 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
428 const int itemCount
= m_itemData
.count();
429 int itemsInHash
= m_items
.count();
431 int index
= m_items
.value(urlToFind
, -1);
432 while (index
< 0 && itemsInHash
< itemCount
) {
433 // Not all URLs are stored yet in m_items. We grow m_items until either
434 // urlToFind is found, or all URLs have been stored in m_items.
435 // Note that we do not add the URLs to m_items one by one, but in
436 // larger blocks. After each block, we check if urlToFind is in
437 // m_items. We could in principle compare urlToFind with each URL while
438 // we are going through m_itemData, but comparing two QUrls will,
439 // unlike calling qHash for the URLs, trigger a parsing of the URLs
440 // which costs both CPU cycles and memory.
441 const int blockSize
= 1000;
442 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
443 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
444 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
445 m_items
.insert(nextUrl
, i
);
448 itemsInHash
= currentBlockEnd
;
449 index
= m_items
.value(urlToFind
, -1);
453 // The item could not be found, even though all items from m_itemData
454 // should be in m_items now. We print some diagnostic information which
455 // might help to find the cause of the problem, but only once. This
456 // prevents that obtaining and printing the debugging information
457 // wastes CPU cycles and floods the shell or .xsession-errors.
458 static bool printDebugInfo
= true;
460 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
461 printDebugInfo
= false;
463 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
464 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
465 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
467 // Check if there are multiple items with the same URL.
468 QMultiHash
<QUrl
, int> indexesForUrl
;
469 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
470 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
473 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
474 for (const QUrl
&url
: uniqueKeys
) {
475 if (indexesForUrl
.count(url
) > 1) {
476 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
478 auto it
= indexesForUrl
.find(url
);
479 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
480 const ItemData
*data
= m_itemData
.at(it
.value());
481 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
483 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
495 KFileItem
KFileItemModel::rootItem() const
497 return m_dirLister
->rootItem();
500 void KFileItemModel::clear()
505 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
507 if (m_roles
== roles
) {
511 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
515 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
516 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
517 if (supportedExpanding
&& !willSupportExpanding
) {
518 // No expanding is supported anymore. Take care to delete all items that have an expansion level
519 // that is not 0 (and hence are part of an expanded item).
520 removeExpandedItems();
527 QSetIterator
<QByteArray
> it(roles
);
528 while (it
.hasNext()) {
529 const QByteArray
&role
= it
.next();
530 m_requestRole
[typeForRole(role
)] = true;
534 // Update m_data with the changed requested roles
535 const int maxIndex
= count() - 1;
536 for (int i
= 0; i
<= maxIndex
; ++i
) {
537 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
540 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
543 // Clear the 'values' of all filtered items. They will be re-populated with the
544 // correct roles the next time 'values' will be accessed via data(int).
545 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
546 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
547 while (filteredIt
!= filteredEnd
) {
548 (*filteredIt
)->values
.clear();
553 QSet
<QByteArray
> KFileItemModel::roles() const
558 bool KFileItemModel::setExpanded(int index
, bool expanded
)
560 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
564 QHash
<QByteArray
, QVariant
> values
;
565 values
.insert(sharedValue("isExpanded"), expanded
);
566 if (!setData(index
, values
)) {
570 const KFileItem item
= m_itemData
.at(index
)->item
;
571 const QUrl url
= item
.url();
572 const QUrl targetUrl
= item
.targetUrl();
574 m_expandedDirs
.insert(targetUrl
, url
);
575 m_dirLister
->openUrl(url
, KDirLister::Keep
);
577 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
578 for (const QVariant
&var
: previouslyExpandedChildren
) {
579 m_urlsToExpand
.insert(var
.toUrl());
582 // Note that there might be (indirect) children of the folder which is to be collapsed in
583 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
584 // possibly without a parent, which might result in a crash, we insert all pending items
585 // right now. All new items which would be without a parent will then be removed.
586 dispatchPendingItemsToInsert();
588 // Check if the index of the collapsed folder has changed. If that is the case, then items
589 // were inserted before the collapsed folder, and its index needs to be updated.
590 if (m_itemData
.at(index
)->item
!= item
) {
591 index
= this->index(item
);
594 m_expandedDirs
.remove(targetUrl
);
595 m_dirLister
->stop(url
);
596 #if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0)
597 m_dirLister
->forgetDirs(url
);
600 const int parentLevel
= expandedParentsCount(index
);
601 const int itemCount
= m_itemData
.count();
602 const int firstChildIndex
= index
+ 1;
604 QVariantList expandedChildren
;
606 int childIndex
= firstChildIndex
;
607 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
608 ItemData
*itemData
= m_itemData
.at(childIndex
);
609 if (itemData
->values
.value("isExpanded").toBool()) {
610 const QUrl targetUrl
= itemData
->item
.targetUrl();
611 const QUrl url
= itemData
->item
.url();
612 m_expandedDirs
.remove(targetUrl
);
613 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
614 #if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0)
615 m_dirLister
->forgetDirs(url
);
617 expandedChildren
.append(targetUrl
);
621 const int childrenCount
= childIndex
- firstChildIndex
;
623 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
624 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
626 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
632 bool KFileItemModel::isExpanded(int index
) const
634 if (index
>= 0 && index
< count()) {
635 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
640 bool KFileItemModel::isExpandable(int index
) const
642 if (index
>= 0 && index
< count()) {
643 // Call data (instead of accessing m_itemData directly)
644 // to ensure that the value is initialized.
645 return data(index
).value("isExpandable").toBool();
650 int KFileItemModel::expandedParentsCount(int index
) const
652 if (index
>= 0 && index
< count()) {
653 return expandedParentsCount(m_itemData
.at(index
));
658 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
661 const auto dirs
= m_expandedDirs
;
662 for (const auto &dir
: dirs
) {
668 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
670 m_urlsToExpand
= urls
;
673 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
675 // Assure that each sub-path of the URL that should be
676 // expanded is added to m_urlsToExpand. KDirLister
677 // does not care whether the parent-URL has already been
679 QUrl urlToExpand
= m_dirLister
->url();
680 const int pos
= urlToExpand
.path().length();
682 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
683 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
684 // so using QString::SkipEmptyParts
685 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
686 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
687 QString path
= urlToExpand
.path();
688 if (!path
.endsWith(QLatin1Char('/'))) {
689 path
.append(QLatin1Char('/'));
691 urlToExpand
.setPath(path
+ subDirs
.at(i
));
692 m_urlsToExpand
.insert(urlToExpand
);
695 // KDirLister::open() must called at least once to trigger an initial
696 // loading. The pending URLs that must be restored are handled
697 // in slotCompleted().
698 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
699 while (it2
.hasNext()) {
700 const int idx
= index(it2
.next());
701 if (idx
>= 0 && !isExpanded(idx
)) {
702 setExpanded(idx
, true);
708 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
710 if (m_filter
.pattern() != nameFilter
) {
711 dispatchPendingItemsToInsert();
712 m_filter
.setPattern(nameFilter
);
717 QString
KFileItemModel::nameFilter() const
719 return m_filter
.pattern();
722 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
724 if (m_filter
.mimeTypes() != filters
) {
725 dispatchPendingItemsToInsert();
726 m_filter
.setMimeTypes(filters
);
731 QStringList
KFileItemModel::mimeTypeFilters() const
733 return m_filter
.mimeTypes();
736 void KFileItemModel::applyFilters()
739 // Check which previously shown items from m_itemData must now get
740 // hidden and hence moved from m_itemData into m_filteredItems.
742 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
744 // This pointer will refer to the next confirmed shown item from the point of
745 // view of the current "itemData" in the upcoming "for" loop.
746 ItemData
*itemShownBelow
= nullptr;
748 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
749 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
750 ItemData
*itemData
= m_itemData
.at(index
);
752 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
753 // We could've entered here for two reasons:
754 // 1. This item passes the filter itself
755 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
757 // So this item must remain shown.
758 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
759 itemShownBelow
= itemData
;
761 // We hide this item for now, however, for expanded folders this is not final:
762 // 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
763 newFilteredIndexes
.prepend(index
);
764 m_filteredItems
.insert(itemData
->item
, itemData
);
765 // indexShownBelow doesn't get updated since this item will be hidden
769 // This will remove the newly filtered items from m_itemData
770 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
773 // Check which hidden items from m_filteredItems should
774 // become visible again and hence moved from m_filteredItems back into m_itemData.
776 QList
<ItemData
*> newVisibleItems
;
778 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
780 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
781 while (it
!= m_filteredItems
.end()) {
782 if (m_filter
.matches(it
.key())) {
783 newVisibleItems
.append(it
.value());
785 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
786 // We will go up through its parental chain until we either:
787 // 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
788 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
789 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
790 parent
= parent
->parent
) {
791 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
792 // and it would mess up the iteration. We will mark it to be removed in step 3.
793 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
796 it
= m_filteredItems
.erase(it
);
798 // Item remains filtered for now
799 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
805 // Handles the ancestorsOfNewVisibleItems.
806 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
807 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
808 if (m_filteredItems
.remove(it
.key())) {
809 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
810 newVisibleItems
.append(it
.value());
814 // This will insert the newly discovered unfiltered items into m_itemData
815 insertItems(newVisibleItems
);
818 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
820 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
821 // There are either no filtered items, or it is not possible to expand
822 // folders -> there cannot be any filtered children.
826 QSet
<ItemData
*> parents
;
827 for (const KItemRange
&range
: itemRanges
) {
828 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
829 parents
.insert(m_itemData
.at(index
));
833 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
834 while (it
!= m_filteredItems
.end()) {
835 if (parents
.contains(it
.value()->parent
)) {
837 it
= m_filteredItems
.erase(it
);
844 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
846 static QList
<RoleInfo
> rolesInfo
;
847 if (rolesInfo
.isEmpty()) {
849 const RoleInfoMap
*map
= rolesInfoMap(count
);
850 for (int i
= 0; i
< count
; ++i
) {
851 if (map
[i
].roleType
!= NoRole
) {
853 info
.role
= map
[i
].role
;
854 info
.translation
= map
[i
].roleTranslation
.toString();
855 if (!map
[i
].groupTranslation
.isEmpty()) {
856 info
.group
= map
[i
].groupTranslation
.toString();
858 // For top level roles, groupTranslation is 0. We must make sure that
859 // info.group is an empty string then because the code that generates
860 // menus tries to put the actions into sub menus otherwise.
861 info
.group
= QString();
863 info
.requiresBaloo
= map
[i
].requiresBaloo
;
864 info
.requiresIndexer
= map
[i
].requiresIndexer
;
865 if (!map
[i
].tooltipTranslation
.isEmpty()) {
866 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
868 info
.tooltip
= QString();
870 rolesInfo
.append(info
);
878 void KFileItemModel::onGroupedSortingChanged(bool current
)
884 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
887 m_sortRole
= typeForRole(current
);
889 if (!m_requestRole
[m_sortRole
]) {
890 QSet
<QByteArray
> newRoles
= m_roles
;
900 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
907 void KFileItemModel::loadSortingSettings()
909 using Choice
= GeneralSettings::EnumSortingChoice
;
910 switch (GeneralSettings::sortingChoice()) {
911 case Choice::NaturalSorting
:
912 m_naturalSorting
= true;
913 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
915 case Choice::CaseSensitiveSorting
:
916 m_naturalSorting
= false;
917 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
919 case Choice::CaseInsensitiveSorting
:
920 m_naturalSorting
= false;
921 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
926 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
927 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
928 m_collator
.compare(QString(), QString());
931 void KFileItemModel::resortAllItems()
933 m_resortAllItemsTimer
->stop();
935 const int itemCount
= count();
936 if (itemCount
<= 0) {
940 #ifdef KFILEITEMMODEL_DEBUG
943 qCDebug(DolphinDebug
) << "===========================================================";
944 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
947 // Remember the order of the current URLs so
948 // that it can be determined which indexes have
949 // been moved because of the resorting.
951 oldUrls
.reserve(itemCount
);
952 for (const ItemData
*itemData
: qAsConst(m_itemData
)) {
953 oldUrls
.append(itemData
->item
.url());
957 m_items
.reserve(itemCount
);
960 sort(m_itemData
.begin(), m_itemData
.end());
961 for (int i
= 0; i
< itemCount
; ++i
) {
962 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
965 // Determine the first index that has been moved.
966 int firstMovedIndex
= 0;
967 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
971 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
972 if (itemsHaveMoved
) {
975 int lastMovedIndex
= itemCount
- 1;
976 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
980 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
982 // Create a list movedToIndexes, which has the property that
983 // movedToIndexes[i] is the new index of the item with the old index
984 // firstMovedIndex + i.
985 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
986 QList
<int> movedToIndexes
;
987 movedToIndexes
.reserve(movedItemsCount
);
988 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
989 const int newIndex
= m_items
.value(oldUrls
.at(i
));
990 movedToIndexes
.append(newIndex
);
993 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
994 } else if (groupedSorting()) {
995 // The groups might have changed even if the order of the items has not.
996 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
998 if (groups() != oldGroups
) {
999 Q_EMIT
groupsChanged();
1003 #ifdef KFILEITEMMODEL_DEBUG
1004 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1008 void KFileItemModel::slotCompleted()
1010 m_maximumUpdateIntervalTimer
->stop();
1011 dispatchPendingItemsToInsert();
1013 if (!m_urlsToExpand
.isEmpty()) {
1014 // Try to find a URL that can be expanded.
1015 // Note that the parent folder must be expanded before any of its subfolders become visible.
1016 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1017 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1018 // Iterate over a const copy because items are deleted and inserted within the loop
1019 const auto urlsToExpand
= m_urlsToExpand
;
1020 for (const QUrl
&url
: urlsToExpand
) {
1021 const int indexForUrl
= index(url
);
1022 if (indexForUrl
>= 0) {
1023 m_urlsToExpand
.remove(url
);
1024 if (setExpanded(indexForUrl
, true)) {
1025 // The dir lister has been triggered. This slot will be called
1026 // again after the directory has been expanded.
1032 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1033 // if these URLs have been deleted in the meantime.
1034 m_urlsToExpand
.clear();
1037 Q_EMIT
directoryLoadingCompleted();
1040 void KFileItemModel::slotCanceled()
1042 m_maximumUpdateIntervalTimer
->stop();
1043 dispatchPendingItemsToInsert();
1045 Q_EMIT
directoryLoadingCanceled();
1048 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1050 Q_ASSERT(!items
.isEmpty());
1052 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1054 if (m_requestRole
[ExpandedParentsCountRole
]) {
1055 // If the expanding of items is enabled, the call
1056 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1057 // might result in emitting the same items twice due to the Keep-parameter.
1058 // This case happens if an item gets expanded, collapsed and expanded again
1059 // before the items could be loaded for the first expansion.
1060 if (index(items
.first().url()) >= 0) {
1061 // The items are already part of the model.
1065 if (directoryUrl
!= directory()) {
1066 // To be able to compare whether the new items may be inserted as children
1067 // of a parent item the pending items must be added to the model first.
1068 dispatchPendingItemsToInsert();
1071 // KDirLister keeps the children of items that got expanded once even if
1072 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1073 // checked whether the parent for new items is still expanded.
1074 const int parentIndex
= index(parentUrl
);
1075 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1076 // The parent is not expanded.
1081 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1083 if (!m_filter
.hasSetFilters()) {
1084 m_pendingItemsToInsert
.append(itemDataList
);
1086 QSet
<ItemData
*> parentsToEnsureVisible
;
1088 // The name or type filter is active. Hide filtered items
1089 // before inserting them into the model and remember
1090 // the filtered items in m_filteredItems.
1091 for (ItemData
*itemData
: itemDataList
) {
1092 if (m_filter
.matches(itemData
->item
)) {
1093 m_pendingItemsToInsert
.append(itemData
);
1094 if (itemData
->parent
) {
1095 parentsToEnsureVisible
.insert(itemData
->parent
);
1098 m_filteredItems
.insert(itemData
->item
, itemData
);
1102 // Entire parental chains must be shown
1103 for (ItemData
*parent
: parentsToEnsureVisible
) {
1104 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1105 m_pendingItemsToInsert
.append(parent
);
1110 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1111 // Assure that items get dispatched if no completed() or canceled() signal is
1112 // emitted during the maximum update interval.
1113 m_maximumUpdateIntervalTimer
->start();
1116 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1119 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1121 int filteredParentsCount
= 0;
1122 // The childless parents not yet removed will always be right above the start of a removed range.
1123 // We iterate backwards to ensure the deepest folders are processed before their parents
1124 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1125 KItemRange itemRange
= removedItemRanges
.at(i
);
1126 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1127 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1128 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1130 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1131 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1132 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1133 // and this deleted range covers all of its descendents, so none will be left.
1134 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1135 // This range's starting index will be extended to include the parent above:
1138 ++filteredParentsCount
;
1139 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1140 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1141 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1142 previousRange
.count
+= itemRange
.count
;
1143 removedItemRanges
.replace(i
- 1, previousRange
);
1144 removedItemRanges
.removeAt(i
);
1146 removedItemRanges
.replace(i
, itemRange
);
1147 // We must revisit this range in the next iteration since its starting index changed
1152 return filteredParentsCount
;
1155 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1157 dispatchPendingItemsToInsert();
1159 QVector
<int> indexesToRemove
;
1160 indexesToRemove
.reserve(items
.count());
1161 KFileItemList dirsChanged
;
1163 const auto currentDir
= directory();
1165 for (const KFileItem
&item
: items
) {
1166 if (item
.url() == currentDir
) {
1167 Q_EMIT
currentDirectoryRemoved();
1171 const int indexForItem
= index(item
);
1172 if (indexForItem
>= 0) {
1173 indexesToRemove
.append(indexForItem
);
1175 // Probably the item has been filtered.
1176 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1177 if (it
!= m_filteredItems
.end()) {
1179 m_filteredItems
.erase(it
);
1183 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1184 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1185 dirsChanged
<< KFileItem(parentUrl
);
1189 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1191 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1192 // Assure that removing a parent item also results in removing all children
1193 QVector
<int> indexesToRemoveWithChildren
;
1194 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1196 const int itemCount
= m_itemData
.count();
1197 for (int index
: qAsConst(indexesToRemove
)) {
1198 indexesToRemoveWithChildren
.append(index
);
1200 const int parentLevel
= expandedParentsCount(index
);
1201 int childIndex
= index
+ 1;
1202 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1203 indexesToRemoveWithChildren
.append(childIndex
);
1208 indexesToRemove
= indexesToRemoveWithChildren
;
1211 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1212 removeFilteredChildren(itemRanges
);
1214 // This call will update itemRanges to include the childless parents that have been filtered.
1215 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1217 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1218 // mixed with expanded folders that are just being filtered out.
1219 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1220 // so removeItems() will check m_filteredItems to differentiate which is which.
1221 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1223 Q_EMIT
fileItemsChanged(dirsChanged
);
1226 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1228 Q_ASSERT(!items
.isEmpty());
1229 #ifdef KFILEITEMMODEL_DEBUG
1230 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1233 // Get the indexes of all items that have been refreshed
1235 indexes
.reserve(items
.count());
1237 QSet
<QByteArray
> changedRoles
;
1238 KFileItemList changedFiles
;
1240 // Contains the indexes of the currently visible items
1241 // that should get hidden and hence moved to m_filteredItems.
1242 QVector
<int> newFilteredIndexes
;
1244 // Contains currently hidden items that should
1245 // get visible and hence removed from m_filteredItems
1246 QList
<ItemData
*> newVisibleItems
;
1248 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1250 while (it
.hasNext()) {
1251 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1252 const KFileItem
&oldItem
= itemPair
.first
;
1253 const KFileItem
&newItem
= itemPair
.second
;
1254 const int indexForItem
= index(oldItem
);
1255 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1256 if (indexForItem
>= 0) {
1257 m_itemData
[indexForItem
]->item
= newItem
;
1259 // Keep old values as long as possible if they could not retrieved synchronously yet.
1260 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1261 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1262 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1263 while (it
.hasNext()) {
1265 const QByteArray
&role
= it
.key();
1266 if (itemData
->values
.value(role
) != it
.value()) {
1267 itemData
->values
.insert(role
, it
.value());
1268 changedRoles
.insert(role
);
1272 m_items
.remove(oldItem
.url());
1273 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1274 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1275 m_items
.insert(newItem
.url(), indexForItem
);
1276 if (newItemMatchesFilter
1277 || (itemData
->values
.value("isExpanded").toBool()
1278 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1279 // We are lenient with expanded folders that originally had visible children.
1280 // If they become childless now they will be caught by filterChildlessParents()
1281 changedFiles
.append(newItem
);
1282 indexes
.append(indexForItem
);
1284 newFilteredIndexes
.append(indexForItem
);
1285 m_filteredItems
.insert(newItem
, itemData
);
1288 // Check if 'oldItem' is one of the filtered items.
1289 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1290 if (it
!= m_filteredItems
.end()) {
1291 ItemData
*const itemData
= it
.value();
1292 itemData
->item
= newItem
;
1294 // The data stored in 'values' might have changed. Therefore, we clear
1295 // 'values' and re-populate it the next time it is requested via data(int).
1296 // Before clearing, we must remember if it was expanded and the expanded parents count,
1297 // otherwise these states would be lost. The data() method will deal with this special case.
1298 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1299 bool hasExpandedParentsCount
= false;
1300 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1301 itemData
->values
.clear();
1303 itemData
->values
.insert("isExpanded", true);
1304 if (hasExpandedParentsCount
) {
1305 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1309 m_filteredItems
.erase(it
);
1310 if (newItemMatchesFilter
) {
1311 newVisibleItems
.append(itemData
);
1313 m_filteredItems
.insert(newItem
, itemData
);
1319 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1321 // We must keep track of parents of new visible items since they must be shown no matter what
1322 // They will be considered "immune" to filterChildlessParents()
1323 QSet
<ItemData
*> parentsToEnsureVisible
;
1325 for (ItemData
*item
: newVisibleItems
) {
1326 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1327 parentsToEnsureVisible
.insert(parent
);
1330 for (ItemData
*parent
: parentsToEnsureVisible
) {
1331 // We make sure they are all unfiltered.
1332 if (m_filteredItems
.remove(parent
->item
)) {
1333 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1334 newVisibleItems
.append(parent
);
1335 // It could be in newFilteredIndexes, we must remove it if it's there:
1336 const int parentIndex
= index(parent
->item
);
1337 if (parentIndex
>= 0) {
1338 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1339 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1340 newFilteredIndexes
.erase(it
);
1346 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1348 // This call will update itemRanges to include the childless parents that have been filtered.
1349 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1351 removeItems(removedRanges
, KeepItemData
);
1353 // Show previously hidden items that should get visible
1354 insertItems(newVisibleItems
);
1356 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1358 // If the changed items have been created recently, they might not be in m_items yet.
1359 // In that case, the list 'indexes' might be empty.
1360 if (indexes
.isEmpty()) {
1364 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1365 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1367 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1368 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1369 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1370 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1375 std::sort(indexes
.begin(), indexes
.end());
1378 // Extract the item-ranges out of the changed indexes
1379 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1380 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1382 Q_EMIT
fileItemsChanged(changedFiles
);
1385 void KFileItemModel::slotClear()
1387 #ifdef KFILEITEMMODEL_DEBUG
1388 qCDebug(DolphinDebug
) << "Clearing all items";
1391 qDeleteAll(m_filteredItems
);
1392 m_filteredItems
.clear();
1395 m_maximumUpdateIntervalTimer
->stop();
1396 m_resortAllItemsTimer
->stop();
1398 qDeleteAll(m_pendingItemsToInsert
);
1399 m_pendingItemsToInsert
.clear();
1401 const int removedCount
= m_itemData
.count();
1402 if (removedCount
> 0) {
1403 qDeleteAll(m_itemData
);
1406 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1409 m_expandedDirs
.clear();
1412 void KFileItemModel::slotSortingChoiceChanged()
1414 loadSortingSettings();
1418 void KFileItemModel::dispatchPendingItemsToInsert()
1420 if (!m_pendingItemsToInsert
.isEmpty()) {
1421 insertItems(m_pendingItemsToInsert
);
1422 m_pendingItemsToInsert
.clear();
1426 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1428 if (newItems
.isEmpty()) {
1432 #ifdef KFILEITEMMODEL_DEBUG
1433 QElapsedTimer timer
;
1435 qCDebug(DolphinDebug
) << "===========================================================";
1436 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1440 prepareItemsForSorting(newItems
);
1442 // Natural sorting of items can be very slow. However, it becomes much faster
1443 // if the input sequence is already mostly sorted. Therefore, we first sort
1444 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1445 if (m_naturalSorting
) {
1446 if (m_sortRole
== NameRole
) {
1447 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1448 } else if (isRoleValueNatural(m_sortRole
)) {
1449 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1450 const QByteArray role
= roleForType(m_sortRole
);
1451 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1453 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1457 sort(newItems
.begin(), newItems
.end());
1459 #ifdef KFILEITEMMODEL_DEBUG
1460 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1463 KItemRangeList itemRanges
;
1464 const int existingItemCount
= m_itemData
.count();
1465 const int newItemCount
= newItems
.count();
1466 const int totalItemCount
= existingItemCount
+ newItemCount
;
1468 if (existingItemCount
== 0) {
1469 // Optimization for the common special case that there are no
1470 // items in the model yet. Happens, e.g., when entering a folder.
1471 m_itemData
= newItems
;
1472 itemRanges
<< KItemRange(0, newItemCount
);
1474 m_itemData
.reserve(totalItemCount
);
1475 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1476 m_itemData
.append(nullptr);
1479 // We build the new list m_itemData in reverse order to minimize
1480 // the number of moves and guarantee O(N) complexity.
1481 int targetIndex
= totalItemCount
- 1;
1482 int sourceIndexExistingItems
= existingItemCount
- 1;
1483 int sourceIndexNewItems
= newItemCount
- 1;
1487 while (sourceIndexNewItems
>= 0) {
1488 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1489 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1490 // Move an existing item to its new position. If any new items
1491 // are behind it, push the item range to itemRanges.
1492 if (rangeCount
> 0) {
1493 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1497 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1498 --sourceIndexExistingItems
;
1500 // Insert a new item into the list.
1502 m_itemData
[targetIndex
] = newItem
;
1503 --sourceIndexNewItems
;
1508 // Push the final item range to itemRanges.
1509 if (rangeCount
> 0) {
1510 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1513 // Note that itemRanges is still sorted in reverse order.
1514 std::reverse(itemRanges
.begin(), itemRanges
.end());
1517 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1518 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1521 Q_EMIT
itemsInserted(itemRanges
);
1523 #ifdef KFILEITEMMODEL_DEBUG
1524 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1528 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1530 if (itemRanges
.isEmpty()) {
1536 // Step 1: Remove the items from m_itemData, and free the ItemData.
1537 int removedItemsCount
= 0;
1538 for (const KItemRange
&range
: itemRanges
) {
1539 removedItemsCount
+= range
.count
;
1541 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1542 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1543 delete m_itemData
.at(index
);
1546 m_itemData
[index
] = nullptr;
1550 // Step 2: Remove the ItemData pointers from the list m_itemData.
1551 int target
= itemRanges
.at(0).index
;
1552 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1555 const int oldItemDataCount
= m_itemData
.count();
1556 while (source
< oldItemDataCount
) {
1557 m_itemData
[target
] = m_itemData
[source
];
1561 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1562 // Skip the items in the next removed range.
1563 source
+= itemRanges
.at(nextRange
).count
;
1568 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1570 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1571 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1574 Q_EMIT
itemsRemoved(itemRanges
);
1577 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1579 if (m_sortRole
== TypeRole
) {
1580 // Try to resolve the MIME-types synchronously to prevent a reordering of
1581 // the items when sorting by type (per default MIME-types are resolved
1582 // asynchronously by KFileItemModelRolesUpdater).
1583 determineMimeTypes(items
, 200);
1586 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1587 const int parentIndex
= index(parentUrl
);
1588 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1590 QList
<ItemData
*> itemDataList
;
1591 itemDataList
.reserve(items
.count());
1593 for (const KFileItem
&item
: items
) {
1594 ItemData
*itemData
= new ItemData();
1595 itemData
->item
= item
;
1596 itemData
->parent
= parentItem
;
1597 itemDataList
.append(itemData
);
1600 return itemDataList
;
1603 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1605 switch (m_sortRole
) {
1607 case PermissionsRole
:
1610 case DestinationRole
:
1612 case DeletionTimeRole
:
1613 // These roles can be determined with retrieveData, and they have to be stored
1614 // in the QHash "values" for the sorting.
1615 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1616 if (itemData
->values
.isEmpty()) {
1617 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1623 // At least store the data including the file type for items with known MIME type.
1624 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1625 if (itemData
->values
.isEmpty()) {
1626 const KFileItem item
= itemData
->item
;
1627 if (item
.isDir() || item
.isMimeTypeKnown()) {
1628 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1635 // The other roles are either resolved by KFileItemModelRolesUpdater
1636 // (this includes the SizeRole for directories), or they do not need
1637 // to be stored in the QHash "values" for sorting because the data can
1638 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1644 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1646 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1647 // if the corresponding item is expanded, and it is not a top-level item.
1648 const ItemData
*parent
= data
->parent
;
1650 if (parent
->parent
) {
1651 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1652 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1661 void KFileItemModel::removeExpandedItems()
1663 QVector
<int> indexesToRemove
;
1665 const int maxIndex
= m_itemData
.count() - 1;
1666 for (int i
= 0; i
<= maxIndex
; ++i
) {
1667 const ItemData
*itemData
= m_itemData
.at(i
);
1668 if (itemData
->parent
) {
1669 indexesToRemove
.append(i
);
1673 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1674 m_expandedDirs
.clear();
1676 // Also remove all filtered items which have a parent.
1677 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1678 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1681 if (it
.value()->parent
) {
1683 it
= m_filteredItems
.erase(it
);
1690 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1692 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1694 // Trigger a resorting if necessary. Note that this can happen even if the sort
1695 // role has not changed at all because the file name can be used as a fallback.
1696 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1697 for (const KItemRange
&range
: itemRanges
) {
1698 bool needsResorting
= false;
1700 const int first
= range
.index
;
1701 const int last
= range
.index
+ range
.count
- 1;
1703 // Resorting the model is necessary if
1704 // (a) The first item in the range is "lessThan" its predecessor,
1705 // (b) the successor of the last item is "lessThan" the last item, or
1706 // (c) the internal order of the items in the range is incorrect.
1707 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1708 needsResorting
= true;
1709 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1710 needsResorting
= true;
1712 for (int index
= first
; index
< last
; ++index
) {
1713 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1714 needsResorting
= true;
1720 if (needsResorting
) {
1721 m_resortAllItemsTimer
->start();
1727 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1728 // The position is still correct, but the groups might have changed
1729 // if the changed item is either the first or the last item in a
1731 // In principle, we could try to find out if the item really is the
1732 // first or last one in its group and then update the groups
1733 // (possibly with a delayed timer to make sure that we don't
1734 // re-calculate the groups very often if items are updated one by
1735 // one), but starting m_resortAllItemsTimer is easier.
1736 m_resortAllItemsTimer
->start();
1740 void KFileItemModel::resetRoles()
1742 for (int i
= 0; i
< RolesCount
; ++i
) {
1743 m_requestRole
[i
] = false;
1747 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1749 static QHash
<QByteArray
, RoleType
> roles
;
1750 if (roles
.isEmpty()) {
1751 // Insert user visible roles that can be accessed with
1752 // KFileItemModel::roleInformation()
1754 const RoleInfoMap
*map
= rolesInfoMap(count
);
1755 for (int i
= 0; i
< count
; ++i
) {
1756 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1759 // Insert internal roles (take care to synchronize the implementation
1760 // with KFileItemModel::roleForType() in case if a change is done).
1761 roles
.insert("isDir", IsDirRole
);
1762 roles
.insert("isLink", IsLinkRole
);
1763 roles
.insert("isHidden", IsHiddenRole
);
1764 roles
.insert("isExpanded", IsExpandedRole
);
1765 roles
.insert("isExpandable", IsExpandableRole
);
1766 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1768 Q_ASSERT(roles
.count() == RolesCount
);
1771 return roles
.value(role
, NoRole
);
1774 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1776 static QHash
<RoleType
, QByteArray
> roles
;
1777 if (roles
.isEmpty()) {
1778 // Insert user visible roles that can be accessed with
1779 // KFileItemModel::roleInformation()
1781 const RoleInfoMap
*map
= rolesInfoMap(count
);
1782 for (int i
= 0; i
< count
; ++i
) {
1783 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1786 // Insert internal roles (take care to synchronize the implementation
1787 // with KFileItemModel::typeForRole() in case if a change is done).
1788 roles
.insert(IsDirRole
, "isDir");
1789 roles
.insert(IsLinkRole
, "isLink");
1790 roles
.insert(IsHiddenRole
, "isHidden");
1791 roles
.insert(IsExpandedRole
, "isExpanded");
1792 roles
.insert(IsExpandableRole
, "isExpandable");
1793 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1795 Q_ASSERT(roles
.count() == RolesCount
);
1798 return roles
.value(roleType
);
1801 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1803 // It is important to insert only roles that are fast to retrieve. E.g.
1804 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1805 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1806 QHash
<QByteArray
, QVariant
> data
;
1807 data
.insert(sharedValue("url"), item
.url());
1809 const bool isDir
= item
.isDir();
1810 if (m_requestRole
[IsDirRole
] && isDir
) {
1811 data
.insert(sharedValue("isDir"), true);
1814 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1815 data
.insert(sharedValue("isLink"), true);
1818 if (m_requestRole
[IsHiddenRole
]) {
1819 data
.insert(sharedValue("isHidden"), item
.isHidden());
1822 if (m_requestRole
[NameRole
]) {
1823 data
.insert(sharedValue("text"), item
.text());
1826 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1827 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1830 if (m_requestRole
[SizeRole
] && !isDir
) {
1831 data
.insert(sharedValue("size"), item
.size());
1834 if (m_requestRole
[ModificationTimeRole
]) {
1835 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1836 // having several thousands of items. Instead read the raw number from UDSEntry directly
1837 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1838 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1839 data
.insert(sharedValue("modificationtime"), dateTime
);
1842 if (m_requestRole
[CreationTimeRole
]) {
1843 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1844 // having several thousands of items. Instead read the raw number from UDSEntry directly
1845 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1846 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1847 data
.insert(sharedValue("creationtime"), dateTime
);
1850 if (m_requestRole
[AccessTimeRole
]) {
1851 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1852 // having several thousands of items. Instead read the raw number from UDSEntry directly
1853 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1854 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1855 data
.insert(sharedValue("accesstime"), dateTime
);
1858 if (m_requestRole
[PermissionsRole
]) {
1859 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1862 if (m_requestRole
[OwnerRole
]) {
1863 data
.insert(sharedValue("owner"), item
.user());
1866 if (m_requestRole
[GroupRole
]) {
1867 data
.insert(sharedValue("group"), item
.group());
1870 if (m_requestRole
[DestinationRole
]) {
1871 QString destination
= item
.linkDest();
1872 if (destination
.isEmpty()) {
1873 destination
= QLatin1Char('-');
1875 data
.insert(sharedValue("destination"), destination
);
1878 if (m_requestRole
[PathRole
]) {
1880 if (item
.url().scheme() == QLatin1String("trash")) {
1881 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1883 // For performance reasons cache the home-path in a static QString
1884 // (see QDir::homePath() for more details)
1885 static QString homePath
;
1886 if (homePath
.isEmpty()) {
1887 homePath
= QDir::homePath();
1890 path
= item
.localPath();
1891 if (path
.startsWith(homePath
)) {
1892 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1896 const int index
= path
.lastIndexOf(item
.text());
1897 path
= path
.mid(0, index
- 1);
1898 data
.insert(sharedValue("path"), path
);
1901 if (m_requestRole
[DeletionTimeRole
]) {
1902 QDateTime deletionTime
;
1903 if (item
.url().scheme() == QLatin1String("trash")) {
1904 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1906 data
.insert(sharedValue("deletiontime"), deletionTime
);
1909 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1910 data
.insert(sharedValue("isExpandable"), true);
1913 if (m_requestRole
[ExpandedParentsCountRole
]) {
1915 const int level
= expandedParentsCount(parent
) + 1;
1916 data
.insert(sharedValue("expandedParentsCount"), level
);
1920 if (item
.isMimeTypeKnown()) {
1921 QString iconName
= item
.iconName();
1922 if (!QIcon::hasThemeIcon(iconName
)) {
1923 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1924 iconName
= mimeType
.genericIconName();
1927 data
.insert(sharedValue("iconName"), iconName
);
1929 if (m_requestRole
[TypeRole
]) {
1930 data
.insert(sharedValue("type"), item
.mimeComment());
1932 } else if (m_requestRole
[TypeRole
] && isDir
) {
1933 static const QString folderMimeType
= item
.mimeComment();
1934 data
.insert(sharedValue("type"), folderMimeType
);
1940 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1944 if (a
->parent
!= b
->parent
) {
1945 const int expansionLevelA
= expandedParentsCount(a
);
1946 const int expansionLevelB
= expandedParentsCount(b
);
1948 // If b has a higher expansion level than a, check if a is a parent
1949 // of b, and make sure that both expansion levels are equal otherwise.
1950 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1951 if (b
->parent
== a
) {
1957 // If a has a higher expansion level than a, check if b is a parent
1958 // of a, and make sure that both expansion levels are equal otherwise.
1959 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1960 if (a
->parent
== b
) {
1966 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1968 // Compare the last parents of a and b which are different.
1969 while (a
->parent
!= b
->parent
) {
1975 // Show hidden files and folders last
1976 if (m_sortHiddenLast
) {
1977 const bool isHiddenA
= a
->item
.isHidden();
1978 const bool isHiddenB
= b
->item
.isHidden();
1979 if (isHiddenA
&& !isHiddenB
) {
1981 } else if (!isHiddenA
&& isHiddenB
) {
1986 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1987 const bool isDirA
= a
->item
.isDir();
1988 const bool isDirB
= b
->item
.isDir();
1989 if (isDirA
&& !isDirB
) {
1991 } else if (!isDirA
&& isDirB
) {
1996 result
= sortRoleCompare(a
, b
, collator
);
1998 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
2001 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
2003 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
2004 return lessThan(a
, b
, m_collator
);
2007 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2008 // Sorting by string can be expensive, in particular if natural sorting is
2009 // enabled. Use all CPU cores to speed up the sorting process.
2010 static const int numberOfThreads
= QThread::idealThreadCount();
2011 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2013 // Sorting by other roles is quite fast. Use only one thread to prevent
2014 // problems caused by non-reentrant comparison functions, see
2015 // https://bugs.kde.org/show_bug.cgi?id=312679
2016 mergeSort(begin
, end
, lambdaLessThan
);
2020 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2022 // This function must never return 0, because that would break stable
2023 // sorting, which leads to all kinds of bugs.
2024 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2025 // If two items have equal sort values, let the fallbacks at the bottom of
2026 // the function handle it.
2027 const KFileItem
&itemA
= a
->item
;
2028 const KFileItem
&itemB
= b
->item
;
2032 switch (m_sortRole
) {
2034 // The name role is handled as default fallback after the switch
2038 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
2039 // folders first then
2040 // items A and B are folders thanks to lessThan checks
2041 auto valueA
= a
->values
.value("count");
2042 auto valueB
= b
->values
.value("count");
2043 if (valueA
.isNull()) {
2044 if (!valueB
.isNull()) {
2047 } else if (valueB
.isNull()) {
2050 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2052 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2059 KIO::filesize_t sizeA
= 0;
2060 if (itemA
.isDir()) {
2061 sizeA
= a
->values
.value("size").toULongLong();
2063 sizeA
= itemA
.size();
2065 KIO::filesize_t sizeB
= 0;
2066 if (itemB
.isDir()) {
2067 sizeB
= b
->values
.value("size").toULongLong();
2069 sizeB
= itemB
.size();
2071 if (sizeA
< sizeB
) {
2073 } else if (sizeA
> sizeB
) {
2079 case ModificationTimeRole
: {
2080 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2081 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2082 if (dateTimeA
< dateTimeB
) {
2084 } else if (dateTimeA
> dateTimeB
) {
2090 case AccessTimeRole
: {
2091 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2092 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2093 if (dateTimeA
< dateTimeB
) {
2095 } else if (dateTimeA
> dateTimeB
) {
2101 case CreationTimeRole
: {
2102 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2103 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2104 if (dateTimeA
< dateTimeB
) {
2106 } else if (dateTimeA
> dateTimeB
) {
2112 case DeletionTimeRole
: {
2113 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2114 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2115 if (dateTimeA
< dateTimeB
) {
2117 } else if (dateTimeA
> dateTimeB
) {
2131 case ReleaseYearRole
: {
2132 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2136 case DimensionsRole
: {
2137 const QByteArray role
= roleForType(m_sortRole
);
2138 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2139 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2141 if (dimensionsA
.width() == dimensionsB
.width()) {
2142 result
= dimensionsA
.height() - dimensionsB
.height();
2144 result
= dimensionsA
.width() - dimensionsB
.width();
2150 const QByteArray role
= roleForType(m_sortRole
);
2151 const QString roleValueA
= a
->values
.value(role
).toString();
2152 const QString roleValueB
= b
->values
.value(role
).toString();
2153 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2155 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2157 } else if (isRoleValueNatural(m_sortRole
)) {
2158 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2160 result
= QString::compare(roleValueA
, roleValueB
);
2167 // The current sort role was sufficient to define an order
2171 // Fallback #1: Compare the text of the items
2172 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2177 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2178 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2183 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2184 // equal. In this case a comparison of the URL is done which is unique in all cases
2185 // within KDirLister.
2186 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2189 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2191 QMutexLocker
collatorLock(s_collatorMutex());
2193 if (m_naturalSorting
) {
2194 return collator
.compare(a
, b
);
2197 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2198 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2199 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2200 // comparison, still a deterministic sort order is required. A case sensitive
2201 // comparison is done as fallback.
2205 return QString::compare(a
, b
, Qt::CaseSensitive
);
2208 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2210 Q_ASSERT(!m_itemData
.isEmpty());
2212 const int maxIndex
= count() - 1;
2213 QList
<QPair
<int, QVariant
>> groups
;
2217 for (int i
= 0; i
<= maxIndex
; ++i
) {
2218 if (isChildItem(i
)) {
2222 const QString name
= m_itemData
.at(i
)->item
.text();
2224 // Use the first character of the name as group indication
2225 QChar newFirstChar
= name
.at(0).toUpper();
2226 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2227 newFirstChar
= name
.at(1).toUpper();
2230 if (firstChar
!= newFirstChar
) {
2231 QString newGroupValue
;
2232 if (newFirstChar
.isLetter()) {
2233 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2234 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2236 // Try to find a matching group in the range 'A' to 'Z'.
2237 static std::vector
<QChar
> lettersAtoZ
;
2238 lettersAtoZ
.reserve('Z' - 'A' + 1);
2239 if (lettersAtoZ
.empty()) {
2240 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2241 lettersAtoZ
.push_back(QLatin1Char(c
));
2245 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2246 return m_collator
.compare(c1
, c2
) < 0;
2249 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2250 if (it
!= lettersAtoZ
.end()) {
2251 if (localeAwareLessThan(newFirstChar
, *it
)) {
2252 // newFirstChar belongs to the group preceding *it.
2253 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2256 newGroupValue
= *it
;
2260 // Symbols from non Latin-based scripts
2261 newGroupValue
= newFirstChar
;
2263 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2264 // Apply group '0 - 9' for any name that starts with a digit
2265 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2267 newGroupValue
= i18nc("@title:group", "Others");
2270 if (newGroupValue
!= groupValue
) {
2271 groupValue
= newGroupValue
;
2272 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2275 firstChar
= newFirstChar
;
2281 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2283 Q_ASSERT(!m_itemData
.isEmpty());
2285 const int maxIndex
= count() - 1;
2286 QList
<QPair
<int, QVariant
>> groups
;
2289 for (int i
= 0; i
<= maxIndex
; ++i
) {
2290 if (isChildItem(i
)) {
2294 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2295 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2296 QString newGroupValue
;
2297 if (!item
.isNull() && item
.isDir()) {
2298 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2299 newGroupValue
= i18nc("@title:group Size", "Folders");
2301 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2305 if (newGroupValue
.isEmpty()) {
2306 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2307 newGroupValue
= i18nc("@title:group Size", "Small");
2308 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2309 newGroupValue
= i18nc("@title:group Size", "Medium");
2311 newGroupValue
= i18nc("@title:group Size", "Big");
2315 if (newGroupValue
!= groupValue
) {
2316 groupValue
= newGroupValue
;
2317 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2324 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2326 Q_ASSERT(!m_itemData
.isEmpty());
2328 const int maxIndex
= count() - 1;
2329 QList
<QPair
<int, QVariant
>> groups
;
2331 const QDate currentDate
= QDate::currentDate();
2333 QDate previousFileDate
;
2335 for (int i
= 0; i
<= maxIndex
; ++i
) {
2336 if (isChildItem(i
)) {
2340 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2341 const QDate fileDate
= fileTime
.date();
2342 if (fileDate
== previousFileDate
) {
2343 // The current item is in the same group as the previous item
2346 previousFileDate
= fileDate
;
2348 const int daysDistance
= fileDate
.daysTo(currentDate
);
2350 QString newGroupValue
;
2351 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2352 switch (daysDistance
/ 7) {
2354 switch (daysDistance
) {
2356 newGroupValue
= i18nc("@title:group Date", "Today");
2359 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2362 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2363 newGroupValue
= i18nc(
2364 "Can be used to script translation of \"dddd\""
2365 "with context @title:group Date",
2371 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2374 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2377 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2381 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2387 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2388 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2389 if (daysDistance
== 1) {
2390 const KLocalizedString format
= ki18nc(
2391 "@title:group Date: "
2392 "MMMM is full month name in current locale, and yyyy is "
2393 "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 "
2394 "part of the text that should not be formatted as a date",
2395 "'Yesterday' (MMMM, yyyy)");
2396 const QString translatedFormat
= format
.toString();
2397 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2398 newGroupValue
= fileTime
.toString(translatedFormat
);
2399 newGroupValue
= i18nc(
2400 "Can be used to script translation of "
2401 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2405 qCWarning(DolphinDebug
).nospace()
2406 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2407 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2408 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2410 } else if (daysDistance
<= 7) {
2412 fileTime
.toString(i18nc("@title:group Date: "
2413 "The week day name: dddd, MMMM is full month name "
2414 "in current locale, and yyyy is full year number.",
2415 "dddd (MMMM, yyyy)"));
2416 newGroupValue
= i18nc(
2417 "Can be used to script translation of "
2418 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2421 } else if (daysDistance
<= 7 * 2) {
2422 const KLocalizedString format
= ki18nc(
2423 "@title:group Date: "
2424 "MMMM is full month name in current locale, and yyyy is "
2425 "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 "
2426 "part of the text that should not be formatted as a date",
2427 "'One Week Ago' (MMMM, yyyy)");
2428 const QString translatedFormat
= format
.toString();
2429 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2430 newGroupValue
= fileTime
.toString(translatedFormat
);
2431 newGroupValue
= i18nc(
2432 "Can be used to script translation of "
2433 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2437 qCWarning(DolphinDebug
).nospace()
2438 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2439 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2440 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2442 } else if (daysDistance
<= 7 * 3) {
2443 const KLocalizedString format
= ki18nc(
2444 "@title:group Date: "
2445 "MMMM is full month name in current locale, and yyyy is "
2446 "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 "
2447 "part of the text that should not be formatted as a date",
2448 "'Two Weeks Ago' (MMMM, yyyy)");
2449 const QString translatedFormat
= format
.toString();
2450 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2451 newGroupValue
= fileTime
.toString(translatedFormat
);
2452 newGroupValue
= i18nc(
2453 "Can be used to script translation of "
2454 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2458 qCWarning(DolphinDebug
).nospace()
2459 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2460 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2461 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2463 } else if (daysDistance
<= 7 * 4) {
2464 const KLocalizedString format
= ki18nc(
2465 "@title:group Date: "
2466 "MMMM is full month name in current locale, and yyyy is "
2467 "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 "
2468 "part of the text that should not be formatted as a date",
2469 "'Three Weeks Ago' (MMMM, yyyy)");
2470 const QString translatedFormat
= format
.toString();
2471 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2472 newGroupValue
= fileTime
.toString(translatedFormat
);
2473 newGroupValue
= i18nc(
2474 "Can be used to script translation of "
2475 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2479 qCWarning(DolphinDebug
).nospace()
2480 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2481 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2482 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2485 const KLocalizedString format
= ki18nc(
2486 "@title:group Date: "
2487 "MMMM is full month name in current locale, and yyyy is "
2488 "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 "
2489 "part of the text that should not be formatted as a date",
2490 "'Earlier on' MMMM, yyyy");
2491 const QString translatedFormat
= format
.toString();
2492 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2493 newGroupValue
= fileTime
.toString(translatedFormat
);
2494 newGroupValue
= i18nc(
2495 "Can be used to script translation of "
2496 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2500 qCWarning(DolphinDebug
).nospace()
2501 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2502 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2503 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2508 fileTime
.toString(i18nc("@title:group "
2509 "The month and year: MMMM is full month name in current locale, "
2510 "and yyyy is full year number",
2512 newGroupValue
= i18nc(
2513 "Can be used to script translation of "
2514 "\"MMMM, yyyy\" with context @title:group Date",
2520 if (newGroupValue
!= groupValue
) {
2521 groupValue
= newGroupValue
;
2522 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2529 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2531 Q_ASSERT(!m_itemData
.isEmpty());
2533 const int maxIndex
= count() - 1;
2534 QList
<QPair
<int, QVariant
>> groups
;
2536 QString permissionsString
;
2538 for (int i
= 0; i
<= maxIndex
; ++i
) {
2539 if (isChildItem(i
)) {
2543 const ItemData
*itemData
= m_itemData
.at(i
);
2544 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2545 if (newPermissionsString
== permissionsString
) {
2548 permissionsString
= newPermissionsString
;
2550 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2554 if (info
.permission(QFile::ReadUser
)) {
2555 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2557 if (info
.permission(QFile::WriteUser
)) {
2558 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2560 if (info
.permission(QFile::ExeUser
)) {
2561 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2563 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2567 if (info
.permission(QFile::ReadGroup
)) {
2568 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2570 if (info
.permission(QFile::WriteGroup
)) {
2571 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2573 if (info
.permission(QFile::ExeGroup
)) {
2574 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2576 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2578 // Set others string
2580 if (info
.permission(QFile::ReadOther
)) {
2581 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2583 if (info
.permission(QFile::WriteOther
)) {
2584 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2586 if (info
.permission(QFile::ExeOther
)) {
2587 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2589 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2591 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2592 if (newGroupValue
!= groupValue
) {
2593 groupValue
= newGroupValue
;
2594 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2601 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2603 Q_ASSERT(!m_itemData
.isEmpty());
2605 const int maxIndex
= count() - 1;
2606 QList
<QPair
<int, QVariant
>> groups
;
2608 int groupValue
= -1;
2609 for (int i
= 0; i
<= maxIndex
; ++i
) {
2610 if (isChildItem(i
)) {
2613 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2614 if (newGroupValue
!= groupValue
) {
2615 groupValue
= newGroupValue
;
2616 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2623 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2625 Q_ASSERT(!m_itemData
.isEmpty());
2627 const int maxIndex
= count() - 1;
2628 QList
<QPair
<int, QVariant
>> groups
;
2630 bool isFirstGroupValue
= true;
2632 for (int i
= 0; i
<= maxIndex
; ++i
) {
2633 if (isChildItem(i
)) {
2636 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2637 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2638 groupValue
= newGroupValue
;
2639 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2640 isFirstGroupValue
= false;
2647 void KFileItemModel::emitSortProgress(int resolvedCount
)
2649 // Be tolerant against a resolvedCount with a wrong range.
2650 // Although there should not be a case where KFileItemModelRolesUpdater
2651 // (= caller) provides a wrong range, it is important to emit
2652 // a useful progress information even if there is an unexpected
2653 // implementation issue.
2655 const int itemCount
= count();
2656 if (resolvedCount
>= itemCount
) {
2657 m_sortingProgressPercent
= -1;
2658 if (m_resortAllItemsTimer
->isActive()) {
2659 m_resortAllItemsTimer
->stop();
2663 Q_EMIT
directorySortingProgress(100);
2664 } else if (itemCount
> 0) {
2665 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2667 const int progress
= resolvedCount
* 100 / itemCount
;
2668 if (m_sortingProgressPercent
!= progress
) {
2669 m_sortingProgressPercent
= progress
;
2670 Q_EMIT
directorySortingProgress(progress
);
2675 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2677 static const RoleInfoMap rolesInfoMap
[] = {
2679 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2680 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2681 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2682 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2683 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2684 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2685 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2686 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2687 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2688 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2689 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2690 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2691 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2692 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2693 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2694 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2695 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2696 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2697 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2698 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2699 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2700 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2701 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2702 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2703 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2704 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2705 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2706 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2707 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2708 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2709 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2710 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2711 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2712 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2713 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2714 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2715 { "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 },
2716 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2717 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2721 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2722 return rolesInfoMap
;
2725 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2727 QElapsedTimer timer
;
2729 for (const KFileItem
&item
: items
) {
2730 // Only determine mime types for files here. For directories,
2731 // KFileItem::determineMimeType() reads the .directory file inside to
2732 // load the icon, but this is not necessary at all if we just need the
2733 // type. Some special code for setting the correct mime type for
2734 // directories is in retrieveData().
2735 if (!item
.isDir()) {
2736 item
.determineMimeType();
2739 if (timer
.elapsed() > timeout
) {
2740 // Don't block the user interface, let the remaining items
2741 // be resolved asynchronously.
2747 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2749 static QSet
<QByteArray
> pool
;
2750 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2752 if (it
!= pool
.constEnd()) {
2760 bool KFileItemModel::isConsistent() const
2762 // m_items may contain less items than m_itemData because m_items
2763 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2764 if (m_items
.count() > m_itemData
.count()) {
2768 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2769 // Check if m_items and m_itemData are consistent.
2770 const KFileItem item
= fileItem(i
);
2771 if (item
.isNull()) {
2772 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2776 const int itemIndex
= index(item
);
2777 if (itemIndex
!= i
) {
2778 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2782 // Check if the items are sorted correctly.
2783 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2784 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2788 // Check if all parent-child relationships are consistent.
2789 const ItemData
*data
= m_itemData
.at(i
);
2790 const ItemData
*parent
= data
->parent
;
2792 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2793 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2797 const int parentIndex
= index(parent
->item
);
2798 if (parentIndex
>= i
) {
2799 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2809 void KFileItemModel::slotListerError(KIO::Job
*job
)
2811 if (job
->error() == KIO::ERR_IS_FILE
) {
2812 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2813 Q_EMIT
urlIsFileError(listJob
->url());
2816 const QString errorString
= job
->errorString();
2817 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));