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