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