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