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