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