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