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