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/kfileitemmodeldirlister.h"
15 #include "private/kfileitemmodelsortalgorithm.h"
17 #include <kio_version.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 KFileItemModelDirLister(this);
58 m_dirLister
->setDelayedMimeTypes(true);
60 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
62 m_dirLister
->setMainWindow(parentWidget
->window());
65 connect(m_dirLister
, &KFileItemModelDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
66 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
67 connect(m_dirLister
, &KFileItemModelDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
68 connect(m_dirLister
, &KFileItemModelDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
69 connect(m_dirLister
, &KFileItemModelDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
70 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
71 connect(m_dirLister
, &KFileItemModelDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
72 connect(m_dirLister
, &KFileItemModelDirLister::errorMessage
, this, &KFileItemModel::errorMessage
);
73 connect(m_dirLister
, &KFileItemModelDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
74 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
75 connect(m_dirLister
, &KFileItemModelDirLister::urlIsFileError
, this, &KFileItemModel::urlIsFileError
);
77 #if KIO_VERSION < QT_VERSION_CHECK(5, 79, 0)
78 connect(m_dirLister
, QOverload
<const QUrl
&>::of(&KCoreDirLister::completed
), this, &KFileItemModel::slotCompleted
);
80 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
83 // Apply default roles that should be determined
85 m_requestRole
[NameRole
] = true;
86 m_requestRole
[IsDirRole
] = true;
87 m_requestRole
[IsLinkRole
] = true;
88 m_roles
.insert("text");
89 m_roles
.insert("isDir");
90 m_roles
.insert("isLink");
91 m_roles
.insert("isHidden");
93 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
94 // before the completed() or canceled() signal has been emitted.
95 m_maximumUpdateIntervalTimer
= new QTimer(this);
96 m_maximumUpdateIntervalTimer
->setInterval(2000);
97 m_maximumUpdateIntervalTimer
->setSingleShot(true);
98 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
100 // When changing the value of an item which represents the sort-role a resorting must be
101 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
102 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
103 // resorting is postponed until the timer has been exceeded.
104 m_resortAllItemsTimer
= new QTimer(this);
105 m_resortAllItemsTimer
->setInterval(500);
106 m_resortAllItemsTimer
->setSingleShot(true);
107 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
109 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
112 KFileItemModel::~KFileItemModel()
114 qDeleteAll(m_itemData
);
115 qDeleteAll(m_filteredItems
);
116 qDeleteAll(m_pendingItemsToInsert
);
119 void KFileItemModel::loadDirectory(const QUrl
&url
)
121 m_dirLister
->openUrl(url
);
124 void KFileItemModel::refreshDirectory(const QUrl
&url
)
126 // Refresh all expanded directories first (Bug 295300)
127 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
128 while (expandedDirs
.hasNext()) {
130 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
133 m_dirLister
->openUrl(url
, KDirLister::Reload
);
136 QUrl
KFileItemModel::directory() const
138 return m_dirLister
->url();
141 void KFileItemModel::cancelDirectoryLoading()
146 int KFileItemModel::count() const
148 return m_itemData
.count();
151 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
153 if (index
>= 0 && index
< count()) {
154 ItemData
* data
= m_itemData
.at(index
);
155 if (data
->values
.isEmpty()) {
156 data
->values
= retrieveData(data
->item
, data
->parent
);
161 return QHash
<QByteArray
, QVariant
>();
164 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
166 if (index
< 0 || index
>= count()) {
170 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
172 // Determine which roles have been changed
173 QSet
<QByteArray
> changedRoles
;
174 QHashIterator
<QByteArray
, QVariant
> it(values
);
175 while (it
.hasNext()) {
177 const QByteArray role
= sharedValue(it
.key());
178 const QVariant value
= it
.value();
180 if (currentValues
[role
] != value
) {
181 currentValues
[role
] = value
;
182 changedRoles
.insert(role
);
186 if (changedRoles
.isEmpty()) {
190 m_itemData
[index
]->values
= currentValues
;
191 if (changedRoles
.contains("text")) {
192 QUrl url
= m_itemData
[index
]->item
.url();
193 url
= url
.adjusted(QUrl::RemoveFilename
);
194 url
.setPath(url
.path() + currentValues
["text"].toString());
195 m_itemData
[index
]->item
.setUrl(url
);
198 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
203 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
205 if (dirsFirst
!= m_sortDirsFirst
) {
206 m_sortDirsFirst
= dirsFirst
;
211 bool KFileItemModel::sortDirectoriesFirst() const
213 return m_sortDirsFirst
;
216 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
218 if (hiddenLast
!= m_sortHiddenLast
) {
219 m_sortHiddenLast
= hiddenLast
;
224 bool KFileItemModel::sortHiddenLast() const
226 return m_sortHiddenLast
;
229 void KFileItemModel::setShowHiddenFiles(bool show
)
231 m_dirLister
->setShowingDotFiles(show
);
232 m_dirLister
->emitChanges();
234 dispatchPendingItemsToInsert();
238 bool KFileItemModel::showHiddenFiles() const
240 return m_dirLister
->showingDotFiles();
243 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
245 m_dirLister
->setDirOnlyMode(enabled
);
248 bool KFileItemModel::showDirectoriesOnly() const
250 return m_dirLister
->dirOnlyMode();
253 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
255 QMimeData
* data
= new QMimeData();
257 // The following code has been taken from KDirModel::mimeData()
258 // (kdelibs/kio/kio/kdirmodel.cpp)
259 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
261 QList
<QUrl
> mostLocalUrls
;
262 const ItemData
* lastAddedItem
= nullptr;
264 for (int index
: indexes
) {
265 const ItemData
* itemData
= m_itemData
.at(index
);
266 const ItemData
* parent
= itemData
->parent
;
268 while (parent
&& parent
!= lastAddedItem
) {
269 parent
= parent
->parent
;
272 if (parent
&& parent
== lastAddedItem
) {
273 // A parent of 'itemData' has been added already.
277 lastAddedItem
= itemData
;
278 const KFileItem
& item
= itemData
->item
;
279 if (!item
.isNull()) {
283 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
287 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
291 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
293 startFromIndex
= qMax(0, startFromIndex
);
294 for (int i
= startFromIndex
; i
< count(); ++i
) {
295 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
299 for (int i
= 0; i
< startFromIndex
; ++i
) {
300 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
307 bool KFileItemModel::supportsDropping(int index
) const
309 const KFileItem item
= fileItem(index
);
310 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
313 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
315 static QHash
<QByteArray
, QString
> description
;
316 if (description
.isEmpty()) {
318 const RoleInfoMap
* map
= rolesInfoMap(count
);
319 for (int i
= 0; i
< count
; ++i
) {
320 if (!map
[i
].roleTranslation
) {
323 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
327 return description
.value(role
);
330 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
332 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
333 #ifdef KFILEITEMMODEL_DEBUG
337 switch (typeForRole(sortRole())) {
338 case NameRole
: m_groups
= nameRoleGroups(); break;
339 case SizeRole
: m_groups
= sizeRoleGroups(); break;
340 case ModificationTimeRole
:
341 m_groups
= timeRoleGroups([](const ItemData
*item
) {
342 return item
->item
.time(KFileItem::ModificationTime
);
345 case CreationTimeRole
:
346 m_groups
= timeRoleGroups([](const ItemData
*item
) {
347 return item
->item
.time(KFileItem::CreationTime
);
351 m_groups
= timeRoleGroups([](const ItemData
*item
) {
352 return item
->item
.time(KFileItem::AccessTime
);
355 case DeletionTimeRole
:
356 m_groups
= timeRoleGroups([](const ItemData
*item
) {
357 return item
->values
.value("deletiontime").toDateTime();
360 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
361 case RatingRole
: m_groups
= ratingRoleGroups(); break;
362 default: m_groups
= genericStringRoleGroups(sortRole()); break;
365 #ifdef KFILEITEMMODEL_DEBUG
366 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
373 KFileItem
KFileItemModel::fileItem(int index
) const
375 if (index
>= 0 && index
< count()) {
376 return m_itemData
.at(index
)->item
;
382 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
384 const int indexForUrl
= index(url
);
385 if (indexForUrl
>= 0) {
386 return m_itemData
.at(indexForUrl
)->item
;
391 int KFileItemModel::index(const KFileItem
& item
) const
393 return index(item
.url());
396 int KFileItemModel::index(const QUrl
& url
) const
398 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
400 const int itemCount
= m_itemData
.count();
401 int itemsInHash
= m_items
.count();
403 int index
= m_items
.value(urlToFind
, -1);
404 while (index
< 0 && itemsInHash
< itemCount
) {
405 // Not all URLs are stored yet in m_items. We grow m_items until either
406 // urlToFind is found, or all URLs have been stored in m_items.
407 // Note that we do not add the URLs to m_items one by one, but in
408 // larger blocks. After each block, we check if urlToFind is in
409 // m_items. We could in principle compare urlToFind with each URL while
410 // we are going through m_itemData, but comparing two QUrls will,
411 // unlike calling qHash for the URLs, trigger a parsing of the URLs
412 // which costs both CPU cycles and memory.
413 const int blockSize
= 1000;
414 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
415 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
416 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
417 m_items
.insert(nextUrl
, i
);
420 itemsInHash
= currentBlockEnd
;
421 index
= m_items
.value(urlToFind
, -1);
425 // The item could not be found, even though all items from m_itemData
426 // should be in m_items now. We print some diagnostic information which
427 // might help to find the cause of the problem, but only once. This
428 // prevents that obtaining and printing the debugging information
429 // wastes CPU cycles and floods the shell or .xsession-errors.
430 static bool printDebugInfo
= true;
432 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
433 printDebugInfo
= false;
435 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
436 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
437 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
439 // Check if there are multiple items with the same URL.
440 QMultiHash
<QUrl
, int> indexesForUrl
;
441 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
442 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
445 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
446 for (const QUrl
& url
: uniqueKeys
) {
447 if (indexesForUrl
.count(url
) > 1) {
448 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
450 auto it
= indexesForUrl
.find(url
);
451 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
452 const ItemData
* data
= m_itemData
.at(it
.value());
453 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
455 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
467 KFileItem
KFileItemModel::rootItem() const
469 return m_dirLister
->rootItem();
472 void KFileItemModel::clear()
477 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
479 if (m_roles
== roles
) {
483 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
487 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
488 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
489 if (supportedExpanding
&& !willSupportExpanding
) {
490 // No expanding is supported anymore. Take care to delete all items that have an expansion level
491 // that is not 0 (and hence are part of an expanded item).
492 removeExpandedItems();
499 QSetIterator
<QByteArray
> it(roles
);
500 while (it
.hasNext()) {
501 const QByteArray
& role
= it
.next();
502 m_requestRole
[typeForRole(role
)] = true;
506 // Update m_data with the changed requested roles
507 const int maxIndex
= count() - 1;
508 for (int i
= 0; i
<= maxIndex
; ++i
) {
509 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
512 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
515 // Clear the 'values' of all filtered items. They will be re-populated with the
516 // correct roles the next time 'values' will be accessed via data(int).
517 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
518 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
519 while (filteredIt
!= filteredEnd
) {
520 (*filteredIt
)->values
.clear();
525 QSet
<QByteArray
> KFileItemModel::roles() const
530 bool KFileItemModel::setExpanded(int index
, bool expanded
)
532 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
536 QHash
<QByteArray
, QVariant
> values
;
537 values
.insert(sharedValue("isExpanded"), expanded
);
538 if (!setData(index
, values
)) {
542 const KFileItem item
= m_itemData
.at(index
)->item
;
543 const QUrl url
= item
.url();
544 const QUrl targetUrl
= item
.targetUrl();
546 m_expandedDirs
.insert(targetUrl
, url
);
547 m_dirLister
->openUrl(url
, KDirLister::Keep
);
549 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
550 for (const QVariant
& var
: previouslyExpandedChildren
) {
551 m_urlsToExpand
.insert(var
.toUrl());
554 // Note that there might be (indirect) children of the folder which is to be collapsed in
555 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
556 // possibly without a parent, which might result in a crash, we insert all pending items
557 // right now. All new items which would be without a parent will then be removed.
558 dispatchPendingItemsToInsert();
560 // Check if the index of the collapsed folder has changed. If that is the case, then items
561 // were inserted before the collapsed folder, and its index needs to be updated.
562 if (m_itemData
.at(index
)->item
!= item
) {
563 index
= this->index(item
);
566 m_expandedDirs
.remove(targetUrl
);
567 m_dirLister
->stop(url
);
569 const int parentLevel
= expandedParentsCount(index
);
570 const int itemCount
= m_itemData
.count();
571 const int firstChildIndex
= index
+ 1;
573 QVariantList expandedChildren
;
575 int childIndex
= firstChildIndex
;
576 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
577 ItemData
* itemData
= m_itemData
.at(childIndex
);
578 if (itemData
->values
.value("isExpanded").toBool()) {
579 const QUrl targetUrl
= itemData
->item
.targetUrl();
580 const QUrl url
= itemData
->item
.url();
581 m_expandedDirs
.remove(targetUrl
);
582 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
583 expandedChildren
.append(targetUrl
);
587 const int childrenCount
= childIndex
- firstChildIndex
;
589 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
590 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
592 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
598 bool KFileItemModel::isExpanded(int index
) const
600 if (index
>= 0 && index
< count()) {
601 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
606 bool KFileItemModel::isExpandable(int index
) const
608 if (index
>= 0 && index
< count()) {
609 // Call data (instead of accessing m_itemData directly)
610 // to ensure that the value is initialized.
611 return data(index
).value("isExpandable").toBool();
616 int KFileItemModel::expandedParentsCount(int index
) const
618 if (index
>= 0 && index
< count()) {
619 return expandedParentsCount(m_itemData
.at(index
));
624 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
627 const auto dirs
= m_expandedDirs
;
628 for (const auto &dir
: dirs
) {
634 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
636 m_urlsToExpand
= urls
;
639 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
642 // Assure that each sub-path of the URL that should be
643 // expanded is added to m_urlsToExpand. KDirLister
644 // does not care whether the parent-URL has already been
646 QUrl urlToExpand
= m_dirLister
->url();
647 const int pos
= urlToExpand
.path().length();
649 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
650 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
651 // so using QString::SkipEmptyParts
652 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
653 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
654 QString path
= urlToExpand
.path();
655 if (!path
.endsWith(QLatin1Char('/'))) {
656 path
.append(QLatin1Char('/'));
658 urlToExpand
.setPath(path
+ subDirs
.at(i
));
659 m_urlsToExpand
.insert(urlToExpand
);
662 // KDirLister::open() must called at least once to trigger an initial
663 // loading. The pending URLs that must be restored are handled
664 // in slotCompleted().
665 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
666 while (it2
.hasNext()) {
667 const int idx
= index(it2
.next());
668 if (idx
>= 0 && !isExpanded(idx
)) {
669 setExpanded(idx
, true);
675 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
677 if (m_filter
.pattern() != nameFilter
) {
678 dispatchPendingItemsToInsert();
679 m_filter
.setPattern(nameFilter
);
684 QString
KFileItemModel::nameFilter() const
686 return m_filter
.pattern();
689 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
691 if (m_filter
.mimeTypes() != filters
) {
692 dispatchPendingItemsToInsert();
693 m_filter
.setMimeTypes(filters
);
698 QStringList
KFileItemModel::mimeTypeFilters() const
700 return m_filter
.mimeTypes();
704 void KFileItemModel::applyFilters()
706 // Check which shown items from m_itemData must get
707 // hidden and hence moved to m_filteredItems.
708 QVector
<int> newFilteredIndexes
;
710 const int itemCount
= m_itemData
.count();
711 for (int index
= 0; index
< itemCount
; ++index
) {
712 ItemData
* itemData
= m_itemData
.at(index
);
714 // Only filter non-expanded items as child items may never
715 // exist without a parent item
716 if (!itemData
->values
.value("isExpanded").toBool()) {
717 const KFileItem item
= itemData
->item
;
718 if (!m_filter
.matches(item
)) {
719 newFilteredIndexes
.append(index
);
720 m_filteredItems
.insert(item
, itemData
);
725 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
726 removeItems(removedRanges
, KeepItemData
);
728 // Check which hidden items from m_filteredItems should
729 // get visible again and hence removed from m_filteredItems.
730 QList
<ItemData
*> newVisibleItems
;
732 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
733 while (it
!= m_filteredItems
.end()) {
734 if (m_filter
.matches(it
.key())) {
735 newVisibleItems
.append(it
.value());
736 it
= m_filteredItems
.erase(it
);
742 insertItems(newVisibleItems
);
745 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
747 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
748 // There are either no filtered items, or it is not possible to expand
749 // folders -> there cannot be any filtered children.
753 QSet
<ItemData
*> parents
;
754 for (const KItemRange
& range
: itemRanges
) {
755 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
756 parents
.insert(m_itemData
.at(index
));
760 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
761 while (it
!= m_filteredItems
.end()) {
762 if (parents
.contains(it
.value()->parent
)) {
764 it
= m_filteredItems
.erase(it
);
771 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
773 static QList
<RoleInfo
> rolesInfo
;
774 if (rolesInfo
.isEmpty()) {
776 const RoleInfoMap
* map
= rolesInfoMap(count
);
777 for (int i
= 0; i
< count
; ++i
) {
778 if (map
[i
].roleType
!= NoRole
) {
780 info
.role
= map
[i
].role
;
781 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
782 if (map
[i
].groupTranslation
) {
783 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
785 // For top level roles, groupTranslation is 0. We must make sure that
786 // info.group is an empty string then because the code that generates
787 // menus tries to put the actions into sub menus otherwise.
788 info
.group
= QString();
790 info
.requiresBaloo
= map
[i
].requiresBaloo
;
791 info
.requiresIndexer
= map
[i
].requiresIndexer
;
792 rolesInfo
.append(info
);
800 void KFileItemModel::onGroupedSortingChanged(bool current
)
806 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
809 m_sortRole
= typeForRole(current
);
811 if (!m_requestRole
[m_sortRole
]) {
812 QSet
<QByteArray
> newRoles
= m_roles
;
822 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
829 void KFileItemModel::loadSortingSettings()
831 using Choice
= GeneralSettings::EnumSortingChoice
;
832 switch (GeneralSettings::sortingChoice()) {
833 case Choice::NaturalSorting
:
834 m_naturalSorting
= true;
835 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
837 case Choice::CaseSensitiveSorting
:
838 m_naturalSorting
= false;
839 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
841 case Choice::CaseInsensitiveSorting
:
842 m_naturalSorting
= false;
843 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
848 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
849 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
850 m_collator
.compare(QString(), QString());
853 void KFileItemModel::resortAllItems()
855 m_resortAllItemsTimer
->stop();
857 const int itemCount
= count();
858 if (itemCount
<= 0) {
862 #ifdef KFILEITEMMODEL_DEBUG
865 qCDebug(DolphinDebug
) << "===========================================================";
866 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
869 // Remember the order of the current URLs so
870 // that it can be determined which indexes have
871 // been moved because of the resorting.
873 oldUrls
.reserve(itemCount
);
874 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
875 oldUrls
.append(itemData
->item
.url());
879 m_items
.reserve(itemCount
);
882 sort(m_itemData
.begin(), m_itemData
.end());
883 for (int i
= 0; i
< itemCount
; ++i
) {
884 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
887 // Determine the first index that has been moved.
888 int firstMovedIndex
= 0;
889 while (firstMovedIndex
< itemCount
890 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
894 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
895 if (itemsHaveMoved
) {
898 int lastMovedIndex
= itemCount
- 1;
899 while (lastMovedIndex
> firstMovedIndex
900 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
904 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
906 // Create a list movedToIndexes, which has the property that
907 // movedToIndexes[i] is the new index of the item with the old index
908 // firstMovedIndex + i.
909 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
910 QList
<int> movedToIndexes
;
911 movedToIndexes
.reserve(movedItemsCount
);
912 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
913 const int newIndex
= m_items
.value(oldUrls
.at(i
));
914 movedToIndexes
.append(newIndex
);
917 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
918 } else if (groupedSorting()) {
919 // The groups might have changed even if the order of the items has not.
920 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
922 if (groups() != oldGroups
) {
923 Q_EMIT
groupsChanged();
927 #ifdef KFILEITEMMODEL_DEBUG
928 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
932 void KFileItemModel::slotCompleted()
934 m_maximumUpdateIntervalTimer
->stop();
935 dispatchPendingItemsToInsert();
937 if (!m_urlsToExpand
.isEmpty()) {
938 // Try to find a URL that can be expanded.
939 // Note that the parent folder must be expanded before any of its subfolders become visible.
940 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
941 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
942 // Iterate over a const copy because items are deleted and inserted within the loop
943 const auto urlsToExpand
= m_urlsToExpand
;
944 for(const QUrl
&url
: urlsToExpand
) {
945 const int indexForUrl
= index(url
);
946 if (indexForUrl
>= 0) {
947 m_urlsToExpand
.remove(url
);
948 if (setExpanded(indexForUrl
, true)) {
949 // The dir lister has been triggered. This slot will be called
950 // again after the directory has been expanded.
956 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
957 // if these URLs have been deleted in the meantime.
958 m_urlsToExpand
.clear();
961 Q_EMIT
directoryLoadingCompleted();
964 void KFileItemModel::slotCanceled()
966 m_maximumUpdateIntervalTimer
->stop();
967 dispatchPendingItemsToInsert();
969 Q_EMIT
directoryLoadingCanceled();
972 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
974 Q_ASSERT(!items
.isEmpty());
977 if (m_expandedDirs
.contains(directoryUrl
)) {
978 parentUrl
= m_expandedDirs
.value(directoryUrl
);
980 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
983 if (m_requestRole
[ExpandedParentsCountRole
]) {
984 // If the expanding of items is enabled, the call
985 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
986 // might result in emitting the same items twice due to the Keep-parameter.
987 // This case happens if an item gets expanded, collapsed and expanded again
988 // before the items could be loaded for the first expansion.
989 if (index(items
.first().url()) >= 0) {
990 // The items are already part of the model.
994 if (directoryUrl
!= directory()) {
995 // To be able to compare whether the new items may be inserted as children
996 // of a parent item the pending items must be added to the model first.
997 dispatchPendingItemsToInsert();
1000 // KDirLister keeps the children of items that got expanded once even if
1001 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1002 // checked whether the parent for new items is still expanded.
1003 const int parentIndex
= index(parentUrl
);
1004 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1005 // The parent is not expanded.
1010 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1012 if (!m_filter
.hasSetFilters()) {
1013 m_pendingItemsToInsert
.append(itemDataList
);
1015 // The name or type filter is active. Hide filtered items
1016 // before inserting them into the model and remember
1017 // the filtered items in m_filteredItems.
1018 for (ItemData
* itemData
: itemDataList
) {
1019 if (m_filter
.matches(itemData
->item
)) {
1020 m_pendingItemsToInsert
.append(itemData
);
1022 m_filteredItems
.insert(itemData
->item
, itemData
);
1027 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1028 // Assure that items get dispatched if no completed() or canceled() signal is
1029 // emitted during the maximum update interval.
1030 m_maximumUpdateIntervalTimer
->start();
1033 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1036 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1038 dispatchPendingItemsToInsert();
1040 QVector
<int> indexesToRemove
;
1041 indexesToRemove
.reserve(items
.count());
1042 KFileItemList dirsChanged
;
1044 for (const KFileItem
& item
: items
) {
1045 const int indexForItem
= index(item
);
1046 if (indexForItem
>= 0) {
1047 indexesToRemove
.append(indexForItem
);
1049 // Probably the item has been filtered.
1050 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1051 if (it
!= m_filteredItems
.end()) {
1053 m_filteredItems
.erase(it
);
1057 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1058 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1059 dirsChanged
<< KFileItem(parentUrl
);
1063 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1065 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1066 // Assure that removing a parent item also results in removing all children
1067 QVector
<int> indexesToRemoveWithChildren
;
1068 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1070 const int itemCount
= m_itemData
.count();
1071 for (int index
: qAsConst(indexesToRemove
)) {
1072 indexesToRemoveWithChildren
.append(index
);
1074 const int parentLevel
= expandedParentsCount(index
);
1075 int childIndex
= index
+ 1;
1076 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1077 indexesToRemoveWithChildren
.append(childIndex
);
1082 indexesToRemove
= indexesToRemoveWithChildren
;
1085 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1086 removeFilteredChildren(itemRanges
);
1087 removeItems(itemRanges
, DeleteItemData
);
1089 Q_EMIT
fileItemsChanged(dirsChanged
);
1092 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1094 Q_ASSERT(!items
.isEmpty());
1095 #ifdef KFILEITEMMODEL_DEBUG
1096 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1099 // Get the indexes of all items that have been refreshed
1101 indexes
.reserve(items
.count());
1103 QSet
<QByteArray
> changedRoles
;
1104 KFileItemList changedFiles
;
1106 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1107 while (it
.hasNext()) {
1108 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1109 const KFileItem
& oldItem
= itemPair
.first
;
1110 const KFileItem
& newItem
= itemPair
.second
;
1111 const int indexForItem
= index(oldItem
);
1112 if (indexForItem
>= 0) {
1113 m_itemData
[indexForItem
]->item
= newItem
;
1115 // Keep old values as long as possible if they could not retrieved synchronously yet.
1116 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1117 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1118 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1119 while (it
.hasNext()) {
1121 const QByteArray
& role
= it
.key();
1122 if (values
.value(role
) != it
.value()) {
1123 values
.insert(role
, it
.value());
1124 changedRoles
.insert(role
);
1128 m_items
.remove(oldItem
.url());
1129 m_items
.insert(newItem
.url(), indexForItem
);
1130 changedFiles
.append(newItem
);
1131 indexes
.append(indexForItem
);
1133 // Check if 'oldItem' is one of the filtered items.
1134 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1135 if (it
!= m_filteredItems
.end()) {
1136 ItemData
* itemData
= it
.value();
1137 itemData
->item
= newItem
;
1139 // The data stored in 'values' might have changed. Therefore, we clear
1140 // 'values' and re-populate it the next time it is requested via data(int).
1141 itemData
->values
.clear();
1143 m_filteredItems
.erase(it
);
1144 m_filteredItems
.insert(newItem
, itemData
);
1149 // If the changed items have been created recently, they might not be in m_items yet.
1150 // In that case, the list 'indexes' might be empty.
1151 if (indexes
.isEmpty()) {
1155 // Extract the item-ranges out of the changed indexes
1156 std::sort(indexes
.begin(), indexes
.end());
1157 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1158 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1160 Q_EMIT
fileItemsChanged(changedFiles
);
1163 void KFileItemModel::slotClear()
1165 #ifdef KFILEITEMMODEL_DEBUG
1166 qCDebug(DolphinDebug
) << "Clearing all items";
1169 qDeleteAll(m_filteredItems
);
1170 m_filteredItems
.clear();
1173 m_maximumUpdateIntervalTimer
->stop();
1174 m_resortAllItemsTimer
->stop();
1176 qDeleteAll(m_pendingItemsToInsert
);
1177 m_pendingItemsToInsert
.clear();
1179 const int removedCount
= m_itemData
.count();
1180 if (removedCount
> 0) {
1181 qDeleteAll(m_itemData
);
1184 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1187 m_expandedDirs
.clear();
1190 void KFileItemModel::slotSortingChoiceChanged()
1192 loadSortingSettings();
1196 void KFileItemModel::dispatchPendingItemsToInsert()
1198 if (!m_pendingItemsToInsert
.isEmpty()) {
1199 insertItems(m_pendingItemsToInsert
);
1200 m_pendingItemsToInsert
.clear();
1204 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1206 if (newItems
.isEmpty()) {
1210 #ifdef KFILEITEMMODEL_DEBUG
1211 QElapsedTimer timer
;
1213 qCDebug(DolphinDebug
) << "===========================================================";
1214 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1218 prepareItemsForSorting(newItems
);
1220 // Natural sorting of items can be very slow. However, it becomes much faster
1221 // if the input sequence is already mostly sorted. Therefore, we first sort
1222 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1223 if (m_naturalSorting
) {
1224 if (m_sortRole
== NameRole
) {
1225 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1226 } else if (isRoleValueNatural(m_sortRole
)) {
1227 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1229 const QByteArray role
= roleForType(m_sortRole
);
1230 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1232 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1236 sort(newItems
.begin(), newItems
.end());
1238 #ifdef KFILEITEMMODEL_DEBUG
1239 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1242 KItemRangeList itemRanges
;
1243 const int existingItemCount
= m_itemData
.count();
1244 const int newItemCount
= newItems
.count();
1245 const int totalItemCount
= existingItemCount
+ newItemCount
;
1247 if (existingItemCount
== 0) {
1248 // Optimization for the common special case that there are no
1249 // items in the model yet. Happens, e.g., when entering a folder.
1250 m_itemData
= newItems
;
1251 itemRanges
<< KItemRange(0, newItemCount
);
1253 m_itemData
.reserve(totalItemCount
);
1254 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1255 m_itemData
.append(nullptr);
1258 // We build the new list m_itemData in reverse order to minimize
1259 // the number of moves and guarantee O(N) complexity.
1260 int targetIndex
= totalItemCount
- 1;
1261 int sourceIndexExistingItems
= existingItemCount
- 1;
1262 int sourceIndexNewItems
= newItemCount
- 1;
1266 while (sourceIndexNewItems
>= 0) {
1267 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1268 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1269 // Move an existing item to its new position. If any new items
1270 // are behind it, push the item range to itemRanges.
1271 if (rangeCount
> 0) {
1272 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1276 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1277 --sourceIndexExistingItems
;
1279 // Insert a new item into the list.
1281 m_itemData
[targetIndex
] = newItem
;
1282 --sourceIndexNewItems
;
1287 // Push the final item range to itemRanges.
1288 if (rangeCount
> 0) {
1289 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1292 // Note that itemRanges is still sorted in reverse order.
1293 std::reverse(itemRanges
.begin(), itemRanges
.end());
1296 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1297 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1300 Q_EMIT
itemsInserted(itemRanges
);
1302 #ifdef KFILEITEMMODEL_DEBUG
1303 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1307 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1309 if (itemRanges
.isEmpty()) {
1315 // Step 1: Remove the items from m_itemData, and free the ItemData.
1316 int removedItemsCount
= 0;
1317 for (const KItemRange
& range
: itemRanges
) {
1318 removedItemsCount
+= range
.count
;
1320 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1321 if (behavior
== DeleteItemData
) {
1322 delete m_itemData
.at(index
);
1325 m_itemData
[index
] = nullptr;
1329 // Step 2: Remove the ItemData pointers from the list m_itemData.
1330 int target
= itemRanges
.at(0).index
;
1331 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1334 const int oldItemDataCount
= m_itemData
.count();
1335 while (source
< oldItemDataCount
) {
1336 m_itemData
[target
] = m_itemData
[source
];
1340 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1341 // Skip the items in the next removed range.
1342 source
+= itemRanges
.at(nextRange
).count
;
1347 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1349 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1350 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1353 Q_EMIT
itemsRemoved(itemRanges
);
1356 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1358 if (m_sortRole
== TypeRole
) {
1359 // Try to resolve the MIME-types synchronously to prevent a reordering of
1360 // the items when sorting by type (per default MIME-types are resolved
1361 // asynchronously by KFileItemModelRolesUpdater).
1362 determineMimeTypes(items
, 200);
1365 const int parentIndex
= index(parentUrl
);
1366 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1368 QList
<ItemData
*> itemDataList
;
1369 itemDataList
.reserve(items
.count());
1371 for (const KFileItem
& item
: items
) {
1372 ItemData
* itemData
= new ItemData();
1373 itemData
->item
= item
;
1374 itemData
->parent
= parentItem
;
1375 itemDataList
.append(itemData
);
1378 return itemDataList
;
1381 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1383 switch (m_sortRole
) {
1384 case PermissionsRole
:
1387 case DestinationRole
:
1389 case DeletionTimeRole
:
1390 // These roles can be determined with retrieveData, and they have to be stored
1391 // in the QHash "values" for the sorting.
1392 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1393 if (itemData
->values
.isEmpty()) {
1394 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1400 // At least store the data including the file type for items with known MIME type.
1401 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1402 if (itemData
->values
.isEmpty()) {
1403 const KFileItem item
= itemData
->item
;
1404 if (item
.isDir() || item
.isMimeTypeKnown()) {
1405 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1412 // The other roles are either resolved by KFileItemModelRolesUpdater
1413 // (this includes the SizeRole for directories), or they do not need
1414 // to be stored in the QHash "values" for sorting because the data can
1415 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1421 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1423 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1424 // if the corresponding item is expanded, and it is not a top-level item.
1425 const ItemData
* parent
= data
->parent
;
1427 if (parent
->parent
) {
1428 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1429 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1438 void KFileItemModel::removeExpandedItems()
1440 QVector
<int> indexesToRemove
;
1442 const int maxIndex
= m_itemData
.count() - 1;
1443 for (int i
= 0; i
<= maxIndex
; ++i
) {
1444 const ItemData
* itemData
= m_itemData
.at(i
);
1445 if (itemData
->parent
) {
1446 indexesToRemove
.append(i
);
1450 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1451 m_expandedDirs
.clear();
1453 // Also remove all filtered items which have a parent.
1454 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1455 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1458 if (it
.value()->parent
) {
1460 it
= m_filteredItems
.erase(it
);
1467 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1469 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1471 // Trigger a resorting if necessary. Note that this can happen even if the sort
1472 // role has not changed at all because the file name can be used as a fallback.
1473 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1474 for (const KItemRange
& range
: itemRanges
) {
1475 bool needsResorting
= false;
1477 const int first
= range
.index
;
1478 const int last
= range
.index
+ range
.count
- 1;
1480 // Resorting the model is necessary if
1481 // (a) The first item in the range is "lessThan" its predecessor,
1482 // (b) the successor of the last item is "lessThan" the last item, or
1483 // (c) the internal order of the items in the range is incorrect.
1485 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1486 needsResorting
= true;
1487 } else if (last
< count() - 1
1488 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1489 needsResorting
= true;
1491 for (int index
= first
; index
< last
; ++index
) {
1492 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1493 needsResorting
= true;
1499 if (needsResorting
) {
1500 m_resortAllItemsTimer
->start();
1506 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1507 // The position is still correct, but the groups might have changed
1508 // if the changed item is either the first or the last item in a
1510 // In principle, we could try to find out if the item really is the
1511 // first or last one in its group and then update the groups
1512 // (possibly with a delayed timer to make sure that we don't
1513 // re-calculate the groups very often if items are updated one by
1514 // one), but starting m_resortAllItemsTimer is easier.
1515 m_resortAllItemsTimer
->start();
1519 void KFileItemModel::resetRoles()
1521 for (int i
= 0; i
< RolesCount
; ++i
) {
1522 m_requestRole
[i
] = false;
1526 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1528 static QHash
<QByteArray
, RoleType
> roles
;
1529 if (roles
.isEmpty()) {
1530 // Insert user visible roles that can be accessed with
1531 // KFileItemModel::roleInformation()
1533 const RoleInfoMap
* map
= rolesInfoMap(count
);
1534 for (int i
= 0; i
< count
; ++i
) {
1535 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1538 // Insert internal roles (take care to synchronize the implementation
1539 // with KFileItemModel::roleForType() in case if a change is done).
1540 roles
.insert("isDir", IsDirRole
);
1541 roles
.insert("isLink", IsLinkRole
);
1542 roles
.insert("isHidden", IsHiddenRole
);
1543 roles
.insert("isExpanded", IsExpandedRole
);
1544 roles
.insert("isExpandable", IsExpandableRole
);
1545 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1547 Q_ASSERT(roles
.count() == RolesCount
);
1550 return roles
.value(role
, NoRole
);
1553 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1555 static QHash
<RoleType
, QByteArray
> roles
;
1556 if (roles
.isEmpty()) {
1557 // Insert user visible roles that can be accessed with
1558 // KFileItemModel::roleInformation()
1560 const RoleInfoMap
* map
= rolesInfoMap(count
);
1561 for (int i
= 0; i
< count
; ++i
) {
1562 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1565 // Insert internal roles (take care to synchronize the implementation
1566 // with KFileItemModel::typeForRole() in case if a change is done).
1567 roles
.insert(IsDirRole
, "isDir");
1568 roles
.insert(IsLinkRole
, "isLink");
1569 roles
.insert(IsHiddenRole
, "isHidden");
1570 roles
.insert(IsExpandedRole
, "isExpanded");
1571 roles
.insert(IsExpandableRole
, "isExpandable");
1572 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1574 Q_ASSERT(roles
.count() == RolesCount
);
1577 return roles
.value(roleType
);
1580 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1582 // It is important to insert only roles that are fast to retrieve. E.g.
1583 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1584 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1585 QHash
<QByteArray
, QVariant
> data
;
1586 data
.insert(sharedValue("url"), item
.url());
1588 const bool isDir
= item
.isDir();
1589 if (m_requestRole
[IsDirRole
] && isDir
) {
1590 data
.insert(sharedValue("isDir"), true);
1593 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1594 data
.insert(sharedValue("isLink"), true);
1597 if (m_requestRole
[IsHiddenRole
]) {
1598 data
.insert(sharedValue("isHidden"), item
.isHidden());
1601 if (m_requestRole
[NameRole
]) {
1602 data
.insert(sharedValue("text"), item
.text());
1605 if (m_requestRole
[SizeRole
] && !isDir
) {
1606 data
.insert(sharedValue("size"), item
.size());
1609 if (m_requestRole
[ModificationTimeRole
]) {
1610 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1611 // having several thousands of items. Instead read the raw number from UDSEntry directly
1612 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1613 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1614 data
.insert(sharedValue("modificationtime"), dateTime
);
1617 if (m_requestRole
[CreationTimeRole
]) {
1618 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1619 // having several thousands of items. Instead read the raw number from UDSEntry directly
1620 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1621 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1622 data
.insert(sharedValue("creationtime"), dateTime
);
1625 if (m_requestRole
[AccessTimeRole
]) {
1626 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1627 // having several thousands of items. Instead read the raw number from UDSEntry directly
1628 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1629 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1630 data
.insert(sharedValue("accesstime"), dateTime
);
1633 if (m_requestRole
[PermissionsRole
]) {
1634 data
.insert(sharedValue("permissions"), item
.permissionsString());
1637 if (m_requestRole
[OwnerRole
]) {
1638 data
.insert(sharedValue("owner"), item
.user());
1641 if (m_requestRole
[GroupRole
]) {
1642 data
.insert(sharedValue("group"), item
.group());
1645 if (m_requestRole
[DestinationRole
]) {
1646 QString destination
= item
.linkDest();
1647 if (destination
.isEmpty()) {
1648 destination
= QLatin1Char('-');
1650 data
.insert(sharedValue("destination"), destination
);
1653 if (m_requestRole
[PathRole
]) {
1655 if (item
.url().scheme() == QLatin1String("trash")) {
1656 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1658 // For performance reasons cache the home-path in a static QString
1659 // (see QDir::homePath() for more details)
1660 static QString homePath
;
1661 if (homePath
.isEmpty()) {
1662 homePath
= QDir::homePath();
1665 path
= item
.localPath();
1666 if (path
.startsWith(homePath
)) {
1667 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1671 const int index
= path
.lastIndexOf(item
.text());
1672 path
= path
.mid(0, index
- 1);
1673 data
.insert(sharedValue("path"), path
);
1676 if (m_requestRole
[DeletionTimeRole
]) {
1677 QDateTime deletionTime
;
1678 if (item
.url().scheme() == QLatin1String("trash")) {
1679 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1681 data
.insert(sharedValue("deletiontime"), deletionTime
);
1684 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1685 data
.insert(sharedValue("isExpandable"), true);
1688 if (m_requestRole
[ExpandedParentsCountRole
]) {
1690 const int level
= expandedParentsCount(parent
) + 1;
1691 data
.insert(sharedValue("expandedParentsCount"), level
);
1695 if (item
.isMimeTypeKnown()) {
1696 QString iconName
= item
.iconName();
1697 if (!QIcon::hasThemeIcon(iconName
)) {
1698 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1699 iconName
= mimeType
.genericIconName();
1702 data
.insert(sharedValue("iconName"), iconName
);
1704 if (m_requestRole
[TypeRole
]) {
1705 data
.insert(sharedValue("type"), item
.mimeComment());
1707 } else if (m_requestRole
[TypeRole
] && isDir
) {
1708 static const QString folderMimeType
= item
.mimeComment();
1709 data
.insert(sharedValue("type"), folderMimeType
);
1715 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1719 if (a
->parent
!= b
->parent
) {
1720 const int expansionLevelA
= expandedParentsCount(a
);
1721 const int expansionLevelB
= expandedParentsCount(b
);
1723 // If b has a higher expansion level than a, check if a is a parent
1724 // of b, and make sure that both expansion levels are equal otherwise.
1725 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1726 if (b
->parent
== a
) {
1732 // If a has a higher expansion level than a, check if b is a parent
1733 // of a, and make sure that both expansion levels are equal otherwise.
1734 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1735 if (a
->parent
== b
) {
1741 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1743 // Compare the last parents of a and b which are different.
1744 while (a
->parent
!= b
->parent
) {
1750 // Show hidden files and folders last
1751 if (m_sortHiddenLast
) {
1752 const bool isHiddenA
= a
->item
.isHidden();
1753 const bool isHiddenB
= b
->item
.isHidden();
1754 if (isHiddenA
&& !isHiddenB
) {
1756 } else if (!isHiddenA
&& isHiddenB
) {
1761 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1762 const bool isDirA
= a
->item
.isDir();
1763 const bool isDirB
= b
->item
.isDir();
1764 if (isDirA
&& !isDirB
) {
1766 } else if (!isDirA
&& isDirB
) {
1771 result
= sortRoleCompare(a
, b
, collator
);
1773 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1776 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1777 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1779 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1781 return lessThan(a
, b
, m_collator
);
1784 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1785 // Sorting by string can be expensive, in particular if natural sorting is
1786 // enabled. Use all CPU cores to speed up the sorting process.
1787 static const int numberOfThreads
= QThread::idealThreadCount();
1788 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1790 // Sorting by other roles is quite fast. Use only one thread to prevent
1791 // problems caused by non-reentrant comparison functions, see
1792 // https://bugs.kde.org/show_bug.cgi?id=312679
1793 mergeSort(begin
, end
, lambdaLessThan
);
1797 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1799 const KFileItem
& itemA
= a
->item
;
1800 const KFileItem
& itemB
= b
->item
;
1804 switch (m_sortRole
) {
1806 // The name role is handled as default fallback after the switch
1810 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1811 // folders first then
1812 // items A and B are folders thanks to lessThan checks
1813 auto valueA
= a
->values
.value("count");
1814 auto valueB
= b
->values
.value("count");
1815 if (valueA
.isNull()) {
1816 if (valueB
.isNull()) {
1823 } else if (valueB
.isNull()) {
1827 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1830 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1839 KIO::filesize_t sizeA
= 0;
1840 if (itemA
.isDir()) {
1841 sizeA
= a
->values
.value("size").toULongLong();
1843 sizeA
= itemA
.size();
1845 KIO::filesize_t sizeB
= 0;
1846 if (itemB
.isDir()) {
1847 sizeB
= b
->values
.value("size").toULongLong();
1849 sizeB
= itemB
.size();
1851 if (sizeA
> sizeB
) {
1853 } else if (sizeA
< sizeB
) {
1861 case ModificationTimeRole
: {
1862 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1863 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1864 if (dateTimeA
< dateTimeB
) {
1866 } else if (dateTimeA
> dateTimeB
) {
1872 case CreationTimeRole
: {
1873 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1874 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1875 if (dateTimeA
< dateTimeB
) {
1877 } else if (dateTimeA
> dateTimeB
) {
1883 case DeletionTimeRole
: {
1884 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1885 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1886 if (dateTimeA
< dateTimeB
) {
1888 } else if (dateTimeA
> dateTimeB
) {
1900 case ReleaseYearRole
: {
1901 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1906 const QByteArray role
= roleForType(m_sortRole
);
1907 const QString roleValueA
= a
->values
.value(role
).toString();
1908 const QString roleValueB
= b
->values
.value(role
).toString();
1909 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1911 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1913 } else if (isRoleValueNatural(m_sortRole
)) {
1914 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1916 result
= QString::compare(roleValueA
, roleValueB
);
1924 // The current sort role was sufficient to define an order
1928 // Fallback #1: Compare the text of the items
1929 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1934 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1935 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1940 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1941 // equal. In this case a comparison of the URL is done which is unique in all cases
1942 // within KDirLister.
1943 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1946 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1948 QMutexLocker
collatorLock(s_collatorMutex());
1950 if (m_naturalSorting
) {
1951 return collator
.compare(a
, b
);
1954 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1955 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1956 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1957 // comparison, still a deterministic sort order is required. A case sensitive
1958 // comparison is done as fallback.
1962 return QString::compare(a
, b
, Qt::CaseSensitive
);
1965 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1967 Q_ASSERT(!m_itemData
.isEmpty());
1969 const int maxIndex
= count() - 1;
1970 QList
<QPair
<int, QVariant
> > groups
;
1974 for (int i
= 0; i
<= maxIndex
; ++i
) {
1975 if (isChildItem(i
)) {
1979 const QString name
= m_itemData
.at(i
)->item
.text();
1981 // Use the first character of the name as group indication
1982 QChar newFirstChar
= name
.at(0).toUpper();
1983 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1984 newFirstChar
= name
.at(1).toUpper();
1987 if (firstChar
!= newFirstChar
) {
1988 QString newGroupValue
;
1989 if (newFirstChar
.isLetter()) {
1991 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1992 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1994 // Try to find a matching group in the range 'A' to 'Z'.
1995 static std::vector
<QChar
> lettersAtoZ
;
1996 lettersAtoZ
.reserve('Z' - 'A' + 1);
1997 if (lettersAtoZ
.empty()) {
1998 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1999 lettersAtoZ
.push_back(QLatin1Char(c
));
2003 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2004 return m_collator
.compare(c1
, c2
) < 0;
2007 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2008 if (it
!= lettersAtoZ
.end()) {
2009 if (localeAwareLessThan(newFirstChar
, *it
)) {
2010 // newFirstChar belongs to the group preceding *it.
2011 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2014 newGroupValue
= *it
;
2018 // Symbols from non Latin-based scripts
2019 newGroupValue
= newFirstChar
;
2021 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2022 // Apply group '0 - 9' for any name that starts with a digit
2023 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2025 newGroupValue
= i18nc("@title:group", "Others");
2028 if (newGroupValue
!= groupValue
) {
2029 groupValue
= newGroupValue
;
2030 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2033 firstChar
= newFirstChar
;
2039 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2041 Q_ASSERT(!m_itemData
.isEmpty());
2043 const int maxIndex
= count() - 1;
2044 QList
<QPair
<int, QVariant
> > groups
;
2047 for (int i
= 0; i
<= maxIndex
; ++i
) {
2048 if (isChildItem(i
)) {
2052 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2053 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2054 QString newGroupValue
;
2055 if (!item
.isNull() && item
.isDir()) {
2056 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2057 newGroupValue
= i18nc("@title:group Size", "Folders");
2059 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2063 if (newGroupValue
.isEmpty()) {
2064 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2065 newGroupValue
= i18nc("@title:group Size", "Small");
2066 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2067 newGroupValue
= i18nc("@title:group Size", "Medium");
2069 newGroupValue
= i18nc("@title:group Size", "Big");
2073 if (newGroupValue
!= groupValue
) {
2074 groupValue
= newGroupValue
;
2075 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2082 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2084 Q_ASSERT(!m_itemData
.isEmpty());
2086 const int maxIndex
= count() - 1;
2087 QList
<QPair
<int, QVariant
> > groups
;
2089 const QDate currentDate
= QDate::currentDate();
2091 QDate previousFileDate
;
2093 for (int i
= 0; i
<= maxIndex
; ++i
) {
2094 if (isChildItem(i
)) {
2098 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2099 const QDate fileDate
= fileTime
.date();
2100 if (fileDate
== previousFileDate
) {
2101 // The current item is in the same group as the previous item
2104 previousFileDate
= fileDate
;
2106 const int daysDistance
= fileDate
.daysTo(currentDate
);
2108 QString newGroupValue
;
2109 if (currentDate
.year() == fileDate
.year() &&
2110 currentDate
.month() == fileDate
.month()) {
2112 switch (daysDistance
/ 7) {
2114 switch (daysDistance
) {
2115 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2116 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2118 newGroupValue
= fileTime
.toString(
2119 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2120 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2121 "with context @title:group Date", "%1", newGroupValue
);
2125 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2128 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2131 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2135 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2141 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2142 if (lastMonthDate
.year() == fileDate
.year() &&
2143 lastMonthDate
.month() == fileDate
.month()) {
2145 if (daysDistance
== 1) {
2146 const KLocalizedString format
= ki18nc("@title:group Date: "
2147 "MMMM is full month name in current locale, and yyyy is "
2148 "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)");
2149 const QString translatedFormat
= format
.toString();
2150 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2151 newGroupValue
= fileTime
.toString(translatedFormat
);
2152 newGroupValue
= i18nc("Can be used to script translation of "
2153 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2154 "%1", newGroupValue
);
2156 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2157 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2158 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2160 } else if (daysDistance
<= 7) {
2161 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2162 "The week day name: dddd, MMMM is full month name "
2163 "in current locale, and yyyy is full year number.",
2164 "dddd (MMMM, yyyy)"));
2165 newGroupValue
= i18nc("Can be used to script translation of "
2166 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2167 "%1", newGroupValue
);
2168 } else if (daysDistance
<= 7 * 2) {
2169 const KLocalizedString format
= ki18nc("@title:group Date: "
2170 "MMMM is full month name in current locale, and yyyy is "
2171 "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)");
2172 const QString translatedFormat
= format
.toString();
2173 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2174 newGroupValue
= fileTime
.toString(translatedFormat
);
2175 newGroupValue
= i18nc("Can be used to script translation of "
2176 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2177 "%1", newGroupValue
);
2179 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2180 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2181 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2183 } else if (daysDistance
<= 7 * 3) {
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", "'Two Weeks 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 "\"'Two Weeks 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 * 4) {
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", "'Three 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 "\"'Three 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
);
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", "'Earlier on' 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 "\"'Earlier on' 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
);
2230 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2231 "The month and year: MMMM is full month name in current locale, "
2232 "and yyyy is full year number", "MMMM, yyyy"));
2233 newGroupValue
= i18nc("Can be used to script translation of "
2234 "\"MMMM, yyyy\" with context @title:group Date",
2235 "%1", newGroupValue
);
2239 if (newGroupValue
!= groupValue
) {
2240 groupValue
= newGroupValue
;
2241 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2248 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2250 Q_ASSERT(!m_itemData
.isEmpty());
2252 const int maxIndex
= count() - 1;
2253 QList
<QPair
<int, QVariant
> > groups
;
2255 QString permissionsString
;
2257 for (int i
= 0; i
<= maxIndex
; ++i
) {
2258 if (isChildItem(i
)) {
2262 const ItemData
* itemData
= m_itemData
.at(i
);
2263 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2264 if (newPermissionsString
== permissionsString
) {
2267 permissionsString
= newPermissionsString
;
2269 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2273 if (info
.permission(QFile::ReadUser
)) {
2274 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2276 if (info
.permission(QFile::WriteUser
)) {
2277 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2279 if (info
.permission(QFile::ExeUser
)) {
2280 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2282 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2286 if (info
.permission(QFile::ReadGroup
)) {
2287 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2289 if (info
.permission(QFile::WriteGroup
)) {
2290 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2292 if (info
.permission(QFile::ExeGroup
)) {
2293 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2295 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2297 // Set others string
2299 if (info
.permission(QFile::ReadOther
)) {
2300 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2302 if (info
.permission(QFile::WriteOther
)) {
2303 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2305 if (info
.permission(QFile::ExeOther
)) {
2306 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2308 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2310 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2311 if (newGroupValue
!= groupValue
) {
2312 groupValue
= newGroupValue
;
2313 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2320 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2322 Q_ASSERT(!m_itemData
.isEmpty());
2324 const int maxIndex
= count() - 1;
2325 QList
<QPair
<int, QVariant
> > groups
;
2327 int groupValue
= -1;
2328 for (int i
= 0; i
<= maxIndex
; ++i
) {
2329 if (isChildItem(i
)) {
2332 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2333 if (newGroupValue
!= groupValue
) {
2334 groupValue
= newGroupValue
;
2335 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2342 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2344 Q_ASSERT(!m_itemData
.isEmpty());
2346 const int maxIndex
= count() - 1;
2347 QList
<QPair
<int, QVariant
> > groups
;
2349 bool isFirstGroupValue
= true;
2351 for (int i
= 0; i
<= maxIndex
; ++i
) {
2352 if (isChildItem(i
)) {
2355 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2356 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2357 groupValue
= newGroupValue
;
2358 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2359 isFirstGroupValue
= false;
2366 void KFileItemModel::emitSortProgress(int resolvedCount
)
2368 // Be tolerant against a resolvedCount with a wrong range.
2369 // Although there should not be a case where KFileItemModelRolesUpdater
2370 // (= caller) provides a wrong range, it is important to emit
2371 // a useful progress information even if there is an unexpected
2372 // implementation issue.
2374 const int itemCount
= count();
2375 if (resolvedCount
>= itemCount
) {
2376 m_sortingProgressPercent
= -1;
2377 if (m_resortAllItemsTimer
->isActive()) {
2378 m_resortAllItemsTimer
->stop();
2382 Q_EMIT
directorySortingProgress(100);
2383 } else if (itemCount
> 0) {
2384 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2386 const int progress
= resolvedCount
* 100 / itemCount
;
2387 if (m_sortingProgressPercent
!= progress
) {
2388 m_sortingProgressPercent
= progress
;
2389 Q_EMIT
directorySortingProgress(progress
);
2394 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2396 static const RoleInfoMap rolesInfoMap
[] = {
2397 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2398 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2399 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2400 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2401 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2402 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2403 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2404 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2405 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2406 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2407 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2408 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2409 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2410 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2411 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2412 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2413 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2414 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2415 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2416 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2417 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2418 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2419 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2420 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2421 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2422 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2423 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2424 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2425 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2426 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2427 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2428 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2429 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2430 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2433 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2434 return rolesInfoMap
;
2437 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2439 QElapsedTimer timer
;
2441 for (const KFileItem
& item
: items
) {
2442 // Only determine mime types for files here. For directories,
2443 // KFileItem::determineMimeType() reads the .directory file inside to
2444 // load the icon, but this is not necessary at all if we just need the
2445 // type. Some special code for setting the correct mime type for
2446 // directories is in retrieveData().
2447 if (!item
.isDir()) {
2448 item
.determineMimeType();
2451 if (timer
.elapsed() > timeout
) {
2452 // Don't block the user interface, let the remaining items
2453 // be resolved asynchronously.
2459 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2461 static QSet
<QByteArray
> pool
;
2462 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2464 if (it
!= pool
.constEnd()) {
2472 bool KFileItemModel::isConsistent() const
2474 // m_items may contain less items than m_itemData because m_items
2475 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2476 if (m_items
.count() > m_itemData
.count()) {
2480 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2481 // Check if m_items and m_itemData are consistent.
2482 const KFileItem item
= fileItem(i
);
2483 if (item
.isNull()) {
2484 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2488 const int itemIndex
= index(item
);
2489 if (itemIndex
!= i
) {
2490 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2494 // Check if the items are sorted correctly.
2495 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2496 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2497 << fileItem(i
- 1) << fileItem(i
);
2501 // Check if all parent-child relationships are consistent.
2502 const ItemData
* data
= m_itemData
.at(i
);
2503 const ItemData
* parent
= data
->parent
;
2505 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2506 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2510 const int parentIndex
= index(parent
->item
);
2511 if (parentIndex
>= i
) {
2512 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;