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