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>
21 #include <QElapsedTimer>
24 #include <QMimeDatabase>
25 #include <QRecursiveMutex>
29 #include <klazylocalizedstring.h>
31 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(QObject
*parent
)
36 : KItemModelBase("text", parent
)
37 , m_dirLister(nullptr)
38 , m_sortDirsFirst(true)
39 , m_sortHiddenLast(false)
40 , m_sortRole(NameRole
)
41 , m_sortingProgressPercent(-1)
48 , m_maximumUpdateIntervalTimer(nullptr)
49 , m_resortAllItemsTimer(nullptr)
50 , m_pendingItemsToInsert()
55 m_collator
.setNumericMode(true);
57 loadSortingSettings();
59 m_dirLister
= new KDirLister(this);
60 m_dirLister
->setAutoErrorHandlingEnabled(false);
61 m_dirLister
->setDelayedMimeTypes(true);
63 const QWidget
*parentWidget
= qobject_cast
<QWidget
*>(parent
);
65 m_dirLister
->setMainWindow(parentWidget
->window());
68 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
69 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
70 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
71 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
72 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
73 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
74 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
75 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
76 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
77 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
78 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
80 // Apply default roles that should be determined
82 m_requestRole
[NameRole
] = true;
83 m_requestRole
[IsDirRole
] = true;
84 m_requestRole
[IsLinkRole
] = true;
85 m_roles
.insert("text");
86 m_roles
.insert("isDir");
87 m_roles
.insert("isLink");
88 m_roles
.insert("isHidden");
90 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
91 // before the completed() or canceled() signal has been emitted.
92 m_maximumUpdateIntervalTimer
= new QTimer(this);
93 m_maximumUpdateIntervalTimer
->setInterval(2000);
94 m_maximumUpdateIntervalTimer
->setSingleShot(true);
95 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
97 // When changing the value of an item which represents the sort-role a resorting must be
98 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
99 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
100 // resorting is postponed until the timer has been exceeded.
101 m_resortAllItemsTimer
= new QTimer(this);
102 m_resortAllItemsTimer
->setInterval(500);
103 m_resortAllItemsTimer
->setSingleShot(true);
104 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
106 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
109 KFileItemModel::~KFileItemModel()
111 qDeleteAll(m_itemData
);
112 qDeleteAll(m_filteredItems
);
113 qDeleteAll(m_pendingItemsToInsert
);
116 void KFileItemModel::loadDirectory(const QUrl
&url
)
118 m_dirLister
->openUrl(url
);
121 void KFileItemModel::refreshDirectory(const QUrl
&url
)
123 // Refresh all expanded directories first (Bug 295300)
124 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
125 while (expandedDirs
.hasNext()) {
127 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
130 m_dirLister
->openUrl(url
, KDirLister::Reload
);
133 QUrl
KFileItemModel::directory() const
135 return m_dirLister
->url();
138 void KFileItemModel::cancelDirectoryLoading()
143 int KFileItemModel::count() const
145 return m_itemData
.count();
148 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
150 if (index
>= 0 && index
< count()) {
151 ItemData
*data
= m_itemData
.at(index
);
152 if (data
->values
.isEmpty()) {
153 data
->values
= retrieveData(data
->item
, data
->parent
);
154 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
155 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
156 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
157 // so this special request of different behavior can be identified here.
158 bool hasExpandedParentsCount
= false;
159 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
161 data
->values
= retrieveData(data
->item
, data
->parent
);
162 data
->values
.insert("isExpanded", true);
163 if (hasExpandedParentsCount
) {
164 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
170 return QHash
<QByteArray
, QVariant
>();
173 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
> &values
)
175 if (index
< 0 || index
>= count()) {
179 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
181 // Determine which roles have been changed
182 QSet
<QByteArray
> changedRoles
;
183 QHashIterator
<QByteArray
, QVariant
> it(values
);
184 while (it
.hasNext()) {
186 const QByteArray role
= sharedValue(it
.key());
187 const QVariant value
= it
.value();
189 if (currentValues
[role
] != value
) {
190 currentValues
[role
] = value
;
191 changedRoles
.insert(role
);
195 if (changedRoles
.isEmpty()) {
199 m_itemData
[index
]->values
= currentValues
;
200 if (changedRoles
.contains("text")) {
201 QUrl url
= m_itemData
[index
]->item
.url();
202 url
= url
.adjusted(QUrl::RemoveFilename
);
203 url
.setPath(url
.path() + currentValues
["text"].toString());
204 m_itemData
[index
]->item
.setUrl(url
);
207 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
212 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
214 if (dirsFirst
!= m_sortDirsFirst
) {
215 m_sortDirsFirst
= dirsFirst
;
220 bool KFileItemModel::sortDirectoriesFirst() const
222 return m_sortDirsFirst
;
225 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
227 if (hiddenLast
!= m_sortHiddenLast
) {
228 m_sortHiddenLast
= hiddenLast
;
233 bool KFileItemModel::sortHiddenLast() const
235 return m_sortHiddenLast
;
238 void KFileItemModel::setShowHiddenFiles(bool show
)
240 m_dirLister
->setShowHiddenFiles(show
);
241 m_dirLister
->emitChanges();
243 dispatchPendingItemsToInsert();
247 bool KFileItemModel::showHiddenFiles() const
249 return m_dirLister
->showHiddenFiles();
252 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
254 m_dirLister
->setDirOnlyMode(enabled
);
257 bool KFileItemModel::showDirectoriesOnly() const
259 return m_dirLister
->dirOnlyMode();
262 QMimeData
*KFileItemModel::createMimeData(const KItemSet
&indexes
) const
264 QMimeData
*data
= new QMimeData();
266 // The following code has been taken from KDirModel::mimeData()
267 // (kdelibs/kio/kio/kdirmodel.cpp)
268 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
270 QList
<QUrl
> mostLocalUrls
;
271 const ItemData
*lastAddedItem
= nullptr;
273 for (int index
: indexes
) {
274 const ItemData
*itemData
= m_itemData
.at(index
);
275 const ItemData
*parent
= itemData
->parent
;
277 while (parent
&& parent
!= lastAddedItem
) {
278 parent
= parent
->parent
;
281 if (parent
&& parent
== lastAddedItem
) {
282 // A parent of 'itemData' has been added already.
286 lastAddedItem
= itemData
;
287 const KFileItem
&item
= itemData
->item
;
288 if (!item
.isNull()) {
292 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
296 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
300 int KFileItemModel::indexForKeyboardSearch(const QString
&text
, int startFromIndex
) const
302 startFromIndex
= qMax(0, startFromIndex
);
303 for (int i
= startFromIndex
; i
< count(); ++i
) {
304 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
308 for (int i
= 0; i
< startFromIndex
; ++i
) {
309 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
316 bool KFileItemModel::supportsDropping(int index
) const
322 item
= fileItem(index
);
324 return !item
.isNull() && ((item
.isDir() && item
.isWritable()) || item
.isDesktopFile());
327 QString
KFileItemModel::roleDescription(const QByteArray
&role
) const
329 static QHash
<QByteArray
, QString
> description
;
330 if (description
.isEmpty()) {
332 const RoleInfoMap
*map
= rolesInfoMap(count
);
333 for (int i
= 0; i
< count
; ++i
) {
334 if (map
[i
].roleTranslation
.isEmpty()) {
337 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
341 return description
.value(role
);
344 QList
<QPair
<int, QVariant
>> KFileItemModel::groups() const
346 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
347 #ifdef KFILEITEMMODEL_DEBUG
351 switch (typeForRole(sortRole())) {
353 m_groups
= nameRoleGroups();
356 m_groups
= sizeRoleGroups();
358 case ModificationTimeRole
:
359 m_groups
= timeRoleGroups([](const ItemData
*item
) {
360 return item
->item
.time(KFileItem::ModificationTime
);
363 case CreationTimeRole
:
364 m_groups
= timeRoleGroups([](const ItemData
*item
) {
365 return item
->item
.time(KFileItem::CreationTime
);
369 m_groups
= timeRoleGroups([](const ItemData
*item
) {
370 return item
->item
.time(KFileItem::AccessTime
);
373 case DeletionTimeRole
:
374 m_groups
= timeRoleGroups([](const ItemData
*item
) {
375 return item
->values
.value("deletiontime").toDateTime();
378 case PermissionsRole
:
379 m_groups
= permissionRoleGroups();
382 m_groups
= ratingRoleGroups();
385 m_groups
= genericStringRoleGroups(sortRole());
389 #ifdef KFILEITEMMODEL_DEBUG
390 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
397 KFileItem
KFileItemModel::fileItem(int index
) const
399 if (index
>= 0 && index
< count()) {
400 return m_itemData
.at(index
)->item
;
406 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
408 const int indexForUrl
= index(url
);
409 if (indexForUrl
>= 0) {
410 return m_itemData
.at(indexForUrl
)->item
;
415 int KFileItemModel::index(const KFileItem
&item
) const
417 return index(item
.url());
420 int KFileItemModel::index(const QUrl
&url
) const
422 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
424 const int itemCount
= m_itemData
.count();
425 int itemsInHash
= m_items
.count();
427 int index
= m_items
.value(urlToFind
, -1);
428 while (index
< 0 && itemsInHash
< itemCount
) {
429 // Not all URLs are stored yet in m_items. We grow m_items until either
430 // urlToFind is found, or all URLs have been stored in m_items.
431 // Note that we do not add the URLs to m_items one by one, but in
432 // larger blocks. After each block, we check if urlToFind is in
433 // m_items. We could in principle compare urlToFind with each URL while
434 // we are going through m_itemData, but comparing two QUrls will,
435 // unlike calling qHash for the URLs, trigger a parsing of the URLs
436 // which costs both CPU cycles and memory.
437 const int blockSize
= 1000;
438 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
439 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
440 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
441 m_items
.insert(nextUrl
, i
);
444 itemsInHash
= currentBlockEnd
;
445 index
= m_items
.value(urlToFind
, -1);
449 // The item could not be found, even though all items from m_itemData
450 // should be in m_items now. We print some diagnostic information which
451 // might help to find the cause of the problem, but only once. This
452 // prevents that obtaining and printing the debugging information
453 // wastes CPU cycles and floods the shell or .xsession-errors.
454 static bool printDebugInfo
= true;
456 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
457 printDebugInfo
= false;
459 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
460 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
461 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
463 // Check if there are multiple items with the same URL.
464 QMultiHash
<QUrl
, int> indexesForUrl
;
465 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
466 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
469 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
470 for (const QUrl
&url
: uniqueKeys
) {
471 if (indexesForUrl
.count(url
) > 1) {
472 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
474 auto it
= indexesForUrl
.find(url
);
475 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
476 const ItemData
*data
= m_itemData
.at(it
.value());
477 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
479 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
491 KFileItem
KFileItemModel::rootItem() const
493 return m_dirLister
->rootItem();
496 void KFileItemModel::clear()
501 void KFileItemModel::setRoles(const QSet
<QByteArray
> &roles
)
503 if (m_roles
== roles
) {
507 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
511 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
512 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
513 if (supportedExpanding
&& !willSupportExpanding
) {
514 // No expanding is supported anymore. Take care to delete all items that have an expansion level
515 // that is not 0 (and hence are part of an expanded item).
516 removeExpandedItems();
523 QSetIterator
<QByteArray
> it(roles
);
524 while (it
.hasNext()) {
525 const QByteArray
&role
= it
.next();
526 m_requestRole
[typeForRole(role
)] = true;
530 // Update m_data with the changed requested roles
531 const int maxIndex
= count() - 1;
532 for (int i
= 0; i
<= maxIndex
; ++i
) {
533 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
536 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
539 // Clear the 'values' of all filtered items. They will be re-populated with the
540 // correct roles the next time 'values' will be accessed via data(int).
541 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
542 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
543 while (filteredIt
!= filteredEnd
) {
544 (*filteredIt
)->values
.clear();
549 QSet
<QByteArray
> KFileItemModel::roles() const
554 bool KFileItemModel::setExpanded(int index
, bool expanded
)
556 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
560 QHash
<QByteArray
, QVariant
> values
;
561 values
.insert(sharedValue("isExpanded"), expanded
);
562 if (!setData(index
, values
)) {
566 const KFileItem item
= m_itemData
.at(index
)->item
;
567 const QUrl url
= item
.url();
568 const QUrl targetUrl
= item
.targetUrl();
570 m_expandedDirs
.insert(targetUrl
, url
);
571 m_dirLister
->openUrl(url
, KDirLister::Keep
);
573 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
574 for (const QVariant
&var
: previouslyExpandedChildren
) {
575 m_urlsToExpand
.insert(var
.toUrl());
578 // Note that there might be (indirect) children of the folder which is to be collapsed in
579 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
580 // possibly without a parent, which might result in a crash, we insert all pending items
581 // right now. All new items which would be without a parent will then be removed.
582 dispatchPendingItemsToInsert();
584 // Check if the index of the collapsed folder has changed. If that is the case, then items
585 // were inserted before the collapsed folder, and its index needs to be updated.
586 if (m_itemData
.at(index
)->item
!= item
) {
587 index
= this->index(item
);
590 m_expandedDirs
.remove(targetUrl
);
591 m_dirLister
->stop(url
);
592 m_dirLister
->forgetDirs(url
);
594 const int parentLevel
= expandedParentsCount(index
);
595 const int itemCount
= m_itemData
.count();
596 const int firstChildIndex
= index
+ 1;
598 QVariantList expandedChildren
;
600 int childIndex
= firstChildIndex
;
601 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
602 ItemData
*itemData
= m_itemData
.at(childIndex
);
603 if (itemData
->values
.value("isExpanded").toBool()) {
604 const QUrl targetUrl
= itemData
->item
.targetUrl();
605 const QUrl url
= itemData
->item
.url();
606 m_expandedDirs
.remove(targetUrl
);
607 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
608 m_dirLister
->forgetDirs(url
);
609 expandedChildren
.append(targetUrl
);
613 const int childrenCount
= childIndex
- firstChildIndex
;
615 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
616 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
618 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
624 bool KFileItemModel::isExpanded(int index
) const
626 if (index
>= 0 && index
< count()) {
627 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
632 bool KFileItemModel::isExpandable(int index
) const
634 if (index
>= 0 && index
< count()) {
635 // Call data (instead of accessing m_itemData directly)
636 // to ensure that the value is initialized.
637 return data(index
).value("isExpandable").toBool();
642 int KFileItemModel::expandedParentsCount(int index
) const
644 if (index
>= 0 && index
< count()) {
645 return expandedParentsCount(m_itemData
.at(index
));
650 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
653 const auto dirs
= m_expandedDirs
;
654 for (const auto &dir
: dirs
) {
660 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
662 m_urlsToExpand
= urls
;
665 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
667 // Assure that each sub-path of the URL that should be
668 // expanded is added to m_urlsToExpand. KDirLister
669 // does not care whether the parent-URL has already been
671 QUrl urlToExpand
= m_dirLister
->url();
672 const int pos
= urlToExpand
.path().length();
674 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
675 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
676 // so using QString::SkipEmptyParts
677 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
678 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
679 QString path
= urlToExpand
.path();
680 if (!path
.endsWith(QLatin1Char('/'))) {
681 path
.append(QLatin1Char('/'));
683 urlToExpand
.setPath(path
+ subDirs
.at(i
));
684 m_urlsToExpand
.insert(urlToExpand
);
687 // KDirLister::open() must called at least once to trigger an initial
688 // loading. The pending URLs that must be restored are handled
689 // in slotCompleted().
690 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
691 while (it2
.hasNext()) {
692 const int idx
= index(it2
.next());
693 if (idx
>= 0 && !isExpanded(idx
)) {
694 setExpanded(idx
, true);
700 void KFileItemModel::setNameFilter(const QString
&nameFilter
)
702 if (m_filter
.pattern() != nameFilter
) {
703 dispatchPendingItemsToInsert();
704 m_filter
.setPattern(nameFilter
);
709 QString
KFileItemModel::nameFilter() const
711 return m_filter
.pattern();
714 void KFileItemModel::setMimeTypeFilters(const QStringList
&filters
)
716 if (m_filter
.mimeTypes() != filters
) {
717 dispatchPendingItemsToInsert();
718 m_filter
.setMimeTypes(filters
);
723 QStringList
KFileItemModel::mimeTypeFilters() const
725 return m_filter
.mimeTypes();
728 void KFileItemModel::applyFilters()
731 // Check which previously shown items from m_itemData must now get
732 // hidden and hence moved from m_itemData into m_filteredItems.
734 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
736 // This pointer will refer to the next confirmed shown item from the point of
737 // view of the current "itemData" in the upcoming "for" loop.
738 ItemData
*itemShownBelow
= nullptr;
740 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
741 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
742 ItemData
*itemData
= m_itemData
.at(index
);
744 if (m_filter
.matches(itemData
->item
) || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
745 // We could've entered here for two reasons:
746 // 1. This item passes the filter itself
747 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
749 // So this item must remain shown.
750 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
751 itemShownBelow
= itemData
;
753 // We hide this item for now, however, for expanded folders this is not final:
754 // 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
755 newFilteredIndexes
.prepend(index
);
756 m_filteredItems
.insert(itemData
->item
, itemData
);
757 // indexShownBelow doesn't get updated since this item will be hidden
761 // This will remove the newly filtered items from m_itemData
762 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
765 // Check which hidden items from m_filteredItems should
766 // become visible again and hence moved from m_filteredItems back into m_itemData.
768 QList
<ItemData
*> newVisibleItems
;
770 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
772 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
773 while (it
!= m_filteredItems
.end()) {
774 if (m_filter
.matches(it
.key())) {
775 newVisibleItems
.append(it
.value());
777 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
778 // We will go up through its parental chain until we either:
779 // 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
780 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
781 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
782 parent
= parent
->parent
) {
783 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
784 // and it would mess up the iteration. We will mark it to be removed in step 3.
785 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
788 it
= m_filteredItems
.erase(it
);
790 // Item remains filtered for now
791 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
797 // Handles the ancestorsOfNewVisibleItems.
798 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
799 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
800 if (m_filteredItems
.remove(it
.key())) {
801 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
802 newVisibleItems
.append(it
.value());
806 // This will insert the newly discovered unfiltered items into m_itemData
807 insertItems(newVisibleItems
);
810 void KFileItemModel::removeFilteredChildren(const KItemRangeList
&itemRanges
)
812 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
813 // There are either no filtered items, or it is not possible to expand
814 // folders -> there cannot be any filtered children.
818 QSet
<ItemData
*> parents
;
819 for (const KItemRange
&range
: itemRanges
) {
820 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
821 parents
.insert(m_itemData
.at(index
));
825 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
826 while (it
!= m_filteredItems
.end()) {
827 if (parents
.contains(it
.value()->parent
)) {
829 it
= m_filteredItems
.erase(it
);
836 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
838 static QList
<RoleInfo
> rolesInfo
;
839 if (rolesInfo
.isEmpty()) {
841 const RoleInfoMap
*map
= rolesInfoMap(count
);
842 for (int i
= 0; i
< count
; ++i
) {
843 if (map
[i
].roleType
!= NoRole
) {
845 info
.role
= map
[i
].role
;
846 info
.translation
= map
[i
].roleTranslation
.toString();
847 if (!map
[i
].groupTranslation
.isEmpty()) {
848 info
.group
= map
[i
].groupTranslation
.toString();
850 // For top level roles, groupTranslation is 0. We must make sure that
851 // info.group is an empty string then because the code that generates
852 // menus tries to put the actions into sub menus otherwise.
853 info
.group
= QString();
855 info
.requiresBaloo
= map
[i
].requiresBaloo
;
856 info
.requiresIndexer
= map
[i
].requiresIndexer
;
857 if (!map
[i
].tooltipTranslation
.isEmpty()) {
858 info
.tooltip
= map
[i
].tooltipTranslation
.toString();
860 info
.tooltip
= QString();
862 rolesInfo
.append(info
);
870 void KFileItemModel::onGroupedSortingChanged(bool current
)
876 void KFileItemModel::onSortRoleChanged(const QByteArray
¤t
, const QByteArray
&previous
, bool resortItems
)
879 m_sortRole
= typeForRole(current
);
881 if (!m_requestRole
[m_sortRole
]) {
882 QSet
<QByteArray
> newRoles
= m_roles
;
892 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
899 void KFileItemModel::loadSortingSettings()
901 using Choice
= GeneralSettings::EnumSortingChoice
;
902 switch (GeneralSettings::sortingChoice()) {
903 case Choice::NaturalSorting
:
904 m_naturalSorting
= true;
905 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
907 case Choice::CaseSensitiveSorting
:
908 m_naturalSorting
= false;
909 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
911 case Choice::CaseInsensitiveSorting
:
912 m_naturalSorting
= false;
913 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
918 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
919 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
920 m_collator
.compare(QString(), QString());
923 void KFileItemModel::resortAllItems()
925 m_resortAllItemsTimer
->stop();
927 const int itemCount
= count();
928 if (itemCount
<= 0) {
932 #ifdef KFILEITEMMODEL_DEBUG
935 qCDebug(DolphinDebug
) << "===========================================================";
936 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
939 // Remember the order of the current URLs so
940 // that it can be determined which indexes have
941 // been moved because of the resorting.
943 oldUrls
.reserve(itemCount
);
944 for (const ItemData
*itemData
: qAsConst(m_itemData
)) {
945 oldUrls
.append(itemData
->item
.url());
949 m_items
.reserve(itemCount
);
952 sort(m_itemData
.begin(), m_itemData
.end());
953 for (int i
= 0; i
< itemCount
; ++i
) {
954 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
957 // Determine the first index that has been moved.
958 int firstMovedIndex
= 0;
959 while (firstMovedIndex
< itemCount
&& firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
963 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
964 if (itemsHaveMoved
) {
967 int lastMovedIndex
= itemCount
- 1;
968 while (lastMovedIndex
> firstMovedIndex
&& lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
972 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
974 // Create a list movedToIndexes, which has the property that
975 // movedToIndexes[i] is the new index of the item with the old index
976 // firstMovedIndex + i.
977 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
978 QList
<int> movedToIndexes
;
979 movedToIndexes
.reserve(movedItemsCount
);
980 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
981 const int newIndex
= m_items
.value(oldUrls
.at(i
));
982 movedToIndexes
.append(newIndex
);
985 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
986 } else if (groupedSorting()) {
987 // The groups might have changed even if the order of the items has not.
988 const QList
<QPair
<int, QVariant
>> oldGroups
= m_groups
;
990 if (groups() != oldGroups
) {
991 Q_EMIT
groupsChanged();
995 #ifdef KFILEITEMMODEL_DEBUG
996 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
1000 void KFileItemModel::slotCompleted()
1002 m_maximumUpdateIntervalTimer
->stop();
1003 dispatchPendingItemsToInsert();
1005 if (!m_urlsToExpand
.isEmpty()) {
1006 // Try to find a URL that can be expanded.
1007 // Note that the parent folder must be expanded before any of its subfolders become visible.
1008 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1009 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1010 // Iterate over a const copy because items are deleted and inserted within the loop
1011 const auto urlsToExpand
= m_urlsToExpand
;
1012 for (const QUrl
&url
: urlsToExpand
) {
1013 const int indexForUrl
= index(url
);
1014 if (indexForUrl
>= 0) {
1015 m_urlsToExpand
.remove(url
);
1016 if (setExpanded(indexForUrl
, true)) {
1017 // The dir lister has been triggered. This slot will be called
1018 // again after the directory has been expanded.
1024 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1025 // if these URLs have been deleted in the meantime.
1026 m_urlsToExpand
.clear();
1029 Q_EMIT
directoryLoadingCompleted();
1032 void KFileItemModel::slotCanceled()
1034 m_maximumUpdateIntervalTimer
->stop();
1035 dispatchPendingItemsToInsert();
1037 Q_EMIT
directoryLoadingCanceled();
1040 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
&items
)
1042 Q_ASSERT(!items
.isEmpty());
1044 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1046 if (m_requestRole
[ExpandedParentsCountRole
]) {
1047 // If the expanding of items is enabled, the call
1048 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1049 // might result in emitting the same items twice due to the Keep-parameter.
1050 // This case happens if an item gets expanded, collapsed and expanded again
1051 // before the items could be loaded for the first expansion.
1052 if (index(items
.first().url()) >= 0) {
1053 // The items are already part of the model.
1057 if (directoryUrl
!= directory()) {
1058 // To be able to compare whether the new items may be inserted as children
1059 // of a parent item the pending items must be added to the model first.
1060 dispatchPendingItemsToInsert();
1063 // KDirLister keeps the children of items that got expanded once even if
1064 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1065 // checked whether the parent for new items is still expanded.
1066 const int parentIndex
= index(parentUrl
);
1067 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1068 // The parent is not expanded.
1073 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1075 if (!m_filter
.hasSetFilters()) {
1076 m_pendingItemsToInsert
.append(itemDataList
);
1078 QSet
<ItemData
*> parentsToEnsureVisible
;
1080 // The name or type filter is active. Hide filtered items
1081 // before inserting them into the model and remember
1082 // the filtered items in m_filteredItems.
1083 for (ItemData
*itemData
: itemDataList
) {
1084 if (m_filter
.matches(itemData
->item
)) {
1085 m_pendingItemsToInsert
.append(itemData
);
1086 if (itemData
->parent
) {
1087 parentsToEnsureVisible
.insert(itemData
->parent
);
1090 m_filteredItems
.insert(itemData
->item
, itemData
);
1094 // Entire parental chains must be shown
1095 for (ItemData
*parent
: parentsToEnsureVisible
) {
1096 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1097 m_pendingItemsToInsert
.append(parent
);
1102 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1103 // Assure that items get dispatched if no completed() or canceled() signal is
1104 // emitted during the maximum update interval.
1105 m_maximumUpdateIntervalTimer
->start();
1108 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1111 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1113 int filteredParentsCount
= 0;
1114 // The childless parents not yet removed will always be right above the start of a removed range.
1115 // We iterate backwards to ensure the deepest folders are processed before their parents
1116 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1117 KItemRange itemRange
= removedItemRanges
.at(i
);
1118 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1119 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1120 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1122 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1123 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1124 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1125 // and this deleted range covers all of its descendents, so none will be left.
1126 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1127 // This range's starting index will be extended to include the parent above:
1130 ++filteredParentsCount
;
1131 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1132 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1133 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1134 previousRange
.count
+= itemRange
.count
;
1135 removedItemRanges
.replace(i
- 1, previousRange
);
1136 removedItemRanges
.removeAt(i
);
1138 removedItemRanges
.replace(i
, itemRange
);
1139 // We must revisit this range in the next iteration since its starting index changed
1144 return filteredParentsCount
;
1147 void KFileItemModel::slotItemsDeleted(const KFileItemList
&items
)
1149 dispatchPendingItemsToInsert();
1151 QVector
<int> indexesToRemove
;
1152 indexesToRemove
.reserve(items
.count());
1153 KFileItemList dirsChanged
;
1155 const auto currentDir
= directory();
1157 for (const KFileItem
&item
: items
) {
1158 if (item
.url() == currentDir
) {
1159 Q_EMIT
currentDirectoryRemoved();
1163 const int indexForItem
= index(item
);
1164 if (indexForItem
>= 0) {
1165 indexesToRemove
.append(indexForItem
);
1167 // Probably the item has been filtered.
1168 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1169 if (it
!= m_filteredItems
.end()) {
1171 m_filteredItems
.erase(it
);
1175 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1176 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1177 dirsChanged
<< KFileItem(parentUrl
);
1181 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1183 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1184 // Assure that removing a parent item also results in removing all children
1185 QVector
<int> indexesToRemoveWithChildren
;
1186 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1188 const int itemCount
= m_itemData
.count();
1189 for (int index
: qAsConst(indexesToRemove
)) {
1190 indexesToRemoveWithChildren
.append(index
);
1192 const int parentLevel
= expandedParentsCount(index
);
1193 int childIndex
= index
+ 1;
1194 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1195 indexesToRemoveWithChildren
.append(childIndex
);
1200 indexesToRemove
= indexesToRemoveWithChildren
;
1203 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1204 removeFilteredChildren(itemRanges
);
1206 // This call will update itemRanges to include the childless parents that have been filtered.
1207 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1209 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1210 // mixed with expanded folders that are just being filtered out.
1211 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1212 // so removeItems() will check m_filteredItems to differentiate which is which.
1213 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1215 Q_EMIT
fileItemsChanged(dirsChanged
);
1218 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
>> &items
)
1220 Q_ASSERT(!items
.isEmpty());
1221 #ifdef KFILEITEMMODEL_DEBUG
1222 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1225 // Get the indexes of all items that have been refreshed
1227 indexes
.reserve(items
.count());
1229 QSet
<QByteArray
> changedRoles
;
1230 KFileItemList changedFiles
;
1232 // Contains the indexes of the currently visible items
1233 // that should get hidden and hence moved to m_filteredItems.
1234 QVector
<int> newFilteredIndexes
;
1236 // Contains currently hidden items that should
1237 // get visible and hence removed from m_filteredItems
1238 QList
<ItemData
*> newVisibleItems
;
1240 QListIterator
<QPair
<KFileItem
, KFileItem
>> it(items
);
1242 while (it
.hasNext()) {
1243 const QPair
<KFileItem
, KFileItem
> &itemPair
= it
.next();
1244 const KFileItem
&oldItem
= itemPair
.first
;
1245 const KFileItem
&newItem
= itemPair
.second
;
1246 const int indexForItem
= index(oldItem
);
1247 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1248 if (indexForItem
>= 0) {
1249 m_itemData
[indexForItem
]->item
= newItem
;
1251 // Keep old values as long as possible if they could not retrieved synchronously yet.
1252 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1253 ItemData
*const itemData
= m_itemData
.at(indexForItem
);
1254 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1255 while (it
.hasNext()) {
1257 const QByteArray
&role
= it
.key();
1258 if (itemData
->values
.value(role
) != it
.value()) {
1259 itemData
->values
.insert(role
, it
.value());
1260 changedRoles
.insert(role
);
1264 m_items
.remove(oldItem
.url());
1265 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1266 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1267 m_items
.insert(newItem
.url(), indexForItem
);
1268 if (newItemMatchesFilter
1269 || (itemData
->values
.value("isExpanded").toBool()
1270 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1271 // We are lenient with expanded folders that originally had visible children.
1272 // If they become childless now they will be caught by filterChildlessParents()
1273 changedFiles
.append(newItem
);
1274 indexes
.append(indexForItem
);
1276 newFilteredIndexes
.append(indexForItem
);
1277 m_filteredItems
.insert(newItem
, itemData
);
1280 // Check if 'oldItem' is one of the filtered items.
1281 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1282 if (it
!= m_filteredItems
.end()) {
1283 ItemData
*const itemData
= it
.value();
1284 itemData
->item
= newItem
;
1286 // The data stored in 'values' might have changed. Therefore, we clear
1287 // 'values' and re-populate it the next time it is requested via data(int).
1288 // Before clearing, we must remember if it was expanded and the expanded parents count,
1289 // otherwise these states would be lost. The data() method will deal with this special case.
1290 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1291 bool hasExpandedParentsCount
= false;
1292 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1293 itemData
->values
.clear();
1295 itemData
->values
.insert("isExpanded", true);
1296 if (hasExpandedParentsCount
) {
1297 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1301 m_filteredItems
.erase(it
);
1302 if (newItemMatchesFilter
) {
1303 newVisibleItems
.append(itemData
);
1305 m_filteredItems
.insert(newItem
, itemData
);
1311 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1313 // We must keep track of parents of new visible items since they must be shown no matter what
1314 // They will be considered "immune" to filterChildlessParents()
1315 QSet
<ItemData
*> parentsToEnsureVisible
;
1317 for (ItemData
*item
: newVisibleItems
) {
1318 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1319 parentsToEnsureVisible
.insert(parent
);
1322 for (ItemData
*parent
: parentsToEnsureVisible
) {
1323 // We make sure they are all unfiltered.
1324 if (m_filteredItems
.remove(parent
->item
)) {
1325 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1326 newVisibleItems
.append(parent
);
1327 // It could be in newFilteredIndexes, we must remove it if it's there:
1328 const int parentIndex
= index(parent
->item
);
1329 if (parentIndex
>= 0) {
1330 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1331 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1332 newFilteredIndexes
.erase(it
);
1338 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1340 // This call will update itemRanges to include the childless parents that have been filtered.
1341 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1343 removeItems(removedRanges
, KeepItemData
);
1345 // Show previously hidden items that should get visible
1346 insertItems(newVisibleItems
);
1348 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1350 // If the changed items have been created recently, they might not be in m_items yet.
1351 // In that case, the list 'indexes' might be empty.
1352 if (indexes
.isEmpty()) {
1356 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1357 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1359 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1360 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1361 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1362 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1367 std::sort(indexes
.begin(), indexes
.end());
1370 // Extract the item-ranges out of the changed indexes
1371 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1372 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1374 Q_EMIT
fileItemsChanged(changedFiles
);
1377 void KFileItemModel::slotClear()
1379 #ifdef KFILEITEMMODEL_DEBUG
1380 qCDebug(DolphinDebug
) << "Clearing all items";
1383 qDeleteAll(m_filteredItems
);
1384 m_filteredItems
.clear();
1387 m_maximumUpdateIntervalTimer
->stop();
1388 m_resortAllItemsTimer
->stop();
1390 qDeleteAll(m_pendingItemsToInsert
);
1391 m_pendingItemsToInsert
.clear();
1393 const int removedCount
= m_itemData
.count();
1394 if (removedCount
> 0) {
1395 qDeleteAll(m_itemData
);
1398 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1401 m_expandedDirs
.clear();
1404 void KFileItemModel::slotSortingChoiceChanged()
1406 loadSortingSettings();
1410 void KFileItemModel::dispatchPendingItemsToInsert()
1412 if (!m_pendingItemsToInsert
.isEmpty()) {
1413 insertItems(m_pendingItemsToInsert
);
1414 m_pendingItemsToInsert
.clear();
1418 void KFileItemModel::insertItems(QList
<ItemData
*> &newItems
)
1420 if (newItems
.isEmpty()) {
1424 #ifdef KFILEITEMMODEL_DEBUG
1425 QElapsedTimer timer
;
1427 qCDebug(DolphinDebug
) << "===========================================================";
1428 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1432 prepareItemsForSorting(newItems
);
1434 // Natural sorting of items can be very slow. However, it becomes much faster
1435 // if the input sequence is already mostly sorted. Therefore, we first sort
1436 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1437 if (m_naturalSorting
) {
1438 if (m_sortRole
== NameRole
) {
1439 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1440 } else if (isRoleValueNatural(m_sortRole
)) {
1441 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1442 const QByteArray role
= roleForType(m_sortRole
);
1443 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1445 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1449 sort(newItems
.begin(), newItems
.end());
1451 #ifdef KFILEITEMMODEL_DEBUG
1452 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1455 KItemRangeList itemRanges
;
1456 const int existingItemCount
= m_itemData
.count();
1457 const int newItemCount
= newItems
.count();
1458 const int totalItemCount
= existingItemCount
+ newItemCount
;
1460 if (existingItemCount
== 0) {
1461 // Optimization for the common special case that there are no
1462 // items in the model yet. Happens, e.g., when entering a folder.
1463 m_itemData
= newItems
;
1464 itemRanges
<< KItemRange(0, newItemCount
);
1466 m_itemData
.reserve(totalItemCount
);
1467 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1468 m_itemData
.append(nullptr);
1471 // We build the new list m_itemData in reverse order to minimize
1472 // the number of moves and guarantee O(N) complexity.
1473 int targetIndex
= totalItemCount
- 1;
1474 int sourceIndexExistingItems
= existingItemCount
- 1;
1475 int sourceIndexNewItems
= newItemCount
- 1;
1479 while (sourceIndexNewItems
>= 0) {
1480 ItemData
*newItem
= newItems
.at(sourceIndexNewItems
);
1481 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1482 // Move an existing item to its new position. If any new items
1483 // are behind it, push the item range to itemRanges.
1484 if (rangeCount
> 0) {
1485 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1489 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1490 --sourceIndexExistingItems
;
1492 // Insert a new item into the list.
1494 m_itemData
[targetIndex
] = newItem
;
1495 --sourceIndexNewItems
;
1500 // Push the final item range to itemRanges.
1501 if (rangeCount
> 0) {
1502 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1505 // Note that itemRanges is still sorted in reverse order.
1506 std::reverse(itemRanges
.begin(), itemRanges
.end());
1509 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1510 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1513 Q_EMIT
itemsInserted(itemRanges
);
1515 #ifdef KFILEITEMMODEL_DEBUG
1516 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1520 void KFileItemModel::removeItems(const KItemRangeList
&itemRanges
, RemoveItemsBehavior behavior
)
1522 if (itemRanges
.isEmpty()) {
1528 // Step 1: Remove the items from m_itemData, and free the ItemData.
1529 int removedItemsCount
= 0;
1530 for (const KItemRange
&range
: itemRanges
) {
1531 removedItemsCount
+= range
.count
;
1533 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1534 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1535 delete m_itemData
.at(index
);
1538 m_itemData
[index
] = nullptr;
1542 // Step 2: Remove the ItemData pointers from the list m_itemData.
1543 int target
= itemRanges
.at(0).index
;
1544 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1547 const int oldItemDataCount
= m_itemData
.count();
1548 while (source
< oldItemDataCount
) {
1549 m_itemData
[target
] = m_itemData
[source
];
1553 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1554 // Skip the items in the next removed range.
1555 source
+= itemRanges
.at(nextRange
).count
;
1560 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1562 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1563 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1566 Q_EMIT
itemsRemoved(itemRanges
);
1569 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
&parentUrl
, const KFileItemList
&items
) const
1571 if (m_sortRole
== TypeRole
) {
1572 // Try to resolve the MIME-types synchronously to prevent a reordering of
1573 // the items when sorting by type (per default MIME-types are resolved
1574 // asynchronously by KFileItemModelRolesUpdater).
1575 determineMimeTypes(items
, 200);
1578 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1579 const int parentIndex
= index(parentUrl
);
1580 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1582 QList
<ItemData
*> itemDataList
;
1583 itemDataList
.reserve(items
.count());
1585 for (const KFileItem
&item
: items
) {
1586 ItemData
*itemData
= new ItemData();
1587 itemData
->item
= item
;
1588 itemData
->parent
= parentItem
;
1589 itemDataList
.append(itemData
);
1592 return itemDataList
;
1595 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*> &itemDataList
)
1597 switch (m_sortRole
) {
1599 case PermissionsRole
:
1602 case DestinationRole
:
1604 case DeletionTimeRole
:
1605 // These roles can be determined with retrieveData, and they have to be stored
1606 // in the QHash "values" for the sorting.
1607 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1608 if (itemData
->values
.isEmpty()) {
1609 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1615 // At least store the data including the file type for items with known MIME type.
1616 for (ItemData
*itemData
: qAsConst(itemDataList
)) {
1617 if (itemData
->values
.isEmpty()) {
1618 const KFileItem item
= itemData
->item
;
1619 if (item
.isDir() || item
.isMimeTypeKnown()) {
1620 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1627 // The other roles are either resolved by KFileItemModelRolesUpdater
1628 // (this includes the SizeRole for directories), or they do not need
1629 // to be stored in the QHash "values" for sorting because the data can
1630 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1636 int KFileItemModel::expandedParentsCount(const ItemData
*data
)
1638 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1639 // if the corresponding item is expanded, and it is not a top-level item.
1640 const ItemData
*parent
= data
->parent
;
1642 if (parent
->parent
) {
1643 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1644 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1653 void KFileItemModel::removeExpandedItems()
1655 QVector
<int> indexesToRemove
;
1657 const int maxIndex
= m_itemData
.count() - 1;
1658 for (int i
= 0; i
<= maxIndex
; ++i
) {
1659 const ItemData
*itemData
= m_itemData
.at(i
);
1660 if (itemData
->parent
) {
1661 indexesToRemove
.append(i
);
1665 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1666 m_expandedDirs
.clear();
1668 // Also remove all filtered items which have a parent.
1669 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1670 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1673 if (it
.value()->parent
) {
1675 it
= m_filteredItems
.erase(it
);
1682 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
&itemRanges
, const QSet
<QByteArray
> &changedRoles
)
1684 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1686 // Trigger a resorting if necessary. Note that this can happen even if the sort
1687 // role has not changed at all because the file name can be used as a fallback.
1688 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1689 for (const KItemRange
&range
: itemRanges
) {
1690 bool needsResorting
= false;
1692 const int first
= range
.index
;
1693 const int last
= range
.index
+ range
.count
- 1;
1695 // Resorting the model is necessary if
1696 // (a) The first item in the range is "lessThan" its predecessor,
1697 // (b) the successor of the last item is "lessThan" the last item, or
1698 // (c) the internal order of the items in the range is incorrect.
1699 if (first
> 0 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1700 needsResorting
= true;
1701 } else if (last
< count() - 1 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1702 needsResorting
= true;
1704 for (int index
= first
; index
< last
; ++index
) {
1705 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1706 needsResorting
= true;
1712 if (needsResorting
) {
1713 m_resortAllItemsTimer
->start();
1719 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1720 // The position is still correct, but the groups might have changed
1721 // if the changed item is either the first or the last item in a
1723 // In principle, we could try to find out if the item really is the
1724 // first or last one in its group and then update the groups
1725 // (possibly with a delayed timer to make sure that we don't
1726 // re-calculate the groups very often if items are updated one by
1727 // one), but starting m_resortAllItemsTimer is easier.
1728 m_resortAllItemsTimer
->start();
1732 void KFileItemModel::resetRoles()
1734 for (int i
= 0; i
< RolesCount
; ++i
) {
1735 m_requestRole
[i
] = false;
1739 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
&role
) const
1741 static QHash
<QByteArray
, RoleType
> roles
;
1742 if (roles
.isEmpty()) {
1743 // Insert user visible roles that can be accessed with
1744 // KFileItemModel::roleInformation()
1746 const RoleInfoMap
*map
= rolesInfoMap(count
);
1747 for (int i
= 0; i
< count
; ++i
) {
1748 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1751 // Insert internal roles (take care to synchronize the implementation
1752 // with KFileItemModel::roleForType() in case if a change is done).
1753 roles
.insert("isDir", IsDirRole
);
1754 roles
.insert("isLink", IsLinkRole
);
1755 roles
.insert("isHidden", IsHiddenRole
);
1756 roles
.insert("isExpanded", IsExpandedRole
);
1757 roles
.insert("isExpandable", IsExpandableRole
);
1758 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1760 Q_ASSERT(roles
.count() == RolesCount
);
1763 return roles
.value(role
, NoRole
);
1766 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1768 static QHash
<RoleType
, QByteArray
> roles
;
1769 if (roles
.isEmpty()) {
1770 // Insert user visible roles that can be accessed with
1771 // KFileItemModel::roleInformation()
1773 const RoleInfoMap
*map
= rolesInfoMap(count
);
1774 for (int i
= 0; i
< count
; ++i
) {
1775 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1778 // Insert internal roles (take care to synchronize the implementation
1779 // with KFileItemModel::typeForRole() in case if a change is done).
1780 roles
.insert(IsDirRole
, "isDir");
1781 roles
.insert(IsLinkRole
, "isLink");
1782 roles
.insert(IsHiddenRole
, "isHidden");
1783 roles
.insert(IsExpandedRole
, "isExpanded");
1784 roles
.insert(IsExpandableRole
, "isExpandable");
1785 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1787 Q_ASSERT(roles
.count() == RolesCount
);
1790 return roles
.value(roleType
);
1793 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
&item
, const ItemData
*parent
) const
1795 // It is important to insert only roles that are fast to retrieve. E.g.
1796 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1797 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1798 QHash
<QByteArray
, QVariant
> data
;
1799 data
.insert(sharedValue("url"), item
.url());
1801 const bool isDir
= item
.isDir();
1802 if (m_requestRole
[IsDirRole
] && isDir
) {
1803 data
.insert(sharedValue("isDir"), true);
1806 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1807 data
.insert(sharedValue("isLink"), true);
1810 if (m_requestRole
[IsHiddenRole
]) {
1811 data
.insert(sharedValue("isHidden"), item
.isHidden());
1814 if (m_requestRole
[NameRole
]) {
1815 data
.insert(sharedValue("text"), item
.text());
1818 if (m_requestRole
[ExtensionRole
] && !isDir
) {
1819 data
.insert(sharedValue("extension"), QFileInfo(item
.name()).suffix());
1822 if (m_requestRole
[SizeRole
] && !isDir
) {
1823 data
.insert(sharedValue("size"), item
.size());
1826 if (m_requestRole
[ModificationTimeRole
]) {
1827 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1828 // having several thousands of items. Instead read the raw number from UDSEntry directly
1829 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1830 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1831 data
.insert(sharedValue("modificationtime"), dateTime
);
1834 if (m_requestRole
[CreationTimeRole
]) {
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_CREATION_TIME
, -1);
1839 data
.insert(sharedValue("creationtime"), dateTime
);
1842 if (m_requestRole
[AccessTimeRole
]) {
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_ACCESS_TIME
, -1);
1847 data
.insert(sharedValue("accesstime"), dateTime
);
1850 if (m_requestRole
[PermissionsRole
]) {
1851 data
.insert(sharedValue("permissions"), QVariantList() << item
.permissionsString() << item
.permissions());
1854 if (m_requestRole
[OwnerRole
]) {
1855 data
.insert(sharedValue("owner"), item
.user());
1858 if (m_requestRole
[GroupRole
]) {
1859 data
.insert(sharedValue("group"), item
.group());
1862 if (m_requestRole
[DestinationRole
]) {
1863 QString destination
= item
.linkDest();
1864 if (destination
.isEmpty()) {
1865 destination
= QLatin1Char('-');
1867 data
.insert(sharedValue("destination"), destination
);
1870 if (m_requestRole
[PathRole
]) {
1872 if (item
.url().scheme() == QLatin1String("trash")) {
1873 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1875 // For performance reasons cache the home-path in a static QString
1876 // (see QDir::homePath() for more details)
1877 static QString homePath
;
1878 if (homePath
.isEmpty()) {
1879 homePath
= QDir::homePath();
1882 path
= item
.localPath();
1883 if (path
.startsWith(homePath
)) {
1884 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1888 const int index
= path
.lastIndexOf(item
.text());
1889 path
= path
.mid(0, index
- 1);
1890 data
.insert(sharedValue("path"), path
);
1893 if (m_requestRole
[DeletionTimeRole
]) {
1894 QDateTime deletionTime
;
1895 if (item
.url().scheme() == QLatin1String("trash")) {
1896 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1898 data
.insert(sharedValue("deletiontime"), deletionTime
);
1901 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1902 data
.insert(sharedValue("isExpandable"), true);
1905 if (m_requestRole
[ExpandedParentsCountRole
]) {
1907 const int level
= expandedParentsCount(parent
) + 1;
1908 data
.insert(sharedValue("expandedParentsCount"), level
);
1912 if (item
.isMimeTypeKnown()) {
1913 QString iconName
= item
.iconName();
1914 if (!QIcon::hasThemeIcon(iconName
)) {
1915 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1916 iconName
= mimeType
.genericIconName();
1919 data
.insert(sharedValue("iconName"), iconName
);
1921 if (m_requestRole
[TypeRole
]) {
1922 data
.insert(sharedValue("type"), item
.mimeComment());
1924 } else if (m_requestRole
[TypeRole
] && isDir
) {
1925 static const QString folderMimeType
= item
.mimeComment();
1926 data
.insert(sharedValue("type"), folderMimeType
);
1932 bool KFileItemModel::lessThan(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
1936 if (a
->parent
!= b
->parent
) {
1937 const int expansionLevelA
= expandedParentsCount(a
);
1938 const int expansionLevelB
= expandedParentsCount(b
);
1940 // If b has a higher expansion level than a, check if a is a parent
1941 // of b, and make sure that both expansion levels are equal otherwise.
1942 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1943 if (b
->parent
== a
) {
1949 // If a has a higher expansion level than a, check if b is a parent
1950 // of a, and make sure that both expansion levels are equal otherwise.
1951 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1952 if (a
->parent
== b
) {
1958 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1960 // Compare the last parents of a and b which are different.
1961 while (a
->parent
!= b
->parent
) {
1967 // Show hidden files and folders last
1968 if (m_sortHiddenLast
) {
1969 const bool isHiddenA
= a
->item
.isHidden();
1970 const bool isHiddenB
= b
->item
.isHidden();
1971 if (isHiddenA
&& !isHiddenB
) {
1973 } else if (!isHiddenA
&& isHiddenB
) {
1978 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1979 const bool isDirA
= a
->item
.isDir();
1980 const bool isDirB
= b
->item
.isDir();
1981 if (isDirA
&& !isDirB
) {
1983 } else if (!isDirA
&& isDirB
) {
1988 result
= sortRoleCompare(a
, b
, collator
);
1990 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1993 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
, const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1995 auto lambdaLessThan
= [&](const KFileItemModel::ItemData
*a
, const KFileItemModel::ItemData
*b
) {
1996 return lessThan(a
, b
, m_collator
);
1999 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
2000 // Sorting by string can be expensive, in particular if natural sorting is
2001 // enabled. Use all CPU cores to speed up the sorting process.
2002 static const int numberOfThreads
= QThread::idealThreadCount();
2003 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
2005 // Sorting by other roles is quite fast. Use only one thread to prevent
2006 // problems caused by non-reentrant comparison functions, see
2007 // https://bugs.kde.org/show_bug.cgi?id=312679
2008 mergeSort(begin
, end
, lambdaLessThan
);
2012 int KFileItemModel::sortRoleCompare(const ItemData
*a
, const ItemData
*b
, const QCollator
&collator
) const
2014 // This function must never return 0, because that would break stable
2015 // sorting, which leads to all kinds of bugs.
2016 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2017 // If two items have equal sort values, let the fallbacks at the bottom of
2018 // the function handle it.
2019 const KFileItem
&itemA
= a
->item
;
2020 const KFileItem
&itemB
= b
->item
;
2024 switch (m_sortRole
) {
2026 // The name role is handled as default fallback after the switch
2030 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
2031 // folders first then
2032 // items A and B are folders thanks to lessThan checks
2033 auto valueA
= a
->values
.value("count");
2034 auto valueB
= b
->values
.value("count");
2035 if (valueA
.isNull()) {
2036 if (!valueB
.isNull()) {
2039 } else if (valueB
.isNull()) {
2042 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2044 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2051 KIO::filesize_t sizeA
= 0;
2052 if (itemA
.isDir()) {
2053 sizeA
= a
->values
.value("size").toULongLong();
2055 sizeA
= itemA
.size();
2057 KIO::filesize_t sizeB
= 0;
2058 if (itemB
.isDir()) {
2059 sizeB
= b
->values
.value("size").toULongLong();
2061 sizeB
= itemB
.size();
2063 if (sizeA
< sizeB
) {
2065 } else if (sizeA
> sizeB
) {
2071 case ModificationTimeRole
: {
2072 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2073 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2074 if (dateTimeA
< dateTimeB
) {
2076 } else if (dateTimeA
> dateTimeB
) {
2082 case AccessTimeRole
: {
2083 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2084 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
2085 if (dateTimeA
< dateTimeB
) {
2087 } else if (dateTimeA
> dateTimeB
) {
2093 case CreationTimeRole
: {
2094 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2095 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2096 if (dateTimeA
< dateTimeB
) {
2098 } else if (dateTimeA
> dateTimeB
) {
2104 case DeletionTimeRole
: {
2105 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2106 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2107 if (dateTimeA
< dateTimeB
) {
2109 } else if (dateTimeA
> dateTimeB
) {
2123 case ReleaseYearRole
: {
2124 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2128 case DimensionsRole
: {
2129 const QByteArray role
= roleForType(m_sortRole
);
2130 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2131 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2133 if (dimensionsA
.width() == dimensionsB
.width()) {
2134 result
= dimensionsA
.height() - dimensionsB
.height();
2136 result
= dimensionsA
.width() - dimensionsB
.width();
2142 const QByteArray role
= roleForType(m_sortRole
);
2143 const QString roleValueA
= a
->values
.value(role
).toString();
2144 const QString roleValueB
= b
->values
.value(role
).toString();
2145 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2147 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2149 } else if (isRoleValueNatural(m_sortRole
)) {
2150 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2152 result
= QString::compare(roleValueA
, roleValueB
);
2159 // The current sort role was sufficient to define an order
2163 // Fallback #1: Compare the text of the items
2164 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2169 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2170 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2175 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2176 // equal. In this case a comparison of the URL is done which is unique in all cases
2177 // within KDirLister.
2178 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2181 int KFileItemModel::stringCompare(const QString
&a
, const QString
&b
, const QCollator
&collator
) const
2183 QMutexLocker
collatorLock(s_collatorMutex());
2185 if (m_naturalSorting
) {
2186 return collator
.compare(a
, b
);
2189 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2190 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2191 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2192 // comparison, still a deterministic sort order is required. A case sensitive
2193 // comparison is done as fallback.
2197 return QString::compare(a
, b
, Qt::CaseSensitive
);
2200 QList
<QPair
<int, QVariant
>> KFileItemModel::nameRoleGroups() const
2202 Q_ASSERT(!m_itemData
.isEmpty());
2204 const int maxIndex
= count() - 1;
2205 QList
<QPair
<int, QVariant
>> groups
;
2209 for (int i
= 0; i
<= maxIndex
; ++i
) {
2210 if (isChildItem(i
)) {
2214 const QString name
= m_itemData
.at(i
)->item
.text();
2216 // Use the first character of the name as group indication
2217 QChar newFirstChar
= name
.at(0).toUpper();
2218 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2219 newFirstChar
= name
.at(1).toUpper();
2222 if (firstChar
!= newFirstChar
) {
2223 QString newGroupValue
;
2224 if (newFirstChar
.isLetter()) {
2225 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2226 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2228 // Try to find a matching group in the range 'A' to 'Z'.
2229 static std::vector
<QChar
> lettersAtoZ
;
2230 lettersAtoZ
.reserve('Z' - 'A' + 1);
2231 if (lettersAtoZ
.empty()) {
2232 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2233 lettersAtoZ
.push_back(QLatin1Char(c
));
2237 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2238 return m_collator
.compare(c1
, c2
) < 0;
2241 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2242 if (it
!= lettersAtoZ
.end()) {
2243 if (localeAwareLessThan(newFirstChar
, *it
)) {
2244 // newFirstChar belongs to the group preceding *it.
2245 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2248 newGroupValue
= *it
;
2252 // Symbols from non Latin-based scripts
2253 newGroupValue
= newFirstChar
;
2255 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2256 // Apply group '0 - 9' for any name that starts with a digit
2257 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2259 newGroupValue
= i18nc("@title:group", "Others");
2262 if (newGroupValue
!= groupValue
) {
2263 groupValue
= newGroupValue
;
2264 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2267 firstChar
= newFirstChar
;
2273 QList
<QPair
<int, QVariant
>> KFileItemModel::sizeRoleGroups() const
2275 Q_ASSERT(!m_itemData
.isEmpty());
2277 const int maxIndex
= count() - 1;
2278 QList
<QPair
<int, QVariant
>> groups
;
2281 for (int i
= 0; i
<= maxIndex
; ++i
) {
2282 if (isChildItem(i
)) {
2286 const KFileItem
&item
= m_itemData
.at(i
)->item
;
2287 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2288 QString newGroupValue
;
2289 if (!item
.isNull() && item
.isDir()) {
2290 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2291 newGroupValue
= i18nc("@title:group Size", "Folders");
2293 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2297 if (newGroupValue
.isEmpty()) {
2298 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2299 newGroupValue
= i18nc("@title:group Size", "Small");
2300 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2301 newGroupValue
= i18nc("@title:group Size", "Medium");
2303 newGroupValue
= i18nc("@title:group Size", "Big");
2307 if (newGroupValue
!= groupValue
) {
2308 groupValue
= newGroupValue
;
2309 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2316 QList
<QPair
<int, QVariant
>> KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2318 Q_ASSERT(!m_itemData
.isEmpty());
2320 const int maxIndex
= count() - 1;
2321 QList
<QPair
<int, QVariant
>> groups
;
2323 const QDate currentDate
= QDate::currentDate();
2325 QDate previousFileDate
;
2327 for (int i
= 0; i
<= maxIndex
; ++i
) {
2328 if (isChildItem(i
)) {
2332 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2333 const QDate fileDate
= fileTime
.date();
2334 if (fileDate
== previousFileDate
) {
2335 // The current item is in the same group as the previous item
2338 previousFileDate
= fileDate
;
2340 const int daysDistance
= fileDate
.daysTo(currentDate
);
2342 QString newGroupValue
;
2343 if (currentDate
.year() == fileDate
.year() && currentDate
.month() == fileDate
.month()) {
2344 switch (daysDistance
/ 7) {
2346 switch (daysDistance
) {
2348 newGroupValue
= i18nc("@title:group Date", "Today");
2351 newGroupValue
= i18nc("@title:group Date", "Yesterday");
2354 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2355 newGroupValue
= i18nc(
2356 "Can be used to script translation of \"dddd\""
2357 "with context @title:group Date",
2363 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2366 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2369 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2373 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2379 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2380 if (lastMonthDate
.year() == fileDate
.year() && lastMonthDate
.month() == fileDate
.month()) {
2381 if (daysDistance
== 1) {
2382 const KLocalizedString format
= ki18nc(
2383 "@title:group Date: "
2384 "MMMM is full month name in current locale, and yyyy is "
2385 "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 "
2386 "part of the text that should not be formatted as a date",
2387 "'Yesterday' (MMMM, yyyy)");
2388 const QString translatedFormat
= format
.toString();
2389 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2390 newGroupValue
= fileTime
.toString(translatedFormat
);
2391 newGroupValue
= i18nc(
2392 "Can be used to script translation of "
2393 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2397 qCWarning(DolphinDebug
).nospace()
2398 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2399 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2400 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2402 } else if (daysDistance
<= 7) {
2404 fileTime
.toString(i18nc("@title:group Date: "
2405 "The week day name: dddd, MMMM is full month name "
2406 "in current locale, and yyyy is full year number.",
2407 "dddd (MMMM, yyyy)"));
2408 newGroupValue
= i18nc(
2409 "Can be used to script translation of "
2410 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2413 } else if (daysDistance
<= 7 * 2) {
2414 const KLocalizedString format
= ki18nc(
2415 "@title:group Date: "
2416 "MMMM is full month name in current locale, and yyyy is "
2417 "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 "
2418 "part of the text that should not be formatted as a date",
2419 "'One Week Ago' (MMMM, yyyy)");
2420 const QString translatedFormat
= format
.toString();
2421 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2422 newGroupValue
= fileTime
.toString(translatedFormat
);
2423 newGroupValue
= i18nc(
2424 "Can be used to script translation of "
2425 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2429 qCWarning(DolphinDebug
).nospace()
2430 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2431 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2432 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2434 } else if (daysDistance
<= 7 * 3) {
2435 const KLocalizedString format
= ki18nc(
2436 "@title:group Date: "
2437 "MMMM is full month name in current locale, and yyyy is "
2438 "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 "
2439 "part of the text that should not be formatted as a date",
2440 "'Two Weeks Ago' (MMMM, yyyy)");
2441 const QString translatedFormat
= format
.toString();
2442 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2443 newGroupValue
= fileTime
.toString(translatedFormat
);
2444 newGroupValue
= i18nc(
2445 "Can be used to script translation of "
2446 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2450 qCWarning(DolphinDebug
).nospace()
2451 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2452 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2453 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2455 } else if (daysDistance
<= 7 * 4) {
2456 const KLocalizedString format
= ki18nc(
2457 "@title:group Date: "
2458 "MMMM is full month name in current locale, and yyyy is "
2459 "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 "
2460 "part of the text that should not be formatted as a date",
2461 "'Three Weeks Ago' (MMMM, yyyy)");
2462 const QString translatedFormat
= format
.toString();
2463 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2464 newGroupValue
= fileTime
.toString(translatedFormat
);
2465 newGroupValue
= i18nc(
2466 "Can be used to script translation of "
2467 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2471 qCWarning(DolphinDebug
).nospace()
2472 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2473 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2474 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2477 const KLocalizedString format
= ki18nc(
2478 "@title:group Date: "
2479 "MMMM is full month name in current locale, and yyyy is "
2480 "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 "
2481 "part of the text that should not be formatted as a date",
2482 "'Earlier on' MMMM, yyyy");
2483 const QString translatedFormat
= format
.toString();
2484 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2485 newGroupValue
= fileTime
.toString(translatedFormat
);
2486 newGroupValue
= i18nc(
2487 "Can be used to script translation of "
2488 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2492 qCWarning(DolphinDebug
).nospace()
2493 << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2494 const QString untranslatedFormat
= format
.toString({QLatin1String("en_US")});
2495 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2500 fileTime
.toString(i18nc("@title:group "
2501 "The month and year: MMMM is full month name in current locale, "
2502 "and yyyy is full year number",
2504 newGroupValue
= i18nc(
2505 "Can be used to script translation of "
2506 "\"MMMM, yyyy\" with context @title:group Date",
2512 if (newGroupValue
!= groupValue
) {
2513 groupValue
= newGroupValue
;
2514 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2521 QList
<QPair
<int, QVariant
>> KFileItemModel::permissionRoleGroups() const
2523 Q_ASSERT(!m_itemData
.isEmpty());
2525 const int maxIndex
= count() - 1;
2526 QList
<QPair
<int, QVariant
>> groups
;
2528 QString permissionsString
;
2530 for (int i
= 0; i
<= maxIndex
; ++i
) {
2531 if (isChildItem(i
)) {
2535 const ItemData
*itemData
= m_itemData
.at(i
);
2536 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2537 if (newPermissionsString
== permissionsString
) {
2540 permissionsString
= newPermissionsString
;
2542 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2546 if (info
.permission(QFile::ReadUser
)) {
2547 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2549 if (info
.permission(QFile::WriteUser
)) {
2550 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2552 if (info
.permission(QFile::ExeUser
)) {
2553 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2555 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.length() - 2);
2559 if (info
.permission(QFile::ReadGroup
)) {
2560 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2562 if (info
.permission(QFile::WriteGroup
)) {
2563 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2565 if (info
.permission(QFile::ExeGroup
)) {
2566 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2568 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.length() - 2);
2570 // Set others string
2572 if (info
.permission(QFile::ReadOther
)) {
2573 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2575 if (info
.permission(QFile::WriteOther
)) {
2576 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2578 if (info
.permission(QFile::ExeOther
)) {
2579 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2581 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.length() - 2);
2583 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2584 if (newGroupValue
!= groupValue
) {
2585 groupValue
= newGroupValue
;
2586 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2593 QList
<QPair
<int, QVariant
>> KFileItemModel::ratingRoleGroups() const
2595 Q_ASSERT(!m_itemData
.isEmpty());
2597 const int maxIndex
= count() - 1;
2598 QList
<QPair
<int, QVariant
>> groups
;
2600 int groupValue
= -1;
2601 for (int i
= 0; i
<= maxIndex
; ++i
) {
2602 if (isChildItem(i
)) {
2605 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2606 if (newGroupValue
!= groupValue
) {
2607 groupValue
= newGroupValue
;
2608 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2615 QList
<QPair
<int, QVariant
>> KFileItemModel::genericStringRoleGroups(const QByteArray
&role
) const
2617 Q_ASSERT(!m_itemData
.isEmpty());
2619 const int maxIndex
= count() - 1;
2620 QList
<QPair
<int, QVariant
>> groups
;
2622 bool isFirstGroupValue
= true;
2624 for (int i
= 0; i
<= maxIndex
; ++i
) {
2625 if (isChildItem(i
)) {
2628 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2629 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2630 groupValue
= newGroupValue
;
2631 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2632 isFirstGroupValue
= false;
2639 void KFileItemModel::emitSortProgress(int resolvedCount
)
2641 // Be tolerant against a resolvedCount with a wrong range.
2642 // Although there should not be a case where KFileItemModelRolesUpdater
2643 // (= caller) provides a wrong range, it is important to emit
2644 // a useful progress information even if there is an unexpected
2645 // implementation issue.
2647 const int itemCount
= count();
2648 if (resolvedCount
>= itemCount
) {
2649 m_sortingProgressPercent
= -1;
2650 if (m_resortAllItemsTimer
->isActive()) {
2651 m_resortAllItemsTimer
->stop();
2655 Q_EMIT
directorySortingProgress(100);
2656 } else if (itemCount
> 0) {
2657 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2659 const int progress
= resolvedCount
* 100 / itemCount
;
2660 if (m_sortingProgressPercent
!= progress
) {
2661 m_sortingProgressPercent
= progress
;
2662 Q_EMIT
directorySortingProgress(progress
);
2667 const KFileItemModel::RoleInfoMap
*KFileItemModel::rolesInfoMap(int &count
)
2669 static const RoleInfoMap rolesInfoMap
[] = {
2671 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2672 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2673 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2674 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2675 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2676 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2677 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2678 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2679 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2680 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2681 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2682 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2683 { "author", AuthorRole
, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2684 { "publisher", PublisherRole
, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2685 { "pageCount", PageCountRole
, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2686 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2687 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2688 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2689 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2690 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2691 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2692 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2693 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2694 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2695 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2696 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2697 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2698 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2699 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2700 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2701 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2702 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2703 { "extension", ExtensionRole
, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2704 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2705 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2706 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2707 { "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 },
2708 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2709 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2713 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2714 return rolesInfoMap
;
2717 void KFileItemModel::determineMimeTypes(const KFileItemList
&items
, int timeout
)
2719 QElapsedTimer timer
;
2721 for (const KFileItem
&item
: items
) {
2722 // Only determine mime types for files here. For directories,
2723 // KFileItem::determineMimeType() reads the .directory file inside to
2724 // load the icon, but this is not necessary at all if we just need the
2725 // type. Some special code for setting the correct mime type for
2726 // directories is in retrieveData().
2727 if (!item
.isDir()) {
2728 item
.determineMimeType();
2731 if (timer
.elapsed() > timeout
) {
2732 // Don't block the user interface, let the remaining items
2733 // be resolved asynchronously.
2739 QByteArray
KFileItemModel::sharedValue(const QByteArray
&value
)
2741 static QSet
<QByteArray
> pool
;
2742 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2744 if (it
!= pool
.constEnd()) {
2752 bool KFileItemModel::isConsistent() const
2754 // m_items may contain less items than m_itemData because m_items
2755 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2756 if (m_items
.count() > m_itemData
.count()) {
2760 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2761 // Check if m_items and m_itemData are consistent.
2762 const KFileItem item
= fileItem(i
);
2763 if (item
.isNull()) {
2764 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2768 const int itemIndex
= index(item
);
2769 if (itemIndex
!= i
) {
2770 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2774 // Check if the items are sorted correctly.
2775 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2776 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:" << fileItem(i
- 1) << fileItem(i
);
2780 // Check if all parent-child relationships are consistent.
2781 const ItemData
*data
= m_itemData
.at(i
);
2782 const ItemData
*parent
= data
->parent
;
2784 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2785 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2789 const int parentIndex
= index(parent
->item
);
2790 if (parentIndex
>= i
) {
2791 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child"
2801 void KFileItemModel::slotListerError(KIO::Job
*job
)
2803 if (job
->error() == KIO::ERR_IS_FILE
) {
2804 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2805 Q_EMIT
urlIsFileError(listJob
->url());
2808 const QString errorString
= job
->errorString();
2809 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));