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