]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Add setting also hide application/x-trash files when hiding hidden files
[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 <KIO/ListJob>
19 #include <KLocalizedString>
20 #include <KUrlMimeData>
21
22 #include <QElapsedTimer>
23 #include <QIcon>
24 #include <QMimeData>
25 #include <QMimeDatabase>
26 #include <QRecursiveMutex>
27 #include <QTimer>
28 #include <QWidget>
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(50);
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() || !GeneralSettings::hideXTrashFile());
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 showTrashMime)
243 {
244 const auto trashMime = QStringLiteral("application/x-trash");
245 QStringList excludeFilter = m_filter.excludeMimeTypes();
246
247 if (showTrashMime) {
248 excludeFilter.removeAll(trashMime);
249 } else if (!excludeFilter.contains(trashMime)) {
250 excludeFilter.append(trashMime);
251 }
252
253 setExcludeMimeTypeFilter(excludeFilter);
254 }
255
256 void KFileItemModel::scheduleResortAllItems()
257 {
258 if (!m_resortAllItemsTimer->isActive()) {
259 m_resortAllItemsTimer->start();
260 }
261 }
262
263 void KFileItemModel::setShowHiddenFiles(bool show)
264 {
265 m_dirLister->setShowHiddenFiles(show);
266 setShowTrashMime(show || !GeneralSettings::hideXTrashFile());
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 : std::as_const(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 // #473377: Delay emitting currentDirectoryRemoved() to avoid modifying KCoreDirLister
1200 // before KCoreDirListerCache::deleteDir() returns.
1201 QTimer::singleShot(0, this, [this] {
1202 Q_EMIT currentDirectoryRemoved();
1203 });
1204
1205 return;
1206 }
1207
1208 const int indexForItem = index(item);
1209 if (indexForItem >= 0) {
1210 indexesToRemove.append(indexForItem);
1211 } else {
1212 // Probably the item has been filtered.
1213 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(item);
1214 if (it != m_filteredItems.end()) {
1215 delete it.value();
1216 m_filteredItems.erase(it);
1217 }
1218 }
1219
1220 QUrl parentUrl = item.url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
1221 if (dirsChanged.findByUrl(parentUrl).isNull()) {
1222 dirsChanged << KFileItem(parentUrl);
1223 }
1224 }
1225
1226 std::sort(indexesToRemove.begin(), indexesToRemove.end());
1227
1228 if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) {
1229 // Assure that removing a parent item also results in removing all children
1230 QVector<int> indexesToRemoveWithChildren;
1231 indexesToRemoveWithChildren.reserve(m_itemData.count());
1232
1233 const int itemCount = m_itemData.count();
1234 for (int index : std::as_const(indexesToRemove)) {
1235 indexesToRemoveWithChildren.append(index);
1236
1237 const int parentLevel = expandedParentsCount(index);
1238 int childIndex = index + 1;
1239 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
1240 indexesToRemoveWithChildren.append(childIndex);
1241 ++childIndex;
1242 }
1243 }
1244
1245 indexesToRemove = indexesToRemoveWithChildren;
1246 }
1247
1248 KItemRangeList itemRanges = KItemRangeList::fromSortedContainer(indexesToRemove);
1249 removeFilteredChildren(itemRanges);
1250
1251 // This call will update itemRanges to include the childless parents that have been filtered.
1252 const int filteredParentsCount = filterChildlessParents(itemRanges);
1253
1254 // If any childless parents were filtered, then itemRanges got updated and now contains items that were really deleted
1255 // mixed with expanded folders that are just being filtered out.
1256 // If that's the case, we pass 'DeleteItemDataIfUnfiltered' as a hint
1257 // so removeItems() will check m_filteredItems to differentiate which is which.
1258 removeItems(itemRanges, filteredParentsCount > 0 ? DeleteItemDataIfUnfiltered : DeleteItemData);
1259
1260 Q_EMIT fileItemsChanged(dirsChanged);
1261 }
1262
1263 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &items)
1264 {
1265 Q_ASSERT(!items.isEmpty());
1266 #ifdef KFILEITEMMODEL_DEBUG
1267 qCDebug(DolphinDebug) << "Refreshing" << items.count() << "items";
1268 #endif
1269
1270 // Get the indexes of all items that have been refreshed
1271 QList<int> indexes;
1272 indexes.reserve(items.count());
1273
1274 QSet<QByteArray> changedRoles;
1275 KFileItemList changedFiles;
1276
1277 // Contains the indexes of the currently visible items
1278 // that should get hidden and hence moved to m_filteredItems.
1279 QVector<int> newFilteredIndexes;
1280
1281 // Contains currently hidden items that should
1282 // get visible and hence removed from m_filteredItems
1283 QList<ItemData *> newVisibleItems;
1284
1285 QListIterator<QPair<KFileItem, KFileItem>> it(items);
1286
1287 while (it.hasNext()) {
1288 const QPair<KFileItem, KFileItem> &itemPair = it.next();
1289 const KFileItem &oldItem = itemPair.first;
1290 const KFileItem &newItem = itemPair.second;
1291 const int indexForItem = index(oldItem);
1292 const bool newItemMatchesFilter = m_filter.matches(newItem);
1293 if (indexForItem >= 0) {
1294 m_itemData[indexForItem]->item = newItem;
1295
1296 // Keep old values as long as possible if they could not retrieved synchronously yet.
1297 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1298 ItemData *const itemData = m_itemData.at(indexForItem);
1299 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
1300 while (it.hasNext()) {
1301 it.next();
1302 const QByteArray &role = it.key();
1303 if (itemData->values.value(role) != it.value()) {
1304 itemData->values.insert(role, it.value());
1305 changedRoles.insert(role);
1306 }
1307 }
1308
1309 m_items.remove(oldItem.url());
1310 // We must maintain m_items consistent with m_itemData for now, this very loop is using it.
1311 // We leave it to be cleared by removeItems() later, when m_itemData actually gets updated.
1312 m_items.insert(newItem.url(), indexForItem);
1313 if (newItemMatchesFilter
1314 || (itemData->values.value("isExpanded").toBool()
1315 && (indexForItem + 1 < m_itemData.count() && m_itemData.at(indexForItem + 1)->parent == itemData))) {
1316 // We are lenient with expanded folders that originally had visible children.
1317 // If they become childless now they will be caught by filterChildlessParents()
1318 changedFiles.append(newItem);
1319 indexes.append(indexForItem);
1320 } else {
1321 newFilteredIndexes.append(indexForItem);
1322 m_filteredItems.insert(newItem, itemData);
1323 }
1324 } else {
1325 // Check if 'oldItem' is one of the filtered items.
1326 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.find(oldItem);
1327 if (it != m_filteredItems.end()) {
1328 ItemData *const itemData = it.value();
1329 itemData->item = newItem;
1330
1331 // The data stored in 'values' might have changed. Therefore, we clear
1332 // 'values' and re-populate it the next time it is requested via data(int).
1333 // Before clearing, we must remember if it was expanded and the expanded parents count,
1334 // otherwise these states would be lost. The data() method will deal with this special case.
1335 const bool isExpanded = itemData->values.value("isExpanded").toBool();
1336 bool hasExpandedParentsCount = false;
1337 const int expandedParentsCount = itemData->values.value("expandedParentsCount").toInt(&hasExpandedParentsCount);
1338 itemData->values.clear();
1339 if (isExpanded) {
1340 itemData->values.insert("isExpanded", true);
1341 if (hasExpandedParentsCount) {
1342 itemData->values.insert("expandedParentsCount", expandedParentsCount);
1343 }
1344 }
1345
1346 m_filteredItems.erase(it);
1347 if (newItemMatchesFilter) {
1348 newVisibleItems.append(itemData);
1349 } else {
1350 m_filteredItems.insert(newItem, itemData);
1351 }
1352 }
1353 }
1354 }
1355
1356 std::sort(newFilteredIndexes.begin(), newFilteredIndexes.end());
1357
1358 // We must keep track of parents of new visible items since they must be shown no matter what
1359 // They will be considered "immune" to filterChildlessParents()
1360 QSet<ItemData *> parentsToEnsureVisible;
1361
1362 for (ItemData *item : newVisibleItems) {
1363 for (ItemData *parent = item->parent; parent && !parentsToEnsureVisible.contains(parent); parent = parent->parent) {
1364 parentsToEnsureVisible.insert(parent);
1365 }
1366 }
1367 for (ItemData *parent : parentsToEnsureVisible) {
1368 // We make sure they are all unfiltered.
1369 if (m_filteredItems.remove(parent->item)) {
1370 // If it is being unfiltered now, we mark it to be inserted by appending it to newVisibleItems
1371 newVisibleItems.append(parent);
1372 // It could be in newFilteredIndexes, we must remove it if it's there:
1373 const int parentIndex = index(parent->item);
1374 if (parentIndex >= 0) {
1375 QVector<int>::iterator it = std::lower_bound(newFilteredIndexes.begin(), newFilteredIndexes.end(), parentIndex);
1376 if (it != newFilteredIndexes.end() && *it == parentIndex) {
1377 newFilteredIndexes.erase(it);
1378 }
1379 }
1380 }
1381 }
1382
1383 KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
1384
1385 // This call will update itemRanges to include the childless parents that have been filtered.
1386 filterChildlessParents(removedRanges, parentsToEnsureVisible);
1387
1388 removeItems(removedRanges, KeepItemData);
1389
1390 // Show previously hidden items that should get visible
1391 insertItems(newVisibleItems);
1392
1393 // Final step: we will emit 'itemsChanged' and 'fileItemsChanged' signals and trigger the asynchronous re-sorting logic.
1394
1395 // If the changed items have been created recently, they might not be in m_items yet.
1396 // In that case, the list 'indexes' might be empty.
1397 if (indexes.isEmpty()) {
1398 return;
1399 }
1400
1401 if (newVisibleItems.count() > 0 || removedRanges.count() > 0) {
1402 // The original indexes have changed and are now worthless since items were removed and/or inserted.
1403 indexes.clear();
1404 // m_items is not yet rebuilt at this point, so we use our own means to resolve the new indexes.
1405 const QSet<const KFileItem> changedFilesSet(changedFiles.cbegin(), changedFiles.cend());
1406 for (int i = 0; i < m_itemData.count(); i++) {
1407 if (changedFilesSet.contains(m_itemData.at(i)->item)) {
1408 indexes.append(i);
1409 }
1410 }
1411 } else {
1412 std::sort(indexes.begin(), indexes.end());
1413 }
1414
1415 // Extract the item-ranges out of the changed indexes
1416 const KItemRangeList itemRangeList = KItemRangeList::fromSortedContainer(indexes);
1417 emitItemsChangedAndTriggerResorting(itemRangeList, changedRoles);
1418
1419 Q_EMIT fileItemsChanged(changedFiles);
1420 }
1421
1422 void KFileItemModel::slotClear()
1423 {
1424 #ifdef KFILEITEMMODEL_DEBUG
1425 qCDebug(DolphinDebug) << "Clearing all items";
1426 #endif
1427
1428 qDeleteAll(m_filteredItems);
1429 m_filteredItems.clear();
1430 m_groups.clear();
1431
1432 m_maximumUpdateIntervalTimer->stop();
1433 m_resortAllItemsTimer->stop();
1434
1435 qDeleteAll(m_pendingItemsToInsert);
1436 m_pendingItemsToInsert.clear();
1437
1438 const int removedCount = m_itemData.count();
1439 if (removedCount > 0) {
1440 qDeleteAll(m_itemData);
1441 m_itemData.clear();
1442 m_items.clear();
1443 Q_EMIT itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
1444 }
1445
1446 m_expandedDirs.clear();
1447 }
1448
1449 void KFileItemModel::slotSortingChoiceChanged()
1450 {
1451 loadSortingSettings();
1452 resortAllItems();
1453 }
1454
1455 void KFileItemModel::dispatchPendingItemsToInsert()
1456 {
1457 if (!m_pendingItemsToInsert.isEmpty()) {
1458 insertItems(m_pendingItemsToInsert);
1459 m_pendingItemsToInsert.clear();
1460 }
1461 }
1462
1463 void KFileItemModel::insertItems(QList<ItemData *> &newItems)
1464 {
1465 if (newItems.isEmpty()) {
1466 return;
1467 }
1468
1469 #ifdef KFILEITEMMODEL_DEBUG
1470 QElapsedTimer timer;
1471 timer.start();
1472 qCDebug(DolphinDebug) << "===========================================================";
1473 qCDebug(DolphinDebug) << "Inserting" << newItems.count() << "items";
1474 #endif
1475
1476 m_groups.clear();
1477 prepareItemsForSorting(newItems);
1478
1479 // Natural sorting of items can be very slow. However, it becomes much faster
1480 // if the input sequence is already mostly sorted. Therefore, we first sort
1481 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1482 if (m_naturalSorting) {
1483 if (m_sortRole == NameRole) {
1484 parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
1485 } else if (isRoleValueNatural(m_sortRole)) {
1486 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
1487 const QByteArray role = roleForType(m_sortRole);
1488 return a->values.value(role).toString() < b->values.value(role).toString();
1489 };
1490 parallelMergeSort(newItems.begin(), newItems.end(), lambdaLessThan, QThread::idealThreadCount());
1491 }
1492 }
1493
1494 sort(newItems.begin(), newItems.end());
1495
1496 #ifdef KFILEITEMMODEL_DEBUG
1497 qCDebug(DolphinDebug) << "[TIME] Sorting:" << timer.elapsed();
1498 #endif
1499
1500 KItemRangeList itemRanges;
1501 const int existingItemCount = m_itemData.count();
1502 const int newItemCount = newItems.count();
1503 const int totalItemCount = existingItemCount + newItemCount;
1504
1505 if (existingItemCount == 0) {
1506 // Optimization for the common special case that there are no
1507 // items in the model yet. Happens, e.g., when entering a folder.
1508 m_itemData = newItems;
1509 itemRanges << KItemRange(0, newItemCount);
1510 } else {
1511 m_itemData.reserve(totalItemCount);
1512 for (int i = existingItemCount; i < totalItemCount; ++i) {
1513 m_itemData.append(nullptr);
1514 }
1515
1516 // We build the new list m_itemData in reverse order to minimize
1517 // the number of moves and guarantee O(N) complexity.
1518 int targetIndex = totalItemCount - 1;
1519 int sourceIndexExistingItems = existingItemCount - 1;
1520 int sourceIndexNewItems = newItemCount - 1;
1521
1522 int rangeCount = 0;
1523
1524 while (sourceIndexNewItems >= 0) {
1525 ItemData *newItem = newItems.at(sourceIndexNewItems);
1526 if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
1527 // Move an existing item to its new position. If any new items
1528 // are behind it, push the item range to itemRanges.
1529 if (rangeCount > 0) {
1530 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1531 rangeCount = 0;
1532 }
1533
1534 m_itemData[targetIndex] = m_itemData.at(sourceIndexExistingItems);
1535 --sourceIndexExistingItems;
1536 } else {
1537 // Insert a new item into the list.
1538 ++rangeCount;
1539 m_itemData[targetIndex] = newItem;
1540 --sourceIndexNewItems;
1541 }
1542 --targetIndex;
1543 }
1544
1545 // Push the final item range to itemRanges.
1546 if (rangeCount > 0) {
1547 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1548 }
1549
1550 // Note that itemRanges is still sorted in reverse order.
1551 std::reverse(itemRanges.begin(), itemRanges.end());
1552 }
1553
1554 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1555 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1556 m_items.clear();
1557
1558 Q_EMIT itemsInserted(itemRanges);
1559
1560 #ifdef KFILEITEMMODEL_DEBUG
1561 qCDebug(DolphinDebug) << "[TIME] Inserting of" << newItems.count() << "items:" << timer.elapsed();
1562 #endif
1563 }
1564
1565 void KFileItemModel::removeItems(const KItemRangeList &itemRanges, RemoveItemsBehavior behavior)
1566 {
1567 if (itemRanges.isEmpty()) {
1568 return;
1569 }
1570
1571 m_groups.clear();
1572
1573 // Step 1: Remove the items from m_itemData, and free the ItemData.
1574 int removedItemsCount = 0;
1575 for (const KItemRange &range : itemRanges) {
1576 removedItemsCount += range.count;
1577
1578 for (int index = range.index; index < range.index + range.count; ++index) {
1579 if (behavior == DeleteItemData || (behavior == DeleteItemDataIfUnfiltered && !m_filteredItems.contains(m_itemData.at(index)->item))) {
1580 delete m_itemData.at(index);
1581 }
1582
1583 m_itemData[index] = nullptr;
1584 }
1585 }
1586
1587 // Step 2: Remove the ItemData pointers from the list m_itemData.
1588 int target = itemRanges.at(0).index;
1589 int source = itemRanges.at(0).index + itemRanges.at(0).count;
1590 int nextRange = 1;
1591
1592 const int oldItemDataCount = m_itemData.count();
1593 while (source < oldItemDataCount) {
1594 m_itemData[target] = m_itemData[source];
1595 ++target;
1596 ++source;
1597
1598 if (nextRange < itemRanges.count() && source == itemRanges.at(nextRange).index) {
1599 // Skip the items in the next removed range.
1600 source += itemRanges.at(nextRange).count;
1601 ++nextRange;
1602 }
1603 }
1604
1605 m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end());
1606
1607 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1608 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1609 m_items.clear();
1610
1611 Q_EMIT itemsRemoved(itemRanges);
1612 }
1613
1614 QList<KFileItemModel::ItemData *> KFileItemModel::createItemDataList(const QUrl &parentUrl, const KFileItemList &items) const
1615 {
1616 if (m_sortRole == TypeRole) {
1617 // Try to resolve the MIME-types synchronously to prevent a reordering of
1618 // the items when sorting by type (per default MIME-types are resolved
1619 // asynchronously by KFileItemModelRolesUpdater).
1620 determineMimeTypes(items, 200);
1621 }
1622
1623 // We search for the parent in m_itemData and then in m_filteredItems if necessary
1624 const int parentIndex = index(parentUrl);
1625 ItemData *parentItem = parentIndex < 0 ? m_filteredItems.value(KFileItem(parentUrl), nullptr) : m_itemData.at(parentIndex);
1626
1627 QList<ItemData *> itemDataList;
1628 itemDataList.reserve(items.count());
1629
1630 for (const KFileItem &item : items) {
1631 ItemData *itemData = new ItemData();
1632 itemData->item = item;
1633 itemData->parent = parentItem;
1634 itemDataList.append(itemData);
1635 }
1636
1637 return itemDataList;
1638 }
1639
1640 void KFileItemModel::prepareItemsForSorting(QList<ItemData *> &itemDataList)
1641 {
1642 switch (m_sortRole) {
1643 case ExtensionRole:
1644 case PermissionsRole:
1645 case OwnerRole:
1646 case GroupRole:
1647 case DestinationRole:
1648 case PathRole:
1649 case DeletionTimeRole:
1650 // These roles can be determined with retrieveData, and they have to be stored
1651 // in the QHash "values" for the sorting.
1652 for (ItemData *itemData : std::as_const(itemDataList)) {
1653 if (itemData->values.isEmpty()) {
1654 itemData->values = retrieveData(itemData->item, itemData->parent);
1655 }
1656 }
1657 break;
1658
1659 case TypeRole:
1660 // At least store the data including the file type for items with known MIME type.
1661 for (ItemData *itemData : std::as_const(itemDataList)) {
1662 if (itemData->values.isEmpty()) {
1663 const KFileItem item = itemData->item;
1664 if (item.isDir() || item.isMimeTypeKnown()) {
1665 itemData->values = retrieveData(itemData->item, itemData->parent);
1666 }
1667 }
1668 }
1669 break;
1670
1671 default:
1672 // The other roles are either resolved by KFileItemModelRolesUpdater
1673 // (this includes the SizeRole for directories), or they do not need
1674 // to be stored in the QHash "values" for sorting because the data can
1675 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1676 // DateRole).
1677 break;
1678 }
1679 }
1680
1681 int KFileItemModel::expandedParentsCount(const ItemData *data)
1682 {
1683 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1684 // if the corresponding item is expanded, and it is not a top-level item.
1685 const ItemData *parent = data->parent;
1686 if (parent) {
1687 if (parent->parent) {
1688 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1689 return parent->values.value("expandedParentsCount").toInt() + 1;
1690 } else {
1691 return 1;
1692 }
1693 } else {
1694 return 0;
1695 }
1696 }
1697
1698 void KFileItemModel::removeExpandedItems()
1699 {
1700 QVector<int> indexesToRemove;
1701
1702 const int maxIndex = m_itemData.count() - 1;
1703 for (int i = 0; i <= maxIndex; ++i) {
1704 const ItemData *itemData = m_itemData.at(i);
1705 if (itemData->parent) {
1706 indexesToRemove.append(i);
1707 }
1708 }
1709
1710 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1711 m_expandedDirs.clear();
1712
1713 // Also remove all filtered items which have a parent.
1714 QHash<KFileItem, ItemData *>::iterator it = m_filteredItems.begin();
1715 const QHash<KFileItem, ItemData *>::iterator end = m_filteredItems.end();
1716
1717 while (it != end) {
1718 if (it.value()->parent) {
1719 delete it.value();
1720 it = m_filteredItems.erase(it);
1721 } else {
1722 ++it;
1723 }
1724 }
1725 }
1726
1727 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList &itemRanges, const QSet<QByteArray> &changedRoles)
1728 {
1729 Q_EMIT itemsChanged(itemRanges, changedRoles);
1730
1731 // Trigger a resorting if necessary. Note that this can happen even if the sort
1732 // role has not changed at all because the file name can be used as a fallback.
1733 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) {
1734 for (const KItemRange &range : itemRanges) {
1735 bool needsResorting = false;
1736
1737 const int first = range.index;
1738 const int last = range.index + range.count - 1;
1739
1740 // Resorting the model is necessary if
1741 // (a) The first item in the range is "lessThan" its predecessor,
1742 // (b) the successor of the last item is "lessThan" the last item, or
1743 // (c) the internal order of the items in the range is incorrect.
1744 if (first > 0 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1745 needsResorting = true;
1746 } else if (last < count() - 1 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1747 needsResorting = true;
1748 } else {
1749 for (int index = first; index < last; ++index) {
1750 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1751 needsResorting = true;
1752 break;
1753 }
1754 }
1755 }
1756
1757 if (needsResorting) {
1758 m_resortAllItemsTimer->start();
1759 return;
1760 }
1761 }
1762 }
1763
1764 if (groupedSorting() && changedRoles.contains(sortRole())) {
1765 // The position is still correct, but the groups might have changed
1766 // if the changed item is either the first or the last item in a
1767 // group.
1768 // In principle, we could try to find out if the item really is the
1769 // first or last one in its group and then update the groups
1770 // (possibly with a delayed timer to make sure that we don't
1771 // re-calculate the groups very often if items are updated one by
1772 // one), but starting m_resortAllItemsTimer is easier.
1773 m_resortAllItemsTimer->start();
1774 }
1775 }
1776
1777 void KFileItemModel::resetRoles()
1778 {
1779 for (int i = 0; i < RolesCount; ++i) {
1780 m_requestRole[i] = false;
1781 }
1782 }
1783
1784 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray &role) const
1785 {
1786 static QHash<QByteArray, RoleType> roles;
1787 if (roles.isEmpty()) {
1788 // Insert user visible roles that can be accessed with
1789 // KFileItemModel::roleInformation()
1790 int count = 0;
1791 const RoleInfoMap *map = rolesInfoMap(count);
1792 for (int i = 0; i < count; ++i) {
1793 roles.insert(map[i].role, map[i].roleType);
1794 }
1795
1796 // Insert internal roles (take care to synchronize the implementation
1797 // with KFileItemModel::roleForType() in case if a change is done).
1798 roles.insert("isDir", IsDirRole);
1799 roles.insert("isLink", IsLinkRole);
1800 roles.insert("isHidden", IsHiddenRole);
1801 roles.insert("isExpanded", IsExpandedRole);
1802 roles.insert("isExpandable", IsExpandableRole);
1803 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1804
1805 Q_ASSERT(roles.count() == RolesCount);
1806 }
1807
1808 return roles.value(role, NoRole);
1809 }
1810
1811 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1812 {
1813 static QHash<RoleType, QByteArray> roles;
1814 if (roles.isEmpty()) {
1815 // Insert user visible roles that can be accessed with
1816 // KFileItemModel::roleInformation()
1817 int count = 0;
1818 const RoleInfoMap *map = rolesInfoMap(count);
1819 for (int i = 0; i < count; ++i) {
1820 roles.insert(map[i].roleType, map[i].role);
1821 }
1822
1823 // Insert internal roles (take care to synchronize the implementation
1824 // with KFileItemModel::typeForRole() in case if a change is done).
1825 roles.insert(IsDirRole, "isDir");
1826 roles.insert(IsLinkRole, "isLink");
1827 roles.insert(IsHiddenRole, "isHidden");
1828 roles.insert(IsExpandedRole, "isExpanded");
1829 roles.insert(IsExpandableRole, "isExpandable");
1830 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1831
1832 Q_ASSERT(roles.count() == RolesCount);
1833 };
1834
1835 return roles.value(roleType);
1836 }
1837
1838 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem &item, const ItemData *parent) const
1839 {
1840 // It is important to insert only roles that are fast to retrieve. E.g.
1841 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1842 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1843 QHash<QByteArray, QVariant> data;
1844 data.insert(sharedValue("url"), item.url());
1845
1846 const bool isDir = item.isDir();
1847 if (m_requestRole[IsDirRole] && isDir) {
1848 data.insert(sharedValue("isDir"), true);
1849 }
1850
1851 if (m_requestRole[IsLinkRole] && item.isLink()) {
1852 data.insert(sharedValue("isLink"), true);
1853 }
1854
1855 if (m_requestRole[IsHiddenRole]) {
1856 data.insert(sharedValue("isHidden"), item.isHidden() || item.mimetype() == QStringLiteral("application/x-trash"));
1857 }
1858
1859 if (m_requestRole[NameRole]) {
1860 data.insert(sharedValue("text"), item.text());
1861 }
1862
1863 if (m_requestRole[ExtensionRole] && !isDir) {
1864 // TODO KF6 use KFileItem::suffix 464722
1865 data.insert(sharedValue("extension"), QFileInfo(item.name()).suffix());
1866 }
1867
1868 if (m_requestRole[SizeRole] && !isDir) {
1869 data.insert(sharedValue("size"), item.size());
1870 }
1871
1872 if (m_requestRole[ModificationTimeRole]) {
1873 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1874 // having several thousands of items. Instead read the raw number from UDSEntry directly
1875 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1876 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1877 data.insert(sharedValue("modificationtime"), dateTime);
1878 }
1879
1880 if (m_requestRole[CreationTimeRole]) {
1881 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1882 // having several thousands of items. Instead read the raw number from UDSEntry directly
1883 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1884 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1885 data.insert(sharedValue("creationtime"), dateTime);
1886 }
1887
1888 if (m_requestRole[AccessTimeRole]) {
1889 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1890 // having several thousands of items. Instead read the raw number from UDSEntry directly
1891 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1892 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1893 data.insert(sharedValue("accesstime"), dateTime);
1894 }
1895
1896 if (m_requestRole[PermissionsRole]) {
1897 data.insert(sharedValue("permissions"), QVariantList() << item.permissionsString() << item.permissions());
1898 }
1899
1900 if (m_requestRole[OwnerRole]) {
1901 data.insert(sharedValue("owner"), item.user());
1902 }
1903
1904 if (m_requestRole[GroupRole]) {
1905 data.insert(sharedValue("group"), item.group());
1906 }
1907
1908 if (m_requestRole[DestinationRole]) {
1909 QString destination = item.linkDest();
1910 if (destination.isEmpty()) {
1911 destination = QLatin1Char('-');
1912 }
1913 data.insert(sharedValue("destination"), destination);
1914 }
1915
1916 if (m_requestRole[PathRole]) {
1917 QString path;
1918 if (item.url().scheme() == QLatin1String("trash")) {
1919 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1920 } else {
1921 // For performance reasons cache the home-path in a static QString
1922 // (see QDir::homePath() for more details)
1923 static QString homePath;
1924 if (homePath.isEmpty()) {
1925 homePath = QDir::homePath();
1926 }
1927
1928 path = item.localPath();
1929 if (path.startsWith(homePath)) {
1930 path.replace(0, homePath.length(), QLatin1Char('~'));
1931 }
1932 }
1933
1934 const int index = path.lastIndexOf(item.text());
1935 path = path.mid(0, index - 1);
1936 data.insert(sharedValue("path"), path);
1937 }
1938
1939 if (m_requestRole[DeletionTimeRole]) {
1940 QDateTime deletionTime;
1941 if (item.url().scheme() == QLatin1String("trash")) {
1942 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
1943 }
1944 data.insert(sharedValue("deletiontime"), deletionTime);
1945 }
1946
1947 if (m_requestRole[IsExpandableRole] && isDir) {
1948 data.insert(sharedValue("isExpandable"), true);
1949 }
1950
1951 if (m_requestRole[ExpandedParentsCountRole]) {
1952 if (parent) {
1953 const int level = expandedParentsCount(parent) + 1;
1954 data.insert(sharedValue("expandedParentsCount"), level);
1955 }
1956 }
1957
1958 if (item.isMimeTypeKnown()) {
1959 QString iconName = item.iconName();
1960 if (!QIcon::hasThemeIcon(iconName)) {
1961 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
1962 iconName = mimeType.genericIconName();
1963 }
1964
1965 data.insert(sharedValue("iconName"), iconName);
1966
1967 if (m_requestRole[TypeRole]) {
1968 data.insert(sharedValue("type"), item.mimeComment());
1969 }
1970 } else if (m_requestRole[TypeRole] && isDir) {
1971 static const QString folderMimeType = item.mimeComment();
1972 data.insert(sharedValue("type"), folderMimeType);
1973 }
1974
1975 return data;
1976 }
1977
1978 bool KFileItemModel::lessThan(const ItemData *a, const ItemData *b, const QCollator &collator) const
1979 {
1980 int result = 0;
1981
1982 if (a->parent != b->parent) {
1983 const int expansionLevelA = expandedParentsCount(a);
1984 const int expansionLevelB = expandedParentsCount(b);
1985
1986 // If b has a higher expansion level than a, check if a is a parent
1987 // of b, and make sure that both expansion levels are equal otherwise.
1988 for (int i = expansionLevelB; i > expansionLevelA; --i) {
1989 if (b->parent == a) {
1990 return true;
1991 }
1992 b = b->parent;
1993 }
1994
1995 // If a has a higher expansion level than a, check if b is a parent
1996 // of a, and make sure that both expansion levels are equal otherwise.
1997 for (int i = expansionLevelA; i > expansionLevelB; --i) {
1998 if (a->parent == b) {
1999 return false;
2000 }
2001 a = a->parent;
2002 }
2003
2004 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
2005
2006 // Compare the last parents of a and b which are different.
2007 while (a->parent != b->parent) {
2008 a = a->parent;
2009 b = b->parent;
2010 }
2011 }
2012
2013 // Show hidden files and folders last
2014 if (m_sortHiddenLast) {
2015 const bool isHiddenA = a->item.isHidden();
2016 const bool isHiddenB = b->item.isHidden();
2017 if (isHiddenA && !isHiddenB) {
2018 return false;
2019 } else if (!isHiddenA && isHiddenB) {
2020 return true;
2021 }
2022 }
2023
2024 if (m_sortDirsFirst || (ContentDisplaySettings::directorySizeCount() && m_sortRole == SizeRole)) {
2025 const bool isDirA = a->item.isDir();
2026 const bool isDirB = b->item.isDir();
2027 if (isDirA && !isDirB) {
2028 return true;
2029 } else if (!isDirA && isDirB) {
2030 return false;
2031 }
2032 }
2033
2034 result = sortRoleCompare(a, b, collator);
2035
2036 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
2037 }
2038
2039 void KFileItemModel::sort(const QList<KFileItemModel::ItemData *>::iterator &begin, const QList<KFileItemModel::ItemData *>::iterator &end) const
2040 {
2041 auto lambdaLessThan = [&](const KFileItemModel::ItemData *a, const KFileItemModel::ItemData *b) {
2042 return lessThan(a, b, m_collator);
2043 };
2044
2045 if (m_sortRole == NameRole || isRoleValueNatural(m_sortRole)) {
2046 // Sorting by string can be expensive, in particular if natural sorting is
2047 // enabled. Use all CPU cores to speed up the sorting process.
2048 static const int numberOfThreads = QThread::idealThreadCount();
2049 parallelMergeSort(begin, end, lambdaLessThan, numberOfThreads);
2050 } else {
2051 // Sorting by other roles is quite fast. Use only one thread to prevent
2052 // problems caused by non-reentrant comparison functions, see
2053 // https://bugs.kde.org/show_bug.cgi?id=312679
2054 mergeSort(begin, end, lambdaLessThan);
2055 }
2056 }
2057
2058 int KFileItemModel::sortRoleCompare(const ItemData *a, const ItemData *b, const QCollator &collator) const
2059 {
2060 // This function must never return 0, because that would break stable
2061 // sorting, which leads to all kinds of bugs.
2062 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2063 // If two items have equal sort values, let the fallbacks at the bottom of
2064 // the function handle it.
2065 const KFileItem &itemA = a->item;
2066 const KFileItem &itemB = b->item;
2067
2068 int result = 0;
2069
2070 switch (m_sortRole) {
2071 case NameRole:
2072 // The name role is handled as default fallback after the switch
2073 break;
2074
2075 case SizeRole: {
2076 if (ContentDisplaySettings::directorySizeCount() && itemA.isDir()) {
2077 // folders first then
2078 // items A and B are folders thanks to lessThan checks
2079 auto valueA = a->values.value("count");
2080 auto valueB = b->values.value("count");
2081 if (valueA.isNull()) {
2082 if (!valueB.isNull()) {
2083 return -1;
2084 }
2085 } else if (valueB.isNull()) {
2086 return +1;
2087 } else {
2088 if (valueA.toLongLong() < valueB.toLongLong()) {
2089 return -1;
2090 } else if (valueA.toLongLong() > valueB.toLongLong()) {
2091 return +1;
2092 }
2093 }
2094 break;
2095 }
2096
2097 KIO::filesize_t sizeA = 0;
2098 if (itemA.isDir()) {
2099 sizeA = a->values.value("size").toULongLong();
2100 } else {
2101 sizeA = itemA.size();
2102 }
2103 KIO::filesize_t sizeB = 0;
2104 if (itemB.isDir()) {
2105 sizeB = b->values.value("size").toULongLong();
2106 } else {
2107 sizeB = itemB.size();
2108 }
2109 if (sizeA < sizeB) {
2110 return -1;
2111 } else if (sizeA > sizeB) {
2112 return +1;
2113 }
2114 break;
2115 }
2116
2117 case ModificationTimeRole: {
2118 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2119 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2120 if (dateTimeA < dateTimeB) {
2121 return -1;
2122 } else if (dateTimeA > dateTimeB) {
2123 return +1;
2124 }
2125 break;
2126 }
2127
2128 case AccessTimeRole: {
2129 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2130 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
2131 if (dateTimeA < dateTimeB) {
2132 return -1;
2133 } else if (dateTimeA > dateTimeB) {
2134 return +1;
2135 }
2136 break;
2137 }
2138
2139 case CreationTimeRole: {
2140 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2141 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2142 if (dateTimeA < dateTimeB) {
2143 return -1;
2144 } else if (dateTimeA > dateTimeB) {
2145 return +1;
2146 }
2147 break;
2148 }
2149
2150 case DeletionTimeRole: {
2151 const QDateTime dateTimeA = a->values.value("deletiontime").toDateTime();
2152 const QDateTime dateTimeB = b->values.value("deletiontime").toDateTime();
2153 if (dateTimeA < dateTimeB) {
2154 return -1;
2155 } else if (dateTimeA > dateTimeB) {
2156 return +1;
2157 }
2158 break;
2159 }
2160
2161 case RatingRole:
2162 case WidthRole:
2163 case HeightRole:
2164 case PublisherRole:
2165 case PageCountRole:
2166 case WordCountRole:
2167 case LineCountRole:
2168 case TrackRole:
2169 case ReleaseYearRole: {
2170 result = a->values.value(roleForType(m_sortRole)).toInt() - b->values.value(roleForType(m_sortRole)).toInt();
2171 break;
2172 }
2173
2174 case DimensionsRole: {
2175 const QByteArray role = roleForType(m_sortRole);
2176 const QSize dimensionsA = a->values.value(role).toSize();
2177 const QSize dimensionsB = b->values.value(role).toSize();
2178
2179 if (dimensionsA.width() == dimensionsB.width()) {
2180 result = dimensionsA.height() - dimensionsB.height();
2181 } else {
2182 result = dimensionsA.width() - dimensionsB.width();
2183 }
2184 break;
2185 }
2186
2187 default: {
2188 const QByteArray role = roleForType(m_sortRole);
2189 const QString roleValueA = a->values.value(role).toString();
2190 const QString roleValueB = b->values.value(role).toString();
2191 if (!roleValueA.isEmpty() && roleValueB.isEmpty()) {
2192 return -1;
2193 } else if (roleValueA.isEmpty() && !roleValueB.isEmpty()) {
2194 return +1;
2195 } else if (isRoleValueNatural(m_sortRole)) {
2196 result = stringCompare(roleValueA, roleValueB, collator);
2197 } else {
2198 result = QString::compare(roleValueA, roleValueB);
2199 }
2200 break;
2201 }
2202 }
2203
2204 if (result != 0) {
2205 // The current sort role was sufficient to define an order
2206 return result;
2207 }
2208
2209 // Fallback #1: Compare the text of the items
2210 result = stringCompare(itemA.text(), itemB.text(), collator);
2211 if (result != 0) {
2212 return result;
2213 }
2214
2215 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2216 result = stringCompare(itemA.name(), itemB.name(), collator);
2217 if (result != 0) {
2218 return result;
2219 }
2220
2221 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2222 // equal. In this case a comparison of the URL is done which is unique in all cases
2223 // within KDirLister.
2224 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
2225 }
2226
2227 int KFileItemModel::stringCompare(const QString &a, const QString &b, const QCollator &collator) const
2228 {
2229 QMutexLocker collatorLock(s_collatorMutex());
2230
2231 if (m_naturalSorting) {
2232 return collator.compare(a, b);
2233 }
2234
2235 const int result = QString::compare(a, b, collator.caseSensitivity());
2236 if (result != 0 || collator.caseSensitivity() == Qt::CaseSensitive) {
2237 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2238 // comparison, still a deterministic sort order is required. A case sensitive
2239 // comparison is done as fallback.
2240 return result;
2241 }
2242
2243 return QString::compare(a, b, Qt::CaseSensitive);
2244 }
2245
2246 QList<QPair<int, QVariant>> KFileItemModel::nameRoleGroups() const
2247 {
2248 Q_ASSERT(!m_itemData.isEmpty());
2249
2250 const int maxIndex = count() - 1;
2251 QList<QPair<int, QVariant>> groups;
2252
2253 QString groupValue;
2254 QChar firstChar;
2255 for (int i = 0; i <= maxIndex; ++i) {
2256 if (isChildItem(i)) {
2257 continue;
2258 }
2259
2260 const QString name = m_itemData.at(i)->item.text();
2261
2262 // Use the first character of the name as group indication
2263 QChar newFirstChar = name.at(0).toUpper();
2264 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
2265 newFirstChar = name.at(1).toUpper();
2266 }
2267
2268 if (firstChar != newFirstChar) {
2269 QString newGroupValue;
2270 if (newFirstChar.isLetter()) {
2271 if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) {
2272 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2273
2274 // Try to find a matching group in the range 'A' to 'Z'.
2275 static std::vector<QChar> lettersAtoZ;
2276 lettersAtoZ.reserve('Z' - 'A' + 1);
2277 if (lettersAtoZ.empty()) {
2278 for (char c = 'A'; c <= 'Z'; ++c) {
2279 lettersAtoZ.push_back(QLatin1Char(c));
2280 }
2281 }
2282
2283 auto localeAwareLessThan = [this](QChar c1, QChar c2) -> bool {
2284 return m_collator.compare(c1, c2) < 0;
2285 };
2286
2287 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), newFirstChar, localeAwareLessThan);
2288 if (it != lettersAtoZ.end()) {
2289 if (localeAwareLessThan(newFirstChar, *it)) {
2290 // newFirstChar belongs to the group preceding *it.
2291 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2292 --it;
2293 }
2294 newGroupValue = *it;
2295 }
2296
2297 } else {
2298 // Symbols from non Latin-based scripts
2299 newGroupValue = newFirstChar;
2300 }
2301 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
2302 // Apply group '0 - 9' for any name that starts with a digit
2303 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
2304 } else {
2305 newGroupValue = i18nc("@title:group", "Others");
2306 }
2307
2308 if (newGroupValue != groupValue) {
2309 groupValue = newGroupValue;
2310 groups.append(QPair<int, QVariant>(i, newGroupValue));
2311 }
2312
2313 firstChar = newFirstChar;
2314 }
2315 }
2316 return groups;
2317 }
2318
2319 QList<QPair<int, QVariant>> KFileItemModel::sizeRoleGroups() const
2320 {
2321 Q_ASSERT(!m_itemData.isEmpty());
2322
2323 const int maxIndex = count() - 1;
2324 QList<QPair<int, QVariant>> groups;
2325
2326 QString groupValue;
2327 for (int i = 0; i <= maxIndex; ++i) {
2328 if (isChildItem(i)) {
2329 continue;
2330 }
2331
2332 const KFileItem &item = m_itemData.at(i)->item;
2333 KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
2334 QString newGroupValue;
2335 if (!item.isNull() && item.isDir()) {
2336 if (ContentDisplaySettings::directorySizeCount() || m_sortDirsFirst) {
2337 newGroupValue = i18nc("@title:group Size", "Folders");
2338 } else {
2339 fileSize = m_itemData.at(i)->values.value("size").toULongLong();
2340 }
2341 }
2342
2343 if (newGroupValue.isEmpty()) {
2344 if (fileSize < 5 * 1024 * 1024) { // < 5 MB
2345 newGroupValue = i18nc("@title:group Size", "Small");
2346 } else if (fileSize < 10 * 1024 * 1024) { // < 10 MB
2347 newGroupValue = i18nc("@title:group Size", "Medium");
2348 } else {
2349 newGroupValue = i18nc("@title:group Size", "Big");
2350 }
2351 }
2352
2353 if (newGroupValue != groupValue) {
2354 groupValue = newGroupValue;
2355 groups.append(QPair<int, QVariant>(i, newGroupValue));
2356 }
2357 }
2358
2359 return groups;
2360 }
2361
2362 QList<QPair<int, QVariant>> KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
2363 {
2364 Q_ASSERT(!m_itemData.isEmpty());
2365
2366 const int maxIndex = count() - 1;
2367 QList<QPair<int, QVariant>> groups;
2368
2369 const QDate currentDate = QDate::currentDate();
2370
2371 QDate previousFileDate;
2372 QString groupValue;
2373 for (int i = 0; i <= maxIndex; ++i) {
2374 if (isChildItem(i)) {
2375 continue;
2376 }
2377
2378 const QDateTime fileTime = fileTimeCb(m_itemData.at(i));
2379 const QDate fileDate = fileTime.date();
2380 if (fileDate == previousFileDate) {
2381 // The current item is in the same group as the previous item
2382 continue;
2383 }
2384 previousFileDate = fileDate;
2385
2386 const int daysDistance = fileDate.daysTo(currentDate);
2387
2388 QString newGroupValue;
2389 if (currentDate.year() == fileDate.year() && currentDate.month() == fileDate.month()) {
2390 switch (daysDistance / 7) {
2391 case 0:
2392 switch (daysDistance) {
2393 case 0:
2394 newGroupValue = i18nc("@title:group Date", "Today");
2395 break;
2396 case 1:
2397 newGroupValue = i18nc("@title:group Date", "Yesterday");
2398 break;
2399 default:
2400 newGroupValue = fileTime.toString(i18nc("@title:group Date: The week day name: dddd", "dddd"));
2401 newGroupValue = i18nc(
2402 "Can be used to script translation of \"dddd\""
2403 "with context @title:group Date",
2404 "%1",
2405 newGroupValue);
2406 }
2407 break;
2408 case 1:
2409 newGroupValue = i18nc("@title:group Date", "One Week Ago");
2410 break;
2411 case 2:
2412 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
2413 break;
2414 case 3:
2415 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
2416 break;
2417 case 4:
2418 case 5:
2419 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
2420 break;
2421 default:
2422 Q_ASSERT(false);
2423 }
2424 } else {
2425 const QDate lastMonthDate = currentDate.addMonths(-1);
2426 if (lastMonthDate.year() == fileDate.year() && lastMonthDate.month() == fileDate.month()) {
2427 if (daysDistance == 1) {
2428 const KLocalizedString format = ki18nc(
2429 "@title:group Date: "
2430 "MMMM is full month name in current locale, and yyyy is "
2431 "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 "
2432 "part of the text that should not be formatted as a date",
2433 "'Yesterday' (MMMM, yyyy)");
2434 const QString translatedFormat = format.toString();
2435 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2436 newGroupValue = fileTime.toString(translatedFormat);
2437 newGroupValue = i18nc(
2438 "Can be used to script translation of "
2439 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2440 "%1",
2441 newGroupValue);
2442 } else {
2443 qCWarning(DolphinDebug).nospace()
2444 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2445 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2446 newGroupValue = fileTime.toString(untranslatedFormat);
2447 }
2448 } else if (daysDistance <= 7) {
2449 newGroupValue =
2450 fileTime.toString(i18nc("@title:group Date: "
2451 "The week day name: dddd, MMMM is full month name "
2452 "in current locale, and yyyy is full year number.",
2453 "dddd (MMMM, yyyy)"));
2454 newGroupValue = i18nc(
2455 "Can be used to script translation of "
2456 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2457 "%1",
2458 newGroupValue);
2459 } else if (daysDistance <= 7 * 2) {
2460 const KLocalizedString format = ki18nc(
2461 "@title:group Date: "
2462 "MMMM is full month name in current locale, and yyyy is "
2463 "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 "
2464 "part of the text that should not be formatted as a date",
2465 "'One Week Ago' (MMMM, yyyy)");
2466 const QString translatedFormat = format.toString();
2467 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2468 newGroupValue = fileTime.toString(translatedFormat);
2469 newGroupValue = i18nc(
2470 "Can be used to script translation of "
2471 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2472 "%1",
2473 newGroupValue);
2474 } else {
2475 qCWarning(DolphinDebug).nospace()
2476 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2477 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2478 newGroupValue = fileTime.toString(untranslatedFormat);
2479 }
2480 } else if (daysDistance <= 7 * 3) {
2481 const KLocalizedString format = ki18nc(
2482 "@title:group Date: "
2483 "MMMM is full month name in current locale, and yyyy is "
2484 "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 "
2485 "part of the text that should not be formatted as a date",
2486 "'Two Weeks Ago' (MMMM, yyyy)");
2487 const QString translatedFormat = format.toString();
2488 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2489 newGroupValue = fileTime.toString(translatedFormat);
2490 newGroupValue = i18nc(
2491 "Can be used to script translation of "
2492 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2493 "%1",
2494 newGroupValue);
2495 } else {
2496 qCWarning(DolphinDebug).nospace()
2497 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2498 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2499 newGroupValue = fileTime.toString(untranslatedFormat);
2500 }
2501 } else if (daysDistance <= 7 * 4) {
2502 const KLocalizedString format = ki18nc(
2503 "@title:group Date: "
2504 "MMMM is full month name in current locale, and yyyy is "
2505 "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 "
2506 "part of the text that should not be formatted as a date",
2507 "'Three Weeks Ago' (MMMM, yyyy)");
2508 const QString translatedFormat = format.toString();
2509 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2510 newGroupValue = fileTime.toString(translatedFormat);
2511 newGroupValue = i18nc(
2512 "Can be used to script translation of "
2513 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2514 "%1",
2515 newGroupValue);
2516 } else {
2517 qCWarning(DolphinDebug).nospace()
2518 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2519 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2520 newGroupValue = fileTime.toString(untranslatedFormat);
2521 }
2522 } else {
2523 const KLocalizedString format = ki18nc(
2524 "@title:group Date: "
2525 "MMMM is full month name in current locale, and yyyy is "
2526 "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 "
2527 "part of the text that should not be formatted as a date",
2528 "'Earlier on' MMMM, yyyy");
2529 const QString translatedFormat = format.toString();
2530 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2531 newGroupValue = fileTime.toString(translatedFormat);
2532 newGroupValue = i18nc(
2533 "Can be used to script translation of "
2534 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2535 "%1",
2536 newGroupValue);
2537 } else {
2538 qCWarning(DolphinDebug).nospace()
2539 << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2540 const QString untranslatedFormat = format.toString({QLatin1String("en_US")});
2541 newGroupValue = fileTime.toString(untranslatedFormat);
2542 }
2543 }
2544 } else {
2545 newGroupValue =
2546 fileTime.toString(i18nc("@title:group "
2547 "The month and year: MMMM is full month name in current locale, "
2548 "and yyyy is full year number",
2549 "MMMM, yyyy"));
2550 newGroupValue = i18nc(
2551 "Can be used to script translation of "
2552 "\"MMMM, yyyy\" with context @title:group Date",
2553 "%1",
2554 newGroupValue);
2555 }
2556 }
2557
2558 if (newGroupValue != groupValue) {
2559 groupValue = newGroupValue;
2560 groups.append(QPair<int, QVariant>(i, newGroupValue));
2561 }
2562 }
2563
2564 return groups;
2565 }
2566
2567 QList<QPair<int, QVariant>> KFileItemModel::permissionRoleGroups() const
2568 {
2569 Q_ASSERT(!m_itemData.isEmpty());
2570
2571 const int maxIndex = count() - 1;
2572 QList<QPair<int, QVariant>> groups;
2573
2574 QString permissionsString;
2575 QString groupValue;
2576 for (int i = 0; i <= maxIndex; ++i) {
2577 if (isChildItem(i)) {
2578 continue;
2579 }
2580
2581 const ItemData *itemData = m_itemData.at(i);
2582 const QString newPermissionsString = itemData->values.value("permissions").toString();
2583 if (newPermissionsString == permissionsString) {
2584 continue;
2585 }
2586 permissionsString = newPermissionsString;
2587
2588 const QFileInfo info(itemData->item.url().toLocalFile());
2589
2590 // Set user string
2591 QString user;
2592 if (info.permission(QFile::ReadUser)) {
2593 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
2594 }
2595 if (info.permission(QFile::WriteUser)) {
2596 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
2597 }
2598 if (info.permission(QFile::ExeUser)) {
2599 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2600 }
2601 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.length() - 2);
2602
2603 // Set group string
2604 QString group;
2605 if (info.permission(QFile::ReadGroup)) {
2606 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
2607 }
2608 if (info.permission(QFile::WriteGroup)) {
2609 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
2610 }
2611 if (info.permission(QFile::ExeGroup)) {
2612 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2613 }
2614 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.length() - 2);
2615
2616 // Set others string
2617 QString others;
2618 if (info.permission(QFile::ReadOther)) {
2619 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
2620 }
2621 if (info.permission(QFile::WriteOther)) {
2622 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
2623 }
2624 if (info.permission(QFile::ExeOther)) {
2625 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2626 }
2627 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.length() - 2);
2628
2629 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
2630 if (newGroupValue != groupValue) {
2631 groupValue = newGroupValue;
2632 groups.append(QPair<int, QVariant>(i, newGroupValue));
2633 }
2634 }
2635
2636 return groups;
2637 }
2638
2639 QList<QPair<int, QVariant>> KFileItemModel::ratingRoleGroups() const
2640 {
2641 Q_ASSERT(!m_itemData.isEmpty());
2642
2643 const int maxIndex = count() - 1;
2644 QList<QPair<int, QVariant>> groups;
2645
2646 int groupValue = -1;
2647 for (int i = 0; i <= maxIndex; ++i) {
2648 if (isChildItem(i)) {
2649 continue;
2650 }
2651 const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt();
2652 if (newGroupValue != groupValue) {
2653 groupValue = newGroupValue;
2654 groups.append(QPair<int, QVariant>(i, newGroupValue));
2655 }
2656 }
2657
2658 return groups;
2659 }
2660
2661 QList<QPair<int, QVariant>> KFileItemModel::genericStringRoleGroups(const QByteArray &role) const
2662 {
2663 Q_ASSERT(!m_itemData.isEmpty());
2664
2665 const int maxIndex = count() - 1;
2666 QList<QPair<int, QVariant>> groups;
2667
2668 bool isFirstGroupValue = true;
2669 QString groupValue;
2670 for (int i = 0; i <= maxIndex; ++i) {
2671 if (isChildItem(i)) {
2672 continue;
2673 }
2674 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
2675 if (newGroupValue != groupValue || isFirstGroupValue) {
2676 groupValue = newGroupValue;
2677 groups.append(QPair<int, QVariant>(i, newGroupValue));
2678 isFirstGroupValue = false;
2679 }
2680 }
2681
2682 return groups;
2683 }
2684
2685 void KFileItemModel::emitSortProgress(int resolvedCount)
2686 {
2687 // Be tolerant against a resolvedCount with a wrong range.
2688 // Although there should not be a case where KFileItemModelRolesUpdater
2689 // (= caller) provides a wrong range, it is important to emit
2690 // a useful progress information even if there is an unexpected
2691 // implementation issue.
2692
2693 const int itemCount = count();
2694 if (resolvedCount >= itemCount) {
2695 m_sortingProgressPercent = -1;
2696 if (m_resortAllItemsTimer->isActive()) {
2697 m_resortAllItemsTimer->stop();
2698 resortAllItems();
2699 }
2700
2701 Q_EMIT directorySortingProgress(100);
2702 } else if (itemCount > 0) {
2703 resolvedCount = qBound(0, resolvedCount, itemCount);
2704
2705 const int progress = resolvedCount * 100 / itemCount;
2706 if (m_sortingProgressPercent != progress) {
2707 m_sortingProgressPercent = progress;
2708 Q_EMIT directorySortingProgress(progress);
2709 }
2710 }
2711 }
2712
2713 const KFileItemModel::RoleInfoMap *KFileItemModel::rolesInfoMap(int &count)
2714 {
2715 static const RoleInfoMap rolesInfoMap[] = {
2716 // clang-format off
2717 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2718 { nullptr, NoRole, KLazyLocalizedString(), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2719 { "text", NameRole, kli18nc("@label", "Name"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2720 { "size", SizeRole, kli18nc("@label", "Size"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2721 { "modificationtime", ModificationTimeRole, kli18nc("@label", "Modified"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2722 { "creationtime", CreationTimeRole, kli18nc("@label", "Created"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2723 { "accesstime", AccessTimeRole, kli18nc("@label", "Accessed"), KLazyLocalizedString(), kli18nc("@tooltip", "The date format can be selected in settings."), false, false },
2724 { "type", TypeRole, kli18nc("@label", "Type"), KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2725 { "rating", RatingRole, kli18nc("@label", "Rating"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2726 { "tags", TagsRole, kli18nc("@label", "Tags"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2727 { "comment", CommentRole, kli18nc("@label", "Comment"), KLazyLocalizedString(), KLazyLocalizedString(), true, false },
2728 { "title", TitleRole, kli18nc("@label", "Title"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2729 { "author", AuthorRole, kli18nc("@label", "Author"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2730 { "publisher", PublisherRole, kli18nc("@label", "Publisher"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2731 { "pageCount", PageCountRole, kli18nc("@label", "Page Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2732 { "wordCount", WordCountRole, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2733 { "lineCount", LineCountRole, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), KLazyLocalizedString(), true, true },
2734 { "imageDateTime", ImageDateTimeRole, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2735 { "dimensions", DimensionsRole, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2736 { "width", WidthRole, kli18nc("@label", "Width"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2737 { "height", HeightRole, kli18nc("@label", "Height"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2738 { "orientation", OrientationRole, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), KLazyLocalizedString(), true, true },
2739 { "artist", ArtistRole, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2740 { "genre", GenreRole, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2741 { "album", AlbumRole, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2742 { "duration", DurationRole, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2743 { "bitrate", BitrateRole, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2744 { "track", TrackRole, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2745 { "releaseYear", ReleaseYearRole, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), KLazyLocalizedString(), true, true },
2746 { "aspectRatio", AspectRatioRole, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2747 { "frameRate", FrameRateRole, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), KLazyLocalizedString(), true, true },
2748 { "path", PathRole, kli18nc("@label", "Path"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2749 { "extension", ExtensionRole, kli18nc("@label", "File Extension"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2750 { "deletiontime", DeletionTimeRole, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2751 { "destination", DestinationRole, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2752 { "originUrl", OriginUrlRole, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), KLazyLocalizedString(), true, false },
2753 { "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 },
2754 { "owner", OwnerRole, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2755 { "group", GroupRole, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), KLazyLocalizedString(), false, false },
2756 };
2757 // clang-format on
2758
2759 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
2760 return rolesInfoMap;
2761 }
2762
2763 void KFileItemModel::determineMimeTypes(const KFileItemList &items, int timeout)
2764 {
2765 QElapsedTimer timer;
2766 timer.start();
2767 for (const KFileItem &item : items) {
2768 // Only determine mime types for files here. For directories,
2769 // KFileItem::determineMimeType() reads the .directory file inside to
2770 // load the icon, but this is not necessary at all if we just need the
2771 // type. Some special code for setting the correct mime type for
2772 // directories is in retrieveData().
2773 if (!item.isDir()) {
2774 item.determineMimeType();
2775 }
2776
2777 if (timer.elapsed() > timeout) {
2778 // Don't block the user interface, let the remaining items
2779 // be resolved asynchronously.
2780 return;
2781 }
2782 }
2783 }
2784
2785 QByteArray KFileItemModel::sharedValue(const QByteArray &value)
2786 {
2787 static QSet<QByteArray> pool;
2788 const QSet<QByteArray>::const_iterator it = pool.constFind(value);
2789
2790 if (it != pool.constEnd()) {
2791 return *it;
2792 } else {
2793 pool.insert(value);
2794 return value;
2795 }
2796 }
2797
2798 bool KFileItemModel::isConsistent() const
2799 {
2800 // m_items may contain less items than m_itemData because m_items
2801 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2802 if (m_items.count() > m_itemData.count()) {
2803 return false;
2804 }
2805
2806 for (int i = 0, iMax = count(); i < iMax; ++i) {
2807 // Check if m_items and m_itemData are consistent.
2808 const KFileItem item = fileItem(i);
2809 if (item.isNull()) {
2810 qCWarning(DolphinDebug) << "Item" << i << "is null";
2811 return false;
2812 }
2813
2814 const int itemIndex = index(item);
2815 if (itemIndex != i) {
2816 qCWarning(DolphinDebug) << "Item" << i << "has a wrong index:" << itemIndex;
2817 return false;
2818 }
2819
2820 // Check if the items are sorted correctly.
2821 if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
2822 qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:" << fileItem(i - 1) << fileItem(i);
2823 return false;
2824 }
2825
2826 // Check if all parent-child relationships are consistent.
2827 const ItemData *data = m_itemData.at(i);
2828 const ItemData *parent = data->parent;
2829 if (parent) {
2830 if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
2831 qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
2832 return false;
2833 }
2834
2835 const int parentIndex = index(parent->item);
2836 if (parentIndex >= i) {
2837 qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child"
2838 << data->item;
2839 return false;
2840 }
2841 }
2842 }
2843
2844 return true;
2845 }
2846
2847 void KFileItemModel::slotListerError(KIO::Job *job)
2848 {
2849 if (job->error() == KIO::ERR_IS_FILE) {
2850 if (auto *listJob = qobject_cast<KIO::ListJob *>(job)) {
2851 Q_EMIT urlIsFileError(listJob->url());
2852 }
2853 } else {
2854 const QString errorString = job->errorString();
2855 Q_EMIT errorMessage(!errorString.isEmpty() ? errorString : i18nc("@info:status", "Unknown error."));
2856 }
2857 }
2858
2859 #include "moc_kfileitemmodel.cpp"