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