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