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_generalsettings.h"
12 #include "dolphin_detailsmodesettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
18 #include <KLocalizedString>
19 #include <KUrlMimeData>
21 #include <QElapsedTimer>
23 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
29 #include <klazylocalizedstring.h>
31 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
33 // #define KFILEITEMMODEL_DEBUG
35 KFileItemModel::KFileItemModel(QObject
* parent
) :
36 KItemModelBase("text", parent
),
38 m_sortDirsFirst(true),
39 m_sortHiddenLast(false),
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
->setShowingDotFiles(show
);
241 m_dirLister
->emitChanges();
243 dispatchPendingItemsToInsert();
247 bool KFileItemModel::showHiddenFiles() const
249 return m_dirLister
->showingDotFiles();
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
318 const KFileItem item
= fileItem(index
);
319 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
322 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
324 static QHash
<QByteArray
, QString
> description
;
325 if (description
.isEmpty()) {
327 const RoleInfoMap
* map
= rolesInfoMap(count
);
328 for (int i
= 0; i
< count
; ++i
) {
329 if (map
[i
].roleTranslation
.isEmpty()) {
332 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
336 return description
.value(role
);
339 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
341 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
342 #ifdef KFILEITEMMODEL_DEBUG
346 switch (typeForRole(sortRole())) {
347 case NameRole
: m_groups
= nameRoleGroups(); break;
348 case SizeRole
: m_groups
= sizeRoleGroups(); break;
349 case ModificationTimeRole
:
350 m_groups
= timeRoleGroups([](const ItemData
*item
) {
351 return item
->item
.time(KFileItem::ModificationTime
);
354 case CreationTimeRole
:
355 m_groups
= timeRoleGroups([](const ItemData
*item
) {
356 return item
->item
.time(KFileItem::CreationTime
);
360 m_groups
= timeRoleGroups([](const ItemData
*item
) {
361 return item
->item
.time(KFileItem::AccessTime
);
364 case DeletionTimeRole
:
365 m_groups
= timeRoleGroups([](const ItemData
*item
) {
366 return item
->values
.value("deletiontime").toDateTime();
369 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
370 case RatingRole
: m_groups
= ratingRoleGroups(); break;
371 default: m_groups
= genericStringRoleGroups(sortRole()); break;
374 #ifdef KFILEITEMMODEL_DEBUG
375 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
382 KFileItem
KFileItemModel::fileItem(int index
) const
384 if (index
>= 0 && index
< count()) {
385 return m_itemData
.at(index
)->item
;
391 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
393 const int indexForUrl
= index(url
);
394 if (indexForUrl
>= 0) {
395 return m_itemData
.at(indexForUrl
)->item
;
400 int KFileItemModel::index(const KFileItem
& item
) const
402 return index(item
.url());
405 int KFileItemModel::index(const QUrl
& url
) const
407 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
409 const int itemCount
= m_itemData
.count();
410 int itemsInHash
= m_items
.count();
412 int index
= m_items
.value(urlToFind
, -1);
413 while (index
< 0 && itemsInHash
< itemCount
) {
414 // Not all URLs are stored yet in m_items. We grow m_items until either
415 // urlToFind is found, or all URLs have been stored in m_items.
416 // Note that we do not add the URLs to m_items one by one, but in
417 // larger blocks. After each block, we check if urlToFind is in
418 // m_items. We could in principle compare urlToFind with each URL while
419 // we are going through m_itemData, but comparing two QUrls will,
420 // unlike calling qHash for the URLs, trigger a parsing of the URLs
421 // which costs both CPU cycles and memory.
422 const int blockSize
= 1000;
423 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
424 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
425 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
426 m_items
.insert(nextUrl
, i
);
429 itemsInHash
= currentBlockEnd
;
430 index
= m_items
.value(urlToFind
, -1);
434 // The item could not be found, even though all items from m_itemData
435 // should be in m_items now. We print some diagnostic information which
436 // might help to find the cause of the problem, but only once. This
437 // prevents that obtaining and printing the debugging information
438 // wastes CPU cycles and floods the shell or .xsession-errors.
439 static bool printDebugInfo
= true;
441 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
442 printDebugInfo
= false;
444 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
445 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
446 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
448 // Check if there are multiple items with the same URL.
449 QMultiHash
<QUrl
, int> indexesForUrl
;
450 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
451 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
454 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
455 for (const QUrl
& url
: uniqueKeys
) {
456 if (indexesForUrl
.count(url
) > 1) {
457 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
459 auto it
= indexesForUrl
.find(url
);
460 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
461 const ItemData
* data
= m_itemData
.at(it
.value());
462 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
464 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
476 KFileItem
KFileItemModel::rootItem() const
478 return m_dirLister
->rootItem();
481 void KFileItemModel::clear()
486 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
488 if (m_roles
== roles
) {
492 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
496 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
497 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
498 if (supportedExpanding
&& !willSupportExpanding
) {
499 // No expanding is supported anymore. Take care to delete all items that have an expansion level
500 // that is not 0 (and hence are part of an expanded item).
501 removeExpandedItems();
508 QSetIterator
<QByteArray
> it(roles
);
509 while (it
.hasNext()) {
510 const QByteArray
& role
= it
.next();
511 m_requestRole
[typeForRole(role
)] = true;
515 // Update m_data with the changed requested roles
516 const int maxIndex
= count() - 1;
517 for (int i
= 0; i
<= maxIndex
; ++i
) {
518 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
521 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
524 // Clear the 'values' of all filtered items. They will be re-populated with the
525 // correct roles the next time 'values' will be accessed via data(int).
526 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
527 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
528 while (filteredIt
!= filteredEnd
) {
529 (*filteredIt
)->values
.clear();
534 QSet
<QByteArray
> KFileItemModel::roles() const
539 bool KFileItemModel::setExpanded(int index
, bool expanded
)
541 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
545 QHash
<QByteArray
, QVariant
> values
;
546 values
.insert(sharedValue("isExpanded"), expanded
);
547 if (!setData(index
, values
)) {
551 const KFileItem item
= m_itemData
.at(index
)->item
;
552 const QUrl url
= item
.url();
553 const QUrl targetUrl
= item
.targetUrl();
555 m_expandedDirs
.insert(targetUrl
, url
);
556 m_dirLister
->openUrl(url
, KDirLister::Keep
);
558 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
559 for (const QVariant
& var
: previouslyExpandedChildren
) {
560 m_urlsToExpand
.insert(var
.toUrl());
563 // Note that there might be (indirect) children of the folder which is to be collapsed in
564 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
565 // possibly without a parent, which might result in a crash, we insert all pending items
566 // right now. All new items which would be without a parent will then be removed.
567 dispatchPendingItemsToInsert();
569 // Check if the index of the collapsed folder has changed. If that is the case, then items
570 // were inserted before the collapsed folder, and its index needs to be updated.
571 if (m_itemData
.at(index
)->item
!= item
) {
572 index
= this->index(item
);
575 m_expandedDirs
.remove(targetUrl
);
576 m_dirLister
->stop(url
);
578 const int parentLevel
= expandedParentsCount(index
);
579 const int itemCount
= m_itemData
.count();
580 const int firstChildIndex
= index
+ 1;
582 QVariantList expandedChildren
;
584 int childIndex
= firstChildIndex
;
585 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
586 ItemData
* itemData
= m_itemData
.at(childIndex
);
587 if (itemData
->values
.value("isExpanded").toBool()) {
588 const QUrl targetUrl
= itemData
->item
.targetUrl();
589 const QUrl url
= itemData
->item
.url();
590 m_expandedDirs
.remove(targetUrl
);
591 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
592 expandedChildren
.append(targetUrl
);
596 const int childrenCount
= childIndex
- firstChildIndex
;
598 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
599 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
601 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
607 bool KFileItemModel::isExpanded(int index
) const
609 if (index
>= 0 && index
< count()) {
610 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
615 bool KFileItemModel::isExpandable(int index
) const
617 if (index
>= 0 && index
< count()) {
618 // Call data (instead of accessing m_itemData directly)
619 // to ensure that the value is initialized.
620 return data(index
).value("isExpandable").toBool();
625 int KFileItemModel::expandedParentsCount(int index
) const
627 if (index
>= 0 && index
< count()) {
628 return expandedParentsCount(m_itemData
.at(index
));
633 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
636 const auto dirs
= m_expandedDirs
;
637 for (const auto &dir
: dirs
) {
643 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
645 m_urlsToExpand
= urls
;
648 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
651 // Assure that each sub-path of the URL that should be
652 // expanded is added to m_urlsToExpand. KDirLister
653 // does not care whether the parent-URL has already been
655 QUrl urlToExpand
= m_dirLister
->url();
656 const int pos
= urlToExpand
.path().length();
658 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
659 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
660 // so using QString::SkipEmptyParts
661 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
662 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
663 QString path
= urlToExpand
.path();
664 if (!path
.endsWith(QLatin1Char('/'))) {
665 path
.append(QLatin1Char('/'));
667 urlToExpand
.setPath(path
+ subDirs
.at(i
));
668 m_urlsToExpand
.insert(urlToExpand
);
671 // KDirLister::open() must called at least once to trigger an initial
672 // loading. The pending URLs that must be restored are handled
673 // in slotCompleted().
674 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
675 while (it2
.hasNext()) {
676 const int idx
= index(it2
.next());
677 if (idx
>= 0 && !isExpanded(idx
)) {
678 setExpanded(idx
, true);
684 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
686 if (m_filter
.pattern() != nameFilter
) {
687 dispatchPendingItemsToInsert();
688 m_filter
.setPattern(nameFilter
);
693 QString
KFileItemModel::nameFilter() const
695 return m_filter
.pattern();
698 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
700 if (m_filter
.mimeTypes() != filters
) {
701 dispatchPendingItemsToInsert();
702 m_filter
.setMimeTypes(filters
);
707 QStringList
KFileItemModel::mimeTypeFilters() const
709 return m_filter
.mimeTypes();
712 void KFileItemModel::applyFilters()
715 // Check which previously shown items from m_itemData must now get
716 // hidden and hence moved from m_itemData into m_filteredItems.
718 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
720 // This pointer will refer to the next confirmed shown item from the point of
721 // view of the current "itemData" in the upcoming "for" loop.
722 ItemData
*itemShownBelow
= nullptr;
724 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
725 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
726 ItemData
*itemData
= m_itemData
.at(index
);
728 if (m_filter
.matches(itemData
->item
)
729 || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
730 // We could've entered here for two reasons:
731 // 1. This item passes the filter itself
732 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
734 // So this item must remain shown.
735 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
736 itemShownBelow
= itemData
;
738 // We hide this item for now, however, for expanded folders this is not final:
739 // 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
740 newFilteredIndexes
.prepend(index
);
741 m_filteredItems
.insert(itemData
->item
, itemData
);
742 // indexShownBelow doesn't get updated since this item will be hidden
746 // This will remove the newly filtered items from m_itemData
747 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
750 // Check which hidden items from m_filteredItems should
751 // become visible again and hence moved from m_filteredItems back into m_itemData.
753 QList
<ItemData
*> newVisibleItems
;
755 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
757 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
758 while (it
!= m_filteredItems
.end()) {
759 if (m_filter
.matches(it
.key())) {
760 newVisibleItems
.append(it
.value());
762 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
763 // We will go up through its parental chain until we either:
764 // 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 nullptr.
766 // 2 - we reach an unfiltered parent or a previously discovered ancestor.
767 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
768 parent
= parent
->parent
) {
769 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
770 // and it would mess up the iteration. We will mark it to be removed in step 3.
771 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
774 it
= m_filteredItems
.erase(it
);
776 // Item remains filtered for now
777 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
783 // Handles the ancestorsOfNewVisibleItems.
784 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
785 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
786 if (m_filteredItems
.remove(it
.key())) {
787 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
788 newVisibleItems
.append(it
.value());
792 // This will insert the newly discovered unfiltered items into m_itemData
793 insertItems(newVisibleItems
);
796 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
798 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
799 // There are either no filtered items, or it is not possible to expand
800 // folders -> there cannot be any filtered children.
804 QSet
<ItemData
*> parents
;
805 for (const KItemRange
& range
: itemRanges
) {
806 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
807 parents
.insert(m_itemData
.at(index
));
811 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
812 while (it
!= m_filteredItems
.end()) {
813 if (parents
.contains(it
.value()->parent
)) {
815 it
= m_filteredItems
.erase(it
);
822 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
824 static QList
<RoleInfo
> rolesInfo
;
825 if (rolesInfo
.isEmpty()) {
827 const RoleInfoMap
* map
= rolesInfoMap(count
);
828 for (int i
= 0; i
< count
; ++i
) {
829 if (map
[i
].roleType
!= NoRole
) {
831 info
.role
= map
[i
].role
;
832 info
.translation
= map
[i
].roleTranslation
.toString();
833 if (!map
[i
].groupTranslation
.isEmpty()) {
834 info
.group
= map
[i
].groupTranslation
.toString();
836 // For top level roles, groupTranslation is 0. We must make sure that
837 // info.group is an empty string then because the code that generates
838 // menus tries to put the actions into sub menus otherwise.
839 info
.group
= QString();
841 info
.requiresBaloo
= map
[i
].requiresBaloo
;
842 info
.requiresIndexer
= map
[i
].requiresIndexer
;
843 rolesInfo
.append(info
);
851 void KFileItemModel::onGroupedSortingChanged(bool current
)
857 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
860 m_sortRole
= typeForRole(current
);
862 if (!m_requestRole
[m_sortRole
]) {
863 QSet
<QByteArray
> newRoles
= m_roles
;
873 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
880 void KFileItemModel::loadSortingSettings()
882 using Choice
= GeneralSettings::EnumSortingChoice
;
883 switch (GeneralSettings::sortingChoice()) {
884 case Choice::NaturalSorting
:
885 m_naturalSorting
= true;
886 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
888 case Choice::CaseSensitiveSorting
:
889 m_naturalSorting
= false;
890 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
892 case Choice::CaseInsensitiveSorting
:
893 m_naturalSorting
= false;
894 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
899 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
900 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
901 m_collator
.compare(QString(), QString());
904 void KFileItemModel::resortAllItems()
906 m_resortAllItemsTimer
->stop();
908 const int itemCount
= count();
909 if (itemCount
<= 0) {
913 #ifdef KFILEITEMMODEL_DEBUG
916 qCDebug(DolphinDebug
) << "===========================================================";
917 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
920 // Remember the order of the current URLs so
921 // that it can be determined which indexes have
922 // been moved because of the resorting.
924 oldUrls
.reserve(itemCount
);
925 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
926 oldUrls
.append(itemData
->item
.url());
930 m_items
.reserve(itemCount
);
933 sort(m_itemData
.begin(), m_itemData
.end());
934 for (int i
= 0; i
< itemCount
; ++i
) {
935 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
938 // Determine the first index that has been moved.
939 int firstMovedIndex
= 0;
940 while (firstMovedIndex
< itemCount
941 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
945 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
946 if (itemsHaveMoved
) {
949 int lastMovedIndex
= itemCount
- 1;
950 while (lastMovedIndex
> firstMovedIndex
951 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
955 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
957 // Create a list movedToIndexes, which has the property that
958 // movedToIndexes[i] is the new index of the item with the old index
959 // firstMovedIndex + i.
960 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
961 QList
<int> movedToIndexes
;
962 movedToIndexes
.reserve(movedItemsCount
);
963 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
964 const int newIndex
= m_items
.value(oldUrls
.at(i
));
965 movedToIndexes
.append(newIndex
);
968 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
969 } else if (groupedSorting()) {
970 // The groups might have changed even if the order of the items has not.
971 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
973 if (groups() != oldGroups
) {
974 Q_EMIT
groupsChanged();
978 #ifdef KFILEITEMMODEL_DEBUG
979 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
983 void KFileItemModel::slotCompleted()
985 m_maximumUpdateIntervalTimer
->stop();
986 dispatchPendingItemsToInsert();
988 if (!m_urlsToExpand
.isEmpty()) {
989 // Try to find a URL that can be expanded.
990 // Note that the parent folder must be expanded before any of its subfolders become visible.
991 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
992 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
993 // Iterate over a const copy because items are deleted and inserted within the loop
994 const auto urlsToExpand
= m_urlsToExpand
;
995 for(const QUrl
&url
: urlsToExpand
) {
996 const int indexForUrl
= index(url
);
997 if (indexForUrl
>= 0) {
998 m_urlsToExpand
.remove(url
);
999 if (setExpanded(indexForUrl
, true)) {
1000 // The dir lister has been triggered. This slot will be called
1001 // again after the directory has been expanded.
1007 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1008 // if these URLs have been deleted in the meantime.
1009 m_urlsToExpand
.clear();
1012 Q_EMIT
directoryLoadingCompleted();
1015 void KFileItemModel::slotCanceled()
1017 m_maximumUpdateIntervalTimer
->stop();
1018 dispatchPendingItemsToInsert();
1020 Q_EMIT
directoryLoadingCanceled();
1023 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
1025 Q_ASSERT(!items
.isEmpty());
1027 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1029 if (m_requestRole
[ExpandedParentsCountRole
]) {
1030 // If the expanding of items is enabled, the call
1031 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1032 // might result in emitting the same items twice due to the Keep-parameter.
1033 // This case happens if an item gets expanded, collapsed and expanded again
1034 // before the items could be loaded for the first expansion.
1035 if (index(items
.first().url()) >= 0) {
1036 // The items are already part of the model.
1040 if (directoryUrl
!= directory()) {
1041 // To be able to compare whether the new items may be inserted as children
1042 // of a parent item the pending items must be added to the model first.
1043 dispatchPendingItemsToInsert();
1046 // KDirLister keeps the children of items that got expanded once even if
1047 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1048 // checked whether the parent for new items is still expanded.
1049 const int parentIndex
= index(parentUrl
);
1050 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1051 // The parent is not expanded.
1056 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1058 if (!m_filter
.hasSetFilters()) {
1059 m_pendingItemsToInsert
.append(itemDataList
);
1061 QSet
<ItemData
*> parentsToEnsureVisible
;
1063 // The name or type filter is active. Hide filtered items
1064 // before inserting them into the model and remember
1065 // the filtered items in m_filteredItems.
1066 for (ItemData
* itemData
: itemDataList
) {
1067 if (m_filter
.matches(itemData
->item
)) {
1068 m_pendingItemsToInsert
.append(itemData
);
1069 if (itemData
->parent
) {
1070 parentsToEnsureVisible
.insert(itemData
->parent
);
1073 m_filteredItems
.insert(itemData
->item
, itemData
);
1077 // Entire parental chains must be shown
1078 for (ItemData
*parent
: parentsToEnsureVisible
) {
1079 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1080 m_pendingItemsToInsert
.append(parent
);
1085 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1086 // Assure that items get dispatched if no completed() or canceled() signal is
1087 // emitted during the maximum update interval.
1088 m_maximumUpdateIntervalTimer
->start();
1091 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1094 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1096 int filteredParentsCount
= 0;
1097 // The childless parents not yet removed will always be right above the start of a removed range.
1098 // We iterate backwards to ensure the deepest folders are processed before their parents
1099 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1100 KItemRange itemRange
= removedItemRanges
.at(i
);
1101 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1102 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1103 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1105 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1106 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1107 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1108 // and this deleted range covers all of its descendents, so none will be left.
1109 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1110 // This range's starting index will be extended to include the parent above:
1113 ++filteredParentsCount
;
1114 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1115 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1116 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1117 previousRange
.count
+= itemRange
.count
;
1118 removedItemRanges
.replace(i
- 1, previousRange
);
1119 removedItemRanges
.removeAt(i
);
1121 removedItemRanges
.replace(i
, itemRange
);
1122 // We must revisit this range in the next iteration since its starting index changed
1127 return filteredParentsCount
;
1130 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1132 dispatchPendingItemsToInsert();
1134 QVector
<int> indexesToRemove
;
1135 indexesToRemove
.reserve(items
.count());
1136 KFileItemList dirsChanged
;
1138 for (const KFileItem
& item
: items
) {
1139 const int indexForItem
= index(item
);
1140 if (indexForItem
>= 0) {
1141 indexesToRemove
.append(indexForItem
);
1143 // Probably the item has been filtered.
1144 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1145 if (it
!= m_filteredItems
.end()) {
1147 m_filteredItems
.erase(it
);
1151 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1152 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1153 dirsChanged
<< KFileItem(parentUrl
);
1157 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1159 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1160 // Assure that removing a parent item also results in removing all children
1161 QVector
<int> indexesToRemoveWithChildren
;
1162 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1164 const int itemCount
= m_itemData
.count();
1165 for (int index
: qAsConst(indexesToRemove
)) {
1166 indexesToRemoveWithChildren
.append(index
);
1168 const int parentLevel
= expandedParentsCount(index
);
1169 int childIndex
= index
+ 1;
1170 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1171 indexesToRemoveWithChildren
.append(childIndex
);
1176 indexesToRemove
= indexesToRemoveWithChildren
;
1179 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1180 removeFilteredChildren(itemRanges
);
1182 // This call will update itemRanges to include the childless parents that have been filtered.
1183 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1185 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1186 // mixed with expanded folders that are just being filtered out.
1187 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1188 // so removeItems() will check m_filteredItems to differentiate which is which.
1189 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1191 Q_EMIT
fileItemsChanged(dirsChanged
);
1194 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1196 Q_ASSERT(!items
.isEmpty());
1197 #ifdef KFILEITEMMODEL_DEBUG
1198 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1201 // Get the indexes of all items that have been refreshed
1203 indexes
.reserve(items
.count());
1205 QSet
<QByteArray
> changedRoles
;
1206 KFileItemList changedFiles
;
1208 // Contains the indexes of the currently visible items
1209 // that should get hidden and hence moved to m_filteredItems.
1210 QVector
<int> newFilteredIndexes
;
1212 // Contains currently hidden items that should
1213 // get visible and hence removed from m_filteredItems
1214 QList
<ItemData
*> newVisibleItems
;
1216 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1218 while (it
.hasNext()) {
1219 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1220 const KFileItem
& oldItem
= itemPair
.first
;
1221 const KFileItem
& newItem
= itemPair
.second
;
1222 const int indexForItem
= index(oldItem
);
1223 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1224 if (indexForItem
>= 0) {
1225 m_itemData
[indexForItem
]->item
= newItem
;
1227 // Keep old values as long as possible if they could not retrieved synchronously yet.
1228 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1229 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1230 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1231 while (it
.hasNext()) {
1233 const QByteArray
& role
= it
.key();
1234 if (itemData
->values
.value(role
) != it
.value()) {
1235 itemData
->values
.insert(role
, it
.value());
1236 changedRoles
.insert(role
);
1240 m_items
.remove(oldItem
.url());
1241 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1242 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1243 m_items
.insert(newItem
.url(), indexForItem
);
1244 if (newItemMatchesFilter
1245 || (itemData
->values
.value("isExpanded").toBool()
1246 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1247 // We are lenient with expanded folders that originally had visible children.
1248 // If they become childless now they will be caught by filterChildlessParents()
1249 changedFiles
.append(newItem
);
1250 indexes
.append(indexForItem
);
1252 newFilteredIndexes
.append(indexForItem
);
1253 m_filteredItems
.insert(newItem
, itemData
);
1256 // Check if 'oldItem' is one of the filtered items.
1257 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1258 if (it
!= m_filteredItems
.end()) {
1259 ItemData
*const itemData
= it
.value();
1260 itemData
->item
= newItem
;
1262 // The data stored in 'values' might have changed. Therefore, we clear
1263 // 'values' and re-populate it the next time it is requested via data(int).
1264 // Before clearing, we must remember if it was expanded and the expanded parents count,
1265 // otherwise these states would be lost. The data() method will deal with this special case.
1266 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1267 bool hasExpandedParentsCount
= false;
1268 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1269 itemData
->values
.clear();
1271 itemData
->values
.insert("isExpanded", true);
1272 if (hasExpandedParentsCount
) {
1273 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1277 m_filteredItems
.erase(it
);
1278 if (newItemMatchesFilter
) {
1279 newVisibleItems
.append(itemData
);
1281 m_filteredItems
.insert(newItem
, itemData
);
1287 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1289 // We must keep track of parents of new visible items since they must be shown no matter what
1290 // They will be considered "immune" to filterChildlessParents()
1291 QSet
<ItemData
*> parentsToEnsureVisible
;
1293 for (ItemData
*item
: newVisibleItems
) {
1294 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1295 parentsToEnsureVisible
.insert(parent
);
1298 for (ItemData
*parent
: parentsToEnsureVisible
) {
1299 // We make sure they are all unfiltered.
1300 if (m_filteredItems
.remove(parent
->item
)) {
1301 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1302 newVisibleItems
.append(parent
);
1303 // It could be in newFilteredIndexes, we must remove it if it's there:
1304 const int parentIndex
= index(parent
->item
);
1305 if (parentIndex
>= 0) {
1306 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1307 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1308 newFilteredIndexes
.erase(it
);
1314 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1316 // This call will update itemRanges to include the childless parents that have been filtered.
1317 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1319 removeItems(removedRanges
, KeepItemData
);
1321 // Show previously hidden items that should get visible
1322 insertItems(newVisibleItems
);
1324 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1326 // If the changed items have been created recently, they might not be in m_items yet.
1327 // In that case, the list 'indexes' might be empty.
1328 if (indexes
.isEmpty()) {
1332 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1333 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1335 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1336 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1337 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1338 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1343 std::sort(indexes
.begin(), indexes
.end());
1346 // Extract the item-ranges out of the changed indexes
1347 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1348 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1350 Q_EMIT
fileItemsChanged(changedFiles
);
1353 void KFileItemModel::slotClear()
1355 #ifdef KFILEITEMMODEL_DEBUG
1356 qCDebug(DolphinDebug
) << "Clearing all items";
1359 qDeleteAll(m_filteredItems
);
1360 m_filteredItems
.clear();
1363 m_maximumUpdateIntervalTimer
->stop();
1364 m_resortAllItemsTimer
->stop();
1366 qDeleteAll(m_pendingItemsToInsert
);
1367 m_pendingItemsToInsert
.clear();
1369 const int removedCount
= m_itemData
.count();
1370 if (removedCount
> 0) {
1371 qDeleteAll(m_itemData
);
1374 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1377 m_expandedDirs
.clear();
1380 void KFileItemModel::slotSortingChoiceChanged()
1382 loadSortingSettings();
1386 void KFileItemModel::dispatchPendingItemsToInsert()
1388 if (!m_pendingItemsToInsert
.isEmpty()) {
1389 insertItems(m_pendingItemsToInsert
);
1390 m_pendingItemsToInsert
.clear();
1394 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1396 if (newItems
.isEmpty()) {
1400 #ifdef KFILEITEMMODEL_DEBUG
1401 QElapsedTimer timer
;
1403 qCDebug(DolphinDebug
) << "===========================================================";
1404 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1408 prepareItemsForSorting(newItems
);
1410 // Natural sorting of items can be very slow. However, it becomes much faster
1411 // if the input sequence is already mostly sorted. Therefore, we first sort
1412 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1413 if (m_naturalSorting
) {
1414 if (m_sortRole
== NameRole
) {
1415 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1416 } else if (isRoleValueNatural(m_sortRole
)) {
1417 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1419 const QByteArray role
= roleForType(m_sortRole
);
1420 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1422 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1426 sort(newItems
.begin(), newItems
.end());
1428 #ifdef KFILEITEMMODEL_DEBUG
1429 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1432 KItemRangeList itemRanges
;
1433 const int existingItemCount
= m_itemData
.count();
1434 const int newItemCount
= newItems
.count();
1435 const int totalItemCount
= existingItemCount
+ newItemCount
;
1437 if (existingItemCount
== 0) {
1438 // Optimization for the common special case that there are no
1439 // items in the model yet. Happens, e.g., when entering a folder.
1440 m_itemData
= newItems
;
1441 itemRanges
<< KItemRange(0, newItemCount
);
1443 m_itemData
.reserve(totalItemCount
);
1444 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1445 m_itemData
.append(nullptr);
1448 // We build the new list m_itemData in reverse order to minimize
1449 // the number of moves and guarantee O(N) complexity.
1450 int targetIndex
= totalItemCount
- 1;
1451 int sourceIndexExistingItems
= existingItemCount
- 1;
1452 int sourceIndexNewItems
= newItemCount
- 1;
1456 while (sourceIndexNewItems
>= 0) {
1457 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1458 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1459 // Move an existing item to its new position. If any new items
1460 // are behind it, push the item range to itemRanges.
1461 if (rangeCount
> 0) {
1462 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1466 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1467 --sourceIndexExistingItems
;
1469 // Insert a new item into the list.
1471 m_itemData
[targetIndex
] = newItem
;
1472 --sourceIndexNewItems
;
1477 // Push the final item range to itemRanges.
1478 if (rangeCount
> 0) {
1479 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1482 // Note that itemRanges is still sorted in reverse order.
1483 std::reverse(itemRanges
.begin(), itemRanges
.end());
1486 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1487 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1490 Q_EMIT
itemsInserted(itemRanges
);
1492 #ifdef KFILEITEMMODEL_DEBUG
1493 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1497 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1499 if (itemRanges
.isEmpty()) {
1505 // Step 1: Remove the items from m_itemData, and free the ItemData.
1506 int removedItemsCount
= 0;
1507 for (const KItemRange
& range
: itemRanges
) {
1508 removedItemsCount
+= range
.count
;
1510 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1511 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1512 delete m_itemData
.at(index
);
1515 m_itemData
[index
] = nullptr;
1519 // Step 2: Remove the ItemData pointers from the list m_itemData.
1520 int target
= itemRanges
.at(0).index
;
1521 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1524 const int oldItemDataCount
= m_itemData
.count();
1525 while (source
< oldItemDataCount
) {
1526 m_itemData
[target
] = m_itemData
[source
];
1530 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1531 // Skip the items in the next removed range.
1532 source
+= itemRanges
.at(nextRange
).count
;
1537 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1539 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1540 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1543 Q_EMIT
itemsRemoved(itemRanges
);
1546 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1548 if (m_sortRole
== TypeRole
) {
1549 // Try to resolve the MIME-types synchronously to prevent a reordering of
1550 // the items when sorting by type (per default MIME-types are resolved
1551 // asynchronously by KFileItemModelRolesUpdater).
1552 determineMimeTypes(items
, 200);
1555 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1556 const int parentIndex
= index(parentUrl
);
1557 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1559 QList
<ItemData
*> itemDataList
;
1560 itemDataList
.reserve(items
.count());
1562 for (const KFileItem
& item
: items
) {
1563 ItemData
* itemData
= new ItemData();
1564 itemData
->item
= item
;
1565 itemData
->parent
= parentItem
;
1566 itemDataList
.append(itemData
);
1569 return itemDataList
;
1572 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1574 switch (m_sortRole
) {
1575 case PermissionsRole
:
1578 case DestinationRole
:
1580 case DeletionTimeRole
:
1581 // These roles can be determined with retrieveData, and they have to be stored
1582 // in the QHash "values" for the sorting.
1583 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1584 if (itemData
->values
.isEmpty()) {
1585 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1591 // At least store the data including the file type for items with known MIME type.
1592 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1593 if (itemData
->values
.isEmpty()) {
1594 const KFileItem item
= itemData
->item
;
1595 if (item
.isDir() || item
.isMimeTypeKnown()) {
1596 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1603 // The other roles are either resolved by KFileItemModelRolesUpdater
1604 // (this includes the SizeRole for directories), or they do not need
1605 // to be stored in the QHash "values" for sorting because the data can
1606 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1612 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1614 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1615 // if the corresponding item is expanded, and it is not a top-level item.
1616 const ItemData
* parent
= data
->parent
;
1618 if (parent
->parent
) {
1619 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1620 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1629 void KFileItemModel::removeExpandedItems()
1631 QVector
<int> indexesToRemove
;
1633 const int maxIndex
= m_itemData
.count() - 1;
1634 for (int i
= 0; i
<= maxIndex
; ++i
) {
1635 const ItemData
* itemData
= m_itemData
.at(i
);
1636 if (itemData
->parent
) {
1637 indexesToRemove
.append(i
);
1641 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1642 m_expandedDirs
.clear();
1644 // Also remove all filtered items which have a parent.
1645 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1646 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1649 if (it
.value()->parent
) {
1651 it
= m_filteredItems
.erase(it
);
1658 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1660 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1662 // Trigger a resorting if necessary. Note that this can happen even if the sort
1663 // role has not changed at all because the file name can be used as a fallback.
1664 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1665 for (const KItemRange
& range
: itemRanges
) {
1666 bool needsResorting
= false;
1668 const int first
= range
.index
;
1669 const int last
= range
.index
+ range
.count
- 1;
1671 // Resorting the model is necessary if
1672 // (a) The first item in the range is "lessThan" its predecessor,
1673 // (b) the successor of the last item is "lessThan" the last item, or
1674 // (c) the internal order of the items in the range is incorrect.
1676 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1677 needsResorting
= true;
1678 } else if (last
< count() - 1
1679 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1680 needsResorting
= true;
1682 for (int index
= first
; index
< last
; ++index
) {
1683 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1684 needsResorting
= true;
1690 if (needsResorting
) {
1691 m_resortAllItemsTimer
->start();
1697 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1698 // The position is still correct, but the groups might have changed
1699 // if the changed item is either the first or the last item in a
1701 // In principle, we could try to find out if the item really is the
1702 // first or last one in its group and then update the groups
1703 // (possibly with a delayed timer to make sure that we don't
1704 // re-calculate the groups very often if items are updated one by
1705 // one), but starting m_resortAllItemsTimer is easier.
1706 m_resortAllItemsTimer
->start();
1710 void KFileItemModel::resetRoles()
1712 for (int i
= 0; i
< RolesCount
; ++i
) {
1713 m_requestRole
[i
] = false;
1717 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1719 static QHash
<QByteArray
, RoleType
> roles
;
1720 if (roles
.isEmpty()) {
1721 // Insert user visible roles that can be accessed with
1722 // KFileItemModel::roleInformation()
1724 const RoleInfoMap
* map
= rolesInfoMap(count
);
1725 for (int i
= 0; i
< count
; ++i
) {
1726 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1729 // Insert internal roles (take care to synchronize the implementation
1730 // with KFileItemModel::roleForType() in case if a change is done).
1731 roles
.insert("isDir", IsDirRole
);
1732 roles
.insert("isLink", IsLinkRole
);
1733 roles
.insert("isHidden", IsHiddenRole
);
1734 roles
.insert("isExpanded", IsExpandedRole
);
1735 roles
.insert("isExpandable", IsExpandableRole
);
1736 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1738 Q_ASSERT(roles
.count() == RolesCount
);
1741 return roles
.value(role
, NoRole
);
1744 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1746 static QHash
<RoleType
, QByteArray
> roles
;
1747 if (roles
.isEmpty()) {
1748 // Insert user visible roles that can be accessed with
1749 // KFileItemModel::roleInformation()
1751 const RoleInfoMap
* map
= rolesInfoMap(count
);
1752 for (int i
= 0; i
< count
; ++i
) {
1753 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1756 // Insert internal roles (take care to synchronize the implementation
1757 // with KFileItemModel::typeForRole() in case if a change is done).
1758 roles
.insert(IsDirRole
, "isDir");
1759 roles
.insert(IsLinkRole
, "isLink");
1760 roles
.insert(IsHiddenRole
, "isHidden");
1761 roles
.insert(IsExpandedRole
, "isExpanded");
1762 roles
.insert(IsExpandableRole
, "isExpandable");
1763 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1765 Q_ASSERT(roles
.count() == RolesCount
);
1768 return roles
.value(roleType
);
1771 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1773 // It is important to insert only roles that are fast to retrieve. E.g.
1774 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1775 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1776 QHash
<QByteArray
, QVariant
> data
;
1777 data
.insert(sharedValue("url"), item
.url());
1779 const bool isDir
= item
.isDir();
1780 if (m_requestRole
[IsDirRole
] && isDir
) {
1781 data
.insert(sharedValue("isDir"), true);
1784 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1785 data
.insert(sharedValue("isLink"), true);
1788 if (m_requestRole
[IsHiddenRole
]) {
1789 data
.insert(sharedValue("isHidden"), item
.isHidden());
1792 if (m_requestRole
[NameRole
]) {
1793 data
.insert(sharedValue("text"), item
.text());
1796 if (m_requestRole
[SizeRole
] && !isDir
) {
1797 data
.insert(sharedValue("size"), item
.size());
1800 if (m_requestRole
[ModificationTimeRole
]) {
1801 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1802 // having several thousands of items. Instead read the raw number from UDSEntry directly
1803 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1804 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1805 data
.insert(sharedValue("modificationtime"), dateTime
);
1808 if (m_requestRole
[CreationTimeRole
]) {
1809 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1810 // having several thousands of items. Instead read the raw number from UDSEntry directly
1811 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1812 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1813 data
.insert(sharedValue("creationtime"), dateTime
);
1816 if (m_requestRole
[AccessTimeRole
]) {
1817 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1818 // having several thousands of items. Instead read the raw number from UDSEntry directly
1819 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1820 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1821 data
.insert(sharedValue("accesstime"), dateTime
);
1824 if (m_requestRole
[PermissionsRole
]) {
1825 data
.insert(sharedValue("permissions"), item
.permissionsString());
1828 if (m_requestRole
[OwnerRole
]) {
1829 data
.insert(sharedValue("owner"), item
.user());
1832 if (m_requestRole
[GroupRole
]) {
1833 data
.insert(sharedValue("group"), item
.group());
1836 if (m_requestRole
[DestinationRole
]) {
1837 QString destination
= item
.linkDest();
1838 if (destination
.isEmpty()) {
1839 destination
= QLatin1Char('-');
1841 data
.insert(sharedValue("destination"), destination
);
1844 if (m_requestRole
[PathRole
]) {
1846 if (item
.url().scheme() == QLatin1String("trash")) {
1847 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1849 // For performance reasons cache the home-path in a static QString
1850 // (see QDir::homePath() for more details)
1851 static QString homePath
;
1852 if (homePath
.isEmpty()) {
1853 homePath
= QDir::homePath();
1856 path
= item
.localPath();
1857 if (path
.startsWith(homePath
)) {
1858 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1862 const int index
= path
.lastIndexOf(item
.text());
1863 path
= path
.mid(0, index
- 1);
1864 data
.insert(sharedValue("path"), path
);
1867 if (m_requestRole
[DeletionTimeRole
]) {
1868 QDateTime deletionTime
;
1869 if (item
.url().scheme() == QLatin1String("trash")) {
1870 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1872 data
.insert(sharedValue("deletiontime"), deletionTime
);
1875 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1876 data
.insert(sharedValue("isExpandable"), true);
1879 if (m_requestRole
[ExpandedParentsCountRole
]) {
1881 const int level
= expandedParentsCount(parent
) + 1;
1882 data
.insert(sharedValue("expandedParentsCount"), level
);
1886 if (item
.isMimeTypeKnown()) {
1887 QString iconName
= item
.iconName();
1888 if (!QIcon::hasThemeIcon(iconName
)) {
1889 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1890 iconName
= mimeType
.genericIconName();
1893 data
.insert(sharedValue("iconName"), iconName
);
1895 if (m_requestRole
[TypeRole
]) {
1896 data
.insert(sharedValue("type"), item
.mimeComment());
1898 } else if (m_requestRole
[TypeRole
] && isDir
) {
1899 static const QString folderMimeType
= item
.mimeComment();
1900 data
.insert(sharedValue("type"), folderMimeType
);
1906 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1910 if (a
->parent
!= b
->parent
) {
1911 const int expansionLevelA
= expandedParentsCount(a
);
1912 const int expansionLevelB
= expandedParentsCount(b
);
1914 // If b has a higher expansion level than a, check if a is a parent
1915 // of b, and make sure that both expansion levels are equal otherwise.
1916 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1917 if (b
->parent
== a
) {
1923 // If a has a higher expansion level than a, check if b is a parent
1924 // of a, and make sure that both expansion levels are equal otherwise.
1925 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1926 if (a
->parent
== b
) {
1932 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1934 // Compare the last parents of a and b which are different.
1935 while (a
->parent
!= b
->parent
) {
1941 // Show hidden files and folders last
1942 if (m_sortHiddenLast
) {
1943 const bool isHiddenA
= a
->item
.isHidden();
1944 const bool isHiddenB
= b
->item
.isHidden();
1945 if (isHiddenA
&& !isHiddenB
) {
1947 } else if (!isHiddenA
&& isHiddenB
) {
1952 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1953 const bool isDirA
= a
->item
.isDir();
1954 const bool isDirB
= b
->item
.isDir();
1955 if (isDirA
&& !isDirB
) {
1957 } else if (!isDirA
&& isDirB
) {
1962 result
= sortRoleCompare(a
, b
, collator
);
1964 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1967 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1968 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1970 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1972 return lessThan(a
, b
, m_collator
);
1975 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1976 // Sorting by string can be expensive, in particular if natural sorting is
1977 // enabled. Use all CPU cores to speed up the sorting process.
1978 static const int numberOfThreads
= QThread::idealThreadCount();
1979 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1981 // Sorting by other roles is quite fast. Use only one thread to prevent
1982 // problems caused by non-reentrant comparison functions, see
1983 // https://bugs.kde.org/show_bug.cgi?id=312679
1984 mergeSort(begin
, end
, lambdaLessThan
);
1988 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1990 // This function must never return 0, because that would break stable
1991 // sorting, which leads to all kinds of bugs.
1992 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1993 // If two items have equal sort values, let the fallbacks at the bottom of
1994 // the function handle it.
1995 const KFileItem
& itemA
= a
->item
;
1996 const KFileItem
& itemB
= b
->item
;
2000 switch (m_sortRole
) {
2002 // The name role is handled as default fallback after the switch
2006 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
2007 // folders first then
2008 // items A and B are folders thanks to lessThan checks
2009 auto valueA
= a
->values
.value("count");
2010 auto valueB
= b
->values
.value("count");
2011 if (valueA
.isNull()) {
2012 if (!valueB
.isNull()) {
2015 } else if (valueB
.isNull()) {
2018 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2020 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2027 KIO::filesize_t sizeA
= 0;
2028 if (itemA
.isDir()) {
2029 sizeA
= a
->values
.value("size").toULongLong();
2031 sizeA
= itemA
.size();
2033 KIO::filesize_t sizeB
= 0;
2034 if (itemB
.isDir()) {
2035 sizeB
= b
->values
.value("size").toULongLong();
2037 sizeB
= itemB
.size();
2039 if (sizeA
< sizeB
) {
2041 } else if (sizeA
> sizeB
) {
2047 case ModificationTimeRole
: {
2048 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2049 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2050 if (dateTimeA
< dateTimeB
) {
2052 } else if (dateTimeA
> dateTimeB
) {
2058 case CreationTimeRole
: {
2059 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2060 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2061 if (dateTimeA
< dateTimeB
) {
2063 } else if (dateTimeA
> dateTimeB
) {
2069 case DeletionTimeRole
: {
2070 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2071 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2072 if (dateTimeA
< dateTimeB
) {
2074 } else if (dateTimeA
> dateTimeB
) {
2086 case ReleaseYearRole
: {
2087 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2092 const QByteArray role
= roleForType(m_sortRole
);
2093 const QString roleValueA
= a
->values
.value(role
).toString();
2094 const QString roleValueB
= b
->values
.value(role
).toString();
2095 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2097 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2099 } else if (isRoleValueNatural(m_sortRole
)) {
2100 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2102 result
= QString::compare(roleValueA
, roleValueB
);
2110 // The current sort role was sufficient to define an order
2114 // Fallback #1: Compare the text of the items
2115 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2120 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2121 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2126 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2127 // equal. In this case a comparison of the URL is done which is unique in all cases
2128 // within KDirLister.
2129 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2132 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
2134 QMutexLocker
collatorLock(s_collatorMutex());
2136 if (m_naturalSorting
) {
2137 return collator
.compare(a
, b
);
2140 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2141 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2142 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2143 // comparison, still a deterministic sort order is required. A case sensitive
2144 // comparison is done as fallback.
2148 return QString::compare(a
, b
, Qt::CaseSensitive
);
2151 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
2153 Q_ASSERT(!m_itemData
.isEmpty());
2155 const int maxIndex
= count() - 1;
2156 QList
<QPair
<int, QVariant
> > groups
;
2160 for (int i
= 0; i
<= maxIndex
; ++i
) {
2161 if (isChildItem(i
)) {
2165 const QString name
= m_itemData
.at(i
)->item
.text();
2167 // Use the first character of the name as group indication
2168 QChar newFirstChar
= name
.at(0).toUpper();
2169 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2170 newFirstChar
= name
.at(1).toUpper();
2173 if (firstChar
!= newFirstChar
) {
2174 QString newGroupValue
;
2175 if (newFirstChar
.isLetter()) {
2177 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2178 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2180 // Try to find a matching group in the range 'A' to 'Z'.
2181 static std::vector
<QChar
> lettersAtoZ
;
2182 lettersAtoZ
.reserve('Z' - 'A' + 1);
2183 if (lettersAtoZ
.empty()) {
2184 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2185 lettersAtoZ
.push_back(QLatin1Char(c
));
2189 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2190 return m_collator
.compare(c1
, c2
) < 0;
2193 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2194 if (it
!= lettersAtoZ
.end()) {
2195 if (localeAwareLessThan(newFirstChar
, *it
)) {
2196 // newFirstChar belongs to the group preceding *it.
2197 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2200 newGroupValue
= *it
;
2204 // Symbols from non Latin-based scripts
2205 newGroupValue
= newFirstChar
;
2207 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2208 // Apply group '0 - 9' for any name that starts with a digit
2209 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2211 newGroupValue
= i18nc("@title:group", "Others");
2214 if (newGroupValue
!= groupValue
) {
2215 groupValue
= newGroupValue
;
2216 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2219 firstChar
= newFirstChar
;
2225 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2227 Q_ASSERT(!m_itemData
.isEmpty());
2229 const int maxIndex
= count() - 1;
2230 QList
<QPair
<int, QVariant
> > groups
;
2233 for (int i
= 0; i
<= maxIndex
; ++i
) {
2234 if (isChildItem(i
)) {
2238 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2239 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2240 QString newGroupValue
;
2241 if (!item
.isNull() && item
.isDir()) {
2242 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2243 newGroupValue
= i18nc("@title:group Size", "Folders");
2245 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2249 if (newGroupValue
.isEmpty()) {
2250 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2251 newGroupValue
= i18nc("@title:group Size", "Small");
2252 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2253 newGroupValue
= i18nc("@title:group Size", "Medium");
2255 newGroupValue
= i18nc("@title:group Size", "Big");
2259 if (newGroupValue
!= groupValue
) {
2260 groupValue
= newGroupValue
;
2261 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2268 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2270 Q_ASSERT(!m_itemData
.isEmpty());
2272 const int maxIndex
= count() - 1;
2273 QList
<QPair
<int, QVariant
> > groups
;
2275 const QDate currentDate
= QDate::currentDate();
2277 QDate previousFileDate
;
2279 for (int i
= 0; i
<= maxIndex
; ++i
) {
2280 if (isChildItem(i
)) {
2284 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2285 const QDate fileDate
= fileTime
.date();
2286 if (fileDate
== previousFileDate
) {
2287 // The current item is in the same group as the previous item
2290 previousFileDate
= fileDate
;
2292 const int daysDistance
= fileDate
.daysTo(currentDate
);
2294 QString newGroupValue
;
2295 if (currentDate
.year() == fileDate
.year() &&
2296 currentDate
.month() == fileDate
.month()) {
2298 switch (daysDistance
/ 7) {
2300 switch (daysDistance
) {
2301 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2302 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2304 newGroupValue
= fileTime
.toString(
2305 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2306 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2307 "with context @title:group Date", "%1", newGroupValue
);
2311 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2314 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2317 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2321 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2327 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2328 if (lastMonthDate
.year() == fileDate
.year() &&
2329 lastMonthDate
.month() == fileDate
.month()) {
2331 if (daysDistance
== 1) {
2332 const KLocalizedString format
= ki18nc("@title:group Date: "
2333 "MMMM is full month name in current locale, and yyyy is "
2334 "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 part of the text that should not be formatted as a date", "'Yesterday' (MMMM, yyyy)");
2335 const QString translatedFormat
= format
.toString();
2336 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2337 newGroupValue
= fileTime
.toString(translatedFormat
);
2338 newGroupValue
= i18nc("Can be used to script translation of "
2339 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2340 "%1", newGroupValue
);
2342 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2343 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2344 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2346 } else if (daysDistance
<= 7) {
2347 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2348 "The week day name: dddd, MMMM is full month name "
2349 "in current locale, and yyyy is full year number.",
2350 "dddd (MMMM, yyyy)"));
2351 newGroupValue
= i18nc("Can be used to script translation of "
2352 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2353 "%1", newGroupValue
);
2354 } else if (daysDistance
<= 7 * 2) {
2355 const KLocalizedString format
= ki18nc("@title:group Date: "
2356 "MMMM is full month name in current locale, and yyyy is "
2357 "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 part of the text that should not be formatted as a date", "'One Week Ago' (MMMM, yyyy)");
2358 const QString translatedFormat
= format
.toString();
2359 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2360 newGroupValue
= fileTime
.toString(translatedFormat
);
2361 newGroupValue
= i18nc("Can be used to script translation of "
2362 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2363 "%1", newGroupValue
);
2365 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2366 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2367 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2369 } else if (daysDistance
<= 7 * 3) {
2370 const KLocalizedString format
= ki18nc("@title:group Date: "
2371 "MMMM is full month name in current locale, and yyyy is "
2372 "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 part of the text that should not be formatted as a date", "'Two Weeks Ago' (MMMM, yyyy)");
2373 const QString translatedFormat
= format
.toString();
2374 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2375 newGroupValue
= fileTime
.toString(translatedFormat
);
2376 newGroupValue
= i18nc("Can be used to script translation of "
2377 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2378 "%1", newGroupValue
);
2380 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2381 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2382 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2384 } else if (daysDistance
<= 7 * 4) {
2385 const KLocalizedString format
= ki18nc("@title:group Date: "
2386 "MMMM is full month name in current locale, and yyyy is "
2387 "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 part of the text that should not be formatted as a date", "'Three Weeks Ago' (MMMM, yyyy)");
2388 const QString translatedFormat
= format
.toString();
2389 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2390 newGroupValue
= fileTime
.toString(translatedFormat
);
2391 newGroupValue
= i18nc("Can be used to script translation of "
2392 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2393 "%1", newGroupValue
);
2395 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2396 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2397 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2400 const KLocalizedString format
= ki18nc("@title:group Date: "
2401 "MMMM is full month name in current locale, and yyyy is "
2402 "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 part of the text that should not be formatted as a date", "'Earlier on' MMMM, yyyy");
2403 const QString translatedFormat
= format
.toString();
2404 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2405 newGroupValue
= fileTime
.toString(translatedFormat
);
2406 newGroupValue
= i18nc("Can be used to script translation of "
2407 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2408 "%1", newGroupValue
);
2410 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2411 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2412 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2416 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2417 "The month and year: MMMM is full month name in current locale, "
2418 "and yyyy is full year number", "MMMM, yyyy"));
2419 newGroupValue
= i18nc("Can be used to script translation of "
2420 "\"MMMM, yyyy\" with context @title:group Date",
2421 "%1", newGroupValue
);
2425 if (newGroupValue
!= groupValue
) {
2426 groupValue
= newGroupValue
;
2427 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2434 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2436 Q_ASSERT(!m_itemData
.isEmpty());
2438 const int maxIndex
= count() - 1;
2439 QList
<QPair
<int, QVariant
> > groups
;
2441 QString permissionsString
;
2443 for (int i
= 0; i
<= maxIndex
; ++i
) {
2444 if (isChildItem(i
)) {
2448 const ItemData
* itemData
= m_itemData
.at(i
);
2449 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2450 if (newPermissionsString
== permissionsString
) {
2453 permissionsString
= newPermissionsString
;
2455 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2459 if (info
.permission(QFile::ReadUser
)) {
2460 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2462 if (info
.permission(QFile::WriteUser
)) {
2463 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2465 if (info
.permission(QFile::ExeUser
)) {
2466 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2468 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2472 if (info
.permission(QFile::ReadGroup
)) {
2473 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2475 if (info
.permission(QFile::WriteGroup
)) {
2476 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2478 if (info
.permission(QFile::ExeGroup
)) {
2479 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2481 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2483 // Set others string
2485 if (info
.permission(QFile::ReadOther
)) {
2486 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2488 if (info
.permission(QFile::WriteOther
)) {
2489 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2491 if (info
.permission(QFile::ExeOther
)) {
2492 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2494 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2496 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2497 if (newGroupValue
!= groupValue
) {
2498 groupValue
= newGroupValue
;
2499 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2506 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2508 Q_ASSERT(!m_itemData
.isEmpty());
2510 const int maxIndex
= count() - 1;
2511 QList
<QPair
<int, QVariant
> > groups
;
2513 int groupValue
= -1;
2514 for (int i
= 0; i
<= maxIndex
; ++i
) {
2515 if (isChildItem(i
)) {
2518 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2519 if (newGroupValue
!= groupValue
) {
2520 groupValue
= newGroupValue
;
2521 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2528 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2530 Q_ASSERT(!m_itemData
.isEmpty());
2532 const int maxIndex
= count() - 1;
2533 QList
<QPair
<int, QVariant
> > groups
;
2535 bool isFirstGroupValue
= true;
2537 for (int i
= 0; i
<= maxIndex
; ++i
) {
2538 if (isChildItem(i
)) {
2541 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2542 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2543 groupValue
= newGroupValue
;
2544 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2545 isFirstGroupValue
= false;
2552 void KFileItemModel::emitSortProgress(int resolvedCount
)
2554 // Be tolerant against a resolvedCount with a wrong range.
2555 // Although there should not be a case where KFileItemModelRolesUpdater
2556 // (= caller) provides a wrong range, it is important to emit
2557 // a useful progress information even if there is an unexpected
2558 // implementation issue.
2560 const int itemCount
= count();
2561 if (resolvedCount
>= itemCount
) {
2562 m_sortingProgressPercent
= -1;
2563 if (m_resortAllItemsTimer
->isActive()) {
2564 m_resortAllItemsTimer
->stop();
2568 Q_EMIT
directorySortingProgress(100);
2569 } else if (itemCount
> 0) {
2570 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2572 const int progress
= resolvedCount
* 100 / itemCount
;
2573 if (m_sortingProgressPercent
!= progress
) {
2574 m_sortingProgressPercent
= progress
;
2575 Q_EMIT
directorySortingProgress(progress
);
2580 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2582 static const RoleInfoMap rolesInfoMap
[] = {
2583 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2584 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2585 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), false, false },
2586 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), false, false },
2587 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), false, false },
2588 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), false, false },
2589 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), false, false },
2590 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), false, false },
2591 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), true, false },
2592 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), true, false },
2593 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), true, false },
2594 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), true, true },
2595 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), true, true },
2596 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), true, true },
2597 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), true, true },
2598 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), true, true },
2599 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), true, true },
2600 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), true, true },
2601 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), true, true },
2602 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), true, true },
2603 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), true, true },
2604 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), true, true },
2605 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), true, true },
2606 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), true, true },
2607 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), true, true },
2608 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), true, true },
2609 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), true, true },
2610 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), false, false },
2611 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), false, false },
2612 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), false, false },
2613 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), true, false },
2614 { "permissions", PermissionsRole
, kli18nc("@label", "Permissions"), kli18nc("@label", "Other"), false, false },
2615 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), false, false },
2616 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), false, false },
2619 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2620 return rolesInfoMap
;
2623 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2625 QElapsedTimer timer
;
2627 for (const KFileItem
& item
: items
) {
2628 // Only determine mime types for files here. For directories,
2629 // KFileItem::determineMimeType() reads the .directory file inside to
2630 // load the icon, but this is not necessary at all if we just need the
2631 // type. Some special code for setting the correct mime type for
2632 // directories is in retrieveData().
2633 if (!item
.isDir()) {
2634 item
.determineMimeType();
2637 if (timer
.elapsed() > timeout
) {
2638 // Don't block the user interface, let the remaining items
2639 // be resolved asynchronously.
2645 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2647 static QSet
<QByteArray
> pool
;
2648 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2650 if (it
!= pool
.constEnd()) {
2658 bool KFileItemModel::isConsistent() const
2660 // m_items may contain less items than m_itemData because m_items
2661 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2662 if (m_items
.count() > m_itemData
.count()) {
2666 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2667 // Check if m_items and m_itemData are consistent.
2668 const KFileItem item
= fileItem(i
);
2669 if (item
.isNull()) {
2670 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2674 const int itemIndex
= index(item
);
2675 if (itemIndex
!= i
) {
2676 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2680 // Check if the items are sorted correctly.
2681 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2682 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2683 << fileItem(i
- 1) << fileItem(i
);
2687 // Check if all parent-child relationships are consistent.
2688 const ItemData
* data
= m_itemData
.at(i
);
2689 const ItemData
* parent
= data
->parent
;
2691 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2692 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2696 const int parentIndex
= index(parent
->item
);
2697 if (parentIndex
>= i
) {
2698 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2707 void KFileItemModel::slotListerError(KIO::Job
*job
)
2709 if (job
->error() == KIO::ERR_IS_FILE
) {
2710 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2711 Q_EMIT
urlIsFileError(listJob
->url());
2714 const QString errorString
= job
->errorString();
2715 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));