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