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