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