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 <kio_version.h>
19 #include <KLocalizedString>
20 #include <KLazyLocalizedString>
21 #include <KUrlMimeData>
23 #include <QElapsedTimer>
25 #include <QMimeDatabase>
28 #include <QRecursiveMutex>
31 #include <klazylocalizedstring.h>
33 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
35 // #define KFILEITEMMODEL_DEBUG
37 KFileItemModel::KFileItemModel(QObject
* parent
) :
38 KItemModelBase("text", parent
),
40 m_sortDirsFirst(true),
41 m_sortHiddenLast(false),
43 m_sortingProgressPercent(-1),
50 m_maximumUpdateIntervalTimer(nullptr),
51 m_resortAllItemsTimer(nullptr),
52 m_pendingItemsToInsert(),
57 m_collator
.setNumericMode(true);
59 loadSortingSettings();
61 m_dirLister
= new KDirLister(this);
62 m_dirLister
->setAutoErrorHandlingEnabled(false);
63 m_dirLister
->setDelayedMimeTypes(true);
65 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
67 m_dirLister
->setMainWindow(parentWidget
->window());
70 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
71 connect(m_dirLister
, &KCoreDirLister::canceled
, this, &KFileItemModel::slotCanceled
);
72 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
73 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
74 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
75 connect(m_dirLister
, &KCoreDirLister::clear
, this, &KFileItemModel::slotClear
);
76 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
77 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
78 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
79 connect(m_dirLister
, &KCoreDirLister::redirection
, this, &KFileItemModel::directoryRedirection
);
80 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
82 // Apply default roles that should be determined
84 m_requestRole
[NameRole
] = true;
85 m_requestRole
[IsDirRole
] = true;
86 m_requestRole
[IsLinkRole
] = true;
87 m_roles
.insert("text");
88 m_roles
.insert("isDir");
89 m_roles
.insert("isLink");
90 m_roles
.insert("isHidden");
92 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
93 // before the completed() or canceled() signal has been emitted.
94 m_maximumUpdateIntervalTimer
= new QTimer(this);
95 m_maximumUpdateIntervalTimer
->setInterval(2000);
96 m_maximumUpdateIntervalTimer
->setSingleShot(true);
97 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
99 // When changing the value of an item which represents the sort-role a resorting must be
100 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
101 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
102 // resorting is postponed until the timer has been exceeded.
103 m_resortAllItemsTimer
= new QTimer(this);
104 m_resortAllItemsTimer
->setInterval(500);
105 m_resortAllItemsTimer
->setSingleShot(true);
106 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
108 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
111 KFileItemModel::~KFileItemModel()
113 qDeleteAll(m_itemData
);
114 qDeleteAll(m_filteredItems
);
115 qDeleteAll(m_pendingItemsToInsert
);
118 void KFileItemModel::loadDirectory(const QUrl
&url
)
120 m_dirLister
->openUrl(url
);
123 void KFileItemModel::refreshDirectory(const QUrl
&url
)
125 // Refresh all expanded directories first (Bug 295300)
126 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
127 while (expandedDirs
.hasNext()) {
129 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
132 m_dirLister
->openUrl(url
, KDirLister::Reload
);
135 QUrl
KFileItemModel::directory() const
137 return m_dirLister
->url();
140 void KFileItemModel::cancelDirectoryLoading()
145 int KFileItemModel::count() const
147 return m_itemData
.count();
150 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
152 if (index
>= 0 && index
< count()) {
153 ItemData
* data
= m_itemData
.at(index
);
154 if (data
->values
.isEmpty()) {
155 data
->values
= retrieveData(data
->item
, data
->parent
);
156 } else if (data
->values
.count() <= 2 && data
->values
.value("isExpanded").toBool()) {
157 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
158 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
159 // so this special request of different behavior can be identified here.
160 bool hasExpandedParentsCount
= false;
161 const int expandedParentsCount
= data
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
163 data
->values
= retrieveData(data
->item
, data
->parent
);
164 data
->values
.insert("isExpanded", true);
165 if (hasExpandedParentsCount
) {
166 data
->values
.insert("expandedParentsCount", expandedParentsCount
);
172 return QHash
<QByteArray
, QVariant
>();
175 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
177 if (index
< 0 || index
>= count()) {
181 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
183 // Determine which roles have been changed
184 QSet
<QByteArray
> changedRoles
;
185 QHashIterator
<QByteArray
, QVariant
> it(values
);
186 while (it
.hasNext()) {
188 const QByteArray role
= sharedValue(it
.key());
189 const QVariant value
= it
.value();
191 if (currentValues
[role
] != value
) {
192 currentValues
[role
] = value
;
193 changedRoles
.insert(role
);
197 if (changedRoles
.isEmpty()) {
201 m_itemData
[index
]->values
= currentValues
;
202 if (changedRoles
.contains("text")) {
203 QUrl url
= m_itemData
[index
]->item
.url();
204 url
= url
.adjusted(QUrl::RemoveFilename
);
205 url
.setPath(url
.path() + currentValues
["text"].toString());
206 m_itemData
[index
]->item
.setUrl(url
);
209 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
214 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
216 if (dirsFirst
!= m_sortDirsFirst
) {
217 m_sortDirsFirst
= dirsFirst
;
222 bool KFileItemModel::sortDirectoriesFirst() const
224 return m_sortDirsFirst
;
227 void KFileItemModel::setSortHiddenLast(bool hiddenLast
)
229 if (hiddenLast
!= m_sortHiddenLast
) {
230 m_sortHiddenLast
= hiddenLast
;
235 bool KFileItemModel::sortHiddenLast() const
237 return m_sortHiddenLast
;
240 void KFileItemModel::setShowHiddenFiles(bool show
)
242 m_dirLister
->setShowingDotFiles(show
);
243 m_dirLister
->emitChanges();
245 dispatchPendingItemsToInsert();
249 bool KFileItemModel::showHiddenFiles() const
251 return m_dirLister
->showingDotFiles();
254 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
256 m_dirLister
->setDirOnlyMode(enabled
);
259 bool KFileItemModel::showDirectoriesOnly() const
261 return m_dirLister
->dirOnlyMode();
264 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
266 QMimeData
* data
= new QMimeData();
268 // The following code has been taken from KDirModel::mimeData()
269 // (kdelibs/kio/kio/kdirmodel.cpp)
270 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
272 QList
<QUrl
> mostLocalUrls
;
273 const ItemData
* lastAddedItem
= nullptr;
275 for (int index
: indexes
) {
276 const ItemData
* itemData
= m_itemData
.at(index
);
277 const ItemData
* parent
= itemData
->parent
;
279 while (parent
&& parent
!= lastAddedItem
) {
280 parent
= parent
->parent
;
283 if (parent
&& parent
== lastAddedItem
) {
284 // A parent of 'itemData' has been added already.
288 lastAddedItem
= itemData
;
289 const KFileItem
& item
= itemData
->item
;
290 if (!item
.isNull()) {
294 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
298 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
302 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
304 startFromIndex
= qMax(0, startFromIndex
);
305 for (int i
= startFromIndex
; i
< count(); ++i
) {
306 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
310 for (int i
= 0; i
< startFromIndex
; ++i
) {
311 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
318 bool KFileItemModel::supportsDropping(int index
) const
320 const KFileItem item
= fileItem(index
);
321 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
324 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
326 static QHash
<QByteArray
, QString
> description
;
327 if (description
.isEmpty()) {
329 const RoleInfoMap
* map
= rolesInfoMap(count
);
330 for (int i
= 0; i
< count
; ++i
) {
331 if (map
[i
].roleTranslation
.isEmpty()) {
334 description
.insert(map
[i
].role
, map
[i
].roleTranslation
.toString());
338 return description
.value(role
);
341 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
343 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
344 #ifdef KFILEITEMMODEL_DEBUG
348 switch (typeForRole(sortRole())) {
349 case NameRole
: m_groups
= nameRoleGroups(); break;
350 case SizeRole
: m_groups
= sizeRoleGroups(); break;
351 case ModificationTimeRole
:
352 m_groups
= timeRoleGroups([](const ItemData
*item
) {
353 return item
->item
.time(KFileItem::ModificationTime
);
356 case CreationTimeRole
:
357 m_groups
= timeRoleGroups([](const ItemData
*item
) {
358 return item
->item
.time(KFileItem::CreationTime
);
362 m_groups
= timeRoleGroups([](const ItemData
*item
) {
363 return item
->item
.time(KFileItem::AccessTime
);
366 case DeletionTimeRole
:
367 m_groups
= timeRoleGroups([](const ItemData
*item
) {
368 return item
->values
.value("deletiontime").toDateTime();
371 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
372 case RatingRole
: m_groups
= ratingRoleGroups(); break;
373 default: m_groups
= genericStringRoleGroups(sortRole()); break;
376 #ifdef KFILEITEMMODEL_DEBUG
377 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
384 KFileItem
KFileItemModel::fileItem(int index
) const
386 if (index
>= 0 && index
< count()) {
387 return m_itemData
.at(index
)->item
;
393 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
395 const int indexForUrl
= index(url
);
396 if (indexForUrl
>= 0) {
397 return m_itemData
.at(indexForUrl
)->item
;
402 int KFileItemModel::index(const KFileItem
& item
) const
404 return index(item
.url());
407 int KFileItemModel::index(const QUrl
& url
) const
409 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
411 const int itemCount
= m_itemData
.count();
412 int itemsInHash
= m_items
.count();
414 int index
= m_items
.value(urlToFind
, -1);
415 while (index
< 0 && itemsInHash
< itemCount
) {
416 // Not all URLs are stored yet in m_items. We grow m_items until either
417 // urlToFind is found, or all URLs have been stored in m_items.
418 // Note that we do not add the URLs to m_items one by one, but in
419 // larger blocks. After each block, we check if urlToFind is in
420 // m_items. We could in principle compare urlToFind with each URL while
421 // we are going through m_itemData, but comparing two QUrls will,
422 // unlike calling qHash for the URLs, trigger a parsing of the URLs
423 // which costs both CPU cycles and memory.
424 const int blockSize
= 1000;
425 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
426 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
427 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
428 m_items
.insert(nextUrl
, i
);
431 itemsInHash
= currentBlockEnd
;
432 index
= m_items
.value(urlToFind
, -1);
436 // The item could not be found, even though all items from m_itemData
437 // should be in m_items now. We print some diagnostic information which
438 // might help to find the cause of the problem, but only once. This
439 // prevents that obtaining and printing the debugging information
440 // wastes CPU cycles and floods the shell or .xsession-errors.
441 static bool printDebugInfo
= true;
443 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
444 printDebugInfo
= false;
446 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
447 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
448 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
450 // Check if there are multiple items with the same URL.
451 QMultiHash
<QUrl
, int> indexesForUrl
;
452 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
453 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
456 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
457 for (const QUrl
& url
: uniqueKeys
) {
458 if (indexesForUrl
.count(url
) > 1) {
459 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
461 auto it
= indexesForUrl
.find(url
);
462 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
463 const ItemData
* data
= m_itemData
.at(it
.value());
464 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
466 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
478 KFileItem
KFileItemModel::rootItem() const
480 return m_dirLister
->rootItem();
483 void KFileItemModel::clear()
488 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
490 if (m_roles
== roles
) {
494 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
498 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
499 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
500 if (supportedExpanding
&& !willSupportExpanding
) {
501 // No expanding is supported anymore. Take care to delete all items that have an expansion level
502 // that is not 0 (and hence are part of an expanded item).
503 removeExpandedItems();
510 QSetIterator
<QByteArray
> it(roles
);
511 while (it
.hasNext()) {
512 const QByteArray
& role
= it
.next();
513 m_requestRole
[typeForRole(role
)] = true;
517 // Update m_data with the changed requested roles
518 const int maxIndex
= count() - 1;
519 for (int i
= 0; i
<= maxIndex
; ++i
) {
520 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
523 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
526 // Clear the 'values' of all filtered items. They will be re-populated with the
527 // correct roles the next time 'values' will be accessed via data(int).
528 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
529 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
530 while (filteredIt
!= filteredEnd
) {
531 (*filteredIt
)->values
.clear();
536 QSet
<QByteArray
> KFileItemModel::roles() const
541 bool KFileItemModel::setExpanded(int index
, bool expanded
)
543 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
547 QHash
<QByteArray
, QVariant
> values
;
548 values
.insert(sharedValue("isExpanded"), expanded
);
549 if (!setData(index
, values
)) {
553 const KFileItem item
= m_itemData
.at(index
)->item
;
554 const QUrl url
= item
.url();
555 const QUrl targetUrl
= item
.targetUrl();
557 m_expandedDirs
.insert(targetUrl
, url
);
558 m_dirLister
->openUrl(url
, KDirLister::Keep
);
560 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
561 for (const QVariant
& var
: previouslyExpandedChildren
) {
562 m_urlsToExpand
.insert(var
.toUrl());
565 // Note that there might be (indirect) children of the folder which is to be collapsed in
566 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
567 // possibly without a parent, which might result in a crash, we insert all pending items
568 // right now. All new items which would be without a parent will then be removed.
569 dispatchPendingItemsToInsert();
571 // Check if the index of the collapsed folder has changed. If that is the case, then items
572 // were inserted before the collapsed folder, and its index needs to be updated.
573 if (m_itemData
.at(index
)->item
!= item
) {
574 index
= this->index(item
);
577 m_expandedDirs
.remove(targetUrl
);
578 m_dirLister
->stop(url
);
579 #if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0)
580 m_dirLister
->forgetDirs(url
);
583 const int parentLevel
= expandedParentsCount(index
);
584 const int itemCount
= m_itemData
.count();
585 const int firstChildIndex
= index
+ 1;
587 QVariantList expandedChildren
;
589 int childIndex
= firstChildIndex
;
590 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
591 ItemData
* itemData
= m_itemData
.at(childIndex
);
592 if (itemData
->values
.value("isExpanded").toBool()) {
593 const QUrl targetUrl
= itemData
->item
.targetUrl();
594 const QUrl url
= itemData
->item
.url();
595 m_expandedDirs
.remove(targetUrl
);
596 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
597 #if KIO_VERSION >= QT_VERSION_CHECK(5, 92, 0)
598 m_dirLister
->forgetDirs(url
);
600 expandedChildren
.append(targetUrl
);
604 const int childrenCount
= childIndex
- firstChildIndex
;
606 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
607 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
609 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
615 bool KFileItemModel::isExpanded(int index
) const
617 if (index
>= 0 && index
< count()) {
618 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
623 bool KFileItemModel::isExpandable(int index
) const
625 if (index
>= 0 && index
< count()) {
626 // Call data (instead of accessing m_itemData directly)
627 // to ensure that the value is initialized.
628 return data(index
).value("isExpandable").toBool();
633 int KFileItemModel::expandedParentsCount(int index
) const
635 if (index
>= 0 && index
< count()) {
636 return expandedParentsCount(m_itemData
.at(index
));
641 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
644 const auto dirs
= m_expandedDirs
;
645 for (const auto &dir
: dirs
) {
651 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
653 m_urlsToExpand
= urls
;
656 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
659 // Assure that each sub-path of the URL that should be
660 // expanded is added to m_urlsToExpand. KDirLister
661 // does not care whether the parent-URL has already been
663 QUrl urlToExpand
= m_dirLister
->url();
664 const int pos
= urlToExpand
.path().length();
666 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
667 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
668 // so using QString::SkipEmptyParts
669 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
670 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
671 QString path
= urlToExpand
.path();
672 if (!path
.endsWith(QLatin1Char('/'))) {
673 path
.append(QLatin1Char('/'));
675 urlToExpand
.setPath(path
+ subDirs
.at(i
));
676 m_urlsToExpand
.insert(urlToExpand
);
679 // KDirLister::open() must called at least once to trigger an initial
680 // loading. The pending URLs that must be restored are handled
681 // in slotCompleted().
682 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
683 while (it2
.hasNext()) {
684 const int idx
= index(it2
.next());
685 if (idx
>= 0 && !isExpanded(idx
)) {
686 setExpanded(idx
, true);
692 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
694 if (m_filter
.pattern() != nameFilter
) {
695 dispatchPendingItemsToInsert();
696 m_filter
.setPattern(nameFilter
);
701 QString
KFileItemModel::nameFilter() const
703 return m_filter
.pattern();
706 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
708 if (m_filter
.mimeTypes() != filters
) {
709 dispatchPendingItemsToInsert();
710 m_filter
.setMimeTypes(filters
);
715 QStringList
KFileItemModel::mimeTypeFilters() const
717 return m_filter
.mimeTypes();
720 void KFileItemModel::applyFilters()
723 // Check which previously shown items from m_itemData must now get
724 // hidden and hence moved from m_itemData into m_filteredItems.
726 QList
<int> newFilteredIndexes
; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
728 // This pointer will refer to the next confirmed shown item from the point of
729 // view of the current "itemData" in the upcoming "for" loop.
730 ItemData
*itemShownBelow
= nullptr;
732 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
733 for (int index
= m_itemData
.count() - 1; index
>= 0; --index
) {
734 ItemData
*itemData
= m_itemData
.at(index
);
736 if (m_filter
.matches(itemData
->item
)
737 || (itemShownBelow
&& itemShownBelow
->parent
== itemData
)) {
738 // We could've entered here for two reasons:
739 // 1. This item passes the filter itself
740 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
742 // So this item must remain shown.
743 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
744 itemShownBelow
= itemData
;
746 // We hide this item for now, however, for expanded folders this is not final:
747 // if after the next "for" loop we discover that its children must now be shown with the newly applied fliter, we shall re-insert it
748 newFilteredIndexes
.prepend(index
);
749 m_filteredItems
.insert(itemData
->item
, itemData
);
750 // indexShownBelow doesn't get updated since this item will be hidden
754 // This will remove the newly filtered items from m_itemData
755 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes
), KeepItemData
);
758 // Check which hidden items from m_filteredItems should
759 // become visible again and hence moved from m_filteredItems back into m_itemData.
761 QList
<ItemData
*> newVisibleItems
;
763 QHash
<KFileItem
, ItemData
*> ancestorsOfNewVisibleItems
; // We will make sure these also become visible in step 3.
765 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
766 while (it
!= m_filteredItems
.end()) {
767 if (m_filter
.matches(it
.key())) {
768 newVisibleItems
.append(it
.value());
770 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
771 // We will go up through its parental chain until we either:
772 // 1 - reach the "root item" of the current view, i.e the currently opened folder on Dolphin. Their children have their ItemData::parent set to nullptr.
774 // 2 - we reach an unfiltered parent or a previously discovered ancestor.
775 for (ItemData
*parent
= it
.value()->parent
; parent
&& !ancestorsOfNewVisibleItems
.contains(parent
->item
) && m_filteredItems
.contains(parent
->item
);
776 parent
= parent
->parent
) {
777 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
778 // and it would mess up the iteration. We will mark it to be removed in step 3.
779 ancestorsOfNewVisibleItems
.insert(parent
->item
, parent
);
782 it
= m_filteredItems
.erase(it
);
784 // Item remains filtered for now
785 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
791 // Handles the ancestorsOfNewVisibleItems.
792 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
793 for (it
= ancestorsOfNewVisibleItems
.begin(); it
!= ancestorsOfNewVisibleItems
.end(); it
++) {
794 if (m_filteredItems
.remove(it
.key())) {
795 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
796 newVisibleItems
.append(it
.value());
800 // This will insert the newly discovered unfiltered items into m_itemData
801 insertItems(newVisibleItems
);
804 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
806 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
807 // There are either no filtered items, or it is not possible to expand
808 // folders -> there cannot be any filtered children.
812 QSet
<ItemData
*> parents
;
813 for (const KItemRange
& range
: itemRanges
) {
814 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
815 parents
.insert(m_itemData
.at(index
));
819 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
820 while (it
!= m_filteredItems
.end()) {
821 if (parents
.contains(it
.value()->parent
)) {
823 it
= m_filteredItems
.erase(it
);
830 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
832 static QList
<RoleInfo
> rolesInfo
;
833 if (rolesInfo
.isEmpty()) {
835 const RoleInfoMap
* map
= rolesInfoMap(count
);
836 for (int i
= 0; i
< count
; ++i
) {
837 if (map
[i
].roleType
!= NoRole
) {
839 info
.role
= map
[i
].role
;
840 info
.translation
= map
[i
].roleTranslation
.toString();
841 if (!map
[i
].groupTranslation
.isEmpty()) {
842 info
.group
= map
[i
].groupTranslation
.toString();
844 // For top level roles, groupTranslation is 0. We must make sure that
845 // info.group is an empty string then because the code that generates
846 // menus tries to put the actions into sub menus otherwise.
847 info
.group
= QString();
849 info
.requiresBaloo
= map
[i
].requiresBaloo
;
850 info
.requiresIndexer
= map
[i
].requiresIndexer
;
851 rolesInfo
.append(info
);
859 void KFileItemModel::onGroupedSortingChanged(bool current
)
865 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
868 m_sortRole
= typeForRole(current
);
870 if (!m_requestRole
[m_sortRole
]) {
871 QSet
<QByteArray
> newRoles
= m_roles
;
881 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
888 void KFileItemModel::loadSortingSettings()
890 using Choice
= GeneralSettings::EnumSortingChoice
;
891 switch (GeneralSettings::sortingChoice()) {
892 case Choice::NaturalSorting
:
893 m_naturalSorting
= true;
894 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
896 case Choice::CaseSensitiveSorting
:
897 m_naturalSorting
= false;
898 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
900 case Choice::CaseInsensitiveSorting
:
901 m_naturalSorting
= false;
902 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
907 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
908 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
909 m_collator
.compare(QString(), QString());
912 void KFileItemModel::resortAllItems()
914 m_resortAllItemsTimer
->stop();
916 const int itemCount
= count();
917 if (itemCount
<= 0) {
921 #ifdef KFILEITEMMODEL_DEBUG
924 qCDebug(DolphinDebug
) << "===========================================================";
925 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
928 // Remember the order of the current URLs so
929 // that it can be determined which indexes have
930 // been moved because of the resorting.
932 oldUrls
.reserve(itemCount
);
933 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
934 oldUrls
.append(itemData
->item
.url());
938 m_items
.reserve(itemCount
);
941 sort(m_itemData
.begin(), m_itemData
.end());
942 for (int i
= 0; i
< itemCount
; ++i
) {
943 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
946 // Determine the first index that has been moved.
947 int firstMovedIndex
= 0;
948 while (firstMovedIndex
< itemCount
949 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
953 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
954 if (itemsHaveMoved
) {
957 int lastMovedIndex
= itemCount
- 1;
958 while (lastMovedIndex
> firstMovedIndex
959 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
963 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
965 // Create a list movedToIndexes, which has the property that
966 // movedToIndexes[i] is the new index of the item with the old index
967 // firstMovedIndex + i.
968 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
969 QList
<int> movedToIndexes
;
970 movedToIndexes
.reserve(movedItemsCount
);
971 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
972 const int newIndex
= m_items
.value(oldUrls
.at(i
));
973 movedToIndexes
.append(newIndex
);
976 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
977 } else if (groupedSorting()) {
978 // The groups might have changed even if the order of the items has not.
979 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
981 if (groups() != oldGroups
) {
982 Q_EMIT
groupsChanged();
986 #ifdef KFILEITEMMODEL_DEBUG
987 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
991 void KFileItemModel::slotCompleted()
993 m_maximumUpdateIntervalTimer
->stop();
994 dispatchPendingItemsToInsert();
996 if (!m_urlsToExpand
.isEmpty()) {
997 // Try to find a URL that can be expanded.
998 // Note that the parent folder must be expanded before any of its subfolders become visible.
999 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1000 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1001 // Iterate over a const copy because items are deleted and inserted within the loop
1002 const auto urlsToExpand
= m_urlsToExpand
;
1003 for(const QUrl
&url
: urlsToExpand
) {
1004 const int indexForUrl
= index(url
);
1005 if (indexForUrl
>= 0) {
1006 m_urlsToExpand
.remove(url
);
1007 if (setExpanded(indexForUrl
, true)) {
1008 // The dir lister has been triggered. This slot will be called
1009 // again after the directory has been expanded.
1015 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1016 // if these URLs have been deleted in the meantime.
1017 m_urlsToExpand
.clear();
1020 Q_EMIT
directoryLoadingCompleted();
1023 void KFileItemModel::slotCanceled()
1025 m_maximumUpdateIntervalTimer
->stop();
1026 dispatchPendingItemsToInsert();
1028 Q_EMIT
directoryLoadingCanceled();
1031 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
1033 Q_ASSERT(!items
.isEmpty());
1035 const QUrl parentUrl
= m_expandedDirs
.value(directoryUrl
, directoryUrl
.adjusted(QUrl::StripTrailingSlash
));
1037 if (m_requestRole
[ExpandedParentsCountRole
]) {
1038 // If the expanding of items is enabled, the call
1039 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1040 // might result in emitting the same items twice due to the Keep-parameter.
1041 // This case happens if an item gets expanded, collapsed and expanded again
1042 // before the items could be loaded for the first expansion.
1043 if (index(items
.first().url()) >= 0) {
1044 // The items are already part of the model.
1048 if (directoryUrl
!= directory()) {
1049 // To be able to compare whether the new items may be inserted as children
1050 // of a parent item the pending items must be added to the model first.
1051 dispatchPendingItemsToInsert();
1054 // KDirLister keeps the children of items that got expanded once even if
1055 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1056 // checked whether the parent for new items is still expanded.
1057 const int parentIndex
= index(parentUrl
);
1058 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
1059 // The parent is not expanded.
1064 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
1066 if (!m_filter
.hasSetFilters()) {
1067 m_pendingItemsToInsert
.append(itemDataList
);
1069 QSet
<ItemData
*> parentsToEnsureVisible
;
1071 // The name or type filter is active. Hide filtered items
1072 // before inserting them into the model and remember
1073 // the filtered items in m_filteredItems.
1074 for (ItemData
* itemData
: itemDataList
) {
1075 if (m_filter
.matches(itemData
->item
)) {
1076 m_pendingItemsToInsert
.append(itemData
);
1077 if (itemData
->parent
) {
1078 parentsToEnsureVisible
.insert(itemData
->parent
);
1081 m_filteredItems
.insert(itemData
->item
, itemData
);
1085 // Entire parental chains must be shown
1086 for (ItemData
*parent
: parentsToEnsureVisible
) {
1087 for (; parent
&& m_filteredItems
.remove(parent
->item
); parent
= parent
->parent
) {
1088 m_pendingItemsToInsert
.append(parent
);
1093 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1094 // Assure that items get dispatched if no completed() or canceled() signal is
1095 // emitted during the maximum update interval.
1096 m_maximumUpdateIntervalTimer
->start();
1099 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1102 int KFileItemModel::filterChildlessParents(KItemRangeList
&removedItemRanges
, const QSet
<ItemData
*> &parentsToEnsureVisible
)
1104 int filteredParentsCount
= 0;
1105 // The childless parents not yet removed will always be right above the start of a removed range.
1106 // We iterate backwards to ensure the deepest folders are processed before their parents
1107 for (int i
= removedItemRanges
.size() - 1; i
>= 0; i
--) {
1108 KItemRange itemRange
= removedItemRanges
.at(i
);
1109 const ItemData
*const firstInRange
= m_itemData
.at(itemRange
.index
);
1110 ItemData
*itemAbove
= itemRange
.index
- 1 >= 0 ? m_itemData
.at(itemRange
.index
- 1) : nullptr;
1111 const ItemData
*const itemBelow
= itemRange
.index
+ itemRange
.count
< m_itemData
.count() ? m_itemData
.at(itemRange
.index
+ itemRange
.count
) : nullptr;
1113 if (itemAbove
&& firstInRange
->parent
== itemAbove
&& !m_filter
.matches(itemAbove
->item
) && (!itemBelow
|| itemBelow
->parent
!= itemAbove
)
1114 && !parentsToEnsureVisible
.contains(itemAbove
)) {
1115 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1116 // and this deleted range covers all of its descendents, so none will be left.
1117 m_filteredItems
.insert(itemAbove
->item
, itemAbove
);
1118 // This range's starting index will be extended to include the parent above:
1121 ++filteredParentsCount
;
1122 KItemRange previousRange
= i
> 0 ? removedItemRanges
.at(i
- 1) : KItemRange();
1123 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1124 if (i
> 0 && previousRange
.index
+ previousRange
.count
== itemRange
.index
) {
1125 previousRange
.count
+= itemRange
.count
;
1126 removedItemRanges
.replace(i
- 1, previousRange
);
1127 removedItemRanges
.removeAt(i
);
1129 removedItemRanges
.replace(i
, itemRange
);
1130 // We must revisit this range in the next iteration since its starting index changed
1135 return filteredParentsCount
;
1138 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1140 dispatchPendingItemsToInsert();
1142 QVector
<int> indexesToRemove
;
1143 indexesToRemove
.reserve(items
.count());
1144 KFileItemList dirsChanged
;
1146 for (const KFileItem
& item
: items
) {
1147 const int indexForItem
= index(item
);
1148 if (indexForItem
>= 0) {
1149 indexesToRemove
.append(indexForItem
);
1151 // Probably the item has been filtered.
1152 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1153 if (it
!= m_filteredItems
.end()) {
1155 m_filteredItems
.erase(it
);
1159 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1160 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1161 dirsChanged
<< KFileItem(parentUrl
);
1165 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1167 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1168 // Assure that removing a parent item also results in removing all children
1169 QVector
<int> indexesToRemoveWithChildren
;
1170 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1172 const int itemCount
= m_itemData
.count();
1173 for (int index
: qAsConst(indexesToRemove
)) {
1174 indexesToRemoveWithChildren
.append(index
);
1176 const int parentLevel
= expandedParentsCount(index
);
1177 int childIndex
= index
+ 1;
1178 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1179 indexesToRemoveWithChildren
.append(childIndex
);
1184 indexesToRemove
= indexesToRemoveWithChildren
;
1187 KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1188 removeFilteredChildren(itemRanges
);
1190 // This call will update itemRanges to include the childless parents that have been filtered.
1191 const int filteredParentsCount
= filterChildlessParents(itemRanges
);
1193 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1194 // mixed with expanded folders that are just being filtered out.
1195 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1196 // so removeItems() will check m_filteredItems to differentiate which is which.
1197 removeItems(itemRanges
, filteredParentsCount
> 0 ? DeleteItemDataIfUnfiltered
: DeleteItemData
);
1199 Q_EMIT
fileItemsChanged(dirsChanged
);
1202 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1204 Q_ASSERT(!items
.isEmpty());
1205 #ifdef KFILEITEMMODEL_DEBUG
1206 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1209 // Get the indexes of all items that have been refreshed
1211 indexes
.reserve(items
.count());
1213 QSet
<QByteArray
> changedRoles
;
1214 KFileItemList changedFiles
;
1216 // Contains the indexes of the currently visible items
1217 // that should get hidden and hence moved to m_filteredItems.
1218 QVector
<int> newFilteredIndexes
;
1220 // Contains currently hidden items that should
1221 // get visible and hence removed from m_filteredItems
1222 QList
<ItemData
*> newVisibleItems
;
1224 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1226 while (it
.hasNext()) {
1227 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1228 const KFileItem
& oldItem
= itemPair
.first
;
1229 const KFileItem
& newItem
= itemPair
.second
;
1230 const int indexForItem
= index(oldItem
);
1231 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1232 if (indexForItem
>= 0) {
1233 m_itemData
[indexForItem
]->item
= newItem
;
1235 // Keep old values as long as possible if they could not retrieved synchronously yet.
1236 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1237 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1238 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1239 while (it
.hasNext()) {
1241 const QByteArray
& role
= it
.key();
1242 if (itemData
->values
.value(role
) != it
.value()) {
1243 itemData
->values
.insert(role
, it
.value());
1244 changedRoles
.insert(role
);
1248 m_items
.remove(oldItem
.url());
1249 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1250 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1251 m_items
.insert(newItem
.url(), indexForItem
);
1252 if (newItemMatchesFilter
1253 || (itemData
->values
.value("isExpanded").toBool()
1254 && (indexForItem
+ 1 < m_itemData
.count() && m_itemData
.at(indexForItem
+ 1)->parent
== itemData
))) {
1255 // We are lenient with expanded folders that originally had visible children.
1256 // If they become childless now they will be caught by filterChildlessParents()
1257 changedFiles
.append(newItem
);
1258 indexes
.append(indexForItem
);
1260 newFilteredIndexes
.append(indexForItem
);
1261 m_filteredItems
.insert(newItem
, itemData
);
1264 // Check if 'oldItem' is one of the filtered items.
1265 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1266 if (it
!= m_filteredItems
.end()) {
1267 ItemData
*const itemData
= it
.value();
1268 itemData
->item
= newItem
;
1270 // The data stored in 'values' might have changed. Therefore, we clear
1271 // 'values' and re-populate it the next time it is requested via data(int).
1272 // Before clearing, we must remember if it was expanded and the expanded parents count,
1273 // otherwise these states would be lost. The data() method will deal with this special case.
1274 const bool isExpanded
= itemData
->values
.value("isExpanded").toBool();
1275 bool hasExpandedParentsCount
= false;
1276 const int expandedParentsCount
= itemData
->values
.value("expandedParentsCount").toInt(&hasExpandedParentsCount
);
1277 itemData
->values
.clear();
1279 itemData
->values
.insert("isExpanded", true);
1280 if (hasExpandedParentsCount
) {
1281 itemData
->values
.insert("expandedParentsCount", expandedParentsCount
);
1285 m_filteredItems
.erase(it
);
1286 if (newItemMatchesFilter
) {
1287 newVisibleItems
.append(itemData
);
1289 m_filteredItems
.insert(newItem
, itemData
);
1295 std::sort(newFilteredIndexes
.begin(), newFilteredIndexes
.end());
1297 // We must keep track of parents of new visible items since they must be shown no matter what
1298 // They will be considered "immune" to filterChildlessParents()
1299 QSet
<ItemData
*> parentsToEnsureVisible
;
1301 for (ItemData
*item
: newVisibleItems
) {
1302 for (ItemData
*parent
= item
->parent
; parent
&& !parentsToEnsureVisible
.contains(parent
); parent
= parent
->parent
) {
1303 parentsToEnsureVisible
.insert(parent
);
1306 for (ItemData
*parent
: parentsToEnsureVisible
) {
1307 // We make sure they are all unfiltered.
1308 if (m_filteredItems
.remove(parent
->item
)) {
1309 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1310 newVisibleItems
.append(parent
);
1311 // It could be in newFilteredIndexes, we must remove it if it's there:
1312 const int parentIndex
= index(parent
->item
);
1313 if (parentIndex
>= 0) {
1314 QVector
<int>::iterator it
= std::lower_bound(newFilteredIndexes
.begin(), newFilteredIndexes
.end(), parentIndex
);
1315 if (it
!= newFilteredIndexes
.end() && *it
== parentIndex
) {
1316 newFilteredIndexes
.erase(it
);
1322 KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1324 // This call will update itemRanges to include the childless parents that have been filtered.
1325 filterChildlessParents(removedRanges
, parentsToEnsureVisible
);
1327 removeItems(removedRanges
, KeepItemData
);
1329 // Show previously hidden items that should get visible
1330 insertItems(newVisibleItems
);
1332 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1334 // If the changed items have been created recently, they might not be in m_items yet.
1335 // In that case, the list 'indexes' might be empty.
1336 if (indexes
.isEmpty()) {
1340 if (newVisibleItems
.count() > 0 || removedRanges
.count() > 0) {
1341 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1343 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1344 const QSet
<const KFileItem
> changedFilesSet(changedFiles
.cbegin(), changedFiles
.cend());
1345 for (int i
= 0; i
< m_itemData
.count(); i
++) {
1346 if (changedFilesSet
.contains(m_itemData
.at(i
)->item
)) {
1351 std::sort(indexes
.begin(), indexes
.end());
1354 // Extract the item-ranges out of the changed indexes
1355 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1356 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1358 Q_EMIT
fileItemsChanged(changedFiles
);
1361 void KFileItemModel::slotClear()
1363 #ifdef KFILEITEMMODEL_DEBUG
1364 qCDebug(DolphinDebug
) << "Clearing all items";
1367 qDeleteAll(m_filteredItems
);
1368 m_filteredItems
.clear();
1371 m_maximumUpdateIntervalTimer
->stop();
1372 m_resortAllItemsTimer
->stop();
1374 qDeleteAll(m_pendingItemsToInsert
);
1375 m_pendingItemsToInsert
.clear();
1377 const int removedCount
= m_itemData
.count();
1378 if (removedCount
> 0) {
1379 qDeleteAll(m_itemData
);
1382 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1385 m_expandedDirs
.clear();
1388 void KFileItemModel::slotSortingChoiceChanged()
1390 loadSortingSettings();
1394 void KFileItemModel::dispatchPendingItemsToInsert()
1396 if (!m_pendingItemsToInsert
.isEmpty()) {
1397 insertItems(m_pendingItemsToInsert
);
1398 m_pendingItemsToInsert
.clear();
1402 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1404 if (newItems
.isEmpty()) {
1408 #ifdef KFILEITEMMODEL_DEBUG
1409 QElapsedTimer timer
;
1411 qCDebug(DolphinDebug
) << "===========================================================";
1412 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1416 prepareItemsForSorting(newItems
);
1418 // Natural sorting of items can be very slow. However, it becomes much faster
1419 // if the input sequence is already mostly sorted. Therefore, we first sort
1420 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1421 if (m_naturalSorting
) {
1422 if (m_sortRole
== NameRole
) {
1423 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1424 } else if (isRoleValueNatural(m_sortRole
)) {
1425 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1427 const QByteArray role
= roleForType(m_sortRole
);
1428 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1430 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1434 sort(newItems
.begin(), newItems
.end());
1436 #ifdef KFILEITEMMODEL_DEBUG
1437 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1440 KItemRangeList itemRanges
;
1441 const int existingItemCount
= m_itemData
.count();
1442 const int newItemCount
= newItems
.count();
1443 const int totalItemCount
= existingItemCount
+ newItemCount
;
1445 if (existingItemCount
== 0) {
1446 // Optimization for the common special case that there are no
1447 // items in the model yet. Happens, e.g., when entering a folder.
1448 m_itemData
= newItems
;
1449 itemRanges
<< KItemRange(0, newItemCount
);
1451 m_itemData
.reserve(totalItemCount
);
1452 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1453 m_itemData
.append(nullptr);
1456 // We build the new list m_itemData in reverse order to minimize
1457 // the number of moves and guarantee O(N) complexity.
1458 int targetIndex
= totalItemCount
- 1;
1459 int sourceIndexExistingItems
= existingItemCount
- 1;
1460 int sourceIndexNewItems
= newItemCount
- 1;
1464 while (sourceIndexNewItems
>= 0) {
1465 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1466 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1467 // Move an existing item to its new position. If any new items
1468 // are behind it, push the item range to itemRanges.
1469 if (rangeCount
> 0) {
1470 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1474 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1475 --sourceIndexExistingItems
;
1477 // Insert a new item into the list.
1479 m_itemData
[targetIndex
] = newItem
;
1480 --sourceIndexNewItems
;
1485 // Push the final item range to itemRanges.
1486 if (rangeCount
> 0) {
1487 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1490 // Note that itemRanges is still sorted in reverse order.
1491 std::reverse(itemRanges
.begin(), itemRanges
.end());
1494 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1495 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1498 Q_EMIT
itemsInserted(itemRanges
);
1500 #ifdef KFILEITEMMODEL_DEBUG
1501 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1505 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1507 if (itemRanges
.isEmpty()) {
1513 // Step 1: Remove the items from m_itemData, and free the ItemData.
1514 int removedItemsCount
= 0;
1515 for (const KItemRange
& range
: itemRanges
) {
1516 removedItemsCount
+= range
.count
;
1518 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1519 if (behavior
== DeleteItemData
|| (behavior
== DeleteItemDataIfUnfiltered
&& !m_filteredItems
.contains(m_itemData
.at(index
)->item
))) {
1520 delete m_itemData
.at(index
);
1523 m_itemData
[index
] = nullptr;
1527 // Step 2: Remove the ItemData pointers from the list m_itemData.
1528 int target
= itemRanges
.at(0).index
;
1529 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1532 const int oldItemDataCount
= m_itemData
.count();
1533 while (source
< oldItemDataCount
) {
1534 m_itemData
[target
] = m_itemData
[source
];
1538 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1539 // Skip the items in the next removed range.
1540 source
+= itemRanges
.at(nextRange
).count
;
1545 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1547 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1548 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1551 Q_EMIT
itemsRemoved(itemRanges
);
1554 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1556 if (m_sortRole
== TypeRole
) {
1557 // Try to resolve the MIME-types synchronously to prevent a reordering of
1558 // the items when sorting by type (per default MIME-types are resolved
1559 // asynchronously by KFileItemModelRolesUpdater).
1560 determineMimeTypes(items
, 200);
1563 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1564 const int parentIndex
= index(parentUrl
);
1565 ItemData
*parentItem
= parentIndex
< 0 ? m_filteredItems
.value(KFileItem(parentUrl
), nullptr) : m_itemData
.at(parentIndex
);
1567 QList
<ItemData
*> itemDataList
;
1568 itemDataList
.reserve(items
.count());
1570 for (const KFileItem
& item
: items
) {
1571 ItemData
* itemData
= new ItemData();
1572 itemData
->item
= item
;
1573 itemData
->parent
= parentItem
;
1574 itemDataList
.append(itemData
);
1577 return itemDataList
;
1580 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1582 switch (m_sortRole
) {
1583 case PermissionsRole
:
1586 case DestinationRole
:
1588 case DeletionTimeRole
:
1589 // These roles can be determined with retrieveData, and they have to be stored
1590 // in the QHash "values" for the sorting.
1591 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1592 if (itemData
->values
.isEmpty()) {
1593 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1599 // At least store the data including the file type for items with known MIME type.
1600 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1601 if (itemData
->values
.isEmpty()) {
1602 const KFileItem item
= itemData
->item
;
1603 if (item
.isDir() || item
.isMimeTypeKnown()) {
1604 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1611 // The other roles are either resolved by KFileItemModelRolesUpdater
1612 // (this includes the SizeRole for directories), or they do not need
1613 // to be stored in the QHash "values" for sorting because the data can
1614 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1620 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1622 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1623 // if the corresponding item is expanded, and it is not a top-level item.
1624 const ItemData
* parent
= data
->parent
;
1626 if (parent
->parent
) {
1627 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1628 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1637 void KFileItemModel::removeExpandedItems()
1639 QVector
<int> indexesToRemove
;
1641 const int maxIndex
= m_itemData
.count() - 1;
1642 for (int i
= 0; i
<= maxIndex
; ++i
) {
1643 const ItemData
* itemData
= m_itemData
.at(i
);
1644 if (itemData
->parent
) {
1645 indexesToRemove
.append(i
);
1649 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1650 m_expandedDirs
.clear();
1652 // Also remove all filtered items which have a parent.
1653 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1654 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1657 if (it
.value()->parent
) {
1659 it
= m_filteredItems
.erase(it
);
1666 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1668 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1670 // Trigger a resorting if necessary. Note that this can happen even if the sort
1671 // role has not changed at all because the file name can be used as a fallback.
1672 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1673 for (const KItemRange
& range
: itemRanges
) {
1674 bool needsResorting
= false;
1676 const int first
= range
.index
;
1677 const int last
= range
.index
+ range
.count
- 1;
1679 // Resorting the model is necessary if
1680 // (a) The first item in the range is "lessThan" its predecessor,
1681 // (b) the successor of the last item is "lessThan" the last item, or
1682 // (c) the internal order of the items in the range is incorrect.
1684 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1685 needsResorting
= true;
1686 } else if (last
< count() - 1
1687 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1688 needsResorting
= true;
1690 for (int index
= first
; index
< last
; ++index
) {
1691 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1692 needsResorting
= true;
1698 if (needsResorting
) {
1699 m_resortAllItemsTimer
->start();
1705 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1706 // The position is still correct, but the groups might have changed
1707 // if the changed item is either the first or the last item in a
1709 // In principle, we could try to find out if the item really is the
1710 // first or last one in its group and then update the groups
1711 // (possibly with a delayed timer to make sure that we don't
1712 // re-calculate the groups very often if items are updated one by
1713 // one), but starting m_resortAllItemsTimer is easier.
1714 m_resortAllItemsTimer
->start();
1718 void KFileItemModel::resetRoles()
1720 for (int i
= 0; i
< RolesCount
; ++i
) {
1721 m_requestRole
[i
] = false;
1725 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1727 static QHash
<QByteArray
, RoleType
> roles
;
1728 if (roles
.isEmpty()) {
1729 // Insert user visible roles that can be accessed with
1730 // KFileItemModel::roleInformation()
1732 const RoleInfoMap
* map
= rolesInfoMap(count
);
1733 for (int i
= 0; i
< count
; ++i
) {
1734 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1737 // Insert internal roles (take care to synchronize the implementation
1738 // with KFileItemModel::roleForType() in case if a change is done).
1739 roles
.insert("isDir", IsDirRole
);
1740 roles
.insert("isLink", IsLinkRole
);
1741 roles
.insert("isHidden", IsHiddenRole
);
1742 roles
.insert("isExpanded", IsExpandedRole
);
1743 roles
.insert("isExpandable", IsExpandableRole
);
1744 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1746 Q_ASSERT(roles
.count() == RolesCount
);
1749 return roles
.value(role
, NoRole
);
1752 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1754 static QHash
<RoleType
, QByteArray
> roles
;
1755 if (roles
.isEmpty()) {
1756 // Insert user visible roles that can be accessed with
1757 // KFileItemModel::roleInformation()
1759 const RoleInfoMap
* map
= rolesInfoMap(count
);
1760 for (int i
= 0; i
< count
; ++i
) {
1761 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1764 // Insert internal roles (take care to synchronize the implementation
1765 // with KFileItemModel::typeForRole() in case if a change is done).
1766 roles
.insert(IsDirRole
, "isDir");
1767 roles
.insert(IsLinkRole
, "isLink");
1768 roles
.insert(IsHiddenRole
, "isHidden");
1769 roles
.insert(IsExpandedRole
, "isExpanded");
1770 roles
.insert(IsExpandableRole
, "isExpandable");
1771 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1773 Q_ASSERT(roles
.count() == RolesCount
);
1776 return roles
.value(roleType
);
1779 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1781 // It is important to insert only roles that are fast to retrieve. E.g.
1782 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1783 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1784 QHash
<QByteArray
, QVariant
> data
;
1785 data
.insert(sharedValue("url"), item
.url());
1787 const bool isDir
= item
.isDir();
1788 if (m_requestRole
[IsDirRole
] && isDir
) {
1789 data
.insert(sharedValue("isDir"), true);
1792 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1793 data
.insert(sharedValue("isLink"), true);
1796 if (m_requestRole
[IsHiddenRole
]) {
1797 data
.insert(sharedValue("isHidden"), item
.isHidden());
1800 if (m_requestRole
[NameRole
]) {
1801 data
.insert(sharedValue("text"), item
.text());
1804 if (m_requestRole
[SizeRole
] && !isDir
) {
1805 data
.insert(sharedValue("size"), item
.size());
1808 if (m_requestRole
[ModificationTimeRole
]) {
1809 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1810 // having several thousands of items. Instead read the raw number from UDSEntry directly
1811 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1812 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1813 data
.insert(sharedValue("modificationtime"), dateTime
);
1816 if (m_requestRole
[CreationTimeRole
]) {
1817 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1818 // having several thousands of items. Instead read the raw number from UDSEntry directly
1819 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1820 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1821 data
.insert(sharedValue("creationtime"), dateTime
);
1824 if (m_requestRole
[AccessTimeRole
]) {
1825 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1826 // having several thousands of items. Instead read the raw number from UDSEntry directly
1827 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1828 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1829 data
.insert(sharedValue("accesstime"), dateTime
);
1832 if (m_requestRole
[PermissionsRole
]) {
1833 data
.insert(sharedValue("permissions"), item
.permissionsString());
1836 if (m_requestRole
[OwnerRole
]) {
1837 data
.insert(sharedValue("owner"), item
.user());
1840 if (m_requestRole
[GroupRole
]) {
1841 data
.insert(sharedValue("group"), item
.group());
1844 if (m_requestRole
[DestinationRole
]) {
1845 QString destination
= item
.linkDest();
1846 if (destination
.isEmpty()) {
1847 destination
= QLatin1Char('-');
1849 data
.insert(sharedValue("destination"), destination
);
1852 if (m_requestRole
[PathRole
]) {
1854 if (item
.url().scheme() == QLatin1String("trash")) {
1855 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1857 // For performance reasons cache the home-path in a static QString
1858 // (see QDir::homePath() for more details)
1859 static QString homePath
;
1860 if (homePath
.isEmpty()) {
1861 homePath
= QDir::homePath();
1864 path
= item
.localPath();
1865 if (path
.startsWith(homePath
)) {
1866 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1870 const int index
= path
.lastIndexOf(item
.text());
1871 path
= path
.mid(0, index
- 1);
1872 data
.insert(sharedValue("path"), path
);
1875 if (m_requestRole
[DeletionTimeRole
]) {
1876 QDateTime deletionTime
;
1877 if (item
.url().scheme() == QLatin1String("trash")) {
1878 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1880 data
.insert(sharedValue("deletiontime"), deletionTime
);
1883 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1884 data
.insert(sharedValue("isExpandable"), true);
1887 if (m_requestRole
[ExpandedParentsCountRole
]) {
1889 const int level
= expandedParentsCount(parent
) + 1;
1890 data
.insert(sharedValue("expandedParentsCount"), level
);
1894 if (item
.isMimeTypeKnown()) {
1895 QString iconName
= item
.iconName();
1896 if (!QIcon::hasThemeIcon(iconName
)) {
1897 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1898 iconName
= mimeType
.genericIconName();
1901 data
.insert(sharedValue("iconName"), iconName
);
1903 if (m_requestRole
[TypeRole
]) {
1904 data
.insert(sharedValue("type"), item
.mimeComment());
1906 } else if (m_requestRole
[TypeRole
] && isDir
) {
1907 static const QString folderMimeType
= item
.mimeComment();
1908 data
.insert(sharedValue("type"), folderMimeType
);
1914 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1918 if (a
->parent
!= b
->parent
) {
1919 const int expansionLevelA
= expandedParentsCount(a
);
1920 const int expansionLevelB
= expandedParentsCount(b
);
1922 // If b has a higher expansion level than a, check if a is a parent
1923 // of b, and make sure that both expansion levels are equal otherwise.
1924 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1925 if (b
->parent
== a
) {
1931 // If a has a higher expansion level than a, check if b is a parent
1932 // of a, and make sure that both expansion levels are equal otherwise.
1933 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1934 if (a
->parent
== b
) {
1940 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1942 // Compare the last parents of a and b which are different.
1943 while (a
->parent
!= b
->parent
) {
1949 // Show hidden files and folders last
1950 if (m_sortHiddenLast
) {
1951 const bool isHiddenA
= a
->item
.isHidden();
1952 const bool isHiddenB
= b
->item
.isHidden();
1953 if (isHiddenA
&& !isHiddenB
) {
1955 } else if (!isHiddenA
&& isHiddenB
) {
1960 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1961 const bool isDirA
= a
->item
.isDir();
1962 const bool isDirB
= b
->item
.isDir();
1963 if (isDirA
&& !isDirB
) {
1965 } else if (!isDirA
&& isDirB
) {
1970 result
= sortRoleCompare(a
, b
, collator
);
1972 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1975 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1976 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1978 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1980 return lessThan(a
, b
, m_collator
);
1983 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1984 // Sorting by string can be expensive, in particular if natural sorting is
1985 // enabled. Use all CPU cores to speed up the sorting process.
1986 static const int numberOfThreads
= QThread::idealThreadCount();
1987 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1989 // Sorting by other roles is quite fast. Use only one thread to prevent
1990 // problems caused by non-reentrant comparison functions, see
1991 // https://bugs.kde.org/show_bug.cgi?id=312679
1992 mergeSort(begin
, end
, lambdaLessThan
);
1996 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1998 // This function must never return 0, because that would break stable
1999 // sorting, which leads to all kinds of bugs.
2000 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2001 // If two items have equal sort values, let the fallbacks at the bottom of
2002 // the function handle it.
2003 const KFileItem
& itemA
= a
->item
;
2004 const KFileItem
& itemB
= b
->item
;
2008 switch (m_sortRole
) {
2010 // The name role is handled as default fallback after the switch
2014 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
2015 // folders first then
2016 // items A and B are folders thanks to lessThan checks
2017 auto valueA
= a
->values
.value("count");
2018 auto valueB
= b
->values
.value("count");
2019 if (valueA
.isNull()) {
2020 if (!valueB
.isNull()) {
2023 } else if (valueB
.isNull()) {
2026 if (valueA
.toLongLong() < valueB
.toLongLong()) {
2028 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
2035 KIO::filesize_t sizeA
= 0;
2036 if (itemA
.isDir()) {
2037 sizeA
= a
->values
.value("size").toULongLong();
2039 sizeA
= itemA
.size();
2041 KIO::filesize_t sizeB
= 0;
2042 if (itemB
.isDir()) {
2043 sizeB
= b
->values
.value("size").toULongLong();
2045 sizeB
= itemB
.size();
2047 if (sizeA
< sizeB
) {
2049 } else if (sizeA
> sizeB
) {
2055 case ModificationTimeRole
: {
2056 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2057 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
2058 if (dateTimeA
< dateTimeB
) {
2060 } else if (dateTimeA
> dateTimeB
) {
2066 case CreationTimeRole
: {
2067 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2068 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
2069 if (dateTimeA
< dateTimeB
) {
2071 } else if (dateTimeA
> dateTimeB
) {
2077 case DeletionTimeRole
: {
2078 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
2079 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
2080 if (dateTimeA
< dateTimeB
) {
2082 } else if (dateTimeA
> dateTimeB
) {
2094 case ReleaseYearRole
: {
2095 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
2099 case DimensionsRole
: {
2100 const QByteArray role
= roleForType(m_sortRole
);
2101 const QSize dimensionsA
= a
->values
.value(role
).toSize();
2102 const QSize dimensionsB
= b
->values
.value(role
).toSize();
2104 if (dimensionsA
.width() == dimensionsB
.width()) {
2105 result
= dimensionsA
.height() - dimensionsB
.height();
2107 result
= dimensionsA
.width() - dimensionsB
.width();
2113 const QByteArray role
= roleForType(m_sortRole
);
2114 const QString roleValueA
= a
->values
.value(role
).toString();
2115 const QString roleValueB
= b
->values
.value(role
).toString();
2116 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
2118 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
2120 } else if (isRoleValueNatural(m_sortRole
)) {
2121 result
= stringCompare(roleValueA
, roleValueB
, collator
);
2123 result
= QString::compare(roleValueA
, roleValueB
);
2131 // The current sort role was sufficient to define an order
2135 // Fallback #1: Compare the text of the items
2136 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
2141 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2142 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
2147 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2148 // equal. In this case a comparison of the URL is done which is unique in all cases
2149 // within KDirLister.
2150 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
2153 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
2155 QMutexLocker
collatorLock(s_collatorMutex());
2157 if (m_naturalSorting
) {
2158 return collator
.compare(a
, b
);
2161 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
2162 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
2163 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2164 // comparison, still a deterministic sort order is required. A case sensitive
2165 // comparison is done as fallback.
2169 return QString::compare(a
, b
, Qt::CaseSensitive
);
2172 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
2174 Q_ASSERT(!m_itemData
.isEmpty());
2176 const int maxIndex
= count() - 1;
2177 QList
<QPair
<int, QVariant
> > groups
;
2181 for (int i
= 0; i
<= maxIndex
; ++i
) {
2182 if (isChildItem(i
)) {
2186 const QString name
= m_itemData
.at(i
)->item
.text();
2188 // Use the first character of the name as group indication
2189 QChar newFirstChar
= name
.at(0).toUpper();
2190 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
2191 newFirstChar
= name
.at(1).toUpper();
2194 if (firstChar
!= newFirstChar
) {
2195 QString newGroupValue
;
2196 if (newFirstChar
.isLetter()) {
2198 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
2199 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2201 // Try to find a matching group in the range 'A' to 'Z'.
2202 static std::vector
<QChar
> lettersAtoZ
;
2203 lettersAtoZ
.reserve('Z' - 'A' + 1);
2204 if (lettersAtoZ
.empty()) {
2205 for (char c
= 'A'; c
<= 'Z'; ++c
) {
2206 lettersAtoZ
.push_back(QLatin1Char(c
));
2210 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
2211 return m_collator
.compare(c1
, c2
) < 0;
2214 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
2215 if (it
!= lettersAtoZ
.end()) {
2216 if (localeAwareLessThan(newFirstChar
, *it
)) {
2217 // newFirstChar belongs to the group preceding *it.
2218 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2221 newGroupValue
= *it
;
2225 // Symbols from non Latin-based scripts
2226 newGroupValue
= newFirstChar
;
2228 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2229 // Apply group '0 - 9' for any name that starts with a digit
2230 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2232 newGroupValue
= i18nc("@title:group", "Others");
2235 if (newGroupValue
!= groupValue
) {
2236 groupValue
= newGroupValue
;
2237 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2240 firstChar
= newFirstChar
;
2246 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2248 Q_ASSERT(!m_itemData
.isEmpty());
2250 const int maxIndex
= count() - 1;
2251 QList
<QPair
<int, QVariant
> > groups
;
2254 for (int i
= 0; i
<= maxIndex
; ++i
) {
2255 if (isChildItem(i
)) {
2259 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2260 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2261 QString newGroupValue
;
2262 if (!item
.isNull() && item
.isDir()) {
2263 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2264 newGroupValue
= i18nc("@title:group Size", "Folders");
2266 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2270 if (newGroupValue
.isEmpty()) {
2271 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2272 newGroupValue
= i18nc("@title:group Size", "Small");
2273 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2274 newGroupValue
= i18nc("@title:group Size", "Medium");
2276 newGroupValue
= i18nc("@title:group Size", "Big");
2280 if (newGroupValue
!= groupValue
) {
2281 groupValue
= newGroupValue
;
2282 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2289 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2291 Q_ASSERT(!m_itemData
.isEmpty());
2293 const int maxIndex
= count() - 1;
2294 QList
<QPair
<int, QVariant
> > groups
;
2296 const QDate currentDate
= QDate::currentDate();
2298 QDate previousFileDate
;
2300 for (int i
= 0; i
<= maxIndex
; ++i
) {
2301 if (isChildItem(i
)) {
2305 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2306 const QDate fileDate
= fileTime
.date();
2307 if (fileDate
== previousFileDate
) {
2308 // The current item is in the same group as the previous item
2311 previousFileDate
= fileDate
;
2313 const int daysDistance
= fileDate
.daysTo(currentDate
);
2315 QString newGroupValue
;
2316 if (currentDate
.year() == fileDate
.year() &&
2317 currentDate
.month() == fileDate
.month()) {
2319 switch (daysDistance
/ 7) {
2321 switch (daysDistance
) {
2322 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2323 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2325 newGroupValue
= fileTime
.toString(
2326 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2327 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2328 "with context @title:group Date", "%1", newGroupValue
);
2332 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2335 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2338 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2342 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2348 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2349 if (lastMonthDate
.year() == fileDate
.year() &&
2350 lastMonthDate
.month() == fileDate
.month()) {
2352 if (daysDistance
== 1) {
2353 const KLocalizedString format
= ki18nc("@title:group Date: "
2354 "MMMM is full month name in current locale, and yyyy is "
2355 "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)");
2356 const QString translatedFormat
= format
.toString();
2357 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2358 newGroupValue
= fileTime
.toString(translatedFormat
);
2359 newGroupValue
= i18nc("Can be used to script translation of "
2360 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2361 "%1", newGroupValue
);
2363 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2364 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2365 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2367 } else if (daysDistance
<= 7) {
2368 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2369 "The week day name: dddd, MMMM is full month name "
2370 "in current locale, and yyyy is full year number.",
2371 "dddd (MMMM, yyyy)"));
2372 newGroupValue
= i18nc("Can be used to script translation of "
2373 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2374 "%1", newGroupValue
);
2375 } else if (daysDistance
<= 7 * 2) {
2376 const KLocalizedString format
= ki18nc("@title:group Date: "
2377 "MMMM is full month name in current locale, and yyyy is "
2378 "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)");
2379 const QString translatedFormat
= format
.toString();
2380 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2381 newGroupValue
= fileTime
.toString(translatedFormat
);
2382 newGroupValue
= i18nc("Can be used to script translation of "
2383 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2384 "%1", newGroupValue
);
2386 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2387 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2388 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2390 } else if (daysDistance
<= 7 * 3) {
2391 const KLocalizedString format
= ki18nc("@title:group Date: "
2392 "MMMM is full month name in current locale, and yyyy is "
2393 "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)");
2394 const QString translatedFormat
= format
.toString();
2395 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2396 newGroupValue
= fileTime
.toString(translatedFormat
);
2397 newGroupValue
= i18nc("Can be used to script translation of "
2398 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2399 "%1", newGroupValue
);
2401 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2402 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2403 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2405 } else if (daysDistance
<= 7 * 4) {
2406 const KLocalizedString format
= ki18nc("@title:group Date: "
2407 "MMMM is full month name in current locale, and yyyy is "
2408 "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)");
2409 const QString translatedFormat
= format
.toString();
2410 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2411 newGroupValue
= fileTime
.toString(translatedFormat
);
2412 newGroupValue
= i18nc("Can be used to script translation of "
2413 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2414 "%1", newGroupValue
);
2416 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2417 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2418 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2421 const KLocalizedString format
= ki18nc("@title:group Date: "
2422 "MMMM is full month name in current locale, and yyyy is "
2423 "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");
2424 const QString translatedFormat
= format
.toString();
2425 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2426 newGroupValue
= fileTime
.toString(translatedFormat
);
2427 newGroupValue
= i18nc("Can be used to script translation of "
2428 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2429 "%1", newGroupValue
);
2431 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2432 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2433 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2437 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2438 "The month and year: MMMM is full month name in current locale, "
2439 "and yyyy is full year number", "MMMM, yyyy"));
2440 newGroupValue
= i18nc("Can be used to script translation of "
2441 "\"MMMM, yyyy\" with context @title:group Date",
2442 "%1", newGroupValue
);
2446 if (newGroupValue
!= groupValue
) {
2447 groupValue
= newGroupValue
;
2448 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2455 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2457 Q_ASSERT(!m_itemData
.isEmpty());
2459 const int maxIndex
= count() - 1;
2460 QList
<QPair
<int, QVariant
> > groups
;
2462 QString permissionsString
;
2464 for (int i
= 0; i
<= maxIndex
; ++i
) {
2465 if (isChildItem(i
)) {
2469 const ItemData
* itemData
= m_itemData
.at(i
);
2470 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2471 if (newPermissionsString
== permissionsString
) {
2474 permissionsString
= newPermissionsString
;
2476 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2480 if (info
.permission(QFile::ReadUser
)) {
2481 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2483 if (info
.permission(QFile::WriteUser
)) {
2484 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2486 if (info
.permission(QFile::ExeUser
)) {
2487 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2489 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2493 if (info
.permission(QFile::ReadGroup
)) {
2494 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2496 if (info
.permission(QFile::WriteGroup
)) {
2497 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2499 if (info
.permission(QFile::ExeGroup
)) {
2500 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2502 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2504 // Set others string
2506 if (info
.permission(QFile::ReadOther
)) {
2507 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2509 if (info
.permission(QFile::WriteOther
)) {
2510 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2512 if (info
.permission(QFile::ExeOther
)) {
2513 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2515 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2517 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2518 if (newGroupValue
!= groupValue
) {
2519 groupValue
= newGroupValue
;
2520 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2527 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2529 Q_ASSERT(!m_itemData
.isEmpty());
2531 const int maxIndex
= count() - 1;
2532 QList
<QPair
<int, QVariant
> > groups
;
2534 int groupValue
= -1;
2535 for (int i
= 0; i
<= maxIndex
; ++i
) {
2536 if (isChildItem(i
)) {
2539 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2540 if (newGroupValue
!= groupValue
) {
2541 groupValue
= newGroupValue
;
2542 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2549 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2551 Q_ASSERT(!m_itemData
.isEmpty());
2553 const int maxIndex
= count() - 1;
2554 QList
<QPair
<int, QVariant
> > groups
;
2556 bool isFirstGroupValue
= true;
2558 for (int i
= 0; i
<= maxIndex
; ++i
) {
2559 if (isChildItem(i
)) {
2562 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2563 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2564 groupValue
= newGroupValue
;
2565 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2566 isFirstGroupValue
= false;
2573 void KFileItemModel::emitSortProgress(int resolvedCount
)
2575 // Be tolerant against a resolvedCount with a wrong range.
2576 // Although there should not be a case where KFileItemModelRolesUpdater
2577 // (= caller) provides a wrong range, it is important to emit
2578 // a useful progress information even if there is an unexpected
2579 // implementation issue.
2581 const int itemCount
= count();
2582 if (resolvedCount
>= itemCount
) {
2583 m_sortingProgressPercent
= -1;
2584 if (m_resortAllItemsTimer
->isActive()) {
2585 m_resortAllItemsTimer
->stop();
2589 Q_EMIT
directorySortingProgress(100);
2590 } else if (itemCount
> 0) {
2591 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2593 const int progress
= resolvedCount
* 100 / itemCount
;
2594 if (m_sortingProgressPercent
!= progress
) {
2595 m_sortingProgressPercent
= progress
;
2596 Q_EMIT
directorySortingProgress(progress
);
2601 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2603 static const RoleInfoMap rolesInfoMap
[] = {
2604 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2605 { nullptr, NoRole
, KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2606 { "text", NameRole
, kli18nc("@label", "Name"), KLazyLocalizedString(), false, false },
2607 { "size", SizeRole
, kli18nc("@label", "Size"), KLazyLocalizedString(), false, false },
2608 { "modificationtime", ModificationTimeRole
, kli18nc("@label", "Modified"), KLazyLocalizedString(), false, false },
2609 { "creationtime", CreationTimeRole
, kli18nc("@label", "Created"), KLazyLocalizedString(), false, false },
2610 { "accesstime", AccessTimeRole
, kli18nc("@label", "Accessed"), KLazyLocalizedString(), false, false },
2611 { "type", TypeRole
, kli18nc("@label", "Type"), KLazyLocalizedString(), false, false },
2612 { "rating", RatingRole
, kli18nc("@label", "Rating"), KLazyLocalizedString(), true, false },
2613 { "tags", TagsRole
, kli18nc("@label", "Tags"), KLazyLocalizedString(), true, false },
2614 { "comment", CommentRole
, kli18nc("@label", "Comment"), KLazyLocalizedString(), true, false },
2615 { "title", TitleRole
, kli18nc("@label", "Title"), kli18nc("@label", "Document"), true, true },
2616 { "wordCount", WordCountRole
, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), true, true },
2617 { "lineCount", LineCountRole
, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), true, true },
2618 { "imageDateTime", ImageDateTimeRole
, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), true, true },
2619 { "dimensions", DimensionsRole
, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), true, true },
2620 { "width", WidthRole
, kli18nc("@label", "Width"), kli18nc("@label", "Image"), true, true },
2621 { "height", HeightRole
, kli18nc("@label", "Height"), kli18nc("@label", "Image"), true, true },
2622 { "orientation", OrientationRole
, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), true, true },
2623 { "artist", ArtistRole
, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), true, true },
2624 { "genre", GenreRole
, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), true, true },
2625 { "album", AlbumRole
, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), true, true },
2626 { "duration", DurationRole
, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), true, true },
2627 { "bitrate", BitrateRole
, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), true, true },
2628 { "track", TrackRole
, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), true, true },
2629 { "releaseYear", ReleaseYearRole
, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), true, true },
2630 { "aspectRatio", AspectRatioRole
, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), true, true },
2631 { "frameRate", FrameRateRole
, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), true, true },
2632 { "path", PathRole
, kli18nc("@label", "Path"), kli18nc("@label", "Other"), false, false },
2633 { "deletiontime", DeletionTimeRole
, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), false, false },
2634 { "destination", DestinationRole
, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), false, false },
2635 { "originUrl", OriginUrlRole
, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), true, false },
2636 { "permissions", PermissionsRole
, kli18nc("@label", "Permissions"), kli18nc("@label", "Other"), false, false },
2637 { "owner", OwnerRole
, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), false, false },
2638 { "group", GroupRole
, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), false, false },
2641 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2642 return rolesInfoMap
;
2645 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2647 QElapsedTimer timer
;
2649 for (const KFileItem
& item
: items
) {
2650 // Only determine mime types for files here. For directories,
2651 // KFileItem::determineMimeType() reads the .directory file inside to
2652 // load the icon, but this is not necessary at all if we just need the
2653 // type. Some special code for setting the correct mime type for
2654 // directories is in retrieveData().
2655 if (!item
.isDir()) {
2656 item
.determineMimeType();
2659 if (timer
.elapsed() > timeout
) {
2660 // Don't block the user interface, let the remaining items
2661 // be resolved asynchronously.
2667 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2669 static QSet
<QByteArray
> pool
;
2670 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2672 if (it
!= pool
.constEnd()) {
2680 bool KFileItemModel::isConsistent() const
2682 // m_items may contain less items than m_itemData because m_items
2683 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2684 if (m_items
.count() > m_itemData
.count()) {
2688 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2689 // Check if m_items and m_itemData are consistent.
2690 const KFileItem item
= fileItem(i
);
2691 if (item
.isNull()) {
2692 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2696 const int itemIndex
= index(item
);
2697 if (itemIndex
!= i
) {
2698 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2702 // Check if the items are sorted correctly.
2703 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2704 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2705 << fileItem(i
- 1) << fileItem(i
);
2709 // Check if all parent-child relationships are consistent.
2710 const ItemData
* data
= m_itemData
.at(i
);
2711 const ItemData
* parent
= data
->parent
;
2713 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2714 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2718 const int parentIndex
= index(parent
->item
);
2719 if (parentIndex
>= i
) {
2720 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2729 void KFileItemModel::slotListerError(KIO::Job
*job
)
2731 if (job
->error() == KIO::ERR_IS_FILE
) {
2732 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2733 Q_EMIT
urlIsFileError(listJob
->url());
2736 const QString errorString
= job
->errorString();
2737 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));