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