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