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>
30 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
32 // #define KFILEITEMMODEL_DEBUG
34 KFileItemModel::KFileItemModel(QObject
* parent
) :
35 KItemModelBase("text", parent
),
37 m_sortDirsFirst(true),
38 m_sortHiddenLast(false),
40 m_sortingProgressPercent(-1),
47 m_maximumUpdateIntervalTimer(nullptr),
48 m_resortAllItemsTimer(nullptr),
49 m_pendingItemsToInsert(),
54 m_collator
.setNumericMode(true);
56 loadSortingSettings();
58 m_dirLister
= new KDirLister(this);
59 m_dirLister
->setAutoErrorHandlingEnabled(false);
60 m_dirLister
->setDelayedMimeTypes(true);
62 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
64 m_dirLister
->setMainWindow(parentWidget
->window());
67 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
68 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
69 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
70 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
71 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
72 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
73 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
74 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
75 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
76 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
77 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
79 // Apply default roles that should be determined
81 m_requestRole
[NameRole
] = true;
82 m_requestRole
[IsDirRole
] = true;
83 m_requestRole
[IsLinkRole
] = true;
84 m_roles
.insert("text");
85 m_roles
.insert("isDir");
86 m_roles
.insert("isLink");
87 m_roles
.insert("isHidden");
89 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
90 // before the completed() or canceled() signal has been emitted.
91 m_maximumUpdateIntervalTimer
= new QTimer(this);
92 m_maximumUpdateIntervalTimer
->setInterval(2000);
93 m_maximumUpdateIntervalTimer
->setSingleShot(true);
94 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
96 // When changing the value of an item which represents the sort-role a resorting must be
97 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
98 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
99 // resorting is postponed until the timer has been exceeded.
100 m_resortAllItemsTimer
= new QTimer(this);
101 m_resortAllItemsTimer
->setInterval(500);
102 m_resortAllItemsTimer
->setSingleShot(true);
103 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
105 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
108 KFileItemModel::~KFileItemModel()
110 qDeleteAll(m_itemData
);
111 qDeleteAll(m_filteredItems
);
112 qDeleteAll(m_pendingItemsToInsert
);
115 void KFileItemModel::loadDirectory(const QUrl
&url
)
117 m_dirLister
->openUrl(url
);
120 void KFileItemModel::refreshDirectory(const QUrl
&url
)
122 // Refresh all expanded directories first (Bug 295300)
123 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
124 while (expandedDirs
.hasNext()) {
126 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
129 m_dirLister
->openUrl(url
, KDirLister::Reload
);
132 QUrl
KFileItemModel::directory() const
134 return m_dirLister
->url();
137 void KFileItemModel::cancelDirectoryLoading()
142 int KFileItemModel::count() const
144 return m_itemData
.count();
147 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
149 if (index
>= 0 && index
< count()) {
150 ItemData
* data
= m_itemData
.at(index
);
151 if (data
->values
.isEmpty()) {
152 data
->values
= retrieveData(data
->item
, data
->parent
);
153 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
154 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
155 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
156 // so this special request of different behavior can be identified here.
157 bool hasExpandedParentsCount
= false;
158 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
160 data
->values
= retrieveData(data
->item
, data
->parent
);
161 data
->values
.insert("isExpanded", true);
162 if (hasExpandedParentsCount
) {
163 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
169 return QHash
<QByteArray
, QVariant
>();
172 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
174 if (index
< 0 || index
>= count()) {
178 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
180 // Determine which roles have been changed
181 QSet
<QByteArray
> changedRoles
;
182 QHashIterator
<QByteArray
, QVariant
> it(values
);
183 while (it
.hasNext()) {
185 const QByteArray role
= sharedValue(it
.key());
186 const QVariant value
= it
.value();
188 if (currentValues
[role
] != value
) {
189 currentValues
[role
] = value
;
190 changedRoles
.insert(role
);
194 if (changedRoles
.isEmpty()) {
198 m_itemData
[index
]->values
= currentValues
;
199 if (changedRoles
.contains("text")) {
200 QUrl url
= m_itemData
[index
]->item
.url();
201 url
= url
.adjusted(QUrl::RemoveFilename
);
202 url
.setPath(url
.path() + currentValues
["text"].toString());
203 m_itemData
[index
]->item
.setUrl(url
);
206 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
211 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
213 if (dirsFirst
!= m_sortDirsFirst
) {
214 m_sortDirsFirst
= dirsFirst
;
219 bool KFileItemModel::sortDirectoriesFirst() const
221 return m_sortDirsFirst
;
224 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
226 if (hiddenLast
!= m_sortHiddenLast
) {
227 m_sortHiddenLast
= hiddenLast
;
232 bool KFileItemModel::sortHiddenLast() const
234 return m_sortHiddenLast
;
237 void KFileItemModel::setShowHiddenFiles(bool show
)
239 m_dirLister
->setShowingDotFiles(show
);
240 m_dirLister
->emitChanges();
242 dispatchPendingItemsToInsert();
246 bool KFileItemModel::showHiddenFiles() const
248 return m_dirLister
->showingDotFiles();
251 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
253 m_dirLister
->setDirOnlyMode(enabled
);
256 bool KFileItemModel::showDirectoriesOnly() const
258 return m_dirLister
->dirOnlyMode();
261 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
263 QMimeData
* data
= new QMimeData();
265 // The following code has been taken from KDirModel::mimeData()
266 // (kdelibs/kio/kio/kdirmodel.cpp)
267 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
269 QList
<QUrl
> mostLocalUrls
;
270 const ItemData
* lastAddedItem
= nullptr;
272 for (int index
: indexes
) {
273 const ItemData
* itemData
= m_itemData
.at(index
);
274 const ItemData
* parent
= itemData
->parent
;
276 while (parent
&& parent
!= lastAddedItem
) {
277 parent
= parent
->parent
;
280 if (parent
&& parent
== lastAddedItem
) {
281 // A parent of 'itemData' has been added already.
285 lastAddedItem
= itemData
;
286 const KFileItem
& item
= itemData
->item
;
287 if (!item
.isNull()) {
291 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
295 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
299 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
301 startFromIndex
= qMax(0, startFromIndex
);
302 for (int i
= startFromIndex
; i
< count(); ++i
) {
303 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
307 for (int i
= 0; i
< startFromIndex
; ++i
) {
308 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
315 bool KFileItemModel::supportsDropping(int index
) const
317 const KFileItem item
= fileItem(index
);
318 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
321 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
323 static QHash
<QByteArray
, QString
> description
;
324 if (description
.isEmpty()) {
326 const RoleInfoMap
* map
= rolesInfoMap(count
);
327 for (int i
= 0; i
< count
; ++i
) {
328 if (!map
[i
].roleTranslation
) {
331 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
335 return description
.value(role
);
338 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
340 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
341 #ifdef KFILEITEMMODEL_DEBUG
345 switch (typeForRole(sortRole())) {
346 case NameRole
: m_groups
= nameRoleGroups(); break;
347 case SizeRole
: m_groups
= sizeRoleGroups(); break;
348 case ModificationTimeRole
:
349 m_groups
= timeRoleGroups([](const ItemData
*item
) {
350 return item
->item
.time(KFileItem::ModificationTime
);
353 case CreationTimeRole
:
354 m_groups
= timeRoleGroups([](const ItemData
*item
) {
355 return item
->item
.time(KFileItem::CreationTime
);
359 m_groups
= timeRoleGroups([](const ItemData
*item
) {
360 return item
->item
.time(KFileItem::AccessTime
);
363 case DeletionTimeRole
:
364 m_groups
= timeRoleGroups([](const ItemData
*item
) {
365 return item
->values
.value("deletiontime").toDateTime();
368 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
369 case RatingRole
: m_groups
= ratingRoleGroups(); break;
370 default: m_groups
= genericStringRoleGroups(sortRole()); break;
373 #ifdef KFILEITEMMODEL_DEBUG
374 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
381 KFileItem
KFileItemModel::fileItem(int index
) const
383 if (index
>= 0 && index
< count()) {
384 return m_itemData
.at(index
)->item
;
390 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
392 const int indexForUrl
= index(url
);
393 if (indexForUrl
>= 0) {
394 return m_itemData
.at(indexForUrl
)->item
;
399 int KFileItemModel::index(const KFileItem
& item
) const
401 return index(item
.url());
404 int KFileItemModel::index(const QUrl
& url
) const
406 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
408 const int itemCount
= m_itemData
.count();
409 int itemsInHash
= m_items
.count();
411 int index
= m_items
.value(urlToFind
, -1);
412 while (index
< 0 && itemsInHash
< itemCount
) {
413 // Not all URLs are stored yet in m_items. We grow m_items until either
414 // urlToFind is found, or all URLs have been stored in m_items.
415 // Note that we do not add the URLs to m_items one by one, but in
416 // larger blocks. After each block, we check if urlToFind is in
417 // m_items. We could in principle compare urlToFind with each URL while
418 // we are going through m_itemData, but comparing two QUrls will,
419 // unlike calling qHash for the URLs, trigger a parsing of the URLs
420 // which costs both CPU cycles and memory.
421 const int blockSize
= 1000;
422 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
423 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
424 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
425 m_items
.insert(nextUrl
, i
);
428 itemsInHash
= currentBlockEnd
;
429 index
= m_items
.value(urlToFind
, -1);
433 // The item could not be found, even though all items from m_itemData
434 // should be in m_items now. We print some diagnostic information which
435 // might help to find the cause of the problem, but only once. This
436 // prevents that obtaining and printing the debugging information
437 // wastes CPU cycles and floods the shell or .xsession-errors.
438 static bool printDebugInfo
= true;
440 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
441 printDebugInfo
= false;
443 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
444 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
445 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
447 // Check if there are multiple items with the same URL.
448 QMultiHash
<QUrl
, int> indexesForUrl
;
449 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
450 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
453 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
454 for (const QUrl
& url
: uniqueKeys
) {
455 if (indexesForUrl
.count(url
) > 1) {
456 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
458 auto it
= indexesForUrl
.find(url
);
459 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
460 const ItemData
* data
= m_itemData
.at(it
.value());
461 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
463 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
475 KFileItem
KFileItemModel::rootItem() const
477 return m_dirLister
->rootItem();
480 void KFileItemModel::clear()
485 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
487 if (m_roles
== roles
) {
491 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
495 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
496 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
497 if (supportedExpanding
&& !willSupportExpanding
) {
498 // No expanding is supported anymore. Take care to delete all items that have an expansion level
499 // that is not 0 (and hence are part of an expanded item).
500 removeExpandedItems();
507 QSetIterator
<QByteArray
> it(roles
);
508 while (it
.hasNext()) {
509 const QByteArray
& role
= it
.next();
510 m_requestRole
[typeForRole(role
)] = true;
514 // Update m_data with the changed requested roles
515 const int maxIndex
= count() - 1;
516 for (int i
= 0; i
<= maxIndex
; ++i
) {
517 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
520 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
523 // Clear the 'values' of all filtered items. They will be re-populated with the
524 // correct roles the next time 'values' will be accessed via data(int).
525 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
526 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
527 while (filteredIt
!= filteredEnd
) {
528 (*filteredIt
)->values
.clear();
533 QSet
<QByteArray
> KFileItemModel::roles() const
538 bool KFileItemModel::setExpanded(int index
, bool expanded
)
540 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
544 QHash
<QByteArray
, QVariant
> values
;
545 values
.insert(sharedValue("isExpanded"), expanded
);
546 if (!setData(index
, values
)) {
550 const KFileItem item
= m_itemData
.at(index
)->item
;
551 const QUrl url
= item
.url();
552 const QUrl targetUrl
= item
.targetUrl();
554 m_expandedDirs
.insert(targetUrl
, url
);
555 m_dirLister
->openUrl(url
, KDirLister::Keep
);
557 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
558 for (const QVariant
& var
: previouslyExpandedChildren
) {
559 m_urlsToExpand
.insert(var
.toUrl());
562 // Note that there might be (indirect) children of the folder which is to be collapsed in
563 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
564 // possibly without a parent, which might result in a crash, we insert all pending items
565 // right now. All new items which would be without a parent will then be removed.
566 dispatchPendingItemsToInsert();
568 // Check if the index of the collapsed folder has changed. If that is the case, then items
569 // were inserted before the collapsed folder, and its index needs to be updated.
570 if (m_itemData
.at(index
)->item
!= item
) {
571 index
= this->index(item
);
574 m_expandedDirs
.remove(targetUrl
);
575 m_dirLister
->stop(url
);
577 const int parentLevel
= expandedParentsCount(index
);
578 const int itemCount
= m_itemData
.count();
579 const int firstChildIndex
= index
+ 1;
581 QVariantList expandedChildren
;
583 int childIndex
= firstChildIndex
;
584 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
585 ItemData
* itemData
= m_itemData
.at(childIndex
);
586 if (itemData
->values
.value("isExpanded").toBool()) {
587 const QUrl targetUrl
= itemData
->item
.targetUrl();
588 const QUrl url
= itemData
->item
.url();
589 m_expandedDirs
.remove(targetUrl
);
590 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
591 expandedChildren
.append(targetUrl
);
595 const int childrenCount
= childIndex
- firstChildIndex
;
597 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
598 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
600 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
606 bool KFileItemModel::isExpanded(int index
) const
608 if (index
>= 0 && index
< count()) {
609 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
614 bool KFileItemModel::isExpandable(int index
) const
616 if (index
>= 0 && index
< count()) {
617 // Call data (instead of accessing m_itemData directly)
618 // to ensure that the value is initialized.
619 return data(index
).value("isExpandable").toBool();
624 int KFileItemModel::expandedParentsCount(int index
) const
626 if (index
>= 0 && index
< count()) {
627 return expandedParentsCount(m_itemData
.at(index
));
632 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
635 const auto dirs
= m_expandedDirs
;
636 for (const auto &dir
: dirs
) {
642 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
644 m_urlsToExpand
= urls
;
647 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
650 // Assure that each sub-path of the URL that should be
651 // expanded is added to m_urlsToExpand. KDirLister
652 // does not care whether the parent-URL has already been
654 QUrl urlToExpand
= m_dirLister
->url();
655 const int pos
= urlToExpand
.path().length();
657 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
658 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
659 // so using QString::SkipEmptyParts
660 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
661 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
662 QString path
= urlToExpand
.path();
663 if (!path
.endsWith(QLatin1Char('/'))) {
664 path
.append(QLatin1Char('/'));
666 urlToExpand
.setPath(path
+ subDirs
.at(i
));
667 m_urlsToExpand
.insert(urlToExpand
);
670 // KDirLister::open() must called at least once to trigger an initial
671 // loading. The pending URLs that must be restored are handled
672 // in slotCompleted().
673 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
674 while (it2
.hasNext()) {
675 const int idx
= index(it2
.next());
676 if (idx
>= 0 && !isExpanded(idx
)) {
677 setExpanded(idx
, true);
683 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
685 if (m_filter
.pattern() != nameFilter
) {
686 dispatchPendingItemsToInsert();
687 m_filter
.setPattern(nameFilter
);
692 QString
KFileItemModel::nameFilter() const
694 return m_filter
.pattern();
697 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
699 if (m_filter
.mimeTypes() != filters
) {
700 dispatchPendingItemsToInsert();
701 m_filter
.setMimeTypes(filters
);
706 QStringList
KFileItemModel::mimeTypeFilters() const
708 return m_filter
.mimeTypes();
711 void KFileItemModel::applyFilters()
714 // Check which previously shown items from m_itemData must now get
715 // hidden and hence moved from m_itemData into m_filteredItems.
717 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
719 // This pointer will refer to the next confirmed shown item from the point of
720 // view of the current "itemData" in the upcoming "for" loop.
721 ItemData
*itemShownBelow
= nullptr;
723 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
724 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
725 ItemData
*itemData
= m_itemData
.at(index
);
727 if (m_filter
.matches(itemData
->item
)
728 || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
729 // We could've entered here for two reasons:
730 // 1. This item passes the filter itself
731 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
733 // So this item must remain shown.
734 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
735 itemShownBelow
= itemData
;
737 // We hide this item for now, however, for expanded folders this is not final:
738 // 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
739 newFilteredIndexes
.prepend(index
);
740 m_filteredItems
.insert(itemData
->item
, itemData
);
741 // indexShownBelow doesn't get updated since this item will be hidden
745 // This will remove the newly filtered items from m_itemData
746 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
749 // Check which hidden items from m_filteredItems should
750 // become visible again and hence moved from m_filteredItems back into m_itemData.
752 QList
<ItemData
*> newVisibleItems
;
754 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
756 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
757 while (it
!= m_filteredItems
.end()) {
758 if (m_filter
.matches(it
.key())) {
759 newVisibleItems
.append(it
.value());
761 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
762 // We will go up through its parental chain until we either:
763 // 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.
765 // 2 - we reach an unfiltered parent or a previously discovered ancestor.
766 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
767 parent
= parent
->parent
) {
768 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
769 // and it would mess up the iteration. We will mark it to be removed in step 3.
770 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
773 it
= m_filteredItems
.erase(it
);
775 // Item remains filtered for now
776 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
782 // Handles the ancestorsOfNewVisibleItems.
783 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
784 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
785 if (m_filteredItems
.remove(it
.key())) {
786 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
787 newVisibleItems
.append(it
.value());
791 // This will insert the newly discovered unfiltered items into m_itemData
792 insertItems(newVisibleItems
);
795 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
797 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
798 // There are either no filtered items, or it is not possible to expand
799 // folders -> there cannot be any filtered children.
803 QSet
<ItemData
*> parents
;
804 for (const KItemRange
& range
: itemRanges
) {
805 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
806 parents
.insert(m_itemData
.at(index
));
810 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
811 while (it
!= m_filteredItems
.end()) {
812 if (parents
.contains(it
.value()->parent
)) {
814 it
= m_filteredItems
.erase(it
);
821 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
823 static QList
<RoleInfo
> rolesInfo
;
824 if (rolesInfo
.isEmpty()) {
826 const RoleInfoMap
* map
= rolesInfoMap(count
);
827 for (int i
= 0; i
< count
; ++i
) {
828 if (map
[i
].roleType
!= NoRole
) {
830 info
.role
= map
[i
].role
;
831 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
832 if (map
[i
].groupTranslation
) {
833 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
835 // For top level roles, groupTranslation is 0. We must make sure that
836 // info.group is an empty string then because the code that generates
837 // menus tries to put the actions into sub menus otherwise.
838 info
.group
= QString();
840 info
.requiresBaloo
= map
[i
].requiresBaloo
;
841 info
.requiresIndexer
= map
[i
].requiresIndexer
;
842 rolesInfo
.append(info
);
850 void KFileItemModel::onGroupedSortingChanged(bool current
)
856 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
859 m_sortRole
= typeForRole(current
);
861 if (!m_requestRole
[m_sortRole
]) {
862 QSet
<QByteArray
> newRoles
= m_roles
;
872 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
879 void KFileItemModel::loadSortingSettings()
881 using Choice
= GeneralSettings::EnumSortingChoice
;
882 switch (GeneralSettings::sortingChoice()) {
883 case Choice::NaturalSorting
:
884 m_naturalSorting
= true;
885 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
887 case Choice::CaseSensitiveSorting
:
888 m_naturalSorting
= false;
889 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
891 case Choice::CaseInsensitiveSorting
:
892 m_naturalSorting
= false;
893 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
898 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
899 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
900 m_collator
.compare(QString(), QString());
903 void KFileItemModel::resortAllItems()
905 m_resortAllItemsTimer
->stop();
907 const int itemCount
= count();
908 if (itemCount
<= 0) {
912 #ifdef KFILEITEMMODEL_DEBUG
915 qCDebug(DolphinDebug
) << "===========================================================";
916 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
919 // Remember the order of the current URLs so
920 // that it can be determined which indexes have
921 // been moved because of the resorting.
923 oldUrls
.reserve(itemCount
);
924 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
925 oldUrls
.append(itemData
->item
.url());
929 m_items
.reserve(itemCount
);
932 sort(m_itemData
.begin(), m_itemData
.end());
933 for (int i
= 0; i
< itemCount
; ++i
) {
934 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
937 // Determine the first index that has been moved.
938 int firstMovedIndex
= 0;
939 while (firstMovedIndex
< itemCount
940 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
944 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
945 if (itemsHaveMoved
) {
948 int lastMovedIndex
= itemCount
- 1;
949 while (lastMovedIndex
> firstMovedIndex
950 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
954 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
956 // Create a list movedToIndexes, which has the property that
957 // movedToIndexes[i] is the new index of the item with the old index
958 // firstMovedIndex + i.
959 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
960 QList
<int> movedToIndexes
;
961 movedToIndexes
.reserve(movedItemsCount
);
962 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
963 const int newIndex
= m_items
.value(oldUrls
.at(i
));
964 movedToIndexes
.append(newIndex
);
967 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
968 } else if (groupedSorting()) {
969 // The groups might have changed even if the order of the items has not.
970 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
972 if (groups() != oldGroups
) {
973 Q_EMIT
groupsChanged();
977 #ifdef KFILEITEMMODEL_DEBUG
978 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
982 void KFileItemModel::slotCompleted()
984 m_maximumUpdateIntervalTimer
->stop();
985 dispatchPendingItemsToInsert();
987 if (!m_urlsToExpand
.isEmpty()) {
988 // Try to find a URL that can be expanded.
989 // Note that the parent folder must be expanded before any of its subfolders become visible.
990 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
991 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
992 // Iterate over a const copy because items are deleted and inserted within the loop
993 const auto urlsToExpand
= m_urlsToExpand
;
994 for(const QUrl
&url
: urlsToExpand
) {
995 const int indexForUrl
= index(url
);
996 if (indexForUrl
>= 0) {
997 m_urlsToExpand
.remove(url
);
998 if (setExpanded(indexForUrl
, true)) {
999 // The dir lister has been triggered. This slot will be called
1000 // again after the directory has been expanded.
1006 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1007 // if these URLs have been deleted in the meantime.
1008 m_urlsToExpand
.clear();
1011 Q_EMIT
directoryLoadingCompleted();
1014 void KFileItemModel::slotCanceled()
1016 m_maximumUpdateIntervalTimer
->stop();
1017 dispatchPendingItemsToInsert();
1019 Q_EMIT
directoryLoadingCanceled();
1022 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
1024 Q_ASSERT(!items
.isEmpty());
1026 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1028 if (m_requestRole
[ExpandedParentsCountRole
]) {
1029 // If the expanding of items is enabled, the call
1030 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1031 // might result in emitting the same items twice due to the Keep-parameter.
1032 // This case happens if an item gets expanded, collapsed and expanded again
1033 // before the items could be loaded for the first expansion.
1034 if (index(items
.first().url()) >= 0) {
1035 // The items are already part of the model.
1039 if (directoryUrl
!= directory()) {
1040 // To be able to compare whether the new items may be inserted as children
1041 // of a parent item the pending items must be added to the model first.
1042 dispatchPendingItemsToInsert();
1045 // KDirLister keeps the children of items that got expanded once even if
1046 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1047 // checked whether the parent for new items is still expanded.
1048 const int parentIndex
= index(parentUrl
);
1049 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1050 // The parent is not expanded.
1055 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1057 if (!m_filter
.hasSetFilters()) {
1058 m_pendingItemsToInsert
.append(itemDataList
);
1060 QSet
<ItemData
*> parentsToEnsureVisible
;
1062 // The name or type filter is active. Hide filtered items
1063 // before inserting them into the model and remember
1064 // the filtered items in m_filteredItems.
1065 for (ItemData
* itemData
: itemDataList
) {
1066 if (m_filter
.matches(itemData
->item
)) {
1067 m_pendingItemsToInsert
.append(itemData
);
1068 if (itemData
->parent
) {
1069 parentsToEnsureVisible
.insert(itemData
->parent
);
1072 m_filteredItems
.insert(itemData
->item
, itemData
);
1076 // Entire parental chains must be shown
1077 for (ItemData
*parent
: parentsToEnsureVisible
) {
1078 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1079 m_pendingItemsToInsert
.append(parent
);
1084 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1085 // Assure that items get dispatched if no completed() or canceled() signal is
1086 // emitted during the maximum update interval.
1087 m_maximumUpdateIntervalTimer
->start();
1090 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1093 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1095 int filteredParentsCount
= 0;
1096 // The childless parents not yet removed will always be right above the start of a removed range.
1097 // We iterate backwards to ensure the deepest folders are processed before their parents
1098 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1099 KItemRange itemRange
= removedItemRanges
.at(i
);
1100 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1101 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1102 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1104 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1105 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1106 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1107 // and this deleted range covers all of its descendents, so none will be left.
1108 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1109 // This range's starting index will be extended to include the parent above:
1112 ++filteredParentsCount
;
1113 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1114 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1115 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1116 previousRange
.count
+= itemRange
.count
;
1117 removedItemRanges
.replace(i
- 1, previousRange
);
1118 removedItemRanges
.removeAt(i
);
1120 removedItemRanges
.replace(i
, itemRange
);
1121 // We must revisit this range in the next iteration since its starting index changed
1126 return filteredParentsCount
;
1129 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1131 dispatchPendingItemsToInsert();
1133 QVector
<int> indexesToRemove
;
1134 indexesToRemove
.reserve(items
.count());
1135 KFileItemList dirsChanged
;
1137 for (const KFileItem
& item
: items
) {
1138 const int indexForItem
= index(item
);
1139 if (indexForItem
>= 0) {
1140 indexesToRemove
.append(indexForItem
);
1142 // Probably the item has been filtered.
1143 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1144 if (it
!= m_filteredItems
.end()) {
1146 m_filteredItems
.erase(it
);
1150 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1151 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1152 dirsChanged
<< KFileItem(parentUrl
);
1156 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1158 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1159 // Assure that removing a parent item also results in removing all children
1160 QVector
<int> indexesToRemoveWithChildren
;
1161 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1163 const int itemCount
= m_itemData
.count();
1164 for (int index
: qAsConst(indexesToRemove
)) {
1165 indexesToRemoveWithChildren
.append(index
);
1167 const int parentLevel
= expandedParentsCount(index
);
1168 int childIndex
= index
+ 1;
1169 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1170 indexesToRemoveWithChildren
.append(childIndex
);
1175 indexesToRemove
= indexesToRemoveWithChildren
;
1178 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1179 removeFilteredChildren(itemRanges
);
1181 // This call will update itemRanges to include the childless parents that have been filtered.
1182 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1184 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1185 // mixed with expanded folders that are just being filtered out.
1186 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1187 // so removeItems() will check m_filteredItems to differentiate which is which.
1188 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1190 Q_EMIT
fileItemsChanged(dirsChanged
);
1193 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1195 Q_ASSERT(!items
.isEmpty());
1196 #ifdef KFILEITEMMODEL_DEBUG
1197 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1200 // Get the indexes of all items that have been refreshed
1202 indexes
.reserve(items
.count());
1204 QSet
<QByteArray
> changedRoles
;
1205 KFileItemList changedFiles
;
1207 // Contains the indexes of the currently visible items
1208 // that should get hidden and hence moved to m_filteredItems.
1209 QVector
<int> newFilteredIndexes
;
1211 // Contains currently hidden items that should
1212 // get visible and hence removed from m_filteredItems
1213 QList
<ItemData
*> newVisibleItems
;
1215 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1217 while (it
.hasNext()) {
1218 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1219 const KFileItem
& oldItem
= itemPair
.first
;
1220 const KFileItem
& newItem
= itemPair
.second
;
1221 const int indexForItem
= index(oldItem
);
1222 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1223 if (indexForItem
>= 0) {
1224 m_itemData
[indexForItem
]->item
= newItem
;
1226 // Keep old values as long as possible if they could not retrieved synchronously yet.
1227 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1228 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1229 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1230 while (it
.hasNext()) {
1232 const QByteArray
& role
= it
.key();
1233 if (itemData
->values
.value(role
) != it
.value()) {
1234 itemData
->values
.insert(role
, it
.value());
1235 changedRoles
.insert(role
);
1239 m_items
.remove(oldItem
.url());
1240 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1241 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1242 m_items
.insert(newItem
.url(), indexForItem
);
1243 if (newItemMatchesFilter
1244 || (itemData
->values
.value("isExpanded").toBool()
1245 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1246 // We are lenient with expanded folders that originally had visible children.
1247 // If they become childless now they will be caught by filterChildlessParents()
1248 changedFiles
.append(newItem
);
1249 indexes
.append(indexForItem
);
1251 newFilteredIndexes
.append(indexForItem
);
1252 m_filteredItems
.insert(newItem
, itemData
);
1255 // Check if 'oldItem' is one of the filtered items.
1256 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1257 if (it
!= m_filteredItems
.end()) {
1258 ItemData
*const itemData
= it
.value();
1259 itemData
->item
= newItem
;
1261 // The data stored in 'values' might have changed. Therefore, we clear
1262 // 'values' and re-populate it the next time it is requested via data(int).
1263 // Before clearing, we must remember if it was expanded and the expanded parents count,
1264 // otherwise these states would be lost. The data() method will deal with this special case.
1265 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1266 bool hasExpandedParentsCount
= false;
1267 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1268 itemData
->values
.clear();
1270 itemData
->values
.insert("isExpanded", true);
1271 if (hasExpandedParentsCount
) {
1272 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1276 m_filteredItems
.erase(it
);
1277 if (newItemMatchesFilter
) {
1278 newVisibleItems
.append(itemData
);
1280 m_filteredItems
.insert(newItem
, itemData
);
1286 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1288 // We must keep track of parents of new visible items since they must be shown no matter what
1289 // They will be considered "immune" to filterChildlessParents()
1290 QSet
<ItemData
*> parentsToEnsureVisible
;
1292 for (ItemData
*item
: newVisibleItems
) {
1293 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1294 parentsToEnsureVisible
.insert(parent
);
1297 for (ItemData
*parent
: parentsToEnsureVisible
) {
1298 // We make sure they are all unfiltered.
1299 if (m_filteredItems
.remove(parent
->item
)) {
1300 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1301 newVisibleItems
.append(parent
);
1302 // It could be in newFilteredIndexes, we must remove it if it's there:
1303 const int parentIndex
= index(parent
->item
);
1304 if (parentIndex
>= 0) {
1305 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1306 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1307 newFilteredIndexes
.erase(it
);
1313 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1315 // This call will update itemRanges to include the childless parents that have been filtered.
1316 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1318 removeItems(removedRanges
, KeepItemData
);
1320 // Show previously hidden items that should get visible
1321 insertItems(newVisibleItems
);
1323 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1325 // If the changed items have been created recently, they might not be in m_items yet.
1326 // In that case, the list 'indexes' might be empty.
1327 if (indexes
.isEmpty()) {
1331 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1332 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1334 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1335 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1336 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1337 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1342 std::sort(indexes
.begin(), indexes
.end());
1345 // Extract the item-ranges out of the changed indexes
1346 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1347 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1349 Q_EMIT
fileItemsChanged(changedFiles
);
1352 void KFileItemModel::slotClear()
1354 #ifdef KFILEITEMMODEL_DEBUG
1355 qCDebug(DolphinDebug
) << "Clearing all items";
1358 qDeleteAll(m_filteredItems
);
1359 m_filteredItems
.clear();
1362 m_maximumUpdateIntervalTimer
->stop();
1363 m_resortAllItemsTimer
->stop();
1365 qDeleteAll(m_pendingItemsToInsert
);
1366 m_pendingItemsToInsert
.clear();
1368 const int removedCount
= m_itemData
.count();
1369 if (removedCount
> 0) {
1370 qDeleteAll(m_itemData
);
1373 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1376 m_expandedDirs
.clear();
1379 void KFileItemModel::slotSortingChoiceChanged()
1381 loadSortingSettings();
1385 void KFileItemModel::dispatchPendingItemsToInsert()
1387 if (!m_pendingItemsToInsert
.isEmpty()) {
1388 insertItems(m_pendingItemsToInsert
);
1389 m_pendingItemsToInsert
.clear();
1393 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1395 if (newItems
.isEmpty()) {
1399 #ifdef KFILEITEMMODEL_DEBUG
1400 QElapsedTimer timer
;
1402 qCDebug(DolphinDebug
) << "===========================================================";
1403 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1407 prepareItemsForSorting(newItems
);
1409 // Natural sorting of items can be very slow. However, it becomes much faster
1410 // if the input sequence is already mostly sorted. Therefore, we first sort
1411 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1412 if (m_naturalSorting
) {
1413 if (m_sortRole
== NameRole
) {
1414 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1415 } else if (isRoleValueNatural(m_sortRole
)) {
1416 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1418 const QByteArray role
= roleForType(m_sortRole
);
1419 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1421 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1425 sort(newItems
.begin(), newItems
.end());
1427 #ifdef KFILEITEMMODEL_DEBUG
1428 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1431 KItemRangeList itemRanges
;
1432 const int existingItemCount
= m_itemData
.count();
1433 const int newItemCount
= newItems
.count();
1434 const int totalItemCount
= existingItemCount
+ newItemCount
;
1436 if (existingItemCount
== 0) {
1437 // Optimization for the common special case that there are no
1438 // items in the model yet. Happens, e.g., when entering a folder.
1439 m_itemData
= newItems
;
1440 itemRanges
<< KItemRange(0, newItemCount
);
1442 m_itemData
.reserve(totalItemCount
);
1443 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1444 m_itemData
.append(nullptr);
1447 // We build the new list m_itemData in reverse order to minimize
1448 // the number of moves and guarantee O(N) complexity.
1449 int targetIndex
= totalItemCount
- 1;
1450 int sourceIndexExistingItems
= existingItemCount
- 1;
1451 int sourceIndexNewItems
= newItemCount
- 1;
1455 while (sourceIndexNewItems
>= 0) {
1456 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1457 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1458 // Move an existing item to its new position. If any new items
1459 // are behind it, push the item range to itemRanges.
1460 if (rangeCount
> 0) {
1461 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1465 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1466 --sourceIndexExistingItems
;
1468 // Insert a new item into the list.
1470 m_itemData
[targetIndex
] = newItem
;
1471 --sourceIndexNewItems
;
1476 // Push the final item range to itemRanges.
1477 if (rangeCount
> 0) {
1478 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1481 // Note that itemRanges is still sorted in reverse order.
1482 std::reverse(itemRanges
.begin(), itemRanges
.end());
1485 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1486 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1489 Q_EMIT
itemsInserted(itemRanges
);
1491 #ifdef KFILEITEMMODEL_DEBUG
1492 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1496 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1498 if (itemRanges
.isEmpty()) {
1504 // Step 1: Remove the items from m_itemData, and free the ItemData.
1505 int removedItemsCount
= 0;
1506 for (const KItemRange
& range
: itemRanges
) {
1507 removedItemsCount
+= range
.count
;
1509 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1510 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1511 delete m_itemData
.at(index
);
1514 m_itemData
[index
] = nullptr;
1518 // Step 2: Remove the ItemData pointers from the list m_itemData.
1519 int target
= itemRanges
.at(0).index
;
1520 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1523 const int oldItemDataCount
= m_itemData
.count();
1524 while (source
< oldItemDataCount
) {
1525 m_itemData
[target
] = m_itemData
[source
];
1529 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1530 // Skip the items in the next removed range.
1531 source
+= itemRanges
.at(nextRange
).count
;
1536 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1538 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1539 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1542 Q_EMIT
itemsRemoved(itemRanges
);
1545 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1547 if (m_sortRole
== TypeRole
) {
1548 // Try to resolve the MIME-types synchronously to prevent a reordering of
1549 // the items when sorting by type (per default MIME-types are resolved
1550 // asynchronously by KFileItemModelRolesUpdater).
1551 determineMimeTypes(items
, 200);
1554 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1555 const int parentIndex
= index(parentUrl
);
1556 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1558 QList
<ItemData
*> itemDataList
;
1559 itemDataList
.reserve(items
.count());
1561 for (const KFileItem
& item
: items
) {
1562 ItemData
* itemData
= new ItemData();
1563 itemData
->item
= item
;
1564 itemData
->parent
= parentItem
;
1565 itemDataList
.append(itemData
);
1568 return itemDataList
;
1571 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1573 switch (m_sortRole
) {
1574 case PermissionsRole
:
1577 case DestinationRole
:
1579 case DeletionTimeRole
:
1580 // These roles can be determined with retrieveData, and they have to be stored
1581 // in the QHash "values" for the sorting.
1582 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1583 if (itemData
->values
.isEmpty()) {
1584 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1590 // At least store the data including the file type for items with known MIME type.
1591 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1592 if (itemData
->values
.isEmpty()) {
1593 const KFileItem item
= itemData
->item
;
1594 if (item
.isDir() || item
.isMimeTypeKnown()) {
1595 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1602 // The other roles are either resolved by KFileItemModelRolesUpdater
1603 // (this includes the SizeRole for directories), or they do not need
1604 // to be stored in the QHash "values" for sorting because the data can
1605 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1611 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1613 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1614 // if the corresponding item is expanded, and it is not a top-level item.
1615 const ItemData
* parent
= data
->parent
;
1617 if (parent
->parent
) {
1618 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1619 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1628 void KFileItemModel::removeExpandedItems()
1630 QVector
<int> indexesToRemove
;
1632 const int maxIndex
= m_itemData
.count() - 1;
1633 for (int i
= 0; i
<= maxIndex
; ++i
) {
1634 const ItemData
* itemData
= m_itemData
.at(i
);
1635 if (itemData
->parent
) {
1636 indexesToRemove
.append(i
);
1640 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1641 m_expandedDirs
.clear();
1643 // Also remove all filtered items which have a parent.
1644 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1645 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1648 if (it
.value()->parent
) {
1650 it
= m_filteredItems
.erase(it
);
1657 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1659 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1661 // Trigger a resorting if necessary. Note that this can happen even if the sort
1662 // role has not changed at all because the file name can be used as a fallback.
1663 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1664 for (const KItemRange
& range
: itemRanges
) {
1665 bool needsResorting
= false;
1667 const int first
= range
.index
;
1668 const int last
= range
.index
+ range
.count
- 1;
1670 // Resorting the model is necessary if
1671 // (a) The first item in the range is "lessThan" its predecessor,
1672 // (b) the successor of the last item is "lessThan" the last item, or
1673 // (c) the internal order of the items in the range is incorrect.
1675 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1676 needsResorting
= true;
1677 } else if (last
< count() - 1
1678 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1679 needsResorting
= true;
1681 for (int index
= first
; index
< last
; ++index
) {
1682 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1683 needsResorting
= true;
1689 if (needsResorting
) {
1690 m_resortAllItemsTimer
->start();
1696 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1697 // The position is still correct, but the groups might have changed
1698 // if the changed item is either the first or the last item in a
1700 // In principle, we could try to find out if the item really is the
1701 // first or last one in its group and then update the groups
1702 // (possibly with a delayed timer to make sure that we don't
1703 // re-calculate the groups very often if items are updated one by
1704 // one), but starting m_resortAllItemsTimer is easier.
1705 m_resortAllItemsTimer
->start();
1709 void KFileItemModel::resetRoles()
1711 for (int i
= 0; i
< RolesCount
; ++i
) {
1712 m_requestRole
[i
] = false;
1716 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1718 static QHash
<QByteArray
, RoleType
> roles
;
1719 if (roles
.isEmpty()) {
1720 // Insert user visible roles that can be accessed with
1721 // KFileItemModel::roleInformation()
1723 const RoleInfoMap
* map
= rolesInfoMap(count
);
1724 for (int i
= 0; i
< count
; ++i
) {
1725 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1728 // Insert internal roles (take care to synchronize the implementation
1729 // with KFileItemModel::roleForType() in case if a change is done).
1730 roles
.insert("isDir", IsDirRole
);
1731 roles
.insert("isLink", IsLinkRole
);
1732 roles
.insert("isHidden", IsHiddenRole
);
1733 roles
.insert("isExpanded", IsExpandedRole
);
1734 roles
.insert("isExpandable", IsExpandableRole
);
1735 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1737 Q_ASSERT(roles
.count() == RolesCount
);
1740 return roles
.value(role
, NoRole
);
1743 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1745 static QHash
<RoleType
, QByteArray
> roles
;
1746 if (roles
.isEmpty()) {
1747 // Insert user visible roles that can be accessed with
1748 // KFileItemModel::roleInformation()
1750 const RoleInfoMap
* map
= rolesInfoMap(count
);
1751 for (int i
= 0; i
< count
; ++i
) {
1752 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1755 // Insert internal roles (take care to synchronize the implementation
1756 // with KFileItemModel::typeForRole() in case if a change is done).
1757 roles
.insert(IsDirRole
, "isDir");
1758 roles
.insert(IsLinkRole
, "isLink");
1759 roles
.insert(IsHiddenRole
, "isHidden");
1760 roles
.insert(IsExpandedRole
, "isExpanded");
1761 roles
.insert(IsExpandableRole
, "isExpandable");
1762 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1764 Q_ASSERT(roles
.count() == RolesCount
);
1767 return roles
.value(roleType
);
1770 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1772 // It is important to insert only roles that are fast to retrieve. E.g.
1773 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1774 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1775 QHash
<QByteArray
, QVariant
> data
;
1776 data
.insert(sharedValue("url"), item
.url());
1778 const bool isDir
= item
.isDir();
1779 if (m_requestRole
[IsDirRole
] && isDir
) {
1780 data
.insert(sharedValue("isDir"), true);
1783 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1784 data
.insert(sharedValue("isLink"), true);
1787 if (m_requestRole
[IsHiddenRole
]) {
1788 data
.insert(sharedValue("isHidden"), item
.isHidden());
1791 if (m_requestRole
[NameRole
]) {
1792 data
.insert(sharedValue("text"), item
.text());
1795 if (m_requestRole
[SizeRole
] && !isDir
) {
1796 data
.insert(sharedValue("size"), item
.size());
1799 if (m_requestRole
[ModificationTimeRole
]) {
1800 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1801 // having several thousands of items. Instead read the raw number from UDSEntry directly
1802 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1803 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1804 data
.insert(sharedValue("modificationtime"), dateTime
);
1807 if (m_requestRole
[CreationTimeRole
]) {
1808 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1809 // having several thousands of items. Instead read the raw number from UDSEntry directly
1810 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1811 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1812 data
.insert(sharedValue("creationtime"), dateTime
);
1815 if (m_requestRole
[AccessTimeRole
]) {
1816 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1817 // having several thousands of items. Instead read the raw number from UDSEntry directly
1818 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1819 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1820 data
.insert(sharedValue("accesstime"), dateTime
);
1823 if (m_requestRole
[PermissionsRole
]) {
1824 data
.insert(sharedValue("permissions"), item
.permissionsString());
1827 if (m_requestRole
[OwnerRole
]) {
1828 data
.insert(sharedValue("owner"), item
.user());
1831 if (m_requestRole
[GroupRole
]) {
1832 data
.insert(sharedValue("group"), item
.group());
1835 if (m_requestRole
[DestinationRole
]) {
1836 QString destination
= item
.linkDest();
1837 if (destination
.isEmpty()) {
1838 destination
= QLatin1Char('-');
1840 data
.insert(sharedValue("destination"), destination
);
1843 if (m_requestRole
[PathRole
]) {
1845 if (item
.url().scheme() == QLatin1String("trash")) {
1846 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1848 // For performance reasons cache the home-path in a static QString
1849 // (see QDir::homePath() for more details)
1850 static QString homePath
;
1851 if (homePath
.isEmpty()) {
1852 homePath
= QDir::homePath();
1855 path
= item
.localPath();
1856 if (path
.startsWith(homePath
)) {
1857 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1861 const int index
= path
.lastIndexOf(item
.text());
1862 path
= path
.mid(0, index
- 1);
1863 data
.insert(sharedValue("path"), path
);
1866 if (m_requestRole
[DeletionTimeRole
]) {
1867 QDateTime deletionTime
;
1868 if (item
.url().scheme() == QLatin1String("trash")) {
1869 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1871 data
.insert(sharedValue("deletiontime"), deletionTime
);
1874 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1875 data
.insert(sharedValue("isExpandable"), true);
1878 if (m_requestRole
[ExpandedParentsCountRole
]) {
1880 const int level
= expandedParentsCount(parent
) + 1;
1881 data
.insert(sharedValue("expandedParentsCount"), level
);
1885 if (item
.isMimeTypeKnown()) {
1886 QString iconName
= item
.iconName();
1887 if (!QIcon::hasThemeIcon(iconName
)) {
1888 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1889 iconName
= mimeType
.genericIconName();
1892 data
.insert(sharedValue("iconName"), iconName
);
1894 if (m_requestRole
[TypeRole
]) {
1895 data
.insert(sharedValue("type"), item
.mimeComment());
1897 } else if (m_requestRole
[TypeRole
] && isDir
) {
1898 static const QString folderMimeType
= item
.mimeComment();
1899 data
.insert(sharedValue("type"), folderMimeType
);
1905 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1909 if (a
->parent
!= b
->parent
) {
1910 const int expansionLevelA
= expandedParentsCount(a
);
1911 const int expansionLevelB
= expandedParentsCount(b
);
1913 // If b has a higher expansion level than a, check if a is a parent
1914 // of b, and make sure that both expansion levels are equal otherwise.
1915 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1916 if (b
->parent
== a
) {
1922 // If a has a higher expansion level than a, check if b is a parent
1923 // of a, and make sure that both expansion levels are equal otherwise.
1924 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1925 if (a
->parent
== b
) {
1931 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1933 // Compare the last parents of a and b which are different.
1934 while (a
->parent
!= b
->parent
) {
1940 // Show hidden files and folders last
1941 if (m_sortHiddenLast
) {
1942 const bool isHiddenA
= a
->item
.isHidden();
1943 const bool isHiddenB
= b
->item
.isHidden();
1944 if (isHiddenA
&& !isHiddenB
) {
1946 } else if (!isHiddenA
&& isHiddenB
) {
1951 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1952 const bool isDirA
= a
->item
.isDir();
1953 const bool isDirB
= b
->item
.isDir();
1954 if (isDirA
&& !isDirB
) {
1956 } else if (!isDirA
&& isDirB
) {
1961 result
= sortRoleCompare(a
, b
, collator
);
1963 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1966 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1967 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1969 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1971 return lessThan(a
, b
, m_collator
);
1974 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1975 // Sorting by string can be expensive, in particular if natural sorting is
1976 // enabled. Use all CPU cores to speed up the sorting process.
1977 static const int numberOfThreads
= QThread::idealThreadCount();
1978 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1980 // Sorting by other roles is quite fast. Use only one thread to prevent
1981 // problems caused by non-reentrant comparison functions, see
1982 // https://bugs.kde.org/show_bug.cgi?id=312679
1983 mergeSort(begin
, end
, lambdaLessThan
);
1987 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1989 // This function must never return 0, because that would break stable
1990 // sorting, which leads to all kinds of bugs.
1991 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1992 // If two items have equal sort values, let the fallbacks at the bottom of
1993 // the function handle it.
1994 const KFileItem
& itemA
= a
->item
;
1995 const KFileItem
& itemB
= b
->item
;
1999 switch (m_sortRole
) {
2001 // The name role is handled as default fallback after the switch
2005 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
2006 // folders first then
2007 // items A and B are folders thanks to lessThan checks
2008 auto valueA
= a
->values
.value("count");
2009 auto valueB
= b
->values
.value("count");
2010 if (valueA
.isNull()) {
2011 if (!valueB
.isNull()) {
2014 } else if (valueB
.isNull()) {
2017 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2019 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2026 KIO::filesize_t sizeA
= 0;
2027 if (itemA
.isDir()) {
2028 sizeA
= a
->values
.value("size").toULongLong();
2030 sizeA
= itemA
.size();
2032 KIO::filesize_t sizeB
= 0;
2033 if (itemB
.isDir()) {
2034 sizeB
= b
->values
.value("size").toULongLong();
2036 sizeB
= itemB
.size();
2038 if (sizeA
< sizeB
) {
2040 } else if (sizeA
> sizeB
) {
2046 case ModificationTimeRole
: {
2047 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2048 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2049 if (dateTimeA
< dateTimeB
) {
2051 } else if (dateTimeA
> dateTimeB
) {
2057 case CreationTimeRole
: {
2058 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2059 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2060 if (dateTimeA
< dateTimeB
) {
2062 } else if (dateTimeA
> dateTimeB
) {
2068 case DeletionTimeRole
: {
2069 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2070 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2071 if (dateTimeA
< dateTimeB
) {
2073 } else if (dateTimeA
> dateTimeB
) {
2085 case ReleaseYearRole
: {
2086 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2091 const QByteArray role
= roleForType(m_sortRole
);
2092 const QString roleValueA
= a
->values
.value(role
).toString();
2093 const QString roleValueB
= b
->values
.value(role
).toString();
2094 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2096 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2098 } else if (isRoleValueNatural(m_sortRole
)) {
2099 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2101 result
= QString::compare(roleValueA
, roleValueB
);
2109 // The current sort role was sufficient to define an order
2113 // Fallback #1: Compare the text of the items
2114 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2119 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2120 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2125 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2126 // equal. In this case a comparison of the URL is done which is unique in all cases
2127 // within KDirLister.
2128 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2131 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
2133 QMutexLocker
collatorLock(s_collatorMutex());
2135 if (m_naturalSorting
) {
2136 return collator
.compare(a
, b
);
2139 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2140 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2141 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2142 // comparison, still a deterministic sort order is required. A case sensitive
2143 // comparison is done as fallback.
2147 return QString::compare(a
, b
, Qt::CaseSensitive
);
2150 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
2152 Q_ASSERT(!m_itemData
.isEmpty());
2154 const int maxIndex
= count() - 1;
2155 QList
<QPair
<int, QVariant
> > groups
;
2159 for (int i
= 0; i
<= maxIndex
; ++i
) {
2160 if (isChildItem(i
)) {
2164 const QString name
= m_itemData
.at(i
)->item
.text();
2166 // Use the first character of the name as group indication
2167 QChar newFirstChar
= name
.at(0).toUpper();
2168 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2169 newFirstChar
= name
.at(1).toUpper();
2172 if (firstChar
!= newFirstChar
) {
2173 QString newGroupValue
;
2174 if (newFirstChar
.isLetter()) {
2176 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2177 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2179 // Try to find a matching group in the range 'A' to 'Z'.
2180 static std::vector
<QChar
> lettersAtoZ
;
2181 lettersAtoZ
.reserve('Z' - 'A' + 1);
2182 if (lettersAtoZ
.empty()) {
2183 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2184 lettersAtoZ
.push_back(QLatin1Char(c
));
2188 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2189 return m_collator
.compare(c1
, c2
) < 0;
2192 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2193 if (it
!= lettersAtoZ
.end()) {
2194 if (localeAwareLessThan(newFirstChar
, *it
)) {
2195 // newFirstChar belongs to the group preceding *it.
2196 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2199 newGroupValue
= *it
;
2203 // Symbols from non Latin-based scripts
2204 newGroupValue
= newFirstChar
;
2206 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2207 // Apply group '0 - 9' for any name that starts with a digit
2208 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2210 newGroupValue
= i18nc("@title:group", "Others");
2213 if (newGroupValue
!= groupValue
) {
2214 groupValue
= newGroupValue
;
2215 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2218 firstChar
= newFirstChar
;
2224 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2226 Q_ASSERT(!m_itemData
.isEmpty());
2228 const int maxIndex
= count() - 1;
2229 QList
<QPair
<int, QVariant
> > groups
;
2232 for (int i
= 0; i
<= maxIndex
; ++i
) {
2233 if (isChildItem(i
)) {
2237 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2238 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2239 QString newGroupValue
;
2240 if (!item
.isNull() && item
.isDir()) {
2241 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2242 newGroupValue
= i18nc("@title:group Size", "Folders");
2244 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2248 if (newGroupValue
.isEmpty()) {
2249 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2250 newGroupValue
= i18nc("@title:group Size", "Small");
2251 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2252 newGroupValue
= i18nc("@title:group Size", "Medium");
2254 newGroupValue
= i18nc("@title:group Size", "Big");
2258 if (newGroupValue
!= groupValue
) {
2259 groupValue
= newGroupValue
;
2260 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2267 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2269 Q_ASSERT(!m_itemData
.isEmpty());
2271 const int maxIndex
= count() - 1;
2272 QList
<QPair
<int, QVariant
> > groups
;
2274 const QDate currentDate
= QDate::currentDate();
2276 QDate previousFileDate
;
2278 for (int i
= 0; i
<= maxIndex
; ++i
) {
2279 if (isChildItem(i
)) {
2283 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2284 const QDate fileDate
= fileTime
.date();
2285 if (fileDate
== previousFileDate
) {
2286 // The current item is in the same group as the previous item
2289 previousFileDate
= fileDate
;
2291 const int daysDistance
= fileDate
.daysTo(currentDate
);
2293 QString newGroupValue
;
2294 if (currentDate
.year() == fileDate
.year() &&
2295 currentDate
.month() == fileDate
.month()) {
2297 switch (daysDistance
/ 7) {
2299 switch (daysDistance
) {
2300 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2301 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2303 newGroupValue
= fileTime
.toString(
2304 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2305 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2306 "with context @title:group Date", "%1", newGroupValue
);
2310 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2313 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2316 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2320 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2326 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2327 if (lastMonthDate
.year() == fileDate
.year() &&
2328 lastMonthDate
.month() == fileDate
.month()) {
2330 if (daysDistance
== 1) {
2331 const KLocalizedString format
= ki18nc("@title:group Date: "
2332 "MMMM is full month name in current locale, and yyyy is "
2333 "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)");
2334 const QString translatedFormat
= format
.toString();
2335 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2336 newGroupValue
= fileTime
.toString(translatedFormat
);
2337 newGroupValue
= i18nc("Can be used to script translation of "
2338 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2339 "%1", newGroupValue
);
2341 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2342 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2343 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2345 } else if (daysDistance
<= 7) {
2346 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2347 "The week day name: dddd, MMMM is full month name "
2348 "in current locale, and yyyy is full year number.",
2349 "dddd (MMMM, yyyy)"));
2350 newGroupValue
= i18nc("Can be used to script translation of "
2351 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2352 "%1", newGroupValue
);
2353 } else if (daysDistance
<= 7 * 2) {
2354 const KLocalizedString format
= ki18nc("@title:group Date: "
2355 "MMMM is full month name in current locale, and yyyy is "
2356 "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)");
2357 const QString translatedFormat
= format
.toString();
2358 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2359 newGroupValue
= fileTime
.toString(translatedFormat
);
2360 newGroupValue
= i18nc("Can be used to script translation of "
2361 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2362 "%1", newGroupValue
);
2364 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2365 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2366 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2368 } else if (daysDistance
<= 7 * 3) {
2369 const KLocalizedString format
= ki18nc("@title:group Date: "
2370 "MMMM is full month name in current locale, and yyyy is "
2371 "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)");
2372 const QString translatedFormat
= format
.toString();
2373 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2374 newGroupValue
= fileTime
.toString(translatedFormat
);
2375 newGroupValue
= i18nc("Can be used to script translation of "
2376 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2377 "%1", newGroupValue
);
2379 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2380 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2381 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2383 } else if (daysDistance
<= 7 * 4) {
2384 const KLocalizedString format
= ki18nc("@title:group Date: "
2385 "MMMM is full month name in current locale, and yyyy is "
2386 "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)");
2387 const QString translatedFormat
= format
.toString();
2388 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2389 newGroupValue
= fileTime
.toString(translatedFormat
);
2390 newGroupValue
= i18nc("Can be used to script translation of "
2391 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2392 "%1", newGroupValue
);
2394 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2395 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2396 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2399 const KLocalizedString format
= ki18nc("@title:group Date: "
2400 "MMMM is full month name in current locale, and yyyy is "
2401 "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");
2402 const QString translatedFormat
= format
.toString();
2403 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2404 newGroupValue
= fileTime
.toString(translatedFormat
);
2405 newGroupValue
= i18nc("Can be used to script translation of "
2406 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2407 "%1", newGroupValue
);
2409 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2410 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2411 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2415 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2416 "The month and year: MMMM is full month name in current locale, "
2417 "and yyyy is full year number", "MMMM, yyyy"));
2418 newGroupValue
= i18nc("Can be used to script translation of "
2419 "\"MMMM, yyyy\" with context @title:group Date",
2420 "%1", newGroupValue
);
2424 if (newGroupValue
!= groupValue
) {
2425 groupValue
= newGroupValue
;
2426 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2433 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2435 Q_ASSERT(!m_itemData
.isEmpty());
2437 const int maxIndex
= count() - 1;
2438 QList
<QPair
<int, QVariant
> > groups
;
2440 QString permissionsString
;
2442 for (int i
= 0; i
<= maxIndex
; ++i
) {
2443 if (isChildItem(i
)) {
2447 const ItemData
* itemData
= m_itemData
.at(i
);
2448 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2449 if (newPermissionsString
== permissionsString
) {
2452 permissionsString
= newPermissionsString
;
2454 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2458 if (info
.permission(QFile::ReadUser
)) {
2459 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2461 if (info
.permission(QFile::WriteUser
)) {
2462 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2464 if (info
.permission(QFile::ExeUser
)) {
2465 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2467 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2471 if (info
.permission(QFile::ReadGroup
)) {
2472 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2474 if (info
.permission(QFile::WriteGroup
)) {
2475 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2477 if (info
.permission(QFile::ExeGroup
)) {
2478 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2480 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2482 // Set others string
2484 if (info
.permission(QFile::ReadOther
)) {
2485 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2487 if (info
.permission(QFile::WriteOther
)) {
2488 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2490 if (info
.permission(QFile::ExeOther
)) {
2491 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2493 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2495 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2496 if (newGroupValue
!= groupValue
) {
2497 groupValue
= newGroupValue
;
2498 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2505 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2507 Q_ASSERT(!m_itemData
.isEmpty());
2509 const int maxIndex
= count() - 1;
2510 QList
<QPair
<int, QVariant
> > groups
;
2512 int groupValue
= -1;
2513 for (int i
= 0; i
<= maxIndex
; ++i
) {
2514 if (isChildItem(i
)) {
2517 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2518 if (newGroupValue
!= groupValue
) {
2519 groupValue
= newGroupValue
;
2520 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2527 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2529 Q_ASSERT(!m_itemData
.isEmpty());
2531 const int maxIndex
= count() - 1;
2532 QList
<QPair
<int, QVariant
> > groups
;
2534 bool isFirstGroupValue
= true;
2536 for (int i
= 0; i
<= maxIndex
; ++i
) {
2537 if (isChildItem(i
)) {
2540 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2541 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2542 groupValue
= newGroupValue
;
2543 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2544 isFirstGroupValue
= false;
2551 void KFileItemModel::emitSortProgress(int resolvedCount
)
2553 // Be tolerant against a resolvedCount with a wrong range.
2554 // Although there should not be a case where KFileItemModelRolesUpdater
2555 // (= caller) provides a wrong range, it is important to emit
2556 // a useful progress information even if there is an unexpected
2557 // implementation issue.
2559 const int itemCount
= count();
2560 if (resolvedCount
>= itemCount
) {
2561 m_sortingProgressPercent
= -1;
2562 if (m_resortAllItemsTimer
->isActive()) {
2563 m_resortAllItemsTimer
->stop();
2567 Q_EMIT
directorySortingProgress(100);
2568 } else if (itemCount
> 0) {
2569 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2571 const int progress
= resolvedCount
* 100 / itemCount
;
2572 if (m_sortingProgressPercent
!= progress
) {
2573 m_sortingProgressPercent
= progress
;
2574 Q_EMIT
directorySortingProgress(progress
);
2579 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2581 static const RoleInfoMap rolesInfoMap
[] = {
2582 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2583 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2584 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2585 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2586 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2587 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2588 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2589 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2590 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2591 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2592 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2593 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2594 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2595 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2596 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2597 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2598 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2599 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2600 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2601 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2602 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2603 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2604 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2605 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2606 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2607 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2608 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2609 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2610 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2611 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2612 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2613 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2614 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2615 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2618 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2619 return rolesInfoMap
;
2622 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2624 QElapsedTimer timer
;
2626 for (const KFileItem
& item
: items
) {
2627 // Only determine mime types for files here. For directories,
2628 // KFileItem::determineMimeType() reads the .directory file inside to
2629 // load the icon, but this is not necessary at all if we just need the
2630 // type. Some special code for setting the correct mime type for
2631 // directories is in retrieveData().
2632 if (!item
.isDir()) {
2633 item
.determineMimeType();
2636 if (timer
.elapsed() > timeout
) {
2637 // Don't block the user interface, let the remaining items
2638 // be resolved asynchronously.
2644 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2646 static QSet
<QByteArray
> pool
;
2647 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2649 if (it
!= pool
.constEnd()) {
2657 bool KFileItemModel::isConsistent() const
2659 // m_items may contain less items than m_itemData because m_items
2660 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2661 if (m_items
.count() > m_itemData
.count()) {
2665 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2666 // Check if m_items and m_itemData are consistent.
2667 const KFileItem item
= fileItem(i
);
2668 if (item
.isNull()) {
2669 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2673 const int itemIndex
= index(item
);
2674 if (itemIndex
!= i
) {
2675 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2679 // Check if the items are sorted correctly.
2680 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2681 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2682 << fileItem(i
- 1) << fileItem(i
);
2686 // Check if all parent-child relationships are consistent.
2687 const ItemData
* data
= m_itemData
.at(i
);
2688 const ItemData
* parent
= data
->parent
;
2690 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2691 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2695 const int parentIndex
= index(parent
->item
);
2696 if (parentIndex
>= i
) {
2697 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2706 void KFileItemModel::slotListerError(KIO::Job
*job
)
2708 if (job
->error() == KIO::ERR_IS_FILE
) {
2709 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2710 Q_EMIT
urlIsFileError(listJob
->url());
2713 const QString errorString
= job
->errorString();
2714 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));