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