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();
699 void KFileItemModel::applyFilters()
701 // Check which shown items from m_itemData must get
702 // hidden and hence moved to m_filteredItems.
703 QVector
<int> newFilteredIndexes
;
705 const int itemCount
= m_itemData
.count();
706 for (int index
= 0; index
< itemCount
; ++index
) {
707 ItemData
* itemData
= m_itemData
.at(index
);
709 // Only filter non-expanded items as child items may never
710 // exist without a parent item
711 if (!itemData
->values
.value("isExpanded").toBool()) {
712 const KFileItem item
= itemData
->item
;
713 if (!m_filter
.matches(item
)) {
714 newFilteredIndexes
.append(index
);
715 m_filteredItems
.insert(item
, itemData
);
720 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
721 removeItems(removedRanges
, KeepItemData
);
723 // Check which hidden items from m_filteredItems should
724 // get visible again and hence removed from m_filteredItems.
725 QList
<ItemData
*> newVisibleItems
;
727 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
728 while (it
!= m_filteredItems
.end()) {
729 if (m_filter
.matches(it
.key())) {
730 newVisibleItems
.append(it
.value());
731 it
= m_filteredItems
.erase(it
);
737 insertItems(newVisibleItems
);
740 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
742 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
743 // There are either no filtered items, or it is not possible to expand
744 // folders -> there cannot be any filtered children.
748 QSet
<ItemData
*> parents
;
749 for (const KItemRange
& range
: itemRanges
) {
750 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
751 parents
.insert(m_itemData
.at(index
));
755 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
756 while (it
!= m_filteredItems
.end()) {
757 if (parents
.contains(it
.value()->parent
)) {
759 it
= m_filteredItems
.erase(it
);
766 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
768 static QList
<RoleInfo
> rolesInfo
;
769 if (rolesInfo
.isEmpty()) {
771 const RoleInfoMap
* map
= rolesInfoMap(count
);
772 for (int i
= 0; i
< count
; ++i
) {
773 if (map
[i
].roleType
!= NoRole
) {
775 info
.role
= map
[i
].role
;
776 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
777 if (map
[i
].groupTranslation
) {
778 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
780 // For top level roles, groupTranslation is 0. We must make sure that
781 // info.group is an empty string then because the code that generates
782 // menus tries to put the actions into sub menus otherwise.
783 info
.group
= QString();
785 info
.requiresBaloo
= map
[i
].requiresBaloo
;
786 info
.requiresIndexer
= map
[i
].requiresIndexer
;
787 rolesInfo
.append(info
);
795 void KFileItemModel::onGroupedSortingChanged(bool current
)
801 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
804 m_sortRole
= typeForRole(current
);
806 if (!m_requestRole
[m_sortRole
]) {
807 QSet
<QByteArray
> newRoles
= m_roles
;
817 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
824 void KFileItemModel::loadSortingSettings()
826 using Choice
= GeneralSettings::EnumSortingChoice
;
827 switch (GeneralSettings::sortingChoice()) {
828 case Choice::NaturalSorting
:
829 m_naturalSorting
= true;
830 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
832 case Choice::CaseSensitiveSorting
:
833 m_naturalSorting
= false;
834 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
836 case Choice::CaseInsensitiveSorting
:
837 m_naturalSorting
= false;
838 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
843 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
844 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
845 m_collator
.compare(QString(), QString());
848 void KFileItemModel::resortAllItems()
850 m_resortAllItemsTimer
->stop();
852 const int itemCount
= count();
853 if (itemCount
<= 0) {
857 #ifdef KFILEITEMMODEL_DEBUG
860 qCDebug(DolphinDebug
) << "===========================================================";
861 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
864 // Remember the order of the current URLs so
865 // that it can be determined which indexes have
866 // been moved because of the resorting.
868 oldUrls
.reserve(itemCount
);
869 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
870 oldUrls
.append(itemData
->item
.url());
874 m_items
.reserve(itemCount
);
877 sort(m_itemData
.begin(), m_itemData
.end());
878 for (int i
= 0; i
< itemCount
; ++i
) {
879 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
882 // Determine the first index that has been moved.
883 int firstMovedIndex
= 0;
884 while (firstMovedIndex
< itemCount
885 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
889 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
890 if (itemsHaveMoved
) {
893 int lastMovedIndex
= itemCount
- 1;
894 while (lastMovedIndex
> firstMovedIndex
895 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
899 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
901 // Create a list movedToIndexes, which has the property that
902 // movedToIndexes[i] is the new index of the item with the old index
903 // firstMovedIndex + i.
904 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
905 QList
<int> movedToIndexes
;
906 movedToIndexes
.reserve(movedItemsCount
);
907 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
908 const int newIndex
= m_items
.value(oldUrls
.at(i
));
909 movedToIndexes
.append(newIndex
);
912 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
913 } else if (groupedSorting()) {
914 // The groups might have changed even if the order of the items has not.
915 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
917 if (groups() != oldGroups
) {
918 Q_EMIT
groupsChanged();
922 #ifdef KFILEITEMMODEL_DEBUG
923 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
927 void KFileItemModel::slotCompleted()
929 m_maximumUpdateIntervalTimer
->stop();
930 dispatchPendingItemsToInsert();
932 if (!m_urlsToExpand
.isEmpty()) {
933 // Try to find a URL that can be expanded.
934 // Note that the parent folder must be expanded before any of its subfolders become visible.
935 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
936 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
937 // Iterate over a const copy because items are deleted and inserted within the loop
938 const auto urlsToExpand
= m_urlsToExpand
;
939 for(const QUrl
&url
: urlsToExpand
) {
940 const int indexForUrl
= index(url
);
941 if (indexForUrl
>= 0) {
942 m_urlsToExpand
.remove(url
);
943 if (setExpanded(indexForUrl
, true)) {
944 // The dir lister has been triggered. This slot will be called
945 // again after the directory has been expanded.
951 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
952 // if these URLs have been deleted in the meantime.
953 m_urlsToExpand
.clear();
956 Q_EMIT
directoryLoadingCompleted();
959 void KFileItemModel::slotCanceled()
961 m_maximumUpdateIntervalTimer
->stop();
962 dispatchPendingItemsToInsert();
964 Q_EMIT
directoryLoadingCanceled();
967 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
969 Q_ASSERT(!items
.isEmpty());
972 if (m_expandedDirs
.contains(directoryUrl
)) {
973 parentUrl
= m_expandedDirs
.value(directoryUrl
);
975 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
978 if (m_requestRole
[ExpandedParentsCountRole
]) {
979 // If the expanding of items is enabled, the call
980 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
981 // might result in emitting the same items twice due to the Keep-parameter.
982 // This case happens if an item gets expanded, collapsed and expanded again
983 // before the items could be loaded for the first expansion.
984 if (index(items
.first().url()) >= 0) {
985 // The items are already part of the model.
989 if (directoryUrl
!= directory()) {
990 // To be able to compare whether the new items may be inserted as children
991 // of a parent item the pending items must be added to the model first.
992 dispatchPendingItemsToInsert();
995 // KDirLister keeps the children of items that got expanded once even if
996 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
997 // checked whether the parent for new items is still expanded.
998 const int parentIndex
= index(parentUrl
);
999 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1000 // The parent is not expanded.
1005 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1007 if (!m_filter
.hasSetFilters()) {
1008 m_pendingItemsToInsert
.append(itemDataList
);
1010 // The name or type filter is active. Hide filtered items
1011 // before inserting them into the model and remember
1012 // the filtered items in m_filteredItems.
1013 for (ItemData
* itemData
: itemDataList
) {
1014 if (m_filter
.matches(itemData
->item
)) {
1015 m_pendingItemsToInsert
.append(itemData
);
1017 m_filteredItems
.insert(itemData
->item
, itemData
);
1022 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1023 // Assure that items get dispatched if no completed() or canceled() signal is
1024 // emitted during the maximum update interval.
1025 m_maximumUpdateIntervalTimer
->start();
1028 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1031 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1033 dispatchPendingItemsToInsert();
1035 QVector
<int> indexesToRemove
;
1036 indexesToRemove
.reserve(items
.count());
1037 KFileItemList dirsChanged
;
1039 for (const KFileItem
& item
: items
) {
1040 const int indexForItem
= index(item
);
1041 if (indexForItem
>= 0) {
1042 indexesToRemove
.append(indexForItem
);
1044 // Probably the item has been filtered.
1045 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1046 if (it
!= m_filteredItems
.end()) {
1048 m_filteredItems
.erase(it
);
1052 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1053 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1054 dirsChanged
<< KFileItem(parentUrl
);
1058 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1060 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1061 // Assure that removing a parent item also results in removing all children
1062 QVector
<int> indexesToRemoveWithChildren
;
1063 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1065 const int itemCount
= m_itemData
.count();
1066 for (int index
: qAsConst(indexesToRemove
)) {
1067 indexesToRemoveWithChildren
.append(index
);
1069 const int parentLevel
= expandedParentsCount(index
);
1070 int childIndex
= index
+ 1;
1071 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1072 indexesToRemoveWithChildren
.append(childIndex
);
1077 indexesToRemove
= indexesToRemoveWithChildren
;
1080 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1081 removeFilteredChildren(itemRanges
);
1082 removeItems(itemRanges
, DeleteItemData
);
1084 Q_EMIT
fileItemsChanged(dirsChanged
);
1087 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1089 Q_ASSERT(!items
.isEmpty());
1090 #ifdef KFILEITEMMODEL_DEBUG
1091 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1094 // Get the indexes of all items that have been refreshed
1096 indexes
.reserve(items
.count());
1098 QSet
<QByteArray
> changedRoles
;
1099 KFileItemList changedFiles
;
1101 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1102 while (it
.hasNext()) {
1103 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1104 const KFileItem
& oldItem
= itemPair
.first
;
1105 const KFileItem
& newItem
= itemPair
.second
;
1106 const int indexForItem
= index(oldItem
);
1107 if (indexForItem
>= 0) {
1108 m_itemData
[indexForItem
]->item
= newItem
;
1110 // Keep old values as long as possible if they could not retrieved synchronously yet.
1111 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1112 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1113 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1114 while (it
.hasNext()) {
1116 const QByteArray
& role
= it
.key();
1117 if (values
.value(role
) != it
.value()) {
1118 values
.insert(role
, it
.value());
1119 changedRoles
.insert(role
);
1123 m_items
.remove(oldItem
.url());
1124 m_items
.insert(newItem
.url(), indexForItem
);
1125 changedFiles
.append(newItem
);
1126 indexes
.append(indexForItem
);
1128 // Check if 'oldItem' is one of the filtered items.
1129 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1130 if (it
!= m_filteredItems
.end()) {
1131 ItemData
* itemData
= it
.value();
1132 itemData
->item
= newItem
;
1134 // The data stored in 'values' might have changed. Therefore, we clear
1135 // 'values' and re-populate it the next time it is requested via data(int).
1136 itemData
->values
.clear();
1138 m_filteredItems
.erase(it
);
1139 m_filteredItems
.insert(newItem
, itemData
);
1144 // If the changed items have been created recently, they might not be in m_items yet.
1145 // In that case, the list 'indexes' might be empty.
1146 if (indexes
.isEmpty()) {
1150 // Extract the item-ranges out of the changed indexes
1151 std::sort(indexes
.begin(), indexes
.end());
1152 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1153 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1155 Q_EMIT
fileItemsChanged(changedFiles
);
1158 void KFileItemModel::slotClear()
1160 #ifdef KFILEITEMMODEL_DEBUG
1161 qCDebug(DolphinDebug
) << "Clearing all items";
1164 qDeleteAll(m_filteredItems
);
1165 m_filteredItems
.clear();
1168 m_maximumUpdateIntervalTimer
->stop();
1169 m_resortAllItemsTimer
->stop();
1171 qDeleteAll(m_pendingItemsToInsert
);
1172 m_pendingItemsToInsert
.clear();
1174 const int removedCount
= m_itemData
.count();
1175 if (removedCount
> 0) {
1176 qDeleteAll(m_itemData
);
1179 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1182 m_expandedDirs
.clear();
1185 void KFileItemModel::slotSortingChoiceChanged()
1187 loadSortingSettings();
1191 void KFileItemModel::dispatchPendingItemsToInsert()
1193 if (!m_pendingItemsToInsert
.isEmpty()) {
1194 insertItems(m_pendingItemsToInsert
);
1195 m_pendingItemsToInsert
.clear();
1199 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1201 if (newItems
.isEmpty()) {
1205 #ifdef KFILEITEMMODEL_DEBUG
1206 QElapsedTimer timer
;
1208 qCDebug(DolphinDebug
) << "===========================================================";
1209 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1213 prepareItemsForSorting(newItems
);
1215 // Natural sorting of items can be very slow. However, it becomes much faster
1216 // if the input sequence is already mostly sorted. Therefore, we first sort
1217 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1218 if (m_naturalSorting
) {
1219 if (m_sortRole
== NameRole
) {
1220 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1221 } else if (isRoleValueNatural(m_sortRole
)) {
1222 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1224 const QByteArray role
= roleForType(m_sortRole
);
1225 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1227 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1231 sort(newItems
.begin(), newItems
.end());
1233 #ifdef KFILEITEMMODEL_DEBUG
1234 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1237 KItemRangeList itemRanges
;
1238 const int existingItemCount
= m_itemData
.count();
1239 const int newItemCount
= newItems
.count();
1240 const int totalItemCount
= existingItemCount
+ newItemCount
;
1242 if (existingItemCount
== 0) {
1243 // Optimization for the common special case that there are no
1244 // items in the model yet. Happens, e.g., when entering a folder.
1245 m_itemData
= newItems
;
1246 itemRanges
<< KItemRange(0, newItemCount
);
1248 m_itemData
.reserve(totalItemCount
);
1249 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1250 m_itemData
.append(nullptr);
1253 // We build the new list m_itemData in reverse order to minimize
1254 // the number of moves and guarantee O(N) complexity.
1255 int targetIndex
= totalItemCount
- 1;
1256 int sourceIndexExistingItems
= existingItemCount
- 1;
1257 int sourceIndexNewItems
= newItemCount
- 1;
1261 while (sourceIndexNewItems
>= 0) {
1262 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1263 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1264 // Move an existing item to its new position. If any new items
1265 // are behind it, push the item range to itemRanges.
1266 if (rangeCount
> 0) {
1267 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1271 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1272 --sourceIndexExistingItems
;
1274 // Insert a new item into the list.
1276 m_itemData
[targetIndex
] = newItem
;
1277 --sourceIndexNewItems
;
1282 // Push the final item range to itemRanges.
1283 if (rangeCount
> 0) {
1284 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1287 // Note that itemRanges is still sorted in reverse order.
1288 std::reverse(itemRanges
.begin(), itemRanges
.end());
1291 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1292 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1295 Q_EMIT
itemsInserted(itemRanges
);
1297 #ifdef KFILEITEMMODEL_DEBUG
1298 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1302 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1304 if (itemRanges
.isEmpty()) {
1310 // Step 1: Remove the items from m_itemData, and free the ItemData.
1311 int removedItemsCount
= 0;
1312 for (const KItemRange
& range
: itemRanges
) {
1313 removedItemsCount
+= range
.count
;
1315 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1316 if (behavior
== DeleteItemData
) {
1317 delete m_itemData
.at(index
);
1320 m_itemData
[index
] = nullptr;
1324 // Step 2: Remove the ItemData pointers from the list m_itemData.
1325 int target
= itemRanges
.at(0).index
;
1326 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1329 const int oldItemDataCount
= m_itemData
.count();
1330 while (source
< oldItemDataCount
) {
1331 m_itemData
[target
] = m_itemData
[source
];
1335 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1336 // Skip the items in the next removed range.
1337 source
+= itemRanges
.at(nextRange
).count
;
1342 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1344 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1345 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1348 Q_EMIT
itemsRemoved(itemRanges
);
1351 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1353 if (m_sortRole
== TypeRole
) {
1354 // Try to resolve the MIME-types synchronously to prevent a reordering of
1355 // the items when sorting by type (per default MIME-types are resolved
1356 // asynchronously by KFileItemModelRolesUpdater).
1357 determineMimeTypes(items
, 200);
1360 const int parentIndex
= index(parentUrl
);
1361 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1363 QList
<ItemData
*> itemDataList
;
1364 itemDataList
.reserve(items
.count());
1366 for (const KFileItem
& item
: items
) {
1367 ItemData
* itemData
= new ItemData();
1368 itemData
->item
= item
;
1369 itemData
->parent
= parentItem
;
1370 itemDataList
.append(itemData
);
1373 return itemDataList
;
1376 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1378 switch (m_sortRole
) {
1379 case PermissionsRole
:
1382 case DestinationRole
:
1384 case DeletionTimeRole
:
1385 // These roles can be determined with retrieveData, and they have to be stored
1386 // in the QHash "values" for the sorting.
1387 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1388 if (itemData
->values
.isEmpty()) {
1389 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1395 // At least store the data including the file type for items with known MIME type.
1396 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1397 if (itemData
->values
.isEmpty()) {
1398 const KFileItem item
= itemData
->item
;
1399 if (item
.isDir() || item
.isMimeTypeKnown()) {
1400 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1407 // The other roles are either resolved by KFileItemModelRolesUpdater
1408 // (this includes the SizeRole for directories), or they do not need
1409 // to be stored in the QHash "values" for sorting because the data can
1410 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1416 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1418 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1419 // if the corresponding item is expanded, and it is not a top-level item.
1420 const ItemData
* parent
= data
->parent
;
1422 if (parent
->parent
) {
1423 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1424 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1433 void KFileItemModel::removeExpandedItems()
1435 QVector
<int> indexesToRemove
;
1437 const int maxIndex
= m_itemData
.count() - 1;
1438 for (int i
= 0; i
<= maxIndex
; ++i
) {
1439 const ItemData
* itemData
= m_itemData
.at(i
);
1440 if (itemData
->parent
) {
1441 indexesToRemove
.append(i
);
1445 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1446 m_expandedDirs
.clear();
1448 // Also remove all filtered items which have a parent.
1449 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1450 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1453 if (it
.value()->parent
) {
1455 it
= m_filteredItems
.erase(it
);
1462 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1464 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1466 // Trigger a resorting if necessary. Note that this can happen even if the sort
1467 // role has not changed at all because the file name can be used as a fallback.
1468 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1469 for (const KItemRange
& range
: itemRanges
) {
1470 bool needsResorting
= false;
1472 const int first
= range
.index
;
1473 const int last
= range
.index
+ range
.count
- 1;
1475 // Resorting the model is necessary if
1476 // (a) The first item in the range is "lessThan" its predecessor,
1477 // (b) the successor of the last item is "lessThan" the last item, or
1478 // (c) the internal order of the items in the range is incorrect.
1480 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1481 needsResorting
= true;
1482 } else if (last
< count() - 1
1483 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1484 needsResorting
= true;
1486 for (int index
= first
; index
< last
; ++index
) {
1487 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1488 needsResorting
= true;
1494 if (needsResorting
) {
1495 m_resortAllItemsTimer
->start();
1501 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1502 // The position is still correct, but the groups might have changed
1503 // if the changed item is either the first or the last item in a
1505 // In principle, we could try to find out if the item really is the
1506 // first or last one in its group and then update the groups
1507 // (possibly with a delayed timer to make sure that we don't
1508 // re-calculate the groups very often if items are updated one by
1509 // one), but starting m_resortAllItemsTimer is easier.
1510 m_resortAllItemsTimer
->start();
1514 void KFileItemModel::resetRoles()
1516 for (int i
= 0; i
< RolesCount
; ++i
) {
1517 m_requestRole
[i
] = false;
1521 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1523 static QHash
<QByteArray
, RoleType
> roles
;
1524 if (roles
.isEmpty()) {
1525 // Insert user visible roles that can be accessed with
1526 // KFileItemModel::roleInformation()
1528 const RoleInfoMap
* map
= rolesInfoMap(count
);
1529 for (int i
= 0; i
< count
; ++i
) {
1530 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1533 // Insert internal roles (take care to synchronize the implementation
1534 // with KFileItemModel::roleForType() in case if a change is done).
1535 roles
.insert("isDir", IsDirRole
);
1536 roles
.insert("isLink", IsLinkRole
);
1537 roles
.insert("isHidden", IsHiddenRole
);
1538 roles
.insert("isExpanded", IsExpandedRole
);
1539 roles
.insert("isExpandable", IsExpandableRole
);
1540 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1542 Q_ASSERT(roles
.count() == RolesCount
);
1545 return roles
.value(role
, NoRole
);
1548 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1550 static QHash
<RoleType
, QByteArray
> roles
;
1551 if (roles
.isEmpty()) {
1552 // Insert user visible roles that can be accessed with
1553 // KFileItemModel::roleInformation()
1555 const RoleInfoMap
* map
= rolesInfoMap(count
);
1556 for (int i
= 0; i
< count
; ++i
) {
1557 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1560 // Insert internal roles (take care to synchronize the implementation
1561 // with KFileItemModel::typeForRole() in case if a change is done).
1562 roles
.insert(IsDirRole
, "isDir");
1563 roles
.insert(IsLinkRole
, "isLink");
1564 roles
.insert(IsHiddenRole
, "isHidden");
1565 roles
.insert(IsExpandedRole
, "isExpanded");
1566 roles
.insert(IsExpandableRole
, "isExpandable");
1567 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1569 Q_ASSERT(roles
.count() == RolesCount
);
1572 return roles
.value(roleType
);
1575 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1577 // It is important to insert only roles that are fast to retrieve. E.g.
1578 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1579 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1580 QHash
<QByteArray
, QVariant
> data
;
1581 data
.insert(sharedValue("url"), item
.url());
1583 const bool isDir
= item
.isDir();
1584 if (m_requestRole
[IsDirRole
] && isDir
) {
1585 data
.insert(sharedValue("isDir"), true);
1588 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1589 data
.insert(sharedValue("isLink"), true);
1592 if (m_requestRole
[IsHiddenRole
]) {
1593 data
.insert(sharedValue("isHidden"), item
.isHidden());
1596 if (m_requestRole
[NameRole
]) {
1597 data
.insert(sharedValue("text"), item
.text());
1600 if (m_requestRole
[SizeRole
] && !isDir
) {
1601 data
.insert(sharedValue("size"), item
.size());
1604 if (m_requestRole
[ModificationTimeRole
]) {
1605 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1606 // having several thousands of items. Instead read the raw number from UDSEntry directly
1607 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1608 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1609 data
.insert(sharedValue("modificationtime"), dateTime
);
1612 if (m_requestRole
[CreationTimeRole
]) {
1613 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1614 // having several thousands of items. Instead read the raw number from UDSEntry directly
1615 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1616 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1617 data
.insert(sharedValue("creationtime"), dateTime
);
1620 if (m_requestRole
[AccessTimeRole
]) {
1621 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1622 // having several thousands of items. Instead read the raw number from UDSEntry directly
1623 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1624 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1625 data
.insert(sharedValue("accesstime"), dateTime
);
1628 if (m_requestRole
[PermissionsRole
]) {
1629 data
.insert(sharedValue("permissions"), item
.permissionsString());
1632 if (m_requestRole
[OwnerRole
]) {
1633 data
.insert(sharedValue("owner"), item
.user());
1636 if (m_requestRole
[GroupRole
]) {
1637 data
.insert(sharedValue("group"), item
.group());
1640 if (m_requestRole
[DestinationRole
]) {
1641 QString destination
= item
.linkDest();
1642 if (destination
.isEmpty()) {
1643 destination
= QLatin1Char('-');
1645 data
.insert(sharedValue("destination"), destination
);
1648 if (m_requestRole
[PathRole
]) {
1650 if (item
.url().scheme() == QLatin1String("trash")) {
1651 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1653 // For performance reasons cache the home-path in a static QString
1654 // (see QDir::homePath() for more details)
1655 static QString homePath
;
1656 if (homePath
.isEmpty()) {
1657 homePath
= QDir::homePath();
1660 path
= item
.localPath();
1661 if (path
.startsWith(homePath
)) {
1662 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1666 const int index
= path
.lastIndexOf(item
.text());
1667 path
= path
.mid(0, index
- 1);
1668 data
.insert(sharedValue("path"), path
);
1671 if (m_requestRole
[DeletionTimeRole
]) {
1672 QDateTime deletionTime
;
1673 if (item
.url().scheme() == QLatin1String("trash")) {
1674 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1676 data
.insert(sharedValue("deletiontime"), deletionTime
);
1679 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1680 data
.insert(sharedValue("isExpandable"), true);
1683 if (m_requestRole
[ExpandedParentsCountRole
]) {
1685 const int level
= expandedParentsCount(parent
) + 1;
1686 data
.insert(sharedValue("expandedParentsCount"), level
);
1690 if (item
.isMimeTypeKnown()) {
1691 QString iconName
= item
.iconName();
1692 if (!QIcon::hasThemeIcon(iconName
)) {
1693 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1694 iconName
= mimeType
.genericIconName();
1697 data
.insert(sharedValue("iconName"), iconName
);
1699 if (m_requestRole
[TypeRole
]) {
1700 data
.insert(sharedValue("type"), item
.mimeComment());
1702 } else if (m_requestRole
[TypeRole
] && isDir
) {
1703 static const QString folderMimeType
= item
.mimeComment();
1704 data
.insert(sharedValue("type"), folderMimeType
);
1710 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1714 if (a
->parent
!= b
->parent
) {
1715 const int expansionLevelA
= expandedParentsCount(a
);
1716 const int expansionLevelB
= expandedParentsCount(b
);
1718 // If b has a higher expansion level than a, check if a is a parent
1719 // of b, and make sure that both expansion levels are equal otherwise.
1720 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1721 if (b
->parent
== a
) {
1727 // If a has a higher expansion level than a, check if b is a parent
1728 // of a, and make sure that both expansion levels are equal otherwise.
1729 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1730 if (a
->parent
== b
) {
1736 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1738 // Compare the last parents of a and b which are different.
1739 while (a
->parent
!= b
->parent
) {
1745 // Show hidden files and folders last
1746 if (m_sortHiddenLast
) {
1747 const bool isHiddenA
= a
->item
.isHidden();
1748 const bool isHiddenB
= b
->item
.isHidden();
1749 if (isHiddenA
&& !isHiddenB
) {
1751 } else if (!isHiddenA
&& isHiddenB
) {
1756 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1757 const bool isDirA
= a
->item
.isDir();
1758 const bool isDirB
= b
->item
.isDir();
1759 if (isDirA
&& !isDirB
) {
1761 } else if (!isDirA
&& isDirB
) {
1766 result
= sortRoleCompare(a
, b
, collator
);
1768 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1771 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1772 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1774 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1776 return lessThan(a
, b
, m_collator
);
1779 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1780 // Sorting by string can be expensive, in particular if natural sorting is
1781 // enabled. Use all CPU cores to speed up the sorting process.
1782 static const int numberOfThreads
= QThread::idealThreadCount();
1783 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1785 // Sorting by other roles is quite fast. Use only one thread to prevent
1786 // problems caused by non-reentrant comparison functions, see
1787 // https://bugs.kde.org/show_bug.cgi?id=312679
1788 mergeSort(begin
, end
, lambdaLessThan
);
1792 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1794 const KFileItem
& itemA
= a
->item
;
1795 const KFileItem
& itemB
= b
->item
;
1799 switch (m_sortRole
) {
1801 // The name role is handled as default fallback after the switch
1805 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1806 // folders first then
1807 // items A and B are folders thanks to lessThan checks
1808 auto valueA
= a
->values
.value("count");
1809 auto valueB
= b
->values
.value("count");
1810 if (valueA
.isNull()) {
1811 if (valueB
.isNull()) {
1818 } else if (valueB
.isNull()) {
1822 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1825 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1834 KIO::filesize_t sizeA
= 0;
1835 if (itemA
.isDir()) {
1836 sizeA
= a
->values
.value("size").toULongLong();
1838 sizeA
= itemA
.size();
1840 KIO::filesize_t sizeB
= 0;
1841 if (itemB
.isDir()) {
1842 sizeB
= b
->values
.value("size").toULongLong();
1844 sizeB
= itemB
.size();
1846 if (sizeA
> sizeB
) {
1848 } else if (sizeA
< sizeB
) {
1856 case ModificationTimeRole
: {
1857 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1858 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1859 if (dateTimeA
< dateTimeB
) {
1861 } else if (dateTimeA
> dateTimeB
) {
1867 case CreationTimeRole
: {
1868 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1869 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1870 if (dateTimeA
< dateTimeB
) {
1872 } else if (dateTimeA
> dateTimeB
) {
1878 case DeletionTimeRole
: {
1879 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1880 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1881 if (dateTimeA
< dateTimeB
) {
1883 } else if (dateTimeA
> dateTimeB
) {
1895 case ReleaseYearRole
: {
1896 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1901 const QByteArray role
= roleForType(m_sortRole
);
1902 const QString roleValueA
= a
->values
.value(role
).toString();
1903 const QString roleValueB
= b
->values
.value(role
).toString();
1904 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1906 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1908 } else if (isRoleValueNatural(m_sortRole
)) {
1909 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1911 result
= QString::compare(roleValueA
, roleValueB
);
1919 // The current sort role was sufficient to define an order
1923 // Fallback #1: Compare the text of the items
1924 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1929 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1930 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1935 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1936 // equal. In this case a comparison of the URL is done which is unique in all cases
1937 // within KDirLister.
1938 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1941 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1943 QMutexLocker
collatorLock(s_collatorMutex());
1945 if (m_naturalSorting
) {
1946 return collator
.compare(a
, b
);
1949 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1950 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1951 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1952 // comparison, still a deterministic sort order is required. A case sensitive
1953 // comparison is done as fallback.
1957 return QString::compare(a
, b
, Qt::CaseSensitive
);
1960 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1962 Q_ASSERT(!m_itemData
.isEmpty());
1964 const int maxIndex
= count() - 1;
1965 QList
<QPair
<int, QVariant
> > groups
;
1969 for (int i
= 0; i
<= maxIndex
; ++i
) {
1970 if (isChildItem(i
)) {
1974 const QString name
= m_itemData
.at(i
)->item
.text();
1976 // Use the first character of the name as group indication
1977 QChar newFirstChar
= name
.at(0).toUpper();
1978 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1979 newFirstChar
= name
.at(1).toUpper();
1982 if (firstChar
!= newFirstChar
) {
1983 QString newGroupValue
;
1984 if (newFirstChar
.isLetter()) {
1986 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1987 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1989 // Try to find a matching group in the range 'A' to 'Z'.
1990 static std::vector
<QChar
> lettersAtoZ
;
1991 lettersAtoZ
.reserve('Z' - 'A' + 1);
1992 if (lettersAtoZ
.empty()) {
1993 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1994 lettersAtoZ
.push_back(QLatin1Char(c
));
1998 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1999 return m_collator
.compare(c1
, c2
) < 0;
2002 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2003 if (it
!= lettersAtoZ
.end()) {
2004 if (localeAwareLessThan(newFirstChar
, *it
)) {
2005 // newFirstChar belongs to the group preceding *it.
2006 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2009 newGroupValue
= *it
;
2013 // Symbols from non Latin-based scripts
2014 newGroupValue
= newFirstChar
;
2016 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2017 // Apply group '0 - 9' for any name that starts with a digit
2018 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2020 newGroupValue
= i18nc("@title:group", "Others");
2023 if (newGroupValue
!= groupValue
) {
2024 groupValue
= newGroupValue
;
2025 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2028 firstChar
= newFirstChar
;
2034 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2036 Q_ASSERT(!m_itemData
.isEmpty());
2038 const int maxIndex
= count() - 1;
2039 QList
<QPair
<int, QVariant
> > groups
;
2042 for (int i
= 0; i
<= maxIndex
; ++i
) {
2043 if (isChildItem(i
)) {
2047 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2048 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2049 QString newGroupValue
;
2050 if (!item
.isNull() && item
.isDir()) {
2051 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2052 newGroupValue
= i18nc("@title:group Size", "Folders");
2054 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2058 if (newGroupValue
.isEmpty()) {
2059 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2060 newGroupValue
= i18nc("@title:group Size", "Small");
2061 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2062 newGroupValue
= i18nc("@title:group Size", "Medium");
2064 newGroupValue
= i18nc("@title:group Size", "Big");
2068 if (newGroupValue
!= groupValue
) {
2069 groupValue
= newGroupValue
;
2070 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2077 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2079 Q_ASSERT(!m_itemData
.isEmpty());
2081 const int maxIndex
= count() - 1;
2082 QList
<QPair
<int, QVariant
> > groups
;
2084 const QDate currentDate
= QDate::currentDate();
2086 QDate previousFileDate
;
2088 for (int i
= 0; i
<= maxIndex
; ++i
) {
2089 if (isChildItem(i
)) {
2093 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2094 const QDate fileDate
= fileTime
.date();
2095 if (fileDate
== previousFileDate
) {
2096 // The current item is in the same group as the previous item
2099 previousFileDate
= fileDate
;
2101 const int daysDistance
= fileDate
.daysTo(currentDate
);
2103 QString newGroupValue
;
2104 if (currentDate
.year() == fileDate
.year() &&
2105 currentDate
.month() == fileDate
.month()) {
2107 switch (daysDistance
/ 7) {
2109 switch (daysDistance
) {
2110 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2111 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2113 newGroupValue
= fileTime
.toString(
2114 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2115 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2116 "with context @title:group Date", "%1", newGroupValue
);
2120 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2123 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2126 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2130 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2136 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2137 if (lastMonthDate
.year() == fileDate
.year() &&
2138 lastMonthDate
.month() == fileDate
.month()) {
2140 if (daysDistance
== 1) {
2141 const KLocalizedString format
= ki18nc("@title:group Date: "
2142 "MMMM is full month name in current locale, and yyyy is "
2143 "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)");
2144 const QString translatedFormat
= format
.toString();
2145 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2146 newGroupValue
= fileTime
.toString(translatedFormat
);
2147 newGroupValue
= i18nc("Can be used to script translation of "
2148 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2149 "%1", newGroupValue
);
2151 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2152 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2153 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2155 } else if (daysDistance
<= 7) {
2156 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2157 "The week day name: dddd, MMMM is full month name "
2158 "in current locale, and yyyy is full year number.",
2159 "dddd (MMMM, yyyy)"));
2160 newGroupValue
= i18nc("Can be used to script translation of "
2161 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2162 "%1", newGroupValue
);
2163 } else if (daysDistance
<= 7 * 2) {
2164 const KLocalizedString format
= ki18nc("@title:group Date: "
2165 "MMMM is full month name in current locale, and yyyy is "
2166 "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)");
2167 const QString translatedFormat
= format
.toString();
2168 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2169 newGroupValue
= fileTime
.toString(translatedFormat
);
2170 newGroupValue
= i18nc("Can be used to script translation of "
2171 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2172 "%1", newGroupValue
);
2174 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2175 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2176 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2178 } else if (daysDistance
<= 7 * 3) {
2179 const KLocalizedString format
= ki18nc("@title:group Date: "
2180 "MMMM is full month name in current locale, and yyyy is "
2181 "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)");
2182 const QString translatedFormat
= format
.toString();
2183 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2184 newGroupValue
= fileTime
.toString(translatedFormat
);
2185 newGroupValue
= i18nc("Can be used to script translation of "
2186 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2187 "%1", newGroupValue
);
2189 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2190 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2191 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2193 } else if (daysDistance
<= 7 * 4) {
2194 const KLocalizedString format
= ki18nc("@title:group Date: "
2195 "MMMM is full month name in current locale, and yyyy is "
2196 "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)");
2197 const QString translatedFormat
= format
.toString();
2198 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2199 newGroupValue
= fileTime
.toString(translatedFormat
);
2200 newGroupValue
= i18nc("Can be used to script translation of "
2201 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2202 "%1", newGroupValue
);
2204 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2205 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2206 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2209 const KLocalizedString format
= ki18nc("@title:group Date: "
2210 "MMMM is full month name in current locale, and yyyy is "
2211 "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");
2212 const QString translatedFormat
= format
.toString();
2213 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2214 newGroupValue
= fileTime
.toString(translatedFormat
);
2215 newGroupValue
= i18nc("Can be used to script translation of "
2216 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2217 "%1", newGroupValue
);
2219 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2220 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2221 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2225 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2226 "The month and year: MMMM is full month name in current locale, "
2227 "and yyyy is full year number", "MMMM, yyyy"));
2228 newGroupValue
= i18nc("Can be used to script translation of "
2229 "\"MMMM, yyyy\" with context @title:group Date",
2230 "%1", newGroupValue
);
2234 if (newGroupValue
!= groupValue
) {
2235 groupValue
= newGroupValue
;
2236 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2243 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2245 Q_ASSERT(!m_itemData
.isEmpty());
2247 const int maxIndex
= count() - 1;
2248 QList
<QPair
<int, QVariant
> > groups
;
2250 QString permissionsString
;
2252 for (int i
= 0; i
<= maxIndex
; ++i
) {
2253 if (isChildItem(i
)) {
2257 const ItemData
* itemData
= m_itemData
.at(i
);
2258 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2259 if (newPermissionsString
== permissionsString
) {
2262 permissionsString
= newPermissionsString
;
2264 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2268 if (info
.permission(QFile::ReadUser
)) {
2269 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2271 if (info
.permission(QFile::WriteUser
)) {
2272 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2274 if (info
.permission(QFile::ExeUser
)) {
2275 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2277 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2281 if (info
.permission(QFile::ReadGroup
)) {
2282 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2284 if (info
.permission(QFile::WriteGroup
)) {
2285 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2287 if (info
.permission(QFile::ExeGroup
)) {
2288 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2290 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2292 // Set others string
2294 if (info
.permission(QFile::ReadOther
)) {
2295 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2297 if (info
.permission(QFile::WriteOther
)) {
2298 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2300 if (info
.permission(QFile::ExeOther
)) {
2301 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2303 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2305 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2306 if (newGroupValue
!= groupValue
) {
2307 groupValue
= newGroupValue
;
2308 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2315 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2317 Q_ASSERT(!m_itemData
.isEmpty());
2319 const int maxIndex
= count() - 1;
2320 QList
<QPair
<int, QVariant
> > groups
;
2322 int groupValue
= -1;
2323 for (int i
= 0; i
<= maxIndex
; ++i
) {
2324 if (isChildItem(i
)) {
2327 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2328 if (newGroupValue
!= groupValue
) {
2329 groupValue
= newGroupValue
;
2330 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2337 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2339 Q_ASSERT(!m_itemData
.isEmpty());
2341 const int maxIndex
= count() - 1;
2342 QList
<QPair
<int, QVariant
> > groups
;
2344 bool isFirstGroupValue
= true;
2346 for (int i
= 0; i
<= maxIndex
; ++i
) {
2347 if (isChildItem(i
)) {
2350 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2351 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2352 groupValue
= newGroupValue
;
2353 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2354 isFirstGroupValue
= false;
2361 void KFileItemModel::emitSortProgress(int resolvedCount
)
2363 // Be tolerant against a resolvedCount with a wrong range.
2364 // Although there should not be a case where KFileItemModelRolesUpdater
2365 // (= caller) provides a wrong range, it is important to emit
2366 // a useful progress information even if there is an unexpected
2367 // implementation issue.
2369 const int itemCount
= count();
2370 if (resolvedCount
>= itemCount
) {
2371 m_sortingProgressPercent
= -1;
2372 if (m_resortAllItemsTimer
->isActive()) {
2373 m_resortAllItemsTimer
->stop();
2377 Q_EMIT
directorySortingProgress(100);
2378 } else if (itemCount
> 0) {
2379 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2381 const int progress
= resolvedCount
* 100 / itemCount
;
2382 if (m_sortingProgressPercent
!= progress
) {
2383 m_sortingProgressPercent
= progress
;
2384 Q_EMIT
directorySortingProgress(progress
);
2389 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2391 static const RoleInfoMap rolesInfoMap
[] = {
2392 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2393 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2394 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2395 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2396 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2397 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2398 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2399 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2400 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2401 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2402 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2403 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2404 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2405 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2406 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2407 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2408 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2409 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2410 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2411 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2412 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2413 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2414 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2415 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2416 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2417 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2418 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2419 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2420 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2421 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2422 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2423 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2424 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2425 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2428 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2429 return rolesInfoMap
;
2432 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2434 QElapsedTimer timer
;
2436 for (const KFileItem
& item
: items
) {
2437 // Only determine mime types for files here. For directories,
2438 // KFileItem::determineMimeType() reads the .directory file inside to
2439 // load the icon, but this is not necessary at all if we just need the
2440 // type. Some special code for setting the correct mime type for
2441 // directories is in retrieveData().
2442 if (!item
.isDir()) {
2443 item
.determineMimeType();
2446 if (timer
.elapsed() > timeout
) {
2447 // Don't block the user interface, let the remaining items
2448 // be resolved asynchronously.
2454 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2456 static QSet
<QByteArray
> pool
;
2457 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2459 if (it
!= pool
.constEnd()) {
2467 bool KFileItemModel::isConsistent() const
2469 // m_items may contain less items than m_itemData because m_items
2470 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2471 if (m_items
.count() > m_itemData
.count()) {
2475 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2476 // Check if m_items and m_itemData are consistent.
2477 const KFileItem item
= fileItem(i
);
2478 if (item
.isNull()) {
2479 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2483 const int itemIndex
= index(item
);
2484 if (itemIndex
!= i
) {
2485 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2489 // Check if the items are sorted correctly.
2490 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2491 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2492 << fileItem(i
- 1) << fileItem(i
);
2496 // Check if all parent-child relationships are consistent.
2497 const ItemData
* data
= m_itemData
.at(i
);
2498 const ItemData
* parent
= data
->parent
;
2500 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2501 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2505 const int parentIndex
= index(parent
->item
);
2506 if (parentIndex
>= i
) {
2507 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2516 void KFileItemModel::slotListerError(KIO::Job
*job
)
2518 if (job
->error() == KIO::ERR_IS_FILE
) {
2519 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2520 Q_EMIT
urlIsFileError(listJob
->url());
2523 const QString errorString
= job
->errorString();
2524 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));