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