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