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