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