]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
natural sort: exclude extension when comparing filenames
[dolphin.git] / src / kitemviews / kfileitemmodel.cpp
1 /*
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>
5 *
6 * SPDX-License-Identifier: GPL-2.0-or-later
7 */
8
9 #include "kfileitemmodel.h"
10
11 #include "dolphin_contentdisplaysettings.h"
12 #include "dolphin_generalsettings.h"
13 #include "dolphindebug.h"
14 #include "private/kfileitemmodelsortalgorithm.h"
15 #include "views/draganddrophelper.h"
16
17 #include <KDirLister>
18 #include <KIO/Job>
19 #include <KIO/ListJob>
20 #include <KLocalizedString>
21 #include <KUrlMimeData>
22
23 #ifndef QT_NO_ACCESSIBILITY
24 #include <QAccessible>
25 #endif
26 #include <QElapsedTimer>
27 #include <QIcon>
28 #include <QMimeData>
29 #include <QMimeDatabase>
30 #include <QRecursiveMutex>
31 #include <QTimer>
32 #include <QWidget>
33 #include <klazylocalizedstring.h>
34
35 Q_GLOBAL_STATIC(QRecursiveMutex, s_collatorMutex)
36
37 // #define KFILEITEMMODEL_DEBUG
38
39 KFileItemModel::KFileItemModel(QObject *parent)
40 : KItemModelBase("text", parent)
41 , m_dirLister(nullptr)
42 , m_sortDirsFirst(true)
43 , m_sortHiddenLast(false)
44 , m_sortRole(NameRole)
45 , m_sortingProgressPercent(-1)
46 , m_roles()
47 , m_itemData()
48 , m_items()
49 , m_filter()
50 , m_filteredItems()
51 , m_requestRole()
52 , m_maximumUpdateIntervalTimer(nullptr)
53 , m_resortAllItemsTimer(nullptr)
54 , m_pendingItemsToInsert()
55 , m_groups()
56 , m_expandedDirs()
57 , m_urlsToExpand()
58 {
59 m_collator.setNumericMode(true);
60
61 loadSortingSettings();
62
63 m_dirLister = new KDirLister(this);
64 m_dirLister->setAutoErrorHandlingEnabled(false);
65 m_dirLister->setDelayedMimeTypes(true);
66
67 const QWidget *parentWidget = qobject_cast<QWidget *>(parent);
68 if (parentWidget) {
69 m_dirLister->setMainWindow(parentWidget->window());
70 }
71
72 connect(m_dirLister, &KCoreDirLister::started, this, &KFileItemModel::directoryLoadingStarted);
73 connect(m_dirLister, &KCoreDirLister::canceled, this, &KFileItemModel::slotCanceled);
74 connect(m_dirLister, &KCoreDirLister::itemsAdded, this, &KFileItemModel::slotItemsAdded);
75 connect(m_dirLister, &KCoreDirLister::itemsDeleted, this, &KFileItemModel::slotItemsDeleted);
76 connect(m_dirLister, &KCoreDirLister::refreshItems, this, &KFileItemModel::slotRefreshItems);
77 connect(m_dirLister, &KCoreDirLister::clear, this, &KFileItemModel::slotClear);
78 connect(m_dirLister, &KCoreDirLister::infoMessage, this, &KFileItemModel::infoMessage);
79 connect(m_dirLister, &KCoreDirLister::jobError, this, &KFileItemModel::slotListerError);
80 connect(m_dirLister, &KCoreDirLister::percent, this, &KFileItemModel::directoryLoadingProgress);
81 connect(m_dirLister, &KCoreDirLister::redirection, this, &KFileItemModel::directoryRedirection);
82 connect(m_dirLister, &KCoreDirLister::listingDirCompleted, this, &KFileItemModel::slotCompleted);
83
84 // Apply default roles that should be determined
85 resetRoles();
86 m_requestRole[NameRole] = true;
87 m_requestRole[IsDirRole] = true;
88 m_requestRole[IsLinkRole] = true;
89 m_roles.insert("text");
90 m_roles.insert("isDir");
91 m_roles.insert("isLink");
92 m_roles.insert("isHidden");
93
94 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
95 // before the completed() or canceled() signal has been emitted.
96 m_maximumUpdateIntervalTimer = new QTimer(this);
97 m_maximumUpdateIntervalTimer->setInterval(2000);
98 m_maximumUpdateIntervalTimer->setSingleShot(true);
99 connect(m_maximumUpdateIntervalTimer, &QTimer::timeout, this, &KFileItemModel::dispatchPendingItemsToInsert);
100
101 // When changing the value of an item which represents the sort-role a resorting must be
102 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
103 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
104 // resorting is postponed until the timer has been exceeded.
105 m_resortAllItemsTimer = new QTimer(this);
106 m_resortAllItemsTimer->setInterval(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
107 // and sorting too infrequently which leads to users seeing an outdated sort order.
108 m_resortAllItemsTimer->setSingleShot(true);
109 connect(m_resortAllItemsTimer, &QTimer::timeout, this, &KFileItemModel::resortAllItems);
110
111 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged, this, &KFileItemModel::slotSortingChoiceChanged);
112
113 setShowTrashMime(m_dirLister->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
114 }
115
116 KFileItemModel::~KFileItemModel()
117 {
118 qDeleteAll(m_itemData);
119 qDeleteAll(m_filteredItems);
120 qDeleteAll(m_pendingItemsToInsert);
121 }
122
123 void KFileItemModel::loadDirectory(const QUrl &url)
124 {
125 m_dirLister->openUrl(url);
126 }
127
128 void KFileItemModel::refreshDirectory(const QUrl &url)
129 {
130 // Refresh all expanded directories first (Bug 295300)
131 QHashIterator<QUrl, QUrl> expandedDirs(m_expandedDirs);
132 while (expandedDirs.hasNext()) {
133 expandedDirs.next();
134 m_dirLister->openUrl(expandedDirs.value(), KDirLister::Reload);
135 }
136
137 m_dirLister->openUrl(url, KDirLister::Reload);
138
139 Q_EMIT directoryRefreshing();
140 }
141
142 QUrl KFileItemModel::directory() const
143 {
144 return m_dirLister->url();
145 }
146
147 void KFileItemModel::cancelDirectoryLoading()
148 {
149 m_dirLister->stop();
150 }
151
152 int KFileItemModel::count() const
153 {
154 return m_itemData.count();
155 }
156
157 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
158 {
159 if (index >= 0 && index < count()) {
160 ItemData *data = m_itemData.at(index);
161 if (data->values.isEmpty()) {
162 data->values = retrieveData(data->item, data->parent);
163 } else if (data->values.count() <= 2 && data->values.value("isExpanded").toBool()) {
164 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
165 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
166 // so this special request of different behavior can be identified here.
167 bool hasExpandedParentsCount = false;
168 const int expandedParentsCount = data->values.value("expandedParentsCount").toInt(&hasExpandedParentsCount);
169
170 data->values = retrieveData(data->item, data->parent);
171 data->values.insert("isExpanded", true);
172 if (hasExpandedParentsCount) {
173 data->values.insert("expandedParentsCount", expandedParentsCount);
174 }
175 }
176
177 return data->values;
178 }
179 return QHash<QByteArray, QVariant>();
180 }
181
182 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant> &values)
183 {
184 if (index < 0 || index >= count()) {
185 return false;
186 }
187
188 QHash<QByteArray, QVariant> currentValues = data(index);
189
190 // Determine which roles have been changed
191 QSet<QByteArray> changedRoles;
192 QHashIterator<QByteArray, QVariant> it(values);
193 while (it.hasNext()) {
194 it.next();
195 const QByteArray role = sharedValue(it.key());
196 const QVariant value = it.value();
197
198 if (currentValues[role] != value) {
199 currentValues[role] = value;
200 changedRoles.insert(role);
201 }
202 }
203
204 if (changedRoles.isEmpty()) {
205 return false;
206 }
207
208 if (changedRoles.contains("text")) {
209 QUrl url = m_itemData[index]->item.url();
210 m_items.remove(url);
211 url = url.adjusted(QUrl::RemoveFilename);
212 url.setPath(url.path() + currentValues["text"].toString());
213 m_itemData[index]->item.setUrl(url);
214 m_items.insert(url, index);
215
216 if (!changedRoles.contains("url")) {
217 changedRoles.insert("url");
218 currentValues["url"] = url;
219 }
220 }
221 m_itemData[index]->values = currentValues;
222
223 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index, 1), changedRoles);
224
225 return true;
226 }
227
228 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst)
229 {
230 if (dirsFirst != m_sortDirsFirst) {
231 m_sortDirsFirst = dirsFirst;
232 resortAllItems();
233 }
234 }
235
236 bool KFileItemModel::sortDirectoriesFirst() const
237 {
238 return m_sortDirsFirst;
239 }
240
241 void KFileItemModel::setSortHiddenLast(bool hiddenLast)
242 {
243 if (hiddenLast != m_sortHiddenLast) {
244 m_sortHiddenLast = hiddenLast;
245 resortAllItems();
246 }
247 }
248
249 bool KFileItemModel::sortHiddenLast() const
250 {
251 return m_sortHiddenLast;
252 }
253
254 void KFileItemModel::setShowTrashMime(bool showTrashMime)
255 {
256 const auto trashMime = QStringLiteral("application/x-trash");
257 QStringList excludeFilter = m_filter.excludeMimeTypes();
258
259 if (showTrashMime) {
260 excludeFilter.removeAll(trashMime);
261 } else if (!excludeFilter.contains(trashMime)) {
262 excludeFilter.append(trashMime);
263 }
264
265 setExcludeMimeTypeFilter(excludeFilter);
266 }
267
268 void KFileItemModel::scheduleResortAllItems()
269 {
270 if (!m_resortAllItemsTimer->isActive()) {
271 m_resortAllItemsTimer->start();
272 }
273 }
274
275 void KFileItemModel::setShowHiddenFiles(bool show)
276 {
277 m_dirLister->setShowHiddenFiles(show);
278 setShowTrashMime(show || !GeneralSettings::hideXTrashFile());
279 m_dirLister->emitChanges();
280 if (show) {
281 dispatchPendingItemsToInsert();
282 }
283 }
284
285 bool KFileItemModel::showHiddenFiles() const
286 {
287 return m_dirLister->showHiddenFiles();
288 }
289
290 void KFileItemModel::setShowDirectoriesOnly(bool enabled)
291 {
292 m_dirLister->setDirOnlyMode(enabled);
293 }
294
295 bool KFileItemModel::showDirectoriesOnly() const
296 {
297 return m_dirLister->dirOnlyMode();
298 }
299
300 QMimeData *KFileItemModel::createMimeData(const KItemSet &indexes) const
301 {
302 QMimeData *data = new QMimeData();
303
304 // The following code has been taken from KDirModel::mimeData()
305 // (kdelibs/kio/kio/kdirmodel.cpp)
306 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
307 QList<QUrl> urls;
308 QList<QUrl> mostLocalUrls;
309 const ItemData *lastAddedItem = nullptr;
310
311 for (int index : indexes) {
312 const ItemData *itemData = m_itemData.at(index);
313 const ItemData *parent = itemData->parent;
314
315 while (parent && parent != lastAddedItem) {
316 parent = parent->parent;
317 }
318
319 if (parent && parent == lastAddedItem) {
320 // A parent of 'itemData' has been added already.
321 continue;
322 }
323
324 lastAddedItem = itemData;
325 const KFileItem &item = itemData->item;
326 if (!item.isNull()) {
327 urls << item.url();
328
329 bool isLocal;
330 mostLocalUrls << item.mostLocalUrl(&isLocal);
331 }
332 }
333
334 KUrlMimeData::setUrls(urls, mostLocalUrls, data);
335 return data;
336 }
337
338 int KFileItemModel::indexForKeyboardSearch(const QString &text, int startFromIndex) const
339 {
340 startFromIndex = qMax(0, startFromIndex);
341 for (int i = startFromIndex; i < count(); ++i) {
342 if (fileItem(i).text().startsWith(text, Qt::CaseInsensitive)) {
343 return i;
344 }
345 }
346 for (int i = 0; i < startFromIndex; ++i) {
347 if (fileItem(i).text().startsWith(text, Qt::CaseInsensitive)) {
348 return i;
349 }
350 }
351 return -1;
352 }
353
354 bool KFileItemModel::supportsDropping(int index) const
355 {
356 KFileItem item;
357 if (index == -1) {
358 item = rootItem();
359 } else {
360 item = fileItem(index);
361 }
362 return !item.isNull() && DragAndDropHelper::supportsDropping(item);
363 }
364
365 bool KFileItemModel::canEnterOnHover(int index) const
366 {
367 KFileItem item;
368 if (index == -1) {
369 item = rootItem();
370 } else {
371 item = fileItem(index);
372 }
373 return !item.isNull() && (item.isDir() || item.isDesktopFile());
374 }
375
376 QString KFileItemModel::roleDescription(const QByteArray &role) const
377 {
378 static QHash<QByteArray, QString> description;
379 if (description.isEmpty()) {
380 int count = 0;
381 const RoleInfoMap *map = rolesInfoMap(count);
382 for (int i = 0; i < count; ++i) {
383 if (map[i].roleTranslation.isEmpty()) {
384 continue;
385 }
386 description.insert(map[i].role, map[i].roleTranslation.toString());
387 }
388 }
389
390 return description.value(role);
391 }
392
393 QList<QPair<int, QVariant>> KFileItemModel::groups() const
394 {
395 if (!m_itemData.isEmpty() && m_groups.isEmpty()) {
396 #ifdef KFILEITEMMODEL_DEBUG
397 QElapsedTimer timer;
398 timer.start();
399 #endif
400 switch (typeForRole(sortRole())) {
401 case NameRole:
402 m_groups = nameRoleGroups();
403 break;
404 case SizeRole:
405 m_groups = sizeRoleGroups();
406 break;
407 case ModificationTimeRole:
408 m_groups = timeRoleGroups([](const ItemData *item) {
409 return item->item.time(KFileItem::ModificationTime);
410 });
411 break;
412 case CreationTimeRole:
413 m_groups = timeRoleGroups([](const ItemData *item) {
414 return item->item.time(KFileItem::CreationTime);
415 });
416 break;
417 case AccessTimeRole:
418 m_groups = timeRoleGroups([](const ItemData *item) {
419 return item->item.time(KFileItem::AccessTime);
420 });
421 break;
422 case DeletionTimeRole:
423 m_groups = timeRoleGroups([](const ItemData *item) {
424 return item->values.value("deletiontime").toDateTime();
425 });
426 break;
427 case PermissionsRole:
428 m_groups = permissionRoleGroups();
429 break;
430 case RatingRole:
431 m_groups = ratingRoleGroups();
432 break;
433 default:
434 m_groups = genericStringRoleGroups(sortRole());
435 break;
436 }
437
438 #ifdef KFILEITEMMODEL_DEBUG
439 qCDebug(DolphinDebug) << "[TIME] Calculating groups for" << count() << "items:" << timer.elapsed();
440 #endif
441 }
442
443 return m_groups;
444 }
445
446 KFileItem KFileItemModel::fileItem(int index) const
447 {
448 if (index >= 0 && index < count()) {
449 return m_itemData.at(index)->item;
450 }
451
452 return KFileItem();
453 }
454
455 KFileItem KFileItemModel::fileItem(const QUrl &url) const
456 {
457 const int indexForUrl = index(url);
458 if (indexForUrl >= 0) {
459 return m_itemData.at(indexForUrl)->item;
460 }
461 return KFileItem();
462 }
463
464 int KFileItemModel::index(const KFileItem &item) const
465 {
466 return index(item.url());
467 }
468
469 int KFileItemModel::index(const QUrl &url) const
470 {
471 const QUrl urlToFind = url.adjusted(QUrl::StripTrailingSlash);
472
473 const int itemCount = m_itemData.count();
474 int itemsInHash = m_items.count();
475
476 int index = m_items.value(urlToFind, -1);
477 while (index < 0 && itemsInHash < itemCount) {
478 // Not all URLs are stored yet in m_items. We grow m_items until either
479 // urlToFind is found, or all URLs have been stored in m_items.
480 // Note that we do not add the URLs to m_items one by one, but in
481 // larger blocks. After each block, we check if urlToFind is in
482 // m_items. We could in principle compare urlToFind with each URL while
483 // we are going through m_itemData, but comparing two QUrls will,
484 // unlike calling qHash for the URLs, trigger a parsing of the URLs
485 // which costs both CPU cycles and memory.
486 const int blockSize = 1000;
487 const int currentBlockEnd = qMin(itemsInHash + blockSize, itemCount);
488 for (int i = itemsInHash; i < currentBlockEnd; ++i) {
489 const QUrl nextUrl = m_itemData.at(i)->item.url();
490 m_items.insert(nextUrl, i);
491 }
492
493 itemsInHash = currentBlockEnd;
494 index = m_items.value(urlToFind, -1);
495 }
496
497 if (index < 0) {
498 // The item could not be found, even though all items from m_itemData
499 // should be in m_items now. We print some diagnostic information which
500 // might help to find the cause of the problem, but only once. This
501 // prevents that obtaining and printing the debugging information
502 // wastes CPU cycles and floods the shell or .xsession-errors.
503 static bool printDebugInfo = true;
504
505 if (m_items.count() != m_itemData.count() && printDebugInfo) {
506 printDebugInfo = false;
507
508 qCWarning(DolphinDebug) << "The model is in an inconsistent state.";
509 qCWarning(DolphinDebug) << "m_items.count() ==" << m_items.count();
510 qCWarning(DolphinDebug) << "m_itemData.count() ==" << m_itemData.count();
511
512 // Check if there are multiple items with the same URL.
513 QMultiHash<QUrl, int> indexesForUrl;
514 for (int i = 0; i < m_itemData.count(); ++i) {
515 indexesForUrl.insert(m_itemData.at(i)->item.url(), i);
516 }
517
518 const auto uniqueKeys = indexesForUrl.uniqueKeys();
519 for (const QUrl &url : uniqueKeys) {
520 if (indexesForUrl.count(url) > 1) {
521 qCWarning(DolphinDebug) << "Multiple items found with the URL" << url;
522
523 auto it = indexesForUrl.find(url);
524 while (it != indexesForUrl.end() && it.key() == url) {
525 const ItemData *data = m_itemData.at(it.value());
526 qCWarning(DolphinDebug) << "index" << it.value() << ":" << data->item;
527 if (data->parent) {
528 qCWarning(DolphinDebug) << "parent" << data->parent->item;
529 }
530 ++it;
531 }
532 }
533 }
534 }
535 }
536
537 return index;
538 }
539
540 KFileItem KFileItemModel::rootItem() const
541 {
542 return m_dirLister->rootItem();
543 }
544
545 void KFileItemModel::clear()
546 {
547 slotClear();
548 }
549
550 void KFileItemModel::setRoles(const QSet<QByteArray> &roles)
551 {
552 if (m_roles == roles) {
553 return;
554 }
555
556 const QSet<QByteArray> changedRoles = (roles - m_roles) + (m_roles - roles);
557 m_roles = roles;
558
559 if (count() > 0) {
560 const bool supportedExpanding = m_requestRole[ExpandedParentsCountRole];
561 const bool willSupportExpanding = roles.contains("expandedParentsCount");
562 if (supportedExpanding && !willSupportExpanding) {
563 // No expanding is supported anymore. Take care to delete all items that have an expansion level
564 // that is not 0 (and hence are part of an expanded item).
565 removeExpandedItems();
566 }
567 }
568
569 m_groups.clear();
570 resetRoles();
571
572 QSetIterator<QByteArray> it(roles);
573 while (it.hasNext()) {
574 const QByteArray &role = it.next();
575 m_requestRole[typeForRole(role)] = true;
576 }
577
578 if (count() > 0) {
579 // Update m_data with the changed requested roles
580 const int maxIndex = count() - 1;
581 for (int i = 0; i <= maxIndex; ++i) {
582 m_itemData[i]->values = retrieveData(m_itemData.at(i)->item, m_itemData.at(i)->parent);
583 }
584
585 Q_EMIT itemsChanged(KItemRangeList() << KItemRange(0, count()), changedRoles);
586 }
587
588 // Clear the 'values' of all filtered items. They will be re-populated with the
589 // correct roles the next time 'values' will be accessed via data(int).
590 QHash<KFileItem, ItemData *>::iterator filteredIt = m_filteredItems.begin();
591 const QHash<KFileItem, ItemData *>::iterator filteredEnd = m_filteredItems.end();
592 while (filteredIt != filteredEnd) {
593 (*filteredIt)->values.clear();
594 ++filteredIt;
595 }
596 }
597
598 QSet<QByteArray> KFileItemModel::roles() const
599 {
600 return m_roles;
601 }
602
603 bool KFileItemModel::setExpanded(int index, bool expanded)
604 {
605 if (!isExpandable(index) || isExpanded(index) == expanded) {
606 return false;
607 }
608
609 QHash<QByteArray, QVariant> values;
610 values.insert(sharedValue("isExpanded"), expanded);
611 if (!setData(index, values)) {
612 return false;
613 }
614
615 const KFileItem item = m_itemData.at(index)->item;
616 const QUrl url = item.url();
617 const QUrl targetUrl = item.targetUrl();
618 if (expanded) {
619 m_expandedDirs.insert(targetUrl, url);
620 m_dirLister->openUrl(url, KDirLister::Keep);
621
622 const QVariantList previouslyExpandedChildren = m_itemData.at(index)->values.value("previouslyExpandedChildren").value<QVariantList>();
623 for (const QVariant &var : previouslyExpandedChildren) {
624 m_urlsToExpand.insert(var.toUrl());
625 }
626 } else {
627 // Note that there might be (indirect) children of the folder which is to be collapsed in
628 // m_pendingItemsToInsert. To prevent that they will be inserted into the model later,
629 // possibly without a parent, which might result in a crash, we insert all pending items
630 // right now. All new items which would be without a parent will then be removed.
631 dispatchPendingItemsToInsert();
632
633 // Check if the index of the collapsed folder has changed. If that is the case, then items
634 // were inserted before the collapsed folder, and its index needs to be updated.
635 if (m_itemData.at(index)->item != item) {
636 index = this->index(item);
637 }
638
639 m_expandedDirs.remove(targetUrl);
640 m_dirLister->stop(url);
641 m_dirLister->forgetDirs(url);
642
643 const int parentLevel = expandedParentsCount(index);
644 const int itemCount = m_itemData.count();
645 const int firstChildIndex = index + 1;
646
647 QVariantList expandedChildren;
648
649 int childIndex = firstChildIndex;
650 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
651 ItemData *itemData = m_itemData.at(childIndex);
652 if (itemData->values.value("isExpanded").toBool()) {
653 const QUrl targetUrl = itemData->item.targetUrl();
654 const QUrl url = itemData->item.url();
655 m_expandedDirs.remove(targetUrl);
656 m_dirLister->stop(url); // TODO: try to unit-test this, see https://bugs.kde.org/show_bug.cgi?id=332102#c11
657 m_dirLister->forgetDirs(url);
658 expandedChildren.append(targetUrl);
659 }
660 ++childIndex;
661 }
662 const int childrenCount = childIndex - firstChildIndex;
663
664 removeFilteredChildren(KItemRangeList() << KItemRange(index, 1 + childrenCount));
665 removeItems(KItemRangeList() << KItemRange(firstChildIndex, childrenCount), DeleteItemData);
666
667 m_itemData.at(index)->values.insert("previouslyExpandedChildren", expandedChildren);
668 }
669
670 return true;
671 }
672
673 bool KFileItemModel::isExpanded(int index) const
674 {
675 if (index >= 0 && index < count()) {
676 return m_itemData.at(index)->values.value("isExpanded").toBool();
677 }
678 return false;
679 }
680
681 bool KFileItemModel::isExpandable(int index) const
682 {
683 if (index >= 0 && index < count()) {
684 // Call data (instead of accessing m_itemData directly)
685 // to ensure that the value is initialized.
686 return data(index).value("isExpandable").toBool();
687 }
688 return false;
689 }
690
691 int KFileItemModel::expandedParentsCount(int index) const
692 {
693 if (index >= 0 && index < count()) {
694 return expandedParentsCount(m_itemData.at(index));
695 }
696 return 0;
697 }
698
699 QSet<QUrl> KFileItemModel::expandedDirectories() const
700 {
701 QSet<QUrl> result;
702 const auto dirs = m_expandedDirs;
703 for (const auto &dir : dirs) {
704 result.insert(dir);
705 }
706 return result;
707 }
708
709 void KFileItemModel::restoreExpandedDirectories(const QSet<QUrl> &urls)
710 {
711 m_urlsToExpand = urls;
712 }
713
714 void KFileItemModel::expandParentDirectories(const QUrl &url)
715 {
716 // Assure that each sub-path of the URL that should be
717 // expanded is added to m_urlsToExpand. KDirLister
718 // does not care whether the parent-URL has already been
719 // expanded.
720 QUrl urlToExpand = m_dirLister->url();
721 const int pos = urlToExpand.path().length();
722
723 // first subdir can be empty, if m_dirLister->url().path() does not end with '/'
724 // this happens if baseUrl is not root but a home directory, see FoldersPanel,
725 // so using QString::SkipEmptyParts
726 const QStringList subDirs = url.path().mid(pos).split(QDir::separator(), Qt::SkipEmptyParts);
727 for (int i = 0; i < subDirs.count() - 1; ++i) {
728 QString path = urlToExpand.path();
729 if (!path.endsWith(QLatin1Char('/'))) {
730 path.append(QLatin1Char('/'));
731 }
732 urlToExpand.setPath(path + subDirs.at(i));
733 m_urlsToExpand.insert(urlToExpand);
734 }
735
736 // KDirLister::open() must called at least once to trigger an initial
737 // loading. The pending URLs that must be restored are handled
738 // in slotCompleted().
739 QSetIterator<QUrl> it2(m_urlsToExpand);
740 while (it2.hasNext()) {
741 const int idx = index(it2.next());
742 if (idx >= 0 && !isExpanded(idx)) {
743 setExpanded(idx, true);
744 break;
745 }
746 }
747 }
748
749 void KFileItemModel::setNameFilter(const QString &nameFilter)
750 {
751 if (m_filter.pattern() != nameFilter) {
752 dispatchPendingItemsToInsert();
753 m_filter.setPattern(nameFilter);
754 applyFilters();
755 }
756 }
757
758 QString KFileItemModel::nameFilter() const
759 {
760 return m_filter.pattern();
761 }
762
763 void KFileItemModel::setMimeTypeFilters(const QStringList &filters)
764 {
765 if (m_filter.mimeTypes() != filters) {
766 dispatchPendingItemsToInsert();
767 m_filter.setMimeTypes(filters);
768 applyFilters();
769 }
770 }
771
772 QStringList KFileItemModel::mimeTypeFilters() const
773 {
774 return m_filter.mimeTypes();
775 }
776
777 void KFileItemModel::setExcludeMimeTypeFilter(const QStringList &filters)
778 {
779 if (m_filter.excludeMimeTypes() != filters) {
780 dispatchPendingItemsToInsert();
781 m_filter.setExcludeMimeTypes(filters);
782 applyFilters();
783 }
784 }
785
786 QStringList KFileItemModel::excludeMimeTypeFilter() const
787 {
788 return m_filter.excludeMimeTypes();
789 }
790
791 void KFileItemModel::applyFilters()
792 {
793 // ===STEP 1===
794 // Check which previously shown items from m_itemData must now get
795 // hidden and hence moved from m_itemData into m_filteredItems.
796
797 QList<int> newFilteredIndexes; // This structure is good for prepending. We will want an ascending sorted Container at the end, this will do fine.
798
799 // This pointer will refer to the next confirmed shown item from the point of
800 // view of the current "itemData" in the upcoming "for" loop.
801 ItemData *itemShownBelow = nullptr;
802
803 // We will iterate backwards because it's convenient to know beforehand if the item just below is its child or not.
804 for (int index = m_itemData.count() - 1; index >= 0; --index) {
805 ItemData *itemData = m_itemData.at(index);
806
807 if (m_filter.matches(itemData->item) || (itemShownBelow && itemShownBelow->parent == itemData)) {
808 // We could've entered here for two reasons:
809 // 1. This item passes the filter itself
810 // 2. This is an expanded folder that doesn't pass the filter but sees a filter-passing child just below
811
812 // So this item must remain shown.
813 // Lets register this item as the next shown item from the point of view of the next iteration of this for loop
814 itemShownBelow = itemData;
815 } else {
816 // We hide this item for now, however, for expanded folders this is not final:
817 // if after the next "for" loop we discover that its children must now be shown with the newly applied fliter, we shall re-insert it
818 newFilteredIndexes.prepend(index);
819 m_filteredItems.insert(itemData->item, itemData);
820 // indexShownBelow doesn't get updated since this item will be hidden
821 }
822 }
823
824 // This will remove the newly filtered items from m_itemData
825 removeItems(KItemRangeList::fromSortedContainer(newFilteredIndexes), KeepItemData);
826
827 // ===STEP 2===
828 // Check which hidden items from m_filteredItems should
829 // become visible again and hence moved from m_filteredItems back into m_itemData.
830
831 QList<ItemData *> newVisibleItems;
832
833 QHash<KFileItem, ItemData *> ancestorsOfNewVisibleItems; // We will make sure these also become visible in step 3.
834
835 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
836 while (it != m_filteredItems.end()) {
837 if (m_filter.matches(it.key())) {
838 newVisibleItems.append(it.value());
839
840 // If this is a child of an expanded folder, we must make sure that its whole parental chain will also be shown.
841 // We will go up through its parental chain until we either:
842 // 1 - reach the "root item" of the current view, i.e the currently opened folder on Dolphin. Their children have their ItemData::parent set to
843 // nullptr. or 2 - we reach an unfiltered parent or a previously discovered ancestor.
844 for (ItemData *parent = it.value()->parent; parent && !ancestorsOfNewVisibleItems.contains(parent->item) && m_filteredItems.contains(parent->item);
845 parent = parent->parent) {
846 // We wish we could remove this parent from m_filteredItems right now, but we are iterating over it
847 // and it would mess up the iteration. We will mark it to be removed in step 3.
848 ancestorsOfNewVisibleItems.insert(parent->item, parent);
849 }
850
851 it = m_filteredItems.erase(it);
852 } else {
853 // Item remains filtered for now
854 // However, for expanded folders this is not final, we may discover later that it has unfiltered descendants.
855 ++it;
856 }
857 }
858
859 // ===STEP 3===
860 // Handles the ancestorsOfNewVisibleItems.
861 // Now that we are done iterating through m_filteredItems we can safely move the ancestorsOfNewVisibleItems from m_filteredItems to newVisibleItems.
862 for (it = ancestorsOfNewVisibleItems.begin(); it != ancestorsOfNewVisibleItems.end(); it++) {
863 if (m_filteredItems.remove(it.key())) {
864 // m_filteredItems still contained this ancestor until now so we can be sure that we aren't adding a duplicate ancestor to newVisibleItems.
865 newVisibleItems.append(it.value());
866 }
867 }
868
869 // This will insert the newly discovered unfiltered items into m_itemData
870 insertItems(newVisibleItems);
871 }
872
873 void KFileItemModel::removeFilteredChildren(const KItemRangeList &itemRanges)
874 {
875 if (m_filteredItems.isEmpty() || !m_requestRole[ExpandedParentsCountRole]) {
876 // There are either no filtered items, or it is not possible to expand
877 // folders -> there cannot be any filtered children.
878 return;
879 }
880
881 QSet<ItemData *> parents;
882 for (const KItemRange &range : itemRanges) {
883 for (int index = range.index; index < range.index + range.count; ++index) {
884 parents.insert(m_itemData.at(index));
885 }
886 }
887
888 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
889 while (it != m_filteredItems.end()) {
890 if (parents.contains(it.value()->parent)) {
891 delete it.value();
892 it = m_filteredItems.erase(it);
893 } else {
894 ++it;
895 }
896 }
897 }
898
899 QList<KFileItemModel::RoleInfo> KFileItemModel::rolesInformation()
900 {
901 static QList<RoleInfo> rolesInfo;
902 if (rolesInfo.isEmpty()) {
903 int count = 0;
904 const RoleInfoMap *map = rolesInfoMap(count);
905 for (int i = 0; i < count; ++i) {
906 if (map[i].roleType != NoRole) {
907 RoleInfo info;
908 info.role = map[i].role;
909 info.translation = map[i].roleTranslation.toString();
910 if (!map[i].groupTranslation.isEmpty()) {
911 info.group = map[i].groupTranslation.toString();
912 } else {
913 // For top level roles, groupTranslation is 0. We must make sure that
914 // info.group is an empty string then because the code that generates
915 // menus tries to put the actions into sub menus otherwise.
916 info.group = QString();
917 }
918 info.requiresBaloo = map[i].requiresBaloo;
919 info.requiresIndexer = map[i].requiresIndexer;
920 if (!map[i].tooltipTranslation.isEmpty()) {
921 info.tooltip = map[i].tooltipTranslation.toString();
922 } else {
923 info.tooltip = QString();
924 }
925 rolesInfo.append(info);
926 }
927 }
928 }
929
930 return rolesInfo;
931 }
932
933 void KFileItemModel::onGroupedSortingChanged(bool current)
934 {
935 Q_UNUSED(current)
936 m_groups.clear();
937 }
938
939 void KFileItemModel::onSortRoleChanged(const QByteArray &current, const QByteArray &previous, bool resortItems)
940 {
941 Q_UNUSED(previous)
942 m_sortRole = typeForRole(current);
943
944 if (!m_requestRole[m_sortRole]) {
945 QSet<QByteArray> newRoles = m_roles;
946 newRoles << current;
947 setRoles(newRoles);
948 }
949
950 if (resortItems) {
951 resortAllItems();
952 }
953 }
954
955 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
956 {
957 Q_UNUSED(current)
958 Q_UNUSED(previous)
959 resortAllItems();
960 }
961
962 void KFileItemModel::loadSortingSettings()
963 {
964 using Choice = GeneralSettings::EnumSortingChoice;
965 switch (GeneralSettings::sortingChoice()) {
966 case Choice::NaturalSorting:
967 m_naturalSorting = true;
968 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
969 break;
970 case Choice::CaseSensitiveSorting:
971 m_naturalSorting = false;
972 m_collator.setCaseSensitivity(Qt::CaseSensitive);
973 break;
974 case Choice::CaseInsensitiveSorting:
975 m_naturalSorting = false;
976 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
977 break;
978 default:
979 Q_UNREACHABLE();
980 }
981 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
982 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
983 m_collator.compare(QString(), QString());
984 }
985
986 void KFileItemModel::resortAllItems()
987 {
988 m_resortAllItemsTimer->stop();
989
990 const int itemCount = count();
991 if (itemCount <= 0) {
992 return;
993 }
994
995 #ifdef KFILEITEMMODEL_DEBUG
996 QElapsedTimer timer;
997 timer.start();
998 qCDebug(DolphinDebug) << "===========================================================";
999 qCDebug(DolphinDebug) << "Resorting" << itemCount << "items";
1000 #endif
1001
1002 // Remember the order of the current URLs so
1003 // that it can be determined which indexes have
1004 // been moved because of the resorting.
1005 QList<QUrl> oldUrls;
1006 oldUrls.reserve(itemCount);
1007 for (const ItemData *itemData : std::as_const(m_itemData)) {
1008 oldUrls.append(itemData->item.url());
1009 }
1010
1011 m_items.clear();
1012 m_items.reserve(itemCount);
1013
1014 // Resort the items
1015 sort(m_itemData.begin(), m_itemData.end());
1016 for (int i = 0; i < itemCount; ++i) {
1017 m_items.insert(m_itemData.at(i)->item.url(), i);
1018 }
1019
1020 // Determine the first index that has been moved.
1021 int firstMovedIndex = 0;
1022 while (firstMovedIndex < itemCount && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) {
1023 ++firstMovedIndex;
1024 }
1025
1026 const bool itemsHaveMoved = firstMovedIndex < itemCount;
1027 if (itemsHaveMoved) {
1028 m_groups.clear();
1029
1030 int lastMovedIndex = itemCount - 1;
1031 while (lastMovedIndex > firstMovedIndex && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) {
1032 --lastMovedIndex;
1033 }
1034
1035 Q_ASSERT(firstMovedIndex <= lastMovedIndex);
1036
1037 // Create a list movedToIndexes, which has the property that
1038 // movedToIndexes[i] is the new index of the item with the old index
1039 // firstMovedIndex + i.
1040 const int movedItemsCount = lastMovedIndex - firstMovedIndex + 1;
1041 QList<int> movedToIndexes;
1042 movedToIndexes.reserve(movedItemsCount);
1043 for (int i = firstMovedIndex; i <= lastMovedIndex; ++i) {
1044 const int newIndex = m_items.value(oldUrls.at(i));
1045 movedToIndexes.append(newIndex);
1046 }
1047
1048 Q_EMIT itemsMoved(KItemRange(firstMovedIndex, movedItemsCount), movedToIndexes);
1049 } else if (groupedSorting()) {
1050 // The groups might have changed even if the order of the items has not.
1051 const QList<QPair<int, QVariant>> oldGroups = m_groups;
1052 m_groups.clear();
1053 if (groups() != oldGroups) {
1054 Q_EMIT groupsChanged();
1055 }
1056 }
1057
1058 #ifdef KFILEITEMMODEL_DEBUG
1059 qCDebug(DolphinDebug) << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
1060 #endif
1061 }
1062
1063 void KFileItemModel::slotCompleted()
1064 {
1065 m_maximumUpdateIntervalTimer->stop();
1066 dispatchPendingItemsToInsert();
1067
1068 if (!m_urlsToExpand.isEmpty()) {
1069 // Try to find a URL that can be expanded.
1070 // Note that the parent folder must be expanded before any of its subfolders become visible.
1071 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1072 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1073 // Iterate over a const copy because items are deleted and inserted within the loop
1074 const auto urlsToExpand = m_urlsToExpand;
1075 for (const QUrl &url : urlsToExpand) {
1076 const int indexForUrl = index(url);
1077 if (indexForUrl >= 0) {
1078 m_urlsToExpand.remove(url);
1079 if (setExpanded(indexForUrl, true)) {
1080 // The dir lister has been triggered. This slot will be called
1081 // again after the directory has been expanded.
1082 return;
1083 }
1084 }
1085 }
1086
1087 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1088 // if these URLs have been deleted in the meantime.
1089 m_urlsToExpand.clear();
1090 }
1091
1092 Q_EMIT directoryLoadingCompleted();
1093 }
1094
1095 void KFileItemModel::slotCanceled()
1096 {
1097 m_maximumUpdateIntervalTimer->stop();
1098 dispatchPendingItemsToInsert();
1099
1100 Q_EMIT directoryLoadingCanceled();
1101 }
1102
1103 void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items)
1104 {
1105 Q_ASSERT(!items.isEmpty());
1106
1107 const QUrl parentUrl = m_expandedDirs.value(directoryUrl, directoryUrl.adjusted(QUrl::StripTrailingSlash));
1108
1109 if (m_requestRole[ExpandedParentsCountRole]) {
1110 // If the expanding of items is enabled, the call
1111 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1112 // might result in emitting the same items twice due to the Keep-parameter.
1113 // This case happens if an item gets expanded, collapsed and expanded again
1114 // before the items could be loaded for the first expansion.
1115 if (index(items.first().url()) >= 0) {
1116 // The items are already part of the model.
1117 return;
1118 }
1119
1120 if (directoryUrl != directory()) {
1121 // To be able to compare whether the new items may be inserted as children
1122 // of a parent item the pending items must be added to the model first.
1123 dispatchPendingItemsToInsert();
1124 }
1125
1126 // KDirLister keeps the children of items that got expanded once even if
1127 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1128 // checked whether the parent for new items is still expanded.
1129 const int parentIndex = index(parentUrl);
1130 if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) {
1131 // The parent is not expanded.
1132 return;
1133 }
1134 }
1135
1136 const QList<ItemData *> itemDataList = createItemDataList(parentUrl, items);
1137
1138 if (!m_filter.hasSetFilters()) {
1139 m_pendingItemsToInsert.append(itemDataList);
1140 } else {
1141 QSet<ItemData *> parentsToEnsureVisible;
1142
1143 // The name or type filter is active. Hide filtered items
1144 // before inserting them into the model and remember
1145 // the filtered items in m_filteredItems.
1146 for (ItemData *itemData : itemDataList) {
1147 if (m_filter.matches(itemData->item)) {
1148 m_pendingItemsToInsert.append(itemData);
1149 if (itemData->parent) {
1150 parentsToEnsureVisible.insert(itemData->parent);
1151 }
1152 } else {
1153 m_filteredItems.insert(itemData->item, itemData);
1154 }
1155 }
1156
1157 // Entire parental chains must be shown
1158 for (ItemData *parent : parentsToEnsureVisible) {
1159 for (; parent && m_filteredItems.remove(parent->item); parent = parent->parent) {
1160 m_pendingItemsToInsert.append(parent);
1161 }
1162 }
1163 }
1164
1165 if (!m_maximumUpdateIntervalTimer->isActive()) {
1166 // Assure that items get dispatched if no completed() or canceled() signal is
1167 // emitted during the maximum update interval.
1168 m_maximumUpdateIntervalTimer->start();
1169 }
1170
1171 Q_EMIT fileItemsChanged({KFileItem(directoryUrl)});
1172 }
1173
1174 int KFileItemModel::filterChildlessParents(KItemRangeList &removedItemRanges, const QSet<ItemData *> &parentsToEnsureVisible)
1175 {
1176 int filteredParentsCount = 0;
1177 // The childless parents not yet removed will always be right above the start of a removed range.
1178 // We iterate backwards to ensure the deepest folders are processed before their parents
1179 for (int i = removedItemRanges.size() - 1; i >= 0; i--) {
1180 KItemRange itemRange = removedItemRanges.at(i);
1181 const ItemData *const firstInRange = m_itemData.at(itemRange.index);
1182 ItemData *itemAbove = itemRange.index - 1 >= 0 ? m_itemData.at(itemRange.index - 1) : nullptr;
1183 const ItemData *const itemBelow = itemRange.index + itemRange.count < m_itemData.count() ? m_itemData.at(itemRange.index + itemRange.count) : nullptr;
1184
1185 if (itemAbove && firstInRange->parent == itemAbove && !m_filter.matches(itemAbove->item) && (!itemBelow || itemBelow->parent != itemAbove)
1186 && !parentsToEnsureVisible.contains(itemAbove)) {
1187 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1188 // and this deleted range covers all of its descendents, so none will be left.
1189 m_filteredItems.insert(itemAbove->item, itemAbove);
1190 // This range's starting index will be extended to include the parent above:
1191 --itemRange.index;
1192 ++itemRange.count;
1193 ++filteredParentsCount;
1194 KItemRange previousRange = i > 0 ? removedItemRanges.at(i - 1) : KItemRange();
1195 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1196 if (i > 0 && previousRange.index + previousRange.count == itemRange.index) {
1197 previousRange.count += itemRange.count;
1198 removedItemRanges.replace(i - 1, previousRange);
1199 removedItemRanges.removeAt(i);
1200 } else {
1201 removedItemRanges.replace(i, itemRange);
1202 // We must revisit this range in the next iteration since its starting index changed
1203 ++i;
1204 }
1205 }
1206 }
1207 return filteredParentsCount;
1208 }
1209
1210 void KFileItemModel::slotItemsDeleted(const KFileItemList &items)
1211 {
1212 dispatchPendingItemsToInsert();
1213
1214 QVector<int> indexesToRemove;
1215 indexesToRemove.reserve(items.count());
1216 KFileItemList dirsChanged;
1217
1218 const auto currentDir = directory();
1219
1220 for (const KFileItem &item : items) {
1221 if (item.url() == currentDir) {
1222 Q_EMIT currentDirectoryRemoved();
1223 return;
1224 }
1225
1226 const int indexForItem = index(item);
1227 if (indexForItem >= 0) {
1228 indexesToRemove.append(indexForItem);
1229 } else {
1230 // Probably the item has been filtered.
1231 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(item);
1232 if (it != m_filteredItems.end()) {
1233 delete it.value();
1234 m_filteredItems.erase(it);
1235 }
1236 }
1237
1238 QUrl parentUrl = item.url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
1239 if (dirsChanged.findByUrl(parentUrl).isNull()) {
1240 dirsChanged << KFileItem(parentUrl);
1241 }
1242 }
1243
1244 std::sort(indexesToRemove.begin(), indexesToRemove.end());
1245
1246 if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) {
1247 // Assure that removing a parent item also results in removing all children
1248 QVector<int> indexesToRemoveWithChildren;
1249 indexesToRemoveWithChildren.reserve(m_itemData.count());
1250
1251 const int itemCount = m_itemData.count();
1252 for (int index : std::as_const(indexesToRemove)) {
1253 indexesToRemoveWithChildren.append(index);
1254
1255 const int parentLevel = expandedParentsCount(index);
1256 int childIndex = index + 1;
1257 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
1258 indexesToRemoveWithChildren.append(childIndex);
1259 ++childIndex;
1260 }
1261 }
1262
1263 indexesToRemove = indexesToRemoveWithChildren;
1264 }
1265
1266 KItemRangeList itemRanges = KItemRangeList::fromSortedContainer(indexesToRemove);
1267 removeFilteredChildren(itemRanges);
1268
1269 // This call will update itemRanges to include the childless parents that have been filtered.
1270 const int filteredParentsCount = filterChildlessParents(itemRanges);
1271
1272 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1273 // mixed with expanded folders that are just being filtered out.
1274 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1275 // so removeItems() will check m_filteredItems to differentiate which is which.
1276 removeItems(itemRanges, filteredParentsCount > 0 ? DeleteItemDataIfUnfiltered : DeleteItemData);
1277
1278 Q_EMIT fileItemsChanged(dirsChanged);
1279 }
1280
1281 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &items)
1282 {
1283 Q_ASSERT(!items.isEmpty());
1284 #ifdef KFILEITEMMODEL_DEBUG
1285 qCDebug(DolphinDebug) << "Refreshing" << items.count() << "items";
1286 #endif
1287
1288 // Get the indexes of all items that have been refreshed
1289 QList<int> indexes;
1290 indexes.reserve(items.count());
1291
1292 QSet<QByteArray> changedRoles;
1293 KFileItemList changedFiles;
1294
1295 // Contains the indexes of the currently visible items
1296 // that should get hidden and hence moved to m_filteredItems.
1297 QVector<int> newFilteredIndexes;
1298
1299 // Contains currently hidden items that should
1300 // get visible and hence removed from m_filteredItems
1301 QList<ItemData *> newVisibleItems;
1302
1303 QListIterator<QPair<KFileItem, KFileItem>> it(items);
1304
1305 while (it.hasNext()) {
1306 const QPair<KFileItem, KFileItem> &itemPair = it.next();
1307 const KFileItem &oldItem = itemPair.first;
1308 const KFileItem &newItem = itemPair.second;
1309 const int indexForItem = index(oldItem);
1310 const bool newItemMatchesFilter = m_filter.matches(newItem);
1311 if (indexForItem >= 0) {
1312 m_itemData[indexForItem]->item = newItem;
1313
1314 // Keep old values as long as possible if they could not retrieved synchronously yet.
1315 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1316 ItemData *const itemData = m_itemData.at(indexForItem);
1317 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
1318 while (it.hasNext()) {
1319 it.next();
1320 const QByteArray &role = it.key();
1321 if (itemData->values.value(role) != it.value()) {
1322 itemData->values.insert(role, it.value());
1323 changedRoles.insert(role);
1324 }
1325 }
1326
1327 m_items.remove(oldItem.url());
1328 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1329 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1330 m_items.insert(newItem.url(), indexForItem);
1331 if (newItemMatchesFilter
1332 || (itemData->values.value("isExpanded").toBool()
1333 && (indexForItem + 1 < m_itemData.count() && m_itemData.at(indexForItem + 1)->parent == itemData))) {
1334 // We are lenient with expanded folders that originally had visible children.
1335 // If they become childless now they will be caught by filterChildlessParents()
1336 changedFiles.append(newItem);
1337 indexes.append(indexForItem);
1338 } else {
1339 newFilteredIndexes.append(indexForItem);
1340 m_filteredItems.insert(newItem, itemData);
1341 }
1342 } else {
1343 // Check if 'oldItem' is one of the filtered items.
1344 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(oldItem);
1345 if (it != m_filteredItems.end()) {
1346 ItemData *const itemData = it.value();
1347 itemData->item = newItem;
1348
1349 // The data stored in 'values' might have changed. Therefore, we clear
1350 // 'values' and re-populate it the next time it is requested via data(int).
1351 // Before clearing, we must remember if it was expanded and the expanded parents count,
1352 // otherwise these states would be lost. The data() method will deal with this special case.
1353 const bool isExpanded = itemData->values.value("isExpanded").toBool();
1354 bool hasExpandedParentsCount = false;
1355 const int expandedParentsCount = itemData->values.value("expandedParentsCount").toInt(&hasExpandedParentsCount);
1356 itemData->values.clear();
1357 if (isExpanded) {
1358 itemData->values.insert("isExpanded", true);
1359 if (hasExpandedParentsCount) {
1360 itemData->values.insert("expandedParentsCount", expandedParentsCount);
1361 }
1362 }
1363
1364 m_filteredItems.erase(it);
1365 if (newItemMatchesFilter) {
1366 newVisibleItems.append(itemData);
1367 } else {
1368 m_filteredItems.insert(newItem, itemData);
1369 }
1370 }
1371 }
1372 }
1373
1374 std::sort(newFilteredIndexes.begin(), newFilteredIndexes.end());
1375
1376 // We must keep track of parents of new visible items since they must be shown no matter what
1377 // They will be considered "immune" to filterChildlessParents()
1378 QSet<ItemData *> parentsToEnsureVisible;
1379
1380 for (ItemData *item : newVisibleItems) {
1381 for (ItemData *parent = item->parent; parent && !parentsToEnsureVisible.contains(parent); parent = parent->parent) {
1382 parentsToEnsureVisible.insert(parent);
1383 }
1384 }
1385 for (ItemData *parent : parentsToEnsureVisible) {
1386 // We make sure they are all unfiltered.
1387 if (m_filteredItems.remove(parent->item)) {
1388 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1389 newVisibleItems.append(parent);
1390 // It could be in newFilteredIndexes, we must remove it if it's there:
1391 const int parentIndex = index(parent->item);
1392 if (parentIndex >= 0) {
1393 QVector<int>::iterator it = std::lower_bound(newFilteredIndexes.begin(), newFilteredIndexes.end(), parentIndex);
1394 if (it != newFilteredIndexes.end() && *it == parentIndex) {
1395 newFilteredIndexes.erase(it);
1396 }
1397 }
1398 }
1399 }
1400
1401 KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
1402
1403 // This call will update itemRanges to include the childless parents that have been filtered.
1404 filterChildlessParents(removedRanges, parentsToEnsureVisible);
1405
1406 removeItems(removedRanges, KeepItemData);
1407
1408 // Show previously hidden items that should get visible
1409 insertItems(newVisibleItems);
1410
1411 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1412
1413 // If the changed items have been created recently, they might not be in m_items yet.
1414 // In that case, the list 'indexes' might be empty.
1415 if (indexes.isEmpty()) {
1416 return;
1417 }
1418
1419 if (newVisibleItems.count() > 0 || removedRanges.count() > 0) {
1420 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1421 indexes.clear();
1422 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1423 const QSet<const KFileItem> changedFilesSet(changedFiles.cbegin(), changedFiles.cend());
1424 for (int i = 0; i < m_itemData.count(); i++) {
1425 if (changedFilesSet.contains(m_itemData.at(i)->item)) {
1426 indexes.append(i);
1427 }
1428 }
1429 } else {
1430 std::sort(indexes.begin(), indexes.end());
1431 }
1432
1433 // Extract the item-ranges out of the changed indexes
1434 const KItemRangeList itemRangeList = KItemRangeList::fromSortedContainer(indexes);
1435 emitItemsChangedAndTriggerResorting(itemRangeList, changedRoles);
1436
1437 Q_EMIT fileItemsChanged(changedFiles);
1438 }
1439
1440 void KFileItemModel::slotClear()
1441 {
1442 #ifdef KFILEITEMMODEL_DEBUG
1443 qCDebug(DolphinDebug) << "Clearing all items";
1444 #endif
1445
1446 qDeleteAll(m_filteredItems);
1447 m_filteredItems.clear();
1448 m_groups.clear();
1449
1450 m_maximumUpdateIntervalTimer->stop();
1451 m_resortAllItemsTimer->stop();
1452
1453 qDeleteAll(m_pendingItemsToInsert);
1454 m_pendingItemsToInsert.clear();
1455
1456 const int removedCount = m_itemData.count();
1457 if (removedCount > 0) {
1458 qDeleteAll(m_itemData);
1459 m_itemData.clear();
1460 m_items.clear();
1461 Q_EMIT itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
1462 }
1463
1464 m_expandedDirs.clear();
1465 }
1466
1467 void KFileItemModel::slotSortingChoiceChanged()
1468 {
1469 loadSortingSettings();
1470 resortAllItems();
1471 }
1472
1473 void KFileItemModel::dispatchPendingItemsToInsert()
1474 {
1475 if (!m_pendingItemsToInsert.isEmpty()) {
1476 insertItems(m_pendingItemsToInsert);
1477 m_pendingItemsToInsert.clear();
1478 }
1479 }
1480
1481 void KFileItemModel::insertItems(QList<ItemData *> &newItems)
1482 {
1483 if (newItems.isEmpty()) {
1484 return;
1485 }
1486
1487 #ifdef KFILEITEMMODEL_DEBUG
1488 QElapsedTimer timer;
1489 timer.start();
1490 qCDebug(DolphinDebug) << "===========================================================";
1491 qCDebug(DolphinDebug) << "Inserting" << newItems.count() << "items";
1492 #endif
1493
1494 m_groups.clear();
1495 prepareItemsForSorting(newItems);
1496
1497 // Natural sorting of items can be very slow. However, it becomes much faster
1498 // if the input sequence is already mostly sorted. Therefore, we first sort
1499 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1500 if (m_naturalSorting) {
1501 if (m_sortRole == NameRole) {
1502 parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
1503 } else if (isRoleValueNatural(m_sortRole)) {
1504 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
1505 const QByteArray role = roleForType(m_sortRole);
1506 return a->values.value(role).toString() < b->values.value(role).toString();
1507 };
1508 parallelMergeSort(newItems.begin(), newItems.end(), lambdaLessThan, QThread::idealThreadCount());
1509 }
1510 }
1511
1512 sort(newItems.begin(), newItems.end());
1513
1514 #ifdef KFILEITEMMODEL_DEBUG
1515 qCDebug(DolphinDebug) << "[TIME] Sorting:" << timer.elapsed();
1516 #endif
1517
1518 KItemRangeList itemRanges;
1519 const int existingItemCount = m_itemData.count();
1520 const int newItemCount = newItems.count();
1521 const int totalItemCount = existingItemCount + newItemCount;
1522
1523 if (existingItemCount == 0) {
1524 // Optimization for the common special case that there are no
1525 // items in the model yet. Happens, e.g., when entering a folder.
1526 m_itemData = newItems;
1527 itemRanges << KItemRange(0, newItemCount);
1528 } else {
1529 m_itemData.reserve(totalItemCount);
1530 for (int i = existingItemCount; i < totalItemCount; ++i) {
1531 m_itemData.append(nullptr);
1532 }
1533
1534 // We build the new list m_itemData in reverse order to minimize
1535 // the number of moves and guarantee O(N) complexity.
1536 int targetIndex = totalItemCount - 1;
1537 int sourceIndexExistingItems = existingItemCount - 1;
1538 int sourceIndexNewItems = newItemCount - 1;
1539
1540 int rangeCount = 0;
1541
1542 while (sourceIndexNewItems >= 0) {
1543 ItemData *newItem = newItems.at(sourceIndexNewItems);
1544 if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
1545 // Move an existing item to its new position. If any new items
1546 // are behind it, push the item range to itemRanges.
1547 if (rangeCount > 0) {
1548 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1549 rangeCount = 0;
1550 }
1551
1552 m_itemData[targetIndex] = m_itemData.at(sourceIndexExistingItems);
1553 --sourceIndexExistingItems;
1554 } else {
1555 // Insert a new item into the list.
1556 ++rangeCount;
1557 m_itemData[targetIndex] = newItem;
1558 --sourceIndexNewItems;
1559 }
1560 --targetIndex;
1561 }
1562
1563 // Push the final item range to itemRanges.
1564 if (rangeCount > 0) {
1565 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1566 }
1567
1568 // Note that itemRanges is still sorted in reverse order.
1569 std::reverse(itemRanges.begin(), itemRanges.end());
1570 }
1571
1572 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1573 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1574 m_items.clear();
1575
1576 Q_EMIT itemsInserted(itemRanges);
1577
1578 #ifdef KFILEITEMMODEL_DEBUG
1579 qCDebug(DolphinDebug) << "[TIME] Inserting of" << newItems.count() << "items:" << timer.elapsed();
1580 #endif
1581 }
1582
1583 void KFileItemModel::removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior)
1584 {
1585 if (itemRanges.isEmpty()) {
1586 return;
1587 }
1588
1589 m_groups.clear();
1590
1591 // Step 1: Remove the items from m_itemData, and free the ItemData.
1592 int removedItemsCount = 0;
1593 for (const KItemRange &range : itemRanges) {
1594 removedItemsCount += range.count;
1595
1596 for (int index = range.index; index < range.index + range.count; ++index) {
1597 if (behavior == DeleteItemData || (behavior == DeleteItemDataIfUnfiltered && !m_filteredItems.contains(m_itemData.at(index)->item))) {
1598 delete m_itemData.at(index);
1599 }
1600
1601 m_itemData[index] = nullptr;
1602 }
1603 }
1604
1605 // Step 2: Remove the ItemData pointers from the list m_itemData.
1606 int target = itemRanges.at(0).index;
1607 int source = itemRanges.at(0).index + itemRanges.at(0).count;
1608 int nextRange = 1;
1609
1610 const int oldItemDataCount = m_itemData.count();
1611 while (source < oldItemDataCount) {
1612 m_itemData[target] = m_itemData[source];
1613 ++target;
1614 ++source;
1615
1616 if (nextRange < itemRanges.count() && source == itemRanges.at(nextRange).index) {
1617 // Skip the items in the next removed range.
1618 source += itemRanges.at(nextRange).count;
1619 ++nextRange;
1620 }
1621 }
1622
1623 m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end());
1624
1625 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1626 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1627 m_items.clear();
1628
1629 Q_EMIT itemsRemoved(itemRanges);
1630 }
1631
1632 QList<KFileItemModel::ItemData *> KFileItemModel::createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const
1633 {
1634 if (m_sortRole == TypeRole) {
1635 // Try to resolve the MIME-types synchronously to prevent a reordering of
1636 // the items when sorting by type (per default MIME-types are resolved
1637 // asynchronously by KFileItemModelRolesUpdater).
1638 determineMimeTypes(items, 200);
1639 }
1640
1641 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1642 const int parentIndex = index(parentUrl);
1643 ItemData *parentItem = parentIndex < 0 ? m_filteredItems.value(KFileItem(parentUrl), nullptr) : m_itemData.at(parentIndex);
1644
1645 QList<ItemData *> itemDataList;
1646 itemDataList.reserve(items.count());
1647
1648 for (const KFileItem &item : items) {
1649 ItemData *itemData = new ItemData();
1650 itemData->item = item;
1651 itemData->parent = parentItem;
1652 itemDataList.append(itemData);
1653 }
1654
1655 return itemDataList;
1656 }
1657
1658 void KFileItemModel::prepareItemsForSorting(QList<ItemData *> &itemDataList)
1659 {
1660 switch (m_sortRole) {
1661 case ExtensionRole:
1662 case PermissionsRole:
1663 case OwnerRole:
1664 case GroupRole:
1665 case DestinationRole:
1666 case PathRole:
1667 case DeletionTimeRole:
1668 // These roles can be determined with retrieveData, and they have to be stored
1669 // in the QHash "values" for the sorting.
1670 for (ItemData *itemData : std::as_const(itemDataList)) {
1671 if (itemData->values.isEmpty()) {
1672 itemData->values = retrieveData(itemData->item, itemData->parent);
1673 }
1674 }
1675 break;
1676
1677 case TypeRole:
1678 // At least store the data including the file type for items with known MIME type.
1679 for (ItemData *itemData : std::as_const(itemDataList)) {
1680 if (itemData->values.isEmpty()) {
1681 const KFileItem item = itemData->item;
1682 if (item.isDir() || item.isMimeTypeKnown()) {
1683 itemData->values = retrieveData(itemData->item, itemData->parent);
1684 }
1685 }
1686 }
1687 break;
1688
1689 default:
1690 // The other roles are either resolved by KFileItemModelRolesUpdater
1691 // (this includes the SizeRole for directories), or they do not need
1692 // to be stored in the QHash "values" for sorting because the data can
1693 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1694 // DateRole).
1695 break;
1696 }
1697 }
1698
1699 int KFileItemModel::expandedParentsCount(const ItemData *data)
1700 {
1701 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1702 // if the corresponding item is expanded, and it is not a top-level item.
1703 const ItemData *parent = data->parent;
1704 if (parent) {
1705 if (parent->parent) {
1706 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1707 return parent->values.value("expandedParentsCount").toInt() + 1;
1708 } else {
1709 return 1;
1710 }
1711 } else {
1712 return 0;
1713 }
1714 }
1715
1716 void KFileItemModel::removeExpandedItems()
1717 {
1718 QVector<int> indexesToRemove;
1719
1720 const int maxIndex = m_itemData.count() - 1;
1721 for (int i = 0; i <= maxIndex; ++i) {
1722 const ItemData *itemData = m_itemData.at(i);
1723 if (itemData->parent) {
1724 indexesToRemove.append(i);
1725 }
1726 }
1727
1728 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1729 m_expandedDirs.clear();
1730
1731 // Also remove all filtered items which have a parent.
1732 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
1733 const QHash<KFileItem, ItemData *>::iterator end = m_filteredItems.end();
1734
1735 while (it != end) {
1736 if (it.value()->parent) {
1737 delete it.value();
1738 it = m_filteredItems.erase(it);
1739 } else {
1740 ++it;
1741 }
1742 }
1743 }
1744
1745 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet<QByteArray> &changedRoles)
1746 {
1747 Q_EMIT itemsChanged(itemRanges, changedRoles);
1748
1749 // Trigger a resorting if necessary. Note that this can happen even if the sort
1750 // role has not changed at all because the file name can be used as a fallback.
1751 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))
1752 || (changedRoles.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1753 for (const KItemRange &range : itemRanges) {
1754 bool needsResorting = false;
1755
1756 const int first = range.index;
1757 const int last = range.index + range.count - 1;
1758
1759 // Resorting the model is necessary if
1760 // (a) The first item in the range is "lessThan" its predecessor,
1761 // (b) the successor of the last item is "lessThan" the last item, or
1762 // (c) the internal order of the items in the range is incorrect.
1763 if (first > 0 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1764 needsResorting = true;
1765 } else if (last < count() - 1 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1766 needsResorting = true;
1767 } else {
1768 for (int index = first; index < last; ++index) {
1769 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1770 needsResorting = true;
1771 break;
1772 }
1773 }
1774 }
1775
1776 if (needsResorting) {
1777 scheduleResortAllItems();
1778 return;
1779 }
1780 }
1781 }
1782
1783 if (groupedSorting() && changedRoles.contains(sortRole())) {
1784 // The position is still correct, but the groups might have changed
1785 // if the changed item is either the first or the last item in a
1786 // group.
1787 // In principle, we could try to find out if the item really is the
1788 // first or last one in its group and then update the groups
1789 // (possibly with a delayed timer to make sure that we don't
1790 // re-calculate the groups very often if items are updated one by
1791 // one), but starting m_resortAllItemsTimer is easier.
1792 m_resortAllItemsTimer->start();
1793 }
1794 }
1795
1796 void KFileItemModel::resetRoles()
1797 {
1798 for (int i = 0; i < RolesCount; ++i) {
1799 m_requestRole[i] = false;
1800 }
1801 }
1802
1803 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray &role) const
1804 {
1805 static QHash<QByteArray, RoleType> roles;
1806 if (roles.isEmpty()) {
1807 // Insert user visible roles that can be accessed with
1808 // KFileItemModel::roleInformation()
1809 int count = 0;
1810 const RoleInfoMap *map = rolesInfoMap(count);
1811 for (int i = 0; i < count; ++i) {
1812 roles.insert(map[i].role, map[i].roleType);
1813 }
1814
1815 // Insert internal roles (take care to synchronize the implementation
1816 // with KFileItemModel::roleForType() in case if a change is done).
1817 roles.insert("isDir", IsDirRole);
1818 roles.insert("isLink", IsLinkRole);
1819 roles.insert("isHidden", IsHiddenRole);
1820 roles.insert("isExpanded", IsExpandedRole);
1821 roles.insert("isExpandable", IsExpandableRole);
1822 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1823
1824 Q_ASSERT(roles.count() == RolesCount);
1825 }
1826
1827 return roles.value(role, NoRole);
1828 }
1829
1830 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1831 {
1832 static QHash<RoleType, QByteArray> roles;
1833 if (roles.isEmpty()) {
1834 // Insert user visible roles that can be accessed with
1835 // KFileItemModel::roleInformation()
1836 int count = 0;
1837 const RoleInfoMap *map = rolesInfoMap(count);
1838 for (int i = 0; i < count; ++i) {
1839 roles.insert(map[i].roleType, map[i].role);
1840 }
1841
1842 // Insert internal roles (take care to synchronize the implementation
1843 // with KFileItemModel::typeForRole() in case if a change is done).
1844 roles.insert(IsDirRole, "isDir");
1845 roles.insert(IsLinkRole, "isLink");
1846 roles.insert(IsHiddenRole, "isHidden");
1847 roles.insert(IsExpandedRole, "isExpanded");
1848 roles.insert(IsExpandableRole, "isExpandable");
1849 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1850
1851 Q_ASSERT(roles.count() == RolesCount);
1852 };
1853
1854 return roles.value(roleType);
1855 }
1856
1857 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem &item, const ItemData *parent) const
1858 {
1859 // It is important to insert only roles that are fast to retrieve. E.g.
1860 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1861 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1862 QHash<QByteArray, QVariant> data;
1863 data.insert(sharedValue("url"), item.url());
1864
1865 const bool isDir = item.isDir();
1866 if (m_requestRole[IsDirRole] && isDir) {
1867 data.insert(sharedValue("isDir"), true);
1868 }
1869
1870 if (m_requestRole[IsLinkRole] && item.isLink()) {
1871 data.insert(sharedValue("isLink"), true);
1872 }
1873
1874 if (m_requestRole[IsHiddenRole]) {
1875 data.insert(sharedValue("isHidden"), item.isHidden() || item.mimetype() == QStringLiteral("application/x-trash"));
1876 }
1877
1878 if (m_requestRole[NameRole]) {
1879 data.insert(sharedValue("text"), item.text());
1880 }
1881
1882 if (m_requestRole[ExtensionRole] && !isDir) {
1883 // TODO KF6 use KFileItem::suffix 464722
1884 data.insert(sharedValue("extension"), QFileInfo(item.name()).suffix());
1885 }
1886
1887 if (m_requestRole[SizeRole] && !isDir) {
1888 data.insert(sharedValue("size"), item.size());
1889 }
1890
1891 if (m_requestRole[ModificationTimeRole]) {
1892 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1893 // having several thousands of items. Instead read the raw number from UDSEntry directly
1894 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1895 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1896 data.insert(sharedValue("modificationtime"), dateTime);
1897 }
1898
1899 if (m_requestRole[CreationTimeRole]) {
1900 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1901 // having several thousands of items. Instead read the raw number from UDSEntry directly
1902 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1903 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1904 data.insert(sharedValue("creationtime"), dateTime);
1905 }
1906
1907 if (m_requestRole[AccessTimeRole]) {
1908 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1909 // having several thousands of items. Instead read the raw number from UDSEntry directly
1910 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1911 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1912 data.insert(sharedValue("accesstime"), dateTime);
1913 }
1914
1915 if (m_requestRole[PermissionsRole]) {
1916 data.insert(sharedValue("permissions"), QVariantList() << item.permissionsString() << item.permissions());
1917 }
1918
1919 if (m_requestRole[OwnerRole]) {
1920 data.insert(sharedValue("owner"), item.user());
1921 }
1922
1923 if (m_requestRole[GroupRole]) {
1924 data.insert(sharedValue("group"), item.group());
1925 }
1926
1927 if (m_requestRole[DestinationRole]) {
1928 QString destination = item.linkDest();
1929 if (destination.isEmpty()) {
1930 destination = QLatin1Char('-');
1931 }
1932 data.insert(sharedValue("destination"), destination);
1933 }
1934
1935 if (m_requestRole[PathRole]) {
1936 QString path;
1937 if (item.url().scheme() == QLatin1String("trash")) {
1938 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1939 } else {
1940 // For performance reasons cache the home-path in a static QString
1941 // (see QDir::homePath() for more details)
1942 static QString homePath;
1943 if (homePath.isEmpty()) {
1944 homePath = QDir::homePath();
1945 }
1946
1947 path = item.localPath();
1948 if (path.startsWith(homePath)) {
1949 path.replace(0, homePath.length(), QLatin1Char('~'));
1950 }
1951 }
1952
1953 const int index = path.lastIndexOf(item.text());
1954 path = path.mid(0, index - 1);
1955 data.insert(sharedValue("path"), path);
1956 }
1957
1958 if (m_requestRole[DeletionTimeRole]) {
1959 QDateTime deletionTime;
1960 if (item.url().scheme() == QLatin1String("trash")) {
1961 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
1962 }
1963 data.insert(sharedValue("deletiontime"), deletionTime);
1964 }
1965
1966 if (m_requestRole[IsExpandableRole] && isDir) {
1967 data.insert(sharedValue("isExpandable"), true);
1968 }
1969
1970 if (m_requestRole[ExpandedParentsCountRole]) {
1971 if (parent) {
1972 const int level = expandedParentsCount(parent) + 1;
1973 data.insert(sharedValue("expandedParentsCount"), level);
1974 }
1975 }
1976
1977 if (item.isMimeTypeKnown()) {
1978 QString iconName = item.iconName();
1979 if (!QIcon::hasThemeIcon(iconName)) {
1980 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
1981 iconName = mimeType.genericIconName();
1982 }
1983
1984 data.insert(sharedValue("iconName"), iconName);
1985
1986 if (m_requestRole[TypeRole]) {
1987 data.insert(sharedValue("type"), item.mimeComment());
1988 }
1989 } else if (m_requestRole[TypeRole] && isDir) {
1990 static const QString folderMimeType = item.mimeComment();
1991 data.insert(sharedValue("type"), folderMimeType);
1992 }
1993
1994 return data;
1995 }
1996
1997 bool KFileItemModel::lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const
1998 {
1999 int result = 0;
2000
2001 if (a->parent != b->parent) {
2002 const int expansionLevelA = expandedParentsCount(a);
2003 const int expansionLevelB = expandedParentsCount(b);
2004
2005 // If b has a higher expansion level than a, check if a is a parent
2006 // of b, and make sure that both expansion levels are equal otherwise.
2007 for (int i = expansionLevelB; i > expansionLevelA; --i) {
2008 if (b->parent == a) {
2009 return true;
2010 }
2011 b = b->parent;
2012 }
2013
2014 // If a has a higher expansion level than a, check if b is a parent
2015 // of a, and make sure that both expansion levels are equal otherwise.
2016 for (int i = expansionLevelA; i > expansionLevelB; --i) {
2017 if (a->parent == b) {
2018 return false;
2019 }
2020 a = a->parent;
2021 }
2022
2023 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
2024
2025 // Compare the last parents of a and b which are different.
2026 while (a->parent != b->parent) {
2027 a = a->parent;
2028 b = b->parent;
2029 }
2030 }
2031
2032 // Show hidden files and folders last
2033 if (m_sortHiddenLast) {
2034 const bool isHiddenA = a->item.isHidden();
2035 const bool isHiddenB = b->item.isHidden();
2036 if (isHiddenA && !isHiddenB) {
2037 return false;
2038 } else if (!isHiddenA && isHiddenB) {
2039 return true;
2040 }
2041 }
2042
2043 if (m_sortDirsFirst
2044 || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount && m_sortRole == SizeRole)) {
2045 const bool isDirA = a->item.isDir();
2046 const bool isDirB = b->item.isDir();
2047 if (isDirA && !isDirB) {
2048 return true;
2049 } else if (!isDirA && isDirB) {
2050 return false;
2051 }
2052 }
2053
2054 result = sortRoleCompare(a, b, collator);
2055
2056 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
2057 }
2058
2059 void KFileItemModel::sort(const QList<KFileItemModel::ItemData *>::iterator &begin, const QList<KFileItemModel::ItemData *>::iterator &end) const
2060 {
2061 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
2062 return lessThan(a, b, m_collator);
2063 };
2064
2065 if (m_sortRole == NameRole || isRoleValueNatural(m_sortRole)) {
2066 // Sorting by string can be expensive, in particular if natural sorting is
2067 // enabled. Use all CPU cores to speed up the sorting process.
2068 static const int numberOfThreads = QThread::idealThreadCount();
2069 parallelMergeSort(begin, end, lambdaLessThan, numberOfThreads);
2070 } else {
2071 // Sorting by other roles is quite fast. Use only one thread to prevent
2072 // problems caused by non-reentrant comparison functions, see
2073 // https://bugs.kde.org/show_bug.cgi?id=312679
2074 mergeSort(begin, end, lambdaLessThan);
2075 }
2076 }
2077
2078 int KFileItemModel::sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const
2079 {
2080 // This function must never return 0, because that would break stable
2081 // sorting, which leads to all kinds of bugs.
2082 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2083 // If two items have equal sort values, let the fallbacks at the bottom of
2084 // the function handle it.
2085 const KFileItem &itemA = a->item;
2086 const KFileItem &itemB = b->item;
2087
2088 int result = 0;
2089
2090 switch (m_sortRole) {
2091 case NameRole:
2092 // The name role is handled as default fallback after the switch
2093 break;
2094
2095 case SizeRole: {
2096 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount && itemA.isDir()) {
2097 // folders first then
2098 // items A and B are folders thanks to lessThan checks
2099 auto valueA = a->values.value("count");
2100 auto valueB = b->values.value("count");
2101 if (valueA.isNull()) {
2102 if (!valueB.isNull()) {
2103 return -1;
2104 }
2105 } else if (valueB.isNull()) {
2106 return +1;
2107 } else {
2108 if (valueA.toLongLong() < valueB.toLongLong()) {
2109 return -1;
2110 } else if (valueA.toLongLong() > valueB.toLongLong()) {
2111 return +1;
2112 }
2113 }
2114 break;
2115 }
2116
2117 KIO::filesize_t sizeA = 0;
2118 if (itemA.isDir()) {
2119 sizeA = a->values.value("size").toULongLong();
2120 } else {
2121 sizeA = itemA.size();
2122 }
2123 KIO::filesize_t sizeB = 0;
2124 if (itemB.isDir()) {
2125 sizeB = b->values.value("size").toULongLong();
2126 } else {
2127 sizeB = itemB.size();
2128 }
2129 if (sizeA < sizeB) {
2130 return -1;
2131 } else if (sizeA > sizeB) {
2132 return +1;
2133 }
2134 break;
2135 }
2136
2137 case ModificationTimeRole: {
2138 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2139 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2140 if (dateTimeA < dateTimeB) {
2141 return -1;
2142 } else if (dateTimeA > dateTimeB) {
2143 return +1;
2144 }
2145 break;
2146 }
2147
2148 case AccessTimeRole: {
2149 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2150 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2151 if (dateTimeA < dateTimeB) {
2152 return -1;
2153 } else if (dateTimeA > dateTimeB) {
2154 return +1;
2155 }
2156 break;
2157 }
2158
2159 case CreationTimeRole: {
2160 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2161 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2162 if (dateTimeA < dateTimeB) {
2163 return -1;
2164 } else if (dateTimeA > dateTimeB) {
2165 return +1;
2166 }
2167 break;
2168 }
2169
2170 case DeletionTimeRole: {
2171 const QDateTime dateTimeA = a->values.value("deletiontime").toDateTime();
2172 const QDateTime dateTimeB = b->values.value("deletiontime").toDateTime();
2173 if (dateTimeA < dateTimeB) {
2174 return -1;
2175 } else if (dateTimeA > dateTimeB) {
2176 return +1;
2177 }
2178 break;
2179 }
2180
2181 case RatingRole:
2182 case WidthRole:
2183 case HeightRole:
2184 case PublisherRole:
2185 case PageCountRole:
2186 case WordCountRole:
2187 case LineCountRole:
2188 case TrackRole:
2189 case ReleaseYearRole: {
2190 result = a->values.value(roleForType(m_sortRole)).toInt() - b->values.value(roleForType(m_sortRole)).toInt();
2191 break;
2192 }
2193
2194 case DimensionsRole: {
2195 const QByteArray role = roleForType(m_sortRole);
2196 const QSize dimensionsA = a->values.value(role).toSize();
2197 const QSize dimensionsB = b->values.value(role).toSize();
2198
2199 if (dimensionsA.width() == dimensionsB.width()) {
2200 result = dimensionsA.height() - dimensionsB.height();
2201 } else {
2202 result = dimensionsA.width() - dimensionsB.width();
2203 }
2204 break;
2205 }
2206
2207 default: {
2208 const QByteArray role = roleForType(m_sortRole);
2209 const QString roleValueA = a->values.value(role).toString();
2210 const QString roleValueB = b->values.value(role).toString();
2211 if (!roleValueA.isEmpty() && roleValueB.isEmpty()) {
2212 return -1;
2213 } else if (roleValueA.isEmpty() && !roleValueB.isEmpty()) {
2214 return +1;
2215 } else if (isRoleValueNatural(m_sortRole)) {
2216 result = stringCompare(roleValueA, roleValueB, collator);
2217 } else {
2218 result = QString::compare(roleValueA, roleValueB);
2219 }
2220 break;
2221 }
2222 }
2223
2224 if (result != 0) {
2225 // The current sort role was sufficient to define an order
2226 return result;
2227 }
2228
2229 // Fallback #1: Compare the text of the items
2230 result = stringCompare(itemA.text(), itemB.text(), collator);
2231 if (result != 0) {
2232 return result;
2233 }
2234
2235 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2236 result = stringCompare(itemA.name(), itemB.name(), collator);
2237 if (result != 0) {
2238 return result;
2239 }
2240
2241 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2242 // equal. In this case a comparison of the URL is done which is unique in all cases
2243 // within KDirLister.
2244 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
2245 }
2246
2247 int KFileItemModel::stringCompare(const QString &a, const QString &b, const QCollator &collator) const
2248 {
2249 QMutexLocker collatorLock(s_collatorMutex());
2250
2251 if (m_naturalSorting) {
2252 // Split extension, taking into account it can be empty
2253 constexpr QString::SectionFlags flags = QString::SectionSkipEmpty | QString::SectionIncludeLeadingSep;
2254
2255 // Sort by baseName first
2256 const QString aBaseName = a.section('.', 0, 0, flags);
2257 const QString bBaseName = b.section('.', 0, 0, flags);
2258
2259 const int res = collator.compare(aBaseName, bBaseName);
2260 if (res != 0 || (aBaseName.length() == a.length() && bBaseName.length() == b.length())) {
2261 return res;
2262 }
2263
2264 // sliced() has undefined behavior when pos < 0 or pos > size().
2265 Q_ASSERT(aBaseName.length() <= a.length() && aBaseName.length() >= 0);
2266 Q_ASSERT(bBaseName.length() <= b.length() && bBaseName.length() >= 0);
2267
2268 // baseNames were equal, sort by extension
2269 return collator.compare(a.sliced(aBaseName.length()), b.sliced(bBaseName.length()));
2270 }
2271
2272 const int result = QString::compare(a, b, collator.caseSensitivity());
2273 if (result != 0 || collator.caseSensitivity() == Qt::CaseSensitive) {
2274 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2275 // comparison, still a deterministic sort order is required. A case sensitive
2276 // comparison is done as fallback.
2277 return result;
2278 }
2279
2280 return QString::compare(a, b, Qt::CaseSensitive);
2281 }
2282
2283 QList<QPair<int, QVariant>> KFileItemModel::nameRoleGroups() const
2284 {
2285 Q_ASSERT(!m_itemData.isEmpty());
2286
2287 const int maxIndex = count() - 1;
2288 QList<QPair<int, QVariant>> groups;
2289
2290 QString groupValue;
2291 QChar firstChar;
2292 for (int i = 0; i <= maxIndex; ++i) {
2293 if (isChildItem(i)) {
2294 continue;
2295 }
2296
2297 const QString name = m_itemData.at(i)->item.text();
2298
2299 // Use the first character of the name as group indication
2300 QChar newFirstChar = name.at(0).toUpper();
2301 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
2302 newFirstChar = name.at(1).toUpper();
2303 }
2304
2305 if (firstChar != newFirstChar) {
2306 QString newGroupValue;
2307 if (newFirstChar.isLetter()) {
2308 if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) {
2309 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2310
2311 // Try to find a matching group in the range 'A' to 'Z'.
2312 static std::vector<QChar> lettersAtoZ;
2313 lettersAtoZ.reserve('Z' - 'A' + 1);
2314 if (lettersAtoZ.empty()) {
2315 for (char c = 'A'; c <= 'Z'; ++c) {
2316 lettersAtoZ.push_back(QLatin1Char(c));
2317 }
2318 }
2319
2320 auto localeAwareLessThan = [this](QChar c1, QChar c2) -> bool {
2321 return m_collator.compare(c1, c2) < 0;
2322 };
2323
2324 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), newFirstChar, localeAwareLessThan);
2325 if (it != lettersAtoZ.end()) {
2326 if (localeAwareLessThan(newFirstChar, *it)) {
2327 // newFirstChar belongs to the group preceding *it.
2328 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2329 --it;
2330 }
2331 newGroupValue = *it;
2332 }
2333
2334 } else {
2335 // Symbols from non Latin-based scripts
2336 newGroupValue = newFirstChar;
2337 }
2338 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
2339 // Apply group '0 - 9' for any name that starts with a digit
2340 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
2341 } else {
2342 newGroupValue = i18nc("@title:group", "Others");
2343 }
2344
2345 if (newGroupValue != groupValue) {
2346 groupValue = newGroupValue;
2347 groups.append(QPair<int, QVariant>(i, newGroupValue));
2348 }
2349
2350 firstChar = newFirstChar;
2351 }
2352 }
2353 return groups;
2354 }
2355
2356 QList<QPair<int, QVariant>> KFileItemModel::sizeRoleGroups() const
2357 {
2358 Q_ASSERT(!m_itemData.isEmpty());
2359
2360 const int maxIndex = count() - 1;
2361 QList<QPair<int, QVariant>> groups;
2362
2363 QString groupValue;
2364 for (int i = 0; i <= maxIndex; ++i) {
2365 if (isChildItem(i)) {
2366 continue;
2367 }
2368
2369 const KFileItem &item = m_itemData.at(i)->item;
2370 KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
2371 QString newGroupValue;
2372 if (!item.isNull() && item.isDir()) {
2373 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount || m_sortDirsFirst) {
2374 newGroupValue = i18nc("@title:group Size", "Folders");
2375 } else {
2376 fileSize = m_itemData.at(i)->values.value("size").toULongLong();
2377 }
2378 }
2379
2380 if (newGroupValue.isEmpty()) {
2381 if (fileSize < 5 * 1024 * 1024) { // < 5 MB
2382 newGroupValue = i18nc("@title:group Size", "Small");
2383 } else if (fileSize < 10 * 1024 * 1024) { // < 10 MB
2384 newGroupValue = i18nc("@title:group Size", "Medium");
2385 } else {
2386 newGroupValue = i18nc("@title:group Size", "Big");
2387 }
2388 }
2389
2390 if (newGroupValue != groupValue) {
2391 groupValue = newGroupValue;
2392 groups.append(QPair<int, QVariant>(i, newGroupValue));
2393 }
2394 }
2395
2396 return groups;
2397 }
2398
2399 QList<QPair<int, QVariant>> KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
2400 {
2401 Q_ASSERT(!m_itemData.isEmpty());
2402
2403 const int maxIndex = count() - 1;
2404 QList<QPair<int, QVariant>> groups;
2405
2406 const QDate currentDate = QDate::currentDate();
2407
2408 QDate previousFileDate;
2409 QString groupValue;
2410 for (int i = 0; i <= maxIndex; ++i) {
2411 if (isChildItem(i)) {
2412 continue;
2413 }
2414
2415 const QLocale locale;
2416 const QDateTime fileTime = fileTimeCb(m_itemData.at(i));
2417 const QDate fileDate = fileTime.date();
2418 if (fileDate == previousFileDate) {
2419 // The current item is in the same group as the previous item
2420 continue;
2421 }
2422 previousFileDate = fileDate;
2423
2424 const int daysDistance = fileDate.daysTo(currentDate);
2425
2426 QString newGroupValue;
2427 if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) {
2428 switch (daysDistance / 7) {
2429 case 0:
2430 switch (daysDistance) {
2431 case 0:
2432 newGroupValue = i18nc("@title:group Date", "Today");
2433 break;
2434 case 1:
2435 newGroupValue = i18nc("@title:group Date", "Yesterday");
2436 break;
2437 default:
2438 newGroupValue = locale.toString(fileTime, i18nc("@title:group Date: The week day name: dddd", "dddd"));
2439 newGroupValue = i18nc(
2440 "Can be used to script translation of \"dddd\""
2441 "with context @title:group Date",
2442 "%1",
2443 newGroupValue);
2444 }
2445 break;
2446 case 1:
2447 newGroupValue = i18nc("@title:group Date", "One Week Ago");
2448 break;
2449 case 2:
2450 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
2451 break;
2452 case 3:
2453 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
2454 break;
2455 case 4:
2456 case 5:
2457 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
2458 break;
2459 default:
2460 Q_ASSERT(false);
2461 }
2462 } else {
2463 const QDate lastMonthDate = currentDate.addMonths(-1);
2464 if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) {
2465 if (daysDistance == 1) {
2466 const KLocalizedString format = ki18nc(
2467 "@title:group Date: "
2468 "MMMM is full month name in current locale, and yyyy is "
2469 "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 "
2470 "part of the text that should not be formatted as a date",
2471 "'Yesterday' (MMMM, yyyy)");
2472 const QString translatedFormat = format.toString();
2473 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2474 newGroupValue = locale.toString(fileTime, translatedFormat);
2475 newGroupValue = i18nc(
2476 "Can be used to script translation of "
2477 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2478 "%1",
2479 newGroupValue);
2480 } else {
2481 qCWarning(DolphinDebug).nospace()
2482 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2483 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2484 newGroupValue = locale.toString(fileTime, untranslatedFormat);
2485 }
2486 } else if (daysDistance <= 7) {
2487 newGroupValue = locale.toString(fileTime,
2488 i18nc("@title:group Date: "
2489 "The week day name: dddd, MMMM is full month name "
2490 "in current locale, and yyyy is full year number.",
2491 "dddd (MMMM, yyyy)"));
2492 newGroupValue = i18nc(
2493 "Can be used to script translation of "
2494 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2495 "%1",
2496 newGroupValue);
2497 } else if (daysDistance <= 7 * 2) {
2498 const KLocalizedString format = ki18nc(
2499 "@title:group Date: "
2500 "MMMM is full month name in current locale, and yyyy is "
2501 "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 "
2502 "part of the text that should not be formatted as a date",
2503 "'One Week Ago' (MMMM, yyyy)");
2504 const QString translatedFormat = format.toString();
2505 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2506 newGroupValue = locale.toString(fileTime, translatedFormat);
2507 newGroupValue = i18nc(
2508 "Can be used to script translation of "
2509 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2510 "%1",
2511 newGroupValue);
2512 } else {
2513 qCWarning(DolphinDebug).nospace()
2514 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2515 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2516 newGroupValue = locale.toString(fileTime, untranslatedFormat);
2517 }
2518 } else if (daysDistance <= 7 * 3) {
2519 const KLocalizedString format = ki18nc(
2520 "@title:group Date: "
2521 "MMMM is full month name in current locale, and yyyy is "
2522 "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 "
2523 "part of the text that should not be formatted as a date",
2524 "'Two Weeks Ago' (MMMM, yyyy)");
2525 const QString translatedFormat = format.toString();
2526 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2527 newGroupValue = locale.toString(fileTime, translatedFormat);
2528 newGroupValue = i18nc(
2529 "Can be used to script translation of "
2530 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2531 "%1",
2532 newGroupValue);
2533 } else {
2534 qCWarning(DolphinDebug).nospace()
2535 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2536 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2537 newGroupValue = locale.toString(fileTime, untranslatedFormat);
2538 }
2539 } else if (daysDistance <= 7 * 4) {
2540 const KLocalizedString format = ki18nc(
2541 "@title:group Date: "
2542 "MMMM is full month name in current locale, and yyyy is "
2543 "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 "
2544 "part of the text that should not be formatted as a date",
2545 "'Three Weeks Ago' (MMMM, yyyy)");
2546 const QString translatedFormat = format.toString();
2547 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2548 newGroupValue = locale.toString(fileTime, translatedFormat);
2549 newGroupValue = i18nc(
2550 "Can be used to script translation of "
2551 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2552 "%1",
2553 newGroupValue);
2554 } else {
2555 qCWarning(DolphinDebug).nospace()
2556 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2557 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2558 newGroupValue = locale.toString(fileTime, untranslatedFormat);
2559 }
2560 } else {
2561 const KLocalizedString format = ki18nc(
2562 "@title:group Date: "
2563 "MMMM is full month name in current locale, and yyyy is "
2564 "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 "
2565 "part of the text that should not be formatted as a date",
2566 "'Earlier on' MMMM, yyyy");
2567 const QString translatedFormat = format.toString();
2568 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2569 newGroupValue = locale.toString(fileTime, translatedFormat);
2570 newGroupValue = i18nc(
2571 "Can be used to script translation of "
2572 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2573 "%1",
2574 newGroupValue);
2575 } else {
2576 qCWarning(DolphinDebug).nospace()
2577 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2578 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2579 newGroupValue = locale.toString(fileTime, untranslatedFormat);
2580 }
2581 }
2582 } else {
2583 newGroupValue = locale.toString(fileTime,
2584 i18nc("@title:group "
2585 "The month and year: MMMM is full month name in current locale, "
2586 "and yyyy is full year number",
2587 "MMMM, yyyy"));
2588 newGroupValue = i18nc(
2589 "Can be used to script translation of "
2590 "\"MMMM, yyyy\" with context @title:group Date",
2591 "%1",
2592 newGroupValue);
2593 }
2594 }
2595
2596 if (newGroupValue != groupValue) {
2597 groupValue = newGroupValue;
2598 groups.append(QPair<int, QVariant>(i, newGroupValue));
2599 }
2600 }
2601
2602 return groups;
2603 }
2604
2605 QList<QPair<int, QVariant>> KFileItemModel::permissionRoleGroups() const
2606 {
2607 Q_ASSERT(!m_itemData.isEmpty());
2608
2609 const int maxIndex = count() - 1;
2610 QList<QPair<int, QVariant>> groups;
2611
2612 QString permissionsString;
2613 QString groupValue;
2614 for (int i = 0; i <= maxIndex; ++i) {
2615 if (isChildItem(i)) {
2616 continue;
2617 }
2618
2619 const ItemData *itemData = m_itemData.at(i);
2620 const QString newPermissionsString = itemData->values.value("permissions").toString();
2621 if (newPermissionsString == permissionsString) {
2622 continue;
2623 }
2624 permissionsString = newPermissionsString;
2625
2626 const QFileInfo info(itemData->item.url().toLocalFile());
2627
2628 // Set user string
2629 QString user;
2630 if (info.permission(QFile::ReadUser)) {
2631 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
2632 }
2633 if (info.permission(QFile::WriteUser)) {
2634 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
2635 }
2636 if (info.permission(QFile::ExeUser)) {
2637 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2638 }
2639 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.length() - 2);
2640
2641 // Set group string
2642 QString group;
2643 if (info.permission(QFile::ReadGroup)) {
2644 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
2645 }
2646 if (info.permission(QFile::WriteGroup)) {
2647 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
2648 }
2649 if (info.permission(QFile::ExeGroup)) {
2650 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2651 }
2652 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.length() - 2);
2653
2654 // Set others string
2655 QString others;
2656 if (info.permission(QFile::ReadOther)) {
2657 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
2658 }
2659 if (info.permission(QFile::WriteOther)) {
2660 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
2661 }
2662 if (info.permission(QFile::ExeOther)) {
2663 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2664 }
2665 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.length() - 2);
2666
2667 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
2668 if (newGroupValue != groupValue) {
2669 groupValue = newGroupValue;
2670 groups.append(QPair<int, QVariant>(i, newGroupValue));
2671 }
2672 }
2673
2674 return groups;
2675 }
2676
2677 QList<QPair<int, QVariant>> KFileItemModel::ratingRoleGroups() const
2678 {
2679 Q_ASSERT(!m_itemData.isEmpty());
2680
2681 const int maxIndex = count() - 1;
2682 QList<QPair<int, QVariant>> groups;
2683
2684 int groupValue = -1;
2685 for (int i = 0; i <= maxIndex; ++i) {
2686 if (isChildItem(i)) {
2687 continue;
2688 }
2689 const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt();
2690 if (newGroupValue != groupValue) {
2691 groupValue = newGroupValue;
2692 groups.append(QPair<int, QVariant>(i, newGroupValue));
2693 }
2694 }
2695
2696 return groups;
2697 }
2698
2699 QList<QPair<int, QVariant>> KFileItemModel::genericStringRoleGroups(const QByteArray &role) const
2700 {
2701 Q_ASSERT(!m_itemData.isEmpty());
2702
2703 const int maxIndex = count() - 1;
2704 QList<QPair<int, QVariant>> groups;
2705
2706 bool isFirstGroupValue = true;
2707 QString groupValue;
2708 for (int i = 0; i <= maxIndex; ++i) {
2709 if (isChildItem(i)) {
2710 continue;
2711 }
2712 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
2713 if (newGroupValue != groupValue || isFirstGroupValue) {
2714 groupValue = newGroupValue;
2715 groups.append(QPair<int, QVariant>(i, newGroupValue));
2716 isFirstGroupValue = false;
2717 }
2718 }
2719
2720 return groups;
2721 }
2722
2723 void KFileItemModel::emitSortProgress(int resolvedCount)
2724 {
2725 // Be tolerant against a resolvedCount with a wrong range.
2726 // Although there should not be a case where KFileItemModelRolesUpdater
2727 // (= caller) provides a wrong range, it is important to emit
2728 // a useful progress information even if there is an unexpected
2729 // implementation issue.
2730
2731 const int itemCount = count();
2732 if (resolvedCount >= itemCount) {
2733 m_sortingProgressPercent = -1;
2734 if (m_resortAllItemsTimer->isActive()) {
2735 m_resortAllItemsTimer->stop();
2736 resortAllItems();
2737 }
2738
2739 Q_EMIT directorySortingProgress(100);
2740 } else if (itemCount > 0) {
2741 resolvedCount = qBound(0, resolvedCount, itemCount);
2742
2743 const int progress = resolvedCount * 100 / itemCount;
2744 if (m_sortingProgressPercent != progress) {
2745 m_sortingProgressPercent = progress;
2746 Q_EMIT directorySortingProgress(progress);
2747 }
2748 }
2749 }
2750
2751 const KFileItemModel::RoleInfoMap *KFileItemModel::rolesInfoMap(int &count)
2752 {
2753 static const RoleInfoMap rolesInfoMap[] = {
2754 // clang-format off
2755 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2756 { nullptr, NoRole, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2757 { "text", NameRole, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2758 { "size", SizeRole, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2759 { "modificationtime", ModificationTimeRole, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2760 { "creationtime", CreationTimeRole, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2761 { "accesstime", AccessTimeRole, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2762 { "type", TypeRole, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2763 { "rating", RatingRole, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2764 { "tags", TagsRole, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2765 { "comment", CommentRole, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2766 { "title", TitleRole, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2767 { "author", AuthorRole, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2768 { "publisher", PublisherRole, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2769 { "pageCount", PageCountRole, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2770 { "wordCount", WordCountRole, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2771 { "lineCount", LineCountRole, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2772 { "imageDateTime", ImageDateTimeRole, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2773 { "dimensions", DimensionsRole, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2774 { "width", WidthRole, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2775 { "height", HeightRole, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2776 { "orientation", OrientationRole, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2777 { "artist", ArtistRole, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2778 { "genre", GenreRole, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2779 { "album", AlbumRole, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2780 { "duration", DurationRole, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2781 { "bitrate", BitrateRole, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2782 { "track", TrackRole, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2783 { "releaseYear", ReleaseYearRole, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2784 { "aspectRatio", AspectRatioRole, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2785 { "frameRate", FrameRateRole, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2786 { "duration", DurationRole, kli18nc("@label", "Duration"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2787 { "path", PathRole, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2788 { "extension", ExtensionRole, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2789 { "deletiontime", DeletionTimeRole, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2790 { "destination", DestinationRole, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2791 { "originUrl", OriginUrlRole, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2792 { "permissions", PermissionsRole, kli18nc("@label", "Permissions"), kli18nc("@label", "Other"), kli18nc("@tooltip", "The permission format can be changed in settings. Options are Symbolic, Numeric (Octal) or Combined formats"), false, false },
2793 { "owner", OwnerRole, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2794 { "group", GroupRole, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2795 };
2796 // clang-format on
2797
2798 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
2799 return rolesInfoMap;
2800 }
2801
2802 void KFileItemModel::determineMimeTypes(const KFileItemList &items, int timeout)
2803 {
2804 QElapsedTimer timer;
2805 timer.start();
2806 for (const KFileItem &item : items) {
2807 // Only determine mime types for files here. For directories,
2808 // KFileItem::determineMimeType() reads the .directory file inside to
2809 // load the icon, but this is not necessary at all if we just need the
2810 // type. Some special code for setting the correct mime type for
2811 // directories is in retrieveData().
2812 if (!item.isDir()) {
2813 item.determineMimeType();
2814 }
2815
2816 if (timer.elapsed() > timeout) {
2817 // Don't block the user interface, let the remaining items
2818 // be resolved asynchronously.
2819 return;
2820 }
2821 }
2822 }
2823
2824 QByteArray KFileItemModel::sharedValue(const QByteArray &value)
2825 {
2826 static QSet<QByteArray> pool;
2827 const QSet<QByteArray>::const_iterator it = pool.constFind(value);
2828
2829 if (it != pool.constEnd()) {
2830 return *it;
2831 } else {
2832 pool.insert(value);
2833 return value;
2834 }
2835 }
2836
2837 bool KFileItemModel::isConsistent() const
2838 {
2839 // m_items may contain less items than m_itemData because m_items
2840 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2841 if (m_items.count() > m_itemData.count()) {
2842 return false;
2843 }
2844
2845 for (int i = 0, iMax = count(); i < iMax; ++i) {
2846 // Check if m_items and m_itemData are consistent.
2847 const KFileItem item = fileItem(i);
2848 if (item.isNull()) {
2849 qCWarning(DolphinDebug) << "Item" << i << "is null";
2850 return false;
2851 }
2852
2853 const int itemIndex = index(item);
2854 if (itemIndex != i) {
2855 qCWarning(DolphinDebug) << "Item" << i << "has a wrong index:" << itemIndex;
2856 return false;
2857 }
2858
2859 // Check if the items are sorted correctly.
2860 if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
2861 qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" << fileItem(i - 1) << fileItem(i);
2862 return false;
2863 }
2864
2865 // Check if all parent-child relationships are consistent.
2866 const ItemData *data = m_itemData.at(i);
2867 const ItemData *parent = data->parent;
2868 if (parent) {
2869 if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
2870 qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
2871 return false;
2872 }
2873
2874 const int parentIndex = index(parent->item);
2875 if (parentIndex >= i) {
2876 qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child"
2877 << data->item;
2878 return false;
2879 }
2880 }
2881 }
2882
2883 return true;
2884 }
2885
2886 void KFileItemModel::slotListerError(KIO::Job *job)
2887 {
2888 const int jobError = job->error();
2889 if (jobError == KIO::ERR_IS_FILE) {
2890 if (auto *listJob = qobject_cast<KIO::ListJob *>(job)) {
2891 Q_EMIT urlIsFileError(listJob->url());
2892 }
2893 } else {
2894 const QString errorString = job->errorString();
2895 Q_EMIT errorMessage(!errorString.isEmpty() ? errorString : i18nc("@info:status", "Unknown error."), jobError);
2896 }
2897 }
2898
2899 #include "moc_kfileitemmodel.cpp"