]> cloud.milkyroute.net Git - dolphin.git/blob - src/kitemviews/kfileitemmodel.cpp
Fix closing a secondary viewContainer on startup settings change
[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 Q_EMIT fileItemsChanged({KFileItem(directoryUrl)});
1020 }
1021
1022 void KFileItemModel::slotItemsDeleted(const KFileItemList& items)
1023 {
1024 dispatchPendingItemsToInsert();
1025
1026 QVector<int> indexesToRemove;
1027 indexesToRemove.reserve(items.count());
1028 KFileItemList dirsChanged;
1029
1030 for (const KFileItem& item : items) {
1031 const int indexForItem = index(item);
1032 if (indexForItem >= 0) {
1033 indexesToRemove.append(indexForItem);
1034 } else {
1035 // Probably the item has been filtered.
1036 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.find(item);
1037 if (it != m_filteredItems.end()) {
1038 delete it.value();
1039 m_filteredItems.erase(it);
1040 }
1041 }
1042
1043 QUrl parentUrl = item.url().adjusted(QUrl::RemoveFilename | QUrl::StripTrailingSlash);
1044 if (dirsChanged.findByUrl(parentUrl).isNull()) {
1045 dirsChanged << KFileItem(parentUrl);
1046 }
1047 }
1048
1049 std::sort(indexesToRemove.begin(), indexesToRemove.end());
1050
1051 if (m_requestRole[ExpandedParentsCountRole] && !m_expandedDirs.isEmpty()) {
1052 // Assure that removing a parent item also results in removing all children
1053 QVector<int> indexesToRemoveWithChildren;
1054 indexesToRemoveWithChildren.reserve(m_itemData.count());
1055
1056 const int itemCount = m_itemData.count();
1057 for (int index : qAsConst(indexesToRemove)) {
1058 indexesToRemoveWithChildren.append(index);
1059
1060 const int parentLevel = expandedParentsCount(index);
1061 int childIndex = index + 1;
1062 while (childIndex < itemCount && expandedParentsCount(childIndex) > parentLevel) {
1063 indexesToRemoveWithChildren.append(childIndex);
1064 ++childIndex;
1065 }
1066 }
1067
1068 indexesToRemove = indexesToRemoveWithChildren;
1069 }
1070
1071 const KItemRangeList itemRanges = KItemRangeList::fromSortedContainer(indexesToRemove);
1072 removeFilteredChildren(itemRanges);
1073 removeItems(itemRanges, DeleteItemData);
1074
1075 Q_EMIT fileItemsChanged(dirsChanged);
1076 }
1077
1078 void KFileItemModel::slotRefreshItems(const QList<QPair<KFileItem, KFileItem> >& items)
1079 {
1080 Q_ASSERT(!items.isEmpty());
1081 #ifdef KFILEITEMMODEL_DEBUG
1082 qCDebug(DolphinDebug) << "Refreshing" << items.count() << "items";
1083 #endif
1084
1085 // Get the indexes of all items that have been refreshed
1086 QList<int> indexes;
1087 indexes.reserve(items.count());
1088
1089 QSet<QByteArray> changedRoles;
1090 KFileItemList changedFiles;
1091
1092 // Contains the indexes of the currently visible items
1093 // that should get hidden and hence moved to m_filteredItems.
1094 QVector<int> newFilteredIndexes;
1095
1096 // Contains currently hidden items that should
1097 // get visible and hence removed from m_filteredItems
1098 QList<ItemData*> newVisibleItems;
1099
1100 QListIterator<QPair<KFileItem, KFileItem> > it(items);
1101 while (it.hasNext()) {
1102 const QPair<KFileItem, KFileItem>& itemPair = it.next();
1103 const KFileItem& oldItem = itemPair.first;
1104 const KFileItem& newItem = itemPair.second;
1105 const int indexForItem = index(oldItem);
1106 const bool newItemMatchesFilter = m_filter.matches(newItem);
1107 if (indexForItem >= 0) {
1108 m_itemData[indexForItem]->item = newItem;
1109
1110 // Keep old values as long as possible if they could not retrieved synchronously yet.
1111 // The update of the values will be done asynchronously by KFileItemModelRolesUpdater.
1112 ItemData * const itemData = m_itemData.at(indexForItem);
1113 QHashIterator<QByteArray, QVariant> it(retrieveData(newItem, itemData->parent));
1114 while (it.hasNext()) {
1115 it.next();
1116 const QByteArray& role = it.key();
1117 if (itemData->values.value(role) != it.value()) {
1118 itemData->values.insert(role, it.value());
1119 changedRoles.insert(role);
1120 }
1121 }
1122
1123 m_items.remove(oldItem.url());
1124 if (newItemMatchesFilter) {
1125 m_items.insert(newItem.url(), indexForItem);
1126 changedFiles.append(newItem);
1127 indexes.append(indexForItem);
1128 } else {
1129 newFilteredIndexes.append(indexForItem);
1130 m_filteredItems.insert(newItem, itemData);
1131 }
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 if (newItemMatchesFilter) {
1145 newVisibleItems.append(itemData);
1146 } else {
1147 m_filteredItems.insert(newItem, itemData);
1148 }
1149 }
1150 }
1151 }
1152
1153 // Hide items, previously visible that should get hidden
1154 const KItemRangeList removedRanges = KItemRangeList::fromSortedContainer(newFilteredIndexes);
1155 removeItems(removedRanges, KeepItemData);
1156
1157 // Show previously hidden items that should get visible
1158 insertItems(newVisibleItems);
1159
1160 // If the changed items have been created recently, they might not be in m_items yet.
1161 // In that case, the list 'indexes' might be empty.
1162 if (indexes.isEmpty()) {
1163 return;
1164 }
1165
1166 // Extract the item-ranges out of the changed indexes
1167 std::sort(indexes.begin(), indexes.end());
1168 const KItemRangeList itemRangeList = KItemRangeList::fromSortedContainer(indexes);
1169 emitItemsChangedAndTriggerResorting(itemRangeList, changedRoles);
1170
1171 Q_EMIT fileItemsChanged(changedFiles);
1172 }
1173
1174 void KFileItemModel::slotClear()
1175 {
1176 #ifdef KFILEITEMMODEL_DEBUG
1177 qCDebug(DolphinDebug) << "Clearing all items";
1178 #endif
1179
1180 qDeleteAll(m_filteredItems);
1181 m_filteredItems.clear();
1182 m_groups.clear();
1183
1184 m_maximumUpdateIntervalTimer->stop();
1185 m_resortAllItemsTimer->stop();
1186
1187 qDeleteAll(m_pendingItemsToInsert);
1188 m_pendingItemsToInsert.clear();
1189
1190 const int removedCount = m_itemData.count();
1191 if (removedCount > 0) {
1192 qDeleteAll(m_itemData);
1193 m_itemData.clear();
1194 m_items.clear();
1195 Q_EMIT itemsRemoved(KItemRangeList() << KItemRange(0, removedCount));
1196 }
1197
1198 m_expandedDirs.clear();
1199 }
1200
1201 void KFileItemModel::slotSortingChoiceChanged()
1202 {
1203 loadSortingSettings();
1204 resortAllItems();
1205 }
1206
1207 void KFileItemModel::dispatchPendingItemsToInsert()
1208 {
1209 if (!m_pendingItemsToInsert.isEmpty()) {
1210 insertItems(m_pendingItemsToInsert);
1211 m_pendingItemsToInsert.clear();
1212 }
1213 }
1214
1215 void KFileItemModel::insertItems(QList<ItemData*>& newItems)
1216 {
1217 if (newItems.isEmpty()) {
1218 return;
1219 }
1220
1221 #ifdef KFILEITEMMODEL_DEBUG
1222 QElapsedTimer timer;
1223 timer.start();
1224 qCDebug(DolphinDebug) << "===========================================================";
1225 qCDebug(DolphinDebug) << "Inserting" << newItems.count() << "items";
1226 #endif
1227
1228 m_groups.clear();
1229 prepareItemsForSorting(newItems);
1230
1231 // Natural sorting of items can be very slow. However, it becomes much faster
1232 // if the input sequence is already mostly sorted. Therefore, we first sort
1233 // 'newItems' according to the QStrings using QString::operator<(), which is quite fast.
1234 if (m_naturalSorting) {
1235 if (m_sortRole == NameRole) {
1236 parallelMergeSort(newItems.begin(), newItems.end(), nameLessThan, QThread::idealThreadCount());
1237 } else if (isRoleValueNatural(m_sortRole)) {
1238 auto lambdaLessThan = [&] (const KFileItemModel::ItemData* a, const KFileItemModel::ItemData* b)
1239 {
1240 const QByteArray role = roleForType(m_sortRole);
1241 return a->values.value(role).toString() < b->values.value(role).toString();
1242 };
1243 parallelMergeSort(newItems.begin(), newItems.end(), lambdaLessThan, QThread::idealThreadCount());
1244 }
1245 }
1246
1247 sort(newItems.begin(), newItems.end());
1248
1249 #ifdef KFILEITEMMODEL_DEBUG
1250 qCDebug(DolphinDebug) << "[TIME] Sorting:" << timer.elapsed();
1251 #endif
1252
1253 KItemRangeList itemRanges;
1254 const int existingItemCount = m_itemData.count();
1255 const int newItemCount = newItems.count();
1256 const int totalItemCount = existingItemCount + newItemCount;
1257
1258 if (existingItemCount == 0) {
1259 // Optimization for the common special case that there are no
1260 // items in the model yet. Happens, e.g., when entering a folder.
1261 m_itemData = newItems;
1262 itemRanges << KItemRange(0, newItemCount);
1263 } else {
1264 m_itemData.reserve(totalItemCount);
1265 for (int i = existingItemCount; i < totalItemCount; ++i) {
1266 m_itemData.append(nullptr);
1267 }
1268
1269 // We build the new list m_itemData in reverse order to minimize
1270 // the number of moves and guarantee O(N) complexity.
1271 int targetIndex = totalItemCount - 1;
1272 int sourceIndexExistingItems = existingItemCount - 1;
1273 int sourceIndexNewItems = newItemCount - 1;
1274
1275 int rangeCount = 0;
1276
1277 while (sourceIndexNewItems >= 0) {
1278 ItemData* newItem = newItems.at(sourceIndexNewItems);
1279 if (sourceIndexExistingItems >= 0 && lessThan(newItem, m_itemData.at(sourceIndexExistingItems), m_collator)) {
1280 // Move an existing item to its new position. If any new items
1281 // are behind it, push the item range to itemRanges.
1282 if (rangeCount > 0) {
1283 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1284 rangeCount = 0;
1285 }
1286
1287 m_itemData[targetIndex] = m_itemData.at(sourceIndexExistingItems);
1288 --sourceIndexExistingItems;
1289 } else {
1290 // Insert a new item into the list.
1291 ++rangeCount;
1292 m_itemData[targetIndex] = newItem;
1293 --sourceIndexNewItems;
1294 }
1295 --targetIndex;
1296 }
1297
1298 // Push the final item range to itemRanges.
1299 if (rangeCount > 0) {
1300 itemRanges << KItemRange(sourceIndexExistingItems + 1, rangeCount);
1301 }
1302
1303 // Note that itemRanges is still sorted in reverse order.
1304 std::reverse(itemRanges.begin(), itemRanges.end());
1305 }
1306
1307 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1308 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1309 m_items.clear();
1310
1311 Q_EMIT itemsInserted(itemRanges);
1312
1313 #ifdef KFILEITEMMODEL_DEBUG
1314 qCDebug(DolphinDebug) << "[TIME] Inserting of" << newItems.count() << "items:" << timer.elapsed();
1315 #endif
1316 }
1317
1318 void KFileItemModel::removeItems(const KItemRangeList& itemRanges, RemoveItemsBehavior behavior)
1319 {
1320 if (itemRanges.isEmpty()) {
1321 return;
1322 }
1323
1324 m_groups.clear();
1325
1326 // Step 1: Remove the items from m_itemData, and free the ItemData.
1327 int removedItemsCount = 0;
1328 for (const KItemRange& range : itemRanges) {
1329 removedItemsCount += range.count;
1330
1331 for (int index = range.index; index < range.index + range.count; ++index) {
1332 if (behavior == DeleteItemData) {
1333 delete m_itemData.at(index);
1334 }
1335
1336 m_itemData[index] = nullptr;
1337 }
1338 }
1339
1340 // Step 2: Remove the ItemData pointers from the list m_itemData.
1341 int target = itemRanges.at(0).index;
1342 int source = itemRanges.at(0).index + itemRanges.at(0).count;
1343 int nextRange = 1;
1344
1345 const int oldItemDataCount = m_itemData.count();
1346 while (source < oldItemDataCount) {
1347 m_itemData[target] = m_itemData[source];
1348 ++target;
1349 ++source;
1350
1351 if (nextRange < itemRanges.count() && source == itemRanges.at(nextRange).index) {
1352 // Skip the items in the next removed range.
1353 source += itemRanges.at(nextRange).count;
1354 ++nextRange;
1355 }
1356 }
1357
1358 m_itemData.erase(m_itemData.end() - removedItemsCount, m_itemData.end());
1359
1360 // The indexes in m_items are not correct anymore. Therefore, we clear m_items.
1361 // It will be re-populated with the updated indices if index(const QUrl&) is called.
1362 m_items.clear();
1363
1364 Q_EMIT itemsRemoved(itemRanges);
1365 }
1366
1367 QList<KFileItemModel::ItemData*> KFileItemModel::createItemDataList(const QUrl& parentUrl, const KFileItemList& items) const
1368 {
1369 if (m_sortRole == TypeRole) {
1370 // Try to resolve the MIME-types synchronously to prevent a reordering of
1371 // the items when sorting by type (per default MIME-types are resolved
1372 // asynchronously by KFileItemModelRolesUpdater).
1373 determineMimeTypes(items, 200);
1374 }
1375
1376 const int parentIndex = index(parentUrl);
1377 ItemData* parentItem = parentIndex < 0 ? nullptr : m_itemData.at(parentIndex);
1378
1379 QList<ItemData*> itemDataList;
1380 itemDataList.reserve(items.count());
1381
1382 for (const KFileItem& item : items) {
1383 ItemData* itemData = new ItemData();
1384 itemData->item = item;
1385 itemData->parent = parentItem;
1386 itemDataList.append(itemData);
1387 }
1388
1389 return itemDataList;
1390 }
1391
1392 void KFileItemModel::prepareItemsForSorting(QList<ItemData*>& itemDataList)
1393 {
1394 switch (m_sortRole) {
1395 case PermissionsRole:
1396 case OwnerRole:
1397 case GroupRole:
1398 case DestinationRole:
1399 case PathRole:
1400 case DeletionTimeRole:
1401 // These roles can be determined with retrieveData, and they have to be stored
1402 // in the QHash "values" for the sorting.
1403 for (ItemData* itemData : qAsConst(itemDataList)) {
1404 if (itemData->values.isEmpty()) {
1405 itemData->values = retrieveData(itemData->item, itemData->parent);
1406 }
1407 }
1408 break;
1409
1410 case TypeRole:
1411 // At least store the data including the file type for items with known MIME type.
1412 for (ItemData* itemData : qAsConst(itemDataList)) {
1413 if (itemData->values.isEmpty()) {
1414 const KFileItem item = itemData->item;
1415 if (item.isDir() || item.isMimeTypeKnown()) {
1416 itemData->values = retrieveData(itemData->item, itemData->parent);
1417 }
1418 }
1419 }
1420 break;
1421
1422 default:
1423 // The other roles are either resolved by KFileItemModelRolesUpdater
1424 // (this includes the SizeRole for directories), or they do not need
1425 // to be stored in the QHash "values" for sorting because the data can
1426 // be retrieved directly from the KFileItem (NameRole, SizeRole for files,
1427 // DateRole).
1428 break;
1429 }
1430 }
1431
1432 int KFileItemModel::expandedParentsCount(const ItemData* data)
1433 {
1434 // The hash 'values' is only guaranteed to contain the key "expandedParentsCount"
1435 // if the corresponding item is expanded, and it is not a top-level item.
1436 const ItemData* parent = data->parent;
1437 if (parent) {
1438 if (parent->parent) {
1439 Q_ASSERT(parent->values.contains("expandedParentsCount"));
1440 return parent->values.value("expandedParentsCount").toInt() + 1;
1441 } else {
1442 return 1;
1443 }
1444 } else {
1445 return 0;
1446 }
1447 }
1448
1449 void KFileItemModel::removeExpandedItems()
1450 {
1451 QVector<int> indexesToRemove;
1452
1453 const int maxIndex = m_itemData.count() - 1;
1454 for (int i = 0; i <= maxIndex; ++i) {
1455 const ItemData* itemData = m_itemData.at(i);
1456 if (itemData->parent) {
1457 indexesToRemove.append(i);
1458 }
1459 }
1460
1461 removeItems(KItemRangeList::fromSortedContainer(indexesToRemove), DeleteItemData);
1462 m_expandedDirs.clear();
1463
1464 // Also remove all filtered items which have a parent.
1465 QHash<KFileItem, ItemData*>::iterator it = m_filteredItems.begin();
1466 const QHash<KFileItem, ItemData*>::iterator end = m_filteredItems.end();
1467
1468 while (it != end) {
1469 if (it.value()->parent) {
1470 delete it.value();
1471 it = m_filteredItems.erase(it);
1472 } else {
1473 ++it;
1474 }
1475 }
1476 }
1477
1478 void KFileItemModel::emitItemsChangedAndTriggerResorting(const KItemRangeList& itemRanges, const QSet<QByteArray>& changedRoles)
1479 {
1480 Q_EMIT itemsChanged(itemRanges, changedRoles);
1481
1482 // Trigger a resorting if necessary. Note that this can happen even if the sort
1483 // role has not changed at all because the file name can be used as a fallback.
1484 if (changedRoles.contains(sortRole()) || changedRoles.contains(roleForType(NameRole))) {
1485 for (const KItemRange& range : itemRanges) {
1486 bool needsResorting = false;
1487
1488 const int first = range.index;
1489 const int last = range.index + range.count - 1;
1490
1491 // Resorting the model is necessary if
1492 // (a) The first item in the range is "lessThan" its predecessor,
1493 // (b) the successor of the last item is "lessThan" the last item, or
1494 // (c) the internal order of the items in the range is incorrect.
1495 if (first > 0
1496 && lessThan(m_itemData.at(first), m_itemData.at(first - 1), m_collator)) {
1497 needsResorting = true;
1498 } else if (last < count() - 1
1499 && lessThan(m_itemData.at(last + 1), m_itemData.at(last), m_collator)) {
1500 needsResorting = true;
1501 } else {
1502 for (int index = first; index < last; ++index) {
1503 if (lessThan(m_itemData.at(index + 1), m_itemData.at(index), m_collator)) {
1504 needsResorting = true;
1505 break;
1506 }
1507 }
1508 }
1509
1510 if (needsResorting) {
1511 m_resortAllItemsTimer->start();
1512 return;
1513 }
1514 }
1515 }
1516
1517 if (groupedSorting() && changedRoles.contains(sortRole())) {
1518 // The position is still correct, but the groups might have changed
1519 // if the changed item is either the first or the last item in a
1520 // group.
1521 // In principle, we could try to find out if the item really is the
1522 // first or last one in its group and then update the groups
1523 // (possibly with a delayed timer to make sure that we don't
1524 // re-calculate the groups very often if items are updated one by
1525 // one), but starting m_resortAllItemsTimer is easier.
1526 m_resortAllItemsTimer->start();
1527 }
1528 }
1529
1530 void KFileItemModel::resetRoles()
1531 {
1532 for (int i = 0; i < RolesCount; ++i) {
1533 m_requestRole[i] = false;
1534 }
1535 }
1536
1537 KFileItemModel::RoleType KFileItemModel::typeForRole(const QByteArray& role) const
1538 {
1539 static QHash<QByteArray, RoleType> roles;
1540 if (roles.isEmpty()) {
1541 // Insert user visible roles that can be accessed with
1542 // KFileItemModel::roleInformation()
1543 int count = 0;
1544 const RoleInfoMap* map = rolesInfoMap(count);
1545 for (int i = 0; i < count; ++i) {
1546 roles.insert(map[i].role, map[i].roleType);
1547 }
1548
1549 // Insert internal roles (take care to synchronize the implementation
1550 // with KFileItemModel::roleForType() in case if a change is done).
1551 roles.insert("isDir", IsDirRole);
1552 roles.insert("isLink", IsLinkRole);
1553 roles.insert("isHidden", IsHiddenRole);
1554 roles.insert("isExpanded", IsExpandedRole);
1555 roles.insert("isExpandable", IsExpandableRole);
1556 roles.insert("expandedParentsCount", ExpandedParentsCountRole);
1557
1558 Q_ASSERT(roles.count() == RolesCount);
1559 }
1560
1561 return roles.value(role, NoRole);
1562 }
1563
1564 QByteArray KFileItemModel::roleForType(RoleType roleType) const
1565 {
1566 static QHash<RoleType, QByteArray> roles;
1567 if (roles.isEmpty()) {
1568 // Insert user visible roles that can be accessed with
1569 // KFileItemModel::roleInformation()
1570 int count = 0;
1571 const RoleInfoMap* map = rolesInfoMap(count);
1572 for (int i = 0; i < count; ++i) {
1573 roles.insert(map[i].roleType, map[i].role);
1574 }
1575
1576 // Insert internal roles (take care to synchronize the implementation
1577 // with KFileItemModel::typeForRole() in case if a change is done).
1578 roles.insert(IsDirRole, "isDir");
1579 roles.insert(IsLinkRole, "isLink");
1580 roles.insert(IsHiddenRole, "isHidden");
1581 roles.insert(IsExpandedRole, "isExpanded");
1582 roles.insert(IsExpandableRole, "isExpandable");
1583 roles.insert(ExpandedParentsCountRole, "expandedParentsCount");
1584
1585 Q_ASSERT(roles.count() == RolesCount);
1586 };
1587
1588 return roles.value(roleType);
1589 }
1590
1591 QHash<QByteArray, QVariant> KFileItemModel::retrieveData(const KFileItem& item, const ItemData* parent) const
1592 {
1593 // It is important to insert only roles that are fast to retrieve. E.g.
1594 // KFileItem::iconName() can be very expensive if the MIME-type is unknown
1595 // and hence will be retrieved asynchronously by KFileItemModelRolesUpdater.
1596 QHash<QByteArray, QVariant> data;
1597 data.insert(sharedValue("url"), item.url());
1598
1599 const bool isDir = item.isDir();
1600 if (m_requestRole[IsDirRole] && isDir) {
1601 data.insert(sharedValue("isDir"), true);
1602 }
1603
1604 if (m_requestRole[IsLinkRole] && item.isLink()) {
1605 data.insert(sharedValue("isLink"), true);
1606 }
1607
1608 if (m_requestRole[IsHiddenRole]) {
1609 data.insert(sharedValue("isHidden"), item.isHidden());
1610 }
1611
1612 if (m_requestRole[NameRole]) {
1613 data.insert(sharedValue("text"), item.text());
1614 }
1615
1616 if (m_requestRole[SizeRole] && !isDir) {
1617 data.insert(sharedValue("size"), item.size());
1618 }
1619
1620 if (m_requestRole[ModificationTimeRole]) {
1621 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1622 // having several thousands of items. Instead read the raw number from UDSEntry directly
1623 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1624 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME, -1);
1625 data.insert(sharedValue("modificationtime"), dateTime);
1626 }
1627
1628 if (m_requestRole[CreationTimeRole]) {
1629 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1630 // having several thousands of items. Instead read the raw number from UDSEntry directly
1631 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1632 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_CREATION_TIME, -1);
1633 data.insert(sharedValue("creationtime"), dateTime);
1634 }
1635
1636 if (m_requestRole[AccessTimeRole]) {
1637 // Don't use KFileItem::timeString() or KFileItem::time() as this is too expensive when
1638 // having several thousands of items. Instead read the raw number from UDSEntry directly
1639 // and the formatting of the date-time will be done on-demand by the view when the date will be shown.
1640 const long long dateTime = item.entry().numberValue(KIO::UDSEntry::UDS_ACCESS_TIME, -1);
1641 data.insert(sharedValue("accesstime"), dateTime);
1642 }
1643
1644 if (m_requestRole[PermissionsRole]) {
1645 data.insert(sharedValue("permissions"), item.permissionsString());
1646 }
1647
1648 if (m_requestRole[OwnerRole]) {
1649 data.insert(sharedValue("owner"), item.user());
1650 }
1651
1652 if (m_requestRole[GroupRole]) {
1653 data.insert(sharedValue("group"), item.group());
1654 }
1655
1656 if (m_requestRole[DestinationRole]) {
1657 QString destination = item.linkDest();
1658 if (destination.isEmpty()) {
1659 destination = QLatin1Char('-');
1660 }
1661 data.insert(sharedValue("destination"), destination);
1662 }
1663
1664 if (m_requestRole[PathRole]) {
1665 QString path;
1666 if (item.url().scheme() == QLatin1String("trash")) {
1667 path = item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA);
1668 } else {
1669 // For performance reasons cache the home-path in a static QString
1670 // (see QDir::homePath() for more details)
1671 static QString homePath;
1672 if (homePath.isEmpty()) {
1673 homePath = QDir::homePath();
1674 }
1675
1676 path = item.localPath();
1677 if (path.startsWith(homePath)) {
1678 path.replace(0, homePath.length(), QLatin1Char('~'));
1679 }
1680 }
1681
1682 const int index = path.lastIndexOf(item.text());
1683 path = path.mid(0, index - 1);
1684 data.insert(sharedValue("path"), path);
1685 }
1686
1687 if (m_requestRole[DeletionTimeRole]) {
1688 QDateTime deletionTime;
1689 if (item.url().scheme() == QLatin1String("trash")) {
1690 deletionTime = QDateTime::fromString(item.entry().stringValue(KIO::UDSEntry::UDS_EXTRA + 1), Qt::ISODate);
1691 }
1692 data.insert(sharedValue("deletiontime"), deletionTime);
1693 }
1694
1695 if (m_requestRole[IsExpandableRole] && isDir) {
1696 data.insert(sharedValue("isExpandable"), true);
1697 }
1698
1699 if (m_requestRole[ExpandedParentsCountRole]) {
1700 if (parent) {
1701 const int level = expandedParentsCount(parent) + 1;
1702 data.insert(sharedValue("expandedParentsCount"), level);
1703 }
1704 }
1705
1706 if (item.isMimeTypeKnown()) {
1707 QString iconName = item.iconName();
1708 if (!QIcon::hasThemeIcon(iconName)) {
1709 QMimeType mimeType = QMimeDatabase().mimeTypeForName(item.mimetype());
1710 iconName = mimeType.genericIconName();
1711 }
1712
1713 data.insert(sharedValue("iconName"), iconName);
1714
1715 if (m_requestRole[TypeRole]) {
1716 data.insert(sharedValue("type"), item.mimeComment());
1717 }
1718 } else if (m_requestRole[TypeRole] && isDir) {
1719 static const QString folderMimeType = item.mimeComment();
1720 data.insert(sharedValue("type"), folderMimeType);
1721 }
1722
1723 return data;
1724 }
1725
1726 bool KFileItemModel::lessThan(const ItemData* a, const ItemData* b, const QCollator& collator) const
1727 {
1728 int result = 0;
1729
1730 if (a->parent != b->parent) {
1731 const int expansionLevelA = expandedParentsCount(a);
1732 const int expansionLevelB = expandedParentsCount(b);
1733
1734 // If b has a higher expansion level than a, check if a is a parent
1735 // of b, and make sure that both expansion levels are equal otherwise.
1736 for (int i = expansionLevelB; i > expansionLevelA; --i) {
1737 if (b->parent == a) {
1738 return true;
1739 }
1740 b = b->parent;
1741 }
1742
1743 // If a has a higher expansion level than a, check if b is a parent
1744 // of a, and make sure that both expansion levels are equal otherwise.
1745 for (int i = expansionLevelA; i > expansionLevelB; --i) {
1746 if (a->parent == b) {
1747 return false;
1748 }
1749 a = a->parent;
1750 }
1751
1752 Q_ASSERT(expandedParentsCount(a) == expandedParentsCount(b));
1753
1754 // Compare the last parents of a and b which are different.
1755 while (a->parent != b->parent) {
1756 a = a->parent;
1757 b = b->parent;
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 }