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