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