]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Merge branch 'release/22.04'
[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 PermissionsRole:
1584 case OwnerRole:
1585 case GroupRole:
1586 case DestinationRole:
1587 case PathRole:
1588 case DeletionTimeRole:
1589 // These roles can be determined with retrieveData, and they have to be stored
1590 // in the QHash "values" for the sorting.
1591 for (ItemData* itemData : qAsConst(itemDataList)) {
1592 if (itemData->values.isEmpty()) {
1593 itemData->values = retrieveData(itemData->item, itemData->parent);
1594 }
1595 }
1596 break;
1597
1598 case TypeRole:
1599 // At least store the data including the file type for items with known MIME type.
1600 for (ItemData* itemData : qAsConst(itemDataList)) {
1601 if (itemData->values.isEmpty()) {
1602 const KFileItem item = itemData->item;
1603 if (item.isDir() || item.isMimeTypeKnown()) {
1604 itemData->values = retrieveData(itemData->item, itemData->parent);
1605 }
1606 }
1607 }
1608 break;
1609
1610 default:
1611 // The other roles are either resolved by KFileItemModelRolesUpdater
1612 // (this includes the SizeRole for directories), or they do not need
1613 // to be stored in the QHash "values" for sorting because the data can
1614 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1615 // DateRole).
1616 break;
1617 }
1618 }
1619
1620 int KFileItemModel::expandedParentsCount(const ItemData* data)
1621 {
1622 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1623 // if the corresponding item is expanded, and it is not a top-level item.
1624 const ItemData* parent = data->parent;
1625 if (parent) {
1626 if (parent->parent) {
1627 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1628 return parent->values.value("expandedParentsCount").toInt() + 1;
1629 } else {
1630 return 1;
1631 }
1632 } else {
1633 return 0;
1634 }
1635 }
1636
1637 void KFileItemModel::removeExpandedItems()
1638 {
1639 QVector<int> indexesToRemove;
1640
1641 const int maxIndex = m_itemData.count() - 1;
1642 for (int i = 0; i <= maxIndex; ++i) {
1643 const ItemData* itemData = m_itemData.at(i);
1644 if (itemData->parent) {
1645 indexesToRemove.append(i);
1646 }
1647 }
1648
1649 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1650 m_expandedDirs.clear();
1651
1652 // Also remove all filtered items which have a parent.
1653 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
1654 const QHash<KFileItem, ItemData*>::iterator end = m_filteredItems.end();
1655
1656 while (it != end) {
1657 if (it.value()->parent) {
1658 delete it.value();
1659 it = m_filteredItems.erase(it);
1660 } else {
1661 ++it;
1662 }
1663 }
1664 }
1665
1666 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles)
1667 {
1668 Q_EMIT itemsChanged(itemRanges, changedRoles);
1669
1670 // Trigger a resorting if necessary. Note that this can happen even if the sort
1671 // role has not changed at all because the file name can be used as a fallback.
1672 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) {
1673 for (const KItemRange& range : itemRanges) {
1674 bool needsResorting = false;
1675
1676 const int first = range.index;
1677 const int last = range.index + range.count - 1;
1678
1679 // Resorting the model is necessary if
1680 // (a) The first item in the range is "lessThan" its predecessor,
1681 // (b) the successor of the last item is "lessThan" the last item, or
1682 // (c) the internal order of the items in the range is incorrect.
1683 if (first > 0
1684 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1685 needsResorting = true;
1686 } else if (last < count() - 1
1687 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1688 needsResorting = true;
1689 } else {
1690 for (int index = first; index < last; ++index) {
1691 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1692 needsResorting = true;
1693 break;
1694 }
1695 }
1696 }
1697
1698 if (needsResorting) {
1699 m_resortAllItemsTimer->start();
1700 return;
1701 }
1702 }
1703 }
1704
1705 if (groupedSorting() && changedRoles.contains(sortRole())) {
1706 // The position is still correct, but the groups might have changed
1707 // if the changed item is either the first or the last item in a
1708 // group.
1709 // In principle, we could try to find out if the item really is the
1710 // first or last one in its group and then update the groups
1711 // (possibly with a delayed timer to make sure that we don't
1712 // re-calculate the groups very often if items are updated one by
1713 // one), but starting m_resortAllItemsTimer is easier.
1714 m_resortAllItemsTimer->start();
1715 }
1716 }
1717
1718 void KFileItemModel::resetRoles()
1719 {
1720 for (int i = 0; i < RolesCount; ++i) {
1721 m_requestRole[i] = false;
1722 }
1723 }
1724
1725 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const
1726 {
1727 static QHash<QByteArray, RoleType> roles;
1728 if (roles.isEmpty()) {
1729 // Insert user visible roles that can be accessed with
1730 // KFileItemModel::roleInformation()
1731 int count = 0;
1732 const RoleInfoMap* map = rolesInfoMap(count);
1733 for (int i = 0; i < count; ++i) {
1734 roles.insert(map[i].role, map[i].roleType);
1735 }
1736
1737 // Insert internal roles (take care to synchronize the implementation
1738 // with KFileItemModel::roleForType() in case if a change is done).
1739 roles.insert("isDir", IsDirRole);
1740 roles.insert("isLink", IsLinkRole);
1741 roles.insert("isHidden", IsHiddenRole);
1742 roles.insert("isExpanded", IsExpandedRole);
1743 roles.insert("isExpandable", IsExpandableRole);
1744 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1745
1746 Q_ASSERT(roles.count() == RolesCount);
1747 }
1748
1749 return roles.value(role, NoRole);
1750 }
1751
1752 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1753 {
1754 static QHash<RoleType, QByteArray> roles;
1755 if (roles.isEmpty()) {
1756 // Insert user visible roles that can be accessed with
1757 // KFileItemModel::roleInformation()
1758 int count = 0;
1759 const RoleInfoMap* map = rolesInfoMap(count);
1760 for (int i = 0; i < count; ++i) {
1761 roles.insert(map[i].roleType, map[i].role);
1762 }
1763
1764 // Insert internal roles (take care to synchronize the implementation
1765 // with KFileItemModel::typeForRole() in case if a change is done).
1766 roles.insert(IsDirRole, "isDir");
1767 roles.insert(IsLinkRole, "isLink");
1768 roles.insert(IsHiddenRole, "isHidden");
1769 roles.insert(IsExpandedRole, "isExpanded");
1770 roles.insert(IsExpandableRole, "isExpandable");
1771 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1772
1773 Q_ASSERT(roles.count() == RolesCount);
1774 };
1775
1776 return roles.value(roleType);
1777 }
1778
1779 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item, const ItemData* parent) const
1780 {
1781 // It is important to insert only roles that are fast to retrieve. E.g.
1782 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1783 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1784 QHash<QByteArray, QVariant> data;
1785 data.insert(sharedValue("url"), item.url());
1786
1787 const bool isDir = item.isDir();
1788 if (m_requestRole[IsDirRole] && isDir) {
1789 data.insert(sharedValue("isDir"), true);
1790 }
1791
1792 if (m_requestRole[IsLinkRole] && item.isLink()) {
1793 data.insert(sharedValue("isLink"), true);
1794 }
1795
1796 if (m_requestRole[IsHiddenRole]) {
1797 data.insert(sharedValue("isHidden"), item.isHidden());
1798 }
1799
1800 if (m_requestRole[NameRole]) {
1801 data.insert(sharedValue("text"), item.text());
1802 }
1803
1804 if (m_requestRole[SizeRole] && !isDir) {
1805 data.insert(sharedValue("size"), item.size());
1806 }
1807
1808 if (m_requestRole[ModificationTimeRole]) {
1809 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1810 // having several thousands of items. Instead read the raw number from UDSEntry directly
1811 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1812 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1813 data.insert(sharedValue("modificationtime"), dateTime);
1814 }
1815
1816 if (m_requestRole[CreationTimeRole]) {
1817 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1818 // having several thousands of items. Instead read the raw number from UDSEntry directly
1819 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1820 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1821 data.insert(sharedValue("creationtime"), dateTime);
1822 }
1823
1824 if (m_requestRole[AccessTimeRole]) {
1825 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1826 // having several thousands of items. Instead read the raw number from UDSEntry directly
1827 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1828 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1829 data.insert(sharedValue("accesstime"), dateTime);
1830 }
1831
1832 if (m_requestRole[PermissionsRole]) {
1833 data.insert(sharedValue("permissions"), item.permissionsString());
1834 }
1835
1836 if (m_requestRole[OwnerRole]) {
1837 data.insert(sharedValue("owner"), item.user());
1838 }
1839
1840 if (m_requestRole[GroupRole]) {
1841 data.insert(sharedValue("group"), item.group());
1842 }
1843
1844 if (m_requestRole[DestinationRole]) {
1845 QString destination = item.linkDest();
1846 if (destination.isEmpty()) {
1847 destination = QLatin1Char('-');
1848 }
1849 data.insert(sharedValue("destination"), destination);
1850 }
1851
1852 if (m_requestRole[PathRole]) {
1853 QString path;
1854 if (item.url().scheme() == QLatin1String("trash")) {
1855 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1856 } else {
1857 // For performance reasons cache the home-path in a static QString
1858 // (see QDir::homePath() for more details)
1859 static QString homePath;
1860 if (homePath.isEmpty()) {
1861 homePath = QDir::homePath();
1862 }
1863
1864 path = item.localPath();
1865 if (path.startsWith(homePath)) {
1866 path.replace(0, homePath.length(), QLatin1Char('~'));
1867 }
1868 }
1869
1870 const int index = path.lastIndexOf(item.text());
1871 path = path.mid(0, index - 1);
1872 data.insert(sharedValue("path"), path);
1873 }
1874
1875 if (m_requestRole[DeletionTimeRole]) {
1876 QDateTime deletionTime;
1877 if (item.url().scheme() == QLatin1String("trash")) {
1878 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
1879 }
1880 data.insert(sharedValue("deletiontime"), deletionTime);
1881 }
1882
1883 if (m_requestRole[IsExpandableRole] && isDir) {
1884 data.insert(sharedValue("isExpandable"), true);
1885 }
1886
1887 if (m_requestRole[ExpandedParentsCountRole]) {
1888 if (parent) {
1889 const int level = expandedParentsCount(parent) + 1;
1890 data.insert(sharedValue("expandedParentsCount"), level);
1891 }
1892 }
1893
1894 if (item.isMimeTypeKnown()) {
1895 QString iconName = item.iconName();
1896 if (!QIcon::hasThemeIcon(iconName)) {
1897 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
1898 iconName = mimeType.genericIconName();
1899 }
1900
1901 data.insert(sharedValue("iconName"), iconName);
1902
1903 if (m_requestRole[TypeRole]) {
1904 data.insert(sharedValue("type"), item.mimeComment());
1905 }
1906 } else if (m_requestRole[TypeRole] && isDir) {
1907 static const QString folderMimeType = item.mimeComment();
1908 data.insert(sharedValue("type"), folderMimeType);
1909 }
1910
1911 return data;
1912 }
1913
1914 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const
1915 {
1916 int result = 0;
1917
1918 if (a->parent != b->parent) {
1919 const int expansionLevelA = expandedParentsCount(a);
1920 const int expansionLevelB = expandedParentsCount(b);
1921
1922 // If b has a higher expansion level than a, check if a is a parent
1923 // of b, and make sure that both expansion levels are equal otherwise.
1924 for (int i = expansionLevelB; i > expansionLevelA; --i) {
1925 if (b->parent == a) {
1926 return true;
1927 }
1928 b = b->parent;
1929 }
1930
1931 // If a has a higher expansion level than a, check if b is a parent
1932 // of a, and make sure that both expansion levels are equal otherwise.
1933 for (int i = expansionLevelA; i > expansionLevelB; --i) {
1934 if (a->parent == b) {
1935 return false;
1936 }
1937 a = a->parent;
1938 }
1939
1940 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
1941
1942 // Compare the last parents of a and b which are different.
1943 while (a->parent != b->parent) {
1944 a = a->parent;
1945 b = b->parent;
1946 }
1947 }
1948
1949 // Show hidden files and folders last
1950 if (m_sortHiddenLast) {
1951 const bool isHiddenA = a->item.isHidden();
1952 const bool isHiddenB = b->item.isHidden();
1953 if (isHiddenA && !isHiddenB) {
1954 return false;
1955 } else if (!isHiddenA && isHiddenB) {
1956 return true;
1957 }
1958 }
1959
1960 if (m_sortDirsFirst || (DetailsModeSettings::directorySizeCount() && m_sortRole == SizeRole)) {
1961 const bool isDirA = a->item.isDir();
1962 const bool isDirB = b->item.isDir();
1963 if (isDirA && !isDirB) {
1964 return true;
1965 } else if (!isDirA && isDirB) {
1966 return false;
1967 }
1968 }
1969
1970 result = sortRoleCompare(a, b, collator);
1971
1972 return (sortOrder() == Qt::AscendingOrder) ? result < 0 : result > 0;
1973 }
1974
1975 void KFileItemModel::sort(const QList<KFileItemModel::ItemData*>::iterator &begin,
1976 const QList<KFileItemModel::ItemData*>::iterator &end) const
1977 {
1978 auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
1979 {
1980 return lessThan(a, b, m_collator);
1981 };
1982
1983 if (m_sortRole == NameRole || isRoleValueNatural(m_sortRole)) {
1984 // Sorting by string can be expensive, in particular if natural sorting is
1985 // enabled. Use all CPU cores to speed up the sorting process.
1986 static const int numberOfThreads = QThread::idealThreadCount();
1987 parallelMergeSort(begin, end, lambdaLessThan, numberOfThreads);
1988 } else {
1989 // Sorting by other roles is quite fast. Use only one thread to prevent
1990 // problems caused by non-reentrant comparison functions, see
1991 // https://bugs.kde.org/show_bug.cgi?id=312679
1992 mergeSort(begin, end, lambdaLessThan);
1993 }
1994 }
1995
1996 int KFileItemModel::sortRoleCompare(const ItemData* a, const ItemData* b, const QCollator& collator) const
1997 {
1998 // This function must never return 0, because that would break stable
1999 // sorting, which leads to all kinds of bugs.
2000 // See: https://bugs.kde.org/show_bug.cgi?id=433247
2001 // If two items have equal sort values, let the fallbacks at the bottom of
2002 // the function handle it.
2003 const KFileItem& itemA = a->item;
2004 const KFileItem& itemB = b->item;
2005
2006 int result = 0;
2007
2008 switch (m_sortRole) {
2009 case NameRole:
2010 // The name role is handled as default fallback after the switch
2011 break;
2012
2013 case SizeRole: {
2014 if (DetailsModeSettings::directorySizeCount() && itemA.isDir()) {
2015 // folders first then
2016 // items A and B are folders thanks to lessThan checks
2017 auto valueA = a->values.value("count");
2018 auto valueB = b->values.value("count");
2019 if (valueA.isNull()) {
2020 if (!valueB.isNull()) {
2021 return -1;
2022 }
2023 } else if (valueB.isNull()) {
2024 return +1;
2025 } else {
2026 if (valueA.toLongLong() < valueB.toLongLong()) {
2027 return -1;
2028 } else if (valueA.toLongLong() > valueB.toLongLong()) {
2029 return +1;
2030 }
2031 }
2032 break;
2033 }
2034
2035 KIO::filesize_t sizeA = 0;
2036 if (itemA.isDir()) {
2037 sizeA = a->values.value("size").toULongLong();
2038 } else {
2039 sizeA = itemA.size();
2040 }
2041 KIO::filesize_t sizeB = 0;
2042 if (itemB.isDir()) {
2043 sizeB = b->values.value("size").toULongLong();
2044 } else {
2045 sizeB = itemB.size();
2046 }
2047 if (sizeA < sizeB) {
2048 return -1;
2049 } else if (sizeA > sizeB) {
2050 return +1;
2051 }
2052 break;
2053 }
2054
2055 case ModificationTimeRole: {
2056 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2057 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
2058 if (dateTimeA < dateTimeB) {
2059 return -1;
2060 } else if (dateTimeA > dateTimeB) {
2061 return +1;
2062 }
2063 break;
2064 }
2065
2066 case CreationTimeRole: {
2067 const long long dateTimeA = itemA.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2068 const long long dateTimeB = itemB.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
2069 if (dateTimeA < dateTimeB) {
2070 return -1;
2071 } else if (dateTimeA > dateTimeB) {
2072 return +1;
2073 }
2074 break;
2075 }
2076
2077 case DeletionTimeRole: {
2078 const QDateTime dateTimeA = a->values.value("deletiontime").toDateTime();
2079 const QDateTime dateTimeB = b->values.value("deletiontime").toDateTime();
2080 if (dateTimeA < dateTimeB) {
2081 return -1;
2082 } else if (dateTimeA > dateTimeB) {
2083 return +1;
2084 }
2085 break;
2086 }
2087
2088 case RatingRole:
2089 case WidthRole:
2090 case HeightRole:
2091 case WordCountRole:
2092 case LineCountRole:
2093 case TrackRole:
2094 case ReleaseYearRole: {
2095 result = a->values.value(roleForType(m_sortRole)).toInt() - b->values.value(roleForType(m_sortRole)).toInt();
2096 break;
2097 }
2098
2099 case DimensionsRole: {
2100 const QByteArray role = roleForType(m_sortRole);
2101 const QSize dimensionsA = a->values.value(role).toSize();
2102 const QSize dimensionsB = b->values.value(role).toSize();
2103
2104 if (dimensionsA.width() == dimensionsB.width()) {
2105 result = dimensionsA.height() - dimensionsB.height();
2106 } else {
2107 result = dimensionsA.width() - dimensionsB.width();
2108 }
2109 break;
2110 }
2111
2112 default: {
2113 const QByteArray role = roleForType(m_sortRole);
2114 const QString roleValueA = a->values.value(role).toString();
2115 const QString roleValueB = b->values.value(role).toString();
2116 if (!roleValueA.isEmpty() && roleValueB.isEmpty()) {
2117 return -1;
2118 } else if (roleValueA.isEmpty() && !roleValueB.isEmpty()) {
2119 return +1;
2120 } else if (isRoleValueNatural(m_sortRole)) {
2121 result = stringCompare(roleValueA, roleValueB, collator);
2122 } else {
2123 result = QString::compare(roleValueA, roleValueB);
2124 }
2125 break;
2126 }
2127
2128 }
2129
2130 if (result != 0) {
2131 // The current sort role was sufficient to define an order
2132 return result;
2133 }
2134
2135 // Fallback #1: Compare the text of the items
2136 result = stringCompare(itemA.text(), itemB.text(), collator);
2137 if (result != 0) {
2138 return result;
2139 }
2140
2141 // Fallback #2: KFileItem::text() may not be unique in case UDS_DISPLAY_NAME is used
2142 result = stringCompare(itemA.name(), itemB.name(), collator);
2143 if (result != 0) {
2144 return result;
2145 }
2146
2147 // Fallback #3: It must be assured that the sort order is always unique even if two values have been
2148 // equal. In this case a comparison of the URL is done which is unique in all cases
2149 // within KDirLister.
2150 return QString::compare(itemA.url().url(), itemB.url().url(), Qt::CaseSensitive);
2151 }
2152
2153 int KFileItemModel::stringCompare(const QString& a, const QString& b, const QCollator& collator) const
2154 {
2155 QMutexLocker collatorLock(s_collatorMutex());
2156
2157 if (m_naturalSorting) {
2158 return collator.compare(a, b);
2159 }
2160
2161 const int result = QString::compare(a, b, collator.caseSensitivity());
2162 if (result != 0 || collator.caseSensitivity() == Qt::CaseSensitive) {
2163 // Only return the result, if the strings are not equal. If they are equal by a case insensitive
2164 // comparison, still a deterministic sort order is required. A case sensitive
2165 // comparison is done as fallback.
2166 return result;
2167 }
2168
2169 return QString::compare(a, b, Qt::CaseSensitive);
2170 }
2171
2172 QList<QPair<int, QVariant> > KFileItemModel::nameRoleGroups() const
2173 {
2174 Q_ASSERT(!m_itemData.isEmpty());
2175
2176 const int maxIndex = count() - 1;
2177 QList<QPair<int, QVariant> > groups;
2178
2179 QString groupValue;
2180 QChar firstChar;
2181 for (int i = 0; i <= maxIndex; ++i) {
2182 if (isChildItem(i)) {
2183 continue;
2184 }
2185
2186 const QString name = m_itemData.at(i)->item.text();
2187
2188 // Use the first character of the name as group indication
2189 QChar newFirstChar = name.at(0).toUpper();
2190 if (newFirstChar == QLatin1Char('~') && name.length() > 1) {
2191 newFirstChar = name.at(1).toUpper();
2192 }
2193
2194 if (firstChar != newFirstChar) {
2195 QString newGroupValue;
2196 if (newFirstChar.isLetter()) {
2197
2198 if (m_collator.compare(newFirstChar, QChar(QLatin1Char('A'))) >= 0 && m_collator.compare(newFirstChar, QChar(QLatin1Char('Z'))) <= 0) {
2199 // WARNING! Symbols based on latin 'Z' like 'Z' with acute are treated wrong as non Latin and put in a new group.
2200
2201 // Try to find a matching group in the range 'A' to 'Z'.
2202 static std::vector<QChar> lettersAtoZ;
2203 lettersAtoZ.reserve('Z' - 'A' + 1);
2204 if (lettersAtoZ.empty()) {
2205 for (char c = 'A'; c <= 'Z'; ++c) {
2206 lettersAtoZ.push_back(QLatin1Char(c));
2207 }
2208 }
2209
2210 auto localeAwareLessThan = [this](QChar c1, QChar c2) -> bool {
2211 return m_collator.compare(c1, c2) < 0;
2212 };
2213
2214 std::vector<QChar>::iterator it = std::lower_bound(lettersAtoZ.begin(), lettersAtoZ.end(), newFirstChar, localeAwareLessThan);
2215 if (it != lettersAtoZ.end()) {
2216 if (localeAwareLessThan(newFirstChar, *it)) {
2217 // newFirstChar belongs to the group preceding *it.
2218 // Example: for an umlaut 'A' in the German locale, *it would be 'B' now.
2219 --it;
2220 }
2221 newGroupValue = *it;
2222 }
2223
2224 } else {
2225 // Symbols from non Latin-based scripts
2226 newGroupValue = newFirstChar;
2227 }
2228 } else if (newFirstChar >= QLatin1Char('0') && newFirstChar <= QLatin1Char('9')) {
2229 // Apply group '0 - 9' for any name that starts with a digit
2230 newGroupValue = i18nc("@title:group Groups that start with a digit", "0 - 9");
2231 } else {
2232 newGroupValue = i18nc("@title:group", "Others");
2233 }
2234
2235 if (newGroupValue != groupValue) {
2236 groupValue = newGroupValue;
2237 groups.append(QPair<int, QVariant>(i, newGroupValue));
2238 }
2239
2240 firstChar = newFirstChar;
2241 }
2242 }
2243 return groups;
2244 }
2245
2246 QList<QPair<int, QVariant> > KFileItemModel::sizeRoleGroups() const
2247 {
2248 Q_ASSERT(!m_itemData.isEmpty());
2249
2250 const int maxIndex = count() - 1;
2251 QList<QPair<int, QVariant> > groups;
2252
2253 QString groupValue;
2254 for (int i = 0; i <= maxIndex; ++i) {
2255 if (isChildItem(i)) {
2256 continue;
2257 }
2258
2259 const KFileItem& item = m_itemData.at(i)->item;
2260 KIO::filesize_t fileSize = !item.isNull() ? item.size() : ~0U;
2261 QString newGroupValue;
2262 if (!item.isNull() && item.isDir()) {
2263 if (DetailsModeSettings::directorySizeCount() || m_sortDirsFirst) {
2264 newGroupValue = i18nc("@title:group Size", "Folders");
2265 } else {
2266 fileSize = m_itemData.at(i)->values.value("size").toULongLong();
2267 }
2268 }
2269
2270 if (newGroupValue.isEmpty()) {
2271 if (fileSize < 5 * 1024 * 1024) { // < 5 MB
2272 newGroupValue = i18nc("@title:group Size", "Small");
2273 } else if (fileSize < 10 * 1024 * 1024) { // < 10 MB
2274 newGroupValue = i18nc("@title:group Size", "Medium");
2275 } else {
2276 newGroupValue = i18nc("@title:group Size", "Big");
2277 }
2278 }
2279
2280 if (newGroupValue != groupValue) {
2281 groupValue = newGroupValue;
2282 groups.append(QPair<int, QVariant>(i, newGroupValue));
2283 }
2284 }
2285
2286 return groups;
2287 }
2288
2289 QList<QPair<int, QVariant> > KFileItemModel::timeRoleGroups(const std::function<QDateTime(const ItemData *)> &fileTimeCb) const
2290 {
2291 Q_ASSERT(!m_itemData.isEmpty());
2292
2293 const int maxIndex = count() - 1;
2294 QList<QPair<int, QVariant> > groups;
2295
2296 const QDate currentDate = QDate::currentDate();
2297
2298 QDate previousFileDate;
2299 QString groupValue;
2300 for (int i = 0; i <= maxIndex; ++i) {
2301 if (isChildItem(i)) {
2302 continue;
2303 }
2304
2305 const QDateTime fileTime = fileTimeCb(m_itemData.at(i));
2306 const QDate fileDate = fileTime.date();
2307 if (fileDate == previousFileDate) {
2308 // The current item is in the same group as the previous item
2309 continue;
2310 }
2311 previousFileDate = fileDate;
2312
2313 const int daysDistance = fileDate.daysTo(currentDate);
2314
2315 QString newGroupValue;
2316 if (currentDate.year() == fileDate.year() &&
2317 currentDate.month() == fileDate.month()) {
2318
2319 switch (daysDistance / 7) {
2320 case 0:
2321 switch (daysDistance) {
2322 case 0: newGroupValue = i18nc("@title:group Date", "Today"); break;
2323 case 1: newGroupValue = i18nc("@title:group Date", "Yesterday"); break;
2324 default:
2325 newGroupValue = fileTime.toString(
2326 i18nc("@title:group Date: The week day name: dddd", "dddd"));
2327 newGroupValue = i18nc("Can be used to script translation of \"dddd\""
2328 "with context @title:group Date", "%1", newGroupValue);
2329 }
2330 break;
2331 case 1:
2332 newGroupValue = i18nc("@title:group Date", "One Week Ago");
2333 break;
2334 case 2:
2335 newGroupValue = i18nc("@title:group Date", "Two Weeks Ago");
2336 break;
2337 case 3:
2338 newGroupValue = i18nc("@title:group Date", "Three Weeks Ago");
2339 break;
2340 case 4:
2341 case 5:
2342 newGroupValue = i18nc("@title:group Date", "Earlier this Month");
2343 break;
2344 default:
2345 Q_ASSERT(false);
2346 }
2347 } else {
2348 const QDate lastMonthDate = currentDate.addMonths(-1);
2349 if (lastMonthDate.year() == fileDate.year() &&
2350 lastMonthDate.month() == fileDate.month()) {
2351
2352 if (daysDistance == 1) {
2353 const KLocalizedString format = ki18nc("@title:group Date: "
2354 "MMMM is full month name in current locale, and yyyy is "
2355 "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)");
2356 const QString translatedFormat = format.toString();
2357 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2358 newGroupValue = fileTime.toString(translatedFormat);
2359 newGroupValue = i18nc("Can be used to script translation of "
2360 "\"'Yesterday' (MMMM, yyyy)\" with context @title:group Date",
2361 "%1", newGroupValue);
2362 } else {
2363 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2364 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2365 newGroupValue = fileTime.toString(untranslatedFormat);
2366 }
2367 } else if (daysDistance <= 7) {
2368 newGroupValue = fileTime.toString(i18nc("@title:group Date: "
2369 "The week day name: dddd, MMMM is full month name "
2370 "in current locale, and yyyy is full year number.",
2371 "dddd (MMMM, yyyy)"));
2372 newGroupValue = i18nc("Can be used to script translation of "
2373 "\"dddd (MMMM, yyyy)\" with context @title:group Date",
2374 "%1", newGroupValue);
2375 } else if (daysDistance <= 7 * 2) {
2376 const KLocalizedString format = ki18nc("@title:group Date: "
2377 "MMMM is full month name in current locale, and yyyy is "
2378 "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)");
2379 const QString translatedFormat = format.toString();
2380 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2381 newGroupValue = fileTime.toString(translatedFormat);
2382 newGroupValue = i18nc("Can be used to script translation of "
2383 "\"'One Week Ago' (MMMM, yyyy)\" with context @title:group Date",
2384 "%1", newGroupValue);
2385 } else {
2386 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2387 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2388 newGroupValue = fileTime.toString(untranslatedFormat);
2389 }
2390 } else if (daysDistance <= 7 * 3) {
2391 const KLocalizedString format = ki18nc("@title:group Date: "
2392 "MMMM is full month name in current locale, and yyyy is "
2393 "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)");
2394 const QString translatedFormat = format.toString();
2395 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2396 newGroupValue = fileTime.toString(translatedFormat);
2397 newGroupValue = i18nc("Can be used to script translation of "
2398 "\"'Two Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2399 "%1", newGroupValue);
2400 } else {
2401 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2402 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2403 newGroupValue = fileTime.toString(untranslatedFormat);
2404 }
2405 } else if (daysDistance <= 7 * 4) {
2406 const KLocalizedString format = ki18nc("@title:group Date: "
2407 "MMMM is full month name in current locale, and yyyy is "
2408 "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)");
2409 const QString translatedFormat = format.toString();
2410 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2411 newGroupValue = fileTime.toString(translatedFormat);
2412 newGroupValue = i18nc("Can be used to script translation of "
2413 "\"'Three Weeks Ago' (MMMM, yyyy)\" with context @title:group Date",
2414 "%1", newGroupValue);
2415 } else {
2416 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2417 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2418 newGroupValue = fileTime.toString(untranslatedFormat);
2419 }
2420 } else {
2421 const KLocalizedString format = ki18nc("@title:group Date: "
2422 "MMMM is full month name in current locale, and yyyy is "
2423 "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");
2424 const QString translatedFormat = format.toString();
2425 if (translatedFormat.count(QLatin1Char('\'')) == 2) {
2426 newGroupValue = fileTime.toString(translatedFormat);
2427 newGroupValue = i18nc("Can be used to script translation of "
2428 "\"'Earlier on' MMMM, yyyy\" with context @title:group Date",
2429 "%1", newGroupValue);
2430 } else {
2431 qCWarning(DolphinDebug).nospace() << "A wrong translation was found: " << translatedFormat << ". Please file a bug report at bugs.kde.org";
2432 const QString untranslatedFormat = format.toString({ QLatin1String("en_US") });
2433 newGroupValue = fileTime.toString(untranslatedFormat);
2434 }
2435 }
2436 } else {
2437 newGroupValue = fileTime.toString(i18nc("@title:group "
2438 "The month and year: MMMM is full month name in current locale, "
2439 "and yyyy is full year number", "MMMM, yyyy"));
2440 newGroupValue = i18nc("Can be used to script translation of "
2441 "\"MMMM, yyyy\" with context @title:group Date",
2442 "%1", newGroupValue);
2443 }
2444 }
2445
2446 if (newGroupValue != groupValue) {
2447 groupValue = newGroupValue;
2448 groups.append(QPair<int, QVariant>(i, newGroupValue));
2449 }
2450 }
2451
2452 return groups;
2453 }
2454
2455 QList<QPair<int, QVariant> > KFileItemModel::permissionRoleGroups() const
2456 {
2457 Q_ASSERT(!m_itemData.isEmpty());
2458
2459 const int maxIndex = count() - 1;
2460 QList<QPair<int, QVariant> > groups;
2461
2462 QString permissionsString;
2463 QString groupValue;
2464 for (int i = 0; i <= maxIndex; ++i) {
2465 if (isChildItem(i)) {
2466 continue;
2467 }
2468
2469 const ItemData* itemData = m_itemData.at(i);
2470 const QString newPermissionsString = itemData->values.value("permissions").toString();
2471 if (newPermissionsString == permissionsString) {
2472 continue;
2473 }
2474 permissionsString = newPermissionsString;
2475
2476 const QFileInfo info(itemData->item.url().toLocalFile());
2477
2478 // Set user string
2479 QString user;
2480 if (info.permission(QFile::ReadUser)) {
2481 user = i18nc("@item:intext Access permission, concatenated", "Read, ");
2482 }
2483 if (info.permission(QFile::WriteUser)) {
2484 user += i18nc("@item:intext Access permission, concatenated", "Write, ");
2485 }
2486 if (info.permission(QFile::ExeUser)) {
2487 user += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2488 }
2489 user = user.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : user.mid(0, user.count() - 2);
2490
2491 // Set group string
2492 QString group;
2493 if (info.permission(QFile::ReadGroup)) {
2494 group = i18nc("@item:intext Access permission, concatenated", "Read, ");
2495 }
2496 if (info.permission(QFile::WriteGroup)) {
2497 group += i18nc("@item:intext Access permission, concatenated", "Write, ");
2498 }
2499 if (info.permission(QFile::ExeGroup)) {
2500 group += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2501 }
2502 group = group.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : group.mid(0, group.count() - 2);
2503
2504 // Set others string
2505 QString others;
2506 if (info.permission(QFile::ReadOther)) {
2507 others = i18nc("@item:intext Access permission, concatenated", "Read, ");
2508 }
2509 if (info.permission(QFile::WriteOther)) {
2510 others += i18nc("@item:intext Access permission, concatenated", "Write, ");
2511 }
2512 if (info.permission(QFile::ExeOther)) {
2513 others += i18nc("@item:intext Access permission, concatenated", "Execute, ");
2514 }
2515 others = others.isEmpty() ? i18nc("@item:intext Access permission, concatenated", "Forbidden") : others.mid(0, others.count() - 2);
2516
2517 const QString newGroupValue = i18nc("@title:group Files and folders by permissions", "User: %1 | Group: %2 | Others: %3", user, group, others);
2518 if (newGroupValue != groupValue) {
2519 groupValue = newGroupValue;
2520 groups.append(QPair<int, QVariant>(i, newGroupValue));
2521 }
2522 }
2523
2524 return groups;
2525 }
2526
2527 QList<QPair<int, QVariant> > KFileItemModel::ratingRoleGroups() const
2528 {
2529 Q_ASSERT(!m_itemData.isEmpty());
2530
2531 const int maxIndex = count() - 1;
2532 QList<QPair<int, QVariant> > groups;
2533
2534 int groupValue = -1;
2535 for (int i = 0; i <= maxIndex; ++i) {
2536 if (isChildItem(i)) {
2537 continue;
2538 }
2539 const int newGroupValue = m_itemData.at(i)->values.value("rating", 0).toInt();
2540 if (newGroupValue != groupValue) {
2541 groupValue = newGroupValue;
2542 groups.append(QPair<int, QVariant>(i, newGroupValue));
2543 }
2544 }
2545
2546 return groups;
2547 }
2548
2549 QList<QPair<int, QVariant> > KFileItemModel::genericStringRoleGroups(const QByteArray& role) const
2550 {
2551 Q_ASSERT(!m_itemData.isEmpty());
2552
2553 const int maxIndex = count() - 1;
2554 QList<QPair<int, QVariant> > groups;
2555
2556 bool isFirstGroupValue = true;
2557 QString groupValue;
2558 for (int i = 0; i <= maxIndex; ++i) {
2559 if (isChildItem(i)) {
2560 continue;
2561 }
2562 const QString newGroupValue = m_itemData.at(i)->values.value(role).toString();
2563 if (newGroupValue != groupValue || isFirstGroupValue) {
2564 groupValue = newGroupValue;
2565 groups.append(QPair<int, QVariant>(i, newGroupValue));
2566 isFirstGroupValue = false;
2567 }
2568 }
2569
2570 return groups;
2571 }
2572
2573 void KFileItemModel::emitSortProgress(int resolvedCount)
2574 {
2575 // Be tolerant against a resolvedCount with a wrong range.
2576 // Although there should not be a case where KFileItemModelRolesUpdater
2577 // (= caller) provides a wrong range, it is important to emit
2578 // a useful progress information even if there is an unexpected
2579 // implementation issue.
2580
2581 const int itemCount = count();
2582 if (resolvedCount >= itemCount) {
2583 m_sortingProgressPercent = -1;
2584 if (m_resortAllItemsTimer->isActive()) {
2585 m_resortAllItemsTimer->stop();
2586 resortAllItems();
2587 }
2588
2589 Q_EMIT directorySortingProgress(100);
2590 } else if (itemCount > 0) {
2591 resolvedCount = qBound(0, resolvedCount, itemCount);
2592
2593 const int progress = resolvedCount * 100 / itemCount;
2594 if (m_sortingProgressPercent != progress) {
2595 m_sortingProgressPercent = progress;
2596 Q_EMIT directorySortingProgress(progress);
2597 }
2598 }
2599 }
2600
2601 const KFileItemModel::RoleInfoMap* KFileItemModel::rolesInfoMap(int& count)
2602 {
2603 static const RoleInfoMap rolesInfoMap[] = {
2604 // | role | roleType | role translation | group translation | requires Baloo | requires indexer
2605 { nullptr, NoRole, KLazyLocalizedString(), KLazyLocalizedString(), false, false },
2606 { "text", NameRole, kli18nc("@label", "Name"), KLazyLocalizedString(), false, false },
2607 { "size", SizeRole, kli18nc("@label", "Size"), KLazyLocalizedString(), false, false },
2608 { "modificationtime", ModificationTimeRole, kli18nc("@label", "Modified"), KLazyLocalizedString(), false, false },
2609 { "creationtime", CreationTimeRole, kli18nc("@label", "Created"), KLazyLocalizedString(), false, false },
2610 { "accesstime", AccessTimeRole, kli18nc("@label", "Accessed"), KLazyLocalizedString(), false, false },
2611 { "type", TypeRole, kli18nc("@label", "Type"), KLazyLocalizedString(), false, false },
2612 { "rating", RatingRole, kli18nc("@label", "Rating"), KLazyLocalizedString(), true, false },
2613 { "tags", TagsRole, kli18nc("@label", "Tags"), KLazyLocalizedString(), true, false },
2614 { "comment", CommentRole, kli18nc("@label", "Comment"), KLazyLocalizedString(), true, false },
2615 { "title", TitleRole, kli18nc("@label", "Title"), kli18nc("@label", "Document"), true, true },
2616 { "wordCount", WordCountRole, kli18nc("@label", "Word Count"), kli18nc("@label", "Document"), true, true },
2617 { "lineCount", LineCountRole, kli18nc("@label", "Line Count"), kli18nc("@label", "Document"), true, true },
2618 { "imageDateTime", ImageDateTimeRole, kli18nc("@label", "Date Photographed"), kli18nc("@label", "Image"), true, true },
2619 { "dimensions", DimensionsRole, kli18nc("@label width x height", "Dimensions"), kli18nc("@label", "Image"), true, true },
2620 { "width", WidthRole, kli18nc("@label", "Width"), kli18nc("@label", "Image"), true, true },
2621 { "height", HeightRole, kli18nc("@label", "Height"), kli18nc("@label", "Image"), true, true },
2622 { "orientation", OrientationRole, kli18nc("@label", "Orientation"), kli18nc("@label", "Image"), true, true },
2623 { "artist", ArtistRole, kli18nc("@label", "Artist"), kli18nc("@label", "Audio"), true, true },
2624 { "genre", GenreRole, kli18nc("@label", "Genre"), kli18nc("@label", "Audio"), true, true },
2625 { "album", AlbumRole, kli18nc("@label", "Album"), kli18nc("@label", "Audio"), true, true },
2626 { "duration", DurationRole, kli18nc("@label", "Duration"), kli18nc("@label", "Audio"), true, true },
2627 { "bitrate", BitrateRole, kli18nc("@label", "Bitrate"), kli18nc("@label", "Audio"), true, true },
2628 { "track", TrackRole, kli18nc("@label", "Track"), kli18nc("@label", "Audio"), true, true },
2629 { "releaseYear", ReleaseYearRole, kli18nc("@label", "Release Year"), kli18nc("@label", "Audio"), true, true },
2630 { "aspectRatio", AspectRatioRole, kli18nc("@label", "Aspect Ratio"), kli18nc("@label", "Video"), true, true },
2631 { "frameRate", FrameRateRole, kli18nc("@label", "Frame Rate"), kli18nc("@label", "Video"), true, true },
2632 { "path", PathRole, kli18nc("@label", "Path"), kli18nc("@label", "Other"), false, false },
2633 { "deletiontime", DeletionTimeRole, kli18nc("@label", "Deletion Time"), kli18nc("@label", "Other"), false, false },
2634 { "destination", DestinationRole, kli18nc("@label", "Link Destination"), kli18nc("@label", "Other"), false, false },
2635 { "originUrl", OriginUrlRole, kli18nc("@label", "Downloaded From"), kli18nc("@label", "Other"), true, false },
2636 { "permissions", PermissionsRole, kli18nc("@label", "Permissions"), kli18nc("@label", "Other"), false, false },
2637 { "owner", OwnerRole, kli18nc("@label", "Owner"), kli18nc("@label", "Other"), false, false },
2638 { "group", GroupRole, kli18nc("@label", "User Group"), kli18nc("@label", "Other"), false, false },
2639 };
2640
2641 count = sizeof(rolesInfoMap) / sizeof(RoleInfoMap);
2642 return rolesInfoMap;
2643 }
2644
2645 void KFileItemModel::determineMimeTypes(const KFileItemList& items, int timeout)
2646 {
2647 QElapsedTimer timer;
2648 timer.start();
2649 for (const KFileItem& item : items) {
2650 // Only determine mime types for files here. For directories,
2651 // KFileItem::determineMimeType() reads the .directory file inside to
2652 // load the icon, but this is not necessary at all if we just need the
2653 // type. Some special code for setting the correct mime type for
2654 // directories is in retrieveData().
2655 if (!item.isDir()) {
2656 item.determineMimeType();
2657 }
2658
2659 if (timer.elapsed() > timeout) {
2660 // Don't block the user interface, let the remaining items
2661 // be resolved asynchronously.
2662 return;
2663 }
2664 }
2665 }
2666
2667 QByteArray KFileItemModel::sharedValue(const QByteArray& value)
2668 {
2669 static QSet<QByteArray> pool;
2670 const QSet<QByteArray>::const_iterator it = pool.constFind(value);
2671
2672 if (it != pool.constEnd()) {
2673 return *it;
2674 } else {
2675 pool.insert(value);
2676 return value;
2677 }
2678 }
2679
2680 bool KFileItemModel::isConsistent() const
2681 {
2682 // m_items may contain less items than m_itemData because m_items
2683 // is populated lazily, see KFileItemModel::index(const QUrl& url).
2684 if (m_items.count() > m_itemData.count()) {
2685 return false;
2686 }
2687
2688 for (int i = 0, iMax = count(); i < iMax; ++i) {
2689 // Check if m_items and m_itemData are consistent.
2690 const KFileItem item = fileItem(i);
2691 if (item.isNull()) {
2692 qCWarning(DolphinDebug) << "Item" << i << "is null";
2693 return false;
2694 }
2695
2696 const int itemIndex = index(item);
2697 if (itemIndex != i) {
2698 qCWarning(DolphinDebug) << "Item" << i << "has a wrong index:" << itemIndex;
2699 return false;
2700 }
2701
2702 // Check if the items are sorted correctly.
2703 if (i > 0 && !lessThan(m_itemData.at(i - 1), m_itemData.at(i), m_collator)) {
2704 qCWarning(DolphinDebug) << "The order of items" << i - 1 << "and" << i << "is wrong:"
2705 << fileItem(i - 1) << fileItem(i);
2706 return false;
2707 }
2708
2709 // Check if all parent-child relationships are consistent.
2710 const ItemData* data = m_itemData.at(i);
2711 const ItemData* parent = data->parent;
2712 if (parent) {
2713 if (expandedParentsCount(data) != expandedParentsCount(parent) + 1) {
2714 qCWarning(DolphinDebug) << "expandedParentsCount is inconsistent for parent" << parent->item << "and child" << data->item;
2715 return false;
2716 }
2717
2718 const int parentIndex = index(parent->item);
2719 if (parentIndex >= i) {
2720 qCWarning(DolphinDebug) << "Index" << parentIndex << "of parent" << parent->item << "is not smaller than index" << i << "of child" << data->item;
2721 return false;
2722 }
2723 }
2724 }
2725
2726 return true;
2727 }
2728
2729 void KFileItemModel::slotListerError(KIO::Job *job)
2730 {
2731 if (job->error() == KIO::ERR_IS_FILE) {
2732 if (auto *listJob = qobject_cast<KIO::ListJob *>(job)) {
2733 Q_EMIT urlIsFileError(listJob->url());
2734 }
2735 } else {
2736 const QString errorString = job->errorString();
2737 Q_EMIT errorMessage(!errorString.isEmpty() ? errorString : i18nc("@info:status", "Unknown error."));
2738 }
2739 }