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