2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphin_detailsmodesettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodeldirlister.h"
15 #include "private/kfileitemmodelsortalgorithm.h"
17 #include <kio_version.h>
18 #include <KLocalizedString>
19 #include <KUrlMimeData>
21 #include <QElapsedTimer>
23 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
29 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
31 // #define KFILEITEMMODEL_DEBUG
33 KFileItemModel::KFileItemModel(QObject
* parent
) :
34 KItemModelBase("text", parent
),
36 m_sortDirsFirst(true),
38 m_sortingProgressPercent(-1),
45 m_maximumUpdateIntervalTimer(nullptr),
46 m_resortAllItemsTimer(nullptr),
47 m_pendingItemsToInsert(),
52 m_collator
.setNumericMode(true);
54 loadSortingSettings();
56 m_dirLister
= new KFileItemModelDirLister(this);
57 m_dirLister
->setDelayedMimeTypes(true);
59 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
61 m_dirLister
->setMainWindow(parentWidget
->window());
64 connect(m_dirLister
, &KFileItemModelDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
65 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
66 connect(m_dirLister
, &KFileItemModelDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
67 connect(m_dirLister
, &KFileItemModelDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
68 connect(m_dirLister
, &KFileItemModelDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
69 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
70 connect(m_dirLister
, &KFileItemModelDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
71 connect(m_dirLister
, &KFileItemModelDirLister::errorMessage
, this, &KFileItemModel::errorMessage
);
72 connect(m_dirLister
, &KFileItemModelDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
73 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
74 connect(m_dirLister
, &KFileItemModelDirLister::urlIsFileError
, this, &KFileItemModel::urlIsFileError
);
76 #if KIO_VERSION < QT_VERSION_CHECK(5, 79, 0)
77 connect(m_dirLister
, QOverload
<const QUrl
&>::of(&KCoreDirLister::completed
), this, &KFileItemModel::slotCompleted
);
79 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
);
160 return QHash
<QByteArray
, QVariant
>();
163 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
165 if (index
< 0 || index
>= count()) {
169 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
171 // Determine which roles have been changed
172 QSet
<QByteArray
> changedRoles
;
173 QHashIterator
<QByteArray
, QVariant
> it(values
);
174 while (it
.hasNext()) {
176 const QByteArray role
= sharedValue(it
.key());
177 const QVariant value
= it
.value();
179 if (currentValues
[role
] != value
) {
180 currentValues
[role
] = value
;
181 changedRoles
.insert(role
);
185 if (changedRoles
.isEmpty()) {
189 m_itemData
[index
]->values
= currentValues
;
190 if (changedRoles
.contains("text")) {
191 QUrl url
= m_itemData
[index
]->item
.url();
192 url
= url
.adjusted(QUrl::RemoveFilename
);
193 url
.setPath(url
.path() + currentValues
["text"].toString());
194 m_itemData
[index
]->item
.setUrl(url
);
197 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
202 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
204 if (dirsFirst
!= m_sortDirsFirst
) {
205 m_sortDirsFirst
= dirsFirst
;
210 bool KFileItemModel::sortDirectoriesFirst() const
212 return m_sortDirsFirst
;
215 void KFileItemModel::setShowHiddenFiles(bool show
)
217 m_dirLister
->setShowingDotFiles(show
);
218 m_dirLister
->emitChanges();
220 dispatchPendingItemsToInsert();
224 bool KFileItemModel::showHiddenFiles() const
226 return m_dirLister
->showingDotFiles();
229 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
231 m_dirLister
->setDirOnlyMode(enabled
);
234 bool KFileItemModel::showDirectoriesOnly() const
236 return m_dirLister
->dirOnlyMode();
239 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
241 QMimeData
* data
= new QMimeData();
243 // The following code has been taken from KDirModel::mimeData()
244 // (kdelibs/kio/kio/kdirmodel.cpp)
245 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
247 QList
<QUrl
> mostLocalUrls
;
248 const ItemData
* lastAddedItem
= nullptr;
250 for (int index
: indexes
) {
251 const ItemData
* itemData
= m_itemData
.at(index
);
252 const ItemData
* parent
= itemData
->parent
;
254 while (parent
&& parent
!= lastAddedItem
) {
255 parent
= parent
->parent
;
258 if (parent
&& parent
== lastAddedItem
) {
259 // A parent of 'itemData' has been added already.
263 lastAddedItem
= itemData
;
264 const KFileItem
& item
= itemData
->item
;
265 if (!item
.isNull()) {
269 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
273 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
277 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
279 startFromIndex
= qMax(0, startFromIndex
);
280 for (int i
= startFromIndex
; i
< count(); ++i
) {
281 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
285 for (int i
= 0; i
< startFromIndex
; ++i
) {
286 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
293 bool KFileItemModel::supportsDropping(int index
) const
295 const KFileItem item
= fileItem(index
);
296 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
299 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
301 static QHash
<QByteArray
, QString
> description
;
302 if (description
.isEmpty()) {
304 const RoleInfoMap
* map
= rolesInfoMap(count
);
305 for (int i
= 0; i
< count
; ++i
) {
306 if (!map
[i
].roleTranslation
) {
309 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
313 return description
.value(role
);
316 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
318 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
319 #ifdef KFILEITEMMODEL_DEBUG
323 switch (typeForRole(sortRole())) {
324 case NameRole
: m_groups
= nameRoleGroups(); break;
325 case SizeRole
: m_groups
= sizeRoleGroups(); break;
326 case ModificationTimeRole
:
327 m_groups
= timeRoleGroups([](const ItemData
*item
) {
328 return item
->item
.time(KFileItem::ModificationTime
);
331 case CreationTimeRole
:
332 m_groups
= timeRoleGroups([](const ItemData
*item
) {
333 return item
->item
.time(KFileItem::CreationTime
);
337 m_groups
= timeRoleGroups([](const ItemData
*item
) {
338 return item
->item
.time(KFileItem::AccessTime
);
341 case DeletionTimeRole
:
342 m_groups
= timeRoleGroups([](const ItemData
*item
) {
343 return item
->values
.value("deletiontime").toDateTime();
346 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
347 case RatingRole
: m_groups
= ratingRoleGroups(); break;
348 default: m_groups
= genericStringRoleGroups(sortRole()); break;
351 #ifdef KFILEITEMMODEL_DEBUG
352 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
359 KFileItem
KFileItemModel::fileItem(int index
) const
361 if (index
>= 0 && index
< count()) {
362 return m_itemData
.at(index
)->item
;
368 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
370 const int indexForUrl
= index(url
);
371 if (indexForUrl
>= 0) {
372 return m_itemData
.at(indexForUrl
)->item
;
377 int KFileItemModel::index(const KFileItem
& item
) const
379 return index(item
.url());
382 int KFileItemModel::index(const QUrl
& url
) const
384 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
386 const int itemCount
= m_itemData
.count();
387 int itemsInHash
= m_items
.count();
389 int index
= m_items
.value(urlToFind
, -1);
390 while (index
< 0 && itemsInHash
< itemCount
) {
391 // Not all URLs are stored yet in m_items. We grow m_items until either
392 // urlToFind is found, or all URLs have been stored in m_items.
393 // Note that we do not add the URLs to m_items one by one, but in
394 // larger blocks. After each block, we check if urlToFind is in
395 // m_items. We could in principle compare urlToFind with each URL while
396 // we are going through m_itemData, but comparing two QUrls will,
397 // unlike calling qHash for the URLs, trigger a parsing of the URLs
398 // which costs both CPU cycles and memory.
399 const int blockSize
= 1000;
400 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
401 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
402 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
403 m_items
.insert(nextUrl
, i
);
406 itemsInHash
= currentBlockEnd
;
407 index
= m_items
.value(urlToFind
, -1);
411 // The item could not be found, even though all items from m_itemData
412 // should be in m_items now. We print some diagnostic information which
413 // might help to find the cause of the problem, but only once. This
414 // prevents that obtaining and printing the debugging information
415 // wastes CPU cycles and floods the shell or .xsession-errors.
416 static bool printDebugInfo
= true;
418 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
419 printDebugInfo
= false;
421 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
422 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
423 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
425 // Check if there are multiple items with the same URL.
426 QMultiHash
<QUrl
, int> indexesForUrl
;
427 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
428 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
431 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
432 for (const QUrl
& url
: uniqueKeys
) {
433 if (indexesForUrl
.count(url
) > 1) {
434 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
436 auto it
= indexesForUrl
.find(url
);
437 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
438 const ItemData
* data
= m_itemData
.at(it
.value());
439 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
441 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
453 KFileItem
KFileItemModel::rootItem() const
455 return m_dirLister
->rootItem();
458 void KFileItemModel::clear()
463 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
465 if (m_roles
== roles
) {
469 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
473 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
474 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
475 if (supportedExpanding
&& !willSupportExpanding
) {
476 // No expanding is supported anymore. Take care to delete all items that have an expansion level
477 // that is not 0 (and hence are part of an expanded item).
478 removeExpandedItems();
485 QSetIterator
<QByteArray
> it(roles
);
486 while (it
.hasNext()) {
487 const QByteArray
& role
= it
.next();
488 m_requestRole
[typeForRole(role
)] = true;
492 // Update m_data with the changed requested roles
493 const int maxIndex
= count() - 1;
494 for (int i
= 0; i
<= maxIndex
; ++i
) {
495 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
498 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
501 // Clear the 'values' of all filtered items. They will be re-populated with the
502 // correct roles the next time 'values' will be accessed via data(int).
503 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
504 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
505 while (filteredIt
!= filteredEnd
) {
506 (*filteredIt
)->values
.clear();
511 QSet
<QByteArray
> KFileItemModel::roles() const
516 bool KFileItemModel::setExpanded(int index
, bool expanded
)
518 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
522 QHash
<QByteArray
, QVariant
> values
;
523 values
.insert(sharedValue("isExpanded"), expanded
);
524 if (!setData(index
, values
)) {
528 const KFileItem item
= m_itemData
.at(index
)->item
;
529 const QUrl url
= item
.url();
530 const QUrl targetUrl
= item
.targetUrl();
532 m_expandedDirs
.insert(targetUrl
, url
);
533 m_dirLister
->openUrl(url
, KDirLister::Keep
);
535 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
536 for (const QVariant
& var
: previouslyExpandedChildren
) {
537 m_urlsToExpand
.insert(var
.toUrl());
540 // Note that there might be (indirect) children of the folder which is to be collapsed in
541 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
542 // possibly without a parent, which might result in a crash, we insert all pending items
543 // right now. All new items which would be without a parent will then be removed.
544 dispatchPendingItemsToInsert();
546 // Check if the index of the collapsed folder has changed. If that is the case, then items
547 // were inserted before the collapsed folder, and its index needs to be updated.
548 if (m_itemData
.at(index
)->item
!= item
) {
549 index
= this->index(item
);
552 m_expandedDirs
.remove(targetUrl
);
553 m_dirLister
->stop(url
);
555 const int parentLevel
= expandedParentsCount(index
);
556 const int itemCount
= m_itemData
.count();
557 const int firstChildIndex
= index
+ 1;
559 QVariantList expandedChildren
;
561 int childIndex
= firstChildIndex
;
562 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
563 ItemData
* itemData
= m_itemData
.at(childIndex
);
564 if (itemData
->values
.value("isExpanded").toBool()) {
565 const QUrl targetUrl
= itemData
->item
.targetUrl();
566 const QUrl url
= itemData
->item
.url();
567 m_expandedDirs
.remove(targetUrl
);
568 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
569 expandedChildren
.append(targetUrl
);
573 const int childrenCount
= childIndex
- firstChildIndex
;
575 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
576 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
578 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
584 bool KFileItemModel::isExpanded(int index
) const
586 if (index
>= 0 && index
< count()) {
587 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
592 bool KFileItemModel::isExpandable(int index
) const
594 if (index
>= 0 && index
< count()) {
595 // Call data (instead of accessing m_itemData directly)
596 // to ensure that the value is initialized.
597 return data(index
).value("isExpandable").toBool();
602 int KFileItemModel::expandedParentsCount(int index
) const
604 if (index
>= 0 && index
< count()) {
605 return expandedParentsCount(m_itemData
.at(index
));
610 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
613 const auto dirs
= m_expandedDirs
;
614 for (const auto &dir
: dirs
) {
620 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
622 m_urlsToExpand
= urls
;
625 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
628 // Assure that each sub-path of the URL that should be
629 // expanded is added to m_urlsToExpand. KDirLister
630 // does not care whether the parent-URL has already been
632 QUrl urlToExpand
= m_dirLister
->url();
633 const int pos
= urlToExpand
.path().length();
635 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
636 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
637 // so using QString::SkipEmptyParts
638 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
639 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
640 QString path
= urlToExpand
.path();
641 if (!path
.endsWith(QLatin1Char('/'))) {
642 path
.append(QLatin1Char('/'));
644 urlToExpand
.setPath(path
+ subDirs
.at(i
));
645 m_urlsToExpand
.insert(urlToExpand
);
648 // KDirLister::open() must called at least once to trigger an initial
649 // loading. The pending URLs that must be restored are handled
650 // in slotCompleted().
651 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
652 while (it2
.hasNext()) {
653 const int idx
= index(it2
.next());
654 if (idx
>= 0 && !isExpanded(idx
)) {
655 setExpanded(idx
, true);
661 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
663 if (m_filter
.pattern() != nameFilter
) {
664 dispatchPendingItemsToInsert();
665 m_filter
.setPattern(nameFilter
);
670 QString
KFileItemModel::nameFilter() const
672 return m_filter
.pattern();
675 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
677 if (m_filter
.mimeTypes() != filters
) {
678 dispatchPendingItemsToInsert();
679 m_filter
.setMimeTypes(filters
);
684 QStringList
KFileItemModel::mimeTypeFilters() const
686 return m_filter
.mimeTypes();
690 void KFileItemModel::applyFilters()
692 // Check which shown items from m_itemData must get
693 // hidden and hence moved to m_filteredItems.
694 QVector
<int> newFilteredIndexes
;
696 const int itemCount
= m_itemData
.count();
697 for (int index
= 0; index
< itemCount
; ++index
) {
698 ItemData
* itemData
= m_itemData
.at(index
);
700 // Only filter non-expanded items as child items may never
701 // exist without a parent item
702 if (!itemData
->values
.value("isExpanded").toBool()) {
703 const KFileItem item
= itemData
->item
;
704 if (!m_filter
.matches(item
)) {
705 newFilteredIndexes
.append(index
);
706 m_filteredItems
.insert(item
, itemData
);
711 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
712 removeItems(removedRanges
, KeepItemData
);
714 // Check which hidden items from m_filteredItems should
715 // get visible again and hence removed from m_filteredItems.
716 QList
<ItemData
*> newVisibleItems
;
718 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
719 while (it
!= m_filteredItems
.end()) {
720 if (m_filter
.matches(it
.key())) {
721 newVisibleItems
.append(it
.value());
722 it
= m_filteredItems
.erase(it
);
728 insertItems(newVisibleItems
);
731 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
733 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
734 // There are either no filtered items, or it is not possible to expand
735 // folders -> there cannot be any filtered children.
739 QSet
<ItemData
*> parents
;
740 for (const KItemRange
& range
: itemRanges
) {
741 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
742 parents
.insert(m_itemData
.at(index
));
746 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
747 while (it
!= m_filteredItems
.end()) {
748 if (parents
.contains(it
.value()->parent
)) {
750 it
= m_filteredItems
.erase(it
);
757 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
759 static QList
<RoleInfo
> rolesInfo
;
760 if (rolesInfo
.isEmpty()) {
762 const RoleInfoMap
* map
= rolesInfoMap(count
);
763 for (int i
= 0; i
< count
; ++i
) {
764 if (map
[i
].roleType
!= NoRole
) {
766 info
.role
= map
[i
].role
;
767 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
768 if (map
[i
].groupTranslation
) {
769 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
771 // For top level roles, groupTranslation is 0. We must make sure that
772 // info.group is an empty string then because the code that generates
773 // menus tries to put the actions into sub menus otherwise.
774 info
.group
= QString();
776 info
.requiresBaloo
= map
[i
].requiresBaloo
;
777 info
.requiresIndexer
= map
[i
].requiresIndexer
;
778 rolesInfo
.append(info
);
786 void KFileItemModel::onGroupedSortingChanged(bool current
)
792 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
795 m_sortRole
= typeForRole(current
);
797 if (!m_requestRole
[m_sortRole
]) {
798 QSet
<QByteArray
> newRoles
= m_roles
;
808 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
815 void KFileItemModel::loadSortingSettings()
817 using Choice
= GeneralSettings::EnumSortingChoice
;
818 switch (GeneralSettings::sortingChoice()) {
819 case Choice::NaturalSorting
:
820 m_naturalSorting
= true;
821 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
823 case Choice::CaseSensitiveSorting
:
824 m_naturalSorting
= false;
825 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
827 case Choice::CaseInsensitiveSorting
:
828 m_naturalSorting
= false;
829 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
834 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
835 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
836 m_collator
.compare(QString(), QString());
839 void KFileItemModel::resortAllItems()
841 m_resortAllItemsTimer
->stop();
843 const int itemCount
= count();
844 if (itemCount
<= 0) {
848 #ifdef KFILEITEMMODEL_DEBUG
851 qCDebug(DolphinDebug
) << "===========================================================";
852 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
855 // Remember the order of the current URLs so
856 // that it can be determined which indexes have
857 // been moved because of the resorting.
859 oldUrls
.reserve(itemCount
);
860 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
861 oldUrls
.append(itemData
->item
.url());
865 m_items
.reserve(itemCount
);
868 sort(m_itemData
.begin(), m_itemData
.end());
869 for (int i
= 0; i
< itemCount
; ++i
) {
870 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
873 // Determine the first index that has been moved.
874 int firstMovedIndex
= 0;
875 while (firstMovedIndex
< itemCount
876 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
880 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
881 if (itemsHaveMoved
) {
884 int lastMovedIndex
= itemCount
- 1;
885 while (lastMovedIndex
> firstMovedIndex
886 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
890 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
892 // Create a list movedToIndexes, which has the property that
893 // movedToIndexes[i] is the new index of the item with the old index
894 // firstMovedIndex + i.
895 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
896 QList
<int> movedToIndexes
;
897 movedToIndexes
.reserve(movedItemsCount
);
898 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
899 const int newIndex
= m_items
.value(oldUrls
.at(i
));
900 movedToIndexes
.append(newIndex
);
903 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
904 } else if (groupedSorting()) {
905 // The groups might have changed even if the order of the items has not.
906 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
908 if (groups() != oldGroups
) {
909 Q_EMIT
groupsChanged();
913 #ifdef KFILEITEMMODEL_DEBUG
914 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
918 void KFileItemModel::slotCompleted()
920 m_maximumUpdateIntervalTimer
->stop();
921 dispatchPendingItemsToInsert();
923 if (!m_urlsToExpand
.isEmpty()) {
924 // Try to find a URL that can be expanded.
925 // Note that the parent folder must be expanded before any of its subfolders become visible.
926 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
927 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
928 // Iterate over a const copy because items are deleted and inserted within the loop
929 const auto urlsToExpand
= m_urlsToExpand
;
930 for(const QUrl
&url
: urlsToExpand
) {
931 const int indexForUrl
= index(url
);
932 if (indexForUrl
>= 0) {
933 m_urlsToExpand
.remove(url
);
934 if (setExpanded(indexForUrl
, true)) {
935 // The dir lister has been triggered. This slot will be called
936 // again after the directory has been expanded.
942 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
943 // if these URLs have been deleted in the meantime.
944 m_urlsToExpand
.clear();
947 Q_EMIT
directoryLoadingCompleted();
950 void KFileItemModel::slotCanceled()
952 m_maximumUpdateIntervalTimer
->stop();
953 dispatchPendingItemsToInsert();
955 Q_EMIT
directoryLoadingCanceled();
958 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
960 Q_ASSERT(!items
.isEmpty());
963 if (m_expandedDirs
.contains(directoryUrl
)) {
964 parentUrl
= m_expandedDirs
.value(directoryUrl
);
966 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
969 if (m_requestRole
[ExpandedParentsCountRole
]) {
970 // If the expanding of items is enabled, the call
971 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
972 // might result in emitting the same items twice due to the Keep-parameter.
973 // This case happens if an item gets expanded, collapsed and expanded again
974 // before the items could be loaded for the first expansion.
975 if (index(items
.first().url()) >= 0) {
976 // The items are already part of the model.
980 if (directoryUrl
!= directory()) {
981 // To be able to compare whether the new items may be inserted as children
982 // of a parent item the pending items must be added to the model first.
983 dispatchPendingItemsToInsert();
986 // KDirLister keeps the children of items that got expanded once even if
987 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
988 // checked whether the parent for new items is still expanded.
989 const int parentIndex
= index(parentUrl
);
990 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
991 // The parent is not expanded.
996 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
998 if (!m_filter
.hasSetFilters()) {
999 m_pendingItemsToInsert
.append(itemDataList
);
1001 // The name or type filter is active. Hide filtered items
1002 // before inserting them into the model and remember
1003 // the filtered items in m_filteredItems.
1004 for (ItemData
* itemData
: itemDataList
) {
1005 if (m_filter
.matches(itemData
->item
)) {
1006 m_pendingItemsToInsert
.append(itemData
);
1008 m_filteredItems
.insert(itemData
->item
, itemData
);
1013 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1014 // Assure that items get dispatched if no completed() or canceled() signal is
1015 // emitted during the maximum update interval.
1016 m_maximumUpdateIntervalTimer
->start();
1020 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1022 dispatchPendingItemsToInsert();
1024 QVector
<int> indexesToRemove
;
1025 indexesToRemove
.reserve(items
.count());
1027 for (const KFileItem
& item
: items
) {
1028 const int indexForItem
= index(item
);
1029 if (indexForItem
>= 0) {
1030 indexesToRemove
.append(indexForItem
);
1032 // Probably the item has been filtered.
1033 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1034 if (it
!= m_filteredItems
.end()) {
1036 m_filteredItems
.erase(it
);
1041 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1043 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1044 // Assure that removing a parent item also results in removing all children
1045 QVector
<int> indexesToRemoveWithChildren
;
1046 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1048 const int itemCount
= m_itemData
.count();
1049 for (int index
: qAsConst(indexesToRemove
)) {
1050 indexesToRemoveWithChildren
.append(index
);
1052 const int parentLevel
= expandedParentsCount(index
);
1053 int childIndex
= index
+ 1;
1054 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1055 indexesToRemoveWithChildren
.append(childIndex
);
1060 indexesToRemove
= indexesToRemoveWithChildren
;
1063 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1064 removeFilteredChildren(itemRanges
);
1065 removeItems(itemRanges
, DeleteItemData
);
1068 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1070 Q_ASSERT(!items
.isEmpty());
1071 #ifdef KFILEITEMMODEL_DEBUG
1072 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1075 // Get the indexes of all items that have been refreshed
1077 indexes
.reserve(items
.count());
1079 QSet
<QByteArray
> changedRoles
;
1081 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1082 while (it
.hasNext()) {
1083 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1084 const KFileItem
& oldItem
= itemPair
.first
;
1085 const KFileItem
& newItem
= itemPair
.second
;
1086 const int indexForItem
= index(oldItem
);
1087 if (indexForItem
>= 0) {
1088 m_itemData
[indexForItem
]->item
= newItem
;
1090 // Keep old values as long as possible if they could not retrieved synchronously yet.
1091 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1092 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1093 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1094 while (it
.hasNext()) {
1096 const QByteArray
& role
= it
.key();
1097 if (values
.value(role
) != it
.value()) {
1098 values
.insert(role
, it
.value());
1099 changedRoles
.insert(role
);
1103 m_items
.remove(oldItem
.url());
1104 m_items
.insert(newItem
.url(), indexForItem
);
1105 indexes
.append(indexForItem
);
1107 // Check if 'oldItem' is one of the filtered items.
1108 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1109 if (it
!= m_filteredItems
.end()) {
1110 ItemData
* itemData
= it
.value();
1111 itemData
->item
= newItem
;
1113 // The data stored in 'values' might have changed. Therefore, we clear
1114 // 'values' and re-populate it the next time it is requested via data(int).
1115 itemData
->values
.clear();
1117 m_filteredItems
.erase(it
);
1118 m_filteredItems
.insert(newItem
, itemData
);
1123 // If the changed items have been created recently, they might not be in m_items yet.
1124 // In that case, the list 'indexes' might be empty.
1125 if (indexes
.isEmpty()) {
1129 // Extract the item-ranges out of the changed indexes
1130 std::sort(indexes
.begin(), indexes
.end());
1131 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1132 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1135 void KFileItemModel::slotClear()
1137 #ifdef KFILEITEMMODEL_DEBUG
1138 qCDebug(DolphinDebug
) << "Clearing all items";
1141 qDeleteAll(m_filteredItems
);
1142 m_filteredItems
.clear();
1145 m_maximumUpdateIntervalTimer
->stop();
1146 m_resortAllItemsTimer
->stop();
1148 qDeleteAll(m_pendingItemsToInsert
);
1149 m_pendingItemsToInsert
.clear();
1151 const int removedCount
= m_itemData
.count();
1152 if (removedCount
> 0) {
1153 qDeleteAll(m_itemData
);
1156 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1159 m_expandedDirs
.clear();
1162 void KFileItemModel::slotSortingChoiceChanged()
1164 loadSortingSettings();
1168 void KFileItemModel::dispatchPendingItemsToInsert()
1170 if (!m_pendingItemsToInsert
.isEmpty()) {
1171 insertItems(m_pendingItemsToInsert
);
1172 m_pendingItemsToInsert
.clear();
1176 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1178 if (newItems
.isEmpty()) {
1182 #ifdef KFILEITEMMODEL_DEBUG
1183 QElapsedTimer timer
;
1185 qCDebug(DolphinDebug
) << "===========================================================";
1186 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1190 prepareItemsForSorting(newItems
);
1192 // Natural sorting of items can be very slow. However, it becomes much faster
1193 // if the input sequence is already mostly sorted. Therefore, we first sort
1194 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1195 if (m_naturalSorting
) {
1196 if (m_sortRole
== NameRole
) {
1197 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1198 } else if (isRoleValueNatural(m_sortRole
)) {
1199 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1201 const QByteArray role
= roleForType(m_sortRole
);
1202 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1204 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1208 sort(newItems
.begin(), newItems
.end());
1210 #ifdef KFILEITEMMODEL_DEBUG
1211 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1214 KItemRangeList itemRanges
;
1215 const int existingItemCount
= m_itemData
.count();
1216 const int newItemCount
= newItems
.count();
1217 const int totalItemCount
= existingItemCount
+ newItemCount
;
1219 if (existingItemCount
== 0) {
1220 // Optimization for the common special case that there are no
1221 // items in the model yet. Happens, e.g., when entering a folder.
1222 m_itemData
= newItems
;
1223 itemRanges
<< KItemRange(0, newItemCount
);
1225 m_itemData
.reserve(totalItemCount
);
1226 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1227 m_itemData
.append(nullptr);
1230 // We build the new list m_itemData in reverse order to minimize
1231 // the number of moves and guarantee O(N) complexity.
1232 int targetIndex
= totalItemCount
- 1;
1233 int sourceIndexExistingItems
= existingItemCount
- 1;
1234 int sourceIndexNewItems
= newItemCount
- 1;
1238 while (sourceIndexNewItems
>= 0) {
1239 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1240 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1241 // Move an existing item to its new position. If any new items
1242 // are behind it, push the item range to itemRanges.
1243 if (rangeCount
> 0) {
1244 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1248 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1249 --sourceIndexExistingItems
;
1251 // Insert a new item into the list.
1253 m_itemData
[targetIndex
] = newItem
;
1254 --sourceIndexNewItems
;
1259 // Push the final item range to itemRanges.
1260 if (rangeCount
> 0) {
1261 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1264 // Note that itemRanges is still sorted in reverse order.
1265 std::reverse(itemRanges
.begin(), itemRanges
.end());
1268 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1269 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1272 Q_EMIT
itemsInserted(itemRanges
);
1274 #ifdef KFILEITEMMODEL_DEBUG
1275 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1279 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1281 if (itemRanges
.isEmpty()) {
1287 // Step 1: Remove the items from m_itemData, and free the ItemData.
1288 int removedItemsCount
= 0;
1289 for (const KItemRange
& range
: itemRanges
) {
1290 removedItemsCount
+= range
.count
;
1292 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1293 if (behavior
== DeleteItemData
) {
1294 delete m_itemData
.at(index
);
1297 m_itemData
[index
] = nullptr;
1301 // Step 2: Remove the ItemData pointers from the list m_itemData.
1302 int target
= itemRanges
.at(0).index
;
1303 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1306 const int oldItemDataCount
= m_itemData
.count();
1307 while (source
< oldItemDataCount
) {
1308 m_itemData
[target
] = m_itemData
[source
];
1312 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1313 // Skip the items in the next removed range.
1314 source
+= itemRanges
.at(nextRange
).count
;
1319 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1321 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1322 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1325 Q_EMIT
itemsRemoved(itemRanges
);
1328 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1330 if (m_sortRole
== TypeRole
) {
1331 // Try to resolve the MIME-types synchronously to prevent a reordering of
1332 // the items when sorting by type (per default MIME-types are resolved
1333 // asynchronously by KFileItemModelRolesUpdater).
1334 determineMimeTypes(items
, 200);
1337 const int parentIndex
= index(parentUrl
);
1338 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1340 QList
<ItemData
*> itemDataList
;
1341 itemDataList
.reserve(items
.count());
1343 for (const KFileItem
& item
: items
) {
1344 ItemData
* itemData
= new ItemData();
1345 itemData
->item
= item
;
1346 itemData
->parent
= parentItem
;
1347 itemDataList
.append(itemData
);
1350 return itemDataList
;
1353 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1355 switch (m_sortRole
) {
1356 case PermissionsRole
:
1359 case DestinationRole
:
1361 case DeletionTimeRole
:
1362 // These roles can be determined with retrieveData, and they have to be stored
1363 // in the QHash "values" for the sorting.
1364 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1365 if (itemData
->values
.isEmpty()) {
1366 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1372 // At least store the data including the file type for items with known MIME type.
1373 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1374 if (itemData
->values
.isEmpty()) {
1375 const KFileItem item
= itemData
->item
;
1376 if (item
.isDir() || item
.isMimeTypeKnown()) {
1377 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1384 // The other roles are either resolved by KFileItemModelRolesUpdater
1385 // (this includes the SizeRole for directories), or they do not need
1386 // to be stored in the QHash "values" for sorting because the data can
1387 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1393 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1395 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1396 // if the corresponding item is expanded, and it is not a top-level item.
1397 const ItemData
* parent
= data
->parent
;
1399 if (parent
->parent
) {
1400 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1401 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1410 void KFileItemModel::removeExpandedItems()
1412 QVector
<int> indexesToRemove
;
1414 const int maxIndex
= m_itemData
.count() - 1;
1415 for (int i
= 0; i
<= maxIndex
; ++i
) {
1416 const ItemData
* itemData
= m_itemData
.at(i
);
1417 if (itemData
->parent
) {
1418 indexesToRemove
.append(i
);
1422 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1423 m_expandedDirs
.clear();
1425 // Also remove all filtered items which have a parent.
1426 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1427 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1430 if (it
.value()->parent
) {
1432 it
= m_filteredItems
.erase(it
);
1439 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1441 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1443 // Trigger a resorting if necessary. Note that this can happen even if the sort
1444 // role has not changed at all because the file name can be used as a fallback.
1445 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1446 for (const KItemRange
& range
: itemRanges
) {
1447 bool needsResorting
= false;
1449 const int first
= range
.index
;
1450 const int last
= range
.index
+ range
.count
- 1;
1452 // Resorting the model is necessary if
1453 // (a) The first item in the range is "lessThan" its predecessor,
1454 // (b) the successor of the last item is "lessThan" the last item, or
1455 // (c) the internal order of the items in the range is incorrect.
1457 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1458 needsResorting
= true;
1459 } else if (last
< count() - 1
1460 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1461 needsResorting
= true;
1463 for (int index
= first
; index
< last
; ++index
) {
1464 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1465 needsResorting
= true;
1471 if (needsResorting
) {
1472 m_resortAllItemsTimer
->start();
1478 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1479 // The position is still correct, but the groups might have changed
1480 // if the changed item is either the first or the last item in a
1482 // In principle, we could try to find out if the item really is the
1483 // first or last one in its group and then update the groups
1484 // (possibly with a delayed timer to make sure that we don't
1485 // re-calculate the groups very often if items are updated one by
1486 // one), but starting m_resortAllItemsTimer is easier.
1487 m_resortAllItemsTimer
->start();
1491 void KFileItemModel::resetRoles()
1493 for (int i
= 0; i
< RolesCount
; ++i
) {
1494 m_requestRole
[i
] = false;
1498 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1500 static QHash
<QByteArray
, RoleType
> roles
;
1501 if (roles
.isEmpty()) {
1502 // Insert user visible roles that can be accessed with
1503 // KFileItemModel::roleInformation()
1505 const RoleInfoMap
* map
= rolesInfoMap(count
);
1506 for (int i
= 0; i
< count
; ++i
) {
1507 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1510 // Insert internal roles (take care to synchronize the implementation
1511 // with KFileItemModel::roleForType() in case if a change is done).
1512 roles
.insert("isDir", IsDirRole
);
1513 roles
.insert("isLink", IsLinkRole
);
1514 roles
.insert("isHidden", IsHiddenRole
);
1515 roles
.insert("isExpanded", IsExpandedRole
);
1516 roles
.insert("isExpandable", IsExpandableRole
);
1517 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1519 Q_ASSERT(roles
.count() == RolesCount
);
1522 return roles
.value(role
, NoRole
);
1525 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1527 static QHash
<RoleType
, QByteArray
> roles
;
1528 if (roles
.isEmpty()) {
1529 // Insert user visible roles that can be accessed with
1530 // KFileItemModel::roleInformation()
1532 const RoleInfoMap
* map
= rolesInfoMap(count
);
1533 for (int i
= 0; i
< count
; ++i
) {
1534 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1537 // Insert internal roles (take care to synchronize the implementation
1538 // with KFileItemModel::typeForRole() in case if a change is done).
1539 roles
.insert(IsDirRole
, "isDir");
1540 roles
.insert(IsLinkRole
, "isLink");
1541 roles
.insert(IsHiddenRole
, "isHidden");
1542 roles
.insert(IsExpandedRole
, "isExpanded");
1543 roles
.insert(IsExpandableRole
, "isExpandable");
1544 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1546 Q_ASSERT(roles
.count() == RolesCount
);
1549 return roles
.value(roleType
);
1552 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1554 // It is important to insert only roles that are fast to retrieve. E.g.
1555 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1556 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1557 QHash
<QByteArray
, QVariant
> data
;
1558 data
.insert(sharedValue("url"), item
.url());
1560 const bool isDir
= item
.isDir();
1561 if (m_requestRole
[IsDirRole
] && isDir
) {
1562 data
.insert(sharedValue("isDir"), true);
1565 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1566 data
.insert(sharedValue("isLink"), true);
1569 if (m_requestRole
[IsHiddenRole
]) {
1570 data
.insert(sharedValue("isHidden"), item
.isHidden());
1573 if (m_requestRole
[NameRole
]) {
1574 data
.insert(sharedValue("text"), item
.text());
1577 if (m_requestRole
[SizeRole
] && !isDir
) {
1578 data
.insert(sharedValue("size"), item
.size());
1581 if (m_requestRole
[ModificationTimeRole
]) {
1582 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1583 // having several thousands of items. Instead read the raw number from UDSEntry directly
1584 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1585 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1586 data
.insert(sharedValue("modificationtime"), dateTime
);
1589 if (m_requestRole
[CreationTimeRole
]) {
1590 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1591 // having several thousands of items. Instead read the raw number from UDSEntry directly
1592 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1593 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1594 data
.insert(sharedValue("creationtime"), dateTime
);
1597 if (m_requestRole
[AccessTimeRole
]) {
1598 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1599 // having several thousands of items. Instead read the raw number from UDSEntry directly
1600 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1601 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1602 data
.insert(sharedValue("accesstime"), dateTime
);
1605 if (m_requestRole
[PermissionsRole
]) {
1606 data
.insert(sharedValue("permissions"), item
.permissionsString());
1609 if (m_requestRole
[OwnerRole
]) {
1610 data
.insert(sharedValue("owner"), item
.user());
1613 if (m_requestRole
[GroupRole
]) {
1614 data
.insert(sharedValue("group"), item
.group());
1617 if (m_requestRole
[DestinationRole
]) {
1618 QString destination
= item
.linkDest();
1619 if (destination
.isEmpty()) {
1620 destination
= QLatin1Char('-');
1622 data
.insert(sharedValue("destination"), destination
);
1625 if (m_requestRole
[PathRole
]) {
1627 if (item
.url().scheme() == QLatin1String("trash")) {
1628 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1630 // For performance reasons cache the home-path in a static QString
1631 // (see QDir::homePath() for more details)
1632 static QString homePath
;
1633 if (homePath
.isEmpty()) {
1634 homePath
= QDir::homePath();
1637 path
= item
.localPath();
1638 if (path
.startsWith(homePath
)) {
1639 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1643 const int index
= path
.lastIndexOf(item
.text());
1644 path
= path
.mid(0, index
- 1);
1645 data
.insert(sharedValue("path"), path
);
1648 if (m_requestRole
[DeletionTimeRole
]) {
1649 QDateTime deletionTime
;
1650 if (item
.url().scheme() == QLatin1String("trash")) {
1651 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1653 data
.insert(sharedValue("deletiontime"), deletionTime
);
1656 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1657 data
.insert(sharedValue("isExpandable"), true);
1660 if (m_requestRole
[ExpandedParentsCountRole
]) {
1662 const int level
= expandedParentsCount(parent
) + 1;
1663 data
.insert(sharedValue("expandedParentsCount"), level
);
1667 if (item
.isMimeTypeKnown()) {
1668 QString iconName
= item
.iconName();
1669 if (!QIcon::hasThemeIcon(iconName
)) {
1670 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1671 iconName
= mimeType
.genericIconName();
1674 data
.insert(sharedValue("iconName"), iconName
);
1676 if (m_requestRole
[TypeRole
]) {
1677 data
.insert(sharedValue("type"), item
.mimeComment());
1679 } else if (m_requestRole
[TypeRole
] && isDir
) {
1680 static const QString folderMimeType
= item
.mimeComment();
1681 data
.insert(sharedValue("type"), folderMimeType
);
1687 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1691 if (a
->parent
!= b
->parent
) {
1692 const int expansionLevelA
= expandedParentsCount(a
);
1693 const int expansionLevelB
= expandedParentsCount(b
);
1695 // If b has a higher expansion level than a, check if a is a parent
1696 // of b, and make sure that both expansion levels are equal otherwise.
1697 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1698 if (b
->parent
== a
) {
1704 // If a has a higher expansion level than a, check if b is a parent
1705 // of a, and make sure that both expansion levels are equal otherwise.
1706 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1707 if (a
->parent
== b
) {
1713 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1715 // Compare the last parents of a and b which are different.
1716 while (a
->parent
!= b
->parent
) {
1722 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1723 const bool isDirA
= a
->item
.isDir();
1724 const bool isDirB
= b
->item
.isDir();
1725 if (isDirA
&& !isDirB
) {
1727 } else if (!isDirA
&& isDirB
) {
1732 result
= sortRoleCompare(a
, b
, collator
);
1734 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1737 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1738 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1740 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1742 return lessThan(a
, b
, m_collator
);
1745 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1746 // Sorting by string can be expensive, in particular if natural sorting is
1747 // enabled. Use all CPU cores to speed up the sorting process.
1748 static const int numberOfThreads
= QThread::idealThreadCount();
1749 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1751 // Sorting by other roles is quite fast. Use only one thread to prevent
1752 // problems caused by non-reentrant comparison functions, see
1753 // https://bugs.kde.org/show_bug.cgi?id=312679
1754 mergeSort(begin
, end
, lambdaLessThan
);
1758 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1760 const KFileItem
& itemA
= a
->item
;
1761 const KFileItem
& itemB
= b
->item
;
1765 switch (m_sortRole
) {
1767 // The name role is handled as default fallback after the switch
1771 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1772 // folders first then
1773 // items A and B are folders thanks to lessThan checks
1774 auto valueA
= a
->values
.value("count");
1775 auto valueB
= b
->values
.value("count");
1776 if (valueA
.isNull()) {
1777 if (valueB
.isNull()) {
1782 } else if (valueB
.isNull()) {
1785 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1792 KIO::filesize_t sizeA
= 0;
1793 if (itemA
.isDir()) {
1794 sizeA
= a
->values
.value("size").toULongLong();
1796 sizeA
= itemA
.size();
1798 KIO::filesize_t sizeB
= 0;
1799 if (itemB
.isDir()) {
1800 sizeB
= b
->values
.value("size").toULongLong();
1802 sizeB
= itemB
.size();
1804 if (sizeA
> sizeB
) {
1806 } else if (sizeA
< sizeB
) {
1814 case ModificationTimeRole
: {
1815 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1816 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1817 if (dateTimeA
< dateTimeB
) {
1819 } else if (dateTimeA
> dateTimeB
) {
1825 case CreationTimeRole
: {
1826 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1827 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1828 if (dateTimeA
< dateTimeB
) {
1830 } else if (dateTimeA
> dateTimeB
) {
1836 case DeletionTimeRole
: {
1837 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1838 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1839 if (dateTimeA
< dateTimeB
) {
1841 } else if (dateTimeA
> dateTimeB
) {
1853 case ReleaseYearRole
: {
1854 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1859 const QByteArray role
= roleForType(m_sortRole
);
1860 const QString roleValueA
= a
->values
.value(role
).toString();
1861 const QString roleValueB
= b
->values
.value(role
).toString();
1862 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1864 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1866 } else if (isRoleValueNatural(m_sortRole
)) {
1867 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1869 result
= QString::compare(roleValueA
, roleValueB
);
1877 // The current sort role was sufficient to define an order
1881 // Fallback #1: Compare the text of the items
1882 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1887 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1888 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1893 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1894 // equal. In this case a comparison of the URL is done which is unique in all cases
1895 // within KDirLister.
1896 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1899 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1901 QMutexLocker
collatorLock(s_collatorMutex());
1903 if (m_naturalSorting
) {
1904 return collator
.compare(a
, b
);
1907 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1908 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1909 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1910 // comparison, still a deterministic sort order is required. A case sensitive
1911 // comparison is done as fallback.
1915 return QString::compare(a
, b
, Qt::CaseSensitive
);
1918 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1920 Q_ASSERT(!m_itemData
.isEmpty());
1922 const int maxIndex
= count() - 1;
1923 QList
<QPair
<int, QVariant
> > groups
;
1927 for (int i
= 0; i
<= maxIndex
; ++i
) {
1928 if (isChildItem(i
)) {
1932 const QString name
= m_itemData
.at(i
)->item
.text();
1934 // Use the first character of the name as group indication
1935 QChar newFirstChar
= name
.at(0).toUpper();
1936 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1937 newFirstChar
= name
.at(1).toUpper();
1940 if (firstChar
!= newFirstChar
) {
1941 QString newGroupValue
;
1942 if (newFirstChar
.isLetter()) {
1944 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1945 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1947 // Try to find a matching group in the range 'A' to 'Z'.
1948 static std::vector
<QChar
> lettersAtoZ
;
1949 lettersAtoZ
.reserve('Z' - 'A' + 1);
1950 if (lettersAtoZ
.empty()) {
1951 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1952 lettersAtoZ
.push_back(QLatin1Char(c
));
1956 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1957 return m_collator
.compare(c1
, c2
) < 0;
1960 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1961 if (it
!= lettersAtoZ
.end()) {
1962 if (localeAwareLessThan(newFirstChar
, *it
)) {
1963 // newFirstChar belongs to the group preceding *it.
1964 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1967 newGroupValue
= *it
;
1971 // Symbols from non Latin-based scripts
1972 newGroupValue
= newFirstChar
;
1974 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
1975 // Apply group '0 - 9' for any name that starts with a digit
1976 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
1978 newGroupValue
= i18nc("@title:group", "Others");
1981 if (newGroupValue
!= groupValue
) {
1982 groupValue
= newGroupValue
;
1983 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
1986 firstChar
= newFirstChar
;
1992 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
1994 Q_ASSERT(!m_itemData
.isEmpty());
1996 const int maxIndex
= count() - 1;
1997 QList
<QPair
<int, QVariant
> > groups
;
2000 for (int i
= 0; i
<= maxIndex
; ++i
) {
2001 if (isChildItem(i
)) {
2005 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2006 const KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2007 QString newGroupValue
;
2008 if (!item
.isNull() && item
.isDir()) {
2009 newGroupValue
= i18nc("@title:group Size", "Folders");
2010 } else if (fileSize
< 5 * 1024 * 1024) {
2011 newGroupValue
= i18nc("@title:group Size", "Small");
2012 } else if (fileSize
< 10 * 1024 * 1024) {
2013 newGroupValue
= i18nc("@title:group Size", "Medium");
2015 newGroupValue
= i18nc("@title:group Size", "Big");
2018 if (newGroupValue
!= groupValue
) {
2019 groupValue
= newGroupValue
;
2020 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2027 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2029 Q_ASSERT(!m_itemData
.isEmpty());
2031 const int maxIndex
= count() - 1;
2032 QList
<QPair
<int, QVariant
> > groups
;
2034 const QDate currentDate
= QDate::currentDate();
2036 QDate previousFileDate
;
2038 for (int i
= 0; i
<= maxIndex
; ++i
) {
2039 if (isChildItem(i
)) {
2043 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2044 const QDate fileDate
= fileTime
.date();
2045 if (fileDate
== previousFileDate
) {
2046 // The current item is in the same group as the previous item
2049 previousFileDate
= fileDate
;
2051 const int daysDistance
= fileDate
.daysTo(currentDate
);
2053 QString newGroupValue
;
2054 if (currentDate
.year() == fileDate
.year() &&
2055 currentDate
.month() == fileDate
.month()) {
2057 switch (daysDistance
/ 7) {
2059 switch (daysDistance
) {
2060 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2061 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2063 newGroupValue
= fileTime
.toString(
2064 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2065 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2066 "with context @title:group Date", "%1", newGroupValue
);
2070 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2073 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2076 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2080 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2086 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2087 if (lastMonthDate
.year() == fileDate
.year() &&
2088 lastMonthDate
.month() == fileDate
.month()) {
2090 if (daysDistance
== 1) {
2091 const KLocalizedString format
= ki18nc("@title:group Date: "
2092 "MMMM is full month name in current locale, and yyyy is "
2093 "full year number", "'Yesterday' (MMMM, yyyy)");
2094 const QString translatedFormat
= format
.toString();
2095 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2096 newGroupValue
= fileTime
.toString(translatedFormat
);
2097 newGroupValue
= i18nc("Can be used to script translation of "
2098 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2099 "%1", newGroupValue
);
2101 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2102 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2103 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2105 } else if (daysDistance
<= 7) {
2106 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2107 "The week day name: dddd, MMMM is full month name "
2108 "in current locale, and yyyy is full year number",
2109 "dddd (MMMM, yyyy)"));
2110 newGroupValue
= i18nc("Can be used to script translation of "
2111 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2112 "%1", newGroupValue
);
2113 } else if (daysDistance
<= 7 * 2) {
2114 const KLocalizedString format
= ki18nc("@title:group Date: "
2115 "MMMM is full month name in current locale, and yyyy is "
2116 "full year number", "'One Week Ago' (MMMM, yyyy)");
2117 const QString translatedFormat
= format
.toString();
2118 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2119 newGroupValue
= fileTime
.toString(translatedFormat
);
2120 newGroupValue
= i18nc("Can be used to script translation of "
2121 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2122 "%1", newGroupValue
);
2124 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2125 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2126 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2128 } else if (daysDistance
<= 7 * 3) {
2129 const KLocalizedString format
= ki18nc("@title:group Date: "
2130 "MMMM is full month name in current locale, and yyyy is "
2131 "full year number", "'Two Weeks Ago' (MMMM, yyyy)");
2132 const QString translatedFormat
= format
.toString();
2133 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2134 newGroupValue
= fileTime
.toString(translatedFormat
);
2135 newGroupValue
= i18nc("Can be used to script translation of "
2136 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2137 "%1", newGroupValue
);
2139 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2140 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2141 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2143 } else if (daysDistance
<= 7 * 4) {
2144 const KLocalizedString format
= ki18nc("@title:group Date: "
2145 "MMMM is full month name in current locale, and yyyy is "
2146 "full year number", "'Three Weeks Ago' (MMMM, yyyy)");
2147 const QString translatedFormat
= format
.toString();
2148 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2149 newGroupValue
= fileTime
.toString(translatedFormat
);
2150 newGroupValue
= i18nc("Can be used to script translation of "
2151 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2152 "%1", newGroupValue
);
2154 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2155 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2156 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2159 const KLocalizedString format
= ki18nc("@title:group Date: "
2160 "MMMM is full month name in current locale, and yyyy is "
2161 "full year number", "'Earlier on' MMMM, yyyy");
2162 const QString translatedFormat
= format
.toString();
2163 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2164 newGroupValue
= fileTime
.toString(translatedFormat
);
2165 newGroupValue
= i18nc("Can be used to script translation of "
2166 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2167 "%1", newGroupValue
);
2169 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2170 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2171 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2175 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2176 "The month and year: MMMM is full month name in current locale, "
2177 "and yyyy is full year number", "MMMM, yyyy"));
2178 newGroupValue
= i18nc("Can be used to script translation of "
2179 "\"MMMM, yyyy\" with context @title:group Date",
2180 "%1", newGroupValue
);
2184 if (newGroupValue
!= groupValue
) {
2185 groupValue
= newGroupValue
;
2186 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2193 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2195 Q_ASSERT(!m_itemData
.isEmpty());
2197 const int maxIndex
= count() - 1;
2198 QList
<QPair
<int, QVariant
> > groups
;
2200 QString permissionsString
;
2202 for (int i
= 0; i
<= maxIndex
; ++i
) {
2203 if (isChildItem(i
)) {
2207 const ItemData
* itemData
= m_itemData
.at(i
);
2208 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2209 if (newPermissionsString
== permissionsString
) {
2212 permissionsString
= newPermissionsString
;
2214 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2218 if (info
.permission(QFile::ReadUser
)) {
2219 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2221 if (info
.permission(QFile::WriteUser
)) {
2222 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2224 if (info
.permission(QFile::ExeUser
)) {
2225 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2227 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2231 if (info
.permission(QFile::ReadGroup
)) {
2232 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2234 if (info
.permission(QFile::WriteGroup
)) {
2235 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2237 if (info
.permission(QFile::ExeGroup
)) {
2238 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2240 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2242 // Set others string
2244 if (info
.permission(QFile::ReadOther
)) {
2245 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2247 if (info
.permission(QFile::WriteOther
)) {
2248 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2250 if (info
.permission(QFile::ExeOther
)) {
2251 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2253 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2255 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2256 if (newGroupValue
!= groupValue
) {
2257 groupValue
= newGroupValue
;
2258 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2265 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2267 Q_ASSERT(!m_itemData
.isEmpty());
2269 const int maxIndex
= count() - 1;
2270 QList
<QPair
<int, QVariant
> > groups
;
2272 int groupValue
= -1;
2273 for (int i
= 0; i
<= maxIndex
; ++i
) {
2274 if (isChildItem(i
)) {
2277 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2278 if (newGroupValue
!= groupValue
) {
2279 groupValue
= newGroupValue
;
2280 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2287 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2289 Q_ASSERT(!m_itemData
.isEmpty());
2291 const int maxIndex
= count() - 1;
2292 QList
<QPair
<int, QVariant
> > groups
;
2294 bool isFirstGroupValue
= true;
2296 for (int i
= 0; i
<= maxIndex
; ++i
) {
2297 if (isChildItem(i
)) {
2300 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2301 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2302 groupValue
= newGroupValue
;
2303 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2304 isFirstGroupValue
= false;
2311 void KFileItemModel::emitSortProgress(int resolvedCount
)
2313 // Be tolerant against a resolvedCount with a wrong range.
2314 // Although there should not be a case where KFileItemModelRolesUpdater
2315 // (= caller) provides a wrong range, it is important to emit
2316 // a useful progress information even if there is an unexpected
2317 // implementation issue.
2319 const int itemCount
= count();
2320 if (resolvedCount
>= itemCount
) {
2321 m_sortingProgressPercent
= -1;
2322 if (m_resortAllItemsTimer
->isActive()) {
2323 m_resortAllItemsTimer
->stop();
2327 Q_EMIT
directorySortingProgress(100);
2328 } else if (itemCount
> 0) {
2329 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2331 const int progress
= resolvedCount
* 100 / itemCount
;
2332 if (m_sortingProgressPercent
!= progress
) {
2333 m_sortingProgressPercent
= progress
;
2334 Q_EMIT
directorySortingProgress(progress
);
2339 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2341 static const RoleInfoMap rolesInfoMap
[] = {
2342 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2343 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2344 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2345 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2346 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2347 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2348 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2349 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2350 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2351 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2352 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2353 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2354 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2355 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2356 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2357 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2358 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2359 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2360 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2361 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2362 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2363 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2364 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2365 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2366 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2367 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2368 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2369 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2370 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2371 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2372 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2373 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2374 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2375 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2378 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2379 return rolesInfoMap
;
2382 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2384 QElapsedTimer timer
;
2386 for (const KFileItem
& item
: items
) {
2387 // Only determine mime types for files here. For directories,
2388 // KFileItem::determineMimeType() reads the .directory file inside to
2389 // load the icon, but this is not necessary at all if we just need the
2390 // type. Some special code for setting the correct mime type for
2391 // directories is in retrieveData().
2392 if (!item
.isDir()) {
2393 item
.determineMimeType();
2396 if (timer
.elapsed() > timeout
) {
2397 // Don't block the user interface, let the remaining items
2398 // be resolved asynchronously.
2404 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2406 static QSet
<QByteArray
> pool
;
2407 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2409 if (it
!= pool
.constEnd()) {
2417 bool KFileItemModel::isConsistent() const
2419 // m_items may contain less items than m_itemData because m_items
2420 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2421 if (m_items
.count() > m_itemData
.count()) {
2425 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2426 // Check if m_items and m_itemData are consistent.
2427 const KFileItem item
= fileItem(i
);
2428 if (item
.isNull()) {
2429 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2433 const int itemIndex
= index(item
);
2434 if (itemIndex
!= i
) {
2435 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2439 // Check if the items are sorted correctly.
2440 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2441 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2442 << fileItem(i
- 1) << fileItem(i
);
2446 // Check if all parent-child relationships are consistent.
2447 const ItemData
* data
= m_itemData
.at(i
);
2448 const ItemData
* parent
= data
->parent
;
2450 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2451 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2455 const int parentIndex
= index(parent
->item
);
2456 if (parentIndex
>= i
) {
2457 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;