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