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 // Contains the indexes of the currently visible items
1102 // that should get hidden and hence moved to m_filteredItems.
1103 QVector
<int> newFilteredIndexes
;
1105 // Contains currently hidden items that should
1106 // get visible and hence removed from m_filteredItems
1107 QList
<ItemData
*> newVisibleItems
;
1109 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1110 while (it
.hasNext()) {
1111 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1112 const KFileItem
& oldItem
= itemPair
.first
;
1113 const KFileItem
& newItem
= itemPair
.second
;
1114 const int indexForItem
= index(oldItem
);
1115 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1116 if (indexForItem
>= 0) {
1117 m_itemData
[indexForItem
]->item
= newItem
;
1119 // Keep old values as long as possible if they could not retrieved synchronously yet.
1120 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1121 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1122 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1123 while (it
.hasNext()) {
1125 const QByteArray
& role
= it
.key();
1126 if (itemData
->values
.value(role
) != it
.value()) {
1127 itemData
->values
.insert(role
, it
.value());
1128 changedRoles
.insert(role
);
1132 m_items
.remove(oldItem
.url());
1133 if (newItemMatchesFilter
) {
1134 m_items
.insert(newItem
.url(), indexForItem
);
1135 changedFiles
.append(newItem
);
1136 indexes
.append(indexForItem
);
1138 newFilteredIndexes
.append(indexForItem
);
1139 m_filteredItems
.insert(newItem
, itemData
);
1142 // Check if 'oldItem' is one of the filtered items.
1143 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1144 if (it
!= m_filteredItems
.end()) {
1145 ItemData
* itemData
= it
.value();
1146 itemData
->item
= newItem
;
1148 // The data stored in 'values' might have changed. Therefore, we clear
1149 // 'values' and re-populate it the next time it is requested via data(int).
1150 itemData
->values
.clear();
1152 m_filteredItems
.erase(it
);
1153 if (newItemMatchesFilter
) {
1154 newVisibleItems
.append(itemData
);
1156 m_filteredItems
.insert(newItem
, itemData
);
1162 // Hide items, previously visible that should get hidden
1163 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1164 removeItems(removedRanges
, KeepItemData
);
1166 // Show previously hidden items that should get visible
1167 insertItems(newVisibleItems
);
1169 // If the changed items have been created recently, they might not be in m_items yet.
1170 // In that case, the list 'indexes' might be empty.
1171 if (indexes
.isEmpty()) {
1175 // Extract the item-ranges out of the changed indexes
1176 std::sort(indexes
.begin(), indexes
.end());
1177 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1178 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1180 Q_EMIT
fileItemsChanged(changedFiles
);
1183 void KFileItemModel::slotClear()
1185 #ifdef KFILEITEMMODEL_DEBUG
1186 qCDebug(DolphinDebug
) << "Clearing all items";
1189 qDeleteAll(m_filteredItems
);
1190 m_filteredItems
.clear();
1193 m_maximumUpdateIntervalTimer
->stop();
1194 m_resortAllItemsTimer
->stop();
1196 qDeleteAll(m_pendingItemsToInsert
);
1197 m_pendingItemsToInsert
.clear();
1199 const int removedCount
= m_itemData
.count();
1200 if (removedCount
> 0) {
1201 qDeleteAll(m_itemData
);
1204 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1207 m_expandedDirs
.clear();
1210 void KFileItemModel::slotSortingChoiceChanged()
1212 loadSortingSettings();
1216 void KFileItemModel::dispatchPendingItemsToInsert()
1218 if (!m_pendingItemsToInsert
.isEmpty()) {
1219 insertItems(m_pendingItemsToInsert
);
1220 m_pendingItemsToInsert
.clear();
1224 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1226 if (newItems
.isEmpty()) {
1230 #ifdef KFILEITEMMODEL_DEBUG
1231 QElapsedTimer timer
;
1233 qCDebug(DolphinDebug
) << "===========================================================";
1234 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1238 prepareItemsForSorting(newItems
);
1240 // Natural sorting of items can be very slow. However, it becomes much faster
1241 // if the input sequence is already mostly sorted. Therefore, we first sort
1242 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1243 if (m_naturalSorting
) {
1244 if (m_sortRole
== NameRole
) {
1245 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1246 } else if (isRoleValueNatural(m_sortRole
)) {
1247 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1249 const QByteArray role
= roleForType(m_sortRole
);
1250 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1252 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1256 sort(newItems
.begin(), newItems
.end());
1258 #ifdef KFILEITEMMODEL_DEBUG
1259 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1262 KItemRangeList itemRanges
;
1263 const int existingItemCount
= m_itemData
.count();
1264 const int newItemCount
= newItems
.count();
1265 const int totalItemCount
= existingItemCount
+ newItemCount
;
1267 if (existingItemCount
== 0) {
1268 // Optimization for the common special case that there are no
1269 // items in the model yet. Happens, e.g., when entering a folder.
1270 m_itemData
= newItems
;
1271 itemRanges
<< KItemRange(0, newItemCount
);
1273 m_itemData
.reserve(totalItemCount
);
1274 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1275 m_itemData
.append(nullptr);
1278 // We build the new list m_itemData in reverse order to minimize
1279 // the number of moves and guarantee O(N) complexity.
1280 int targetIndex
= totalItemCount
- 1;
1281 int sourceIndexExistingItems
= existingItemCount
- 1;
1282 int sourceIndexNewItems
= newItemCount
- 1;
1286 while (sourceIndexNewItems
>= 0) {
1287 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1288 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1289 // Move an existing item to its new position. If any new items
1290 // are behind it, push the item range to itemRanges.
1291 if (rangeCount
> 0) {
1292 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1296 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1297 --sourceIndexExistingItems
;
1299 // Insert a new item into the list.
1301 m_itemData
[targetIndex
] = newItem
;
1302 --sourceIndexNewItems
;
1307 // Push the final item range to itemRanges.
1308 if (rangeCount
> 0) {
1309 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1312 // Note that itemRanges is still sorted in reverse order.
1313 std::reverse(itemRanges
.begin(), itemRanges
.end());
1316 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1317 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1320 Q_EMIT
itemsInserted(itemRanges
);
1322 #ifdef KFILEITEMMODEL_DEBUG
1323 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1327 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1329 if (itemRanges
.isEmpty()) {
1335 // Step 1: Remove the items from m_itemData, and free the ItemData.
1336 int removedItemsCount
= 0;
1337 for (const KItemRange
& range
: itemRanges
) {
1338 removedItemsCount
+= range
.count
;
1340 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1341 if (behavior
== DeleteItemData
) {
1342 delete m_itemData
.at(index
);
1345 m_itemData
[index
] = nullptr;
1349 // Step 2: Remove the ItemData pointers from the list m_itemData.
1350 int target
= itemRanges
.at(0).index
;
1351 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1354 const int oldItemDataCount
= m_itemData
.count();
1355 while (source
< oldItemDataCount
) {
1356 m_itemData
[target
] = m_itemData
[source
];
1360 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1361 // Skip the items in the next removed range.
1362 source
+= itemRanges
.at(nextRange
).count
;
1367 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1369 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1370 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1373 Q_EMIT
itemsRemoved(itemRanges
);
1376 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1378 if (m_sortRole
== TypeRole
) {
1379 // Try to resolve the MIME-types synchronously to prevent a reordering of
1380 // the items when sorting by type (per default MIME-types are resolved
1381 // asynchronously by KFileItemModelRolesUpdater).
1382 determineMimeTypes(items
, 200);
1385 const int parentIndex
= index(parentUrl
);
1386 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1388 QList
<ItemData
*> itemDataList
;
1389 itemDataList
.reserve(items
.count());
1391 for (const KFileItem
& item
: items
) {
1392 ItemData
* itemData
= new ItemData();
1393 itemData
->item
= item
;
1394 itemData
->parent
= parentItem
;
1395 itemDataList
.append(itemData
);
1398 return itemDataList
;
1401 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1403 switch (m_sortRole
) {
1404 case PermissionsRole
:
1407 case DestinationRole
:
1409 case DeletionTimeRole
:
1410 // These roles can be determined with retrieveData, and they have to be stored
1411 // in the QHash "values" for the sorting.
1412 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1413 if (itemData
->values
.isEmpty()) {
1414 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1420 // At least store the data including the file type for items with known MIME type.
1421 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1422 if (itemData
->values
.isEmpty()) {
1423 const KFileItem item
= itemData
->item
;
1424 if (item
.isDir() || item
.isMimeTypeKnown()) {
1425 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1432 // The other roles are either resolved by KFileItemModelRolesUpdater
1433 // (this includes the SizeRole for directories), or they do not need
1434 // to be stored in the QHash "values" for sorting because the data can
1435 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1441 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1443 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1444 // if the corresponding item is expanded, and it is not a top-level item.
1445 const ItemData
* parent
= data
->parent
;
1447 if (parent
->parent
) {
1448 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1449 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1458 void KFileItemModel::removeExpandedItems()
1460 QVector
<int> indexesToRemove
;
1462 const int maxIndex
= m_itemData
.count() - 1;
1463 for (int i
= 0; i
<= maxIndex
; ++i
) {
1464 const ItemData
* itemData
= m_itemData
.at(i
);
1465 if (itemData
->parent
) {
1466 indexesToRemove
.append(i
);
1470 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1471 m_expandedDirs
.clear();
1473 // Also remove all filtered items which have a parent.
1474 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1475 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1478 if (it
.value()->parent
) {
1480 it
= m_filteredItems
.erase(it
);
1487 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1489 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1491 // Trigger a resorting if necessary. Note that this can happen even if the sort
1492 // role has not changed at all because the file name can be used as a fallback.
1493 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1494 for (const KItemRange
& range
: itemRanges
) {
1495 bool needsResorting
= false;
1497 const int first
= range
.index
;
1498 const int last
= range
.index
+ range
.count
- 1;
1500 // Resorting the model is necessary if
1501 // (a) The first item in the range is "lessThan" its predecessor,
1502 // (b) the successor of the last item is "lessThan" the last item, or
1503 // (c) the internal order of the items in the range is incorrect.
1505 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1506 needsResorting
= true;
1507 } else if (last
< count() - 1
1508 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1509 needsResorting
= true;
1511 for (int index
= first
; index
< last
; ++index
) {
1512 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1513 needsResorting
= true;
1519 if (needsResorting
) {
1520 m_resortAllItemsTimer
->start();
1526 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1527 // The position is still correct, but the groups might have changed
1528 // if the changed item is either the first or the last item in a
1530 // In principle, we could try to find out if the item really is the
1531 // first or last one in its group and then update the groups
1532 // (possibly with a delayed timer to make sure that we don't
1533 // re-calculate the groups very often if items are updated one by
1534 // one), but starting m_resortAllItemsTimer is easier.
1535 m_resortAllItemsTimer
->start();
1539 void KFileItemModel::resetRoles()
1541 for (int i
= 0; i
< RolesCount
; ++i
) {
1542 m_requestRole
[i
] = false;
1546 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1548 static QHash
<QByteArray
, RoleType
> roles
;
1549 if (roles
.isEmpty()) {
1550 // Insert user visible roles that can be accessed with
1551 // KFileItemModel::roleInformation()
1553 const RoleInfoMap
* map
= rolesInfoMap(count
);
1554 for (int i
= 0; i
< count
; ++i
) {
1555 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1558 // Insert internal roles (take care to synchronize the implementation
1559 // with KFileItemModel::roleForType() in case if a change is done).
1560 roles
.insert("isDir", IsDirRole
);
1561 roles
.insert("isLink", IsLinkRole
);
1562 roles
.insert("isHidden", IsHiddenRole
);
1563 roles
.insert("isExpanded", IsExpandedRole
);
1564 roles
.insert("isExpandable", IsExpandableRole
);
1565 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1567 Q_ASSERT(roles
.count() == RolesCount
);
1570 return roles
.value(role
, NoRole
);
1573 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1575 static QHash
<RoleType
, QByteArray
> roles
;
1576 if (roles
.isEmpty()) {
1577 // Insert user visible roles that can be accessed with
1578 // KFileItemModel::roleInformation()
1580 const RoleInfoMap
* map
= rolesInfoMap(count
);
1581 for (int i
= 0; i
< count
; ++i
) {
1582 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1585 // Insert internal roles (take care to synchronize the implementation
1586 // with KFileItemModel::typeForRole() in case if a change is done).
1587 roles
.insert(IsDirRole
, "isDir");
1588 roles
.insert(IsLinkRole
, "isLink");
1589 roles
.insert(IsHiddenRole
, "isHidden");
1590 roles
.insert(IsExpandedRole
, "isExpanded");
1591 roles
.insert(IsExpandableRole
, "isExpandable");
1592 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1594 Q_ASSERT(roles
.count() == RolesCount
);
1597 return roles
.value(roleType
);
1600 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1602 // It is important to insert only roles that are fast to retrieve. E.g.
1603 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1604 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1605 QHash
<QByteArray
, QVariant
> data
;
1606 data
.insert(sharedValue("url"), item
.url());
1608 const bool isDir
= item
.isDir();
1609 if (m_requestRole
[IsDirRole
] && isDir
) {
1610 data
.insert(sharedValue("isDir"), true);
1613 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1614 data
.insert(sharedValue("isLink"), true);
1617 if (m_requestRole
[IsHiddenRole
]) {
1618 data
.insert(sharedValue("isHidden"), item
.isHidden());
1621 if (m_requestRole
[NameRole
]) {
1622 data
.insert(sharedValue("text"), item
.text());
1625 if (m_requestRole
[SizeRole
] && !isDir
) {
1626 data
.insert(sharedValue("size"), item
.size());
1629 if (m_requestRole
[ModificationTimeRole
]) {
1630 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1631 // having several thousands of items. Instead read the raw number from UDSEntry directly
1632 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1633 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1634 data
.insert(sharedValue("modificationtime"), dateTime
);
1637 if (m_requestRole
[CreationTimeRole
]) {
1638 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1639 // having several thousands of items. Instead read the raw number from UDSEntry directly
1640 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1641 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1642 data
.insert(sharedValue("creationtime"), dateTime
);
1645 if (m_requestRole
[AccessTimeRole
]) {
1646 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1647 // having several thousands of items. Instead read the raw number from UDSEntry directly
1648 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1649 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1650 data
.insert(sharedValue("accesstime"), dateTime
);
1653 if (m_requestRole
[PermissionsRole
]) {
1654 data
.insert(sharedValue("permissions"), item
.permissionsString());
1657 if (m_requestRole
[OwnerRole
]) {
1658 data
.insert(sharedValue("owner"), item
.user());
1661 if (m_requestRole
[GroupRole
]) {
1662 data
.insert(sharedValue("group"), item
.group());
1665 if (m_requestRole
[DestinationRole
]) {
1666 QString destination
= item
.linkDest();
1667 if (destination
.isEmpty()) {
1668 destination
= QLatin1Char('-');
1670 data
.insert(sharedValue("destination"), destination
);
1673 if (m_requestRole
[PathRole
]) {
1675 if (item
.url().scheme() == QLatin1String("trash")) {
1676 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1678 // For performance reasons cache the home-path in a static QString
1679 // (see QDir::homePath() for more details)
1680 static QString homePath
;
1681 if (homePath
.isEmpty()) {
1682 homePath
= QDir::homePath();
1685 path
= item
.localPath();
1686 if (path
.startsWith(homePath
)) {
1687 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1691 const int index
= path
.lastIndexOf(item
.text());
1692 path
= path
.mid(0, index
- 1);
1693 data
.insert(sharedValue("path"), path
);
1696 if (m_requestRole
[DeletionTimeRole
]) {
1697 QDateTime deletionTime
;
1698 if (item
.url().scheme() == QLatin1String("trash")) {
1699 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1701 data
.insert(sharedValue("deletiontime"), deletionTime
);
1704 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1705 data
.insert(sharedValue("isExpandable"), true);
1708 if (m_requestRole
[ExpandedParentsCountRole
]) {
1710 const int level
= expandedParentsCount(parent
) + 1;
1711 data
.insert(sharedValue("expandedParentsCount"), level
);
1715 if (item
.isMimeTypeKnown()) {
1716 QString iconName
= item
.iconName();
1717 if (!QIcon::hasThemeIcon(iconName
)) {
1718 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1719 iconName
= mimeType
.genericIconName();
1722 data
.insert(sharedValue("iconName"), iconName
);
1724 if (m_requestRole
[TypeRole
]) {
1725 data
.insert(sharedValue("type"), item
.mimeComment());
1727 } else if (m_requestRole
[TypeRole
] && isDir
) {
1728 static const QString folderMimeType
= item
.mimeComment();
1729 data
.insert(sharedValue("type"), folderMimeType
);
1735 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1739 if (a
->parent
!= b
->parent
) {
1740 const int expansionLevelA
= expandedParentsCount(a
);
1741 const int expansionLevelB
= expandedParentsCount(b
);
1743 // If b has a higher expansion level than a, check if a is a parent
1744 // of b, and make sure that both expansion levels are equal otherwise.
1745 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1746 if (b
->parent
== a
) {
1752 // If a has a higher expansion level than a, check if b is a parent
1753 // of a, and make sure that both expansion levels are equal otherwise.
1754 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1755 if (a
->parent
== b
) {
1761 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1763 // Compare the last parents of a and b which are different.
1764 while (a
->parent
!= b
->parent
) {
1770 // Show hidden files and folders last
1771 if (m_sortHiddenLast
) {
1772 const bool isHiddenA
= a
->item
.isHidden();
1773 const bool isHiddenB
= b
->item
.isHidden();
1774 if (isHiddenA
&& !isHiddenB
) {
1776 } else if (!isHiddenA
&& isHiddenB
) {
1781 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1782 const bool isDirA
= a
->item
.isDir();
1783 const bool isDirB
= b
->item
.isDir();
1784 if (isDirA
&& !isDirB
) {
1786 } else if (!isDirA
&& isDirB
) {
1791 result
= sortRoleCompare(a
, b
, collator
);
1793 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1796 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1797 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1799 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1801 return lessThan(a
, b
, m_collator
);
1804 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1805 // Sorting by string can be expensive, in particular if natural sorting is
1806 // enabled. Use all CPU cores to speed up the sorting process.
1807 static const int numberOfThreads
= QThread::idealThreadCount();
1808 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1810 // Sorting by other roles is quite fast. Use only one thread to prevent
1811 // problems caused by non-reentrant comparison functions, see
1812 // https://bugs.kde.org/show_bug.cgi?id=312679
1813 mergeSort(begin
, end
, lambdaLessThan
);
1817 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1819 // This function must never return 0, because that would break stable
1820 // sorting, which leads to all kinds of bugs.
1821 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1822 // If two items have equal sort values, let the fallbacks at the bottom of
1823 // the function handle it.
1824 const KFileItem
& itemA
= a
->item
;
1825 const KFileItem
& itemB
= b
->item
;
1829 switch (m_sortRole
) {
1831 // The name role is handled as default fallback after the switch
1835 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1836 // folders first then
1837 // items A and B are folders thanks to lessThan checks
1838 auto valueA
= a
->values
.value("count");
1839 auto valueB
= b
->values
.value("count");
1840 if (valueA
.isNull()) {
1841 if (!valueB
.isNull()) {
1844 } else if (valueB
.isNull()) {
1847 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1849 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1856 KIO::filesize_t sizeA
= 0;
1857 if (itemA
.isDir()) {
1858 sizeA
= a
->values
.value("size").toULongLong();
1860 sizeA
= itemA
.size();
1862 KIO::filesize_t sizeB
= 0;
1863 if (itemB
.isDir()) {
1864 sizeB
= b
->values
.value("size").toULongLong();
1866 sizeB
= itemB
.size();
1868 if (sizeA
< sizeB
) {
1870 } else if (sizeA
> sizeB
) {
1876 case ModificationTimeRole
: {
1877 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1878 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1879 if (dateTimeA
< dateTimeB
) {
1881 } else if (dateTimeA
> dateTimeB
) {
1887 case CreationTimeRole
: {
1888 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1889 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1890 if (dateTimeA
< dateTimeB
) {
1892 } else if (dateTimeA
> dateTimeB
) {
1898 case DeletionTimeRole
: {
1899 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1900 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1901 if (dateTimeA
< dateTimeB
) {
1903 } else if (dateTimeA
> dateTimeB
) {
1915 case ReleaseYearRole
: {
1916 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1921 const QByteArray role
= roleForType(m_sortRole
);
1922 const QString roleValueA
= a
->values
.value(role
).toString();
1923 const QString roleValueB
= b
->values
.value(role
).toString();
1924 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1926 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1928 } else if (isRoleValueNatural(m_sortRole
)) {
1929 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1931 result
= QString::compare(roleValueA
, roleValueB
);
1939 // The current sort role was sufficient to define an order
1943 // Fallback #1: Compare the text of the items
1944 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1949 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1950 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1955 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1956 // equal. In this case a comparison of the URL is done which is unique in all cases
1957 // within KDirLister.
1958 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1961 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1963 QMutexLocker
collatorLock(s_collatorMutex());
1965 if (m_naturalSorting
) {
1966 return collator
.compare(a
, b
);
1969 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1970 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1971 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1972 // comparison, still a deterministic sort order is required. A case sensitive
1973 // comparison is done as fallback.
1977 return QString::compare(a
, b
, Qt::CaseSensitive
);
1980 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1982 Q_ASSERT(!m_itemData
.isEmpty());
1984 const int maxIndex
= count() - 1;
1985 QList
<QPair
<int, QVariant
> > groups
;
1989 for (int i
= 0; i
<= maxIndex
; ++i
) {
1990 if (isChildItem(i
)) {
1994 const QString name
= m_itemData
.at(i
)->item
.text();
1996 // Use the first character of the name as group indication
1997 QChar newFirstChar
= name
.at(0).toUpper();
1998 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1999 newFirstChar
= name
.at(1).toUpper();
2002 if (firstChar
!= newFirstChar
) {
2003 QString newGroupValue
;
2004 if (newFirstChar
.isLetter()) {
2006 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2007 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2009 // Try to find a matching group in the range 'A' to 'Z'.
2010 static std::vector
<QChar
> lettersAtoZ
;
2011 lettersAtoZ
.reserve('Z' - 'A' + 1);
2012 if (lettersAtoZ
.empty()) {
2013 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2014 lettersAtoZ
.push_back(QLatin1Char(c
));
2018 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2019 return m_collator
.compare(c1
, c2
) < 0;
2022 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2023 if (it
!= lettersAtoZ
.end()) {
2024 if (localeAwareLessThan(newFirstChar
, *it
)) {
2025 // newFirstChar belongs to the group preceding *it.
2026 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2029 newGroupValue
= *it
;
2033 // Symbols from non Latin-based scripts
2034 newGroupValue
= newFirstChar
;
2036 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2037 // Apply group '0 - 9' for any name that starts with a digit
2038 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2040 newGroupValue
= i18nc("@title:group", "Others");
2043 if (newGroupValue
!= groupValue
) {
2044 groupValue
= newGroupValue
;
2045 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2048 firstChar
= newFirstChar
;
2054 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2056 Q_ASSERT(!m_itemData
.isEmpty());
2058 const int maxIndex
= count() - 1;
2059 QList
<QPair
<int, QVariant
> > groups
;
2062 for (int i
= 0; i
<= maxIndex
; ++i
) {
2063 if (isChildItem(i
)) {
2067 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2068 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2069 QString newGroupValue
;
2070 if (!item
.isNull() && item
.isDir()) {
2071 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2072 newGroupValue
= i18nc("@title:group Size", "Folders");
2074 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2078 if (newGroupValue
.isEmpty()) {
2079 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2080 newGroupValue
= i18nc("@title:group Size", "Small");
2081 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2082 newGroupValue
= i18nc("@title:group Size", "Medium");
2084 newGroupValue
= i18nc("@title:group Size", "Big");
2088 if (newGroupValue
!= groupValue
) {
2089 groupValue
= newGroupValue
;
2090 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2097 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2099 Q_ASSERT(!m_itemData
.isEmpty());
2101 const int maxIndex
= count() - 1;
2102 QList
<QPair
<int, QVariant
> > groups
;
2104 const QDate currentDate
= QDate::currentDate();
2106 QDate previousFileDate
;
2108 for (int i
= 0; i
<= maxIndex
; ++i
) {
2109 if (isChildItem(i
)) {
2113 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2114 const QDate fileDate
= fileTime
.date();
2115 if (fileDate
== previousFileDate
) {
2116 // The current item is in the same group as the previous item
2119 previousFileDate
= fileDate
;
2121 const int daysDistance
= fileDate
.daysTo(currentDate
);
2123 QString newGroupValue
;
2124 if (currentDate
.year() == fileDate
.year() &&
2125 currentDate
.month() == fileDate
.month()) {
2127 switch (daysDistance
/ 7) {
2129 switch (daysDistance
) {
2130 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2131 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2133 newGroupValue
= fileTime
.toString(
2134 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2135 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2136 "with context @title:group Date", "%1", newGroupValue
);
2140 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2143 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2146 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2150 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2156 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2157 if (lastMonthDate
.year() == fileDate
.year() &&
2158 lastMonthDate
.month() == fileDate
.month()) {
2160 if (daysDistance
== 1) {
2161 const KLocalizedString format
= ki18nc("@title:group Date: "
2162 "MMMM is full month name in current locale, and yyyy is "
2163 "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)");
2164 const QString translatedFormat
= format
.toString();
2165 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2166 newGroupValue
= fileTime
.toString(translatedFormat
);
2167 newGroupValue
= i18nc("Can be used to script translation of "
2168 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2169 "%1", newGroupValue
);
2171 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2172 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2173 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2175 } else if (daysDistance
<= 7) {
2176 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2177 "The week day name: dddd, MMMM is full month name "
2178 "in current locale, and yyyy is full year number.",
2179 "dddd (MMMM, yyyy)"));
2180 newGroupValue
= i18nc("Can be used to script translation of "
2181 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2182 "%1", newGroupValue
);
2183 } else if (daysDistance
<= 7 * 2) {
2184 const KLocalizedString format
= ki18nc("@title:group Date: "
2185 "MMMM is full month name in current locale, and yyyy is "
2186 "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)");
2187 const QString translatedFormat
= format
.toString();
2188 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2189 newGroupValue
= fileTime
.toString(translatedFormat
);
2190 newGroupValue
= i18nc("Can be used to script translation of "
2191 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2192 "%1", newGroupValue
);
2194 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2195 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2196 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2198 } else if (daysDistance
<= 7 * 3) {
2199 const KLocalizedString format
= ki18nc("@title:group Date: "
2200 "MMMM is full month name in current locale, and yyyy is "
2201 "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)");
2202 const QString translatedFormat
= format
.toString();
2203 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2204 newGroupValue
= fileTime
.toString(translatedFormat
);
2205 newGroupValue
= i18nc("Can be used to script translation of "
2206 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2207 "%1", newGroupValue
);
2209 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2210 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2211 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2213 } else if (daysDistance
<= 7 * 4) {
2214 const KLocalizedString format
= ki18nc("@title:group Date: "
2215 "MMMM is full month name in current locale, and yyyy is "
2216 "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)");
2217 const QString translatedFormat
= format
.toString();
2218 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2219 newGroupValue
= fileTime
.toString(translatedFormat
);
2220 newGroupValue
= i18nc("Can be used to script translation of "
2221 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2222 "%1", newGroupValue
);
2224 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2225 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2226 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2229 const KLocalizedString format
= ki18nc("@title:group Date: "
2230 "MMMM is full month name in current locale, and yyyy is "
2231 "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");
2232 const QString translatedFormat
= format
.toString();
2233 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2234 newGroupValue
= fileTime
.toString(translatedFormat
);
2235 newGroupValue
= i18nc("Can be used to script translation of "
2236 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2237 "%1", newGroupValue
);
2239 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2240 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2241 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2245 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2246 "The month and year: MMMM is full month name in current locale, "
2247 "and yyyy is full year number", "MMMM, yyyy"));
2248 newGroupValue
= i18nc("Can be used to script translation of "
2249 "\"MMMM, yyyy\" with context @title:group Date",
2250 "%1", newGroupValue
);
2254 if (newGroupValue
!= groupValue
) {
2255 groupValue
= newGroupValue
;
2256 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2263 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2265 Q_ASSERT(!m_itemData
.isEmpty());
2267 const int maxIndex
= count() - 1;
2268 QList
<QPair
<int, QVariant
> > groups
;
2270 QString permissionsString
;
2272 for (int i
= 0; i
<= maxIndex
; ++i
) {
2273 if (isChildItem(i
)) {
2277 const ItemData
* itemData
= m_itemData
.at(i
);
2278 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2279 if (newPermissionsString
== permissionsString
) {
2282 permissionsString
= newPermissionsString
;
2284 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2288 if (info
.permission(QFile::ReadUser
)) {
2289 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2291 if (info
.permission(QFile::WriteUser
)) {
2292 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2294 if (info
.permission(QFile::ExeUser
)) {
2295 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2297 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2301 if (info
.permission(QFile::ReadGroup
)) {
2302 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2304 if (info
.permission(QFile::WriteGroup
)) {
2305 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2307 if (info
.permission(QFile::ExeGroup
)) {
2308 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2310 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2312 // Set others string
2314 if (info
.permission(QFile::ReadOther
)) {
2315 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2317 if (info
.permission(QFile::WriteOther
)) {
2318 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2320 if (info
.permission(QFile::ExeOther
)) {
2321 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2323 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2325 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2326 if (newGroupValue
!= groupValue
) {
2327 groupValue
= newGroupValue
;
2328 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2335 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2337 Q_ASSERT(!m_itemData
.isEmpty());
2339 const int maxIndex
= count() - 1;
2340 QList
<QPair
<int, QVariant
> > groups
;
2342 int groupValue
= -1;
2343 for (int i
= 0; i
<= maxIndex
; ++i
) {
2344 if (isChildItem(i
)) {
2347 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2348 if (newGroupValue
!= groupValue
) {
2349 groupValue
= newGroupValue
;
2350 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2357 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2359 Q_ASSERT(!m_itemData
.isEmpty());
2361 const int maxIndex
= count() - 1;
2362 QList
<QPair
<int, QVariant
> > groups
;
2364 bool isFirstGroupValue
= true;
2366 for (int i
= 0; i
<= maxIndex
; ++i
) {
2367 if (isChildItem(i
)) {
2370 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2371 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2372 groupValue
= newGroupValue
;
2373 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2374 isFirstGroupValue
= false;
2381 void KFileItemModel::emitSortProgress(int resolvedCount
)
2383 // Be tolerant against a resolvedCount with a wrong range.
2384 // Although there should not be a case where KFileItemModelRolesUpdater
2385 // (= caller) provides a wrong range, it is important to emit
2386 // a useful progress information even if there is an unexpected
2387 // implementation issue.
2389 const int itemCount
= count();
2390 if (resolvedCount
>= itemCount
) {
2391 m_sortingProgressPercent
= -1;
2392 if (m_resortAllItemsTimer
->isActive()) {
2393 m_resortAllItemsTimer
->stop();
2397 Q_EMIT
directorySortingProgress(100);
2398 } else if (itemCount
> 0) {
2399 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2401 const int progress
= resolvedCount
* 100 / itemCount
;
2402 if (m_sortingProgressPercent
!= progress
) {
2403 m_sortingProgressPercent
= progress
;
2404 Q_EMIT
directorySortingProgress(progress
);
2409 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2411 static const RoleInfoMap rolesInfoMap
[] = {
2412 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2413 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2414 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2415 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2416 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2417 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2418 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2419 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2420 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2421 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2422 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2423 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2424 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2425 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2426 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2427 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2428 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2429 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2430 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2431 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2432 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2433 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2434 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2435 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2436 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2437 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2438 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2439 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2440 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2441 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2442 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2443 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2444 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2445 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2448 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2449 return rolesInfoMap
;
2452 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2454 QElapsedTimer timer
;
2456 for (const KFileItem
& item
: items
) {
2457 // Only determine mime types for files here. For directories,
2458 // KFileItem::determineMimeType() reads the .directory file inside to
2459 // load the icon, but this is not necessary at all if we just need the
2460 // type. Some special code for setting the correct mime type for
2461 // directories is in retrieveData().
2462 if (!item
.isDir()) {
2463 item
.determineMimeType();
2466 if (timer
.elapsed() > timeout
) {
2467 // Don't block the user interface, let the remaining items
2468 // be resolved asynchronously.
2474 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2476 static QSet
<QByteArray
> pool
;
2477 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2479 if (it
!= pool
.constEnd()) {
2487 bool KFileItemModel::isConsistent() const
2489 // m_items may contain less items than m_itemData because m_items
2490 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2491 if (m_items
.count() > m_itemData
.count()) {
2495 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2496 // Check if m_items and m_itemData are consistent.
2497 const KFileItem item
= fileItem(i
);
2498 if (item
.isNull()) {
2499 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2503 const int itemIndex
= index(item
);
2504 if (itemIndex
!= i
) {
2505 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2509 // Check if the items are sorted correctly.
2510 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2511 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2512 << fileItem(i
- 1) << fileItem(i
);
2516 // Check if all parent-child relationships are consistent.
2517 const ItemData
* data
= m_itemData
.at(i
);
2518 const ItemData
* parent
= data
->parent
;
2520 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2521 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2525 const int parentIndex
= index(parent
->item
);
2526 if (parentIndex
>= i
) {
2527 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2536 void KFileItemModel::slotListerError(KIO::Job
*job
)
2538 if (job
->error() == KIO::ERR_IS_FILE
) {
2539 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2540 Q_EMIT
urlIsFileError(listJob
->url());
2543 const QString errorString
= job
->errorString();
2544 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));