2 * SPDX-FileCopyrightText: 2011 Peter Penz <peter.penz19@gmail.com>
3 * SPDX-FileCopyrightText: 2013 Frank Reininghaus <frank78ac@googlemail.com>
4 * SPDX-FileCopyrightText: 2013 Emmanuel Pescosta <emmanuelpescosta099@gmail.com>
6 * SPDX-License-Identifier: GPL-2.0-or-later
9 #include "kfileitemmodel.h"
11 #include "dolphin_generalsettings.h"
12 #include "dolphin_detailsmodesettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
18 #include <KLocalizedString>
19 #include <KUrlMimeData>
21 #include <QElapsedTimer>
23 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
29 Q_GLOBAL_STATIC(QRecursiveMutex
, s_collatorMutex
)
31 // #define KFILEITEMMODEL_DEBUG
33 KFileItemModel::KFileItemModel(QObject
* parent
) :
34 KItemModelBase("text", parent
),
36 m_sortDirsFirst(true),
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 KDirLister(this);
57 m_dirLister
->setAutoErrorHandlingEnabled(false);
58 m_dirLister
->setDelayedMimeTypes(true);
60 const QWidget
* parentWidget
= qobject_cast
<QWidget
*>(parent
);
62 m_dirLister
->setMainWindow(parentWidget
->window());
65 connect(m_dirLister
, &KCoreDirLister::started
, this, &KFileItemModel::directoryLoadingStarted
);
66 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::canceled
), this, &KFileItemModel::slotCanceled
);
67 connect(m_dirLister
, &KCoreDirLister::itemsAdded
, this, &KFileItemModel::slotItemsAdded
);
68 connect(m_dirLister
, &KCoreDirLister::itemsDeleted
, this, &KFileItemModel::slotItemsDeleted
);
69 connect(m_dirLister
, &KCoreDirLister::refreshItems
, this, &KFileItemModel::slotRefreshItems
);
70 connect(m_dirLister
, QOverload
<>::of(&KCoreDirLister::clear
), this, &KFileItemModel::slotClear
);
71 connect(m_dirLister
, &KCoreDirLister::infoMessage
, this, &KFileItemModel::infoMessage
);
72 connect(m_dirLister
, &KCoreDirLister::jobError
, this, &KFileItemModel::slotListerError
);
73 connect(m_dirLister
, &KCoreDirLister::percent
, this, &KFileItemModel::directoryLoadingProgress
);
74 connect(m_dirLister
, QOverload
<const QUrl
&, const QUrl
&>::of(&KCoreDirLister::redirection
), this, &KFileItemModel::directoryRedirection
);
75 connect(m_dirLister
, &KCoreDirLister::listingDirCompleted
, this, &KFileItemModel::slotCompleted
);
77 // Apply default roles that should be determined
79 m_requestRole
[NameRole
] = true;
80 m_requestRole
[IsDirRole
] = true;
81 m_requestRole
[IsLinkRole
] = true;
82 m_roles
.insert("text");
83 m_roles
.insert("isDir");
84 m_roles
.insert("isLink");
85 m_roles
.insert("isHidden");
87 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
88 // before the completed() or canceled() signal has been emitted.
89 m_maximumUpdateIntervalTimer
= new QTimer(this);
90 m_maximumUpdateIntervalTimer
->setInterval(2000);
91 m_maximumUpdateIntervalTimer
->setSingleShot(true);
92 connect(m_maximumUpdateIntervalTimer
, &QTimer::timeout
, this, &KFileItemModel::dispatchPendingItemsToInsert
);
94 // When changing the value of an item which represents the sort-role a resorting must be
95 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
96 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
97 // resorting is postponed until the timer has been exceeded.
98 m_resortAllItemsTimer
= new QTimer(this);
99 m_resortAllItemsTimer
->setInterval(500);
100 m_resortAllItemsTimer
->setSingleShot(true);
101 connect(m_resortAllItemsTimer
, &QTimer::timeout
, this, &KFileItemModel::resortAllItems
);
103 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged
, this, &KFileItemModel::slotSortingChoiceChanged
);
106 KFileItemModel::~KFileItemModel()
108 qDeleteAll(m_itemData
);
109 qDeleteAll(m_filteredItems
);
110 qDeleteAll(m_pendingItemsToInsert
);
113 void KFileItemModel::loadDirectory(const QUrl
&url
)
115 m_dirLister
->openUrl(url
);
118 void KFileItemModel::refreshDirectory(const QUrl
&url
)
120 // Refresh all expanded directories first (Bug 295300)
121 QHashIterator
<QUrl
, QUrl
> expandedDirs(m_expandedDirs
);
122 while (expandedDirs
.hasNext()) {
124 m_dirLister
->openUrl(expandedDirs
.value(), KDirLister::Reload
);
127 m_dirLister
->openUrl(url
, KDirLister::Reload
);
130 QUrl
KFileItemModel::directory() const
132 return m_dirLister
->url();
135 void KFileItemModel::cancelDirectoryLoading()
140 int KFileItemModel::count() const
142 return m_itemData
.count();
145 QHash
<QByteArray
, QVariant
> KFileItemModel::data(int index
) const
147 if (index
>= 0 && index
< count()) {
148 ItemData
* data
= m_itemData
.at(index
);
149 if (data
->values
.isEmpty()) {
150 data
->values
= retrieveData(data
->item
, data
->parent
);
155 return QHash
<QByteArray
, QVariant
>();
158 bool KFileItemModel::setData(int index
, const QHash
<QByteArray
, QVariant
>& values
)
160 if (index
< 0 || index
>= count()) {
164 QHash
<QByteArray
, QVariant
> currentValues
= data(index
);
166 // Determine which roles have been changed
167 QSet
<QByteArray
> changedRoles
;
168 QHashIterator
<QByteArray
, QVariant
> it(values
);
169 while (it
.hasNext()) {
171 const QByteArray role
= sharedValue(it
.key());
172 const QVariant value
= it
.value();
174 if (currentValues
[role
] != value
) {
175 currentValues
[role
] = value
;
176 changedRoles
.insert(role
);
180 if (changedRoles
.isEmpty()) {
184 m_itemData
[index
]->values
= currentValues
;
185 if (changedRoles
.contains("text")) {
186 QUrl url
= m_itemData
[index
]->item
.url();
187 url
= url
.adjusted(QUrl::RemoveFilename
);
188 url
.setPath(url
.path() + currentValues
["text"].toString());
189 m_itemData
[index
]->item
.setUrl(url
);
192 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index
, 1), changedRoles
);
197 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst
)
199 if (dirsFirst
!= m_sortDirsFirst
) {
200 m_sortDirsFirst
= dirsFirst
;
205 bool KFileItemModel::sortDirectoriesFirst() const
207 return m_sortDirsFirst
;
210 void KFileItemModel::setShowHiddenFiles(bool show
)
212 m_dirLister
->setShowingDotFiles(show
);
213 m_dirLister
->emitChanges();
215 dispatchPendingItemsToInsert();
219 bool KFileItemModel::showHiddenFiles() const
221 return m_dirLister
->showingDotFiles();
224 void KFileItemModel::setShowDirectoriesOnly(bool enabled
)
226 m_dirLister
->setDirOnlyMode(enabled
);
229 bool KFileItemModel::showDirectoriesOnly() const
231 return m_dirLister
->dirOnlyMode();
234 QMimeData
* KFileItemModel::createMimeData(const KItemSet
& indexes
) const
236 QMimeData
* data
= new QMimeData();
238 // The following code has been taken from KDirModel::mimeData()
239 // (kdelibs/kio/kio/kdirmodel.cpp)
240 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
242 QList
<QUrl
> mostLocalUrls
;
243 const ItemData
* lastAddedItem
= nullptr;
245 for (int index
: indexes
) {
246 const ItemData
* itemData
= m_itemData
.at(index
);
247 const ItemData
* parent
= itemData
->parent
;
249 while (parent
&& parent
!= lastAddedItem
) {
250 parent
= parent
->parent
;
253 if (parent
&& parent
== lastAddedItem
) {
254 // A parent of 'itemData' has been added already.
258 lastAddedItem
= itemData
;
259 const KFileItem
& item
= itemData
->item
;
260 if (!item
.isNull()) {
264 mostLocalUrls
<< item
.mostLocalUrl(&isLocal
);
268 KUrlMimeData::setUrls(urls
, mostLocalUrls
, data
);
272 int KFileItemModel::indexForKeyboardSearch(const QString
& text
, int startFromIndex
) const
274 startFromIndex
= qMax(0, startFromIndex
);
275 for (int i
= startFromIndex
; i
< count(); ++i
) {
276 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
280 for (int i
= 0; i
< startFromIndex
; ++i
) {
281 if (fileItem(i
).text().startsWith(text
, Qt::CaseInsensitive
)) {
288 bool KFileItemModel::supportsDropping(int index
) const
290 const KFileItem item
= fileItem(index
);
291 return !item
.isNull() && (item
.isDir() || item
.isDesktopFile());
294 QString
KFileItemModel::roleDescription(const QByteArray
& role
) const
296 static QHash
<QByteArray
, QString
> description
;
297 if (description
.isEmpty()) {
299 const RoleInfoMap
* map
= rolesInfoMap(count
);
300 for (int i
= 0; i
< count
; ++i
) {
301 if (!map
[i
].roleTranslation
) {
304 description
.insert(map
[i
].role
, i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
));
308 return description
.value(role
);
311 QList
<QPair
<int, QVariant
> > KFileItemModel::groups() const
313 if (!m_itemData
.isEmpty() && m_groups
.isEmpty()) {
314 #ifdef KFILEITEMMODEL_DEBUG
318 switch (typeForRole(sortRole())) {
319 case NameRole
: m_groups
= nameRoleGroups(); break;
320 case SizeRole
: m_groups
= sizeRoleGroups(); break;
321 case ModificationTimeRole
:
322 m_groups
= timeRoleGroups([](const ItemData
*item
) {
323 return item
->item
.time(KFileItem::ModificationTime
);
326 case CreationTimeRole
:
327 m_groups
= timeRoleGroups([](const ItemData
*item
) {
328 return item
->item
.time(KFileItem::CreationTime
);
332 m_groups
= timeRoleGroups([](const ItemData
*item
) {
333 return item
->item
.time(KFileItem::AccessTime
);
336 case DeletionTimeRole
:
337 m_groups
= timeRoleGroups([](const ItemData
*item
) {
338 return item
->values
.value("deletiontime").toDateTime();
341 case PermissionsRole
: m_groups
= permissionRoleGroups(); break;
342 case RatingRole
: m_groups
= ratingRoleGroups(); break;
343 default: m_groups
= genericStringRoleGroups(sortRole()); break;
346 #ifdef KFILEITEMMODEL_DEBUG
347 qCDebug(DolphinDebug
) << "[TIME] Calculating groups for" << count() << "items:" << timer
.elapsed();
354 KFileItem
KFileItemModel::fileItem(int index
) const
356 if (index
>= 0 && index
< count()) {
357 return m_itemData
.at(index
)->item
;
363 KFileItem
KFileItemModel::fileItem(const QUrl
&url
) const
365 const int indexForUrl
= index(url
);
366 if (indexForUrl
>= 0) {
367 return m_itemData
.at(indexForUrl
)->item
;
372 int KFileItemModel::index(const KFileItem
& item
) const
374 return index(item
.url());
377 int KFileItemModel::index(const QUrl
& url
) const
379 const QUrl urlToFind
= url
.adjusted(QUrl::StripTrailingSlash
);
381 const int itemCount
= m_itemData
.count();
382 int itemsInHash
= m_items
.count();
384 int index
= m_items
.value(urlToFind
, -1);
385 while (index
< 0 && itemsInHash
< itemCount
) {
386 // Not all URLs are stored yet in m_items. We grow m_items until either
387 // urlToFind is found, or all URLs have been stored in m_items.
388 // Note that we do not add the URLs to m_items one by one, but in
389 // larger blocks. After each block, we check if urlToFind is in
390 // m_items. We could in principle compare urlToFind with each URL while
391 // we are going through m_itemData, but comparing two QUrls will,
392 // unlike calling qHash for the URLs, trigger a parsing of the URLs
393 // which costs both CPU cycles and memory.
394 const int blockSize
= 1000;
395 const int currentBlockEnd
= qMin(itemsInHash
+ blockSize
, itemCount
);
396 for (int i
= itemsInHash
; i
< currentBlockEnd
; ++i
) {
397 const QUrl nextUrl
= m_itemData
.at(i
)->item
.url();
398 m_items
.insert(nextUrl
, i
);
401 itemsInHash
= currentBlockEnd
;
402 index
= m_items
.value(urlToFind
, -1);
406 // The item could not be found, even though all items from m_itemData
407 // should be in m_items now. We print some diagnostic information which
408 // might help to find the cause of the problem, but only once. This
409 // prevents that obtaining and printing the debugging information
410 // wastes CPU cycles and floods the shell or .xsession-errors.
411 static bool printDebugInfo
= true;
413 if (m_items
.count() != m_itemData
.count() && printDebugInfo
) {
414 printDebugInfo
= false;
416 qCWarning(DolphinDebug
) << "The model is in an inconsistent state.";
417 qCWarning(DolphinDebug
) << "m_items.count() ==" << m_items
.count();
418 qCWarning(DolphinDebug
) << "m_itemData.count() ==" << m_itemData
.count();
420 // Check if there are multiple items with the same URL.
421 QMultiHash
<QUrl
, int> indexesForUrl
;
422 for (int i
= 0; i
< m_itemData
.count(); ++i
) {
423 indexesForUrl
.insert(m_itemData
.at(i
)->item
.url(), i
);
426 const auto uniqueKeys
= indexesForUrl
.uniqueKeys();
427 for (const QUrl
& url
: uniqueKeys
) {
428 if (indexesForUrl
.count(url
) > 1) {
429 qCWarning(DolphinDebug
) << "Multiple items found with the URL" << url
;
431 auto it
= indexesForUrl
.find(url
);
432 while (it
!= indexesForUrl
.end() && it
.key() == url
) {
433 const ItemData
* data
= m_itemData
.at(it
.value());
434 qCWarning(DolphinDebug
) << "index" << it
.value() << ":" << data
->item
;
436 qCWarning(DolphinDebug
) << "parent" << data
->parent
->item
;
448 KFileItem
KFileItemModel::rootItem() const
450 return m_dirLister
->rootItem();
453 void KFileItemModel::clear()
458 void KFileItemModel::setRoles(const QSet
<QByteArray
>& roles
)
460 if (m_roles
== roles
) {
464 const QSet
<QByteArray
> changedRoles
= (roles
- m_roles
) + (m_roles
- roles
);
468 const bool supportedExpanding
= m_requestRole
[ExpandedParentsCountRole
];
469 const bool willSupportExpanding
= roles
.contains("expandedParentsCount");
470 if (supportedExpanding
&& !willSupportExpanding
) {
471 // No expanding is supported anymore. Take care to delete all items that have an expansion level
472 // that is not 0 (and hence are part of an expanded item).
473 removeExpandedItems();
480 QSetIterator
<QByteArray
> it(roles
);
481 while (it
.hasNext()) {
482 const QByteArray
& role
= it
.next();
483 m_requestRole
[typeForRole(role
)] = true;
487 // Update m_data with the changed requested roles
488 const int maxIndex
= count() - 1;
489 for (int i
= 0; i
<= maxIndex
; ++i
) {
490 m_itemData
[i
]->values
= retrieveData(m_itemData
.at(i
)->item
, m_itemData
.at(i
)->parent
);
493 Q_EMIT
itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles
);
496 // Clear the 'values' of all filtered items. They will be re-populated with the
497 // correct roles the next time 'values' will be accessed via data(int).
498 QHash
<KFileItem
, ItemData
*>::iterator filteredIt
= m_filteredItems
.begin();
499 const QHash
<KFileItem
, ItemData
*>::iterator filteredEnd
= m_filteredItems
.end();
500 while (filteredIt
!= filteredEnd
) {
501 (*filteredIt
)->values
.clear();
506 QSet
<QByteArray
> KFileItemModel::roles() const
511 bool KFileItemModel::setExpanded(int index
, bool expanded
)
513 if (!isExpandable(index
) || isExpanded(index
) == expanded
) {
517 QHash
<QByteArray
, QVariant
> values
;
518 values
.insert(sharedValue("isExpanded"), expanded
);
519 if (!setData(index
, values
)) {
523 const KFileItem item
= m_itemData
.at(index
)->item
;
524 const QUrl url
= item
.url();
525 const QUrl targetUrl
= item
.targetUrl();
527 m_expandedDirs
.insert(targetUrl
, url
);
528 m_dirLister
->openUrl(url
, KDirLister::Keep
);
530 const QVariantList previouslyExpandedChildren
= m_itemData
.at(index
)->values
.value("previouslyExpandedChildren").value
<QVariantList
>();
531 for (const QVariant
& var
: previouslyExpandedChildren
) {
532 m_urlsToExpand
.insert(var
.toUrl());
535 // Note that there might be (indirect) children of the folder which is to be collapsed in
536 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
537 // possibly without a parent, which might result in a crash, we insert all pending items
538 // right now. All new items which would be without a parent will then be removed.
539 dispatchPendingItemsToInsert();
541 // Check if the index of the collapsed folder has changed. If that is the case, then items
542 // were inserted before the collapsed folder, and its index needs to be updated.
543 if (m_itemData
.at(index
)->item
!= item
) {
544 index
= this->index(item
);
547 m_expandedDirs
.remove(targetUrl
);
548 m_dirLister
->stop(url
);
550 const int parentLevel
= expandedParentsCount(index
);
551 const int itemCount
= m_itemData
.count();
552 const int firstChildIndex
= index
+ 1;
554 QVariantList expandedChildren
;
556 int childIndex
= firstChildIndex
;
557 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
558 ItemData
* itemData
= m_itemData
.at(childIndex
);
559 if (itemData
->values
.value("isExpanded").toBool()) {
560 const QUrl targetUrl
= itemData
->item
.targetUrl();
561 const QUrl url
= itemData
->item
.url();
562 m_expandedDirs
.remove(targetUrl
);
563 m_dirLister
->stop(url
); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
564 expandedChildren
.append(targetUrl
);
568 const int childrenCount
= childIndex
- firstChildIndex
;
570 removeFilteredChildren(KItemRangeList() << KItemRange(index
, 1 + childrenCount
));
571 removeItems(KItemRangeList() << KItemRange(firstChildIndex
, childrenCount
), DeleteItemData
);
573 m_itemData
.at(index
)->values
.insert("previouslyExpandedChildren", expandedChildren
);
579 bool KFileItemModel::isExpanded(int index
) const
581 if (index
>= 0 && index
< count()) {
582 return m_itemData
.at(index
)->values
.value("isExpanded").toBool();
587 bool KFileItemModel::isExpandable(int index
) const
589 if (index
>= 0 && index
< count()) {
590 // Call data (instead of accessing m_itemData directly)
591 // to ensure that the value is initialized.
592 return data(index
).value("isExpandable").toBool();
597 int KFileItemModel::expandedParentsCount(int index
) const
599 if (index
>= 0 && index
< count()) {
600 return expandedParentsCount(m_itemData
.at(index
));
605 QSet
<QUrl
> KFileItemModel::expandedDirectories() const
608 const auto dirs
= m_expandedDirs
;
609 for (const auto &dir
: dirs
) {
615 void KFileItemModel::restoreExpandedDirectories(const QSet
<QUrl
> &urls
)
617 m_urlsToExpand
= urls
;
620 void KFileItemModel::expandParentDirectories(const QUrl
&url
)
623 // Assure that each sub-path of the URL that should be
624 // expanded is added to m_urlsToExpand. KDirLister
625 // does not care whether the parent-URL has already been
627 QUrl urlToExpand
= m_dirLister
->url();
628 const int pos
= urlToExpand
.path().length();
630 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
631 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
632 // so using QString::SkipEmptyParts
633 const QStringList subDirs
= url
.path().mid(pos
).split(QDir::separator(), Qt::SkipEmptyParts
);
634 for (int i
= 0; i
< subDirs
.count() - 1; ++i
) {
635 QString path
= urlToExpand
.path();
636 if (!path
.endsWith(QLatin1Char('/'))) {
637 path
.append(QLatin1Char('/'));
639 urlToExpand
.setPath(path
+ subDirs
.at(i
));
640 m_urlsToExpand
.insert(urlToExpand
);
643 // KDirLister::open() must called at least once to trigger an initial
644 // loading. The pending URLs that must be restored are handled
645 // in slotCompleted().
646 QSetIterator
<QUrl
> it2(m_urlsToExpand
);
647 while (it2
.hasNext()) {
648 const int idx
= index(it2
.next());
649 if (idx
>= 0 && !isExpanded(idx
)) {
650 setExpanded(idx
, true);
656 void KFileItemModel::setNameFilter(const QString
& nameFilter
)
658 if (m_filter
.pattern() != nameFilter
) {
659 dispatchPendingItemsToInsert();
660 m_filter
.setPattern(nameFilter
);
665 QString
KFileItemModel::nameFilter() const
667 return m_filter
.pattern();
670 void KFileItemModel::setMimeTypeFilters(const QStringList
& filters
)
672 if (m_filter
.mimeTypes() != filters
) {
673 dispatchPendingItemsToInsert();
674 m_filter
.setMimeTypes(filters
);
679 QStringList
KFileItemModel::mimeTypeFilters() const
681 return m_filter
.mimeTypes();
685 void KFileItemModel::applyFilters()
687 // Check which shown items from m_itemData must get
688 // hidden and hence moved to m_filteredItems.
689 QVector
<int> newFilteredIndexes
;
691 const int itemCount
= m_itemData
.count();
692 for (int index
= 0; index
< itemCount
; ++index
) {
693 ItemData
* itemData
= m_itemData
.at(index
);
695 // Only filter non-expanded items as child items may never
696 // exist without a parent item
697 if (!itemData
->values
.value("isExpanded").toBool()) {
698 const KFileItem item
= itemData
->item
;
699 if (!m_filter
.matches(item
)) {
700 newFilteredIndexes
.append(index
);
701 m_filteredItems
.insert(item
, itemData
);
706 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
707 removeItems(removedRanges
, KeepItemData
);
709 // Check which hidden items from m_filteredItems should
710 // get visible again and hence removed from m_filteredItems.
711 QList
<ItemData
*> newVisibleItems
;
713 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
714 while (it
!= m_filteredItems
.end()) {
715 if (m_filter
.matches(it
.key())) {
716 newVisibleItems
.append(it
.value());
717 it
= m_filteredItems
.erase(it
);
723 insertItems(newVisibleItems
);
726 void KFileItemModel::removeFilteredChildren(const KItemRangeList
& itemRanges
)
728 if (m_filteredItems
.isEmpty() || !m_requestRole
[ExpandedParentsCountRole
]) {
729 // There are either no filtered items, or it is not possible to expand
730 // folders -> there cannot be any filtered children.
734 QSet
<ItemData
*> parents
;
735 for (const KItemRange
& range
: itemRanges
) {
736 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
737 parents
.insert(m_itemData
.at(index
));
741 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
742 while (it
!= m_filteredItems
.end()) {
743 if (parents
.contains(it
.value()->parent
)) {
745 it
= m_filteredItems
.erase(it
);
752 QList
<KFileItemModel::RoleInfo
> KFileItemModel::rolesInformation()
754 static QList
<RoleInfo
> rolesInfo
;
755 if (rolesInfo
.isEmpty()) {
757 const RoleInfoMap
* map
= rolesInfoMap(count
);
758 for (int i
= 0; i
< count
; ++i
) {
759 if (map
[i
].roleType
!= NoRole
) {
761 info
.role
= map
[i
].role
;
762 info
.translation
= i18nc(map
[i
].roleTranslationContext
, map
[i
].roleTranslation
);
763 if (map
[i
].groupTranslation
) {
764 info
.group
= i18nc(map
[i
].groupTranslationContext
, map
[i
].groupTranslation
);
766 // For top level roles, groupTranslation is 0. We must make sure that
767 // info.group is an empty string then because the code that generates
768 // menus tries to put the actions into sub menus otherwise.
769 info
.group
= QString();
771 info
.requiresBaloo
= map
[i
].requiresBaloo
;
772 info
.requiresIndexer
= map
[i
].requiresIndexer
;
773 rolesInfo
.append(info
);
781 void KFileItemModel::onGroupedSortingChanged(bool current
)
787 void KFileItemModel::onSortRoleChanged(const QByteArray
& current
, const QByteArray
& previous
, bool resortItems
)
790 m_sortRole
= typeForRole(current
);
792 if (!m_requestRole
[m_sortRole
]) {
793 QSet
<QByteArray
> newRoles
= m_roles
;
803 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current
, Qt::SortOrder previous
)
810 void KFileItemModel::loadSortingSettings()
812 using Choice
= GeneralSettings::EnumSortingChoice
;
813 switch (GeneralSettings::sortingChoice()) {
814 case Choice::NaturalSorting
:
815 m_naturalSorting
= true;
816 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
818 case Choice::CaseSensitiveSorting
:
819 m_naturalSorting
= false;
820 m_collator
.setCaseSensitivity(Qt::CaseSensitive
);
822 case Choice::CaseInsensitiveSorting
:
823 m_naturalSorting
= false;
824 m_collator
.setCaseSensitivity(Qt::CaseInsensitive
);
829 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
830 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
831 m_collator
.compare(QString(), QString());
834 void KFileItemModel::resortAllItems()
836 m_resortAllItemsTimer
->stop();
838 const int itemCount
= count();
839 if (itemCount
<= 0) {
843 #ifdef KFILEITEMMODEL_DEBUG
846 qCDebug(DolphinDebug
) << "===========================================================";
847 qCDebug(DolphinDebug
) << "Resorting" << itemCount
<< "items";
850 // Remember the order of the current URLs so
851 // that it can be determined which indexes have
852 // been moved because of the resorting.
854 oldUrls
.reserve(itemCount
);
855 for (const ItemData
* itemData
: qAsConst(m_itemData
)) {
856 oldUrls
.append(itemData
->item
.url());
860 m_items
.reserve(itemCount
);
863 sort(m_itemData
.begin(), m_itemData
.end());
864 for (int i
= 0; i
< itemCount
; ++i
) {
865 m_items
.insert(m_itemData
.at(i
)->item
.url(), i
);
868 // Determine the first index that has been moved.
869 int firstMovedIndex
= 0;
870 while (firstMovedIndex
< itemCount
871 && firstMovedIndex
== m_items
.value(oldUrls
.at(firstMovedIndex
))) {
875 const bool itemsHaveMoved
= firstMovedIndex
< itemCount
;
876 if (itemsHaveMoved
) {
879 int lastMovedIndex
= itemCount
- 1;
880 while (lastMovedIndex
> firstMovedIndex
881 && lastMovedIndex
== m_items
.value(oldUrls
.at(lastMovedIndex
))) {
885 Q_ASSERT(firstMovedIndex
<= lastMovedIndex
);
887 // Create a list movedToIndexes, which has the property that
888 // movedToIndexes[i] is the new index of the item with the old index
889 // firstMovedIndex + i.
890 const int movedItemsCount
= lastMovedIndex
- firstMovedIndex
+ 1;
891 QList
<int> movedToIndexes
;
892 movedToIndexes
.reserve(movedItemsCount
);
893 for (int i
= firstMovedIndex
; i
<= lastMovedIndex
; ++i
) {
894 const int newIndex
= m_items
.value(oldUrls
.at(i
));
895 movedToIndexes
.append(newIndex
);
898 Q_EMIT
itemsMoved(KItemRange(firstMovedIndex
, movedItemsCount
), movedToIndexes
);
899 } else if (groupedSorting()) {
900 // The groups might have changed even if the order of the items has not.
901 const QList
<QPair
<int, QVariant
> > oldGroups
= m_groups
;
903 if (groups() != oldGroups
) {
904 Q_EMIT
groupsChanged();
908 #ifdef KFILEITEMMODEL_DEBUG
909 qCDebug(DolphinDebug
) << "[TIME] Resorting of" << itemCount
<< "items:" << timer
.elapsed();
913 void KFileItemModel::slotCompleted()
915 m_maximumUpdateIntervalTimer
->stop();
916 dispatchPendingItemsToInsert();
918 if (!m_urlsToExpand
.isEmpty()) {
919 // Try to find a URL that can be expanded.
920 // Note that the parent folder must be expanded before any of its subfolders become visible.
921 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
922 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
923 // Iterate over a const copy because items are deleted and inserted within the loop
924 const auto urlsToExpand
= m_urlsToExpand
;
925 for(const QUrl
&url
: urlsToExpand
) {
926 const int indexForUrl
= index(url
);
927 if (indexForUrl
>= 0) {
928 m_urlsToExpand
.remove(url
);
929 if (setExpanded(indexForUrl
, true)) {
930 // The dir lister has been triggered. This slot will be called
931 // again after the directory has been expanded.
937 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
938 // if these URLs have been deleted in the meantime.
939 m_urlsToExpand
.clear();
942 Q_EMIT
directoryLoadingCompleted();
945 void KFileItemModel::slotCanceled()
947 m_maximumUpdateIntervalTimer
->stop();
948 dispatchPendingItemsToInsert();
950 Q_EMIT
directoryLoadingCanceled();
953 void KFileItemModel::slotItemsAdded(const QUrl
&directoryUrl
, const KFileItemList
& items
)
955 Q_ASSERT(!items
.isEmpty());
958 if (m_expandedDirs
.contains(directoryUrl
)) {
959 parentUrl
= m_expandedDirs
.value(directoryUrl
);
961 parentUrl
= directoryUrl
.adjusted(QUrl::StripTrailingSlash
);
964 if (m_requestRole
[ExpandedParentsCountRole
]) {
965 // If the expanding of items is enabled, the call
966 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
967 // might result in emitting the same items twice due to the Keep-parameter.
968 // This case happens if an item gets expanded, collapsed and expanded again
969 // before the items could be loaded for the first expansion.
970 if (index(items
.first().url()) >= 0) {
971 // The items are already part of the model.
975 if (directoryUrl
!= directory()) {
976 // To be able to compare whether the new items may be inserted as children
977 // of a parent item the pending items must be added to the model first.
978 dispatchPendingItemsToInsert();
981 // KDirLister keeps the children of items that got expanded once even if
982 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
983 // checked whether the parent for new items is still expanded.
984 const int parentIndex
= index(parentUrl
);
985 if (parentIndex
>= 0 && !m_itemData
[parentIndex
]->values
.value("isExpanded").toBool()) {
986 // The parent is not expanded.
991 const QList
<ItemData
*> itemDataList
= createItemDataList(parentUrl
, items
);
993 if (!m_filter
.hasSetFilters()) {
994 m_pendingItemsToInsert
.append(itemDataList
);
996 // The name or type filter is active. Hide filtered items
997 // before inserting them into the model and remember
998 // the filtered items in m_filteredItems.
999 for (ItemData
* itemData
: itemDataList
) {
1000 if (m_filter
.matches(itemData
->item
)) {
1001 m_pendingItemsToInsert
.append(itemData
);
1003 m_filteredItems
.insert(itemData
->item
, itemData
);
1008 if (!m_maximumUpdateIntervalTimer
->isActive()) {
1009 // Assure that items get dispatched if no completed() or canceled() signal is
1010 // emitted during the maximum update interval.
1011 m_maximumUpdateIntervalTimer
->start();
1014 Q_EMIT
fileItemsChanged({KFileItem(directoryUrl
)});
1017 void KFileItemModel::slotItemsDeleted(const KFileItemList
& items
)
1019 dispatchPendingItemsToInsert();
1021 QVector
<int> indexesToRemove
;
1022 indexesToRemove
.reserve(items
.count());
1023 KFileItemList dirsChanged
;
1025 for (const KFileItem
& item
: items
) {
1026 const int indexForItem
= index(item
);
1027 if (indexForItem
>= 0) {
1028 indexesToRemove
.append(indexForItem
);
1030 // Probably the item has been filtered.
1031 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(item
);
1032 if (it
!= m_filteredItems
.end()) {
1034 m_filteredItems
.erase(it
);
1038 QUrl parentUrl
= item
.url().adjusted(QUrl::RemoveFilename
| QUrl::StripTrailingSlash
);
1039 if (dirsChanged
.findByUrl(parentUrl
).isNull()) {
1040 dirsChanged
<< KFileItem(parentUrl
);
1044 std::sort(indexesToRemove
.begin(), indexesToRemove
.end());
1046 if (m_requestRole
[ExpandedParentsCountRole
] && !m_expandedDirs
.isEmpty()) {
1047 // Assure that removing a parent item also results in removing all children
1048 QVector
<int> indexesToRemoveWithChildren
;
1049 indexesToRemoveWithChildren
.reserve(m_itemData
.count());
1051 const int itemCount
= m_itemData
.count();
1052 for (int index
: qAsConst(indexesToRemove
)) {
1053 indexesToRemoveWithChildren
.append(index
);
1055 const int parentLevel
= expandedParentsCount(index
);
1056 int childIndex
= index
+ 1;
1057 while (childIndex
< itemCount
&& expandedParentsCount(childIndex
) > parentLevel
) {
1058 indexesToRemoveWithChildren
.append(childIndex
);
1063 indexesToRemove
= indexesToRemoveWithChildren
;
1066 const KItemRangeList itemRanges
= KItemRangeList::fromSortedContainer(indexesToRemove
);
1067 removeFilteredChildren(itemRanges
);
1068 removeItems(itemRanges
, DeleteItemData
);
1070 Q_EMIT
fileItemsChanged(dirsChanged
);
1073 void KFileItemModel::slotRefreshItems(const QList
<QPair
<KFileItem
, KFileItem
> >& items
)
1075 Q_ASSERT(!items
.isEmpty());
1076 #ifdef KFILEITEMMODEL_DEBUG
1077 qCDebug(DolphinDebug
) << "Refreshing" << items
.count() << "items";
1080 // Get the indexes of all items that have been refreshed
1082 indexes
.reserve(items
.count());
1084 QSet
<QByteArray
> changedRoles
;
1085 KFileItemList changedFiles
;
1087 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1088 while (it
.hasNext()) {
1089 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1090 const KFileItem
& oldItem
= itemPair
.first
;
1091 const KFileItem
& newItem
= itemPair
.second
;
1092 const int indexForItem
= index(oldItem
);
1093 if (indexForItem
>= 0) {
1094 m_itemData
[indexForItem
]->item
= newItem
;
1096 // Keep old values as long as possible if they could not retrieved synchronously yet.
1097 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1098 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, m_itemData
.at(indexForItem
)->parent
));
1099 QHash
<QByteArray
, QVariant
>& values
= m_itemData
[indexForItem
]->values
;
1100 while (it
.hasNext()) {
1102 const QByteArray
& role
= it
.key();
1103 if (values
.value(role
) != it
.value()) {
1104 values
.insert(role
, it
.value());
1105 changedRoles
.insert(role
);
1109 m_items
.remove(oldItem
.url());
1110 m_items
.insert(newItem
.url(), indexForItem
);
1111 changedFiles
.append(newItem
);
1112 indexes
.append(indexForItem
);
1114 // Check if 'oldItem' is one of the filtered items.
1115 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1116 if (it
!= m_filteredItems
.end()) {
1117 ItemData
* itemData
= it
.value();
1118 itemData
->item
= newItem
;
1120 // The data stored in 'values' might have changed. Therefore, we clear
1121 // 'values' and re-populate it the next time it is requested via data(int).
1122 itemData
->values
.clear();
1124 m_filteredItems
.erase(it
);
1125 m_filteredItems
.insert(newItem
, itemData
);
1130 // If the changed items have been created recently, they might not be in m_items yet.
1131 // In that case, the list 'indexes' might be empty.
1132 if (indexes
.isEmpty()) {
1136 // Extract the item-ranges out of the changed indexes
1137 std::sort(indexes
.begin(), indexes
.end());
1138 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1139 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1141 Q_EMIT
fileItemsChanged(changedFiles
);
1144 void KFileItemModel::slotClear()
1146 #ifdef KFILEITEMMODEL_DEBUG
1147 qCDebug(DolphinDebug
) << "Clearing all items";
1150 qDeleteAll(m_filteredItems
);
1151 m_filteredItems
.clear();
1154 m_maximumUpdateIntervalTimer
->stop();
1155 m_resortAllItemsTimer
->stop();
1157 qDeleteAll(m_pendingItemsToInsert
);
1158 m_pendingItemsToInsert
.clear();
1160 const int removedCount
= m_itemData
.count();
1161 if (removedCount
> 0) {
1162 qDeleteAll(m_itemData
);
1165 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1168 m_expandedDirs
.clear();
1171 void KFileItemModel::slotSortingChoiceChanged()
1173 loadSortingSettings();
1177 void KFileItemModel::dispatchPendingItemsToInsert()
1179 if (!m_pendingItemsToInsert
.isEmpty()) {
1180 insertItems(m_pendingItemsToInsert
);
1181 m_pendingItemsToInsert
.clear();
1185 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1187 if (newItems
.isEmpty()) {
1191 #ifdef KFILEITEMMODEL_DEBUG
1192 QElapsedTimer timer
;
1194 qCDebug(DolphinDebug
) << "===========================================================";
1195 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1199 prepareItemsForSorting(newItems
);
1201 // Natural sorting of items can be very slow. However, it becomes much faster
1202 // if the input sequence is already mostly sorted. Therefore, we first sort
1203 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1204 if (m_naturalSorting
) {
1205 if (m_sortRole
== NameRole
) {
1206 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1207 } else if (isRoleValueNatural(m_sortRole
)) {
1208 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1210 const QByteArray role
= roleForType(m_sortRole
);
1211 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1213 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1217 sort(newItems
.begin(), newItems
.end());
1219 #ifdef KFILEITEMMODEL_DEBUG
1220 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1223 KItemRangeList itemRanges
;
1224 const int existingItemCount
= m_itemData
.count();
1225 const int newItemCount
= newItems
.count();
1226 const int totalItemCount
= existingItemCount
+ newItemCount
;
1228 if (existingItemCount
== 0) {
1229 // Optimization for the common special case that there are no
1230 // items in the model yet. Happens, e.g., when entering a folder.
1231 m_itemData
= newItems
;
1232 itemRanges
<< KItemRange(0, newItemCount
);
1234 m_itemData
.reserve(totalItemCount
);
1235 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1236 m_itemData
.append(nullptr);
1239 // We build the new list m_itemData in reverse order to minimize
1240 // the number of moves and guarantee O(N) complexity.
1241 int targetIndex
= totalItemCount
- 1;
1242 int sourceIndexExistingItems
= existingItemCount
- 1;
1243 int sourceIndexNewItems
= newItemCount
- 1;
1247 while (sourceIndexNewItems
>= 0) {
1248 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1249 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1250 // Move an existing item to its new position. If any new items
1251 // are behind it, push the item range to itemRanges.
1252 if (rangeCount
> 0) {
1253 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1257 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1258 --sourceIndexExistingItems
;
1260 // Insert a new item into the list.
1262 m_itemData
[targetIndex
] = newItem
;
1263 --sourceIndexNewItems
;
1268 // Push the final item range to itemRanges.
1269 if (rangeCount
> 0) {
1270 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1273 // Note that itemRanges is still sorted in reverse order.
1274 std::reverse(itemRanges
.begin(), itemRanges
.end());
1277 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1278 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1281 Q_EMIT
itemsInserted(itemRanges
);
1283 #ifdef KFILEITEMMODEL_DEBUG
1284 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1288 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1290 if (itemRanges
.isEmpty()) {
1296 // Step 1: Remove the items from m_itemData, and free the ItemData.
1297 int removedItemsCount
= 0;
1298 for (const KItemRange
& range
: itemRanges
) {
1299 removedItemsCount
+= range
.count
;
1301 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1302 if (behavior
== DeleteItemData
) {
1303 delete m_itemData
.at(index
);
1306 m_itemData
[index
] = nullptr;
1310 // Step 2: Remove the ItemData pointers from the list m_itemData.
1311 int target
= itemRanges
.at(0).index
;
1312 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1315 const int oldItemDataCount
= m_itemData
.count();
1316 while (source
< oldItemDataCount
) {
1317 m_itemData
[target
] = m_itemData
[source
];
1321 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1322 // Skip the items in the next removed range.
1323 source
+= itemRanges
.at(nextRange
).count
;
1328 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1330 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1331 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1334 Q_EMIT
itemsRemoved(itemRanges
);
1337 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1339 if (m_sortRole
== TypeRole
) {
1340 // Try to resolve the MIME-types synchronously to prevent a reordering of
1341 // the items when sorting by type (per default MIME-types are resolved
1342 // asynchronously by KFileItemModelRolesUpdater).
1343 determineMimeTypes(items
, 200);
1346 const int parentIndex
= index(parentUrl
);
1347 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1349 QList
<ItemData
*> itemDataList
;
1350 itemDataList
.reserve(items
.count());
1352 for (const KFileItem
& item
: items
) {
1353 ItemData
* itemData
= new ItemData();
1354 itemData
->item
= item
;
1355 itemData
->parent
= parentItem
;
1356 itemDataList
.append(itemData
);
1359 return itemDataList
;
1362 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1364 switch (m_sortRole
) {
1365 case PermissionsRole
:
1368 case DestinationRole
:
1370 case DeletionTimeRole
:
1371 // These roles can be determined with retrieveData, and they have to be stored
1372 // in the QHash "values" for the sorting.
1373 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1374 if (itemData
->values
.isEmpty()) {
1375 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1381 // At least store the data including the file type for items with known MIME type.
1382 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1383 if (itemData
->values
.isEmpty()) {
1384 const KFileItem item
= itemData
->item
;
1385 if (item
.isDir() || item
.isMimeTypeKnown()) {
1386 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1393 // The other roles are either resolved by KFileItemModelRolesUpdater
1394 // (this includes the SizeRole for directories), or they do not need
1395 // to be stored in the QHash "values" for sorting because the data can
1396 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1402 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1404 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1405 // if the corresponding item is expanded, and it is not a top-level item.
1406 const ItemData
* parent
= data
->parent
;
1408 if (parent
->parent
) {
1409 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1410 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1419 void KFileItemModel::removeExpandedItems()
1421 QVector
<int> indexesToRemove
;
1423 const int maxIndex
= m_itemData
.count() - 1;
1424 for (int i
= 0; i
<= maxIndex
; ++i
) {
1425 const ItemData
* itemData
= m_itemData
.at(i
);
1426 if (itemData
->parent
) {
1427 indexesToRemove
.append(i
);
1431 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1432 m_expandedDirs
.clear();
1434 // Also remove all filtered items which have a parent.
1435 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1436 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1439 if (it
.value()->parent
) {
1441 it
= m_filteredItems
.erase(it
);
1448 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1450 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1452 // Trigger a resorting if necessary. Note that this can happen even if the sort
1453 // role has not changed at all because the file name can be used as a fallback.
1454 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1455 for (const KItemRange
& range
: itemRanges
) {
1456 bool needsResorting
= false;
1458 const int first
= range
.index
;
1459 const int last
= range
.index
+ range
.count
- 1;
1461 // Resorting the model is necessary if
1462 // (a) The first item in the range is "lessThan" its predecessor,
1463 // (b) the successor of the last item is "lessThan" the last item, or
1464 // (c) the internal order of the items in the range is incorrect.
1466 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1467 needsResorting
= true;
1468 } else if (last
< count() - 1
1469 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1470 needsResorting
= true;
1472 for (int index
= first
; index
< last
; ++index
) {
1473 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1474 needsResorting
= true;
1480 if (needsResorting
) {
1481 m_resortAllItemsTimer
->start();
1487 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1488 // The position is still correct, but the groups might have changed
1489 // if the changed item is either the first or the last item in a
1491 // In principle, we could try to find out if the item really is the
1492 // first or last one in its group and then update the groups
1493 // (possibly with a delayed timer to make sure that we don't
1494 // re-calculate the groups very often if items are updated one by
1495 // one), but starting m_resortAllItemsTimer is easier.
1496 m_resortAllItemsTimer
->start();
1500 void KFileItemModel::resetRoles()
1502 for (int i
= 0; i
< RolesCount
; ++i
) {
1503 m_requestRole
[i
] = false;
1507 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1509 static QHash
<QByteArray
, RoleType
> roles
;
1510 if (roles
.isEmpty()) {
1511 // Insert user visible roles that can be accessed with
1512 // KFileItemModel::roleInformation()
1514 const RoleInfoMap
* map
= rolesInfoMap(count
);
1515 for (int i
= 0; i
< count
; ++i
) {
1516 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1519 // Insert internal roles (take care to synchronize the implementation
1520 // with KFileItemModel::roleForType() in case if a change is done).
1521 roles
.insert("isDir", IsDirRole
);
1522 roles
.insert("isLink", IsLinkRole
);
1523 roles
.insert("isHidden", IsHiddenRole
);
1524 roles
.insert("isExpanded", IsExpandedRole
);
1525 roles
.insert("isExpandable", IsExpandableRole
);
1526 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1528 Q_ASSERT(roles
.count() == RolesCount
);
1531 return roles
.value(role
, NoRole
);
1534 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1536 static QHash
<RoleType
, QByteArray
> roles
;
1537 if (roles
.isEmpty()) {
1538 // Insert user visible roles that can be accessed with
1539 // KFileItemModel::roleInformation()
1541 const RoleInfoMap
* map
= rolesInfoMap(count
);
1542 for (int i
= 0; i
< count
; ++i
) {
1543 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1546 // Insert internal roles (take care to synchronize the implementation
1547 // with KFileItemModel::typeForRole() in case if a change is done).
1548 roles
.insert(IsDirRole
, "isDir");
1549 roles
.insert(IsLinkRole
, "isLink");
1550 roles
.insert(IsHiddenRole
, "isHidden");
1551 roles
.insert(IsExpandedRole
, "isExpanded");
1552 roles
.insert(IsExpandableRole
, "isExpandable");
1553 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1555 Q_ASSERT(roles
.count() == RolesCount
);
1558 return roles
.value(roleType
);
1561 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1563 // It is important to insert only roles that are fast to retrieve. E.g.
1564 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1565 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1566 QHash
<QByteArray
, QVariant
> data
;
1567 data
.insert(sharedValue("url"), item
.url());
1569 const bool isDir
= item
.isDir();
1570 if (m_requestRole
[IsDirRole
] && isDir
) {
1571 data
.insert(sharedValue("isDir"), true);
1574 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1575 data
.insert(sharedValue("isLink"), true);
1578 if (m_requestRole
[IsHiddenRole
]) {
1579 data
.insert(sharedValue("isHidden"), item
.isHidden());
1582 if (m_requestRole
[NameRole
]) {
1583 data
.insert(sharedValue("text"), item
.text());
1586 if (m_requestRole
[SizeRole
] && !isDir
) {
1587 data
.insert(sharedValue("size"), item
.size());
1590 if (m_requestRole
[ModificationTimeRole
]) {
1591 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1592 // having several thousands of items. Instead read the raw number from UDSEntry directly
1593 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1594 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1595 data
.insert(sharedValue("modificationtime"), dateTime
);
1598 if (m_requestRole
[CreationTimeRole
]) {
1599 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1600 // having several thousands of items. Instead read the raw number from UDSEntry directly
1601 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1602 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1603 data
.insert(sharedValue("creationtime"), dateTime
);
1606 if (m_requestRole
[AccessTimeRole
]) {
1607 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1608 // having several thousands of items. Instead read the raw number from UDSEntry directly
1609 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1610 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1611 data
.insert(sharedValue("accesstime"), dateTime
);
1614 if (m_requestRole
[PermissionsRole
]) {
1615 data
.insert(sharedValue("permissions"), item
.permissionsString());
1618 if (m_requestRole
[OwnerRole
]) {
1619 data
.insert(sharedValue("owner"), item
.user());
1622 if (m_requestRole
[GroupRole
]) {
1623 data
.insert(sharedValue("group"), item
.group());
1626 if (m_requestRole
[DestinationRole
]) {
1627 QString destination
= item
.linkDest();
1628 if (destination
.isEmpty()) {
1629 destination
= QLatin1Char('-');
1631 data
.insert(sharedValue("destination"), destination
);
1634 if (m_requestRole
[PathRole
]) {
1636 if (item
.url().scheme() == QLatin1String("trash")) {
1637 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1639 // For performance reasons cache the home-path in a static QString
1640 // (see QDir::homePath() for more details)
1641 static QString homePath
;
1642 if (homePath
.isEmpty()) {
1643 homePath
= QDir::homePath();
1646 path
= item
.localPath();
1647 if (path
.startsWith(homePath
)) {
1648 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1652 const int index
= path
.lastIndexOf(item
.text());
1653 path
= path
.mid(0, index
- 1);
1654 data
.insert(sharedValue("path"), path
);
1657 if (m_requestRole
[DeletionTimeRole
]) {
1658 QDateTime deletionTime
;
1659 if (item
.url().scheme() == QLatin1String("trash")) {
1660 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1662 data
.insert(sharedValue("deletiontime"), deletionTime
);
1665 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1666 data
.insert(sharedValue("isExpandable"), true);
1669 if (m_requestRole
[ExpandedParentsCountRole
]) {
1671 const int level
= expandedParentsCount(parent
) + 1;
1672 data
.insert(sharedValue("expandedParentsCount"), level
);
1676 if (item
.isMimeTypeKnown()) {
1677 QString iconName
= item
.iconName();
1678 if (!QIcon::hasThemeIcon(iconName
)) {
1679 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1680 iconName
= mimeType
.genericIconName();
1683 data
.insert(sharedValue("iconName"), iconName
);
1685 if (m_requestRole
[TypeRole
]) {
1686 data
.insert(sharedValue("type"), item
.mimeComment());
1688 } else if (m_requestRole
[TypeRole
] && isDir
) {
1689 static const QString folderMimeType
= item
.mimeComment();
1690 data
.insert(sharedValue("type"), folderMimeType
);
1696 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1700 if (a
->parent
!= b
->parent
) {
1701 const int expansionLevelA
= expandedParentsCount(a
);
1702 const int expansionLevelB
= expandedParentsCount(b
);
1704 // If b has a higher expansion level than a, check if a is a parent
1705 // of b, and make sure that both expansion levels are equal otherwise.
1706 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1707 if (b
->parent
== a
) {
1713 // If a has a higher expansion level than a, check if b is a parent
1714 // of a, and make sure that both expansion levels are equal otherwise.
1715 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1716 if (a
->parent
== b
) {
1722 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1724 // Compare the last parents of a and b which are different.
1725 while (a
->parent
!= b
->parent
) {
1731 // Show hidden files and folders last
1732 const bool isHiddenA
= a
->item
.isHidden();
1733 const bool isHiddenB
= b
->item
.isHidden();
1734 if (isHiddenA
&& !isHiddenB
) {
1736 } else if (!isHiddenA
&& isHiddenB
) {
1740 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1741 const bool isDirA
= a
->item
.isDir();
1742 const bool isDirB
= b
->item
.isDir();
1743 if (isDirA
&& !isDirB
) {
1745 } else if (!isDirA
&& isDirB
) {
1750 result
= sortRoleCompare(a
, b
, collator
);
1752 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1755 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1756 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1758 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1760 return lessThan(a
, b
, m_collator
);
1763 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1764 // Sorting by string can be expensive, in particular if natural sorting is
1765 // enabled. Use all CPU cores to speed up the sorting process.
1766 static const int numberOfThreads
= QThread::idealThreadCount();
1767 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1769 // Sorting by other roles is quite fast. Use only one thread to prevent
1770 // problems caused by non-reentrant comparison functions, see
1771 // https://bugs.kde.org/show_bug.cgi?id=312679
1772 mergeSort(begin
, end
, lambdaLessThan
);
1776 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1778 const KFileItem
& itemA
= a
->item
;
1779 const KFileItem
& itemB
= b
->item
;
1783 switch (m_sortRole
) {
1785 // The name role is handled as default fallback after the switch
1789 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1790 // folders first then
1791 // items A and B are folders thanks to lessThan checks
1792 auto valueA
= a
->values
.value("count");
1793 auto valueB
= b
->values
.value("count");
1794 if (valueA
.isNull()) {
1795 if (valueB
.isNull()) {
1802 } else if (valueB
.isNull()) {
1806 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1809 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1818 KIO::filesize_t sizeA
= 0;
1819 if (itemA
.isDir()) {
1820 sizeA
= a
->values
.value("size").toULongLong();
1822 sizeA
= itemA
.size();
1824 KIO::filesize_t sizeB
= 0;
1825 if (itemB
.isDir()) {
1826 sizeB
= b
->values
.value("size").toULongLong();
1828 sizeB
= itemB
.size();
1830 if (sizeA
> sizeB
) {
1832 } else if (sizeA
< sizeB
) {
1840 case ModificationTimeRole
: {
1841 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1842 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1843 if (dateTimeA
< dateTimeB
) {
1845 } else if (dateTimeA
> dateTimeB
) {
1851 case CreationTimeRole
: {
1852 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1853 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1854 if (dateTimeA
< dateTimeB
) {
1856 } else if (dateTimeA
> dateTimeB
) {
1862 case DeletionTimeRole
: {
1863 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1864 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1865 if (dateTimeA
< dateTimeB
) {
1867 } else if (dateTimeA
> dateTimeB
) {
1879 case ReleaseYearRole
: {
1880 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1885 const QByteArray role
= roleForType(m_sortRole
);
1886 const QString roleValueA
= a
->values
.value(role
).toString();
1887 const QString roleValueB
= b
->values
.value(role
).toString();
1888 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1890 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1892 } else if (isRoleValueNatural(m_sortRole
)) {
1893 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1895 result
= QString::compare(roleValueA
, roleValueB
);
1903 // The current sort role was sufficient to define an order
1907 // Fallback #1: Compare the text of the items
1908 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1913 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1914 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1919 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1920 // equal. In this case a comparison of the URL is done which is unique in all cases
1921 // within KDirLister.
1922 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1925 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1927 QMutexLocker
collatorLock(s_collatorMutex());
1929 if (m_naturalSorting
) {
1930 return collator
.compare(a
, b
);
1933 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1934 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1935 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1936 // comparison, still a deterministic sort order is required. A case sensitive
1937 // comparison is done as fallback.
1941 return QString::compare(a
, b
, Qt::CaseSensitive
);
1944 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1946 Q_ASSERT(!m_itemData
.isEmpty());
1948 const int maxIndex
= count() - 1;
1949 QList
<QPair
<int, QVariant
> > groups
;
1953 for (int i
= 0; i
<= maxIndex
; ++i
) {
1954 if (isChildItem(i
)) {
1958 const QString name
= m_itemData
.at(i
)->item
.text();
1960 // Use the first character of the name as group indication
1961 QChar newFirstChar
= name
.at(0).toUpper();
1962 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1963 newFirstChar
= name
.at(1).toUpper();
1966 if (firstChar
!= newFirstChar
) {
1967 QString newGroupValue
;
1968 if (newFirstChar
.isLetter()) {
1970 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1971 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1973 // Try to find a matching group in the range 'A' to 'Z'.
1974 static std::vector
<QChar
> lettersAtoZ
;
1975 lettersAtoZ
.reserve('Z' - 'A' + 1);
1976 if (lettersAtoZ
.empty()) {
1977 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1978 lettersAtoZ
.push_back(QLatin1Char(c
));
1982 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1983 return m_collator
.compare(c1
, c2
) < 0;
1986 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1987 if (it
!= lettersAtoZ
.end()) {
1988 if (localeAwareLessThan(newFirstChar
, *it
)) {
1989 // newFirstChar belongs to the group preceding *it.
1990 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
1993 newGroupValue
= *it
;
1997 // Symbols from non Latin-based scripts
1998 newGroupValue
= newFirstChar
;
2000 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2001 // Apply group '0 - 9' for any name that starts with a digit
2002 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2004 newGroupValue
= i18nc("@title:group", "Others");
2007 if (newGroupValue
!= groupValue
) {
2008 groupValue
= newGroupValue
;
2009 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2012 firstChar
= newFirstChar
;
2018 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2020 Q_ASSERT(!m_itemData
.isEmpty());
2022 const int maxIndex
= count() - 1;
2023 QList
<QPair
<int, QVariant
> > groups
;
2026 for (int i
= 0; i
<= maxIndex
; ++i
) {
2027 if (isChildItem(i
)) {
2031 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2032 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2033 QString newGroupValue
;
2034 if (!item
.isNull() && item
.isDir()) {
2035 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2036 newGroupValue
= i18nc("@title:group Size", "Folders");
2038 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2042 if (newGroupValue
.isEmpty()) {
2043 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2044 newGroupValue
= i18nc("@title:group Size", "Small");
2045 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2046 newGroupValue
= i18nc("@title:group Size", "Medium");
2048 newGroupValue
= i18nc("@title:group Size", "Big");
2052 if (newGroupValue
!= groupValue
) {
2053 groupValue
= newGroupValue
;
2054 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2061 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2063 Q_ASSERT(!m_itemData
.isEmpty());
2065 const int maxIndex
= count() - 1;
2066 QList
<QPair
<int, QVariant
> > groups
;
2068 const QDate currentDate
= QDate::currentDate();
2070 QDate previousFileDate
;
2072 for (int i
= 0; i
<= maxIndex
; ++i
) {
2073 if (isChildItem(i
)) {
2077 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2078 const QDate fileDate
= fileTime
.date();
2079 if (fileDate
== previousFileDate
) {
2080 // The current item is in the same group as the previous item
2083 previousFileDate
= fileDate
;
2085 const int daysDistance
= fileDate
.daysTo(currentDate
);
2087 QString newGroupValue
;
2088 if (currentDate
.year() == fileDate
.year() &&
2089 currentDate
.month() == fileDate
.month()) {
2091 switch (daysDistance
/ 7) {
2093 switch (daysDistance
) {
2094 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2095 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2097 newGroupValue
= fileTime
.toString(
2098 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2099 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2100 "with context @title:group Date", "%1", newGroupValue
);
2104 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2107 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2110 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2114 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2120 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2121 if (lastMonthDate
.year() == fileDate
.year() &&
2122 lastMonthDate
.month() == fileDate
.month()) {
2124 if (daysDistance
== 1) {
2125 const KLocalizedString format
= ki18nc("@title:group Date: "
2126 "MMMM is full month name in current locale, and yyyy is "
2127 "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)");
2128 const QString translatedFormat
= format
.toString();
2129 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2130 newGroupValue
= fileTime
.toString(translatedFormat
);
2131 newGroupValue
= i18nc("Can be used to script translation of "
2132 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2133 "%1", newGroupValue
);
2135 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2136 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2137 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2139 } else if (daysDistance
<= 7) {
2140 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2141 "The week day name: dddd, MMMM is full month name "
2142 "in current locale, and yyyy is full year number.",
2143 "dddd (MMMM, yyyy)"));
2144 newGroupValue
= i18nc("Can be used to script translation of "
2145 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2146 "%1", newGroupValue
);
2147 } else if (daysDistance
<= 7 * 2) {
2148 const KLocalizedString format
= ki18nc("@title:group Date: "
2149 "MMMM is full month name in current locale, and yyyy is "
2150 "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)");
2151 const QString translatedFormat
= format
.toString();
2152 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2153 newGroupValue
= fileTime
.toString(translatedFormat
);
2154 newGroupValue
= i18nc("Can be used to script translation of "
2155 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2156 "%1", newGroupValue
);
2158 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2159 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2160 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2162 } else if (daysDistance
<= 7 * 3) {
2163 const KLocalizedString format
= ki18nc("@title:group Date: "
2164 "MMMM is full month name in current locale, and yyyy is "
2165 "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)");
2166 const QString translatedFormat
= format
.toString();
2167 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2168 newGroupValue
= fileTime
.toString(translatedFormat
);
2169 newGroupValue
= i18nc("Can be used to script translation of "
2170 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2171 "%1", newGroupValue
);
2173 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2174 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2175 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2177 } else if (daysDistance
<= 7 * 4) {
2178 const KLocalizedString format
= ki18nc("@title:group Date: "
2179 "MMMM is full month name in current locale, and yyyy is "
2180 "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)");
2181 const QString translatedFormat
= format
.toString();
2182 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2183 newGroupValue
= fileTime
.toString(translatedFormat
);
2184 newGroupValue
= i18nc("Can be used to script translation of "
2185 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2186 "%1", newGroupValue
);
2188 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2189 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2190 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2193 const KLocalizedString format
= ki18nc("@title:group Date: "
2194 "MMMM is full month name in current locale, and yyyy is "
2195 "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");
2196 const QString translatedFormat
= format
.toString();
2197 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2198 newGroupValue
= fileTime
.toString(translatedFormat
);
2199 newGroupValue
= i18nc("Can be used to script translation of "
2200 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2201 "%1", newGroupValue
);
2203 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2204 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2205 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2209 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2210 "The month and year: MMMM is full month name in current locale, "
2211 "and yyyy is full year number", "MMMM, yyyy"));
2212 newGroupValue
= i18nc("Can be used to script translation of "
2213 "\"MMMM, yyyy\" with context @title:group Date",
2214 "%1", newGroupValue
);
2218 if (newGroupValue
!= groupValue
) {
2219 groupValue
= newGroupValue
;
2220 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2227 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2229 Q_ASSERT(!m_itemData
.isEmpty());
2231 const int maxIndex
= count() - 1;
2232 QList
<QPair
<int, QVariant
> > groups
;
2234 QString permissionsString
;
2236 for (int i
= 0; i
<= maxIndex
; ++i
) {
2237 if (isChildItem(i
)) {
2241 const ItemData
* itemData
= m_itemData
.at(i
);
2242 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2243 if (newPermissionsString
== permissionsString
) {
2246 permissionsString
= newPermissionsString
;
2248 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2252 if (info
.permission(QFile::ReadUser
)) {
2253 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2255 if (info
.permission(QFile::WriteUser
)) {
2256 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2258 if (info
.permission(QFile::ExeUser
)) {
2259 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2261 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2265 if (info
.permission(QFile::ReadGroup
)) {
2266 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2268 if (info
.permission(QFile::WriteGroup
)) {
2269 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2271 if (info
.permission(QFile::ExeGroup
)) {
2272 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2274 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2276 // Set others string
2278 if (info
.permission(QFile::ReadOther
)) {
2279 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2281 if (info
.permission(QFile::WriteOther
)) {
2282 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2284 if (info
.permission(QFile::ExeOther
)) {
2285 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2287 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2289 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2290 if (newGroupValue
!= groupValue
) {
2291 groupValue
= newGroupValue
;
2292 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2299 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2301 Q_ASSERT(!m_itemData
.isEmpty());
2303 const int maxIndex
= count() - 1;
2304 QList
<QPair
<int, QVariant
> > groups
;
2306 int groupValue
= -1;
2307 for (int i
= 0; i
<= maxIndex
; ++i
) {
2308 if (isChildItem(i
)) {
2311 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2312 if (newGroupValue
!= groupValue
) {
2313 groupValue
= newGroupValue
;
2314 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2321 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2323 Q_ASSERT(!m_itemData
.isEmpty());
2325 const int maxIndex
= count() - 1;
2326 QList
<QPair
<int, QVariant
> > groups
;
2328 bool isFirstGroupValue
= true;
2330 for (int i
= 0; i
<= maxIndex
; ++i
) {
2331 if (isChildItem(i
)) {
2334 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2335 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2336 groupValue
= newGroupValue
;
2337 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2338 isFirstGroupValue
= false;
2345 void KFileItemModel::emitSortProgress(int resolvedCount
)
2347 // Be tolerant against a resolvedCount with a wrong range.
2348 // Although there should not be a case where KFileItemModelRolesUpdater
2349 // (= caller) provides a wrong range, it is important to emit
2350 // a useful progress information even if there is an unexpected
2351 // implementation issue.
2353 const int itemCount
= count();
2354 if (resolvedCount
>= itemCount
) {
2355 m_sortingProgressPercent
= -1;
2356 if (m_resortAllItemsTimer
->isActive()) {
2357 m_resortAllItemsTimer
->stop();
2361 Q_EMIT
directorySortingProgress(100);
2362 } else if (itemCount
> 0) {
2363 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2365 const int progress
= resolvedCount
* 100 / itemCount
;
2366 if (m_sortingProgressPercent
!= progress
) {
2367 m_sortingProgressPercent
= progress
;
2368 Q_EMIT
directorySortingProgress(progress
);
2373 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2375 static const RoleInfoMap rolesInfoMap
[] = {
2376 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2377 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2378 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2379 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2380 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2381 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2382 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2383 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2384 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2385 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2386 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2387 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2388 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2389 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2390 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2391 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2392 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2393 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2394 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2395 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2396 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2397 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2398 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2399 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2400 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2401 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2402 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2403 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2404 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2405 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2406 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2407 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2408 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2409 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2412 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2413 return rolesInfoMap
;
2416 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2418 QElapsedTimer timer
;
2420 for (const KFileItem
& item
: items
) {
2421 // Only determine mime types for files here. For directories,
2422 // KFileItem::determineMimeType() reads the .directory file inside to
2423 // load the icon, but this is not necessary at all if we just need the
2424 // type. Some special code for setting the correct mime type for
2425 // directories is in retrieveData().
2426 if (!item
.isDir()) {
2427 item
.determineMimeType();
2430 if (timer
.elapsed() > timeout
) {
2431 // Don't block the user interface, let the remaining items
2432 // be resolved asynchronously.
2438 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2440 static QSet
<QByteArray
> pool
;
2441 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2443 if (it
!= pool
.constEnd()) {
2451 bool KFileItemModel::isConsistent() const
2453 // m_items may contain less items than m_itemData because m_items
2454 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2455 if (m_items
.count() > m_itemData
.count()) {
2459 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2460 // Check if m_items and m_itemData are consistent.
2461 const KFileItem item
= fileItem(i
);
2462 if (item
.isNull()) {
2463 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2467 const int itemIndex
= index(item
);
2468 if (itemIndex
!= i
) {
2469 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2473 // Check if the items are sorted correctly.
2474 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2475 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2476 << fileItem(i
- 1) << fileItem(i
);
2480 // Check if all parent-child relationships are consistent.
2481 const ItemData
* data
= m_itemData
.at(i
);
2482 const ItemData
* parent
= data
->parent
;
2484 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2485 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2489 const int parentIndex
= index(parent
->item
);
2490 if (parentIndex
>= i
) {
2491 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2500 void KFileItemModel::slotListerError(KIO::Job
*job
)
2502 if (job
->error() == KIO::ERR_IS_FILE
) {
2503 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2504 Q_EMIT
urlIsFileError(listJob
->url());
2507 const QString errorString
= job
->errorString();
2508 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));