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