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 // Contains the indexes of the currently visible items
1088 // that should get hidden and hence moved to m_filteredItems.
1089 QVector
<int> newFilteredIndexes
;
1091 // Contains currently hidden items that should
1092 // get visible and hence removed from m_filteredItems
1093 QList
<ItemData
*> newVisibleItems
;
1095 QListIterator
<QPair
<KFileItem
, KFileItem
> > it(items
);
1096 while (it
.hasNext()) {
1097 const QPair
<KFileItem
, KFileItem
>& itemPair
= it
.next();
1098 const KFileItem
& oldItem
= itemPair
.first
;
1099 const KFileItem
& newItem
= itemPair
.second
;
1100 const int indexForItem
= index(oldItem
);
1101 const bool newItemMatchesFilter
= m_filter
.matches(newItem
);
1102 if (indexForItem
>= 0) {
1103 m_itemData
[indexForItem
]->item
= newItem
;
1105 // Keep old values as long as possible if they could not retrieved synchronously yet.
1106 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1107 ItemData
* const itemData
= m_itemData
.at(indexForItem
);
1108 QHashIterator
<QByteArray
, QVariant
> it(retrieveData(newItem
, itemData
->parent
));
1109 while (it
.hasNext()) {
1111 const QByteArray
& role
= it
.key();
1112 if (itemData
->values
.value(role
) != it
.value()) {
1113 itemData
->values
.insert(role
, it
.value());
1114 changedRoles
.insert(role
);
1118 m_items
.remove(oldItem
.url());
1119 if (newItemMatchesFilter
) {
1120 m_items
.insert(newItem
.url(), indexForItem
);
1121 changedFiles
.append(newItem
);
1122 indexes
.append(indexForItem
);
1124 newFilteredIndexes
.append(indexForItem
);
1125 m_filteredItems
.insert(newItem
, itemData
);
1128 // Check if 'oldItem' is one of the filtered items.
1129 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.find(oldItem
);
1130 if (it
!= m_filteredItems
.end()) {
1131 ItemData
* itemData
= it
.value();
1132 itemData
->item
= newItem
;
1134 // The data stored in 'values' might have changed. Therefore, we clear
1135 // 'values' and re-populate it the next time it is requested via data(int).
1136 itemData
->values
.clear();
1138 m_filteredItems
.erase(it
);
1139 if (newItemMatchesFilter
) {
1140 newVisibleItems
.append(itemData
);
1142 m_filteredItems
.insert(newItem
, itemData
);
1148 // Hide items, previously visible that should get hidden
1149 const KItemRangeList removedRanges
= KItemRangeList::fromSortedContainer(newFilteredIndexes
);
1150 removeItems(removedRanges
, KeepItemData
);
1152 // Show previously hidden items that should get visible
1153 insertItems(newVisibleItems
);
1155 // If the changed items have been created recently, they might not be in m_items yet.
1156 // In that case, the list 'indexes' might be empty.
1157 if (indexes
.isEmpty()) {
1161 // Extract the item-ranges out of the changed indexes
1162 std::sort(indexes
.begin(), indexes
.end());
1163 const KItemRangeList itemRangeList
= KItemRangeList::fromSortedContainer(indexes
);
1164 emitItemsChangedAndTriggerResorting(itemRangeList
, changedRoles
);
1166 Q_EMIT
fileItemsChanged(changedFiles
);
1169 void KFileItemModel::slotClear()
1171 #ifdef KFILEITEMMODEL_DEBUG
1172 qCDebug(DolphinDebug
) << "Clearing all items";
1175 qDeleteAll(m_filteredItems
);
1176 m_filteredItems
.clear();
1179 m_maximumUpdateIntervalTimer
->stop();
1180 m_resortAllItemsTimer
->stop();
1182 qDeleteAll(m_pendingItemsToInsert
);
1183 m_pendingItemsToInsert
.clear();
1185 const int removedCount
= m_itemData
.count();
1186 if (removedCount
> 0) {
1187 qDeleteAll(m_itemData
);
1190 Q_EMIT
itemsRemoved(KItemRangeList() << KItemRange(0, removedCount
));
1193 m_expandedDirs
.clear();
1196 void KFileItemModel::slotSortingChoiceChanged()
1198 loadSortingSettings();
1202 void KFileItemModel::dispatchPendingItemsToInsert()
1204 if (!m_pendingItemsToInsert
.isEmpty()) {
1205 insertItems(m_pendingItemsToInsert
);
1206 m_pendingItemsToInsert
.clear();
1210 void KFileItemModel::insertItems(QList
<ItemData
*>& newItems
)
1212 if (newItems
.isEmpty()) {
1216 #ifdef KFILEITEMMODEL_DEBUG
1217 QElapsedTimer timer
;
1219 qCDebug(DolphinDebug
) << "===========================================================";
1220 qCDebug(DolphinDebug
) << "Inserting" << newItems
.count() << "items";
1224 prepareItemsForSorting(newItems
);
1226 // Natural sorting of items can be very slow. However, it becomes much faster
1227 // if the input sequence is already mostly sorted. Therefore, we first sort
1228 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1229 if (m_naturalSorting
) {
1230 if (m_sortRole
== NameRole
) {
1231 parallelMergeSort(newItems
.begin(), newItems
.end(), nameLessThan
, QThread::idealThreadCount());
1232 } else if (isRoleValueNatural(m_sortRole
)) {
1233 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1235 const QByteArray role
= roleForType(m_sortRole
);
1236 return a
->values
.value(role
).toString() < b
->values
.value(role
).toString();
1238 parallelMergeSort(newItems
.begin(), newItems
.end(), lambdaLessThan
, QThread::idealThreadCount());
1242 sort(newItems
.begin(), newItems
.end());
1244 #ifdef KFILEITEMMODEL_DEBUG
1245 qCDebug(DolphinDebug
) << "[TIME] Sorting:" << timer
.elapsed();
1248 KItemRangeList itemRanges
;
1249 const int existingItemCount
= m_itemData
.count();
1250 const int newItemCount
= newItems
.count();
1251 const int totalItemCount
= existingItemCount
+ newItemCount
;
1253 if (existingItemCount
== 0) {
1254 // Optimization for the common special case that there are no
1255 // items in the model yet. Happens, e.g., when entering a folder.
1256 m_itemData
= newItems
;
1257 itemRanges
<< KItemRange(0, newItemCount
);
1259 m_itemData
.reserve(totalItemCount
);
1260 for (int i
= existingItemCount
; i
< totalItemCount
; ++i
) {
1261 m_itemData
.append(nullptr);
1264 // We build the new list m_itemData in reverse order to minimize
1265 // the number of moves and guarantee O(N) complexity.
1266 int targetIndex
= totalItemCount
- 1;
1267 int sourceIndexExistingItems
= existingItemCount
- 1;
1268 int sourceIndexNewItems
= newItemCount
- 1;
1272 while (sourceIndexNewItems
>= 0) {
1273 ItemData
* newItem
= newItems
.at(sourceIndexNewItems
);
1274 if (sourceIndexExistingItems
>= 0 && lessThan(newItem
, m_itemData
.at(sourceIndexExistingItems
), m_collator
)) {
1275 // Move an existing item to its new position. If any new items
1276 // are behind it, push the item range to itemRanges.
1277 if (rangeCount
> 0) {
1278 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1282 m_itemData
[targetIndex
] = m_itemData
.at(sourceIndexExistingItems
);
1283 --sourceIndexExistingItems
;
1285 // Insert a new item into the list.
1287 m_itemData
[targetIndex
] = newItem
;
1288 --sourceIndexNewItems
;
1293 // Push the final item range to itemRanges.
1294 if (rangeCount
> 0) {
1295 itemRanges
<< KItemRange(sourceIndexExistingItems
+ 1, rangeCount
);
1298 // Note that itemRanges is still sorted in reverse order.
1299 std::reverse(itemRanges
.begin(), itemRanges
.end());
1302 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1303 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1306 Q_EMIT
itemsInserted(itemRanges
);
1308 #ifdef KFILEITEMMODEL_DEBUG
1309 qCDebug(DolphinDebug
) << "[TIME] Inserting of" << newItems
.count() << "items:" << timer
.elapsed();
1313 void KFileItemModel::removeItems(const KItemRangeList
& itemRanges
, RemoveItemsBehavior behavior
)
1315 if (itemRanges
.isEmpty()) {
1321 // Step 1: Remove the items from m_itemData, and free the ItemData.
1322 int removedItemsCount
= 0;
1323 for (const KItemRange
& range
: itemRanges
) {
1324 removedItemsCount
+= range
.count
;
1326 for (int index
= range
.index
; index
< range
.index
+ range
.count
; ++index
) {
1327 if (behavior
== DeleteItemData
) {
1328 delete m_itemData
.at(index
);
1331 m_itemData
[index
] = nullptr;
1335 // Step 2: Remove the ItemData pointers from the list m_itemData.
1336 int target
= itemRanges
.at(0).index
;
1337 int source
= itemRanges
.at(0).index
+ itemRanges
.at(0).count
;
1340 const int oldItemDataCount
= m_itemData
.count();
1341 while (source
< oldItemDataCount
) {
1342 m_itemData
[target
] = m_itemData
[source
];
1346 if (nextRange
< itemRanges
.count() && source
== itemRanges
.at(nextRange
).index
) {
1347 // Skip the items in the next removed range.
1348 source
+= itemRanges
.at(nextRange
).count
;
1353 m_itemData
.erase(m_itemData
.end() - removedItemsCount
, m_itemData
.end());
1355 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1356 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1359 Q_EMIT
itemsRemoved(itemRanges
);
1362 QList
<KFileItemModel::ItemData
*> KFileItemModel::createItemDataList(const QUrl
& parentUrl
, const KFileItemList
& items
) const
1364 if (m_sortRole
== TypeRole
) {
1365 // Try to resolve the MIME-types synchronously to prevent a reordering of
1366 // the items when sorting by type (per default MIME-types are resolved
1367 // asynchronously by KFileItemModelRolesUpdater).
1368 determineMimeTypes(items
, 200);
1371 const int parentIndex
= index(parentUrl
);
1372 ItemData
* parentItem
= parentIndex
< 0 ? nullptr : m_itemData
.at(parentIndex
);
1374 QList
<ItemData
*> itemDataList
;
1375 itemDataList
.reserve(items
.count());
1377 for (const KFileItem
& item
: items
) {
1378 ItemData
* itemData
= new ItemData();
1379 itemData
->item
= item
;
1380 itemData
->parent
= parentItem
;
1381 itemDataList
.append(itemData
);
1384 return itemDataList
;
1387 void KFileItemModel::prepareItemsForSorting(QList
<ItemData
*>& itemDataList
)
1389 switch (m_sortRole
) {
1390 case PermissionsRole
:
1393 case DestinationRole
:
1395 case DeletionTimeRole
:
1396 // These roles can be determined with retrieveData, and they have to be stored
1397 // in the QHash "values" for the sorting.
1398 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1399 if (itemData
->values
.isEmpty()) {
1400 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1406 // At least store the data including the file type for items with known MIME type.
1407 for (ItemData
* itemData
: qAsConst(itemDataList
)) {
1408 if (itemData
->values
.isEmpty()) {
1409 const KFileItem item
= itemData
->item
;
1410 if (item
.isDir() || item
.isMimeTypeKnown()) {
1411 itemData
->values
= retrieveData(itemData
->item
, itemData
->parent
);
1418 // The other roles are either resolved by KFileItemModelRolesUpdater
1419 // (this includes the SizeRole for directories), or they do not need
1420 // to be stored in the QHash "values" for sorting because the data can
1421 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1427 int KFileItemModel::expandedParentsCount(const ItemData
* data
)
1429 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1430 // if the corresponding item is expanded, and it is not a top-level item.
1431 const ItemData
* parent
= data
->parent
;
1433 if (parent
->parent
) {
1434 Q_ASSERT(parent
->values
.contains("expandedParentsCount"));
1435 return parent
->values
.value("expandedParentsCount").toInt() + 1;
1444 void KFileItemModel::removeExpandedItems()
1446 QVector
<int> indexesToRemove
;
1448 const int maxIndex
= m_itemData
.count() - 1;
1449 for (int i
= 0; i
<= maxIndex
; ++i
) {
1450 const ItemData
* itemData
= m_itemData
.at(i
);
1451 if (itemData
->parent
) {
1452 indexesToRemove
.append(i
);
1456 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove
), DeleteItemData
);
1457 m_expandedDirs
.clear();
1459 // Also remove all filtered items which have a parent.
1460 QHash
<KFileItem
, ItemData
*>::iterator it
= m_filteredItems
.begin();
1461 const QHash
<KFileItem
, ItemData
*>::iterator end
= m_filteredItems
.end();
1464 if (it
.value()->parent
) {
1466 it
= m_filteredItems
.erase(it
);
1473 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList
& itemRanges
, const QSet
<QByteArray
>& changedRoles
)
1475 Q_EMIT
itemsChanged(itemRanges
, changedRoles
);
1477 // Trigger a resorting if necessary. Note that this can happen even if the sort
1478 // role has not changed at all because the file name can be used as a fallback.
1479 if (changedRoles
.contains(sortRole()) || changedRoles
.contains(roleForType(NameRole
))) {
1480 for (const KItemRange
& range
: itemRanges
) {
1481 bool needsResorting
= false;
1483 const int first
= range
.index
;
1484 const int last
= range
.index
+ range
.count
- 1;
1486 // Resorting the model is necessary if
1487 // (a) The first item in the range is "lessThan" its predecessor,
1488 // (b) the successor of the last item is "lessThan" the last item, or
1489 // (c) the internal order of the items in the range is incorrect.
1491 && lessThan(m_itemData
.at(first
), m_itemData
.at(first
- 1), m_collator
)) {
1492 needsResorting
= true;
1493 } else if (last
< count() - 1
1494 && lessThan(m_itemData
.at(last
+ 1), m_itemData
.at(last
), m_collator
)) {
1495 needsResorting
= true;
1497 for (int index
= first
; index
< last
; ++index
) {
1498 if (lessThan(m_itemData
.at(index
+ 1), m_itemData
.at(index
), m_collator
)) {
1499 needsResorting
= true;
1505 if (needsResorting
) {
1506 m_resortAllItemsTimer
->start();
1512 if (groupedSorting() && changedRoles
.contains(sortRole())) {
1513 // The position is still correct, but the groups might have changed
1514 // if the changed item is either the first or the last item in a
1516 // In principle, we could try to find out if the item really is the
1517 // first or last one in its group and then update the groups
1518 // (possibly with a delayed timer to make sure that we don't
1519 // re-calculate the groups very often if items are updated one by
1520 // one), but starting m_resortAllItemsTimer is easier.
1521 m_resortAllItemsTimer
->start();
1525 void KFileItemModel::resetRoles()
1527 for (int i
= 0; i
< RolesCount
; ++i
) {
1528 m_requestRole
[i
] = false;
1532 KFileItemModel::RoleType
KFileItemModel::typeForRole(const QByteArray
& role
) const
1534 static QHash
<QByteArray
, RoleType
> roles
;
1535 if (roles
.isEmpty()) {
1536 // Insert user visible roles that can be accessed with
1537 // KFileItemModel::roleInformation()
1539 const RoleInfoMap
* map
= rolesInfoMap(count
);
1540 for (int i
= 0; i
< count
; ++i
) {
1541 roles
.insert(map
[i
].role
, map
[i
].roleType
);
1544 // Insert internal roles (take care to synchronize the implementation
1545 // with KFileItemModel::roleForType() in case if a change is done).
1546 roles
.insert("isDir", IsDirRole
);
1547 roles
.insert("isLink", IsLinkRole
);
1548 roles
.insert("isHidden", IsHiddenRole
);
1549 roles
.insert("isExpanded", IsExpandedRole
);
1550 roles
.insert("isExpandable", IsExpandableRole
);
1551 roles
.insert("expandedParentsCount", ExpandedParentsCountRole
);
1553 Q_ASSERT(roles
.count() == RolesCount
);
1556 return roles
.value(role
, NoRole
);
1559 QByteArray
KFileItemModel::roleForType(RoleType roleType
) const
1561 static QHash
<RoleType
, QByteArray
> roles
;
1562 if (roles
.isEmpty()) {
1563 // Insert user visible roles that can be accessed with
1564 // KFileItemModel::roleInformation()
1566 const RoleInfoMap
* map
= rolesInfoMap(count
);
1567 for (int i
= 0; i
< count
; ++i
) {
1568 roles
.insert(map
[i
].roleType
, map
[i
].role
);
1571 // Insert internal roles (take care to synchronize the implementation
1572 // with KFileItemModel::typeForRole() in case if a change is done).
1573 roles
.insert(IsDirRole
, "isDir");
1574 roles
.insert(IsLinkRole
, "isLink");
1575 roles
.insert(IsHiddenRole
, "isHidden");
1576 roles
.insert(IsExpandedRole
, "isExpanded");
1577 roles
.insert(IsExpandableRole
, "isExpandable");
1578 roles
.insert(ExpandedParentsCountRole
, "expandedParentsCount");
1580 Q_ASSERT(roles
.count() == RolesCount
);
1583 return roles
.value(roleType
);
1586 QHash
<QByteArray
, QVariant
> KFileItemModel::retrieveData(const KFileItem
& item
, const ItemData
* parent
) const
1588 // It is important to insert only roles that are fast to retrieve. E.g.
1589 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1590 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1591 QHash
<QByteArray
, QVariant
> data
;
1592 data
.insert(sharedValue("url"), item
.url());
1594 const bool isDir
= item
.isDir();
1595 if (m_requestRole
[IsDirRole
] && isDir
) {
1596 data
.insert(sharedValue("isDir"), true);
1599 if (m_requestRole
[IsLinkRole
] && item
.isLink()) {
1600 data
.insert(sharedValue("isLink"), true);
1603 if (m_requestRole
[IsHiddenRole
]) {
1604 data
.insert(sharedValue("isHidden"), item
.isHidden());
1607 if (m_requestRole
[NameRole
]) {
1608 data
.insert(sharedValue("text"), item
.text());
1611 if (m_requestRole
[SizeRole
] && !isDir
) {
1612 data
.insert(sharedValue("size"), item
.size());
1615 if (m_requestRole
[ModificationTimeRole
]) {
1616 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1617 // having several thousands of items. Instead read the raw number from UDSEntry directly
1618 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1619 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1620 data
.insert(sharedValue("modificationtime"), dateTime
);
1623 if (m_requestRole
[CreationTimeRole
]) {
1624 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1625 // having several thousands of items. Instead read the raw number from UDSEntry directly
1626 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1627 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1628 data
.insert(sharedValue("creationtime"), dateTime
);
1631 if (m_requestRole
[AccessTimeRole
]) {
1632 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1633 // having several thousands of items. Instead read the raw number from UDSEntry directly
1634 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1635 const long long dateTime
= item
.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME
, -1);
1636 data
.insert(sharedValue("accesstime"), dateTime
);
1639 if (m_requestRole
[PermissionsRole
]) {
1640 data
.insert(sharedValue("permissions"), item
.permissionsString());
1643 if (m_requestRole
[OwnerRole
]) {
1644 data
.insert(sharedValue("owner"), item
.user());
1647 if (m_requestRole
[GroupRole
]) {
1648 data
.insert(sharedValue("group"), item
.group());
1651 if (m_requestRole
[DestinationRole
]) {
1652 QString destination
= item
.linkDest();
1653 if (destination
.isEmpty()) {
1654 destination
= QLatin1Char('-');
1656 data
.insert(sharedValue("destination"), destination
);
1659 if (m_requestRole
[PathRole
]) {
1661 if (item
.url().scheme() == QLatin1String("trash")) {
1662 path
= item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
);
1664 // For performance reasons cache the home-path in a static QString
1665 // (see QDir::homePath() for more details)
1666 static QString homePath
;
1667 if (homePath
.isEmpty()) {
1668 homePath
= QDir::homePath();
1671 path
= item
.localPath();
1672 if (path
.startsWith(homePath
)) {
1673 path
.replace(0, homePath
.length(), QLatin1Char('~'));
1677 const int index
= path
.lastIndexOf(item
.text());
1678 path
= path
.mid(0, index
- 1);
1679 data
.insert(sharedValue("path"), path
);
1682 if (m_requestRole
[DeletionTimeRole
]) {
1683 QDateTime deletionTime
;
1684 if (item
.url().scheme() == QLatin1String("trash")) {
1685 deletionTime
= QDateTime::fromString(item
.entry().stringValue(KIO::UDSEntry::UDS_EXTRA
+ 1), Qt::ISODate
);
1687 data
.insert(sharedValue("deletiontime"), deletionTime
);
1690 if (m_requestRole
[IsExpandableRole
] && isDir
) {
1691 data
.insert(sharedValue("isExpandable"), true);
1694 if (m_requestRole
[ExpandedParentsCountRole
]) {
1696 const int level
= expandedParentsCount(parent
) + 1;
1697 data
.insert(sharedValue("expandedParentsCount"), level
);
1701 if (item
.isMimeTypeKnown()) {
1702 QString iconName
= item
.iconName();
1703 if (!QIcon::hasThemeIcon(iconName
)) {
1704 QMimeType mimeType
= QMimeDatabase().mimeTypeForName(item
.mimetype());
1705 iconName
= mimeType
.genericIconName();
1708 data
.insert(sharedValue("iconName"), iconName
);
1710 if (m_requestRole
[TypeRole
]) {
1711 data
.insert(sharedValue("type"), item
.mimeComment());
1713 } else if (m_requestRole
[TypeRole
] && isDir
) {
1714 static const QString folderMimeType
= item
.mimeComment();
1715 data
.insert(sharedValue("type"), folderMimeType
);
1721 bool KFileItemModel::lessThan(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1725 if (a
->parent
!= b
->parent
) {
1726 const int expansionLevelA
= expandedParentsCount(a
);
1727 const int expansionLevelB
= expandedParentsCount(b
);
1729 // If b has a higher expansion level than a, check if a is a parent
1730 // of b, and make sure that both expansion levels are equal otherwise.
1731 for (int i
= expansionLevelB
; i
> expansionLevelA
; --i
) {
1732 if (b
->parent
== a
) {
1738 // If a has a higher expansion level than a, check if b is a parent
1739 // of a, and make sure that both expansion levels are equal otherwise.
1740 for (int i
= expansionLevelA
; i
> expansionLevelB
; --i
) {
1741 if (a
->parent
== b
) {
1747 Q_ASSERT(expandedParentsCount(a
) == expandedParentsCount(b
));
1749 // Compare the last parents of a and b which are different.
1750 while (a
->parent
!= b
->parent
) {
1756 if (m_sortDirsFirst
|| (DetailsModeSettings::directorySizeCount() && m_sortRole
== SizeRole
)) {
1757 const bool isDirA
= a
->item
.isDir();
1758 const bool isDirB
= b
->item
.isDir();
1759 if (isDirA
&& !isDirB
) {
1761 } else if (!isDirA
&& isDirB
) {
1766 result
= sortRoleCompare(a
, b
, collator
);
1768 return (sortOrder() == Qt::AscendingOrder
) ? result
< 0 : result
> 0;
1771 void KFileItemModel::sort(const QList
<KFileItemModel::ItemData
*>::iterator
&begin
,
1772 const QList
<KFileItemModel::ItemData
*>::iterator
&end
) const
1774 auto lambdaLessThan
= [&] (const KFileItemModel::ItemData
* a
, const KFileItemModel::ItemData
* b
)
1776 return lessThan(a
, b
, m_collator
);
1779 if (m_sortRole
== NameRole
|| isRoleValueNatural(m_sortRole
)) {
1780 // Sorting by string can be expensive, in particular if natural sorting is
1781 // enabled. Use all CPU cores to speed up the sorting process.
1782 static const int numberOfThreads
= QThread::idealThreadCount();
1783 parallelMergeSort(begin
, end
, lambdaLessThan
, numberOfThreads
);
1785 // Sorting by other roles is quite fast. Use only one thread to prevent
1786 // problems caused by non-reentrant comparison functions, see
1787 // https://bugs.kde.org/show_bug.cgi?id=312679
1788 mergeSort(begin
, end
, lambdaLessThan
);
1792 int KFileItemModel::sortRoleCompare(const ItemData
* a
, const ItemData
* b
, const QCollator
& collator
) const
1794 // This function must never return 0, because that would break stable
1795 // sorting, which leads to all kinds of bugs.
1796 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1797 // If two items have equal sort values, let the fallbacks at the bottom of
1798 // the function handle it.
1799 const KFileItem
& itemA
= a
->item
;
1800 const KFileItem
& itemB
= b
->item
;
1804 switch (m_sortRole
) {
1806 // The name role is handled as default fallback after the switch
1810 if (DetailsModeSettings::directorySizeCount() && itemA
.isDir()) {
1811 // folders first then
1812 // items A and B are folders thanks to lessThan checks
1813 auto valueA
= a
->values
.value("count");
1814 auto valueB
= b
->values
.value("count");
1815 if (valueA
.isNull()) {
1816 if (!valueB
.isNull()) {
1819 } else if (valueB
.isNull()) {
1822 if (valueA
.toLongLong() < valueB
.toLongLong()) {
1824 } else if (valueA
.toLongLong() > valueB
.toLongLong()) {
1831 KIO::filesize_t sizeA
= 0;
1832 if (itemA
.isDir()) {
1833 sizeA
= a
->values
.value("size").toULongLong();
1835 sizeA
= itemA
.size();
1837 KIO::filesize_t sizeB
= 0;
1838 if (itemB
.isDir()) {
1839 sizeB
= b
->values
.value("size").toULongLong();
1841 sizeB
= itemB
.size();
1843 if (sizeA
< sizeB
) {
1845 } else if (sizeA
> sizeB
) {
1851 case ModificationTimeRole
: {
1852 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1853 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME
, -1);
1854 if (dateTimeA
< dateTimeB
) {
1856 } else if (dateTimeA
> dateTimeB
) {
1862 case CreationTimeRole
: {
1863 const long long dateTimeA
= itemA
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1864 const long long dateTimeB
= itemB
.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME
, -1);
1865 if (dateTimeA
< dateTimeB
) {
1867 } else if (dateTimeA
> dateTimeB
) {
1873 case DeletionTimeRole
: {
1874 const QDateTime dateTimeA
= a
->values
.value("deletiontime").toDateTime();
1875 const QDateTime dateTimeB
= b
->values
.value("deletiontime").toDateTime();
1876 if (dateTimeA
< dateTimeB
) {
1878 } else if (dateTimeA
> dateTimeB
) {
1890 case ReleaseYearRole
: {
1891 result
= a
->values
.value(roleForType(m_sortRole
)).toInt() - b
->values
.value(roleForType(m_sortRole
)).toInt();
1896 const QByteArray role
= roleForType(m_sortRole
);
1897 const QString roleValueA
= a
->values
.value(role
).toString();
1898 const QString roleValueB
= b
->values
.value(role
).toString();
1899 if (!roleValueA
.isEmpty() && roleValueB
.isEmpty()) {
1901 } else if (roleValueA
.isEmpty() && !roleValueB
.isEmpty()) {
1903 } else if (isRoleValueNatural(m_sortRole
)) {
1904 result
= stringCompare(roleValueA
, roleValueB
, collator
);
1906 result
= QString::compare(roleValueA
, roleValueB
);
1914 // The current sort role was sufficient to define an order
1918 // Fallback #1: Compare the text of the items
1919 result
= stringCompare(itemA
.text(), itemB
.text(), collator
);
1924 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1925 result
= stringCompare(itemA
.name(), itemB
.name(), collator
);
1930 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1931 // equal. In this case a comparison of the URL is done which is unique in all cases
1932 // within KDirLister.
1933 return QString::compare(itemA
.url().url(), itemB
.url().url(), Qt::CaseSensitive
);
1936 int KFileItemModel::stringCompare(const QString
& a
, const QString
& b
, const QCollator
& collator
) const
1938 QMutexLocker
collatorLock(s_collatorMutex());
1940 if (m_naturalSorting
) {
1941 return collator
.compare(a
, b
);
1944 const int result
= QString::compare(a
, b
, collator
.caseSensitivity());
1945 if (result
!= 0 || collator
.caseSensitivity() == Qt::CaseSensitive
) {
1946 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1947 // comparison, still a deterministic sort order is required. A case sensitive
1948 // comparison is done as fallback.
1952 return QString::compare(a
, b
, Qt::CaseSensitive
);
1955 QList
<QPair
<int, QVariant
> > KFileItemModel::nameRoleGroups() const
1957 Q_ASSERT(!m_itemData
.isEmpty());
1959 const int maxIndex
= count() - 1;
1960 QList
<QPair
<int, QVariant
> > groups
;
1964 for (int i
= 0; i
<= maxIndex
; ++i
) {
1965 if (isChildItem(i
)) {
1969 const QString name
= m_itemData
.at(i
)->item
.text();
1971 // Use the first character of the name as group indication
1972 QChar newFirstChar
= name
.at(0).toUpper();
1973 if (newFirstChar
== QLatin1Char('~') && name
.length() > 1) {
1974 newFirstChar
= name
.at(1).toUpper();
1977 if (firstChar
!= newFirstChar
) {
1978 QString newGroupValue
;
1979 if (newFirstChar
.isLetter()) {
1981 if (m_collator
.compare(newFirstChar
, QChar(QLatin1Char('A'))) >= 0 && m_collator
.compare(newFirstChar
, QChar(QLatin1Char('Z'))) <= 0) {
1982 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
1984 // Try to find a matching group in the range 'A' to 'Z'.
1985 static std::vector
<QChar
> lettersAtoZ
;
1986 lettersAtoZ
.reserve('Z' - 'A' + 1);
1987 if (lettersAtoZ
.empty()) {
1988 for (char c
= 'A'; c
<= 'Z'; ++c
) {
1989 lettersAtoZ
.push_back(QLatin1Char(c
));
1993 auto localeAwareLessThan
= [this](QChar c1
, QChar c2
) -> bool {
1994 return m_collator
.compare(c1
, c2
) < 0;
1997 std::vector
<QChar
>::iterator it
= std::lower_bound(lettersAtoZ
.begin(), lettersAtoZ
.end(), newFirstChar
, localeAwareLessThan
);
1998 if (it
!= lettersAtoZ
.end()) {
1999 if (localeAwareLessThan(newFirstChar
, *it
)) {
2000 // newFirstChar belongs to the group preceding *it.
2001 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2004 newGroupValue
= *it
;
2008 // Symbols from non Latin-based scripts
2009 newGroupValue
= newFirstChar
;
2011 } else if (newFirstChar
>= QLatin1Char('0') && newFirstChar
<= QLatin1Char('9')) {
2012 // Apply group '0 - 9' for any name that starts with a digit
2013 newGroupValue
= i18nc("@title:group Groups that start with a digit", "0 - 9");
2015 newGroupValue
= i18nc("@title:group", "Others");
2018 if (newGroupValue
!= groupValue
) {
2019 groupValue
= newGroupValue
;
2020 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2023 firstChar
= newFirstChar
;
2029 QList
<QPair
<int, QVariant
> > KFileItemModel::sizeRoleGroups() const
2031 Q_ASSERT(!m_itemData
.isEmpty());
2033 const int maxIndex
= count() - 1;
2034 QList
<QPair
<int, QVariant
> > groups
;
2037 for (int i
= 0; i
<= maxIndex
; ++i
) {
2038 if (isChildItem(i
)) {
2042 const KFileItem
& item
= m_itemData
.at(i
)->item
;
2043 KIO::filesize_t fileSize
= !item
.isNull() ? item
.size() : ~0U;
2044 QString newGroupValue
;
2045 if (!item
.isNull() && item
.isDir()) {
2046 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst
) {
2047 newGroupValue
= i18nc("@title:group Size", "Folders");
2049 fileSize
= m_itemData
.at(i
)->values
.value("size").toULongLong();
2053 if (newGroupValue
.isEmpty()) {
2054 if (fileSize
< 5 * 1024 * 1024) { // < 5 MB
2055 newGroupValue
= i18nc("@title:group Size", "Small");
2056 } else if (fileSize
< 10 * 1024 * 1024) { // < 10 MB
2057 newGroupValue
= i18nc("@title:group Size", "Medium");
2059 newGroupValue
= i18nc("@title:group Size", "Big");
2063 if (newGroupValue
!= groupValue
) {
2064 groupValue
= newGroupValue
;
2065 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2072 QList
<QPair
<int, QVariant
> > KFileItemModel::timeRoleGroups(const std::function
<QDateTime(const ItemData
*)> &fileTimeCb
) const
2074 Q_ASSERT(!m_itemData
.isEmpty());
2076 const int maxIndex
= count() - 1;
2077 QList
<QPair
<int, QVariant
> > groups
;
2079 const QDate currentDate
= QDate::currentDate();
2081 QDate previousFileDate
;
2083 for (int i
= 0; i
<= maxIndex
; ++i
) {
2084 if (isChildItem(i
)) {
2088 const QDateTime fileTime
= fileTimeCb(m_itemData
.at(i
));
2089 const QDate fileDate
= fileTime
.date();
2090 if (fileDate
== previousFileDate
) {
2091 // The current item is in the same group as the previous item
2094 previousFileDate
= fileDate
;
2096 const int daysDistance
= fileDate
.daysTo(currentDate
);
2098 QString newGroupValue
;
2099 if (currentDate
.year() == fileDate
.year() &&
2100 currentDate
.month() == fileDate
.month()) {
2102 switch (daysDistance
/ 7) {
2104 switch (daysDistance
) {
2105 case 0: newGroupValue
= i18nc("@title:group Date", "Today"); break;
2106 case 1: newGroupValue
= i18nc("@title:group Date", "Yesterday"); break;
2108 newGroupValue
= fileTime
.toString(
2109 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2110 newGroupValue
= i18nc("Can be used to script translation of \"dddd\""
2111 "with context @title:group Date", "%1", newGroupValue
);
2115 newGroupValue
= i18nc("@title:group Date", "One Week Ago");
2118 newGroupValue
= i18nc("@title:group Date", "Two Weeks Ago");
2121 newGroupValue
= i18nc("@title:group Date", "Three Weeks Ago");
2125 newGroupValue
= i18nc("@title:group Date", "Earlier this Month");
2131 const QDate lastMonthDate
= currentDate
.addMonths(-1);
2132 if (lastMonthDate
.year() == fileDate
.year() &&
2133 lastMonthDate
.month() == fileDate
.month()) {
2135 if (daysDistance
== 1) {
2136 const KLocalizedString format
= ki18nc("@title:group Date: "
2137 "MMMM is full month name in current locale, and yyyy is "
2138 "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)");
2139 const QString translatedFormat
= format
.toString();
2140 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2141 newGroupValue
= fileTime
.toString(translatedFormat
);
2142 newGroupValue
= i18nc("Can be used to script translation of "
2143 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2144 "%1", newGroupValue
);
2146 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2147 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2148 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2150 } else if (daysDistance
<= 7) {
2151 newGroupValue
= fileTime
.toString(i18nc("@title:group Date: "
2152 "The week day name: dddd, MMMM is full month name "
2153 "in current locale, and yyyy is full year number.",
2154 "dddd (MMMM, yyyy)"));
2155 newGroupValue
= i18nc("Can be used to script translation of "
2156 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2157 "%1", newGroupValue
);
2158 } else if (daysDistance
<= 7 * 2) {
2159 const KLocalizedString format
= ki18nc("@title:group Date: "
2160 "MMMM is full month name in current locale, and yyyy is "
2161 "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)");
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 "\"'One Week Ago' (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
);
2173 } else if (daysDistance
<= 7 * 3) {
2174 const KLocalizedString format
= ki18nc("@title:group Date: "
2175 "MMMM is full month name in current locale, and yyyy is "
2176 "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)");
2177 const QString translatedFormat
= format
.toString();
2178 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2179 newGroupValue
= fileTime
.toString(translatedFormat
);
2180 newGroupValue
= i18nc("Can be used to script translation of "
2181 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2182 "%1", newGroupValue
);
2184 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2185 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2186 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2188 } else if (daysDistance
<= 7 * 4) {
2189 const KLocalizedString format
= ki18nc("@title:group Date: "
2190 "MMMM is full month name in current locale, and yyyy is "
2191 "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)");
2192 const QString translatedFormat
= format
.toString();
2193 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2194 newGroupValue
= fileTime
.toString(translatedFormat
);
2195 newGroupValue
= i18nc("Can be used to script translation of "
2196 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2197 "%1", newGroupValue
);
2199 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2200 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2201 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2204 const KLocalizedString format
= ki18nc("@title:group Date: "
2205 "MMMM is full month name in current locale, and yyyy is "
2206 "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");
2207 const QString translatedFormat
= format
.toString();
2208 if (translatedFormat
.count(QLatin1Char('\'')) == 2) {
2209 newGroupValue
= fileTime
.toString(translatedFormat
);
2210 newGroupValue
= i18nc("Can be used to script translation of "
2211 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2212 "%1", newGroupValue
);
2214 qCWarning(DolphinDebug
).nospace() << "A wrong translation was found: " << translatedFormat
<< ". Please file a bug report at bugs.kde.org";
2215 const QString untranslatedFormat
= format
.toString({ QLatin1String("en_US") });
2216 newGroupValue
= fileTime
.toString(untranslatedFormat
);
2220 newGroupValue
= fileTime
.toString(i18nc("@title:group "
2221 "The month and year: MMMM is full month name in current locale, "
2222 "and yyyy is full year number", "MMMM, yyyy"));
2223 newGroupValue
= i18nc("Can be used to script translation of "
2224 "\"MMMM, yyyy\" with context @title:group Date",
2225 "%1", newGroupValue
);
2229 if (newGroupValue
!= groupValue
) {
2230 groupValue
= newGroupValue
;
2231 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2238 QList
<QPair
<int, QVariant
> > KFileItemModel::permissionRoleGroups() const
2240 Q_ASSERT(!m_itemData
.isEmpty());
2242 const int maxIndex
= count() - 1;
2243 QList
<QPair
<int, QVariant
> > groups
;
2245 QString permissionsString
;
2247 for (int i
= 0; i
<= maxIndex
; ++i
) {
2248 if (isChildItem(i
)) {
2252 const ItemData
* itemData
= m_itemData
.at(i
);
2253 const QString newPermissionsString
= itemData
->values
.value("permissions").toString();
2254 if (newPermissionsString
== permissionsString
) {
2257 permissionsString
= newPermissionsString
;
2259 const QFileInfo
info(itemData
->item
.url().toLocalFile());
2263 if (info
.permission(QFile::ReadUser
)) {
2264 user
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2266 if (info
.permission(QFile::WriteUser
)) {
2267 user
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2269 if (info
.permission(QFile::ExeUser
)) {
2270 user
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2272 user
= user
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user
.mid(0, user
.count() - 2);
2276 if (info
.permission(QFile::ReadGroup
)) {
2277 group
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2279 if (info
.permission(QFile::WriteGroup
)) {
2280 group
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2282 if (info
.permission(QFile::ExeGroup
)) {
2283 group
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2285 group
= group
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group
.mid(0, group
.count() - 2);
2287 // Set others string
2289 if (info
.permission(QFile::ReadOther
)) {
2290 others
= i18nc("@item:intext Access permission, concatenated", "Read, ");
2292 if (info
.permission(QFile::WriteOther
)) {
2293 others
+= i18nc("@item:intext Access permission, concatenated", "Write, ");
2295 if (info
.permission(QFile::ExeOther
)) {
2296 others
+= i18nc("@item:intext Access permission, concatenated", "Execute, ");
2298 others
= others
.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others
.mid(0, others
.count() - 2);
2300 const QString newGroupValue
= i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user
, group
, others
);
2301 if (newGroupValue
!= groupValue
) {
2302 groupValue
= newGroupValue
;
2303 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2310 QList
<QPair
<int, QVariant
> > KFileItemModel::ratingRoleGroups() const
2312 Q_ASSERT(!m_itemData
.isEmpty());
2314 const int maxIndex
= count() - 1;
2315 QList
<QPair
<int, QVariant
> > groups
;
2317 int groupValue
= -1;
2318 for (int i
= 0; i
<= maxIndex
; ++i
) {
2319 if (isChildItem(i
)) {
2322 const int newGroupValue
= m_itemData
.at(i
)->values
.value("rating", 0).toInt();
2323 if (newGroupValue
!= groupValue
) {
2324 groupValue
= newGroupValue
;
2325 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2332 QList
<QPair
<int, QVariant
> > KFileItemModel::genericStringRoleGroups(const QByteArray
& role
) const
2334 Q_ASSERT(!m_itemData
.isEmpty());
2336 const int maxIndex
= count() - 1;
2337 QList
<QPair
<int, QVariant
> > groups
;
2339 bool isFirstGroupValue
= true;
2341 for (int i
= 0; i
<= maxIndex
; ++i
) {
2342 if (isChildItem(i
)) {
2345 const QString newGroupValue
= m_itemData
.at(i
)->values
.value(role
).toString();
2346 if (newGroupValue
!= groupValue
|| isFirstGroupValue
) {
2347 groupValue
= newGroupValue
;
2348 groups
.append(QPair
<int, QVariant
>(i
, newGroupValue
));
2349 isFirstGroupValue
= false;
2356 void KFileItemModel::emitSortProgress(int resolvedCount
)
2358 // Be tolerant against a resolvedCount with a wrong range.
2359 // Although there should not be a case where KFileItemModelRolesUpdater
2360 // (= caller) provides a wrong range, it is important to emit
2361 // a useful progress information even if there is an unexpected
2362 // implementation issue.
2364 const int itemCount
= count();
2365 if (resolvedCount
>= itemCount
) {
2366 m_sortingProgressPercent
= -1;
2367 if (m_resortAllItemsTimer
->isActive()) {
2368 m_resortAllItemsTimer
->stop();
2372 Q_EMIT
directorySortingProgress(100);
2373 } else if (itemCount
> 0) {
2374 resolvedCount
= qBound(0, resolvedCount
, itemCount
);
2376 const int progress
= resolvedCount
* 100 / itemCount
;
2377 if (m_sortingProgressPercent
!= progress
) {
2378 m_sortingProgressPercent
= progress
;
2379 Q_EMIT
directorySortingProgress(progress
);
2384 const KFileItemModel::RoleInfoMap
* KFileItemModel::rolesInfoMap(int& count
)
2386 static const RoleInfoMap rolesInfoMap
[] = {
2387 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2388 { nullptr, NoRole
, nullptr, nullptr, nullptr, nullptr, false, false },
2389 { "text", NameRole
, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2390 { "size", SizeRole
, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2391 { "modificationtime", ModificationTimeRole
, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2392 { "creationtime", CreationTimeRole
, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2393 { "accesstime", AccessTimeRole
, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2394 { "type", TypeRole
, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2395 { "rating", RatingRole
, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2396 { "tags", TagsRole
, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2397 { "comment", CommentRole
, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2398 { "title", TitleRole
, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2399 { "wordCount", WordCountRole
, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2400 { "lineCount", LineCountRole
, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2401 { "imageDateTime", ImageDateTimeRole
, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2402 { "width", WidthRole
, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2403 { "height", HeightRole
, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2404 { "orientation", OrientationRole
, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2405 { "artist", ArtistRole
, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2406 { "genre", GenreRole
, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2407 { "album", AlbumRole
, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2408 { "duration", DurationRole
, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2409 { "bitrate", BitrateRole
, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2410 { "track", TrackRole
, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2411 { "releaseYear", ReleaseYearRole
, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2412 { "aspectRatio", AspectRatioRole
, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2413 { "frameRate", FrameRateRole
, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2414 { "path", PathRole
, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2415 { "deletiontime", DeletionTimeRole
, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2416 { "destination", DestinationRole
, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2417 { "originUrl", OriginUrlRole
, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2418 { "permissions", PermissionsRole
, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2419 { "owner", OwnerRole
, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2420 { "group", GroupRole
, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2423 count
= sizeof(rolesInfoMap
) / sizeof(RoleInfoMap
);
2424 return rolesInfoMap
;
2427 void KFileItemModel::determineMimeTypes(const KFileItemList
& items
, int timeout
)
2429 QElapsedTimer timer
;
2431 for (const KFileItem
& item
: items
) {
2432 // Only determine mime types for files here. For directories,
2433 // KFileItem::determineMimeType() reads the .directory file inside to
2434 // load the icon, but this is not necessary at all if we just need the
2435 // type. Some special code for setting the correct mime type for
2436 // directories is in retrieveData().
2437 if (!item
.isDir()) {
2438 item
.determineMimeType();
2441 if (timer
.elapsed() > timeout
) {
2442 // Don't block the user interface, let the remaining items
2443 // be resolved asynchronously.
2449 QByteArray
KFileItemModel::sharedValue(const QByteArray
& value
)
2451 static QSet
<QByteArray
> pool
;
2452 const QSet
<QByteArray
>::const_iterator it
= pool
.constFind(value
);
2454 if (it
!= pool
.constEnd()) {
2462 bool KFileItemModel::isConsistent() const
2464 // m_items may contain less items than m_itemData because m_items
2465 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2466 if (m_items
.count() > m_itemData
.count()) {
2470 for (int i
= 0, iMax
= count(); i
< iMax
; ++i
) {
2471 // Check if m_items and m_itemData are consistent.
2472 const KFileItem item
= fileItem(i
);
2473 if (item
.isNull()) {
2474 qCWarning(DolphinDebug
) << "Item" << i
<< "is null";
2478 const int itemIndex
= index(item
);
2479 if (itemIndex
!= i
) {
2480 qCWarning(DolphinDebug
) << "Item" << i
<< "has a wrong index:" << itemIndex
;
2484 // Check if the items are sorted correctly.
2485 if (i
> 0 && !lessThan(m_itemData
.at(i
- 1), m_itemData
.at(i
), m_collator
)) {
2486 qCWarning(DolphinDebug
) << "The order of items" << i
- 1 << "and" << i
<< "is wrong:"
2487 << fileItem(i
- 1) << fileItem(i
);
2491 // Check if all parent-child relationships are consistent.
2492 const ItemData
* data
= m_itemData
.at(i
);
2493 const ItemData
* parent
= data
->parent
;
2495 if (expandedParentsCount(data
) != expandedParentsCount(parent
) + 1) {
2496 qCWarning(DolphinDebug
) << "expandedParentsCount is inconsistent for parent" << parent
->item
<< "and child" << data
->item
;
2500 const int parentIndex
= index(parent
->item
);
2501 if (parentIndex
>= i
) {
2502 qCWarning(DolphinDebug
) << "Index" << parentIndex
<< "of parent" << parent
->item
<< "is not smaller than index" << i
<< "of child" << data
->item
;
2511 void KFileItemModel::slotListerError(KIO::Job
*job
)
2513 if (job
->error() == KIO::ERR_IS_FILE
) {
2514 if (auto *listJob
= qobject_cast
<KIO::ListJob
*>(job
)) {
2515 Q_EMIT
urlIsFileError(listJob
->url());
2518 const QString errorString
= job
->errorString();
2519 Q_EMIT
errorMessage(!errorString
.isEmpty() ? errorString
: i18nc("@info:status", "Unknown error."));