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