]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Merge branch 'work/zakharafoniam/useful-groups' of https://invent.kde.org/zakharafoni...
[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 #include <QElapsedTimer>
24 #include <QIcon>
25 #include <QMimeData>
26 #include <QMimeDatabase>
27 #include <QRecursiveMutex>
28 #include <QTimer>
29 #include <QWidget>
30 #include <klazylocalizedstring.h>
31
32 Q_GLOBAL_STATIC(QRecursiveMutex, s_collatorMutex)
33
34 // #define KFILEITEMMODEL_DEBUG
35
36 KFileItemModel::KFileItemModel(QObject *parent)
37 : KItemModelBase("text", "none", parent)
38 , m_dirLister(nullptr)
39 , m_sortDirsFirst(true)
40 , m_sortHiddenLast(false)
41 , m_sortRole(NameRole)
42 , m_sortingProgressPercent(-1)
43 , m_roles()
44 , m_itemData()
45 , m_items()
46 , m_filter()
47 , m_filteredItems()
48 , m_requestRole()
49 , m_maximumUpdateIntervalTimer(nullptr)
50 , m_resortAllItemsTimer(nullptr)
51 , m_pendingItemsToInsert()
52 , m_groups()
53 , m_expandedDirs()
54 , m_urlsToExpand()
55 {
56 m_collator.setNumericMode(true);
57
58 loadSortingSettings();
59
60 m_dirLister = new KDirLister(this);
61 m_dirLister->setAutoErrorHandlingEnabled(false);
62 m_dirLister->setDelayedMimeTypes(true);
63
64 const QWidget *parentWidget = qobject_cast<QWidget *>(parent);
65 if (parentWidget) {
66 m_dirLister->setMainWindow(parentWidget->window());
67 }
68
69 connect(m_dirLister, &KCoreDirLister::started, this, &KFileItemModel::directoryLoadingStarted);
70 connect(m_dirLister, &KCoreDirLister::canceled, this, &KFileItemModel::slotCanceled);
71 connect(m_dirLister, &KCoreDirLister::itemsAdded, this, &KFileItemModel::slotItemsAdded);
72 connect(m_dirLister, &KCoreDirLister::itemsDeleted, this, &KFileItemModel::slotItemsDeleted);
73 connect(m_dirLister, &KCoreDirLister::refreshItems, this, &KFileItemModel::slotRefreshItems);
74 connect(m_dirLister, &KCoreDirLister::clear, this, &KFileItemModel::slotClear);
75 connect(m_dirLister, &KCoreDirLister::infoMessage, this, &KFileItemModel::infoMessage);
76 connect(m_dirLister, &KCoreDirLister::jobError, this, &KFileItemModel::slotListerError);
77 connect(m_dirLister, &KCoreDirLister::percent, this, &KFileItemModel::directoryLoadingProgress);
78 connect(m_dirLister, &KCoreDirLister::redirection, this, &KFileItemModel::directoryRedirection);
79 connect(m_dirLister, &KCoreDirLister::listingDirCompleted, this, &KFileItemModel::slotCompleted);
80
81 // Apply default roles that should be determined
82 resetRoles();
83 m_requestRole[NameRole] = true;
84 m_requestRole[IsDirRole] = true;
85 m_requestRole[IsLinkRole] = true;
86 m_roles.insert("text");
87 m_roles.insert("isDir");
88 m_roles.insert("isLink");
89 m_roles.insert("isHidden");
90
91 // For slow KIO-slaves like used for searching it makes sense to show results periodically even
92 // before the completed() or canceled() signal has been emitted.
93 m_maximumUpdateIntervalTimer = new QTimer(this);
94 m_maximumUpdateIntervalTimer->setInterval(2000);
95 m_maximumUpdateIntervalTimer->setSingleShot(true);
96 connect(m_maximumUpdateIntervalTimer, &QTimer::timeout, this, &KFileItemModel::dispatchPendingItemsToInsert);
97
98 // When changing the value of an item which represents the sort-role a resorting must be
99 // triggered. Especially in combination with KFileItemModelRolesUpdater this might be done
100 // for a lot of items within a quite small timeslot. To prevent expensive resortings the
101 // resorting is postponed until the timer has been exceeded.
102 m_resortAllItemsTimer = new QTimer(this);
103 m_resortAllItemsTimer->setInterval(100); // 100 is a middle ground between sorting too frequently which makes the view unreadable
104 // and sorting too infrequently which leads to users seeing an outdated sort order.
105 m_resortAllItemsTimer->setSingleShot(true);
106 connect(m_resortAllItemsTimer, &QTimer::timeout, this, &KFileItemModel::resortAllItems);
107
108 connect(GeneralSettings::self(), &GeneralSettings::sortingChoiceChanged, this, &KFileItemModel::slotSortingChoiceChanged);
109
110 setShowTrashMime(m_dirLister->showHiddenFiles() || !GeneralSettings::hideXTrashFile());
111 }
112
113 KFileItemModel::~KFileItemModel()
114 {
115 qDeleteAll(m_itemData);
116 qDeleteAll(m_filteredItems);
117 qDeleteAll(m_pendingItemsToInsert);
118 }
119
120 void KFileItemModel::loadDirectory(const QUrl &url)
121 {
122 m_dirLister->openUrl(url);
123 }
124
125 void KFileItemModel::refreshDirectory(const QUrl &url)
126 {
127 // Refresh all expanded directories first (Bug 295300)
128 QHashIterator<QUrl, QUrl> expandedDirs(m_expandedDirs);
129 while (expandedDirs.hasNext()) {
130 expandedDirs.next();
131 m_dirLister->openUrl(expandedDirs.value(), KDirLister::Reload);
132 }
133
134 m_dirLister->openUrl(url, KDirLister::Reload);
135
136 Q_EMIT directoryRefreshing();
137 }
138
139 QUrl KFileItemModel::directory() const
140 {
141 return m_dirLister->url();
142 }
143
144 void KFileItemModel::cancelDirectoryLoading()
145 {
146 m_dirLister->stop();
147 }
148
149 int KFileItemModel::count() const
150 {
151 return m_itemData.count();
152 }
153
154 QHash<QByteArray, QVariant> KFileItemModel::data(int index) const
155 {
156 if (index >= 0 && index < count()) {
157 ItemData *data = m_itemData.at(index);
158 if (data->values.isEmpty()) {
159 data->values = retrieveData(data->item, data->parent);
160 } else if (data->values.count() <= 2 && data->values.value("isExpanded").toBool()) {
161 // Special case dealt by slotRefreshItems(), avoid losing the "isExpanded" and "expandedParentsCount" state when refreshing
162 // slotRefreshItems() makes sure folders keep the "isExpanded" and "expandedParentsCount" while clearing the remaining values
163 // so this special request of different behavior can be identified here.
164 bool hasExpandedParentsCount = false;
165 const int expandedParentsCount = data->values.value("expandedParentsCount").toInt(&hasExpandedParentsCount);
166
167 data->values = retrieveData(data->item, data->parent);
168 data->values.insert("isExpanded", true);
169 if (hasExpandedParentsCount) {
170 data->values.insert("expandedParentsCount", expandedParentsCount);
171 }
172 }
173
174 return data->values;
175 }
176 return QHash<QByteArray, QVariant>();
177 }
178
179 bool KFileItemModel::setData(int index, const QHash<QByteArray, QVariant> &values)
180 {
181 if (index < 0 || index >= count()) {
182 return false;
183 }
184
185 QHash<QByteArray, QVariant> currentValues = data(index);
186
187 // Determine which roles have been changed
188 QSet<QByteArray> changedRoles;
189 QHashIterator<QByteArray, QVariant> it(values);
190 while (it.hasNext()) {
191 it.next();
192 const QByteArray role = sharedValue(it.key());
193 const QVariant value = it.value();
194
195 if (currentValues[role] != value) {
196 currentValues[role] = value;
197 changedRoles.insert(role);
198 }
199 }
200
201 if (changedRoles.isEmpty()) {
202 return false;
203 }
204
205 m_itemData[index]->values = currentValues;
206 if (changedRoles.contains("text")) {
207 QUrl url = m_itemData[index]->item.url();
208 url = url.adjusted(QUrl::RemoveFilename);
209 url.setPath(url.path() + currentValues["text"].toString());
210 m_itemData[index]->item.setUrl(url);
211 }
212
213 emitItemsChangedAndTriggerResorting(KItemRangeList() << KItemRange(index, 1), changedRoles);
214
215 return true;
216 }
217
218 void KFileItemModel::setSortDirectoriesFirst(bool dirsFirst)
219 {
220 if (dirsFirst != m_sortDirsFirst) {
221 m_sortDirsFirst = dirsFirst;
222 resortAllItems();
223 }
224 }
225
226 bool KFileItemModel::sortDirectoriesFirst() const
227 {
228 return m_sortDirsFirst;
229 }
230
231 void KFileItemModel::setSortHiddenLast(bool hiddenLast)
232 {
233 if (hiddenLast != m_sortHiddenLast) {
234 m_sortHiddenLast = hiddenLast;
235 resortAllItems();
236 }
237 }
238
239 bool KFileItemModel::sortHiddenLast() const
240 {
241 return m_sortHiddenLast;
242 }
243
244 void KFileItemModel::setShowTrashMime(bool showTrashMime)
245 {
246 const auto trashMime = QStringLiteral("application/x-trash");
247 QStringList excludeFilter = m_filter.excludeMimeTypes();
248
249 if (showTrashMime) {
250 excludeFilter.removeAll(trashMime);
251 } else if (!excludeFilter.contains(trashMime)) {
252 excludeFilter.append(trashMime);
253 }
254
255 setExcludeMimeTypeFilter(excludeFilter);
256 }
257
258 void KFileItemModel::scheduleResortAllItems()
259 {
260 if (!m_resortAllItemsTimer->isActive()) {
261 m_resortAllItemsTimer->start();
262 }
263 }
264
265 void KFileItemModel::setShowHiddenFiles(bool show)
266 {
267 m_dirLister->setShowHiddenFiles(show);
268 setShowTrashMime(show || !GeneralSettings::hideXTrashFile());
269 m_dirLister->emitChanges();
270 if (show) {
271 dispatchPendingItemsToInsert();
272 }
273 }
274
275 bool KFileItemModel::showHiddenFiles() const
276 {
277 return m_dirLister->showHiddenFiles();
278 }
279
280 void KFileItemModel::setShowDirectoriesOnly(bool enabled)
281 {
282 m_dirLister->setDirOnlyMode(enabled);
283 }
284
285 bool KFileItemModel::showDirectoriesOnly() const
286 {
287 return m_dirLister->dirOnlyMode();
288 }
289
290 QMimeData *KFileItemModel::createMimeData(const KItemSet &indexes) const
291 {
292 QMimeData *data = new QMimeData();
293
294 // The following code has been taken from KDirModel::mimeData()
295 // (kdelibs/kio/kio/kdirmodel.cpp)
296 // SPDX-FileCopyrightText: 2006 David Faure <faure@kde.org>
297 QList<QUrl> urls;
298 QList<QUrl> mostLocalUrls;
299 const ItemData *lastAddedItem = nullptr;
300
301 for (int index : indexes) {
302 const ItemData *itemData = m_itemData.at(index);
303 const ItemData *parent = itemData->parent;
304
305 while (parent && parent != lastAddedItem) {
306 parent = parent->parent;
307 }
308
309 if (parent && parent == lastAddedItem) {
310 // A parent of 'itemData' has been added already.
311 continue;
312 }
313
314 lastAddedItem = itemData;
315 const KFileItem &item = itemData->item;
316 if (!item.isNull()) {
317 urls << item.url();
318
319 bool isLocal;
320 mostLocalUrls << item.mostLocalUrl(&isLocal);
321 }
322 }
323
324 KUrlMimeData::setUrls(urls, mostLocalUrls, data);
325 return data;
326 }
327
328 int KFileItemModel::indexForKeyboardSearch(const QString &text, int startFromIndex) const
329 {
330 startFromIndex = qMax(0, startFromIndex);
331 for (int i = startFromIndex; i < count(); ++i) {
332 if (fileItem(i).text().startsWith(text, Qt::CaseInsensitive)) {
333 return i;
334 }
335 }
336 for (int i = 0; i < startFromIndex; ++i) {
337 if (fileItem(i).text().startsWith(text, Qt::CaseInsensitive)) {
338 return i;
339 }
340 }
341 return -1;
342 }
343
344 bool KFileItemModel::supportsDropping(int index) const
345 {
346 KFileItem item;
347 if (index == -1) {
348 item = rootItem();
349 } else {
350 item = fileItem(index);
351 }
352 return !item.isNull() && DragAndDropHelper::supportsDropping(item);
353 }
354
355 bool KFileItemModel::canEnterOnHover(int index) const
356 {
357 KFileItem item;
358 if (index == -1) {
359 item = rootItem();
360 } else {
361 item = fileItem(index);
362 }
363 return !item.isNull() && (item.isDir() || item.isDesktopFile());
364 }
365
366 QString KFileItemModel::roleDescription(const QByteArray &role) const
367 {
368 static QHash<QByteArray, QString> description;
369 if (description.isEmpty()) {
370 int count = 0;
371 const RoleInfoMap *map = rolesInfoMap(count);
372 for (int i = 0; i < count; ++i) {
373 if (map[i].roleTranslation.isEmpty()) {
374 continue;
375 }
376 description.insert(map[i].role, map[i].roleTranslation.toString());
377 }
378 }
379
380 return description.value(role);
381 }
382
383 QList<QPair<int, QVariant>> KFileItemModel::groups() const
384 {
385 if (!m_itemData.isEmpty() && m_groups.isEmpty()) {
386 #ifdef KFILEITEMMODEL_DEBUG
387 QElapsedTimer timer;
388 timer.start();
389 #endif
390 QByteArray role = groupRole();
391 if (typeForRole(role) == NoRole) {
392 // Handle extra grouping information
393 if (m_groupExtraInfo == "followSort") {
394 role = sortRole();
395 }
396 }
397 switch (typeForRole(role)) {
398 case NoRole:
399 m_groups.clear();
400 break;
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(role);
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 KFileItemModel::RoleInfo KFileItemModel::roleInformation(const QByteArray &role)
900 {
901 static QHash<QByteArray, RoleInfo> information;
902 if (information.isEmpty()) {
903 int count = 0;
904 const RoleInfoMap *map = rolesInfoMap(count);
905 for (int i = 0; i < count; ++i) {
906 RoleInfo info;
907 info.role = map[i].role;
908 info.translation = map[i].roleTranslation.toString();
909 if (!map[i].groupTranslation.isEmpty()) {
910 info.group = map[i].groupTranslation.toString();
911 } else {
912 // For top level roles, groupTranslation is 0. We must make sure that
913 // info.group is an empty string then because the code that generates
914 // menus tries to put the actions into sub menus otherwise.
915 info.group = QString();
916 }
917 info.requiresBaloo = map[i].requiresBaloo;
918 info.requiresIndexer = map[i].requiresIndexer;
919 if (!map[i].tooltipTranslation.isEmpty()) {
920 info.tooltip = map[i].tooltipTranslation.toString();
921 } else {
922 info.tooltip = QString();
923 }
924
925 information.insert(map[i].role, info);
926 }
927 }
928
929 return information.value(role);
930 }
931
932 QList<KFileItemModel::RoleInfo> KFileItemModel::rolesInformation()
933 {
934 static QList<RoleInfo> rolesInfo;
935 if (rolesInfo.isEmpty()) {
936 int count = 0;
937 const RoleInfoMap *map = rolesInfoMap(count);
938 for (int i = 0; i < count; ++i) {
939 if (map[i].roleType != NoRole) {
940 RoleInfo info = roleInformation(map[i].role);
941 rolesInfo.append(info);
942 }
943 }
944 }
945
946 return rolesInfo;
947 }
948
949 QList<KFileItemModel::RoleInfo> KFileItemModel::extraGroupingInformation()
950 {
951 static QList<RoleInfo> rolesInfo{
952 {QByteArray("none"), kli18nc("@label", "No grouping").toString(), nullptr, nullptr, false, false},
953 {QByteArray("followSort"), kli18nc("@label", "Follow sorting").toString(), nullptr, nullptr, false, false}
954 };
955 return rolesInfo;
956 }
957
958 void KFileItemModel::onGroupedSortingChanged(bool current)
959 {
960 Q_UNUSED(current)
961 m_groups.clear();
962 }
963
964 void KFileItemModel::onSortRoleChanged(const QByteArray &current, const QByteArray &previous, bool resortItems)
965 {
966 Q_UNUSED(previous)
967 m_sortRole = typeForRole(current);
968 if (m_sortRole == NoRole) {
969 // Requested role not in list of roles. This could
970 // be used for indicating non-trivial sorting behavior
971 m_sortExtraInfo = current;
972 } else {
973 m_sortExtraInfo.clear();
974 }
975
976 if (!m_requestRole[m_sortRole]) {
977 QSet<QByteArray> newRoles = m_roles;
978 newRoles << current;
979 setRoles(newRoles);
980 }
981
982 if (resortItems) {
983 resortAllItems();
984 }
985 }
986
987 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
988 {
989 Q_UNUSED(current)
990 Q_UNUSED(previous)
991 resortAllItems();
992 }
993
994 void KFileItemModel::onGroupRoleChanged(const QByteArray &current, const QByteArray &previous, bool resortItems)
995 {
996 Q_UNUSED(previous)
997 m_groupRole = typeForRole(current);
998 if (m_groupRole == NoRole) {
999 // Requested role not in list of roles. This could
1000 // be used for indicating non-trivial grouping behavior
1001 m_groupExtraInfo = current;
1002 } else {
1003 m_groupExtraInfo.clear();
1004 }
1005
1006 if (!m_requestRole[m_groupRole]) {
1007 QSet<QByteArray> newRoles = m_roles;
1008 newRoles << current;
1009 setRoles(newRoles);
1010 }
1011
1012 if (resortItems) {
1013 resortAllItems();
1014 }
1015 }
1016
1017 void KFileItemModel::onGroupOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
1018 {
1019 Q_UNUSED(current)
1020 Q_UNUSED(previous)
1021 resortAllItems();
1022 }
1023
1024 void KFileItemModel::loadSortingSettings()
1025 {
1026 using Choice = GeneralSettings::EnumSortingChoice;
1027 switch (GeneralSettings::sortingChoice()) {
1028 case Choice::NaturalSorting:
1029 m_naturalSorting = true;
1030 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
1031 break;
1032 case Choice::CaseSensitiveSorting:
1033 m_naturalSorting = false;
1034 m_collator.setCaseSensitivity(Qt::CaseSensitive);
1035 break;
1036 case Choice::CaseInsensitiveSorting:
1037 m_naturalSorting = false;
1038 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
1039 break;
1040 default:
1041 Q_UNREACHABLE();
1042 }
1043 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
1044 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
1045 m_collator.compare(QString(), QString());
1046 ContentDisplaySettings::self();
1047 }
1048
1049 void KFileItemModel::resortAllItems()
1050 {
1051 m_resortAllItemsTimer->stop();
1052
1053 const int itemCount = count();
1054 if (itemCount <= 0) {
1055 return;
1056 }
1057
1058 #ifdef KFILEITEMMODEL_DEBUG
1059 QElapsedTimer timer;
1060 timer.start();
1061 qCDebug(DolphinDebug) << "===========================================================";
1062 qCDebug(DolphinDebug) << "Resorting" << itemCount << "items";
1063 #endif
1064
1065 // Remember the order of the current URLs so
1066 // that it can be determined which indexes have
1067 // been moved because of the resorting.
1068 QList<QUrl> oldUrls;
1069 oldUrls.reserve(itemCount);
1070 for (const ItemData *itemData : std::as_const(m_itemData)) {
1071 oldUrls.append(itemData->item.url());
1072 }
1073
1074 m_items.clear();
1075 m_items.reserve(itemCount);
1076
1077 // Resort the items
1078 sort(m_itemData.begin(), m_itemData.end());
1079 for (int i = 0; i < itemCount; ++i) {
1080 m_items.insert(m_itemData.at(i)->item.url(), i);
1081 }
1082
1083 // Determine the first index that has been moved.
1084 int firstMovedIndex = 0;
1085 while (firstMovedIndex < itemCount && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) {
1086 ++firstMovedIndex;
1087 }
1088
1089 const bool itemsHaveMoved = firstMovedIndex < itemCount;
1090 if (itemsHaveMoved) {
1091 m_groups.clear();
1092
1093 int lastMovedIndex = itemCount - 1;
1094 while (lastMovedIndex > firstMovedIndex && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) {
1095 --lastMovedIndex;
1096 }
1097
1098 Q_ASSERT(firstMovedIndex <= lastMovedIndex);
1099
1100 // Create a list movedToIndexes, which has the property that
1101 // movedToIndexes[i] is the new index of the item with the old index
1102 // firstMovedIndex + i.
1103 const int movedItemsCount = lastMovedIndex - firstMovedIndex + 1;
1104 QList<int> movedToIndexes;
1105 movedToIndexes.reserve(movedItemsCount);
1106 for (int i = firstMovedIndex; i <= lastMovedIndex; ++i) {
1107 const int newIndex = m_items.value(oldUrls.at(i));
1108 movedToIndexes.append(newIndex);
1109 }
1110
1111 Q_EMIT itemsMoved(KItemRange(firstMovedIndex, movedItemsCount), movedToIndexes);
1112 }
1113 if (groupedSorting()) {
1114 // The groups might have changed even if the order of the items has not.
1115 const QList<QPair<int, QVariant>> oldGroups = m_groups;
1116 m_groups.clear();
1117 if (groups() != oldGroups) {
1118 Q_EMIT groupsChanged();
1119 }
1120 }
1121
1122 #ifdef KFILEITEMMODEL_DEBUG
1123 qCDebug(DolphinDebug) << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
1124 #endif
1125 }
1126
1127 void KFileItemModel::slotCompleted()
1128 {
1129 m_maximumUpdateIntervalTimer->stop();
1130 dispatchPendingItemsToInsert();
1131
1132 if (!m_urlsToExpand.isEmpty()) {
1133 // Try to find a URL that can be expanded.
1134 // Note that the parent folder must be expanded before any of its subfolders become visible.
1135 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
1136 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
1137 // Iterate over a const copy because items are deleted and inserted within the loop
1138 const auto urlsToExpand = m_urlsToExpand;
1139 for (const QUrl &url : urlsToExpand) {
1140 const int indexForUrl = index(url);
1141 if (indexForUrl >= 0) {
1142 m_urlsToExpand.remove(url);
1143 if (setExpanded(indexForUrl, true)) {
1144 // The dir lister has been triggered. This slot will be called
1145 // again after the directory has been expanded.
1146 return;
1147 }
1148 }
1149 }
1150
1151 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
1152 // if these URLs have been deleted in the meantime.
1153 m_urlsToExpand.clear();
1154 }
1155
1156 Q_EMIT directoryLoadingCompleted();
1157 }
1158
1159 void KFileItemModel::slotCanceled()
1160 {
1161 m_maximumUpdateIntervalTimer->stop();
1162 dispatchPendingItemsToInsert();
1163
1164 Q_EMIT directoryLoadingCanceled();
1165 }
1166
1167 void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList &items)
1168 {
1169 Q_ASSERT(!items.isEmpty());
1170
1171 const QUrl parentUrl = m_expandedDirs.value(directoryUrl, directoryUrl.adjusted(QUrl::StripTrailingSlash));
1172
1173 if (m_requestRole[ExpandedParentsCountRole]) {
1174 // If the expanding of items is enabled, the call
1175 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
1176 // might result in emitting the same items twice due to the Keep-parameter.
1177 // This case happens if an item gets expanded, collapsed and expanded again
1178 // before the items could be loaded for the first expansion.
1179 if (index(items.first().url()) >= 0) {
1180 // The items are already part of the model.
1181 return;
1182 }
1183
1184 if (directoryUrl != directory()) {
1185 // To be able to compare whether the new items may be inserted as children
1186 // of a parent item the pending items must be added to the model first.
1187 dispatchPendingItemsToInsert();
1188 }
1189
1190 // KDirLister keeps the children of items that got expanded once even if
1191 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
1192 // checked whether the parent for new items is still expanded.
1193 const int parentIndex = index(parentUrl);
1194 if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) {
1195 // The parent is not expanded.
1196 return;
1197 }
1198 }
1199
1200 const QList<ItemData *> itemDataList = createItemDataList(parentUrl, items);
1201
1202 if (!m_filter.hasSetFilters()) {
1203 m_pendingItemsToInsert.append(itemDataList);
1204 } else {
1205 QSet<ItemData *> parentsToEnsureVisible;
1206
1207 // The name or type filter is active. Hide filtered items
1208 // before inserting them into the model and remember
1209 // the filtered items in m_filteredItems.
1210 for (ItemData *itemData : itemDataList) {
1211 if (m_filter.matches(itemData->item)) {
1212 m_pendingItemsToInsert.append(itemData);
1213 if (itemData->parent) {
1214 parentsToEnsureVisible.insert(itemData->parent);
1215 }
1216 } else {
1217 m_filteredItems.insert(itemData->item, itemData);
1218 }
1219 }
1220
1221 // Entire parental chains must be shown
1222 for (ItemData *parent : parentsToEnsureVisible) {
1223 for (; parent && m_filteredItems.remove(parent->item); parent = parent->parent) {
1224 m_pendingItemsToInsert.append(parent);
1225 }
1226 }
1227 }
1228
1229 if (!m_maximumUpdateIntervalTimer->isActive()) {
1230 // Assure that items get dispatched if no completed() or canceled() signal is
1231 // emitted during the maximum update interval.
1232 m_maximumUpdateIntervalTimer->start();
1233 }
1234
1235 Q_EMIT fileItemsChanged({KFileItem(directoryUrl)});
1236 }
1237
1238 int KFileItemModel::filterChildlessParents(KItemRangeList &removedItemRanges, const QSet<ItemData *> &parentsToEnsureVisible)
1239 {
1240 int filteredParentsCount = 0;
1241 // The childless parents not yet removed will always be right above the start of a removed range.
1242 // We iterate backwards to ensure the deepest folders are processed before their parents
1243 for (int i = removedItemRanges.size() - 1; i >= 0; i--) {
1244 KItemRange itemRange = removedItemRanges.at(i);
1245 const ItemData *const firstInRange = m_itemData.at(itemRange.index);
1246 ItemData *itemAbove = itemRange.index - 1 >= 0 ? m_itemData.at(itemRange.index - 1) : nullptr;
1247 const ItemData *const itemBelow = itemRange.index + itemRange.count < m_itemData.count() ? m_itemData.at(itemRange.index + itemRange.count) : nullptr;
1248
1249 if (itemAbove && firstInRange->parent == itemAbove && !m_filter.matches(itemAbove->item) && (!itemBelow || itemBelow->parent != itemAbove)
1250 && !parentsToEnsureVisible.contains(itemAbove)) {
1251 // The item above exists, is the parent, doesn't pass the filter, does not belong to parentsToEnsureVisible
1252 // and this deleted range covers all of its descendents, so none will be left.
1253 m_filteredItems.insert(itemAbove->item, itemAbove);
1254 // This range's starting index will be extended to include the parent above:
1255 --itemRange.index;
1256 ++itemRange.count;
1257 ++filteredParentsCount;
1258 KItemRange previousRange = i > 0 ? removedItemRanges.at(i - 1) : KItemRange();
1259 // We must check if this caused the range to touch the previous range, if that's the case they shall be merged
1260 if (i > 0 && previousRange.index + previousRange.count == itemRange.index) {
1261 previousRange.count += itemRange.count;
1262 removedItemRanges.replace(i - 1, previousRange);
1263 removedItemRanges.removeAt(i);
1264 } else {
1265 removedItemRanges.replace(i, itemRange);
1266 // We must revisit this range in the next iteration since its starting index changed
1267 ++i;
1268 }
1269 }
1270 }
1271 return filteredParentsCount;
1272 }
1273
1274 void KFileItemModel::slotItemsDeleted(const KFileItemList &items)
1275 {
1276 dispatchPendingItemsToInsert();
1277
1278 QVector<int> indexesToRemove;
1279 indexesToRemove.reserve(items.count());
1280 KFileItemList dirsChanged;
1281
1282 const auto currentDir = directory();
1283
1284 for (const KFileItem &item : items) {
1285 if (item.url() == currentDir) {
1286 Q_EMIT currentDirectoryRemoved();
1287 return;
1288 }
1289
1290 const int indexForItem = index(item);
1291 if (indexForItem >= 0) {
1292 indexesToRemove.append(indexForItem);
1293 } else {
1294 // Probably the item has been filtered.
1295 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(item);
1296 if (it != m_filteredItems.end()) {
1297 delete it.value();
1298 m_filteredItems.erase(it);
1299 }
1300 }
1301
1302 QUrl parentUrl = item.url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
1303 if (dirsChanged.findByUrl(parentUrl).isNull()) {
1304 dirsChanged << KFileItem(parentUrl);
1305 }
1306 }
1307
1308 std::sort(indexesToRemove.begin(), indexesToRemove.end());
1309
1310 if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) {
1311 // Assure that removing a parent item also results in removing all children
1312 QVector<int> indexesToRemoveWithChildren;
1313 indexesToRemoveWithChildren.reserve(m_itemData.count());
1314
1315 const int itemCount = m_itemData.count();
1316 for (int index : std::as_const(indexesToRemove)) {
1317 indexesToRemoveWithChildren.append(index);
1318
1319 const int parentLevel = expandedParentsCount(index);
1320 int childIndex = index + 1;
1321 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
1322 indexesToRemoveWithChildren.append(childIndex);
1323 ++childIndex;
1324 }
1325 }
1326
1327 indexesToRemove = indexesToRemoveWithChildren;
1328 }
1329
1330 KItemRangeList itemRanges = KItemRangeList::fromSortedContainer(indexesToRemove);
1331 removeFilteredChildren(itemRanges);
1332
1333 // This call will update itemRanges to include the childless parents that have been filtered.
1334 const int filteredParentsCount = filterChildlessParents(itemRanges);
1335
1336 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1337 // mixed with expanded folders that are just being filtered out.
1338 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1339 // so removeItems() will check m_filteredItems to differentiate which is which.
1340 removeItems(itemRanges, filteredParentsCount > 0 ? DeleteItemDataIfUnfiltered : DeleteItemData);
1341
1342 Q_EMIT fileItemsChanged(dirsChanged);
1343 }
1344
1345 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &items)
1346 {
1347 Q_ASSERT(!items.isEmpty());
1348 #ifdef KFILEITEMMODEL_DEBUG
1349 qCDebug(DolphinDebug) << "Refreshing" << items.count() << "items";
1350 #endif
1351
1352 // Get the indexes of all items that have been refreshed
1353 QList<int> indexes;
1354 indexes.reserve(items.count());
1355
1356 QSet<QByteArray> changedRoles;
1357 KFileItemList changedFiles;
1358
1359 // Contains the indexes of the currently visible items
1360 // that should get hidden and hence moved to m_filteredItems.
1361 QVector<int> newFilteredIndexes;
1362
1363 // Contains currently hidden items that should
1364 // get visible and hence removed from m_filteredItems
1365 QList<ItemData *> newVisibleItems;
1366
1367 QListIterator<QPair<KFileItem, KFileItem>> it(items);
1368
1369 while (it.hasNext()) {
1370 const QPair<KFileItem, KFileItem> &itemPair = it.next();
1371 const KFileItem &oldItem = itemPair.first;
1372 const KFileItem &newItem = itemPair.second;
1373 const int indexForItem = index(oldItem);
1374 const bool newItemMatchesFilter = m_filter.matches(newItem);
1375 if (indexForItem >= 0) {
1376 m_itemData[indexForItem]->item = newItem;
1377
1378 // Keep old values as long as possible if they could not retrieved synchronously yet.
1379 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1380 ItemData *const itemData = m_itemData.at(indexForItem);
1381 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
1382 while (it.hasNext()) {
1383 it.next();
1384 const QByteArray &role = it.key();
1385 if (itemData->values.value(role) != it.value()) {
1386 itemData->values.insert(role, it.value());
1387 changedRoles.insert(role);
1388 }
1389 }
1390
1391 m_items.remove(oldItem.url());
1392 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1393 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1394 m_items.insert(newItem.url(), indexForItem);
1395 if (newItemMatchesFilter
1396 || (itemData->values.value("isExpanded").toBool()
1397 && (indexForItem + 1 < m_itemData.count() && m_itemData.at(indexForItem + 1)->parent == itemData))) {
1398 // We are lenient with expanded folders that originally had visible children.
1399 // If they become childless now they will be caught by filterChildlessParents()
1400 changedFiles.append(newItem);
1401 indexes.append(indexForItem);
1402 } else {
1403 newFilteredIndexes.append(indexForItem);
1404 m_filteredItems.insert(newItem, itemData);
1405 }
1406 } else {
1407 // Check if 'oldItem' is one of the filtered items.
1408 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(oldItem);
1409 if (it != m_filteredItems.end()) {
1410 ItemData *const itemData = it.value();
1411 itemData->item = newItem;
1412
1413 // The data stored in 'values' might have changed. Therefore, we clear
1414 // 'values' and re-populate it the next time it is requested via data(int).
1415 // Before clearing, we must remember if it was expanded and the expanded parents count,
1416 // otherwise these states would be lost. The data() method will deal with this special case.
1417 const bool isExpanded = itemData->values.value("isExpanded").toBool();
1418 bool hasExpandedParentsCount = false;
1419 const int expandedParentsCount = itemData->values.value("expandedParentsCount").toInt(&hasExpandedParentsCount);
1420 itemData->values.clear();
1421 if (isExpanded) {
1422 itemData->values.insert("isExpanded", true);
1423 if (hasExpandedParentsCount) {
1424 itemData->values.insert("expandedParentsCount", expandedParentsCount);
1425 }
1426 }
1427
1428 m_filteredItems.erase(it);
1429 if (newItemMatchesFilter) {
1430 newVisibleItems.append(itemData);
1431 } else {
1432 m_filteredItems.insert(newItem, itemData);
1433 }
1434 }
1435 }
1436 }
1437
1438 std::sort(newFilteredIndexes.begin(), newFilteredIndexes.end());
1439
1440 // We must keep track of parents of new visible items since they must be shown no matter what
1441 // They will be considered "immune" to filterChildlessParents()
1442 QSet<ItemData *> parentsToEnsureVisible;
1443
1444 for (ItemData *item : newVisibleItems) {
1445 for (ItemData *parent = item->parent; parent && !parentsToEnsureVisible.contains(parent); parent = parent->parent) {
1446 parentsToEnsureVisible.insert(parent);
1447 }
1448 }
1449 for (ItemData *parent : parentsToEnsureVisible) {
1450 // We make sure they are all unfiltered.
1451 if (m_filteredItems.remove(parent->item)) {
1452 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1453 newVisibleItems.append(parent);
1454 // It could be in newFilteredIndexes, we must remove it if it's there:
1455 const int parentIndex = index(parent->item);
1456 if (parentIndex >= 0) {
1457 QVector<int>::iterator it = std::lower_bound(newFilteredIndexes.begin(), newFilteredIndexes.end(), parentIndex);
1458 if (it != newFilteredIndexes.end() && *it == parentIndex) {
1459 newFilteredIndexes.erase(it);
1460 }
1461 }
1462 }
1463 }
1464
1465 KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
1466
1467 // This call will update itemRanges to include the childless parents that have been filtered.
1468 filterChildlessParents(removedRanges, parentsToEnsureVisible);
1469
1470 removeItems(removedRanges, KeepItemData);
1471
1472 // Show previously hidden items that should get visible
1473 insertItems(newVisibleItems);
1474
1475 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1476
1477 // If the changed items have been created recently, they might not be in m_items yet.
1478 // In that case, the list 'indexes' might be empty.
1479 if (indexes.isEmpty()) {
1480 return;
1481 }
1482
1483 if (newVisibleItems.count() > 0 || removedRanges.count() > 0) {
1484 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1485 indexes.clear();
1486 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1487 const QSet<const KFileItem> changedFilesSet(changedFiles.cbegin(), changedFiles.cend());
1488 for (int i = 0; i < m_itemData.count(); i++) {
1489 if (changedFilesSet.contains(m_itemData.at(i)->item)) {
1490 indexes.append(i);
1491 }
1492 }
1493 } else {
1494 std::sort(indexes.begin(), indexes.end());
1495 }
1496
1497 // Extract the item-ranges out of the changed indexes
1498 const KItemRangeList itemRangeList = KItemRangeList::fromSortedContainer(indexes);
1499 emitItemsChangedAndTriggerResorting(itemRangeList, changedRoles);
1500
1501 Q_EMIT fileItemsChanged(changedFiles);
1502 }
1503
1504 void KFileItemModel::slotClear()
1505 {
1506 #ifdef KFILEITEMMODEL_DEBUG
1507 qCDebug(DolphinDebug) << "Clearing all items";
1508 #endif
1509
1510 qDeleteAll(m_filteredItems);
1511 m_filteredItems.clear();
1512 m_groups.clear();
1513
1514 m_maximumUpdateIntervalTimer->stop();
1515 m_resortAllItemsTimer->stop();
1516
1517 qDeleteAll(m_pendingItemsToInsert);
1518 m_pendingItemsToInsert.clear();
1519
1520 const int removedCount = m_itemData.count();
1521 if (removedCount > 0) {
1522 qDeleteAll(m_itemData);
1523 m_itemData.clear();
1524 m_items.clear();
1525 Q_EMIT itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
1526 }
1527
1528 m_expandedDirs.clear();
1529 }
1530
1531 void KFileItemModel::slotSortingChoiceChanged()
1532 {
1533 loadSortingSettings();
1534 resortAllItems();
1535 }
1536
1537 void KFileItemModel::dispatchPendingItemsToInsert()
1538 {
1539 if (!m_pendingItemsToInsert.isEmpty()) {
1540 insertItems(m_pendingItemsToInsert);
1541 m_pendingItemsToInsert.clear();
1542 }
1543 }
1544
1545 void KFileItemModel::insertItems(QList<ItemData *> &newItems)
1546 {
1547 if (newItems.isEmpty()) {
1548 return;
1549 }
1550
1551 #ifdef KFILEITEMMODEL_DEBUG
1552 QElapsedTimer timer;
1553 timer.start();
1554 qCDebug(DolphinDebug) << "===========================================================";
1555 qCDebug(DolphinDebug) << "Inserting" << newItems.count() << "items";
1556 #endif
1557
1558 m_groups.clear();
1559 prepareItemsForSorting(newItems);
1560
1561 // Natural sorting of items can be very slow. However, it becomes much faster
1562 // if the input sequence is already mostly sorted. Therefore, we first sort
1563 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1564 if (m_naturalSorting) {
1565 if (m_sortRole == NameRole) {
1566 parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
1567 } else if (isRoleValueNatural(m_sortRole)) {
1568 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
1569 const QByteArray role = roleForType(m_sortRole);
1570 return a->values.value(role).toString() < b->values.value(role).toString();
1571 };
1572 parallelMergeSort(newItems.begin(), newItems.end(), lambdaLessThan, QThread::idealThreadCount());
1573 }
1574 }
1575
1576 sort(newItems.begin(), newItems.end());
1577
1578 #ifdef KFILEITEMMODEL_DEBUG
1579 qCDebug(DolphinDebug) << "[TIME] Sorting:" << timer.elapsed();
1580 #endif
1581
1582 KItemRangeList itemRanges;
1583 const int existingItemCount = m_itemData.count();
1584 const int newItemCount = newItems.count();
1585 const int totalItemCount = existingItemCount + newItemCount;
1586
1587 if (existingItemCount == 0) {
1588 // Optimization for the common special case that there are no
1589 // items in the model yet. Happens, e.g., when entering a folder.
1590 m_itemData = newItems;
1591 itemRanges << KItemRange(0, newItemCount);
1592 } else {
1593 m_itemData.reserve(totalItemCount);
1594 for (int i = existingItemCount; i < totalItemCount; ++i) {
1595 m_itemData.append(nullptr);
1596 }
1597
1598 // We build the new list m_itemData in reverse order to minimize
1599 // the number of moves and guarantee O(N) complexity.
1600 int targetIndex = totalItemCount - 1;
1601 int sourceIndexExistingItems = existingItemCount - 1;
1602 int sourceIndexNewItems = newItemCount - 1;
1603
1604 int rangeCount = 0;
1605
1606 while (sourceIndexNewItems >= 0) {
1607 ItemData *newItem = newItems.at(sourceIndexNewItems);
1608 if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
1609 // Move an existing item to its new position. If any new items
1610 // are behind it, push the item range to itemRanges.
1611 if (rangeCount > 0) {
1612 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1613 rangeCount = 0;
1614 }
1615
1616 m_itemData[targetIndex] = m_itemData.at(sourceIndexExistingItems);
1617 --sourceIndexExistingItems;
1618 } else {
1619 // Insert a new item into the list.
1620 ++rangeCount;
1621 m_itemData[targetIndex] = newItem;
1622 --sourceIndexNewItems;
1623 }
1624 --targetIndex;
1625 }
1626
1627 // Push the final item range to itemRanges.
1628 if (rangeCount > 0) {
1629 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1630 }
1631
1632 // Note that itemRanges is still sorted in reverse order.
1633 std::reverse(itemRanges.begin(), itemRanges.end());
1634 }
1635
1636 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1637 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1638 m_items.clear();
1639
1640 Q_EMIT itemsInserted(itemRanges);
1641
1642 #ifdef KFILEITEMMODEL_DEBUG
1643 qCDebug(DolphinDebug) << "[TIME] Inserting of" << newItems.count() << "items:" << timer.elapsed();
1644 #endif
1645 }
1646
1647 void KFileItemModel::removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior)
1648 {
1649 if (itemRanges.isEmpty()) {
1650 return;
1651 }
1652
1653 m_groups.clear();
1654
1655 // Step 1: Remove the items from m_itemData, and free the ItemData.
1656 int removedItemsCount = 0;
1657 for (const KItemRange &range : itemRanges) {
1658 removedItemsCount += range.count;
1659
1660 for (int index = range.index; index < range.index + range.count; ++index) {
1661 if (behavior == DeleteItemData || (behavior == DeleteItemDataIfUnfiltered && !m_filteredItems.contains(m_itemData.at(index)->item))) {
1662 delete m_itemData.at(index);
1663 }
1664
1665 m_itemData[index] = nullptr;
1666 }
1667 }
1668
1669 // Step 2: Remove the ItemData pointers from the list m_itemData.
1670 int target = itemRanges.at(0).index;
1671 int source = itemRanges.at(0).index + itemRanges.at(0).count;
1672 int nextRange = 1;
1673
1674 const int oldItemDataCount = m_itemData.count();
1675 while (source < oldItemDataCount) {
1676 m_itemData[target] = m_itemData[source];
1677 ++target;
1678 ++source;
1679
1680 if (nextRange < itemRanges.count() && source == itemRanges.at(nextRange).index) {
1681 // Skip the items in the next removed range.
1682 source += itemRanges.at(nextRange).count;
1683 ++nextRange;
1684 }
1685 }
1686
1687 m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end());
1688
1689 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1690 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1691 m_items.clear();
1692
1693 Q_EMIT itemsRemoved(itemRanges);
1694 }
1695
1696 QList<KFileItemModel::ItemData *> KFileItemModel::createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const
1697 {
1698 if (m_sortRole == TypeRole || m_groupRole == TypeRole) {
1699 // Try to resolve the MIME-types synchronously to prevent a reordering of
1700 // the items when sorting by type (per default MIME-types are resolved
1701 // asynchronously by KFileItemModelRolesUpdater).
1702 determineMimeTypes(items, 200);
1703 }
1704
1705 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1706 const int parentIndex = index(parentUrl);
1707 ItemData *parentItem = parentIndex < 0 ? m_filteredItems.value(KFileItem(parentUrl), nullptr) : m_itemData.at(parentIndex);
1708
1709 QList<ItemData *> itemDataList;
1710 itemDataList.reserve(items.count());
1711
1712 for (const KFileItem &item : items) {
1713 ItemData *itemData = new ItemData();
1714 itemData->item = item;
1715 itemData->parent = parentItem;
1716 itemDataList.append(itemData);
1717 }
1718
1719 return itemDataList;
1720 }
1721
1722 void KFileItemModel::prepareItemsWithRole(QList<ItemData *> &itemDataList, RoleType roleType)
1723 {
1724 switch (roleType) {
1725 case ExtensionRole:
1726 case PermissionsRole:
1727 case OwnerRole:
1728 case GroupRole:
1729 case DestinationRole:
1730 case PathRole:
1731 case DeletionTimeRole:
1732 // These roles can be determined with retrieveData, and they have to be stored
1733 // in the QHash "values" for the sorting.
1734 for (ItemData *itemData : std::as_const(itemDataList)) {
1735 if (itemData->values.isEmpty()) {
1736 itemData->values = retrieveData(itemData->item, itemData->parent);
1737 }
1738 }
1739 break;
1740
1741 case TypeRole:
1742 // At least store the data including the file type for items with known MIME type.
1743 for (ItemData *itemData : std::as_const(itemDataList)) {
1744 if (itemData->values.isEmpty()) {
1745 const KFileItem item = itemData->item;
1746 if (item.isDir() || item.isMimeTypeKnown()) {
1747 itemData->values = retrieveData(itemData->item, itemData->parent);
1748 }
1749 }
1750 }
1751 break;
1752
1753 default:
1754 // The other roles are either resolved by KFileItemModelRolesUpdater
1755 // (this includes the SizeRole for directories), or they do not need
1756 // to be stored in the QHash "values" for sorting because the data can
1757 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1758 // DateRole).
1759 break;
1760 }
1761 }
1762
1763 void KFileItemModel::prepareItemsForSorting(QList<ItemData *> &itemDataList)
1764 {
1765 prepareItemsWithRole(itemDataList, m_sortRole);
1766 prepareItemsWithRole(itemDataList, m_groupRole);
1767 }
1768
1769 int KFileItemModel::expandedParentsCount(const ItemData *data)
1770 {
1771 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1772 // if the corresponding item is expanded, and it is not a top-level item.
1773 const ItemData *parent = data->parent;
1774 if (parent) {
1775 if (parent->parent) {
1776 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1777 return parent->values.value("expandedParentsCount").toInt() + 1;
1778 } else {
1779 return 1;
1780 }
1781 } else {
1782 return 0;
1783 }
1784 }
1785
1786 void KFileItemModel::removeExpandedItems()
1787 {
1788 QVector<int> indexesToRemove;
1789
1790 const int maxIndex = m_itemData.count() - 1;
1791 for (int i = 0; i <= maxIndex; ++i) {
1792 const ItemData *itemData = m_itemData.at(i);
1793 if (itemData->parent) {
1794 indexesToRemove.append(i);
1795 }
1796 }
1797
1798 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1799 m_expandedDirs.clear();
1800
1801 // Also remove all filtered items which have a parent.
1802 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
1803 const QHash<KFileItem, ItemData *>::iterator end = m_filteredItems.end();
1804
1805 while (it != end) {
1806 if (it.value()->parent) {
1807 delete it.value();
1808 it = m_filteredItems.erase(it);
1809 } else {
1810 ++it;
1811 }
1812 }
1813 }
1814
1815 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet<QByteArray> &changedRoles)
1816 {
1817 Q_EMIT itemsChanged(itemRanges, changedRoles);
1818
1819 // Trigger a resorting if necessary. Note that this can happen even if the sort
1820 // role has not changed at all because the file name can be used as a fallback.
1821 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))
1822 || (changedRoles.contains("count") && sortRole() == "size")) { // "count" is used in the "size" sort role, so this might require a resorting.
1823 for (const KItemRange &range : itemRanges) {
1824 bool needsResorting = false;
1825
1826 const int first = range.index;
1827 const int last = range.index + range.count - 1;
1828
1829 // Resorting the model is necessary if
1830 // (a) The first item in the range is "lessThan" its predecessor,
1831 // (b) the successor of the last item is "lessThan" the last item, or
1832 // (c) the internal order of the items in the range is incorrect.
1833 if (first > 0 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1834 needsResorting = true;
1835 } else if (last < count() - 1 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1836 needsResorting = true;
1837 } else {
1838 for (int index = first; index < last; ++index) {
1839 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1840 needsResorting = true;
1841 break;
1842 }
1843 }
1844 }
1845
1846 if (needsResorting) {
1847 scheduleResortAllItems();
1848 return;
1849 }
1850 }
1851 }
1852
1853 if (groupedSorting() && changedRoles.contains(sortRole())) {
1854 // The position is still correct, but the groups might have changed
1855 // if the changed item is either the first or the last item in a
1856 // group.
1857 // In principle, we could try to find out if the item really is the
1858 // first or last one in its group and then update the groups
1859 // (possibly with a delayed timer to make sure that we don't
1860 // re-calculate the groups very often if items are updated one by
1861 // one), but starting m_resortAllItemsTimer is easier.
1862 m_resortAllItemsTimer->start();
1863 }
1864 }
1865
1866 void KFileItemModel::resetRoles()
1867 {
1868 for (int i = 0; i < RolesCount; ++i) {
1869 m_requestRole[i] = false;
1870 }
1871 }
1872
1873 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray &role) const
1874 {
1875 static QHash<QByteArray, RoleType> roles;
1876 if (roles.isEmpty()) {
1877 // Insert user visible roles that can be accessed with
1878 // KFileItemModel::roleInformation()
1879 int count = 0;
1880 const RoleInfoMap *map = rolesInfoMap(count);
1881 for (int i = 0; i < count; ++i) {
1882 roles.insert(map[i].role, map[i].roleType);
1883 }
1884
1885 // Insert internal roles (take care to synchronize the implementation
1886 // with KFileItemModel::roleForType() in case if a change is done).
1887 roles.insert("isDir", IsDirRole);
1888 roles.insert("isLink", IsLinkRole);
1889 roles.insert("isHidden", IsHiddenRole);
1890 roles.insert("isExpanded", IsExpandedRole);
1891 roles.insert("isExpandable", IsExpandableRole);
1892 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1893
1894 Q_ASSERT(roles.count() == RolesCount);
1895 }
1896
1897 return roles.value(role, NoRole);
1898 }
1899
1900 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1901 {
1902 static QHash<RoleType, QByteArray> roles;
1903 if (roles.isEmpty()) {
1904 // Insert user visible roles that can be accessed with
1905 // KFileItemModel::roleInformation()
1906 int count = 0;
1907 const RoleInfoMap *map = rolesInfoMap(count);
1908 for (int i = 0; i < count; ++i) {
1909 roles.insert(map[i].roleType, map[i].role);
1910 }
1911
1912 // Insert internal roles (take care to synchronize the implementation
1913 // with KFileItemModel::typeForRole() in case if a change is done).
1914 roles.insert(IsDirRole, "isDir");
1915 roles.insert(IsLinkRole, "isLink");
1916 roles.insert(IsHiddenRole, "isHidden");
1917 roles.insert(IsExpandedRole, "isExpanded");
1918 roles.insert(IsExpandableRole, "isExpandable");
1919 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1920
1921 Q_ASSERT(roles.count() == RolesCount);
1922 };
1923
1924 return roles.value(roleType);
1925 }
1926
1927 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem &item, const ItemData *parent) const
1928 {
1929 // It is important to insert only roles that are fast to retrieve. E.g.
1930 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1931 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1932 QHash<QByteArray, QVariant> data;
1933 data.insert(sharedValue("url"), item.url());
1934
1935 const bool isDir = item.isDir();
1936 if (m_requestRole[IsDirRole] && isDir) {
1937 data.insert(sharedValue("isDir"), true);
1938 }
1939
1940 if (m_requestRole[IsLinkRole] && item.isLink()) {
1941 data.insert(sharedValue("isLink"), true);
1942 }
1943
1944 if (m_requestRole[IsHiddenRole]) {
1945 data.insert(sharedValue("isHidden"), item.isHidden() || item.mimetype() == QStringLiteral("application/x-trash"));
1946 }
1947
1948 if (m_requestRole[NameRole]) {
1949 data.insert(sharedValue("text"), item.text());
1950 }
1951
1952 if (m_requestRole[ExtensionRole] && !isDir) {
1953 // TODO KF6 use KFileItem::suffix 464722
1954 data.insert(sharedValue("extension"), QFileInfo(item.name()).suffix());
1955 }
1956
1957 if (m_requestRole[SizeRole] && !isDir) {
1958 data.insert(sharedValue("size"), item.size());
1959 }
1960
1961 if (m_requestRole[ModificationTimeRole]) {
1962 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1963 // having several thousands of items. Instead read the raw number from UDSEntry directly
1964 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1965 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1966 data.insert(sharedValue("modificationtime"), dateTime);
1967 }
1968
1969 if (m_requestRole[CreationTimeRole]) {
1970 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1971 // having several thousands of items. Instead read the raw number from UDSEntry directly
1972 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1973 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1974 data.insert(sharedValue("creationtime"), dateTime);
1975 }
1976
1977 if (m_requestRole[AccessTimeRole]) {
1978 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1979 // having several thousands of items. Instead read the raw number from UDSEntry directly
1980 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1981 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1982 data.insert(sharedValue("accesstime"), dateTime);
1983 }
1984
1985 if (m_requestRole[PermissionsRole]) {
1986 data.insert(sharedValue("permissions"), QVariantList() << item.permissionsString() << item.permissions());
1987 }
1988
1989 if (m_requestRole[OwnerRole]) {
1990 data.insert(sharedValue("owner"), item.user());
1991 }
1992
1993 if (m_requestRole[GroupRole]) {
1994 data.insert(sharedValue("group"), item.group());
1995 }
1996
1997 if (m_requestRole[DestinationRole]) {
1998 QString destination = item.linkDest();
1999 if (destination.isEmpty()) {
2000 destination = QLatin1Char('-');
2001 }
2002 data.insert(sharedValue("destination"), destination);
2003 }
2004
2005 if (m_requestRole[PathRole]) {
2006 QString path;
2007 if (item.url().scheme() == QLatin1String("trash")) {
2008 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
2009 } else {
2010 // For performance reasons cache the home-path in a static QString
2011 // (see QDir::homePath() for more details)
2012 static QString homePath;
2013 if (homePath.isEmpty()) {
2014 homePath = QDir::homePath();
2015 }
2016
2017 path = item.localPath();
2018 if (path.startsWith(homePath)) {
2019 path.replace(0, homePath.length(), QLatin1Char('~'));
2020 }
2021 }
2022
2023 const int index = path.lastIndexOf(item.text());
2024 path = path.mid(0, index - 1);
2025 data.insert(sharedValue("path"), path);
2026 }
2027
2028 if (m_requestRole[DeletionTimeRole]) {
2029 QDateTime deletionTime;
2030 if (item.url().scheme() == QLatin1String("trash")) {
2031 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
2032 }
2033 data.insert(sharedValue("deletiontime"), deletionTime);
2034 }
2035
2036 if (m_requestRole[IsExpandableRole] && isDir) {
2037 data.insert(sharedValue("isExpandable"), true);
2038 }
2039
2040 if (m_requestRole[ExpandedParentsCountRole]) {
2041 if (parent) {
2042 const int level = expandedParentsCount(parent) + 1;
2043 data.insert(sharedValue("expandedParentsCount"), level);
2044 }
2045 }
2046
2047 if (item.isMimeTypeKnown()) {
2048 QString iconName = item.iconName();
2049 if (!QIcon::hasThemeIcon(iconName)) {
2050 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
2051 iconName = mimeType.genericIconName();
2052 }
2053
2054 data.insert(sharedValue("iconName"), iconName);
2055
2056 if (m_requestRole[TypeRole]) {
2057 data.insert(sharedValue("type"), item.mimeComment());
2058 }
2059 } else if (m_requestRole[TypeRole] && isDir) {
2060 static const QString folderMimeType = item.mimeComment();
2061 data.insert(sharedValue("type"), folderMimeType);
2062 }
2063
2064 return data;
2065 }
2066
2067 bool KFileItemModel::lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const
2068 {
2069 int result = 0;
2070
2071 if (a->parent != b->parent) {
2072 const int expansionLevelA = expandedParentsCount(a);
2073 const int expansionLevelB = expandedParentsCount(b);
2074
2075 // If b has a higher expansion level than a, check if a is a parent
2076 // of b, and make sure that both expansion levels are equal otherwise.
2077 for (int i = expansionLevelB; i > expansionLevelA; --i) {
2078 if (b->parent == a) {
2079 return true;
2080 }
2081 b = b->parent;
2082 }
2083
2084 // If a has a higher expansion level than a, check if b is a parent
2085 // of a, and make sure that both expansion levels are equal otherwise.
2086 for (int i = expansionLevelA; i > expansionLevelB; --i) {
2087 if (a->parent == b) {
2088 return false;
2089 }
2090 a = a->parent;
2091 }
2092
2093 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
2094
2095 // Compare the last parents of a and b which are different.
2096 while (a->parent != b->parent) {
2097 a = a->parent;
2098 b = b->parent;
2099 }
2100 }
2101
2102 result = groupRoleCompare(a, b, collator);
2103 if (result == 0) {
2104 // Show hidden files and folders last
2105 if (m_sortHiddenLast) {
2106 const bool isHiddenA = a->item.isHidden();
2107 const bool isHiddenB = b->item.isHidden();
2108 if (isHiddenA && !isHiddenB) {
2109 return false;
2110 } else if (!isHiddenA && isHiddenB) {
2111 return true;
2112 }
2113 }
2114 if (m_sortDirsFirst || (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount && m_sortRole == SizeRole)) {
2115 const bool isDirA = a->item.isDir();
2116 const bool isDirB = b->item.isDir();
2117 if (isDirA && !isDirB) {
2118 return true;
2119 } else if (!isDirA && isDirB) {
2120 return false;
2121 }
2122 }
2123 result = sortRoleCompare(a, b, collator);
2124 result = (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
2125 } else {
2126 result = (groupOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
2127 }
2128 return result;
2129 }
2130
2131 void KFileItemModel::sort(const QList<KFileItemModel::ItemData *>::iterator &begin, const QList<KFileItemModel::ItemData *>::iterator &end) const
2132 {
2133 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
2134 return lessThan(a, b, m_collator);
2135 };
2136
2137 if (m_sortRole == NameRole || isRoleValueNatural(m_sortRole)) {
2138 // Sorting by string can be expensive, in particular if natural sorting is
2139 // enabled. Use all CPU cores to speed up the sorting process.
2140 static const int numberOfThreads = QThread::idealThreadCount();
2141 parallelMergeSort(begin, end, lambdaLessThan, numberOfThreads);
2142 } else {
2143 // Sorting by other roles is quite fast. Use only one thread to prevent
2144 // problems caused by non-reentrant comparison functions, see
2145 // https://bugs.kde.org/show_bug.cgi?id=312679
2146 mergeSort(begin, end, lambdaLessThan);
2147 }
2148 }
2149
2150 int KFileItemModel::sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const
2151 {
2152 // This function must never return 0, because that would break stable
2153 // sorting, which leads to all kinds of bugs.
2154 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2155 // If two items have equal sort values, let the fallbacks at the bottom of
2156 // the function handle it.
2157 const KFileItem &itemA = a->item;
2158 const KFileItem &itemB = b->item;
2159
2160 int result = 0;
2161
2162 switch (m_sortRole) {
2163 case NameRole:
2164 // The name role is handled as default fallback after the switch
2165 break;
2166
2167 case SizeRole: {
2168 if (ContentDisplaySettings::directorySizeMode() == ContentDisplaySettings::EnumDirectorySizeMode::ContentCount && itemA.isDir()) {
2169 // folders first then
2170 // items A and B are folders thanks to lessThan checks
2171 auto valueA = a->values.value("count");
2172 auto valueB = b->values.value("count");
2173 if (valueA.isNull()) {
2174 if (!valueB.isNull()) {
2175 return -1;
2176 }
2177 } else if (valueB.isNull()) {
2178 return +1;
2179 } else {
2180 if (valueA.toLongLong() < valueB.toLongLong()) {
2181 return -1;
2182 } else if (valueA.toLongLong() > valueB.toLongLong()) {
2183 return +1;
2184 }
2185 }
2186 break;
2187 }
2188
2189 KIO::filesize_t sizeA = 0;
2190 if (itemA.isDir()) {
2191 sizeA = a->values.value("size").toULongLong();
2192 } else {
2193 sizeA = itemA.size();
2194 }
2195 KIO::filesize_t sizeB = 0;
2196 if (itemB.isDir()) {
2197 sizeB = b->values.value("size").toULongLong();
2198 } else {
2199 sizeB = itemB.size();
2200 }
2201 if (sizeA < sizeB) {
2202 return -1;
2203 } else if (sizeA > sizeB) {
2204 return +1;
2205 }
2206 break;
2207 }
2208
2209 case ModificationTimeRole: {
2210 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2211 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2212 if (dateTimeA < dateTimeB) {
2213 return -1;
2214 } else if (dateTimeA > dateTimeB) {
2215 return +1;
2216 }
2217 break;
2218 }
2219
2220 case AccessTimeRole: {
2221 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2222 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2223 if (dateTimeA < dateTimeB) {
2224 return -1;
2225 } else if (dateTimeA > dateTimeB) {
2226 return +1;
2227 }
2228 break;
2229 }
2230
2231 case CreationTimeRole: {
2232 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2233 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2234 if (dateTimeA < dateTimeB) {
2235 return -1;
2236 } else if (dateTimeA > dateTimeB) {
2237 return +1;
2238 }
2239 break;
2240 }
2241
2242 case DeletionTimeRole: {
2243 const QDateTime dateTimeA = a->values.value("deletiontime").toDateTime();
2244 const QDateTime dateTimeB = b->values.value("deletiontime").toDateTime();
2245 if (dateTimeA < dateTimeB) {
2246 return -1;
2247 } else if (dateTimeA > dateTimeB) {
2248 return +1;
2249 }
2250 break;
2251 }
2252
2253 case RatingRole:
2254 case WidthRole:
2255 case HeightRole:
2256 case PublisherRole:
2257 case PageCountRole:
2258 case WordCountRole:
2259 case LineCountRole:
2260 case TrackRole:
2261 case ReleaseYearRole: {
2262 result = a->values.value(roleForType(m_sortRole)).toInt() - b->values.value(roleForType(m_sortRole)).toInt();
2263 break;
2264 }
2265
2266 case DimensionsRole: {
2267 const QByteArray role = roleForType(m_sortRole);
2268 const QSize dimensionsA = a->values.value(role).toSize();
2269 const QSize dimensionsB = b->values.value(role).toSize();
2270
2271 if (dimensionsA.width() == dimensionsB.width()) {
2272 result = dimensionsA.height() - dimensionsB.height();
2273 } else {
2274 result = dimensionsA.width() - dimensionsB.width();
2275 }
2276 break;
2277 }
2278
2279 default: {
2280 const QByteArray role = roleForType(m_sortRole);
2281 const QString roleValueA = a->values.value(role).toString();
2282 const QString roleValueB = b->values.value(role).toString();
2283 if (!roleValueA.isEmpty() && roleValueB.isEmpty()) {
2284 return -1;
2285 } else if (roleValueA.isEmpty() && !roleValueB.isEmpty()) {
2286 return +1;
2287 } else if (isRoleValueNatural(m_sortRole)) {
2288 result = stringCompare(roleValueA, roleValueB, collator);
2289 } else {
2290 result = QString::compare(roleValueA, roleValueB);
2291 }
2292 break;
2293 }
2294 }
2295
2296 if (result != 0) {
2297 // The current sort role was sufficient to define an order
2298 return result;
2299 }
2300
2301 // Fallback #1: Compare the text of the items
2302 result = stringCompare(itemA.text(), itemB.text(), collator);
2303 if (result != 0) {
2304 return result;
2305 }
2306
2307 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2308 result = stringCompare(itemA.name(), itemB.name(), collator);
2309 if (result != 0) {
2310 return result;
2311 }
2312
2313 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2314 // equal. In this case a comparison of the URL is done which is unique in all cases
2315 // within KDirLister.
2316 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
2317 }
2318
2319 int KFileItemModel::groupRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const
2320 {
2321 // Unlike sortRoleCompare, this function can and often will return 0.
2322 int result = 0;
2323
2324 ItemGroupInfo groupA, groupB;
2325 switch (m_groupRole) {
2326 case NoRole:
2327 // Non-trivial grouping behavior might be handled there in the future.
2328 return 0;
2329 case NameRole:
2330 groupA = nameRoleGroup(a, false);
2331 groupB = nameRoleGroup(b, false);
2332 break;
2333 case SizeRole:
2334 groupA = sizeRoleGroup(a, false);
2335 groupB = sizeRoleGroup(b, false);
2336 break;
2337 case ModificationTimeRole:
2338 groupA = timeRoleGroup(
2339 [](const ItemData *item) {
2340 return item->item.time(KFileItem::ModificationTime);
2341 },
2342 a,
2343 false);
2344 groupB = timeRoleGroup(
2345 [](const ItemData *item) {
2346 return item->item.time(KFileItem::ModificationTime);
2347 },
2348 b,
2349 false);
2350 break;
2351 case CreationTimeRole:
2352 groupA = timeRoleGroup(
2353 [](const ItemData *item) {
2354 return item->item.time(KFileItem::CreationTime);
2355 },
2356 a,
2357 false);
2358 groupB = timeRoleGroup(
2359 [](const ItemData *item) {
2360 return item->item.time(KFileItem::CreationTime);
2361 },
2362 b,
2363 false);
2364 break;
2365 case AccessTimeRole:
2366 groupA = timeRoleGroup(
2367 [](const ItemData *item) {
2368 return item->item.time(KFileItem::AccessTime);
2369 },
2370 a,
2371 false);
2372 groupB = timeRoleGroup(
2373 [](const ItemData *item) {
2374 return item->item.time(KFileItem::AccessTime);
2375 },
2376 b,
2377 false);
2378 break;
2379 case DeletionTimeRole:
2380 groupA = timeRoleGroup(
2381 [](const ItemData *item) {
2382 return item->values.value("deletiontime").toDateTime();
2383 },
2384 a,
2385 false);
2386 groupB = timeRoleGroup(
2387 [](const ItemData *item) {
2388 return item->values.value("deletiontime").toDateTime();
2389 },
2390 b,
2391 false);
2392 break;
2393 case PermissionsRole:
2394 groupA = permissionRoleGroup(a, false);
2395 groupB = permissionRoleGroup(b, false);
2396 break;
2397 case RatingRole:
2398 groupA = ratingRoleGroup(a, false);
2399 groupB = ratingRoleGroup(b, false);
2400 break;
2401 case TypeRole:
2402 groupA = typeRoleGroup(a);
2403 groupB = typeRoleGroup(b);
2404 break;
2405 default: {
2406 groupA = genericStringRoleGroup(groupRole(), a);
2407 groupB = genericStringRoleGroup(groupRole(), b);
2408 break;
2409 }
2410 }
2411 if (groupA.comparable < groupB.comparable) {
2412 result = -1;
2413 } else if (groupA.comparable > groupB.comparable) {
2414 result = 1;
2415 } else {
2416 result = stringCompare(groupA.text, groupB.text, collator);
2417 }
2418 return result;
2419 }
2420
2421 int KFileItemModel::stringCompare(const QString &a, const QString &b, const QCollator &collator) const
2422 {
2423 QMutexLocker collatorLock(s_collatorMutex());
2424
2425 if (m_naturalSorting) {
2426 return collator.compare(a, b);
2427 }
2428
2429 const int result = QString::compare(a, b, collator.caseSensitivity());
2430 if (result != 0 || collator.caseSensitivity() == Qt::CaseSensitive) {
2431 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2432 // comparison, still a deterministic sort order is required. A case sensitive
2433 // comparison is done as fallback.
2434 return result;
2435 }
2436
2437 return QString::compare(a, b, Qt::CaseSensitive);
2438 }
2439
2440 KFileItemModel::ItemGroupInfo KFileItemModel::nameRoleGroup(const ItemData *itemData, bool withString) const
2441 {
2442 static ItemGroupInfo oldGroupInfo;
2443 static QChar oldFirstChar;
2444 ItemGroupInfo groupInfo;
2445 QChar firstChar;
2446
2447 const QString name = itemData->item.text();
2448
2449 QMutexLocker collatorLock(s_collatorMutex());
2450
2451 // Use the first character of the name as group indication
2452 firstChar = name.at(0).toUpper();
2453
2454 if (firstChar == oldFirstChar) {
2455 return oldGroupInfo;
2456 }
2457 if (firstChar == QLatin1Char('~') && name.length() > 1) {
2458 firstChar = name.at(1).toUpper();
2459 }
2460 if (firstChar.isLetter()) {
2461 if (m_collator.compare(firstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(firstChar, QChar(QLatin1Char('Z'))) <= 0) {
2462 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2463
2464 // Try to find a matching group in the range 'A' to 'Z'.
2465 static std::vector<QChar> lettersAtoZ;
2466 lettersAtoZ.reserve('Z' - 'A' + 1);
2467 if (lettersAtoZ.empty()) {
2468 for (char c = 'A'; c <= 'Z'; ++c) {
2469 lettersAtoZ.push_back(QLatin1Char(c));
2470 }
2471 }
2472
2473 auto localeAwareLessThan = [this](QChar c1, QChar c2) -> bool {
2474 return m_collator.compare(c1, c2) < 0;
2475 };
2476
2477 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), firstChar, localeAwareLessThan);
2478 if (it != lettersAtoZ.end()) {
2479 if (localeAwareLessThan(firstChar, *it)) {
2480 // newFirstChar belongs to the group preceding *it.
2481 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2482 --it;
2483 }
2484 if (withString) {
2485 groupInfo.text = *it;
2486 }
2487 groupInfo.comparable = (*it).unicode();
2488 }
2489
2490 } else {
2491 // Symbols from non Latin-based scripts
2492 if (withString) {
2493 groupInfo.text = firstChar;
2494 }
2495 groupInfo.comparable = firstChar.unicode();
2496 }
2497 } else if (firstChar >= QLatin1Char('0') && firstChar <= QLatin1Char('9')) {
2498 // Apply group '0 - 9' for any name that starts with a digit
2499 if (withString) {
2500 groupInfo.text = i18nc("@title:group Groups that start with a digit", "0 - 9");
2501 }
2502 groupInfo.comparable = (int)'0';
2503 } else {
2504 if (withString) {
2505 groupInfo.text = i18nc("@title:group", "Others");
2506 }
2507 groupInfo.comparable = (int)'.';
2508 }
2509 oldFirstChar = firstChar;
2510 oldGroupInfo = groupInfo;
2511 return groupInfo;
2512 }
2513
2514 KFileItemModel::ItemGroupInfo KFileItemModel::sizeRoleGroup(const ItemData *itemData, bool withString) const
2515 {
2516 static ItemGroupInfo oldGroupInfo;
2517 static KIO::filesize_t oldFileSize;
2518 ItemGroupInfo groupInfo;
2519 KIO::filesize_t fileSize;
2520
2521 const KFileItem item = itemData->item;
2522 fileSize = !item.isNull() ? item.size() : ~0U;
2523
2524 groupInfo.comparable = -1; // None
2525 if (!item.isNull() && item.isDir()) {
2526 if (ContentDisplaySettings::directorySizeMode() != ContentDisplaySettings::EnumDirectorySizeMode::ContentSize) {
2527 groupInfo.comparable = 0; // Folders
2528 } else {
2529 fileSize = itemData->values.value("size").toULongLong();
2530 }
2531 }
2532 if (fileSize == oldFileSize) {
2533 return oldGroupInfo;
2534 }
2535 if (groupInfo.comparable < 0) {
2536 if (fileSize < 5 * 1024 * 1024) { // < 5 MB
2537 groupInfo.comparable = 1; // Small
2538 } else if (fileSize < 10 * 1024 * 1024) { // < 10 MB
2539 groupInfo.comparable = 2; // Medium
2540 } else {
2541 groupInfo.comparable = 3; // Big
2542 }
2543 }
2544
2545 if (withString) {
2546 char const *groupNames[] = {"Folders", "Small", "Medium", "Big"};
2547 groupInfo.text = i18nc("@title:group Size", groupNames[groupInfo.comparable]);
2548 }
2549 oldFileSize = fileSize;
2550 oldGroupInfo = groupInfo;
2551 return groupInfo;
2552 }
2553
2554 KFileItemModel::ItemGroupInfo
2555 KFileItemModel::timeRoleGroup(const std::function<QDateTime(const ItemData *)> &fileTimeCb, const ItemData *itemData, bool withString) const
2556 {
2557 static ItemGroupInfo oldGroupInfo;
2558 static QDate oldFileDate;
2559 ItemGroupInfo groupInfo;
2560
2561 const QDate currentDate = QDate::currentDate();
2562 const QDateTime fileTime = fileTimeCb(itemData);
2563 const QDate fileDate = fileTime.date();
2564 const int daysDistance = fileDate.daysTo(currentDate);
2565
2566 // Simplified grouping algorithm, preserving dates
2567 // but not taking "pretty printing" into account
2568 if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) {
2569 if (daysDistance < 7) {
2570 groupInfo.comparable = daysDistance; // Today, Yesterday and week days
2571 } else if (daysDistance < 14) {
2572 groupInfo.comparable = 10; // One Week Ago
2573 } else if (daysDistance < 21) {
2574 groupInfo.comparable = 20; // Two Weeks Ago
2575 } else if (daysDistance < 28) {
2576 groupInfo.comparable = 30; // Three Weeks Ago
2577 } else {
2578 groupInfo.comparable = 40; // Earlier This Month
2579 }
2580 } else {
2581 const QDate lastMonthDate = currentDate.addMonths(-1);
2582 if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) {
2583 if (daysDistance < 7) {
2584 groupInfo.comparable = daysDistance; // Today, Yesterday and week days (Month, Year)
2585 } else if (daysDistance < 14) {
2586 groupInfo.comparable = 11; // One Week Ago (Month, Year)
2587 } else if (daysDistance < 21) {
2588 groupInfo.comparable = 21; // Two Weeks Ago (Month, Year)
2589 } else if (daysDistance < 28) {
2590 groupInfo.comparable = 31; // Three Weeks Ago (Month, Year)
2591 } else {
2592 groupInfo.comparable = 41; // Earlier on Month, Year
2593 }
2594 } else {
2595 // The trick will fail for dates past April, 178956967 or before 1 AD.
2596 groupInfo.comparable = 2147483647 - (fileDate.year() * 12 + fileDate.month() - 1); // Month, Year; newer < older
2597 }
2598 }
2599 if (withString) {
2600 if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) {
2601 switch (daysDistance / 7) {
2602 case 0:
2603 switch (daysDistance) {
2604 case 0:
2605 groupInfo.text = i18nc("@title:group Date", "Today");
2606 break;
2607 case 1:
2608 groupInfo.text = i18nc("@title:group Date", "Yesterday");
2609 break;
2610 default:
2611 groupInfo.text = fileTime.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2612 groupInfo.text = i18nc(
2613 "Can be used to script translation of \"dddd\""
2614 "with context @title:group Date",
2615 "%1",
2616 groupInfo.text);
2617 }
2618 break;
2619 case 1:
2620 groupInfo.text = i18nc("@title:group Date", "One Week Ago");
2621 break;
2622 case 2:
2623 groupInfo.text = i18nc("@title:group Date", "Two Weeks Ago");
2624 break;
2625 case 3:
2626 groupInfo.text = i18nc("@title:group Date", "Three Weeks Ago");
2627 break;
2628 case 4:
2629 case 5:
2630 groupInfo.text = i18nc("@title:group Date", "Earlier this Month");
2631 break;
2632 default:
2633 Q_ASSERT(false);
2634 }
2635 } else {
2636 const QDate lastMonthDate = currentDate.addMonths(-1);
2637 if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) {
2638 if (daysDistance == 1) {
2639 const KLocalizedString format = ki18nc(
2640 "@title:group Date: "
2641 "MMMM is full month name in current locale, and yyyy is "
2642 "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 "
2643 "part of the text that should not be formatted as a date",
2644 "'Yesterday' (MMMM, yyyy)");
2645 const QString translatedFormat = format.toString();
2646 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2647 groupInfo.text = fileTime.toString(translatedFormat);
2648 groupInfo.text = i18nc(
2649 "Can be used to script translation of "
2650 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2651 "%1",
2652 groupInfo.text);
2653 } else {
2654 qCWarning(DolphinDebug).nospace()
2655 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2656 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2657 groupInfo.text = fileTime.toString(untranslatedFormat);
2658 }
2659 } else if (daysDistance < 7) {
2660 groupInfo.text =
2661 fileTime.toString(i18nc("@title:group Date: "
2662 "The week day name: dddd, MMMM is full month name "
2663 "in current locale, and yyyy is full year number.",
2664 "dddd (MMMM, yyyy)"));
2665 groupInfo.text = i18nc(
2666 "Can be used to script translation of "
2667 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2668 "%1",
2669 groupInfo.text);
2670 } else if (daysDistance < 7 * 2) {
2671 const KLocalizedString format = ki18nc(
2672 "@title:group Date: "
2673 "MMMM is full month name in current locale, and yyyy is "
2674 "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 "
2675 "part of the text that should not be formatted as a date",
2676 "'One Week Ago' (MMMM, yyyy)");
2677 const QString translatedFormat = format.toString();
2678 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2679 groupInfo.text = fileTime.toString(translatedFormat);
2680 groupInfo.text = i18nc(
2681 "Can be used to script translation of "
2682 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2683 "%1",
2684 groupInfo.text);
2685 } else {
2686 qCWarning(DolphinDebug).nospace()
2687 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2688 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2689 groupInfo.text = fileTime.toString(untranslatedFormat);
2690 }
2691 } else if (daysDistance < 7 * 3) {
2692 const KLocalizedString format = ki18nc(
2693 "@title:group Date: "
2694 "MMMM is full month name in current locale, and yyyy is "
2695 "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 "
2696 "part of the text that should not be formatted as a date",
2697 "'Two Weeks Ago' (MMMM, yyyy)");
2698 const QString translatedFormat = format.toString();
2699 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2700 groupInfo.text = fileTime.toString(translatedFormat);
2701 groupInfo.text = i18nc(
2702 "Can be used to script translation of "
2703 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2704 "%1",
2705 groupInfo.text);
2706 } else {
2707 qCWarning(DolphinDebug).nospace()
2708 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2709 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2710 groupInfo.text = fileTime.toString(untranslatedFormat);
2711 }
2712 } else if (daysDistance < 7 * 4) {
2713 const KLocalizedString format = ki18nc(
2714 "@title:group Date: "
2715 "MMMM is full month name in current locale, and yyyy is "
2716 "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 "
2717 "part of the text that should not be formatted as a date",
2718 "'Three Weeks Ago' (MMMM, yyyy)");
2719 const QString translatedFormat = format.toString();
2720 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2721 groupInfo.text = fileTime.toString(translatedFormat);
2722 groupInfo.text = i18nc(
2723 "Can be used to script translation of "
2724 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2725 "%1",
2726 groupInfo.text);
2727 } else {
2728 qCWarning(DolphinDebug).nospace()
2729 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2730 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2731 groupInfo.text = fileTime.toString(untranslatedFormat);
2732 }
2733 } else {
2734 const KLocalizedString format = ki18nc(
2735 "@title:group Date: "
2736 "MMMM is full month name in current locale, and yyyy is "
2737 "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 "
2738 "part of the text that should not be formatted as a date",
2739 "'Earlier on' MMMM, yyyy");
2740 const QString translatedFormat = format.toString();
2741 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2742 groupInfo.text = fileTime.toString(translatedFormat);
2743 groupInfo.text = i18nc(
2744 "Can be used to script translation of "
2745 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2746 "%1",
2747 groupInfo.text);
2748 } else {
2749 qCWarning(DolphinDebug).nospace()
2750 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2751 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2752 groupInfo.text = fileTime.toString(untranslatedFormat);
2753 }
2754 }
2755 } else {
2756 groupInfo.text =
2757 fileTime.toString(i18nc("@title:group "
2758 "The month and year: MMMM is full month name in current locale, "
2759 "and yyyy is full year number",
2760 "MMMM, yyyy"));
2761 groupInfo.text = i18nc(
2762 "Can be used to script translation of "
2763 "\"MMMM, yyyy\" with context @title:group Date",
2764 "%1",
2765 groupInfo.text);
2766 }
2767 }
2768 }
2769 oldFileDate = fileDate;
2770 oldGroupInfo = groupInfo;
2771 return groupInfo;
2772 }
2773
2774 KFileItemModel::ItemGroupInfo KFileItemModel::permissionRoleGroup(const ItemData *itemData, bool withString) const
2775 {
2776 static ItemGroupInfo oldGroupInfo;
2777 static QFileDevice::Permissions oldPermissions;
2778 ItemGroupInfo groupInfo;
2779
2780 const QFileInfo info(itemData->item.url().toLocalFile());
2781 const QFileDevice::Permissions permissions = info.permissions();
2782 if (permissions == oldPermissions) {
2783 return oldGroupInfo;
2784 }
2785 groupInfo.comparable = (int)permissions;
2786
2787 if (withString) {
2788 // Set user string
2789 QString user;
2790 if (permissions & QFile::ReadUser) {
2791 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
2792 }
2793 if (permissions & QFile::WriteUser) {
2794 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
2795 }
2796 if (permissions & QFile::ExeUser) {
2797 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2798 }
2799 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.length() - 2);
2800
2801 // Set group string
2802 QString group;
2803 if (permissions & QFile::ReadGroup) {
2804 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
2805 }
2806 if (permissions & QFile::WriteGroup) {
2807 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
2808 }
2809 if (permissions & QFile::ExeGroup) {
2810 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2811 }
2812 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.length() - 2);
2813
2814 // Set others string
2815 QString others;
2816 if (permissions & QFile::ReadOther) {
2817 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
2818 }
2819 if (permissions & QFile::WriteOther) {
2820 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
2821 }
2822 if (permissions & QFile::ExeOther) {
2823 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2824 }
2825 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.length() - 2);
2826 groupInfo.text = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
2827 }
2828 oldPermissions = permissions;
2829 oldGroupInfo = groupInfo;
2830 return groupInfo;
2831 }
2832
2833 KFileItemModel::ItemGroupInfo KFileItemModel::ratingRoleGroup(const ItemData *itemData, bool withString) const
2834 {
2835 ItemGroupInfo groupInfo;
2836 groupInfo.comparable = itemData->values.value("rating", 0).toInt();
2837 if (withString) {
2838 // Dolphin does not currently use string representation of star rating
2839 // as stars are rendered as graphics in group headers.
2840 groupInfo.text = i18nc("@item:intext Rated N (stars)", "Rated %i", QString::number(groupInfo.comparable));
2841 }
2842 return groupInfo;
2843 }
2844
2845 KFileItemModel::ItemGroupInfo KFileItemModel::genericStringRoleGroup(const QByteArray &role, const ItemData *itemData) const
2846 {
2847 return {0, itemData->values.value(role).toString()};
2848 }
2849
2850 QList<QPair<int, QVariant>> KFileItemModel::nameRoleGroups() const
2851 {
2852 Q_ASSERT(!m_itemData.isEmpty());
2853
2854 const int maxIndex = count() - 1;
2855 QList<QPair<int, QVariant>> groups;
2856
2857 ItemGroupInfo groupInfo;
2858 for (int i = 0; i <= maxIndex; ++i) {
2859 if (isChildItem(i)) {
2860 continue;
2861 }
2862
2863 ItemGroupInfo newGroupInfo = nameRoleGroup(m_itemData.at(i));
2864
2865 if (newGroupInfo != groupInfo) {
2866 groupInfo = newGroupInfo;
2867 groups.append(QPair<int, QVariant>(i, newGroupInfo.text));
2868 }
2869 }
2870 return groups;
2871 }
2872
2873 QList<QPair<int, QVariant>> KFileItemModel::sizeRoleGroups() const
2874 {
2875 Q_ASSERT(!m_itemData.isEmpty());
2876
2877 const int maxIndex = count() - 1;
2878 QList<QPair<int, QVariant>> groups;
2879
2880 ItemGroupInfo groupInfo;
2881 for (int i = 0; i <= maxIndex; ++i) {
2882 if (isChildItem(i)) {
2883 continue;
2884 }
2885
2886 ItemGroupInfo newGroupInfo = sizeRoleGroup(m_itemData.at(i));
2887
2888 if (newGroupInfo != groupInfo) {
2889 groupInfo = newGroupInfo;
2890 groups.append(QPair<int, QVariant>(i, newGroupInfo.text));
2891 }
2892 }
2893 return groups;
2894 }
2895
2896 KFileItemModel::ItemGroupInfo KFileItemModel::typeRoleGroup(const ItemData *itemData) const
2897 {
2898 int priority = 0;
2899 if (itemData->item.isDir() && m_sortDirsFirst) {
2900 // Ensure folders stay first regardless of grouping order
2901 if (groupOrder() == Qt::AscendingOrder) {
2902 priority = -1;
2903 } else {
2904 priority = 1;
2905 }
2906 }
2907 return {priority, itemData->values.value("type").toString()};
2908 }
2909
2910 QList<QPair<int, QVariant>> KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
2911 {
2912 Q_ASSERT(!m_itemData.isEmpty());
2913
2914 const int maxIndex = count() - 1;
2915 QList<QPair<int, QVariant>> groups;
2916
2917 ItemGroupInfo groupInfo;
2918 for (int i = 0; i <= maxIndex; ++i) {
2919 if (isChildItem(i)) {
2920 continue;
2921 }
2922
2923 ItemGroupInfo newGroupInfo = timeRoleGroup(fileTimeCb, m_itemData.at(i));
2924
2925 if (newGroupInfo != groupInfo) {
2926 groupInfo = newGroupInfo;
2927 groups.append(QPair<int, QVariant>(i, newGroupInfo.text));
2928 }
2929 }
2930 return groups;
2931 }
2932
2933 QList<QPair<int, QVariant>> KFileItemModel::permissionRoleGroups() const
2934 {
2935 Q_ASSERT(!m_itemData.isEmpty());
2936
2937 const int maxIndex = count() - 1;
2938 QList<QPair<int, QVariant>> groups;
2939
2940 ItemGroupInfo groupInfo;
2941 for (int i = 0; i <= maxIndex; ++i) {
2942 if (isChildItem(i)) {
2943 continue;
2944 }
2945
2946 ItemGroupInfo newGroupInfo = permissionRoleGroup(m_itemData.at(i));
2947
2948 if (newGroupInfo != groupInfo) {
2949 groupInfo = newGroupInfo;
2950 groups.append(QPair<int, QVariant>(i, newGroupInfo.text));
2951 }
2952 }
2953 return groups;
2954 }
2955
2956 QList<QPair<int, QVariant>> KFileItemModel::ratingRoleGroups() const
2957 {
2958 Q_ASSERT(!m_itemData.isEmpty());
2959
2960 const int maxIndex = count() - 1;
2961 QList<QPair<int, QVariant>> groups;
2962
2963 ItemGroupInfo groupInfo;
2964 for (int i = 0; i <= maxIndex; ++i) {
2965 if (isChildItem(i)) {
2966 continue;
2967 }
2968
2969 ItemGroupInfo newGroupInfo = ratingRoleGroup(m_itemData.at(i));
2970
2971 if (newGroupInfo != groupInfo) {
2972 groupInfo = newGroupInfo;
2973 // Using the numeric representation because Dolphin has a special
2974 // case for drawing stars.
2975 groups.append(QPair<int, QVariant>(i, newGroupInfo.comparable));
2976 }
2977 }
2978 return groups;
2979 }
2980
2981 QList<QPair<int, QVariant>> KFileItemModel::genericStringRoleGroups(const QByteArray &role) const
2982 {
2983 Q_ASSERT(!m_itemData.isEmpty());
2984
2985 const int maxIndex = count() - 1;
2986 QList<QPair<int, QVariant>> groups;
2987
2988 ItemGroupInfo groupInfo;
2989 for (int i = 0; i <= maxIndex; ++i) {
2990 if (isChildItem(i)) {
2991 continue;
2992 }
2993
2994 ItemGroupInfo newGroupInfo = genericStringRoleGroup(role, m_itemData.at(i));
2995
2996 if (newGroupInfo != groupInfo) {
2997 groupInfo = newGroupInfo;
2998 groups.append(QPair<int, QVariant>(i, newGroupInfo.text));
2999 }
3000 }
3001 return groups;
3002 }
3003
3004 void KFileItemModel::emitSortProgress(int resolvedCount)
3005 {
3006 // Be tolerant against a resolvedCount with a wrong range.
3007 // Although there should not be a case where KFileItemModelRolesUpdater
3008 // (= caller) provides a wrong range, it is important to emit
3009 // a useful progress information even if there is an unexpected
3010 // implementation issue.
3011
3012 const int itemCount = count();
3013 if (resolvedCount >= itemCount) {
3014 m_sortingProgressPercent = -1;
3015 if (m_resortAllItemsTimer->isActive()) {
3016 m_resortAllItemsTimer->stop();
3017 resortAllItems();
3018 }
3019
3020 Q_EMIT directorySortingProgress(100);
3021 } else if (itemCount > 0) {
3022 resolvedCount = qBound(0, resolvedCount, itemCount);
3023
3024 const int progress = resolvedCount * 100 / itemCount;
3025 if (m_sortingProgressPercent != progress) {
3026 m_sortingProgressPercent = progress;
3027 Q_EMIT directorySortingProgress(progress);
3028 }
3029 }
3030 }
3031
3032 const KFileItemModel::RoleInfoMap *KFileItemModel::rolesInfoMap(int &count)
3033 {
3034 static const RoleInfoMap rolesInfoMap[] = {
3035 // clang-format off
3036 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
3037 { nullptr, NoRole, kli18nc("@label", "None"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
3038 { "text", NameRole, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
3039 { "size", SizeRole, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
3040 { "modificationtime", ModificationTimeRole, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
3041 { "creationtime", CreationTimeRole, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
3042 { "accesstime", AccessTimeRole, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
3043 { "type", TypeRole, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
3044 { "rating", RatingRole, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3045 { "tags", TagsRole, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3046 { "comment", CommentRole, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
3047 { "title", TitleRole, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3048 { "author", AuthorRole, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3049 { "publisher", PublisherRole, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3050 { "pageCount", PageCountRole, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3051 { "wordCount", WordCountRole, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3052 { "lineCount", LineCountRole, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
3053 { "imageDateTime", ImageDateTimeRole, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3054 { "dimensions", DimensionsRole, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3055 { "width", WidthRole, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3056 { "height", HeightRole, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3057 { "orientation", OrientationRole, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
3058 { "artist", ArtistRole, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3059 { "genre", GenreRole, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3060 { "album", AlbumRole, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3061 { "duration", DurationRole, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3062 { "bitrate", BitrateRole, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3063 { "track", TrackRole, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3064 { "releaseYear", ReleaseYearRole, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
3065 { "aspectRatio", AspectRatioRole, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
3066 { "frameRate", FrameRateRole, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
3067 { "path", PathRole, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3068 { "extension", ExtensionRole, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3069 { "deletiontime", DeletionTimeRole, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3070 { "destination", DestinationRole, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3071 { "originUrl", OriginUrlRole, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
3072 { "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 },
3073 { "owner", OwnerRole, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3074 { "group", GroupRole, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
3075 };
3076 // clang-format on
3077
3078 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
3079 return rolesInfoMap;
3080 }
3081
3082 void KFileItemModel::determineMimeTypes(const KFileItemList &items, int timeout)
3083 {
3084 QElapsedTimer timer;
3085 timer.start();
3086 for (const KFileItem &item : items) {
3087 // Only determine mime types for files here. For directories,
3088 // KFileItem::determineMimeType() reads the .directory file inside to
3089 // load the icon, but this is not necessary at all if we just need the
3090 // type. Some special code for setting the correct mime type for
3091 // directories is in retrieveData().
3092 if (!item.isDir()) {
3093 item.determineMimeType();
3094 }
3095
3096 if (timer.elapsed() > timeout) {
3097 // Don't block the user interface, let the remaining items
3098 // be resolved asynchronously.
3099 return;
3100 }
3101 }
3102 }
3103
3104 QByteArray KFileItemModel::sharedValue(const QByteArray &value)
3105 {
3106 static QSet<QByteArray> pool;
3107 const QSet<QByteArray>::const_iterator it = pool.constFind(value);
3108
3109 if (it != pool.constEnd()) {
3110 return *it;
3111 } else {
3112 pool.insert(value);
3113 return value;
3114 }
3115 }
3116
3117 bool KFileItemModel::isConsistent() const
3118 {
3119 // m_items may contain less items than m_itemData because m_items
3120 // is populated lazily, see KFileItemModel::index(const QUrl& url).
3121 if (m_items.count() > m_itemData.count()) {
3122 return false;
3123 }
3124
3125 for (int i = 0, iMax = count(); i < iMax; ++i) {
3126 // Check if m_items and m_itemData are consistent.
3127 const KFileItem item = fileItem(i);
3128 if (item.isNull()) {
3129 qCWarning(DolphinDebug) << "Item" << i << "is null";
3130 return false;
3131 }
3132
3133 const int itemIndex = index(item);
3134 if (itemIndex != i) {
3135 qCWarning(DolphinDebug) << "Item" << i << "has a wrong index:" << itemIndex;
3136 return false;
3137 }
3138
3139 // Check if the items are sorted correctly.
3140 if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
3141 qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" << fileItem(i - 1) << fileItem(i);
3142 return false;
3143 }
3144
3145 // Check if all parent-child relationships are consistent.
3146 const ItemData *data = m_itemData.at(i);
3147 const ItemData *parent = data->parent;
3148 if (parent) {
3149 if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
3150 qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
3151 return false;
3152 }
3153
3154 const int parentIndex = index(parent->item);
3155 if (parentIndex >= i) {
3156 qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child"
3157 << data->item;
3158 return false;
3159 }
3160 }
3161 }
3162
3163 return true;
3164 }
3165
3166 void KFileItemModel::slotListerError(KIO::Job *job)
3167 {
3168 if (job->error() == KIO::ERR_IS_FILE) {
3169 if (auto *listJob = qobject_cast<KIO::ListJob *>(job)) {
3170 Q_EMIT urlIsFileError(listJob->url());
3171 }
3172 } else {
3173 const QString errorString = job->errorString();
3174 Q_EMIT errorMessage(!errorString.isEmpty() ? errorString : i18nc("@info:status", "Unknown error."));
3175 }
3176 }
3177
3178 #include "moc_kfileitemmodel.cpp"