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