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