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