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