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