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