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