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