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