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