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