]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Merge branch 'release/21.08'
[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
699 void KFileItemModel::applyFilters()
700 {
701 // Check which shown items from m_itemData must get
702 // hidden and hence moved to m_filteredItems.
703 QVector<int> newFilteredIndexes;
704
705 const int itemCount = m_itemData.count();
706 for (int index = 0; index < itemCount; ++index) {
707 ItemData* itemData = m_itemData.at(index);
708
709 // Only filter non-expanded items as child items may never
710 // exist without a parent item
711 if (!itemData->values.value("isExpanded").toBool()) {
712 const KFileItem item = itemData->item;
713 if (!m_filter.matches(item)) {
714 newFilteredIndexes.append(index);
715 m_filteredItems.insert(item, itemData);
716 }
717 }
718 }
719
720 const KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
721 removeItems(removedRanges, KeepItemData);
722
723 // Check which hidden items from m_filteredItems should
724 // get visible again and hence removed from m_filteredItems.
725 QList<ItemData*> newVisibleItems;
726
727 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
728 while (it != m_filteredItems.end()) {
729 if (m_filter.matches(it.key())) {
730 newVisibleItems.append(it.value());
731 it = m_filteredItems.erase(it);
732 } else {
733 ++it;
734 }
735 }
736
737 insertItems(newVisibleItems);
738 }
739
740 void KFileItemModel::removeFilteredChildren(const KItemRangeList& itemRanges)
741 {
742 if (m_filteredItems.isEmpty() || !m_requestRole[ExpandedParentsCountRole]) {
743 // There are either no filtered items, or it is not possible to expand
744 // folders -> there cannot be any filtered children.
745 return;
746 }
747
748 QSet<ItemData*> parents;
749 for (const KItemRange& range : itemRanges) {
750 for (int index = range.index; index < range.index + range.count; ++index) {
751 parents.insert(m_itemData.at(index));
752 }
753 }
754
755 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
756 while (it != m_filteredItems.end()) {
757 if (parents.contains(it.value()->parent)) {
758 delete it.value();
759 it = m_filteredItems.erase(it);
760 } else {
761 ++it;
762 }
763 }
764 }
765
766 QList<KFileItemModel::RoleInfo> KFileItemModel::rolesInformation()
767 {
768 static QList<RoleInfo> rolesInfo;
769 if (rolesInfo.isEmpty()) {
770 int count = 0;
771 const RoleInfoMap* map = rolesInfoMap(count);
772 for (int i = 0; i < count; ++i) {
773 if (map[i].roleType != NoRole) {
774 RoleInfo info;
775 info.role = map[i].role;
776 info.translation = i18nc(map[i].roleTranslationContext, map[i].roleTranslation);
777 if (map[i].groupTranslation) {
778 info.group = i18nc(map[i].groupTranslationContext, map[i].groupTranslation);
779 } else {
780 // For top level roles, groupTranslation is 0. We must make sure that
781 // info.group is an empty string then because the code that generates
782 // menus tries to put the actions into sub menus otherwise.
783 info.group = QString();
784 }
785 info.requiresBaloo = map[i].requiresBaloo;
786 info.requiresIndexer = map[i].requiresIndexer;
787 rolesInfo.append(info);
788 }
789 }
790 }
791
792 return rolesInfo;
793 }
794
795 void KFileItemModel::onGroupedSortingChanged(bool current)
796 {
797 Q_UNUSED(current)
798 m_groups.clear();
799 }
800
801 void KFileItemModel::onSortRoleChanged(const QByteArray& current, const QByteArray& previous, bool resortItems)
802 {
803 Q_UNUSED(previous)
804 m_sortRole = typeForRole(current);
805
806 if (!m_requestRole[m_sortRole]) {
807 QSet<QByteArray> newRoles = m_roles;
808 newRoles << current;
809 setRoles(newRoles);
810 }
811
812 if (resortItems) {
813 resortAllItems();
814 }
815 }
816
817 void KFileItemModel::onSortOrderChanged(Qt::SortOrder current, Qt::SortOrder previous)
818 {
819 Q_UNUSED(current)
820 Q_UNUSED(previous)
821 resortAllItems();
822 }
823
824 void KFileItemModel::loadSortingSettings()
825 {
826 using Choice = GeneralSettings::EnumSortingChoice;
827 switch (GeneralSettings::sortingChoice()) {
828 case Choice::NaturalSorting:
829 m_naturalSorting = true;
830 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
831 break;
832 case Choice::CaseSensitiveSorting:
833 m_naturalSorting = false;
834 m_collator.setCaseSensitivity(Qt::CaseSensitive);
835 break;
836 case Choice::CaseInsensitiveSorting:
837 m_naturalSorting = false;
838 m_collator.setCaseSensitivity(Qt::CaseInsensitive);
839 break;
840 default:
841 Q_UNREACHABLE();
842 }
843 // Workaround for bug https://bugreports.qt.io/browse/QTBUG-69361
844 // Force the clean state of QCollator in single thread to avoid thread safety problems in sort
845 m_collator.compare(QString(), QString());
846 }
847
848 void KFileItemModel::resortAllItems()
849 {
850 m_resortAllItemsTimer->stop();
851
852 const int itemCount = count();
853 if (itemCount <= 0) {
854 return;
855 }
856
857 #ifdef KFILEITEMMODEL_DEBUG
858 QElapsedTimer timer;
859 timer.start();
860 qCDebug(DolphinDebug) << "===========================================================";
861 qCDebug(DolphinDebug) << "Resorting" << itemCount << "items";
862 #endif
863
864 // Remember the order of the current URLs so
865 // that it can be determined which indexes have
866 // been moved because of the resorting.
867 QList<QUrl> oldUrls;
868 oldUrls.reserve(itemCount);
869 for (const ItemData* itemData : qAsConst(m_itemData)) {
870 oldUrls.append(itemData->item.url());
871 }
872
873 m_items.clear();
874 m_items.reserve(itemCount);
875
876 // Resort the items
877 sort(m_itemData.begin(), m_itemData.end());
878 for (int i = 0; i < itemCount; ++i) {
879 m_items.insert(m_itemData.at(i)->item.url(), i);
880 }
881
882 // Determine the first index that has been moved.
883 int firstMovedIndex = 0;
884 while (firstMovedIndex < itemCount
885 && firstMovedIndex == m_items.value(oldUrls.at(firstMovedIndex))) {
886 ++firstMovedIndex;
887 }
888
889 const bool itemsHaveMoved = firstMovedIndex < itemCount;
890 if (itemsHaveMoved) {
891 m_groups.clear();
892
893 int lastMovedIndex = itemCount - 1;
894 while (lastMovedIndex > firstMovedIndex
895 && lastMovedIndex == m_items.value(oldUrls.at(lastMovedIndex))) {
896 --lastMovedIndex;
897 }
898
899 Q_ASSERT(firstMovedIndex <= lastMovedIndex);
900
901 // Create a list movedToIndexes, which has the property that
902 // movedToIndexes[i] is the new index of the item with the old index
903 // firstMovedIndex + i.
904 const int movedItemsCount = lastMovedIndex - firstMovedIndex + 1;
905 QList<int> movedToIndexes;
906 movedToIndexes.reserve(movedItemsCount);
907 for (int i = firstMovedIndex; i <= lastMovedIndex; ++i) {
908 const int newIndex = m_items.value(oldUrls.at(i));
909 movedToIndexes.append(newIndex);
910 }
911
912 Q_EMIT itemsMoved(KItemRange(firstMovedIndex, movedItemsCount), movedToIndexes);
913 } else if (groupedSorting()) {
914 // The groups might have changed even if the order of the items has not.
915 const QList<QPair<int, QVariant> > oldGroups = m_groups;
916 m_groups.clear();
917 if (groups() != oldGroups) {
918 Q_EMIT groupsChanged();
919 }
920 }
921
922 #ifdef KFILEITEMMODEL_DEBUG
923 qCDebug(DolphinDebug) << "[TIME] Resorting of" << itemCount << "items:" << timer.elapsed();
924 #endif
925 }
926
927 void KFileItemModel::slotCompleted()
928 {
929 m_maximumUpdateIntervalTimer->stop();
930 dispatchPendingItemsToInsert();
931
932 if (!m_urlsToExpand.isEmpty()) {
933 // Try to find a URL that can be expanded.
934 // Note that the parent folder must be expanded before any of its subfolders become visible.
935 // Therefore, some URLs in m_restoredExpandedUrls might not be visible yet
936 // -> we expand the first visible URL we find in m_restoredExpandedUrls.
937 // Iterate over a const copy because items are deleted and inserted within the loop
938 const auto urlsToExpand = m_urlsToExpand;
939 for(const QUrl &url : urlsToExpand) {
940 const int indexForUrl = index(url);
941 if (indexForUrl >= 0) {
942 m_urlsToExpand.remove(url);
943 if (setExpanded(indexForUrl, true)) {
944 // The dir lister has been triggered. This slot will be called
945 // again after the directory has been expanded.
946 return;
947 }
948 }
949 }
950
951 // None of the URLs in m_restoredExpandedUrls could be found in the model. This can happen
952 // if these URLs have been deleted in the meantime.
953 m_urlsToExpand.clear();
954 }
955
956 Q_EMIT directoryLoadingCompleted();
957 }
958
959 void KFileItemModel::slotCanceled()
960 {
961 m_maximumUpdateIntervalTimer->stop();
962 dispatchPendingItemsToInsert();
963
964 Q_EMIT directoryLoadingCanceled();
965 }
966
967 void KFileItemModel::slotItemsAdded(const QUrl &directoryUrl, const KFileItemList& items)
968 {
969 Q_ASSERT(!items.isEmpty());
970
971 QUrl parentUrl;
972 if (m_expandedDirs.contains(directoryUrl)) {
973 parentUrl = m_expandedDirs.value(directoryUrl);
974 } else {
975 parentUrl = directoryUrl.adjusted(QUrl::StripTrailingSlash);
976 }
977
978 if (m_requestRole[ExpandedParentsCountRole]) {
979 // If the expanding of items is enabled, the call
980 // dirLister->openUrl(url, KDirLister::Keep) in KFileItemModel::setExpanded()
981 // might result in emitting the same items twice due to the Keep-parameter.
982 // This case happens if an item gets expanded, collapsed and expanded again
983 // before the items could be loaded for the first expansion.
984 if (index(items.first().url()) >= 0) {
985 // The items are already part of the model.
986 return;
987 }
988
989 if (directoryUrl != directory()) {
990 // To be able to compare whether the new items may be inserted as children
991 // of a parent item the pending items must be added to the model first.
992 dispatchPendingItemsToInsert();
993 }
994
995 // KDirLister keeps the children of items that got expanded once even if
996 // they got collapsed again with KFileItemModel::setExpanded(false). So it must be
997 // checked whether the parent for new items is still expanded.
998 const int parentIndex = index(parentUrl);
999 if (parentIndex >= 0 && !m_itemData[parentIndex]->values.value("isExpanded").toBool()) {
1000 // The parent is not expanded.
1001 return;
1002 }
1003 }
1004
1005 const QList<ItemData*> itemDataList = createItemDataList(parentUrl, items);
1006
1007 if (!m_filter.hasSetFilters()) {
1008 m_pendingItemsToInsert.append(itemDataList);
1009 } else {
1010 // The name or type filter is active. Hide filtered items
1011 // before inserting them into the model and remember
1012 // the filtered items in m_filteredItems.
1013 for (ItemData* itemData : itemDataList) {
1014 if (m_filter.matches(itemData->item)) {
1015 m_pendingItemsToInsert.append(itemData);
1016 } else {
1017 m_filteredItems.insert(itemData->item, itemData);
1018 }
1019 }
1020 }
1021
1022 if (!m_maximumUpdateIntervalTimer->isActive()) {
1023 // Assure that items get dispatched if no completed() or canceled() signal is
1024 // emitted during the maximum update interval.
1025 m_maximumUpdateIntervalTimer->start();
1026 }
1027
1028 Q_EMIT fileItemsChanged({KFileItem(directoryUrl)});
1029 }
1030
1031 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
1032 {
1033 dispatchPendingItemsToInsert();
1034
1035 QVector<int> indexesToRemove;
1036 indexesToRemove.reserve(items.count());
1037 KFileItemList dirsChanged;
1038
1039 for (const KFileItem& item : items) {
1040 const int indexForItem = index(item);
1041 if (indexForItem >= 0) {
1042 indexesToRemove.append(indexForItem);
1043 } else {
1044 // Probably the item has been filtered.
1045 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(item);
1046 if (it != m_filteredItems.end()) {
1047 delete it.value();
1048 m_filteredItems.erase(it);
1049 }
1050 }
1051
1052 QUrl parentUrl = item.url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
1053 if (dirsChanged.findByUrl(parentUrl).isNull()) {
1054 dirsChanged << KFileItem(parentUrl);
1055 }
1056 }
1057
1058 std::sort(indexesToRemove.begin(), indexesToRemove.end());
1059
1060 if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) {
1061 // Assure that removing a parent item also results in removing all children
1062 QVector<int> indexesToRemoveWithChildren;
1063 indexesToRemoveWithChildren.reserve(m_itemData.count());
1064
1065 const int itemCount = m_itemData.count();
1066 for (int index : qAsConst(indexesToRemove)) {
1067 indexesToRemoveWithChildren.append(index);
1068
1069 const int parentLevel = expandedParentsCount(index);
1070 int childIndex = index + 1;
1071 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
1072 indexesToRemoveWithChildren.append(childIndex);
1073 ++childIndex;
1074 }
1075 }
1076
1077 indexesToRemove = indexesToRemoveWithChildren;
1078 }
1079
1080 const KItemRangeList itemRanges = KItemRangeList::fromSortedContainer(indexesToRemove);
1081 removeFilteredChildren(itemRanges);
1082 removeItems(itemRanges, DeleteItemData);
1083
1084 Q_EMIT fileItemsChanged(dirsChanged);
1085 }
1086
1087 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
1088 {
1089 Q_ASSERT(!items.isEmpty());
1090 #ifdef KFILEITEMMODEL_DEBUG
1091 qCDebug(DolphinDebug) << "Refreshing" << items.count() << "items";
1092 #endif
1093
1094 // Get the indexes of all items that have been refreshed
1095 QList<int> indexes;
1096 indexes.reserve(items.count());
1097
1098 QSet<QByteArray> changedRoles;
1099 KFileItemList changedFiles;
1100
1101 // Contains the indexes of the currently visible items
1102 // that should get hidden and hence moved to m_filteredItems.
1103 QVector<int> newFilteredIndexes;
1104
1105 // Contains currently hidden items that should
1106 // get visible and hence removed from m_filteredItems
1107 QList<ItemData*> newVisibleItems;
1108
1109 QListIterator<QPair<KFileItem, KFileItem> > it(items);
1110 while (it.hasNext()) {
1111 const QPair<KFileItem, KFileItem>& itemPair = it.next();
1112 const KFileItem& oldItem = itemPair.first;
1113 const KFileItem& newItem = itemPair.second;
1114 const int indexForItem = index(oldItem);
1115 const bool newItemMatchesFilter = m_filter.matches(newItem);
1116 if (indexForItem >= 0) {
1117 m_itemData[indexForItem]->item = newItem;
1118
1119 // Keep old values as long as possible if they could not retrieved synchronously yet.
1120 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1121 ItemData * const itemData = m_itemData.at(indexForItem);
1122 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
1123 while (it.hasNext()) {
1124 it.next();
1125 const QByteArray& role = it.key();
1126 if (itemData->values.value(role) != it.value()) {
1127 itemData->values.insert(role, it.value());
1128 changedRoles.insert(role);
1129 }
1130 }
1131
1132 m_items.remove(oldItem.url());
1133 if (newItemMatchesFilter) {
1134 m_items.insert(newItem.url(), indexForItem);
1135 changedFiles.append(newItem);
1136 indexes.append(indexForItem);
1137 } else {
1138 newFilteredIndexes.append(indexForItem);
1139 m_filteredItems.insert(newItem, itemData);
1140 }
1141 } else {
1142 // Check if 'oldItem' is one of the filtered items.
1143 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(oldItem);
1144 if (it != m_filteredItems.end()) {
1145 ItemData* itemData = it.value();
1146 itemData->item = newItem;
1147
1148 // The data stored in 'values' might have changed. Therefore, we clear
1149 // 'values' and re-populate it the next time it is requested via data(int).
1150 itemData->values.clear();
1151
1152 m_filteredItems.erase(it);
1153 if (newItemMatchesFilter) {
1154 newVisibleItems.append(itemData);
1155 } else {
1156 m_filteredItems.insert(newItem, itemData);
1157 }
1158 }
1159 }
1160 }
1161
1162 // Hide items, previously visible that should get hidden
1163 const KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
1164 removeItems(removedRanges, KeepItemData);
1165
1166 // Show previously hidden items that should get visible
1167 insertItems(newVisibleItems);
1168
1169 // If the changed items have been created recently, they might not be in m_items yet.
1170 // In that case, the list 'indexes' might be empty.
1171 if (indexes.isEmpty()) {
1172 return;
1173 }
1174
1175 // Extract the item-ranges out of the changed indexes
1176 std::sort(indexes.begin(), indexes.end());
1177 const KItemRangeList itemRangeList = KItemRangeList::fromSortedContainer(indexes);
1178 emitItemsChangedAndTriggerResorting(itemRangeList, changedRoles);
1179
1180 Q_EMIT fileItemsChanged(changedFiles);
1181 }
1182
1183 void KFileItemModel::slotClear()
1184 {
1185 #ifdef KFILEITEMMODEL_DEBUG
1186 qCDebug(DolphinDebug) << "Clearing all items";
1187 #endif
1188
1189 qDeleteAll(m_filteredItems);
1190 m_filteredItems.clear();
1191 m_groups.clear();
1192
1193 m_maximumUpdateIntervalTimer->stop();
1194 m_resortAllItemsTimer->stop();
1195
1196 qDeleteAll(m_pendingItemsToInsert);
1197 m_pendingItemsToInsert.clear();
1198
1199 const int removedCount = m_itemData.count();
1200 if (removedCount > 0) {
1201 qDeleteAll(m_itemData);
1202 m_itemData.clear();
1203 m_items.clear();
1204 Q_EMIT itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
1205 }
1206
1207 m_expandedDirs.clear();
1208 }
1209
1210 void KFileItemModel::slotSortingChoiceChanged()
1211 {
1212 loadSortingSettings();
1213 resortAllItems();
1214 }
1215
1216 void KFileItemModel::dispatchPendingItemsToInsert()
1217 {
1218 if (!m_pendingItemsToInsert.isEmpty()) {
1219 insertItems(m_pendingItemsToInsert);
1220 m_pendingItemsToInsert.clear();
1221 }
1222 }
1223
1224 void KFileItemModel::insertItems(QList<ItemData*>& newItems)
1225 {
1226 if (newItems.isEmpty()) {
1227 return;
1228 }
1229
1230 #ifdef KFILEITEMMODEL_DEBUG
1231 QElapsedTimer timer;
1232 timer.start();
1233 qCDebug(DolphinDebug) << "===========================================================";
1234 qCDebug(DolphinDebug) << "Inserting" << newItems.count() << "items";
1235 #endif
1236
1237 m_groups.clear();
1238 prepareItemsForSorting(newItems);
1239
1240 // Natural sorting of items can be very slow. However, it becomes much faster
1241 // if the input sequence is already mostly sorted. Therefore, we first sort
1242 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1243 if (m_naturalSorting) {
1244 if (m_sortRole == NameRole) {
1245 parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
1246 } else if (isRoleValueNatural(m_sortRole)) {
1247 auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
1248 {
1249 const QByteArray role = roleForType(m_sortRole);
1250 return a->values.value(role).toString() < b->values.value(role).toString();
1251 };
1252 parallelMergeSort(newItems.begin(), newItems.end(), lambdaLessThan, QThread::idealThreadCount());
1253 }
1254 }
1255
1256 sort(newItems.begin(), newItems.end());
1257
1258 #ifdef KFILEITEMMODEL_DEBUG
1259 qCDebug(DolphinDebug) << "[TIME] Sorting:" << timer.elapsed();
1260 #endif
1261
1262 KItemRangeList itemRanges;
1263 const int existingItemCount = m_itemData.count();
1264 const int newItemCount = newItems.count();
1265 const int totalItemCount = existingItemCount + newItemCount;
1266
1267 if (existingItemCount == 0) {
1268 // Optimization for the common special case that there are no
1269 // items in the model yet. Happens, e.g., when entering a folder.
1270 m_itemData = newItems;
1271 itemRanges << KItemRange(0, newItemCount);
1272 } else {
1273 m_itemData.reserve(totalItemCount);
1274 for (int i = existingItemCount; i < totalItemCount; ++i) {
1275 m_itemData.append(nullptr);
1276 }
1277
1278 // We build the new list m_itemData in reverse order to minimize
1279 // the number of moves and guarantee O(N) complexity.
1280 int targetIndex = totalItemCount - 1;
1281 int sourceIndexExistingItems = existingItemCount - 1;
1282 int sourceIndexNewItems = newItemCount - 1;
1283
1284 int rangeCount = 0;
1285
1286 while (sourceIndexNewItems >= 0) {
1287 ItemData* newItem = newItems.at(sourceIndexNewItems);
1288 if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
1289 // Move an existing item to its new position. If any new items
1290 // are behind it, push the item range to itemRanges.
1291 if (rangeCount > 0) {
1292 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1293 rangeCount = 0;
1294 }
1295
1296 m_itemData[targetIndex] = m_itemData.at(sourceIndexExistingItems);
1297 --sourceIndexExistingItems;
1298 } else {
1299 // Insert a new item into the list.
1300 ++rangeCount;
1301 m_itemData[targetIndex] = newItem;
1302 --sourceIndexNewItems;
1303 }
1304 --targetIndex;
1305 }
1306
1307 // Push the final item range to itemRanges.
1308 if (rangeCount > 0) {
1309 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1310 }
1311
1312 // Note that itemRanges is still sorted in reverse order.
1313 std::reverse(itemRanges.begin(), itemRanges.end());
1314 }
1315
1316 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1317 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1318 m_items.clear();
1319
1320 Q_EMIT itemsInserted(itemRanges);
1321
1322 #ifdef KFILEITEMMODEL_DEBUG
1323 qCDebug(DolphinDebug) << "[TIME] Inserting of" << newItems.count() << "items:" << timer.elapsed();
1324 #endif
1325 }
1326
1327 void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior)
1328 {
1329 if (itemRanges.isEmpty()) {
1330 return;
1331 }
1332
1333 m_groups.clear();
1334
1335 // Step 1: Remove the items from m_itemData, and free the ItemData.
1336 int removedItemsCount = 0;
1337 for (const KItemRange& range : itemRanges) {
1338 removedItemsCount += range.count;
1339
1340 for (int index = range.index; index < range.index + range.count; ++index) {
1341 if (behavior == DeleteItemData) {
1342 delete m_itemData.at(index);
1343 }
1344
1345 m_itemData[index] = nullptr;
1346 }
1347 }
1348
1349 // Step 2: Remove the ItemData pointers from the list m_itemData.
1350 int target = itemRanges.at(0).index;
1351 int source = itemRanges.at(0).index + itemRanges.at(0).count;
1352 int nextRange = 1;
1353
1354 const int oldItemDataCount = m_itemData.count();
1355 while (source < oldItemDataCount) {
1356 m_itemData[target] = m_itemData[source];
1357 ++target;
1358 ++source;
1359
1360 if (nextRange < itemRanges.count() && source == itemRanges.at(nextRange).index) {
1361 // Skip the items in the next removed range.
1362 source += itemRanges.at(nextRange).count;
1363 ++nextRange;
1364 }
1365 }
1366
1367 m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end());
1368
1369 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1370 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1371 m_items.clear();
1372
1373 Q_EMIT itemsRemoved(itemRanges);
1374 }
1375
1376 QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const
1377 {
1378 if (m_sortRole == TypeRole) {
1379 // Try to resolve the MIME-types synchronously to prevent a reordering of
1380 // the items when sorting by type (per default MIME-types are resolved
1381 // asynchronously by KFileItemModelRolesUpdater).
1382 determineMimeTypes(items, 200);
1383 }
1384
1385 const int parentIndex = index(parentUrl);
1386 ItemData* parentItem = parentIndex < 0 ? nullptr : m_itemData.at(parentIndex);
1387
1388 QList<ItemData*> itemDataList;
1389 itemDataList.reserve(items.count());
1390
1391 for (const KFileItem& item : items) {
1392 ItemData* itemData = new ItemData();
1393 itemData->item = item;
1394 itemData->parent = parentItem;
1395 itemDataList.append(itemData);
1396 }
1397
1398 return itemDataList;
1399 }
1400
1401 void KFileItemModel::prepareItemsForSorting(QList<ItemData*>& itemDataList)
1402 {
1403 switch (m_sortRole) {
1404 case PermissionsRole:
1405 case OwnerRole:
1406 case GroupRole:
1407 case DestinationRole:
1408 case PathRole:
1409 case DeletionTimeRole:
1410 // These roles can be determined with retrieveData, and they have to be stored
1411 // in the QHash "values" for the sorting.
1412 for (ItemData* itemData : qAsConst(itemDataList)) {
1413 if (itemData->values.isEmpty()) {
1414 itemData->values = retrieveData(itemData->item, itemData->parent);
1415 }
1416 }
1417 break;
1418
1419 case TypeRole:
1420 // At least store the data including the file type for items with known MIME type.
1421 for (ItemData* itemData : qAsConst(itemDataList)) {
1422 if (itemData->values.isEmpty()) {
1423 const KFileItem item = itemData->item;
1424 if (item.isDir() || item.isMimeTypeKnown()) {
1425 itemData->values = retrieveData(itemData->item, itemData->parent);
1426 }
1427 }
1428 }
1429 break;
1430
1431 default:
1432 // The other roles are either resolved by KFileItemModelRolesUpdater
1433 // (this includes the SizeRole for directories), or they do not need
1434 // to be stored in the QHash "values" for sorting because the data can
1435 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1436 // DateRole).
1437 break;
1438 }
1439 }
1440
1441 int KFileItemModel::expandedParentsCount(const ItemData* data)
1442 {
1443 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1444 // if the corresponding item is expanded, and it is not a top-level item.
1445 const ItemData* parent = data->parent;
1446 if (parent) {
1447 if (parent->parent) {
1448 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1449 return parent->values.value("expandedParentsCount").toInt() + 1;
1450 } else {
1451 return 1;
1452 }
1453 } else {
1454 return 0;
1455 }
1456 }
1457
1458 void KFileItemModel::removeExpandedItems()
1459 {
1460 QVector<int> indexesToRemove;
1461
1462 const int maxIndex = m_itemData.count() - 1;
1463 for (int i = 0; i <= maxIndex; ++i) {
1464 const ItemData* itemData = m_itemData.at(i);
1465 if (itemData->parent) {
1466 indexesToRemove.append(i);
1467 }
1468 }
1469
1470 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1471 m_expandedDirs.clear();
1472
1473 // Also remove all filtered items which have a parent.
1474 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
1475 const QHash<KFileItem, ItemData*>::iterator end = m_filteredItems.end();
1476
1477 while (it != end) {
1478 if (it.value()->parent) {
1479 delete it.value();
1480 it = m_filteredItems.erase(it);
1481 } else {
1482 ++it;
1483 }
1484 }
1485 }
1486
1487 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles)
1488 {
1489 Q_EMIT itemsChanged(itemRanges, changedRoles);
1490
1491 // Trigger a resorting if necessary. Note that this can happen even if the sort
1492 // role has not changed at all because the file name can be used as a fallback.
1493 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) {
1494 for (const KItemRange& range : itemRanges) {
1495 bool needsResorting = false;
1496
1497 const int first = range.index;
1498 const int last = range.index + range.count - 1;
1499
1500 // Resorting the model is necessary if
1501 // (a) The first item in the range is "lessThan" its predecessor,
1502 // (b) the successor of the last item is "lessThan" the last item, or
1503 // (c) the internal order of the items in the range is incorrect.
1504 if (first > 0
1505 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1506 needsResorting = true;
1507 } else if (last < count() - 1
1508 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1509 needsResorting = true;
1510 } else {
1511 for (int index = first; index < last; ++index) {
1512 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1513 needsResorting = true;
1514 break;
1515 }
1516 }
1517 }
1518
1519 if (needsResorting) {
1520 m_resortAllItemsTimer->start();
1521 return;
1522 }
1523 }
1524 }
1525
1526 if (groupedSorting() && changedRoles.contains(sortRole())) {
1527 // The position is still correct, but the groups might have changed
1528 // if the changed item is either the first or the last item in a
1529 // group.
1530 // In principle, we could try to find out if the item really is the
1531 // first or last one in its group and then update the groups
1532 // (possibly with a delayed timer to make sure that we don't
1533 // re-calculate the groups very often if items are updated one by
1534 // one), but starting m_resortAllItemsTimer is easier.
1535 m_resortAllItemsTimer->start();
1536 }
1537 }
1538
1539 void KFileItemModel::resetRoles()
1540 {
1541 for (int i = 0; i < RolesCount; ++i) {
1542 m_requestRole[i] = false;
1543 }
1544 }
1545
1546 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const
1547 {
1548 static QHash<QByteArray, RoleType> roles;
1549 if (roles.isEmpty()) {
1550 // Insert user visible roles that can be accessed with
1551 // KFileItemModel::roleInformation()
1552 int count = 0;
1553 const RoleInfoMap* map = rolesInfoMap(count);
1554 for (int i = 0; i < count; ++i) {
1555 roles.insert(map[i].role, map[i].roleType);
1556 }
1557
1558 // Insert internal roles (take care to synchronize the implementation
1559 // with KFileItemModel::roleForType() in case if a change is done).
1560 roles.insert("isDir", IsDirRole);
1561 roles.insert("isLink", IsLinkRole);
1562 roles.insert("isHidden", IsHiddenRole);
1563 roles.insert("isExpanded", IsExpandedRole);
1564 roles.insert("isExpandable", IsExpandableRole);
1565 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1566
1567 Q_ASSERT(roles.count() == RolesCount);
1568 }
1569
1570 return roles.value(role, NoRole);
1571 }
1572
1573 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1574 {
1575 static QHash<RoleType, QByteArray> roles;
1576 if (roles.isEmpty()) {
1577 // Insert user visible roles that can be accessed with
1578 // KFileItemModel::roleInformation()
1579 int count = 0;
1580 const RoleInfoMap* map = rolesInfoMap(count);
1581 for (int i = 0; i < count; ++i) {
1582 roles.insert(map[i].roleType, map[i].role);
1583 }
1584
1585 // Insert internal roles (take care to synchronize the implementation
1586 // with KFileItemModel::typeForRole() in case if a change is done).
1587 roles.insert(IsDirRole, "isDir");
1588 roles.insert(IsLinkRole, "isLink");
1589 roles.insert(IsHiddenRole, "isHidden");
1590 roles.insert(IsExpandedRole, "isExpanded");
1591 roles.insert(IsExpandableRole, "isExpandable");
1592 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1593
1594 Q_ASSERT(roles.count() == RolesCount);
1595 };
1596
1597 return roles.value(roleType);
1598 }
1599
1600 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item, const ItemData* parent) const
1601 {
1602 // It is important to insert only roles that are fast to retrieve. E.g.
1603 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1604 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1605 QHash<QByteArray, QVariant> data;
1606 data.insert(sharedValue("url"), item.url());
1607
1608 const bool isDir = item.isDir();
1609 if (m_requestRole[IsDirRole] && isDir) {
1610 data.insert(sharedValue("isDir"), true);
1611 }
1612
1613 if (m_requestRole[IsLinkRole] && item.isLink()) {
1614 data.insert(sharedValue("isLink"), true);
1615 }
1616
1617 if (m_requestRole[IsHiddenRole]) {
1618 data.insert(sharedValue("isHidden"), item.isHidden());
1619 }
1620
1621 if (m_requestRole[NameRole]) {
1622 data.insert(sharedValue("text"), item.text());
1623 }
1624
1625 if (m_requestRole[SizeRole] && !isDir) {
1626 data.insert(sharedValue("size"), item.size());
1627 }
1628
1629 if (m_requestRole[ModificationTimeRole]) {
1630 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1631 // having several thousands of items. Instead read the raw number from UDSEntry directly
1632 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1633 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1634 data.insert(sharedValue("modificationtime"), dateTime);
1635 }
1636
1637 if (m_requestRole[CreationTimeRole]) {
1638 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1639 // having several thousands of items. Instead read the raw number from UDSEntry directly
1640 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1641 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1642 data.insert(sharedValue("creationtime"), dateTime);
1643 }
1644
1645 if (m_requestRole[AccessTimeRole]) {
1646 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1647 // having several thousands of items. Instead read the raw number from UDSEntry directly
1648 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1649 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1650 data.insert(sharedValue("accesstime"), dateTime);
1651 }
1652
1653 if (m_requestRole[PermissionsRole]) {
1654 data.insert(sharedValue("permissions"), item.permissionsString());
1655 }
1656
1657 if (m_requestRole[OwnerRole]) {
1658 data.insert(sharedValue("owner"), item.user());
1659 }
1660
1661 if (m_requestRole[GroupRole]) {
1662 data.insert(sharedValue("group"), item.group());
1663 }
1664
1665 if (m_requestRole[DestinationRole]) {
1666 QString destination = item.linkDest();
1667 if (destination.isEmpty()) {
1668 destination = QLatin1Char('-');
1669 }
1670 data.insert(sharedValue("destination"), destination);
1671 }
1672
1673 if (m_requestRole[PathRole]) {
1674 QString path;
1675 if (item.url().scheme() == QLatin1String("trash")) {
1676 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1677 } else {
1678 // For performance reasons cache the home-path in a static QString
1679 // (see QDir::homePath() for more details)
1680 static QString homePath;
1681 if (homePath.isEmpty()) {
1682 homePath = QDir::homePath();
1683 }
1684
1685 path = item.localPath();
1686 if (path.startsWith(homePath)) {
1687 path.replace(0, homePath.length(), QLatin1Char('~'));
1688 }
1689 }
1690
1691 const int index = path.lastIndexOf(item.text());
1692 path = path.mid(0, index - 1);
1693 data.insert(sharedValue("path"), path);
1694 }
1695
1696 if (m_requestRole[DeletionTimeRole]) {
1697 QDateTime deletionTime;
1698 if (item.url().scheme() == QLatin1String("trash")) {
1699 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
1700 }
1701 data.insert(sharedValue("deletiontime"), deletionTime);
1702 }
1703
1704 if (m_requestRole[IsExpandableRole] && isDir) {
1705 data.insert(sharedValue("isExpandable"), true);
1706 }
1707
1708 if (m_requestRole[ExpandedParentsCountRole]) {
1709 if (parent) {
1710 const int level = expandedParentsCount(parent) + 1;
1711 data.insert(sharedValue("expandedParentsCount"), level);
1712 }
1713 }
1714
1715 if (item.isMimeTypeKnown()) {
1716 QString iconName = item.iconName();
1717 if (!QIcon::hasThemeIcon(iconName)) {
1718 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
1719 iconName = mimeType.genericIconName();
1720 }
1721
1722 data.insert(sharedValue("iconName"), iconName);
1723
1724 if (m_requestRole[TypeRole]) {
1725 data.insert(sharedValue("type"), item.mimeComment());
1726 }
1727 } else if (m_requestRole[TypeRole] && isDir) {
1728 static const QString folderMimeType = item.mimeComment();
1729 data.insert(sharedValue("type"), folderMimeType);
1730 }
1731
1732 return data;
1733 }
1734
1735 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const
1736 {
1737 int result = 0;
1738
1739 if (a->parent != b->parent) {
1740 const int expansionLevelA = expandedParentsCount(a);
1741 const int expansionLevelB = expandedParentsCount(b);
1742
1743 // If b has a higher expansion level than a, check if a is a parent
1744 // of b, and make sure that both expansion levels are equal otherwise.
1745 for (int i = expansionLevelB; i > expansionLevelA; --i) {
1746 if (b->parent == a) {
1747 return true;
1748 }
1749 b = b->parent;
1750 }
1751
1752 // If a has a higher expansion level than a, check if b is a parent
1753 // of a, and make sure that both expansion levels are equal otherwise.
1754 for (int i = expansionLevelA; i > expansionLevelB; --i) {
1755 if (a->parent == b) {
1756 return false;
1757 }
1758 a = a->parent;
1759 }
1760
1761 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
1762
1763 // Compare the last parents of a and b which are different.
1764 while (a->parent != b->parent) {
1765 a = a->parent;
1766 b = b->parent;
1767 }
1768 }
1769
1770 // Show hidden files and folders last
1771 if (m_sortHiddenLast) {
1772 const bool isHiddenA = a->item.isHidden();
1773 const bool isHiddenB = b->item.isHidden();
1774 if (isHiddenA && !isHiddenB) {
1775 return false;
1776 } else if (!isHiddenA && isHiddenB) {
1777 return true;
1778 }
1779 }
1780
1781 if (m_sortDirsFirst || (DetailsModeSettings::directorySizeCount() && m_sortRole == SizeRole)) {
1782 const bool isDirA = a->item.isDir();
1783 const bool isDirB = b->item.isDir();
1784 if (isDirA && !isDirB) {
1785 return true;
1786 } else if (!isDirA && isDirB) {
1787 return false;
1788 }
1789 }
1790
1791 result = sortRoleCompare(a, b, collator);
1792
1793 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1794 }
1795
1796 void KFileItemModel::sort(const QList<KFileItemModel::ItemData*>::iterator &begin,
1797 const QList<KFileItemModel::ItemData*>::iterator &end) const
1798 {
1799 auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
1800 {
1801 return lessThan(a, b, m_collator);
1802 };
1803
1804 if (m_sortRole == NameRole || isRoleValueNatural(m_sortRole)) {
1805 // Sorting by string can be expensive, in particular if natural sorting is
1806 // enabled. Use all CPU cores to speed up the sorting process.
1807 static const int numberOfThreads = QThread::idealThreadCount();
1808 parallelMergeSort(begin, end, lambdaLessThan, numberOfThreads);
1809 } else {
1810 // Sorting by other roles is quite fast. Use only one thread to prevent
1811 // problems caused by non-reentrant comparison functions, see
1812 // https://bugs.kde.org/show_bug.cgi?id=312679
1813 mergeSort(begin, end, lambdaLessThan);
1814 }
1815 }
1816
1817 int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const
1818 {
1819 // This function must never return 0, because that would break stable
1820 // sorting, which leads to all kinds of bugs.
1821 // See: https://bugs.kde.org/show_bug.cgi?id=433247
1822 // If two items have equal sort values, let the fallbacks at the bottom of
1823 // the function handle it.
1824 const KFileItem& itemA = a->item;
1825 const KFileItem& itemB = b->item;
1826
1827 int result = 0;
1828
1829 switch (m_sortRole) {
1830 case NameRole:
1831 // The name role is handled as default fallback after the switch
1832 break;
1833
1834 case SizeRole: {
1835 if (DetailsModeSettings::directorySizeCount() && itemA.isDir()) {
1836 // folders first then
1837 // items A and B are folders thanks to lessThan checks
1838 auto valueA = a->values.value("count");
1839 auto valueB = b->values.value("count");
1840 if (valueA.isNull()) {
1841 if (!valueB.isNull()) {
1842 return -1;
1843 }
1844 } else if (valueB.isNull()) {
1845 return +1;
1846 } else {
1847 if (valueA.toLongLong() < valueB.toLongLong()) {
1848 return -1;
1849 } else if (valueA.toLongLong() > valueB.toLongLong()) {
1850 return +1;
1851 }
1852 }
1853 break;
1854 }
1855
1856 KIO::filesize_t sizeA = 0;
1857 if (itemA.isDir()) {
1858 sizeA = a->values.value("size").toULongLong();
1859 } else {
1860 sizeA = itemA.size();
1861 }
1862 KIO::filesize_t sizeB = 0;
1863 if (itemB.isDir()) {
1864 sizeB = b->values.value("size").toULongLong();
1865 } else {
1866 sizeB = itemB.size();
1867 }
1868 if (sizeA < sizeB) {
1869 return -1;
1870 } else if (sizeA > sizeB) {
1871 return +1;
1872 }
1873 break;
1874 }
1875
1876 case ModificationTimeRole: {
1877 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1878 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1879 if (dateTimeA < dateTimeB) {
1880 return -1;
1881 } else if (dateTimeA > dateTimeB) {
1882 return +1;
1883 }
1884 break;
1885 }
1886
1887 case CreationTimeRole: {
1888 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1889 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1890 if (dateTimeA < dateTimeB) {
1891 return -1;
1892 } else if (dateTimeA > dateTimeB) {
1893 return +1;
1894 }
1895 break;
1896 }
1897
1898 case DeletionTimeRole: {
1899 const QDateTime dateTimeA = a->values.value("deletiontime").toDateTime();
1900 const QDateTime dateTimeB = b->values.value("deletiontime").toDateTime();
1901 if (dateTimeA < dateTimeB) {
1902 return -1;
1903 } else if (dateTimeA > dateTimeB) {
1904 return +1;
1905 }
1906 break;
1907 }
1908
1909 case RatingRole:
1910 case WidthRole:
1911 case HeightRole:
1912 case WordCountRole:
1913 case LineCountRole:
1914 case TrackRole:
1915 case ReleaseYearRole: {
1916 result = a->values.value(roleForType(m_sortRole)).toInt() - b->values.value(roleForType(m_sortRole)).toInt();
1917 break;
1918 }
1919
1920 default: {
1921 const QByteArray role = roleForType(m_sortRole);
1922 const QString roleValueA = a->values.value(role).toString();
1923 const QString roleValueB = b->values.value(role).toString();
1924 if (!roleValueA.isEmpty() && roleValueB.isEmpty()) {
1925 return -1;
1926 } else if (roleValueA.isEmpty() && !roleValueB.isEmpty()) {
1927 return +1;
1928 } else if (isRoleValueNatural(m_sortRole)) {
1929 result = stringCompare(roleValueA, roleValueB, collator);
1930 } else {
1931 result = QString::compare(roleValueA, roleValueB);
1932 }
1933 break;
1934 }
1935
1936 }
1937
1938 if (result != 0) {
1939 // The current sort role was sufficient to define an order
1940 return result;
1941 }
1942
1943 // Fallback #1: Compare the text of the items
1944 result = stringCompare(itemA.text(), itemB.text(), collator);
1945 if (result != 0) {
1946 return result;
1947 }
1948
1949 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
1950 result = stringCompare(itemA.name(), itemB.name(), collator);
1951 if (result != 0) {
1952 return result;
1953 }
1954
1955 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
1956 // equal. In this case a comparison of the URL is done which is unique in all cases
1957 // within KDirLister.
1958 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
1959 }
1960
1961 int KFileItemModel::stringCompare(const QString& a, const QString& b, const QCollator& collator) const
1962 {
1963 QMutexLocker collatorLock(s_collatorMutex());
1964
1965 if (m_naturalSorting) {
1966 return collator.compare(a, b);
1967 }
1968
1969 const int result = QString::compare(a, b, collator.caseSensitivity());
1970 if (result != 0 || collator.caseSensitivity() == Qt::CaseSensitive) {
1971 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
1972 // comparison, still a deterministic sort order is required. A case sensitive
1973 // comparison is done as fallback.
1974 return result;
1975 }
1976
1977 return QString::compare(a, b, Qt::CaseSensitive);
1978 }
1979
1980 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
1981 {
1982 Q_ASSERT(!m_itemData.isEmpty());
1983
1984 const int maxIndex = count() - 1;
1985 QList<QPair<int, QVariant> > groups;
1986
1987 QString groupValue;
1988 QChar firstChar;
1989 for (int i = 0; i <= maxIndex; ++i) {
1990 if (isChildItem(i)) {
1991 continue;
1992 }
1993
1994 const QString name = m_itemData.at(i)->item.text();
1995
1996 // Use the first character of the name as group indication
1997 QChar newFirstChar = name.at(0).toUpper();
1998 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
1999 newFirstChar = name.at(1).toUpper();
2000 }
2001
2002 if (firstChar != newFirstChar) {
2003 QString newGroupValue;
2004 if (newFirstChar.isLetter()) {
2005
2006 if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) {
2007 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2008
2009 // Try to find a matching group in the range 'A' to 'Z'.
2010 static std::vector<QChar> lettersAtoZ;
2011 lettersAtoZ.reserve('Z' - 'A' + 1);
2012 if (lettersAtoZ.empty()) {
2013 for (char c = 'A'; c <= 'Z'; ++c) {
2014 lettersAtoZ.push_back(QLatin1Char(c));
2015 }
2016 }
2017
2018 auto localeAwareLessThan = [this](QChar c1, QChar c2) -> bool {
2019 return m_collator.compare(c1, c2) < 0;
2020 };
2021
2022 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), newFirstChar, localeAwareLessThan);
2023 if (it != lettersAtoZ.end()) {
2024 if (localeAwareLessThan(newFirstChar, *it)) {
2025 // newFirstChar belongs to the group preceding *it.
2026 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2027 --it;
2028 }
2029 newGroupValue = *it;
2030 }
2031
2032 } else {
2033 // Symbols from non Latin-based scripts
2034 newGroupValue = newFirstChar;
2035 }
2036 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
2037 // Apply group '0 - 9' for any name that starts with a digit
2038 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
2039 } else {
2040 newGroupValue = i18nc("@title:group", "Others");
2041 }
2042
2043 if (newGroupValue != groupValue) {
2044 groupValue = newGroupValue;
2045 groups.append(QPair<int, QVariant>(i, newGroupValue));
2046 }
2047
2048 firstChar = newFirstChar;
2049 }
2050 }
2051 return groups;
2052 }
2053
2054 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
2055 {
2056 Q_ASSERT(!m_itemData.isEmpty());
2057
2058 const int maxIndex = count() - 1;
2059 QList<QPair<int, QVariant> > groups;
2060
2061 QString groupValue;
2062 for (int i = 0; i <= maxIndex; ++i) {
2063 if (isChildItem(i)) {
2064 continue;
2065 }
2066
2067 const KFileItem& item = m_itemData.at(i)->item;
2068 KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
2069 QString newGroupValue;
2070 if (!item.isNull() && item.isDir()) {
2071 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst) {
2072 newGroupValue = i18nc("@title:group Size", "Folders");
2073 } else {
2074 fileSize = m_itemData.at(i)->values.value("size").toULongLong();
2075 }
2076 }
2077
2078 if (newGroupValue.isEmpty()) {
2079 if (fileSize < 5 * 1024 * 1024) { // < 5 MB
2080 newGroupValue = i18nc("@title:group Size", "Small");
2081 } else if (fileSize < 10 * 1024 * 1024) { // < 10 MB
2082 newGroupValue = i18nc("@title:group Size", "Medium");
2083 } else {
2084 newGroupValue = i18nc("@title:group Size", "Big");
2085 }
2086 }
2087
2088 if (newGroupValue != groupValue) {
2089 groupValue = newGroupValue;
2090 groups.append(QPair<int, QVariant>(i, newGroupValue));
2091 }
2092 }
2093
2094 return groups;
2095 }
2096
2097 QList<QPair<int, QVariant> > KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
2098 {
2099 Q_ASSERT(!m_itemData.isEmpty());
2100
2101 const int maxIndex = count() - 1;
2102 QList<QPair<int, QVariant> > groups;
2103
2104 const QDate currentDate = QDate::currentDate();
2105
2106 QDate previousFileDate;
2107 QString groupValue;
2108 for (int i = 0; i <= maxIndex; ++i) {
2109 if (isChildItem(i)) {
2110 continue;
2111 }
2112
2113 const QDateTime fileTime = fileTimeCb(m_itemData.at(i));
2114 const QDate fileDate = fileTime.date();
2115 if (fileDate == previousFileDate) {
2116 // The current item is in the same group as the previous item
2117 continue;
2118 }
2119 previousFileDate = fileDate;
2120
2121 const int daysDistance = fileDate.daysTo(currentDate);
2122
2123 QString newGroupValue;
2124 if (currentDate.year() == fileDate.year() &&
2125 currentDate.month() == fileDate.month()) {
2126
2127 switch (daysDistance / 7) {
2128 case 0:
2129 switch (daysDistance) {
2130 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
2131 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
2132 default:
2133 newGroupValue = fileTime.toString(
2134 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2135 newGroupValue = i18nc("Can be used to script translation of \"dddd\""
2136 "with context @title:group Date", "%1", newGroupValue);
2137 }
2138 break;
2139 case 1:
2140 newGroupValue = i18nc("@title:group Date", "One Week Ago");
2141 break;
2142 case 2:
2143 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
2144 break;
2145 case 3:
2146 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
2147 break;
2148 case 4:
2149 case 5:
2150 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
2151 break;
2152 default:
2153 Q_ASSERT(false);
2154 }
2155 } else {
2156 const QDate lastMonthDate = currentDate.addMonths(-1);
2157 if (lastMonthDate.year() == fileDate.year() &&
2158 lastMonthDate.month() == fileDate.month()) {
2159
2160 if (daysDistance == 1) {
2161 const KLocalizedString format = ki18nc("@title:group Date: "
2162 "MMMM is full month name in current locale, and yyyy is "
2163 "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)");
2164 const QString translatedFormat = format.toString();
2165 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2166 newGroupValue = fileTime.toString(translatedFormat);
2167 newGroupValue = i18nc("Can be used to script translation of "
2168 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2169 "%1", newGroupValue);
2170 } else {
2171 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2172 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2173 newGroupValue = fileTime.toString(untranslatedFormat);
2174 }
2175 } else if (daysDistance <= 7) {
2176 newGroupValue = fileTime.toString(i18nc("@title:group Date: "
2177 "The week day name: dddd, MMMM is full month name "
2178 "in current locale, and yyyy is full year number.",
2179 "dddd (MMMM, yyyy)"));
2180 newGroupValue = i18nc("Can be used to script translation of "
2181 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2182 "%1", newGroupValue);
2183 } else if (daysDistance <= 7 * 2) {
2184 const KLocalizedString format = ki18nc("@title:group Date: "
2185 "MMMM is full month name in current locale, and yyyy is "
2186 "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)");
2187 const QString translatedFormat = format.toString();
2188 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2189 newGroupValue = fileTime.toString(translatedFormat);
2190 newGroupValue = i18nc("Can be used to script translation of "
2191 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2192 "%1", newGroupValue);
2193 } else {
2194 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2195 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2196 newGroupValue = fileTime.toString(untranslatedFormat);
2197 }
2198 } else if (daysDistance <= 7 * 3) {
2199 const KLocalizedString format = ki18nc("@title:group Date: "
2200 "MMMM is full month name in current locale, and yyyy is "
2201 "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)");
2202 const QString translatedFormat = format.toString();
2203 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2204 newGroupValue = fileTime.toString(translatedFormat);
2205 newGroupValue = i18nc("Can be used to script translation of "
2206 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2207 "%1", newGroupValue);
2208 } else {
2209 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2210 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2211 newGroupValue = fileTime.toString(untranslatedFormat);
2212 }
2213 } else if (daysDistance <= 7 * 4) {
2214 const KLocalizedString format = ki18nc("@title:group Date: "
2215 "MMMM is full month name in current locale, and yyyy is "
2216 "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)");
2217 const QString translatedFormat = format.toString();
2218 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2219 newGroupValue = fileTime.toString(translatedFormat);
2220 newGroupValue = i18nc("Can be used to script translation of "
2221 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2222 "%1", newGroupValue);
2223 } else {
2224 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2225 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2226 newGroupValue = fileTime.toString(untranslatedFormat);
2227 }
2228 } else {
2229 const KLocalizedString format = ki18nc("@title:group Date: "
2230 "MMMM is full month name in current locale, and yyyy is "
2231 "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");
2232 const QString translatedFormat = format.toString();
2233 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2234 newGroupValue = fileTime.toString(translatedFormat);
2235 newGroupValue = i18nc("Can be used to script translation of "
2236 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2237 "%1", newGroupValue);
2238 } else {
2239 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2240 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2241 newGroupValue = fileTime.toString(untranslatedFormat);
2242 }
2243 }
2244 } else {
2245 newGroupValue = fileTime.toString(i18nc("@title:group "
2246 "The month and year: MMMM is full month name in current locale, "
2247 "and yyyy is full year number", "MMMM, yyyy"));
2248 newGroupValue = i18nc("Can be used to script translation of "
2249 "\"MMMM, yyyy\" with context @title:group Date",
2250 "%1", newGroupValue);
2251 }
2252 }
2253
2254 if (newGroupValue != groupValue) {
2255 groupValue = newGroupValue;
2256 groups.append(QPair<int, QVariant>(i, newGroupValue));
2257 }
2258 }
2259
2260 return groups;
2261 }
2262
2263 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
2264 {
2265 Q_ASSERT(!m_itemData.isEmpty());
2266
2267 const int maxIndex = count() - 1;
2268 QList<QPair<int, QVariant> > groups;
2269
2270 QString permissionsString;
2271 QString groupValue;
2272 for (int i = 0; i <= maxIndex; ++i) {
2273 if (isChildItem(i)) {
2274 continue;
2275 }
2276
2277 const ItemData* itemData = m_itemData.at(i);
2278 const QString newPermissionsString = itemData->values.value("permissions").toString();
2279 if (newPermissionsString == permissionsString) {
2280 continue;
2281 }
2282 permissionsString = newPermissionsString;
2283
2284 const QFileInfo info(itemData->item.url().toLocalFile());
2285
2286 // Set user string
2287 QString user;
2288 if (info.permission(QFile::ReadUser)) {
2289 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
2290 }
2291 if (info.permission(QFile::WriteUser)) {
2292 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
2293 }
2294 if (info.permission(QFile::ExeUser)) {
2295 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2296 }
2297 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
2298
2299 // Set group string
2300 QString group;
2301 if (info.permission(QFile::ReadGroup)) {
2302 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
2303 }
2304 if (info.permission(QFile::WriteGroup)) {
2305 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
2306 }
2307 if (info.permission(QFile::ExeGroup)) {
2308 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2309 }
2310 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
2311
2312 // Set others string
2313 QString others;
2314 if (info.permission(QFile::ReadOther)) {
2315 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
2316 }
2317 if (info.permission(QFile::WriteOther)) {
2318 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
2319 }
2320 if (info.permission(QFile::ExeOther)) {
2321 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2322 }
2323 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
2324
2325 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
2326 if (newGroupValue != groupValue) {
2327 groupValue = newGroupValue;
2328 groups.append(QPair<int, QVariant>(i, newGroupValue));
2329 }
2330 }
2331
2332 return groups;
2333 }
2334
2335 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
2336 {
2337 Q_ASSERT(!m_itemData.isEmpty());
2338
2339 const int maxIndex = count() - 1;
2340 QList<QPair<int, QVariant> > groups;
2341
2342 int groupValue = -1;
2343 for (int i = 0; i <= maxIndex; ++i) {
2344 if (isChildItem(i)) {
2345 continue;
2346 }
2347 const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt();
2348 if (newGroupValue != groupValue) {
2349 groupValue = newGroupValue;
2350 groups.append(QPair<int, QVariant>(i, newGroupValue));
2351 }
2352 }
2353
2354 return groups;
2355 }
2356
2357 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
2358 {
2359 Q_ASSERT(!m_itemData.isEmpty());
2360
2361 const int maxIndex = count() - 1;
2362 QList<QPair<int, QVariant> > groups;
2363
2364 bool isFirstGroupValue = true;
2365 QString groupValue;
2366 for (int i = 0; i <= maxIndex; ++i) {
2367 if (isChildItem(i)) {
2368 continue;
2369 }
2370 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
2371 if (newGroupValue != groupValue || isFirstGroupValue) {
2372 groupValue = newGroupValue;
2373 groups.append(QPair<int, QVariant>(i, newGroupValue));
2374 isFirstGroupValue = false;
2375 }
2376 }
2377
2378 return groups;
2379 }
2380
2381 void KFileItemModel::emitSortProgress(int resolvedCount)
2382 {
2383 // Be tolerant against a resolvedCount with a wrong range.
2384 // Although there should not be a case where KFileItemModelRolesUpdater
2385 // (= caller) provides a wrong range, it is important to emit
2386 // a useful progress information even if there is an unexpected
2387 // implementation issue.
2388
2389 const int itemCount = count();
2390 if (resolvedCount >= itemCount) {
2391 m_sortingProgressPercent = -1;
2392 if (m_resortAllItemsTimer->isActive()) {
2393 m_resortAllItemsTimer->stop();
2394 resortAllItems();
2395 }
2396
2397 Q_EMIT directorySortingProgress(100);
2398 } else if (itemCount > 0) {
2399 resolvedCount = qBound(0, resolvedCount, itemCount);
2400
2401 const int progress = resolvedCount * 100 / itemCount;
2402 if (m_sortingProgressPercent != progress) {
2403 m_sortingProgressPercent = progress;
2404 Q_EMIT directorySortingProgress(progress);
2405 }
2406 }
2407 }
2408
2409 const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count)
2410 {
2411 static const RoleInfoMap rolesInfoMap[] = {
2412 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2413 { nullptr, NoRole, nullptr, nullptr, nullptr, nullptr, false, false },
2414 { "text", NameRole, I18NC_NOOP("@label", "Name"), nullptr, nullptr, false, false },
2415 { "size", SizeRole, I18NC_NOOP("@label", "Size"), nullptr, nullptr, false, false },
2416 { "modificationtime", ModificationTimeRole, I18NC_NOOP("@label", "Modified"), nullptr, nullptr, false, false },
2417 { "creationtime", CreationTimeRole, I18NC_NOOP("@label", "Created"), nullptr, nullptr, false, false },
2418 { "accesstime", AccessTimeRole, I18NC_NOOP("@label", "Accessed"), nullptr, nullptr, false, false },
2419 { "type", TypeRole, I18NC_NOOP("@label", "Type"), nullptr, nullptr, false, false },
2420 { "rating", RatingRole, I18NC_NOOP("@label", "Rating"), nullptr, nullptr, true, false },
2421 { "tags", TagsRole, I18NC_NOOP("@label", "Tags"), nullptr, nullptr, true, false },
2422 { "comment", CommentRole, I18NC_NOOP("@label", "Comment"), nullptr, nullptr, true, false },
2423 { "title", TitleRole, I18NC_NOOP("@label", "Title"), I18NC_NOOP("@label", "Document"), true, true },
2424 { "wordCount", WordCountRole, I18NC_NOOP("@label", "Word Count"), I18NC_NOOP("@label", "Document"), true, true },
2425 { "lineCount", LineCountRole, I18NC_NOOP("@label", "Line Count"), I18NC_NOOP("@label", "Document"), true, true },
2426 { "imageDateTime", ImageDateTimeRole, I18NC_NOOP("@label", "Date Photographed"), I18NC_NOOP("@label", "Image"), true, true },
2427 { "width", WidthRole, I18NC_NOOP("@label", "Width"), I18NC_NOOP("@label", "Image"), true, true },
2428 { "height", HeightRole, I18NC_NOOP("@label", "Height"), I18NC_NOOP("@label", "Image"), true, true },
2429 { "orientation", OrientationRole, I18NC_NOOP("@label", "Orientation"), I18NC_NOOP("@label", "Image"), true, true },
2430 { "artist", ArtistRole, I18NC_NOOP("@label", "Artist"), I18NC_NOOP("@label", "Audio"), true, true },
2431 { "genre", GenreRole, I18NC_NOOP("@label", "Genre"), I18NC_NOOP("@label", "Audio"), true, true },
2432 { "album", AlbumRole, I18NC_NOOP("@label", "Album"), I18NC_NOOP("@label", "Audio"), true, true },
2433 { "duration", DurationRole, I18NC_NOOP("@label", "Duration"), I18NC_NOOP("@label", "Audio"), true, true },
2434 { "bitrate", BitrateRole, I18NC_NOOP("@label", "Bitrate"), I18NC_NOOP("@label", "Audio"), true, true },
2435 { "track", TrackRole, I18NC_NOOP("@label", "Track"), I18NC_NOOP("@label", "Audio"), true, true },
2436 { "releaseYear", ReleaseYearRole, I18NC_NOOP("@label", "Release Year"), I18NC_NOOP("@label", "Audio"), true, true },
2437 { "aspectRatio", AspectRatioRole, I18NC_NOOP("@label", "Aspect Ratio"), I18NC_NOOP("@label", "Video"), true, true },
2438 { "frameRate", FrameRateRole, I18NC_NOOP("@label", "Frame Rate"), I18NC_NOOP("@label", "Video"), true, true },
2439 { "path", PathRole, I18NC_NOOP("@label", "Path"), I18NC_NOOP("@label", "Other"), false, false },
2440 { "deletiontime", DeletionTimeRole, I18NC_NOOP("@label", "Deletion Time"), I18NC_NOOP("@label", "Other"), false, false },
2441 { "destination", DestinationRole, I18NC_NOOP("@label", "Link Destination"), I18NC_NOOP("@label", "Other"), false, false },
2442 { "originUrl", OriginUrlRole, I18NC_NOOP("@label", "Downloaded From"), I18NC_NOOP("@label", "Other"), true, false },
2443 { "permissions", PermissionsRole, I18NC_NOOP("@label", "Permissions"), I18NC_NOOP("@label", "Other"), false, false },
2444 { "owner", OwnerRole, I18NC_NOOP("@label", "Owner"), I18NC_NOOP("@label", "Other"), false, false },
2445 { "group", GroupRole, I18NC_NOOP("@label", "User Group"), I18NC_NOOP("@label", "Other"), false, false },
2446 };
2447
2448 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
2449 return rolesInfoMap;
2450 }
2451
2452 void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout)
2453 {
2454 QElapsedTimer timer;
2455 timer.start();
2456 for (const KFileItem& item : items) {
2457 // Only determine mime types for files here. For directories,
2458 // KFileItem::determineMimeType() reads the .directory file inside to
2459 // load the icon, but this is not necessary at all if we just need the
2460 // type. Some special code for setting the correct mime type for
2461 // directories is in retrieveData().
2462 if (!item.isDir()) {
2463 item.determineMimeType();
2464 }
2465
2466 if (timer.elapsed() > timeout) {
2467 // Don't block the user interface, let the remaining items
2468 // be resolved asynchronously.
2469 return;
2470 }
2471 }
2472 }
2473
2474 QByteArray KFileItemModel::sharedValue(const QByteArray& value)
2475 {
2476 static QSet<QByteArray> pool;
2477 const QSet<QByteArray>::const_iterator it = pool.constFind(value);
2478
2479 if (it != pool.constEnd()) {
2480 return *it;
2481 } else {
2482 pool.insert(value);
2483 return value;
2484 }
2485 }
2486
2487 bool KFileItemModel::isConsistent() const
2488 {
2489 // m_items may contain less items than m_itemData because m_items
2490 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2491 if (m_items.count() > m_itemData.count()) {
2492 return false;
2493 }
2494
2495 for (int i = 0, iMax = count(); i < iMax; ++i) {
2496 // Check if m_items and m_itemData are consistent.
2497 const KFileItem item = fileItem(i);
2498 if (item.isNull()) {
2499 qCWarning(DolphinDebug) << "Item" << i << "is null";
2500 return false;
2501 }
2502
2503 const int itemIndex = index(item);
2504 if (itemIndex != i) {
2505 qCWarning(DolphinDebug) << "Item" << i << "has a wrong index:" << itemIndex;
2506 return false;
2507 }
2508
2509 // Check if the items are sorted correctly.
2510 if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
2511 qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:"
2512 << fileItem(i - 1) << fileItem(i);
2513 return false;
2514 }
2515
2516 // Check if all parent-child relationships are consistent.
2517 const ItemData* data = m_itemData.at(i);
2518 const ItemData* parent = data->parent;
2519 if (parent) {
2520 if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
2521 qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
2522 return false;
2523 }
2524
2525 const int parentIndex = index(parent->item);
2526 if (parentIndex >= i) {
2527 qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child" << data->item;
2528 return false;
2529 }
2530 }
2531 }
2532
2533 return true;
2534 }
2535
2536 void KFileItemModel::slotListerError(KIO::Job *job)
2537 {
2538 if (job->error() == KIO::ERR_IS_FILE) {
2539 if (auto *listJob = qobject_cast<KIO::ListJob *>(job)) {
2540 Q_EMIT urlIsFileError(listJob->url());
2541 }
2542 } else {
2543 const QString errorString = job->errorString();
2544 Q_EMIT errorMessage(!errorString.isEmpty() ? errorString : i18nc("@info:status", "Unknown error."));
2545 }
2546 }