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 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
31 // #define KFILEITEMMODEL_DEBUG
33 KFileItemModel::KFileItemModel(QObject
* parent
) :
34 KItemModelBase("text", parent
),
36 m_sortDirsFirst(true),
37 m_sortHiddenLast(false),
39 m_sortingProgressPercent(-1),
46 m_maximumUpdateIntervalTimer(nullptr),
47 m_resortAllItemsTimer(nullptr),
48 m_pendingItemsToInsert(),
53 m_collator
.setNumericMode(true);
55 loadSortingSettings();
57 m_dirLister
= new KDirLister(this);
58 m_dirLister
->setAutoErrorHandlingEnabled(false);
59 m_dirLister
->setDelayedMimeTypes(true);
61 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
63 m_dirLister
->setMainWindow(parentWidget
->window());
66 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
67 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
68 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
69 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
70 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
71 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
72 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
73 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
74 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
75 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
76 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
78 // Apply default roles that should be determined
80 m_requestRole
[NameRole
] = true;
81 m_requestRole
[IsDirRole
] = true;
82 m_requestRole
[IsLinkRole
] = true;
83 m_roles
.insert("text");
84 m_roles
.insert("isDir");
85 m_roles
.insert("isLink");
86 m_roles
.insert("isHidden");
88 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
89 // before the completed() or canceled() signal has been emitted.
90 m_maximumUpdateIntervalTimer
= new QTimer(this);
91 m_maximumUpdateIntervalTimer
->setInterval(2000);
92 m_maximumUpdateIntervalTimer
->setSingleShot(true);
93 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
95 // When changing the value of an item which represents the sort-role a resorting must be
96 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
97 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
98 // resorting is postponed until the timer has been exceeded.
99 m_resortAllItemsTimer
= new QTimer(this);
100 m_resortAllItemsTimer
->setInterval(500);
101 m_resortAllItemsTimer
->setSingleShot(true);
102 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
104 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
107 KFileItemModel::~KFileItemModel()
109 qDeleteAll(m_itemData
);
110 qDeleteAll(m_filteredItems
);
111 qDeleteAll(m_pendingItemsToInsert
);
114 void KFileItemModel::loadDirectory(const QUrl
&url
)
116 m_dirLister
->openUrl(url
);
119 void KFileItemModel::refreshDirectory(const QUrl
&url
)
121 // Refresh all expanded directories first (Bug 295300)
122 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
123 while (expandedDirs
.hasNext()) {
125 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
128 m_dirLister
->openUrl(url
, KDirLister::Reload
);
131 QUrl
KFileItemModel::directory() const
133 return m_dirLister
->url();
136 void KFileItemModel::cancelDirectoryLoading()
141 int KFileItemModel::count() const
143 return m_itemData
.count();
146 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
148 if (index
>= 0 && index
< count()) {
149 ItemData
* data
= m_itemData
.at(index
);
150 if (data
->values
.isEmpty()) {
151 data
->values
= retrieveData(data
->item
, data
->parent
);
156 return QHash
<QByteArray
, QVariant
>();
159 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
161 if (index
< 0 || index
>= count()) {
165 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
167 // Determine which roles have been changed
168 QSet
<QByteArray
> changedRoles
;
169 QHashIterator
<QByteArray
, QVariant
> it(values
);
170 while (it
.hasNext()) {
172 const QByteArray role
= sharedValue(it
.key());
173 const QVariant value
= it
.value();
175 if (currentValues
[role
] != value
) {
176 currentValues
[role
] = value
;
177 changedRoles
.insert(role
);
181 if (changedRoles
.isEmpty()) {
185 m_itemData
[index
]->values
= currentValues
;
186 if (changedRoles
.contains("text")) {
187 QUrl url
= m_itemData
[index
]->item
.url();
188 url
= url
.adjusted(QUrl::RemoveFilename
);
189 url
.setPath(url
.path() + currentValues
["text"].toString());
190 m_itemData
[index
]->item
.setUrl(url
);
193 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
198 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
200 if (dirsFirst
!= m_sortDirsFirst
) {
201 m_sortDirsFirst
= dirsFirst
;
206 bool KFileItemModel::sortDirectoriesFirst() const
208 return m_sortDirsFirst
;
211 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
213 if (hiddenLast
!= m_sortHiddenLast
) {
214 m_sortHiddenLast
= hiddenLast
;
219 bool KFileItemModel::sortHiddenLast() const
221 return m_sortHiddenLast
;
224 void KFileItemModel::setShowHiddenFiles(bool show
)
226 m_dirLister
->setShowingDotFiles(show
);
227 m_dirLister
->emitChanges();
229 dispatchPendingItemsToInsert();
233 bool KFileItemModel::showHiddenFiles() const
235 return m_dirLister
->showingDotFiles();
238 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
240 m_dirLister
->setDirOnlyMode(enabled
);
243 bool KFileItemModel::showDirectoriesOnly() const
245 return m_dirLister
->dirOnlyMode();
248 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
250 QMimeData
* data
= new QMimeData();
252 // The following code has been taken from KDirModel::mimeData()
253 // (kdelibs/kio/kio/kdirmodel.cpp)
254 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
256 QList
<QUrl
> mostLocalUrls
;
257 const ItemData
* lastAddedItem
= nullptr;
259 for (int index
: indexes
) {
260 const ItemData
* itemData
= m_itemData
.at(index
);
261 const ItemData
* parent
= itemData
->parent
;
263 while (parent
&& parent
!= lastAddedItem
) {
264 parent
= parent
->parent
;
267 if (parent
&& parent
== lastAddedItem
) {
268 // A parent of 'itemData' has been added already.
272 lastAddedItem
= itemData
;
273 const KFileItem
& item
= itemData
->item
;
274 if (!item
.isNull()) {
278 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
282 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
286 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
288 startFromIndex
= qMax(0, startFromIndex
);
289 for (int i
= startFromIndex
; i
< count(); ++i
) {
290 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
294 for (int i
= 0; i
< startFromIndex
; ++i
) {
295 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
302 bool KFileItemModel::supportsDropping(int index
) const
304 const KFileItem item
= fileItem(index
);
305 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
308 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
310 static QHash
<QByteArray
, QString
> description
;
311 if (description
.isEmpty()) {
313 const RoleInfoMap
* map
= rolesInfoMap(count
);
314 for (int i
= 0; i
< count
; ++i
) {
315 if (!map
[i
].roleTranslation
) {
318 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
322 return description
.value(role
);
325 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
327 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
328 #ifdef KFILEITEMMODEL_DEBUG
332 switch (typeForRole(sortRole())) {
333 case NameRole
: m_groups
= nameRoleGroups(); break;
334 case SizeRole
: m_groups
= sizeRoleGroups(); break;
335 case ModificationTimeRole
:
336 m_groups
= timeRoleGroups([](const ItemData
*item
) {
337 return item
->item
.time(KFileItem::ModificationTime
);
340 case CreationTimeRole
:
341 m_groups
= timeRoleGroups([](const ItemData
*item
) {
342 return item
->item
.time(KFileItem::CreationTime
);
346 m_groups
= timeRoleGroups([](const ItemData
*item
) {
347 return item
->item
.time(KFileItem::AccessTime
);
350 case DeletionTimeRole
:
351 m_groups
= timeRoleGroups([](const ItemData
*item
) {
352 return item
->values
.value("deletiontime").toDateTime();
355 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
356 case RatingRole
: m_groups
= ratingRoleGroups(); break;
357 default: m_groups
= genericStringRoleGroups(sortRole()); break;
360 #ifdef KFILEITEMMODEL_DEBUG
361 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
368 KFileItem
KFileItemModel::fileItem(int index
) const
370 if (index
>= 0 && index
< count()) {
371 return m_itemData
.at(index
)->item
;
377 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
379 const int indexForUrl
= index(url
);
380 if (indexForUrl
>= 0) {
381 return m_itemData
.at(indexForUrl
)->item
;
386 int KFileItemModel::index(const KFileItem
& item
) const
388 return index(item
.url());
391 int KFileItemModel::index(const QUrl
& url
) const
393 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
395 const int itemCount
= m_itemData
.count();
396 int itemsInHash
= m_items
.count();
398 int index
= m_items
.value(urlToFind
, -1);
399 while (index
< 0 && itemsInHash
< itemCount
) {
400 // Not all URLs are stored yet in m_items. We grow m_items until either
401 // urlToFind is found, or all URLs have been stored in m_items.
402 // Note that we do not add the URLs to m_items one by one, but in
403 // larger blocks. After each block, we check if urlToFind is in
404 // m_items. We could in principle compare urlToFind with each URL while
405 // we are going through m_itemData, but comparing two QUrls will,
406 // unlike calling qHash for the URLs, trigger a parsing of the URLs
407 // which costs both CPU cycles and memory.
408 const int blockSize
= 1000;
409 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
410 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
411 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
412 m_items
.insert(nextUrl
, i
);
415 itemsInHash
= currentBlockEnd
;
416 index
= m_items
.value(urlToFind
, -1);
420 // The item could not be found, even though all items from m_itemData
421 // should be in m_items now. We print some diagnostic information which
422 // might help to find the cause of the problem, but only once. This
423 // prevents that obtaining and printing the debugging information
424 // wastes CPU cycles and floods the shell or .xsession-errors.
425 static bool printDebugInfo
= true;
427 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
428 printDebugInfo
= false;
430 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
431 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
432 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
434 // Check if there are multiple items with the same URL.
435 QMultiHash
<QUrl
, int> indexesForUrl
;
436 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
437 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
440 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
441 for (const QUrl
& url
: uniqueKeys
) {
442 if (indexesForUrl
.count(url
) > 1) {
443 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
445 auto it
= indexesForUrl
.find(url
);
446 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
447 const ItemData
* data
= m_itemData
.at(it
.value());
448 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
450 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
462 KFileItem
KFileItemModel::rootItem() const
464 return m_dirLister
->rootItem();
467 void KFileItemModel::clear()
472 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
474 if (m_roles
== roles
) {
478 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
482 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
483 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
484 if (supportedExpanding
&& !willSupportExpanding
) {
485 // No expanding is supported anymore. Take care to delete all items that have an expansion level
486 // that is not 0 (and hence are part of an expanded item).
487 removeExpandedItems();
494 QSetIterator
<QByteArray
> it(roles
);
495 while (it
.hasNext()) {
496 const QByteArray
& role
= it
.next();
497 m_requestRole
[typeForRole(role
)] = true;
501 // Update m_data with the changed requested roles
502 const int maxIndex
= count() - 1;
503 for (int i
= 0; i
<= maxIndex
; ++i
) {
504 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
507 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
510 // Clear the 'values' of all filtered items. They will be re-populated with the
511 // correct roles the next time 'values' will be accessed via data(int).
512 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
513 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
514 while (filteredIt
!= filteredEnd
) {
515 (*filteredIt
)->values
.clear();
520 QSet
<QByteArray
> KFileItemModel::roles() const
525 bool KFileItemModel::setExpanded(int index
, bool expanded
)
527 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
531 QHash
<QByteArray
, QVariant
> values
;
532 values
.insert(sharedValue("isExpanded"), expanded
);
533 if (!setData(index
, values
)) {
537 const KFileItem item
= m_itemData
.at(index
)->item
;
538 const QUrl url
= item
.url();
539 const QUrl targetUrl
= item
.targetUrl();
541 m_expandedDirs
.insert(targetUrl
, url
);
542 m_dirLister
->openUrl(url
, KDirLister::Keep
);
544 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
545 for (const QVariant
& var
: previouslyExpandedChildren
) {
546 m_urlsToExpand
.insert(var
.toUrl());
549 // Note that there might be (indirect) children of the folder which is to be collapsed in
550 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
551 // possibly without a parent, which might result in a crash, we insert all pending items
552 // right now. All new items which would be without a parent will then be removed.
553 dispatchPendingItemsToInsert();
555 // Check if the index of the collapsed folder has changed. If that is the case, then items
556 // were inserted before the collapsed folder, and its index needs to be updated.
557 if (m_itemData
.at(index
)->item
!= item
) {
558 index
= this->index(item
);
561 m_expandedDirs
.remove(targetUrl
);
562 m_dirLister
->stop(url
);
564 const int parentLevel
= expandedParentsCount(index
);
565 const int itemCount
= m_itemData
.count();
566 const int firstChildIndex
= index
+ 1;
568 QVariantList expandedChildren
;
570 int childIndex
= firstChildIndex
;
571 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
572 ItemData
* itemData
= m_itemData
.at(childIndex
);
573 if (itemData
->values
.value("isExpanded").toBool()) {
574 const QUrl targetUrl
= itemData
->item
.targetUrl();
575 const QUrl url
= itemData
->item
.url();
576 m_expandedDirs
.remove(targetUrl
);
577 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
578 expandedChildren
.append(targetUrl
);
582 const int childrenCount
= childIndex
- firstChildIndex
;
584 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
585 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
587 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
593 bool KFileItemModel::isExpanded(int index
) const
595 if (index
>= 0 && index
< count()) {
596 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
601 bool KFileItemModel::isExpandable(int index
) const
603 if (index
>= 0 && index
< count()) {
604 // Call data (instead of accessing m_itemData directly)
605 // to ensure that the value is initialized.
606 return data(index
).value("isExpandable").toBool();
611 int KFileItemModel::expandedParentsCount(int index
) const
613 if (index
>= 0 && index
< count()) {
614 return expandedParentsCount(m_itemData
.at(index
));
619 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
622 const auto dirs
= m_expandedDirs
;
623 for (const auto &dir
: dirs
) {
629 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
631 m_urlsToExpand
= urls
;
634 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
637 // Assure that each sub-path of the URL that should be
638 // expanded is added to m_urlsToExpand. KDirLister
639 // does not care whether the parent-URL has already been
641 QUrl urlToExpand
= m_dirLister
->url();
642 const int pos
= urlToExpand
.path().length();
644 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
645 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
646 // so using QString::SkipEmptyParts
647 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
648 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
649 QString path
= urlToExpand
.path();
650 if (!path
.endsWith(QLatin1Char('/'))) {
651 path
.append(QLatin1Char('/'));
653 urlToExpand
.setPath(path
+ subDirs
.at(i
));
654 m_urlsToExpand
.insert(urlToExpand
);
657 // KDirLister::open() must called at least once to trigger an initial
658 // loading. The pending URLs that must be restored are handled
659 // in slotCompleted().
660 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
661 while (it2
.hasNext()) {
662 const int idx
= index(it2
.next());
663 if (idx
>= 0 && !isExpanded(idx
)) {
664 setExpanded(idx
, true);
670 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
672 if (m_filter
.pattern() != nameFilter
) {
673 dispatchPendingItemsToInsert();
674 m_filter
.setPattern(nameFilter
);
679 QString
KFileItemModel::nameFilter() const
681 return m_filter
.pattern();
684 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
686 if (m_filter
.mimeTypes() != filters
) {
687 dispatchPendingItemsToInsert();
688 m_filter
.setMimeTypes(filters
);
693 QStringList
KFileItemModel::mimeTypeFilters() const
695 return m_filter
.mimeTypes();
698 void KFileItemModel::applyFilters()
701 // Check which previously shown items from m_itemData must now get
702 // hidden and hence moved from m_itemData into m_filteredItems.
704 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
706 // This pointer will refer to the next confirmed shown item from the point of
707 // view of the current "itemData" in the upcoming "for" loop.
708 ItemData
*itemShownBelow
= nullptr;
710 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
711 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
712 ItemData
*itemData
= m_itemData
.at(index
);
714 if (m_filter
.matches(itemData
->item
)
715 || (itemShownBelow
&& itemShownBelow
->parent
== itemData
&& itemData
->values
.value("isExpanded").toBool())) {
716 // We could've entered here for two reasons:
717 // 1. This item passes the filter itself
718 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
720 // So this item must remain shown.
721 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
722 itemShownBelow
= itemData
;
724 // We hide this item for now, however, for expanded folders this is not final:
725 // 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
726 newFilteredIndexes
.prepend(index
);
727 m_filteredItems
.insert(itemData
->item
, itemData
);
728 // indexShownBelow doesn't get updated since this item will be hidden
732 // This will remove the newly filtered items from m_itemData
733 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
736 // Check which hidden items from m_filteredItems should
737 // become visible again and hence moved from m_filteredItems back into m_itemData.
739 QList
<ItemData
*> newVisibleItems
;
741 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
743 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
744 while (it
!= m_filteredItems
.end()) {
745 if (m_filter
.matches(it
.key())) {
746 newVisibleItems
.append(it
.value());
748 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
749 // We will go up through its parental chain until we either:
750 // 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.
752 // 2 - we reach an unfiltered parent or a previously discovered ancestor.
753 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
754 parent
= parent
->parent
) {
755 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
756 // and it would mess up the iteration. We will mark it to be removed in step 3.
757 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
760 it
= m_filteredItems
.erase(it
);
762 // Item remains filtered for now
763 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
769 // Handles the ancestorsOfNewVisibleItems.
770 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
771 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
772 if (m_filteredItems
.remove(it
.key())) {
773 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
774 newVisibleItems
.append(it
.value());
778 // This will insert the newly discovered unfiltered items into m_itemData
779 insertItems(newVisibleItems
);
782 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
784 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
785 // There are either no filtered items, or it is not possible to expand
786 // folders -> there cannot be any filtered children.
790 QSet
<ItemData
*> parents
;
791 for (const KItemRange
& range
: itemRanges
) {
792 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
793 parents
.insert(m_itemData
.at(index
));
797 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
798 while (it
!= m_filteredItems
.end()) {
799 if (parents
.contains(it
.value()->parent
)) {
801 it
= m_filteredItems
.erase(it
);
808 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
810 static QList
<RoleInfo
> rolesInfo
;
811 if (rolesInfo
.isEmpty()) {
813 const RoleInfoMap
* map
= rolesInfoMap(count
);
814 for (int i
= 0; i
< count
; ++i
) {
815 if (map
[i
].roleType
!= NoRole
) {
817 info
.role
= map
[i
].role
;
818 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
819 if (map
[i
].groupTranslation
) {
820 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
822 // For top level roles, groupTranslation is 0. We must make sure that
823 // info.group is an empty string then because the code that generates
824 // menus tries to put the actions into sub menus otherwise.
825 info
.group
= QString();
827 info
.requiresBaloo
= map
[i
].requiresBaloo
;
828 info
.requiresIndexer
= map
[i
].requiresIndexer
;
829 rolesInfo
.append(info
);
837 void KFileItemModel::onGroupedSortingChanged(bool current
)
843 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
846 m_sortRole
= typeForRole(current
);
848 if (!m_requestRole
[m_sortRole
]) {
849 QSet
<QByteArray
> newRoles
= m_roles
;
859 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
866 void KFileItemModel::loadSortingSettings()
868 using Choice
= GeneralSettings::EnumSortingChoice
;
869 switch (GeneralSettings::sortingChoice()) {
870 case Choice::NaturalSorting
:
871 m_naturalSorting
= true;
872 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
874 case Choice::CaseSensitiveSorting
:
875 m_naturalSorting
= false;
876 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
878 case Choice::CaseInsensitiveSorting
:
879 m_naturalSorting
= false;
880 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
885 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
886 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
887 m_collator
.compare(QString(), QString());
890 void KFileItemModel::resortAllItems()
892 m_resortAllItemsTimer
->stop();
894 const int itemCount
= count();
895 if (itemCount
<= 0) {
899 #ifdef KFILEITEMMODEL_DEBUG
902 qCDebug(DolphinDebug
) << "===========================================================";
903 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
906 // Remember the order of the current URLs so
907 // that it can be determined which indexes have
908 // been moved because of the resorting.
910 oldUrls
.reserve(itemCount
);
911 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
912 oldUrls
.append(itemData
->item
.url());
916 m_items
.reserve(itemCount
);
919 sort(m_itemData
.begin(), m_itemData
.end());
920 for (int i
= 0; i
< itemCount
; ++i
) {
921 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
924 // Determine the first index that has been moved.
925 int firstMovedIndex
= 0;
926 while (firstMovedIndex
< itemCount
927 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
931 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
932 if (itemsHaveMoved
) {
935 int lastMovedIndex
= itemCount
- 1;
936 while (lastMovedIndex
> firstMovedIndex
937 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
941 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
943 // Create a list movedToIndexes, which has the property that
944 // movedToIndexes[i] is the new index of the item with the old index
945 // firstMovedIndex + i.
946 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
947 QList
<int> movedToIndexes
;
948 movedToIndexes
.reserve(movedItemsCount
);
949 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
950 const int newIndex
= m_items
.value(oldUrls
.at(i
));
951 movedToIndexes
.append(newIndex
);
954 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
955 } else if (groupedSorting()) {
956 // The groups might have changed even if the order of the items has not.
957 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
959 if (groups() != oldGroups
) {
960 Q_EMIT
groupsChanged();
964 #ifdef KFILEITEMMODEL_DEBUG
965 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
969 void KFileItemModel::slotCompleted()
971 m_maximumUpdateIntervalTimer
->stop();
972 dispatchPendingItemsToInsert();
974 if (!m_urlsToExpand
.isEmpty()) {
975 // Try to find a URL that can be expanded.
976 // Note that the parent folder must be expanded before any of its subfolders become visible.
977 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
978 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
979 // Iterate over a const copy because items are deleted and inserted within the loop
980 const auto urlsToExpand
= m_urlsToExpand
;
981 for(const QUrl
&url
: urlsToExpand
) {
982 const int indexForUrl
= index(url
);
983 if (indexForUrl
>= 0) {
984 m_urlsToExpand
.remove(url
);
985 if (setExpanded(indexForUrl
, true)) {
986 // The dir lister has been triggered. This slot will be called
987 // again after the directory has been expanded.
993 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
994 // if these URLs have been deleted in the meantime.
995 m_urlsToExpand
.clear();
998 Q_EMIT
directoryLoadingCompleted();
1001 void KFileItemModel::slotCanceled()
1003 m_maximumUpdateIntervalTimer
->stop();
1004 dispatchPendingItemsToInsert();
1006 Q_EMIT
directoryLoadingCanceled();
1009 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
1011 Q_ASSERT(!items
.isEmpty());
1014 if (m_expandedDirs
.contains(directoryUrl
)) {
1015 parentUrl
= m_expandedDirs
.value(directoryUrl
);
1017 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
1020 if (m_requestRole
[ExpandedParentsCountRole
]) {
1021 // If the expanding of items is enabled, the call
1022 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1023 // might result in emitting the same items twice due to the Keep-parameter.
1024 // This case happens if an item gets expanded, collapsed and expanded again
1025 // before the items could be loaded for the first expansion.
1026 if (index(items
.first().url()) >= 0) {
1027 // The items are already part of the model.
1031 if (directoryUrl
!= directory()) {
1032 // To be able to compare whether the new items may be inserted as children
1033 // of a parent item the pending items must be added to the model first.
1034 dispatchPendingItemsToInsert();
1037 // KDirLister keeps the children of items that got expanded once even if
1038 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1039 // checked whether the parent for new items is still expanded.
1040 const int parentIndex
= index(parentUrl
);
1041 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1042 // The parent is not expanded.
1047 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1049 if (!m_filter
.hasSetFilters()) {
1050 m_pendingItemsToInsert
.append(itemDataList
);
1052 // The name or type filter is active. Hide filtered items
1053 // before inserting them into the model and remember
1054 // the filtered items in m_filteredItems.
1055 for (ItemData
* itemData
: itemDataList
) {
1056 if (m_filter
.matches(itemData
->item
)) {
1057 m_pendingItemsToInsert
.append(itemData
);
1059 m_filteredItems
.insert(itemData
->item
, itemData
);
1064 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1065 // Assure that items get dispatched if no completed() or canceled() signal is
1066 // emitted during the maximum update interval.
1067 m_maximumUpdateIntervalTimer
->start();
1070 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1073 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1075 dispatchPendingItemsToInsert();
1077 QVector
<int> indexesToRemove
;
1078 indexesToRemove
.reserve(items
.count());
1079 KFileItemList dirsChanged
;
1081 for (const KFileItem
& item
: items
) {
1082 const int indexForItem
= index(item
);
1083 if (indexForItem
>= 0) {
1084 indexesToRemove
.append(indexForItem
);
1086 // Probably the item has been filtered.
1087 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1088 if (it
!= m_filteredItems
.end()) {
1090 m_filteredItems
.erase(it
);
1094 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1095 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1096 dirsChanged
<< KFileItem(parentUrl
);
1100 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1102 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1103 // Assure that removing a parent item also results in removing all children
1104 QVector
<int> indexesToRemoveWithChildren
;
1105 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1107 const int itemCount
= m_itemData
.count();
1108 for (int index
: qAsConst(indexesToRemove
)) {
1109 indexesToRemoveWithChildren
.append(index
);
1111 const int parentLevel
= expandedParentsCount(index
);
1112 int childIndex
= index
+ 1;
1113 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1114 indexesToRemoveWithChildren
.append(childIndex
);
1119 indexesToRemove
= indexesToRemoveWithChildren
;
1122 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1123 removeFilteredChildren(itemRanges
);
1124 removeItems(itemRanges
, DeleteItemData
);
1126 Q_EMIT
fileItemsChanged(dirsChanged
);
1129 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1131 Q_ASSERT(!items
.isEmpty());
1132 #ifdef KFILEITEMMODEL_DEBUG
1133 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1136 // Get the indexes of all items that have been refreshed
1138 indexes
.reserve(items
.count());
1140 QSet
<QByteArray
> changedRoles
;
1141 KFileItemList changedFiles
;
1143 // Contains the indexes of the currently visible items
1144 // that should get hidden and hence moved to m_filteredItems.
1145 QVector
<int> newFilteredIndexes
;
1147 // Contains currently hidden items that should
1148 // get visible and hence removed from m_filteredItems
1149 QList
<ItemData
*> newVisibleItems
;
1151 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1152 while (it
.hasNext()) {
1153 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1154 const KFileItem
& oldItem
= itemPair
.first
;
1155 const KFileItem
& newItem
= itemPair
.second
;
1156 const int indexForItem
= index(oldItem
);
1157 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1158 if (indexForItem
>= 0) {
1159 m_itemData
[indexForItem
]->item
= newItem
;
1161 // Keep old values as long as possible if they could not retrieved synchronously yet.
1162 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1163 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1164 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1165 while (it
.hasNext()) {
1167 const QByteArray
& role
= it
.key();
1168 if (itemData
->values
.value(role
) != it
.value()) {
1169 itemData
->values
.insert(role
, it
.value());
1170 changedRoles
.insert(role
);
1174 m_items
.remove(oldItem
.url());
1175 if (newItemMatchesFilter
) {
1176 m_items
.insert(newItem
.url(), indexForItem
);
1177 changedFiles
.append(newItem
);
1178 indexes
.append(indexForItem
);
1180 newFilteredIndexes
.append(indexForItem
);
1181 m_filteredItems
.insert(newItem
, itemData
);
1184 // Check if 'oldItem' is one of the filtered items.
1185 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1186 if (it
!= m_filteredItems
.end()) {
1187 ItemData
* itemData
= it
.value();
1188 itemData
->item
= newItem
;
1190 // The data stored in 'values' might have changed. Therefore, we clear
1191 // 'values' and re-populate it the next time it is requested via data(int).
1192 itemData
->values
.clear();
1194 m_filteredItems
.erase(it
);
1195 if (newItemMatchesFilter
) {
1196 newVisibleItems
.append(itemData
);
1198 m_filteredItems
.insert(newItem
, itemData
);
1204 // Hide items, previously visible that should get hidden
1205 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1206 removeItems(removedRanges
, KeepItemData
);
1208 // Show previously hidden items that should get visible
1209 insertItems(newVisibleItems
);
1211 // If the changed items have been created recently, they might not be in m_items yet.
1212 // In that case, the list 'indexes' might be empty.
1213 if (indexes
.isEmpty()) {
1217 // Extract the item-ranges out of the changed indexes
1218 std::sort(indexes
.begin(), indexes
.end());
1219 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1220 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1222 Q_EMIT
fileItemsChanged(changedFiles
);
1225 void KFileItemModel::slotClear()
1227 #ifdef KFILEITEMMODEL_DEBUG
1228 qCDebug(DolphinDebug
) << "Clearing all items";
1231 qDeleteAll(m_filteredItems
);
1232 m_filteredItems
.clear();
1235 m_maximumUpdateIntervalTimer
->stop();
1236 m_resortAllItemsTimer
->stop();
1238 qDeleteAll(m_pendingItemsToInsert
);
1239 m_pendingItemsToInsert
.clear();
1241 const int removedCount
= m_itemData
.count();
1242 if (removedCount
> 0) {
1243 qDeleteAll(m_itemData
);
1246 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1249 m_expandedDirs
.clear();
1252 void KFileItemModel::slotSortingChoiceChanged()
1254 loadSortingSettings();
1258 void KFileItemModel::dispatchPendingItemsToInsert()
1260 if (!m_pendingItemsToInsert
.isEmpty()) {
1261 insertItems(m_pendingItemsToInsert
);
1262 m_pendingItemsToInsert
.clear();
1266 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1268 if (newItems
.isEmpty()) {
1272 #ifdef KFILEITEMMODEL_DEBUG
1273 QElapsedTimer timer
;
1275 qCDebug(DolphinDebug
) << "===========================================================";
1276 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1280 prepareItemsForSorting(newItems
);
1282 // Natural sorting of items can be very slow. However, it becomes much faster
1283 // if the input sequence is already mostly sorted. Therefore, we first sort
1284 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1285 if (m_naturalSorting
) {
1286 if (m_sortRole
== NameRole
) {
1287 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1288 } else if (isRoleValueNatural(m_sortRole
)) {
1289 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1291 const QByteArray role
= roleForType(m_sortRole
);
1292 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1294 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1298 sort(newItems
.begin(), newItems
.end());
1300 #ifdef KFILEITEMMODEL_DEBUG
1301 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1304 KItemRangeList itemRanges
;
1305 const int existingItemCount
= m_itemData
.count();
1306 const int newItemCount
= newItems
.count();
1307 const int totalItemCount
= existingItemCount
+ newItemCount
;
1309 if (existingItemCount
== 0) {
1310 // Optimization for the common special case that there are no
1311 // items in the model yet. Happens, e.g., when entering a folder.
1312 m_itemData
= newItems
;
1313 itemRanges
<< KItemRange(0, newItemCount
);
1315 m_itemData
.reserve(totalItemCount
);
1316 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1317 m_itemData
.append(nullptr);
1320 // We build the new list m_itemData in reverse order to minimize
1321 // the number of moves and guarantee O(N) complexity.
1322 int targetIndex
= totalItemCount
- 1;
1323 int sourceIndexExistingItems
= existingItemCount
- 1;
1324 int sourceIndexNewItems
= newItemCount
- 1;
1328 while (sourceIndexNewItems
>= 0) {
1329 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1330 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1331 // Move an existing item to its new position. If any new items
1332 // are behind it, push the item range to itemRanges.
1333 if (rangeCount
> 0) {
1334 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1338 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1339 --sourceIndexExistingItems
;
1341 // Insert a new item into the list.
1343 m_itemData
[targetIndex
] = newItem
;
1344 --sourceIndexNewItems
;
1349 // Push the final item range to itemRanges.
1350 if (rangeCount
> 0) {
1351 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1354 // Note that itemRanges is still sorted in reverse order.
1355 std::reverse(itemRanges
.begin(), itemRanges
.end());
1358 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1359 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1362 Q_EMIT
itemsInserted(itemRanges
);
1364 #ifdef KFILEITEMMODEL_DEBUG
1365 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1369 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1371 if (itemRanges
.isEmpty()) {
1377 // Step 1: Remove the items from m_itemData, and free the ItemData.
1378 int removedItemsCount
= 0;
1379 for (const KItemRange
& range
: itemRanges
) {
1380 removedItemsCount
+= range
.count
;
1382 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1383 if (behavior
== DeleteItemData
) {
1384 delete m_itemData
.at(index
);
1387 m_itemData
[index
] = nullptr;
1391 // Step 2: Remove the ItemData pointers from the list m_itemData.
1392 int target
= itemRanges
.at(0).index
;
1393 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1396 const int oldItemDataCount
= m_itemData
.count();
1397 while (source
< oldItemDataCount
) {
1398 m_itemData
[target
] = m_itemData
[source
];
1402 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1403 // Skip the items in the next removed range.
1404 source
+= itemRanges
.at(nextRange
).count
;
1409 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1411 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1412 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1415 Q_EMIT
itemsRemoved(itemRanges
);
1418 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1420 if (m_sortRole
== TypeRole
) {
1421 // Try to resolve the MIME-types synchronously to prevent a reordering of
1422 // the items when sorting by type (per default MIME-types are resolved
1423 // asynchronously by KFileItemModelRolesUpdater).
1424 determineMimeTypes(items
, 200);
1427 const int parentIndex
= index(parentUrl
);
1428 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1430 QList
<ItemData
*> itemDataList
;
1431 itemDataList
.reserve(items
.count());
1433 for (const KFileItem
& item
: items
) {
1434 ItemData
* itemData
= new ItemData();
1435 itemData
->item
= item
;
1436 itemData
->parent
= parentItem
;
1437 itemDataList
.append(itemData
);
1440 return itemDataList
;
1443 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1445 switch (m_sortRole
) {
1446 case PermissionsRole
:
1449 case DestinationRole
:
1451 case DeletionTimeRole
:
1452 // These roles can be determined with retrieveData, and they have to be stored
1453 // in the QHash "values" for the sorting.
1454 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1455 if (itemData
->values
.isEmpty()) {
1456 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1462 // At least store the data including the file type for items with known MIME type.
1463 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1464 if (itemData
->values
.isEmpty()) {
1465 const KFileItem item
= itemData
->item
;
1466 if (item
.isDir() || item
.isMimeTypeKnown()) {
1467 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1474 // The other roles are either resolved by KFileItemModelRolesUpdater
1475 // (this includes the SizeRole for directories), or they do not need
1476 // to be stored in the QHash "values" for sorting because the data can
1477 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1483 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1485 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1486 // if the corresponding item is expanded, and it is not a top-level item.
1487 const ItemData
* parent
= data
->parent
;
1489 if (parent
->parent
) {
1490 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1491 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1500 void KFileItemModel::removeExpandedItems()
1502 QVector
<int> indexesToRemove
;
1504 const int maxIndex
= m_itemData
.count() - 1;
1505 for (int i
= 0; i
<= maxIndex
; ++i
) {
1506 const ItemData
* itemData
= m_itemData
.at(i
);
1507 if (itemData
->parent
) {
1508 indexesToRemove
.append(i
);
1512 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1513 m_expandedDirs
.clear();
1515 // Also remove all filtered items which have a parent.
1516 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1517 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1520 if (it
.value()->parent
) {
1522 it
= m_filteredItems
.erase(it
);
1529 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1531 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1533 // Trigger a resorting if necessary. Note that this can happen even if the sort
1534 // role has not changed at all because the file name can be used as a fallback.
1535 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1536 for (const KItemRange
& range
: itemRanges
) {
1537 bool needsResorting
= false;
1539 const int first
= range
.index
;
1540 const int last
= range
.index
+ range
.count
- 1;
1542 // Resorting the model is necessary if
1543 // (a) The first item in the range is "lessThan" its predecessor,
1544 // (b) the successor of the last item is "lessThan" the last item, or
1545 // (c) the internal order of the items in the range is incorrect.
1547 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1548 needsResorting
= true;
1549 } else if (last
< count() - 1
1550 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1551 needsResorting
= true;
1553 for (int index
= first
; index
< last
; ++index
) {
1554 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1555 needsResorting
= true;
1561 if (needsResorting
) {
1562 m_resortAllItemsTimer
->start();
1568 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1569 // The position is still correct, but the groups might have changed
1570 // if the changed item is either the first or the last item in a
1572 // In principle, we could try to find out if the item really is the
1573 // first or last one in its group and then update the groups
1574 // (possibly with a delayed timer to make sure that we don't
1575 // re-calculate the groups very often if items are updated one by
1576 // one), but starting m_resortAllItemsTimer is easier.
1577 m_resortAllItemsTimer
->start();
1581 void KFileItemModel::resetRoles()
1583 for (int i
= 0; i
< RolesCount
; ++i
) {
1584 m_requestRole
[i
] = false;
1588 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1590 static QHash
<QByteArray
, RoleType
> roles
;
1591 if (roles
.isEmpty()) {
1592 // Insert user visible roles that can be accessed with
1593 // KFileItemModel::roleInformation()
1595 const RoleInfoMap
* map
= rolesInfoMap(count
);
1596 for (int i
= 0; i
< count
; ++i
) {
1597 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1600 // Insert internal roles (take care to synchronize the implementation
1601 // with KFileItemModel::roleForType() in case if a change is done).
1602 roles
.insert("isDir", IsDirRole
);
1603 roles
.insert("isLink", IsLinkRole
);
1604 roles
.insert("isHidden", IsHiddenRole
);
1605 roles
.insert("isExpanded", IsExpandedRole
);
1606 roles
.insert("isExpandable", IsExpandableRole
);
1607 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1609 Q_ASSERT(roles
.count() == RolesCount
);
1612 return roles
.value(role
, NoRole
);
1615 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1617 static QHash
<RoleType
, QByteArray
> roles
;
1618 if (roles
.isEmpty()) {
1619 // Insert user visible roles that can be accessed with
1620 // KFileItemModel::roleInformation()
1622 const RoleInfoMap
* map
= rolesInfoMap(count
);
1623 for (int i
= 0; i
< count
; ++i
) {
1624 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1627 // Insert internal roles (take care to synchronize the implementation
1628 // with KFileItemModel::typeForRole() in case if a change is done).
1629 roles
.insert(IsDirRole
, "isDir");
1630 roles
.insert(IsLinkRole
, "isLink");
1631 roles
.insert(IsHiddenRole
, "isHidden");
1632 roles
.insert(IsExpandedRole
, "isExpanded");
1633 roles
.insert(IsExpandableRole
, "isExpandable");
1634 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1636 Q_ASSERT(roles
.count() == RolesCount
);
1639 return roles
.value(roleType
);
1642 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1644 // It is important to insert only roles that are fast to retrieve. E.g.
1645 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1646 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1647 QHash
<QByteArray
, QVariant
> data
;
1648 data
.insert(sharedValue("url"), item
.url());
1650 const bool isDir
= item
.isDir();
1651 if (m_requestRole
[IsDirRole
] && isDir
) {
1652 data
.insert(sharedValue("isDir"), true);
1655 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1656 data
.insert(sharedValue("isLink"), true);
1659 if (m_requestRole
[IsHiddenRole
]) {
1660 data
.insert(sharedValue("isHidden"), item
.isHidden());
1663 if (m_requestRole
[NameRole
]) {
1664 data
.insert(sharedValue("text"), item
.text());
1667 if (m_requestRole
[SizeRole
] && !isDir
) {
1668 data
.insert(sharedValue("size"), item
.size());
1671 if (m_requestRole
[ModificationTimeRole
]) {
1672 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1673 // having several thousands of items. Instead read the raw number from UDSEntry directly
1674 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1675 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1676 data
.insert(sharedValue("modificationtime"), dateTime
);
1679 if (m_requestRole
[CreationTimeRole
]) {
1680 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1681 // having several thousands of items. Instead read the raw number from UDSEntry directly
1682 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1683 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1684 data
.insert(sharedValue("creationtime"), dateTime
);
1687 if (m_requestRole
[AccessTimeRole
]) {
1688 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1689 // having several thousands of items. Instead read the raw number from UDSEntry directly
1690 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1691 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1692 data
.insert(sharedValue("accesstime"), dateTime
);
1695 if (m_requestRole
[PermissionsRole
]) {
1696 data
.insert(sharedValue("permissions"), item
.permissionsString());
1699 if (m_requestRole
[OwnerRole
]) {
1700 data
.insert(sharedValue("owner"), item
.user());
1703 if (m_requestRole
[GroupRole
]) {
1704 data
.insert(sharedValue("group"), item
.group());
1707 if (m_requestRole
[DestinationRole
]) {
1708 QString destination
= item
.linkDest();
1709 if (destination
.isEmpty()) {
1710 destination
= QLatin1Char('-');
1712 data
.insert(sharedValue("destination"), destination
);
1715 if (m_requestRole
[PathRole
]) {
1717 if (item
.url().scheme() == QLatin1String("trash")) {
1718 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1720 // For performance reasons cache the home-path in a static QString
1721 // (see QDir::homePath() for more details)
1722 static QString homePath
;
1723 if (homePath
.isEmpty()) {
1724 homePath
= QDir::homePath();
1727 path
= item
.localPath();
1728 if (path
.startsWith(homePath
)) {
1729 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1733 const int index
= path
.lastIndexOf(item
.text());
1734 path
= path
.mid(0, index
- 1);
1735 data
.insert(sharedValue("path"), path
);
1738 if (m_requestRole
[DeletionTimeRole
]) {
1739 QDateTime deletionTime
;
1740 if (item
.url().scheme() == QLatin1String("trash")) {
1741 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1743 data
.insert(sharedValue("deletiontime"), deletionTime
);
1746 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1747 data
.insert(sharedValue("isExpandable"), true);
1750 if (m_requestRole
[ExpandedParentsCountRole
]) {
1752 const int level
= expandedParentsCount(parent
) + 1;
1753 data
.insert(sharedValue("expandedParentsCount"), level
);
1757 if (item
.isMimeTypeKnown()) {
1758 QString iconName
= item
.iconName();
1759 if (!QIcon::hasThemeIcon(iconName
)) {
1760 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1761 iconName
= mimeType
.genericIconName();
1764 data
.insert(sharedValue("iconName"), iconName
);
1766 if (m_requestRole
[TypeRole
]) {
1767 data
.insert(sharedValue("type"), item
.mimeComment());
1769 } else if (m_requestRole
[TypeRole
] && isDir
) {
1770 static const QString folderMimeType
= item
.mimeComment();
1771 data
.insert(sharedValue("type"), folderMimeType
);
1777 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1781 if (a
->parent
!= b
->parent
) {
1782 const int expansionLevelA
= expandedParentsCount(a
);
1783 const int expansionLevelB
= expandedParentsCount(b
);
1785 // If b has a higher expansion level than a, check if a is a parent
1786 // of b, and make sure that both expansion levels are equal otherwise.
1787 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1788 if (b
->parent
== a
) {
1794 // If a has a higher expansion level than a, check if b is a parent
1795 // of a, and make sure that both expansion levels are equal otherwise.
1796 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1797 if (a
->parent
== b
) {
1803 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1805 // Compare the last parents of a and b which are different.
1806 while (a
->parent
!= b
->parent
) {
1812 // Show hidden files and folders last
1813 if (m_sortHiddenLast
) {
1814 const bool isHiddenA
= a
->item
.isHidden();
1815 const bool isHiddenB
= b
->item
.isHidden();
1816 if (isHiddenA
&& !isHiddenB
) {
1818 } else if (!isHiddenA
&& isHiddenB
) {
1823 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1824 const bool isDirA
= a
->item
.isDir();
1825 const bool isDirB
= b
->item
.isDir();
1826 if (isDirA
&& !isDirB
) {
1828 } else if (!isDirA
&& isDirB
) {
1833 result
= sortRoleCompare(a
, b
, collator
);
1835 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1838 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1839 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1841 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1843 return lessThan(a
, b
, m_collator
);
1846 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1847 // Sorting by string can be expensive, in particular if natural sorting is
1848 // enabled. Use all CPU cores to speed up the sorting process.
1849 static const int numberOfThreads
= QThread::idealThreadCount();
1850 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1852 // Sorting by other roles is quite fast. Use only one thread to prevent
1853 // problems caused by non-reentrant comparison functions, see
1854 // https://bugs.kde.org/show_bug.cgi?id=312679
1855 mergeSort(begin
, end
, lambdaLessThan
);
1859 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1861 // This function must never return 0, because that would break stable
1862 // sorting, which leads to all kinds of bugs.
1863 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1864 // If two items have equal sort values, let the fallbacks at the bottom of
1865 // the function handle it.
1866 const KFileItem
& itemA
= a
->item
;
1867 const KFileItem
& itemB
= b
->item
;
1871 switch (m_sortRole
) {
1873 // The name role is handled as default fallback after the switch
1877 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1878 // folders first then
1879 // items A and B are folders thanks to lessThan checks
1880 auto valueA
= a
->values
.value("count");
1881 auto valueB
= b
->values
.value("count");
1882 if (valueA
.isNull()) {
1883 if (!valueB
.isNull()) {
1886 } else if (valueB
.isNull()) {
1889 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1891 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1898 KIO::filesize_t sizeA
= 0;
1899 if (itemA
.isDir()) {
1900 sizeA
= a
->values
.value("size").toULongLong();
1902 sizeA
= itemA
.size();
1904 KIO::filesize_t sizeB
= 0;
1905 if (itemB
.isDir()) {
1906 sizeB
= b
->values
.value("size").toULongLong();
1908 sizeB
= itemB
.size();
1910 if (sizeA
< sizeB
) {
1912 } else if (sizeA
> sizeB
) {
1918 case ModificationTimeRole
: {
1919 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1920 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1921 if (dateTimeA
< dateTimeB
) {
1923 } else if (dateTimeA
> dateTimeB
) {
1929 case CreationTimeRole
: {
1930 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1931 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1932 if (dateTimeA
< dateTimeB
) {
1934 } else if (dateTimeA
> dateTimeB
) {
1940 case DeletionTimeRole
: {
1941 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1942 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1943 if (dateTimeA
< dateTimeB
) {
1945 } else if (dateTimeA
> dateTimeB
) {
1957 case ReleaseYearRole
: {
1958 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1963 const QByteArray role
= roleForType(m_sortRole
);
1964 const QString roleValueA
= a
->values
.value(role
).toString();
1965 const QString roleValueB
= b
->values
.value(role
).toString();
1966 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1968 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1970 } else if (isRoleValueNatural(m_sortRole
)) {
1971 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1973 result
= QString::compare(roleValueA
, roleValueB
);
1981 // The current sort role was sufficient to define an order
1985 // Fallback #1: Compare the text of the items
1986 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1991 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1992 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1997 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1998 // equal. In this case a comparison of the URL is done which is unique in all cases
1999 // within KDirLister.
2000 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2003 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
2005 QMutexLocker
collatorLock(s_collatorMutex());
2007 if (m_naturalSorting
) {
2008 return collator
.compare(a
, b
);
2011 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2012 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2013 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2014 // comparison, still a deterministic sort order is required. A case sensitive
2015 // comparison is done as fallback.
2019 return QString::compare(a
, b
, Qt::CaseSensitive
);
2022 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
2024 Q_ASSERT(!m_itemData
.isEmpty());
2026 const int maxIndex
= count() - 1;
2027 QList
<QPair
<int, QVariant
> > groups
;
2031 for (int i
= 0; i
<= maxIndex
; ++i
) {
2032 if (isChildItem(i
)) {
2036 const QString name
= m_itemData
.at(i
)->item
.text();
2038 // Use the first character of the name as group indication
2039 QChar newFirstChar
= name
.at(0).toUpper();
2040 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2041 newFirstChar
= name
.at(1).toUpper();
2044 if (firstChar
!= newFirstChar
) {
2045 QString newGroupValue
;
2046 if (newFirstChar
.isLetter()) {
2048 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2049 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2051 // Try to find a matching group in the range 'A' to 'Z'.
2052 static std::vector
<QChar
> lettersAtoZ
;
2053 lettersAtoZ
.reserve('Z' - 'A' + 1);
2054 if (lettersAtoZ
.empty()) {
2055 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2056 lettersAtoZ
.push_back(QLatin1Char(c
));
2060 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2061 return m_collator
.compare(c1
, c2
) < 0;
2064 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2065 if (it
!= lettersAtoZ
.end()) {
2066 if (localeAwareLessThan(newFirstChar
, *it
)) {
2067 // newFirstChar belongs to the group preceding *it.
2068 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2071 newGroupValue
= *it
;
2075 // Symbols from non Latin-based scripts
2076 newGroupValue
= newFirstChar
;
2078 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2079 // Apply group '0 - 9' for any name that starts with a digit
2080 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2082 newGroupValue
= i18nc("@title:group", "Others");
2085 if (newGroupValue
!= groupValue
) {
2086 groupValue
= newGroupValue
;
2087 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2090 firstChar
= newFirstChar
;
2096 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2098 Q_ASSERT(!m_itemData
.isEmpty());
2100 const int maxIndex
= count() - 1;
2101 QList
<QPair
<int, QVariant
> > groups
;
2104 for (int i
= 0; i
<= maxIndex
; ++i
) {
2105 if (isChildItem(i
)) {
2109 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2110 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2111 QString newGroupValue
;
2112 if (!item
.isNull() && item
.isDir()) {
2113 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2114 newGroupValue
= i18nc("@title:group Size", "Folders");
2116 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2120 if (newGroupValue
.isEmpty()) {
2121 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2122 newGroupValue
= i18nc("@title:group Size", "Small");
2123 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2124 newGroupValue
= i18nc("@title:group Size", "Medium");
2126 newGroupValue
= i18nc("@title:group Size", "Big");
2130 if (newGroupValue
!= groupValue
) {
2131 groupValue
= newGroupValue
;
2132 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2139 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2141 Q_ASSERT(!m_itemData
.isEmpty());
2143 const int maxIndex
= count() - 1;
2144 QList
<QPair
<int, QVariant
> > groups
;
2146 const QDate currentDate
= QDate::currentDate();
2148 QDate previousFileDate
;
2150 for (int i
= 0; i
<= maxIndex
; ++i
) {
2151 if (isChildItem(i
)) {
2155 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2156 const QDate fileDate
= fileTime
.date();
2157 if (fileDate
== previousFileDate
) {
2158 // The current item is in the same group as the previous item
2161 previousFileDate
= fileDate
;
2163 const int daysDistance
= fileDate
.daysTo(currentDate
);
2165 QString newGroupValue
;
2166 if (currentDate
.year() == fileDate
.year() &&
2167 currentDate
.month() == fileDate
.month()) {
2169 switch (daysDistance
/ 7) {
2171 switch (daysDistance
) {
2172 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2173 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2175 newGroupValue
= fileTime
.toString(
2176 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2177 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2178 "with context @title:group Date", "%1", newGroupValue
);
2182 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2185 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2188 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2192 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2198 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2199 if (lastMonthDate
.year() == fileDate
.year() &&
2200 lastMonthDate
.month() == fileDate
.month()) {
2202 if (daysDistance
== 1) {
2203 const KLocalizedString format
= ki18nc("@title:group Date: "
2204 "MMMM is full month name in current locale, and yyyy is "
2205 "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)");
2206 const QString translatedFormat
= format
.toString();
2207 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2208 newGroupValue
= fileTime
.toString(translatedFormat
);
2209 newGroupValue
= i18nc("Can be used to script translation of "
2210 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2211 "%1", newGroupValue
);
2213 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2214 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2215 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2217 } else if (daysDistance
<= 7) {
2218 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2219 "The week day name: dddd, MMMM is full month name "
2220 "in current locale, and yyyy is full year number.",
2221 "dddd (MMMM, yyyy)"));
2222 newGroupValue
= i18nc("Can be used to script translation of "
2223 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2224 "%1", newGroupValue
);
2225 } else if (daysDistance
<= 7 * 2) {
2226 const KLocalizedString format
= ki18nc("@title:group Date: "
2227 "MMMM is full month name in current locale, and yyyy is "
2228 "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)");
2229 const QString translatedFormat
= format
.toString();
2230 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2231 newGroupValue
= fileTime
.toString(translatedFormat
);
2232 newGroupValue
= i18nc("Can be used to script translation of "
2233 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2234 "%1", newGroupValue
);
2236 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2237 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2238 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2240 } else if (daysDistance
<= 7 * 3) {
2241 const KLocalizedString format
= ki18nc("@title:group Date: "
2242 "MMMM is full month name in current locale, and yyyy is "
2243 "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)");
2244 const QString translatedFormat
= format
.toString();
2245 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2246 newGroupValue
= fileTime
.toString(translatedFormat
);
2247 newGroupValue
= i18nc("Can be used to script translation of "
2248 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2249 "%1", newGroupValue
);
2251 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2252 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2253 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2255 } else if (daysDistance
<= 7 * 4) {
2256 const KLocalizedString format
= ki18nc("@title:group Date: "
2257 "MMMM is full month name in current locale, and yyyy is "
2258 "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)");
2259 const QString translatedFormat
= format
.toString();
2260 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2261 newGroupValue
= fileTime
.toString(translatedFormat
);
2262 newGroupValue
= i18nc("Can be used to script translation of "
2263 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2264 "%1", newGroupValue
);
2266 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2267 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2268 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2271 const KLocalizedString format
= ki18nc("@title:group Date: "
2272 "MMMM is full month name in current locale, and yyyy is "
2273 "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");
2274 const QString translatedFormat
= format
.toString();
2275 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2276 newGroupValue
= fileTime
.toString(translatedFormat
);
2277 newGroupValue
= i18nc("Can be used to script translation of "
2278 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2279 "%1", newGroupValue
);
2281 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2282 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2283 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2287 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2288 "The month and year: MMMM is full month name in current locale, "
2289 "and yyyy is full year number", "MMMM, yyyy"));
2290 newGroupValue
= i18nc("Can be used to script translation of "
2291 "\"MMMM, yyyy\" with context @title:group Date",
2292 "%1", newGroupValue
);
2296 if (newGroupValue
!= groupValue
) {
2297 groupValue
= newGroupValue
;
2298 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2305 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2307 Q_ASSERT(!m_itemData
.isEmpty());
2309 const int maxIndex
= count() - 1;
2310 QList
<QPair
<int, QVariant
> > groups
;
2312 QString permissionsString
;
2314 for (int i
= 0; i
<= maxIndex
; ++i
) {
2315 if (isChildItem(i
)) {
2319 const ItemData
* itemData
= m_itemData
.at(i
);
2320 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2321 if (newPermissionsString
== permissionsString
) {
2324 permissionsString
= newPermissionsString
;
2326 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2330 if (info
.permission(QFile::ReadUser
)) {
2331 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2333 if (info
.permission(QFile::WriteUser
)) {
2334 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2336 if (info
.permission(QFile::ExeUser
)) {
2337 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2339 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2343 if (info
.permission(QFile::ReadGroup
)) {
2344 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2346 if (info
.permission(QFile::WriteGroup
)) {
2347 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2349 if (info
.permission(QFile::ExeGroup
)) {
2350 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2352 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2354 // Set others string
2356 if (info
.permission(QFile::ReadOther
)) {
2357 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2359 if (info
.permission(QFile::WriteOther
)) {
2360 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2362 if (info
.permission(QFile::ExeOther
)) {
2363 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2365 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2367 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2368 if (newGroupValue
!= groupValue
) {
2369 groupValue
= newGroupValue
;
2370 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2377 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2379 Q_ASSERT(!m_itemData
.isEmpty());
2381 const int maxIndex
= count() - 1;
2382 QList
<QPair
<int, QVariant
> > groups
;
2384 int groupValue
= -1;
2385 for (int i
= 0; i
<= maxIndex
; ++i
) {
2386 if (isChildItem(i
)) {
2389 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2390 if (newGroupValue
!= groupValue
) {
2391 groupValue
= newGroupValue
;
2392 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2399 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2401 Q_ASSERT(!m_itemData
.isEmpty());
2403 const int maxIndex
= count() - 1;
2404 QList
<QPair
<int, QVariant
> > groups
;
2406 bool isFirstGroupValue
= true;
2408 for (int i
= 0; i
<= maxIndex
; ++i
) {
2409 if (isChildItem(i
)) {
2412 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2413 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2414 groupValue
= newGroupValue
;
2415 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2416 isFirstGroupValue
= false;
2423 void KFileItemModel::emitSortProgress(int resolvedCount
)
2425 // Be tolerant against a resolvedCount with a wrong range.
2426 // Although there should not be a case where KFileItemModelRolesUpdater
2427 // (= caller) provides a wrong range, it is important to emit
2428 // a useful progress information even if there is an unexpected
2429 // implementation issue.
2431 const int itemCount
= count();
2432 if (resolvedCount
>= itemCount
) {
2433 m_sortingProgressPercent
= -1;
2434 if (m_resortAllItemsTimer
->isActive()) {
2435 m_resortAllItemsTimer
->stop();
2439 Q_EMIT
directorySortingProgress(100);
2440 } else if (itemCount
> 0) {
2441 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2443 const int progress
= resolvedCount
* 100 / itemCount
;
2444 if (m_sortingProgressPercent
!= progress
) {
2445 m_sortingProgressPercent
= progress
;
2446 Q_EMIT
directorySortingProgress(progress
);
2451 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2453 static const RoleInfoMap rolesInfoMap
[] = {
2454 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2455 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2456 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2457 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2458 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2459 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2460 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2461 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2462 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2463 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2464 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2465 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2466 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2467 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2468 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2469 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2470 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2471 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2472 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2473 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2474 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2475 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2476 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2477 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2478 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2479 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2480 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2481 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2482 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2483 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2484 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2485 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2486 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2487 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2490 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2491 return rolesInfoMap
;
2494 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2496 QElapsedTimer timer
;
2498 for (const KFileItem
& item
: items
) {
2499 // Only determine mime types for files here. For directories,
2500 // KFileItem::determineMimeType() reads the .directory file inside to
2501 // load the icon, but this is not necessary at all if we just need the
2502 // type. Some special code for setting the correct mime type for
2503 // directories is in retrieveData().
2504 if (!item
.isDir()) {
2505 item
.determineMimeType();
2508 if (timer
.elapsed() > timeout
) {
2509 // Don't block the user interface, let the remaining items
2510 // be resolved asynchronously.
2516 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2518 static QSet
<QByteArray
> pool
;
2519 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2521 if (it
!= pool
.constEnd()) {
2529 bool KFileItemModel::isConsistent() const
2531 // m_items may contain less items than m_itemData because m_items
2532 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2533 if (m_items
.count() > m_itemData
.count()) {
2537 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2538 // Check if m_items and m_itemData are consistent.
2539 const KFileItem item
= fileItem(i
);
2540 if (item
.isNull()) {
2541 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2545 const int itemIndex
= index(item
);
2546 if (itemIndex
!= i
) {
2547 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2551 // Check if the items are sorted correctly.
2552 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2553 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2554 << fileItem(i
- 1) << fileItem(i
);
2558 // Check if all parent-child relationships are consistent.
2559 const ItemData
* data
= m_itemData
.at(i
);
2560 const ItemData
* parent
= data
->parent
;
2562 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2563 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2567 const int parentIndex
= index(parent
->item
);
2568 if (parentIndex
>= i
) {
2569 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2578 void KFileItemModel::slotListerError(KIO::Job
*job
)
2580 if (job
->error() == KIO::ERR_IS_FILE
) {
2581 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2582 Q_EMIT
urlIsFileError(listJob
->url());
2585 const QString errorString
= job
->errorString();
2586 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));